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.

22813 lines
675 KiB

  1. /**
  2. * vis.js
  3. * https://github.com/almende/vis
  4. *
  5. * A dynamic, browser-based visualization library.
  6. *
  7. * @version 1.0.2
  8. * @date 2014-05-28
  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. * Deep extend an object a with the properties of object b
  354. * @param {Object} a
  355. * @param {Object} b
  356. * @returns {Object}
  357. */
  358. util.deepExtend = function deepExtend (a, b) {
  359. // TODO: add support for Arrays to deepExtend
  360. if (Array.isArray(b)) {
  361. throw new TypeError('Arrays are not supported by deepExtend');
  362. }
  363. for (var prop in b) {
  364. if (b.hasOwnProperty(prop)) {
  365. if (b[prop] && b[prop].constructor === Object) {
  366. if (a[prop] === undefined) {
  367. a[prop] = {};
  368. }
  369. if (a[prop].constructor === Object) {
  370. deepExtend(a[prop], b[prop]);
  371. }
  372. else {
  373. a[prop] = b[prop];
  374. }
  375. } else if (Array.isArray(b[prop])) {
  376. throw new TypeError('Arrays are not supported by deepExtend');
  377. } else {
  378. a[prop] = b[prop];
  379. }
  380. }
  381. }
  382. return a;
  383. };
  384. /**
  385. * Test whether all elements in two arrays are equal.
  386. * @param {Array} a
  387. * @param {Array} b
  388. * @return {boolean} Returns true if both arrays have the same length and same
  389. * elements.
  390. */
  391. util.equalArray = function (a, b) {
  392. if (a.length != b.length) return false;
  393. for (var i = 0, len = a.length; i < len; i++) {
  394. if (a[i] != b[i]) return false;
  395. }
  396. return true;
  397. };
  398. /**
  399. * Convert an object to another type
  400. * @param {Boolean | Number | String | Date | Moment | Null | undefined} object
  401. * @param {String | undefined} type Name of the type. Available types:
  402. * 'Boolean', 'Number', 'String',
  403. * 'Date', 'Moment', ISODate', 'ASPDate'.
  404. * @return {*} object
  405. * @throws Error
  406. */
  407. util.convert = function convert(object, type) {
  408. var match;
  409. if (object === undefined) {
  410. return undefined;
  411. }
  412. if (object === null) {
  413. return null;
  414. }
  415. if (!type) {
  416. return object;
  417. }
  418. if (!(typeof type === 'string') && !(type instanceof String)) {
  419. throw new Error('Type must be a string');
  420. }
  421. //noinspection FallthroughInSwitchStatementJS
  422. switch (type) {
  423. case 'boolean':
  424. case 'Boolean':
  425. return Boolean(object);
  426. case 'number':
  427. case 'Number':
  428. return Number(object.valueOf());
  429. case 'string':
  430. case 'String':
  431. return String(object);
  432. case 'Date':
  433. if (util.isNumber(object)) {
  434. return new Date(object);
  435. }
  436. if (object instanceof Date) {
  437. return new Date(object.valueOf());
  438. }
  439. else if (moment.isMoment(object)) {
  440. return new Date(object.valueOf());
  441. }
  442. if (util.isString(object)) {
  443. match = ASPDateRegex.exec(object);
  444. if (match) {
  445. // object is an ASP date
  446. return new Date(Number(match[1])); // parse number
  447. }
  448. else {
  449. return moment(object).toDate(); // parse string
  450. }
  451. }
  452. else {
  453. throw new Error(
  454. 'Cannot convert object of type ' + util.getType(object) +
  455. ' to type Date');
  456. }
  457. case 'Moment':
  458. if (util.isNumber(object)) {
  459. return moment(object);
  460. }
  461. if (object instanceof Date) {
  462. return moment(object.valueOf());
  463. }
  464. else if (moment.isMoment(object)) {
  465. return moment(object);
  466. }
  467. if (util.isString(object)) {
  468. match = ASPDateRegex.exec(object);
  469. if (match) {
  470. // object is an ASP date
  471. return moment(Number(match[1])); // parse number
  472. }
  473. else {
  474. return moment(object); // parse string
  475. }
  476. }
  477. else {
  478. throw new Error(
  479. 'Cannot convert object of type ' + util.getType(object) +
  480. ' to type Date');
  481. }
  482. case 'ISODate':
  483. if (util.isNumber(object)) {
  484. return new Date(object);
  485. }
  486. else if (object instanceof Date) {
  487. return object.toISOString();
  488. }
  489. else if (moment.isMoment(object)) {
  490. return object.toDate().toISOString();
  491. }
  492. else if (util.isString(object)) {
  493. match = ASPDateRegex.exec(object);
  494. if (match) {
  495. // object is an ASP date
  496. return new Date(Number(match[1])).toISOString(); // parse number
  497. }
  498. else {
  499. return new Date(object).toISOString(); // parse string
  500. }
  501. }
  502. else {
  503. throw new Error(
  504. 'Cannot convert object of type ' + util.getType(object) +
  505. ' to type ISODate');
  506. }
  507. case 'ASPDate':
  508. if (util.isNumber(object)) {
  509. return '/Date(' + object + ')/';
  510. }
  511. else if (object instanceof Date) {
  512. return '/Date(' + object.valueOf() + ')/';
  513. }
  514. else if (util.isString(object)) {
  515. match = ASPDateRegex.exec(object);
  516. var value;
  517. if (match) {
  518. // object is an ASP date
  519. value = new Date(Number(match[1])).valueOf(); // parse number
  520. }
  521. else {
  522. value = new Date(object).valueOf(); // parse string
  523. }
  524. return '/Date(' + value + ')/';
  525. }
  526. else {
  527. throw new Error(
  528. 'Cannot convert object of type ' + util.getType(object) +
  529. ' to type ASPDate');
  530. }
  531. default:
  532. throw new Error('Cannot convert object of type ' + util.getType(object) +
  533. ' to type "' + type + '"');
  534. }
  535. };
  536. // parse ASP.Net Date pattern,
  537. // for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/'
  538. // code from http://momentjs.com/
  539. var ASPDateRegex = /^\/?Date\((\-?\d+)/i;
  540. /**
  541. * Get the type of an object, for example util.getType([]) returns 'Array'
  542. * @param {*} object
  543. * @return {String} type
  544. */
  545. util.getType = function getType(object) {
  546. var type = typeof object;
  547. if (type == 'object') {
  548. if (object == null) {
  549. return 'null';
  550. }
  551. if (object instanceof Boolean) {
  552. return 'Boolean';
  553. }
  554. if (object instanceof Number) {
  555. return 'Number';
  556. }
  557. if (object instanceof String) {
  558. return 'String';
  559. }
  560. if (object instanceof Array) {
  561. return 'Array';
  562. }
  563. if (object instanceof Date) {
  564. return 'Date';
  565. }
  566. return 'Object';
  567. }
  568. else if (type == 'number') {
  569. return 'Number';
  570. }
  571. else if (type == 'boolean') {
  572. return 'Boolean';
  573. }
  574. else if (type == 'string') {
  575. return 'String';
  576. }
  577. return type;
  578. };
  579. /**
  580. * Retrieve the absolute left value of a DOM element
  581. * @param {Element} elem A dom element, for example a div
  582. * @return {number} left The absolute left position of this element
  583. * in the browser page.
  584. */
  585. util.getAbsoluteLeft = function getAbsoluteLeft (elem) {
  586. var doc = document.documentElement;
  587. var body = document.body;
  588. var left = elem.offsetLeft;
  589. var e = elem.offsetParent;
  590. while (e != null && e != body && e != doc) {
  591. left += e.offsetLeft;
  592. left -= e.scrollLeft;
  593. e = e.offsetParent;
  594. }
  595. return left;
  596. };
  597. /**
  598. * Retrieve the absolute top value of a DOM element
  599. * @param {Element} elem A dom element, for example a div
  600. * @return {number} top The absolute top position of this element
  601. * in the browser page.
  602. */
  603. util.getAbsoluteTop = function getAbsoluteTop (elem) {
  604. var doc = document.documentElement;
  605. var body = document.body;
  606. var top = elem.offsetTop;
  607. var e = elem.offsetParent;
  608. while (e != null && e != body && e != doc) {
  609. top += e.offsetTop;
  610. top -= e.scrollTop;
  611. e = e.offsetParent;
  612. }
  613. return top;
  614. };
  615. /**
  616. * Get the absolute, vertical mouse position from an event.
  617. * @param {Event} event
  618. * @return {Number} pageY
  619. */
  620. util.getPageY = function getPageY (event) {
  621. if ('pageY' in event) {
  622. return event.pageY;
  623. }
  624. else {
  625. var clientY;
  626. if (('targetTouches' in event) && event.targetTouches.length) {
  627. clientY = event.targetTouches[0].clientY;
  628. }
  629. else {
  630. clientY = event.clientY;
  631. }
  632. var doc = document.documentElement;
  633. var body = document.body;
  634. return clientY +
  635. ( doc && doc.scrollTop || body && body.scrollTop || 0 ) -
  636. ( doc && doc.clientTop || body && body.clientTop || 0 );
  637. }
  638. };
  639. /**
  640. * Get the absolute, horizontal mouse position from an event.
  641. * @param {Event} event
  642. * @return {Number} pageX
  643. */
  644. util.getPageX = function getPageX (event) {
  645. if ('pageY' in event) {
  646. return event.pageX;
  647. }
  648. else {
  649. var clientX;
  650. if (('targetTouches' in event) && event.targetTouches.length) {
  651. clientX = event.targetTouches[0].clientX;
  652. }
  653. else {
  654. clientX = event.clientX;
  655. }
  656. var doc = document.documentElement;
  657. var body = document.body;
  658. return clientX +
  659. ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) -
  660. ( doc && doc.clientLeft || body && body.clientLeft || 0 );
  661. }
  662. };
  663. /**
  664. * add a className to the given elements style
  665. * @param {Element} elem
  666. * @param {String} className
  667. */
  668. util.addClassName = function addClassName(elem, className) {
  669. var classes = elem.className.split(' ');
  670. if (classes.indexOf(className) == -1) {
  671. classes.push(className); // add the class to the array
  672. elem.className = classes.join(' ');
  673. }
  674. };
  675. /**
  676. * add a className to the given elements style
  677. * @param {Element} elem
  678. * @param {String} className
  679. */
  680. util.removeClassName = function removeClassname(elem, className) {
  681. var classes = elem.className.split(' ');
  682. var index = classes.indexOf(className);
  683. if (index != -1) {
  684. classes.splice(index, 1); // remove the class from the array
  685. elem.className = classes.join(' ');
  686. }
  687. };
  688. /**
  689. * For each method for both arrays and objects.
  690. * In case of an array, the built-in Array.forEach() is applied.
  691. * In case of an Object, the method loops over all properties of the object.
  692. * @param {Object | Array} object An Object or Array
  693. * @param {function} callback Callback method, called for each item in
  694. * the object or array with three parameters:
  695. * callback(value, index, object)
  696. */
  697. util.forEach = function forEach (object, callback) {
  698. var i,
  699. len;
  700. if (object instanceof Array) {
  701. // array
  702. for (i = 0, len = object.length; i < len; i++) {
  703. callback(object[i], i, object);
  704. }
  705. }
  706. else {
  707. // object
  708. for (i in object) {
  709. if (object.hasOwnProperty(i)) {
  710. callback(object[i], i, object);
  711. }
  712. }
  713. }
  714. };
  715. /**
  716. * Convert an object into an array: all objects properties are put into the
  717. * array. The resulting array is unordered.
  718. * @param {Object} object
  719. * @param {Array} array
  720. */
  721. util.toArray = function toArray(object) {
  722. var array = [];
  723. for (var prop in object) {
  724. if (object.hasOwnProperty(prop)) array.push(object[prop]);
  725. }
  726. return array;
  727. }
  728. /**
  729. * Update a property in an object
  730. * @param {Object} object
  731. * @param {String} key
  732. * @param {*} value
  733. * @return {Boolean} changed
  734. */
  735. util.updateProperty = function updateProperty (object, key, value) {
  736. if (object[key] !== value) {
  737. object[key] = value;
  738. return true;
  739. }
  740. else {
  741. return false;
  742. }
  743. };
  744. /**
  745. * Add and event listener. Works for all browsers
  746. * @param {Element} element An html element
  747. * @param {string} action The action, for example "click",
  748. * without the prefix "on"
  749. * @param {function} listener The callback function to be executed
  750. * @param {boolean} [useCapture]
  751. */
  752. util.addEventListener = function addEventListener(element, action, listener, useCapture) {
  753. if (element.addEventListener) {
  754. if (useCapture === undefined)
  755. useCapture = false;
  756. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  757. action = "DOMMouseScroll"; // For Firefox
  758. }
  759. element.addEventListener(action, listener, useCapture);
  760. } else {
  761. element.attachEvent("on" + action, listener); // IE browsers
  762. }
  763. };
  764. /**
  765. * Remove an event listener from an element
  766. * @param {Element} element An html dom element
  767. * @param {string} action The name of the event, for example "mousedown"
  768. * @param {function} listener The listener function
  769. * @param {boolean} [useCapture]
  770. */
  771. util.removeEventListener = function removeEventListener(element, action, listener, useCapture) {
  772. if (element.removeEventListener) {
  773. // non-IE browsers
  774. if (useCapture === undefined)
  775. useCapture = false;
  776. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  777. action = "DOMMouseScroll"; // For Firefox
  778. }
  779. element.removeEventListener(action, listener, useCapture);
  780. } else {
  781. // IE browsers
  782. element.detachEvent("on" + action, listener);
  783. }
  784. };
  785. /**
  786. * Get HTML element which is the target of the event
  787. * @param {Event} event
  788. * @return {Element} target element
  789. */
  790. util.getTarget = function getTarget(event) {
  791. // code from http://www.quirksmode.org/js/events_properties.html
  792. if (!event) {
  793. event = window.event;
  794. }
  795. var target;
  796. if (event.target) {
  797. target = event.target;
  798. }
  799. else if (event.srcElement) {
  800. target = event.srcElement;
  801. }
  802. if (target.nodeType != undefined && target.nodeType == 3) {
  803. // defeat Safari bug
  804. target = target.parentNode;
  805. }
  806. return target;
  807. };
  808. /**
  809. * Fake a hammer.js gesture. Event can be a ScrollEvent or MouseMoveEvent
  810. * @param {Element} element
  811. * @param {Event} event
  812. */
  813. util.fakeGesture = function fakeGesture (element, event) {
  814. var eventType = null;
  815. // for hammer.js 1.0.5
  816. var gesture = Hammer.event.collectEventData(this, eventType, event);
  817. // for hammer.js 1.0.6
  818. //var touches = Hammer.event.getTouchList(event, eventType);
  819. // var gesture = Hammer.event.collectEventData(this, eventType, touches, event);
  820. // on IE in standards mode, no touches are recognized by hammer.js,
  821. // resulting in NaN values for center.pageX and center.pageY
  822. if (isNaN(gesture.center.pageX)) {
  823. gesture.center.pageX = event.pageX;
  824. }
  825. if (isNaN(gesture.center.pageY)) {
  826. gesture.center.pageY = event.pageY;
  827. }
  828. return gesture;
  829. };
  830. util.option = {};
  831. /**
  832. * Convert a value into a boolean
  833. * @param {Boolean | function | undefined} value
  834. * @param {Boolean} [defaultValue]
  835. * @returns {Boolean} bool
  836. */
  837. util.option.asBoolean = function (value, defaultValue) {
  838. if (typeof value == 'function') {
  839. value = value();
  840. }
  841. if (value != null) {
  842. return (value != false);
  843. }
  844. return defaultValue || null;
  845. };
  846. /**
  847. * Convert a value into a number
  848. * @param {Boolean | function | undefined} value
  849. * @param {Number} [defaultValue]
  850. * @returns {Number} number
  851. */
  852. util.option.asNumber = function (value, defaultValue) {
  853. if (typeof value == 'function') {
  854. value = value();
  855. }
  856. if (value != null) {
  857. return Number(value) || defaultValue || null;
  858. }
  859. return defaultValue || null;
  860. };
  861. /**
  862. * Convert a value into a string
  863. * @param {String | function | undefined} value
  864. * @param {String} [defaultValue]
  865. * @returns {String} str
  866. */
  867. util.option.asString = function (value, defaultValue) {
  868. if (typeof value == 'function') {
  869. value = value();
  870. }
  871. if (value != null) {
  872. return String(value);
  873. }
  874. return defaultValue || null;
  875. };
  876. /**
  877. * Convert a size or location into a string with pixels or a percentage
  878. * @param {String | Number | function | undefined} value
  879. * @param {String} [defaultValue]
  880. * @returns {String} size
  881. */
  882. util.option.asSize = function (value, defaultValue) {
  883. if (typeof value == 'function') {
  884. value = value();
  885. }
  886. if (util.isString(value)) {
  887. return value;
  888. }
  889. else if (util.isNumber(value)) {
  890. return value + 'px';
  891. }
  892. else {
  893. return defaultValue || null;
  894. }
  895. };
  896. /**
  897. * Convert a value into a DOM element
  898. * @param {HTMLElement | function | undefined} value
  899. * @param {HTMLElement} [defaultValue]
  900. * @returns {HTMLElement | null} dom
  901. */
  902. util.option.asElement = function (value, defaultValue) {
  903. if (typeof value == 'function') {
  904. value = value();
  905. }
  906. return value || defaultValue || null;
  907. };
  908. util.GiveDec = function GiveDec(Hex) {
  909. var Value;
  910. if (Hex == "A")
  911. Value = 10;
  912. else if (Hex == "B")
  913. Value = 11;
  914. else if (Hex == "C")
  915. Value = 12;
  916. else if (Hex == "D")
  917. Value = 13;
  918. else if (Hex == "E")
  919. Value = 14;
  920. else if (Hex == "F")
  921. Value = 15;
  922. else
  923. Value = eval(Hex);
  924. return Value;
  925. };
  926. util.GiveHex = function GiveHex(Dec) {
  927. var Value;
  928. if(Dec == 10)
  929. Value = "A";
  930. else if (Dec == 11)
  931. Value = "B";
  932. else if (Dec == 12)
  933. Value = "C";
  934. else if (Dec == 13)
  935. Value = "D";
  936. else if (Dec == 14)
  937. Value = "E";
  938. else if (Dec == 15)
  939. Value = "F";
  940. else
  941. Value = "" + Dec;
  942. return Value;
  943. };
  944. /**
  945. * Parse a color property into an object with border, background, and
  946. * highlight colors
  947. * @param {Object | String} color
  948. * @return {Object} colorObject
  949. */
  950. util.parseColor = function(color) {
  951. var c;
  952. if (util.isString(color)) {
  953. if (util.isValidHex(color)) {
  954. var hsv = util.hexToHSV(color);
  955. var lighterColorHSV = {h:hsv.h,s:hsv.s * 0.45,v:Math.min(1,hsv.v * 1.05)};
  956. var darkerColorHSV = {h:hsv.h,s:Math.min(1,hsv.v * 1.25),v:hsv.v*0.6};
  957. var darkerColorHex = util.HSVToHex(darkerColorHSV.h ,darkerColorHSV.h ,darkerColorHSV.v);
  958. var lighterColorHex = util.HSVToHex(lighterColorHSV.h,lighterColorHSV.s,lighterColorHSV.v);
  959. c = {
  960. background: color,
  961. border:darkerColorHex,
  962. highlight: {
  963. background:lighterColorHex,
  964. border:darkerColorHex
  965. }
  966. };
  967. }
  968. else {
  969. c = {
  970. background:color,
  971. border:color,
  972. highlight: {
  973. background:color,
  974. border:color
  975. }
  976. };
  977. }
  978. }
  979. else {
  980. c = {};
  981. c.background = color.background || 'white';
  982. c.border = color.border || c.background;
  983. if (util.isString(color.highlight)) {
  984. c.highlight = {
  985. border: color.highlight,
  986. background: color.highlight
  987. }
  988. }
  989. else {
  990. c.highlight = {};
  991. c.highlight.background = color.highlight && color.highlight.background || c.background;
  992. c.highlight.border = color.highlight && color.highlight.border || c.border;
  993. }
  994. }
  995. return c;
  996. };
  997. /**
  998. * http://www.yellowpipe.com/yis/tools/hex-to-rgb/color-converter.php
  999. *
  1000. * @param {String} hex
  1001. * @returns {{r: *, g: *, b: *}}
  1002. */
  1003. util.hexToRGB = function hexToRGB(hex) {
  1004. hex = hex.replace("#","").toUpperCase();
  1005. var a = util.GiveDec(hex.substring(0, 1));
  1006. var b = util.GiveDec(hex.substring(1, 2));
  1007. var c = util.GiveDec(hex.substring(2, 3));
  1008. var d = util.GiveDec(hex.substring(3, 4));
  1009. var e = util.GiveDec(hex.substring(4, 5));
  1010. var f = util.GiveDec(hex.substring(5, 6));
  1011. var r = (a * 16) + b;
  1012. var g = (c * 16) + d;
  1013. var b = (e * 16) + f;
  1014. return {r:r,g:g,b:b};
  1015. };
  1016. util.RGBToHex = function RGBToHex(red,green,blue) {
  1017. var a = util.GiveHex(Math.floor(red / 16));
  1018. var b = util.GiveHex(red % 16);
  1019. var c = util.GiveHex(Math.floor(green / 16));
  1020. var d = util.GiveHex(green % 16);
  1021. var e = util.GiveHex(Math.floor(blue / 16));
  1022. var f = util.GiveHex(blue % 16);
  1023. var hex = a + b + c + d + e + f;
  1024. return "#" + hex;
  1025. };
  1026. /**
  1027. * http://www.javascripter.net/faq/rgb2hsv.htm
  1028. *
  1029. * @param red
  1030. * @param green
  1031. * @param blue
  1032. * @returns {*}
  1033. * @constructor
  1034. */
  1035. util.RGBToHSV = function RGBToHSV (red,green,blue) {
  1036. red=red/255; green=green/255; blue=blue/255;
  1037. var minRGB = Math.min(red,Math.min(green,blue));
  1038. var maxRGB = Math.max(red,Math.max(green,blue));
  1039. // Black-gray-white
  1040. if (minRGB == maxRGB) {
  1041. return {h:0,s:0,v:minRGB};
  1042. }
  1043. // Colors other than black-gray-white:
  1044. var d = (red==minRGB) ? green-blue : ((blue==minRGB) ? red-green : blue-red);
  1045. var h = (red==minRGB) ? 3 : ((blue==minRGB) ? 1 : 5);
  1046. var hue = 60*(h - d/(maxRGB - minRGB))/360;
  1047. var saturation = (maxRGB - minRGB)/maxRGB;
  1048. var value = maxRGB;
  1049. return {h:hue,s:saturation,v:value};
  1050. };
  1051. /**
  1052. * https://gist.github.com/mjijackson/5311256
  1053. * @param hue
  1054. * @param saturation
  1055. * @param value
  1056. * @returns {{r: number, g: number, b: number}}
  1057. * @constructor
  1058. */
  1059. util.HSVToRGB = function HSVToRGB(h, s, v) {
  1060. var r, g, b;
  1061. var i = Math.floor(h * 6);
  1062. var f = h * 6 - i;
  1063. var p = v * (1 - s);
  1064. var q = v * (1 - f * s);
  1065. var t = v * (1 - (1 - f) * s);
  1066. switch (i % 6) {
  1067. case 0: r = v, g = t, b = p; break;
  1068. case 1: r = q, g = v, b = p; break;
  1069. case 2: r = p, g = v, b = t; break;
  1070. case 3: r = p, g = q, b = v; break;
  1071. case 4: r = t, g = p, b = v; break;
  1072. case 5: r = v, g = p, b = q; break;
  1073. }
  1074. return {r:Math.floor(r * 255), g:Math.floor(g * 255), b:Math.floor(b * 255) };
  1075. };
  1076. util.HSVToHex = function HSVToHex(h, s, v) {
  1077. var rgb = util.HSVToRGB(h, s, v);
  1078. return util.RGBToHex(rgb.r, rgb.g, rgb.b);
  1079. };
  1080. util.hexToHSV = function hexToHSV(hex) {
  1081. var rgb = util.hexToRGB(hex);
  1082. return util.RGBToHSV(rgb.r, rgb.g, rgb.b);
  1083. };
  1084. util.isValidHex = function isValidHex(hex) {
  1085. var isOk = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(hex);
  1086. return isOk;
  1087. };
  1088. util.copyObject = function copyObject(objectFrom, objectTo) {
  1089. for (var i in objectFrom) {
  1090. if (objectFrom.hasOwnProperty(i)) {
  1091. if (typeof objectFrom[i] == "object") {
  1092. objectTo[i] = {};
  1093. util.copyObject(objectFrom[i], objectTo[i]);
  1094. }
  1095. else {
  1096. objectTo[i] = objectFrom[i];
  1097. }
  1098. }
  1099. }
  1100. };
  1101. /**
  1102. * DataSet
  1103. *
  1104. * Usage:
  1105. * var dataSet = new DataSet({
  1106. * fieldId: '_id',
  1107. * convert: {
  1108. * // ...
  1109. * }
  1110. * });
  1111. *
  1112. * dataSet.add(item);
  1113. * dataSet.add(data);
  1114. * dataSet.update(item);
  1115. * dataSet.update(data);
  1116. * dataSet.remove(id);
  1117. * dataSet.remove(ids);
  1118. * var data = dataSet.get();
  1119. * var data = dataSet.get(id);
  1120. * var data = dataSet.get(ids);
  1121. * var data = dataSet.get(ids, options, data);
  1122. * dataSet.clear();
  1123. *
  1124. * A data set can:
  1125. * - add/remove/update data
  1126. * - gives triggers upon changes in the data
  1127. * - can import/export data in various data formats
  1128. *
  1129. * @param {Array | DataTable} [data] Optional array with initial data
  1130. * @param {Object} [options] Available options:
  1131. * {String} fieldId Field name of the id in the
  1132. * items, 'id' by default.
  1133. * {Object.<String, String} convert
  1134. * A map with field names as key,
  1135. * and the field type as value.
  1136. * @constructor DataSet
  1137. */
  1138. // TODO: add a DataSet constructor DataSet(data, options)
  1139. function DataSet (data, options) {
  1140. this.id = util.randomUUID();
  1141. // correctly read optional arguments
  1142. if (data && !Array.isArray(data) && !util.isDataTable(data)) {
  1143. options = data;
  1144. data = null;
  1145. }
  1146. this.options = options || {};
  1147. this.data = {}; // map with data indexed by id
  1148. this.fieldId = this.options.fieldId || 'id'; // name of the field containing id
  1149. this.convert = {}; // field types by field name
  1150. this.showInternalIds = this.options.showInternalIds || false; // show internal ids with the get function
  1151. if (this.options.convert) {
  1152. for (var field in this.options.convert) {
  1153. if (this.options.convert.hasOwnProperty(field)) {
  1154. var value = this.options.convert[field];
  1155. if (value == 'Date' || value == 'ISODate' || value == 'ASPDate') {
  1156. this.convert[field] = 'Date';
  1157. }
  1158. else {
  1159. this.convert[field] = value;
  1160. }
  1161. }
  1162. }
  1163. }
  1164. this.subscribers = {}; // event subscribers
  1165. this.internalIds = {}; // internally generated id's
  1166. // add initial data when provided
  1167. if (data) {
  1168. this.add(data);
  1169. }
  1170. }
  1171. /**
  1172. * Subscribe to an event, add an event listener
  1173. * @param {String} event Event name. Available events: 'put', 'update',
  1174. * 'remove'
  1175. * @param {function} callback Callback method. Called with three parameters:
  1176. * {String} event
  1177. * {Object | null} params
  1178. * {String | Number} senderId
  1179. */
  1180. DataSet.prototype.on = function on (event, callback) {
  1181. var subscribers = this.subscribers[event];
  1182. if (!subscribers) {
  1183. subscribers = [];
  1184. this.subscribers[event] = subscribers;
  1185. }
  1186. subscribers.push({
  1187. callback: callback
  1188. });
  1189. };
  1190. // TODO: make this function deprecated (replaced with `on` since version 0.5)
  1191. DataSet.prototype.subscribe = DataSet.prototype.on;
  1192. /**
  1193. * Unsubscribe from an event, remove an event listener
  1194. * @param {String} event
  1195. * @param {function} callback
  1196. */
  1197. DataSet.prototype.off = function off(event, callback) {
  1198. var subscribers = this.subscribers[event];
  1199. if (subscribers) {
  1200. this.subscribers[event] = subscribers.filter(function (listener) {
  1201. return (listener.callback != callback);
  1202. });
  1203. }
  1204. };
  1205. // TODO: make this function deprecated (replaced with `on` since version 0.5)
  1206. DataSet.prototype.unsubscribe = DataSet.prototype.off;
  1207. /**
  1208. * Trigger an event
  1209. * @param {String} event
  1210. * @param {Object | null} params
  1211. * @param {String} [senderId] Optional id of the sender.
  1212. * @private
  1213. */
  1214. DataSet.prototype._trigger = function (event, params, senderId) {
  1215. if (event == '*') {
  1216. throw new Error('Cannot trigger event *');
  1217. }
  1218. var subscribers = [];
  1219. if (event in this.subscribers) {
  1220. subscribers = subscribers.concat(this.subscribers[event]);
  1221. }
  1222. if ('*' in this.subscribers) {
  1223. subscribers = subscribers.concat(this.subscribers['*']);
  1224. }
  1225. for (var i = 0; i < subscribers.length; i++) {
  1226. var subscriber = subscribers[i];
  1227. if (subscriber.callback) {
  1228. subscriber.callback(event, params, senderId || null);
  1229. }
  1230. }
  1231. };
  1232. /**
  1233. * Add data.
  1234. * Adding an item will fail when there already is an item with the same id.
  1235. * @param {Object | Array | DataTable} data
  1236. * @param {String} [senderId] Optional sender id
  1237. * @return {Array} addedIds Array with the ids of the added items
  1238. */
  1239. DataSet.prototype.add = function (data, senderId) {
  1240. var addedIds = [],
  1241. id,
  1242. me = this;
  1243. if (data instanceof Array) {
  1244. // Array
  1245. for (var i = 0, len = data.length; i < len; i++) {
  1246. id = me._addItem(data[i]);
  1247. addedIds.push(id);
  1248. }
  1249. }
  1250. else if (util.isDataTable(data)) {
  1251. // Google DataTable
  1252. var columns = this._getColumnNames(data);
  1253. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1254. var item = {};
  1255. for (var col = 0, cols = columns.length; col < cols; col++) {
  1256. var field = columns[col];
  1257. item[field] = data.getValue(row, col);
  1258. }
  1259. id = me._addItem(item);
  1260. addedIds.push(id);
  1261. }
  1262. }
  1263. else if (data instanceof Object) {
  1264. // Single item
  1265. id = me._addItem(data);
  1266. addedIds.push(id);
  1267. }
  1268. else {
  1269. throw new Error('Unknown dataType');
  1270. }
  1271. if (addedIds.length) {
  1272. this._trigger('add', {items: addedIds}, senderId);
  1273. }
  1274. return addedIds;
  1275. };
  1276. /**
  1277. * Update existing items. When an item does not exist, it will be created
  1278. * @param {Object | Array | DataTable} data
  1279. * @param {String} [senderId] Optional sender id
  1280. * @return {Array} updatedIds The ids of the added or updated items
  1281. */
  1282. DataSet.prototype.update = function (data, senderId) {
  1283. var addedIds = [],
  1284. updatedIds = [],
  1285. me = this,
  1286. fieldId = me.fieldId;
  1287. var addOrUpdate = function (item) {
  1288. var id = item[fieldId];
  1289. if (me.data[id]) {
  1290. // update item
  1291. id = me._updateItem(item);
  1292. updatedIds.push(id);
  1293. }
  1294. else {
  1295. // add new item
  1296. id = me._addItem(item);
  1297. addedIds.push(id);
  1298. }
  1299. };
  1300. if (data instanceof Array) {
  1301. // Array
  1302. for (var i = 0, len = data.length; i < len; i++) {
  1303. addOrUpdate(data[i]);
  1304. }
  1305. }
  1306. else if (util.isDataTable(data)) {
  1307. // Google DataTable
  1308. var columns = this._getColumnNames(data);
  1309. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1310. var item = {};
  1311. for (var col = 0, cols = columns.length; col < cols; col++) {
  1312. var field = columns[col];
  1313. item[field] = data.getValue(row, col);
  1314. }
  1315. addOrUpdate(item);
  1316. }
  1317. }
  1318. else if (data instanceof Object) {
  1319. // Single item
  1320. addOrUpdate(data);
  1321. }
  1322. else {
  1323. throw new Error('Unknown dataType');
  1324. }
  1325. if (addedIds.length) {
  1326. this._trigger('add', {items: addedIds}, senderId);
  1327. }
  1328. if (updatedIds.length) {
  1329. this._trigger('update', {items: updatedIds}, senderId);
  1330. }
  1331. return addedIds.concat(updatedIds);
  1332. };
  1333. /**
  1334. * Get a data item or multiple items.
  1335. *
  1336. * Usage:
  1337. *
  1338. * get()
  1339. * get(options: Object)
  1340. * get(options: Object, data: Array | DataTable)
  1341. *
  1342. * get(id: Number | String)
  1343. * get(id: Number | String, options: Object)
  1344. * get(id: Number | String, options: Object, data: Array | DataTable)
  1345. *
  1346. * get(ids: Number[] | String[])
  1347. * get(ids: Number[] | String[], options: Object)
  1348. * get(ids: Number[] | String[], options: Object, data: Array | DataTable)
  1349. *
  1350. * Where:
  1351. *
  1352. * {Number | String} id The id of an item
  1353. * {Number[] | String{}} ids An array with ids of items
  1354. * {Object} options An Object with options. Available options:
  1355. * {String} [type] Type of data to be returned. Can
  1356. * be 'DataTable' or 'Array' (default)
  1357. * {Object.<String, String>} [convert]
  1358. * {String[]} [fields] field names to be returned
  1359. * {function} [filter] filter items
  1360. * {String | function} [order] Order the items by
  1361. * a field name or custom sort function.
  1362. * {Array | DataTable} [data] If provided, items will be appended to this
  1363. * array or table. Required in case of Google
  1364. * DataTable.
  1365. *
  1366. * @throws Error
  1367. */
  1368. DataSet.prototype.get = function (args) {
  1369. var me = this;
  1370. var globalShowInternalIds = this.showInternalIds;
  1371. // parse the arguments
  1372. var id, ids, options, data;
  1373. var firstType = util.getType(arguments[0]);
  1374. if (firstType == 'String' || firstType == 'Number') {
  1375. // get(id [, options] [, data])
  1376. id = arguments[0];
  1377. options = arguments[1];
  1378. data = arguments[2];
  1379. }
  1380. else if (firstType == 'Array') {
  1381. // get(ids [, options] [, data])
  1382. ids = arguments[0];
  1383. options = arguments[1];
  1384. data = arguments[2];
  1385. }
  1386. else {
  1387. // get([, options] [, data])
  1388. options = arguments[0];
  1389. data = arguments[1];
  1390. }
  1391. // determine the return type
  1392. var type;
  1393. if (options && options.type) {
  1394. type = (options.type == 'DataTable') ? 'DataTable' : 'Array';
  1395. if (data && (type != util.getType(data))) {
  1396. throw new Error('Type of parameter "data" (' + util.getType(data) + ') ' +
  1397. 'does not correspond with specified options.type (' + options.type + ')');
  1398. }
  1399. if (type == 'DataTable' && !util.isDataTable(data)) {
  1400. throw new Error('Parameter "data" must be a DataTable ' +
  1401. 'when options.type is "DataTable"');
  1402. }
  1403. }
  1404. else if (data) {
  1405. type = (util.getType(data) == 'DataTable') ? 'DataTable' : 'Array';
  1406. }
  1407. else {
  1408. type = 'Array';
  1409. }
  1410. // we allow the setting of this value for a single get request.
  1411. if (options != undefined) {
  1412. if (options.showInternalIds != undefined) {
  1413. this.showInternalIds = options.showInternalIds;
  1414. }
  1415. }
  1416. // build options
  1417. var convert = options && options.convert || this.options.convert;
  1418. var filter = options && options.filter;
  1419. var items = [], item, itemId, i, len;
  1420. // convert items
  1421. if (id != undefined) {
  1422. // return a single item
  1423. item = me._getItem(id, convert);
  1424. if (filter && !filter(item)) {
  1425. item = null;
  1426. }
  1427. }
  1428. else if (ids != undefined) {
  1429. // return a subset of items
  1430. for (i = 0, len = ids.length; i < len; i++) {
  1431. item = me._getItem(ids[i], convert);
  1432. if (!filter || filter(item)) {
  1433. items.push(item);
  1434. }
  1435. }
  1436. }
  1437. else {
  1438. // return all items
  1439. for (itemId in this.data) {
  1440. if (this.data.hasOwnProperty(itemId)) {
  1441. item = me._getItem(itemId, convert);
  1442. if (!filter || filter(item)) {
  1443. items.push(item);
  1444. }
  1445. }
  1446. }
  1447. }
  1448. // restore the global value of showInternalIds
  1449. this.showInternalIds = globalShowInternalIds;
  1450. // order the results
  1451. if (options && options.order && id == undefined) {
  1452. this._sort(items, options.order);
  1453. }
  1454. // filter fields of the items
  1455. if (options && options.fields) {
  1456. var fields = options.fields;
  1457. if (id != undefined) {
  1458. item = this._filterFields(item, fields);
  1459. }
  1460. else {
  1461. for (i = 0, len = items.length; i < len; i++) {
  1462. items[i] = this._filterFields(items[i], fields);
  1463. }
  1464. }
  1465. }
  1466. // return the results
  1467. if (type == 'DataTable') {
  1468. var columns = this._getColumnNames(data);
  1469. if (id != undefined) {
  1470. // append a single item to the data table
  1471. me._appendRow(data, columns, item);
  1472. }
  1473. else {
  1474. // copy the items to the provided data table
  1475. for (i = 0, len = items.length; i < len; i++) {
  1476. me._appendRow(data, columns, items[i]);
  1477. }
  1478. }
  1479. return data;
  1480. }
  1481. else {
  1482. // return an array
  1483. if (id != undefined) {
  1484. // a single item
  1485. return item;
  1486. }
  1487. else {
  1488. // multiple items
  1489. if (data) {
  1490. // copy the items to the provided array
  1491. for (i = 0, len = items.length; i < len; i++) {
  1492. data.push(items[i]);
  1493. }
  1494. return data;
  1495. }
  1496. else {
  1497. // just return our array
  1498. return items;
  1499. }
  1500. }
  1501. }
  1502. };
  1503. /**
  1504. * Get ids of all items or from a filtered set of items.
  1505. * @param {Object} [options] An Object with options. Available options:
  1506. * {function} [filter] filter items
  1507. * {String | function} [order] Order the items by
  1508. * a field name or custom sort function.
  1509. * @return {Array} ids
  1510. */
  1511. DataSet.prototype.getIds = function (options) {
  1512. var data = this.data,
  1513. filter = options && options.filter,
  1514. order = options && options.order,
  1515. convert = options && options.convert || this.options.convert,
  1516. i,
  1517. len,
  1518. id,
  1519. item,
  1520. items,
  1521. ids = [];
  1522. if (filter) {
  1523. // get filtered items
  1524. if (order) {
  1525. // create ordered list
  1526. items = [];
  1527. for (id in data) {
  1528. if (data.hasOwnProperty(id)) {
  1529. item = this._getItem(id, convert);
  1530. if (filter(item)) {
  1531. items.push(item);
  1532. }
  1533. }
  1534. }
  1535. this._sort(items, order);
  1536. for (i = 0, len = items.length; i < len; i++) {
  1537. ids[i] = items[i][this.fieldId];
  1538. }
  1539. }
  1540. else {
  1541. // create unordered list
  1542. for (id in data) {
  1543. if (data.hasOwnProperty(id)) {
  1544. item = this._getItem(id, convert);
  1545. if (filter(item)) {
  1546. ids.push(item[this.fieldId]);
  1547. }
  1548. }
  1549. }
  1550. }
  1551. }
  1552. else {
  1553. // get all items
  1554. if (order) {
  1555. // create an ordered list
  1556. items = [];
  1557. for (id in data) {
  1558. if (data.hasOwnProperty(id)) {
  1559. items.push(data[id]);
  1560. }
  1561. }
  1562. this._sort(items, order);
  1563. for (i = 0, len = items.length; i < len; i++) {
  1564. ids[i] = items[i][this.fieldId];
  1565. }
  1566. }
  1567. else {
  1568. // create unordered list
  1569. for (id in data) {
  1570. if (data.hasOwnProperty(id)) {
  1571. item = data[id];
  1572. ids.push(item[this.fieldId]);
  1573. }
  1574. }
  1575. }
  1576. }
  1577. return ids;
  1578. };
  1579. /**
  1580. * Execute a callback function for every item in the dataset.
  1581. * @param {function} callback
  1582. * @param {Object} [options] Available options:
  1583. * {Object.<String, String>} [convert]
  1584. * {String[]} [fields] filter fields
  1585. * {function} [filter] filter items
  1586. * {String | function} [order] Order the items by
  1587. * a field name or custom sort function.
  1588. */
  1589. DataSet.prototype.forEach = function (callback, options) {
  1590. var filter = options && options.filter,
  1591. convert = options && options.convert || this.options.convert,
  1592. data = this.data,
  1593. item,
  1594. id;
  1595. if (options && options.order) {
  1596. // execute forEach on ordered list
  1597. var items = this.get(options);
  1598. for (var i = 0, len = items.length; i < len; i++) {
  1599. item = items[i];
  1600. id = item[this.fieldId];
  1601. callback(item, id);
  1602. }
  1603. }
  1604. else {
  1605. // unordered
  1606. for (id in data) {
  1607. if (data.hasOwnProperty(id)) {
  1608. item = this._getItem(id, convert);
  1609. if (!filter || filter(item)) {
  1610. callback(item, id);
  1611. }
  1612. }
  1613. }
  1614. }
  1615. };
  1616. /**
  1617. * Map every item in the dataset.
  1618. * @param {function} callback
  1619. * @param {Object} [options] Available options:
  1620. * {Object.<String, String>} [convert]
  1621. * {String[]} [fields] filter fields
  1622. * {function} [filter] filter items
  1623. * {String | function} [order] Order the items by
  1624. * a field name or custom sort function.
  1625. * @return {Object[]} mappedItems
  1626. */
  1627. DataSet.prototype.map = function (callback, options) {
  1628. var filter = options && options.filter,
  1629. convert = options && options.convert || this.options.convert,
  1630. mappedItems = [],
  1631. data = this.data,
  1632. item;
  1633. // convert and filter items
  1634. for (var id in data) {
  1635. if (data.hasOwnProperty(id)) {
  1636. item = this._getItem(id, convert);
  1637. if (!filter || filter(item)) {
  1638. mappedItems.push(callback(item, id));
  1639. }
  1640. }
  1641. }
  1642. // order items
  1643. if (options && options.order) {
  1644. this._sort(mappedItems, options.order);
  1645. }
  1646. return mappedItems;
  1647. };
  1648. /**
  1649. * Filter the fields of an item
  1650. * @param {Object} item
  1651. * @param {String[]} fields Field names
  1652. * @return {Object} filteredItem
  1653. * @private
  1654. */
  1655. DataSet.prototype._filterFields = function (item, fields) {
  1656. var filteredItem = {};
  1657. for (var field in item) {
  1658. if (item.hasOwnProperty(field) && (fields.indexOf(field) != -1)) {
  1659. filteredItem[field] = item[field];
  1660. }
  1661. }
  1662. return filteredItem;
  1663. };
  1664. /**
  1665. * Sort the provided array with items
  1666. * @param {Object[]} items
  1667. * @param {String | function} order A field name or custom sort function.
  1668. * @private
  1669. */
  1670. DataSet.prototype._sort = function (items, order) {
  1671. if (util.isString(order)) {
  1672. // order by provided field name
  1673. var name = order; // field name
  1674. items.sort(function (a, b) {
  1675. var av = a[name];
  1676. var bv = b[name];
  1677. return (av > bv) ? 1 : ((av < bv) ? -1 : 0);
  1678. });
  1679. }
  1680. else if (typeof order === 'function') {
  1681. // order by sort function
  1682. items.sort(order);
  1683. }
  1684. // TODO: extend order by an Object {field:String, direction:String}
  1685. // where direction can be 'asc' or 'desc'
  1686. else {
  1687. throw new TypeError('Order must be a function or a string');
  1688. }
  1689. };
  1690. /**
  1691. * Remove an object by pointer or by id
  1692. * @param {String | Number | Object | Array} id Object or id, or an array with
  1693. * objects or ids to be removed
  1694. * @param {String} [senderId] Optional sender id
  1695. * @return {Array} removedIds
  1696. */
  1697. DataSet.prototype.remove = function (id, senderId) {
  1698. var removedIds = [],
  1699. i, len, removedId;
  1700. if (id instanceof Array) {
  1701. for (i = 0, len = id.length; i < len; i++) {
  1702. removedId = this._remove(id[i]);
  1703. if (removedId != null) {
  1704. removedIds.push(removedId);
  1705. }
  1706. }
  1707. }
  1708. else {
  1709. removedId = this._remove(id);
  1710. if (removedId != null) {
  1711. removedIds.push(removedId);
  1712. }
  1713. }
  1714. if (removedIds.length) {
  1715. this._trigger('remove', {items: removedIds}, senderId);
  1716. }
  1717. return removedIds;
  1718. };
  1719. /**
  1720. * Remove an item by its id
  1721. * @param {Number | String | Object} id id or item
  1722. * @returns {Number | String | null} id
  1723. * @private
  1724. */
  1725. DataSet.prototype._remove = function (id) {
  1726. if (util.isNumber(id) || util.isString(id)) {
  1727. if (this.data[id]) {
  1728. delete this.data[id];
  1729. delete this.internalIds[id];
  1730. return id;
  1731. }
  1732. }
  1733. else if (id instanceof Object) {
  1734. var itemId = id[this.fieldId];
  1735. if (itemId && this.data[itemId]) {
  1736. delete this.data[itemId];
  1737. delete this.internalIds[itemId];
  1738. return itemId;
  1739. }
  1740. }
  1741. return null;
  1742. };
  1743. /**
  1744. * Clear the data
  1745. * @param {String} [senderId] Optional sender id
  1746. * @return {Array} removedIds The ids of all removed items
  1747. */
  1748. DataSet.prototype.clear = function (senderId) {
  1749. var ids = Object.keys(this.data);
  1750. this.data = {};
  1751. this.internalIds = {};
  1752. this._trigger('remove', {items: ids}, senderId);
  1753. return ids;
  1754. };
  1755. /**
  1756. * Find the item with maximum value of a specified field
  1757. * @param {String} field
  1758. * @return {Object | null} item Item containing max value, or null if no items
  1759. */
  1760. DataSet.prototype.max = function (field) {
  1761. var data = this.data,
  1762. max = null,
  1763. maxField = null;
  1764. for (var id in data) {
  1765. if (data.hasOwnProperty(id)) {
  1766. var item = data[id];
  1767. var itemField = item[field];
  1768. if (itemField != null && (!max || itemField > maxField)) {
  1769. max = item;
  1770. maxField = itemField;
  1771. }
  1772. }
  1773. }
  1774. return max;
  1775. };
  1776. /**
  1777. * Find the item with minimum value of a specified field
  1778. * @param {String} field
  1779. * @return {Object | null} item Item containing max value, or null if no items
  1780. */
  1781. DataSet.prototype.min = function (field) {
  1782. var data = this.data,
  1783. min = null,
  1784. minField = null;
  1785. for (var id in data) {
  1786. if (data.hasOwnProperty(id)) {
  1787. var item = data[id];
  1788. var itemField = item[field];
  1789. if (itemField != null && (!min || itemField < minField)) {
  1790. min = item;
  1791. minField = itemField;
  1792. }
  1793. }
  1794. }
  1795. return min;
  1796. };
  1797. /**
  1798. * Find all distinct values of a specified field
  1799. * @param {String} field
  1800. * @return {Array} values Array containing all distinct values. If data items
  1801. * do not contain the specified field are ignored.
  1802. * The returned array is unordered.
  1803. */
  1804. DataSet.prototype.distinct = function (field) {
  1805. var data = this.data,
  1806. values = [],
  1807. fieldType = this.options.convert[field],
  1808. count = 0;
  1809. for (var prop in data) {
  1810. if (data.hasOwnProperty(prop)) {
  1811. var item = data[prop];
  1812. var value = util.convert(item[field], fieldType);
  1813. var exists = false;
  1814. for (var i = 0; i < count; i++) {
  1815. if (values[i] == value) {
  1816. exists = true;
  1817. break;
  1818. }
  1819. }
  1820. if (!exists && (value !== undefined)) {
  1821. values[count] = value;
  1822. count++;
  1823. }
  1824. }
  1825. }
  1826. return values;
  1827. };
  1828. /**
  1829. * Add a single item. Will fail when an item with the same id already exists.
  1830. * @param {Object} item
  1831. * @return {String} id
  1832. * @private
  1833. */
  1834. DataSet.prototype._addItem = function (item) {
  1835. var id = item[this.fieldId];
  1836. if (id != undefined) {
  1837. // check whether this id is already taken
  1838. if (this.data[id]) {
  1839. // item already exists
  1840. throw new Error('Cannot add item: item with id ' + id + ' already exists');
  1841. }
  1842. }
  1843. else {
  1844. // generate an id
  1845. id = util.randomUUID();
  1846. item[this.fieldId] = id;
  1847. this.internalIds[id] = item;
  1848. }
  1849. var d = {};
  1850. for (var field in item) {
  1851. if (item.hasOwnProperty(field)) {
  1852. var fieldType = this.convert[field]; // type may be undefined
  1853. d[field] = util.convert(item[field], fieldType);
  1854. }
  1855. }
  1856. this.data[id] = d;
  1857. return id;
  1858. };
  1859. /**
  1860. * Get an item. Fields can be converted to a specific type
  1861. * @param {String} id
  1862. * @param {Object.<String, String>} [convert] field types to convert
  1863. * @return {Object | null} item
  1864. * @private
  1865. */
  1866. DataSet.prototype._getItem = function (id, convert) {
  1867. var field, value;
  1868. // get the item from the dataset
  1869. var raw = this.data[id];
  1870. if (!raw) {
  1871. return null;
  1872. }
  1873. // convert the items field types
  1874. var converted = {},
  1875. fieldId = this.fieldId,
  1876. internalIds = this.internalIds;
  1877. if (convert) {
  1878. for (field in raw) {
  1879. if (raw.hasOwnProperty(field)) {
  1880. value = raw[field];
  1881. // output all fields, except internal ids
  1882. if ((field != fieldId) || (!(value in internalIds) || this.showInternalIds)) {
  1883. converted[field] = util.convert(value, convert[field]);
  1884. }
  1885. }
  1886. }
  1887. }
  1888. else {
  1889. // no field types specified, no converting needed
  1890. for (field in raw) {
  1891. if (raw.hasOwnProperty(field)) {
  1892. value = raw[field];
  1893. // output all fields, except internal ids
  1894. if ((field != fieldId) || (!(value in internalIds) || this.showInternalIds)) {
  1895. converted[field] = value;
  1896. }
  1897. }
  1898. }
  1899. }
  1900. return converted;
  1901. };
  1902. /**
  1903. * Update a single item: merge with existing item.
  1904. * Will fail when the item has no id, or when there does not exist an item
  1905. * with the same id.
  1906. * @param {Object} item
  1907. * @return {String} id
  1908. * @private
  1909. */
  1910. DataSet.prototype._updateItem = function (item) {
  1911. var id = item[this.fieldId];
  1912. if (id == undefined) {
  1913. throw new Error('Cannot update item: item has no id (item: ' + JSON.stringify(item) + ')');
  1914. }
  1915. var d = this.data[id];
  1916. if (!d) {
  1917. // item doesn't exist
  1918. throw new Error('Cannot update item: no item with id ' + id + ' found');
  1919. }
  1920. // merge with current item
  1921. for (var field in item) {
  1922. if (item.hasOwnProperty(field)) {
  1923. var fieldType = this.convert[field]; // type may be undefined
  1924. d[field] = util.convert(item[field], fieldType);
  1925. }
  1926. }
  1927. return id;
  1928. };
  1929. /**
  1930. * check if an id is an internal or external id
  1931. * @param id
  1932. * @returns {boolean}
  1933. * @private
  1934. */
  1935. DataSet.prototype.isInternalId = function(id) {
  1936. return (id in this.internalIds);
  1937. };
  1938. /**
  1939. * Get an array with the column names of a Google DataTable
  1940. * @param {DataTable} dataTable
  1941. * @return {String[]} columnNames
  1942. * @private
  1943. */
  1944. DataSet.prototype._getColumnNames = function (dataTable) {
  1945. var columns = [];
  1946. for (var col = 0, cols = dataTable.getNumberOfColumns(); col < cols; col++) {
  1947. columns[col] = dataTable.getColumnId(col) || dataTable.getColumnLabel(col);
  1948. }
  1949. return columns;
  1950. };
  1951. /**
  1952. * Append an item as a row to the dataTable
  1953. * @param dataTable
  1954. * @param columns
  1955. * @param item
  1956. * @private
  1957. */
  1958. DataSet.prototype._appendRow = function (dataTable, columns, item) {
  1959. var row = dataTable.addRow();
  1960. for (var col = 0, cols = columns.length; col < cols; col++) {
  1961. var field = columns[col];
  1962. dataTable.setValue(row, col, item[field]);
  1963. }
  1964. };
  1965. /**
  1966. * DataView
  1967. *
  1968. * a dataview offers a filtered view on a dataset or an other dataview.
  1969. *
  1970. * @param {DataSet | DataView} data
  1971. * @param {Object} [options] Available options: see method get
  1972. *
  1973. * @constructor DataView
  1974. */
  1975. function DataView (data, options) {
  1976. this.id = util.randomUUID();
  1977. this.data = null;
  1978. this.ids = {}; // ids of the items currently in memory (just contains a boolean true)
  1979. this.options = options || {};
  1980. this.fieldId = 'id'; // name of the field containing id
  1981. this.subscribers = {}; // event subscribers
  1982. var me = this;
  1983. this.listener = function () {
  1984. me._onEvent.apply(me, arguments);
  1985. };
  1986. this.setData(data);
  1987. }
  1988. // TODO: implement a function .config() to dynamically update things like configured filter
  1989. // and trigger changes accordingly
  1990. /**
  1991. * Set a data source for the view
  1992. * @param {DataSet | DataView} data
  1993. */
  1994. DataView.prototype.setData = function (data) {
  1995. var ids, dataItems, i, len;
  1996. if (this.data) {
  1997. // unsubscribe from current dataset
  1998. if (this.data.unsubscribe) {
  1999. this.data.unsubscribe('*', this.listener);
  2000. }
  2001. // trigger a remove of all items in memory
  2002. ids = [];
  2003. for (var id in this.ids) {
  2004. if (this.ids.hasOwnProperty(id)) {
  2005. ids.push(id);
  2006. }
  2007. }
  2008. this.ids = {};
  2009. this._trigger('remove', {items: ids});
  2010. }
  2011. this.data = data;
  2012. if (this.data) {
  2013. // update fieldId
  2014. this.fieldId = this.options.fieldId ||
  2015. (this.data && this.data.options && this.data.options.fieldId) ||
  2016. 'id';
  2017. // trigger an add of all added items
  2018. ids = this.data.getIds({filter: this.options && this.options.filter});
  2019. for (i = 0, len = ids.length; i < len; i++) {
  2020. id = ids[i];
  2021. this.ids[id] = true;
  2022. }
  2023. this._trigger('add', {items: ids});
  2024. // subscribe to new dataset
  2025. if (this.data.on) {
  2026. this.data.on('*', this.listener);
  2027. }
  2028. }
  2029. };
  2030. /**
  2031. * Get data from the data view
  2032. *
  2033. * Usage:
  2034. *
  2035. * get()
  2036. * get(options: Object)
  2037. * get(options: Object, data: Array | DataTable)
  2038. *
  2039. * get(id: Number)
  2040. * get(id: Number, options: Object)
  2041. * get(id: Number, options: Object, data: Array | DataTable)
  2042. *
  2043. * get(ids: Number[])
  2044. * get(ids: Number[], options: Object)
  2045. * get(ids: Number[], options: Object, data: Array | DataTable)
  2046. *
  2047. * Where:
  2048. *
  2049. * {Number | String} id The id of an item
  2050. * {Number[] | String{}} ids An array with ids of items
  2051. * {Object} options An Object with options. Available options:
  2052. * {String} [type] Type of data to be returned. Can
  2053. * be 'DataTable' or 'Array' (default)
  2054. * {Object.<String, String>} [convert]
  2055. * {String[]} [fields] field names to be returned
  2056. * {function} [filter] filter items
  2057. * {String | function} [order] Order the items by
  2058. * a field name or custom sort function.
  2059. * {Array | DataTable} [data] If provided, items will be appended to this
  2060. * array or table. Required in case of Google
  2061. * DataTable.
  2062. * @param args
  2063. */
  2064. DataView.prototype.get = function (args) {
  2065. var me = this;
  2066. // parse the arguments
  2067. var ids, options, data;
  2068. var firstType = util.getType(arguments[0]);
  2069. if (firstType == 'String' || firstType == 'Number' || firstType == 'Array') {
  2070. // get(id(s) [, options] [, data])
  2071. ids = arguments[0]; // can be a single id or an array with ids
  2072. options = arguments[1];
  2073. data = arguments[2];
  2074. }
  2075. else {
  2076. // get([, options] [, data])
  2077. options = arguments[0];
  2078. data = arguments[1];
  2079. }
  2080. // extend the options with the default options and provided options
  2081. var viewOptions = util.extend({}, this.options, options);
  2082. // create a combined filter method when needed
  2083. if (this.options.filter && options && options.filter) {
  2084. viewOptions.filter = function (item) {
  2085. return me.options.filter(item) && options.filter(item);
  2086. }
  2087. }
  2088. // build up the call to the linked data set
  2089. var getArguments = [];
  2090. if (ids != undefined) {
  2091. getArguments.push(ids);
  2092. }
  2093. getArguments.push(viewOptions);
  2094. getArguments.push(data);
  2095. return this.data && this.data.get.apply(this.data, getArguments);
  2096. };
  2097. /**
  2098. * Get ids of all items or from a filtered set of items.
  2099. * @param {Object} [options] An Object with options. Available options:
  2100. * {function} [filter] filter items
  2101. * {String | function} [order] Order the items by
  2102. * a field name or custom sort function.
  2103. * @return {Array} ids
  2104. */
  2105. DataView.prototype.getIds = function (options) {
  2106. var ids;
  2107. if (this.data) {
  2108. var defaultFilter = this.options.filter;
  2109. var filter;
  2110. if (options && options.filter) {
  2111. if (defaultFilter) {
  2112. filter = function (item) {
  2113. return defaultFilter(item) && options.filter(item);
  2114. }
  2115. }
  2116. else {
  2117. filter = options.filter;
  2118. }
  2119. }
  2120. else {
  2121. filter = defaultFilter;
  2122. }
  2123. ids = this.data.getIds({
  2124. filter: filter,
  2125. order: options && options.order
  2126. });
  2127. }
  2128. else {
  2129. ids = [];
  2130. }
  2131. return ids;
  2132. };
  2133. /**
  2134. * Event listener. Will propagate all events from the connected data set to
  2135. * the subscribers of the DataView, but will filter the items and only trigger
  2136. * when there are changes in the filtered data set.
  2137. * @param {String} event
  2138. * @param {Object | null} params
  2139. * @param {String} senderId
  2140. * @private
  2141. */
  2142. DataView.prototype._onEvent = function (event, params, senderId) {
  2143. var i, len, id, item,
  2144. ids = params && params.items,
  2145. data = this.data,
  2146. added = [],
  2147. updated = [],
  2148. removed = [];
  2149. if (ids && data) {
  2150. switch (event) {
  2151. case 'add':
  2152. // filter the ids of the added items
  2153. for (i = 0, len = ids.length; i < len; i++) {
  2154. id = ids[i];
  2155. item = this.get(id);
  2156. if (item) {
  2157. this.ids[id] = true;
  2158. added.push(id);
  2159. }
  2160. }
  2161. break;
  2162. case 'update':
  2163. // determine the event from the views viewpoint: an updated
  2164. // item can be added, updated, or removed from this view.
  2165. for (i = 0, len = ids.length; i < len; i++) {
  2166. id = ids[i];
  2167. item = this.get(id);
  2168. if (item) {
  2169. if (this.ids[id]) {
  2170. updated.push(id);
  2171. }
  2172. else {
  2173. this.ids[id] = true;
  2174. added.push(id);
  2175. }
  2176. }
  2177. else {
  2178. if (this.ids[id]) {
  2179. delete this.ids[id];
  2180. removed.push(id);
  2181. }
  2182. else {
  2183. // nothing interesting for me :-(
  2184. }
  2185. }
  2186. }
  2187. break;
  2188. case 'remove':
  2189. // filter the ids of the removed items
  2190. for (i = 0, len = ids.length; i < len; i++) {
  2191. id = ids[i];
  2192. if (this.ids[id]) {
  2193. delete this.ids[id];
  2194. removed.push(id);
  2195. }
  2196. }
  2197. break;
  2198. }
  2199. if (added.length) {
  2200. this._trigger('add', {items: added}, senderId);
  2201. }
  2202. if (updated.length) {
  2203. this._trigger('update', {items: updated}, senderId);
  2204. }
  2205. if (removed.length) {
  2206. this._trigger('remove', {items: removed}, senderId);
  2207. }
  2208. }
  2209. };
  2210. // copy subscription functionality from DataSet
  2211. DataView.prototype.on = DataSet.prototype.on;
  2212. DataView.prototype.off = DataSet.prototype.off;
  2213. DataView.prototype._trigger = DataSet.prototype._trigger;
  2214. // TODO: make these functions deprecated (replaced with `on` and `off` since version 0.5)
  2215. DataView.prototype.subscribe = DataView.prototype.on;
  2216. DataView.prototype.unsubscribe = DataView.prototype.off;
  2217. /**
  2218. * Utility functions for ordering and stacking of items
  2219. */
  2220. var stack = {};
  2221. /**
  2222. * Order items by their start data
  2223. * @param {Item[]} items
  2224. */
  2225. stack.orderByStart = function orderByStart(items) {
  2226. items.sort(function (a, b) {
  2227. return a.data.start - b.data.start;
  2228. });
  2229. };
  2230. /**
  2231. * Order items by their end date. If they have no end date, their start date
  2232. * is used.
  2233. * @param {Item[]} items
  2234. */
  2235. stack.orderByEnd = function orderByEnd(items) {
  2236. items.sort(function (a, b) {
  2237. var aTime = ('end' in a.data) ? a.data.end : a.data.start,
  2238. bTime = ('end' in b.data) ? b.data.end : b.data.start;
  2239. return aTime - bTime;
  2240. });
  2241. };
  2242. /**
  2243. * Adjust vertical positions of the items such that they don't overlap each
  2244. * other.
  2245. * @param {Item[]} items
  2246. * All visible items
  2247. * @param {{item: number, axis: number}} margin
  2248. * Margins between items and between items and the axis.
  2249. * @param {boolean} [force=false]
  2250. * If true, all items will be repositioned. If false (default), only
  2251. * items having a top===null will be re-stacked
  2252. */
  2253. stack.stack = function _stack (items, margin, force) {
  2254. var i, iMax;
  2255. if (force) {
  2256. // reset top position of all items
  2257. for (i = 0, iMax = items.length; i < iMax; i++) {
  2258. items[i].top = null;
  2259. }
  2260. }
  2261. // calculate new, non-overlapping positions
  2262. for (i = 0, iMax = items.length; i < iMax; i++) {
  2263. var item = items[i];
  2264. if (item.top === null) {
  2265. // initialize top position
  2266. item.top = margin.axis;
  2267. do {
  2268. // TODO: optimize checking for overlap. when there is a gap without items,
  2269. // you only need to check for items from the next item on, not from zero
  2270. var collidingItem = null;
  2271. for (var j = 0, jj = items.length; j < jj; j++) {
  2272. var other = items[j];
  2273. if (other.top !== null && other !== item && stack.collision(item, other, margin.item)) {
  2274. collidingItem = other;
  2275. break;
  2276. }
  2277. }
  2278. if (collidingItem != null) {
  2279. // There is a collision. Reposition the items above the colliding element
  2280. item.top = collidingItem.top + collidingItem.height + margin.item;
  2281. }
  2282. } while (collidingItem);
  2283. }
  2284. }
  2285. };
  2286. /**
  2287. * Adjust vertical positions of the items without stacking them
  2288. * @param {Item[]} items
  2289. * All visible items
  2290. * @param {{item: number, axis: number}} margin
  2291. * Margins between items and between items and the axis.
  2292. */
  2293. stack.nostack = function nostack (items, margin) {
  2294. var i, iMax;
  2295. // reset top position of all items
  2296. for (i = 0, iMax = items.length; i < iMax; i++) {
  2297. items[i].top = margin.axis;
  2298. }
  2299. };
  2300. /**
  2301. * Test if the two provided items collide
  2302. * The items must have parameters left, width, top, and height.
  2303. * @param {Item} a The first item
  2304. * @param {Item} b The second item
  2305. * @param {Number} margin A minimum required margin.
  2306. * If margin is provided, the two items will be
  2307. * marked colliding when they overlap or
  2308. * when the margin between the two is smaller than
  2309. * the requested margin.
  2310. * @return {boolean} true if a and b collide, else false
  2311. */
  2312. stack.collision = function collision (a, b, margin) {
  2313. return ((a.left - margin) < (b.left + b.width) &&
  2314. (a.left + a.width + margin) > b.left &&
  2315. (a.top - margin) < (b.top + b.height) &&
  2316. (a.top + a.height + margin) > b.top);
  2317. };
  2318. /**
  2319. * @constructor TimeStep
  2320. * The class TimeStep is an iterator for dates. You provide a start date and an
  2321. * end date. The class itself determines the best scale (step size) based on the
  2322. * provided start Date, end Date, and minimumStep.
  2323. *
  2324. * If minimumStep is provided, the step size is chosen as close as possible
  2325. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2326. * provided, the scale is set to 1 DAY.
  2327. * The minimumStep should correspond with the onscreen size of about 6 characters
  2328. *
  2329. * Alternatively, you can set a scale by hand.
  2330. * After creation, you can initialize the class by executing first(). Then you
  2331. * can iterate from the start date to the end date via next(). You can check if
  2332. * the end date is reached with the function hasNext(). After each step, you can
  2333. * retrieve the current date via getCurrent().
  2334. * The TimeStep has scales ranging from milliseconds, seconds, minutes, hours,
  2335. * days, to years.
  2336. *
  2337. * Version: 1.2
  2338. *
  2339. * @param {Date} [start] The start date, for example new Date(2010, 9, 21)
  2340. * or new Date(2010, 9, 21, 23, 45, 00)
  2341. * @param {Date} [end] The end date
  2342. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  2343. */
  2344. function TimeStep(start, end, minimumStep) {
  2345. // variables
  2346. this.current = new Date();
  2347. this._start = new Date();
  2348. this._end = new Date();
  2349. this.autoScale = true;
  2350. this.scale = TimeStep.SCALE.DAY;
  2351. this.step = 1;
  2352. // initialize the range
  2353. this.setRange(start, end, minimumStep);
  2354. }
  2355. /// enum scale
  2356. TimeStep.SCALE = {
  2357. MILLISECOND: 1,
  2358. SECOND: 2,
  2359. MINUTE: 3,
  2360. HOUR: 4,
  2361. DAY: 5,
  2362. WEEKDAY: 6,
  2363. MONTH: 7,
  2364. YEAR: 8
  2365. };
  2366. /**
  2367. * Set a new range
  2368. * If minimumStep is provided, the step size is chosen as close as possible
  2369. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2370. * provided, the scale is set to 1 DAY.
  2371. * The minimumStep should correspond with the onscreen size of about 6 characters
  2372. * @param {Date} [start] The start date and time.
  2373. * @param {Date} [end] The end date and time.
  2374. * @param {int} [minimumStep] Optional. Minimum step size in milliseconds
  2375. */
  2376. TimeStep.prototype.setRange = function(start, end, minimumStep) {
  2377. if (!(start instanceof Date) || !(end instanceof Date)) {
  2378. throw "No legal start or end date in method setRange";
  2379. }
  2380. this._start = (start != undefined) ? new Date(start.valueOf()) : new Date();
  2381. this._end = (end != undefined) ? new Date(end.valueOf()) : new Date();
  2382. if (this.autoScale) {
  2383. this.setMinimumStep(minimumStep);
  2384. }
  2385. };
  2386. /**
  2387. * Set the range iterator to the start date.
  2388. */
  2389. TimeStep.prototype.first = function() {
  2390. this.current = new Date(this._start.valueOf());
  2391. this.roundToMinor();
  2392. };
  2393. /**
  2394. * Round the current date to the first minor date value
  2395. * This must be executed once when the current date is set to start Date
  2396. */
  2397. TimeStep.prototype.roundToMinor = function() {
  2398. // round to floor
  2399. // IMPORTANT: we have no breaks in this switch! (this is no bug)
  2400. //noinspection FallthroughInSwitchStatementJS
  2401. switch (this.scale) {
  2402. case TimeStep.SCALE.YEAR:
  2403. this.current.setFullYear(this.step * Math.floor(this.current.getFullYear() / this.step));
  2404. this.current.setMonth(0);
  2405. case TimeStep.SCALE.MONTH: this.current.setDate(1);
  2406. case TimeStep.SCALE.DAY: // intentional fall through
  2407. case TimeStep.SCALE.WEEKDAY: this.current.setHours(0);
  2408. case TimeStep.SCALE.HOUR: this.current.setMinutes(0);
  2409. case TimeStep.SCALE.MINUTE: this.current.setSeconds(0);
  2410. case TimeStep.SCALE.SECOND: this.current.setMilliseconds(0);
  2411. //case TimeStep.SCALE.MILLISECOND: // nothing to do for milliseconds
  2412. }
  2413. if (this.step != 1) {
  2414. // round down to the first minor value that is a multiple of the current step size
  2415. switch (this.scale) {
  2416. case TimeStep.SCALE.MILLISECOND: this.current.setMilliseconds(this.current.getMilliseconds() - this.current.getMilliseconds() % this.step); break;
  2417. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() - this.current.getSeconds() % this.step); break;
  2418. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() - this.current.getMinutes() % this.step); break;
  2419. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() - this.current.getHours() % this.step); break;
  2420. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2421. case TimeStep.SCALE.DAY: this.current.setDate((this.current.getDate()-1) - (this.current.getDate()-1) % this.step + 1); break;
  2422. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() - this.current.getMonth() % this.step); break;
  2423. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() - this.current.getFullYear() % this.step); break;
  2424. default: break;
  2425. }
  2426. }
  2427. };
  2428. /**
  2429. * Check if the there is a next step
  2430. * @return {boolean} true if the current date has not passed the end date
  2431. */
  2432. TimeStep.prototype.hasNext = function () {
  2433. return (this.current.valueOf() <= this._end.valueOf());
  2434. };
  2435. /**
  2436. * Do the next step
  2437. */
  2438. TimeStep.prototype.next = function() {
  2439. var prev = this.current.valueOf();
  2440. // Two cases, needed to prevent issues with switching daylight savings
  2441. // (end of March and end of October)
  2442. if (this.current.getMonth() < 6) {
  2443. switch (this.scale) {
  2444. case TimeStep.SCALE.MILLISECOND:
  2445. this.current = new Date(this.current.valueOf() + this.step); break;
  2446. case TimeStep.SCALE.SECOND: this.current = new Date(this.current.valueOf() + this.step * 1000); break;
  2447. case TimeStep.SCALE.MINUTE: this.current = new Date(this.current.valueOf() + this.step * 1000 * 60); break;
  2448. case TimeStep.SCALE.HOUR:
  2449. this.current = new Date(this.current.valueOf() + this.step * 1000 * 60 * 60);
  2450. // in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...)
  2451. var h = this.current.getHours();
  2452. this.current.setHours(h - (h % this.step));
  2453. break;
  2454. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2455. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2456. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2457. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2458. default: break;
  2459. }
  2460. }
  2461. else {
  2462. switch (this.scale) {
  2463. case TimeStep.SCALE.MILLISECOND: this.current = new Date(this.current.valueOf() + this.step); break;
  2464. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() + this.step); break;
  2465. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() + this.step); break;
  2466. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() + this.step); break;
  2467. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2468. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2469. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2470. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2471. default: break;
  2472. }
  2473. }
  2474. if (this.step != 1) {
  2475. // round down to the correct major value
  2476. switch (this.scale) {
  2477. case TimeStep.SCALE.MILLISECOND: if(this.current.getMilliseconds() < this.step) this.current.setMilliseconds(0); break;
  2478. case TimeStep.SCALE.SECOND: if(this.current.getSeconds() < this.step) this.current.setSeconds(0); break;
  2479. case TimeStep.SCALE.MINUTE: if(this.current.getMinutes() < this.step) this.current.setMinutes(0); break;
  2480. case TimeStep.SCALE.HOUR: if(this.current.getHours() < this.step) this.current.setHours(0); break;
  2481. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2482. case TimeStep.SCALE.DAY: if(this.current.getDate() < this.step+1) this.current.setDate(1); break;
  2483. case TimeStep.SCALE.MONTH: if(this.current.getMonth() < this.step) this.current.setMonth(0); break;
  2484. case TimeStep.SCALE.YEAR: break; // nothing to do for year
  2485. default: break;
  2486. }
  2487. }
  2488. // safety mechanism: if current time is still unchanged, move to the end
  2489. if (this.current.valueOf() == prev) {
  2490. this.current = new Date(this._end.valueOf());
  2491. }
  2492. };
  2493. /**
  2494. * Get the current datetime
  2495. * @return {Date} current The current date
  2496. */
  2497. TimeStep.prototype.getCurrent = function() {
  2498. return this.current;
  2499. };
  2500. /**
  2501. * Set a custom scale. Autoscaling will be disabled.
  2502. * For example setScale(SCALE.MINUTES, 5) will result
  2503. * in minor steps of 5 minutes, and major steps of an hour.
  2504. *
  2505. * @param {TimeStep.SCALE} newScale
  2506. * A scale. Choose from SCALE.MILLISECOND,
  2507. * SCALE.SECOND, SCALE.MINUTE, SCALE.HOUR,
  2508. * SCALE.WEEKDAY, SCALE.DAY, SCALE.MONTH,
  2509. * SCALE.YEAR.
  2510. * @param {Number} newStep A step size, by default 1. Choose for
  2511. * example 1, 2, 5, or 10.
  2512. */
  2513. TimeStep.prototype.setScale = function(newScale, newStep) {
  2514. this.scale = newScale;
  2515. if (newStep > 0) {
  2516. this.step = newStep;
  2517. }
  2518. this.autoScale = false;
  2519. };
  2520. /**
  2521. * Enable or disable autoscaling
  2522. * @param {boolean} enable If true, autoascaling is set true
  2523. */
  2524. TimeStep.prototype.setAutoScale = function (enable) {
  2525. this.autoScale = enable;
  2526. };
  2527. /**
  2528. * Automatically determine the scale that bests fits the provided minimum step
  2529. * @param {Number} [minimumStep] The minimum step size in milliseconds
  2530. */
  2531. TimeStep.prototype.setMinimumStep = function(minimumStep) {
  2532. if (minimumStep == undefined) {
  2533. return;
  2534. }
  2535. var stepYear = (1000 * 60 * 60 * 24 * 30 * 12);
  2536. var stepMonth = (1000 * 60 * 60 * 24 * 30);
  2537. var stepDay = (1000 * 60 * 60 * 24);
  2538. var stepHour = (1000 * 60 * 60);
  2539. var stepMinute = (1000 * 60);
  2540. var stepSecond = (1000);
  2541. var stepMillisecond= (1);
  2542. // find the smallest step that is larger than the provided minimumStep
  2543. if (stepYear*1000 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1000;}
  2544. if (stepYear*500 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 500;}
  2545. if (stepYear*100 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 100;}
  2546. if (stepYear*50 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 50;}
  2547. if (stepYear*10 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 10;}
  2548. if (stepYear*5 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 5;}
  2549. if (stepYear > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1;}
  2550. if (stepMonth*3 > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 3;}
  2551. if (stepMonth > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 1;}
  2552. if (stepDay*5 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 5;}
  2553. if (stepDay*2 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 2;}
  2554. if (stepDay > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 1;}
  2555. if (stepDay/2 > minimumStep) {this.scale = TimeStep.SCALE.WEEKDAY; this.step = 1;}
  2556. if (stepHour*4 > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 4;}
  2557. if (stepHour > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 1;}
  2558. if (stepMinute*15 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 15;}
  2559. if (stepMinute*10 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 10;}
  2560. if (stepMinute*5 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 5;}
  2561. if (stepMinute > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 1;}
  2562. if (stepSecond*15 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 15;}
  2563. if (stepSecond*10 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 10;}
  2564. if (stepSecond*5 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 5;}
  2565. if (stepSecond > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 1;}
  2566. if (stepMillisecond*200 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 200;}
  2567. if (stepMillisecond*100 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 100;}
  2568. if (stepMillisecond*50 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 50;}
  2569. if (stepMillisecond*10 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 10;}
  2570. if (stepMillisecond*5 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 5;}
  2571. if (stepMillisecond > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 1;}
  2572. };
  2573. /**
  2574. * Snap a date to a rounded value.
  2575. * The snap intervals are dependent on the current scale and step.
  2576. * @param {Date} date the date to be snapped.
  2577. * @return {Date} snappedDate
  2578. */
  2579. TimeStep.prototype.snap = function(date) {
  2580. var clone = new Date(date.valueOf());
  2581. if (this.scale == TimeStep.SCALE.YEAR) {
  2582. var year = clone.getFullYear() + Math.round(clone.getMonth() / 12);
  2583. clone.setFullYear(Math.round(year / this.step) * this.step);
  2584. clone.setMonth(0);
  2585. clone.setDate(0);
  2586. clone.setHours(0);
  2587. clone.setMinutes(0);
  2588. clone.setSeconds(0);
  2589. clone.setMilliseconds(0);
  2590. }
  2591. else if (this.scale == TimeStep.SCALE.MONTH) {
  2592. if (clone.getDate() > 15) {
  2593. clone.setDate(1);
  2594. clone.setMonth(clone.getMonth() + 1);
  2595. // important: first set Date to 1, after that change the month.
  2596. }
  2597. else {
  2598. clone.setDate(1);
  2599. }
  2600. clone.setHours(0);
  2601. clone.setMinutes(0);
  2602. clone.setSeconds(0);
  2603. clone.setMilliseconds(0);
  2604. }
  2605. else if (this.scale == TimeStep.SCALE.DAY) {
  2606. //noinspection FallthroughInSwitchStatementJS
  2607. switch (this.step) {
  2608. case 5:
  2609. case 2:
  2610. clone.setHours(Math.round(clone.getHours() / 24) * 24); break;
  2611. default:
  2612. clone.setHours(Math.round(clone.getHours() / 12) * 12); break;
  2613. }
  2614. clone.setMinutes(0);
  2615. clone.setSeconds(0);
  2616. clone.setMilliseconds(0);
  2617. }
  2618. else if (this.scale == TimeStep.SCALE.WEEKDAY) {
  2619. //noinspection FallthroughInSwitchStatementJS
  2620. switch (this.step) {
  2621. case 5:
  2622. case 2:
  2623. clone.setHours(Math.round(clone.getHours() / 12) * 12); break;
  2624. default:
  2625. clone.setHours(Math.round(clone.getHours() / 6) * 6); break;
  2626. }
  2627. clone.setMinutes(0);
  2628. clone.setSeconds(0);
  2629. clone.setMilliseconds(0);
  2630. }
  2631. else if (this.scale == TimeStep.SCALE.HOUR) {
  2632. switch (this.step) {
  2633. case 4:
  2634. clone.setMinutes(Math.round(clone.getMinutes() / 60) * 60); break;
  2635. default:
  2636. clone.setMinutes(Math.round(clone.getMinutes() / 30) * 30); break;
  2637. }
  2638. clone.setSeconds(0);
  2639. clone.setMilliseconds(0);
  2640. } else if (this.scale == TimeStep.SCALE.MINUTE) {
  2641. //noinspection FallthroughInSwitchStatementJS
  2642. switch (this.step) {
  2643. case 15:
  2644. case 10:
  2645. clone.setMinutes(Math.round(clone.getMinutes() / 5) * 5);
  2646. clone.setSeconds(0);
  2647. break;
  2648. case 5:
  2649. clone.setSeconds(Math.round(clone.getSeconds() / 60) * 60); break;
  2650. default:
  2651. clone.setSeconds(Math.round(clone.getSeconds() / 30) * 30); break;
  2652. }
  2653. clone.setMilliseconds(0);
  2654. }
  2655. else if (this.scale == TimeStep.SCALE.SECOND) {
  2656. //noinspection FallthroughInSwitchStatementJS
  2657. switch (this.step) {
  2658. case 15:
  2659. case 10:
  2660. clone.setSeconds(Math.round(clone.getSeconds() / 5) * 5);
  2661. clone.setMilliseconds(0);
  2662. break;
  2663. case 5:
  2664. clone.setMilliseconds(Math.round(clone.getMilliseconds() / 1000) * 1000); break;
  2665. default:
  2666. clone.setMilliseconds(Math.round(clone.getMilliseconds() / 500) * 500); break;
  2667. }
  2668. }
  2669. else if (this.scale == TimeStep.SCALE.MILLISECOND) {
  2670. var step = this.step > 5 ? this.step / 2 : 1;
  2671. clone.setMilliseconds(Math.round(clone.getMilliseconds() / step) * step);
  2672. }
  2673. return clone;
  2674. };
  2675. /**
  2676. * Check if the current value is a major value (for example when the step
  2677. * is DAY, a major value is each first day of the MONTH)
  2678. * @return {boolean} true if current date is major, else false.
  2679. */
  2680. TimeStep.prototype.isMajor = function() {
  2681. switch (this.scale) {
  2682. case TimeStep.SCALE.MILLISECOND:
  2683. return (this.current.getMilliseconds() == 0);
  2684. case TimeStep.SCALE.SECOND:
  2685. return (this.current.getSeconds() == 0);
  2686. case TimeStep.SCALE.MINUTE:
  2687. return (this.current.getHours() == 0) && (this.current.getMinutes() == 0);
  2688. // Note: this is no bug. Major label is equal for both minute and hour scale
  2689. case TimeStep.SCALE.HOUR:
  2690. return (this.current.getHours() == 0);
  2691. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2692. case TimeStep.SCALE.DAY:
  2693. return (this.current.getDate() == 1);
  2694. case TimeStep.SCALE.MONTH:
  2695. return (this.current.getMonth() == 0);
  2696. case TimeStep.SCALE.YEAR:
  2697. return false;
  2698. default:
  2699. return false;
  2700. }
  2701. };
  2702. /**
  2703. * Returns formatted text for the minor axislabel, depending on the current
  2704. * date and the scale. For example when scale is MINUTE, the current time is
  2705. * formatted as "hh:mm".
  2706. * @param {Date} [date] custom date. if not provided, current date is taken
  2707. */
  2708. TimeStep.prototype.getLabelMinor = function(date) {
  2709. if (date == undefined) {
  2710. date = this.current;
  2711. }
  2712. switch (this.scale) {
  2713. case TimeStep.SCALE.MILLISECOND: return moment(date).format('SSS');
  2714. case TimeStep.SCALE.SECOND: return moment(date).format('s');
  2715. case TimeStep.SCALE.MINUTE: return moment(date).format('HH:mm');
  2716. case TimeStep.SCALE.HOUR: return moment(date).format('HH:mm');
  2717. case TimeStep.SCALE.WEEKDAY: return moment(date).format('ddd D');
  2718. case TimeStep.SCALE.DAY: return moment(date).format('D');
  2719. case TimeStep.SCALE.MONTH: return moment(date).format('MMM');
  2720. case TimeStep.SCALE.YEAR: return moment(date).format('YYYY');
  2721. default: return '';
  2722. }
  2723. };
  2724. /**
  2725. * Returns formatted text for the major axis label, depending on the current
  2726. * date and the scale. For example when scale is MINUTE, the major scale is
  2727. * hours, and the hour will be formatted as "hh".
  2728. * @param {Date} [date] custom date. if not provided, current date is taken
  2729. */
  2730. TimeStep.prototype.getLabelMajor = function(date) {
  2731. if (date == undefined) {
  2732. date = this.current;
  2733. }
  2734. //noinspection FallthroughInSwitchStatementJS
  2735. switch (this.scale) {
  2736. case TimeStep.SCALE.MILLISECOND:return moment(date).format('HH:mm:ss');
  2737. case TimeStep.SCALE.SECOND: return moment(date).format('D MMMM HH:mm');
  2738. case TimeStep.SCALE.MINUTE:
  2739. case TimeStep.SCALE.HOUR: return moment(date).format('ddd D MMMM');
  2740. case TimeStep.SCALE.WEEKDAY:
  2741. case TimeStep.SCALE.DAY: return moment(date).format('MMMM YYYY');
  2742. case TimeStep.SCALE.MONTH: return moment(date).format('YYYY');
  2743. case TimeStep.SCALE.YEAR: return '';
  2744. default: return '';
  2745. }
  2746. };
  2747. /**
  2748. * @constructor Range
  2749. * A Range controls a numeric range with a start and end value.
  2750. * The Range adjusts the range based on mouse events or programmatic changes,
  2751. * and triggers events when the range is changing or has been changed.
  2752. * @param {RootPanel} root Root panel, used to subscribe to events
  2753. * @param {Panel} parent Parent panel, used to attach to the DOM
  2754. * @param {Object} [options] See description at Range.setOptions
  2755. */
  2756. function Range(root, parent, options) {
  2757. this.id = util.randomUUID();
  2758. this.start = null; // Number
  2759. this.end = null; // Number
  2760. this.root = root;
  2761. this.parent = parent;
  2762. this.options = options || {};
  2763. // drag listeners for dragging
  2764. this.root.on('dragstart', this._onDragStart.bind(this));
  2765. this.root.on('drag', this._onDrag.bind(this));
  2766. this.root.on('dragend', this._onDragEnd.bind(this));
  2767. // ignore dragging when holding
  2768. this.root.on('hold', this._onHold.bind(this));
  2769. // mouse wheel for zooming
  2770. this.root.on('mousewheel', this._onMouseWheel.bind(this));
  2771. this.root.on('DOMMouseScroll', this._onMouseWheel.bind(this)); // For FF
  2772. // pinch to zoom
  2773. this.root.on('touch', this._onTouch.bind(this));
  2774. this.root.on('pinch', this._onPinch.bind(this));
  2775. this.setOptions(options);
  2776. }
  2777. // turn Range into an event emitter
  2778. Emitter(Range.prototype);
  2779. /**
  2780. * Set options for the range controller
  2781. * @param {Object} options Available options:
  2782. * {Number} min Minimum value for start
  2783. * {Number} max Maximum value for end
  2784. * {Number} zoomMin Set a minimum value for
  2785. * (end - start).
  2786. * {Number} zoomMax Set a maximum value for
  2787. * (end - start).
  2788. */
  2789. Range.prototype.setOptions = function (options) {
  2790. util.extend(this.options, options);
  2791. // re-apply range with new limitations
  2792. if (this.start !== null && this.end !== null) {
  2793. this.setRange(this.start, this.end);
  2794. }
  2795. };
  2796. /**
  2797. * Test whether direction has a valid value
  2798. * @param {String} direction 'horizontal' or 'vertical'
  2799. */
  2800. function validateDirection (direction) {
  2801. if (direction != 'horizontal' && direction != 'vertical') {
  2802. throw new TypeError('Unknown direction "' + direction + '". ' +
  2803. 'Choose "horizontal" or "vertical".');
  2804. }
  2805. }
  2806. /**
  2807. * Set a new start and end range
  2808. * @param {Number} [start]
  2809. * @param {Number} [end]
  2810. */
  2811. Range.prototype.setRange = function(start, end) {
  2812. var changed = this._applyRange(start, end);
  2813. if (changed) {
  2814. var params = {
  2815. start: new Date(this.start),
  2816. end: new Date(this.end)
  2817. };
  2818. this.emit('rangechange', params);
  2819. this.emit('rangechanged', params);
  2820. }
  2821. };
  2822. /**
  2823. * Set a new start and end range. This method is the same as setRange, but
  2824. * does not trigger a range change and range changed event, and it returns
  2825. * true when the range is changed
  2826. * @param {Number} [start]
  2827. * @param {Number} [end]
  2828. * @return {Boolean} changed
  2829. * @private
  2830. */
  2831. Range.prototype._applyRange = function(start, end) {
  2832. var newStart = (start != null) ? util.convert(start, 'Date').valueOf() : this.start,
  2833. newEnd = (end != null) ? util.convert(end, 'Date').valueOf() : this.end,
  2834. max = (this.options.max != null) ? util.convert(this.options.max, 'Date').valueOf() : null,
  2835. min = (this.options.min != null) ? util.convert(this.options.min, 'Date').valueOf() : null,
  2836. diff;
  2837. // check for valid number
  2838. if (isNaN(newStart) || newStart === null) {
  2839. throw new Error('Invalid start "' + start + '"');
  2840. }
  2841. if (isNaN(newEnd) || newEnd === null) {
  2842. throw new Error('Invalid end "' + end + '"');
  2843. }
  2844. // prevent start < end
  2845. if (newEnd < newStart) {
  2846. newEnd = newStart;
  2847. }
  2848. // prevent start < min
  2849. if (min !== null) {
  2850. if (newStart < min) {
  2851. diff = (min - newStart);
  2852. newStart += diff;
  2853. newEnd += diff;
  2854. // prevent end > max
  2855. if (max != null) {
  2856. if (newEnd > max) {
  2857. newEnd = max;
  2858. }
  2859. }
  2860. }
  2861. }
  2862. // prevent end > max
  2863. if (max !== null) {
  2864. if (newEnd > max) {
  2865. diff = (newEnd - max);
  2866. newStart -= diff;
  2867. newEnd -= diff;
  2868. // prevent start < min
  2869. if (min != null) {
  2870. if (newStart < min) {
  2871. newStart = min;
  2872. }
  2873. }
  2874. }
  2875. }
  2876. // prevent (end-start) < zoomMin
  2877. if (this.options.zoomMin !== null) {
  2878. var zoomMin = parseFloat(this.options.zoomMin);
  2879. if (zoomMin < 0) {
  2880. zoomMin = 0;
  2881. }
  2882. if ((newEnd - newStart) < zoomMin) {
  2883. if ((this.end - this.start) === zoomMin) {
  2884. // ignore this action, we are already zoomed to the minimum
  2885. newStart = this.start;
  2886. newEnd = this.end;
  2887. }
  2888. else {
  2889. // zoom to the minimum
  2890. diff = (zoomMin - (newEnd - newStart));
  2891. newStart -= diff / 2;
  2892. newEnd += diff / 2;
  2893. }
  2894. }
  2895. }
  2896. // prevent (end-start) > zoomMax
  2897. if (this.options.zoomMax !== null) {
  2898. var zoomMax = parseFloat(this.options.zoomMax);
  2899. if (zoomMax < 0) {
  2900. zoomMax = 0;
  2901. }
  2902. if ((newEnd - newStart) > zoomMax) {
  2903. if ((this.end - this.start) === zoomMax) {
  2904. // ignore this action, we are already zoomed to the maximum
  2905. newStart = this.start;
  2906. newEnd = this.end;
  2907. }
  2908. else {
  2909. // zoom to the maximum
  2910. diff = ((newEnd - newStart) - zoomMax);
  2911. newStart += diff / 2;
  2912. newEnd -= diff / 2;
  2913. }
  2914. }
  2915. }
  2916. var changed = (this.start != newStart || this.end != newEnd);
  2917. this.start = newStart;
  2918. this.end = newEnd;
  2919. return changed;
  2920. };
  2921. /**
  2922. * Retrieve the current range.
  2923. * @return {Object} An object with start and end properties
  2924. */
  2925. Range.prototype.getRange = function() {
  2926. return {
  2927. start: this.start,
  2928. end: this.end
  2929. };
  2930. };
  2931. /**
  2932. * Calculate the conversion offset and scale for current range, based on
  2933. * the provided width
  2934. * @param {Number} width
  2935. * @returns {{offset: number, scale: number}} conversion
  2936. */
  2937. Range.prototype.conversion = function (width) {
  2938. return Range.conversion(this.start, this.end, width);
  2939. };
  2940. /**
  2941. * Static method to calculate the conversion offset and scale for a range,
  2942. * based on the provided start, end, and width
  2943. * @param {Number} start
  2944. * @param {Number} end
  2945. * @param {Number} width
  2946. * @returns {{offset: number, scale: number}} conversion
  2947. */
  2948. Range.conversion = function (start, end, width) {
  2949. if (width != 0 && (end - start != 0)) {
  2950. return {
  2951. offset: start,
  2952. scale: width / (end - start)
  2953. }
  2954. }
  2955. else {
  2956. return {
  2957. offset: 0,
  2958. scale: 1
  2959. };
  2960. }
  2961. };
  2962. // global (private) object to store drag params
  2963. var touchParams = {};
  2964. /**
  2965. * Start dragging horizontally or vertically
  2966. * @param {Event} event
  2967. * @private
  2968. */
  2969. Range.prototype._onDragStart = function(event) {
  2970. // refuse to drag when we where pinching to prevent the timeline make a jump
  2971. // when releasing the fingers in opposite order from the touch screen
  2972. if (touchParams.ignore) return;
  2973. // TODO: reckon with option movable
  2974. touchParams.start = this.start;
  2975. touchParams.end = this.end;
  2976. var frame = this.parent.frame;
  2977. if (frame) {
  2978. frame.style.cursor = 'move';
  2979. }
  2980. };
  2981. /**
  2982. * Perform dragging operating.
  2983. * @param {Event} event
  2984. * @private
  2985. */
  2986. Range.prototype._onDrag = function (event) {
  2987. var direction = this.options.direction;
  2988. validateDirection(direction);
  2989. // TODO: reckon with option movable
  2990. // refuse to drag when we where pinching to prevent the timeline make a jump
  2991. // when releasing the fingers in opposite order from the touch screen
  2992. if (touchParams.ignore) return;
  2993. var delta = (direction == 'horizontal') ? event.gesture.deltaX : event.gesture.deltaY,
  2994. interval = (touchParams.end - touchParams.start),
  2995. width = (direction == 'horizontal') ? this.parent.width : this.parent.height,
  2996. diffRange = -delta / width * interval;
  2997. this._applyRange(touchParams.start + diffRange, touchParams.end + diffRange);
  2998. this.emit('rangechange', {
  2999. start: new Date(this.start),
  3000. end: new Date(this.end)
  3001. });
  3002. };
  3003. /**
  3004. * Stop dragging operating.
  3005. * @param {event} event
  3006. * @private
  3007. */
  3008. Range.prototype._onDragEnd = function (event) {
  3009. // refuse to drag when we where pinching to prevent the timeline make a jump
  3010. // when releasing the fingers in opposite order from the touch screen
  3011. if (touchParams.ignore) return;
  3012. // TODO: reckon with option movable
  3013. if (this.parent.frame) {
  3014. this.parent.frame.style.cursor = 'auto';
  3015. }
  3016. // fire a rangechanged event
  3017. this.emit('rangechanged', {
  3018. start: new Date(this.start),
  3019. end: new Date(this.end)
  3020. });
  3021. };
  3022. /**
  3023. * Event handler for mouse wheel event, used to zoom
  3024. * Code from http://adomas.org/javascript-mouse-wheel/
  3025. * @param {Event} event
  3026. * @private
  3027. */
  3028. Range.prototype._onMouseWheel = function(event) {
  3029. // TODO: reckon with option zoomable
  3030. // retrieve delta
  3031. var delta = 0;
  3032. if (event.wheelDelta) { /* IE/Opera. */
  3033. delta = event.wheelDelta / 120;
  3034. } else if (event.detail) { /* Mozilla case. */
  3035. // In Mozilla, sign of delta is different than in IE.
  3036. // Also, delta is multiple of 3.
  3037. delta = -event.detail / 3;
  3038. }
  3039. // If delta is nonzero, handle it.
  3040. // Basically, delta is now positive if wheel was scrolled up,
  3041. // and negative, if wheel was scrolled down.
  3042. if (delta) {
  3043. // perform the zoom action. Delta is normally 1 or -1
  3044. // adjust a negative delta such that zooming in with delta 0.1
  3045. // equals zooming out with a delta -0.1
  3046. var scale;
  3047. if (delta < 0) {
  3048. scale = 1 - (delta / 5);
  3049. }
  3050. else {
  3051. scale = 1 / (1 + (delta / 5)) ;
  3052. }
  3053. // calculate center, the date to zoom around
  3054. var gesture = util.fakeGesture(this, event),
  3055. pointer = getPointer(gesture.center, this.parent.frame),
  3056. pointerDate = this._pointerToDate(pointer);
  3057. this.zoom(scale, pointerDate);
  3058. }
  3059. // Prevent default actions caused by mouse wheel
  3060. // (else the page and timeline both zoom and scroll)
  3061. event.preventDefault();
  3062. };
  3063. /**
  3064. * Start of a touch gesture
  3065. * @private
  3066. */
  3067. Range.prototype._onTouch = function (event) {
  3068. touchParams.start = this.start;
  3069. touchParams.end = this.end;
  3070. touchParams.ignore = false;
  3071. touchParams.center = null;
  3072. // don't move the range when dragging a selected event
  3073. // TODO: it's not so neat to have to know about the state of the ItemSet
  3074. var item = ItemSet.itemFromTarget(event);
  3075. if (item && item.selected && this.options.editable) {
  3076. touchParams.ignore = true;
  3077. }
  3078. };
  3079. /**
  3080. * On start of a hold gesture
  3081. * @private
  3082. */
  3083. Range.prototype._onHold = function () {
  3084. touchParams.ignore = true;
  3085. };
  3086. /**
  3087. * Handle pinch event
  3088. * @param {Event} event
  3089. * @private
  3090. */
  3091. Range.prototype._onPinch = function (event) {
  3092. var direction = this.options.direction;
  3093. touchParams.ignore = true;
  3094. // TODO: reckon with option zoomable
  3095. if (event.gesture.touches.length > 1) {
  3096. if (!touchParams.center) {
  3097. touchParams.center = getPointer(event.gesture.center, this.parent.frame);
  3098. }
  3099. var scale = 1 / event.gesture.scale,
  3100. initDate = this._pointerToDate(touchParams.center),
  3101. center = getPointer(event.gesture.center, this.parent.frame),
  3102. date = this._pointerToDate(this.parent, center),
  3103. delta = date - initDate; // TODO: utilize delta
  3104. // calculate new start and end
  3105. var newStart = parseInt(initDate + (touchParams.start - initDate) * scale);
  3106. var newEnd = parseInt(initDate + (touchParams.end - initDate) * scale);
  3107. // apply new range
  3108. this.setRange(newStart, newEnd);
  3109. }
  3110. };
  3111. /**
  3112. * Helper function to calculate the center date for zooming
  3113. * @param {{x: Number, y: Number}} pointer
  3114. * @return {number} date
  3115. * @private
  3116. */
  3117. Range.prototype._pointerToDate = function (pointer) {
  3118. var conversion;
  3119. var direction = this.options.direction;
  3120. validateDirection(direction);
  3121. if (direction == 'horizontal') {
  3122. var width = this.parent.width;
  3123. conversion = this.conversion(width);
  3124. return pointer.x / conversion.scale + conversion.offset;
  3125. }
  3126. else {
  3127. var height = this.parent.height;
  3128. conversion = this.conversion(height);
  3129. return pointer.y / conversion.scale + conversion.offset;
  3130. }
  3131. };
  3132. /**
  3133. * Get the pointer location relative to the location of the dom element
  3134. * @param {{pageX: Number, pageY: Number}} touch
  3135. * @param {Element} element HTML DOM element
  3136. * @return {{x: Number, y: Number}} pointer
  3137. * @private
  3138. */
  3139. function getPointer (touch, element) {
  3140. return {
  3141. x: touch.pageX - vis.util.getAbsoluteLeft(element),
  3142. y: touch.pageY - vis.util.getAbsoluteTop(element)
  3143. };
  3144. }
  3145. /**
  3146. * Zoom the range the given scale in or out. Start and end date will
  3147. * be adjusted, and the timeline will be redrawn. You can optionally give a
  3148. * date around which to zoom.
  3149. * For example, try scale = 0.9 or 1.1
  3150. * @param {Number} scale Scaling factor. Values above 1 will zoom out,
  3151. * values below 1 will zoom in.
  3152. * @param {Number} [center] Value representing a date around which will
  3153. * be zoomed.
  3154. */
  3155. Range.prototype.zoom = function(scale, center) {
  3156. // if centerDate is not provided, take it half between start Date and end Date
  3157. if (center == null) {
  3158. center = (this.start + this.end) / 2;
  3159. }
  3160. // calculate new start and end
  3161. var newStart = center + (this.start - center) * scale;
  3162. var newEnd = center + (this.end - center) * scale;
  3163. this.setRange(newStart, newEnd);
  3164. };
  3165. /**
  3166. * Move the range with a given delta to the left or right. Start and end
  3167. * value will be adjusted. For example, try delta = 0.1 or -0.1
  3168. * @param {Number} delta Moving amount. Positive value will move right,
  3169. * negative value will move left
  3170. */
  3171. Range.prototype.move = function(delta) {
  3172. // zoom start Date and end Date relative to the centerDate
  3173. var diff = (this.end - this.start);
  3174. // apply new values
  3175. var newStart = this.start + diff * delta;
  3176. var newEnd = this.end + diff * delta;
  3177. // TODO: reckon with min and max range
  3178. this.start = newStart;
  3179. this.end = newEnd;
  3180. };
  3181. /**
  3182. * Move the range to a new center point
  3183. * @param {Number} moveTo New center point of the range
  3184. */
  3185. Range.prototype.moveTo = function(moveTo) {
  3186. var center = (this.start + this.end) / 2;
  3187. var diff = center - moveTo;
  3188. // calculate new start and end
  3189. var newStart = this.start - diff;
  3190. var newEnd = this.end - diff;
  3191. this.setRange(newStart, newEnd);
  3192. };
  3193. /**
  3194. * Prototype for visual components
  3195. */
  3196. function Component () {
  3197. this.id = null;
  3198. this.parent = null;
  3199. this.childs = null;
  3200. this.options = null;
  3201. this.top = 0;
  3202. this.left = 0;
  3203. this.width = 0;
  3204. this.height = 0;
  3205. }
  3206. // Turn the Component into an event emitter
  3207. Emitter(Component.prototype);
  3208. /**
  3209. * Set parameters for the frame. Parameters will be merged in current parameter
  3210. * set.
  3211. * @param {Object} options Available parameters:
  3212. * {String | function} [className]
  3213. * {String | Number | function} [left]
  3214. * {String | Number | function} [top]
  3215. * {String | Number | function} [width]
  3216. * {String | Number | function} [height]
  3217. */
  3218. Component.prototype.setOptions = function setOptions(options) {
  3219. if (options) {
  3220. util.extend(this.options, options);
  3221. this.repaint();
  3222. }
  3223. };
  3224. /**
  3225. * Get an option value by name
  3226. * The function will first check this.options object, and else will check
  3227. * this.defaultOptions.
  3228. * @param {String} name
  3229. * @return {*} value
  3230. */
  3231. Component.prototype.getOption = function getOption(name) {
  3232. var value;
  3233. if (this.options) {
  3234. value = this.options[name];
  3235. }
  3236. if (value === undefined && this.defaultOptions) {
  3237. value = this.defaultOptions[name];
  3238. }
  3239. return value;
  3240. };
  3241. /**
  3242. * Get the frame element of the component, the outer HTML DOM element.
  3243. * @returns {HTMLElement | null} frame
  3244. */
  3245. Component.prototype.getFrame = function getFrame() {
  3246. // should be implemented by the component
  3247. return null;
  3248. };
  3249. /**
  3250. * Repaint the component
  3251. * @return {boolean} Returns true if the component is resized
  3252. */
  3253. Component.prototype.repaint = function repaint() {
  3254. // should be implemented by the component
  3255. return false;
  3256. };
  3257. /**
  3258. * Test whether the component is resized since the last time _isResized() was
  3259. * called.
  3260. * @return {Boolean} Returns true if the component is resized
  3261. * @protected
  3262. */
  3263. Component.prototype._isResized = function _isResized() {
  3264. var resized = (this._previousWidth !== this.width || this._previousHeight !== this.height);
  3265. this._previousWidth = this.width;
  3266. this._previousHeight = this.height;
  3267. return resized;
  3268. };
  3269. /**
  3270. * A panel can contain components
  3271. * @param {Object} [options] Available parameters:
  3272. * {String | Number | function} [left]
  3273. * {String | Number | function} [top]
  3274. * {String | Number | function} [width]
  3275. * {String | Number | function} [height]
  3276. * {String | function} [className]
  3277. * @constructor Panel
  3278. * @extends Component
  3279. */
  3280. function Panel(options) {
  3281. this.id = util.randomUUID();
  3282. this.parent = null;
  3283. this.childs = [];
  3284. this.options = options || {};
  3285. // create frame
  3286. this.frame = (typeof document !== 'undefined') ? document.createElement('div') : null;
  3287. }
  3288. Panel.prototype = new Component();
  3289. /**
  3290. * Set options. Will extend the current options.
  3291. * @param {Object} [options] Available parameters:
  3292. * {String | function} [className]
  3293. * {String | Number | function} [left]
  3294. * {String | Number | function} [top]
  3295. * {String | Number | function} [width]
  3296. * {String | Number | function} [height]
  3297. */
  3298. Panel.prototype.setOptions = Component.prototype.setOptions;
  3299. /**
  3300. * Get the outer frame of the panel
  3301. * @returns {HTMLElement} frame
  3302. */
  3303. Panel.prototype.getFrame = function () {
  3304. return this.frame;
  3305. };
  3306. /**
  3307. * Append a child to the panel
  3308. * @param {Component} child
  3309. */
  3310. Panel.prototype.appendChild = function (child) {
  3311. this.childs.push(child);
  3312. child.parent = this;
  3313. // attach to the DOM
  3314. var frame = child.getFrame();
  3315. if (frame) {
  3316. if (frame.parentNode) {
  3317. frame.parentNode.removeChild(frame);
  3318. }
  3319. this.frame.appendChild(frame);
  3320. }
  3321. };
  3322. /**
  3323. * Insert a child to the panel
  3324. * @param {Component} child
  3325. * @param {Component} beforeChild
  3326. */
  3327. Panel.prototype.insertBefore = function (child, beforeChild) {
  3328. var index = this.childs.indexOf(beforeChild);
  3329. if (index != -1) {
  3330. this.childs.splice(index, 0, child);
  3331. child.parent = this;
  3332. // attach to the DOM
  3333. var frame = child.getFrame();
  3334. if (frame) {
  3335. if (frame.parentNode) {
  3336. frame.parentNode.removeChild(frame);
  3337. }
  3338. var beforeFrame = beforeChild.getFrame();
  3339. if (beforeFrame) {
  3340. this.frame.insertBefore(frame, beforeFrame);
  3341. }
  3342. else {
  3343. this.frame.appendChild(frame);
  3344. }
  3345. }
  3346. }
  3347. };
  3348. /**
  3349. * Remove a child from the panel
  3350. * @param {Component} child
  3351. */
  3352. Panel.prototype.removeChild = function (child) {
  3353. var index = this.childs.indexOf(child);
  3354. if (index != -1) {
  3355. this.childs.splice(index, 1);
  3356. child.parent = null;
  3357. // remove from the DOM
  3358. var frame = child.getFrame();
  3359. if (frame && frame.parentNode) {
  3360. this.frame.removeChild(frame);
  3361. }
  3362. }
  3363. };
  3364. /**
  3365. * Test whether the panel contains given child
  3366. * @param {Component} child
  3367. */
  3368. Panel.prototype.hasChild = function (child) {
  3369. var index = this.childs.indexOf(child);
  3370. return (index != -1);
  3371. };
  3372. /**
  3373. * Repaint the component
  3374. * @return {boolean} Returns true if the component was resized since previous repaint
  3375. */
  3376. Panel.prototype.repaint = function () {
  3377. var asString = util.option.asString,
  3378. options = this.options,
  3379. frame = this.getFrame();
  3380. // update className
  3381. frame.className = 'vpanel' + (options.className ? (' ' + asString(options.className)) : '');
  3382. // repaint the child components
  3383. var childsResized = this._repaintChilds();
  3384. // update frame size
  3385. this._updateSize();
  3386. return this._isResized() || childsResized;
  3387. };
  3388. /**
  3389. * Repaint all childs of the panel
  3390. * @return {boolean} Returns true if the component is resized
  3391. * @private
  3392. */
  3393. Panel.prototype._repaintChilds = function () {
  3394. var resized = false;
  3395. for (var i = 0, ii = this.childs.length; i < ii; i++) {
  3396. resized = this.childs[i].repaint() || resized;
  3397. }
  3398. return resized;
  3399. };
  3400. /**
  3401. * Apply the size from options to the panel, and recalculate it's actual size.
  3402. * @private
  3403. */
  3404. Panel.prototype._updateSize = function () {
  3405. // apply size
  3406. this.frame.style.top = util.option.asSize(this.options.top);
  3407. this.frame.style.bottom = util.option.asSize(this.options.bottom);
  3408. this.frame.style.left = util.option.asSize(this.options.left);
  3409. this.frame.style.right = util.option.asSize(this.options.right);
  3410. this.frame.style.width = util.option.asSize(this.options.width, '100%');
  3411. this.frame.style.height = util.option.asSize(this.options.height, '');
  3412. // get actual size
  3413. this.top = this.frame.offsetTop;
  3414. this.left = this.frame.offsetLeft;
  3415. this.width = this.frame.offsetWidth;
  3416. this.height = this.frame.offsetHeight;
  3417. };
  3418. /**
  3419. * A root panel can hold components. The root panel must be initialized with
  3420. * a DOM element as container.
  3421. * @param {HTMLElement} container
  3422. * @param {Object} [options] Available parameters: see RootPanel.setOptions.
  3423. * @constructor RootPanel
  3424. * @extends Panel
  3425. */
  3426. function RootPanel(container, options) {
  3427. this.id = util.randomUUID();
  3428. this.container = container;
  3429. this.options = options || {};
  3430. this.defaultOptions = {
  3431. autoResize: true
  3432. };
  3433. // create the HTML DOM
  3434. this._create();
  3435. // attach the root panel to the provided container
  3436. if (!this.container) throw new Error('Cannot repaint root panel: no container attached');
  3437. this.container.appendChild(this.getFrame());
  3438. this._initWatch();
  3439. }
  3440. RootPanel.prototype = new Panel();
  3441. /**
  3442. * Create the HTML DOM for the root panel
  3443. */
  3444. RootPanel.prototype._create = function _create() {
  3445. // create frame
  3446. this.frame = document.createElement('div');
  3447. // create event listeners for all interesting events, these events will be
  3448. // emitted via emitter
  3449. this.hammer = Hammer(this.frame, {
  3450. prevent_default: true
  3451. });
  3452. this.listeners = {};
  3453. var me = this;
  3454. var events = [
  3455. 'touch', 'pinch', 'tap', 'doubletap', 'hold',
  3456. 'dragstart', 'drag', 'dragend',
  3457. 'mousewheel', 'DOMMouseScroll' // DOMMouseScroll is for Firefox
  3458. ];
  3459. events.forEach(function (event) {
  3460. var listener = function () {
  3461. var args = [event].concat(Array.prototype.slice.call(arguments, 0));
  3462. me.emit.apply(me, args);
  3463. };
  3464. me.hammer.on(event, listener);
  3465. me.listeners[event] = listener;
  3466. });
  3467. };
  3468. /**
  3469. * Set options. Will extend the current options.
  3470. * @param {Object} [options] Available parameters:
  3471. * {String | function} [className]
  3472. * {String | Number | function} [left]
  3473. * {String | Number | function} [top]
  3474. * {String | Number | function} [width]
  3475. * {String | Number | function} [height]
  3476. * {Boolean | function} [autoResize]
  3477. */
  3478. RootPanel.prototype.setOptions = function setOptions(options) {
  3479. if (options) {
  3480. util.extend(this.options, options);
  3481. this.repaint();
  3482. this._initWatch();
  3483. }
  3484. };
  3485. /**
  3486. * Get the frame of the root panel
  3487. */
  3488. RootPanel.prototype.getFrame = function getFrame() {
  3489. return this.frame;
  3490. };
  3491. /**
  3492. * Repaint the root panel
  3493. */
  3494. RootPanel.prototype.repaint = function repaint() {
  3495. // update class name
  3496. var options = this.options;
  3497. var editable = options.editable.updateTime || options.editable.updateGroup;
  3498. var className = 'vis timeline rootpanel ' + options.orientation + (editable ? ' editable' : '');
  3499. if (options.className) className += ' ' + util.option.asString(className);
  3500. this.frame.className = className;
  3501. // repaint the child components
  3502. var childsResized = this._repaintChilds();
  3503. // update frame size
  3504. this.frame.style.maxHeight = util.option.asSize(this.options.maxHeight, '');
  3505. this.frame.style.minHeight = util.option.asSize(this.options.minHeight, '');
  3506. this._updateSize();
  3507. // if the root panel or any of its childs is resized, repaint again,
  3508. // as other components may need to be resized accordingly
  3509. var resized = this._isResized() || childsResized;
  3510. if (resized) {
  3511. setTimeout(this.repaint.bind(this), 0);
  3512. }
  3513. };
  3514. /**
  3515. * Initialize watching when option autoResize is true
  3516. * @private
  3517. */
  3518. RootPanel.prototype._initWatch = function _initWatch() {
  3519. var autoResize = this.getOption('autoResize');
  3520. if (autoResize) {
  3521. this._watch();
  3522. }
  3523. else {
  3524. this._unwatch();
  3525. }
  3526. };
  3527. /**
  3528. * Watch for changes in the size of the frame. On resize, the Panel will
  3529. * automatically redraw itself.
  3530. * @private
  3531. */
  3532. RootPanel.prototype._watch = function _watch() {
  3533. var me = this;
  3534. this._unwatch();
  3535. var checkSize = function checkSize() {
  3536. var autoResize = me.getOption('autoResize');
  3537. if (!autoResize) {
  3538. // stop watching when the option autoResize is changed to false
  3539. me._unwatch();
  3540. return;
  3541. }
  3542. if (me.frame) {
  3543. // check whether the frame is resized
  3544. if ((me.frame.clientWidth != me.lastWidth) ||
  3545. (me.frame.clientHeight != me.lastHeight)) {
  3546. me.lastWidth = me.frame.clientWidth;
  3547. me.lastHeight = me.frame.clientHeight;
  3548. me.repaint();
  3549. // TODO: emit a resize event instead?
  3550. }
  3551. }
  3552. };
  3553. // TODO: automatically cleanup the event listener when the frame is deleted
  3554. util.addEventListener(window, 'resize', checkSize);
  3555. this.watchTimer = setInterval(checkSize, 1000);
  3556. };
  3557. /**
  3558. * Stop watching for a resize of the frame.
  3559. * @private
  3560. */
  3561. RootPanel.prototype._unwatch = function _unwatch() {
  3562. if (this.watchTimer) {
  3563. clearInterval(this.watchTimer);
  3564. this.watchTimer = undefined;
  3565. }
  3566. // TODO: remove event listener on window.resize
  3567. };
  3568. /**
  3569. * A horizontal time axis
  3570. * @param {Object} [options] See TimeAxis.setOptions for the available
  3571. * options.
  3572. * @constructor TimeAxis
  3573. * @extends Component
  3574. */
  3575. function TimeAxis (options) {
  3576. this.id = util.randomUUID();
  3577. this.dom = {
  3578. majorLines: [],
  3579. majorTexts: [],
  3580. minorLines: [],
  3581. minorTexts: [],
  3582. redundant: {
  3583. majorLines: [],
  3584. majorTexts: [],
  3585. minorLines: [],
  3586. minorTexts: []
  3587. }
  3588. };
  3589. this.props = {
  3590. range: {
  3591. start: 0,
  3592. end: 0,
  3593. minimumStep: 0
  3594. },
  3595. lineTop: 0
  3596. };
  3597. this.options = options || {};
  3598. this.defaultOptions = {
  3599. orientation: 'bottom', // supported: 'top', 'bottom'
  3600. // TODO: implement timeaxis orientations 'left' and 'right'
  3601. showMinorLabels: true,
  3602. showMajorLabels: true
  3603. };
  3604. this.range = null;
  3605. // create the HTML DOM
  3606. this._create();
  3607. }
  3608. TimeAxis.prototype = new Component();
  3609. // TODO: comment options
  3610. TimeAxis.prototype.setOptions = Component.prototype.setOptions;
  3611. /**
  3612. * Create the HTML DOM for the TimeAxis
  3613. */
  3614. TimeAxis.prototype._create = function _create() {
  3615. this.frame = document.createElement('div');
  3616. };
  3617. /**
  3618. * Set a range (start and end)
  3619. * @param {Range | Object} range A Range or an object containing start and end.
  3620. */
  3621. TimeAxis.prototype.setRange = function (range) {
  3622. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  3623. throw new TypeError('Range must be an instance of Range, ' +
  3624. 'or an object containing start and end.');
  3625. }
  3626. this.range = range;
  3627. };
  3628. /**
  3629. * Get the outer frame of the time axis
  3630. * @return {HTMLElement} frame
  3631. */
  3632. TimeAxis.prototype.getFrame = function getFrame() {
  3633. return this.frame;
  3634. };
  3635. /**
  3636. * Repaint the component
  3637. * @return {boolean} Returns true if the component is resized
  3638. */
  3639. TimeAxis.prototype.repaint = function () {
  3640. var asSize = util.option.asSize,
  3641. options = this.options,
  3642. props = this.props,
  3643. frame = this.frame;
  3644. // update classname
  3645. frame.className = 'timeaxis'; // TODO: add className from options if defined
  3646. var parent = frame.parentNode;
  3647. if (parent) {
  3648. // calculate character width and height
  3649. this._calculateCharSize();
  3650. // TODO: recalculate sizes only needed when parent is resized or options is changed
  3651. var orientation = this.getOption('orientation'),
  3652. showMinorLabels = this.getOption('showMinorLabels'),
  3653. showMajorLabels = this.getOption('showMajorLabels');
  3654. // determine the width and height of the elemens for the axis
  3655. var parentHeight = this.parent.height;
  3656. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  3657. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  3658. this.height = props.minorLabelHeight + props.majorLabelHeight;
  3659. this.width = frame.offsetWidth; // TODO: only update the width when the frame is resized?
  3660. props.minorLineHeight = parentHeight + props.minorLabelHeight;
  3661. props.minorLineWidth = 1; // TODO: really calculate width
  3662. props.majorLineHeight = parentHeight + this.height;
  3663. props.majorLineWidth = 1; // TODO: really calculate width
  3664. // take frame offline while updating (is almost twice as fast)
  3665. var beforeChild = frame.nextSibling;
  3666. parent.removeChild(frame);
  3667. // TODO: top/bottom positioning should be determined by options set in the Timeline, not here
  3668. if (orientation == 'top') {
  3669. frame.style.top = '0';
  3670. frame.style.left = '0';
  3671. frame.style.bottom = '';
  3672. frame.style.width = asSize(options.width, '100%');
  3673. frame.style.height = this.height + 'px';
  3674. }
  3675. else { // bottom
  3676. frame.style.top = '';
  3677. frame.style.bottom = '0';
  3678. frame.style.left = '0';
  3679. frame.style.width = asSize(options.width, '100%');
  3680. frame.style.height = this.height + 'px';
  3681. }
  3682. this._repaintLabels();
  3683. this._repaintLine();
  3684. // put frame online again
  3685. if (beforeChild) {
  3686. parent.insertBefore(frame, beforeChild);
  3687. }
  3688. else {
  3689. parent.appendChild(frame)
  3690. }
  3691. }
  3692. return this._isResized();
  3693. };
  3694. /**
  3695. * Repaint major and minor text labels and vertical grid lines
  3696. * @private
  3697. */
  3698. TimeAxis.prototype._repaintLabels = function () {
  3699. var orientation = this.getOption('orientation');
  3700. // calculate range and step (step such that we have space for 7 characters per label)
  3701. var start = util.convert(this.range.start, 'Number'),
  3702. end = util.convert(this.range.end, 'Number'),
  3703. minimumStep = this.options.toTime((this.props.minorCharWidth || 10) * 7).valueOf()
  3704. -this.options.toTime(0).valueOf();
  3705. var step = new TimeStep(new Date(start), new Date(end), minimumStep);
  3706. this.step = step;
  3707. // Move all DOM elements to a "redundant" list, where they
  3708. // can be picked for re-use, and clear the lists with lines and texts.
  3709. // At the end of the function _repaintLabels, left over elements will be cleaned up
  3710. var dom = this.dom;
  3711. dom.redundant.majorLines = dom.majorLines;
  3712. dom.redundant.majorTexts = dom.majorTexts;
  3713. dom.redundant.minorLines = dom.minorLines;
  3714. dom.redundant.minorTexts = dom.minorTexts;
  3715. dom.majorLines = [];
  3716. dom.majorTexts = [];
  3717. dom.minorLines = [];
  3718. dom.minorTexts = [];
  3719. step.first();
  3720. var xFirstMajorLabel = undefined;
  3721. var max = 0;
  3722. while (step.hasNext() && max < 1000) {
  3723. max++;
  3724. var cur = step.getCurrent(),
  3725. x = this.options.toScreen(cur),
  3726. isMajor = step.isMajor();
  3727. // TODO: lines must have a width, such that we can create css backgrounds
  3728. if (this.getOption('showMinorLabels')) {
  3729. this._repaintMinorText(x, step.getLabelMinor(), orientation);
  3730. }
  3731. if (isMajor && this.getOption('showMajorLabels')) {
  3732. if (x > 0) {
  3733. if (xFirstMajorLabel == undefined) {
  3734. xFirstMajorLabel = x;
  3735. }
  3736. this._repaintMajorText(x, step.getLabelMajor(), orientation);
  3737. }
  3738. this._repaintMajorLine(x, orientation);
  3739. }
  3740. else {
  3741. this._repaintMinorLine(x, orientation);
  3742. }
  3743. step.next();
  3744. }
  3745. // create a major label on the left when needed
  3746. if (this.getOption('showMajorLabels')) {
  3747. var leftTime = this.options.toTime(0),
  3748. leftText = step.getLabelMajor(leftTime),
  3749. widthText = leftText.length * (this.props.majorCharWidth || 10) + 10; // upper bound estimation
  3750. if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) {
  3751. this._repaintMajorText(0, leftText, orientation);
  3752. }
  3753. }
  3754. // Cleanup leftover DOM elements from the redundant list
  3755. util.forEach(this.dom.redundant, function (arr) {
  3756. while (arr.length) {
  3757. var elem = arr.pop();
  3758. if (elem && elem.parentNode) {
  3759. elem.parentNode.removeChild(elem);
  3760. }
  3761. }
  3762. });
  3763. };
  3764. /**
  3765. * Create a minor label for the axis at position x
  3766. * @param {Number} x
  3767. * @param {String} text
  3768. * @param {String} orientation "top" or "bottom" (default)
  3769. * @private
  3770. */
  3771. TimeAxis.prototype._repaintMinorText = function (x, text, orientation) {
  3772. // reuse redundant label
  3773. var label = this.dom.redundant.minorTexts.shift();
  3774. if (!label) {
  3775. // create new label
  3776. var content = document.createTextNode('');
  3777. label = document.createElement('div');
  3778. label.appendChild(content);
  3779. label.className = 'text minor';
  3780. this.frame.appendChild(label);
  3781. }
  3782. this.dom.minorTexts.push(label);
  3783. label.childNodes[0].nodeValue = text;
  3784. if (orientation == 'top') {
  3785. label.style.top = this.props.majorLabelHeight + 'px';
  3786. label.style.bottom = '';
  3787. }
  3788. else {
  3789. label.style.top = '';
  3790. label.style.bottom = this.props.majorLabelHeight + 'px';
  3791. }
  3792. label.style.left = x + 'px';
  3793. //label.title = title; // TODO: this is a heavy operation
  3794. };
  3795. /**
  3796. * Create a Major label for the axis at position x
  3797. * @param {Number} x
  3798. * @param {String} text
  3799. * @param {String} orientation "top" or "bottom" (default)
  3800. * @private
  3801. */
  3802. TimeAxis.prototype._repaintMajorText = function (x, text, orientation) {
  3803. // reuse redundant label
  3804. var label = this.dom.redundant.majorTexts.shift();
  3805. if (!label) {
  3806. // create label
  3807. var content = document.createTextNode(text);
  3808. label = document.createElement('div');
  3809. label.className = 'text major';
  3810. label.appendChild(content);
  3811. this.frame.appendChild(label);
  3812. }
  3813. this.dom.majorTexts.push(label);
  3814. label.childNodes[0].nodeValue = text;
  3815. //label.title = title; // TODO: this is a heavy operation
  3816. if (orientation == 'top') {
  3817. label.style.top = '0px';
  3818. label.style.bottom = '';
  3819. }
  3820. else {
  3821. label.style.top = '';
  3822. label.style.bottom = '0px';
  3823. }
  3824. label.style.left = x + 'px';
  3825. };
  3826. /**
  3827. * Create a minor line for the axis at position x
  3828. * @param {Number} x
  3829. * @param {String} orientation "top" or "bottom" (default)
  3830. * @private
  3831. */
  3832. TimeAxis.prototype._repaintMinorLine = function (x, orientation) {
  3833. // reuse redundant line
  3834. var line = this.dom.redundant.minorLines.shift();
  3835. if (!line) {
  3836. // create vertical line
  3837. line = document.createElement('div');
  3838. line.className = 'grid vertical minor';
  3839. this.frame.appendChild(line);
  3840. }
  3841. this.dom.minorLines.push(line);
  3842. var props = this.props;
  3843. if (orientation == 'top') {
  3844. line.style.top = this.props.majorLabelHeight + 'px';
  3845. line.style.bottom = '';
  3846. }
  3847. else {
  3848. line.style.top = '';
  3849. line.style.bottom = this.props.majorLabelHeight + 'px';
  3850. }
  3851. line.style.height = props.minorLineHeight + 'px';
  3852. line.style.left = (x - props.minorLineWidth / 2) + 'px';
  3853. };
  3854. /**
  3855. * Create a Major line for the axis at position x
  3856. * @param {Number} x
  3857. * @param {String} orientation "top" or "bottom" (default)
  3858. * @private
  3859. */
  3860. TimeAxis.prototype._repaintMajorLine = function (x, orientation) {
  3861. // reuse redundant line
  3862. var line = this.dom.redundant.majorLines.shift();
  3863. if (!line) {
  3864. // create vertical line
  3865. line = document.createElement('DIV');
  3866. line.className = 'grid vertical major';
  3867. this.frame.appendChild(line);
  3868. }
  3869. this.dom.majorLines.push(line);
  3870. var props = this.props;
  3871. if (orientation == 'top') {
  3872. line.style.top = '0px';
  3873. line.style.bottom = '';
  3874. }
  3875. else {
  3876. line.style.top = '';
  3877. line.style.bottom = '0px';
  3878. }
  3879. line.style.left = (x - props.majorLineWidth / 2) + 'px';
  3880. line.style.height = props.majorLineHeight + 'px';
  3881. };
  3882. /**
  3883. * Repaint the horizontal line for the axis
  3884. * @private
  3885. */
  3886. TimeAxis.prototype._repaintLine = function() {
  3887. var line = this.dom.line,
  3888. frame = this.frame,
  3889. orientation = this.getOption('orientation');
  3890. // line before all axis elements
  3891. if (this.getOption('showMinorLabels') || this.getOption('showMajorLabels')) {
  3892. if (line) {
  3893. // put this line at the end of all childs
  3894. frame.removeChild(line);
  3895. frame.appendChild(line);
  3896. }
  3897. else {
  3898. // create the axis line
  3899. line = document.createElement('div');
  3900. line.className = 'grid horizontal major';
  3901. frame.appendChild(line);
  3902. this.dom.line = line;
  3903. }
  3904. if (orientation == 'top') {
  3905. line.style.top = this.height + 'px';
  3906. line.style.bottom = '';
  3907. }
  3908. else {
  3909. line.style.top = '';
  3910. line.style.bottom = this.height + 'px';
  3911. }
  3912. }
  3913. else {
  3914. if (line && line.parentNode) {
  3915. line.parentNode.removeChild(line);
  3916. delete this.dom.line;
  3917. }
  3918. }
  3919. };
  3920. /**
  3921. * Determine the size of text on the axis (both major and minor axis).
  3922. * The size is calculated only once and then cached in this.props.
  3923. * @private
  3924. */
  3925. TimeAxis.prototype._calculateCharSize = function () {
  3926. // Note: We calculate char size with every repaint. Size may change, for
  3927. // example when any of the timelines parents had display:none for example.
  3928. // determine the char width and height on the minor axis
  3929. if (!this.dom.measureCharMinor) {
  3930. this.dom.measureCharMinor = document.createElement('DIV');
  3931. this.dom.measureCharMinor.className = 'text minor measure';
  3932. this.dom.measureCharMinor.style.position = 'absolute';
  3933. this.dom.measureCharMinor.appendChild(document.createTextNode('0'));
  3934. this.frame.appendChild(this.dom.measureCharMinor);
  3935. }
  3936. this.props.minorCharHeight = this.dom.measureCharMinor.clientHeight;
  3937. this.props.minorCharWidth = this.dom.measureCharMinor.clientWidth;
  3938. // determine the char width and height on the major axis
  3939. if (!this.dom.measureCharMajor) {
  3940. this.dom.measureCharMajor = document.createElement('DIV');
  3941. this.dom.measureCharMajor.className = 'text minor measure';
  3942. this.dom.measureCharMajor.style.position = 'absolute';
  3943. this.dom.measureCharMajor.appendChild(document.createTextNode('0'));
  3944. this.frame.appendChild(this.dom.measureCharMajor);
  3945. }
  3946. this.props.majorCharHeight = this.dom.measureCharMajor.clientHeight;
  3947. this.props.majorCharWidth = this.dom.measureCharMajor.clientWidth;
  3948. };
  3949. /**
  3950. * Snap a date to a rounded value.
  3951. * The snap intervals are dependent on the current scale and step.
  3952. * @param {Date} date the date to be snapped.
  3953. * @return {Date} snappedDate
  3954. */
  3955. TimeAxis.prototype.snap = function snap (date) {
  3956. return this.step.snap(date);
  3957. };
  3958. /**
  3959. * A current time bar
  3960. * @param {Range} range
  3961. * @param {Object} [options] Available parameters:
  3962. * {Boolean} [showCurrentTime]
  3963. * @constructor CurrentTime
  3964. * @extends Component
  3965. */
  3966. function CurrentTime (range, options) {
  3967. this.id = util.randomUUID();
  3968. this.range = range;
  3969. this.options = options || {};
  3970. this.defaultOptions = {
  3971. showCurrentTime: false
  3972. };
  3973. this._create();
  3974. }
  3975. CurrentTime.prototype = new Component();
  3976. CurrentTime.prototype.setOptions = Component.prototype.setOptions;
  3977. /**
  3978. * Create the HTML DOM for the current time bar
  3979. * @private
  3980. */
  3981. CurrentTime.prototype._create = function _create () {
  3982. var bar = document.createElement('div');
  3983. bar.className = 'currenttime';
  3984. bar.style.position = 'absolute';
  3985. bar.style.top = '0px';
  3986. bar.style.height = '100%';
  3987. this.bar = bar;
  3988. };
  3989. /**
  3990. * Get the frame element of the current time bar
  3991. * @returns {HTMLElement} frame
  3992. */
  3993. CurrentTime.prototype.getFrame = function getFrame() {
  3994. return this.bar;
  3995. };
  3996. /**
  3997. * Repaint the component
  3998. * @return {boolean} Returns true if the component is resized
  3999. */
  4000. CurrentTime.prototype.repaint = function repaint() {
  4001. var parent = this.parent;
  4002. var now = new Date();
  4003. var x = this.options.toScreen(now);
  4004. this.bar.style.left = x + 'px';
  4005. this.bar.title = 'Current time: ' + now;
  4006. return false;
  4007. };
  4008. /**
  4009. * Start auto refreshing the current time bar
  4010. */
  4011. CurrentTime.prototype.start = function start() {
  4012. var me = this;
  4013. function update () {
  4014. me.stop();
  4015. // determine interval to refresh
  4016. var scale = me.range.conversion(me.parent.width).scale;
  4017. var interval = 1 / scale / 10;
  4018. if (interval < 30) interval = 30;
  4019. if (interval > 1000) interval = 1000;
  4020. me.repaint();
  4021. // start a timer to adjust for the new time
  4022. me.currentTimeTimer = setTimeout(update, interval);
  4023. }
  4024. update();
  4025. };
  4026. /**
  4027. * Stop auto refreshing the current time bar
  4028. */
  4029. CurrentTime.prototype.stop = function stop() {
  4030. if (this.currentTimeTimer !== undefined) {
  4031. clearTimeout(this.currentTimeTimer);
  4032. delete this.currentTimeTimer;
  4033. }
  4034. };
  4035. /**
  4036. * A custom time bar
  4037. * @param {Object} [options] Available parameters:
  4038. * {Boolean} [showCustomTime]
  4039. * @constructor CustomTime
  4040. * @extends Component
  4041. */
  4042. function CustomTime (options) {
  4043. this.id = util.randomUUID();
  4044. this.options = options || {};
  4045. this.defaultOptions = {
  4046. showCustomTime: false
  4047. };
  4048. this.customTime = new Date();
  4049. this.eventParams = {}; // stores state parameters while dragging the bar
  4050. // create the DOM
  4051. this._create();
  4052. }
  4053. CustomTime.prototype = new Component();
  4054. CustomTime.prototype.setOptions = Component.prototype.setOptions;
  4055. /**
  4056. * Create the DOM for the custom time
  4057. * @private
  4058. */
  4059. CustomTime.prototype._create = function _create () {
  4060. var bar = document.createElement('div');
  4061. bar.className = 'customtime';
  4062. bar.style.position = 'absolute';
  4063. bar.style.top = '0px';
  4064. bar.style.height = '100%';
  4065. this.bar = bar;
  4066. var drag = document.createElement('div');
  4067. drag.style.position = 'relative';
  4068. drag.style.top = '0px';
  4069. drag.style.left = '-10px';
  4070. drag.style.height = '100%';
  4071. drag.style.width = '20px';
  4072. bar.appendChild(drag);
  4073. // attach event listeners
  4074. this.hammer = Hammer(bar, {
  4075. prevent_default: true
  4076. });
  4077. this.hammer.on('dragstart', this._onDragStart.bind(this));
  4078. this.hammer.on('drag', this._onDrag.bind(this));
  4079. this.hammer.on('dragend', this._onDragEnd.bind(this));
  4080. };
  4081. /**
  4082. * Get the frame element of the custom time bar
  4083. * @returns {HTMLElement} frame
  4084. */
  4085. CustomTime.prototype.getFrame = function getFrame() {
  4086. return this.bar;
  4087. };
  4088. /**
  4089. * Repaint the component
  4090. * @return {boolean} Returns true if the component is resized
  4091. */
  4092. CustomTime.prototype.repaint = function () {
  4093. var x = this.options.toScreen(this.customTime);
  4094. this.bar.style.left = x + 'px';
  4095. this.bar.title = 'Time: ' + this.customTime;
  4096. return false;
  4097. };
  4098. /**
  4099. * Set custom time.
  4100. * @param {Date} time
  4101. */
  4102. CustomTime.prototype.setCustomTime = function(time) {
  4103. this.customTime = new Date(time.valueOf());
  4104. this.repaint();
  4105. };
  4106. /**
  4107. * Retrieve the current custom time.
  4108. * @return {Date} customTime
  4109. */
  4110. CustomTime.prototype.getCustomTime = function() {
  4111. return new Date(this.customTime.valueOf());
  4112. };
  4113. /**
  4114. * Start moving horizontally
  4115. * @param {Event} event
  4116. * @private
  4117. */
  4118. CustomTime.prototype._onDragStart = function(event) {
  4119. this.eventParams.dragging = true;
  4120. this.eventParams.customTime = this.customTime;
  4121. event.stopPropagation();
  4122. event.preventDefault();
  4123. };
  4124. /**
  4125. * Perform moving operating.
  4126. * @param {Event} event
  4127. * @private
  4128. */
  4129. CustomTime.prototype._onDrag = function (event) {
  4130. if (!this.eventParams.dragging) return;
  4131. var deltaX = event.gesture.deltaX,
  4132. x = this.options.toScreen(this.eventParams.customTime) + deltaX,
  4133. time = this.options.toTime(x);
  4134. this.setCustomTime(time);
  4135. // fire a timechange event
  4136. this.emit('timechange', {
  4137. time: new Date(this.customTime.valueOf())
  4138. });
  4139. event.stopPropagation();
  4140. event.preventDefault();
  4141. };
  4142. /**
  4143. * Stop moving operating.
  4144. * @param {event} event
  4145. * @private
  4146. */
  4147. CustomTime.prototype._onDragEnd = function (event) {
  4148. if (!this.eventParams.dragging) return;
  4149. // fire a timechanged event
  4150. this.emit('timechanged', {
  4151. time: new Date(this.customTime.valueOf())
  4152. });
  4153. event.stopPropagation();
  4154. event.preventDefault();
  4155. };
  4156. var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items
  4157. /**
  4158. * An ItemSet holds a set of items and ranges which can be displayed in a
  4159. * range. The width is determined by the parent of the ItemSet, and the height
  4160. * is determined by the size of the items.
  4161. * @param {Panel} backgroundPanel Panel which can be used to display the
  4162. * vertical lines of box items.
  4163. * @param {Panel} axisPanel Panel on the axis where the dots of box-items
  4164. * can be displayed.
  4165. * @param {Panel} sidePanel Left side panel holding labels
  4166. * @param {Object} [options] See ItemSet.setOptions for the available options.
  4167. * @constructor ItemSet
  4168. * @extends Panel
  4169. */
  4170. function ItemSet(backgroundPanel, axisPanel, sidePanel, options) {
  4171. this.id = util.randomUUID();
  4172. // one options object is shared by this itemset and all its items
  4173. this.options = options || {};
  4174. this.backgroundPanel = backgroundPanel;
  4175. this.axisPanel = axisPanel;
  4176. this.sidePanel = sidePanel;
  4177. this.itemOptions = Object.create(this.options);
  4178. this.dom = {};
  4179. this.hammer = null;
  4180. var me = this;
  4181. this.itemsData = null; // DataSet
  4182. this.groupsData = null; // DataSet
  4183. this.range = null; // Range or Object {start: number, end: number}
  4184. // listeners for the DataSet of the items
  4185. this.itemListeners = {
  4186. 'add': function (event, params, senderId) {
  4187. if (senderId != me.id) me._onAdd(params.items);
  4188. },
  4189. 'update': function (event, params, senderId) {
  4190. if (senderId != me.id) me._onUpdate(params.items);
  4191. },
  4192. 'remove': function (event, params, senderId) {
  4193. if (senderId != me.id) me._onRemove(params.items);
  4194. }
  4195. };
  4196. // listeners for the DataSet of the groups
  4197. this.groupListeners = {
  4198. 'add': function (event, params, senderId) {
  4199. if (senderId != me.id) me._onAddGroups(params.items);
  4200. },
  4201. 'update': function (event, params, senderId) {
  4202. if (senderId != me.id) me._onUpdateGroups(params.items);
  4203. },
  4204. 'remove': function (event, params, senderId) {
  4205. if (senderId != me.id) me._onRemoveGroups(params.items);
  4206. }
  4207. };
  4208. this.items = {}; // object with an Item for every data item
  4209. this.groups = {}; // Group object for every group
  4210. this.groupIds = [];
  4211. this.selection = []; // list with the ids of all selected nodes
  4212. this.stackDirty = true; // if true, all items will be restacked on next repaint
  4213. this.touchParams = {}; // stores properties while dragging
  4214. // create the HTML DOM
  4215. this._create();
  4216. }
  4217. ItemSet.prototype = new Panel();
  4218. // available item types will be registered here
  4219. ItemSet.types = {
  4220. box: ItemBox,
  4221. range: ItemRange,
  4222. rangeoverflow: ItemRangeOverflow,
  4223. point: ItemPoint
  4224. };
  4225. /**
  4226. * Create the HTML DOM for the ItemSet
  4227. */
  4228. ItemSet.prototype._create = function _create(){
  4229. var frame = document.createElement('div');
  4230. frame['timeline-itemset'] = this;
  4231. this.frame = frame;
  4232. // create background panel
  4233. var background = document.createElement('div');
  4234. background.className = 'background';
  4235. this.backgroundPanel.frame.appendChild(background);
  4236. this.dom.background = background;
  4237. // create foreground panel
  4238. var foreground = document.createElement('div');
  4239. foreground.className = 'foreground';
  4240. frame.appendChild(foreground);
  4241. this.dom.foreground = foreground;
  4242. // create axis panel
  4243. var axis = document.createElement('div');
  4244. axis.className = 'axis';
  4245. this.dom.axis = axis;
  4246. this.axisPanel.frame.appendChild(axis);
  4247. // create labelset
  4248. var labelSet = document.createElement('div');
  4249. labelSet.className = 'labelset';
  4250. this.dom.labelSet = labelSet;
  4251. this.sidePanel.frame.appendChild(labelSet);
  4252. // create ungrouped Group
  4253. this._updateUngrouped();
  4254. // attach event listeners
  4255. // TODO: use event listeners from the rootpanel to improve performance?
  4256. this.hammer = Hammer(frame, {
  4257. prevent_default: true
  4258. });
  4259. this.hammer.on('dragstart', this._onDragStart.bind(this));
  4260. this.hammer.on('drag', this._onDrag.bind(this));
  4261. this.hammer.on('dragend', this._onDragEnd.bind(this));
  4262. };
  4263. /**
  4264. * Set options for the ItemSet. Existing options will be extended/overwritten.
  4265. * @param {Object} [options] The following options are available:
  4266. * {String | function} [className]
  4267. * class name for the itemset
  4268. * {String} [type]
  4269. * Default type for the items. Choose from 'box'
  4270. * (default), 'point', or 'range'. The default
  4271. * Style can be overwritten by individual items.
  4272. * {String} align
  4273. * Alignment for the items, only applicable for
  4274. * ItemBox. Choose 'center' (default), 'left', or
  4275. * 'right'.
  4276. * {String} orientation
  4277. * Orientation of the item set. Choose 'top' or
  4278. * 'bottom' (default).
  4279. * {Number} margin.axis
  4280. * Margin between the axis and the items in pixels.
  4281. * Default is 20.
  4282. * {Number} margin.item
  4283. * Margin between items in pixels. Default is 10.
  4284. * {Number} padding
  4285. * Padding of the contents of an item in pixels.
  4286. * Must correspond with the items css. Default is 5.
  4287. * {Function} snap
  4288. * Function to let items snap to nice dates when
  4289. * dragging items.
  4290. */
  4291. ItemSet.prototype.setOptions = function setOptions(options) {
  4292. Component.prototype.setOptions.call(this, options);
  4293. };
  4294. /**
  4295. * Mark the ItemSet dirty so it will refresh everything with next repaint
  4296. */
  4297. ItemSet.prototype.markDirty = function markDirty() {
  4298. this.groupIds = [];
  4299. this.stackDirty = true;
  4300. };
  4301. /**
  4302. * Hide the component from the DOM
  4303. */
  4304. ItemSet.prototype.hide = function hide() {
  4305. // remove the axis with dots
  4306. if (this.dom.axis.parentNode) {
  4307. this.dom.axis.parentNode.removeChild(this.dom.axis);
  4308. }
  4309. // remove the background with vertical lines
  4310. if (this.dom.background.parentNode) {
  4311. this.dom.background.parentNode.removeChild(this.dom.background);
  4312. }
  4313. // remove the labelset containing all group labels
  4314. if (this.dom.labelSet.parentNode) {
  4315. this.dom.labelSet.parentNode.removeChild(this.dom.labelSet);
  4316. }
  4317. };
  4318. /**
  4319. * Show the component in the DOM (when not already visible).
  4320. * @return {Boolean} changed
  4321. */
  4322. ItemSet.prototype.show = function show() {
  4323. // show axis with dots
  4324. if (!this.dom.axis.parentNode) {
  4325. this.axisPanel.frame.appendChild(this.dom.axis);
  4326. }
  4327. // show background with vertical lines
  4328. if (!this.dom.background.parentNode) {
  4329. this.backgroundPanel.frame.appendChild(this.dom.background);
  4330. }
  4331. // show labelset containing labels
  4332. if (!this.dom.labelSet.parentNode) {
  4333. this.sidePanel.frame.appendChild(this.dom.labelSet);
  4334. }
  4335. };
  4336. /**
  4337. * Set range (start and end).
  4338. * @param {Range | Object} range A Range or an object containing start and end.
  4339. */
  4340. ItemSet.prototype.setRange = function setRange(range) {
  4341. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  4342. throw new TypeError('Range must be an instance of Range, ' +
  4343. 'or an object containing start and end.');
  4344. }
  4345. this.range = range;
  4346. };
  4347. /**
  4348. * Set selected items by their id. Replaces the current selection
  4349. * Unknown id's are silently ignored.
  4350. * @param {Array} [ids] An array with zero or more id's of the items to be
  4351. * selected. If ids is an empty array, all items will be
  4352. * unselected.
  4353. */
  4354. ItemSet.prototype.setSelection = function setSelection(ids) {
  4355. var i, ii, id, item;
  4356. if (ids) {
  4357. if (!Array.isArray(ids)) {
  4358. throw new TypeError('Array expected');
  4359. }
  4360. // unselect currently selected items
  4361. for (i = 0, ii = this.selection.length; i < ii; i++) {
  4362. id = this.selection[i];
  4363. item = this.items[id];
  4364. if (item) item.unselect();
  4365. }
  4366. // select items
  4367. this.selection = [];
  4368. for (i = 0, ii = ids.length; i < ii; i++) {
  4369. id = ids[i];
  4370. item = this.items[id];
  4371. if (item) {
  4372. this.selection.push(id);
  4373. item.select();
  4374. }
  4375. }
  4376. }
  4377. };
  4378. /**
  4379. * Get the selected items by their id
  4380. * @return {Array} ids The ids of the selected items
  4381. */
  4382. ItemSet.prototype.getSelection = function getSelection() {
  4383. return this.selection.concat([]);
  4384. };
  4385. /**
  4386. * Deselect a selected item
  4387. * @param {String | Number} id
  4388. * @private
  4389. */
  4390. ItemSet.prototype._deselect = function _deselect(id) {
  4391. var selection = this.selection;
  4392. for (var i = 0, ii = selection.length; i < ii; i++) {
  4393. if (selection[i] == id) { // non-strict comparison!
  4394. selection.splice(i, 1);
  4395. break;
  4396. }
  4397. }
  4398. };
  4399. /**
  4400. * Return the item sets frame
  4401. * @returns {HTMLElement} frame
  4402. */
  4403. ItemSet.prototype.getFrame = function getFrame() {
  4404. return this.frame;
  4405. };
  4406. /**
  4407. * Repaint the component
  4408. * @return {boolean} Returns true if the component is resized
  4409. */
  4410. ItemSet.prototype.repaint = function repaint() {
  4411. var margin = this.options.margin,
  4412. range = this.range,
  4413. asSize = util.option.asSize,
  4414. asString = util.option.asString,
  4415. options = this.options,
  4416. orientation = this.getOption('orientation'),
  4417. resized = false,
  4418. frame = this.frame;
  4419. // TODO: document this feature to specify one margin for both item and axis distance
  4420. if (typeof margin === 'number') {
  4421. margin = {
  4422. item: margin,
  4423. axis: margin
  4424. };
  4425. }
  4426. // update className
  4427. frame.className = 'itemset' + (options.className ? (' ' + asString(options.className)) : '');
  4428. // reorder the groups (if needed)
  4429. resized = this._orderGroups() || resized;
  4430. // check whether zoomed (in that case we need to re-stack everything)
  4431. // TODO: would be nicer to get this as a trigger from Range
  4432. var visibleInterval = this.range.end - this.range.start;
  4433. var zoomed = (visibleInterval != this.lastVisibleInterval) || (this.width != this.lastWidth);
  4434. if (zoomed) this.stackDirty = true;
  4435. this.lastVisibleInterval = visibleInterval;
  4436. this.lastWidth = this.width;
  4437. // repaint all groups
  4438. var restack = this.stackDirty,
  4439. firstGroup = this._firstGroup(),
  4440. firstMargin = {
  4441. item: margin.item,
  4442. axis: margin.axis
  4443. },
  4444. nonFirstMargin = {
  4445. item: margin.item,
  4446. axis: margin.item / 2
  4447. },
  4448. height = 0,
  4449. minHeight = margin.axis + margin.item;
  4450. util.forEach(this.groups, function (group) {
  4451. var groupMargin = (group == firstGroup) ? firstMargin : nonFirstMargin;
  4452. resized = group.repaint(range, groupMargin, restack) || resized;
  4453. height += group.height;
  4454. });
  4455. height = Math.max(height, minHeight);
  4456. this.stackDirty = false;
  4457. // reposition frame
  4458. frame.style.left = asSize(options.left, '');
  4459. frame.style.right = asSize(options.right, '');
  4460. frame.style.top = asSize((orientation == 'top') ? '0' : '');
  4461. frame.style.bottom = asSize((orientation == 'top') ? '' : '0');
  4462. frame.style.width = asSize(options.width, '100%');
  4463. frame.style.height = asSize(height);
  4464. //frame.style.height = asSize('height' in options ? options.height : height); // TODO: reckon with height
  4465. // calculate actual size and position
  4466. this.top = frame.offsetTop;
  4467. this.left = frame.offsetLeft;
  4468. this.width = frame.offsetWidth;
  4469. this.height = height;
  4470. // reposition axis
  4471. this.dom.axis.style.left = asSize(options.left, '0');
  4472. this.dom.axis.style.right = asSize(options.right, '');
  4473. this.dom.axis.style.width = asSize(options.width, '100%');
  4474. this.dom.axis.style.height = asSize(0);
  4475. this.dom.axis.style.top = asSize((orientation == 'top') ? '0' : '');
  4476. this.dom.axis.style.bottom = asSize((orientation == 'top') ? '' : '0');
  4477. // check if this component is resized
  4478. resized = this._isResized() || resized;
  4479. return resized;
  4480. };
  4481. /**
  4482. * Get the first group, aligned with the axis
  4483. * @return {Group | null} firstGroup
  4484. * @private
  4485. */
  4486. ItemSet.prototype._firstGroup = function _firstGroup() {
  4487. var firstGroupIndex = (this.options.orientation == 'top') ? 0 : (this.groupIds.length - 1);
  4488. var firstGroupId = this.groupIds[firstGroupIndex];
  4489. var firstGroup = this.groups[firstGroupId] || this.groups[UNGROUPED];
  4490. return firstGroup || null;
  4491. };
  4492. /**
  4493. * Create or delete the group holding all ungrouped items. This group is used when
  4494. * there are no groups specified.
  4495. * @protected
  4496. */
  4497. ItemSet.prototype._updateUngrouped = function _updateUngrouped() {
  4498. var ungrouped = this.groups[UNGROUPED];
  4499. if (this.groupsData) {
  4500. // remove the group holding all ungrouped items
  4501. if (ungrouped) {
  4502. ungrouped.hide();
  4503. delete this.groups[UNGROUPED];
  4504. }
  4505. }
  4506. else {
  4507. // create a group holding all (unfiltered) items
  4508. if (!ungrouped) {
  4509. var id = null;
  4510. var data = null;
  4511. ungrouped = new Group(id, data, this);
  4512. this.groups[UNGROUPED] = ungrouped;
  4513. for (var itemId in this.items) {
  4514. if (this.items.hasOwnProperty(itemId)) {
  4515. ungrouped.add(this.items[itemId]);
  4516. }
  4517. }
  4518. ungrouped.show();
  4519. }
  4520. }
  4521. };
  4522. /**
  4523. * Get the foreground container element
  4524. * @return {HTMLElement} foreground
  4525. */
  4526. ItemSet.prototype.getForeground = function getForeground() {
  4527. return this.dom.foreground;
  4528. };
  4529. /**
  4530. * Get the background container element
  4531. * @return {HTMLElement} background
  4532. */
  4533. ItemSet.prototype.getBackground = function getBackground() {
  4534. return this.dom.background;
  4535. };
  4536. /**
  4537. * Get the axis container element
  4538. * @return {HTMLElement} axis
  4539. */
  4540. ItemSet.prototype.getAxis = function getAxis() {
  4541. return this.dom.axis;
  4542. };
  4543. /**
  4544. * Get the element for the labelset
  4545. * @return {HTMLElement} labelSet
  4546. */
  4547. ItemSet.prototype.getLabelSet = function getLabelSet() {
  4548. return this.dom.labelSet;
  4549. };
  4550. /**
  4551. * Set items
  4552. * @param {vis.DataSet | null} items
  4553. */
  4554. ItemSet.prototype.setItems = function setItems(items) {
  4555. var me = this,
  4556. ids,
  4557. oldItemsData = this.itemsData;
  4558. // replace the dataset
  4559. if (!items) {
  4560. this.itemsData = null;
  4561. }
  4562. else if (items instanceof DataSet || items instanceof DataView) {
  4563. this.itemsData = items;
  4564. }
  4565. else {
  4566. throw new TypeError('Data must be an instance of DataSet or DataView');
  4567. }
  4568. if (oldItemsData) {
  4569. // unsubscribe from old dataset
  4570. util.forEach(this.itemListeners, function (callback, event) {
  4571. oldItemsData.unsubscribe(event, callback);
  4572. });
  4573. // remove all drawn items
  4574. ids = oldItemsData.getIds();
  4575. this._onRemove(ids);
  4576. }
  4577. if (this.itemsData) {
  4578. // subscribe to new dataset
  4579. var id = this.id;
  4580. util.forEach(this.itemListeners, function (callback, event) {
  4581. me.itemsData.on(event, callback, id);
  4582. });
  4583. // add all new items
  4584. ids = this.itemsData.getIds();
  4585. this._onAdd(ids);
  4586. // update the group holding all ungrouped items
  4587. this._updateUngrouped();
  4588. }
  4589. };
  4590. /**
  4591. * Get the current items
  4592. * @returns {vis.DataSet | null}
  4593. */
  4594. ItemSet.prototype.getItems = function getItems() {
  4595. return this.itemsData;
  4596. };
  4597. /**
  4598. * Set groups
  4599. * @param {vis.DataSet} groups
  4600. */
  4601. ItemSet.prototype.setGroups = function setGroups(groups) {
  4602. var me = this,
  4603. ids;
  4604. // unsubscribe from current dataset
  4605. if (this.groupsData) {
  4606. util.forEach(this.groupListeners, function (callback, event) {
  4607. me.groupsData.unsubscribe(event, callback);
  4608. });
  4609. // remove all drawn groups
  4610. ids = this.groupsData.getIds();
  4611. this.groupsData = null;
  4612. this._onRemoveGroups(ids); // note: this will cause a repaint
  4613. }
  4614. // replace the dataset
  4615. if (!groups) {
  4616. this.groupsData = null;
  4617. }
  4618. else if (groups instanceof DataSet || groups instanceof DataView) {
  4619. this.groupsData = groups;
  4620. }
  4621. else {
  4622. throw new TypeError('Data must be an instance of DataSet or DataView');
  4623. }
  4624. if (this.groupsData) {
  4625. // subscribe to new dataset
  4626. var id = this.id;
  4627. util.forEach(this.groupListeners, function (callback, event) {
  4628. me.groupsData.on(event, callback, id);
  4629. });
  4630. // draw all ms
  4631. ids = this.groupsData.getIds();
  4632. this._onAddGroups(ids);
  4633. }
  4634. // update the group holding all ungrouped items
  4635. this._updateUngrouped();
  4636. // update the order of all items in each group
  4637. this._order();
  4638. this.emit('change');
  4639. };
  4640. /**
  4641. * Get the current groups
  4642. * @returns {vis.DataSet | null} groups
  4643. */
  4644. ItemSet.prototype.getGroups = function getGroups() {
  4645. return this.groupsData;
  4646. };
  4647. /**
  4648. * Remove an item by its id
  4649. * @param {String | Number} id
  4650. */
  4651. ItemSet.prototype.removeItem = function removeItem (id) {
  4652. var item = this.itemsData.get(id),
  4653. dataset = this._myDataSet();
  4654. if (item) {
  4655. // confirm deletion
  4656. this.options.onRemove(item, function (item) {
  4657. if (item) {
  4658. // remove by id here, it is possible that an item has no id defined
  4659. // itself, so better not delete by the item itself
  4660. dataset.remove(id);
  4661. }
  4662. });
  4663. }
  4664. };
  4665. /**
  4666. * Handle updated items
  4667. * @param {Number[]} ids
  4668. * @protected
  4669. */
  4670. ItemSet.prototype._onUpdate = function _onUpdate(ids) {
  4671. var me = this,
  4672. items = this.items,
  4673. itemOptions = this.itemOptions;
  4674. ids.forEach(function (id) {
  4675. var itemData = me.itemsData.get(id),
  4676. item = items[id],
  4677. type = itemData.type ||
  4678. (itemData.start && itemData.end && 'range') ||
  4679. me.options.type ||
  4680. 'box';
  4681. var constructor = ItemSet.types[type];
  4682. if (item) {
  4683. // update item
  4684. if (!constructor || !(item instanceof constructor)) {
  4685. // item type has changed, delete the item and recreate it
  4686. me._removeItem(item);
  4687. item = null;
  4688. }
  4689. else {
  4690. me._updateItem(item, itemData);
  4691. }
  4692. }
  4693. if (!item) {
  4694. // create item
  4695. if (constructor) {
  4696. item = new constructor(itemData, me.options, itemOptions);
  4697. item.id = id; // TODO: not so nice setting id afterwards
  4698. me._addItem(item);
  4699. }
  4700. else {
  4701. throw new TypeError('Unknown item type "' + type + '"');
  4702. }
  4703. }
  4704. });
  4705. this._order();
  4706. this.stackDirty = true; // force re-stacking of all items next repaint
  4707. this.emit('change');
  4708. };
  4709. /**
  4710. * Handle added items
  4711. * @param {Number[]} ids
  4712. * @protected
  4713. */
  4714. ItemSet.prototype._onAdd = ItemSet.prototype._onUpdate;
  4715. /**
  4716. * Handle removed items
  4717. * @param {Number[]} ids
  4718. * @protected
  4719. */
  4720. ItemSet.prototype._onRemove = function _onRemove(ids) {
  4721. var count = 0;
  4722. var me = this;
  4723. ids.forEach(function (id) {
  4724. var item = me.items[id];
  4725. if (item) {
  4726. count++;
  4727. me._removeItem(item);
  4728. }
  4729. });
  4730. if (count) {
  4731. // update order
  4732. this._order();
  4733. this.stackDirty = true; // force re-stacking of all items next repaint
  4734. this.emit('change');
  4735. }
  4736. };
  4737. /**
  4738. * Update the order of item in all groups
  4739. * @private
  4740. */
  4741. ItemSet.prototype._order = function _order() {
  4742. // reorder the items in all groups
  4743. // TODO: optimization: only reorder groups affected by the changed items
  4744. util.forEach(this.groups, function (group) {
  4745. group.order();
  4746. });
  4747. };
  4748. /**
  4749. * Handle updated groups
  4750. * @param {Number[]} ids
  4751. * @private
  4752. */
  4753. ItemSet.prototype._onUpdateGroups = function _onUpdateGroups(ids) {
  4754. this._onAddGroups(ids);
  4755. };
  4756. /**
  4757. * Handle changed groups
  4758. * @param {Number[]} ids
  4759. * @private
  4760. */
  4761. ItemSet.prototype._onAddGroups = function _onAddGroups(ids) {
  4762. var me = this;
  4763. ids.forEach(function (id) {
  4764. var groupData = me.groupsData.get(id);
  4765. var group = me.groups[id];
  4766. if (!group) {
  4767. // check for reserved ids
  4768. if (id == UNGROUPED) {
  4769. throw new Error('Illegal group id. ' + id + ' is a reserved id.');
  4770. }
  4771. var groupOptions = Object.create(me.options);
  4772. util.extend(groupOptions, {
  4773. height: null
  4774. });
  4775. group = new Group(id, groupData, me);
  4776. me.groups[id] = group;
  4777. // add items with this groupId to the new group
  4778. for (var itemId in me.items) {
  4779. if (me.items.hasOwnProperty(itemId)) {
  4780. var item = me.items[itemId];
  4781. if (item.data.group == id) {
  4782. group.add(item);
  4783. }
  4784. }
  4785. }
  4786. group.order();
  4787. group.show();
  4788. }
  4789. else {
  4790. // update group
  4791. group.setData(groupData);
  4792. }
  4793. });
  4794. this.emit('change');
  4795. };
  4796. /**
  4797. * Handle removed groups
  4798. * @param {Number[]} ids
  4799. * @private
  4800. */
  4801. ItemSet.prototype._onRemoveGroups = function _onRemoveGroups(ids) {
  4802. var groups = this.groups;
  4803. ids.forEach(function (id) {
  4804. var group = groups[id];
  4805. if (group) {
  4806. group.hide();
  4807. delete groups[id];
  4808. }
  4809. });
  4810. this.markDirty();
  4811. this.emit('change');
  4812. };
  4813. /**
  4814. * Reorder the groups if needed
  4815. * @return {boolean} changed
  4816. * @private
  4817. */
  4818. ItemSet.prototype._orderGroups = function () {
  4819. if (this.groupsData) {
  4820. // reorder the groups
  4821. var groupIds = this.groupsData.getIds({
  4822. order: this.options.groupOrder
  4823. });
  4824. var changed = !util.equalArray(groupIds, this.groupIds);
  4825. if (changed) {
  4826. // hide all groups, removes them from the DOM
  4827. var groups = this.groups;
  4828. groupIds.forEach(function (groupId) {
  4829. groups[groupId].hide();
  4830. });
  4831. // show the groups again, attach them to the DOM in correct order
  4832. groupIds.forEach(function (groupId) {
  4833. groups[groupId].show();
  4834. });
  4835. this.groupIds = groupIds;
  4836. }
  4837. return changed;
  4838. }
  4839. else {
  4840. return false;
  4841. }
  4842. };
  4843. /**
  4844. * Add a new item
  4845. * @param {Item} item
  4846. * @private
  4847. */
  4848. ItemSet.prototype._addItem = function _addItem(item) {
  4849. this.items[item.id] = item;
  4850. // add to group
  4851. var groupId = this.groupsData ? item.data.group : UNGROUPED;
  4852. var group = this.groups[groupId];
  4853. if (group) group.add(item);
  4854. };
  4855. /**
  4856. * Update an existing item
  4857. * @param {Item} item
  4858. * @param {Object} itemData
  4859. * @private
  4860. */
  4861. ItemSet.prototype._updateItem = function _updateItem(item, itemData) {
  4862. var oldGroupId = item.data.group;
  4863. item.data = itemData;
  4864. if (item.displayed) {
  4865. item.repaint();
  4866. }
  4867. // update group
  4868. if (oldGroupId != item.data.group) {
  4869. var oldGroup = this.groups[oldGroupId];
  4870. if (oldGroup) oldGroup.remove(item);
  4871. var groupId = this.groupsData ? item.data.group : UNGROUPED;
  4872. var group = this.groups[groupId];
  4873. if (group) group.add(item);
  4874. }
  4875. };
  4876. /**
  4877. * Delete an item from the ItemSet: remove it from the DOM, from the map
  4878. * with items, and from the map with visible items, and from the selection
  4879. * @param {Item} item
  4880. * @private
  4881. */
  4882. ItemSet.prototype._removeItem = function _removeItem(item) {
  4883. // remove from DOM
  4884. item.hide();
  4885. // remove from items
  4886. delete this.items[item.id];
  4887. // remove from selection
  4888. var index = this.selection.indexOf(item.id);
  4889. if (index != -1) this.selection.splice(index, 1);
  4890. // remove from group
  4891. var groupId = this.groupsData ? item.data.group : UNGROUPED;
  4892. var group = this.groups[groupId];
  4893. if (group) group.remove(item);
  4894. };
  4895. /**
  4896. * Create an array containing all items being a range (having an end date)
  4897. * @param array
  4898. * @returns {Array}
  4899. * @private
  4900. */
  4901. ItemSet.prototype._constructByEndArray = function _constructByEndArray(array) {
  4902. var endArray = [];
  4903. for (var i = 0; i < array.length; i++) {
  4904. if (array[i] instanceof ItemRange) {
  4905. endArray.push(array[i]);
  4906. }
  4907. }
  4908. return endArray;
  4909. };
  4910. /**
  4911. * Get the width of the group labels
  4912. * @return {Number} width
  4913. */
  4914. ItemSet.prototype.getLabelsWidth = function getLabelsWidth() {
  4915. var width = 0;
  4916. util.forEach(this.groups, function (group) {
  4917. width = Math.max(width, group.getLabelWidth());
  4918. });
  4919. return width;
  4920. };
  4921. /**
  4922. * Get the height of the itemsets background
  4923. * @return {Number} height
  4924. */
  4925. ItemSet.prototype.getBackgroundHeight = function getBackgroundHeight() {
  4926. return this.height;
  4927. };
  4928. /**
  4929. * Start dragging the selected events
  4930. * @param {Event} event
  4931. * @private
  4932. */
  4933. ItemSet.prototype._onDragStart = function (event) {
  4934. if (!this.options.editable.updateTime && !this.options.editable.updateGroup) {
  4935. return;
  4936. }
  4937. var item = ItemSet.itemFromTarget(event),
  4938. me = this,
  4939. props;
  4940. if (item && item.selected) {
  4941. var dragLeftItem = event.target.dragLeftItem;
  4942. var dragRightItem = event.target.dragRightItem;
  4943. if (dragLeftItem) {
  4944. props = {
  4945. item: dragLeftItem
  4946. };
  4947. if (me.options.editable.updateTime) {
  4948. props.start = item.data.start.valueOf();
  4949. }
  4950. if (me.options.editable.updateGroup) {
  4951. if ('group' in item.data) props.group = item.data.group;
  4952. }
  4953. this.touchParams.itemProps = [props];
  4954. }
  4955. else if (dragRightItem) {
  4956. props = {
  4957. item: dragRightItem
  4958. };
  4959. if (me.options.editable.updateTime) {
  4960. props.end = item.data.end.valueOf();
  4961. }
  4962. if (me.options.editable.updateGroup) {
  4963. if ('group' in item.data) props.group = item.data.group;
  4964. }
  4965. this.touchParams.itemProps = [props];
  4966. }
  4967. else {
  4968. this.touchParams.itemProps = this.getSelection().map(function (id) {
  4969. var item = me.items[id];
  4970. var props = {
  4971. item: item
  4972. };
  4973. if (me.options.editable.updateTime) {
  4974. if ('start' in item.data) props.start = item.data.start.valueOf();
  4975. if ('end' in item.data) props.end = item.data.end.valueOf();
  4976. }
  4977. if (me.options.editable.updateGroup) {
  4978. if ('group' in item.data) props.group = item.data.group;
  4979. }
  4980. return props;
  4981. });
  4982. }
  4983. event.stopPropagation();
  4984. }
  4985. };
  4986. /**
  4987. * Drag selected items
  4988. * @param {Event} event
  4989. * @private
  4990. */
  4991. ItemSet.prototype._onDrag = function (event) {
  4992. if (this.touchParams.itemProps) {
  4993. var snap = this.options.snap || null,
  4994. deltaX = event.gesture.deltaX,
  4995. scale = (this.width / (this.range.end - this.range.start)),
  4996. offset = deltaX / scale;
  4997. // move
  4998. this.touchParams.itemProps.forEach(function (props) {
  4999. if ('start' in props) {
  5000. var start = new Date(props.start + offset);
  5001. props.item.data.start = snap ? snap(start) : start;
  5002. }
  5003. if ('end' in props) {
  5004. var end = new Date(props.end + offset);
  5005. props.item.data.end = snap ? snap(end) : end;
  5006. }
  5007. if ('group' in props) {
  5008. // drag from one group to another
  5009. var group = ItemSet.groupFromTarget(event);
  5010. if (group && group.groupId != props.item.data.group) {
  5011. var oldGroup = props.item.parent;
  5012. oldGroup.remove(props.item);
  5013. oldGroup.order();
  5014. group.add(props.item);
  5015. group.order();
  5016. props.item.data.group = group.groupId;
  5017. }
  5018. }
  5019. });
  5020. // TODO: implement onMoving handler
  5021. this.stackDirty = true; // force re-stacking of all items next repaint
  5022. this.emit('change');
  5023. event.stopPropagation();
  5024. }
  5025. };
  5026. /**
  5027. * End of dragging selected items
  5028. * @param {Event} event
  5029. * @private
  5030. */
  5031. ItemSet.prototype._onDragEnd = function (event) {
  5032. if (this.touchParams.itemProps) {
  5033. // prepare a change set for the changed items
  5034. var changes = [],
  5035. me = this,
  5036. dataset = this._myDataSet();
  5037. this.touchParams.itemProps.forEach(function (props) {
  5038. var id = props.item.id,
  5039. itemData = me.itemsData.get(id);
  5040. var changed = false;
  5041. if ('start' in props.item.data) {
  5042. changed = (props.start != props.item.data.start.valueOf());
  5043. itemData.start = util.convert(props.item.data.start, dataset.convert['start']);
  5044. }
  5045. if ('end' in props.item.data) {
  5046. changed = changed || (props.end != props.item.data.end.valueOf());
  5047. itemData.end = util.convert(props.item.data.end, dataset.convert['end']);
  5048. }
  5049. if ('group' in props.item.data) {
  5050. changed = changed || (props.group != props.item.data.group);
  5051. itemData.group = props.item.data.group;
  5052. }
  5053. // only apply changes when start or end is actually changed
  5054. if (changed) {
  5055. me.options.onMove(itemData, function (itemData) {
  5056. if (itemData) {
  5057. // apply changes
  5058. itemData[dataset.fieldId] = id; // ensure the item contains its id (can be undefined)
  5059. changes.push(itemData);
  5060. }
  5061. else {
  5062. // restore original values
  5063. if ('start' in props) props.item.data.start = props.start;
  5064. if ('end' in props) props.item.data.end = props.end;
  5065. me.stackDirty = true; // force re-stacking of all items next repaint
  5066. me.emit('change');
  5067. }
  5068. });
  5069. }
  5070. });
  5071. this.touchParams.itemProps = null;
  5072. // apply the changes to the data (if there are changes)
  5073. if (changes.length) {
  5074. dataset.update(changes);
  5075. }
  5076. event.stopPropagation();
  5077. }
  5078. };
  5079. /**
  5080. * Find an item from an event target:
  5081. * searches for the attribute 'timeline-item' in the event target's element tree
  5082. * @param {Event} event
  5083. * @return {Item | null} item
  5084. */
  5085. ItemSet.itemFromTarget = function itemFromTarget (event) {
  5086. var target = event.target;
  5087. while (target) {
  5088. if (target.hasOwnProperty('timeline-item')) {
  5089. return target['timeline-item'];
  5090. }
  5091. target = target.parentNode;
  5092. }
  5093. return null;
  5094. };
  5095. /**
  5096. * Find the Group from an event target:
  5097. * searches for the attribute 'timeline-group' in the event target's element tree
  5098. * @param {Event} event
  5099. * @return {Group | null} group
  5100. */
  5101. ItemSet.groupFromTarget = function groupFromTarget (event) {
  5102. var target = event.target;
  5103. while (target) {
  5104. if (target.hasOwnProperty('timeline-group')) {
  5105. return target['timeline-group'];
  5106. }
  5107. target = target.parentNode;
  5108. }
  5109. return null;
  5110. };
  5111. /**
  5112. * Find the ItemSet from an event target:
  5113. * searches for the attribute 'timeline-itemset' in the event target's element tree
  5114. * @param {Event} event
  5115. * @return {ItemSet | null} item
  5116. */
  5117. ItemSet.itemSetFromTarget = function itemSetFromTarget (event) {
  5118. var target = event.target;
  5119. while (target) {
  5120. if (target.hasOwnProperty('timeline-itemset')) {
  5121. return target['timeline-itemset'];
  5122. }
  5123. target = target.parentNode;
  5124. }
  5125. return null;
  5126. };
  5127. /**
  5128. * Find the DataSet to which this ItemSet is connected
  5129. * @returns {null | DataSet} dataset
  5130. * @private
  5131. */
  5132. ItemSet.prototype._myDataSet = function _myDataSet() {
  5133. // find the root DataSet
  5134. var dataset = this.itemsData;
  5135. while (dataset instanceof DataView) {
  5136. dataset = dataset.data;
  5137. }
  5138. return dataset;
  5139. };
  5140. /**
  5141. * @constructor Item
  5142. * @param {Object} data Object containing (optional) parameters type,
  5143. * start, end, content, group, className.
  5144. * @param {Object} [options] Options to set initial property values
  5145. * @param {Object} [defaultOptions] default options
  5146. * // TODO: describe available options
  5147. */
  5148. function Item (data, options, defaultOptions) {
  5149. this.id = null;
  5150. this.parent = null;
  5151. this.data = data;
  5152. this.dom = null;
  5153. this.options = options || {};
  5154. this.defaultOptions = defaultOptions || {};
  5155. this.selected = false;
  5156. this.displayed = false;
  5157. this.dirty = true;
  5158. this.top = null;
  5159. this.left = null;
  5160. this.width = null;
  5161. this.height = null;
  5162. }
  5163. /**
  5164. * Select current item
  5165. */
  5166. Item.prototype.select = function select() {
  5167. this.selected = true;
  5168. if (this.displayed) this.repaint();
  5169. };
  5170. /**
  5171. * Unselect current item
  5172. */
  5173. Item.prototype.unselect = function unselect() {
  5174. this.selected = false;
  5175. if (this.displayed) this.repaint();
  5176. };
  5177. /**
  5178. * Set a parent for the item
  5179. * @param {ItemSet | Group} parent
  5180. */
  5181. Item.prototype.setParent = function setParent(parent) {
  5182. if (this.displayed) {
  5183. this.hide();
  5184. this.parent = parent;
  5185. if (this.parent) {
  5186. this.show();
  5187. }
  5188. }
  5189. else {
  5190. this.parent = parent;
  5191. }
  5192. };
  5193. /**
  5194. * Check whether this item is visible inside given range
  5195. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  5196. * @returns {boolean} True if visible
  5197. */
  5198. Item.prototype.isVisible = function isVisible (range) {
  5199. // Should be implemented by Item implementations
  5200. return false;
  5201. };
  5202. /**
  5203. * Show the Item in the DOM (when not already visible)
  5204. * @return {Boolean} changed
  5205. */
  5206. Item.prototype.show = function show() {
  5207. return false;
  5208. };
  5209. /**
  5210. * Hide the Item from the DOM (when visible)
  5211. * @return {Boolean} changed
  5212. */
  5213. Item.prototype.hide = function hide() {
  5214. return false;
  5215. };
  5216. /**
  5217. * Repaint the item
  5218. */
  5219. Item.prototype.repaint = function repaint() {
  5220. // should be implemented by the item
  5221. };
  5222. /**
  5223. * Reposition the Item horizontally
  5224. */
  5225. Item.prototype.repositionX = function repositionX() {
  5226. // should be implemented by the item
  5227. };
  5228. /**
  5229. * Reposition the Item vertically
  5230. */
  5231. Item.prototype.repositionY = function repositionY() {
  5232. // should be implemented by the item
  5233. };
  5234. /**
  5235. * Repaint a delete button on the top right of the item when the item is selected
  5236. * @param {HTMLElement} anchor
  5237. * @protected
  5238. */
  5239. Item.prototype._repaintDeleteButton = function (anchor) {
  5240. if (this.selected && this.options.editable.remove && !this.dom.deleteButton) {
  5241. // create and show button
  5242. var me = this;
  5243. var deleteButton = document.createElement('div');
  5244. deleteButton.className = 'delete';
  5245. deleteButton.title = 'Delete this item';
  5246. Hammer(deleteButton, {
  5247. preventDefault: true
  5248. }).on('tap', function (event) {
  5249. me.parent.removeFromDataSet(me);
  5250. event.stopPropagation();
  5251. });
  5252. anchor.appendChild(deleteButton);
  5253. this.dom.deleteButton = deleteButton;
  5254. }
  5255. else if (!this.selected && this.dom.deleteButton) {
  5256. // remove button
  5257. if (this.dom.deleteButton.parentNode) {
  5258. this.dom.deleteButton.parentNode.removeChild(this.dom.deleteButton);
  5259. }
  5260. this.dom.deleteButton = null;
  5261. }
  5262. };
  5263. /**
  5264. * @constructor ItemBox
  5265. * @extends Item
  5266. * @param {Object} data Object containing parameters start
  5267. * content, className.
  5268. * @param {Object} [options] Options to set initial property values
  5269. * @param {Object} [defaultOptions] default options
  5270. * // TODO: describe available options
  5271. */
  5272. function ItemBox (data, options, defaultOptions) {
  5273. this.props = {
  5274. dot: {
  5275. width: 0,
  5276. height: 0
  5277. },
  5278. line: {
  5279. width: 0,
  5280. height: 0
  5281. }
  5282. };
  5283. // validate data
  5284. if (data) {
  5285. if (data.start == undefined) {
  5286. throw new Error('Property "start" missing in item ' + data);
  5287. }
  5288. }
  5289. Item.call(this, data, options, defaultOptions);
  5290. }
  5291. ItemBox.prototype = new Item (null);
  5292. /**
  5293. * Check whether this item is visible inside given range
  5294. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  5295. * @returns {boolean} True if visible
  5296. */
  5297. ItemBox.prototype.isVisible = function isVisible (range) {
  5298. // determine visibility
  5299. // TODO: account for the real width of the item. Right now we just add 1/4 to the window
  5300. var interval = (range.end - range.start) / 4;
  5301. return (this.data.start > range.start - interval) && (this.data.start < range.end + interval);
  5302. };
  5303. /**
  5304. * Repaint the item
  5305. */
  5306. ItemBox.prototype.repaint = function repaint() {
  5307. var dom = this.dom;
  5308. if (!dom) {
  5309. // create DOM
  5310. this.dom = {};
  5311. dom = this.dom;
  5312. // create main box
  5313. dom.box = document.createElement('DIV');
  5314. // contents box (inside the background box). used for making margins
  5315. dom.content = document.createElement('DIV');
  5316. dom.content.className = 'content';
  5317. dom.box.appendChild(dom.content);
  5318. // line to axis
  5319. dom.line = document.createElement('DIV');
  5320. dom.line.className = 'line';
  5321. // dot on axis
  5322. dom.dot = document.createElement('DIV');
  5323. dom.dot.className = 'dot';
  5324. // attach this item as attribute
  5325. dom.box['timeline-item'] = this;
  5326. }
  5327. // append DOM to parent DOM
  5328. if (!this.parent) {
  5329. throw new Error('Cannot repaint item: no parent attached');
  5330. }
  5331. if (!dom.box.parentNode) {
  5332. var foreground = this.parent.getForeground();
  5333. if (!foreground) throw new Error('Cannot repaint time axis: parent has no foreground container element');
  5334. foreground.appendChild(dom.box);
  5335. }
  5336. if (!dom.line.parentNode) {
  5337. var background = this.parent.getBackground();
  5338. if (!background) throw new Error('Cannot repaint time axis: parent has no background container element');
  5339. background.appendChild(dom.line);
  5340. }
  5341. if (!dom.dot.parentNode) {
  5342. var axis = this.parent.getAxis();
  5343. if (!background) throw new Error('Cannot repaint time axis: parent has no axis container element');
  5344. axis.appendChild(dom.dot);
  5345. }
  5346. this.displayed = true;
  5347. // update contents
  5348. if (this.data.content != this.content) {
  5349. this.content = this.data.content;
  5350. if (this.content instanceof Element) {
  5351. dom.content.innerHTML = '';
  5352. dom.content.appendChild(this.content);
  5353. }
  5354. else if (this.data.content != undefined) {
  5355. dom.content.innerHTML = this.content;
  5356. }
  5357. else {
  5358. throw new Error('Property "content" missing in item ' + this.data.id);
  5359. }
  5360. this.dirty = true;
  5361. }
  5362. // update class
  5363. var className = (this.data.className? ' ' + this.data.className : '') +
  5364. (this.selected ? ' selected' : '');
  5365. if (this.className != className) {
  5366. this.className = className;
  5367. dom.box.className = 'item box' + className;
  5368. dom.line.className = 'item line' + className;
  5369. dom.dot.className = 'item dot' + className;
  5370. this.dirty = true;
  5371. }
  5372. // recalculate size
  5373. if (this.dirty) {
  5374. this.props.dot.height = dom.dot.offsetHeight;
  5375. this.props.dot.width = dom.dot.offsetWidth;
  5376. this.props.line.width = dom.line.offsetWidth;
  5377. this.width = dom.box.offsetWidth;
  5378. this.height = dom.box.offsetHeight;
  5379. this.dirty = false;
  5380. }
  5381. this._repaintDeleteButton(dom.box);
  5382. };
  5383. /**
  5384. * Show the item in the DOM (when not already displayed). The items DOM will
  5385. * be created when needed.
  5386. */
  5387. ItemBox.prototype.show = function show() {
  5388. if (!this.displayed) {
  5389. this.repaint();
  5390. }
  5391. };
  5392. /**
  5393. * Hide the item from the DOM (when visible)
  5394. */
  5395. ItemBox.prototype.hide = function hide() {
  5396. if (this.displayed) {
  5397. var dom = this.dom;
  5398. if (dom.box.parentNode) dom.box.parentNode.removeChild(dom.box);
  5399. if (dom.line.parentNode) dom.line.parentNode.removeChild(dom.line);
  5400. if (dom.dot.parentNode) dom.dot.parentNode.removeChild(dom.dot);
  5401. this.top = null;
  5402. this.left = null;
  5403. this.displayed = false;
  5404. }
  5405. };
  5406. /**
  5407. * Reposition the item horizontally
  5408. * @Override
  5409. */
  5410. ItemBox.prototype.repositionX = function repositionX() {
  5411. var start = this.defaultOptions.toScreen(this.data.start),
  5412. align = this.options.align || this.defaultOptions.align,
  5413. left,
  5414. box = this.dom.box,
  5415. line = this.dom.line,
  5416. dot = this.dom.dot;
  5417. // calculate left position of the box
  5418. if (align == 'right') {
  5419. this.left = start - this.width;
  5420. }
  5421. else if (align == 'left') {
  5422. this.left = start;
  5423. }
  5424. else {
  5425. // default or 'center'
  5426. this.left = start - this.width / 2;
  5427. }
  5428. // reposition box
  5429. box.style.left = this.left + 'px';
  5430. // reposition line
  5431. line.style.left = (start - this.props.line.width / 2) + 'px';
  5432. // reposition dot
  5433. dot.style.left = (start - this.props.dot.width / 2) + 'px';
  5434. };
  5435. /**
  5436. * Reposition the item vertically
  5437. * @Override
  5438. */
  5439. ItemBox.prototype.repositionY = function repositionY () {
  5440. var orientation = this.options.orientation || this.defaultOptions.orientation,
  5441. box = this.dom.box,
  5442. line = this.dom.line,
  5443. dot = this.dom.dot;
  5444. if (orientation == 'top') {
  5445. box.style.top = (this.top || 0) + 'px';
  5446. box.style.bottom = '';
  5447. line.style.top = '0';
  5448. line.style.bottom = '';
  5449. line.style.height = (this.parent.top + this.top + 1) + 'px';
  5450. }
  5451. else { // orientation 'bottom'
  5452. box.style.top = '';
  5453. box.style.bottom = (this.top || 0) + 'px';
  5454. line.style.top = (this.parent.top + this.parent.height - this.top - 1) + 'px';
  5455. line.style.bottom = '0';
  5456. line.style.height = '';
  5457. }
  5458. dot.style.top = (-this.props.dot.height / 2) + 'px';
  5459. };
  5460. /**
  5461. * @constructor ItemPoint
  5462. * @extends Item
  5463. * @param {Object} data Object containing parameters start
  5464. * content, className.
  5465. * @param {Object} [options] Options to set initial property values
  5466. * @param {Object} [defaultOptions] default options
  5467. * // TODO: describe available options
  5468. */
  5469. function ItemPoint (data, options, defaultOptions) {
  5470. this.props = {
  5471. dot: {
  5472. top: 0,
  5473. width: 0,
  5474. height: 0
  5475. },
  5476. content: {
  5477. height: 0,
  5478. marginLeft: 0
  5479. }
  5480. };
  5481. // validate data
  5482. if (data) {
  5483. if (data.start == undefined) {
  5484. throw new Error('Property "start" missing in item ' + data);
  5485. }
  5486. }
  5487. Item.call(this, data, options, defaultOptions);
  5488. }
  5489. ItemPoint.prototype = new Item (null);
  5490. /**
  5491. * Check whether this item is visible inside given range
  5492. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  5493. * @returns {boolean} True if visible
  5494. */
  5495. ItemPoint.prototype.isVisible = function isVisible (range) {
  5496. // determine visibility
  5497. // TODO: account for the real width of the item. Right now we just add 1/4 to the window
  5498. var interval = (range.end - range.start) / 4;
  5499. return (this.data.start > range.start - interval) && (this.data.start < range.end + interval);
  5500. };
  5501. /**
  5502. * Repaint the item
  5503. */
  5504. ItemPoint.prototype.repaint = function repaint() {
  5505. var dom = this.dom;
  5506. if (!dom) {
  5507. // create DOM
  5508. this.dom = {};
  5509. dom = this.dom;
  5510. // background box
  5511. dom.point = document.createElement('div');
  5512. // className is updated in repaint()
  5513. // contents box, right from the dot
  5514. dom.content = document.createElement('div');
  5515. dom.content.className = 'content';
  5516. dom.point.appendChild(dom.content);
  5517. // dot at start
  5518. dom.dot = document.createElement('div');
  5519. dom.point.appendChild(dom.dot);
  5520. // attach this item as attribute
  5521. dom.point['timeline-item'] = this;
  5522. }
  5523. // append DOM to parent DOM
  5524. if (!this.parent) {
  5525. throw new Error('Cannot repaint item: no parent attached');
  5526. }
  5527. if (!dom.point.parentNode) {
  5528. var foreground = this.parent.getForeground();
  5529. if (!foreground) {
  5530. throw new Error('Cannot repaint time axis: parent has no foreground container element');
  5531. }
  5532. foreground.appendChild(dom.point);
  5533. }
  5534. this.displayed = true;
  5535. // update contents
  5536. if (this.data.content != this.content) {
  5537. this.content = this.data.content;
  5538. if (this.content instanceof Element) {
  5539. dom.content.innerHTML = '';
  5540. dom.content.appendChild(this.content);
  5541. }
  5542. else if (this.data.content != undefined) {
  5543. dom.content.innerHTML = this.content;
  5544. }
  5545. else {
  5546. throw new Error('Property "content" missing in item ' + this.data.id);
  5547. }
  5548. this.dirty = true;
  5549. }
  5550. // update class
  5551. var className = (this.data.className? ' ' + this.data.className : '') +
  5552. (this.selected ? ' selected' : '');
  5553. if (this.className != className) {
  5554. this.className = className;
  5555. dom.point.className = 'item point' + className;
  5556. dom.dot.className = 'item dot' + className;
  5557. this.dirty = true;
  5558. }
  5559. // recalculate size
  5560. if (this.dirty) {
  5561. this.width = dom.point.offsetWidth;
  5562. this.height = dom.point.offsetHeight;
  5563. this.props.dot.width = dom.dot.offsetWidth;
  5564. this.props.dot.height = dom.dot.offsetHeight;
  5565. this.props.content.height = dom.content.offsetHeight;
  5566. // resize contents
  5567. dom.content.style.marginLeft = 2 * this.props.dot.width + 'px';
  5568. //dom.content.style.marginRight = ... + 'px'; // TODO: margin right
  5569. dom.dot.style.top = ((this.height - this.props.dot.height) / 2) + 'px';
  5570. dom.dot.style.left = (this.props.dot.width / 2) + 'px';
  5571. this.dirty = false;
  5572. }
  5573. this._repaintDeleteButton(dom.point);
  5574. };
  5575. /**
  5576. * Show the item in the DOM (when not already visible). The items DOM will
  5577. * be created when needed.
  5578. */
  5579. ItemPoint.prototype.show = function show() {
  5580. if (!this.displayed) {
  5581. this.repaint();
  5582. }
  5583. };
  5584. /**
  5585. * Hide the item from the DOM (when visible)
  5586. */
  5587. ItemPoint.prototype.hide = function hide() {
  5588. if (this.displayed) {
  5589. if (this.dom.point.parentNode) {
  5590. this.dom.point.parentNode.removeChild(this.dom.point);
  5591. }
  5592. this.top = null;
  5593. this.left = null;
  5594. this.displayed = false;
  5595. }
  5596. };
  5597. /**
  5598. * Reposition the item horizontally
  5599. * @Override
  5600. */
  5601. ItemPoint.prototype.repositionX = function repositionX() {
  5602. var start = this.defaultOptions.toScreen(this.data.start);
  5603. this.left = start - this.props.dot.width;
  5604. // reposition point
  5605. this.dom.point.style.left = this.left + 'px';
  5606. };
  5607. /**
  5608. * Reposition the item vertically
  5609. * @Override
  5610. */
  5611. ItemPoint.prototype.repositionY = function repositionY () {
  5612. var orientation = this.options.orientation || this.defaultOptions.orientation,
  5613. point = this.dom.point;
  5614. if (orientation == 'top') {
  5615. point.style.top = this.top + 'px';
  5616. point.style.bottom = '';
  5617. }
  5618. else {
  5619. point.style.top = '';
  5620. point.style.bottom = this.top + 'px';
  5621. }
  5622. };
  5623. /**
  5624. * @constructor ItemRange
  5625. * @extends Item
  5626. * @param {Object} data Object containing parameters start, end
  5627. * content, className.
  5628. * @param {Object} [options] Options to set initial property values
  5629. * @param {Object} [defaultOptions] default options
  5630. * // TODO: describe available options
  5631. */
  5632. function ItemRange (data, options, defaultOptions) {
  5633. this.props = {
  5634. content: {
  5635. width: 0
  5636. }
  5637. };
  5638. // validate data
  5639. if (data) {
  5640. if (data.start == undefined) {
  5641. throw new Error('Property "start" missing in item ' + data.id);
  5642. }
  5643. if (data.end == undefined) {
  5644. throw new Error('Property "end" missing in item ' + data.id);
  5645. }
  5646. }
  5647. Item.call(this, data, options, defaultOptions);
  5648. }
  5649. ItemRange.prototype = new Item (null);
  5650. ItemRange.prototype.baseClassName = 'item range';
  5651. /**
  5652. * Check whether this item is visible inside given range
  5653. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  5654. * @returns {boolean} True if visible
  5655. */
  5656. ItemRange.prototype.isVisible = function isVisible (range) {
  5657. // determine visibility
  5658. return (this.data.start < range.end) && (this.data.end > range.start);
  5659. };
  5660. /**
  5661. * Repaint the item
  5662. */
  5663. ItemRange.prototype.repaint = function repaint() {
  5664. var dom = this.dom;
  5665. if (!dom) {
  5666. // create DOM
  5667. this.dom = {};
  5668. dom = this.dom;
  5669. // background box
  5670. dom.box = document.createElement('div');
  5671. // className is updated in repaint()
  5672. // contents box
  5673. dom.content = document.createElement('div');
  5674. dom.content.className = 'content';
  5675. dom.box.appendChild(dom.content);
  5676. // attach this item as attribute
  5677. dom.box['timeline-item'] = this;
  5678. }
  5679. // append DOM to parent DOM
  5680. if (!this.parent) {
  5681. throw new Error('Cannot repaint item: no parent attached');
  5682. }
  5683. if (!dom.box.parentNode) {
  5684. var foreground = this.parent.getForeground();
  5685. if (!foreground) {
  5686. throw new Error('Cannot repaint time axis: parent has no foreground container element');
  5687. }
  5688. foreground.appendChild(dom.box);
  5689. }
  5690. this.displayed = true;
  5691. // update contents
  5692. if (this.data.content != this.content) {
  5693. this.content = this.data.content;
  5694. if (this.content instanceof Element) {
  5695. dom.content.innerHTML = '';
  5696. dom.content.appendChild(this.content);
  5697. }
  5698. else if (this.data.content != undefined) {
  5699. dom.content.innerHTML = this.content;
  5700. }
  5701. else {
  5702. throw new Error('Property "content" missing in item ' + this.data.id);
  5703. }
  5704. this.dirty = true;
  5705. }
  5706. // update class
  5707. var className = (this.data.className ? (' ' + this.data.className) : '') +
  5708. (this.selected ? ' selected' : '');
  5709. if (this.className != className) {
  5710. this.className = className;
  5711. dom.box.className = this.baseClassName + className;
  5712. this.dirty = true;
  5713. }
  5714. // recalculate size
  5715. if (this.dirty) {
  5716. this.props.content.width = this.dom.content.offsetWidth;
  5717. this.height = this.dom.box.offsetHeight;
  5718. this.dirty = false;
  5719. }
  5720. this._repaintDeleteButton(dom.box);
  5721. this._repaintDragLeft();
  5722. this._repaintDragRight();
  5723. };
  5724. /**
  5725. * Show the item in the DOM (when not already visible). The items DOM will
  5726. * be created when needed.
  5727. */
  5728. ItemRange.prototype.show = function show() {
  5729. if (!this.displayed) {
  5730. this.repaint();
  5731. }
  5732. };
  5733. /**
  5734. * Hide the item from the DOM (when visible)
  5735. * @return {Boolean} changed
  5736. */
  5737. ItemRange.prototype.hide = function hide() {
  5738. if (this.displayed) {
  5739. var box = this.dom.box;
  5740. if (box.parentNode) {
  5741. box.parentNode.removeChild(box);
  5742. }
  5743. this.top = null;
  5744. this.left = null;
  5745. this.displayed = false;
  5746. }
  5747. };
  5748. /**
  5749. * Reposition the item horizontally
  5750. * @Override
  5751. */
  5752. ItemRange.prototype.repositionX = function repositionX() {
  5753. var props = this.props,
  5754. parentWidth = this.parent.width,
  5755. start = this.defaultOptions.toScreen(this.data.start),
  5756. end = this.defaultOptions.toScreen(this.data.end),
  5757. padding = 'padding' in this.options ? this.options.padding : this.defaultOptions.padding,
  5758. contentLeft;
  5759. // limit the width of the this, as browsers cannot draw very wide divs
  5760. if (start < -parentWidth) {
  5761. start = -parentWidth;
  5762. }
  5763. if (end > 2 * parentWidth) {
  5764. end = 2 * parentWidth;
  5765. }
  5766. // when range exceeds left of the window, position the contents at the left of the visible area
  5767. if (start < 0) {
  5768. contentLeft = Math.min(-start,
  5769. (end - start - props.content.width - 2 * padding));
  5770. // TODO: remove the need for options.padding. it's terrible.
  5771. }
  5772. else {
  5773. contentLeft = 0;
  5774. }
  5775. this.left = start;
  5776. this.width = Math.max(end - start, 1);
  5777. this.dom.box.style.left = this.left + 'px';
  5778. this.dom.box.style.width = this.width + 'px';
  5779. this.dom.content.style.left = contentLeft + 'px';
  5780. };
  5781. /**
  5782. * Reposition the item vertically
  5783. * @Override
  5784. */
  5785. ItemRange.prototype.repositionY = function repositionY() {
  5786. var orientation = this.options.orientation || this.defaultOptions.orientation,
  5787. box = this.dom.box;
  5788. if (orientation == 'top') {
  5789. box.style.top = this.top + 'px';
  5790. box.style.bottom = '';
  5791. }
  5792. else {
  5793. box.style.top = '';
  5794. box.style.bottom = this.top + 'px';
  5795. }
  5796. };
  5797. /**
  5798. * Repaint a drag area on the left side of the range when the range is selected
  5799. * @protected
  5800. */
  5801. ItemRange.prototype._repaintDragLeft = function () {
  5802. if (this.selected && this.options.editable.updateTime && !this.dom.dragLeft) {
  5803. // create and show drag area
  5804. var dragLeft = document.createElement('div');
  5805. dragLeft.className = 'drag-left';
  5806. dragLeft.dragLeftItem = this;
  5807. // TODO: this should be redundant?
  5808. Hammer(dragLeft, {
  5809. preventDefault: true
  5810. }).on('drag', function () {
  5811. //console.log('drag left')
  5812. });
  5813. this.dom.box.appendChild(dragLeft);
  5814. this.dom.dragLeft = dragLeft;
  5815. }
  5816. else if (!this.selected && this.dom.dragLeft) {
  5817. // delete drag area
  5818. if (this.dom.dragLeft.parentNode) {
  5819. this.dom.dragLeft.parentNode.removeChild(this.dom.dragLeft);
  5820. }
  5821. this.dom.dragLeft = null;
  5822. }
  5823. };
  5824. /**
  5825. * Repaint a drag area on the right side of the range when the range is selected
  5826. * @protected
  5827. */
  5828. ItemRange.prototype._repaintDragRight = function () {
  5829. if (this.selected && this.options.editable.updateTime && !this.dom.dragRight) {
  5830. // create and show drag area
  5831. var dragRight = document.createElement('div');
  5832. dragRight.className = 'drag-right';
  5833. dragRight.dragRightItem = this;
  5834. // TODO: this should be redundant?
  5835. Hammer(dragRight, {
  5836. preventDefault: true
  5837. }).on('drag', function () {
  5838. //console.log('drag right')
  5839. });
  5840. this.dom.box.appendChild(dragRight);
  5841. this.dom.dragRight = dragRight;
  5842. }
  5843. else if (!this.selected && this.dom.dragRight) {
  5844. // delete drag area
  5845. if (this.dom.dragRight.parentNode) {
  5846. this.dom.dragRight.parentNode.removeChild(this.dom.dragRight);
  5847. }
  5848. this.dom.dragRight = null;
  5849. }
  5850. };
  5851. /**
  5852. * @constructor ItemRangeOverflow
  5853. * @extends ItemRange
  5854. * @param {Object} data Object containing parameters start, end
  5855. * content, className.
  5856. * @param {Object} [options] Options to set initial property values
  5857. * @param {Object} [defaultOptions] default options
  5858. * // TODO: describe available options
  5859. */
  5860. function ItemRangeOverflow (data, options, defaultOptions) {
  5861. this.props = {
  5862. content: {
  5863. left: 0,
  5864. width: 0
  5865. }
  5866. };
  5867. ItemRange.call(this, data, options, defaultOptions);
  5868. }
  5869. ItemRangeOverflow.prototype = new ItemRange (null);
  5870. ItemRangeOverflow.prototype.baseClassName = 'item rangeoverflow';
  5871. /**
  5872. * Reposition the item horizontally
  5873. * @Override
  5874. */
  5875. ItemRangeOverflow.prototype.repositionX = function repositionX() {
  5876. var parentWidth = this.parent.width,
  5877. start = this.defaultOptions.toScreen(this.data.start),
  5878. end = this.defaultOptions.toScreen(this.data.end),
  5879. padding = 'padding' in this.options ? this.options.padding : this.defaultOptions.padding,
  5880. contentLeft;
  5881. // limit the width of the this, as browsers cannot draw very wide divs
  5882. if (start < -parentWidth) {
  5883. start = -parentWidth;
  5884. }
  5885. if (end > 2 * parentWidth) {
  5886. end = 2 * parentWidth;
  5887. }
  5888. // when range exceeds left of the window, position the contents at the left of the visible area
  5889. contentLeft = Math.max(-start, 0);
  5890. this.left = start;
  5891. var boxWidth = Math.max(end - start, 1);
  5892. this.width = boxWidth + this.props.content.width;
  5893. // Note: The calculation of width is an optimistic calculation, giving
  5894. // a width which will not change when moving the Timeline
  5895. // So no restacking needed, which is nicer for the eye
  5896. this.dom.box.style.left = this.left + 'px';
  5897. this.dom.box.style.width = boxWidth + 'px';
  5898. this.dom.content.style.left = contentLeft + 'px';
  5899. };
  5900. /**
  5901. * @constructor Group
  5902. * @param {Number | String} groupId
  5903. * @param {Object} data
  5904. * @param {ItemSet} itemSet
  5905. */
  5906. function Group (groupId, data, itemSet) {
  5907. this.groupId = groupId;
  5908. this.itemSet = itemSet;
  5909. this.dom = {};
  5910. this.props = {
  5911. label: {
  5912. width: 0,
  5913. height: 0
  5914. }
  5915. };
  5916. this.items = {}; // items filtered by groupId of this group
  5917. this.visibleItems = []; // items currently visible in window
  5918. this.orderedItems = { // items sorted by start and by end
  5919. byStart: [],
  5920. byEnd: []
  5921. };
  5922. this._create();
  5923. this.setData(data);
  5924. }
  5925. /**
  5926. * Create DOM elements for the group
  5927. * @private
  5928. */
  5929. Group.prototype._create = function() {
  5930. var label = document.createElement('div');
  5931. label.className = 'vlabel';
  5932. this.dom.label = label;
  5933. var inner = document.createElement('div');
  5934. inner.className = 'inner';
  5935. label.appendChild(inner);
  5936. this.dom.inner = inner;
  5937. var foreground = document.createElement('div');
  5938. foreground.className = 'group';
  5939. foreground['timeline-group'] = this;
  5940. this.dom.foreground = foreground;
  5941. this.dom.background = document.createElement('div');
  5942. this.dom.axis = document.createElement('div');
  5943. // create a hidden marker to detect when the Timelines container is attached
  5944. // to the DOM, or the style of a parent of the Timeline is changed from
  5945. // display:none is changed to visible.
  5946. this.dom.marker = document.createElement('div');
  5947. this.dom.marker.style.visibility = 'hidden';
  5948. this.dom.marker.innerHTML = '?';
  5949. this.dom.background.appendChild(this.dom.marker);
  5950. };
  5951. /**
  5952. * Set the group data for this group
  5953. * @param {Object} data Group data, can contain properties content and className
  5954. */
  5955. Group.prototype.setData = function setData(data) {
  5956. // update contents
  5957. var content = data && data.content;
  5958. if (content instanceof Element) {
  5959. this.dom.inner.appendChild(content);
  5960. }
  5961. else if (content != undefined) {
  5962. this.dom.inner.innerHTML = content;
  5963. }
  5964. else {
  5965. this.dom.inner.innerHTML = this.groupId;
  5966. }
  5967. // update className
  5968. var className = data && data.className;
  5969. if (className) {
  5970. util.addClassName(this.dom.label, className);
  5971. }
  5972. };
  5973. /**
  5974. * Get the foreground container element
  5975. * @return {HTMLElement} foreground
  5976. */
  5977. Group.prototype.getForeground = function getForeground() {
  5978. return this.dom.foreground;
  5979. };
  5980. /**
  5981. * Get the background container element
  5982. * @return {HTMLElement} background
  5983. */
  5984. Group.prototype.getBackground = function getBackground() {
  5985. return this.dom.background;
  5986. };
  5987. /**
  5988. * Get the axis container element
  5989. * @return {HTMLElement} axis
  5990. */
  5991. Group.prototype.getAxis = function getAxis() {
  5992. return this.dom.axis;
  5993. };
  5994. /**
  5995. * Get the width of the group label
  5996. * @return {number} width
  5997. */
  5998. Group.prototype.getLabelWidth = function getLabelWidth() {
  5999. return this.props.label.width;
  6000. };
  6001. /**
  6002. * Repaint this group
  6003. * @param {{start: number, end: number}} range
  6004. * @param {{item: number, axis: number}} margin
  6005. * @param {boolean} [restack=false] Force restacking of all items
  6006. * @return {boolean} Returns true if the group is resized
  6007. */
  6008. Group.prototype.repaint = function repaint(range, margin, restack) {
  6009. var resized = false;
  6010. this.visibleItems = this._updateVisibleItems(this.orderedItems, this.visibleItems, range);
  6011. // force recalculation of the height of the items when the marker height changed
  6012. // (due to the Timeline being attached to the DOM or changed from display:none to visible)
  6013. var markerHeight = this.dom.marker.clientHeight;
  6014. if (markerHeight != this.lastMarkerHeight) {
  6015. this.lastMarkerHeight = markerHeight;
  6016. util.forEach(this.items, function (item) {
  6017. item.dirty = true;
  6018. if (item.displayed) item.repaint();
  6019. });
  6020. restack = true;
  6021. }
  6022. // reposition visible items vertically
  6023. if (this.itemSet.options.stack) { // TODO: ugly way to access options...
  6024. stack.stack(this.visibleItems, margin, restack);
  6025. }
  6026. else { // no stacking
  6027. stack.nostack(this.visibleItems, margin);
  6028. }
  6029. for (var i = 0, ii = this.visibleItems.length; i < ii; i++) {
  6030. var item = this.visibleItems[i];
  6031. item.repositionY();
  6032. }
  6033. // recalculate the height of the group
  6034. var height;
  6035. var visibleItems = this.visibleItems;
  6036. if (visibleItems.length) {
  6037. var min = visibleItems[0].top;
  6038. var max = visibleItems[0].top + visibleItems[0].height;
  6039. util.forEach(visibleItems, function (item) {
  6040. min = Math.min(min, item.top);
  6041. max = Math.max(max, (item.top + item.height));
  6042. });
  6043. height = (max - min) + margin.axis + margin.item;
  6044. }
  6045. else {
  6046. height = margin.axis + margin.item;
  6047. }
  6048. height = Math.max(height, this.props.label.height);
  6049. // calculate actual size and position
  6050. var foreground = this.dom.foreground;
  6051. this.top = foreground.offsetTop;
  6052. this.left = foreground.offsetLeft;
  6053. this.width = foreground.offsetWidth;
  6054. resized = util.updateProperty(this, 'height', height) || resized;
  6055. // recalculate size of label
  6056. resized = util.updateProperty(this.props.label, 'width', this.dom.inner.clientWidth) || resized;
  6057. resized = util.updateProperty(this.props.label, 'height', this.dom.inner.clientHeight) || resized;
  6058. // apply new height
  6059. foreground.style.height = height + 'px';
  6060. this.dom.label.style.height = height + 'px';
  6061. return resized;
  6062. };
  6063. /**
  6064. * Show this group: attach to the DOM
  6065. */
  6066. Group.prototype.show = function show() {
  6067. if (!this.dom.label.parentNode) {
  6068. this.itemSet.getLabelSet().appendChild(this.dom.label);
  6069. }
  6070. if (!this.dom.foreground.parentNode) {
  6071. this.itemSet.getForeground().appendChild(this.dom.foreground);
  6072. }
  6073. if (!this.dom.background.parentNode) {
  6074. this.itemSet.getBackground().appendChild(this.dom.background);
  6075. }
  6076. if (!this.dom.axis.parentNode) {
  6077. this.itemSet.getAxis().appendChild(this.dom.axis);
  6078. }
  6079. };
  6080. /**
  6081. * Hide this group: remove from the DOM
  6082. */
  6083. Group.prototype.hide = function hide() {
  6084. var label = this.dom.label;
  6085. if (label.parentNode) {
  6086. label.parentNode.removeChild(label);
  6087. }
  6088. var foreground = this.dom.foreground;
  6089. if (foreground.parentNode) {
  6090. foreground.parentNode.removeChild(foreground);
  6091. }
  6092. var background = this.dom.background;
  6093. if (background.parentNode) {
  6094. background.parentNode.removeChild(background);
  6095. }
  6096. var axis = this.dom.axis;
  6097. if (axis.parentNode) {
  6098. axis.parentNode.removeChild(axis);
  6099. }
  6100. };
  6101. /**
  6102. * Add an item to the group
  6103. * @param {Item} item
  6104. */
  6105. Group.prototype.add = function add(item) {
  6106. this.items[item.id] = item;
  6107. item.setParent(this);
  6108. if (item instanceof ItemRange && this.visibleItems.indexOf(item) == -1) {
  6109. var range = this.itemSet.range; // TODO: not nice accessing the range like this
  6110. this._checkIfVisible(item, this.visibleItems, range);
  6111. }
  6112. };
  6113. /**
  6114. * Remove an item from the group
  6115. * @param {Item} item
  6116. */
  6117. Group.prototype.remove = function remove(item) {
  6118. delete this.items[item.id];
  6119. item.setParent(this.itemSet);
  6120. // remove from visible items
  6121. var index = this.visibleItems.indexOf(item);
  6122. if (index != -1) this.visibleItems.splice(index, 1);
  6123. // TODO: also remove from ordered items?
  6124. };
  6125. /**
  6126. * Remove an item from the corresponding DataSet
  6127. * @param {Item} item
  6128. */
  6129. Group.prototype.removeFromDataSet = function removeFromDataSet(item) {
  6130. this.itemSet.removeItem(item.id);
  6131. };
  6132. /**
  6133. * Reorder the items
  6134. */
  6135. Group.prototype.order = function order() {
  6136. var array = util.toArray(this.items);
  6137. this.orderedItems.byStart = array;
  6138. this.orderedItems.byEnd = this._constructByEndArray(array);
  6139. stack.orderByStart(this.orderedItems.byStart);
  6140. stack.orderByEnd(this.orderedItems.byEnd);
  6141. };
  6142. /**
  6143. * Create an array containing all items being a range (having an end date)
  6144. * @param {Item[]} array
  6145. * @returns {ItemRange[]}
  6146. * @private
  6147. */
  6148. Group.prototype._constructByEndArray = function _constructByEndArray(array) {
  6149. var endArray = [];
  6150. for (var i = 0; i < array.length; i++) {
  6151. if (array[i] instanceof ItemRange) {
  6152. endArray.push(array[i]);
  6153. }
  6154. }
  6155. return endArray;
  6156. };
  6157. /**
  6158. * Update the visible items
  6159. * @param {{byStart: Item[], byEnd: Item[]}} orderedItems All items ordered by start date and by end date
  6160. * @param {Item[]} visibleItems The previously visible items.
  6161. * @param {{start: number, end: number}} range Visible range
  6162. * @return {Item[]} visibleItems The new visible items.
  6163. * @private
  6164. */
  6165. Group.prototype._updateVisibleItems = function _updateVisibleItems(orderedItems, visibleItems, range) {
  6166. var initialPosByStart,
  6167. newVisibleItems = [],
  6168. i;
  6169. // first check if the items that were in view previously are still in view.
  6170. // this handles the case for the ItemRange that is both before and after the current one.
  6171. if (visibleItems.length > 0) {
  6172. for (i = 0; i < visibleItems.length; i++) {
  6173. this._checkIfVisible(visibleItems[i], newVisibleItems, range);
  6174. }
  6175. }
  6176. // If there were no visible items previously, use binarySearch to find a visible ItemPoint or ItemRange (based on startTime)
  6177. if (newVisibleItems.length == 0) {
  6178. initialPosByStart = this._binarySearch(orderedItems, range, false);
  6179. }
  6180. else {
  6181. initialPosByStart = orderedItems.byStart.indexOf(newVisibleItems[0]);
  6182. }
  6183. // use visible search to find a visible ItemRange (only based on endTime)
  6184. var initialPosByEnd = this._binarySearch(orderedItems, range, true);
  6185. // if we found a initial ID to use, trace it up and down until we meet an invisible item.
  6186. if (initialPosByStart != -1) {
  6187. for (i = initialPosByStart; i >= 0; i--) {
  6188. if (this._checkIfInvisible(orderedItems.byStart[i], newVisibleItems, range)) {break;}
  6189. }
  6190. for (i = initialPosByStart + 1; i < orderedItems.byStart.length; i++) {
  6191. if (this._checkIfInvisible(orderedItems.byStart[i], newVisibleItems, range)) {break;}
  6192. }
  6193. }
  6194. // if we found a initial ID to use, trace it up and down until we meet an invisible item.
  6195. if (initialPosByEnd != -1) {
  6196. for (i = initialPosByEnd; i >= 0; i--) {
  6197. if (this._checkIfInvisible(orderedItems.byEnd[i], newVisibleItems, range)) {break;}
  6198. }
  6199. for (i = initialPosByEnd + 1; i < orderedItems.byEnd.length; i++) {
  6200. if (this._checkIfInvisible(orderedItems.byEnd[i], newVisibleItems, range)) {break;}
  6201. }
  6202. }
  6203. return newVisibleItems;
  6204. };
  6205. /**
  6206. * This function does a binary search for a visible item. The user can select either the this.orderedItems.byStart or .byEnd
  6207. * arrays. This is done by giving a boolean value true if you want to use the byEnd.
  6208. * This is done to be able to select the correct if statement (we do not want to check if an item is visible, we want to check
  6209. * if the time we selected (start or end) is within the current range).
  6210. *
  6211. * The trick is that every interval has to either enter the screen at the initial load or by dragging. The case of the ItemRange that is
  6212. * before and after the current range is handled by simply checking if it was in view before and if it is again. For all the rest,
  6213. * either the start OR end time has to be in the range.
  6214. *
  6215. * @param {{byStart: Item[], byEnd: Item[]}} orderedItems
  6216. * @param {{start: number, end: number}} range
  6217. * @param {Boolean} byEnd
  6218. * @returns {number}
  6219. * @private
  6220. */
  6221. Group.prototype._binarySearch = function _binarySearch(orderedItems, range, byEnd) {
  6222. var array = [];
  6223. var byTime = byEnd ? 'end' : 'start';
  6224. if (byEnd == true) {array = orderedItems.byEnd; }
  6225. else {array = orderedItems.byStart;}
  6226. var interval = range.end - range.start;
  6227. var found = false;
  6228. var low = 0;
  6229. var high = array.length;
  6230. var guess = Math.floor(0.5*(high+low));
  6231. var newGuess;
  6232. if (high == 0) {guess = -1;}
  6233. else if (high == 1) {
  6234. if ((array[guess].data[byTime] > range.start - interval) && (array[guess].data[byTime] < range.end)) {
  6235. guess = 0;
  6236. }
  6237. else {
  6238. guess = -1;
  6239. }
  6240. }
  6241. else {
  6242. high -= 1;
  6243. while (found == false) {
  6244. if ((array[guess].data[byTime] > range.start - interval) && (array[guess].data[byTime] < range.end)) {
  6245. found = true;
  6246. }
  6247. else {
  6248. if (array[guess].data[byTime] < range.start - interval) { // it is too small --> increase low
  6249. low = Math.floor(0.5*(high+low));
  6250. }
  6251. else { // it is too big --> decrease high
  6252. high = Math.floor(0.5*(high+low));
  6253. }
  6254. newGuess = Math.floor(0.5*(high+low));
  6255. // not in list;
  6256. if (guess == newGuess) {
  6257. guess = -1;
  6258. found = true;
  6259. }
  6260. else {
  6261. guess = newGuess;
  6262. }
  6263. }
  6264. }
  6265. }
  6266. return guess;
  6267. };
  6268. /**
  6269. * this function checks if an item is invisible. If it is NOT we make it visible
  6270. * and add it to the global visible items. If it is, return true.
  6271. *
  6272. * @param {Item} item
  6273. * @param {Item[]} visibleItems
  6274. * @param {{start:number, end:number}} range
  6275. * @returns {boolean}
  6276. * @private
  6277. */
  6278. Group.prototype._checkIfInvisible = function _checkIfInvisible(item, visibleItems, range) {
  6279. if (item.isVisible(range)) {
  6280. if (!item.displayed) item.show();
  6281. item.repositionX();
  6282. if (visibleItems.indexOf(item) == -1) {
  6283. visibleItems.push(item);
  6284. }
  6285. return false;
  6286. }
  6287. else {
  6288. return true;
  6289. }
  6290. };
  6291. /**
  6292. * this function is very similar to the _checkIfInvisible() but it does not
  6293. * return booleans, hides the item if it should not be seen and always adds to
  6294. * the visibleItems.
  6295. * this one is for brute forcing and hiding.
  6296. *
  6297. * @param {Item} item
  6298. * @param {Array} visibleItems
  6299. * @param {{start:number, end:number}} range
  6300. * @private
  6301. */
  6302. Group.prototype._checkIfVisible = function _checkIfVisible(item, visibleItems, range) {
  6303. if (item.isVisible(range)) {
  6304. if (!item.displayed) item.show();
  6305. // reposition item horizontally
  6306. item.repositionX();
  6307. visibleItems.push(item);
  6308. }
  6309. else {
  6310. if (item.displayed) item.hide();
  6311. }
  6312. };
  6313. /**
  6314. * Create a timeline visualization
  6315. * @param {HTMLElement} container
  6316. * @param {vis.DataSet | Array | google.visualization.DataTable} [items]
  6317. * @param {Object} [options] See Timeline.setOptions for the available options.
  6318. * @constructor
  6319. */
  6320. function Timeline (container, items, options) {
  6321. // validate arguments
  6322. if (!container) throw new Error('No container element provided');
  6323. var me = this;
  6324. var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0);
  6325. this.defaultOptions = {
  6326. orientation: 'bottom',
  6327. direction: 'horizontal', // 'horizontal' or 'vertical'
  6328. autoResize: true,
  6329. stack: true,
  6330. editable: {
  6331. updateTime: false,
  6332. updateGroup: false,
  6333. add: false,
  6334. remove: false
  6335. },
  6336. selectable: true,
  6337. min: null,
  6338. max: null,
  6339. zoomMin: 10, // milliseconds
  6340. zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000, // milliseconds
  6341. // moveable: true, // TODO: option moveable
  6342. // zoomable: true, // TODO: option zoomable
  6343. showMinorLabels: true,
  6344. showMajorLabels: true,
  6345. showCurrentTime: false,
  6346. showCustomTime: false,
  6347. groupOrder: null,
  6348. width: null,
  6349. height: null,
  6350. maxHeight: null,
  6351. minHeight: null,
  6352. type: 'box',
  6353. align: 'center',
  6354. margin: {
  6355. axis: 20,
  6356. item: 10
  6357. },
  6358. padding: 5,
  6359. onAdd: function (item, callback) {
  6360. callback(item);
  6361. },
  6362. onUpdate: function (item, callback) {
  6363. callback(item);
  6364. },
  6365. onMove: function (item, callback) {
  6366. callback(item);
  6367. },
  6368. onRemove: function (item, callback) {
  6369. callback(item);
  6370. }
  6371. };
  6372. this.options = {};
  6373. util.deepExtend(this.options, this.defaultOptions);
  6374. util.deepExtend(this.options, {
  6375. snap: null, // will be specified after timeaxis is created
  6376. toScreen: me._toScreen.bind(me),
  6377. toTime: me._toTime.bind(me)
  6378. });
  6379. // root panel
  6380. var rootOptions = util.extend(Object.create(this.options), {
  6381. height: function () {
  6382. if (me.options.height) {
  6383. // fixed height
  6384. return me.options.height;
  6385. }
  6386. else {
  6387. // auto height
  6388. // TODO: implement a css based solution to automatically have the right hight
  6389. return (me.timeAxis.height + me.contentPanel.height) + 'px';
  6390. }
  6391. }
  6392. });
  6393. this.rootPanel = new RootPanel(container, rootOptions);
  6394. // single select (or unselect) when tapping an item
  6395. this.rootPanel.on('tap', this._onSelectItem.bind(this));
  6396. // multi select when holding mouse/touch, or on ctrl+click
  6397. this.rootPanel.on('hold', this._onMultiSelectItem.bind(this));
  6398. // add item on doubletap
  6399. this.rootPanel.on('doubletap', this._onAddItem.bind(this));
  6400. // side panel
  6401. var sideOptions = util.extend(Object.create(this.options), {
  6402. top: function () {
  6403. return (sideOptions.orientation == 'top') ? '0' : '';
  6404. },
  6405. bottom: function () {
  6406. return (sideOptions.orientation == 'top') ? '' : '0';
  6407. },
  6408. left: '0',
  6409. right: null,
  6410. height: '100%',
  6411. width: function () {
  6412. if (me.itemSet) {
  6413. return me.itemSet.getLabelsWidth();
  6414. }
  6415. else {
  6416. return 0;
  6417. }
  6418. },
  6419. className: function () {
  6420. return 'side' + (me.groupsData ? '' : ' hidden');
  6421. }
  6422. });
  6423. this.sidePanel = new Panel(sideOptions);
  6424. this.rootPanel.appendChild(this.sidePanel);
  6425. // main panel (contains time axis and itemsets)
  6426. var mainOptions = util.extend(Object.create(this.options), {
  6427. left: function () {
  6428. // we align left to enable a smooth resizing of the window
  6429. return me.sidePanel.width;
  6430. },
  6431. right: null,
  6432. height: '100%',
  6433. width: function () {
  6434. return me.rootPanel.width - me.sidePanel.width;
  6435. },
  6436. className: 'main'
  6437. });
  6438. this.mainPanel = new Panel(mainOptions);
  6439. this.rootPanel.appendChild(this.mainPanel);
  6440. // range
  6441. // TODO: move range inside rootPanel?
  6442. var rangeOptions = Object.create(this.options);
  6443. this.range = new Range(this.rootPanel, this.mainPanel, rangeOptions);
  6444. this.range.setRange(
  6445. now.clone().add('days', -3).valueOf(),
  6446. now.clone().add('days', 4).valueOf()
  6447. );
  6448. this.range.on('rangechange', function (properties) {
  6449. me.rootPanel.repaint();
  6450. me.emit('rangechange', properties);
  6451. });
  6452. this.range.on('rangechanged', function (properties) {
  6453. me.rootPanel.repaint();
  6454. me.emit('rangechanged', properties);
  6455. });
  6456. // panel with time axis
  6457. var timeAxisOptions = util.extend(Object.create(rootOptions), {
  6458. range: this.range,
  6459. left: null,
  6460. top: null,
  6461. width: null,
  6462. height: null
  6463. });
  6464. this.timeAxis = new TimeAxis(timeAxisOptions);
  6465. this.timeAxis.setRange(this.range);
  6466. this.options.snap = this.timeAxis.snap.bind(this.timeAxis);
  6467. this.mainPanel.appendChild(this.timeAxis);
  6468. // content panel (contains itemset(s))
  6469. var contentOptions = util.extend(Object.create(this.options), {
  6470. top: function () {
  6471. return (me.options.orientation == 'top') ? (me.timeAxis.height + 'px') : '';
  6472. },
  6473. bottom: function () {
  6474. return (me.options.orientation == 'top') ? '' : (me.timeAxis.height + 'px');
  6475. },
  6476. left: null,
  6477. right: null,
  6478. height: null,
  6479. width: null,
  6480. className: 'content'
  6481. });
  6482. this.contentPanel = new Panel(contentOptions);
  6483. this.mainPanel.appendChild(this.contentPanel);
  6484. // content panel (contains the vertical lines of box items)
  6485. var backgroundOptions = util.extend(Object.create(this.options), {
  6486. top: function () {
  6487. return (me.options.orientation == 'top') ? (me.timeAxis.height + 'px') : '';
  6488. },
  6489. bottom: function () {
  6490. return (me.options.orientation == 'top') ? '' : (me.timeAxis.height + 'px');
  6491. },
  6492. left: null,
  6493. right: null,
  6494. height: function () {
  6495. return me.contentPanel.height;
  6496. },
  6497. width: null,
  6498. className: 'background'
  6499. });
  6500. this.backgroundPanel = new Panel(backgroundOptions);
  6501. this.mainPanel.insertBefore(this.backgroundPanel, this.contentPanel);
  6502. // panel with axis holding the dots of item boxes
  6503. var axisPanelOptions = util.extend(Object.create(rootOptions), {
  6504. left: 0,
  6505. top: function () {
  6506. return (me.options.orientation == 'top') ? (me.timeAxis.height + 'px') : '';
  6507. },
  6508. bottom: function () {
  6509. return (me.options.orientation == 'top') ? '' : (me.timeAxis.height + 'px');
  6510. },
  6511. width: '100%',
  6512. height: 0,
  6513. className: 'axis'
  6514. });
  6515. this.axisPanel = new Panel(axisPanelOptions);
  6516. this.mainPanel.appendChild(this.axisPanel);
  6517. // content panel (contains itemset(s))
  6518. var sideContentOptions = util.extend(Object.create(this.options), {
  6519. top: function () {
  6520. return (me.options.orientation == 'top') ? (me.timeAxis.height + 'px') : '';
  6521. },
  6522. bottom: function () {
  6523. return (me.options.orientation == 'top') ? '' : (me.timeAxis.height + 'px');
  6524. },
  6525. left: null,
  6526. right: null,
  6527. height: null,
  6528. width: null,
  6529. className: 'side-content'
  6530. });
  6531. this.sideContentPanel = new Panel(sideContentOptions);
  6532. this.sidePanel.appendChild(this.sideContentPanel);
  6533. // current time bar
  6534. // Note: time bar will be attached in this.setOptions when selected
  6535. this.currentTime = new CurrentTime(this.range, rootOptions);
  6536. // custom time bar
  6537. // Note: time bar will be attached in this.setOptions when selected
  6538. this.customTime = new CustomTime(rootOptions);
  6539. this.customTime.on('timechange', function (time) {
  6540. me.emit('timechange', time);
  6541. });
  6542. this.customTime.on('timechanged', function (time) {
  6543. me.emit('timechanged', time);
  6544. });
  6545. // itemset containing items and groups
  6546. var itemOptions = util.extend(Object.create(this.options), {
  6547. left: null,
  6548. right: null,
  6549. top: null,
  6550. bottom: null,
  6551. width: null,
  6552. height: null
  6553. });
  6554. this.itemSet = new ItemSet(this.backgroundPanel, this.axisPanel, this.sideContentPanel, itemOptions);
  6555. this.itemSet.setRange(this.range);
  6556. this.itemSet.on('change', me.rootPanel.repaint.bind(me.rootPanel));
  6557. this.contentPanel.appendChild(this.itemSet);
  6558. this.itemsData = null; // DataSet
  6559. this.groupsData = null; // DataSet
  6560. // apply options
  6561. if (options) {
  6562. this.setOptions(options);
  6563. }
  6564. // create itemset
  6565. if (items) {
  6566. this.setItems(items);
  6567. }
  6568. }
  6569. // turn Timeline into an event emitter
  6570. Emitter(Timeline.prototype);
  6571. /**
  6572. * Set options
  6573. * @param {Object} options TODO: describe the available options
  6574. */
  6575. Timeline.prototype.setOptions = function (options) {
  6576. util.deepExtend(this.options, options);
  6577. if ('editable' in options) {
  6578. var isBoolean = typeof options.editable === 'boolean';
  6579. this.options.editable = {
  6580. updateTime: isBoolean ? options.editable : (options.editable.updateTime || false),
  6581. updateGroup: isBoolean ? options.editable : (options.editable.updateGroup || false),
  6582. add: isBoolean ? options.editable : (options.editable.add || false),
  6583. remove: isBoolean ? options.editable : (options.editable.remove || false)
  6584. };
  6585. }
  6586. // force update of range (apply new min/max etc.)
  6587. // both start and end are optional
  6588. this.range.setRange(options.start, options.end);
  6589. if ('editable' in options || 'selectable' in options) {
  6590. if (this.options.selectable) {
  6591. // force update of selection
  6592. this.setSelection(this.getSelection());
  6593. }
  6594. else {
  6595. // remove selection
  6596. this.setSelection([]);
  6597. }
  6598. }
  6599. // force the itemSet to refresh: options like orientation and margins may be changed
  6600. this.itemSet.markDirty();
  6601. // validate the callback functions
  6602. var validateCallback = (function (fn) {
  6603. if (!(this.options[fn] instanceof Function) || this.options[fn].length != 2) {
  6604. throw new Error('option ' + fn + ' must be a function ' + fn + '(item, callback)');
  6605. }
  6606. }).bind(this);
  6607. ['onAdd', 'onUpdate', 'onRemove', 'onMove'].forEach(validateCallback);
  6608. // add/remove the current time bar
  6609. if (this.options.showCurrentTime) {
  6610. if (!this.mainPanel.hasChild(this.currentTime)) {
  6611. this.mainPanel.appendChild(this.currentTime);
  6612. this.currentTime.start();
  6613. }
  6614. }
  6615. else {
  6616. if (this.mainPanel.hasChild(this.currentTime)) {
  6617. this.currentTime.stop();
  6618. this.mainPanel.removeChild(this.currentTime);
  6619. }
  6620. }
  6621. // add/remove the custom time bar
  6622. if (this.options.showCustomTime) {
  6623. if (!this.mainPanel.hasChild(this.customTime)) {
  6624. this.mainPanel.appendChild(this.customTime);
  6625. }
  6626. }
  6627. else {
  6628. if (this.mainPanel.hasChild(this.customTime)) {
  6629. this.mainPanel.removeChild(this.customTime);
  6630. }
  6631. }
  6632. // TODO: remove deprecation error one day (deprecated since version 0.8.0)
  6633. if (options && options.order) {
  6634. throw new Error('Option order is deprecated. There is no replacement for this feature.');
  6635. }
  6636. // repaint everything
  6637. this.rootPanel.repaint();
  6638. };
  6639. /**
  6640. * Set a custom time bar
  6641. * @param {Date} time
  6642. */
  6643. Timeline.prototype.setCustomTime = function (time) {
  6644. if (!this.customTime) {
  6645. throw new Error('Cannot get custom time: Custom time bar is not enabled');
  6646. }
  6647. this.customTime.setCustomTime(time);
  6648. };
  6649. /**
  6650. * Retrieve the current custom time.
  6651. * @return {Date} customTime
  6652. */
  6653. Timeline.prototype.getCustomTime = function() {
  6654. if (!this.customTime) {
  6655. throw new Error('Cannot get custom time: Custom time bar is not enabled');
  6656. }
  6657. return this.customTime.getCustomTime();
  6658. };
  6659. /**
  6660. * Set items
  6661. * @param {vis.DataSet | Array | google.visualization.DataTable | null} items
  6662. */
  6663. Timeline.prototype.setItems = function(items) {
  6664. var initialLoad = (this.itemsData == null);
  6665. // convert to type DataSet when needed
  6666. var newDataSet;
  6667. if (!items) {
  6668. newDataSet = null;
  6669. }
  6670. else if (items instanceof DataSet || items instanceof DataView) {
  6671. newDataSet = items;
  6672. }
  6673. else {
  6674. // turn an array into a dataset
  6675. newDataSet = new DataSet(items, {
  6676. convert: {
  6677. start: 'Date',
  6678. end: 'Date'
  6679. }
  6680. });
  6681. }
  6682. // set items
  6683. this.itemsData = newDataSet;
  6684. this.itemSet.setItems(newDataSet);
  6685. if (initialLoad && (this.options.start == undefined || this.options.end == undefined)) {
  6686. this.fit();
  6687. var start = (this.options.start != undefined) ? util.convert(this.options.start, 'Date') : null;
  6688. var end = (this.options.end != undefined) ? util.convert(this.options.end, 'Date') : null;
  6689. this.setWindow(start, end);
  6690. }
  6691. };
  6692. /**
  6693. * Set groups
  6694. * @param {vis.DataSet | Array | google.visualization.DataTable} groups
  6695. */
  6696. Timeline.prototype.setGroups = function setGroups(groups) {
  6697. // convert to type DataSet when needed
  6698. var newDataSet;
  6699. if (!groups) {
  6700. newDataSet = null;
  6701. }
  6702. else if (groups instanceof DataSet || groups instanceof DataView) {
  6703. newDataSet = groups;
  6704. }
  6705. else {
  6706. // turn an array into a dataset
  6707. newDataSet = new DataSet(groups);
  6708. }
  6709. this.groupsData = newDataSet;
  6710. this.itemSet.setGroups(newDataSet);
  6711. };
  6712. /**
  6713. * Clear the Timeline. By Default, items, groups and options are cleared.
  6714. * Example usage:
  6715. *
  6716. * timeline.clear(); // clear items, groups, and options
  6717. * timeline.clear({options: true}); // clear options only
  6718. *
  6719. * @param {Object} [what] Optionally specify what to clear. By default:
  6720. * {items: true, groups: true, options: true}
  6721. */
  6722. Timeline.prototype.clear = function clear(what) {
  6723. // clear items
  6724. if (!what || what.items) {
  6725. this.setItems(null);
  6726. }
  6727. // clear groups
  6728. if (!what || what.groups) {
  6729. this.setGroups(null);
  6730. }
  6731. // clear options
  6732. if (!what || what.options) {
  6733. this.setOptions(this.defaultOptions);
  6734. }
  6735. };
  6736. /**
  6737. * Set Timeline window such that it fits all items
  6738. */
  6739. Timeline.prototype.fit = function fit() {
  6740. // apply the data range as range
  6741. var dataRange = this.getItemRange();
  6742. // add 5% space on both sides
  6743. var start = dataRange.min;
  6744. var end = dataRange.max;
  6745. if (start != null && end != null) {
  6746. var interval = (end.valueOf() - start.valueOf());
  6747. if (interval <= 0) {
  6748. // prevent an empty interval
  6749. interval = 24 * 60 * 60 * 1000; // 1 day
  6750. }
  6751. start = new Date(start.valueOf() - interval * 0.05);
  6752. end = new Date(end.valueOf() + interval * 0.05);
  6753. }
  6754. // skip range set if there is no start and end date
  6755. if (start === null && end === null) {
  6756. return;
  6757. }
  6758. this.range.setRange(start, end);
  6759. };
  6760. /**
  6761. * Get the data range of the item set.
  6762. * @returns {{min: Date, max: Date}} range A range with a start and end Date.
  6763. * When no minimum is found, min==null
  6764. * When no maximum is found, max==null
  6765. */
  6766. Timeline.prototype.getItemRange = function getItemRange() {
  6767. // calculate min from start filed
  6768. var itemsData = this.itemsData,
  6769. min = null,
  6770. max = null;
  6771. if (itemsData) {
  6772. // calculate the minimum value of the field 'start'
  6773. var minItem = itemsData.min('start');
  6774. min = minItem ? minItem.start.valueOf() : null;
  6775. // calculate maximum value of fields 'start' and 'end'
  6776. var maxStartItem = itemsData.max('start');
  6777. if (maxStartItem) {
  6778. max = maxStartItem.start.valueOf();
  6779. }
  6780. var maxEndItem = itemsData.max('end');
  6781. if (maxEndItem) {
  6782. if (max == null) {
  6783. max = maxEndItem.end.valueOf();
  6784. }
  6785. else {
  6786. max = Math.max(max, maxEndItem.end.valueOf());
  6787. }
  6788. }
  6789. }
  6790. return {
  6791. min: (min != null) ? new Date(min) : null,
  6792. max: (max != null) ? new Date(max) : null
  6793. };
  6794. };
  6795. /**
  6796. * Set selected items by their id. Replaces the current selection
  6797. * Unknown id's are silently ignored.
  6798. * @param {Array} [ids] An array with zero or more id's of the items to be
  6799. * selected. If ids is an empty array, all items will be
  6800. * unselected.
  6801. */
  6802. Timeline.prototype.setSelection = function setSelection (ids) {
  6803. this.itemSet.setSelection(ids);
  6804. };
  6805. /**
  6806. * Get the selected items by their id
  6807. * @return {Array} ids The ids of the selected items
  6808. */
  6809. Timeline.prototype.getSelection = function getSelection() {
  6810. return this.itemSet.getSelection();
  6811. };
  6812. /**
  6813. * Set the visible window. Both parameters are optional, you can change only
  6814. * start or only end. Syntax:
  6815. *
  6816. * TimeLine.setWindow(start, end)
  6817. * TimeLine.setWindow(range)
  6818. *
  6819. * Where start and end can be a Date, number, or string, and range is an
  6820. * object with properties start and end.
  6821. *
  6822. * @param {Date | Number | String | Object} [start] Start date of visible window
  6823. * @param {Date | Number | String} [end] End date of visible window
  6824. */
  6825. Timeline.prototype.setWindow = function setWindow(start, end) {
  6826. if (arguments.length == 1) {
  6827. var range = arguments[0];
  6828. this.range.setRange(range.start, range.end);
  6829. }
  6830. else {
  6831. this.range.setRange(start, end);
  6832. }
  6833. };
  6834. /**
  6835. * Get the visible window
  6836. * @return {{start: Date, end: Date}} Visible range
  6837. */
  6838. Timeline.prototype.getWindow = function setWindow() {
  6839. var range = this.range.getRange();
  6840. return {
  6841. start: new Date(range.start),
  6842. end: new Date(range.end)
  6843. };
  6844. };
  6845. /**
  6846. * Force a repaint of the Timeline. Can be useful to manually repaint when
  6847. * option autoResize=false
  6848. */
  6849. Timeline.prototype.repaint = function repaint() {
  6850. this.rootPanel.repaint();
  6851. };
  6852. /**
  6853. * Handle selecting/deselecting an item when tapping it
  6854. * @param {Event} event
  6855. * @private
  6856. */
  6857. // TODO: move this function to ItemSet
  6858. Timeline.prototype._onSelectItem = function (event) {
  6859. if (!this.options.selectable) return;
  6860. var ctrlKey = event.gesture.srcEvent && event.gesture.srcEvent.ctrlKey;
  6861. var shiftKey = event.gesture.srcEvent && event.gesture.srcEvent.shiftKey;
  6862. if (ctrlKey || shiftKey) {
  6863. this._onMultiSelectItem(event);
  6864. return;
  6865. }
  6866. var oldSelection = this.getSelection();
  6867. var item = ItemSet.itemFromTarget(event);
  6868. var selection = item ? [item.id] : [];
  6869. this.setSelection(selection);
  6870. var newSelection = this.getSelection();
  6871. // if selection is changed, emit a select event
  6872. if (!util.equalArray(oldSelection, newSelection)) {
  6873. this.emit('select', {
  6874. items: this.getSelection()
  6875. });
  6876. }
  6877. event.stopPropagation();
  6878. };
  6879. /**
  6880. * Handle creation and updates of an item on double tap
  6881. * @param event
  6882. * @private
  6883. */
  6884. Timeline.prototype._onAddItem = function (event) {
  6885. if (!this.options.selectable) return;
  6886. if (!this.options.editable.add) return;
  6887. var me = this,
  6888. item = ItemSet.itemFromTarget(event);
  6889. if (item) {
  6890. // update item
  6891. // execute async handler to update the item (or cancel it)
  6892. var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset
  6893. this.options.onUpdate(itemData, function (itemData) {
  6894. if (itemData) {
  6895. me.itemsData.update(itemData);
  6896. }
  6897. });
  6898. }
  6899. else {
  6900. // add item
  6901. var xAbs = vis.util.getAbsoluteLeft(this.contentPanel.frame);
  6902. var x = event.gesture.center.pageX - xAbs;
  6903. var newItem = {
  6904. start: this.timeAxis.snap(this._toTime(x)),
  6905. content: 'new item'
  6906. };
  6907. // when default type is a range, add a default end date to the new item
  6908. if (this.options.type === 'range' || this.options.type == 'rangeoverflow') {
  6909. newItem.end = this.timeAxis.snap(this._toTime(x + this.rootPanel.width / 5));
  6910. }
  6911. var id = util.randomUUID();
  6912. newItem[this.itemsData.fieldId] = id;
  6913. var group = ItemSet.groupFromTarget(event);
  6914. if (group) {
  6915. newItem.group = group.groupId;
  6916. }
  6917. // execute async handler to customize (or cancel) adding an item
  6918. this.options.onAdd(newItem, function (item) {
  6919. if (item) {
  6920. me.itemsData.add(newItem);
  6921. // TODO: need to trigger a repaint?
  6922. }
  6923. });
  6924. }
  6925. };
  6926. /**
  6927. * Handle selecting/deselecting multiple items when holding an item
  6928. * @param {Event} event
  6929. * @private
  6930. */
  6931. // TODO: move this function to ItemSet
  6932. Timeline.prototype._onMultiSelectItem = function (event) {
  6933. if (!this.options.selectable) return;
  6934. var selection,
  6935. item = ItemSet.itemFromTarget(event);
  6936. if (item) {
  6937. // multi select items
  6938. selection = this.getSelection(); // current selection
  6939. var index = selection.indexOf(item.id);
  6940. if (index == -1) {
  6941. // item is not yet selected -> select it
  6942. selection.push(item.id);
  6943. }
  6944. else {
  6945. // item is already selected -> deselect it
  6946. selection.splice(index, 1);
  6947. }
  6948. this.setSelection(selection);
  6949. this.emit('select', {
  6950. items: this.getSelection()
  6951. });
  6952. event.stopPropagation();
  6953. }
  6954. };
  6955. /**
  6956. * Convert a position on screen (pixels) to a datetime
  6957. * @param {int} x Position on the screen in pixels
  6958. * @return {Date} time The datetime the corresponds with given position x
  6959. * @private
  6960. */
  6961. Timeline.prototype._toTime = function _toTime(x) {
  6962. var conversion = this.range.conversion(this.mainPanel.width);
  6963. return new Date(x / conversion.scale + conversion.offset);
  6964. };
  6965. /**
  6966. * Convert a datetime (Date object) into a position on the screen
  6967. * @param {Date} time A date
  6968. * @return {int} x The position on the screen in pixels which corresponds
  6969. * with the given date.
  6970. * @private
  6971. */
  6972. Timeline.prototype._toScreen = function _toScreen(time) {
  6973. var conversion = this.range.conversion(this.mainPanel.width);
  6974. return (time.valueOf() - conversion.offset) * conversion.scale;
  6975. };
  6976. (function(exports) {
  6977. /**
  6978. * Parse a text source containing data in DOT language into a JSON object.
  6979. * The object contains two lists: one with nodes and one with edges.
  6980. *
  6981. * DOT language reference: http://www.graphviz.org/doc/info/lang.html
  6982. *
  6983. * @param {String} data Text containing a graph in DOT-notation
  6984. * @return {Object} graph An object containing two parameters:
  6985. * {Object[]} nodes
  6986. * {Object[]} edges
  6987. */
  6988. function parseDOT (data) {
  6989. dot = data;
  6990. return parseGraph();
  6991. }
  6992. // token types enumeration
  6993. var TOKENTYPE = {
  6994. NULL : 0,
  6995. DELIMITER : 1,
  6996. IDENTIFIER: 2,
  6997. UNKNOWN : 3
  6998. };
  6999. // map with all delimiters
  7000. var DELIMITERS = {
  7001. '{': true,
  7002. '}': true,
  7003. '[': true,
  7004. ']': true,
  7005. ';': true,
  7006. '=': true,
  7007. ',': true,
  7008. '->': true,
  7009. '--': true
  7010. };
  7011. var dot = ''; // current dot file
  7012. var index = 0; // current index in dot file
  7013. var c = ''; // current token character in expr
  7014. var token = ''; // current token
  7015. var tokenType = TOKENTYPE.NULL; // type of the token
  7016. /**
  7017. * Get the first character from the dot file.
  7018. * The character is stored into the char c. If the end of the dot file is
  7019. * reached, the function puts an empty string in c.
  7020. */
  7021. function first() {
  7022. index = 0;
  7023. c = dot.charAt(0);
  7024. }
  7025. /**
  7026. * Get the next character from the dot file.
  7027. * The character is stored into the char c. If the end of the dot file is
  7028. * reached, the function puts an empty string in c.
  7029. */
  7030. function next() {
  7031. index++;
  7032. c = dot.charAt(index);
  7033. }
  7034. /**
  7035. * Preview the next character from the dot file.
  7036. * @return {String} cNext
  7037. */
  7038. function nextPreview() {
  7039. return dot.charAt(index + 1);
  7040. }
  7041. /**
  7042. * Test whether given character is alphabetic or numeric
  7043. * @param {String} c
  7044. * @return {Boolean} isAlphaNumeric
  7045. */
  7046. var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/;
  7047. function isAlphaNumeric(c) {
  7048. return regexAlphaNumeric.test(c);
  7049. }
  7050. /**
  7051. * Merge all properties of object b into object b
  7052. * @param {Object} a
  7053. * @param {Object} b
  7054. * @return {Object} a
  7055. */
  7056. function merge (a, b) {
  7057. if (!a) {
  7058. a = {};
  7059. }
  7060. if (b) {
  7061. for (var name in b) {
  7062. if (b.hasOwnProperty(name)) {
  7063. a[name] = b[name];
  7064. }
  7065. }
  7066. }
  7067. return a;
  7068. }
  7069. /**
  7070. * Set a value in an object, where the provided parameter name can be a
  7071. * path with nested parameters. For example:
  7072. *
  7073. * var obj = {a: 2};
  7074. * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}}
  7075. *
  7076. * @param {Object} obj
  7077. * @param {String} path A parameter name or dot-separated parameter path,
  7078. * like "color.highlight.border".
  7079. * @param {*} value
  7080. */
  7081. function setValue(obj, path, value) {
  7082. var keys = path.split('.');
  7083. var o = obj;
  7084. while (keys.length) {
  7085. var key = keys.shift();
  7086. if (keys.length) {
  7087. // this isn't the end point
  7088. if (!o[key]) {
  7089. o[key] = {};
  7090. }
  7091. o = o[key];
  7092. }
  7093. else {
  7094. // this is the end point
  7095. o[key] = value;
  7096. }
  7097. }
  7098. }
  7099. /**
  7100. * Add a node to a graph object. If there is already a node with
  7101. * the same id, their attributes will be merged.
  7102. * @param {Object} graph
  7103. * @param {Object} node
  7104. */
  7105. function addNode(graph, node) {
  7106. var i, len;
  7107. var current = null;
  7108. // find root graph (in case of subgraph)
  7109. var graphs = [graph]; // list with all graphs from current graph to root graph
  7110. var root = graph;
  7111. while (root.parent) {
  7112. graphs.push(root.parent);
  7113. root = root.parent;
  7114. }
  7115. // find existing node (at root level) by its id
  7116. if (root.nodes) {
  7117. for (i = 0, len = root.nodes.length; i < len; i++) {
  7118. if (node.id === root.nodes[i].id) {
  7119. current = root.nodes[i];
  7120. break;
  7121. }
  7122. }
  7123. }
  7124. if (!current) {
  7125. // this is a new node
  7126. current = {
  7127. id: node.id
  7128. };
  7129. if (graph.node) {
  7130. // clone default attributes
  7131. current.attr = merge(current.attr, graph.node);
  7132. }
  7133. }
  7134. // add node to this (sub)graph and all its parent graphs
  7135. for (i = graphs.length - 1; i >= 0; i--) {
  7136. var g = graphs[i];
  7137. if (!g.nodes) {
  7138. g.nodes = [];
  7139. }
  7140. if (g.nodes.indexOf(current) == -1) {
  7141. g.nodes.push(current);
  7142. }
  7143. }
  7144. // merge attributes
  7145. if (node.attr) {
  7146. current.attr = merge(current.attr, node.attr);
  7147. }
  7148. }
  7149. /**
  7150. * Add an edge to a graph object
  7151. * @param {Object} graph
  7152. * @param {Object} edge
  7153. */
  7154. function addEdge(graph, edge) {
  7155. if (!graph.edges) {
  7156. graph.edges = [];
  7157. }
  7158. graph.edges.push(edge);
  7159. if (graph.edge) {
  7160. var attr = merge({}, graph.edge); // clone default attributes
  7161. edge.attr = merge(attr, edge.attr); // merge attributes
  7162. }
  7163. }
  7164. /**
  7165. * Create an edge to a graph object
  7166. * @param {Object} graph
  7167. * @param {String | Number | Object} from
  7168. * @param {String | Number | Object} to
  7169. * @param {String} type
  7170. * @param {Object | null} attr
  7171. * @return {Object} edge
  7172. */
  7173. function createEdge(graph, from, to, type, attr) {
  7174. var edge = {
  7175. from: from,
  7176. to: to,
  7177. type: type
  7178. };
  7179. if (graph.edge) {
  7180. edge.attr = merge({}, graph.edge); // clone default attributes
  7181. }
  7182. edge.attr = merge(edge.attr || {}, attr); // merge attributes
  7183. return edge;
  7184. }
  7185. /**
  7186. * Get next token in the current dot file.
  7187. * The token and token type are available as token and tokenType
  7188. */
  7189. function getToken() {
  7190. tokenType = TOKENTYPE.NULL;
  7191. token = '';
  7192. // skip over whitespaces
  7193. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  7194. next();
  7195. }
  7196. do {
  7197. var isComment = false;
  7198. // skip comment
  7199. if (c == '#') {
  7200. // find the previous non-space character
  7201. var i = index - 1;
  7202. while (dot.charAt(i) == ' ' || dot.charAt(i) == '\t') {
  7203. i--;
  7204. }
  7205. if (dot.charAt(i) == '\n' || dot.charAt(i) == '') {
  7206. // the # is at the start of a line, this is indeed a line comment
  7207. while (c != '' && c != '\n') {
  7208. next();
  7209. }
  7210. isComment = true;
  7211. }
  7212. }
  7213. if (c == '/' && nextPreview() == '/') {
  7214. // skip line comment
  7215. while (c != '' && c != '\n') {
  7216. next();
  7217. }
  7218. isComment = true;
  7219. }
  7220. if (c == '/' && nextPreview() == '*') {
  7221. // skip block comment
  7222. while (c != '') {
  7223. if (c == '*' && nextPreview() == '/') {
  7224. // end of block comment found. skip these last two characters
  7225. next();
  7226. next();
  7227. break;
  7228. }
  7229. else {
  7230. next();
  7231. }
  7232. }
  7233. isComment = true;
  7234. }
  7235. // skip over whitespaces
  7236. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  7237. next();
  7238. }
  7239. }
  7240. while (isComment);
  7241. // check for end of dot file
  7242. if (c == '') {
  7243. // token is still empty
  7244. tokenType = TOKENTYPE.DELIMITER;
  7245. return;
  7246. }
  7247. // check for delimiters consisting of 2 characters
  7248. var c2 = c + nextPreview();
  7249. if (DELIMITERS[c2]) {
  7250. tokenType = TOKENTYPE.DELIMITER;
  7251. token = c2;
  7252. next();
  7253. next();
  7254. return;
  7255. }
  7256. // check for delimiters consisting of 1 character
  7257. if (DELIMITERS[c]) {
  7258. tokenType = TOKENTYPE.DELIMITER;
  7259. token = c;
  7260. next();
  7261. return;
  7262. }
  7263. // check for an identifier (number or string)
  7264. // TODO: more precise parsing of numbers/strings (and the port separator ':')
  7265. if (isAlphaNumeric(c) || c == '-') {
  7266. token += c;
  7267. next();
  7268. while (isAlphaNumeric(c)) {
  7269. token += c;
  7270. next();
  7271. }
  7272. if (token == 'false') {
  7273. token = false; // convert to boolean
  7274. }
  7275. else if (token == 'true') {
  7276. token = true; // convert to boolean
  7277. }
  7278. else if (!isNaN(Number(token))) {
  7279. token = Number(token); // convert to number
  7280. }
  7281. tokenType = TOKENTYPE.IDENTIFIER;
  7282. return;
  7283. }
  7284. // check for a string enclosed by double quotes
  7285. if (c == '"') {
  7286. next();
  7287. while (c != '' && (c != '"' || (c == '"' && nextPreview() == '"'))) {
  7288. token += c;
  7289. if (c == '"') { // skip the escape character
  7290. next();
  7291. }
  7292. next();
  7293. }
  7294. if (c != '"') {
  7295. throw newSyntaxError('End of string " expected');
  7296. }
  7297. next();
  7298. tokenType = TOKENTYPE.IDENTIFIER;
  7299. return;
  7300. }
  7301. // something unknown is found, wrong characters, a syntax error
  7302. tokenType = TOKENTYPE.UNKNOWN;
  7303. while (c != '') {
  7304. token += c;
  7305. next();
  7306. }
  7307. throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"');
  7308. }
  7309. /**
  7310. * Parse a graph.
  7311. * @returns {Object} graph
  7312. */
  7313. function parseGraph() {
  7314. var graph = {};
  7315. first();
  7316. getToken();
  7317. // optional strict keyword
  7318. if (token == 'strict') {
  7319. graph.strict = true;
  7320. getToken();
  7321. }
  7322. // graph or digraph keyword
  7323. if (token == 'graph' || token == 'digraph') {
  7324. graph.type = token;
  7325. getToken();
  7326. }
  7327. // optional graph id
  7328. if (tokenType == TOKENTYPE.IDENTIFIER) {
  7329. graph.id = token;
  7330. getToken();
  7331. }
  7332. // open angle bracket
  7333. if (token != '{') {
  7334. throw newSyntaxError('Angle bracket { expected');
  7335. }
  7336. getToken();
  7337. // statements
  7338. parseStatements(graph);
  7339. // close angle bracket
  7340. if (token != '}') {
  7341. throw newSyntaxError('Angle bracket } expected');
  7342. }
  7343. getToken();
  7344. // end of file
  7345. if (token !== '') {
  7346. throw newSyntaxError('End of file expected');
  7347. }
  7348. getToken();
  7349. // remove temporary default properties
  7350. delete graph.node;
  7351. delete graph.edge;
  7352. delete graph.graph;
  7353. return graph;
  7354. }
  7355. /**
  7356. * Parse a list with statements.
  7357. * @param {Object} graph
  7358. */
  7359. function parseStatements (graph) {
  7360. while (token !== '' && token != '}') {
  7361. parseStatement(graph);
  7362. if (token == ';') {
  7363. getToken();
  7364. }
  7365. }
  7366. }
  7367. /**
  7368. * Parse a single statement. Can be a an attribute statement, node
  7369. * statement, a series of node statements and edge statements, or a
  7370. * parameter.
  7371. * @param {Object} graph
  7372. */
  7373. function parseStatement(graph) {
  7374. // parse subgraph
  7375. var subgraph = parseSubgraph(graph);
  7376. if (subgraph) {
  7377. // edge statements
  7378. parseEdge(graph, subgraph);
  7379. return;
  7380. }
  7381. // parse an attribute statement
  7382. var attr = parseAttributeStatement(graph);
  7383. if (attr) {
  7384. return;
  7385. }
  7386. // parse node
  7387. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7388. throw newSyntaxError('Identifier expected');
  7389. }
  7390. var id = token; // id can be a string or a number
  7391. getToken();
  7392. if (token == '=') {
  7393. // id statement
  7394. getToken();
  7395. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7396. throw newSyntaxError('Identifier expected');
  7397. }
  7398. graph[id] = token;
  7399. getToken();
  7400. // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] "
  7401. }
  7402. else {
  7403. parseNodeStatement(graph, id);
  7404. }
  7405. }
  7406. /**
  7407. * Parse a subgraph
  7408. * @param {Object} graph parent graph object
  7409. * @return {Object | null} subgraph
  7410. */
  7411. function parseSubgraph (graph) {
  7412. var subgraph = null;
  7413. // optional subgraph keyword
  7414. if (token == 'subgraph') {
  7415. subgraph = {};
  7416. subgraph.type = 'subgraph';
  7417. getToken();
  7418. // optional graph id
  7419. if (tokenType == TOKENTYPE.IDENTIFIER) {
  7420. subgraph.id = token;
  7421. getToken();
  7422. }
  7423. }
  7424. // open angle bracket
  7425. if (token == '{') {
  7426. getToken();
  7427. if (!subgraph) {
  7428. subgraph = {};
  7429. }
  7430. subgraph.parent = graph;
  7431. subgraph.node = graph.node;
  7432. subgraph.edge = graph.edge;
  7433. subgraph.graph = graph.graph;
  7434. // statements
  7435. parseStatements(subgraph);
  7436. // close angle bracket
  7437. if (token != '}') {
  7438. throw newSyntaxError('Angle bracket } expected');
  7439. }
  7440. getToken();
  7441. // remove temporary default properties
  7442. delete subgraph.node;
  7443. delete subgraph.edge;
  7444. delete subgraph.graph;
  7445. delete subgraph.parent;
  7446. // register at the parent graph
  7447. if (!graph.subgraphs) {
  7448. graph.subgraphs = [];
  7449. }
  7450. graph.subgraphs.push(subgraph);
  7451. }
  7452. return subgraph;
  7453. }
  7454. /**
  7455. * parse an attribute statement like "node [shape=circle fontSize=16]".
  7456. * Available keywords are 'node', 'edge', 'graph'.
  7457. * The previous list with default attributes will be replaced
  7458. * @param {Object} graph
  7459. * @returns {String | null} keyword Returns the name of the parsed attribute
  7460. * (node, edge, graph), or null if nothing
  7461. * is parsed.
  7462. */
  7463. function parseAttributeStatement (graph) {
  7464. // attribute statements
  7465. if (token == 'node') {
  7466. getToken();
  7467. // node attributes
  7468. graph.node = parseAttributeList();
  7469. return 'node';
  7470. }
  7471. else if (token == 'edge') {
  7472. getToken();
  7473. // edge attributes
  7474. graph.edge = parseAttributeList();
  7475. return 'edge';
  7476. }
  7477. else if (token == 'graph') {
  7478. getToken();
  7479. // graph attributes
  7480. graph.graph = parseAttributeList();
  7481. return 'graph';
  7482. }
  7483. return null;
  7484. }
  7485. /**
  7486. * parse a node statement
  7487. * @param {Object} graph
  7488. * @param {String | Number} id
  7489. */
  7490. function parseNodeStatement(graph, id) {
  7491. // node statement
  7492. var node = {
  7493. id: id
  7494. };
  7495. var attr = parseAttributeList();
  7496. if (attr) {
  7497. node.attr = attr;
  7498. }
  7499. addNode(graph, node);
  7500. // edge statements
  7501. parseEdge(graph, id);
  7502. }
  7503. /**
  7504. * Parse an edge or a series of edges
  7505. * @param {Object} graph
  7506. * @param {String | Number} from Id of the from node
  7507. */
  7508. function parseEdge(graph, from) {
  7509. while (token == '->' || token == '--') {
  7510. var to;
  7511. var type = token;
  7512. getToken();
  7513. var subgraph = parseSubgraph(graph);
  7514. if (subgraph) {
  7515. to = subgraph;
  7516. }
  7517. else {
  7518. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7519. throw newSyntaxError('Identifier or subgraph expected');
  7520. }
  7521. to = token;
  7522. addNode(graph, {
  7523. id: to
  7524. });
  7525. getToken();
  7526. }
  7527. // parse edge attributes
  7528. var attr = parseAttributeList();
  7529. // create edge
  7530. var edge = createEdge(graph, from, to, type, attr);
  7531. addEdge(graph, edge);
  7532. from = to;
  7533. }
  7534. }
  7535. /**
  7536. * Parse a set with attributes,
  7537. * for example [label="1.000", shape=solid]
  7538. * @return {Object | null} attr
  7539. */
  7540. function parseAttributeList() {
  7541. var attr = null;
  7542. while (token == '[') {
  7543. getToken();
  7544. attr = {};
  7545. while (token !== '' && token != ']') {
  7546. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7547. throw newSyntaxError('Attribute name expected');
  7548. }
  7549. var name = token;
  7550. getToken();
  7551. if (token != '=') {
  7552. throw newSyntaxError('Equal sign = expected');
  7553. }
  7554. getToken();
  7555. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7556. throw newSyntaxError('Attribute value expected');
  7557. }
  7558. var value = token;
  7559. setValue(attr, name, value); // name can be a path
  7560. getToken();
  7561. if (token ==',') {
  7562. getToken();
  7563. }
  7564. }
  7565. if (token != ']') {
  7566. throw newSyntaxError('Bracket ] expected');
  7567. }
  7568. getToken();
  7569. }
  7570. return attr;
  7571. }
  7572. /**
  7573. * Create a syntax error with extra information on current token and index.
  7574. * @param {String} message
  7575. * @returns {SyntaxError} err
  7576. */
  7577. function newSyntaxError(message) {
  7578. return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')');
  7579. }
  7580. /**
  7581. * Chop off text after a maximum length
  7582. * @param {String} text
  7583. * @param {Number} maxLength
  7584. * @returns {String}
  7585. */
  7586. function chop (text, maxLength) {
  7587. return (text.length <= maxLength) ? text : (text.substr(0, 27) + '...');
  7588. }
  7589. /**
  7590. * Execute a function fn for each pair of elements in two arrays
  7591. * @param {Array | *} array1
  7592. * @param {Array | *} array2
  7593. * @param {function} fn
  7594. */
  7595. function forEach2(array1, array2, fn) {
  7596. if (array1 instanceof Array) {
  7597. array1.forEach(function (elem1) {
  7598. if (array2 instanceof Array) {
  7599. array2.forEach(function (elem2) {
  7600. fn(elem1, elem2);
  7601. });
  7602. }
  7603. else {
  7604. fn(elem1, array2);
  7605. }
  7606. });
  7607. }
  7608. else {
  7609. if (array2 instanceof Array) {
  7610. array2.forEach(function (elem2) {
  7611. fn(array1, elem2);
  7612. });
  7613. }
  7614. else {
  7615. fn(array1, array2);
  7616. }
  7617. }
  7618. }
  7619. /**
  7620. * Convert a string containing a graph in DOT language into a map containing
  7621. * with nodes and edges in the format of graph.
  7622. * @param {String} data Text containing a graph in DOT-notation
  7623. * @return {Object} graphData
  7624. */
  7625. function DOTToGraph (data) {
  7626. // parse the DOT file
  7627. var dotData = parseDOT(data);
  7628. var graphData = {
  7629. nodes: [],
  7630. edges: [],
  7631. options: {}
  7632. };
  7633. // copy the nodes
  7634. if (dotData.nodes) {
  7635. dotData.nodes.forEach(function (dotNode) {
  7636. var graphNode = {
  7637. id: dotNode.id,
  7638. label: String(dotNode.label || dotNode.id)
  7639. };
  7640. merge(graphNode, dotNode.attr);
  7641. if (graphNode.image) {
  7642. graphNode.shape = 'image';
  7643. }
  7644. graphData.nodes.push(graphNode);
  7645. });
  7646. }
  7647. // copy the edges
  7648. if (dotData.edges) {
  7649. /**
  7650. * Convert an edge in DOT format to an edge with VisGraph format
  7651. * @param {Object} dotEdge
  7652. * @returns {Object} graphEdge
  7653. */
  7654. function convertEdge(dotEdge) {
  7655. var graphEdge = {
  7656. from: dotEdge.from,
  7657. to: dotEdge.to
  7658. };
  7659. merge(graphEdge, dotEdge.attr);
  7660. graphEdge.style = (dotEdge.type == '->') ? 'arrow' : 'line';
  7661. return graphEdge;
  7662. }
  7663. dotData.edges.forEach(function (dotEdge) {
  7664. var from, to;
  7665. if (dotEdge.from instanceof Object) {
  7666. from = dotEdge.from.nodes;
  7667. }
  7668. else {
  7669. from = {
  7670. id: dotEdge.from
  7671. }
  7672. }
  7673. if (dotEdge.to instanceof Object) {
  7674. to = dotEdge.to.nodes;
  7675. }
  7676. else {
  7677. to = {
  7678. id: dotEdge.to
  7679. }
  7680. }
  7681. if (dotEdge.from instanceof Object && dotEdge.from.edges) {
  7682. dotEdge.from.edges.forEach(function (subEdge) {
  7683. var graphEdge = convertEdge(subEdge);
  7684. graphData.edges.push(graphEdge);
  7685. });
  7686. }
  7687. forEach2(from, to, function (from, to) {
  7688. var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr);
  7689. var graphEdge = convertEdge(subEdge);
  7690. graphData.edges.push(graphEdge);
  7691. });
  7692. if (dotEdge.to instanceof Object && dotEdge.to.edges) {
  7693. dotEdge.to.edges.forEach(function (subEdge) {
  7694. var graphEdge = convertEdge(subEdge);
  7695. graphData.edges.push(graphEdge);
  7696. });
  7697. }
  7698. });
  7699. }
  7700. // copy the options
  7701. if (dotData.attr) {
  7702. graphData.options = dotData.attr;
  7703. }
  7704. return graphData;
  7705. }
  7706. // exports
  7707. exports.parseDOT = parseDOT;
  7708. exports.DOTToGraph = DOTToGraph;
  7709. })(typeof util !== 'undefined' ? util : exports);
  7710. /**
  7711. * Canvas shapes used by the Graph
  7712. */
  7713. if (typeof CanvasRenderingContext2D !== 'undefined') {
  7714. /**
  7715. * Draw a circle shape
  7716. */
  7717. CanvasRenderingContext2D.prototype.circle = function(x, y, r) {
  7718. this.beginPath();
  7719. this.arc(x, y, r, 0, 2*Math.PI, false);
  7720. };
  7721. /**
  7722. * Draw a square shape
  7723. * @param {Number} x horizontal center
  7724. * @param {Number} y vertical center
  7725. * @param {Number} r size, width and height of the square
  7726. */
  7727. CanvasRenderingContext2D.prototype.square = function(x, y, r) {
  7728. this.beginPath();
  7729. this.rect(x - r, y - r, r * 2, r * 2);
  7730. };
  7731. /**
  7732. * Draw a triangle shape
  7733. * @param {Number} x horizontal center
  7734. * @param {Number} y vertical center
  7735. * @param {Number} r radius, half the length of the sides of the triangle
  7736. */
  7737. CanvasRenderingContext2D.prototype.triangle = function(x, y, r) {
  7738. // http://en.wikipedia.org/wiki/Equilateral_triangle
  7739. this.beginPath();
  7740. var s = r * 2;
  7741. var s2 = s / 2;
  7742. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  7743. var h = Math.sqrt(s * s - s2 * s2); // height
  7744. this.moveTo(x, y - (h - ir));
  7745. this.lineTo(x + s2, y + ir);
  7746. this.lineTo(x - s2, y + ir);
  7747. this.lineTo(x, y - (h - ir));
  7748. this.closePath();
  7749. };
  7750. /**
  7751. * Draw a triangle shape in downward orientation
  7752. * @param {Number} x horizontal center
  7753. * @param {Number} y vertical center
  7754. * @param {Number} r radius
  7755. */
  7756. CanvasRenderingContext2D.prototype.triangleDown = function(x, y, r) {
  7757. // http://en.wikipedia.org/wiki/Equilateral_triangle
  7758. this.beginPath();
  7759. var s = r * 2;
  7760. var s2 = s / 2;
  7761. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  7762. var h = Math.sqrt(s * s - s2 * s2); // height
  7763. this.moveTo(x, y + (h - ir));
  7764. this.lineTo(x + s2, y - ir);
  7765. this.lineTo(x - s2, y - ir);
  7766. this.lineTo(x, y + (h - ir));
  7767. this.closePath();
  7768. };
  7769. /**
  7770. * Draw a star shape, a star with 5 points
  7771. * @param {Number} x horizontal center
  7772. * @param {Number} y vertical center
  7773. * @param {Number} r radius, half the length of the sides of the triangle
  7774. */
  7775. CanvasRenderingContext2D.prototype.star = function(x, y, r) {
  7776. // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/
  7777. this.beginPath();
  7778. for (var n = 0; n < 10; n++) {
  7779. var radius = (n % 2 === 0) ? r * 1.3 : r * 0.5;
  7780. this.lineTo(
  7781. x + radius * Math.sin(n * 2 * Math.PI / 10),
  7782. y - radius * Math.cos(n * 2 * Math.PI / 10)
  7783. );
  7784. }
  7785. this.closePath();
  7786. };
  7787. /**
  7788. * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas
  7789. */
  7790. CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) {
  7791. var r2d = Math.PI/180;
  7792. if( w - ( 2 * r ) < 0 ) { r = ( w / 2 ); } //ensure that the radius isn't too large for x
  7793. if( h - ( 2 * r ) < 0 ) { r = ( h / 2 ); } //ensure that the radius isn't too large for y
  7794. this.beginPath();
  7795. this.moveTo(x+r,y);
  7796. this.lineTo(x+w-r,y);
  7797. this.arc(x+w-r,y+r,r,r2d*270,r2d*360,false);
  7798. this.lineTo(x+w,y+h-r);
  7799. this.arc(x+w-r,y+h-r,r,0,r2d*90,false);
  7800. this.lineTo(x+r,y+h);
  7801. this.arc(x+r,y+h-r,r,r2d*90,r2d*180,false);
  7802. this.lineTo(x,y+r);
  7803. this.arc(x+r,y+r,r,r2d*180,r2d*270,false);
  7804. };
  7805. /**
  7806. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  7807. */
  7808. CanvasRenderingContext2D.prototype.ellipse = function(x, y, w, h) {
  7809. var kappa = .5522848,
  7810. ox = (w / 2) * kappa, // control point offset horizontal
  7811. oy = (h / 2) * kappa, // control point offset vertical
  7812. xe = x + w, // x-end
  7813. ye = y + h, // y-end
  7814. xm = x + w / 2, // x-middle
  7815. ym = y + h / 2; // y-middle
  7816. this.beginPath();
  7817. this.moveTo(x, ym);
  7818. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  7819. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  7820. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  7821. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  7822. };
  7823. /**
  7824. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  7825. */
  7826. CanvasRenderingContext2D.prototype.database = function(x, y, w, h) {
  7827. var f = 1/3;
  7828. var wEllipse = w;
  7829. var hEllipse = h * f;
  7830. var kappa = .5522848,
  7831. ox = (wEllipse / 2) * kappa, // control point offset horizontal
  7832. oy = (hEllipse / 2) * kappa, // control point offset vertical
  7833. xe = x + wEllipse, // x-end
  7834. ye = y + hEllipse, // y-end
  7835. xm = x + wEllipse / 2, // x-middle
  7836. ym = y + hEllipse / 2, // y-middle
  7837. ymb = y + (h - hEllipse/2), // y-midlle, bottom ellipse
  7838. yeb = y + h; // y-end, bottom ellipse
  7839. this.beginPath();
  7840. this.moveTo(xe, ym);
  7841. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  7842. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  7843. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  7844. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  7845. this.lineTo(xe, ymb);
  7846. this.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb);
  7847. this.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb);
  7848. this.lineTo(x, ym);
  7849. };
  7850. /**
  7851. * Draw an arrow point (no line)
  7852. */
  7853. CanvasRenderingContext2D.prototype.arrow = function(x, y, angle, length) {
  7854. // tail
  7855. var xt = x - length * Math.cos(angle);
  7856. var yt = y - length * Math.sin(angle);
  7857. // inner tail
  7858. // TODO: allow to customize different shapes
  7859. var xi = x - length * 0.9 * Math.cos(angle);
  7860. var yi = y - length * 0.9 * Math.sin(angle);
  7861. // left
  7862. var xl = xt + length / 3 * Math.cos(angle + 0.5 * Math.PI);
  7863. var yl = yt + length / 3 * Math.sin(angle + 0.5 * Math.PI);
  7864. // right
  7865. var xr = xt + length / 3 * Math.cos(angle - 0.5 * Math.PI);
  7866. var yr = yt + length / 3 * Math.sin(angle - 0.5 * Math.PI);
  7867. this.beginPath();
  7868. this.moveTo(x, y);
  7869. this.lineTo(xl, yl);
  7870. this.lineTo(xi, yi);
  7871. this.lineTo(xr, yr);
  7872. this.closePath();
  7873. };
  7874. /**
  7875. * Sets up the dashedLine functionality for drawing
  7876. * Original code came from http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
  7877. * @author David Jordan
  7878. * @date 2012-08-08
  7879. */
  7880. CanvasRenderingContext2D.prototype.dashedLine = function(x,y,x2,y2,dashArray){
  7881. if (!dashArray) dashArray=[10,5];
  7882. if (dashLength==0) dashLength = 0.001; // Hack for Safari
  7883. var dashCount = dashArray.length;
  7884. this.moveTo(x, y);
  7885. var dx = (x2-x), dy = (y2-y);
  7886. var slope = dy/dx;
  7887. var distRemaining = Math.sqrt( dx*dx + dy*dy );
  7888. var dashIndex=0, draw=true;
  7889. while (distRemaining>=0.1){
  7890. var dashLength = dashArray[dashIndex++%dashCount];
  7891. if (dashLength > distRemaining) dashLength = distRemaining;
  7892. var xStep = Math.sqrt( dashLength*dashLength / (1 + slope*slope) );
  7893. if (dx<0) xStep = -xStep;
  7894. x += xStep;
  7895. y += slope*xStep;
  7896. this[draw ? 'lineTo' : 'moveTo'](x,y);
  7897. distRemaining -= dashLength;
  7898. draw = !draw;
  7899. }
  7900. };
  7901. // TODO: add diamond shape
  7902. }
  7903. /**
  7904. * @class Node
  7905. * A node. A node can be connected to other nodes via one or multiple edges.
  7906. * @param {object} properties An object containing properties for the node. All
  7907. * properties are optional, except for the id.
  7908. * {number} id Id of the node. Required
  7909. * {string} label Text label for the node
  7910. * {number} x Horizontal position of the node
  7911. * {number} y Vertical position of the node
  7912. * {string} shape Node shape, available:
  7913. * "database", "circle", "ellipse",
  7914. * "box", "image", "text", "dot",
  7915. * "star", "triangle", "triangleDown",
  7916. * "square"
  7917. * {string} image An image url
  7918. * {string} title An title text, can be HTML
  7919. * {anytype} group A group name or number
  7920. * @param {Graph.Images} imagelist A list with images. Only needed
  7921. * when the node has an image
  7922. * @param {Graph.Groups} grouplist A list with groups. Needed for
  7923. * retrieving group properties
  7924. * @param {Object} constants An object with default values for
  7925. * example for the color
  7926. *
  7927. */
  7928. function Node(properties, imagelist, grouplist, constants) {
  7929. this.selected = false;
  7930. this.edges = []; // all edges connected to this node
  7931. this.dynamicEdges = [];
  7932. this.reroutedEdges = {};
  7933. this.group = constants.nodes.group;
  7934. this.fontSize = constants.nodes.fontSize;
  7935. this.fontFace = constants.nodes.fontFace;
  7936. this.fontColor = constants.nodes.fontColor;
  7937. this.fontDrawThreshold = 3;
  7938. this.color = constants.nodes.color;
  7939. // set defaults for the properties
  7940. this.id = undefined;
  7941. this.shape = constants.nodes.shape;
  7942. this.image = constants.nodes.image;
  7943. this.x = null;
  7944. this.y = null;
  7945. this.xFixed = false;
  7946. this.yFixed = false;
  7947. this.horizontalAlignLeft = true; // these are for the navigation controls
  7948. this.verticalAlignTop = true; // these are for the navigation controls
  7949. this.radius = constants.nodes.radius;
  7950. this.baseRadiusValue = constants.nodes.radius;
  7951. this.radiusFixed = false;
  7952. this.radiusMin = constants.nodes.radiusMin;
  7953. this.radiusMax = constants.nodes.radiusMax;
  7954. this.level = -1;
  7955. this.preassignedLevel = false;
  7956. this.imagelist = imagelist;
  7957. this.grouplist = grouplist;
  7958. // physics properties
  7959. this.fx = 0.0; // external force x
  7960. this.fy = 0.0; // external force y
  7961. this.vx = 0.0; // velocity x
  7962. this.vy = 0.0; // velocity y
  7963. this.minForce = constants.minForce;
  7964. this.damping = constants.physics.damping;
  7965. this.mass = 1; // kg
  7966. this.fixedData = {x:null,y:null};
  7967. this.setProperties(properties, constants);
  7968. // creating the variables for clustering
  7969. this.resetCluster();
  7970. this.dynamicEdgesLength = 0;
  7971. this.clusterSession = 0;
  7972. this.clusterSizeWidthFactor = constants.clustering.nodeScaling.width;
  7973. this.clusterSizeHeightFactor = constants.clustering.nodeScaling.height;
  7974. this.clusterSizeRadiusFactor = constants.clustering.nodeScaling.radius;
  7975. this.maxNodeSizeIncrements = constants.clustering.maxNodeSizeIncrements;
  7976. this.growthIndicator = 0;
  7977. // variables to tell the node about the graph.
  7978. this.graphScaleInv = 1;
  7979. this.graphScale = 1;
  7980. this.canvasTopLeft = {"x": -300, "y": -300};
  7981. this.canvasBottomRight = {"x": 300, "y": 300};
  7982. this.parentEdgeId = null;
  7983. }
  7984. /**
  7985. * (re)setting the clustering variables and objects
  7986. */
  7987. Node.prototype.resetCluster = function() {
  7988. // clustering variables
  7989. this.formationScale = undefined; // this is used to determine when to open the cluster
  7990. this.clusterSize = 1; // this signifies the total amount of nodes in this cluster
  7991. this.containedNodes = {};
  7992. this.containedEdges = {};
  7993. this.clusterSessions = [];
  7994. };
  7995. /**
  7996. * Attach a edge to the node
  7997. * @param {Edge} edge
  7998. */
  7999. Node.prototype.attachEdge = function(edge) {
  8000. if (this.edges.indexOf(edge) == -1) {
  8001. this.edges.push(edge);
  8002. }
  8003. if (this.dynamicEdges.indexOf(edge) == -1) {
  8004. this.dynamicEdges.push(edge);
  8005. }
  8006. this.dynamicEdgesLength = this.dynamicEdges.length;
  8007. };
  8008. /**
  8009. * Detach a edge from the node
  8010. * @param {Edge} edge
  8011. */
  8012. Node.prototype.detachEdge = function(edge) {
  8013. var index = this.edges.indexOf(edge);
  8014. if (index != -1) {
  8015. this.edges.splice(index, 1);
  8016. this.dynamicEdges.splice(index, 1);
  8017. }
  8018. this.dynamicEdgesLength = this.dynamicEdges.length;
  8019. };
  8020. /**
  8021. * Set or overwrite properties for the node
  8022. * @param {Object} properties an object with properties
  8023. * @param {Object} constants and object with default, global properties
  8024. */
  8025. Node.prototype.setProperties = function(properties, constants) {
  8026. if (!properties) {
  8027. return;
  8028. }
  8029. this.originalLabel = undefined;
  8030. // basic properties
  8031. if (properties.id !== undefined) {this.id = properties.id;}
  8032. if (properties.label !== undefined) {this.label = properties.label; this.originalLabel = properties.label;}
  8033. if (properties.title !== undefined) {this.title = properties.title;}
  8034. if (properties.group !== undefined) {this.group = properties.group;}
  8035. if (properties.x !== undefined) {this.x = properties.x;}
  8036. if (properties.y !== undefined) {this.y = properties.y;}
  8037. if (properties.value !== undefined) {this.value = properties.value;}
  8038. if (properties.level !== undefined) {this.level = properties.level; this.preassignedLevel = true;}
  8039. // physics
  8040. if (properties.mass !== undefined) {this.mass = properties.mass;}
  8041. // navigation controls properties
  8042. if (properties.horizontalAlignLeft !== undefined) {this.horizontalAlignLeft = properties.horizontalAlignLeft;}
  8043. if (properties.verticalAlignTop !== undefined) {this.verticalAlignTop = properties.verticalAlignTop;}
  8044. if (properties.triggerFunction !== undefined) {this.triggerFunction = properties.triggerFunction;}
  8045. if (this.id === undefined) {
  8046. throw "Node must have an id";
  8047. }
  8048. // copy group properties
  8049. if (this.group) {
  8050. var groupObj = this.grouplist.get(this.group);
  8051. for (var prop in groupObj) {
  8052. if (groupObj.hasOwnProperty(prop)) {
  8053. this[prop] = groupObj[prop];
  8054. }
  8055. }
  8056. }
  8057. // individual shape properties
  8058. if (properties.shape !== undefined) {this.shape = properties.shape;}
  8059. if (properties.image !== undefined) {this.image = properties.image;}
  8060. if (properties.radius !== undefined) {this.radius = properties.radius;}
  8061. if (properties.color !== undefined) {this.color = util.parseColor(properties.color);}
  8062. if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;}
  8063. if (properties.fontSize !== undefined) {this.fontSize = properties.fontSize;}
  8064. if (properties.fontFace !== undefined) {this.fontFace = properties.fontFace;}
  8065. if (this.image !== undefined && this.image != "") {
  8066. if (this.imagelist) {
  8067. this.imageObj = this.imagelist.load(this.image);
  8068. }
  8069. else {
  8070. throw "No imagelist provided";
  8071. }
  8072. }
  8073. this.xFixed = this.xFixed || (properties.x !== undefined && !properties.allowedToMoveX);
  8074. this.yFixed = this.yFixed || (properties.y !== undefined && !properties.allowedToMoveY);
  8075. this.radiusFixed = this.radiusFixed || (properties.radius !== undefined);
  8076. if (this.shape == 'image') {
  8077. this.radiusMin = constants.nodes.widthMin;
  8078. this.radiusMax = constants.nodes.widthMax;
  8079. }
  8080. // choose draw method depending on the shape
  8081. switch (this.shape) {
  8082. case 'database': this.draw = this._drawDatabase; this.resize = this._resizeDatabase; break;
  8083. case 'box': this.draw = this._drawBox; this.resize = this._resizeBox; break;
  8084. case 'circle': this.draw = this._drawCircle; this.resize = this._resizeCircle; break;
  8085. case 'ellipse': this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  8086. // TODO: add diamond shape
  8087. case 'image': this.draw = this._drawImage; this.resize = this._resizeImage; break;
  8088. case 'text': this.draw = this._drawText; this.resize = this._resizeText; break;
  8089. case 'dot': this.draw = this._drawDot; this.resize = this._resizeShape; break;
  8090. case 'square': this.draw = this._drawSquare; this.resize = this._resizeShape; break;
  8091. case 'triangle': this.draw = this._drawTriangle; this.resize = this._resizeShape; break;
  8092. case 'triangleDown': this.draw = this._drawTriangleDown; this.resize = this._resizeShape; break;
  8093. case 'star': this.draw = this._drawStar; this.resize = this._resizeShape; break;
  8094. default: this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  8095. }
  8096. // reset the size of the node, this can be changed
  8097. this._reset();
  8098. };
  8099. /**
  8100. * select this node
  8101. */
  8102. Node.prototype.select = function() {
  8103. this.selected = true;
  8104. this._reset();
  8105. };
  8106. /**
  8107. * unselect this node
  8108. */
  8109. Node.prototype.unselect = function() {
  8110. this.selected = false;
  8111. this._reset();
  8112. };
  8113. /**
  8114. * Reset the calculated size of the node, forces it to recalculate its size
  8115. */
  8116. Node.prototype.clearSizeCache = function() {
  8117. this._reset();
  8118. };
  8119. /**
  8120. * Reset the calculated size of the node, forces it to recalculate its size
  8121. * @private
  8122. */
  8123. Node.prototype._reset = function() {
  8124. this.width = undefined;
  8125. this.height = undefined;
  8126. };
  8127. /**
  8128. * get the title of this node.
  8129. * @return {string} title The title of the node, or undefined when no title
  8130. * has been set.
  8131. */
  8132. Node.prototype.getTitle = function() {
  8133. return typeof this.title === "function" ? this.title() : this.title;
  8134. };
  8135. /**
  8136. * Calculate the distance to the border of the Node
  8137. * @param {CanvasRenderingContext2D} ctx
  8138. * @param {Number} angle Angle in radians
  8139. * @returns {number} distance Distance to the border in pixels
  8140. */
  8141. Node.prototype.distanceToBorder = function (ctx, angle) {
  8142. var borderWidth = 1;
  8143. if (!this.width) {
  8144. this.resize(ctx);
  8145. }
  8146. switch (this.shape) {
  8147. case 'circle':
  8148. case 'dot':
  8149. return this.radius + borderWidth;
  8150. case 'ellipse':
  8151. var a = this.width / 2;
  8152. var b = this.height / 2;
  8153. var w = (Math.sin(angle) * a);
  8154. var h = (Math.cos(angle) * b);
  8155. return a * b / Math.sqrt(w * w + h * h);
  8156. // TODO: implement distanceToBorder for database
  8157. // TODO: implement distanceToBorder for triangle
  8158. // TODO: implement distanceToBorder for triangleDown
  8159. case 'box':
  8160. case 'image':
  8161. case 'text':
  8162. default:
  8163. if (this.width) {
  8164. return Math.min(
  8165. Math.abs(this.width / 2 / Math.cos(angle)),
  8166. Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth;
  8167. // TODO: reckon with border radius too in case of box
  8168. }
  8169. else {
  8170. return 0;
  8171. }
  8172. }
  8173. // TODO: implement calculation of distance to border for all shapes
  8174. };
  8175. /**
  8176. * Set forces acting on the node
  8177. * @param {number} fx Force in horizontal direction
  8178. * @param {number} fy Force in vertical direction
  8179. */
  8180. Node.prototype._setForce = function(fx, fy) {
  8181. this.fx = fx;
  8182. this.fy = fy;
  8183. };
  8184. /**
  8185. * Add forces acting on the node
  8186. * @param {number} fx Force in horizontal direction
  8187. * @param {number} fy Force in vertical direction
  8188. * @private
  8189. */
  8190. Node.prototype._addForce = function(fx, fy) {
  8191. this.fx += fx;
  8192. this.fy += fy;
  8193. };
  8194. /**
  8195. * Perform one discrete step for the node
  8196. * @param {number} interval Time interval in seconds
  8197. */
  8198. Node.prototype.discreteStep = function(interval) {
  8199. if (!this.xFixed) {
  8200. var dx = this.damping * this.vx; // damping force
  8201. var ax = (this.fx - dx) / this.mass; // acceleration
  8202. this.vx += ax * interval; // velocity
  8203. this.x += this.vx * interval; // position
  8204. }
  8205. if (!this.yFixed) {
  8206. var dy = this.damping * this.vy; // damping force
  8207. var ay = (this.fy - dy) / this.mass; // acceleration
  8208. this.vy += ay * interval; // velocity
  8209. this.y += this.vy * interval; // position
  8210. }
  8211. };
  8212. /**
  8213. * Perform one discrete step for the node
  8214. * @param {number} interval Time interval in seconds
  8215. * @param {number} maxVelocity The speed limit imposed on the velocity
  8216. */
  8217. Node.prototype.discreteStepLimited = function(interval, maxVelocity) {
  8218. if (!this.xFixed) {
  8219. var dx = this.damping * this.vx; // damping force
  8220. var ax = (this.fx - dx) / this.mass; // acceleration
  8221. this.vx += ax * interval; // velocity
  8222. this.vx = (Math.abs(this.vx) > maxVelocity) ? ((this.vx > 0) ? maxVelocity : -maxVelocity) : this.vx;
  8223. this.x += this.vx * interval; // position
  8224. }
  8225. else {
  8226. this.fx = 0;
  8227. }
  8228. if (!this.yFixed) {
  8229. var dy = this.damping * this.vy; // damping force
  8230. var ay = (this.fy - dy) / this.mass; // acceleration
  8231. this.vy += ay * interval; // velocity
  8232. this.vy = (Math.abs(this.vy) > maxVelocity) ? ((this.vy > 0) ? maxVelocity : -maxVelocity) : this.vy;
  8233. this.y += this.vy * interval; // position
  8234. }
  8235. else {
  8236. this.fy = 0;
  8237. }
  8238. };
  8239. /**
  8240. * Check if this node has a fixed x and y position
  8241. * @return {boolean} true if fixed, false if not
  8242. */
  8243. Node.prototype.isFixed = function() {
  8244. return (this.xFixed && this.yFixed);
  8245. };
  8246. /**
  8247. * Check if this node is moving
  8248. * @param {number} vmin the minimum velocity considered as "moving"
  8249. * @return {boolean} true if moving, false if it has no velocity
  8250. */
  8251. // TODO: replace this method with calculating the kinetic energy
  8252. Node.prototype.isMoving = function(vmin) {
  8253. return (Math.abs(this.vx) > vmin || Math.abs(this.vy) > vmin);
  8254. };
  8255. /**
  8256. * check if this node is selecte
  8257. * @return {boolean} selected True if node is selected, else false
  8258. */
  8259. Node.prototype.isSelected = function() {
  8260. return this.selected;
  8261. };
  8262. /**
  8263. * Retrieve the value of the node. Can be undefined
  8264. * @return {Number} value
  8265. */
  8266. Node.prototype.getValue = function() {
  8267. return this.value;
  8268. };
  8269. /**
  8270. * Calculate the distance from the nodes location to the given location (x,y)
  8271. * @param {Number} x
  8272. * @param {Number} y
  8273. * @return {Number} value
  8274. */
  8275. Node.prototype.getDistance = function(x, y) {
  8276. var dx = this.x - x,
  8277. dy = this.y - y;
  8278. return Math.sqrt(dx * dx + dy * dy);
  8279. };
  8280. /**
  8281. * Adjust the value range of the node. The node will adjust it's radius
  8282. * based on its value.
  8283. * @param {Number} min
  8284. * @param {Number} max
  8285. */
  8286. Node.prototype.setValueRange = function(min, max) {
  8287. if (!this.radiusFixed && this.value !== undefined) {
  8288. if (max == min) {
  8289. this.radius = (this.radiusMin + this.radiusMax) / 2;
  8290. }
  8291. else {
  8292. var scale = (this.radiusMax - this.radiusMin) / (max - min);
  8293. this.radius = (this.value - min) * scale + this.radiusMin;
  8294. }
  8295. }
  8296. this.baseRadiusValue = this.radius;
  8297. };
  8298. /**
  8299. * Draw this node in the given canvas
  8300. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8301. * @param {CanvasRenderingContext2D} ctx
  8302. */
  8303. Node.prototype.draw = function(ctx) {
  8304. throw "Draw method not initialized for node";
  8305. };
  8306. /**
  8307. * Recalculate the size of this node in the given canvas
  8308. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8309. * @param {CanvasRenderingContext2D} ctx
  8310. */
  8311. Node.prototype.resize = function(ctx) {
  8312. throw "Resize method not initialized for node";
  8313. };
  8314. /**
  8315. * Check if this object is overlapping with the provided object
  8316. * @param {Object} obj an object with parameters left, top, right, bottom
  8317. * @return {boolean} True if location is located on node
  8318. */
  8319. Node.prototype.isOverlappingWith = function(obj) {
  8320. return (this.left < obj.right &&
  8321. this.left + this.width > obj.left &&
  8322. this.top < obj.bottom &&
  8323. this.top + this.height > obj.top);
  8324. };
  8325. Node.prototype._resizeImage = function (ctx) {
  8326. // TODO: pre calculate the image size
  8327. if (!this.width || !this.height) { // undefined or 0
  8328. var width, height;
  8329. if (this.value) {
  8330. this.radius = this.baseRadiusValue;
  8331. var scale = this.imageObj.height / this.imageObj.width;
  8332. if (scale !== undefined) {
  8333. width = this.radius || this.imageObj.width;
  8334. height = this.radius * scale || this.imageObj.height;
  8335. }
  8336. else {
  8337. width = 0;
  8338. height = 0;
  8339. }
  8340. }
  8341. else {
  8342. width = this.imageObj.width;
  8343. height = this.imageObj.height;
  8344. }
  8345. this.width = width;
  8346. this.height = height;
  8347. this.growthIndicator = 0;
  8348. if (this.width > 0 && this.height > 0) {
  8349. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8350. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8351. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8352. this.growthIndicator = this.width - width;
  8353. }
  8354. }
  8355. };
  8356. Node.prototype._drawImage = function (ctx) {
  8357. this._resizeImage(ctx);
  8358. this.left = this.x - this.width / 2;
  8359. this.top = this.y - this.height / 2;
  8360. var yLabel;
  8361. if (this.imageObj.width != 0 ) {
  8362. // draw the shade
  8363. if (this.clusterSize > 1) {
  8364. var lineWidth = ((this.clusterSize > 1) ? 10 : 0.0);
  8365. lineWidth *= this.graphScaleInv;
  8366. lineWidth = Math.min(0.2 * this.width,lineWidth);
  8367. ctx.globalAlpha = 0.5;
  8368. ctx.drawImage(this.imageObj, this.left - lineWidth, this.top - lineWidth, this.width + 2*lineWidth, this.height + 2*lineWidth);
  8369. }
  8370. // draw the image
  8371. ctx.globalAlpha = 1.0;
  8372. ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height);
  8373. yLabel = this.y + this.height / 2;
  8374. }
  8375. else {
  8376. // image still loading... just draw the label for now
  8377. yLabel = this.y;
  8378. }
  8379. this._label(ctx, this.label, this.x, yLabel, undefined, "top");
  8380. };
  8381. Node.prototype._resizeBox = function (ctx) {
  8382. if (!this.width) {
  8383. var margin = 5;
  8384. var textSize = this.getTextSize(ctx);
  8385. this.width = textSize.width + 2 * margin;
  8386. this.height = textSize.height + 2 * margin;
  8387. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  8388. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  8389. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  8390. // this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8391. }
  8392. };
  8393. Node.prototype._drawBox = function (ctx) {
  8394. this._resizeBox(ctx);
  8395. this.left = this.x - this.width / 2;
  8396. this.top = this.y - this.height / 2;
  8397. var clusterLineWidth = 2.5;
  8398. var selectionLineWidth = 2;
  8399. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8400. // draw the outer border
  8401. if (this.clusterSize > 1) {
  8402. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8403. ctx.lineWidth *= this.graphScaleInv;
  8404. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8405. ctx.roundRect(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth, this.radius);
  8406. ctx.stroke();
  8407. }
  8408. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8409. ctx.lineWidth *= this.graphScaleInv;
  8410. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8411. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8412. ctx.roundRect(this.left, this.top, this.width, this.height, this.radius);
  8413. ctx.fill();
  8414. ctx.stroke();
  8415. this._label(ctx, this.label, this.x, this.y);
  8416. };
  8417. Node.prototype._resizeDatabase = function (ctx) {
  8418. if (!this.width) {
  8419. var margin = 5;
  8420. var textSize = this.getTextSize(ctx);
  8421. var size = textSize.width + 2 * margin;
  8422. this.width = size;
  8423. this.height = size;
  8424. // scaling used for clustering
  8425. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8426. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8427. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8428. this.growthIndicator = this.width - size;
  8429. }
  8430. };
  8431. Node.prototype._drawDatabase = function (ctx) {
  8432. this._resizeDatabase(ctx);
  8433. this.left = this.x - this.width / 2;
  8434. this.top = this.y - this.height / 2;
  8435. var clusterLineWidth = 2.5;
  8436. var selectionLineWidth = 2;
  8437. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8438. // draw the outer border
  8439. if (this.clusterSize > 1) {
  8440. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8441. ctx.lineWidth *= this.graphScaleInv;
  8442. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8443. 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);
  8444. ctx.stroke();
  8445. }
  8446. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8447. ctx.lineWidth *= this.graphScaleInv;
  8448. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8449. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8450. ctx.database(this.x - this.width/2, this.y - this.height*0.5, this.width, this.height);
  8451. ctx.fill();
  8452. ctx.stroke();
  8453. this._label(ctx, this.label, this.x, this.y);
  8454. };
  8455. Node.prototype._resizeCircle = function (ctx) {
  8456. if (!this.width) {
  8457. var margin = 5;
  8458. var textSize = this.getTextSize(ctx);
  8459. var diameter = Math.max(textSize.width, textSize.height) + 2 * margin;
  8460. this.radius = diameter / 2;
  8461. this.width = diameter;
  8462. this.height = diameter;
  8463. // scaling used for clustering
  8464. // this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  8465. // this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  8466. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8467. this.growthIndicator = this.radius - 0.5*diameter;
  8468. }
  8469. };
  8470. Node.prototype._drawCircle = function (ctx) {
  8471. this._resizeCircle(ctx);
  8472. this.left = this.x - this.width / 2;
  8473. this.top = this.y - this.height / 2;
  8474. var clusterLineWidth = 2.5;
  8475. var selectionLineWidth = 2;
  8476. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8477. // draw the outer border
  8478. if (this.clusterSize > 1) {
  8479. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8480. ctx.lineWidth *= this.graphScaleInv;
  8481. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8482. ctx.circle(this.x, this.y, this.radius+2*ctx.lineWidth);
  8483. ctx.stroke();
  8484. }
  8485. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8486. ctx.lineWidth *= this.graphScaleInv;
  8487. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8488. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8489. ctx.circle(this.x, this.y, this.radius);
  8490. ctx.fill();
  8491. ctx.stroke();
  8492. this._label(ctx, this.label, this.x, this.y);
  8493. };
  8494. Node.prototype._resizeEllipse = function (ctx) {
  8495. if (!this.width) {
  8496. var textSize = this.getTextSize(ctx);
  8497. this.width = textSize.width * 1.5;
  8498. this.height = textSize.height * 2;
  8499. if (this.width < this.height) {
  8500. this.width = this.height;
  8501. }
  8502. var defaultSize = this.width;
  8503. // scaling used for clustering
  8504. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8505. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8506. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8507. this.growthIndicator = this.width - defaultSize;
  8508. }
  8509. };
  8510. Node.prototype._drawEllipse = function (ctx) {
  8511. this._resizeEllipse(ctx);
  8512. this.left = this.x - this.width / 2;
  8513. this.top = this.y - this.height / 2;
  8514. var clusterLineWidth = 2.5;
  8515. var selectionLineWidth = 2;
  8516. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8517. // draw the outer border
  8518. if (this.clusterSize > 1) {
  8519. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8520. ctx.lineWidth *= this.graphScaleInv;
  8521. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8522. ctx.ellipse(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth);
  8523. ctx.stroke();
  8524. }
  8525. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8526. ctx.lineWidth *= this.graphScaleInv;
  8527. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8528. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8529. ctx.ellipse(this.left, this.top, this.width, this.height);
  8530. ctx.fill();
  8531. ctx.stroke();
  8532. this._label(ctx, this.label, this.x, this.y);
  8533. };
  8534. Node.prototype._drawDot = function (ctx) {
  8535. this._drawShape(ctx, 'circle');
  8536. };
  8537. Node.prototype._drawTriangle = function (ctx) {
  8538. this._drawShape(ctx, 'triangle');
  8539. };
  8540. Node.prototype._drawTriangleDown = function (ctx) {
  8541. this._drawShape(ctx, 'triangleDown');
  8542. };
  8543. Node.prototype._drawSquare = function (ctx) {
  8544. this._drawShape(ctx, 'square');
  8545. };
  8546. Node.prototype._drawStar = function (ctx) {
  8547. this._drawShape(ctx, 'star');
  8548. };
  8549. Node.prototype._resizeShape = function (ctx) {
  8550. if (!this.width) {
  8551. this.radius = this.baseRadiusValue;
  8552. var size = 2 * this.radius;
  8553. this.width = size;
  8554. this.height = size;
  8555. // scaling used for clustering
  8556. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8557. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8558. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8559. this.growthIndicator = this.width - size;
  8560. }
  8561. };
  8562. Node.prototype._drawShape = function (ctx, shape) {
  8563. this._resizeShape(ctx);
  8564. this.left = this.x - this.width / 2;
  8565. this.top = this.y - this.height / 2;
  8566. var clusterLineWidth = 2.5;
  8567. var selectionLineWidth = 2;
  8568. var radiusMultiplier = 2;
  8569. // choose draw method depending on the shape
  8570. switch (shape) {
  8571. case 'dot': radiusMultiplier = 2; break;
  8572. case 'square': radiusMultiplier = 2; break;
  8573. case 'triangle': radiusMultiplier = 3; break;
  8574. case 'triangleDown': radiusMultiplier = 3; break;
  8575. case 'star': radiusMultiplier = 4; break;
  8576. }
  8577. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8578. // draw the outer border
  8579. if (this.clusterSize > 1) {
  8580. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8581. ctx.lineWidth *= this.graphScaleInv;
  8582. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8583. ctx[shape](this.x, this.y, this.radius + radiusMultiplier * ctx.lineWidth);
  8584. ctx.stroke();
  8585. }
  8586. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8587. ctx.lineWidth *= this.graphScaleInv;
  8588. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8589. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8590. ctx[shape](this.x, this.y, this.radius);
  8591. ctx.fill();
  8592. ctx.stroke();
  8593. if (this.label) {
  8594. this._label(ctx, this.label, this.x, this.y + this.height / 2, undefined, 'top');
  8595. }
  8596. };
  8597. Node.prototype._resizeText = function (ctx) {
  8598. if (!this.width) {
  8599. var margin = 5;
  8600. var textSize = this.getTextSize(ctx);
  8601. this.width = textSize.width + 2 * margin;
  8602. this.height = textSize.height + 2 * margin;
  8603. // scaling used for clustering
  8604. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8605. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8606. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8607. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  8608. }
  8609. };
  8610. Node.prototype._drawText = function (ctx) {
  8611. this._resizeText(ctx);
  8612. this.left = this.x - this.width / 2;
  8613. this.top = this.y - this.height / 2;
  8614. this._label(ctx, this.label, this.x, this.y);
  8615. };
  8616. Node.prototype._label = function (ctx, text, x, y, align, baseline) {
  8617. if (text && this.fontSize * this.graphScale > this.fontDrawThreshold) {
  8618. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  8619. ctx.fillStyle = this.fontColor || "black";
  8620. ctx.textAlign = align || "center";
  8621. ctx.textBaseline = baseline || "middle";
  8622. var lines = text.split('\n'),
  8623. lineCount = lines.length,
  8624. fontSize = (this.fontSize + 4),
  8625. yLine = y + (1 - lineCount) / 2 * fontSize;
  8626. for (var i = 0; i < lineCount; i++) {
  8627. ctx.fillText(lines[i], x, yLine);
  8628. yLine += fontSize;
  8629. }
  8630. }
  8631. };
  8632. Node.prototype.getTextSize = function(ctx) {
  8633. if (this.label !== undefined) {
  8634. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  8635. var lines = this.label.split('\n'),
  8636. height = (this.fontSize + 4) * lines.length,
  8637. width = 0;
  8638. for (var i = 0, iMax = lines.length; i < iMax; i++) {
  8639. width = Math.max(width, ctx.measureText(lines[i]).width);
  8640. }
  8641. return {"width": width, "height": height};
  8642. }
  8643. else {
  8644. return {"width": 0, "height": 0};
  8645. }
  8646. };
  8647. /**
  8648. * this is used to determine if a node is visible at all. this is used to determine when it needs to be drawn.
  8649. * there is a safety margin of 0.3 * width;
  8650. *
  8651. * @returns {boolean}
  8652. */
  8653. Node.prototype.inArea = function() {
  8654. if (this.width !== undefined) {
  8655. return (this.x + this.width*this.graphScaleInv >= this.canvasTopLeft.x &&
  8656. this.x - this.width*this.graphScaleInv < this.canvasBottomRight.x &&
  8657. this.y + this.height*this.graphScaleInv >= this.canvasTopLeft.y &&
  8658. this.y - this.height*this.graphScaleInv < this.canvasBottomRight.y);
  8659. }
  8660. else {
  8661. return true;
  8662. }
  8663. };
  8664. /**
  8665. * checks if the core of the node is in the display area, this is used for opening clusters around zoom
  8666. * @returns {boolean}
  8667. */
  8668. Node.prototype.inView = function() {
  8669. return (this.x >= this.canvasTopLeft.x &&
  8670. this.x < this.canvasBottomRight.x &&
  8671. this.y >= this.canvasTopLeft.y &&
  8672. this.y < this.canvasBottomRight.y);
  8673. };
  8674. /**
  8675. * This allows the zoom level of the graph to influence the rendering
  8676. * We store the inverted scale and the coordinates of the top left, and bottom right points of the canvas
  8677. *
  8678. * @param scale
  8679. * @param canvasTopLeft
  8680. * @param canvasBottomRight
  8681. */
  8682. Node.prototype.setScaleAndPos = function(scale,canvasTopLeft,canvasBottomRight) {
  8683. this.graphScaleInv = 1.0/scale;
  8684. this.graphScale = scale;
  8685. this.canvasTopLeft = canvasTopLeft;
  8686. this.canvasBottomRight = canvasBottomRight;
  8687. };
  8688. /**
  8689. * This allows the zoom level of the graph to influence the rendering
  8690. *
  8691. * @param scale
  8692. */
  8693. Node.prototype.setScale = function(scale) {
  8694. this.graphScaleInv = 1.0/scale;
  8695. this.graphScale = scale;
  8696. };
  8697. /**
  8698. * set the velocity at 0. Is called when this node is contained in another during clustering
  8699. */
  8700. Node.prototype.clearVelocity = function() {
  8701. this.vx = 0;
  8702. this.vy = 0;
  8703. };
  8704. /**
  8705. * Basic preservation of (kinectic) energy
  8706. *
  8707. * @param massBeforeClustering
  8708. */
  8709. Node.prototype.updateVelocity = function(massBeforeClustering) {
  8710. var energyBefore = this.vx * this.vx * massBeforeClustering;
  8711. //this.vx = (this.vx < 0) ? -Math.sqrt(energyBefore/this.mass) : Math.sqrt(energyBefore/this.mass);
  8712. this.vx = Math.sqrt(energyBefore/this.mass);
  8713. energyBefore = this.vy * this.vy * massBeforeClustering;
  8714. //this.vy = (this.vy < 0) ? -Math.sqrt(energyBefore/this.mass) : Math.sqrt(energyBefore/this.mass);
  8715. this.vy = Math.sqrt(energyBefore/this.mass);
  8716. };
  8717. /**
  8718. * @class Edge
  8719. *
  8720. * A edge connects two nodes
  8721. * @param {Object} properties Object with properties. Must contain
  8722. * At least properties from and to.
  8723. * Available properties: from (number),
  8724. * to (number), label (string, color (string),
  8725. * width (number), style (string),
  8726. * length (number), title (string)
  8727. * @param {Graph} graph A graph object, used to find and edge to
  8728. * nodes.
  8729. * @param {Object} constants An object with default values for
  8730. * example for the color
  8731. */
  8732. function Edge (properties, graph, constants) {
  8733. if (!graph) {
  8734. throw "No graph provided";
  8735. }
  8736. this.graph = graph;
  8737. // initialize constants
  8738. this.widthMin = constants.edges.widthMin;
  8739. this.widthMax = constants.edges.widthMax;
  8740. // initialize variables
  8741. this.id = undefined;
  8742. this.fromId = undefined;
  8743. this.toId = undefined;
  8744. this.style = constants.edges.style;
  8745. this.title = undefined;
  8746. this.width = constants.edges.width;
  8747. this.value = undefined;
  8748. this.length = constants.physics.springLength;
  8749. this.customLength = false;
  8750. this.selected = false;
  8751. this.smooth = constants.smoothCurves;
  8752. this.arrowScaleFactor = constants.edges.arrowScaleFactor;
  8753. this.from = null; // a node
  8754. this.to = null; // a node
  8755. this.via = null; // a temp node
  8756. // we use this to be able to reconnect the edge to a cluster if its node is put into a cluster
  8757. // by storing the original information we can revert to the original connection when the cluser is opened.
  8758. this.originalFromId = [];
  8759. this.originalToId = [];
  8760. this.connected = false;
  8761. // Added to support dashed lines
  8762. // David Jordan
  8763. // 2012-08-08
  8764. this.dash = util.extend({}, constants.edges.dash); // contains properties length, gap, altLength
  8765. this.color = {color:constants.edges.color.color,
  8766. highlight:constants.edges.color.highlight};
  8767. this.widthFixed = false;
  8768. this.lengthFixed = false;
  8769. this.setProperties(properties, constants);
  8770. }
  8771. /**
  8772. * Set or overwrite properties for the edge
  8773. * @param {Object} properties an object with properties
  8774. * @param {Object} constants and object with default, global properties
  8775. */
  8776. Edge.prototype.setProperties = function(properties, constants) {
  8777. if (!properties) {
  8778. return;
  8779. }
  8780. if (properties.from !== undefined) {this.fromId = properties.from;}
  8781. if (properties.to !== undefined) {this.toId = properties.to;}
  8782. if (properties.id !== undefined) {this.id = properties.id;}
  8783. if (properties.style !== undefined) {this.style = properties.style;}
  8784. if (properties.label !== undefined) {this.label = properties.label;}
  8785. if (this.label) {
  8786. this.fontSize = constants.edges.fontSize;
  8787. this.fontFace = constants.edges.fontFace;
  8788. this.fontColor = constants.edges.fontColor;
  8789. this.fontFill = constants.edges.fontFill;
  8790. if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;}
  8791. if (properties.fontSize !== undefined) {this.fontSize = properties.fontSize;}
  8792. if (properties.fontFace !== undefined) {this.fontFace = properties.fontFace;}
  8793. if (properties.fontFill !== undefined) {this.fontFill = properties.fontFill;}
  8794. }
  8795. if (properties.title !== undefined) {this.title = properties.title;}
  8796. if (properties.width !== undefined) {this.width = properties.width;}
  8797. if (properties.value !== undefined) {this.value = properties.value;}
  8798. if (properties.length !== undefined) {this.length = properties.length;
  8799. this.customLength = true;}
  8800. // scale the arrow
  8801. if (properties.arrowScaleFactor !== undefined) {this.arrowScaleFactor = properties.arrowScaleFactor;}
  8802. // Added to support dashed lines
  8803. // David Jordan
  8804. // 2012-08-08
  8805. if (properties.dash) {
  8806. if (properties.dash.length !== undefined) {this.dash.length = properties.dash.length;}
  8807. if (properties.dash.gap !== undefined) {this.dash.gap = properties.dash.gap;}
  8808. if (properties.dash.altLength !== undefined) {this.dash.altLength = properties.dash.altLength;}
  8809. }
  8810. if (properties.color !== undefined) {
  8811. if (util.isString(properties.color)) {
  8812. this.color.color = properties.color;
  8813. this.color.highlight = properties.color;
  8814. }
  8815. else {
  8816. if (properties.color.color !== undefined) {this.color.color = properties.color.color;}
  8817. if (properties.color.highlight !== undefined) {this.color.highlight = properties.color.highlight;}
  8818. }
  8819. }
  8820. // A node is connected when it has a from and to node.
  8821. this.connect();
  8822. this.widthFixed = this.widthFixed || (properties.width !== undefined);
  8823. this.lengthFixed = this.lengthFixed || (properties.length !== undefined);
  8824. // set draw method based on style
  8825. switch (this.style) {
  8826. case 'line': this.draw = this._drawLine; break;
  8827. case 'arrow': this.draw = this._drawArrow; break;
  8828. case 'arrow-center': this.draw = this._drawArrowCenter; break;
  8829. case 'dash-line': this.draw = this._drawDashLine; break;
  8830. default: this.draw = this._drawLine; break;
  8831. }
  8832. };
  8833. /**
  8834. * Connect an edge to its nodes
  8835. */
  8836. Edge.prototype.connect = function () {
  8837. this.disconnect();
  8838. this.from = this.graph.nodes[this.fromId] || null;
  8839. this.to = this.graph.nodes[this.toId] || null;
  8840. this.connected = (this.from && this.to);
  8841. if (this.connected) {
  8842. this.from.attachEdge(this);
  8843. this.to.attachEdge(this);
  8844. }
  8845. else {
  8846. if (this.from) {
  8847. this.from.detachEdge(this);
  8848. }
  8849. if (this.to) {
  8850. this.to.detachEdge(this);
  8851. }
  8852. }
  8853. };
  8854. /**
  8855. * Disconnect an edge from its nodes
  8856. */
  8857. Edge.prototype.disconnect = function () {
  8858. if (this.from) {
  8859. this.from.detachEdge(this);
  8860. this.from = null;
  8861. }
  8862. if (this.to) {
  8863. this.to.detachEdge(this);
  8864. this.to = null;
  8865. }
  8866. this.connected = false;
  8867. };
  8868. /**
  8869. * get the title of this edge.
  8870. * @return {string} title The title of the edge, or undefined when no title
  8871. * has been set.
  8872. */
  8873. Edge.prototype.getTitle = function() {
  8874. return typeof this.title === "function" ? this.title() : this.title;
  8875. };
  8876. /**
  8877. * Retrieve the value of the edge. Can be undefined
  8878. * @return {Number} value
  8879. */
  8880. Edge.prototype.getValue = function() {
  8881. return this.value;
  8882. };
  8883. /**
  8884. * Adjust the value range of the edge. The edge will adjust it's width
  8885. * based on its value.
  8886. * @param {Number} min
  8887. * @param {Number} max
  8888. */
  8889. Edge.prototype.setValueRange = function(min, max) {
  8890. if (!this.widthFixed && this.value !== undefined) {
  8891. var scale = (this.widthMax - this.widthMin) / (max - min);
  8892. this.width = (this.value - min) * scale + this.widthMin;
  8893. }
  8894. };
  8895. /**
  8896. * Redraw a edge
  8897. * Draw this edge in the given canvas
  8898. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8899. * @param {CanvasRenderingContext2D} ctx
  8900. */
  8901. Edge.prototype.draw = function(ctx) {
  8902. throw "Method draw not initialized in edge";
  8903. };
  8904. /**
  8905. * Check if this object is overlapping with the provided object
  8906. * @param {Object} obj an object with parameters left, top
  8907. * @return {boolean} True if location is located on the edge
  8908. */
  8909. Edge.prototype.isOverlappingWith = function(obj) {
  8910. if (this.connected) {
  8911. var distMax = 10;
  8912. var xFrom = this.from.x;
  8913. var yFrom = this.from.y;
  8914. var xTo = this.to.x;
  8915. var yTo = this.to.y;
  8916. var xObj = obj.left;
  8917. var yObj = obj.top;
  8918. var dist = this._getDistanceToEdge(xFrom, yFrom, xTo, yTo, xObj, yObj);
  8919. return (dist < distMax);
  8920. }
  8921. else {
  8922. return false
  8923. }
  8924. };
  8925. /**
  8926. * Redraw a edge as a line
  8927. * Draw this edge in the given canvas
  8928. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8929. * @param {CanvasRenderingContext2D} ctx
  8930. * @private
  8931. */
  8932. Edge.prototype._drawLine = function(ctx) {
  8933. // set style
  8934. if (this.selected == true) {ctx.strokeStyle = this.color.highlight;}
  8935. else {ctx.strokeStyle = this.color.color;}
  8936. ctx.lineWidth = this._getLineWidth();
  8937. if (this.from != this.to) {
  8938. // draw line
  8939. this._line(ctx);
  8940. // draw label
  8941. var point;
  8942. if (this.label) {
  8943. if (this.smooth == true) {
  8944. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  8945. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  8946. point = {x:midpointX, y:midpointY};
  8947. }
  8948. else {
  8949. point = this._pointOnLine(0.5);
  8950. }
  8951. this._label(ctx, this.label, point.x, point.y);
  8952. }
  8953. }
  8954. else {
  8955. var x, y;
  8956. var radius = this.length / 4;
  8957. var node = this.from;
  8958. if (!node.width) {
  8959. node.resize(ctx);
  8960. }
  8961. if (node.width > node.height) {
  8962. x = node.x + node.width / 2;
  8963. y = node.y - radius;
  8964. }
  8965. else {
  8966. x = node.x + radius;
  8967. y = node.y - node.height / 2;
  8968. }
  8969. this._circle(ctx, x, y, radius);
  8970. point = this._pointOnCircle(x, y, radius, 0.5);
  8971. this._label(ctx, this.label, point.x, point.y);
  8972. }
  8973. };
  8974. /**
  8975. * Get the line width of the edge. Depends on width and whether one of the
  8976. * connected nodes is selected.
  8977. * @return {Number} width
  8978. * @private
  8979. */
  8980. Edge.prototype._getLineWidth = function() {
  8981. if (this.selected == true) {
  8982. return Math.min(this.width * 2, this.widthMax)*this.graphScaleInv;
  8983. }
  8984. else {
  8985. return this.width*this.graphScaleInv;
  8986. }
  8987. };
  8988. /**
  8989. * Draw a line between two nodes
  8990. * @param {CanvasRenderingContext2D} ctx
  8991. * @private
  8992. */
  8993. Edge.prototype._line = function (ctx) {
  8994. // draw a straight line
  8995. ctx.beginPath();
  8996. ctx.moveTo(this.from.x, this.from.y);
  8997. if (this.smooth == true) {
  8998. ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y);
  8999. }
  9000. else {
  9001. ctx.lineTo(this.to.x, this.to.y);
  9002. }
  9003. ctx.stroke();
  9004. };
  9005. /**
  9006. * Draw a line from a node to itself, a circle
  9007. * @param {CanvasRenderingContext2D} ctx
  9008. * @param {Number} x
  9009. * @param {Number} y
  9010. * @param {Number} radius
  9011. * @private
  9012. */
  9013. Edge.prototype._circle = function (ctx, x, y, radius) {
  9014. // draw a circle
  9015. ctx.beginPath();
  9016. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  9017. ctx.stroke();
  9018. };
  9019. /**
  9020. * Draw label with white background and with the middle at (x, y)
  9021. * @param {CanvasRenderingContext2D} ctx
  9022. * @param {String} text
  9023. * @param {Number} x
  9024. * @param {Number} y
  9025. * @private
  9026. */
  9027. Edge.prototype._label = function (ctx, text, x, y) {
  9028. if (text) {
  9029. // TODO: cache the calculated size
  9030. ctx.font = ((this.from.selected || this.to.selected) ? "bold " : "") +
  9031. this.fontSize + "px " + this.fontFace;
  9032. ctx.fillStyle = this.fontFill;
  9033. var width = ctx.measureText(text).width;
  9034. var height = this.fontSize;
  9035. var left = x - width / 2;
  9036. var top = y - height / 2;
  9037. ctx.fillRect(left, top, width, height);
  9038. // draw text
  9039. ctx.fillStyle = this.fontColor || "black";
  9040. ctx.textAlign = "left";
  9041. ctx.textBaseline = "top";
  9042. ctx.fillText(text, left, top);
  9043. }
  9044. };
  9045. /**
  9046. * Redraw a edge as a dashed line
  9047. * Draw this edge in the given canvas
  9048. * @author David Jordan
  9049. * @date 2012-08-08
  9050. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9051. * @param {CanvasRenderingContext2D} ctx
  9052. * @private
  9053. */
  9054. Edge.prototype._drawDashLine = function(ctx) {
  9055. // set style
  9056. if (this.selected == true) {ctx.strokeStyle = this.color.highlight;}
  9057. else {ctx.strokeStyle = this.color.color;}
  9058. ctx.lineWidth = this._getLineWidth();
  9059. // only firefox and chrome support this method, else we use the legacy one.
  9060. if (ctx.mozDash !== undefined || ctx.setLineDash !== undefined) {
  9061. ctx.beginPath();
  9062. ctx.moveTo(this.from.x, this.from.y);
  9063. // configure the dash pattern
  9064. var pattern = [0];
  9065. if (this.dash.length !== undefined && this.dash.gap !== undefined) {
  9066. pattern = [this.dash.length,this.dash.gap];
  9067. }
  9068. else {
  9069. pattern = [5,5];
  9070. }
  9071. // set dash settings for chrome or firefox
  9072. if (typeof ctx.setLineDash !== 'undefined') { //Chrome
  9073. ctx.setLineDash(pattern);
  9074. ctx.lineDashOffset = 0;
  9075. } else { //Firefox
  9076. ctx.mozDash = pattern;
  9077. ctx.mozDashOffset = 0;
  9078. }
  9079. // draw the line
  9080. if (this.smooth == true) {
  9081. ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y);
  9082. }
  9083. else {
  9084. ctx.lineTo(this.to.x, this.to.y);
  9085. }
  9086. ctx.stroke();
  9087. // restore the dash settings.
  9088. if (typeof ctx.setLineDash !== 'undefined') { //Chrome
  9089. ctx.setLineDash([0]);
  9090. ctx.lineDashOffset = 0;
  9091. } else { //Firefox
  9092. ctx.mozDash = [0];
  9093. ctx.mozDashOffset = 0;
  9094. }
  9095. }
  9096. else { // unsupporting smooth lines
  9097. // draw dashed line
  9098. ctx.beginPath();
  9099. ctx.lineCap = 'round';
  9100. if (this.dash.altLength !== undefined) //If an alt dash value has been set add to the array this value
  9101. {
  9102. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  9103. [this.dash.length,this.dash.gap,this.dash.altLength,this.dash.gap]);
  9104. }
  9105. 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
  9106. {
  9107. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  9108. [this.dash.length,this.dash.gap]);
  9109. }
  9110. else //If all else fails draw a line
  9111. {
  9112. ctx.moveTo(this.from.x, this.from.y);
  9113. ctx.lineTo(this.to.x, this.to.y);
  9114. }
  9115. ctx.stroke();
  9116. }
  9117. // draw label
  9118. if (this.label) {
  9119. var point;
  9120. if (this.smooth == true) {
  9121. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9122. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9123. point = {x:midpointX, y:midpointY};
  9124. }
  9125. else {
  9126. point = this._pointOnLine(0.5);
  9127. }
  9128. this._label(ctx, this.label, point.x, point.y);
  9129. }
  9130. };
  9131. /**
  9132. * Get a point on a line
  9133. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  9134. * @return {Object} point
  9135. * @private
  9136. */
  9137. Edge.prototype._pointOnLine = function (percentage) {
  9138. return {
  9139. x: (1 - percentage) * this.from.x + percentage * this.to.x,
  9140. y: (1 - percentage) * this.from.y + percentage * this.to.y
  9141. }
  9142. };
  9143. /**
  9144. * Get a point on a circle
  9145. * @param {Number} x
  9146. * @param {Number} y
  9147. * @param {Number} radius
  9148. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  9149. * @return {Object} point
  9150. * @private
  9151. */
  9152. Edge.prototype._pointOnCircle = function (x, y, radius, percentage) {
  9153. var angle = (percentage - 3/8) * 2 * Math.PI;
  9154. return {
  9155. x: x + radius * Math.cos(angle),
  9156. y: y - radius * Math.sin(angle)
  9157. }
  9158. };
  9159. /**
  9160. * Redraw a edge as a line with an arrow halfway the line
  9161. * Draw this edge in the given canvas
  9162. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9163. * @param {CanvasRenderingContext2D} ctx
  9164. * @private
  9165. */
  9166. Edge.prototype._drawArrowCenter = function(ctx) {
  9167. var point;
  9168. // set style
  9169. if (this.selected == true) {ctx.strokeStyle = this.color.highlight; ctx.fillStyle = this.color.highlight;}
  9170. else {ctx.strokeStyle = this.color.color; ctx.fillStyle = this.color.color;}
  9171. ctx.lineWidth = this._getLineWidth();
  9172. if (this.from != this.to) {
  9173. // draw line
  9174. this._line(ctx);
  9175. var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  9176. var length = (10 + 5 * this.width) * this.arrowScaleFactor;
  9177. // draw an arrow halfway the line
  9178. if (this.smooth == true) {
  9179. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9180. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9181. point = {x:midpointX, y:midpointY};
  9182. }
  9183. else {
  9184. point = this._pointOnLine(0.5);
  9185. }
  9186. ctx.arrow(point.x, point.y, angle, length);
  9187. ctx.fill();
  9188. ctx.stroke();
  9189. // draw label
  9190. if (this.label) {
  9191. this._label(ctx, this.label, point.x, point.y);
  9192. }
  9193. }
  9194. else {
  9195. // draw circle
  9196. var x, y;
  9197. var radius = 0.25 * Math.max(100,this.length);
  9198. var node = this.from;
  9199. if (!node.width) {
  9200. node.resize(ctx);
  9201. }
  9202. if (node.width > node.height) {
  9203. x = node.x + node.width * 0.5;
  9204. y = node.y - radius;
  9205. }
  9206. else {
  9207. x = node.x + radius;
  9208. y = node.y - node.height * 0.5;
  9209. }
  9210. this._circle(ctx, x, y, radius);
  9211. // draw all arrows
  9212. var angle = 0.2 * Math.PI;
  9213. var length = (10 + 5 * this.width) * this.arrowScaleFactor;
  9214. point = this._pointOnCircle(x, y, radius, 0.5);
  9215. ctx.arrow(point.x, point.y, angle, length);
  9216. ctx.fill();
  9217. ctx.stroke();
  9218. // draw label
  9219. if (this.label) {
  9220. point = this._pointOnCircle(x, y, radius, 0.5);
  9221. this._label(ctx, this.label, point.x, point.y);
  9222. }
  9223. }
  9224. };
  9225. /**
  9226. * Redraw a edge as a line with an arrow
  9227. * Draw this edge in the given canvas
  9228. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9229. * @param {CanvasRenderingContext2D} ctx
  9230. * @private
  9231. */
  9232. Edge.prototype._drawArrow = function(ctx) {
  9233. // set style
  9234. if (this.selected == true) {ctx.strokeStyle = this.color.highlight; ctx.fillStyle = this.color.highlight;}
  9235. else {ctx.strokeStyle = this.color.color; ctx.fillStyle = this.color.color;}
  9236. ctx.lineWidth = this._getLineWidth();
  9237. var angle, length;
  9238. //draw a line
  9239. if (this.from != this.to) {
  9240. angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  9241. var dx = (this.to.x - this.from.x);
  9242. var dy = (this.to.y - this.from.y);
  9243. var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  9244. var fromBorderDist = this.from.distanceToBorder(ctx, angle + Math.PI);
  9245. var fromBorderPoint = (edgeSegmentLength - fromBorderDist) / edgeSegmentLength;
  9246. var xFrom = (fromBorderPoint) * this.from.x + (1 - fromBorderPoint) * this.to.x;
  9247. var yFrom = (fromBorderPoint) * this.from.y + (1 - fromBorderPoint) * this.to.y;
  9248. if (this.smooth == true) {
  9249. angle = Math.atan2((this.to.y - this.via.y), (this.to.x - this.via.x));
  9250. dx = (this.to.x - this.via.x);
  9251. dy = (this.to.y - this.via.y);
  9252. edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  9253. }
  9254. var toBorderDist = this.to.distanceToBorder(ctx, angle);
  9255. var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength;
  9256. var xTo,yTo;
  9257. if (this.smooth == true) {
  9258. xTo = (1 - toBorderPoint) * this.via.x + toBorderPoint * this.to.x;
  9259. yTo = (1 - toBorderPoint) * this.via.y + toBorderPoint * this.to.y;
  9260. }
  9261. else {
  9262. xTo = (1 - toBorderPoint) * this.from.x + toBorderPoint * this.to.x;
  9263. yTo = (1 - toBorderPoint) * this.from.y + toBorderPoint * this.to.y;
  9264. }
  9265. ctx.beginPath();
  9266. ctx.moveTo(xFrom,yFrom);
  9267. if (this.smooth == true) {
  9268. ctx.quadraticCurveTo(this.via.x,this.via.y,xTo, yTo);
  9269. }
  9270. else {
  9271. ctx.lineTo(xTo, yTo);
  9272. }
  9273. ctx.stroke();
  9274. // draw arrow at the end of the line
  9275. length = (10 + 5 * this.width) * this.arrowScaleFactor;
  9276. ctx.arrow(xTo, yTo, angle, length);
  9277. ctx.fill();
  9278. ctx.stroke();
  9279. // draw label
  9280. if (this.label) {
  9281. var point;
  9282. if (this.smooth == true) {
  9283. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9284. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9285. point = {x:midpointX, y:midpointY};
  9286. }
  9287. else {
  9288. point = this._pointOnLine(0.5);
  9289. }
  9290. this._label(ctx, this.label, point.x, point.y);
  9291. }
  9292. }
  9293. else {
  9294. // draw circle
  9295. var node = this.from;
  9296. var x, y, arrow;
  9297. var radius = 0.25 * Math.max(100,this.length);
  9298. if (!node.width) {
  9299. node.resize(ctx);
  9300. }
  9301. if (node.width > node.height) {
  9302. x = node.x + node.width * 0.5;
  9303. y = node.y - radius;
  9304. arrow = {
  9305. x: x,
  9306. y: node.y,
  9307. angle: 0.9 * Math.PI
  9308. };
  9309. }
  9310. else {
  9311. x = node.x + radius;
  9312. y = node.y - node.height * 0.5;
  9313. arrow = {
  9314. x: node.x,
  9315. y: y,
  9316. angle: 0.6 * Math.PI
  9317. };
  9318. }
  9319. ctx.beginPath();
  9320. // TODO: similarly, for a line without arrows, draw to the border of the nodes instead of the center
  9321. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  9322. ctx.stroke();
  9323. // draw all arrows
  9324. var length = (10 + 5 * this.width) * this.arrowScaleFactor;
  9325. ctx.arrow(arrow.x, arrow.y, arrow.angle, length);
  9326. ctx.fill();
  9327. ctx.stroke();
  9328. // draw label
  9329. if (this.label) {
  9330. point = this._pointOnCircle(x, y, radius, 0.5);
  9331. this._label(ctx, this.label, point.x, point.y);
  9332. }
  9333. }
  9334. };
  9335. /**
  9336. * Calculate the distance between a point (x3,y3) and a line segment from
  9337. * (x1,y1) to (x2,y2).
  9338. * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
  9339. * @param {number} x1
  9340. * @param {number} y1
  9341. * @param {number} x2
  9342. * @param {number} y2
  9343. * @param {number} x3
  9344. * @param {number} y3
  9345. * @private
  9346. */
  9347. Edge.prototype._getDistanceToEdge = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is the point
  9348. if (this.smooth == true) {
  9349. var minDistance = 1e9;
  9350. var i,t,x,y,dx,dy;
  9351. for (i = 0; i < 10; i++) {
  9352. t = 0.1*i;
  9353. x = Math.pow(1-t,2)*x1 + (2*t*(1 - t))*this.via.x + Math.pow(t,2)*x2;
  9354. y = Math.pow(1-t,2)*y1 + (2*t*(1 - t))*this.via.y + Math.pow(t,2)*y2;
  9355. dx = Math.abs(x3-x);
  9356. dy = Math.abs(y3-y);
  9357. minDistance = Math.min(minDistance,Math.sqrt(dx*dx + dy*dy));
  9358. }
  9359. return minDistance
  9360. }
  9361. else {
  9362. var px = x2-x1,
  9363. py = y2-y1,
  9364. something = px*px + py*py,
  9365. u = ((x3 - x1) * px + (y3 - y1) * py) / something;
  9366. if (u > 1) {
  9367. u = 1;
  9368. }
  9369. else if (u < 0) {
  9370. u = 0;
  9371. }
  9372. var x = x1 + u * px,
  9373. y = y1 + u * py,
  9374. dx = x - x3,
  9375. dy = y - y3;
  9376. //# Note: If the actual distance does not matter,
  9377. //# if you only want to compare what this function
  9378. //# returns to other results of this function, you
  9379. //# can just return the squared distance instead
  9380. //# (i.e. remove the sqrt) to gain a little performance
  9381. return Math.sqrt(dx*dx + dy*dy);
  9382. }
  9383. };
  9384. /**
  9385. * This allows the zoom level of the graph to influence the rendering
  9386. *
  9387. * @param scale
  9388. */
  9389. Edge.prototype.setScale = function(scale) {
  9390. this.graphScaleInv = 1.0/scale;
  9391. };
  9392. Edge.prototype.select = function() {
  9393. this.selected = true;
  9394. };
  9395. Edge.prototype.unselect = function() {
  9396. this.selected = false;
  9397. };
  9398. Edge.prototype.positionBezierNode = function() {
  9399. if (this.via !== null) {
  9400. this.via.x = 0.5 * (this.from.x + this.to.x);
  9401. this.via.y = 0.5 * (this.from.y + this.to.y);
  9402. }
  9403. };
  9404. /**
  9405. * Popup is a class to create a popup window with some text
  9406. * @param {Element} container The container object.
  9407. * @param {Number} [x]
  9408. * @param {Number} [y]
  9409. * @param {String} [text]
  9410. * @param {Object} [style] An object containing borderColor,
  9411. * backgroundColor, etc.
  9412. */
  9413. function Popup(container, x, y, text, style) {
  9414. if (container) {
  9415. this.container = container;
  9416. }
  9417. else {
  9418. this.container = document.body;
  9419. }
  9420. // x, y and text are optional, see if a style object was passed in their place
  9421. if (style === undefined) {
  9422. if (typeof x === "object") {
  9423. style = x;
  9424. x = undefined;
  9425. } else if (typeof text === "object") {
  9426. style = text;
  9427. text = undefined;
  9428. } else {
  9429. // for backwards compatibility, in case clients other than Graph are creating Popup directly
  9430. style = {
  9431. fontColor: 'black',
  9432. fontSize: 14, // px
  9433. fontFace: 'verdana',
  9434. color: {
  9435. border: '#666',
  9436. background: '#FFFFC6'
  9437. }
  9438. }
  9439. }
  9440. }
  9441. this.x = 0;
  9442. this.y = 0;
  9443. this.padding = 5;
  9444. if (x !== undefined && y !== undefined ) {
  9445. this.setPosition(x, y);
  9446. }
  9447. if (text !== undefined) {
  9448. this.setText(text);
  9449. }
  9450. // create the frame
  9451. this.frame = document.createElement("div");
  9452. var styleAttr = this.frame.style;
  9453. styleAttr.position = "absolute";
  9454. styleAttr.visibility = "hidden";
  9455. styleAttr.border = "1px solid " + style.color.border;
  9456. styleAttr.color = style.fontColor;
  9457. styleAttr.fontSize = style.fontSize + "px";
  9458. styleAttr.fontFamily = style.fontFace;
  9459. styleAttr.padding = this.padding + "px";
  9460. styleAttr.backgroundColor = style.color.background;
  9461. styleAttr.borderRadius = "3px";
  9462. styleAttr.MozBorderRadius = "3px";
  9463. styleAttr.WebkitBorderRadius = "3px";
  9464. styleAttr.boxShadow = "3px 3px 10px rgba(128, 128, 128, 0.5)";
  9465. styleAttr.whiteSpace = "nowrap";
  9466. this.container.appendChild(this.frame);
  9467. }
  9468. /**
  9469. * @param {number} x Horizontal position of the popup window
  9470. * @param {number} y Vertical position of the popup window
  9471. */
  9472. Popup.prototype.setPosition = function(x, y) {
  9473. this.x = parseInt(x);
  9474. this.y = parseInt(y);
  9475. };
  9476. /**
  9477. * Set the text for the popup window. This can be HTML code
  9478. * @param {string} text
  9479. */
  9480. Popup.prototype.setText = function(text) {
  9481. this.frame.innerHTML = text;
  9482. };
  9483. /**
  9484. * Show the popup window
  9485. * @param {boolean} show Optional. Show or hide the window
  9486. */
  9487. Popup.prototype.show = function (show) {
  9488. if (show === undefined) {
  9489. show = true;
  9490. }
  9491. if (show) {
  9492. var height = this.frame.clientHeight;
  9493. var width = this.frame.clientWidth;
  9494. var maxHeight = this.frame.parentNode.clientHeight;
  9495. var maxWidth = this.frame.parentNode.clientWidth;
  9496. var top = (this.y - height);
  9497. if (top + height + this.padding > maxHeight) {
  9498. top = maxHeight - height - this.padding;
  9499. }
  9500. if (top < this.padding) {
  9501. top = this.padding;
  9502. }
  9503. var left = this.x;
  9504. if (left + width + this.padding > maxWidth) {
  9505. left = maxWidth - width - this.padding;
  9506. }
  9507. if (left < this.padding) {
  9508. left = this.padding;
  9509. }
  9510. this.frame.style.left = left + "px";
  9511. this.frame.style.top = top + "px";
  9512. this.frame.style.visibility = "visible";
  9513. }
  9514. else {
  9515. this.hide();
  9516. }
  9517. };
  9518. /**
  9519. * Hide the popup window
  9520. */
  9521. Popup.prototype.hide = function () {
  9522. this.frame.style.visibility = "hidden";
  9523. };
  9524. /**
  9525. * @class Groups
  9526. * This class can store groups and properties specific for groups.
  9527. */
  9528. function Groups() {
  9529. this.clear();
  9530. this.defaultIndex = 0;
  9531. }
  9532. /**
  9533. * default constants for group colors
  9534. */
  9535. Groups.DEFAULT = [
  9536. {border: "#2B7CE9", background: "#97C2FC", highlight: {border: "#2B7CE9", background: "#D2E5FF"}}, // blue
  9537. {border: "#FFA500", background: "#FFFF00", highlight: {border: "#FFA500", background: "#FFFFA3"}}, // yellow
  9538. {border: "#FA0A10", background: "#FB7E81", highlight: {border: "#FA0A10", background: "#FFAFB1"}}, // red
  9539. {border: "#41A906", background: "#7BE141", highlight: {border: "#41A906", background: "#A1EC76"}}, // green
  9540. {border: "#E129F0", background: "#EB7DF4", highlight: {border: "#E129F0", background: "#F0B3F5"}}, // magenta
  9541. {border: "#7C29F0", background: "#AD85E4", highlight: {border: "#7C29F0", background: "#D3BDF0"}}, // purple
  9542. {border: "#C37F00", background: "#FFA807", highlight: {border: "#C37F00", background: "#FFCA66"}}, // orange
  9543. {border: "#4220FB", background: "#6E6EFD", highlight: {border: "#4220FB", background: "#9B9BFD"}}, // darkblue
  9544. {border: "#FD5A77", background: "#FFC0CB", highlight: {border: "#FD5A77", background: "#FFD1D9"}}, // pink
  9545. {border: "#4AD63A", background: "#C2FABC", highlight: {border: "#4AD63A", background: "#E6FFE3"}} // mint
  9546. ];
  9547. /**
  9548. * Clear all groups
  9549. */
  9550. Groups.prototype.clear = function () {
  9551. this.groups = {};
  9552. this.groups.length = function()
  9553. {
  9554. var i = 0;
  9555. for ( var p in this ) {
  9556. if (this.hasOwnProperty(p)) {
  9557. i++;
  9558. }
  9559. }
  9560. return i;
  9561. }
  9562. };
  9563. /**
  9564. * get group properties of a groupname. If groupname is not found, a new group
  9565. * is added.
  9566. * @param {*} groupname Can be a number, string, Date, etc.
  9567. * @return {Object} group The created group, containing all group properties
  9568. */
  9569. Groups.prototype.get = function (groupname) {
  9570. var group = this.groups[groupname];
  9571. if (group == undefined) {
  9572. // create new group
  9573. var index = this.defaultIndex % Groups.DEFAULT.length;
  9574. this.defaultIndex++;
  9575. group = {};
  9576. group.color = Groups.DEFAULT[index];
  9577. this.groups[groupname] = group;
  9578. }
  9579. return group;
  9580. };
  9581. /**
  9582. * Add a custom group style
  9583. * @param {String} groupname
  9584. * @param {Object} style An object containing borderColor,
  9585. * backgroundColor, etc.
  9586. * @return {Object} group The created group object
  9587. */
  9588. Groups.prototype.add = function (groupname, style) {
  9589. this.groups[groupname] = style;
  9590. if (style.color) {
  9591. style.color = util.parseColor(style.color);
  9592. }
  9593. return style;
  9594. };
  9595. /**
  9596. * @class Images
  9597. * This class loads images and keeps them stored.
  9598. */
  9599. function Images() {
  9600. this.images = {};
  9601. this.callback = undefined;
  9602. }
  9603. /**
  9604. * Set an onload callback function. This will be called each time an image
  9605. * is loaded
  9606. * @param {function} callback
  9607. */
  9608. Images.prototype.setOnloadCallback = function(callback) {
  9609. this.callback = callback;
  9610. };
  9611. /**
  9612. *
  9613. * @param {string} url Url of the image
  9614. * @return {Image} img The image object
  9615. */
  9616. Images.prototype.load = function(url) {
  9617. var img = this.images[url];
  9618. if (img == undefined) {
  9619. // create the image
  9620. var images = this;
  9621. img = new Image();
  9622. this.images[url] = img;
  9623. img.onload = function() {
  9624. if (images.callback) {
  9625. images.callback(this);
  9626. }
  9627. };
  9628. img.src = url;
  9629. }
  9630. return img;
  9631. };
  9632. /**
  9633. * Created by Alex on 2/6/14.
  9634. */
  9635. var physicsMixin = {
  9636. /**
  9637. * Toggling barnes Hut calculation on and off.
  9638. *
  9639. * @private
  9640. */
  9641. _toggleBarnesHut: function () {
  9642. this.constants.physics.barnesHut.enabled = !this.constants.physics.barnesHut.enabled;
  9643. this._loadSelectedForceSolver();
  9644. this.moving = true;
  9645. this.start();
  9646. },
  9647. /**
  9648. * This loads the node force solver based on the barnes hut or repulsion algorithm
  9649. *
  9650. * @private
  9651. */
  9652. _loadSelectedForceSolver: function () {
  9653. // this overloads the this._calculateNodeForces
  9654. if (this.constants.physics.barnesHut.enabled == true) {
  9655. this._clearMixin(repulsionMixin);
  9656. this._clearMixin(hierarchalRepulsionMixin);
  9657. this.constants.physics.centralGravity = this.constants.physics.barnesHut.centralGravity;
  9658. this.constants.physics.springLength = this.constants.physics.barnesHut.springLength;
  9659. this.constants.physics.springConstant = this.constants.physics.barnesHut.springConstant;
  9660. this.constants.physics.damping = this.constants.physics.barnesHut.damping;
  9661. this._loadMixin(barnesHutMixin);
  9662. }
  9663. else if (this.constants.physics.hierarchicalRepulsion.enabled == true) {
  9664. this._clearMixin(barnesHutMixin);
  9665. this._clearMixin(repulsionMixin);
  9666. this.constants.physics.centralGravity = this.constants.physics.hierarchicalRepulsion.centralGravity;
  9667. this.constants.physics.springLength = this.constants.physics.hierarchicalRepulsion.springLength;
  9668. this.constants.physics.springConstant = this.constants.physics.hierarchicalRepulsion.springConstant;
  9669. this.constants.physics.damping = this.constants.physics.hierarchicalRepulsion.damping;
  9670. this._loadMixin(hierarchalRepulsionMixin);
  9671. }
  9672. else {
  9673. this._clearMixin(barnesHutMixin);
  9674. this._clearMixin(hierarchalRepulsionMixin);
  9675. this.barnesHutTree = undefined;
  9676. this.constants.physics.centralGravity = this.constants.physics.repulsion.centralGravity;
  9677. this.constants.physics.springLength = this.constants.physics.repulsion.springLength;
  9678. this.constants.physics.springConstant = this.constants.physics.repulsion.springConstant;
  9679. this.constants.physics.damping = this.constants.physics.repulsion.damping;
  9680. this._loadMixin(repulsionMixin);
  9681. }
  9682. },
  9683. /**
  9684. * Before calculating the forces, we check if we need to cluster to keep up performance and we check
  9685. * if there is more than one node. If it is just one node, we dont calculate anything.
  9686. *
  9687. * @private
  9688. */
  9689. _initializeForceCalculation: function () {
  9690. // stop calculation if there is only one node
  9691. if (this.nodeIndices.length == 1) {
  9692. this.nodes[this.nodeIndices[0]]._setForce(0, 0);
  9693. }
  9694. else {
  9695. // if there are too many nodes on screen, we cluster without repositioning
  9696. if (this.nodeIndices.length > this.constants.clustering.clusterThreshold && this.constants.clustering.enabled == true) {
  9697. this.clusterToFit(this.constants.clustering.reduceToNodes, false);
  9698. }
  9699. // we now start the force calculation
  9700. this._calculateForces();
  9701. }
  9702. },
  9703. /**
  9704. * Calculate the external forces acting on the nodes
  9705. * Forces are caused by: edges, repulsing forces between nodes, gravity
  9706. * @private
  9707. */
  9708. _calculateForces: function () {
  9709. // Gravity is required to keep separated groups from floating off
  9710. // the forces are reset to zero in this loop by using _setForce instead
  9711. // of _addForce
  9712. this._calculateGravitationalForces();
  9713. this._calculateNodeForces();
  9714. if (this.constants.smoothCurves == true) {
  9715. this._calculateSpringForcesWithSupport();
  9716. }
  9717. else {
  9718. this._calculateSpringForces();
  9719. }
  9720. },
  9721. /**
  9722. * Smooth curves are created by adding invisible nodes in the center of the edges. These nodes are also
  9723. * handled in the calculateForces function. We then use a quadratic curve with the center node as control.
  9724. * This function joins the datanodes and invisible (called support) nodes into one object.
  9725. * We do this so we do not contaminate this.nodes with the support nodes.
  9726. *
  9727. * @private
  9728. */
  9729. _updateCalculationNodes: function () {
  9730. if (this.constants.smoothCurves == true) {
  9731. this.calculationNodes = {};
  9732. this.calculationNodeIndices = [];
  9733. for (var nodeId in this.nodes) {
  9734. if (this.nodes.hasOwnProperty(nodeId)) {
  9735. this.calculationNodes[nodeId] = this.nodes[nodeId];
  9736. }
  9737. }
  9738. var supportNodes = this.sectors['support']['nodes'];
  9739. for (var supportNodeId in supportNodes) {
  9740. if (supportNodes.hasOwnProperty(supportNodeId)) {
  9741. if (this.edges.hasOwnProperty(supportNodes[supportNodeId].parentEdgeId)) {
  9742. this.calculationNodes[supportNodeId] = supportNodes[supportNodeId];
  9743. }
  9744. else {
  9745. supportNodes[supportNodeId]._setForce(0, 0);
  9746. }
  9747. }
  9748. }
  9749. for (var idx in this.calculationNodes) {
  9750. if (this.calculationNodes.hasOwnProperty(idx)) {
  9751. this.calculationNodeIndices.push(idx);
  9752. }
  9753. }
  9754. }
  9755. else {
  9756. this.calculationNodes = this.nodes;
  9757. this.calculationNodeIndices = this.nodeIndices;
  9758. }
  9759. },
  9760. /**
  9761. * this function applies the central gravity effect to keep groups from floating off
  9762. *
  9763. * @private
  9764. */
  9765. _calculateGravitationalForces: function () {
  9766. var dx, dy, distance, node, i;
  9767. var nodes = this.calculationNodes;
  9768. var gravity = this.constants.physics.centralGravity;
  9769. var gravityForce = 0;
  9770. for (i = 0; i < this.calculationNodeIndices.length; i++) {
  9771. node = nodes[this.calculationNodeIndices[i]];
  9772. node.damping = this.constants.physics.damping; // possibly add function to alter damping properties of clusters.
  9773. // gravity does not apply when we are in a pocket sector
  9774. if (this._sector() == "default" && gravity != 0) {
  9775. dx = -node.x;
  9776. dy = -node.y;
  9777. distance = Math.sqrt(dx * dx + dy * dy);
  9778. gravityForce = (distance == 0) ? 0 : (gravity / distance);
  9779. node.fx = dx * gravityForce;
  9780. node.fy = dy * gravityForce;
  9781. }
  9782. else {
  9783. node.fx = 0;
  9784. node.fy = 0;
  9785. }
  9786. }
  9787. },
  9788. /**
  9789. * this function calculates the effects of the springs in the case of unsmooth curves.
  9790. *
  9791. * @private
  9792. */
  9793. _calculateSpringForces: function () {
  9794. var edgeLength, edge, edgeId;
  9795. var dx, dy, fx, fy, springForce, distance;
  9796. var edges = this.edges;
  9797. // forces caused by the edges, modelled as springs
  9798. for (edgeId in edges) {
  9799. if (edges.hasOwnProperty(edgeId)) {
  9800. edge = edges[edgeId];
  9801. if (edge.connected) {
  9802. // only calculate forces if nodes are in the same sector
  9803. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  9804. edgeLength = edge.customLength ? edge.length : this.constants.physics.springLength;
  9805. // this implies that the edges between big clusters are longer
  9806. edgeLength += (edge.to.clusterSize + edge.from.clusterSize - 2) * this.constants.clustering.edgeGrowth;
  9807. dx = (edge.from.x - edge.to.x);
  9808. dy = (edge.from.y - edge.to.y);
  9809. distance = Math.sqrt(dx * dx + dy * dy);
  9810. if (distance == 0) {
  9811. distance = 0.01;
  9812. }
  9813. // the 1/distance is so the fx and fy can be calculated without sine or cosine.
  9814. springForce = this.constants.physics.springConstant * (edgeLength - distance) / distance;
  9815. fx = dx * springForce;
  9816. fy = dy * springForce;
  9817. edge.from.fx += fx;
  9818. edge.from.fy += fy;
  9819. edge.to.fx -= fx;
  9820. edge.to.fy -= fy;
  9821. }
  9822. }
  9823. }
  9824. }
  9825. },
  9826. /**
  9827. * This function calculates the springforces on the nodes, accounting for the support nodes.
  9828. *
  9829. * @private
  9830. */
  9831. _calculateSpringForcesWithSupport: function () {
  9832. var edgeLength, edge, edgeId, combinedClusterSize;
  9833. var edges = this.edges;
  9834. // forces caused by the edges, modelled as springs
  9835. for (edgeId in edges) {
  9836. if (edges.hasOwnProperty(edgeId)) {
  9837. edge = edges[edgeId];
  9838. if (edge.connected) {
  9839. // only calculate forces if nodes are in the same sector
  9840. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  9841. if (edge.via != null) {
  9842. var node1 = edge.to;
  9843. var node2 = edge.via;
  9844. var node3 = edge.from;
  9845. edgeLength = edge.customLength ? edge.length : this.constants.physics.springLength;
  9846. combinedClusterSize = node1.clusterSize + node3.clusterSize - 2;
  9847. // this implies that the edges between big clusters are longer
  9848. edgeLength += combinedClusterSize * this.constants.clustering.edgeGrowth;
  9849. this._calculateSpringForce(node1, node2, 0.5 * edgeLength);
  9850. this._calculateSpringForce(node2, node3, 0.5 * edgeLength);
  9851. }
  9852. }
  9853. }
  9854. }
  9855. }
  9856. },
  9857. /**
  9858. * This is the code actually performing the calculation for the function above. It is split out to avoid repetition.
  9859. *
  9860. * @param node1
  9861. * @param node2
  9862. * @param edgeLength
  9863. * @private
  9864. */
  9865. _calculateSpringForce: function (node1, node2, edgeLength) {
  9866. var dx, dy, fx, fy, springForce, distance;
  9867. dx = (node1.x - node2.x);
  9868. dy = (node1.y - node2.y);
  9869. distance = Math.sqrt(dx * dx + dy * dy);
  9870. if (distance == 0) {
  9871. distance = 0.01;
  9872. }
  9873. // the 1/distance is so the fx and fy can be calculated without sine or cosine.
  9874. springForce = this.constants.physics.springConstant * (edgeLength - distance) / distance;
  9875. fx = dx * springForce;
  9876. fy = dy * springForce;
  9877. node1.fx += fx;
  9878. node1.fy += fy;
  9879. node2.fx -= fx;
  9880. node2.fy -= fy;
  9881. },
  9882. /**
  9883. * Load the HTML for the physics config and bind it
  9884. * @private
  9885. */
  9886. _loadPhysicsConfiguration: function () {
  9887. if (this.physicsConfiguration === undefined) {
  9888. this.backupConstants = {};
  9889. util.copyObject(this.constants, this.backupConstants);
  9890. var hierarchicalLayoutDirections = ["LR", "RL", "UD", "DU"];
  9891. this.physicsConfiguration = document.createElement('div');
  9892. this.physicsConfiguration.className = "PhysicsConfiguration";
  9893. this.physicsConfiguration.innerHTML = '' +
  9894. '<table><tr><td><b>Simulation Mode:</b></td></tr>' +
  9895. '<tr>' +
  9896. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod1" value="BH" checked="checked">Barnes Hut</td>' +
  9897. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod2" value="R">Repulsion</td>' +
  9898. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod3" value="H">Hierarchical</td>' +
  9899. '</tr>' +
  9900. '</table>' +
  9901. '<table id="graph_BH_table" style="display:none">' +
  9902. '<tr><td><b>Barnes Hut</b></td></tr>' +
  9903. '<tr>' +
  9904. '<td width="150px">gravitationalConstant</td><td>0</td><td><input type="range" min="0" 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>' +
  9905. '</tr>' +
  9906. '<tr>' +
  9907. '<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>' +
  9908. '</tr>' +
  9909. '<tr>' +
  9910. '<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>' +
  9911. '</tr>' +
  9912. '<tr>' +
  9913. '<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>' +
  9914. '</tr>' +
  9915. '<tr>' +
  9916. '<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>' +
  9917. '</tr>' +
  9918. '</table>' +
  9919. '<table id="graph_R_table" style="display:none">' +
  9920. '<tr><td><b>Repulsion</b></td></tr>' +
  9921. '<tr>' +
  9922. '<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>' +
  9923. '</tr>' +
  9924. '<tr>' +
  9925. '<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>' +
  9926. '</tr>' +
  9927. '<tr>' +
  9928. '<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>' +
  9929. '</tr>' +
  9930. '<tr>' +
  9931. '<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>' +
  9932. '</tr>' +
  9933. '<tr>' +
  9934. '<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>' +
  9935. '</tr>' +
  9936. '</table>' +
  9937. '<table id="graph_H_table" style="display:none">' +
  9938. '<tr><td width="150"><b>Hierarchical</b></td></tr>' +
  9939. '<tr>' +
  9940. '<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>' +
  9941. '</tr>' +
  9942. '<tr>' +
  9943. '<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>' +
  9944. '</tr>' +
  9945. '<tr>' +
  9946. '<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>' +
  9947. '</tr>' +
  9948. '<tr>' +
  9949. '<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>' +
  9950. '</tr>' +
  9951. '<tr>' +
  9952. '<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>' +
  9953. '</tr>' +
  9954. '<tr>' +
  9955. '<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>' +
  9956. '</tr>' +
  9957. '<tr>' +
  9958. '<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>' +
  9959. '</tr>' +
  9960. '<tr>' +
  9961. '<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>' +
  9962. '</tr>' +
  9963. '</table>' +
  9964. '<table><tr><td><b>Options:</b></td></tr>' +
  9965. '<tr>' +
  9966. '<td width="180px"><input type="button" id="graph_toggleSmooth" value="Toggle smoothCurves" style="width:150px"></td>' +
  9967. '<td width="180px"><input type="button" id="graph_repositionNodes" value="Reinitialize" style="width:150px"></td>' +
  9968. '<td width="180px"><input type="button" id="graph_generateOptions" value="Generate Options" style="width:150px"></td>' +
  9969. '</tr>' +
  9970. '</table>'
  9971. this.containerElement.parentElement.insertBefore(this.physicsConfiguration, this.containerElement);
  9972. this.optionsDiv = document.createElement("div");
  9973. this.optionsDiv.style.fontSize = "14px";
  9974. this.optionsDiv.style.fontFamily = "verdana";
  9975. this.containerElement.parentElement.insertBefore(this.optionsDiv, this.containerElement);
  9976. var rangeElement;
  9977. rangeElement = document.getElementById('graph_BH_gc');
  9978. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_gc', -1, "physics_barnesHut_gravitationalConstant");
  9979. rangeElement = document.getElementById('graph_BH_cg');
  9980. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_cg', 1, "physics_centralGravity");
  9981. rangeElement = document.getElementById('graph_BH_sc');
  9982. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_sc', 1, "physics_springConstant");
  9983. rangeElement = document.getElementById('graph_BH_sl');
  9984. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_sl', 1, "physics_springLength");
  9985. rangeElement = document.getElementById('graph_BH_damp');
  9986. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_damp', 1, "physics_damping");
  9987. rangeElement = document.getElementById('graph_R_nd');
  9988. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_nd', 1, "physics_repulsion_nodeDistance");
  9989. rangeElement = document.getElementById('graph_R_cg');
  9990. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_cg', 1, "physics_centralGravity");
  9991. rangeElement = document.getElementById('graph_R_sc');
  9992. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_sc', 1, "physics_springConstant");
  9993. rangeElement = document.getElementById('graph_R_sl');
  9994. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_sl', 1, "physics_springLength");
  9995. rangeElement = document.getElementById('graph_R_damp');
  9996. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_damp', 1, "physics_damping");
  9997. rangeElement = document.getElementById('graph_H_nd');
  9998. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_nd', 1, "physics_hierarchicalRepulsion_nodeDistance");
  9999. rangeElement = document.getElementById('graph_H_cg');
  10000. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_cg', 1, "physics_centralGravity");
  10001. rangeElement = document.getElementById('graph_H_sc');
  10002. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_sc', 1, "physics_springConstant");
  10003. rangeElement = document.getElementById('graph_H_sl');
  10004. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_sl', 1, "physics_springLength");
  10005. rangeElement = document.getElementById('graph_H_damp');
  10006. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_damp', 1, "physics_damping");
  10007. rangeElement = document.getElementById('graph_H_direction');
  10008. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_direction', hierarchicalLayoutDirections, "hierarchicalLayout_direction");
  10009. rangeElement = document.getElementById('graph_H_levsep');
  10010. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_levsep', 1, "hierarchicalLayout_levelSeparation");
  10011. rangeElement = document.getElementById('graph_H_nspac');
  10012. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_nspac', 1, "hierarchicalLayout_nodeSpacing");
  10013. var radioButton1 = document.getElementById("graph_physicsMethod1");
  10014. var radioButton2 = document.getElementById("graph_physicsMethod2");
  10015. var radioButton3 = document.getElementById("graph_physicsMethod3");
  10016. radioButton2.checked = true;
  10017. if (this.constants.physics.barnesHut.enabled) {
  10018. radioButton1.checked = true;
  10019. }
  10020. if (this.constants.hierarchicalLayout.enabled) {
  10021. radioButton3.checked = true;
  10022. }
  10023. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  10024. var graph_repositionNodes = document.getElementById("graph_repositionNodes");
  10025. var graph_generateOptions = document.getElementById("graph_generateOptions");
  10026. graph_toggleSmooth.onclick = graphToggleSmoothCurves.bind(this);
  10027. graph_repositionNodes.onclick = graphRepositionNodes.bind(this);
  10028. graph_generateOptions.onclick = graphGenerateOptions.bind(this);
  10029. if (this.constants.smoothCurves == true) {
  10030. graph_toggleSmooth.style.background = "#A4FF56";
  10031. }
  10032. else {
  10033. graph_toggleSmooth.style.background = "#FF8532";
  10034. }
  10035. switchConfigurations.apply(this);
  10036. radioButton1.onchange = switchConfigurations.bind(this);
  10037. radioButton2.onchange = switchConfigurations.bind(this);
  10038. radioButton3.onchange = switchConfigurations.bind(this);
  10039. }
  10040. },
  10041. /**
  10042. * This overwrites the this.constants.
  10043. *
  10044. * @param constantsVariableName
  10045. * @param value
  10046. * @private
  10047. */
  10048. _overWriteGraphConstants: function (constantsVariableName, value) {
  10049. var nameArray = constantsVariableName.split("_");
  10050. if (nameArray.length == 1) {
  10051. this.constants[nameArray[0]] = value;
  10052. }
  10053. else if (nameArray.length == 2) {
  10054. this.constants[nameArray[0]][nameArray[1]] = value;
  10055. }
  10056. else if (nameArray.length == 3) {
  10057. this.constants[nameArray[0]][nameArray[1]][nameArray[2]] = value;
  10058. }
  10059. }
  10060. };
  10061. /**
  10062. * this function is bound to the toggle smooth curves button. That is also why it is not in the prototype.
  10063. */
  10064. function graphToggleSmoothCurves () {
  10065. this.constants.smoothCurves = !this.constants.smoothCurves;
  10066. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  10067. if (this.constants.smoothCurves == true) {graph_toggleSmooth.style.background = "#A4FF56";}
  10068. else {graph_toggleSmooth.style.background = "#FF8532";}
  10069. this._configureSmoothCurves(false);
  10070. };
  10071. /**
  10072. * this function is used to scramble the nodes
  10073. *
  10074. */
  10075. function graphRepositionNodes () {
  10076. for (var nodeId in this.calculationNodes) {
  10077. if (this.calculationNodes.hasOwnProperty(nodeId)) {
  10078. this.calculationNodes[nodeId].vx = 0; this.calculationNodes[nodeId].vy = 0;
  10079. this.calculationNodes[nodeId].fx = 0; this.calculationNodes[nodeId].fy = 0;
  10080. }
  10081. }
  10082. if (this.constants.hierarchicalLayout.enabled == true) {
  10083. this._setupHierarchicalLayout();
  10084. }
  10085. else {
  10086. this.repositionNodes();
  10087. }
  10088. this.moving = true;
  10089. this.start();
  10090. };
  10091. /**
  10092. * this is used to generate an options file from the playing with physics system.
  10093. */
  10094. function graphGenerateOptions () {
  10095. var options = "No options are required, default values used.";
  10096. var optionsSpecific = [];
  10097. var radioButton1 = document.getElementById("graph_physicsMethod1");
  10098. var radioButton2 = document.getElementById("graph_physicsMethod2");
  10099. if (radioButton1.checked == true) {
  10100. if (this.constants.physics.barnesHut.gravitationalConstant != this.backupConstants.physics.barnesHut.gravitationalConstant) {optionsSpecific.push("gravitationalConstant: " + this.constants.physics.barnesHut.gravitationalConstant);}
  10101. if (this.constants.physics.centralGravity != this.backupConstants.physics.barnesHut.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  10102. if (this.constants.physics.springLength != this.backupConstants.physics.barnesHut.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  10103. if (this.constants.physics.springConstant != this.backupConstants.physics.barnesHut.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  10104. if (this.constants.physics.damping != this.backupConstants.physics.barnesHut.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  10105. if (optionsSpecific.length != 0) {
  10106. options = "var options = {";
  10107. options += "physics: {barnesHut: {";
  10108. for (var i = 0; i < optionsSpecific.length; i++) {
  10109. options += optionsSpecific[i];
  10110. if (i < optionsSpecific.length - 1) {
  10111. options += ", "
  10112. }
  10113. }
  10114. options += '}}'
  10115. }
  10116. if (this.constants.smoothCurves != this.backupConstants.smoothCurves) {
  10117. if (optionsSpecific.length == 0) {options = "var options = {";}
  10118. else {options += ", "}
  10119. options += "smoothCurves: " + this.constants.smoothCurves;
  10120. }
  10121. if (options != "No options are required, default values used.") {
  10122. options += '};'
  10123. }
  10124. }
  10125. else if (radioButton2.checked == true) {
  10126. options = "var options = {";
  10127. options += "physics: {barnesHut: {enabled: false}";
  10128. if (this.constants.physics.repulsion.nodeDistance != this.backupConstants.physics.repulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.repulsion.nodeDistance);}
  10129. if (this.constants.physics.centralGravity != this.backupConstants.physics.repulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  10130. if (this.constants.physics.springLength != this.backupConstants.physics.repulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  10131. if (this.constants.physics.springConstant != this.backupConstants.physics.repulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  10132. if (this.constants.physics.damping != this.backupConstants.physics.repulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  10133. if (optionsSpecific.length != 0) {
  10134. options += ", repulsion: {";
  10135. for (var i = 0; i < optionsSpecific.length; i++) {
  10136. options += optionsSpecific[i];
  10137. if (i < optionsSpecific.length - 1) {
  10138. options += ", "
  10139. }
  10140. }
  10141. options += '}}'
  10142. }
  10143. if (optionsSpecific.length == 0) {options += "}"}
  10144. if (this.constants.smoothCurves != this.backupConstants.smoothCurves) {
  10145. options += ", smoothCurves: " + this.constants.smoothCurves;
  10146. }
  10147. options += '};'
  10148. }
  10149. else {
  10150. options = "var options = {";
  10151. if (this.constants.physics.hierarchicalRepulsion.nodeDistance != this.backupConstants.physics.hierarchicalRepulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.hierarchicalRepulsion.nodeDistance);}
  10152. if (this.constants.physics.centralGravity != this.backupConstants.physics.hierarchicalRepulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  10153. if (this.constants.physics.springLength != this.backupConstants.physics.hierarchicalRepulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  10154. if (this.constants.physics.springConstant != this.backupConstants.physics.hierarchicalRepulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  10155. if (this.constants.physics.damping != this.backupConstants.physics.hierarchicalRepulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  10156. if (optionsSpecific.length != 0) {
  10157. options += "physics: {hierarchicalRepulsion: {";
  10158. for (var i = 0; i < optionsSpecific.length; i++) {
  10159. options += optionsSpecific[i];
  10160. if (i < optionsSpecific.length - 1) {
  10161. options += ", ";
  10162. }
  10163. }
  10164. options += '}},';
  10165. }
  10166. options += 'hierarchicalLayout: {';
  10167. optionsSpecific = [];
  10168. if (this.constants.hierarchicalLayout.direction != this.backupConstants.hierarchicalLayout.direction) {optionsSpecific.push("direction: " + this.constants.hierarchicalLayout.direction);}
  10169. if (Math.abs(this.constants.hierarchicalLayout.levelSeparation) != this.backupConstants.hierarchicalLayout.levelSeparation) {optionsSpecific.push("levelSeparation: " + this.constants.hierarchicalLayout.levelSeparation);}
  10170. if (this.constants.hierarchicalLayout.nodeSpacing != this.backupConstants.hierarchicalLayout.nodeSpacing) {optionsSpecific.push("nodeSpacing: " + this.constants.hierarchicalLayout.nodeSpacing);}
  10171. if (optionsSpecific.length != 0) {
  10172. for (var i = 0; i < optionsSpecific.length; i++) {
  10173. options += optionsSpecific[i];
  10174. if (i < optionsSpecific.length - 1) {
  10175. options += ", "
  10176. }
  10177. }
  10178. options += '}'
  10179. }
  10180. else {
  10181. options += "enabled:true}";
  10182. }
  10183. options += '};'
  10184. }
  10185. this.optionsDiv.innerHTML = options;
  10186. };
  10187. /**
  10188. * this is used to switch between barnesHut, repulsion and hierarchical.
  10189. *
  10190. */
  10191. function switchConfigurations () {
  10192. var ids = ["graph_BH_table", "graph_R_table", "graph_H_table"];
  10193. var radioButton = document.querySelector('input[name="graph_physicsMethod"]:checked').value;
  10194. var tableId = "graph_" + radioButton + "_table";
  10195. var table = document.getElementById(tableId);
  10196. table.style.display = "block";
  10197. for (var i = 0; i < ids.length; i++) {
  10198. if (ids[i] != tableId) {
  10199. table = document.getElementById(ids[i]);
  10200. table.style.display = "none";
  10201. }
  10202. }
  10203. this._restoreNodes();
  10204. if (radioButton == "R") {
  10205. this.constants.hierarchicalLayout.enabled = false;
  10206. this.constants.physics.hierarchicalRepulsion.enabled = false;
  10207. this.constants.physics.barnesHut.enabled = false;
  10208. }
  10209. else if (radioButton == "H") {
  10210. if (this.constants.hierarchicalLayout.enabled == false) {
  10211. this.constants.hierarchicalLayout.enabled = true;
  10212. this.constants.physics.hierarchicalRepulsion.enabled = true;
  10213. this.constants.physics.barnesHut.enabled = false;
  10214. this._setupHierarchicalLayout();
  10215. }
  10216. }
  10217. else {
  10218. this.constants.hierarchicalLayout.enabled = false;
  10219. this.constants.physics.hierarchicalRepulsion.enabled = false;
  10220. this.constants.physics.barnesHut.enabled = true;
  10221. }
  10222. this._loadSelectedForceSolver();
  10223. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  10224. if (this.constants.smoothCurves == true) {graph_toggleSmooth.style.background = "#A4FF56";}
  10225. else {graph_toggleSmooth.style.background = "#FF8532";}
  10226. this.moving = true;
  10227. this.start();
  10228. }
  10229. /**
  10230. * this generates the ranges depending on the iniital values.
  10231. *
  10232. * @param id
  10233. * @param map
  10234. * @param constantsVariableName
  10235. */
  10236. function showValueOfRange (id,map,constantsVariableName) {
  10237. var valueId = id + "_value";
  10238. var rangeValue = document.getElementById(id).value;
  10239. if (map instanceof Array) {
  10240. document.getElementById(valueId).value = map[parseInt(rangeValue)];
  10241. this._overWriteGraphConstants(constantsVariableName,map[parseInt(rangeValue)]);
  10242. }
  10243. else {
  10244. document.getElementById(valueId).value = parseInt(map) * parseFloat(rangeValue);
  10245. this._overWriteGraphConstants(constantsVariableName, parseInt(map) * parseFloat(rangeValue));
  10246. }
  10247. if (constantsVariableName == "hierarchicalLayout_direction" ||
  10248. constantsVariableName == "hierarchicalLayout_levelSeparation" ||
  10249. constantsVariableName == "hierarchicalLayout_nodeSpacing") {
  10250. this._setupHierarchicalLayout();
  10251. }
  10252. this.moving = true;
  10253. this.start();
  10254. };
  10255. /**
  10256. * Created by Alex on 2/10/14.
  10257. */
  10258. var hierarchalRepulsionMixin = {
  10259. /**
  10260. * Calculate the forces the nodes apply on eachother based on a repulsion field.
  10261. * This field is linearly approximated.
  10262. *
  10263. * @private
  10264. */
  10265. _calculateNodeForces: function () {
  10266. var dx, dy, distance, fx, fy, combinedClusterSize,
  10267. repulsingForce, node1, node2, i, j;
  10268. var nodes = this.calculationNodes;
  10269. var nodeIndices = this.calculationNodeIndices;
  10270. // approximation constants
  10271. var b = 5;
  10272. var a_base = 0.5 * -b;
  10273. // repulsing forces between nodes
  10274. var nodeDistance = this.constants.physics.hierarchicalRepulsion.nodeDistance;
  10275. var minimumDistance = nodeDistance;
  10276. // we loop from i over all but the last entree in the array
  10277. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  10278. for (i = 0; i < nodeIndices.length - 1; i++) {
  10279. node1 = nodes[nodeIndices[i]];
  10280. for (j = i + 1; j < nodeIndices.length; j++) {
  10281. node2 = nodes[nodeIndices[j]];
  10282. dx = node2.x - node1.x;
  10283. dy = node2.y - node1.y;
  10284. distance = Math.sqrt(dx * dx + dy * dy);
  10285. var a = a_base / minimumDistance;
  10286. if (distance < 2 * minimumDistance) {
  10287. repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness))
  10288. // normalize force with
  10289. if (distance == 0) {
  10290. distance = 0.01;
  10291. }
  10292. else {
  10293. repulsingForce = repulsingForce / distance;
  10294. }
  10295. fx = dx * repulsingForce;
  10296. fy = dy * repulsingForce;
  10297. node1.fx -= fx;
  10298. node1.fy -= fy;
  10299. node2.fx += fx;
  10300. node2.fy += fy;
  10301. }
  10302. }
  10303. }
  10304. }
  10305. };
  10306. /**
  10307. * Created by Alex on 2/10/14.
  10308. */
  10309. var barnesHutMixin = {
  10310. /**
  10311. * This function calculates the forces the nodes apply on eachother based on a gravitational model.
  10312. * The Barnes Hut method is used to speed up this N-body simulation.
  10313. *
  10314. * @private
  10315. */
  10316. _calculateNodeForces : function() {
  10317. if (this.constants.physics.barnesHut.gravitationalConstant != 0) {
  10318. var node;
  10319. var nodes = this.calculationNodes;
  10320. var nodeIndices = this.calculationNodeIndices;
  10321. var nodeCount = nodeIndices.length;
  10322. this._formBarnesHutTree(nodes,nodeIndices);
  10323. var barnesHutTree = this.barnesHutTree;
  10324. // place the nodes one by one recursively
  10325. for (var i = 0; i < nodeCount; i++) {
  10326. node = nodes[nodeIndices[i]];
  10327. // starting with root is irrelevant, it never passes the BarnesHut condition
  10328. this._getForceContribution(barnesHutTree.root.children.NW,node);
  10329. this._getForceContribution(barnesHutTree.root.children.NE,node);
  10330. this._getForceContribution(barnesHutTree.root.children.SW,node);
  10331. this._getForceContribution(barnesHutTree.root.children.SE,node);
  10332. }
  10333. }
  10334. },
  10335. /**
  10336. * This function traverses the barnesHutTree. It checks when it can approximate distant nodes with their center of mass.
  10337. * If a region contains a single node, we check if it is not itself, then we apply the force.
  10338. *
  10339. * @param parentBranch
  10340. * @param node
  10341. * @private
  10342. */
  10343. _getForceContribution : function(parentBranch,node) {
  10344. // we get no force contribution from an empty region
  10345. if (parentBranch.childrenCount > 0) {
  10346. var dx,dy,distance;
  10347. // get the distance from the center of mass to the node.
  10348. dx = parentBranch.centerOfMass.x - node.x;
  10349. dy = parentBranch.centerOfMass.y - node.y;
  10350. distance = Math.sqrt(dx * dx + dy * dy);
  10351. // BarnesHut condition
  10352. // original condition : s/d < theta = passed === d/s > 1/theta = passed
  10353. // calcSize = 1/s --> d * 1/s > 1/theta = passed
  10354. if (distance * parentBranch.calcSize > this.constants.physics.barnesHut.theta) {
  10355. // duplicate code to reduce function calls to speed up program
  10356. if (distance == 0) {
  10357. distance = 0.1*Math.random();
  10358. dx = distance;
  10359. }
  10360. var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.mass / (distance * distance * distance);
  10361. var fx = dx * gravityForce;
  10362. var fy = dy * gravityForce;
  10363. node.fx += fx;
  10364. node.fy += fy;
  10365. }
  10366. else {
  10367. // Did not pass the condition, go into children if available
  10368. if (parentBranch.childrenCount == 4) {
  10369. this._getForceContribution(parentBranch.children.NW,node);
  10370. this._getForceContribution(parentBranch.children.NE,node);
  10371. this._getForceContribution(parentBranch.children.SW,node);
  10372. this._getForceContribution(parentBranch.children.SE,node);
  10373. }
  10374. else { // parentBranch must have only one node, if it was empty we wouldnt be here
  10375. if (parentBranch.children.data.id != node.id) { // if it is not self
  10376. // duplicate code to reduce function calls to speed up program
  10377. if (distance == 0) {
  10378. distance = 0.5*Math.random();
  10379. dx = distance;
  10380. }
  10381. var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.mass / (distance * distance * distance);
  10382. var fx = dx * gravityForce;
  10383. var fy = dy * gravityForce;
  10384. node.fx += fx;
  10385. node.fy += fy;
  10386. }
  10387. }
  10388. }
  10389. }
  10390. },
  10391. /**
  10392. * This function constructs the barnesHut tree recursively. It creates the root, splits it and starts placing the nodes.
  10393. *
  10394. * @param nodes
  10395. * @param nodeIndices
  10396. * @private
  10397. */
  10398. _formBarnesHutTree : function(nodes,nodeIndices) {
  10399. var node;
  10400. var nodeCount = nodeIndices.length;
  10401. var minX = Number.MAX_VALUE,
  10402. minY = Number.MAX_VALUE,
  10403. maxX =-Number.MAX_VALUE,
  10404. maxY =-Number.MAX_VALUE;
  10405. // get the range of the nodes
  10406. for (var i = 0; i < nodeCount; i++) {
  10407. var x = nodes[nodeIndices[i]].x;
  10408. var y = nodes[nodeIndices[i]].y;
  10409. if (x < minX) { minX = x; }
  10410. if (x > maxX) { maxX = x; }
  10411. if (y < minY) { minY = y; }
  10412. if (y > maxY) { maxY = y; }
  10413. }
  10414. // make the range a square
  10415. var sizeDiff = Math.abs(maxX - minX) - Math.abs(maxY - minY); // difference between X and Y
  10416. if (sizeDiff > 0) {minY -= 0.5 * sizeDiff; maxY += 0.5 * sizeDiff;} // xSize > ySize
  10417. else {minX += 0.5 * sizeDiff; maxX -= 0.5 * sizeDiff;} // xSize < ySize
  10418. var minimumTreeSize = 1e-5;
  10419. var rootSize = Math.max(minimumTreeSize,Math.abs(maxX - minX));
  10420. var halfRootSize = 0.5 * rootSize;
  10421. var centerX = 0.5 * (minX + maxX), centerY = 0.5 * (minY + maxY);
  10422. // construct the barnesHutTree
  10423. var barnesHutTree = {root:{
  10424. centerOfMass:{x:0,y:0}, // Center of Mass
  10425. mass:0,
  10426. range: {minX:centerX-halfRootSize,maxX:centerX+halfRootSize,
  10427. minY:centerY-halfRootSize,maxY:centerY+halfRootSize},
  10428. size: rootSize,
  10429. calcSize: 1 / rootSize,
  10430. children: {data:null},
  10431. maxWidth: 0,
  10432. level: 0,
  10433. childrenCount: 4
  10434. }};
  10435. this._splitBranch(barnesHutTree.root);
  10436. // place the nodes one by one recursively
  10437. for (i = 0; i < nodeCount; i++) {
  10438. node = nodes[nodeIndices[i]];
  10439. this._placeInTree(barnesHutTree.root,node);
  10440. }
  10441. // make global
  10442. this.barnesHutTree = barnesHutTree
  10443. },
  10444. /**
  10445. * this updates the mass of a branch. this is increased by adding a node.
  10446. *
  10447. * @param parentBranch
  10448. * @param node
  10449. * @private
  10450. */
  10451. _updateBranchMass : function(parentBranch, node) {
  10452. var totalMass = parentBranch.mass + node.mass;
  10453. var totalMassInv = 1/totalMass;
  10454. parentBranch.centerOfMass.x = parentBranch.centerOfMass.x * parentBranch.mass + node.x * node.mass;
  10455. parentBranch.centerOfMass.x *= totalMassInv;
  10456. parentBranch.centerOfMass.y = parentBranch.centerOfMass.y * parentBranch.mass + node.y * node.mass;
  10457. parentBranch.centerOfMass.y *= totalMassInv;
  10458. parentBranch.mass = totalMass;
  10459. var biggestSize = Math.max(Math.max(node.height,node.radius),node.width);
  10460. parentBranch.maxWidth = (parentBranch.maxWidth < biggestSize) ? biggestSize : parentBranch.maxWidth;
  10461. },
  10462. /**
  10463. * determine in which branch the node will be placed.
  10464. *
  10465. * @param parentBranch
  10466. * @param node
  10467. * @param skipMassUpdate
  10468. * @private
  10469. */
  10470. _placeInTree : function(parentBranch,node,skipMassUpdate) {
  10471. if (skipMassUpdate != true || skipMassUpdate === undefined) {
  10472. // update the mass of the branch.
  10473. this._updateBranchMass(parentBranch,node);
  10474. }
  10475. if (parentBranch.children.NW.range.maxX > node.x) { // in NW or SW
  10476. if (parentBranch.children.NW.range.maxY > node.y) { // in NW
  10477. this._placeInRegion(parentBranch,node,"NW");
  10478. }
  10479. else { // in SW
  10480. this._placeInRegion(parentBranch,node,"SW");
  10481. }
  10482. }
  10483. else { // in NE or SE
  10484. if (parentBranch.children.NW.range.maxY > node.y) { // in NE
  10485. this._placeInRegion(parentBranch,node,"NE");
  10486. }
  10487. else { // in SE
  10488. this._placeInRegion(parentBranch,node,"SE");
  10489. }
  10490. }
  10491. },
  10492. /**
  10493. * actually place the node in a region (or branch)
  10494. *
  10495. * @param parentBranch
  10496. * @param node
  10497. * @param region
  10498. * @private
  10499. */
  10500. _placeInRegion : function(parentBranch,node,region) {
  10501. switch (parentBranch.children[region].childrenCount) {
  10502. case 0: // place node here
  10503. parentBranch.children[region].children.data = node;
  10504. parentBranch.children[region].childrenCount = 1;
  10505. this._updateBranchMass(parentBranch.children[region],node);
  10506. break;
  10507. case 1: // convert into children
  10508. // if there are two nodes exactly overlapping (on init, on opening of cluster etc.)
  10509. // we move one node a pixel and we do not put it in the tree.
  10510. if (parentBranch.children[region].children.data.x == node.x &&
  10511. parentBranch.children[region].children.data.y == node.y) {
  10512. node.x += Math.random();
  10513. node.y += Math.random();
  10514. }
  10515. else {
  10516. this._splitBranch(parentBranch.children[region]);
  10517. this._placeInTree(parentBranch.children[region],node);
  10518. }
  10519. break;
  10520. case 4: // place in branch
  10521. this._placeInTree(parentBranch.children[region],node);
  10522. break;
  10523. }
  10524. },
  10525. /**
  10526. * this function splits a branch into 4 sub branches. If the branch contained a node, we place it in the subbranch
  10527. * after the split is complete.
  10528. *
  10529. * @param parentBranch
  10530. * @private
  10531. */
  10532. _splitBranch : function(parentBranch) {
  10533. // if the branch is filled with a node, replace the node in the new subset.
  10534. var containedNode = null;
  10535. if (parentBranch.childrenCount == 1) {
  10536. containedNode = parentBranch.children.data;
  10537. parentBranch.mass = 0; parentBranch.centerOfMass.x = 0; parentBranch.centerOfMass.y = 0;
  10538. }
  10539. parentBranch.childrenCount = 4;
  10540. parentBranch.children.data = null;
  10541. this._insertRegion(parentBranch,"NW");
  10542. this._insertRegion(parentBranch,"NE");
  10543. this._insertRegion(parentBranch,"SW");
  10544. this._insertRegion(parentBranch,"SE");
  10545. if (containedNode != null) {
  10546. this._placeInTree(parentBranch,containedNode);
  10547. }
  10548. },
  10549. /**
  10550. * This function subdivides the region into four new segments.
  10551. * Specifically, this inserts a single new segment.
  10552. * It fills the children section of the parentBranch
  10553. *
  10554. * @param parentBranch
  10555. * @param region
  10556. * @param parentRange
  10557. * @private
  10558. */
  10559. _insertRegion : function(parentBranch, region) {
  10560. var minX,maxX,minY,maxY;
  10561. var childSize = 0.5 * parentBranch.size;
  10562. switch (region) {
  10563. case "NW":
  10564. minX = parentBranch.range.minX;
  10565. maxX = parentBranch.range.minX + childSize;
  10566. minY = parentBranch.range.minY;
  10567. maxY = parentBranch.range.minY + childSize;
  10568. break;
  10569. case "NE":
  10570. minX = parentBranch.range.minX + childSize;
  10571. maxX = parentBranch.range.maxX;
  10572. minY = parentBranch.range.minY;
  10573. maxY = parentBranch.range.minY + childSize;
  10574. break;
  10575. case "SW":
  10576. minX = parentBranch.range.minX;
  10577. maxX = parentBranch.range.minX + childSize;
  10578. minY = parentBranch.range.minY + childSize;
  10579. maxY = parentBranch.range.maxY;
  10580. break;
  10581. case "SE":
  10582. minX = parentBranch.range.minX + childSize;
  10583. maxX = parentBranch.range.maxX;
  10584. minY = parentBranch.range.minY + childSize;
  10585. maxY = parentBranch.range.maxY;
  10586. break;
  10587. }
  10588. parentBranch.children[region] = {
  10589. centerOfMass:{x:0,y:0},
  10590. mass:0,
  10591. range:{minX:minX,maxX:maxX,minY:minY,maxY:maxY},
  10592. size: 0.5 * parentBranch.size,
  10593. calcSize: 2 * parentBranch.calcSize,
  10594. children: {data:null},
  10595. maxWidth: 0,
  10596. level: parentBranch.level+1,
  10597. childrenCount: 0
  10598. };
  10599. },
  10600. /**
  10601. * This function is for debugging purposed, it draws the tree.
  10602. *
  10603. * @param ctx
  10604. * @param color
  10605. * @private
  10606. */
  10607. _drawTree : function(ctx,color) {
  10608. if (this.barnesHutTree !== undefined) {
  10609. ctx.lineWidth = 1;
  10610. this._drawBranch(this.barnesHutTree.root,ctx,color);
  10611. }
  10612. },
  10613. /**
  10614. * This function is for debugging purposes. It draws the branches recursively.
  10615. *
  10616. * @param branch
  10617. * @param ctx
  10618. * @param color
  10619. * @private
  10620. */
  10621. _drawBranch : function(branch,ctx,color) {
  10622. if (color === undefined) {
  10623. color = "#FF0000";
  10624. }
  10625. if (branch.childrenCount == 4) {
  10626. this._drawBranch(branch.children.NW,ctx);
  10627. this._drawBranch(branch.children.NE,ctx);
  10628. this._drawBranch(branch.children.SE,ctx);
  10629. this._drawBranch(branch.children.SW,ctx);
  10630. }
  10631. ctx.strokeStyle = color;
  10632. ctx.beginPath();
  10633. ctx.moveTo(branch.range.minX,branch.range.minY);
  10634. ctx.lineTo(branch.range.maxX,branch.range.minY);
  10635. ctx.stroke();
  10636. ctx.beginPath();
  10637. ctx.moveTo(branch.range.maxX,branch.range.minY);
  10638. ctx.lineTo(branch.range.maxX,branch.range.maxY);
  10639. ctx.stroke();
  10640. ctx.beginPath();
  10641. ctx.moveTo(branch.range.maxX,branch.range.maxY);
  10642. ctx.lineTo(branch.range.minX,branch.range.maxY);
  10643. ctx.stroke();
  10644. ctx.beginPath();
  10645. ctx.moveTo(branch.range.minX,branch.range.maxY);
  10646. ctx.lineTo(branch.range.minX,branch.range.minY);
  10647. ctx.stroke();
  10648. /*
  10649. if (branch.mass > 0) {
  10650. ctx.circle(branch.centerOfMass.x, branch.centerOfMass.y, 3*branch.mass);
  10651. ctx.stroke();
  10652. }
  10653. */
  10654. }
  10655. };
  10656. /**
  10657. * Created by Alex on 2/10/14.
  10658. */
  10659. var repulsionMixin = {
  10660. /**
  10661. * Calculate the forces the nodes apply on eachother based on a repulsion field.
  10662. * This field is linearly approximated.
  10663. *
  10664. * @private
  10665. */
  10666. _calculateNodeForces: function () {
  10667. var dx, dy, angle, distance, fx, fy, combinedClusterSize,
  10668. repulsingForce, node1, node2, i, j;
  10669. var nodes = this.calculationNodes;
  10670. var nodeIndices = this.calculationNodeIndices;
  10671. // approximation constants
  10672. var a_base = -2 / 3;
  10673. var b = 4 / 3;
  10674. // repulsing forces between nodes
  10675. var nodeDistance = this.constants.physics.repulsion.nodeDistance;
  10676. var minimumDistance = nodeDistance;
  10677. // we loop from i over all but the last entree in the array
  10678. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  10679. for (i = 0; i < nodeIndices.length - 1; i++) {
  10680. node1 = nodes[nodeIndices[i]];
  10681. for (j = i + 1; j < nodeIndices.length; j++) {
  10682. node2 = nodes[nodeIndices[j]];
  10683. combinedClusterSize = node1.clusterSize + node2.clusterSize - 2;
  10684. dx = node2.x - node1.x;
  10685. dy = node2.y - node1.y;
  10686. distance = Math.sqrt(dx * dx + dy * dy);
  10687. minimumDistance = (combinedClusterSize == 0) ? nodeDistance : (nodeDistance * (1 + combinedClusterSize * this.constants.clustering.distanceAmplification));
  10688. var a = a_base / minimumDistance;
  10689. if (distance < 2 * minimumDistance) {
  10690. if (distance < 0.5 * minimumDistance) {
  10691. repulsingForce = 1.0;
  10692. }
  10693. else {
  10694. repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness))
  10695. }
  10696. // amplify the repulsion for clusters.
  10697. repulsingForce *= (combinedClusterSize == 0) ? 1 : 1 + combinedClusterSize * this.constants.clustering.forceAmplification;
  10698. repulsingForce = repulsingForce / distance;
  10699. fx = dx * repulsingForce;
  10700. fy = dy * repulsingForce;
  10701. node1.fx -= fx;
  10702. node1.fy -= fy;
  10703. node2.fx += fx;
  10704. node2.fy += fy;
  10705. }
  10706. }
  10707. }
  10708. }
  10709. };
  10710. var HierarchicalLayoutMixin = {
  10711. _resetLevels : function() {
  10712. for (var nodeId in this.nodes) {
  10713. if (this.nodes.hasOwnProperty(nodeId)) {
  10714. var node = this.nodes[nodeId];
  10715. if (node.preassignedLevel == false) {
  10716. node.level = -1;
  10717. }
  10718. }
  10719. }
  10720. },
  10721. /**
  10722. * This is the main function to layout the nodes in a hierarchical way.
  10723. * It checks if the node details are supplied correctly
  10724. *
  10725. * @private
  10726. */
  10727. _setupHierarchicalLayout : function() {
  10728. if (this.constants.hierarchicalLayout.enabled == true) {
  10729. if (this.constants.hierarchicalLayout.direction == "RL" || this.constants.hierarchicalLayout.direction == "DU") {
  10730. this.constants.hierarchicalLayout.levelSeparation *= -1;
  10731. }
  10732. else {
  10733. this.constants.hierarchicalLayout.levelSeparation = Math.abs(this.constants.hierarchicalLayout.levelSeparation);
  10734. }
  10735. // get the size of the largest hubs and check if the user has defined a level for a node.
  10736. var hubsize = 0;
  10737. var node, nodeId;
  10738. var definedLevel = false;
  10739. var undefinedLevel = false;
  10740. for (nodeId in this.nodes) {
  10741. if (this.nodes.hasOwnProperty(nodeId)) {
  10742. node = this.nodes[nodeId];
  10743. if (node.level != -1) {
  10744. definedLevel = true;
  10745. }
  10746. else {
  10747. undefinedLevel = true;
  10748. }
  10749. if (hubsize < node.edges.length) {
  10750. hubsize = node.edges.length;
  10751. }
  10752. }
  10753. }
  10754. // if the user defined some levels but not all, alert and run without hierarchical layout
  10755. if (undefinedLevel == true && definedLevel == true) {
  10756. alert("To use the hierarchical layout, nodes require either no predefined levels or levels have to be defined for all nodes.");
  10757. this.zoomExtent(true,this.constants.clustering.enabled);
  10758. if (!this.constants.clustering.enabled) {
  10759. this.start();
  10760. }
  10761. }
  10762. else {
  10763. // setup the system to use hierarchical method.
  10764. this._changeConstants();
  10765. // define levels if undefined by the users. Based on hubsize
  10766. if (undefinedLevel == true) {
  10767. this._determineLevels(hubsize);
  10768. }
  10769. // check the distribution of the nodes per level.
  10770. var distribution = this._getDistribution();
  10771. // place the nodes on the canvas. This also stablilizes the system.
  10772. this._placeNodesByHierarchy(distribution);
  10773. // start the simulation.
  10774. this.start();
  10775. }
  10776. }
  10777. },
  10778. /**
  10779. * This function places the nodes on the canvas based on the hierarchial distribution.
  10780. *
  10781. * @param {Object} distribution | obtained by the function this._getDistribution()
  10782. * @private
  10783. */
  10784. _placeNodesByHierarchy : function(distribution) {
  10785. var nodeId, node;
  10786. // start placing all the level 0 nodes first. Then recursively position their branches.
  10787. for (nodeId in distribution[0].nodes) {
  10788. if (distribution[0].nodes.hasOwnProperty(nodeId)) {
  10789. node = distribution[0].nodes[nodeId];
  10790. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  10791. if (node.xFixed) {
  10792. node.x = distribution[0].minPos;
  10793. node.xFixed = false;
  10794. distribution[0].minPos += distribution[0].nodeSpacing;
  10795. }
  10796. }
  10797. else {
  10798. if (node.yFixed) {
  10799. node.y = distribution[0].minPos;
  10800. node.yFixed = false;
  10801. distribution[0].minPos += distribution[0].nodeSpacing;
  10802. }
  10803. }
  10804. this._placeBranchNodes(node.edges,node.id,distribution,node.level);
  10805. }
  10806. }
  10807. // stabilize the system after positioning. This function calls zoomExtent.
  10808. this._stabilize();
  10809. },
  10810. /**
  10811. * This function get the distribution of levels based on hubsize
  10812. *
  10813. * @returns {Object}
  10814. * @private
  10815. */
  10816. _getDistribution : function() {
  10817. var distribution = {};
  10818. var nodeId, node, level;
  10819. // 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.
  10820. // the fix of X is removed after the x value has been set.
  10821. for (nodeId in this.nodes) {
  10822. if (this.nodes.hasOwnProperty(nodeId)) {
  10823. node = this.nodes[nodeId];
  10824. node.xFixed = true;
  10825. node.yFixed = true;
  10826. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  10827. node.y = this.constants.hierarchicalLayout.levelSeparation*node.level;
  10828. }
  10829. else {
  10830. node.x = this.constants.hierarchicalLayout.levelSeparation*node.level;
  10831. }
  10832. if (!distribution.hasOwnProperty(node.level)) {
  10833. distribution[node.level] = {amount: 0, nodes: {}, minPos:0, nodeSpacing:0};
  10834. }
  10835. distribution[node.level].amount += 1;
  10836. distribution[node.level].nodes[node.id] = node;
  10837. }
  10838. }
  10839. // determine the largest amount of nodes of all levels
  10840. var maxCount = 0;
  10841. for (level in distribution) {
  10842. if (distribution.hasOwnProperty(level)) {
  10843. if (maxCount < distribution[level].amount) {
  10844. maxCount = distribution[level].amount;
  10845. }
  10846. }
  10847. }
  10848. // set the initial position and spacing of each nodes accordingly
  10849. for (level in distribution) {
  10850. if (distribution.hasOwnProperty(level)) {
  10851. distribution[level].nodeSpacing = (maxCount + 1) * this.constants.hierarchicalLayout.nodeSpacing;
  10852. distribution[level].nodeSpacing /= (distribution[level].amount + 1);
  10853. distribution[level].minPos = distribution[level].nodeSpacing - (0.5 * (distribution[level].amount + 1) * distribution[level].nodeSpacing);
  10854. }
  10855. }
  10856. return distribution;
  10857. },
  10858. /**
  10859. * this function allocates nodes in levels based on the recursive branching from the largest hubs.
  10860. *
  10861. * @param hubsize
  10862. * @private
  10863. */
  10864. _determineLevels : function(hubsize) {
  10865. var nodeId, node;
  10866. // determine hubs
  10867. for (nodeId in this.nodes) {
  10868. if (this.nodes.hasOwnProperty(nodeId)) {
  10869. node = this.nodes[nodeId];
  10870. if (node.edges.length == hubsize) {
  10871. node.level = 0;
  10872. }
  10873. }
  10874. }
  10875. // branch from hubs
  10876. for (nodeId in this.nodes) {
  10877. if (this.nodes.hasOwnProperty(nodeId)) {
  10878. node = this.nodes[nodeId];
  10879. if (node.level == 0) {
  10880. this._setLevel(1,node.edges,node.id);
  10881. }
  10882. }
  10883. }
  10884. },
  10885. /**
  10886. * Since hierarchical layout does not support:
  10887. * - smooth curves (based on the physics),
  10888. * - clustering (based on dynamic node counts)
  10889. *
  10890. * We disable both features so there will be no problems.
  10891. *
  10892. * @private
  10893. */
  10894. _changeConstants : function() {
  10895. this.constants.clustering.enabled = false;
  10896. this.constants.physics.barnesHut.enabled = false;
  10897. this.constants.physics.hierarchicalRepulsion.enabled = true;
  10898. this._loadSelectedForceSolver();
  10899. this.constants.smoothCurves = false;
  10900. this._configureSmoothCurves();
  10901. },
  10902. /**
  10903. * This is a recursively called function to enumerate the branches from the largest hubs and place the nodes
  10904. * on a X position that ensures there will be no overlap.
  10905. *
  10906. * @param edges
  10907. * @param parentId
  10908. * @param distribution
  10909. * @param parentLevel
  10910. * @private
  10911. */
  10912. _placeBranchNodes : function(edges, parentId, distribution, parentLevel) {
  10913. for (var i = 0; i < edges.length; i++) {
  10914. var childNode = null;
  10915. if (edges[i].toId == parentId) {
  10916. childNode = edges[i].from;
  10917. }
  10918. else {
  10919. childNode = edges[i].to;
  10920. }
  10921. // if a node is conneceted to another node on the same level (or higher (means lower level))!, this is not handled here.
  10922. var nodeMoved = false;
  10923. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  10924. if (childNode.xFixed && childNode.level > parentLevel) {
  10925. childNode.xFixed = false;
  10926. childNode.x = distribution[childNode.level].minPos;
  10927. nodeMoved = true;
  10928. }
  10929. }
  10930. else {
  10931. if (childNode.yFixed && childNode.level > parentLevel) {
  10932. childNode.yFixed = false;
  10933. childNode.y = distribution[childNode.level].minPos;
  10934. nodeMoved = true;
  10935. }
  10936. }
  10937. if (nodeMoved == true) {
  10938. distribution[childNode.level].minPos += distribution[childNode.level].nodeSpacing;
  10939. if (childNode.edges.length > 1) {
  10940. this._placeBranchNodes(childNode.edges,childNode.id,distribution,childNode.level);
  10941. }
  10942. }
  10943. }
  10944. },
  10945. /**
  10946. * this function is called recursively to enumerate the barnches of the largest hubs and give each node a level.
  10947. *
  10948. * @param level
  10949. * @param edges
  10950. * @param parentId
  10951. * @private
  10952. */
  10953. _setLevel : function(level, edges, parentId) {
  10954. for (var i = 0; i < edges.length; i++) {
  10955. var childNode = null;
  10956. if (edges[i].toId == parentId) {
  10957. childNode = edges[i].from;
  10958. }
  10959. else {
  10960. childNode = edges[i].to;
  10961. }
  10962. if (childNode.level == -1 || childNode.level > level) {
  10963. childNode.level = level;
  10964. if (edges.length > 1) {
  10965. this._setLevel(level+1, childNode.edges, childNode.id);
  10966. }
  10967. }
  10968. }
  10969. },
  10970. /**
  10971. * Unfix nodes
  10972. *
  10973. * @private
  10974. */
  10975. _restoreNodes : function() {
  10976. for (nodeId in this.nodes) {
  10977. if (this.nodes.hasOwnProperty(nodeId)) {
  10978. this.nodes[nodeId].xFixed = false;
  10979. this.nodes[nodeId].yFixed = false;
  10980. }
  10981. }
  10982. }
  10983. };
  10984. /**
  10985. * Created by Alex on 2/4/14.
  10986. */
  10987. var manipulationMixin = {
  10988. /**
  10989. * clears the toolbar div element of children
  10990. *
  10991. * @private
  10992. */
  10993. _clearManipulatorBar : function() {
  10994. while (this.manipulationDiv.hasChildNodes()) {
  10995. this.manipulationDiv.removeChild(this.manipulationDiv.firstChild);
  10996. }
  10997. },
  10998. /**
  10999. * Manipulation UI temporarily overloads certain functions to extend or replace them. To be able to restore
  11000. * these functions to their original functionality, we saved them in this.cachedFunctions.
  11001. * This function restores these functions to their original function.
  11002. *
  11003. * @private
  11004. */
  11005. _restoreOverloadedFunctions : function() {
  11006. for (var functionName in this.cachedFunctions) {
  11007. if (this.cachedFunctions.hasOwnProperty(functionName)) {
  11008. this[functionName] = this.cachedFunctions[functionName];
  11009. }
  11010. }
  11011. },
  11012. /**
  11013. * Enable or disable edit-mode.
  11014. *
  11015. * @private
  11016. */
  11017. _toggleEditMode : function() {
  11018. this.editMode = !this.editMode;
  11019. var toolbar = document.getElementById("graph-manipulationDiv");
  11020. var closeDiv = document.getElementById("graph-manipulation-closeDiv");
  11021. var editModeDiv = document.getElementById("graph-manipulation-editMode");
  11022. if (this.editMode == true) {
  11023. toolbar.style.display="block";
  11024. closeDiv.style.display="block";
  11025. editModeDiv.style.display="none";
  11026. closeDiv.onclick = this._toggleEditMode.bind(this);
  11027. }
  11028. else {
  11029. toolbar.style.display="none";
  11030. closeDiv.style.display="none";
  11031. editModeDiv.style.display="block";
  11032. closeDiv.onclick = null;
  11033. }
  11034. this._createManipulatorBar()
  11035. },
  11036. /**
  11037. * main function, creates the main toolbar. Removes functions bound to the select event. Binds all the buttons of the toolbar.
  11038. *
  11039. * @private
  11040. */
  11041. _createManipulatorBar : function() {
  11042. // remove bound functions
  11043. if (this.boundFunction) {
  11044. this.off('select', this.boundFunction);
  11045. }
  11046. // restore overloaded functions
  11047. this._restoreOverloadedFunctions();
  11048. // resume calculation
  11049. this.freezeSimulation = false;
  11050. // reset global variables
  11051. this.blockConnectingEdgeSelection = false;
  11052. this.forceAppendSelection = false;
  11053. if (this.editMode == true) {
  11054. while (this.manipulationDiv.hasChildNodes()) {
  11055. this.manipulationDiv.removeChild(this.manipulationDiv.firstChild);
  11056. }
  11057. // add the icons to the manipulator div
  11058. this.manipulationDiv.innerHTML = "" +
  11059. "<span class='graph-manipulationUI add' id='graph-manipulate-addNode'>" +
  11060. "<span class='graph-manipulationLabel'>"+this.constants.labels['add'] +"</span></span>" +
  11061. "<div class='graph-seperatorLine'></div>" +
  11062. "<span class='graph-manipulationUI connect' id='graph-manipulate-connectNode'>" +
  11063. "<span class='graph-manipulationLabel'>"+this.constants.labels['link'] +"</span></span>";
  11064. if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
  11065. this.manipulationDiv.innerHTML += "" +
  11066. "<div class='graph-seperatorLine'></div>" +
  11067. "<span class='graph-manipulationUI edit' id='graph-manipulate-editNode'>" +
  11068. "<span class='graph-manipulationLabel'>"+this.constants.labels['editNode'] +"</span></span>";
  11069. }
  11070. if (this._selectionIsEmpty() == false) {
  11071. this.manipulationDiv.innerHTML += "" +
  11072. "<div class='graph-seperatorLine'></div>" +
  11073. "<span class='graph-manipulationUI delete' id='graph-manipulate-delete'>" +
  11074. "<span class='graph-manipulationLabel'>"+this.constants.labels['del'] +"</span></span>";
  11075. }
  11076. // bind the icons
  11077. var addNodeButton = document.getElementById("graph-manipulate-addNode");
  11078. addNodeButton.onclick = this._createAddNodeToolbar.bind(this);
  11079. var addEdgeButton = document.getElementById("graph-manipulate-connectNode");
  11080. addEdgeButton.onclick = this._createAddEdgeToolbar.bind(this);
  11081. if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
  11082. var editButton = document.getElementById("graph-manipulate-editNode");
  11083. editButton.onclick = this._editNode.bind(this);
  11084. }
  11085. if (this._selectionIsEmpty() == false) {
  11086. var deleteButton = document.getElementById("graph-manipulate-delete");
  11087. deleteButton.onclick = this._deleteSelected.bind(this);
  11088. }
  11089. var closeDiv = document.getElementById("graph-manipulation-closeDiv");
  11090. closeDiv.onclick = this._toggleEditMode.bind(this);
  11091. this.boundFunction = this._createManipulatorBar.bind(this);
  11092. this.on('select', this.boundFunction);
  11093. }
  11094. else {
  11095. this.editModeDiv.innerHTML = "" +
  11096. "<span class='graph-manipulationUI edit editmode' id='graph-manipulate-editModeButton'>" +
  11097. "<span class='graph-manipulationLabel'>" + this.constants.labels['edit'] + "</span></span>";
  11098. var editModeButton = document.getElementById("graph-manipulate-editModeButton");
  11099. editModeButton.onclick = this._toggleEditMode.bind(this);
  11100. }
  11101. },
  11102. /**
  11103. * Create the toolbar for adding Nodes
  11104. *
  11105. * @private
  11106. */
  11107. _createAddNodeToolbar : function() {
  11108. // clear the toolbar
  11109. this._clearManipulatorBar();
  11110. if (this.boundFunction) {
  11111. this.off('select', this.boundFunction);
  11112. }
  11113. // create the toolbar contents
  11114. this.manipulationDiv.innerHTML = "" +
  11115. "<span class='graph-manipulationUI back' id='graph-manipulate-back'>" +
  11116. "<span class='graph-manipulationLabel'>" + this.constants.labels['back'] + " </span></span>" +
  11117. "<div class='graph-seperatorLine'></div>" +
  11118. "<span class='graph-manipulationUI none' id='graph-manipulate-back'>" +
  11119. "<span id='graph-manipulatorLabel' class='graph-manipulationLabel'>" + this.constants.labels['addDescription'] + "</span></span>";
  11120. // bind the icon
  11121. var backButton = document.getElementById("graph-manipulate-back");
  11122. backButton.onclick = this._createManipulatorBar.bind(this);
  11123. // we use the boundFunction so we can reference it when we unbind it from the "select" event.
  11124. this.boundFunction = this._addNode.bind(this);
  11125. this.on('select', this.boundFunction);
  11126. },
  11127. /**
  11128. * create the toolbar to connect nodes
  11129. *
  11130. * @private
  11131. */
  11132. _createAddEdgeToolbar : function() {
  11133. // clear the toolbar
  11134. this._clearManipulatorBar();
  11135. this._unselectAll(true);
  11136. this.freezeSimulation = true;
  11137. if (this.boundFunction) {
  11138. this.off('select', this.boundFunction);
  11139. }
  11140. this._unselectAll();
  11141. this.forceAppendSelection = false;
  11142. this.blockConnectingEdgeSelection = true;
  11143. this.manipulationDiv.innerHTML = "" +
  11144. "<span class='graph-manipulationUI back' id='graph-manipulate-back'>" +
  11145. "<span class='graph-manipulationLabel'>" + this.constants.labels['back'] + " </span></span>" +
  11146. "<div class='graph-seperatorLine'></div>" +
  11147. "<span class='graph-manipulationUI none' id='graph-manipulate-back'>" +
  11148. "<span id='graph-manipulatorLabel' class='graph-manipulationLabel'>" + this.constants.labels['linkDescription'] + "</span></span>";
  11149. // bind the icon
  11150. var backButton = document.getElementById("graph-manipulate-back");
  11151. backButton.onclick = this._createManipulatorBar.bind(this);
  11152. // we use the boundFunction so we can reference it when we unbind it from the "select" event.
  11153. this.boundFunction = this._handleConnect.bind(this);
  11154. this.on('select', this.boundFunction);
  11155. // temporarily overload functions
  11156. this.cachedFunctions["_handleTouch"] = this._handleTouch;
  11157. this.cachedFunctions["_handleOnRelease"] = this._handleOnRelease;
  11158. this._handleTouch = this._handleConnect;
  11159. this._handleOnRelease = this._finishConnect;
  11160. // redraw to show the unselect
  11161. this._redraw();
  11162. },
  11163. /**
  11164. * the function bound to the selection event. It checks if you want to connect a cluster and changes the description
  11165. * to walk the user through the process.
  11166. *
  11167. * @private
  11168. */
  11169. _handleConnect : function(pointer) {
  11170. if (this._getSelectedNodeCount() == 0) {
  11171. var node = this._getNodeAt(pointer);
  11172. if (node != null) {
  11173. if (node.clusterSize > 1) {
  11174. alert("Cannot create edges to a cluster.")
  11175. }
  11176. else {
  11177. this._selectObject(node,false);
  11178. // create a node the temporary line can look at
  11179. this.sectors['support']['nodes']['targetNode'] = new Node({id:'targetNode'},{},{},this.constants);
  11180. this.sectors['support']['nodes']['targetNode'].x = node.x;
  11181. this.sectors['support']['nodes']['targetNode'].y = node.y;
  11182. this.sectors['support']['nodes']['targetViaNode'] = new Node({id:'targetViaNode'},{},{},this.constants);
  11183. this.sectors['support']['nodes']['targetViaNode'].x = node.x;
  11184. this.sectors['support']['nodes']['targetViaNode'].y = node.y;
  11185. this.sectors['support']['nodes']['targetViaNode'].parentEdgeId = "connectionEdge";
  11186. // create a temporary edge
  11187. this.edges['connectionEdge'] = new Edge({id:"connectionEdge",from:node.id,to:this.sectors['support']['nodes']['targetNode'].id}, this, this.constants);
  11188. this.edges['connectionEdge'].from = node;
  11189. this.edges['connectionEdge'].connected = true;
  11190. this.edges['connectionEdge'].smooth = true;
  11191. this.edges['connectionEdge'].selected = true;
  11192. this.edges['connectionEdge'].to = this.sectors['support']['nodes']['targetNode'];
  11193. this.edges['connectionEdge'].via = this.sectors['support']['nodes']['targetViaNode'];
  11194. this.cachedFunctions["_handleOnDrag"] = this._handleOnDrag;
  11195. this._handleOnDrag = function(event) {
  11196. var pointer = this._getPointer(event.gesture.center);
  11197. this.sectors['support']['nodes']['targetNode'].x = this._XconvertDOMtoCanvas(pointer.x);
  11198. this.sectors['support']['nodes']['targetNode'].y = this._YconvertDOMtoCanvas(pointer.y);
  11199. this.sectors['support']['nodes']['targetViaNode'].x = 0.5 * (this._XconvertDOMtoCanvas(pointer.x) + this.edges['connectionEdge'].from.x);
  11200. this.sectors['support']['nodes']['targetViaNode'].y = this._YconvertDOMtoCanvas(pointer.y);
  11201. };
  11202. this.moving = true;
  11203. this.start();
  11204. }
  11205. }
  11206. }
  11207. },
  11208. _finishConnect : function(pointer) {
  11209. if (this._getSelectedNodeCount() == 1) {
  11210. // restore the drag function
  11211. this._handleOnDrag = this.cachedFunctions["_handleOnDrag"];
  11212. delete this.cachedFunctions["_handleOnDrag"];
  11213. // remember the edge id
  11214. var connectFromId = this.edges['connectionEdge'].fromId;
  11215. // remove the temporary nodes and edge
  11216. delete this.edges['connectionEdge'];
  11217. delete this.sectors['support']['nodes']['targetNode'];
  11218. delete this.sectors['support']['nodes']['targetViaNode'];
  11219. var node = this._getNodeAt(pointer);
  11220. if (node != null) {
  11221. if (node.clusterSize > 1) {
  11222. alert("Cannot create edges to a cluster.")
  11223. }
  11224. else {
  11225. this._createEdge(connectFromId,node.id);
  11226. this._createManipulatorBar();
  11227. }
  11228. }
  11229. this._unselectAll();
  11230. }
  11231. },
  11232. /**
  11233. * Adds a node on the specified location
  11234. */
  11235. _addNode : function() {
  11236. if (this._selectionIsEmpty() && this.editMode == true) {
  11237. var positionObject = this._pointerToPositionObject(this.pointerPosition);
  11238. var defaultData = {id:util.randomUUID(),x:positionObject.left,y:positionObject.top,label:"new",allowedToMoveX:true,allowedToMoveY:true};
  11239. if (this.triggerFunctions.add) {
  11240. if (this.triggerFunctions.add.length == 2) {
  11241. var me = this;
  11242. this.triggerFunctions.add(defaultData, function(finalizedData) {
  11243. me.nodesData.add(finalizedData);
  11244. me._createManipulatorBar();
  11245. me.moving = true;
  11246. me.start();
  11247. });
  11248. }
  11249. else {
  11250. alert(this.constants.labels['addError']);
  11251. this._createManipulatorBar();
  11252. this.moving = true;
  11253. this.start();
  11254. }
  11255. }
  11256. else {
  11257. this.nodesData.add(defaultData);
  11258. this._createManipulatorBar();
  11259. this.moving = true;
  11260. this.start();
  11261. }
  11262. }
  11263. },
  11264. /**
  11265. * connect two nodes with a new edge.
  11266. *
  11267. * @private
  11268. */
  11269. _createEdge : function(sourceNodeId,targetNodeId) {
  11270. if (this.editMode == true) {
  11271. var defaultData = {from:sourceNodeId, to:targetNodeId};
  11272. if (this.triggerFunctions.connect) {
  11273. if (this.triggerFunctions.connect.length == 2) {
  11274. var me = this;
  11275. this.triggerFunctions.connect(defaultData, function(finalizedData) {
  11276. me.edgesData.add(finalizedData);
  11277. me.moving = true;
  11278. me.start();
  11279. });
  11280. }
  11281. else {
  11282. alert(this.constants.labels["linkError"]);
  11283. this.moving = true;
  11284. this.start();
  11285. }
  11286. }
  11287. else {
  11288. this.edgesData.add(defaultData);
  11289. this.moving = true;
  11290. this.start();
  11291. }
  11292. }
  11293. },
  11294. /**
  11295. * Create the toolbar to edit the selected node. The label and the color can be changed. Other colors are derived from the chosen color.
  11296. *
  11297. * @private
  11298. */
  11299. _editNode : function() {
  11300. if (this.triggerFunctions.edit && this.editMode == true) {
  11301. var node = this._getSelectedNode();
  11302. var data = {id:node.id,
  11303. label: node.label,
  11304. group: node.group,
  11305. shape: node.shape,
  11306. color: {
  11307. background:node.color.background,
  11308. border:node.color.border,
  11309. highlight: {
  11310. background:node.color.highlight.background,
  11311. border:node.color.highlight.border
  11312. }
  11313. }};
  11314. if (this.triggerFunctions.edit.length == 2) {
  11315. var me = this;
  11316. this.triggerFunctions.edit(data, function (finalizedData) {
  11317. me.nodesData.update(finalizedData);
  11318. me._createManipulatorBar();
  11319. me.moving = true;
  11320. me.start();
  11321. });
  11322. }
  11323. else {
  11324. alert(this.constants.labels["editError"]);
  11325. }
  11326. }
  11327. else {
  11328. alert(this.constants.labels["editBoundError"]);
  11329. }
  11330. },
  11331. /**
  11332. * delete everything in the selection
  11333. *
  11334. * @private
  11335. */
  11336. _deleteSelected : function() {
  11337. if (!this._selectionIsEmpty() && this.editMode == true) {
  11338. if (!this._clusterInSelection()) {
  11339. var selectedNodes = this.getSelectedNodes();
  11340. var selectedEdges = this.getSelectedEdges();
  11341. if (this.triggerFunctions.del) {
  11342. var me = this;
  11343. var data = {nodes: selectedNodes, edges: selectedEdges};
  11344. if (this.triggerFunctions.del.length = 2) {
  11345. this.triggerFunctions.del(data, function (finalizedData) {
  11346. me.edgesData.remove(finalizedData.edges);
  11347. me.nodesData.remove(finalizedData.nodes);
  11348. me._unselectAll();
  11349. me.moving = true;
  11350. me.start();
  11351. });
  11352. }
  11353. else {
  11354. alert(this.constants.labels["deleteError"])
  11355. }
  11356. }
  11357. else {
  11358. this.edgesData.remove(selectedEdges);
  11359. this.nodesData.remove(selectedNodes);
  11360. this._unselectAll();
  11361. this.moving = true;
  11362. this.start();
  11363. }
  11364. }
  11365. else {
  11366. alert(this.constants.labels["deleteClusterError"]);
  11367. }
  11368. }
  11369. }
  11370. };
  11371. /**
  11372. * Creation of the SectorMixin var.
  11373. *
  11374. * This contains all the functions the Graph object can use to employ the sector system.
  11375. * The sector system is always used by Graph, though the benefits only apply to the use of clustering.
  11376. * If clustering is not used, there is no overhead except for a duplicate object with references to nodes and edges.
  11377. *
  11378. * Alex de Mulder
  11379. * 21-01-2013
  11380. */
  11381. var SectorMixin = {
  11382. /**
  11383. * This function is only called by the setData function of the Graph object.
  11384. * This loads the global references into the active sector. This initializes the sector.
  11385. *
  11386. * @private
  11387. */
  11388. _putDataInSector : function() {
  11389. this.sectors["active"][this._sector()].nodes = this.nodes;
  11390. this.sectors["active"][this._sector()].edges = this.edges;
  11391. this.sectors["active"][this._sector()].nodeIndices = this.nodeIndices;
  11392. },
  11393. /**
  11394. * /**
  11395. * This function sets the global references to nodes, edges and nodeIndices back to
  11396. * those of the supplied (active) sector. If a type is defined, do the specific type
  11397. *
  11398. * @param {String} sectorId
  11399. * @param {String} [sectorType] | "active" or "frozen"
  11400. * @private
  11401. */
  11402. _switchToSector : function(sectorId, sectorType) {
  11403. if (sectorType === undefined || sectorType == "active") {
  11404. this._switchToActiveSector(sectorId);
  11405. }
  11406. else {
  11407. this._switchToFrozenSector(sectorId);
  11408. }
  11409. },
  11410. /**
  11411. * This function sets the global references to nodes, edges and nodeIndices back to
  11412. * those of the supplied active sector.
  11413. *
  11414. * @param sectorId
  11415. * @private
  11416. */
  11417. _switchToActiveSector : function(sectorId) {
  11418. this.nodeIndices = this.sectors["active"][sectorId]["nodeIndices"];
  11419. this.nodes = this.sectors["active"][sectorId]["nodes"];
  11420. this.edges = this.sectors["active"][sectorId]["edges"];
  11421. },
  11422. /**
  11423. * This function sets the global references to nodes, edges and nodeIndices back to
  11424. * those of the supplied active sector.
  11425. *
  11426. * @param sectorId
  11427. * @private
  11428. */
  11429. _switchToSupportSector : function() {
  11430. this.nodeIndices = this.sectors["support"]["nodeIndices"];
  11431. this.nodes = this.sectors["support"]["nodes"];
  11432. this.edges = this.sectors["support"]["edges"];
  11433. },
  11434. /**
  11435. * This function sets the global references to nodes, edges and nodeIndices back to
  11436. * those of the supplied frozen sector.
  11437. *
  11438. * @param sectorId
  11439. * @private
  11440. */
  11441. _switchToFrozenSector : function(sectorId) {
  11442. this.nodeIndices = this.sectors["frozen"][sectorId]["nodeIndices"];
  11443. this.nodes = this.sectors["frozen"][sectorId]["nodes"];
  11444. this.edges = this.sectors["frozen"][sectorId]["edges"];
  11445. },
  11446. /**
  11447. * This function sets the global references to nodes, edges and nodeIndices back to
  11448. * those of the currently active sector.
  11449. *
  11450. * @private
  11451. */
  11452. _loadLatestSector : function() {
  11453. this._switchToSector(this._sector());
  11454. },
  11455. /**
  11456. * This function returns the currently active sector Id
  11457. *
  11458. * @returns {String}
  11459. * @private
  11460. */
  11461. _sector : function() {
  11462. return this.activeSector[this.activeSector.length-1];
  11463. },
  11464. /**
  11465. * This function returns the previously active sector Id
  11466. *
  11467. * @returns {String}
  11468. * @private
  11469. */
  11470. _previousSector : function() {
  11471. if (this.activeSector.length > 1) {
  11472. return this.activeSector[this.activeSector.length-2];
  11473. }
  11474. else {
  11475. throw new TypeError('there are not enough sectors in the this.activeSector array.');
  11476. }
  11477. },
  11478. /**
  11479. * We add the active sector at the end of the this.activeSector array
  11480. * This ensures it is the currently active sector returned by _sector() and it reaches the top
  11481. * of the activeSector stack. When we reverse our steps we move from the end to the beginning of this stack.
  11482. *
  11483. * @param newId
  11484. * @private
  11485. */
  11486. _setActiveSector : function(newId) {
  11487. this.activeSector.push(newId);
  11488. },
  11489. /**
  11490. * We remove the currently active sector id from the active sector stack. This happens when
  11491. * we reactivate the previously active sector
  11492. *
  11493. * @private
  11494. */
  11495. _forgetLastSector : function() {
  11496. this.activeSector.pop();
  11497. },
  11498. /**
  11499. * This function creates a new active sector with the supplied newId. This newId
  11500. * is the expanding node id.
  11501. *
  11502. * @param {String} newId | Id of the new active sector
  11503. * @private
  11504. */
  11505. _createNewSector : function(newId) {
  11506. // create the new sector
  11507. this.sectors["active"][newId] = {"nodes":{},
  11508. "edges":{},
  11509. "nodeIndices":[],
  11510. "formationScale": this.scale,
  11511. "drawingNode": undefined};
  11512. // create the new sector render node. This gives visual feedback that you are in a new sector.
  11513. this.sectors["active"][newId]['drawingNode'] = new Node(
  11514. {id:newId,
  11515. color: {
  11516. background: "#eaefef",
  11517. border: "495c5e"
  11518. }
  11519. },{},{},this.constants);
  11520. this.sectors["active"][newId]['drawingNode'].clusterSize = 2;
  11521. },
  11522. /**
  11523. * This function removes the currently active sector. This is called when we create a new
  11524. * active sector.
  11525. *
  11526. * @param {String} sectorId | Id of the active sector that will be removed
  11527. * @private
  11528. */
  11529. _deleteActiveSector : function(sectorId) {
  11530. delete this.sectors["active"][sectorId];
  11531. },
  11532. /**
  11533. * This function removes the currently active sector. This is called when we reactivate
  11534. * the previously active sector.
  11535. *
  11536. * @param {String} sectorId | Id of the active sector that will be removed
  11537. * @private
  11538. */
  11539. _deleteFrozenSector : function(sectorId) {
  11540. delete this.sectors["frozen"][sectorId];
  11541. },
  11542. /**
  11543. * Freezing an active sector means moving it from the "active" object to the "frozen" object.
  11544. * We copy the references, then delete the active entree.
  11545. *
  11546. * @param sectorId
  11547. * @private
  11548. */
  11549. _freezeSector : function(sectorId) {
  11550. // we move the set references from the active to the frozen stack.
  11551. this.sectors["frozen"][sectorId] = this.sectors["active"][sectorId];
  11552. // we have moved the sector data into the frozen set, we now remove it from the active set
  11553. this._deleteActiveSector(sectorId);
  11554. },
  11555. /**
  11556. * This is the reverse operation of _freezeSector. Activating means moving the sector from the "frozen"
  11557. * object to the "active" object.
  11558. *
  11559. * @param sectorId
  11560. * @private
  11561. */
  11562. _activateSector : function(sectorId) {
  11563. // we move the set references from the frozen to the active stack.
  11564. this.sectors["active"][sectorId] = this.sectors["frozen"][sectorId];
  11565. // we have moved the sector data into the active set, we now remove it from the frozen stack
  11566. this._deleteFrozenSector(sectorId);
  11567. },
  11568. /**
  11569. * This function merges the data from the currently active sector with a frozen sector. This is used
  11570. * in the process of reverting back to the previously active sector.
  11571. * The data that is placed in the frozen (the previously active) sector is the node that has been removed from it
  11572. * upon the creation of a new active sector.
  11573. *
  11574. * @param sectorId
  11575. * @private
  11576. */
  11577. _mergeThisWithFrozen : function(sectorId) {
  11578. // copy all nodes
  11579. for (var nodeId in this.nodes) {
  11580. if (this.nodes.hasOwnProperty(nodeId)) {
  11581. this.sectors["frozen"][sectorId]["nodes"][nodeId] = this.nodes[nodeId];
  11582. }
  11583. }
  11584. // copy all edges (if not fully clustered, else there are no edges)
  11585. for (var edgeId in this.edges) {
  11586. if (this.edges.hasOwnProperty(edgeId)) {
  11587. this.sectors["frozen"][sectorId]["edges"][edgeId] = this.edges[edgeId];
  11588. }
  11589. }
  11590. // merge the nodeIndices
  11591. for (var i = 0; i < this.nodeIndices.length; i++) {
  11592. this.sectors["frozen"][sectorId]["nodeIndices"].push(this.nodeIndices[i]);
  11593. }
  11594. },
  11595. /**
  11596. * This clusters the sector to one cluster. It was a single cluster before this process started so
  11597. * we revert to that state. The clusterToFit function with a maximum size of 1 node does this.
  11598. *
  11599. * @private
  11600. */
  11601. _collapseThisToSingleCluster : function() {
  11602. this.clusterToFit(1,false);
  11603. },
  11604. /**
  11605. * We create a new active sector from the node that we want to open.
  11606. *
  11607. * @param node
  11608. * @private
  11609. */
  11610. _addSector : function(node) {
  11611. // this is the currently active sector
  11612. var sector = this._sector();
  11613. // // this should allow me to select nodes from a frozen set.
  11614. // if (this.sectors['active'][sector]["nodes"].hasOwnProperty(node.id)) {
  11615. // console.log("the node is part of the active sector");
  11616. // }
  11617. // else {
  11618. // console.log("I dont know what happened!!");
  11619. // }
  11620. // when we switch to a new sector, we remove the node that will be expanded from the current nodes list.
  11621. delete this.nodes[node.id];
  11622. var unqiueIdentifier = util.randomUUID();
  11623. // we fully freeze the currently active sector
  11624. this._freezeSector(sector);
  11625. // we create a new active sector. This sector has the Id of the node to ensure uniqueness
  11626. this._createNewSector(unqiueIdentifier);
  11627. // we add the active sector to the sectors array to be able to revert these steps later on
  11628. this._setActiveSector(unqiueIdentifier);
  11629. // we redirect the global references to the new sector's references. this._sector() now returns unqiueIdentifier
  11630. this._switchToSector(this._sector());
  11631. // finally we add the node we removed from our previous active sector to the new active sector
  11632. this.nodes[node.id] = node;
  11633. },
  11634. /**
  11635. * We close the sector that is currently open and revert back to the one before.
  11636. * If the active sector is the "default" sector, nothing happens.
  11637. *
  11638. * @private
  11639. */
  11640. _collapseSector : function() {
  11641. // the currently active sector
  11642. var sector = this._sector();
  11643. // we cannot collapse the default sector
  11644. if (sector != "default") {
  11645. if ((this.nodeIndices.length == 1) ||
  11646. (this.sectors["active"][sector]["drawingNode"].width*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  11647. (this.sectors["active"][sector]["drawingNode"].height*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  11648. var previousSector = this._previousSector();
  11649. // we collapse the sector back to a single cluster
  11650. this._collapseThisToSingleCluster();
  11651. // we move the remaining nodes, edges and nodeIndices to the previous sector.
  11652. // This previous sector is the one we will reactivate
  11653. this._mergeThisWithFrozen(previousSector);
  11654. // the previously active (frozen) sector now has all the data from the currently active sector.
  11655. // we can now delete the active sector.
  11656. this._deleteActiveSector(sector);
  11657. // we activate the previously active (and currently frozen) sector.
  11658. this._activateSector(previousSector);
  11659. // we load the references from the newly active sector into the global references
  11660. this._switchToSector(previousSector);
  11661. // we forget the previously active sector because we reverted to the one before
  11662. this._forgetLastSector();
  11663. // finally, we update the node index list.
  11664. this._updateNodeIndexList();
  11665. // we refresh the list with calulation nodes and calculation node indices.
  11666. this._updateCalculationNodes();
  11667. }
  11668. }
  11669. },
  11670. /**
  11671. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  11672. *
  11673. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11674. * | we dont pass the function itself because then the "this" is the window object
  11675. * | instead of the Graph object
  11676. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11677. * @private
  11678. */
  11679. _doInAllActiveSectors : function(runFunction,argument) {
  11680. if (argument === undefined) {
  11681. for (var sector in this.sectors["active"]) {
  11682. if (this.sectors["active"].hasOwnProperty(sector)) {
  11683. // switch the global references to those of this sector
  11684. this._switchToActiveSector(sector);
  11685. this[runFunction]();
  11686. }
  11687. }
  11688. }
  11689. else {
  11690. for (var sector in this.sectors["active"]) {
  11691. if (this.sectors["active"].hasOwnProperty(sector)) {
  11692. // switch the global references to those of this sector
  11693. this._switchToActiveSector(sector);
  11694. var args = Array.prototype.splice.call(arguments, 1);
  11695. if (args.length > 1) {
  11696. this[runFunction](args[0],args[1]);
  11697. }
  11698. else {
  11699. this[runFunction](argument);
  11700. }
  11701. }
  11702. }
  11703. }
  11704. // we revert the global references back to our active sector
  11705. this._loadLatestSector();
  11706. },
  11707. /**
  11708. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  11709. *
  11710. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11711. * | we dont pass the function itself because then the "this" is the window object
  11712. * | instead of the Graph object
  11713. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11714. * @private
  11715. */
  11716. _doInSupportSector : function(runFunction,argument) {
  11717. if (argument === undefined) {
  11718. this._switchToSupportSector();
  11719. this[runFunction]();
  11720. }
  11721. else {
  11722. this._switchToSupportSector();
  11723. var args = Array.prototype.splice.call(arguments, 1);
  11724. if (args.length > 1) {
  11725. this[runFunction](args[0],args[1]);
  11726. }
  11727. else {
  11728. this[runFunction](argument);
  11729. }
  11730. }
  11731. // we revert the global references back to our active sector
  11732. this._loadLatestSector();
  11733. },
  11734. /**
  11735. * This runs a function in all frozen sectors. This is used in the _redraw().
  11736. *
  11737. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11738. * | we don't pass the function itself because then the "this" is the window object
  11739. * | instead of the Graph object
  11740. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11741. * @private
  11742. */
  11743. _doInAllFrozenSectors : function(runFunction,argument) {
  11744. if (argument === undefined) {
  11745. for (var sector in this.sectors["frozen"]) {
  11746. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  11747. // switch the global references to those of this sector
  11748. this._switchToFrozenSector(sector);
  11749. this[runFunction]();
  11750. }
  11751. }
  11752. }
  11753. else {
  11754. for (var sector in this.sectors["frozen"]) {
  11755. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  11756. // switch the global references to those of this sector
  11757. this._switchToFrozenSector(sector);
  11758. var args = Array.prototype.splice.call(arguments, 1);
  11759. if (args.length > 1) {
  11760. this[runFunction](args[0],args[1]);
  11761. }
  11762. else {
  11763. this[runFunction](argument);
  11764. }
  11765. }
  11766. }
  11767. }
  11768. this._loadLatestSector();
  11769. },
  11770. /**
  11771. * This runs a function in all sectors. This is used in the _redraw().
  11772. *
  11773. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11774. * | we don't pass the function itself because then the "this" is the window object
  11775. * | instead of the Graph object
  11776. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11777. * @private
  11778. */
  11779. _doInAllSectors : function(runFunction,argument) {
  11780. var args = Array.prototype.splice.call(arguments, 1);
  11781. if (argument === undefined) {
  11782. this._doInAllActiveSectors(runFunction);
  11783. this._doInAllFrozenSectors(runFunction);
  11784. }
  11785. else {
  11786. if (args.length > 1) {
  11787. this._doInAllActiveSectors(runFunction,args[0],args[1]);
  11788. this._doInAllFrozenSectors(runFunction,args[0],args[1]);
  11789. }
  11790. else {
  11791. this._doInAllActiveSectors(runFunction,argument);
  11792. this._doInAllFrozenSectors(runFunction,argument);
  11793. }
  11794. }
  11795. },
  11796. /**
  11797. * This clears the nodeIndices list. We cannot use this.nodeIndices = [] because we would break the link with the
  11798. * active sector. Thus we clear the nodeIndices in the active sector, then reconnect the this.nodeIndices to it.
  11799. *
  11800. * @private
  11801. */
  11802. _clearNodeIndexList : function() {
  11803. var sector = this._sector();
  11804. this.sectors["active"][sector]["nodeIndices"] = [];
  11805. this.nodeIndices = this.sectors["active"][sector]["nodeIndices"];
  11806. },
  11807. /**
  11808. * Draw the encompassing sector node
  11809. *
  11810. * @param ctx
  11811. * @param sectorType
  11812. * @private
  11813. */
  11814. _drawSectorNodes : function(ctx,sectorType) {
  11815. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  11816. for (var sector in this.sectors[sectorType]) {
  11817. if (this.sectors[sectorType].hasOwnProperty(sector)) {
  11818. if (this.sectors[sectorType][sector]["drawingNode"] !== undefined) {
  11819. this._switchToSector(sector,sectorType);
  11820. minY = 1e9; maxY = -1e9; minX = 1e9; maxX = -1e9;
  11821. for (var nodeId in this.nodes) {
  11822. if (this.nodes.hasOwnProperty(nodeId)) {
  11823. node = this.nodes[nodeId];
  11824. node.resize(ctx);
  11825. if (minX > node.x - 0.5 * node.width) {minX = node.x - 0.5 * node.width;}
  11826. if (maxX < node.x + 0.5 * node.width) {maxX = node.x + 0.5 * node.width;}
  11827. if (minY > node.y - 0.5 * node.height) {minY = node.y - 0.5 * node.height;}
  11828. if (maxY < node.y + 0.5 * node.height) {maxY = node.y + 0.5 * node.height;}
  11829. }
  11830. }
  11831. node = this.sectors[sectorType][sector]["drawingNode"];
  11832. node.x = 0.5 * (maxX + minX);
  11833. node.y = 0.5 * (maxY + minY);
  11834. node.width = 2 * (node.x - minX);
  11835. node.height = 2 * (node.y - minY);
  11836. node.radius = Math.sqrt(Math.pow(0.5*node.width,2) + Math.pow(0.5*node.height,2));
  11837. node.setScale(this.scale);
  11838. node._drawCircle(ctx);
  11839. }
  11840. }
  11841. }
  11842. },
  11843. _drawAllSectorNodes : function(ctx) {
  11844. this._drawSectorNodes(ctx,"frozen");
  11845. this._drawSectorNodes(ctx,"active");
  11846. this._loadLatestSector();
  11847. }
  11848. };
  11849. /**
  11850. * Creation of the ClusterMixin var.
  11851. *
  11852. * This contains all the functions the Graph object can use to employ clustering
  11853. *
  11854. * Alex de Mulder
  11855. * 21-01-2013
  11856. */
  11857. var ClusterMixin = {
  11858. /**
  11859. * This is only called in the constructor of the graph object
  11860. *
  11861. */
  11862. startWithClustering : function() {
  11863. // cluster if the data set is big
  11864. this.clusterToFit(this.constants.clustering.initialMaxNodes, true);
  11865. // updates the lables after clustering
  11866. this.updateLabels();
  11867. // this is called here because if clusterin is disabled, the start and stabilize are called in
  11868. // the setData function.
  11869. if (this.stabilize) {
  11870. this._stabilize();
  11871. }
  11872. this.start();
  11873. },
  11874. /**
  11875. * This function clusters until the initialMaxNodes has been reached
  11876. *
  11877. * @param {Number} maxNumberOfNodes
  11878. * @param {Boolean} reposition
  11879. */
  11880. clusterToFit : function(maxNumberOfNodes, reposition) {
  11881. var numberOfNodes = this.nodeIndices.length;
  11882. var maxLevels = 50;
  11883. var level = 0;
  11884. // we first cluster the hubs, then we pull in the outliers, repeat
  11885. while (numberOfNodes > maxNumberOfNodes && level < maxLevels) {
  11886. if (level % 3 == 0) {
  11887. this.forceAggregateHubs(true);
  11888. this.normalizeClusterLevels();
  11889. }
  11890. else {
  11891. this.increaseClusterLevel(); // this also includes a cluster normalization
  11892. }
  11893. numberOfNodes = this.nodeIndices.length;
  11894. level += 1;
  11895. }
  11896. // after the clustering we reposition the nodes to reduce the initial chaos
  11897. if (level > 0 && reposition == true) {
  11898. this.repositionNodes();
  11899. }
  11900. this._updateCalculationNodes();
  11901. },
  11902. /**
  11903. * This function can be called to open up a specific cluster. It is only called by
  11904. * It will unpack the cluster back one level.
  11905. *
  11906. * @param node | Node object: cluster to open.
  11907. */
  11908. openCluster : function(node) {
  11909. var isMovingBeforeClustering = this.moving;
  11910. if (node.clusterSize > this.constants.clustering.sectorThreshold && this._nodeInActiveArea(node) &&
  11911. !(this._sector() == "default" && this.nodeIndices.length == 1)) {
  11912. // this loads a new sector, loads the nodes and edges and nodeIndices of it.
  11913. this._addSector(node);
  11914. var level = 0;
  11915. // we decluster until we reach a decent number of nodes
  11916. while ((this.nodeIndices.length < this.constants.clustering.initialMaxNodes) && (level < 10)) {
  11917. this.decreaseClusterLevel();
  11918. level += 1;
  11919. }
  11920. }
  11921. else {
  11922. this._expandClusterNode(node,false,true);
  11923. // update the index list, dynamic edges and labels
  11924. this._updateNodeIndexList();
  11925. this._updateDynamicEdges();
  11926. this._updateCalculationNodes();
  11927. this.updateLabels();
  11928. }
  11929. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  11930. if (this.moving != isMovingBeforeClustering) {
  11931. this.start();
  11932. }
  11933. },
  11934. /**
  11935. * This calls the updateClustes with default arguments
  11936. */
  11937. updateClustersDefault : function() {
  11938. if (this.constants.clustering.enabled == true) {
  11939. this.updateClusters(0,false,false);
  11940. }
  11941. },
  11942. /**
  11943. * This function can be called to increase the cluster level. This means that the nodes with only one edge connection will
  11944. * be clustered with their connected node. This can be repeated as many times as needed.
  11945. * This can be called externally (by a keybind for instance) to reduce the complexity of big datasets.
  11946. */
  11947. increaseClusterLevel : function() {
  11948. this.updateClusters(-1,false,true);
  11949. },
  11950. /**
  11951. * This function can be called to decrease the cluster level. This means that the nodes with only one edge connection will
  11952. * be unpacked if they are a cluster. This can be repeated as many times as needed.
  11953. * This can be called externally (by a key-bind for instance) to look into clusters without zooming.
  11954. */
  11955. decreaseClusterLevel : function() {
  11956. this.updateClusters(1,false,true);
  11957. },
  11958. /**
  11959. * This is the main clustering function. It clusters and declusters on zoom or forced
  11960. * This function clusters on zoom, it can be called with a predefined zoom direction
  11961. * If out, check if we can form clusters, if in, check if we can open clusters.
  11962. * This function is only called from _zoom()
  11963. *
  11964. * @param {Number} zoomDirection | -1 / 0 / +1 for zoomOut / determineByZoom / zoomIn
  11965. * @param {Boolean} recursive | enabled or disable recursive calling of the opening of clusters
  11966. * @param {Boolean} force | enabled or disable forcing
  11967. * @param {Boolean} doNotStart | if true do not call start
  11968. *
  11969. */
  11970. updateClusters : function(zoomDirection,recursive,force,doNotStart) {
  11971. var isMovingBeforeClustering = this.moving;
  11972. var amountOfNodes = this.nodeIndices.length;
  11973. // on zoom out collapse the sector if the scale is at the level the sector was made
  11974. if (this.previousScale > this.scale && zoomDirection == 0) {
  11975. this._collapseSector();
  11976. }
  11977. // check if we zoom in or out
  11978. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  11979. // forming clusters when forced pulls outliers in. When not forced, the edge length of the
  11980. // outer nodes determines if it is being clustered
  11981. this._formClusters(force);
  11982. }
  11983. else if (this.previousScale < this.scale || zoomDirection == 1) { // zoom in
  11984. if (force == true) {
  11985. // _openClusters checks for each node if the formationScale of the cluster is smaller than
  11986. // the current scale and if so, declusters. When forced, all clusters are reduced by one step
  11987. this._openClusters(recursive,force);
  11988. }
  11989. else {
  11990. // if a cluster takes up a set percentage of the active window
  11991. this._openClustersBySize();
  11992. }
  11993. }
  11994. this._updateNodeIndexList();
  11995. // if a cluster was NOT formed and the user zoomed out, we try clustering by hubs
  11996. if (this.nodeIndices.length == amountOfNodes && (this.previousScale > this.scale || zoomDirection == -1)) {
  11997. this._aggregateHubs(force);
  11998. this._updateNodeIndexList();
  11999. }
  12000. // we now reduce chains.
  12001. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  12002. this.handleChains();
  12003. this._updateNodeIndexList();
  12004. }
  12005. this.previousScale = this.scale;
  12006. // rest of the update the index list, dynamic edges and labels
  12007. this._updateDynamicEdges();
  12008. this.updateLabels();
  12009. // if a cluster was formed, we increase the clusterSession
  12010. if (this.nodeIndices.length < amountOfNodes) { // this means a clustering operation has taken place
  12011. this.clusterSession += 1;
  12012. // if clusters have been made, we normalize the cluster level
  12013. this.normalizeClusterLevels();
  12014. }
  12015. if (doNotStart == false || doNotStart === undefined) {
  12016. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  12017. if (this.moving != isMovingBeforeClustering) {
  12018. this.start();
  12019. }
  12020. }
  12021. this._updateCalculationNodes();
  12022. },
  12023. /**
  12024. * This function handles the chains. It is called on every updateClusters().
  12025. */
  12026. handleChains : function() {
  12027. // after clustering we check how many chains there are
  12028. var chainPercentage = this._getChainFraction();
  12029. if (chainPercentage > this.constants.clustering.chainThreshold) {
  12030. this._reduceAmountOfChains(1 - this.constants.clustering.chainThreshold / chainPercentage)
  12031. }
  12032. },
  12033. /**
  12034. * this functions starts clustering by hubs
  12035. * The minimum hub threshold is set globally
  12036. *
  12037. * @private
  12038. */
  12039. _aggregateHubs : function(force) {
  12040. this._getHubSize();
  12041. this._formClustersByHub(force,false);
  12042. },
  12043. /**
  12044. * This function is fired by keypress. It forces hubs to form.
  12045. *
  12046. */
  12047. forceAggregateHubs : function(doNotStart) {
  12048. var isMovingBeforeClustering = this.moving;
  12049. var amountOfNodes = this.nodeIndices.length;
  12050. this._aggregateHubs(true);
  12051. // update the index list, dynamic edges and labels
  12052. this._updateNodeIndexList();
  12053. this._updateDynamicEdges();
  12054. this.updateLabels();
  12055. // if a cluster was formed, we increase the clusterSession
  12056. if (this.nodeIndices.length != amountOfNodes) {
  12057. this.clusterSession += 1;
  12058. }
  12059. if (doNotStart == false || doNotStart === undefined) {
  12060. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  12061. if (this.moving != isMovingBeforeClustering) {
  12062. this.start();
  12063. }
  12064. }
  12065. },
  12066. /**
  12067. * If a cluster takes up more than a set percentage of the screen, open the cluster
  12068. *
  12069. * @private
  12070. */
  12071. _openClustersBySize : function() {
  12072. for (var nodeId in this.nodes) {
  12073. if (this.nodes.hasOwnProperty(nodeId)) {
  12074. var node = this.nodes[nodeId];
  12075. if (node.inView() == true) {
  12076. if ((node.width*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  12077. (node.height*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  12078. this.openCluster(node);
  12079. }
  12080. }
  12081. }
  12082. }
  12083. },
  12084. /**
  12085. * This function loops over all nodes in the nodeIndices list. For each node it checks if it is a cluster and if it
  12086. * has to be opened based on the current zoom level.
  12087. *
  12088. * @private
  12089. */
  12090. _openClusters : function(recursive,force) {
  12091. for (var i = 0; i < this.nodeIndices.length; i++) {
  12092. var node = this.nodes[this.nodeIndices[i]];
  12093. this._expandClusterNode(node,recursive,force);
  12094. this._updateCalculationNodes();
  12095. }
  12096. },
  12097. /**
  12098. * This function checks if a node has to be opened. This is done by checking the zoom level.
  12099. * If the node contains child nodes, this function is recursively called on the child nodes as well.
  12100. * This recursive behaviour is optional and can be set by the recursive argument.
  12101. *
  12102. * @param {Node} parentNode | to check for cluster and expand
  12103. * @param {Boolean} recursive | enabled or disable recursive calling
  12104. * @param {Boolean} force | enabled or disable forcing
  12105. * @param {Boolean} [openAll] | This will recursively force all nodes in the parent to be released
  12106. * @private
  12107. */
  12108. _expandClusterNode : function(parentNode, recursive, force, openAll) {
  12109. // first check if node is a cluster
  12110. if (parentNode.clusterSize > 1) {
  12111. // this means that on a double tap event or a zoom event, the cluster fully unpacks if it is smaller than 20
  12112. if (parentNode.clusterSize < this.constants.clustering.sectorThreshold) {
  12113. openAll = true;
  12114. }
  12115. recursive = openAll ? true : recursive;
  12116. // if the last child has been added on a smaller scale than current scale decluster
  12117. if (parentNode.formationScale < this.scale || force == true) {
  12118. // we will check if any of the contained child nodes should be removed from the cluster
  12119. for (var containedNodeId in parentNode.containedNodes) {
  12120. if (parentNode.containedNodes.hasOwnProperty(containedNodeId)) {
  12121. var childNode = parentNode.containedNodes[containedNodeId];
  12122. // force expand will expand the largest cluster size clusters. Since we cluster from outside in, we assume that
  12123. // the largest cluster is the one that comes from outside
  12124. if (force == true) {
  12125. if (childNode.clusterSession == parentNode.clusterSessions[parentNode.clusterSessions.length-1]
  12126. || openAll) {
  12127. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  12128. }
  12129. }
  12130. else {
  12131. if (this._nodeInActiveArea(parentNode)) {
  12132. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  12133. }
  12134. }
  12135. }
  12136. }
  12137. }
  12138. }
  12139. },
  12140. /**
  12141. * ONLY CALLED FROM _expandClusterNode
  12142. *
  12143. * This function will expel a child_node from a parent_node. This is to de-cluster the node. This function will remove
  12144. * the child node from the parent contained_node object and put it back into the global nodes object.
  12145. * The same holds for the edge that was connected to the child node. It is moved back into the global edges object.
  12146. *
  12147. * @param {Node} parentNode | the parent node
  12148. * @param {String} containedNodeId | child_node id as it is contained in the containedNodes object of the parent node
  12149. * @param {Boolean} recursive | This will also check if the child needs to be expanded.
  12150. * With force and recursive both true, the entire cluster is unpacked
  12151. * @param {Boolean} force | This will disregard the zoom level and will expel this child from the parent
  12152. * @param {Boolean} openAll | This will recursively force all nodes in the parent to be released
  12153. * @private
  12154. */
  12155. _expelChildFromParent : function(parentNode, containedNodeId, recursive, force, openAll) {
  12156. var childNode = parentNode.containedNodes[containedNodeId];
  12157. // if child node has been added on smaller scale than current, kick out
  12158. if (childNode.formationScale < this.scale || force == true) {
  12159. // unselect all selected items
  12160. this._unselectAll();
  12161. // put the child node back in the global nodes object
  12162. this.nodes[containedNodeId] = childNode;
  12163. // release the contained edges from this childNode back into the global edges
  12164. this._releaseContainedEdges(parentNode,childNode);
  12165. // reconnect rerouted edges to the childNode
  12166. this._connectEdgeBackToChild(parentNode,childNode);
  12167. // validate all edges in dynamicEdges
  12168. this._validateEdges(parentNode);
  12169. // undo the changes from the clustering operation on the parent node
  12170. parentNode.mass -= childNode.mass;
  12171. parentNode.clusterSize -= childNode.clusterSize;
  12172. parentNode.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize);
  12173. parentNode.dynamicEdgesLength = parentNode.dynamicEdges.length;
  12174. // place the child node near the parent, not at the exact same location to avoid chaos in the system
  12175. childNode.x = parentNode.x + parentNode.growthIndicator * (0.5 - Math.random());
  12176. childNode.y = parentNode.y + parentNode.growthIndicator * (0.5 - Math.random());
  12177. // remove node from the list
  12178. delete parentNode.containedNodes[containedNodeId];
  12179. // check if there are other childs with this clusterSession in the parent.
  12180. var othersPresent = false;
  12181. for (var childNodeId in parentNode.containedNodes) {
  12182. if (parentNode.containedNodes.hasOwnProperty(childNodeId)) {
  12183. if (parentNode.containedNodes[childNodeId].clusterSession == childNode.clusterSession) {
  12184. othersPresent = true;
  12185. break;
  12186. }
  12187. }
  12188. }
  12189. // if there are no others, remove the cluster session from the list
  12190. if (othersPresent == false) {
  12191. parentNode.clusterSessions.pop();
  12192. }
  12193. this._repositionBezierNodes(childNode);
  12194. // this._repositionBezierNodes(parentNode);
  12195. // remove the clusterSession from the child node
  12196. childNode.clusterSession = 0;
  12197. // recalculate the size of the node on the next time the node is rendered
  12198. parentNode.clearSizeCache();
  12199. // restart the simulation to reorganise all nodes
  12200. this.moving = true;
  12201. }
  12202. // check if a further expansion step is possible if recursivity is enabled
  12203. if (recursive == true) {
  12204. this._expandClusterNode(childNode,recursive,force,openAll);
  12205. }
  12206. },
  12207. /**
  12208. * position the bezier nodes at the center of the edges
  12209. *
  12210. * @param node
  12211. * @private
  12212. */
  12213. _repositionBezierNodes : function(node) {
  12214. for (var i = 0; i < node.dynamicEdges.length; i++) {
  12215. node.dynamicEdges[i].positionBezierNode();
  12216. }
  12217. },
  12218. /**
  12219. * This function checks if any nodes at the end of their trees have edges below a threshold length
  12220. * This function is called only from updateClusters()
  12221. * forceLevelCollapse ignores the length of the edge and collapses one level
  12222. * This means that a node with only one edge will be clustered with its connected node
  12223. *
  12224. * @private
  12225. * @param {Boolean} force
  12226. */
  12227. _formClusters : function(force) {
  12228. if (force == false) {
  12229. this._formClustersByZoom();
  12230. }
  12231. else {
  12232. this._forceClustersByZoom();
  12233. }
  12234. },
  12235. /**
  12236. * This function handles the clustering by zooming out, this is based on a minimum edge distance
  12237. *
  12238. * @private
  12239. */
  12240. _formClustersByZoom : function() {
  12241. var dx,dy,length,
  12242. minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  12243. // check if any edges are shorter than minLength and start the clustering
  12244. // the clustering favours the node with the larger mass
  12245. for (var edgeId in this.edges) {
  12246. if (this.edges.hasOwnProperty(edgeId)) {
  12247. var edge = this.edges[edgeId];
  12248. if (edge.connected) {
  12249. if (edge.toId != edge.fromId) {
  12250. dx = (edge.to.x - edge.from.x);
  12251. dy = (edge.to.y - edge.from.y);
  12252. length = Math.sqrt(dx * dx + dy * dy);
  12253. if (length < minLength) {
  12254. // first check which node is larger
  12255. var parentNode = edge.from;
  12256. var childNode = edge.to;
  12257. if (edge.to.mass > edge.from.mass) {
  12258. parentNode = edge.to;
  12259. childNode = edge.from;
  12260. }
  12261. if (childNode.dynamicEdgesLength == 1) {
  12262. this._addToCluster(parentNode,childNode,false);
  12263. }
  12264. else if (parentNode.dynamicEdgesLength == 1) {
  12265. this._addToCluster(childNode,parentNode,false);
  12266. }
  12267. }
  12268. }
  12269. }
  12270. }
  12271. }
  12272. },
  12273. /**
  12274. * This function forces the graph to cluster all nodes with only one connecting edge to their
  12275. * connected node.
  12276. *
  12277. * @private
  12278. */
  12279. _forceClustersByZoom : function() {
  12280. for (var nodeId in this.nodes) {
  12281. // another node could have absorbed this child.
  12282. if (this.nodes.hasOwnProperty(nodeId)) {
  12283. var childNode = this.nodes[nodeId];
  12284. // the edges can be swallowed by another decrease
  12285. if (childNode.dynamicEdgesLength == 1 && childNode.dynamicEdges.length != 0) {
  12286. var edge = childNode.dynamicEdges[0];
  12287. var parentNode = (edge.toId == childNode.id) ? this.nodes[edge.fromId] : this.nodes[edge.toId];
  12288. // group to the largest node
  12289. if (childNode.id != parentNode.id) {
  12290. if (parentNode.mass > childNode.mass) {
  12291. this._addToCluster(parentNode,childNode,true);
  12292. }
  12293. else {
  12294. this._addToCluster(childNode,parentNode,true);
  12295. }
  12296. }
  12297. }
  12298. }
  12299. }
  12300. },
  12301. /**
  12302. * To keep the nodes of roughly equal size we normalize the cluster levels.
  12303. * This function clusters a node to its smallest connected neighbour.
  12304. *
  12305. * @param node
  12306. * @private
  12307. */
  12308. _clusterToSmallestNeighbour : function(node) {
  12309. var smallestNeighbour = -1;
  12310. var smallestNeighbourNode = null;
  12311. for (var i = 0; i < node.dynamicEdges.length; i++) {
  12312. if (node.dynamicEdges[i] !== undefined) {
  12313. var neighbour = null;
  12314. if (node.dynamicEdges[i].fromId != node.id) {
  12315. neighbour = node.dynamicEdges[i].from;
  12316. }
  12317. else if (node.dynamicEdges[i].toId != node.id) {
  12318. neighbour = node.dynamicEdges[i].to;
  12319. }
  12320. if (neighbour != null && smallestNeighbour > neighbour.clusterSessions.length) {
  12321. smallestNeighbour = neighbour.clusterSessions.length;
  12322. smallestNeighbourNode = neighbour;
  12323. }
  12324. }
  12325. }
  12326. if (neighbour != null && this.nodes[neighbour.id] !== undefined) {
  12327. this._addToCluster(neighbour, node, true);
  12328. }
  12329. },
  12330. /**
  12331. * This function forms clusters from hubs, it loops over all nodes
  12332. *
  12333. * @param {Boolean} force | Disregard zoom level
  12334. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  12335. * @private
  12336. */
  12337. _formClustersByHub : function(force, onlyEqual) {
  12338. // we loop over all nodes in the list
  12339. for (var nodeId in this.nodes) {
  12340. // we check if it is still available since it can be used by the clustering in this loop
  12341. if (this.nodes.hasOwnProperty(nodeId)) {
  12342. this._formClusterFromHub(this.nodes[nodeId],force,onlyEqual);
  12343. }
  12344. }
  12345. },
  12346. /**
  12347. * This function forms a cluster from a specific preselected hub node
  12348. *
  12349. * @param {Node} hubNode | the node we will cluster as a hub
  12350. * @param {Boolean} force | Disregard zoom level
  12351. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  12352. * @param {Number} [absorptionSizeOffset] |
  12353. * @private
  12354. */
  12355. _formClusterFromHub : function(hubNode, force, onlyEqual, absorptionSizeOffset) {
  12356. if (absorptionSizeOffset === undefined) {
  12357. absorptionSizeOffset = 0;
  12358. }
  12359. // we decide if the node is a hub
  12360. if ((hubNode.dynamicEdgesLength >= this.hubThreshold && onlyEqual == false) ||
  12361. (hubNode.dynamicEdgesLength == this.hubThreshold && onlyEqual == true)) {
  12362. // initialize variables
  12363. var dx,dy,length;
  12364. var minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  12365. var allowCluster = false;
  12366. // we create a list of edges because the dynamicEdges change over the course of this loop
  12367. var edgesIdarray = [];
  12368. var amountOfInitialEdges = hubNode.dynamicEdges.length;
  12369. for (var j = 0; j < amountOfInitialEdges; j++) {
  12370. edgesIdarray.push(hubNode.dynamicEdges[j].id);
  12371. }
  12372. // if the hub clustering is not forces, we check if one of the edges connected
  12373. // to a cluster is small enough based on the constants.clustering.clusterEdgeThreshold
  12374. if (force == false) {
  12375. allowCluster = false;
  12376. for (j = 0; j < amountOfInitialEdges; j++) {
  12377. var edge = this.edges[edgesIdarray[j]];
  12378. if (edge !== undefined) {
  12379. if (edge.connected) {
  12380. if (edge.toId != edge.fromId) {
  12381. dx = (edge.to.x - edge.from.x);
  12382. dy = (edge.to.y - edge.from.y);
  12383. length = Math.sqrt(dx * dx + dy * dy);
  12384. if (length < minLength) {
  12385. allowCluster = true;
  12386. break;
  12387. }
  12388. }
  12389. }
  12390. }
  12391. }
  12392. }
  12393. // start the clustering if allowed
  12394. if ((!force && allowCluster) || force) {
  12395. // we loop over all edges INITIALLY connected to this hub
  12396. for (j = 0; j < amountOfInitialEdges; j++) {
  12397. edge = this.edges[edgesIdarray[j]];
  12398. // the edge can be clustered by this function in a previous loop
  12399. if (edge !== undefined) {
  12400. var childNode = this.nodes[(edge.fromId == hubNode.id) ? edge.toId : edge.fromId];
  12401. // we do not want hubs to merge with other hubs nor do we want to cluster itself.
  12402. if ((childNode.dynamicEdges.length <= (this.hubThreshold + absorptionSizeOffset)) &&
  12403. (childNode.id != hubNode.id)) {
  12404. this._addToCluster(hubNode,childNode,force);
  12405. }
  12406. }
  12407. }
  12408. }
  12409. }
  12410. },
  12411. /**
  12412. * This function adds the child node to the parent node, creating a cluster if it is not already.
  12413. *
  12414. * @param {Node} parentNode | this is the node that will house the child node
  12415. * @param {Node} childNode | this node will be deleted from the global this.nodes and stored in the parent node
  12416. * @param {Boolean} force | true will only update the remainingEdges at the very end of the clustering, ensuring single level collapse
  12417. * @private
  12418. */
  12419. _addToCluster : function(parentNode, childNode, force) {
  12420. // join child node in the parent node
  12421. parentNode.containedNodes[childNode.id] = childNode;
  12422. // manage all the edges connected to the child and parent nodes
  12423. for (var i = 0; i < childNode.dynamicEdges.length; i++) {
  12424. var edge = childNode.dynamicEdges[i];
  12425. if (edge.toId == parentNode.id || edge.fromId == parentNode.id) { // edge connected to parentNode
  12426. this._addToContainedEdges(parentNode,childNode,edge);
  12427. }
  12428. else {
  12429. this._connectEdgeToCluster(parentNode,childNode,edge);
  12430. }
  12431. }
  12432. // a contained node has no dynamic edges.
  12433. childNode.dynamicEdges = [];
  12434. // remove circular edges from clusters
  12435. this._containCircularEdgesFromNode(parentNode,childNode);
  12436. // remove the childNode from the global nodes object
  12437. delete this.nodes[childNode.id];
  12438. // update the properties of the child and parent
  12439. var massBefore = parentNode.mass;
  12440. childNode.clusterSession = this.clusterSession;
  12441. parentNode.mass += childNode.mass;
  12442. parentNode.clusterSize += childNode.clusterSize;
  12443. parentNode.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize);
  12444. // keep track of the clustersessions so we can open the cluster up as it has been formed.
  12445. if (parentNode.clusterSessions[parentNode.clusterSessions.length - 1] != this.clusterSession) {
  12446. parentNode.clusterSessions.push(this.clusterSession);
  12447. }
  12448. // forced clusters only open from screen size and double tap
  12449. if (force == true) {
  12450. // parentNode.formationScale = Math.pow(1 - (1.0/11.0),this.clusterSession+3);
  12451. parentNode.formationScale = 0;
  12452. }
  12453. else {
  12454. parentNode.formationScale = this.scale; // The latest child has been added on this scale
  12455. }
  12456. // recalculate the size of the node on the next time the node is rendered
  12457. parentNode.clearSizeCache();
  12458. // set the pop-out scale for the childnode
  12459. parentNode.containedNodes[childNode.id].formationScale = parentNode.formationScale;
  12460. // nullify the movement velocity of the child, this is to avoid hectic behaviour
  12461. childNode.clearVelocity();
  12462. // the mass has altered, preservation of energy dictates the velocity to be updated
  12463. parentNode.updateVelocity(massBefore);
  12464. // restart the simulation to reorganise all nodes
  12465. this.moving = true;
  12466. },
  12467. /**
  12468. * This function will apply the changes made to the remainingEdges during the formation of the clusters.
  12469. * This is a seperate function to allow for level-wise collapsing of the node barnesHutTree.
  12470. * It has to be called if a level is collapsed. It is called by _formClusters().
  12471. * @private
  12472. */
  12473. _updateDynamicEdges : function() {
  12474. for (var i = 0; i < this.nodeIndices.length; i++) {
  12475. var node = this.nodes[this.nodeIndices[i]];
  12476. node.dynamicEdgesLength = node.dynamicEdges.length;
  12477. // this corrects for multiple edges pointing at the same other node
  12478. var correction = 0;
  12479. if (node.dynamicEdgesLength > 1) {
  12480. for (var j = 0; j < node.dynamicEdgesLength - 1; j++) {
  12481. var edgeToId = node.dynamicEdges[j].toId;
  12482. var edgeFromId = node.dynamicEdges[j].fromId;
  12483. for (var k = j+1; k < node.dynamicEdgesLength; k++) {
  12484. if ((node.dynamicEdges[k].toId == edgeToId && node.dynamicEdges[k].fromId == edgeFromId) ||
  12485. (node.dynamicEdges[k].fromId == edgeToId && node.dynamicEdges[k].toId == edgeFromId)) {
  12486. correction += 1;
  12487. }
  12488. }
  12489. }
  12490. }
  12491. node.dynamicEdgesLength -= correction;
  12492. }
  12493. },
  12494. /**
  12495. * This adds an edge from the childNode to the contained edges of the parent node
  12496. *
  12497. * @param parentNode | Node object
  12498. * @param childNode | Node object
  12499. * @param edge | Edge object
  12500. * @private
  12501. */
  12502. _addToContainedEdges : function(parentNode, childNode, edge) {
  12503. // create an array object if it does not yet exist for this childNode
  12504. if (!(parentNode.containedEdges.hasOwnProperty(childNode.id))) {
  12505. parentNode.containedEdges[childNode.id] = []
  12506. }
  12507. // add this edge to the list
  12508. parentNode.containedEdges[childNode.id].push(edge);
  12509. // remove the edge from the global edges object
  12510. delete this.edges[edge.id];
  12511. // remove the edge from the parent object
  12512. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12513. if (parentNode.dynamicEdges[i].id == edge.id) {
  12514. parentNode.dynamicEdges.splice(i,1);
  12515. break;
  12516. }
  12517. }
  12518. },
  12519. /**
  12520. * This function connects an edge that was connected to a child node to the parent node.
  12521. * It keeps track of which nodes it has been connected to with the originalId array.
  12522. *
  12523. * @param {Node} parentNode | Node object
  12524. * @param {Node} childNode | Node object
  12525. * @param {Edge} edge | Edge object
  12526. * @private
  12527. */
  12528. _connectEdgeToCluster : function(parentNode, childNode, edge) {
  12529. // handle circular edges
  12530. if (edge.toId == edge.fromId) {
  12531. this._addToContainedEdges(parentNode, childNode, edge);
  12532. }
  12533. else {
  12534. if (edge.toId == childNode.id) { // edge connected to other node on the "to" side
  12535. edge.originalToId.push(childNode.id);
  12536. edge.to = parentNode;
  12537. edge.toId = parentNode.id;
  12538. }
  12539. else { // edge connected to other node with the "from" side
  12540. edge.originalFromId.push(childNode.id);
  12541. edge.from = parentNode;
  12542. edge.fromId = parentNode.id;
  12543. }
  12544. this._addToReroutedEdges(parentNode,childNode,edge);
  12545. }
  12546. },
  12547. /**
  12548. * If a node is connected to itself, a circular edge is drawn. When clustering we want to contain
  12549. * these edges inside of the cluster.
  12550. *
  12551. * @param parentNode
  12552. * @param childNode
  12553. * @private
  12554. */
  12555. _containCircularEdgesFromNode : function(parentNode, childNode) {
  12556. // manage all the edges connected to the child and parent nodes
  12557. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12558. var edge = parentNode.dynamicEdges[i];
  12559. // handle circular edges
  12560. if (edge.toId == edge.fromId) {
  12561. this._addToContainedEdges(parentNode, childNode, edge);
  12562. }
  12563. }
  12564. },
  12565. /**
  12566. * This adds an edge from the childNode to the rerouted edges of the parent node
  12567. *
  12568. * @param parentNode | Node object
  12569. * @param childNode | Node object
  12570. * @param edge | Edge object
  12571. * @private
  12572. */
  12573. _addToReroutedEdges : function(parentNode, childNode, edge) {
  12574. // create an array object if it does not yet exist for this childNode
  12575. // we store the edge in the rerouted edges so we can restore it when the cluster pops open
  12576. if (!(parentNode.reroutedEdges.hasOwnProperty(childNode.id))) {
  12577. parentNode.reroutedEdges[childNode.id] = [];
  12578. }
  12579. parentNode.reroutedEdges[childNode.id].push(edge);
  12580. // this edge becomes part of the dynamicEdges of the cluster node
  12581. parentNode.dynamicEdges.push(edge);
  12582. },
  12583. /**
  12584. * This function connects an edge that was connected to a cluster node back to the child node.
  12585. *
  12586. * @param parentNode | Node object
  12587. * @param childNode | Node object
  12588. * @private
  12589. */
  12590. _connectEdgeBackToChild : function(parentNode, childNode) {
  12591. if (parentNode.reroutedEdges.hasOwnProperty(childNode.id)) {
  12592. for (var i = 0; i < parentNode.reroutedEdges[childNode.id].length; i++) {
  12593. var edge = parentNode.reroutedEdges[childNode.id][i];
  12594. if (edge.originalFromId[edge.originalFromId.length-1] == childNode.id) {
  12595. edge.originalFromId.pop();
  12596. edge.fromId = childNode.id;
  12597. edge.from = childNode;
  12598. }
  12599. else {
  12600. edge.originalToId.pop();
  12601. edge.toId = childNode.id;
  12602. edge.to = childNode;
  12603. }
  12604. // append this edge to the list of edges connecting to the childnode
  12605. childNode.dynamicEdges.push(edge);
  12606. // remove the edge from the parent object
  12607. for (var j = 0; j < parentNode.dynamicEdges.length; j++) {
  12608. if (parentNode.dynamicEdges[j].id == edge.id) {
  12609. parentNode.dynamicEdges.splice(j,1);
  12610. break;
  12611. }
  12612. }
  12613. }
  12614. // remove the entry from the rerouted edges
  12615. delete parentNode.reroutedEdges[childNode.id];
  12616. }
  12617. },
  12618. /**
  12619. * When loops are clustered, an edge can be both in the rerouted array and the contained array.
  12620. * This function is called last to verify that all edges in dynamicEdges are in fact connected to the
  12621. * parentNode
  12622. *
  12623. * @param parentNode | Node object
  12624. * @private
  12625. */
  12626. _validateEdges : function(parentNode) {
  12627. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12628. var edge = parentNode.dynamicEdges[i];
  12629. if (parentNode.id != edge.toId && parentNode.id != edge.fromId) {
  12630. parentNode.dynamicEdges.splice(i,1);
  12631. }
  12632. }
  12633. },
  12634. /**
  12635. * This function released the contained edges back into the global domain and puts them back into the
  12636. * dynamic edges of both parent and child.
  12637. *
  12638. * @param {Node} parentNode |
  12639. * @param {Node} childNode |
  12640. * @private
  12641. */
  12642. _releaseContainedEdges : function(parentNode, childNode) {
  12643. for (var i = 0; i < parentNode.containedEdges[childNode.id].length; i++) {
  12644. var edge = parentNode.containedEdges[childNode.id][i];
  12645. // put the edge back in the global edges object
  12646. this.edges[edge.id] = edge;
  12647. // put the edge back in the dynamic edges of the child and parent
  12648. childNode.dynamicEdges.push(edge);
  12649. parentNode.dynamicEdges.push(edge);
  12650. }
  12651. // remove the entry from the contained edges
  12652. delete parentNode.containedEdges[childNode.id];
  12653. },
  12654. // ------------------- UTILITY FUNCTIONS ---------------------------- //
  12655. /**
  12656. * This updates the node labels for all nodes (for debugging purposes)
  12657. */
  12658. updateLabels : function() {
  12659. var nodeId;
  12660. // update node labels
  12661. for (nodeId in this.nodes) {
  12662. if (this.nodes.hasOwnProperty(nodeId)) {
  12663. var node = this.nodes[nodeId];
  12664. if (node.clusterSize > 1) {
  12665. node.label = "[".concat(String(node.clusterSize),"]");
  12666. }
  12667. }
  12668. }
  12669. // update node labels
  12670. for (nodeId in this.nodes) {
  12671. if (this.nodes.hasOwnProperty(nodeId)) {
  12672. node = this.nodes[nodeId];
  12673. if (node.clusterSize == 1) {
  12674. if (node.originalLabel !== undefined) {
  12675. node.label = node.originalLabel;
  12676. }
  12677. else {
  12678. node.label = String(node.id);
  12679. }
  12680. }
  12681. }
  12682. }
  12683. // /* Debug Override */
  12684. // for (nodeId in this.nodes) {
  12685. // if (this.nodes.hasOwnProperty(nodeId)) {
  12686. // node = this.nodes[nodeId];
  12687. // node.label = String(node.level);
  12688. // }
  12689. // }
  12690. },
  12691. /**
  12692. * We want to keep the cluster level distribution rather small. This means we do not want unclustered nodes
  12693. * if the rest of the nodes are already a few cluster levels in.
  12694. * To fix this we use this function. It determines the min and max cluster level and sends nodes that have not
  12695. * clustered enough to the clusterToSmallestNeighbours function.
  12696. */
  12697. normalizeClusterLevels : function() {
  12698. var maxLevel = 0;
  12699. var minLevel = 1e9;
  12700. var clusterLevel = 0;
  12701. var nodeId;
  12702. // we loop over all nodes in the list
  12703. for (nodeId in this.nodes) {
  12704. if (this.nodes.hasOwnProperty(nodeId)) {
  12705. clusterLevel = this.nodes[nodeId].clusterSessions.length;
  12706. if (maxLevel < clusterLevel) {maxLevel = clusterLevel;}
  12707. if (minLevel > clusterLevel) {minLevel = clusterLevel;}
  12708. }
  12709. }
  12710. if (maxLevel - minLevel > this.constants.clustering.clusterLevelDifference) {
  12711. var amountOfNodes = this.nodeIndices.length;
  12712. var targetLevel = maxLevel - this.constants.clustering.clusterLevelDifference;
  12713. // we loop over all nodes in the list
  12714. for (nodeId in this.nodes) {
  12715. if (this.nodes.hasOwnProperty(nodeId)) {
  12716. if (this.nodes[nodeId].clusterSessions.length < targetLevel) {
  12717. this._clusterToSmallestNeighbour(this.nodes[nodeId]);
  12718. }
  12719. }
  12720. }
  12721. this._updateNodeIndexList();
  12722. this._updateDynamicEdges();
  12723. // if a cluster was formed, we increase the clusterSession
  12724. if (this.nodeIndices.length != amountOfNodes) {
  12725. this.clusterSession += 1;
  12726. }
  12727. }
  12728. },
  12729. /**
  12730. * This function determines if the cluster we want to decluster is in the active area
  12731. * this means around the zoom center
  12732. *
  12733. * @param {Node} node
  12734. * @returns {boolean}
  12735. * @private
  12736. */
  12737. _nodeInActiveArea : function(node) {
  12738. return (
  12739. Math.abs(node.x - this.areaCenter.x) <= this.constants.clustering.activeAreaBoxSize/this.scale
  12740. &&
  12741. Math.abs(node.y - this.areaCenter.y) <= this.constants.clustering.activeAreaBoxSize/this.scale
  12742. )
  12743. },
  12744. /**
  12745. * This is an adaptation of the original repositioning function. This is called if the system is clustered initially
  12746. * It puts large clusters away from the center and randomizes the order.
  12747. *
  12748. */
  12749. repositionNodes : function() {
  12750. for (var i = 0; i < this.nodeIndices.length; i++) {
  12751. var node = this.nodes[this.nodeIndices[i]];
  12752. if ((node.xFixed == false || node.yFixed == false)) {
  12753. var radius = 10 * 0.1*this.nodeIndices.length * Math.min(100,node.mass);
  12754. var angle = 2 * Math.PI * Math.random();
  12755. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  12756. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  12757. this._repositionBezierNodes(node);
  12758. }
  12759. }
  12760. },
  12761. /**
  12762. * We determine how many connections denote an important hub.
  12763. * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%)
  12764. *
  12765. * @private
  12766. */
  12767. _getHubSize : function() {
  12768. var average = 0;
  12769. var averageSquared = 0;
  12770. var hubCounter = 0;
  12771. var largestHub = 0;
  12772. for (var i = 0; i < this.nodeIndices.length; i++) {
  12773. var node = this.nodes[this.nodeIndices[i]];
  12774. if (node.dynamicEdgesLength > largestHub) {
  12775. largestHub = node.dynamicEdgesLength;
  12776. }
  12777. average += node.dynamicEdgesLength;
  12778. averageSquared += Math.pow(node.dynamicEdgesLength,2);
  12779. hubCounter += 1;
  12780. }
  12781. average = average / hubCounter;
  12782. averageSquared = averageSquared / hubCounter;
  12783. var variance = averageSquared - Math.pow(average,2);
  12784. var standardDeviation = Math.sqrt(variance);
  12785. this.hubThreshold = Math.floor(average + 2*standardDeviation);
  12786. // always have at least one to cluster
  12787. if (this.hubThreshold > largestHub) {
  12788. this.hubThreshold = largestHub;
  12789. }
  12790. // console.log("average",average,"averageSQ",averageSquared,"var",variance,"std",standardDeviation);
  12791. // console.log("hubThreshold:",this.hubThreshold);
  12792. },
  12793. /**
  12794. * We reduce the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  12795. * with this amount we can cluster specifically on these chains.
  12796. *
  12797. * @param {Number} fraction | between 0 and 1, the percentage of chains to reduce
  12798. * @private
  12799. */
  12800. _reduceAmountOfChains : function(fraction) {
  12801. this.hubThreshold = 2;
  12802. var reduceAmount = Math.floor(this.nodeIndices.length * fraction);
  12803. for (var nodeId in this.nodes) {
  12804. if (this.nodes.hasOwnProperty(nodeId)) {
  12805. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  12806. if (reduceAmount > 0) {
  12807. this._formClusterFromHub(this.nodes[nodeId],true,true,1);
  12808. reduceAmount -= 1;
  12809. }
  12810. }
  12811. }
  12812. }
  12813. },
  12814. /**
  12815. * We get the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  12816. * with this amount we can cluster specifically on these chains.
  12817. *
  12818. * @private
  12819. */
  12820. _getChainFraction : function() {
  12821. var chains = 0;
  12822. var total = 0;
  12823. for (var nodeId in this.nodes) {
  12824. if (this.nodes.hasOwnProperty(nodeId)) {
  12825. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  12826. chains += 1;
  12827. }
  12828. total += 1;
  12829. }
  12830. }
  12831. return chains/total;
  12832. }
  12833. };
  12834. var SelectionMixin = {
  12835. /**
  12836. * This function can be called from the _doInAllSectors function
  12837. *
  12838. * @param object
  12839. * @param overlappingNodes
  12840. * @private
  12841. */
  12842. _getNodesOverlappingWith : function(object, overlappingNodes) {
  12843. var nodes = this.nodes;
  12844. for (var nodeId in nodes) {
  12845. if (nodes.hasOwnProperty(nodeId)) {
  12846. if (nodes[nodeId].isOverlappingWith(object)) {
  12847. overlappingNodes.push(nodeId);
  12848. }
  12849. }
  12850. }
  12851. },
  12852. /**
  12853. * retrieve all nodes overlapping with given object
  12854. * @param {Object} object An object with parameters left, top, right, bottom
  12855. * @return {Number[]} An array with id's of the overlapping nodes
  12856. * @private
  12857. */
  12858. _getAllNodesOverlappingWith : function (object) {
  12859. var overlappingNodes = [];
  12860. this._doInAllActiveSectors("_getNodesOverlappingWith",object,overlappingNodes);
  12861. return overlappingNodes;
  12862. },
  12863. /**
  12864. * Return a position object in canvasspace from a single point in screenspace
  12865. *
  12866. * @param pointer
  12867. * @returns {{left: number, top: number, right: number, bottom: number}}
  12868. * @private
  12869. */
  12870. _pointerToPositionObject : function(pointer) {
  12871. var x = this._XconvertDOMtoCanvas(pointer.x);
  12872. var y = this._YconvertDOMtoCanvas(pointer.y);
  12873. return {left: x,
  12874. top: y,
  12875. right: x,
  12876. bottom: y};
  12877. },
  12878. /**
  12879. * Get the top node at the a specific point (like a click)
  12880. *
  12881. * @param {{x: Number, y: Number}} pointer
  12882. * @return {Node | null} node
  12883. * @private
  12884. */
  12885. _getNodeAt : function (pointer) {
  12886. // we first check if this is an navigation controls element
  12887. var positionObject = this._pointerToPositionObject(pointer);
  12888. var overlappingNodes = this._getAllNodesOverlappingWith(positionObject);
  12889. // if there are overlapping nodes, select the last one, this is the
  12890. // one which is drawn on top of the others
  12891. if (overlappingNodes.length > 0) {
  12892. return this.nodes[overlappingNodes[overlappingNodes.length - 1]];
  12893. }
  12894. else {
  12895. return null;
  12896. }
  12897. },
  12898. /**
  12899. * retrieve all edges overlapping with given object, selector is around center
  12900. * @param {Object} object An object with parameters left, top, right, bottom
  12901. * @return {Number[]} An array with id's of the overlapping nodes
  12902. * @private
  12903. */
  12904. _getEdgesOverlappingWith : function (object, overlappingEdges) {
  12905. var edges = this.edges;
  12906. for (var edgeId in edges) {
  12907. if (edges.hasOwnProperty(edgeId)) {
  12908. if (edges[edgeId].isOverlappingWith(object)) {
  12909. overlappingEdges.push(edgeId);
  12910. }
  12911. }
  12912. }
  12913. },
  12914. /**
  12915. * retrieve all nodes overlapping with given object
  12916. * @param {Object} object An object with parameters left, top, right, bottom
  12917. * @return {Number[]} An array with id's of the overlapping nodes
  12918. * @private
  12919. */
  12920. _getAllEdgesOverlappingWith : function (object) {
  12921. var overlappingEdges = [];
  12922. this._doInAllActiveSectors("_getEdgesOverlappingWith",object,overlappingEdges);
  12923. return overlappingEdges;
  12924. },
  12925. /**
  12926. * Place holder. To implement change the _getNodeAt to a _getObjectAt. Have the _getObjectAt call
  12927. * _getNodeAt and _getEdgesAt, then priortize the selection to user preferences.
  12928. *
  12929. * @param pointer
  12930. * @returns {null}
  12931. * @private
  12932. */
  12933. _getEdgeAt : function(pointer) {
  12934. var positionObject = this._pointerToPositionObject(pointer);
  12935. var overlappingEdges = this._getAllEdgesOverlappingWith(positionObject);
  12936. if (overlappingEdges.length > 0) {
  12937. return this.edges[overlappingEdges[overlappingEdges.length - 1]];
  12938. }
  12939. else {
  12940. return null;
  12941. }
  12942. },
  12943. /**
  12944. * Add object to the selection array.
  12945. *
  12946. * @param obj
  12947. * @private
  12948. */
  12949. _addToSelection : function(obj) {
  12950. if (obj instanceof Node) {
  12951. this.selectionObj.nodes[obj.id] = obj;
  12952. }
  12953. else {
  12954. this.selectionObj.edges[obj.id] = obj;
  12955. }
  12956. },
  12957. /**
  12958. * Remove a single option from selection.
  12959. *
  12960. * @param {Object} obj
  12961. * @private
  12962. */
  12963. _removeFromSelection : function(obj) {
  12964. if (obj instanceof Node) {
  12965. delete this.selectionObj.nodes[obj.id];
  12966. }
  12967. else {
  12968. delete this.selectionObj.edges[obj.id];
  12969. }
  12970. },
  12971. /**
  12972. * Unselect all. The selectionObj is useful for this.
  12973. *
  12974. * @param {Boolean} [doNotTrigger] | ignore trigger
  12975. * @private
  12976. */
  12977. _unselectAll : function(doNotTrigger) {
  12978. if (doNotTrigger === undefined) {
  12979. doNotTrigger = false;
  12980. }
  12981. for(var nodeId in this.selectionObj.nodes) {
  12982. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  12983. this.selectionObj.nodes[nodeId].unselect();
  12984. }
  12985. }
  12986. for(var edgeId in this.selectionObj.edges) {
  12987. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  12988. this.selectionObj.edges[edgeId].unselect();
  12989. }
  12990. }
  12991. this.selectionObj = {nodes:{},edges:{}};
  12992. if (doNotTrigger == false) {
  12993. this.emit('select', this.getSelection());
  12994. }
  12995. },
  12996. /**
  12997. * Unselect all clusters. The selectionObj is useful for this.
  12998. *
  12999. * @param {Boolean} [doNotTrigger] | ignore trigger
  13000. * @private
  13001. */
  13002. _unselectClusters : function(doNotTrigger) {
  13003. if (doNotTrigger === undefined) {
  13004. doNotTrigger = false;
  13005. }
  13006. for (var nodeId in this.selectionObj.nodes) {
  13007. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13008. if (this.selectionObj.nodes[nodeId].clusterSize > 1) {
  13009. this.selectionObj.nodes[nodeId].unselect();
  13010. this._removeFromSelection(this.selectionObj.nodes[nodeId]);
  13011. }
  13012. }
  13013. }
  13014. if (doNotTrigger == false) {
  13015. this.emit('select', this.getSelection());
  13016. }
  13017. },
  13018. /**
  13019. * return the number of selected nodes
  13020. *
  13021. * @returns {number}
  13022. * @private
  13023. */
  13024. _getSelectedNodeCount : function() {
  13025. var count = 0;
  13026. for (var nodeId in this.selectionObj.nodes) {
  13027. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13028. count += 1;
  13029. }
  13030. }
  13031. return count;
  13032. },
  13033. /**
  13034. * return the number of selected nodes
  13035. *
  13036. * @returns {number}
  13037. * @private
  13038. */
  13039. _getSelectedNode : function() {
  13040. for (var nodeId in this.selectionObj.nodes) {
  13041. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13042. return this.selectionObj.nodes[nodeId];
  13043. }
  13044. }
  13045. return null;
  13046. },
  13047. /**
  13048. * return the number of selected edges
  13049. *
  13050. * @returns {number}
  13051. * @private
  13052. */
  13053. _getSelectedEdgeCount : function() {
  13054. var count = 0;
  13055. for (var edgeId in this.selectionObj.edges) {
  13056. if (this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13057. count += 1;
  13058. }
  13059. }
  13060. return count;
  13061. },
  13062. /**
  13063. * return the number of selected objects.
  13064. *
  13065. * @returns {number}
  13066. * @private
  13067. */
  13068. _getSelectedObjectCount : function() {
  13069. var count = 0;
  13070. for(var nodeId in this.selectionObj.nodes) {
  13071. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13072. count += 1;
  13073. }
  13074. }
  13075. for(var edgeId in this.selectionObj.edges) {
  13076. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13077. count += 1;
  13078. }
  13079. }
  13080. return count;
  13081. },
  13082. /**
  13083. * Check if anything is selected
  13084. *
  13085. * @returns {boolean}
  13086. * @private
  13087. */
  13088. _selectionIsEmpty : function() {
  13089. for(var nodeId in this.selectionObj.nodes) {
  13090. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13091. return false;
  13092. }
  13093. }
  13094. for(var edgeId in this.selectionObj.edges) {
  13095. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13096. return false;
  13097. }
  13098. }
  13099. return true;
  13100. },
  13101. /**
  13102. * check if one of the selected nodes is a cluster.
  13103. *
  13104. * @returns {boolean}
  13105. * @private
  13106. */
  13107. _clusterInSelection : function() {
  13108. for(var nodeId in this.selectionObj.nodes) {
  13109. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13110. if (this.selectionObj.nodes[nodeId].clusterSize > 1) {
  13111. return true;
  13112. }
  13113. }
  13114. }
  13115. return false;
  13116. },
  13117. /**
  13118. * select the edges connected to the node that is being selected
  13119. *
  13120. * @param {Node} node
  13121. * @private
  13122. */
  13123. _selectConnectedEdges : function(node) {
  13124. for (var i = 0; i < node.dynamicEdges.length; i++) {
  13125. var edge = node.dynamicEdges[i];
  13126. edge.select();
  13127. this._addToSelection(edge);
  13128. }
  13129. },
  13130. /**
  13131. * unselect the edges connected to the node that is being selected
  13132. *
  13133. * @param {Node} node
  13134. * @private
  13135. */
  13136. _unselectConnectedEdges : function(node) {
  13137. for (var i = 0; i < node.dynamicEdges.length; i++) {
  13138. var edge = node.dynamicEdges[i];
  13139. edge.unselect();
  13140. this._removeFromSelection(edge);
  13141. }
  13142. },
  13143. /**
  13144. * This is called when someone clicks on a node. either select or deselect it.
  13145. * If there is an existing selection and we don't want to append to it, clear the existing selection
  13146. *
  13147. * @param {Node || Edge} object
  13148. * @param {Boolean} append
  13149. * @param {Boolean} [doNotTrigger] | ignore trigger
  13150. * @private
  13151. */
  13152. _selectObject : function(object, append, doNotTrigger) {
  13153. if (doNotTrigger === undefined) {
  13154. doNotTrigger = false;
  13155. }
  13156. if (this._selectionIsEmpty() == false && append == false && this.forceAppendSelection == false) {
  13157. this._unselectAll(true);
  13158. }
  13159. if (object.selected == false) {
  13160. object.select();
  13161. this._addToSelection(object);
  13162. if (object instanceof Node && this.blockConnectingEdgeSelection == false) {
  13163. this._selectConnectedEdges(object);
  13164. }
  13165. }
  13166. else {
  13167. object.unselect();
  13168. this._removeFromSelection(object);
  13169. }
  13170. if (doNotTrigger == false) {
  13171. this.emit('select', this.getSelection());
  13172. }
  13173. },
  13174. /**
  13175. * handles the selection part of the touch, only for navigation controls elements;
  13176. * Touch is triggered before tap, also before hold. Hold triggers after a while.
  13177. * This is the most responsive solution
  13178. *
  13179. * @param {Object} pointer
  13180. * @private
  13181. */
  13182. _handleTouch : function(pointer) {
  13183. },
  13184. /**
  13185. * handles the selection part of the tap;
  13186. *
  13187. * @param {Object} pointer
  13188. * @private
  13189. */
  13190. _handleTap : function(pointer) {
  13191. var node = this._getNodeAt(pointer);
  13192. if (node != null) {
  13193. this._selectObject(node,false);
  13194. }
  13195. else {
  13196. var edge = this._getEdgeAt(pointer);
  13197. if (edge != null) {
  13198. this._selectObject(edge,false);
  13199. }
  13200. else {
  13201. this._unselectAll();
  13202. }
  13203. }
  13204. this.emit("click", this.getSelection());
  13205. this._redraw();
  13206. },
  13207. /**
  13208. * handles the selection part of the double tap and opens a cluster if needed
  13209. *
  13210. * @param {Object} pointer
  13211. * @private
  13212. */
  13213. _handleDoubleTap : function(pointer) {
  13214. var node = this._getNodeAt(pointer);
  13215. if (node != null && node !== undefined) {
  13216. // we reset the areaCenter here so the opening of the node will occur
  13217. this.areaCenter = {"x" : this._XconvertDOMtoCanvas(pointer.x),
  13218. "y" : this._YconvertDOMtoCanvas(pointer.y)};
  13219. this.openCluster(node);
  13220. }
  13221. this.emit("doubleClick", this.getSelection());
  13222. },
  13223. /**
  13224. * Handle the onHold selection part
  13225. *
  13226. * @param pointer
  13227. * @private
  13228. */
  13229. _handleOnHold : function(pointer) {
  13230. var node = this._getNodeAt(pointer);
  13231. if (node != null) {
  13232. this._selectObject(node,true);
  13233. }
  13234. else {
  13235. var edge = this._getEdgeAt(pointer);
  13236. if (edge != null) {
  13237. this._selectObject(edge,true);
  13238. }
  13239. }
  13240. this._redraw();
  13241. },
  13242. /**
  13243. * handle the onRelease event. These functions are here for the navigation controls module.
  13244. *
  13245. * @private
  13246. */
  13247. _handleOnRelease : function(pointer) {
  13248. },
  13249. /**
  13250. *
  13251. * retrieve the currently selected objects
  13252. * @return {Number[] | String[]} selection An array with the ids of the
  13253. * selected nodes.
  13254. */
  13255. getSelection : function() {
  13256. var nodeIds = this.getSelectedNodes();
  13257. var edgeIds = this.getSelectedEdges();
  13258. return {nodes:nodeIds, edges:edgeIds};
  13259. },
  13260. /**
  13261. *
  13262. * retrieve the currently selected nodes
  13263. * @return {String} selection An array with the ids of the
  13264. * selected nodes.
  13265. */
  13266. getSelectedNodes : function() {
  13267. var idArray = [];
  13268. for(var nodeId in this.selectionObj.nodes) {
  13269. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13270. idArray.push(nodeId);
  13271. }
  13272. }
  13273. return idArray
  13274. },
  13275. /**
  13276. *
  13277. * retrieve the currently selected edges
  13278. * @return {Array} selection An array with the ids of the
  13279. * selected nodes.
  13280. */
  13281. getSelectedEdges : function() {
  13282. var idArray = [];
  13283. for(var edgeId in this.selectionObj.edges) {
  13284. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13285. idArray.push(edgeId);
  13286. }
  13287. }
  13288. return idArray;
  13289. },
  13290. /**
  13291. * select zero or more nodes
  13292. * @param {Number[] | String[]} selection An array with the ids of the
  13293. * selected nodes.
  13294. */
  13295. setSelection : function(selection) {
  13296. var i, iMax, id;
  13297. if (!selection || (selection.length == undefined))
  13298. throw 'Selection must be an array with ids';
  13299. // first unselect any selected node
  13300. this._unselectAll(true);
  13301. for (i = 0, iMax = selection.length; i < iMax; i++) {
  13302. id = selection[i];
  13303. var node = this.nodes[id];
  13304. if (!node) {
  13305. throw new RangeError('Node with id "' + id + '" not found');
  13306. }
  13307. this._selectObject(node,true,true);
  13308. }
  13309. this.redraw();
  13310. },
  13311. /**
  13312. * Validate the selection: remove ids of nodes which no longer exist
  13313. * @private
  13314. */
  13315. _updateSelection : function () {
  13316. for(var nodeId in this.selectionObj.nodes) {
  13317. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13318. if (!this.nodes.hasOwnProperty(nodeId)) {
  13319. delete this.selectionObj.nodes[nodeId];
  13320. }
  13321. }
  13322. }
  13323. for(var edgeId in this.selectionObj.edges) {
  13324. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13325. if (!this.edges.hasOwnProperty(edgeId)) {
  13326. delete this.selectionObj.edges[edgeId];
  13327. }
  13328. }
  13329. }
  13330. }
  13331. };
  13332. /**
  13333. * Created by Alex on 1/22/14.
  13334. */
  13335. var NavigationMixin = {
  13336. _cleanNavigation : function() {
  13337. // clean up previosu navigation items
  13338. var wrapper = document.getElementById('graph-navigation_wrapper');
  13339. if (wrapper != null) {
  13340. this.containerElement.removeChild(wrapper);
  13341. }
  13342. document.onmouseup = null;
  13343. },
  13344. /**
  13345. * Creation of the navigation controls nodes. They are drawn over the rest of the nodes and are not affected by scale and translation
  13346. * they have a triggerFunction which is called on click. If the position of the navigation controls is dependent
  13347. * on this.frame.canvas.clientWidth or this.frame.canvas.clientHeight, we flag horizontalAlignLeft and verticalAlignTop false.
  13348. * This means that the location will be corrected by the _relocateNavigation function on a size change of the canvas.
  13349. *
  13350. * @private
  13351. */
  13352. _loadNavigationElements : function() {
  13353. this._cleanNavigation();
  13354. this.navigationDivs = {};
  13355. var navigationDivs = ['up','down','left','right','zoomIn','zoomOut','zoomExtends'];
  13356. var navigationDivActions = ['_moveUp','_moveDown','_moveLeft','_moveRight','_zoomIn','_zoomOut','zoomExtent'];
  13357. this.navigationDivs['wrapper'] = document.createElement('div');
  13358. this.navigationDivs['wrapper'].id = "graph-navigation_wrapper";
  13359. this.navigationDivs['wrapper'].style.position = "absolute";
  13360. this.navigationDivs['wrapper'].style.width = this.frame.canvas.clientWidth + "px";
  13361. this.navigationDivs['wrapper'].style.height = this.frame.canvas.clientHeight + "px";
  13362. this.containerElement.insertBefore(this.navigationDivs['wrapper'],this.frame);
  13363. for (var i = 0; i < navigationDivs.length; i++) {
  13364. this.navigationDivs[navigationDivs[i]] = document.createElement('div');
  13365. this.navigationDivs[navigationDivs[i]].id = "graph-navigation_" + navigationDivs[i];
  13366. this.navigationDivs[navigationDivs[i]].className = "graph-navigation " + navigationDivs[i];
  13367. this.navigationDivs['wrapper'].appendChild(this.navigationDivs[navigationDivs[i]]);
  13368. this.navigationDivs[navigationDivs[i]].onmousedown = this[navigationDivActions[i]].bind(this);
  13369. }
  13370. document.onmouseup = this._stopMovement.bind(this);
  13371. },
  13372. /**
  13373. * this stops all movement induced by the navigation buttons
  13374. *
  13375. * @private
  13376. */
  13377. _stopMovement : function() {
  13378. this._xStopMoving();
  13379. this._yStopMoving();
  13380. this._stopZoom();
  13381. },
  13382. /**
  13383. * stops the actions performed by page up and down etc.
  13384. *
  13385. * @param event
  13386. * @private
  13387. */
  13388. _preventDefault : function(event) {
  13389. if (event !== undefined) {
  13390. if (event.preventDefault) {
  13391. event.preventDefault();
  13392. } else {
  13393. event.returnValue = false;
  13394. }
  13395. }
  13396. },
  13397. /**
  13398. * move the screen up
  13399. * By using the increments, instead of adding a fixed number to the translation, we keep fluent and
  13400. * instant movement. The onKeypress event triggers immediately, then pauses, then triggers frequently
  13401. * To avoid this behaviour, we do the translation in the start loop.
  13402. *
  13403. * @private
  13404. */
  13405. _moveUp : function(event) {
  13406. this.yIncrement = this.constants.keyboard.speed.y;
  13407. this.start(); // if there is no node movement, the calculation wont be done
  13408. this._preventDefault(event);
  13409. if (this.navigationDivs) {
  13410. this.navigationDivs['up'].className += " active";
  13411. }
  13412. },
  13413. /**
  13414. * move the screen down
  13415. * @private
  13416. */
  13417. _moveDown : function(event) {
  13418. this.yIncrement = -this.constants.keyboard.speed.y;
  13419. this.start(); // if there is no node movement, the calculation wont be done
  13420. this._preventDefault(event);
  13421. if (this.navigationDivs) {
  13422. this.navigationDivs['down'].className += " active";
  13423. }
  13424. },
  13425. /**
  13426. * move the screen left
  13427. * @private
  13428. */
  13429. _moveLeft : function(event) {
  13430. this.xIncrement = this.constants.keyboard.speed.x;
  13431. this.start(); // if there is no node movement, the calculation wont be done
  13432. this._preventDefault(event);
  13433. if (this.navigationDivs) {
  13434. this.navigationDivs['left'].className += " active";
  13435. }
  13436. },
  13437. /**
  13438. * move the screen right
  13439. * @private
  13440. */
  13441. _moveRight : function(event) {
  13442. this.xIncrement = -this.constants.keyboard.speed.y;
  13443. this.start(); // if there is no node movement, the calculation wont be done
  13444. this._preventDefault(event);
  13445. if (this.navigationDivs) {
  13446. this.navigationDivs['right'].className += " active";
  13447. }
  13448. },
  13449. /**
  13450. * Zoom in, using the same method as the movement.
  13451. * @private
  13452. */
  13453. _zoomIn : function(event) {
  13454. this.zoomIncrement = this.constants.keyboard.speed.zoom;
  13455. this.start(); // if there is no node movement, the calculation wont be done
  13456. this._preventDefault(event);
  13457. if (this.navigationDivs) {
  13458. this.navigationDivs['zoomIn'].className += " active";
  13459. }
  13460. },
  13461. /**
  13462. * Zoom out
  13463. * @private
  13464. */
  13465. _zoomOut : function() {
  13466. this.zoomIncrement = -this.constants.keyboard.speed.zoom;
  13467. this.start(); // if there is no node movement, the calculation wont be done
  13468. this._preventDefault(event);
  13469. if (this.navigationDivs) {
  13470. this.navigationDivs['zoomOut'].className += " active";
  13471. }
  13472. },
  13473. /**
  13474. * Stop zooming and unhighlight the zoom controls
  13475. * @private
  13476. */
  13477. _stopZoom : function() {
  13478. this.zoomIncrement = 0;
  13479. if (this.navigationDivs) {
  13480. this.navigationDivs['zoomIn'].className = this.navigationDivs['zoomIn'].className.replace(" active","");
  13481. this.navigationDivs['zoomOut'].className = this.navigationDivs['zoomOut'].className.replace(" active","");
  13482. }
  13483. },
  13484. /**
  13485. * Stop moving in the Y direction and unHighlight the up and down
  13486. * @private
  13487. */
  13488. _yStopMoving : function() {
  13489. this.yIncrement = 0;
  13490. if (this.navigationDivs) {
  13491. this.navigationDivs['up'].className = this.navigationDivs['up'].className.replace(" active","");
  13492. this.navigationDivs['down'].className = this.navigationDivs['down'].className.replace(" active","");
  13493. }
  13494. },
  13495. /**
  13496. * Stop moving in the X direction and unHighlight left and right.
  13497. * @private
  13498. */
  13499. _xStopMoving : function() {
  13500. this.xIncrement = 0;
  13501. if (this.navigationDivs) {
  13502. this.navigationDivs['left'].className = this.navigationDivs['left'].className.replace(" active","");
  13503. this.navigationDivs['right'].className = this.navigationDivs['right'].className.replace(" active","");
  13504. }
  13505. }
  13506. };
  13507. /**
  13508. * Created by Alex on 2/10/14.
  13509. */
  13510. var graphMixinLoaders = {
  13511. /**
  13512. * Load a mixin into the graph object
  13513. *
  13514. * @param {Object} sourceVariable | this object has to contain functions.
  13515. * @private
  13516. */
  13517. _loadMixin: function (sourceVariable) {
  13518. for (var mixinFunction in sourceVariable) {
  13519. if (sourceVariable.hasOwnProperty(mixinFunction)) {
  13520. Graph.prototype[mixinFunction] = sourceVariable[mixinFunction];
  13521. }
  13522. }
  13523. },
  13524. /**
  13525. * removes a mixin from the graph object.
  13526. *
  13527. * @param {Object} sourceVariable | this object has to contain functions.
  13528. * @private
  13529. */
  13530. _clearMixin: function (sourceVariable) {
  13531. for (var mixinFunction in sourceVariable) {
  13532. if (sourceVariable.hasOwnProperty(mixinFunction)) {
  13533. Graph.prototype[mixinFunction] = undefined;
  13534. }
  13535. }
  13536. },
  13537. /**
  13538. * Mixin the physics system and initialize the parameters required.
  13539. *
  13540. * @private
  13541. */
  13542. _loadPhysicsSystem: function () {
  13543. this._loadMixin(physicsMixin);
  13544. this._loadSelectedForceSolver();
  13545. if (this.constants.configurePhysics == true) {
  13546. this._loadPhysicsConfiguration();
  13547. }
  13548. },
  13549. /**
  13550. * Mixin the cluster system and initialize the parameters required.
  13551. *
  13552. * @private
  13553. */
  13554. _loadClusterSystem: function () {
  13555. this.clusterSession = 0;
  13556. this.hubThreshold = 5;
  13557. this._loadMixin(ClusterMixin);
  13558. },
  13559. /**
  13560. * Mixin the sector system and initialize the parameters required
  13561. *
  13562. * @private
  13563. */
  13564. _loadSectorSystem: function () {
  13565. this.sectors = {};
  13566. this.activeSector = ["default"];
  13567. this.sectors["active"] = {};
  13568. this.sectors["active"]["default"] = {"nodes": {},
  13569. "edges": {},
  13570. "nodeIndices": [],
  13571. "formationScale": 1.0,
  13572. "drawingNode": undefined };
  13573. this.sectors["frozen"] = {};
  13574. this.sectors["support"] = {"nodes": {},
  13575. "edges": {},
  13576. "nodeIndices": [],
  13577. "formationScale": 1.0,
  13578. "drawingNode": undefined };
  13579. this.nodeIndices = this.sectors["active"]["default"]["nodeIndices"]; // the node indices list is used to speed up the computation of the repulsion fields
  13580. this._loadMixin(SectorMixin);
  13581. },
  13582. /**
  13583. * Mixin the selection system and initialize the parameters required
  13584. *
  13585. * @private
  13586. */
  13587. _loadSelectionSystem: function () {
  13588. this.selectionObj = {nodes: {}, edges: {}};
  13589. this._loadMixin(SelectionMixin);
  13590. },
  13591. /**
  13592. * Mixin the navigationUI (User Interface) system and initialize the parameters required
  13593. *
  13594. * @private
  13595. */
  13596. _loadManipulationSystem: function () {
  13597. // reset global variables -- these are used by the selection of nodes and edges.
  13598. this.blockConnectingEdgeSelection = false;
  13599. this.forceAppendSelection = false;
  13600. if (this.constants.dataManipulation.enabled == true) {
  13601. // load the manipulator HTML elements. All styling done in css.
  13602. if (this.manipulationDiv === undefined) {
  13603. this.manipulationDiv = document.createElement('div');
  13604. this.manipulationDiv.className = 'graph-manipulationDiv';
  13605. this.manipulationDiv.id = 'graph-manipulationDiv';
  13606. if (this.editMode == true) {
  13607. this.manipulationDiv.style.display = "block";
  13608. }
  13609. else {
  13610. this.manipulationDiv.style.display = "none";
  13611. }
  13612. this.containerElement.insertBefore(this.manipulationDiv, this.frame);
  13613. }
  13614. if (this.editModeDiv === undefined) {
  13615. this.editModeDiv = document.createElement('div');
  13616. this.editModeDiv.className = 'graph-manipulation-editMode';
  13617. this.editModeDiv.id = 'graph-manipulation-editMode';
  13618. if (this.editMode == true) {
  13619. this.editModeDiv.style.display = "none";
  13620. }
  13621. else {
  13622. this.editModeDiv.style.display = "block";
  13623. }
  13624. this.containerElement.insertBefore(this.editModeDiv, this.frame);
  13625. }
  13626. if (this.closeDiv === undefined) {
  13627. this.closeDiv = document.createElement('div');
  13628. this.closeDiv.className = 'graph-manipulation-closeDiv';
  13629. this.closeDiv.id = 'graph-manipulation-closeDiv';
  13630. this.closeDiv.style.display = this.manipulationDiv.style.display;
  13631. this.containerElement.insertBefore(this.closeDiv, this.frame);
  13632. }
  13633. // load the manipulation functions
  13634. this._loadMixin(manipulationMixin);
  13635. // create the manipulator toolbar
  13636. this._createManipulatorBar();
  13637. }
  13638. else {
  13639. if (this.manipulationDiv !== undefined) {
  13640. // removes all the bindings and overloads
  13641. this._createManipulatorBar();
  13642. // remove the manipulation divs
  13643. this.containerElement.removeChild(this.manipulationDiv);
  13644. this.containerElement.removeChild(this.editModeDiv);
  13645. this.containerElement.removeChild(this.closeDiv);
  13646. this.manipulationDiv = undefined;
  13647. this.editModeDiv = undefined;
  13648. this.closeDiv = undefined;
  13649. // remove the mixin functions
  13650. this._clearMixin(manipulationMixin);
  13651. }
  13652. }
  13653. },
  13654. /**
  13655. * Mixin the navigation (User Interface) system and initialize the parameters required
  13656. *
  13657. * @private
  13658. */
  13659. _loadNavigationControls: function () {
  13660. this._loadMixin(NavigationMixin);
  13661. // the clean function removes the button divs, this is done to remove the bindings.
  13662. this._cleanNavigation();
  13663. if (this.constants.navigation.enabled == true) {
  13664. this._loadNavigationElements();
  13665. }
  13666. },
  13667. /**
  13668. * Mixin the hierarchical layout system.
  13669. *
  13670. * @private
  13671. */
  13672. _loadHierarchySystem: function () {
  13673. this._loadMixin(HierarchicalLayoutMixin);
  13674. }
  13675. };
  13676. /**
  13677. * @constructor Graph
  13678. * Create a graph visualization, displaying nodes and edges.
  13679. *
  13680. * @param {Element} container The DOM element in which the Graph will
  13681. * be created. Normally a div element.
  13682. * @param {Object} data An object containing parameters
  13683. * {Array} nodes
  13684. * {Array} edges
  13685. * @param {Object} options Options
  13686. */
  13687. function Graph (container, data, options) {
  13688. this._initializeMixinLoaders();
  13689. // create variables and set default values
  13690. this.containerElement = container;
  13691. this.width = '100%';
  13692. this.height = '100%';
  13693. // render and calculation settings
  13694. this.renderRefreshRate = 60; // hz (fps)
  13695. this.renderTimestep = 1000 / this.renderRefreshRate; // ms -- saves calculation later on
  13696. this.renderTime = 0.5 * this.renderTimestep; // measured time it takes to render a frame
  13697. this.maxPhysicsTicksPerRender = 3; // max amount of physics ticks per render step.
  13698. this.physicsDiscreteStepsize = 0.65; // discrete stepsize of the simulation
  13699. this.stabilize = true; // stabilize before displaying the graph
  13700. this.selectable = true;
  13701. this.initializing = true;
  13702. // these functions are triggered when the dataset is edited
  13703. this.triggerFunctions = {add:null,edit:null,connect:null,del:null};
  13704. // set constant values
  13705. this.constants = {
  13706. nodes: {
  13707. radiusMin: 5,
  13708. radiusMax: 20,
  13709. radius: 5,
  13710. shape: 'ellipse',
  13711. image: undefined,
  13712. widthMin: 16, // px
  13713. widthMax: 64, // px
  13714. fixed: false,
  13715. fontColor: 'black',
  13716. fontSize: 14, // px
  13717. fontFace: 'verdana',
  13718. level: -1,
  13719. color: {
  13720. border: '#2B7CE9',
  13721. background: '#97C2FC',
  13722. highlight: {
  13723. border: '#2B7CE9',
  13724. background: '#D2E5FF'
  13725. }
  13726. },
  13727. borderColor: '#2B7CE9',
  13728. backgroundColor: '#97C2FC',
  13729. highlightColor: '#D2E5FF',
  13730. group: undefined
  13731. },
  13732. edges: {
  13733. widthMin: 1,
  13734. widthMax: 15,
  13735. width: 1,
  13736. style: 'line',
  13737. color: {
  13738. color:'#848484',
  13739. highlight:'#848484'
  13740. },
  13741. fontColor: '#343434',
  13742. fontSize: 14, // px
  13743. fontFace: 'arial',
  13744. fontFill: 'white',
  13745. arrowScaleFactor: 1,
  13746. dash: {
  13747. length: 10,
  13748. gap: 5,
  13749. altLength: undefined
  13750. }
  13751. },
  13752. configurePhysics:false,
  13753. physics: {
  13754. barnesHut: {
  13755. enabled: true,
  13756. theta: 1 / 0.6, // inverted to save time during calculation
  13757. gravitationalConstant: -2000,
  13758. centralGravity: 0.3,
  13759. springLength: 95,
  13760. springConstant: 0.04,
  13761. damping: 0.09
  13762. },
  13763. repulsion: {
  13764. centralGravity: 0.1,
  13765. springLength: 200,
  13766. springConstant: 0.05,
  13767. nodeDistance: 100,
  13768. damping: 0.09
  13769. },
  13770. hierarchicalRepulsion: {
  13771. enabled: false,
  13772. centralGravity: 0.0,
  13773. springLength: 100,
  13774. springConstant: 0.01,
  13775. nodeDistance: 60,
  13776. damping: 0.09
  13777. },
  13778. damping: null,
  13779. centralGravity: null,
  13780. springLength: null,
  13781. springConstant: null
  13782. },
  13783. clustering: { // Per Node in Cluster = PNiC
  13784. enabled: false, // (Boolean) | global on/off switch for clustering.
  13785. initialMaxNodes: 100, // (# nodes) | if the initial amount of nodes is larger than this, we cluster until the total number is less than this threshold.
  13786. 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
  13787. 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
  13788. chainThreshold: 0.4, // (% of all drawn nodes)| maximum percentage of allowed chainnodes (long strings of connected nodes) within all nodes. (lower means less chains).
  13789. clusterEdgeThreshold: 20, // (px) | edge length threshold. if smaller, this node is clustered.
  13790. sectorThreshold: 100, // (# nodes in cluster) | cluster size threshold. If larger, expanding in own sector.
  13791. 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.
  13792. fontSizeMultiplier: 4.0, // (px PNiC) | how much the cluster font size grows per node in cluster (in px).
  13793. maxFontSize: 1000,
  13794. forceAmplification: 0.1, // (multiplier PNiC) | factor of increase fo the repulsion force of a cluster (per node in cluster).
  13795. distanceAmplification: 0.1, // (multiplier PNiC) | factor how much the repulsion distance of a cluster increases (per node in cluster).
  13796. edgeGrowth: 20, // (px PNiC) | amount of clusterSize connected to the edge is multiplied with this and added to edgeLength.
  13797. nodeScaling: {width: 1, // (px PNiC) | growth of the width per node in cluster.
  13798. height: 1, // (px PNiC) | growth of the height per node in cluster.
  13799. radius: 1}, // (px PNiC) | growth of the radius per node in cluster.
  13800. maxNodeSizeIncrements: 600, // (# increments) | max growth of the width per node in cluster.
  13801. activeAreaBoxSize: 80, // (px) | box area around the curser where clusters are popped open.
  13802. clusterLevelDifference: 2
  13803. },
  13804. navigation: {
  13805. enabled: false
  13806. },
  13807. keyboard: {
  13808. enabled: false,
  13809. speed: {x: 10, y: 10, zoom: 0.02}
  13810. },
  13811. dataManipulation: {
  13812. enabled: false,
  13813. initiallyVisible: false
  13814. },
  13815. hierarchicalLayout: {
  13816. enabled:false,
  13817. levelSeparation: 150,
  13818. nodeSpacing: 100,
  13819. direction: "UD" // UD, DU, LR, RL
  13820. },
  13821. freezeForStabilization: false,
  13822. smoothCurves: true,
  13823. maxVelocity: 10,
  13824. minVelocity: 0.1, // px/s
  13825. stabilizationIterations: 1000, // maximum number of iteration to stabilize
  13826. labels:{
  13827. add:"Add Node",
  13828. edit:"Edit",
  13829. link:"Add Link",
  13830. del:"Delete selected",
  13831. editNode:"Edit Node",
  13832. back:"Back",
  13833. addDescription:"Click in an empty space to place a new node.",
  13834. linkDescription:"Click on a node and drag the edge to another node to connect them.",
  13835. addError:"The function for add does not support two arguments (data,callback).",
  13836. linkError:"The function for connect does not support two arguments (data,callback).",
  13837. editError:"The function for edit does not support two arguments (data, callback).",
  13838. editBoundError:"No edit function has been bound to this button.",
  13839. deleteError:"The function for delete does not support two arguments (data, callback).",
  13840. deleteClusterError:"Clusters cannot be deleted."
  13841. },
  13842. tooltip: {
  13843. delay: 300,
  13844. fontColor: 'black',
  13845. fontSize: 14, // px
  13846. fontFace: 'verdana',
  13847. color: {
  13848. border: '#666',
  13849. background: '#FFFFC6'
  13850. }
  13851. },
  13852. moveable: true,
  13853. zoomable: true
  13854. };
  13855. this.editMode = this.constants.dataManipulation.initiallyVisible;
  13856. // Node variables
  13857. var graph = this;
  13858. this.groups = new Groups(); // object with groups
  13859. this.images = new Images(); // object with images
  13860. this.images.setOnloadCallback(function () {
  13861. graph._redraw();
  13862. });
  13863. // keyboard navigation variables
  13864. this.xIncrement = 0;
  13865. this.yIncrement = 0;
  13866. this.zoomIncrement = 0;
  13867. // loading all the mixins:
  13868. // load the force calculation functions, grouped under the physics system.
  13869. this._loadPhysicsSystem();
  13870. // create a frame and canvas
  13871. this._create();
  13872. // load the sector system. (mandatory, fully integrated with Graph)
  13873. this._loadSectorSystem();
  13874. // load the cluster system. (mandatory, even when not using the cluster system, there are function calls to it)
  13875. this._loadClusterSystem();
  13876. // load the selection system. (mandatory, required by Graph)
  13877. this._loadSelectionSystem();
  13878. // load the selection system. (mandatory, required by Graph)
  13879. this._loadHierarchySystem();
  13880. // apply options
  13881. this._setTranslation(this.frame.clientWidth / 2, this.frame.clientHeight / 2);
  13882. this._setScale(1);
  13883. this.setOptions(options);
  13884. // other vars
  13885. this.freezeSimulation = false;// freeze the simulation
  13886. this.cachedFunctions = {};
  13887. // containers for nodes and edges
  13888. this.calculationNodes = {};
  13889. this.calculationNodeIndices = [];
  13890. this.nodeIndices = []; // array with all the indices of the nodes. Used to speed up forces calculation
  13891. this.nodes = {}; // object with Node objects
  13892. this.edges = {}; // object with Edge objects
  13893. // position and scale variables and objects
  13894. this.canvasTopLeft = {"x": 0,"y": 0}; // coordinates of the top left of the canvas. they will be set during _redraw.
  13895. this.canvasBottomRight = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  13896. this.pointerPosition = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  13897. this.areaCenter = {}; // object with x and y elements used for determining the center of the zoom action
  13898. this.scale = 1; // defining the global scale variable in the constructor
  13899. this.previousScale = this.scale; // this is used to check if the zoom operation is zooming in or out
  13900. // datasets or dataviews
  13901. this.nodesData = null; // A DataSet or DataView
  13902. this.edgesData = null; // A DataSet or DataView
  13903. // create event listeners used to subscribe on the DataSets of the nodes and edges
  13904. this.nodesListeners = {
  13905. 'add': function (event, params) {
  13906. graph._addNodes(params.items);
  13907. graph.start();
  13908. },
  13909. 'update': function (event, params) {
  13910. graph._updateNodes(params.items);
  13911. graph.start();
  13912. },
  13913. 'remove': function (event, params) {
  13914. graph._removeNodes(params.items);
  13915. graph.start();
  13916. }
  13917. };
  13918. this.edgesListeners = {
  13919. 'add': function (event, params) {
  13920. graph._addEdges(params.items);
  13921. graph.start();
  13922. },
  13923. 'update': function (event, params) {
  13924. graph._updateEdges(params.items);
  13925. graph.start();
  13926. },
  13927. 'remove': function (event, params) {
  13928. graph._removeEdges(params.items);
  13929. graph.start();
  13930. }
  13931. };
  13932. // properties for the animation
  13933. this.moving = true;
  13934. this.timer = undefined; // Scheduling function. Is definded in this.start();
  13935. // load data (the disable start variable will be the same as the enabled clustering)
  13936. this.setData(data,this.constants.clustering.enabled || this.constants.hierarchicalLayout.enabled);
  13937. // hierarchical layout
  13938. this.initializing = false;
  13939. if (this.constants.hierarchicalLayout.enabled == true) {
  13940. this._setupHierarchicalLayout();
  13941. }
  13942. else {
  13943. // zoom so all data will fit on the screen, if clustering is enabled, we do not want start to be called here.
  13944. if (this.stabilize == false) {
  13945. this.zoomExtent(true,this.constants.clustering.enabled);
  13946. }
  13947. }
  13948. // if clustering is disabled, the simulation will have started in the setData function
  13949. if (this.constants.clustering.enabled) {
  13950. this.startWithClustering();
  13951. }
  13952. }
  13953. // Extend Graph with an Emitter mixin
  13954. Emitter(Graph.prototype);
  13955. /**
  13956. * Get the script path where the vis.js library is located
  13957. *
  13958. * @returns {string | null} path Path or null when not found. Path does not
  13959. * end with a slash.
  13960. * @private
  13961. */
  13962. Graph.prototype._getScriptPath = function() {
  13963. var scripts = document.getElementsByTagName( 'script' );
  13964. // find script named vis.js or vis.min.js
  13965. for (var i = 0; i < scripts.length; i++) {
  13966. var src = scripts[i].src;
  13967. var match = src && /\/?vis(.min)?\.js$/.exec(src);
  13968. if (match) {
  13969. // return path without the script name
  13970. return src.substring(0, src.length - match[0].length);
  13971. }
  13972. }
  13973. return null;
  13974. };
  13975. /**
  13976. * Find the center position of the graph
  13977. * @private
  13978. */
  13979. Graph.prototype._getRange = function() {
  13980. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  13981. for (var nodeId in this.nodes) {
  13982. if (this.nodes.hasOwnProperty(nodeId)) {
  13983. node = this.nodes[nodeId];
  13984. if (minX > (node.x)) {minX = node.x;}
  13985. if (maxX < (node.x)) {maxX = node.x;}
  13986. if (minY > (node.y)) {minY = node.y;}
  13987. if (maxY < (node.y)) {maxY = node.y;}
  13988. }
  13989. }
  13990. if (minX == 1e9 && maxX == -1e9 && minY == 1e9 && maxY == -1e9) {
  13991. minY = 0, maxY = 0, minX = 0, maxX = 0;
  13992. }
  13993. return {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  13994. };
  13995. /**
  13996. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  13997. * @returns {{x: number, y: number}}
  13998. * @private
  13999. */
  14000. Graph.prototype._findCenter = function(range) {
  14001. return {x: (0.5 * (range.maxX + range.minX)),
  14002. y: (0.5 * (range.maxY + range.minY))};
  14003. };
  14004. /**
  14005. * center the graph
  14006. *
  14007. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  14008. */
  14009. Graph.prototype._centerGraph = function(range) {
  14010. var center = this._findCenter(range);
  14011. center.x *= this.scale;
  14012. center.y *= this.scale;
  14013. center.x -= 0.5 * this.frame.canvas.clientWidth;
  14014. center.y -= 0.5 * this.frame.canvas.clientHeight;
  14015. this._setTranslation(-center.x,-center.y); // set at 0,0
  14016. };
  14017. /**
  14018. * This function zooms out to fit all data on screen based on amount of nodes
  14019. *
  14020. * @param {Boolean} [initialZoom] | zoom based on fitted formula or range, true = fitted, default = false;
  14021. * @param {Boolean} [disableStart] | If true, start is not called.
  14022. */
  14023. Graph.prototype.zoomExtent = function(initialZoom, disableStart) {
  14024. if (initialZoom === undefined) {
  14025. initialZoom = false;
  14026. }
  14027. if (disableStart === undefined) {
  14028. disableStart = false;
  14029. }
  14030. var range = this._getRange();
  14031. var zoomLevel;
  14032. if (initialZoom == true) {
  14033. var numberOfNodes = this.nodeIndices.length;
  14034. if (this.constants.smoothCurves == true) {
  14035. if (this.constants.clustering.enabled == true &&
  14036. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  14037. 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.
  14038. }
  14039. else {
  14040. zoomLevel = 12.662 / (numberOfNodes + 7.4147) + 0.0964822; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  14041. }
  14042. }
  14043. else {
  14044. if (this.constants.clustering.enabled == true &&
  14045. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  14046. 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.
  14047. }
  14048. else {
  14049. zoomLevel = 30.5062972 / (numberOfNodes + 19.93597763) + 0.08413486; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  14050. }
  14051. }
  14052. // correct for larger canvasses.
  14053. var factor = Math.min(this.frame.canvas.clientWidth / 600, this.frame.canvas.clientHeight / 600);
  14054. zoomLevel *= factor;
  14055. }
  14056. else {
  14057. var xDistance = (Math.abs(range.minX) + Math.abs(range.maxX)) * 1.1;
  14058. var yDistance = (Math.abs(range.minY) + Math.abs(range.maxY)) * 1.1;
  14059. var xZoomLevel = this.frame.canvas.clientWidth / xDistance;
  14060. var yZoomLevel = this.frame.canvas.clientHeight / yDistance;
  14061. zoomLevel = (xZoomLevel <= yZoomLevel) ? xZoomLevel : yZoomLevel;
  14062. }
  14063. if (zoomLevel > 1.0) {
  14064. zoomLevel = 1.0;
  14065. }
  14066. this._setScale(zoomLevel);
  14067. this._centerGraph(range);
  14068. if (disableStart == false) {
  14069. this.moving = true;
  14070. this.start();
  14071. }
  14072. };
  14073. /**
  14074. * Update the this.nodeIndices with the most recent node index list
  14075. * @private
  14076. */
  14077. Graph.prototype._updateNodeIndexList = function() {
  14078. this._clearNodeIndexList();
  14079. for (var idx in this.nodes) {
  14080. if (this.nodes.hasOwnProperty(idx)) {
  14081. this.nodeIndices.push(idx);
  14082. }
  14083. }
  14084. };
  14085. /**
  14086. * Set nodes and edges, and optionally options as well.
  14087. *
  14088. * @param {Object} data Object containing parameters:
  14089. * {Array | DataSet | DataView} [nodes] Array with nodes
  14090. * {Array | DataSet | DataView} [edges] Array with edges
  14091. * {String} [dot] String containing data in DOT format
  14092. * {Options} [options] Object with options
  14093. * @param {Boolean} [disableStart] | optional: disable the calling of the start function.
  14094. */
  14095. Graph.prototype.setData = function(data, disableStart) {
  14096. if (disableStart === undefined) {
  14097. disableStart = false;
  14098. }
  14099. if (data && data.dot && (data.nodes || data.edges)) {
  14100. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  14101. ' parameter pair "nodes" and "edges", but not both.');
  14102. }
  14103. // set options
  14104. this.setOptions(data && data.options);
  14105. // set all data
  14106. if (data && data.dot) {
  14107. // parse DOT file
  14108. if(data && data.dot) {
  14109. var dotData = vis.util.DOTToGraph(data.dot);
  14110. this.setData(dotData);
  14111. return;
  14112. }
  14113. }
  14114. else {
  14115. this._setNodes(data && data.nodes);
  14116. this._setEdges(data && data.edges);
  14117. }
  14118. this._putDataInSector();
  14119. if (!disableStart) {
  14120. // find a stable position or start animating to a stable position
  14121. if (this.stabilize) {
  14122. var me = this;
  14123. setTimeout(function() {me._stabilize(); me.start();},0)
  14124. }
  14125. else {
  14126. this.start();
  14127. }
  14128. }
  14129. };
  14130. /**
  14131. * Set options
  14132. * @param {Object} options
  14133. * @param {Boolean} [initializeView] | set zoom and translation to default.
  14134. */
  14135. Graph.prototype.setOptions = function (options) {
  14136. if (options) {
  14137. var prop;
  14138. // retrieve parameter values
  14139. if (options.width !== undefined) {this.width = options.width;}
  14140. if (options.height !== undefined) {this.height = options.height;}
  14141. if (options.stabilize !== undefined) {this.stabilize = options.stabilize;}
  14142. if (options.selectable !== undefined) {this.selectable = options.selectable;}
  14143. if (options.smoothCurves !== undefined) {this.constants.smoothCurves = options.smoothCurves;}
  14144. if (options.freezeForStabilization !== undefined) {this.constants.freezeForStabilization = options.freezeForStabilization;}
  14145. if (options.configurePhysics !== undefined){this.constants.configurePhysics = options.configurePhysics;}
  14146. if (options.stabilizationIterations !== undefined) {this.constants.stabilizationIterations = options.stabilizationIterations;}
  14147. if (options.moveable !== undefined) {this.constants.moveable = options.moveable;}
  14148. if (options.zoomable !== undefined) {this.constants.zoomable = options.zoomable;}
  14149. if (options.labels !== undefined) {
  14150. for (prop in options.labels) {
  14151. if (options.labels.hasOwnProperty(prop)) {
  14152. this.constants.labels[prop] = options.labels[prop];
  14153. }
  14154. }
  14155. }
  14156. if (options.onAdd) {
  14157. this.triggerFunctions.add = options.onAdd;
  14158. }
  14159. if (options.onEdit) {
  14160. this.triggerFunctions.edit = options.onEdit;
  14161. }
  14162. if (options.onConnect) {
  14163. this.triggerFunctions.connect = options.onConnect;
  14164. }
  14165. if (options.onDelete) {
  14166. this.triggerFunctions.del = options.onDelete;
  14167. }
  14168. if (options.physics) {
  14169. if (options.physics.barnesHut) {
  14170. this.constants.physics.barnesHut.enabled = true;
  14171. for (prop in options.physics.barnesHut) {
  14172. if (options.physics.barnesHut.hasOwnProperty(prop)) {
  14173. this.constants.physics.barnesHut[prop] = options.physics.barnesHut[prop];
  14174. }
  14175. }
  14176. }
  14177. if (options.physics.repulsion) {
  14178. this.constants.physics.barnesHut.enabled = false;
  14179. for (prop in options.physics.repulsion) {
  14180. if (options.physics.repulsion.hasOwnProperty(prop)) {
  14181. this.constants.physics.repulsion[prop] = options.physics.repulsion[prop];
  14182. }
  14183. }
  14184. }
  14185. if (options.physics.hierarchicalRepulsion) {
  14186. this.constants.hierarchicalLayout.enabled = true;
  14187. this.constants.physics.hierarchicalRepulsion.enabled = true;
  14188. this.constants.physics.barnesHut.enabled = false;
  14189. for (prop in options.physics.hierarchicalRepulsion) {
  14190. if (options.physics.hierarchicalRepulsion.hasOwnProperty(prop)) {
  14191. this.constants.physics.hierarchicalRepulsion[prop] = options.physics.hierarchicalRepulsion[prop];
  14192. }
  14193. }
  14194. }
  14195. }
  14196. if (options.hierarchicalLayout) {
  14197. this.constants.hierarchicalLayout.enabled = true;
  14198. for (prop in options.hierarchicalLayout) {
  14199. if (options.hierarchicalLayout.hasOwnProperty(prop)) {
  14200. this.constants.hierarchicalLayout[prop] = options.hierarchicalLayout[prop];
  14201. }
  14202. }
  14203. }
  14204. else if (options.hierarchicalLayout !== undefined) {
  14205. this.constants.hierarchicalLayout.enabled = false;
  14206. }
  14207. if (options.clustering) {
  14208. this.constants.clustering.enabled = true;
  14209. for (prop in options.clustering) {
  14210. if (options.clustering.hasOwnProperty(prop)) {
  14211. this.constants.clustering[prop] = options.clustering[prop];
  14212. }
  14213. }
  14214. }
  14215. else if (options.clustering !== undefined) {
  14216. this.constants.clustering.enabled = false;
  14217. }
  14218. if (options.navigation) {
  14219. this.constants.navigation.enabled = true;
  14220. for (prop in options.navigation) {
  14221. if (options.navigation.hasOwnProperty(prop)) {
  14222. this.constants.navigation[prop] = options.navigation[prop];
  14223. }
  14224. }
  14225. }
  14226. else if (options.navigation !== undefined) {
  14227. this.constants.navigation.enabled = false;
  14228. }
  14229. if (options.keyboard) {
  14230. this.constants.keyboard.enabled = true;
  14231. for (prop in options.keyboard) {
  14232. if (options.keyboard.hasOwnProperty(prop)) {
  14233. this.constants.keyboard[prop] = options.keyboard[prop];
  14234. }
  14235. }
  14236. }
  14237. else if (options.keyboard !== undefined) {
  14238. this.constants.keyboard.enabled = false;
  14239. }
  14240. if (options.dataManipulation) {
  14241. this.constants.dataManipulation.enabled = true;
  14242. for (prop in options.dataManipulation) {
  14243. if (options.dataManipulation.hasOwnProperty(prop)) {
  14244. this.constants.dataManipulation[prop] = options.dataManipulation[prop];
  14245. }
  14246. }
  14247. }
  14248. else if (options.dataManipulation !== undefined) {
  14249. this.constants.dataManipulation.enabled = false;
  14250. }
  14251. // TODO: work out these options and document them
  14252. if (options.edges) {
  14253. for (prop in options.edges) {
  14254. if (options.edges.hasOwnProperty(prop)) {
  14255. if (typeof options.edges[prop] != "object") {
  14256. this.constants.edges[prop] = options.edges[prop];
  14257. }
  14258. }
  14259. }
  14260. if (options.edges.color !== undefined) {
  14261. if (util.isString(options.edges.color)) {
  14262. this.constants.edges.color = {};
  14263. this.constants.edges.color.color = options.edges.color;
  14264. this.constants.edges.color.highlight = options.edges.color;
  14265. }
  14266. else {
  14267. if (options.edges.color.color !== undefined) {this.constants.edges.color.color = options.edges.color.color;}
  14268. if (options.edges.color.highlight !== undefined) {this.constants.edges.color.highlight = options.edges.color.highlight;}
  14269. }
  14270. }
  14271. if (!options.edges.fontColor) {
  14272. if (options.edges.color !== undefined) {
  14273. if (util.isString(options.edges.color)) {this.constants.edges.fontColor = options.edges.color;}
  14274. else if (options.edges.color.color !== undefined) {this.constants.edges.fontColor = options.edges.color.color;}
  14275. }
  14276. }
  14277. // Added to support dashed lines
  14278. // David Jordan
  14279. // 2012-08-08
  14280. if (options.edges.dash) {
  14281. if (options.edges.dash.length !== undefined) {
  14282. this.constants.edges.dash.length = options.edges.dash.length;
  14283. }
  14284. if (options.edges.dash.gap !== undefined) {
  14285. this.constants.edges.dash.gap = options.edges.dash.gap;
  14286. }
  14287. if (options.edges.dash.altLength !== undefined) {
  14288. this.constants.edges.dash.altLength = options.edges.dash.altLength;
  14289. }
  14290. }
  14291. }
  14292. if (options.nodes) {
  14293. for (prop in options.nodes) {
  14294. if (options.nodes.hasOwnProperty(prop)) {
  14295. this.constants.nodes[prop] = options.nodes[prop];
  14296. }
  14297. }
  14298. if (options.nodes.color) {
  14299. this.constants.nodes.color = util.parseColor(options.nodes.color);
  14300. }
  14301. /*
  14302. if (options.nodes.widthMin) this.constants.nodes.radiusMin = options.nodes.widthMin;
  14303. if (options.nodes.widthMax) this.constants.nodes.radiusMax = options.nodes.widthMax;
  14304. */
  14305. }
  14306. if (options.groups) {
  14307. for (var groupname in options.groups) {
  14308. if (options.groups.hasOwnProperty(groupname)) {
  14309. var group = options.groups[groupname];
  14310. this.groups.add(groupname, group);
  14311. }
  14312. }
  14313. }
  14314. if (options.tooltip) {
  14315. for (prop in options.tooltip) {
  14316. if (options.tooltip.hasOwnProperty(prop)) {
  14317. this.constants.tooltip[prop] = options.tooltip[prop];
  14318. }
  14319. }
  14320. if (options.tooltip.color) {
  14321. this.constants.tooltip.color = util.parseColor(options.tooltip.color);
  14322. }
  14323. }
  14324. }
  14325. // (Re)loading the mixins that can be enabled or disabled in the options.
  14326. // load the force calculation functions, grouped under the physics system.
  14327. this._loadPhysicsSystem();
  14328. // load the navigation system.
  14329. this._loadNavigationControls();
  14330. // load the data manipulation system
  14331. this._loadManipulationSystem();
  14332. // configure the smooth curves
  14333. this._configureSmoothCurves();
  14334. // bind keys. If disabled, this will not do anything;
  14335. this._createKeyBinds();
  14336. this.setSize(this.width, this.height);
  14337. this.moving = true;
  14338. this.start();
  14339. };
  14340. /**
  14341. * Create the main frame for the Graph.
  14342. * This function is executed once when a Graph object is created. The frame
  14343. * contains a canvas, and this canvas contains all objects like the axis and
  14344. * nodes.
  14345. * @private
  14346. */
  14347. Graph.prototype._create = function () {
  14348. // remove all elements from the container element.
  14349. while (this.containerElement.hasChildNodes()) {
  14350. this.containerElement.removeChild(this.containerElement.firstChild);
  14351. }
  14352. this.frame = document.createElement('div');
  14353. this.frame.className = 'graph-frame';
  14354. this.frame.style.position = 'relative';
  14355. this.frame.style.overflow = 'hidden';
  14356. // create the graph canvas (HTML canvas element)
  14357. this.frame.canvas = document.createElement( 'canvas' );
  14358. this.frame.canvas.style.position = 'relative';
  14359. this.frame.appendChild(this.frame.canvas);
  14360. if (!this.frame.canvas.getContext) {
  14361. var noCanvas = document.createElement( 'DIV' );
  14362. noCanvas.style.color = 'red';
  14363. noCanvas.style.fontWeight = 'bold' ;
  14364. noCanvas.style.padding = '10px';
  14365. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  14366. this.frame.canvas.appendChild(noCanvas);
  14367. }
  14368. var me = this;
  14369. this.drag = {};
  14370. this.pinch = {};
  14371. this.hammer = Hammer(this.frame.canvas, {
  14372. prevent_default: true
  14373. });
  14374. this.hammer.on('tap', me._onTap.bind(me) );
  14375. this.hammer.on('doubletap', me._onDoubleTap.bind(me) );
  14376. this.hammer.on('hold', me._onHold.bind(me) );
  14377. this.hammer.on('pinch', me._onPinch.bind(me) );
  14378. this.hammer.on('touch', me._onTouch.bind(me) );
  14379. this.hammer.on('dragstart', me._onDragStart.bind(me) );
  14380. this.hammer.on('drag', me._onDrag.bind(me) );
  14381. this.hammer.on('dragend', me._onDragEnd.bind(me) );
  14382. this.hammer.on('release', me._onRelease.bind(me) );
  14383. this.hammer.on('mousewheel',me._onMouseWheel.bind(me) );
  14384. this.hammer.on('DOMMouseScroll',me._onMouseWheel.bind(me) ); // for FF
  14385. this.hammer.on('mousemove', me._onMouseMoveTitle.bind(me) );
  14386. // add the frame to the container element
  14387. this.containerElement.appendChild(this.frame);
  14388. };
  14389. /**
  14390. * Binding the keys for keyboard navigation. These functions are defined in the NavigationMixin
  14391. * @private
  14392. */
  14393. Graph.prototype._createKeyBinds = function() {
  14394. var me = this;
  14395. this.mousetrap = mousetrap;
  14396. this.mousetrap.reset();
  14397. if (this.constants.keyboard.enabled == true) {
  14398. this.mousetrap.bind("up", this._moveUp.bind(me) , "keydown");
  14399. this.mousetrap.bind("up", this._yStopMoving.bind(me), "keyup");
  14400. this.mousetrap.bind("down", this._moveDown.bind(me) , "keydown");
  14401. this.mousetrap.bind("down", this._yStopMoving.bind(me), "keyup");
  14402. this.mousetrap.bind("left", this._moveLeft.bind(me) , "keydown");
  14403. this.mousetrap.bind("left", this._xStopMoving.bind(me), "keyup");
  14404. this.mousetrap.bind("right",this._moveRight.bind(me), "keydown");
  14405. this.mousetrap.bind("right",this._xStopMoving.bind(me), "keyup");
  14406. this.mousetrap.bind("=", this._zoomIn.bind(me), "keydown");
  14407. this.mousetrap.bind("=", this._stopZoom.bind(me), "keyup");
  14408. this.mousetrap.bind("-", this._zoomOut.bind(me), "keydown");
  14409. this.mousetrap.bind("-", this._stopZoom.bind(me), "keyup");
  14410. this.mousetrap.bind("[", this._zoomIn.bind(me), "keydown");
  14411. this.mousetrap.bind("[", this._stopZoom.bind(me), "keyup");
  14412. this.mousetrap.bind("]", this._zoomOut.bind(me), "keydown");
  14413. this.mousetrap.bind("]", this._stopZoom.bind(me), "keyup");
  14414. this.mousetrap.bind("pageup",this._zoomIn.bind(me), "keydown");
  14415. this.mousetrap.bind("pageup",this._stopZoom.bind(me), "keyup");
  14416. this.mousetrap.bind("pagedown",this._zoomOut.bind(me),"keydown");
  14417. this.mousetrap.bind("pagedown",this._stopZoom.bind(me), "keyup");
  14418. }
  14419. if (this.constants.dataManipulation.enabled == true) {
  14420. this.mousetrap.bind("escape",this._createManipulatorBar.bind(me));
  14421. this.mousetrap.bind("del",this._deleteSelected.bind(me));
  14422. }
  14423. };
  14424. /**
  14425. * Get the pointer location from a touch location
  14426. * @param {{pageX: Number, pageY: Number}} touch
  14427. * @return {{x: Number, y: Number}} pointer
  14428. * @private
  14429. */
  14430. Graph.prototype._getPointer = function (touch) {
  14431. return {
  14432. x: touch.pageX - vis.util.getAbsoluteLeft(this.frame.canvas),
  14433. y: touch.pageY - vis.util.getAbsoluteTop(this.frame.canvas)
  14434. };
  14435. };
  14436. /**
  14437. * On start of a touch gesture, store the pointer
  14438. * @param event
  14439. * @private
  14440. */
  14441. Graph.prototype._onTouch = function (event) {
  14442. this.drag.pointer = this._getPointer(event.gesture.center);
  14443. this.drag.pinched = false;
  14444. this.pinch.scale = this._getScale();
  14445. this._handleTouch(this.drag.pointer);
  14446. };
  14447. /**
  14448. * handle drag start event
  14449. * @private
  14450. */
  14451. Graph.prototype._onDragStart = function () {
  14452. this._handleDragStart();
  14453. };
  14454. /**
  14455. * This function is called by _onDragStart.
  14456. * It is separated out because we can then overload it for the datamanipulation system.
  14457. *
  14458. * @private
  14459. */
  14460. Graph.prototype._handleDragStart = function() {
  14461. var drag = this.drag;
  14462. var node = this._getNodeAt(drag.pointer);
  14463. // note: drag.pointer is set in _onTouch to get the initial touch location
  14464. drag.dragging = true;
  14465. drag.selection = [];
  14466. drag.translation = this._getTranslation();
  14467. drag.nodeId = null;
  14468. if (node != null) {
  14469. drag.nodeId = node.id;
  14470. // select the clicked node if not yet selected
  14471. if (!node.isSelected()) {
  14472. this._selectObject(node,false);
  14473. }
  14474. // create an array with the selected nodes and their original location and status
  14475. for (var objectId in this.selectionObj.nodes) {
  14476. if (this.selectionObj.nodes.hasOwnProperty(objectId)) {
  14477. var object = this.selectionObj.nodes[objectId];
  14478. var s = {
  14479. id: object.id,
  14480. node: object,
  14481. // store original x, y, xFixed and yFixed, make the node temporarily Fixed
  14482. x: object.x,
  14483. y: object.y,
  14484. xFixed: object.xFixed,
  14485. yFixed: object.yFixed
  14486. };
  14487. object.xFixed = true;
  14488. object.yFixed = true;
  14489. drag.selection.push(s);
  14490. }
  14491. }
  14492. }
  14493. };
  14494. /**
  14495. * handle drag event
  14496. * @private
  14497. */
  14498. Graph.prototype._onDrag = function (event) {
  14499. this._handleOnDrag(event)
  14500. };
  14501. /**
  14502. * This function is called by _onDrag.
  14503. * It is separated out because we can then overload it for the datamanipulation system.
  14504. *
  14505. * @private
  14506. */
  14507. Graph.prototype._handleOnDrag = function(event) {
  14508. if (this.drag.pinched) {
  14509. return;
  14510. }
  14511. var pointer = this._getPointer(event.gesture.center);
  14512. var me = this,
  14513. drag = this.drag,
  14514. selection = drag.selection;
  14515. if (selection && selection.length) {
  14516. // calculate delta's and new location
  14517. var deltaX = pointer.x - drag.pointer.x,
  14518. deltaY = pointer.y - drag.pointer.y;
  14519. // update position of all selected nodes
  14520. selection.forEach(function (s) {
  14521. var node = s.node;
  14522. if (!s.xFixed) {
  14523. node.x = me._XconvertDOMtoCanvas(me._XconvertCanvasToDOM(s.x) + deltaX);
  14524. }
  14525. if (!s.yFixed) {
  14526. node.y = me._YconvertDOMtoCanvas(me._YconvertCanvasToDOM(s.y) + deltaY);
  14527. }
  14528. });
  14529. // start _animationStep if not yet running
  14530. if (!this.moving) {
  14531. this.moving = true;
  14532. this.start();
  14533. }
  14534. }
  14535. else {
  14536. if (this.constants.moveable == true) {
  14537. // move the graph
  14538. var diffX = pointer.x - this.drag.pointer.x;
  14539. var diffY = pointer.y - this.drag.pointer.y;
  14540. this._setTranslation(
  14541. this.drag.translation.x + diffX,
  14542. this.drag.translation.y + diffY);
  14543. this._redraw();
  14544. this.moving = true;
  14545. this.start();
  14546. }
  14547. }
  14548. };
  14549. /**
  14550. * handle drag start event
  14551. * @private
  14552. */
  14553. Graph.prototype._onDragEnd = function () {
  14554. this.drag.dragging = false;
  14555. var selection = this.drag.selection;
  14556. if (selection) {
  14557. selection.forEach(function (s) {
  14558. // restore original xFixed and yFixed
  14559. s.node.xFixed = s.xFixed;
  14560. s.node.yFixed = s.yFixed;
  14561. });
  14562. }
  14563. };
  14564. /**
  14565. * handle tap/click event: select/unselect a node
  14566. * @private
  14567. */
  14568. Graph.prototype._onTap = function (event) {
  14569. var pointer = this._getPointer(event.gesture.center);
  14570. this.pointerPosition = pointer;
  14571. this._handleTap(pointer);
  14572. };
  14573. /**
  14574. * handle doubletap event
  14575. * @private
  14576. */
  14577. Graph.prototype._onDoubleTap = function (event) {
  14578. var pointer = this._getPointer(event.gesture.center);
  14579. this._handleDoubleTap(pointer);
  14580. };
  14581. /**
  14582. * handle long tap event: multi select nodes
  14583. * @private
  14584. */
  14585. Graph.prototype._onHold = function (event) {
  14586. var pointer = this._getPointer(event.gesture.center);
  14587. this.pointerPosition = pointer;
  14588. this._handleOnHold(pointer);
  14589. };
  14590. /**
  14591. * handle the release of the screen
  14592. *
  14593. * @private
  14594. */
  14595. Graph.prototype._onRelease = function (event) {
  14596. var pointer = this._getPointer(event.gesture.center);
  14597. this._handleOnRelease(pointer);
  14598. };
  14599. /**
  14600. * Handle pinch event
  14601. * @param event
  14602. * @private
  14603. */
  14604. Graph.prototype._onPinch = function (event) {
  14605. var pointer = this._getPointer(event.gesture.center);
  14606. this.drag.pinched = true;
  14607. if (!('scale' in this.pinch)) {
  14608. this.pinch.scale = 1;
  14609. }
  14610. // TODO: enabled moving while pinching?
  14611. var scale = this.pinch.scale * event.gesture.scale;
  14612. this._zoom(scale, pointer)
  14613. };
  14614. /**
  14615. * Zoom the graph in or out
  14616. * @param {Number} scale a number around 1, and between 0.01 and 10
  14617. * @param {{x: Number, y: Number}} pointer Position on screen
  14618. * @return {Number} appliedScale scale is limited within the boundaries
  14619. * @private
  14620. */
  14621. Graph.prototype._zoom = function(scale, pointer) {
  14622. if (this.constants.zoomable == true) {
  14623. var scaleOld = this._getScale();
  14624. if (scale < 0.00001) {
  14625. scale = 0.00001;
  14626. }
  14627. if (scale > 10) {
  14628. scale = 10;
  14629. }
  14630. // + this.frame.canvas.clientHeight / 2
  14631. var translation = this._getTranslation();
  14632. var scaleFrac = scale / scaleOld;
  14633. var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac;
  14634. var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac;
  14635. this.areaCenter = {"x" : this._XconvertDOMtoCanvas(pointer.x),
  14636. "y" : this._YconvertDOMtoCanvas(pointer.y)};
  14637. this._setScale(scale);
  14638. this._setTranslation(tx, ty);
  14639. this.updateClustersDefault();
  14640. this._redraw();
  14641. if (scaleOld < scale) {
  14642. this.emit("zoom", {direction:"+"});
  14643. }
  14644. else {
  14645. this.emit("zoom", {direction:"-"});
  14646. }
  14647. return scale;
  14648. }
  14649. };
  14650. /**
  14651. * Event handler for mouse wheel event, used to zoom the timeline
  14652. * See http://adomas.org/javascript-mouse-wheel/
  14653. * https://github.com/EightMedia/hammer.js/issues/256
  14654. * @param {MouseEvent} event
  14655. * @private
  14656. */
  14657. Graph.prototype._onMouseWheel = function(event) {
  14658. // retrieve delta
  14659. var delta = 0;
  14660. if (event.wheelDelta) { /* IE/Opera. */
  14661. delta = event.wheelDelta/120;
  14662. } else if (event.detail) { /* Mozilla case. */
  14663. // In Mozilla, sign of delta is different than in IE.
  14664. // Also, delta is multiple of 3.
  14665. delta = -event.detail/3;
  14666. }
  14667. // If delta is nonzero, handle it.
  14668. // Basically, delta is now positive if wheel was scrolled up,
  14669. // and negative, if wheel was scrolled down.
  14670. if (delta) {
  14671. // calculate the new scale
  14672. var scale = this._getScale();
  14673. var zoom = delta / 10;
  14674. if (delta < 0) {
  14675. zoom = zoom / (1 - zoom);
  14676. }
  14677. scale *= (1 + zoom);
  14678. // calculate the pointer location
  14679. var gesture = util.fakeGesture(this, event);
  14680. var pointer = this._getPointer(gesture.center);
  14681. // apply the new scale
  14682. this._zoom(scale, pointer);
  14683. }
  14684. // Prevent default actions caused by mouse wheel.
  14685. event.preventDefault();
  14686. };
  14687. /**
  14688. * Mouse move handler for checking whether the title moves over a node with a title.
  14689. * @param {Event} event
  14690. * @private
  14691. */
  14692. Graph.prototype._onMouseMoveTitle = function (event) {
  14693. var gesture = util.fakeGesture(this, event);
  14694. var pointer = this._getPointer(gesture.center);
  14695. // check if the previously selected node is still selected
  14696. if (this.popupNode) {
  14697. this._checkHidePopup(pointer);
  14698. }
  14699. // start a timeout that will check if the mouse is positioned above
  14700. // an element
  14701. var me = this;
  14702. var checkShow = function() {
  14703. me._checkShowPopup(pointer);
  14704. };
  14705. if (this.popupTimer) {
  14706. clearInterval(this.popupTimer); // stop any running calculationTimer
  14707. }
  14708. if (!this.drag.dragging) {
  14709. this.popupTimer = setTimeout(checkShow, this.constants.tooltip.delay);
  14710. }
  14711. };
  14712. /**
  14713. * Check if there is an element on the given position in the graph
  14714. * (a node or edge). If so, and if this element has a title,
  14715. * show a popup window with its title.
  14716. *
  14717. * @param {{x:Number, y:Number}} pointer
  14718. * @private
  14719. */
  14720. Graph.prototype._checkShowPopup = function (pointer) {
  14721. var obj = {
  14722. left: this._XconvertDOMtoCanvas(pointer.x),
  14723. top: this._YconvertDOMtoCanvas(pointer.y),
  14724. right: this._XconvertDOMtoCanvas(pointer.x),
  14725. bottom: this._YconvertDOMtoCanvas(pointer.y)
  14726. };
  14727. var id;
  14728. var lastPopupNode = this.popupNode;
  14729. if (this.popupNode == undefined) {
  14730. // search the nodes for overlap, select the top one in case of multiple nodes
  14731. var nodes = this.nodes;
  14732. for (id in nodes) {
  14733. if (nodes.hasOwnProperty(id)) {
  14734. var node = nodes[id];
  14735. if (node.getTitle() !== undefined && node.isOverlappingWith(obj)) {
  14736. this.popupNode = node;
  14737. break;
  14738. }
  14739. }
  14740. }
  14741. }
  14742. if (this.popupNode === undefined) {
  14743. // search the edges for overlap
  14744. var edges = this.edges;
  14745. for (id in edges) {
  14746. if (edges.hasOwnProperty(id)) {
  14747. var edge = edges[id];
  14748. if (edge.connected && (edge.getTitle() !== undefined) &&
  14749. edge.isOverlappingWith(obj)) {
  14750. this.popupNode = edge;
  14751. break;
  14752. }
  14753. }
  14754. }
  14755. }
  14756. if (this.popupNode) {
  14757. // show popup message window
  14758. if (this.popupNode != lastPopupNode) {
  14759. var me = this;
  14760. if (!me.popup) {
  14761. me.popup = new Popup(me.frame, me.constants.tooltip);
  14762. }
  14763. // adjust a small offset such that the mouse cursor is located in the
  14764. // bottom left location of the popup, and you can easily move over the
  14765. // popup area
  14766. me.popup.setPosition(pointer.x - 3, pointer.y - 3);
  14767. me.popup.setText(me.popupNode.getTitle());
  14768. me.popup.show();
  14769. }
  14770. }
  14771. else {
  14772. if (this.popup) {
  14773. this.popup.hide();
  14774. }
  14775. }
  14776. };
  14777. /**
  14778. * Check if the popup must be hided, which is the case when the mouse is no
  14779. * longer hovering on the object
  14780. * @param {{x:Number, y:Number}} pointer
  14781. * @private
  14782. */
  14783. Graph.prototype._checkHidePopup = function (pointer) {
  14784. if (!this.popupNode || !this._getNodeAt(pointer) ) {
  14785. this.popupNode = undefined;
  14786. if (this.popup) {
  14787. this.popup.hide();
  14788. }
  14789. }
  14790. };
  14791. /**
  14792. * Set a new size for the graph
  14793. * @param {string} width Width in pixels or percentage (for example '800px'
  14794. * or '50%')
  14795. * @param {string} height Height in pixels or percentage (for example '400px'
  14796. * or '30%')
  14797. */
  14798. Graph.prototype.setSize = function(width, height) {
  14799. this.frame.style.width = width;
  14800. this.frame.style.height = height;
  14801. this.frame.canvas.style.width = '100%';
  14802. this.frame.canvas.style.height = '100%';
  14803. this.frame.canvas.width = this.frame.canvas.clientWidth;
  14804. this.frame.canvas.height = this.frame.canvas.clientHeight;
  14805. if (this.manipulationDiv !== undefined) {
  14806. this.manipulationDiv.style.width = this.frame.canvas.clientWidth + "px";
  14807. }
  14808. if (this.navigationDivs !== undefined) {
  14809. if (this.navigationDivs['wrapper'] !== undefined) {
  14810. this.navigationDivs['wrapper'].style.width = this.frame.canvas.clientWidth + "px";
  14811. this.navigationDivs['wrapper'].style.height = this.frame.canvas.clientHeight + "px";
  14812. }
  14813. }
  14814. this.emit('resize', {width:this.frame.canvas.width,height:this.frame.canvas.height});
  14815. };
  14816. /**
  14817. * Set a data set with nodes for the graph
  14818. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  14819. * @private
  14820. */
  14821. Graph.prototype._setNodes = function(nodes) {
  14822. var oldNodesData = this.nodesData;
  14823. if (nodes instanceof DataSet || nodes instanceof DataView) {
  14824. this.nodesData = nodes;
  14825. }
  14826. else if (nodes instanceof Array) {
  14827. this.nodesData = new DataSet();
  14828. this.nodesData.add(nodes);
  14829. }
  14830. else if (!nodes) {
  14831. this.nodesData = new DataSet();
  14832. }
  14833. else {
  14834. throw new TypeError('Array or DataSet expected');
  14835. }
  14836. if (oldNodesData) {
  14837. // unsubscribe from old dataset
  14838. util.forEach(this.nodesListeners, function (callback, event) {
  14839. oldNodesData.off(event, callback);
  14840. });
  14841. }
  14842. // remove drawn nodes
  14843. this.nodes = {};
  14844. if (this.nodesData) {
  14845. // subscribe to new dataset
  14846. var me = this;
  14847. util.forEach(this.nodesListeners, function (callback, event) {
  14848. me.nodesData.on(event, callback);
  14849. });
  14850. // draw all new nodes
  14851. var ids = this.nodesData.getIds();
  14852. this._addNodes(ids);
  14853. }
  14854. this._updateSelection();
  14855. };
  14856. /**
  14857. * Add nodes
  14858. * @param {Number[] | String[]} ids
  14859. * @private
  14860. */
  14861. Graph.prototype._addNodes = function(ids) {
  14862. var id;
  14863. for (var i = 0, len = ids.length; i < len; i++) {
  14864. id = ids[i];
  14865. var data = this.nodesData.get(id);
  14866. var node = new Node(data, this.images, this.groups, this.constants);
  14867. this.nodes[id] = node; // note: this may replace an existing node
  14868. if ((node.xFixed == false || node.yFixed == false) && (node.x === null || node.y === null)) {
  14869. var radius = 10 * 0.1*ids.length;
  14870. var angle = 2 * Math.PI * Math.random();
  14871. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  14872. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  14873. }
  14874. this.moving = true;
  14875. }
  14876. this._updateNodeIndexList();
  14877. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  14878. this._resetLevels();
  14879. this._setupHierarchicalLayout();
  14880. }
  14881. this._updateCalculationNodes();
  14882. this._reconnectEdges();
  14883. this._updateValueRange(this.nodes);
  14884. this.updateLabels();
  14885. };
  14886. /**
  14887. * Update existing nodes, or create them when not yet existing
  14888. * @param {Number[] | String[]} ids
  14889. * @private
  14890. */
  14891. Graph.prototype._updateNodes = function(ids) {
  14892. var nodes = this.nodes,
  14893. nodesData = this.nodesData;
  14894. for (var i = 0, len = ids.length; i < len; i++) {
  14895. var id = ids[i];
  14896. var node = nodes[id];
  14897. var data = nodesData.get(id);
  14898. if (node) {
  14899. // update node
  14900. node.setProperties(data, this.constants);
  14901. }
  14902. else {
  14903. // create node
  14904. node = new Node(properties, this.images, this.groups, this.constants);
  14905. nodes[id] = node;
  14906. }
  14907. }
  14908. this.moving = true;
  14909. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  14910. this._resetLevels();
  14911. this._setupHierarchicalLayout();
  14912. }
  14913. this._updateNodeIndexList();
  14914. this._reconnectEdges();
  14915. this._updateValueRange(nodes);
  14916. };
  14917. /**
  14918. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  14919. * @param {Number[] | String[]} ids
  14920. * @private
  14921. */
  14922. Graph.prototype._removeNodes = function(ids) {
  14923. var nodes = this.nodes;
  14924. for (var i = 0, len = ids.length; i < len; i++) {
  14925. var id = ids[i];
  14926. delete nodes[id];
  14927. }
  14928. this._updateNodeIndexList();
  14929. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  14930. this._resetLevels();
  14931. this._setupHierarchicalLayout();
  14932. }
  14933. this._updateCalculationNodes();
  14934. this._reconnectEdges();
  14935. this._updateSelection();
  14936. this._updateValueRange(nodes);
  14937. };
  14938. /**
  14939. * Load edges by reading the data table
  14940. * @param {Array | DataSet | DataView} edges The data containing the edges.
  14941. * @private
  14942. * @private
  14943. */
  14944. Graph.prototype._setEdges = function(edges) {
  14945. var oldEdgesData = this.edgesData;
  14946. if (edges instanceof DataSet || edges instanceof DataView) {
  14947. this.edgesData = edges;
  14948. }
  14949. else if (edges instanceof Array) {
  14950. this.edgesData = new DataSet();
  14951. this.edgesData.add(edges);
  14952. }
  14953. else if (!edges) {
  14954. this.edgesData = new DataSet();
  14955. }
  14956. else {
  14957. throw new TypeError('Array or DataSet expected');
  14958. }
  14959. if (oldEdgesData) {
  14960. // unsubscribe from old dataset
  14961. util.forEach(this.edgesListeners, function (callback, event) {
  14962. oldEdgesData.off(event, callback);
  14963. });
  14964. }
  14965. // remove drawn edges
  14966. this.edges = {};
  14967. if (this.edgesData) {
  14968. // subscribe to new dataset
  14969. var me = this;
  14970. util.forEach(this.edgesListeners, function (callback, event) {
  14971. me.edgesData.on(event, callback);
  14972. });
  14973. // draw all new nodes
  14974. var ids = this.edgesData.getIds();
  14975. this._addEdges(ids);
  14976. }
  14977. this._reconnectEdges();
  14978. };
  14979. /**
  14980. * Add edges
  14981. * @param {Number[] | String[]} ids
  14982. * @private
  14983. */
  14984. Graph.prototype._addEdges = function (ids) {
  14985. var edges = this.edges,
  14986. edgesData = this.edgesData;
  14987. for (var i = 0, len = ids.length; i < len; i++) {
  14988. var id = ids[i];
  14989. var oldEdge = edges[id];
  14990. if (oldEdge) {
  14991. oldEdge.disconnect();
  14992. }
  14993. var data = edgesData.get(id, {"showInternalIds" : true});
  14994. edges[id] = new Edge(data, this, this.constants);
  14995. }
  14996. this.moving = true;
  14997. this._updateValueRange(edges);
  14998. this._createBezierNodes();
  14999. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  15000. this._resetLevels();
  15001. this._setupHierarchicalLayout();
  15002. }
  15003. this._updateCalculationNodes();
  15004. };
  15005. /**
  15006. * Update existing edges, or create them when not yet existing
  15007. * @param {Number[] | String[]} ids
  15008. * @private
  15009. */
  15010. Graph.prototype._updateEdges = function (ids) {
  15011. var edges = this.edges,
  15012. edgesData = this.edgesData;
  15013. for (var i = 0, len = ids.length; i < len; i++) {
  15014. var id = ids[i];
  15015. var data = edgesData.get(id);
  15016. var edge = edges[id];
  15017. if (edge) {
  15018. // update edge
  15019. edge.disconnect();
  15020. edge.setProperties(data, this.constants);
  15021. edge.connect();
  15022. }
  15023. else {
  15024. // create edge
  15025. edge = new Edge(data, this, this.constants);
  15026. this.edges[id] = edge;
  15027. }
  15028. }
  15029. this._createBezierNodes();
  15030. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  15031. this._resetLevels();
  15032. this._setupHierarchicalLayout();
  15033. }
  15034. this.moving = true;
  15035. this._updateValueRange(edges);
  15036. };
  15037. /**
  15038. * Remove existing edges. Non existing ids will be ignored
  15039. * @param {Number[] | String[]} ids
  15040. * @private
  15041. */
  15042. Graph.prototype._removeEdges = function (ids) {
  15043. var edges = this.edges;
  15044. for (var i = 0, len = ids.length; i < len; i++) {
  15045. var id = ids[i];
  15046. var edge = edges[id];
  15047. if (edge) {
  15048. if (edge.via != null) {
  15049. delete this.sectors['support']['nodes'][edge.via.id];
  15050. }
  15051. edge.disconnect();
  15052. delete edges[id];
  15053. }
  15054. }
  15055. this.moving = true;
  15056. this._updateValueRange(edges);
  15057. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  15058. this._resetLevels();
  15059. this._setupHierarchicalLayout();
  15060. }
  15061. this._updateCalculationNodes();
  15062. };
  15063. /**
  15064. * Reconnect all edges
  15065. * @private
  15066. */
  15067. Graph.prototype._reconnectEdges = function() {
  15068. var id,
  15069. nodes = this.nodes,
  15070. edges = this.edges;
  15071. for (id in nodes) {
  15072. if (nodes.hasOwnProperty(id)) {
  15073. nodes[id].edges = [];
  15074. }
  15075. }
  15076. for (id in edges) {
  15077. if (edges.hasOwnProperty(id)) {
  15078. var edge = edges[id];
  15079. edge.from = null;
  15080. edge.to = null;
  15081. edge.connect();
  15082. }
  15083. }
  15084. };
  15085. /**
  15086. * Update the values of all object in the given array according to the current
  15087. * value range of the objects in the array.
  15088. * @param {Object} obj An object containing a set of Edges or Nodes
  15089. * The objects must have a method getValue() and
  15090. * setValueRange(min, max).
  15091. * @private
  15092. */
  15093. Graph.prototype._updateValueRange = function(obj) {
  15094. var id;
  15095. // determine the range of the objects
  15096. var valueMin = undefined;
  15097. var valueMax = undefined;
  15098. for (id in obj) {
  15099. if (obj.hasOwnProperty(id)) {
  15100. var value = obj[id].getValue();
  15101. if (value !== undefined) {
  15102. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  15103. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  15104. }
  15105. }
  15106. }
  15107. // adjust the range of all objects
  15108. if (valueMin !== undefined && valueMax !== undefined) {
  15109. for (id in obj) {
  15110. if (obj.hasOwnProperty(id)) {
  15111. obj[id].setValueRange(valueMin, valueMax);
  15112. }
  15113. }
  15114. }
  15115. };
  15116. /**
  15117. * Redraw the graph with the current data
  15118. * chart will be resized too.
  15119. */
  15120. Graph.prototype.redraw = function() {
  15121. this.setSize(this.width, this.height);
  15122. this._redraw();
  15123. };
  15124. /**
  15125. * Redraw the graph with the current data
  15126. * @private
  15127. */
  15128. Graph.prototype._redraw = function() {
  15129. var ctx = this.frame.canvas.getContext('2d');
  15130. // clear the canvas
  15131. var w = this.frame.canvas.width;
  15132. var h = this.frame.canvas.height;
  15133. ctx.clearRect(0, 0, w, h);
  15134. // set scaling and translation
  15135. ctx.save();
  15136. ctx.translate(this.translation.x, this.translation.y);
  15137. ctx.scale(this.scale, this.scale);
  15138. this.canvasTopLeft = {
  15139. "x": this._XconvertDOMtoCanvas(0),
  15140. "y": this._YconvertDOMtoCanvas(0)
  15141. };
  15142. this.canvasBottomRight = {
  15143. "x": this._XconvertDOMtoCanvas(this.frame.canvas.clientWidth),
  15144. "y": this._YconvertDOMtoCanvas(this.frame.canvas.clientHeight)
  15145. };
  15146. this._doInAllSectors("_drawAllSectorNodes",ctx);
  15147. this._doInAllSectors("_drawEdges",ctx);
  15148. this._doInAllSectors("_drawNodes",ctx,false);
  15149. // this._doInSupportSector("_drawNodes",ctx,true);
  15150. // this._drawTree(ctx,"#F00F0F");
  15151. // restore original scaling and translation
  15152. ctx.restore();
  15153. };
  15154. /**
  15155. * Set the translation of the graph
  15156. * @param {Number} offsetX Horizontal offset
  15157. * @param {Number} offsetY Vertical offset
  15158. * @private
  15159. */
  15160. Graph.prototype._setTranslation = function(offsetX, offsetY) {
  15161. if (this.translation === undefined) {
  15162. this.translation = {
  15163. x: 0,
  15164. y: 0
  15165. };
  15166. }
  15167. if (offsetX !== undefined) {
  15168. this.translation.x = offsetX;
  15169. }
  15170. if (offsetY !== undefined) {
  15171. this.translation.y = offsetY;
  15172. }
  15173. this.emit('viewChanged');
  15174. };
  15175. /**
  15176. * Get the translation of the graph
  15177. * @return {Object} translation An object with parameters x and y, both a number
  15178. * @private
  15179. */
  15180. Graph.prototype._getTranslation = function() {
  15181. return {
  15182. x: this.translation.x,
  15183. y: this.translation.y
  15184. };
  15185. };
  15186. /**
  15187. * Scale the graph
  15188. * @param {Number} scale Scaling factor 1.0 is unscaled
  15189. * @private
  15190. */
  15191. Graph.prototype._setScale = function(scale) {
  15192. this.scale = scale;
  15193. };
  15194. /**
  15195. * Get the current scale of the graph
  15196. * @return {Number} scale Scaling factor 1.0 is unscaled
  15197. * @private
  15198. */
  15199. Graph.prototype._getScale = function() {
  15200. return this.scale;
  15201. };
  15202. /**
  15203. * Convert the X coordinate in DOM-space (coordinate point in browser relative to the container div) to
  15204. * the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon)
  15205. * @param {number} x
  15206. * @returns {number}
  15207. * @private
  15208. */
  15209. Graph.prototype._XconvertDOMtoCanvas = function(x) {
  15210. return (x - this.translation.x) / this.scale;
  15211. };
  15212. /**
  15213. * Convert the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to
  15214. * the X coordinate in DOM-space (coordinate point in browser relative to the container div)
  15215. * @param {number} x
  15216. * @returns {number}
  15217. * @private
  15218. */
  15219. Graph.prototype._XconvertCanvasToDOM = function(x) {
  15220. return x * this.scale + this.translation.x;
  15221. };
  15222. /**
  15223. * Convert the Y coordinate in DOM-space (coordinate point in browser relative to the container div) to
  15224. * the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon)
  15225. * @param {number} y
  15226. * @returns {number}
  15227. * @private
  15228. */
  15229. Graph.prototype._YconvertDOMtoCanvas = function(y) {
  15230. return (y - this.translation.y) / this.scale;
  15231. };
  15232. /**
  15233. * Convert the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to
  15234. * the Y coordinate in DOM-space (coordinate point in browser relative to the container div)
  15235. * @param {number} y
  15236. * @returns {number}
  15237. * @private
  15238. */
  15239. Graph.prototype._YconvertCanvasToDOM = function(y) {
  15240. return y * this.scale + this.translation.y ;
  15241. };
  15242. /**
  15243. *
  15244. * @param {object} pos = {x: number, y: number}
  15245. * @returns {{x: number, y: number}}
  15246. * @constructor
  15247. */
  15248. Graph.prototype.canvasToDOM = function(pos) {
  15249. return {x:this._XconvertCanvasToDOM(pos.x),y:this._YconvertCanvasToDOM(pos.y)};
  15250. }
  15251. /**
  15252. *
  15253. * @param {object} pos = {x: number, y: number}
  15254. * @returns {{x: number, y: number}}
  15255. * @constructor
  15256. */
  15257. Graph.prototype.DOMtoCanvas = function(pos) {
  15258. return {x:this._XconvertDOMtoCanvas(pos.x),y:this._YconvertDOMtoCanvas(pos.y)};
  15259. }
  15260. /**
  15261. * Redraw all nodes
  15262. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  15263. * @param {CanvasRenderingContext2D} ctx
  15264. * @param {Boolean} [alwaysShow]
  15265. * @private
  15266. */
  15267. Graph.prototype._drawNodes = function(ctx,alwaysShow) {
  15268. if (alwaysShow === undefined) {
  15269. alwaysShow = false;
  15270. }
  15271. // first draw the unselected nodes
  15272. var nodes = this.nodes;
  15273. var selected = [];
  15274. for (var id in nodes) {
  15275. if (nodes.hasOwnProperty(id)) {
  15276. nodes[id].setScaleAndPos(this.scale,this.canvasTopLeft,this.canvasBottomRight);
  15277. if (nodes[id].isSelected()) {
  15278. selected.push(id);
  15279. }
  15280. else {
  15281. if (nodes[id].inArea() || alwaysShow) {
  15282. nodes[id].draw(ctx);
  15283. }
  15284. }
  15285. }
  15286. }
  15287. // draw the selected nodes on top
  15288. for (var s = 0, sMax = selected.length; s < sMax; s++) {
  15289. if (nodes[selected[s]].inArea() || alwaysShow) {
  15290. nodes[selected[s]].draw(ctx);
  15291. }
  15292. }
  15293. };
  15294. /**
  15295. * Redraw all edges
  15296. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  15297. * @param {CanvasRenderingContext2D} ctx
  15298. * @private
  15299. */
  15300. Graph.prototype._drawEdges = function(ctx) {
  15301. var edges = this.edges;
  15302. for (var id in edges) {
  15303. if (edges.hasOwnProperty(id)) {
  15304. var edge = edges[id];
  15305. edge.setScale(this.scale);
  15306. if (edge.connected) {
  15307. edges[id].draw(ctx);
  15308. }
  15309. }
  15310. }
  15311. };
  15312. /**
  15313. * Find a stable position for all nodes
  15314. * @private
  15315. */
  15316. Graph.prototype._stabilize = function() {
  15317. if (this.constants.freezeForStabilization == true) {
  15318. this._freezeDefinedNodes();
  15319. }
  15320. // find stable position
  15321. var count = 0;
  15322. while (this.moving && count < this.constants.stabilizationIterations) {
  15323. this._physicsTick();
  15324. count++;
  15325. }
  15326. this.zoomExtent(false,true);
  15327. if (this.constants.freezeForStabilization == true) {
  15328. this._restoreFrozenNodes();
  15329. }
  15330. this.emit("stabilized",{iterations:count});
  15331. };
  15332. /**
  15333. * When initializing and stabilizing, we can freeze nodes with a predefined position. This greatly speeds up stabilization
  15334. * because only the supportnodes for the smoothCurves have to settle.
  15335. *
  15336. * @private
  15337. */
  15338. Graph.prototype._freezeDefinedNodes = function() {
  15339. var nodes = this.nodes;
  15340. for (var id in nodes) {
  15341. if (nodes.hasOwnProperty(id)) {
  15342. if (nodes[id].x != null && nodes[id].y != null) {
  15343. nodes[id].fixedData.x = nodes[id].xFixed;
  15344. nodes[id].fixedData.y = nodes[id].yFixed;
  15345. nodes[id].xFixed = true;
  15346. nodes[id].yFixed = true;
  15347. }
  15348. }
  15349. }
  15350. };
  15351. /**
  15352. * Unfreezes the nodes that have been frozen by _freezeDefinedNodes.
  15353. *
  15354. * @private
  15355. */
  15356. Graph.prototype._restoreFrozenNodes = function() {
  15357. var nodes = this.nodes;
  15358. for (var id in nodes) {
  15359. if (nodes.hasOwnProperty(id)) {
  15360. if (nodes[id].fixedData.x != null) {
  15361. nodes[id].xFixed = nodes[id].fixedData.x;
  15362. nodes[id].yFixed = nodes[id].fixedData.y;
  15363. }
  15364. }
  15365. }
  15366. };
  15367. /**
  15368. * Check if any of the nodes is still moving
  15369. * @param {number} vmin the minimum velocity considered as 'moving'
  15370. * @return {boolean} true if moving, false if non of the nodes is moving
  15371. * @private
  15372. */
  15373. Graph.prototype._isMoving = function(vmin) {
  15374. var nodes = this.nodes;
  15375. for (var id in nodes) {
  15376. if (nodes.hasOwnProperty(id) && nodes[id].isMoving(vmin)) {
  15377. return true;
  15378. }
  15379. }
  15380. return false;
  15381. };
  15382. /**
  15383. * /**
  15384. * Perform one discrete step for all nodes
  15385. *
  15386. * @private
  15387. */
  15388. Graph.prototype._discreteStepNodes = function() {
  15389. var interval = this.physicsDiscreteStepsize;
  15390. var nodes = this.nodes;
  15391. var nodeId;
  15392. var nodesPresent = false;
  15393. if (this.constants.maxVelocity > 0) {
  15394. for (nodeId in nodes) {
  15395. if (nodes.hasOwnProperty(nodeId)) {
  15396. nodes[nodeId].discreteStepLimited(interval, this.constants.maxVelocity);
  15397. nodesPresent = true;
  15398. }
  15399. }
  15400. }
  15401. else {
  15402. for (nodeId in nodes) {
  15403. if (nodes.hasOwnProperty(nodeId)) {
  15404. nodes[nodeId].discreteStep(interval);
  15405. nodesPresent = true;
  15406. }
  15407. }
  15408. }
  15409. if (nodesPresent == true) {
  15410. var vminCorrected = this.constants.minVelocity / Math.max(this.scale,0.05);
  15411. if (vminCorrected > 0.5*this.constants.maxVelocity) {
  15412. this.moving = true;
  15413. }
  15414. else {
  15415. this.moving = this._isMoving(vminCorrected);
  15416. }
  15417. }
  15418. };
  15419. /**
  15420. * A single simulation step (or "tick") in the physics simulation
  15421. *
  15422. * @private
  15423. */
  15424. Graph.prototype._physicsTick = function() {
  15425. if (!this.freezeSimulation) {
  15426. if (this.moving) {
  15427. this._doInAllActiveSectors("_initializeForceCalculation");
  15428. this._doInAllActiveSectors("_discreteStepNodes");
  15429. if (this.constants.smoothCurves) {
  15430. this._doInSupportSector("_discreteStepNodes");
  15431. }
  15432. this._findCenter(this._getRange())
  15433. }
  15434. }
  15435. };
  15436. /**
  15437. * This function runs one step of the animation. It calls an x amount of physics ticks and one render tick.
  15438. * It reschedules itself at the beginning of the function
  15439. *
  15440. * @private
  15441. */
  15442. Graph.prototype._animationStep = function() {
  15443. // reset the timer so a new scheduled animation step can be set
  15444. this.timer = undefined;
  15445. // handle the keyboad movement
  15446. this._handleNavigation();
  15447. // this schedules a new animation step
  15448. this.start();
  15449. // start the physics simulation
  15450. var calculationTime = Date.now();
  15451. var maxSteps = 1;
  15452. this._physicsTick();
  15453. var timeRequired = Date.now() - calculationTime;
  15454. while (timeRequired < (this.renderTimestep - this.renderTime) && maxSteps < this.maxPhysicsTicksPerRender) {
  15455. this._physicsTick();
  15456. timeRequired = Date.now() - calculationTime;
  15457. maxSteps++;
  15458. }
  15459. // start the rendering process
  15460. var renderTime = Date.now();
  15461. this._redraw();
  15462. this.renderTime = Date.now() - renderTime;
  15463. };
  15464. if (typeof window !== 'undefined') {
  15465. window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
  15466. window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
  15467. }
  15468. /**
  15469. * Schedule a animation step with the refreshrate interval.
  15470. */
  15471. Graph.prototype.start = function() {
  15472. if (this.moving || this.xIncrement != 0 || this.yIncrement != 0 || this.zoomIncrement != 0) {
  15473. if (!this.timer) {
  15474. var ua = navigator.userAgent.toLowerCase();
  15475. var requiresTimeout = false;
  15476. if (ua.indexOf('msie 9.0') != -1) { // IE 9
  15477. requiresTimeout = true;
  15478. }
  15479. else if (ua.indexOf('safari') != -1) { // safari
  15480. if (ua.indexOf('chrome') <= -1) {
  15481. requiresTimeout = true;
  15482. }
  15483. }
  15484. if (requiresTimeout == true) {
  15485. this.timer = window.setTimeout(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  15486. }
  15487. else{
  15488. this.timer = window.requestAnimationFrame(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  15489. }
  15490. }
  15491. }
  15492. else {
  15493. this._redraw();
  15494. }
  15495. };
  15496. /**
  15497. * Move the graph according to the keyboard presses.
  15498. *
  15499. * @private
  15500. */
  15501. Graph.prototype._handleNavigation = function() {
  15502. if (this.xIncrement != 0 || this.yIncrement != 0) {
  15503. var translation = this._getTranslation();
  15504. this._setTranslation(translation.x+this.xIncrement, translation.y+this.yIncrement);
  15505. }
  15506. if (this.zoomIncrement != 0) {
  15507. var center = {
  15508. x: this.frame.canvas.clientWidth / 2,
  15509. y: this.frame.canvas.clientHeight / 2
  15510. };
  15511. this._zoom(this.scale*(1 + this.zoomIncrement), center);
  15512. }
  15513. };
  15514. /**
  15515. * Freeze the _animationStep
  15516. */
  15517. Graph.prototype.toggleFreeze = function() {
  15518. if (this.freezeSimulation == false) {
  15519. this.freezeSimulation = true;
  15520. }
  15521. else {
  15522. this.freezeSimulation = false;
  15523. this.start();
  15524. }
  15525. };
  15526. /**
  15527. * This function cleans the support nodes if they are not needed and adds them when they are.
  15528. *
  15529. * @param {boolean} [disableStart]
  15530. * @private
  15531. */
  15532. Graph.prototype._configureSmoothCurves = function(disableStart) {
  15533. if (disableStart === undefined) {
  15534. disableStart = true;
  15535. }
  15536. if (this.constants.smoothCurves == true) {
  15537. this._createBezierNodes();
  15538. }
  15539. else {
  15540. // delete the support nodes
  15541. this.sectors['support']['nodes'] = {};
  15542. for (var edgeId in this.edges) {
  15543. if (this.edges.hasOwnProperty(edgeId)) {
  15544. this.edges[edgeId].smooth = false;
  15545. this.edges[edgeId].via = null;
  15546. }
  15547. }
  15548. }
  15549. this._updateCalculationNodes();
  15550. if (!disableStart) {
  15551. this.moving = true;
  15552. this.start();
  15553. }
  15554. };
  15555. /**
  15556. * Bezier curves require an anchor point to calculate the smooth flow. These points are nodes. These nodes are invisible but
  15557. * are used for the force calculation.
  15558. *
  15559. * @private
  15560. */
  15561. Graph.prototype._createBezierNodes = function() {
  15562. if (this.constants.smoothCurves == true) {
  15563. for (var edgeId in this.edges) {
  15564. if (this.edges.hasOwnProperty(edgeId)) {
  15565. var edge = this.edges[edgeId];
  15566. if (edge.via == null) {
  15567. edge.smooth = true;
  15568. var nodeId = "edgeId:".concat(edge.id);
  15569. this.sectors['support']['nodes'][nodeId] = new Node(
  15570. {id:nodeId,
  15571. mass:1,
  15572. shape:'circle',
  15573. image:"",
  15574. internalMultiplier:1
  15575. },{},{},this.constants);
  15576. edge.via = this.sectors['support']['nodes'][nodeId];
  15577. edge.via.parentEdgeId = edge.id;
  15578. edge.positionBezierNode();
  15579. }
  15580. }
  15581. }
  15582. }
  15583. };
  15584. /**
  15585. * load the functions that load the mixins into the prototype.
  15586. *
  15587. * @private
  15588. */
  15589. Graph.prototype._initializeMixinLoaders = function () {
  15590. for (var mixinFunction in graphMixinLoaders) {
  15591. if (graphMixinLoaders.hasOwnProperty(mixinFunction)) {
  15592. Graph.prototype[mixinFunction] = graphMixinLoaders[mixinFunction];
  15593. }
  15594. }
  15595. };
  15596. /**
  15597. * Load the XY positions of the nodes into the dataset.
  15598. */
  15599. Graph.prototype.storePosition = function() {
  15600. var dataArray = [];
  15601. for (var nodeId in this.nodes) {
  15602. if (this.nodes.hasOwnProperty(nodeId)) {
  15603. var node = this.nodes[nodeId];
  15604. var allowedToMoveX = !this.nodes.xFixed;
  15605. var allowedToMoveY = !this.nodes.yFixed;
  15606. if (this.nodesData.data[nodeId].x != Math.round(node.x) || this.nodesData.data[nodeId].y != Math.round(node.y)) {
  15607. dataArray.push({id:nodeId,x:Math.round(node.x),y:Math.round(node.y),allowedToMoveX:allowedToMoveX,allowedToMoveY:allowedToMoveY});
  15608. }
  15609. }
  15610. }
  15611. this.nodesData.update(dataArray);
  15612. };
  15613. /**
  15614. * vis.js module exports
  15615. */
  15616. var vis = {
  15617. util: util,
  15618. moment: moment,
  15619. DataSet: DataSet,
  15620. DataView: DataView,
  15621. Range: Range,
  15622. stack: stack,
  15623. TimeStep: TimeStep,
  15624. components: {
  15625. items: {
  15626. Item: Item,
  15627. ItemBox: ItemBox,
  15628. ItemPoint: ItemPoint,
  15629. ItemRange: ItemRange
  15630. },
  15631. Component: Component,
  15632. Panel: Panel,
  15633. RootPanel: RootPanel,
  15634. ItemSet: ItemSet,
  15635. TimeAxis: TimeAxis
  15636. },
  15637. graph: {
  15638. Node: Node,
  15639. Edge: Edge,
  15640. Popup: Popup,
  15641. Groups: Groups,
  15642. Images: Images
  15643. },
  15644. Timeline: Timeline,
  15645. Graph: Graph
  15646. };
  15647. /**
  15648. * CommonJS module exports
  15649. */
  15650. if (typeof exports !== 'undefined') {
  15651. exports = vis;
  15652. }
  15653. if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  15654. module.exports = vis;
  15655. }
  15656. /**
  15657. * AMD module exports
  15658. */
  15659. if (typeof(define) === 'function') {
  15660. define(function () {
  15661. return vis;
  15662. });
  15663. }
  15664. /**
  15665. * Window exports
  15666. */
  15667. if (typeof window !== 'undefined') {
  15668. // attach the module to the window, load as a regular javascript file
  15669. window['vis'] = vis;
  15670. }
  15671. },{"emitter-component":2,"hammerjs":3,"moment":4,"mousetrap":5}],2:[function(require,module,exports){
  15672. /**
  15673. * Expose `Emitter`.
  15674. */
  15675. module.exports = Emitter;
  15676. /**
  15677. * Initialize a new `Emitter`.
  15678. *
  15679. * @api public
  15680. */
  15681. function Emitter(obj) {
  15682. if (obj) return mixin(obj);
  15683. };
  15684. /**
  15685. * Mixin the emitter properties.
  15686. *
  15687. * @param {Object} obj
  15688. * @return {Object}
  15689. * @api private
  15690. */
  15691. function mixin(obj) {
  15692. for (var key in Emitter.prototype) {
  15693. obj[key] = Emitter.prototype[key];
  15694. }
  15695. return obj;
  15696. }
  15697. /**
  15698. * Listen on the given `event` with `fn`.
  15699. *
  15700. * @param {String} event
  15701. * @param {Function} fn
  15702. * @return {Emitter}
  15703. * @api public
  15704. */
  15705. Emitter.prototype.on =
  15706. Emitter.prototype.addEventListener = function(event, fn){
  15707. this._callbacks = this._callbacks || {};
  15708. (this._callbacks[event] = this._callbacks[event] || [])
  15709. .push(fn);
  15710. return this;
  15711. };
  15712. /**
  15713. * Adds an `event` listener that will be invoked a single
  15714. * time then automatically removed.
  15715. *
  15716. * @param {String} event
  15717. * @param {Function} fn
  15718. * @return {Emitter}
  15719. * @api public
  15720. */
  15721. Emitter.prototype.once = function(event, fn){
  15722. var self = this;
  15723. this._callbacks = this._callbacks || {};
  15724. function on() {
  15725. self.off(event, on);
  15726. fn.apply(this, arguments);
  15727. }
  15728. on.fn = fn;
  15729. this.on(event, on);
  15730. return this;
  15731. };
  15732. /**
  15733. * Remove the given callback for `event` or all
  15734. * registered callbacks.
  15735. *
  15736. * @param {String} event
  15737. * @param {Function} fn
  15738. * @return {Emitter}
  15739. * @api public
  15740. */
  15741. Emitter.prototype.off =
  15742. Emitter.prototype.removeListener =
  15743. Emitter.prototype.removeAllListeners =
  15744. Emitter.prototype.removeEventListener = function(event, fn){
  15745. this._callbacks = this._callbacks || {};
  15746. // all
  15747. if (0 == arguments.length) {
  15748. this._callbacks = {};
  15749. return this;
  15750. }
  15751. // specific event
  15752. var callbacks = this._callbacks[event];
  15753. if (!callbacks) return this;
  15754. // remove all handlers
  15755. if (1 == arguments.length) {
  15756. delete this._callbacks[event];
  15757. return this;
  15758. }
  15759. // remove specific handler
  15760. var cb;
  15761. for (var i = 0; i < callbacks.length; i++) {
  15762. cb = callbacks[i];
  15763. if (cb === fn || cb.fn === fn) {
  15764. callbacks.splice(i, 1);
  15765. break;
  15766. }
  15767. }
  15768. return this;
  15769. };
  15770. /**
  15771. * Emit `event` with the given args.
  15772. *
  15773. * @param {String} event
  15774. * @param {Mixed} ...
  15775. * @return {Emitter}
  15776. */
  15777. Emitter.prototype.emit = function(event){
  15778. this._callbacks = this._callbacks || {};
  15779. var args = [].slice.call(arguments, 1)
  15780. , callbacks = this._callbacks[event];
  15781. if (callbacks) {
  15782. callbacks = callbacks.slice(0);
  15783. for (var i = 0, len = callbacks.length; i < len; ++i) {
  15784. callbacks[i].apply(this, args);
  15785. }
  15786. }
  15787. return this;
  15788. };
  15789. /**
  15790. * Return array of callbacks for `event`.
  15791. *
  15792. * @param {String} event
  15793. * @return {Array}
  15794. * @api public
  15795. */
  15796. Emitter.prototype.listeners = function(event){
  15797. this._callbacks = this._callbacks || {};
  15798. return this._callbacks[event] || [];
  15799. };
  15800. /**
  15801. * Check if this emitter has `event` handlers.
  15802. *
  15803. * @param {String} event
  15804. * @return {Boolean}
  15805. * @api public
  15806. */
  15807. Emitter.prototype.hasListeners = function(event){
  15808. return !! this.listeners(event).length;
  15809. };
  15810. },{}],3:[function(require,module,exports){
  15811. /*! Hammer.JS - v1.0.5 - 2013-04-07
  15812. * http://eightmedia.github.com/hammer.js
  15813. *
  15814. * Copyright (c) 2013 Jorik Tangelder <j.tangelder@gmail.com>;
  15815. * Licensed under the MIT license */
  15816. (function(window, undefined) {
  15817. 'use strict';
  15818. /**
  15819. * Hammer
  15820. * use this to create instances
  15821. * @param {HTMLElement} element
  15822. * @param {Object} options
  15823. * @returns {Hammer.Instance}
  15824. * @constructor
  15825. */
  15826. var Hammer = function(element, options) {
  15827. return new Hammer.Instance(element, options || {});
  15828. };
  15829. // default settings
  15830. Hammer.defaults = {
  15831. // add styles and attributes to the element to prevent the browser from doing
  15832. // its native behavior. this doesnt prevent the scrolling, but cancels
  15833. // the contextmenu, tap highlighting etc
  15834. // set to false to disable this
  15835. stop_browser_behavior: {
  15836. // this also triggers onselectstart=false for IE
  15837. userSelect: 'none',
  15838. // this makes the element blocking in IE10 >, you could experiment with the value
  15839. // see for more options this issue; https://github.com/EightMedia/hammer.js/issues/241
  15840. touchAction: 'none',
  15841. touchCallout: 'none',
  15842. contentZooming: 'none',
  15843. userDrag: 'none',
  15844. tapHighlightColor: 'rgba(0,0,0,0)'
  15845. }
  15846. // more settings are defined per gesture at gestures.js
  15847. };
  15848. // detect touchevents
  15849. Hammer.HAS_POINTEREVENTS = navigator.pointerEnabled || navigator.msPointerEnabled;
  15850. Hammer.HAS_TOUCHEVENTS = ('ontouchstart' in window);
  15851. // dont use mouseevents on mobile devices
  15852. Hammer.MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;
  15853. Hammer.NO_MOUSEEVENTS = Hammer.HAS_TOUCHEVENTS && navigator.userAgent.match(Hammer.MOBILE_REGEX);
  15854. // eventtypes per touchevent (start, move, end)
  15855. // are filled by Hammer.event.determineEventTypes on setup
  15856. Hammer.EVENT_TYPES = {};
  15857. // direction defines
  15858. Hammer.DIRECTION_DOWN = 'down';
  15859. Hammer.DIRECTION_LEFT = 'left';
  15860. Hammer.DIRECTION_UP = 'up';
  15861. Hammer.DIRECTION_RIGHT = 'right';
  15862. // pointer type
  15863. Hammer.POINTER_MOUSE = 'mouse';
  15864. Hammer.POINTER_TOUCH = 'touch';
  15865. Hammer.POINTER_PEN = 'pen';
  15866. // touch event defines
  15867. Hammer.EVENT_START = 'start';
  15868. Hammer.EVENT_MOVE = 'move';
  15869. Hammer.EVENT_END = 'end';
  15870. // hammer document where the base events are added at
  15871. Hammer.DOCUMENT = document;
  15872. // plugins namespace
  15873. Hammer.plugins = {};
  15874. // if the window events are set...
  15875. Hammer.READY = false;
  15876. /**
  15877. * setup events to detect gestures on the document
  15878. */
  15879. function setup() {
  15880. if(Hammer.READY) {
  15881. return;
  15882. }
  15883. // find what eventtypes we add listeners to
  15884. Hammer.event.determineEventTypes();
  15885. // Register all gestures inside Hammer.gestures
  15886. for(var name in Hammer.gestures) {
  15887. if(Hammer.gestures.hasOwnProperty(name)) {
  15888. Hammer.detection.register(Hammer.gestures[name]);
  15889. }
  15890. }
  15891. // Add touch events on the document
  15892. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_MOVE, Hammer.detection.detect);
  15893. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_END, Hammer.detection.detect);
  15894. // Hammer is ready...!
  15895. Hammer.READY = true;
  15896. }
  15897. /**
  15898. * create new hammer instance
  15899. * all methods should return the instance itself, so it is chainable.
  15900. * @param {HTMLElement} element
  15901. * @param {Object} [options={}]
  15902. * @returns {Hammer.Instance}
  15903. * @constructor
  15904. */
  15905. Hammer.Instance = function(element, options) {
  15906. var self = this;
  15907. // setup HammerJS window events and register all gestures
  15908. // this also sets up the default options
  15909. setup();
  15910. this.element = element;
  15911. // start/stop detection option
  15912. this.enabled = true;
  15913. // merge options
  15914. this.options = Hammer.utils.extend(
  15915. Hammer.utils.extend({}, Hammer.defaults),
  15916. options || {});
  15917. // add some css to the element to prevent the browser from doing its native behavoir
  15918. if(this.options.stop_browser_behavior) {
  15919. Hammer.utils.stopDefaultBrowserBehavior(this.element, this.options.stop_browser_behavior);
  15920. }
  15921. // start detection on touchstart
  15922. Hammer.event.onTouch(element, Hammer.EVENT_START, function(ev) {
  15923. if(self.enabled) {
  15924. Hammer.detection.startDetect(self, ev);
  15925. }
  15926. });
  15927. // return instance
  15928. return this;
  15929. };
  15930. Hammer.Instance.prototype = {
  15931. /**
  15932. * bind events to the instance
  15933. * @param {String} gesture
  15934. * @param {Function} handler
  15935. * @returns {Hammer.Instance}
  15936. */
  15937. on: function onEvent(gesture, handler){
  15938. var gestures = gesture.split(' ');
  15939. for(var t=0; t<gestures.length; t++) {
  15940. this.element.addEventListener(gestures[t], handler, false);
  15941. }
  15942. return this;
  15943. },
  15944. /**
  15945. * unbind events to the instance
  15946. * @param {String} gesture
  15947. * @param {Function} handler
  15948. * @returns {Hammer.Instance}
  15949. */
  15950. off: function offEvent(gesture, handler){
  15951. var gestures = gesture.split(' ');
  15952. for(var t=0; t<gestures.length; t++) {
  15953. this.element.removeEventListener(gestures[t], handler, false);
  15954. }
  15955. return this;
  15956. },
  15957. /**
  15958. * trigger gesture event
  15959. * @param {String} gesture
  15960. * @param {Object} eventData
  15961. * @returns {Hammer.Instance}
  15962. */
  15963. trigger: function triggerEvent(gesture, eventData){
  15964. // create DOM event
  15965. var event = Hammer.DOCUMENT.createEvent('Event');
  15966. event.initEvent(gesture, true, true);
  15967. event.gesture = eventData;
  15968. // trigger on the target if it is in the instance element,
  15969. // this is for event delegation tricks
  15970. var element = this.element;
  15971. if(Hammer.utils.hasParent(eventData.target, element)) {
  15972. element = eventData.target;
  15973. }
  15974. element.dispatchEvent(event);
  15975. return this;
  15976. },
  15977. /**
  15978. * enable of disable hammer.js detection
  15979. * @param {Boolean} state
  15980. * @returns {Hammer.Instance}
  15981. */
  15982. enable: function enable(state) {
  15983. this.enabled = state;
  15984. return this;
  15985. }
  15986. };
  15987. /**
  15988. * this holds the last move event,
  15989. * used to fix empty touchend issue
  15990. * see the onTouch event for an explanation
  15991. * @type {Object}
  15992. */
  15993. var last_move_event = null;
  15994. /**
  15995. * when the mouse is hold down, this is true
  15996. * @type {Boolean}
  15997. */
  15998. var enable_detect = false;
  15999. /**
  16000. * when touch events have been fired, this is true
  16001. * @type {Boolean}
  16002. */
  16003. var touch_triggered = false;
  16004. Hammer.event = {
  16005. /**
  16006. * simple addEventListener
  16007. * @param {HTMLElement} element
  16008. * @param {String} type
  16009. * @param {Function} handler
  16010. */
  16011. bindDom: function(element, type, handler) {
  16012. var types = type.split(' ');
  16013. for(var t=0; t<types.length; t++) {
  16014. element.addEventListener(types[t], handler, false);
  16015. }
  16016. },
  16017. /**
  16018. * touch events with mouse fallback
  16019. * @param {HTMLElement} element
  16020. * @param {String} eventType like Hammer.EVENT_MOVE
  16021. * @param {Function} handler
  16022. */
  16023. onTouch: function onTouch(element, eventType, handler) {
  16024. var self = this;
  16025. this.bindDom(element, Hammer.EVENT_TYPES[eventType], function bindDomOnTouch(ev) {
  16026. var sourceEventType = ev.type.toLowerCase();
  16027. // onmouseup, but when touchend has been fired we do nothing.
  16028. // this is for touchdevices which also fire a mouseup on touchend
  16029. if(sourceEventType.match(/mouse/) && touch_triggered) {
  16030. return;
  16031. }
  16032. // mousebutton must be down or a touch event
  16033. else if( sourceEventType.match(/touch/) || // touch events are always on screen
  16034. sourceEventType.match(/pointerdown/) || // pointerevents touch
  16035. (sourceEventType.match(/mouse/) && ev.which === 1) // mouse is pressed
  16036. ){
  16037. enable_detect = true;
  16038. }
  16039. // we are in a touch event, set the touch triggered bool to true,
  16040. // this for the conflicts that may occur on ios and android
  16041. if(sourceEventType.match(/touch|pointer/)) {
  16042. touch_triggered = true;
  16043. }
  16044. // count the total touches on the screen
  16045. var count_touches = 0;
  16046. // when touch has been triggered in this detection session
  16047. // and we are now handling a mouse event, we stop that to prevent conflicts
  16048. if(enable_detect) {
  16049. // update pointerevent
  16050. if(Hammer.HAS_POINTEREVENTS && eventType != Hammer.EVENT_END) {
  16051. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  16052. }
  16053. // touch
  16054. else if(sourceEventType.match(/touch/)) {
  16055. count_touches = ev.touches.length;
  16056. }
  16057. // mouse
  16058. else if(!touch_triggered) {
  16059. count_touches = sourceEventType.match(/up/) ? 0 : 1;
  16060. }
  16061. // if we are in a end event, but when we remove one touch and
  16062. // we still have enough, set eventType to move
  16063. if(count_touches > 0 && eventType == Hammer.EVENT_END) {
  16064. eventType = Hammer.EVENT_MOVE;
  16065. }
  16066. // no touches, force the end event
  16067. else if(!count_touches) {
  16068. eventType = Hammer.EVENT_END;
  16069. }
  16070. // because touchend has no touches, and we often want to use these in our gestures,
  16071. // we send the last move event as our eventData in touchend
  16072. if(!count_touches && last_move_event !== null) {
  16073. ev = last_move_event;
  16074. }
  16075. // store the last move event
  16076. else {
  16077. last_move_event = ev;
  16078. }
  16079. // trigger the handler
  16080. handler.call(Hammer.detection, self.collectEventData(element, eventType, ev));
  16081. // remove pointerevent from list
  16082. if(Hammer.HAS_POINTEREVENTS && eventType == Hammer.EVENT_END) {
  16083. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  16084. }
  16085. }
  16086. //debug(sourceEventType +" "+ eventType);
  16087. // on the end we reset everything
  16088. if(!count_touches) {
  16089. last_move_event = null;
  16090. enable_detect = false;
  16091. touch_triggered = false;
  16092. Hammer.PointerEvent.reset();
  16093. }
  16094. });
  16095. },
  16096. /**
  16097. * we have different events for each device/browser
  16098. * determine what we need and set them in the Hammer.EVENT_TYPES constant
  16099. */
  16100. determineEventTypes: function determineEventTypes() {
  16101. // determine the eventtype we want to set
  16102. var types;
  16103. // pointerEvents magic
  16104. if(Hammer.HAS_POINTEREVENTS) {
  16105. types = Hammer.PointerEvent.getEvents();
  16106. }
  16107. // on Android, iOS, blackberry, windows mobile we dont want any mouseevents
  16108. else if(Hammer.NO_MOUSEEVENTS) {
  16109. types = [
  16110. 'touchstart',
  16111. 'touchmove',
  16112. 'touchend touchcancel'];
  16113. }
  16114. // for non pointer events browsers and mixed browsers,
  16115. // like chrome on windows8 touch laptop
  16116. else {
  16117. types = [
  16118. 'touchstart mousedown',
  16119. 'touchmove mousemove',
  16120. 'touchend touchcancel mouseup'];
  16121. }
  16122. Hammer.EVENT_TYPES[Hammer.EVENT_START] = types[0];
  16123. Hammer.EVENT_TYPES[Hammer.EVENT_MOVE] = types[1];
  16124. Hammer.EVENT_TYPES[Hammer.EVENT_END] = types[2];
  16125. },
  16126. /**
  16127. * create touchlist depending on the event
  16128. * @param {Object} ev
  16129. * @param {String} eventType used by the fakemultitouch plugin
  16130. */
  16131. getTouchList: function getTouchList(ev/*, eventType*/) {
  16132. // get the fake pointerEvent touchlist
  16133. if(Hammer.HAS_POINTEREVENTS) {
  16134. return Hammer.PointerEvent.getTouchList();
  16135. }
  16136. // get the touchlist
  16137. else if(ev.touches) {
  16138. return ev.touches;
  16139. }
  16140. // make fake touchlist from mouse position
  16141. else {
  16142. return [{
  16143. identifier: 1,
  16144. pageX: ev.pageX,
  16145. pageY: ev.pageY,
  16146. target: ev.target
  16147. }];
  16148. }
  16149. },
  16150. /**
  16151. * collect event data for Hammer js
  16152. * @param {HTMLElement} element
  16153. * @param {String} eventType like Hammer.EVENT_MOVE
  16154. * @param {Object} eventData
  16155. */
  16156. collectEventData: function collectEventData(element, eventType, ev) {
  16157. var touches = this.getTouchList(ev, eventType);
  16158. // find out pointerType
  16159. var pointerType = Hammer.POINTER_TOUCH;
  16160. if(ev.type.match(/mouse/) || Hammer.PointerEvent.matchType(Hammer.POINTER_MOUSE, ev)) {
  16161. pointerType = Hammer.POINTER_MOUSE;
  16162. }
  16163. return {
  16164. center : Hammer.utils.getCenter(touches),
  16165. timeStamp : new Date().getTime(),
  16166. target : ev.target,
  16167. touches : touches,
  16168. eventType : eventType,
  16169. pointerType : pointerType,
  16170. srcEvent : ev,
  16171. /**
  16172. * prevent the browser default actions
  16173. * mostly used to disable scrolling of the browser
  16174. */
  16175. preventDefault: function() {
  16176. if(this.srcEvent.preventManipulation) {
  16177. this.srcEvent.preventManipulation();
  16178. }
  16179. if(this.srcEvent.preventDefault) {
  16180. this.srcEvent.preventDefault();
  16181. }
  16182. },
  16183. /**
  16184. * stop bubbling the event up to its parents
  16185. */
  16186. stopPropagation: function() {
  16187. this.srcEvent.stopPropagation();
  16188. },
  16189. /**
  16190. * immediately stop gesture detection
  16191. * might be useful after a swipe was detected
  16192. * @return {*}
  16193. */
  16194. stopDetect: function() {
  16195. return Hammer.detection.stopDetect();
  16196. }
  16197. };
  16198. }
  16199. };
  16200. Hammer.PointerEvent = {
  16201. /**
  16202. * holds all pointers
  16203. * @type {Object}
  16204. */
  16205. pointers: {},
  16206. /**
  16207. * get a list of pointers
  16208. * @returns {Array} touchlist
  16209. */
  16210. getTouchList: function() {
  16211. var self = this;
  16212. var touchlist = [];
  16213. // we can use forEach since pointerEvents only is in IE10
  16214. Object.keys(self.pointers).sort().forEach(function(id) {
  16215. touchlist.push(self.pointers[id]);
  16216. });
  16217. return touchlist;
  16218. },
  16219. /**
  16220. * update the position of a pointer
  16221. * @param {String} type Hammer.EVENT_END
  16222. * @param {Object} pointerEvent
  16223. */
  16224. updatePointer: function(type, pointerEvent) {
  16225. if(type == Hammer.EVENT_END) {
  16226. this.pointers = {};
  16227. }
  16228. else {
  16229. pointerEvent.identifier = pointerEvent.pointerId;
  16230. this.pointers[pointerEvent.pointerId] = pointerEvent;
  16231. }
  16232. return Object.keys(this.pointers).length;
  16233. },
  16234. /**
  16235. * check if ev matches pointertype
  16236. * @param {String} pointerType Hammer.POINTER_MOUSE
  16237. * @param {PointerEvent} ev
  16238. */
  16239. matchType: function(pointerType, ev) {
  16240. if(!ev.pointerType) {
  16241. return false;
  16242. }
  16243. var types = {};
  16244. types[Hammer.POINTER_MOUSE] = (ev.pointerType == ev.MSPOINTER_TYPE_MOUSE || ev.pointerType == Hammer.POINTER_MOUSE);
  16245. types[Hammer.POINTER_TOUCH] = (ev.pointerType == ev.MSPOINTER_TYPE_TOUCH || ev.pointerType == Hammer.POINTER_TOUCH);
  16246. types[Hammer.POINTER_PEN] = (ev.pointerType == ev.MSPOINTER_TYPE_PEN || ev.pointerType == Hammer.POINTER_PEN);
  16247. return types[pointerType];
  16248. },
  16249. /**
  16250. * get events
  16251. */
  16252. getEvents: function() {
  16253. return [
  16254. 'pointerdown MSPointerDown',
  16255. 'pointermove MSPointerMove',
  16256. 'pointerup pointercancel MSPointerUp MSPointerCancel'
  16257. ];
  16258. },
  16259. /**
  16260. * reset the list
  16261. */
  16262. reset: function() {
  16263. this.pointers = {};
  16264. }
  16265. };
  16266. Hammer.utils = {
  16267. /**
  16268. * extend method,
  16269. * also used for cloning when dest is an empty object
  16270. * @param {Object} dest
  16271. * @param {Object} src
  16272. * @parm {Boolean} merge do a merge
  16273. * @returns {Object} dest
  16274. */
  16275. extend: function extend(dest, src, merge) {
  16276. for (var key in src) {
  16277. if(dest[key] !== undefined && merge) {
  16278. continue;
  16279. }
  16280. dest[key] = src[key];
  16281. }
  16282. return dest;
  16283. },
  16284. /**
  16285. * find if a node is in the given parent
  16286. * used for event delegation tricks
  16287. * @param {HTMLElement} node
  16288. * @param {HTMLElement} parent
  16289. * @returns {boolean} has_parent
  16290. */
  16291. hasParent: function(node, parent) {
  16292. while(node){
  16293. if(node == parent) {
  16294. return true;
  16295. }
  16296. node = node.parentNode;
  16297. }
  16298. return false;
  16299. },
  16300. /**
  16301. * get the center of all the touches
  16302. * @param {Array} touches
  16303. * @returns {Object} center
  16304. */
  16305. getCenter: function getCenter(touches) {
  16306. var valuesX = [], valuesY = [];
  16307. for(var t= 0,len=touches.length; t<len; t++) {
  16308. valuesX.push(touches[t].pageX);
  16309. valuesY.push(touches[t].pageY);
  16310. }
  16311. return {
  16312. pageX: ((Math.min.apply(Math, valuesX) + Math.max.apply(Math, valuesX)) / 2),
  16313. pageY: ((Math.min.apply(Math, valuesY) + Math.max.apply(Math, valuesY)) / 2)
  16314. };
  16315. },
  16316. /**
  16317. * calculate the velocity between two points
  16318. * @param {Number} delta_time
  16319. * @param {Number} delta_x
  16320. * @param {Number} delta_y
  16321. * @returns {Object} velocity
  16322. */
  16323. getVelocity: function getVelocity(delta_time, delta_x, delta_y) {
  16324. return {
  16325. x: Math.abs(delta_x / delta_time) || 0,
  16326. y: Math.abs(delta_y / delta_time) || 0
  16327. };
  16328. },
  16329. /**
  16330. * calculate the angle between two coordinates
  16331. * @param {Touch} touch1
  16332. * @param {Touch} touch2
  16333. * @returns {Number} angle
  16334. */
  16335. getAngle: function getAngle(touch1, touch2) {
  16336. var y = touch2.pageY - touch1.pageY,
  16337. x = touch2.pageX - touch1.pageX;
  16338. return Math.atan2(y, x) * 180 / Math.PI;
  16339. },
  16340. /**
  16341. * angle to direction define
  16342. * @param {Touch} touch1
  16343. * @param {Touch} touch2
  16344. * @returns {String} direction constant, like Hammer.DIRECTION_LEFT
  16345. */
  16346. getDirection: function getDirection(touch1, touch2) {
  16347. var x = Math.abs(touch1.pageX - touch2.pageX),
  16348. y = Math.abs(touch1.pageY - touch2.pageY);
  16349. if(x >= y) {
  16350. return touch1.pageX - touch2.pageX > 0 ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  16351. }
  16352. else {
  16353. return touch1.pageY - touch2.pageY > 0 ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  16354. }
  16355. },
  16356. /**
  16357. * calculate the distance between two touches
  16358. * @param {Touch} touch1
  16359. * @param {Touch} touch2
  16360. * @returns {Number} distance
  16361. */
  16362. getDistance: function getDistance(touch1, touch2) {
  16363. var x = touch2.pageX - touch1.pageX,
  16364. y = touch2.pageY - touch1.pageY;
  16365. return Math.sqrt((x*x) + (y*y));
  16366. },
  16367. /**
  16368. * calculate the scale factor between two touchLists (fingers)
  16369. * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
  16370. * @param {Array} start
  16371. * @param {Array} end
  16372. * @returns {Number} scale
  16373. */
  16374. getScale: function getScale(start, end) {
  16375. // need two fingers...
  16376. if(start.length >= 2 && end.length >= 2) {
  16377. return this.getDistance(end[0], end[1]) /
  16378. this.getDistance(start[0], start[1]);
  16379. }
  16380. return 1;
  16381. },
  16382. /**
  16383. * calculate the rotation degrees between two touchLists (fingers)
  16384. * @param {Array} start
  16385. * @param {Array} end
  16386. * @returns {Number} rotation
  16387. */
  16388. getRotation: function getRotation(start, end) {
  16389. // need two fingers
  16390. if(start.length >= 2 && end.length >= 2) {
  16391. return this.getAngle(end[1], end[0]) -
  16392. this.getAngle(start[1], start[0]);
  16393. }
  16394. return 0;
  16395. },
  16396. /**
  16397. * boolean if the direction is vertical
  16398. * @param {String} direction
  16399. * @returns {Boolean} is_vertical
  16400. */
  16401. isVertical: function isVertical(direction) {
  16402. return (direction == Hammer.DIRECTION_UP || direction == Hammer.DIRECTION_DOWN);
  16403. },
  16404. /**
  16405. * stop browser default behavior with css props
  16406. * @param {HtmlElement} element
  16407. * @param {Object} css_props
  16408. */
  16409. stopDefaultBrowserBehavior: function stopDefaultBrowserBehavior(element, css_props) {
  16410. var prop,
  16411. vendors = ['webkit','khtml','moz','ms','o',''];
  16412. if(!css_props || !element.style) {
  16413. return;
  16414. }
  16415. // with css properties for modern browsers
  16416. for(var i = 0; i < vendors.length; i++) {
  16417. for(var p in css_props) {
  16418. if(css_props.hasOwnProperty(p)) {
  16419. prop = p;
  16420. // vender prefix at the property
  16421. if(vendors[i]) {
  16422. prop = vendors[i] + prop.substring(0, 1).toUpperCase() + prop.substring(1);
  16423. }
  16424. // set the style
  16425. element.style[prop] = css_props[p];
  16426. }
  16427. }
  16428. }
  16429. // also the disable onselectstart
  16430. if(css_props.userSelect == 'none') {
  16431. element.onselectstart = function() {
  16432. return false;
  16433. };
  16434. }
  16435. }
  16436. };
  16437. Hammer.detection = {
  16438. // contains all registred Hammer.gestures in the correct order
  16439. gestures: [],
  16440. // data of the current Hammer.gesture detection session
  16441. current: null,
  16442. // the previous Hammer.gesture session data
  16443. // is a full clone of the previous gesture.current object
  16444. previous: null,
  16445. // when this becomes true, no gestures are fired
  16446. stopped: false,
  16447. /**
  16448. * start Hammer.gesture detection
  16449. * @param {Hammer.Instance} inst
  16450. * @param {Object} eventData
  16451. */
  16452. startDetect: function startDetect(inst, eventData) {
  16453. // already busy with a Hammer.gesture detection on an element
  16454. if(this.current) {
  16455. return;
  16456. }
  16457. this.stopped = false;
  16458. this.current = {
  16459. inst : inst, // reference to HammerInstance we're working for
  16460. startEvent : Hammer.utils.extend({}, eventData), // start eventData for distances, timing etc
  16461. lastEvent : false, // last eventData
  16462. name : '' // current gesture we're in/detected, can be 'tap', 'hold' etc
  16463. };
  16464. this.detect(eventData);
  16465. },
  16466. /**
  16467. * Hammer.gesture detection
  16468. * @param {Object} eventData
  16469. * @param {Object} eventData
  16470. */
  16471. detect: function detect(eventData) {
  16472. if(!this.current || this.stopped) {
  16473. return;
  16474. }
  16475. // extend event data with calculations about scale, distance etc
  16476. eventData = this.extendEventData(eventData);
  16477. // instance options
  16478. var inst_options = this.current.inst.options;
  16479. // call Hammer.gesture handlers
  16480. for(var g=0,len=this.gestures.length; g<len; g++) {
  16481. var gesture = this.gestures[g];
  16482. // only when the instance options have enabled this gesture
  16483. if(!this.stopped && inst_options[gesture.name] !== false) {
  16484. // if a handler returns false, we stop with the detection
  16485. if(gesture.handler.call(gesture, eventData, this.current.inst) === false) {
  16486. this.stopDetect();
  16487. break;
  16488. }
  16489. }
  16490. }
  16491. // store as previous event event
  16492. if(this.current) {
  16493. this.current.lastEvent = eventData;
  16494. }
  16495. // endevent, but not the last touch, so dont stop
  16496. if(eventData.eventType == Hammer.EVENT_END && !eventData.touches.length-1) {
  16497. this.stopDetect();
  16498. }
  16499. return eventData;
  16500. },
  16501. /**
  16502. * clear the Hammer.gesture vars
  16503. * this is called on endDetect, but can also be used when a final Hammer.gesture has been detected
  16504. * to stop other Hammer.gestures from being fired
  16505. */
  16506. stopDetect: function stopDetect() {
  16507. // clone current data to the store as the previous gesture
  16508. // used for the double tap gesture, since this is an other gesture detect session
  16509. this.previous = Hammer.utils.extend({}, this.current);
  16510. // reset the current
  16511. this.current = null;
  16512. // stopped!
  16513. this.stopped = true;
  16514. },
  16515. /**
  16516. * extend eventData for Hammer.gestures
  16517. * @param {Object} ev
  16518. * @returns {Object} ev
  16519. */
  16520. extendEventData: function extendEventData(ev) {
  16521. var startEv = this.current.startEvent;
  16522. // if the touches change, set the new touches over the startEvent touches
  16523. // this because touchevents don't have all the touches on touchstart, or the
  16524. // user must place his fingers at the EXACT same time on the screen, which is not realistic
  16525. // but, sometimes it happens that both fingers are touching at the EXACT same time
  16526. if(startEv && (ev.touches.length != startEv.touches.length || ev.touches === startEv.touches)) {
  16527. // extend 1 level deep to get the touchlist with the touch objects
  16528. startEv.touches = [];
  16529. for(var i=0,len=ev.touches.length; i<len; i++) {
  16530. startEv.touches.push(Hammer.utils.extend({}, ev.touches[i]));
  16531. }
  16532. }
  16533. var delta_time = ev.timeStamp - startEv.timeStamp,
  16534. delta_x = ev.center.pageX - startEv.center.pageX,
  16535. delta_y = ev.center.pageY - startEv.center.pageY,
  16536. velocity = Hammer.utils.getVelocity(delta_time, delta_x, delta_y);
  16537. Hammer.utils.extend(ev, {
  16538. deltaTime : delta_time,
  16539. deltaX : delta_x,
  16540. deltaY : delta_y,
  16541. velocityX : velocity.x,
  16542. velocityY : velocity.y,
  16543. distance : Hammer.utils.getDistance(startEv.center, ev.center),
  16544. angle : Hammer.utils.getAngle(startEv.center, ev.center),
  16545. direction : Hammer.utils.getDirection(startEv.center, ev.center),
  16546. scale : Hammer.utils.getScale(startEv.touches, ev.touches),
  16547. rotation : Hammer.utils.getRotation(startEv.touches, ev.touches),
  16548. startEvent : startEv
  16549. });
  16550. return ev;
  16551. },
  16552. /**
  16553. * register new gesture
  16554. * @param {Object} gesture object, see gestures.js for documentation
  16555. * @returns {Array} gestures
  16556. */
  16557. register: function register(gesture) {
  16558. // add an enable gesture options if there is no given
  16559. var options = gesture.defaults || {};
  16560. if(options[gesture.name] === undefined) {
  16561. options[gesture.name] = true;
  16562. }
  16563. // extend Hammer default options with the Hammer.gesture options
  16564. Hammer.utils.extend(Hammer.defaults, options, true);
  16565. // set its index
  16566. gesture.index = gesture.index || 1000;
  16567. // add Hammer.gesture to the list
  16568. this.gestures.push(gesture);
  16569. // sort the list by index
  16570. this.gestures.sort(function(a, b) {
  16571. if (a.index < b.index) {
  16572. return -1;
  16573. }
  16574. if (a.index > b.index) {
  16575. return 1;
  16576. }
  16577. return 0;
  16578. });
  16579. return this.gestures;
  16580. }
  16581. };
  16582. Hammer.gestures = Hammer.gestures || {};
  16583. /**
  16584. * Custom gestures
  16585. * ==============================
  16586. *
  16587. * Gesture object
  16588. * --------------------
  16589. * The object structure of a gesture:
  16590. *
  16591. * { name: 'mygesture',
  16592. * index: 1337,
  16593. * defaults: {
  16594. * mygesture_option: true
  16595. * }
  16596. * handler: function(type, ev, inst) {
  16597. * // trigger gesture event
  16598. * inst.trigger(this.name, ev);
  16599. * }
  16600. * }
  16601. * @param {String} name
  16602. * this should be the name of the gesture, lowercase
  16603. * it is also being used to disable/enable the gesture per instance config.
  16604. *
  16605. * @param {Number} [index=1000]
  16606. * the index of the gesture, where it is going to be in the stack of gestures detection
  16607. * like when you build an gesture that depends on the drag gesture, it is a good
  16608. * idea to place it after the index of the drag gesture.
  16609. *
  16610. * @param {Object} [defaults={}]
  16611. * the default settings of the gesture. these are added to the instance settings,
  16612. * and can be overruled per instance. you can also add the name of the gesture,
  16613. * but this is also added by default (and set to true).
  16614. *
  16615. * @param {Function} handler
  16616. * this handles the gesture detection of your custom gesture and receives the
  16617. * following arguments:
  16618. *
  16619. * @param {Object} eventData
  16620. * event data containing the following properties:
  16621. * timeStamp {Number} time the event occurred
  16622. * target {HTMLElement} target element
  16623. * touches {Array} touches (fingers, pointers, mouse) on the screen
  16624. * pointerType {String} kind of pointer that was used. matches Hammer.POINTER_MOUSE|TOUCH
  16625. * center {Object} center position of the touches. contains pageX and pageY
  16626. * deltaTime {Number} the total time of the touches in the screen
  16627. * deltaX {Number} the delta on x axis we haved moved
  16628. * deltaY {Number} the delta on y axis we haved moved
  16629. * velocityX {Number} the velocity on the x
  16630. * velocityY {Number} the velocity on y
  16631. * angle {Number} the angle we are moving
  16632. * direction {String} the direction we are moving. matches Hammer.DIRECTION_UP|DOWN|LEFT|RIGHT
  16633. * distance {Number} the distance we haved moved
  16634. * scale {Number} scaling of the touches, needs 2 touches
  16635. * rotation {Number} rotation of the touches, needs 2 touches *
  16636. * eventType {String} matches Hammer.EVENT_START|MOVE|END
  16637. * srcEvent {Object} the source event, like TouchStart or MouseDown *
  16638. * startEvent {Object} contains the same properties as above,
  16639. * but from the first touch. this is used to calculate
  16640. * distances, deltaTime, scaling etc
  16641. *
  16642. * @param {Hammer.Instance} inst
  16643. * the instance we are doing the detection for. you can get the options from
  16644. * the inst.options object and trigger the gesture event by calling inst.trigger
  16645. *
  16646. *
  16647. * Handle gestures
  16648. * --------------------
  16649. * inside the handler you can get/set Hammer.detection.current. This is the current
  16650. * detection session. It has the following properties
  16651. * @param {String} name
  16652. * contains the name of the gesture we have detected. it has not a real function,
  16653. * only to check in other gestures if something is detected.
  16654. * like in the drag gesture we set it to 'drag' and in the swipe gesture we can
  16655. * check if the current gesture is 'drag' by accessing Hammer.detection.current.name
  16656. *
  16657. * @readonly
  16658. * @param {Hammer.Instance} inst
  16659. * the instance we do the detection for
  16660. *
  16661. * @readonly
  16662. * @param {Object} startEvent
  16663. * contains the properties of the first gesture detection in this session.
  16664. * Used for calculations about timing, distance, etc.
  16665. *
  16666. * @readonly
  16667. * @param {Object} lastEvent
  16668. * contains all the properties of the last gesture detect in this session.
  16669. *
  16670. * after the gesture detection session has been completed (user has released the screen)
  16671. * the Hammer.detection.current object is copied into Hammer.detection.previous,
  16672. * this is usefull for gestures like doubletap, where you need to know if the
  16673. * previous gesture was a tap
  16674. *
  16675. * options that have been set by the instance can be received by calling inst.options
  16676. *
  16677. * You can trigger a gesture event by calling inst.trigger("mygesture", event).
  16678. * The first param is the name of your gesture, the second the event argument
  16679. *
  16680. *
  16681. * Register gestures
  16682. * --------------------
  16683. * When an gesture is added to the Hammer.gestures object, it is auto registered
  16684. * at the setup of the first Hammer instance. You can also call Hammer.detection.register
  16685. * manually and pass your gesture object as a param
  16686. *
  16687. */
  16688. /**
  16689. * Hold
  16690. * Touch stays at the same place for x time
  16691. * @events hold
  16692. */
  16693. Hammer.gestures.Hold = {
  16694. name: 'hold',
  16695. index: 10,
  16696. defaults: {
  16697. hold_timeout : 500,
  16698. hold_threshold : 1
  16699. },
  16700. timer: null,
  16701. handler: function holdGesture(ev, inst) {
  16702. switch(ev.eventType) {
  16703. case Hammer.EVENT_START:
  16704. // clear any running timers
  16705. clearTimeout(this.timer);
  16706. // set the gesture so we can check in the timeout if it still is
  16707. Hammer.detection.current.name = this.name;
  16708. // set timer and if after the timeout it still is hold,
  16709. // we trigger the hold event
  16710. this.timer = setTimeout(function() {
  16711. if(Hammer.detection.current.name == 'hold') {
  16712. inst.trigger('hold', ev);
  16713. }
  16714. }, inst.options.hold_timeout);
  16715. break;
  16716. // when you move or end we clear the timer
  16717. case Hammer.EVENT_MOVE:
  16718. if(ev.distance > inst.options.hold_threshold) {
  16719. clearTimeout(this.timer);
  16720. }
  16721. break;
  16722. case Hammer.EVENT_END:
  16723. clearTimeout(this.timer);
  16724. break;
  16725. }
  16726. }
  16727. };
  16728. /**
  16729. * Tap/DoubleTap
  16730. * Quick touch at a place or double at the same place
  16731. * @events tap, doubletap
  16732. */
  16733. Hammer.gestures.Tap = {
  16734. name: 'tap',
  16735. index: 100,
  16736. defaults: {
  16737. tap_max_touchtime : 250,
  16738. tap_max_distance : 10,
  16739. tap_always : true,
  16740. doubletap_distance : 20,
  16741. doubletap_interval : 300
  16742. },
  16743. handler: function tapGesture(ev, inst) {
  16744. if(ev.eventType == Hammer.EVENT_END) {
  16745. // previous gesture, for the double tap since these are two different gesture detections
  16746. var prev = Hammer.detection.previous,
  16747. did_doubletap = false;
  16748. // when the touchtime is higher then the max touch time
  16749. // or when the moving distance is too much
  16750. if(ev.deltaTime > inst.options.tap_max_touchtime ||
  16751. ev.distance > inst.options.tap_max_distance) {
  16752. return;
  16753. }
  16754. // check if double tap
  16755. if(prev && prev.name == 'tap' &&
  16756. (ev.timeStamp - prev.lastEvent.timeStamp) < inst.options.doubletap_interval &&
  16757. ev.distance < inst.options.doubletap_distance) {
  16758. inst.trigger('doubletap', ev);
  16759. did_doubletap = true;
  16760. }
  16761. // do a single tap
  16762. if(!did_doubletap || inst.options.tap_always) {
  16763. Hammer.detection.current.name = 'tap';
  16764. inst.trigger(Hammer.detection.current.name, ev);
  16765. }
  16766. }
  16767. }
  16768. };
  16769. /**
  16770. * Swipe
  16771. * triggers swipe events when the end velocity is above the threshold
  16772. * @events swipe, swipeleft, swiperight, swipeup, swipedown
  16773. */
  16774. Hammer.gestures.Swipe = {
  16775. name: 'swipe',
  16776. index: 40,
  16777. defaults: {
  16778. // set 0 for unlimited, but this can conflict with transform
  16779. swipe_max_touches : 1,
  16780. swipe_velocity : 0.7
  16781. },
  16782. handler: function swipeGesture(ev, inst) {
  16783. if(ev.eventType == Hammer.EVENT_END) {
  16784. // max touches
  16785. if(inst.options.swipe_max_touches > 0 &&
  16786. ev.touches.length > inst.options.swipe_max_touches) {
  16787. return;
  16788. }
  16789. // when the distance we moved is too small we skip this gesture
  16790. // or we can be already in dragging
  16791. if(ev.velocityX > inst.options.swipe_velocity ||
  16792. ev.velocityY > inst.options.swipe_velocity) {
  16793. // trigger swipe events
  16794. inst.trigger(this.name, ev);
  16795. inst.trigger(this.name + ev.direction, ev);
  16796. }
  16797. }
  16798. }
  16799. };
  16800. /**
  16801. * Drag
  16802. * Move with x fingers (default 1) around on the page. Blocking the scrolling when
  16803. * moving left and right is a good practice. When all the drag events are blocking
  16804. * you disable scrolling on that area.
  16805. * @events drag, drapleft, dragright, dragup, dragdown
  16806. */
  16807. Hammer.gestures.Drag = {
  16808. name: 'drag',
  16809. index: 50,
  16810. defaults: {
  16811. drag_min_distance : 10,
  16812. // set 0 for unlimited, but this can conflict with transform
  16813. drag_max_touches : 1,
  16814. // prevent default browser behavior when dragging occurs
  16815. // be careful with it, it makes the element a blocking element
  16816. // when you are using the drag gesture, it is a good practice to set this true
  16817. drag_block_horizontal : false,
  16818. drag_block_vertical : false,
  16819. // drag_lock_to_axis keeps the drag gesture on the axis that it started on,
  16820. // It disallows vertical directions if the initial direction was horizontal, and vice versa.
  16821. drag_lock_to_axis : false,
  16822. // drag lock only kicks in when distance > drag_lock_min_distance
  16823. // This way, locking occurs only when the distance has become large enough to reliably determine the direction
  16824. drag_lock_min_distance : 25
  16825. },
  16826. triggered: false,
  16827. handler: function dragGesture(ev, inst) {
  16828. // current gesture isnt drag, but dragged is true
  16829. // this means an other gesture is busy. now call dragend
  16830. if(Hammer.detection.current.name != this.name && this.triggered) {
  16831. inst.trigger(this.name +'end', ev);
  16832. this.triggered = false;
  16833. return;
  16834. }
  16835. // max touches
  16836. if(inst.options.drag_max_touches > 0 &&
  16837. ev.touches.length > inst.options.drag_max_touches) {
  16838. return;
  16839. }
  16840. switch(ev.eventType) {
  16841. case Hammer.EVENT_START:
  16842. this.triggered = false;
  16843. break;
  16844. case Hammer.EVENT_MOVE:
  16845. // when the distance we moved is too small we skip this gesture
  16846. // or we can be already in dragging
  16847. if(ev.distance < inst.options.drag_min_distance &&
  16848. Hammer.detection.current.name != this.name) {
  16849. return;
  16850. }
  16851. // we are dragging!
  16852. Hammer.detection.current.name = this.name;
  16853. // lock drag to axis?
  16854. if(Hammer.detection.current.lastEvent.drag_locked_to_axis || (inst.options.drag_lock_to_axis && inst.options.drag_lock_min_distance<=ev.distance)) {
  16855. ev.drag_locked_to_axis = true;
  16856. }
  16857. var last_direction = Hammer.detection.current.lastEvent.direction;
  16858. if(ev.drag_locked_to_axis && last_direction !== ev.direction) {
  16859. // keep direction on the axis that the drag gesture started on
  16860. if(Hammer.utils.isVertical(last_direction)) {
  16861. ev.direction = (ev.deltaY < 0) ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  16862. }
  16863. else {
  16864. ev.direction = (ev.deltaX < 0) ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  16865. }
  16866. }
  16867. // first time, trigger dragstart event
  16868. if(!this.triggered) {
  16869. inst.trigger(this.name +'start', ev);
  16870. this.triggered = true;
  16871. }
  16872. // trigger normal event
  16873. inst.trigger(this.name, ev);
  16874. // direction event, like dragdown
  16875. inst.trigger(this.name + ev.direction, ev);
  16876. // block the browser events
  16877. if( (inst.options.drag_block_vertical && Hammer.utils.isVertical(ev.direction)) ||
  16878. (inst.options.drag_block_horizontal && !Hammer.utils.isVertical(ev.direction))) {
  16879. ev.preventDefault();
  16880. }
  16881. break;
  16882. case Hammer.EVENT_END:
  16883. // trigger dragend
  16884. if(this.triggered) {
  16885. inst.trigger(this.name +'end', ev);
  16886. }
  16887. this.triggered = false;
  16888. break;
  16889. }
  16890. }
  16891. };
  16892. /**
  16893. * Transform
  16894. * User want to scale or rotate with 2 fingers
  16895. * @events transform, pinch, pinchin, pinchout, rotate
  16896. */
  16897. Hammer.gestures.Transform = {
  16898. name: 'transform',
  16899. index: 45,
  16900. defaults: {
  16901. // factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1
  16902. transform_min_scale : 0.01,
  16903. // rotation in degrees
  16904. transform_min_rotation : 1,
  16905. // prevent default browser behavior when two touches are on the screen
  16906. // but it makes the element a blocking element
  16907. // when you are using the transform gesture, it is a good practice to set this true
  16908. transform_always_block : false
  16909. },
  16910. triggered: false,
  16911. handler: function transformGesture(ev, inst) {
  16912. // current gesture isnt drag, but dragged is true
  16913. // this means an other gesture is busy. now call dragend
  16914. if(Hammer.detection.current.name != this.name && this.triggered) {
  16915. inst.trigger(this.name +'end', ev);
  16916. this.triggered = false;
  16917. return;
  16918. }
  16919. // atleast multitouch
  16920. if(ev.touches.length < 2) {
  16921. return;
  16922. }
  16923. // prevent default when two fingers are on the screen
  16924. if(inst.options.transform_always_block) {
  16925. ev.preventDefault();
  16926. }
  16927. switch(ev.eventType) {
  16928. case Hammer.EVENT_START:
  16929. this.triggered = false;
  16930. break;
  16931. case Hammer.EVENT_MOVE:
  16932. var scale_threshold = Math.abs(1-ev.scale);
  16933. var rotation_threshold = Math.abs(ev.rotation);
  16934. // when the distance we moved is too small we skip this gesture
  16935. // or we can be already in dragging
  16936. if(scale_threshold < inst.options.transform_min_scale &&
  16937. rotation_threshold < inst.options.transform_min_rotation) {
  16938. return;
  16939. }
  16940. // we are transforming!
  16941. Hammer.detection.current.name = this.name;
  16942. // first time, trigger dragstart event
  16943. if(!this.triggered) {
  16944. inst.trigger(this.name +'start', ev);
  16945. this.triggered = true;
  16946. }
  16947. inst.trigger(this.name, ev); // basic transform event
  16948. // trigger rotate event
  16949. if(rotation_threshold > inst.options.transform_min_rotation) {
  16950. inst.trigger('rotate', ev);
  16951. }
  16952. // trigger pinch event
  16953. if(scale_threshold > inst.options.transform_min_scale) {
  16954. inst.trigger('pinch', ev);
  16955. inst.trigger('pinch'+ ((ev.scale < 1) ? 'in' : 'out'), ev);
  16956. }
  16957. break;
  16958. case Hammer.EVENT_END:
  16959. // trigger dragend
  16960. if(this.triggered) {
  16961. inst.trigger(this.name +'end', ev);
  16962. }
  16963. this.triggered = false;
  16964. break;
  16965. }
  16966. }
  16967. };
  16968. /**
  16969. * Touch
  16970. * Called as first, tells the user has touched the screen
  16971. * @events touch
  16972. */
  16973. Hammer.gestures.Touch = {
  16974. name: 'touch',
  16975. index: -Infinity,
  16976. defaults: {
  16977. // call preventDefault at touchstart, and makes the element blocking by
  16978. // disabling the scrolling of the page, but it improves gestures like
  16979. // transforming and dragging.
  16980. // be careful with using this, it can be very annoying for users to be stuck
  16981. // on the page
  16982. prevent_default: false,
  16983. // disable mouse events, so only touch (or pen!) input triggers events
  16984. prevent_mouseevents: false
  16985. },
  16986. handler: function touchGesture(ev, inst) {
  16987. if(inst.options.prevent_mouseevents && ev.pointerType == Hammer.POINTER_MOUSE) {
  16988. ev.stopDetect();
  16989. return;
  16990. }
  16991. if(inst.options.prevent_default) {
  16992. ev.preventDefault();
  16993. }
  16994. if(ev.eventType == Hammer.EVENT_START) {
  16995. inst.trigger(this.name, ev);
  16996. }
  16997. }
  16998. };
  16999. /**
  17000. * Release
  17001. * Called as last, tells the user has released the screen
  17002. * @events release
  17003. */
  17004. Hammer.gestures.Release = {
  17005. name: 'release',
  17006. index: Infinity,
  17007. handler: function releaseGesture(ev, inst) {
  17008. if(ev.eventType == Hammer.EVENT_END) {
  17009. inst.trigger(this.name, ev);
  17010. }
  17011. }
  17012. };
  17013. // node export
  17014. if(typeof module === 'object' && typeof module.exports === 'object'){
  17015. module.exports = Hammer;
  17016. }
  17017. // just window export
  17018. else {
  17019. window.Hammer = Hammer;
  17020. // requireJS module definition
  17021. if(typeof window.define === 'function' && window.define.amd) {
  17022. window.define('hammer', [], function() {
  17023. return Hammer;
  17024. });
  17025. }
  17026. }
  17027. })(this);
  17028. },{}],4:[function(require,module,exports){
  17029. var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};//! moment.js
  17030. //! version : 2.6.0
  17031. //! authors : Tim Wood, Iskren Chernev, Moment.js contributors
  17032. //! license : MIT
  17033. //! momentjs.com
  17034. (function (undefined) {
  17035. /************************************
  17036. Constants
  17037. ************************************/
  17038. var moment,
  17039. VERSION = "2.6.0",
  17040. // the global-scope this is NOT the global object in Node.js
  17041. globalScope = typeof global !== 'undefined' ? global : this,
  17042. oldGlobalMoment,
  17043. round = Math.round,
  17044. i,
  17045. YEAR = 0,
  17046. MONTH = 1,
  17047. DATE = 2,
  17048. HOUR = 3,
  17049. MINUTE = 4,
  17050. SECOND = 5,
  17051. MILLISECOND = 6,
  17052. // internal storage for language config files
  17053. languages = {},
  17054. // moment internal properties
  17055. momentProperties = {
  17056. _isAMomentObject: null,
  17057. _i : null,
  17058. _f : null,
  17059. _l : null,
  17060. _strict : null,
  17061. _isUTC : null,
  17062. _offset : null, // optional. Combine with _isUTC
  17063. _pf : null,
  17064. _lang : null // optional
  17065. },
  17066. // check for nodeJS
  17067. hasModule = (typeof module !== 'undefined' && module.exports),
  17068. // ASP.NET json date format regex
  17069. aspNetJsonRegex = /^\/?Date\((\-?\d+)/i,
  17070. aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,
  17071. // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
  17072. // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
  17073. isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/,
  17074. // format tokens
  17075. 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,
  17076. localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g,
  17077. // parsing token regexes
  17078. parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99
  17079. parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999
  17080. parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999
  17081. parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999
  17082. parseTokenDigits = /\d+/, // nonzero number of digits
  17083. 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.
  17084. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z
  17085. parseTokenT = /T/i, // T (ISO separator)
  17086. parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
  17087. parseTokenOrdinal = /\d{1,2}/,
  17088. //strict parsing regexes
  17089. parseTokenOneDigit = /\d/, // 0 - 9
  17090. parseTokenTwoDigits = /\d\d/, // 00 - 99
  17091. parseTokenThreeDigits = /\d{3}/, // 000 - 999
  17092. parseTokenFourDigits = /\d{4}/, // 0000 - 9999
  17093. parseTokenSixDigits = /[+-]?\d{6}/, // -999,999 - 999,999
  17094. parseTokenSignedNumber = /[+-]?\d+/, // -inf - inf
  17095. // iso 8601 regex
  17096. // 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)
  17097. 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)?)?$/,
  17098. isoFormat = 'YYYY-MM-DDTHH:mm:ssZ',
  17099. isoDates = [
  17100. ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/],
  17101. ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/],
  17102. ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/],
  17103. ['GGGG-[W]WW', /\d{4}-W\d{2}/],
  17104. ['YYYY-DDD', /\d{4}-\d{3}/]
  17105. ],
  17106. // iso time formats and regexes
  17107. isoTimes = [
  17108. ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d+/],
  17109. ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/],
  17110. ['HH:mm', /(T| )\d\d:\d\d/],
  17111. ['HH', /(T| )\d\d/]
  17112. ],
  17113. // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"]
  17114. parseTimezoneChunker = /([\+\-]|\d\d)/gi,
  17115. // getter and setter names
  17116. proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'),
  17117. unitMillisecondFactors = {
  17118. 'Milliseconds' : 1,
  17119. 'Seconds' : 1e3,
  17120. 'Minutes' : 6e4,
  17121. 'Hours' : 36e5,
  17122. 'Days' : 864e5,
  17123. 'Months' : 2592e6,
  17124. 'Years' : 31536e6
  17125. },
  17126. unitAliases = {
  17127. ms : 'millisecond',
  17128. s : 'second',
  17129. m : 'minute',
  17130. h : 'hour',
  17131. d : 'day',
  17132. D : 'date',
  17133. w : 'week',
  17134. W : 'isoWeek',
  17135. M : 'month',
  17136. Q : 'quarter',
  17137. y : 'year',
  17138. DDD : 'dayOfYear',
  17139. e : 'weekday',
  17140. E : 'isoWeekday',
  17141. gg: 'weekYear',
  17142. GG: 'isoWeekYear'
  17143. },
  17144. camelFunctions = {
  17145. dayofyear : 'dayOfYear',
  17146. isoweekday : 'isoWeekday',
  17147. isoweek : 'isoWeek',
  17148. weekyear : 'weekYear',
  17149. isoweekyear : 'isoWeekYear'
  17150. },
  17151. // format function strings
  17152. formatFunctions = {},
  17153. // tokens to ordinalize and pad
  17154. ordinalizeTokens = 'DDD w W M D d'.split(' '),
  17155. paddedTokens = 'M D H h m s w W'.split(' '),
  17156. formatTokenFunctions = {
  17157. M : function () {
  17158. return this.month() + 1;
  17159. },
  17160. MMM : function (format) {
  17161. return this.lang().monthsShort(this, format);
  17162. },
  17163. MMMM : function (format) {
  17164. return this.lang().months(this, format);
  17165. },
  17166. D : function () {
  17167. return this.date();
  17168. },
  17169. DDD : function () {
  17170. return this.dayOfYear();
  17171. },
  17172. d : function () {
  17173. return this.day();
  17174. },
  17175. dd : function (format) {
  17176. return this.lang().weekdaysMin(this, format);
  17177. },
  17178. ddd : function (format) {
  17179. return this.lang().weekdaysShort(this, format);
  17180. },
  17181. dddd : function (format) {
  17182. return this.lang().weekdays(this, format);
  17183. },
  17184. w : function () {
  17185. return this.week();
  17186. },
  17187. W : function () {
  17188. return this.isoWeek();
  17189. },
  17190. YY : function () {
  17191. return leftZeroFill(this.year() % 100, 2);
  17192. },
  17193. YYYY : function () {
  17194. return leftZeroFill(this.year(), 4);
  17195. },
  17196. YYYYY : function () {
  17197. return leftZeroFill(this.year(), 5);
  17198. },
  17199. YYYYYY : function () {
  17200. var y = this.year(), sign = y >= 0 ? '+' : '-';
  17201. return sign + leftZeroFill(Math.abs(y), 6);
  17202. },
  17203. gg : function () {
  17204. return leftZeroFill(this.weekYear() % 100, 2);
  17205. },
  17206. gggg : function () {
  17207. return leftZeroFill(this.weekYear(), 4);
  17208. },
  17209. ggggg : function () {
  17210. return leftZeroFill(this.weekYear(), 5);
  17211. },
  17212. GG : function () {
  17213. return leftZeroFill(this.isoWeekYear() % 100, 2);
  17214. },
  17215. GGGG : function () {
  17216. return leftZeroFill(this.isoWeekYear(), 4);
  17217. },
  17218. GGGGG : function () {
  17219. return leftZeroFill(this.isoWeekYear(), 5);
  17220. },
  17221. e : function () {
  17222. return this.weekday();
  17223. },
  17224. E : function () {
  17225. return this.isoWeekday();
  17226. },
  17227. a : function () {
  17228. return this.lang().meridiem(this.hours(), this.minutes(), true);
  17229. },
  17230. A : function () {
  17231. return this.lang().meridiem(this.hours(), this.minutes(), false);
  17232. },
  17233. H : function () {
  17234. return this.hours();
  17235. },
  17236. h : function () {
  17237. return this.hours() % 12 || 12;
  17238. },
  17239. m : function () {
  17240. return this.minutes();
  17241. },
  17242. s : function () {
  17243. return this.seconds();
  17244. },
  17245. S : function () {
  17246. return toInt(this.milliseconds() / 100);
  17247. },
  17248. SS : function () {
  17249. return leftZeroFill(toInt(this.milliseconds() / 10), 2);
  17250. },
  17251. SSS : function () {
  17252. return leftZeroFill(this.milliseconds(), 3);
  17253. },
  17254. SSSS : function () {
  17255. return leftZeroFill(this.milliseconds(), 3);
  17256. },
  17257. Z : function () {
  17258. var a = -this.zone(),
  17259. b = "+";
  17260. if (a < 0) {
  17261. a = -a;
  17262. b = "-";
  17263. }
  17264. return b + leftZeroFill(toInt(a / 60), 2) + ":" + leftZeroFill(toInt(a) % 60, 2);
  17265. },
  17266. ZZ : function () {
  17267. var a = -this.zone(),
  17268. b = "+";
  17269. if (a < 0) {
  17270. a = -a;
  17271. b = "-";
  17272. }
  17273. return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2);
  17274. },
  17275. z : function () {
  17276. return this.zoneAbbr();
  17277. },
  17278. zz : function () {
  17279. return this.zoneName();
  17280. },
  17281. X : function () {
  17282. return this.unix();
  17283. },
  17284. Q : function () {
  17285. return this.quarter();
  17286. }
  17287. },
  17288. lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin'];
  17289. function defaultParsingFlags() {
  17290. // We need to deep clone this object, and es5 standard is not very
  17291. // helpful.
  17292. return {
  17293. empty : false,
  17294. unusedTokens : [],
  17295. unusedInput : [],
  17296. overflow : -2,
  17297. charsLeftOver : 0,
  17298. nullInput : false,
  17299. invalidMonth : null,
  17300. invalidFormat : false,
  17301. userInvalidated : false,
  17302. iso: false
  17303. };
  17304. }
  17305. function deprecate(msg, fn) {
  17306. var firstTime = true;
  17307. function printMsg() {
  17308. if (moment.suppressDeprecationWarnings === false &&
  17309. typeof console !== 'undefined' && console.warn) {
  17310. console.warn("Deprecation warning: " + msg);
  17311. }
  17312. }
  17313. return extend(function () {
  17314. if (firstTime) {
  17315. printMsg();
  17316. firstTime = false;
  17317. }
  17318. return fn.apply(this, arguments);
  17319. }, fn);
  17320. }
  17321. function padToken(func, count) {
  17322. return function (a) {
  17323. return leftZeroFill(func.call(this, a), count);
  17324. };
  17325. }
  17326. function ordinalizeToken(func, period) {
  17327. return function (a) {
  17328. return this.lang().ordinal(func.call(this, a), period);
  17329. };
  17330. }
  17331. while (ordinalizeTokens.length) {
  17332. i = ordinalizeTokens.pop();
  17333. formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i);
  17334. }
  17335. while (paddedTokens.length) {
  17336. i = paddedTokens.pop();
  17337. formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2);
  17338. }
  17339. formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3);
  17340. /************************************
  17341. Constructors
  17342. ************************************/
  17343. function Language() {
  17344. }
  17345. // Moment prototype object
  17346. function Moment(config) {
  17347. checkOverflow(config);
  17348. extend(this, config);
  17349. }
  17350. // Duration Constructor
  17351. function Duration(duration) {
  17352. var normalizedInput = normalizeObjectUnits(duration),
  17353. years = normalizedInput.year || 0,
  17354. quarters = normalizedInput.quarter || 0,
  17355. months = normalizedInput.month || 0,
  17356. weeks = normalizedInput.week || 0,
  17357. days = normalizedInput.day || 0,
  17358. hours = normalizedInput.hour || 0,
  17359. minutes = normalizedInput.minute || 0,
  17360. seconds = normalizedInput.second || 0,
  17361. milliseconds = normalizedInput.millisecond || 0;
  17362. // representation for dateAddRemove
  17363. this._milliseconds = +milliseconds +
  17364. seconds * 1e3 + // 1000
  17365. minutes * 6e4 + // 1000 * 60
  17366. hours * 36e5; // 1000 * 60 * 60
  17367. // Because of dateAddRemove treats 24 hours as different from a
  17368. // day when working around DST, we need to store them separately
  17369. this._days = +days +
  17370. weeks * 7;
  17371. // It is impossible translate months into days without knowing
  17372. // which months you are are talking about, so we have to store
  17373. // it separately.
  17374. this._months = +months +
  17375. quarters * 3 +
  17376. years * 12;
  17377. this._data = {};
  17378. this._bubble();
  17379. }
  17380. /************************************
  17381. Helpers
  17382. ************************************/
  17383. function extend(a, b) {
  17384. for (var i in b) {
  17385. if (b.hasOwnProperty(i)) {
  17386. a[i] = b[i];
  17387. }
  17388. }
  17389. if (b.hasOwnProperty("toString")) {
  17390. a.toString = b.toString;
  17391. }
  17392. if (b.hasOwnProperty("valueOf")) {
  17393. a.valueOf = b.valueOf;
  17394. }
  17395. return a;
  17396. }
  17397. function cloneMoment(m) {
  17398. var result = {}, i;
  17399. for (i in m) {
  17400. if (m.hasOwnProperty(i) && momentProperties.hasOwnProperty(i)) {
  17401. result[i] = m[i];
  17402. }
  17403. }
  17404. return result;
  17405. }
  17406. function absRound(number) {
  17407. if (number < 0) {
  17408. return Math.ceil(number);
  17409. } else {
  17410. return Math.floor(number);
  17411. }
  17412. }
  17413. // left zero fill a number
  17414. // see http://jsperf.com/left-zero-filling for performance comparison
  17415. function leftZeroFill(number, targetLength, forceSign) {
  17416. var output = '' + Math.abs(number),
  17417. sign = number >= 0;
  17418. while (output.length < targetLength) {
  17419. output = '0' + output;
  17420. }
  17421. return (sign ? (forceSign ? '+' : '') : '-') + output;
  17422. }
  17423. // helper function for _.addTime and _.subtractTime
  17424. function addOrSubtractDurationFromMoment(mom, duration, isAdding, updateOffset) {
  17425. var milliseconds = duration._milliseconds,
  17426. days = duration._days,
  17427. months = duration._months;
  17428. updateOffset = updateOffset == null ? true : updateOffset;
  17429. if (milliseconds) {
  17430. mom._d.setTime(+mom._d + milliseconds * isAdding);
  17431. }
  17432. if (days) {
  17433. rawSetter(mom, 'Date', rawGetter(mom, 'Date') + days * isAdding);
  17434. }
  17435. if (months) {
  17436. rawMonthSetter(mom, rawGetter(mom, 'Month') + months * isAdding);
  17437. }
  17438. if (updateOffset) {
  17439. moment.updateOffset(mom, days || months);
  17440. }
  17441. }
  17442. // check if is an array
  17443. function isArray(input) {
  17444. return Object.prototype.toString.call(input) === '[object Array]';
  17445. }
  17446. function isDate(input) {
  17447. return Object.prototype.toString.call(input) === '[object Date]' ||
  17448. input instanceof Date;
  17449. }
  17450. // compare two arrays, return the number of differences
  17451. function compareArrays(array1, array2, dontConvert) {
  17452. var len = Math.min(array1.length, array2.length),
  17453. lengthDiff = Math.abs(array1.length - array2.length),
  17454. diffs = 0,
  17455. i;
  17456. for (i = 0; i < len; i++) {
  17457. if ((dontConvert && array1[i] !== array2[i]) ||
  17458. (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
  17459. diffs++;
  17460. }
  17461. }
  17462. return diffs + lengthDiff;
  17463. }
  17464. function normalizeUnits(units) {
  17465. if (units) {
  17466. var lowered = units.toLowerCase().replace(/(.)s$/, '$1');
  17467. units = unitAliases[units] || camelFunctions[lowered] || lowered;
  17468. }
  17469. return units;
  17470. }
  17471. function normalizeObjectUnits(inputObject) {
  17472. var normalizedInput = {},
  17473. normalizedProp,
  17474. prop;
  17475. for (prop in inputObject) {
  17476. if (inputObject.hasOwnProperty(prop)) {
  17477. normalizedProp = normalizeUnits(prop);
  17478. if (normalizedProp) {
  17479. normalizedInput[normalizedProp] = inputObject[prop];
  17480. }
  17481. }
  17482. }
  17483. return normalizedInput;
  17484. }
  17485. function makeList(field) {
  17486. var count, setter;
  17487. if (field.indexOf('week') === 0) {
  17488. count = 7;
  17489. setter = 'day';
  17490. }
  17491. else if (field.indexOf('month') === 0) {
  17492. count = 12;
  17493. setter = 'month';
  17494. }
  17495. else {
  17496. return;
  17497. }
  17498. moment[field] = function (format, index) {
  17499. var i, getter,
  17500. method = moment.fn._lang[field],
  17501. results = [];
  17502. if (typeof format === 'number') {
  17503. index = format;
  17504. format = undefined;
  17505. }
  17506. getter = function (i) {
  17507. var m = moment().utc().set(setter, i);
  17508. return method.call(moment.fn._lang, m, format || '');
  17509. };
  17510. if (index != null) {
  17511. return getter(index);
  17512. }
  17513. else {
  17514. for (i = 0; i < count; i++) {
  17515. results.push(getter(i));
  17516. }
  17517. return results;
  17518. }
  17519. };
  17520. }
  17521. function toInt(argumentForCoercion) {
  17522. var coercedNumber = +argumentForCoercion,
  17523. value = 0;
  17524. if (coercedNumber !== 0 && isFinite(coercedNumber)) {
  17525. if (coercedNumber >= 0) {
  17526. value = Math.floor(coercedNumber);
  17527. } else {
  17528. value = Math.ceil(coercedNumber);
  17529. }
  17530. }
  17531. return value;
  17532. }
  17533. function daysInMonth(year, month) {
  17534. return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
  17535. }
  17536. function weeksInYear(year, dow, doy) {
  17537. return weekOfYear(moment([year, 11, 31 + dow - doy]), dow, doy).week;
  17538. }
  17539. function daysInYear(year) {
  17540. return isLeapYear(year) ? 366 : 365;
  17541. }
  17542. function isLeapYear(year) {
  17543. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  17544. }
  17545. function checkOverflow(m) {
  17546. var overflow;
  17547. if (m._a && m._pf.overflow === -2) {
  17548. overflow =
  17549. m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH :
  17550. m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE :
  17551. m._a[HOUR] < 0 || m._a[HOUR] > 23 ? HOUR :
  17552. m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE :
  17553. m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND :
  17554. m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND :
  17555. -1;
  17556. if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
  17557. overflow = DATE;
  17558. }
  17559. m._pf.overflow = overflow;
  17560. }
  17561. }
  17562. function isValid(m) {
  17563. if (m._isValid == null) {
  17564. m._isValid = !isNaN(m._d.getTime()) &&
  17565. m._pf.overflow < 0 &&
  17566. !m._pf.empty &&
  17567. !m._pf.invalidMonth &&
  17568. !m._pf.nullInput &&
  17569. !m._pf.invalidFormat &&
  17570. !m._pf.userInvalidated;
  17571. if (m._strict) {
  17572. m._isValid = m._isValid &&
  17573. m._pf.charsLeftOver === 0 &&
  17574. m._pf.unusedTokens.length === 0;
  17575. }
  17576. }
  17577. return m._isValid;
  17578. }
  17579. function normalizeLanguage(key) {
  17580. return key ? key.toLowerCase().replace('_', '-') : key;
  17581. }
  17582. // Return a moment from input, that is local/utc/zone equivalent to model.
  17583. function makeAs(input, model) {
  17584. return model._isUTC ? moment(input).zone(model._offset || 0) :
  17585. moment(input).local();
  17586. }
  17587. /************************************
  17588. Languages
  17589. ************************************/
  17590. extend(Language.prototype, {
  17591. set : function (config) {
  17592. var prop, i;
  17593. for (i in config) {
  17594. prop = config[i];
  17595. if (typeof prop === 'function') {
  17596. this[i] = prop;
  17597. } else {
  17598. this['_' + i] = prop;
  17599. }
  17600. }
  17601. },
  17602. _months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
  17603. months : function (m) {
  17604. return this._months[m.month()];
  17605. },
  17606. _monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),
  17607. monthsShort : function (m) {
  17608. return this._monthsShort[m.month()];
  17609. },
  17610. monthsParse : function (monthName) {
  17611. var i, mom, regex;
  17612. if (!this._monthsParse) {
  17613. this._monthsParse = [];
  17614. }
  17615. for (i = 0; i < 12; i++) {
  17616. // make the regex if we don't have it already
  17617. if (!this._monthsParse[i]) {
  17618. mom = moment.utc([2000, i]);
  17619. regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  17620. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  17621. }
  17622. // test the regex
  17623. if (this._monthsParse[i].test(monthName)) {
  17624. return i;
  17625. }
  17626. }
  17627. },
  17628. _weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
  17629. weekdays : function (m) {
  17630. return this._weekdays[m.day()];
  17631. },
  17632. _weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),
  17633. weekdaysShort : function (m) {
  17634. return this._weekdaysShort[m.day()];
  17635. },
  17636. _weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"),
  17637. weekdaysMin : function (m) {
  17638. return this._weekdaysMin[m.day()];
  17639. },
  17640. weekdaysParse : function (weekdayName) {
  17641. var i, mom, regex;
  17642. if (!this._weekdaysParse) {
  17643. this._weekdaysParse = [];
  17644. }
  17645. for (i = 0; i < 7; i++) {
  17646. // make the regex if we don't have it already
  17647. if (!this._weekdaysParse[i]) {
  17648. mom = moment([2000, 1]).day(i);
  17649. regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
  17650. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  17651. }
  17652. // test the regex
  17653. if (this._weekdaysParse[i].test(weekdayName)) {
  17654. return i;
  17655. }
  17656. }
  17657. },
  17658. _longDateFormat : {
  17659. LT : "h:mm A",
  17660. L : "MM/DD/YYYY",
  17661. LL : "MMMM D YYYY",
  17662. LLL : "MMMM D YYYY LT",
  17663. LLLL : "dddd, MMMM D YYYY LT"
  17664. },
  17665. longDateFormat : function (key) {
  17666. var output = this._longDateFormat[key];
  17667. if (!output && this._longDateFormat[key.toUpperCase()]) {
  17668. output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) {
  17669. return val.slice(1);
  17670. });
  17671. this._longDateFormat[key] = output;
  17672. }
  17673. return output;
  17674. },
  17675. isPM : function (input) {
  17676. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  17677. // Using charAt should be more compatible.
  17678. return ((input + '').toLowerCase().charAt(0) === 'p');
  17679. },
  17680. _meridiemParse : /[ap]\.?m?\.?/i,
  17681. meridiem : function (hours, minutes, isLower) {
  17682. if (hours > 11) {
  17683. return isLower ? 'pm' : 'PM';
  17684. } else {
  17685. return isLower ? 'am' : 'AM';
  17686. }
  17687. },
  17688. _calendar : {
  17689. sameDay : '[Today at] LT',
  17690. nextDay : '[Tomorrow at] LT',
  17691. nextWeek : 'dddd [at] LT',
  17692. lastDay : '[Yesterday at] LT',
  17693. lastWeek : '[Last] dddd [at] LT',
  17694. sameElse : 'L'
  17695. },
  17696. calendar : function (key, mom) {
  17697. var output = this._calendar[key];
  17698. return typeof output === 'function' ? output.apply(mom) : output;
  17699. },
  17700. _relativeTime : {
  17701. future : "in %s",
  17702. past : "%s ago",
  17703. s : "a few seconds",
  17704. m : "a minute",
  17705. mm : "%d minutes",
  17706. h : "an hour",
  17707. hh : "%d hours",
  17708. d : "a day",
  17709. dd : "%d days",
  17710. M : "a month",
  17711. MM : "%d months",
  17712. y : "a year",
  17713. yy : "%d years"
  17714. },
  17715. relativeTime : function (number, withoutSuffix, string, isFuture) {
  17716. var output = this._relativeTime[string];
  17717. return (typeof output === 'function') ?
  17718. output(number, withoutSuffix, string, isFuture) :
  17719. output.replace(/%d/i, number);
  17720. },
  17721. pastFuture : function (diff, output) {
  17722. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  17723. return typeof format === 'function' ? format(output) : format.replace(/%s/i, output);
  17724. },
  17725. ordinal : function (number) {
  17726. return this._ordinal.replace("%d", number);
  17727. },
  17728. _ordinal : "%d",
  17729. preparse : function (string) {
  17730. return string;
  17731. },
  17732. postformat : function (string) {
  17733. return string;
  17734. },
  17735. week : function (mom) {
  17736. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  17737. },
  17738. _week : {
  17739. dow : 0, // Sunday is the first day of the week.
  17740. doy : 6 // The week that contains Jan 1st is the first week of the year.
  17741. },
  17742. _invalidDate: 'Invalid date',
  17743. invalidDate: function () {
  17744. return this._invalidDate;
  17745. }
  17746. });
  17747. // Loads a language definition into the `languages` cache. The function
  17748. // takes a key and optionally values. If not in the browser and no values
  17749. // are provided, it will load the language file module. As a convenience,
  17750. // this function also returns the language values.
  17751. function loadLang(key, values) {
  17752. values.abbr = key;
  17753. if (!languages[key]) {
  17754. languages[key] = new Language();
  17755. }
  17756. languages[key].set(values);
  17757. return languages[key];
  17758. }
  17759. // Remove a language from the `languages` cache. Mostly useful in tests.
  17760. function unloadLang(key) {
  17761. delete languages[key];
  17762. }
  17763. // Determines which language definition to use and returns it.
  17764. //
  17765. // With no parameters, it will return the global language. If you
  17766. // pass in a language key, such as 'en', it will return the
  17767. // definition for 'en', so long as 'en' has already been loaded using
  17768. // moment.lang.
  17769. function getLangDefinition(key) {
  17770. var i = 0, j, lang, next, split,
  17771. get = function (k) {
  17772. if (!languages[k] && hasModule) {
  17773. try {
  17774. require('./lang/' + k);
  17775. } catch (e) { }
  17776. }
  17777. return languages[k];
  17778. };
  17779. if (!key) {
  17780. return moment.fn._lang;
  17781. }
  17782. if (!isArray(key)) {
  17783. //short-circuit everything else
  17784. lang = get(key);
  17785. if (lang) {
  17786. return lang;
  17787. }
  17788. key = [key];
  17789. }
  17790. //pick the language from the array
  17791. //try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
  17792. //substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
  17793. while (i < key.length) {
  17794. split = normalizeLanguage(key[i]).split('-');
  17795. j = split.length;
  17796. next = normalizeLanguage(key[i + 1]);
  17797. next = next ? next.split('-') : null;
  17798. while (j > 0) {
  17799. lang = get(split.slice(0, j).join('-'));
  17800. if (lang) {
  17801. return lang;
  17802. }
  17803. if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
  17804. //the next array item is better than a shallower substring of this one
  17805. break;
  17806. }
  17807. j--;
  17808. }
  17809. i++;
  17810. }
  17811. return moment.fn._lang;
  17812. }
  17813. /************************************
  17814. Formatting
  17815. ************************************/
  17816. function removeFormattingTokens(input) {
  17817. if (input.match(/\[[\s\S]/)) {
  17818. return input.replace(/^\[|\]$/g, "");
  17819. }
  17820. return input.replace(/\\/g, "");
  17821. }
  17822. function makeFormatFunction(format) {
  17823. var array = format.match(formattingTokens), i, length;
  17824. for (i = 0, length = array.length; i < length; i++) {
  17825. if (formatTokenFunctions[array[i]]) {
  17826. array[i] = formatTokenFunctions[array[i]];
  17827. } else {
  17828. array[i] = removeFormattingTokens(array[i]);
  17829. }
  17830. }
  17831. return function (mom) {
  17832. var output = "";
  17833. for (i = 0; i < length; i++) {
  17834. output += array[i] instanceof Function ? array[i].call(mom, format) : array[i];
  17835. }
  17836. return output;
  17837. };
  17838. }
  17839. // format date using native date object
  17840. function formatMoment(m, format) {
  17841. if (!m.isValid()) {
  17842. return m.lang().invalidDate();
  17843. }
  17844. format = expandFormat(format, m.lang());
  17845. if (!formatFunctions[format]) {
  17846. formatFunctions[format] = makeFormatFunction(format);
  17847. }
  17848. return formatFunctions[format](m);
  17849. }
  17850. function expandFormat(format, lang) {
  17851. var i = 5;
  17852. function replaceLongDateFormatTokens(input) {
  17853. return lang.longDateFormat(input) || input;
  17854. }
  17855. localFormattingTokens.lastIndex = 0;
  17856. while (i >= 0 && localFormattingTokens.test(format)) {
  17857. format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
  17858. localFormattingTokens.lastIndex = 0;
  17859. i -= 1;
  17860. }
  17861. return format;
  17862. }
  17863. /************************************
  17864. Parsing
  17865. ************************************/
  17866. // get the regex to find the next token
  17867. function getParseRegexForToken(token, config) {
  17868. var a, strict = config._strict;
  17869. switch (token) {
  17870. case 'Q':
  17871. return parseTokenOneDigit;
  17872. case 'DDDD':
  17873. return parseTokenThreeDigits;
  17874. case 'YYYY':
  17875. case 'GGGG':
  17876. case 'gggg':
  17877. return strict ? parseTokenFourDigits : parseTokenOneToFourDigits;
  17878. case 'Y':
  17879. case 'G':
  17880. case 'g':
  17881. return parseTokenSignedNumber;
  17882. case 'YYYYYY':
  17883. case 'YYYYY':
  17884. case 'GGGGG':
  17885. case 'ggggg':
  17886. return strict ? parseTokenSixDigits : parseTokenOneToSixDigits;
  17887. case 'S':
  17888. if (strict) { return parseTokenOneDigit; }
  17889. /* falls through */
  17890. case 'SS':
  17891. if (strict) { return parseTokenTwoDigits; }
  17892. /* falls through */
  17893. case 'SSS':
  17894. if (strict) { return parseTokenThreeDigits; }
  17895. /* falls through */
  17896. case 'DDD':
  17897. return parseTokenOneToThreeDigits;
  17898. case 'MMM':
  17899. case 'MMMM':
  17900. case 'dd':
  17901. case 'ddd':
  17902. case 'dddd':
  17903. return parseTokenWord;
  17904. case 'a':
  17905. case 'A':
  17906. return getLangDefinition(config._l)._meridiemParse;
  17907. case 'X':
  17908. return parseTokenTimestampMs;
  17909. case 'Z':
  17910. case 'ZZ':
  17911. return parseTokenTimezone;
  17912. case 'T':
  17913. return parseTokenT;
  17914. case 'SSSS':
  17915. return parseTokenDigits;
  17916. case 'MM':
  17917. case 'DD':
  17918. case 'YY':
  17919. case 'GG':
  17920. case 'gg':
  17921. case 'HH':
  17922. case 'hh':
  17923. case 'mm':
  17924. case 'ss':
  17925. case 'ww':
  17926. case 'WW':
  17927. return strict ? parseTokenTwoDigits : parseTokenOneOrTwoDigits;
  17928. case 'M':
  17929. case 'D':
  17930. case 'd':
  17931. case 'H':
  17932. case 'h':
  17933. case 'm':
  17934. case 's':
  17935. case 'w':
  17936. case 'W':
  17937. case 'e':
  17938. case 'E':
  17939. return parseTokenOneOrTwoDigits;
  17940. case 'Do':
  17941. return parseTokenOrdinal;
  17942. default :
  17943. a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), "i"));
  17944. return a;
  17945. }
  17946. }
  17947. function timezoneMinutesFromString(string) {
  17948. string = string || "";
  17949. var possibleTzMatches = (string.match(parseTokenTimezone) || []),
  17950. tzChunk = possibleTzMatches[possibleTzMatches.length - 1] || [],
  17951. parts = (tzChunk + '').match(parseTimezoneChunker) || ['-', 0, 0],
  17952. minutes = +(parts[1] * 60) + toInt(parts[2]);
  17953. return parts[0] === '+' ? -minutes : minutes;
  17954. }
  17955. // function to convert string input to date
  17956. function addTimeToArrayFromToken(token, input, config) {
  17957. var a, datePartArray = config._a;
  17958. switch (token) {
  17959. // QUARTER
  17960. case 'Q':
  17961. if (input != null) {
  17962. datePartArray[MONTH] = (toInt(input) - 1) * 3;
  17963. }
  17964. break;
  17965. // MONTH
  17966. case 'M' : // fall through to MM
  17967. case 'MM' :
  17968. if (input != null) {
  17969. datePartArray[MONTH] = toInt(input) - 1;
  17970. }
  17971. break;
  17972. case 'MMM' : // fall through to MMMM
  17973. case 'MMMM' :
  17974. a = getLangDefinition(config._l).monthsParse(input);
  17975. // if we didn't find a month name, mark the date as invalid.
  17976. if (a != null) {
  17977. datePartArray[MONTH] = a;
  17978. } else {
  17979. config._pf.invalidMonth = input;
  17980. }
  17981. break;
  17982. // DAY OF MONTH
  17983. case 'D' : // fall through to DD
  17984. case 'DD' :
  17985. if (input != null) {
  17986. datePartArray[DATE] = toInt(input);
  17987. }
  17988. break;
  17989. case 'Do' :
  17990. if (input != null) {
  17991. datePartArray[DATE] = toInt(parseInt(input, 10));
  17992. }
  17993. break;
  17994. // DAY OF YEAR
  17995. case 'DDD' : // fall through to DDDD
  17996. case 'DDDD' :
  17997. if (input != null) {
  17998. config._dayOfYear = toInt(input);
  17999. }
  18000. break;
  18001. // YEAR
  18002. case 'YY' :
  18003. datePartArray[YEAR] = moment.parseTwoDigitYear(input);
  18004. break;
  18005. case 'YYYY' :
  18006. case 'YYYYY' :
  18007. case 'YYYYYY' :
  18008. datePartArray[YEAR] = toInt(input);
  18009. break;
  18010. // AM / PM
  18011. case 'a' : // fall through to A
  18012. case 'A' :
  18013. config._isPm = getLangDefinition(config._l).isPM(input);
  18014. break;
  18015. // 24 HOUR
  18016. case 'H' : // fall through to hh
  18017. case 'HH' : // fall through to hh
  18018. case 'h' : // fall through to hh
  18019. case 'hh' :
  18020. datePartArray[HOUR] = toInt(input);
  18021. break;
  18022. // MINUTE
  18023. case 'm' : // fall through to mm
  18024. case 'mm' :
  18025. datePartArray[MINUTE] = toInt(input);
  18026. break;
  18027. // SECOND
  18028. case 's' : // fall through to ss
  18029. case 'ss' :
  18030. datePartArray[SECOND] = toInt(input);
  18031. break;
  18032. // MILLISECOND
  18033. case 'S' :
  18034. case 'SS' :
  18035. case 'SSS' :
  18036. case 'SSSS' :
  18037. datePartArray[MILLISECOND] = toInt(('0.' + input) * 1000);
  18038. break;
  18039. // UNIX TIMESTAMP WITH MS
  18040. case 'X':
  18041. config._d = new Date(parseFloat(input) * 1000);
  18042. break;
  18043. // TIMEZONE
  18044. case 'Z' : // fall through to ZZ
  18045. case 'ZZ' :
  18046. config._useUTC = true;
  18047. config._tzm = timezoneMinutesFromString(input);
  18048. break;
  18049. case 'w':
  18050. case 'ww':
  18051. case 'W':
  18052. case 'WW':
  18053. case 'd':
  18054. case 'dd':
  18055. case 'ddd':
  18056. case 'dddd':
  18057. case 'e':
  18058. case 'E':
  18059. token = token.substr(0, 1);
  18060. /* falls through */
  18061. case 'gg':
  18062. case 'gggg':
  18063. case 'GG':
  18064. case 'GGGG':
  18065. case 'GGGGG':
  18066. token = token.substr(0, 2);
  18067. if (input) {
  18068. config._w = config._w || {};
  18069. config._w[token] = input;
  18070. }
  18071. break;
  18072. }
  18073. }
  18074. // convert an array to a date.
  18075. // the array should mirror the parameters below
  18076. // note: all values past the year are optional and will default to the lowest possible value.
  18077. // [year, month, day , hour, minute, second, millisecond]
  18078. function dateFromConfig(config) {
  18079. var i, date, input = [], currentDate,
  18080. yearToUse, fixYear, w, temp, lang, weekday, week;
  18081. if (config._d) {
  18082. return;
  18083. }
  18084. currentDate = currentDateArray(config);
  18085. //compute day of the year from weeks and weekdays
  18086. if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
  18087. fixYear = function (val) {
  18088. var intVal = parseInt(val, 10);
  18089. return val ?
  18090. (val.length < 3 ? (intVal > 68 ? 1900 + intVal : 2000 + intVal) : intVal) :
  18091. (config._a[YEAR] == null ? moment().weekYear() : config._a[YEAR]);
  18092. };
  18093. w = config._w;
  18094. if (w.GG != null || w.W != null || w.E != null) {
  18095. temp = dayOfYearFromWeeks(fixYear(w.GG), w.W || 1, w.E, 4, 1);
  18096. }
  18097. else {
  18098. lang = getLangDefinition(config._l);
  18099. weekday = w.d != null ? parseWeekday(w.d, lang) :
  18100. (w.e != null ? parseInt(w.e, 10) + lang._week.dow : 0);
  18101. week = parseInt(w.w, 10) || 1;
  18102. //if we're parsing 'd', then the low day numbers may be next week
  18103. if (w.d != null && weekday < lang._week.dow) {
  18104. week++;
  18105. }
  18106. temp = dayOfYearFromWeeks(fixYear(w.gg), week, weekday, lang._week.doy, lang._week.dow);
  18107. }
  18108. config._a[YEAR] = temp.year;
  18109. config._dayOfYear = temp.dayOfYear;
  18110. }
  18111. //if the day of the year is set, figure out what it is
  18112. if (config._dayOfYear) {
  18113. yearToUse = config._a[YEAR] == null ? currentDate[YEAR] : config._a[YEAR];
  18114. if (config._dayOfYear > daysInYear(yearToUse)) {
  18115. config._pf._overflowDayOfYear = true;
  18116. }
  18117. date = makeUTCDate(yearToUse, 0, config._dayOfYear);
  18118. config._a[MONTH] = date.getUTCMonth();
  18119. config._a[DATE] = date.getUTCDate();
  18120. }
  18121. // Default to current date.
  18122. // * if no year, month, day of month are given, default to today
  18123. // * if day of month is given, default month and year
  18124. // * if month is given, default only year
  18125. // * if year is given, don't default anything
  18126. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  18127. config._a[i] = input[i] = currentDate[i];
  18128. }
  18129. // Zero out whatever was not defaulted, including time
  18130. for (; i < 7; i++) {
  18131. config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
  18132. }
  18133. // add the offsets to the time to be parsed so that we can have a clean array for checking isValid
  18134. input[HOUR] += toInt((config._tzm || 0) / 60);
  18135. input[MINUTE] += toInt((config._tzm || 0) % 60);
  18136. config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input);
  18137. }
  18138. function dateFromObject(config) {
  18139. var normalizedInput;
  18140. if (config._d) {
  18141. return;
  18142. }
  18143. normalizedInput = normalizeObjectUnits(config._i);
  18144. config._a = [
  18145. normalizedInput.year,
  18146. normalizedInput.month,
  18147. normalizedInput.day,
  18148. normalizedInput.hour,
  18149. normalizedInput.minute,
  18150. normalizedInput.second,
  18151. normalizedInput.millisecond
  18152. ];
  18153. dateFromConfig(config);
  18154. }
  18155. function currentDateArray(config) {
  18156. var now = new Date();
  18157. if (config._useUTC) {
  18158. return [
  18159. now.getUTCFullYear(),
  18160. now.getUTCMonth(),
  18161. now.getUTCDate()
  18162. ];
  18163. } else {
  18164. return [now.getFullYear(), now.getMonth(), now.getDate()];
  18165. }
  18166. }
  18167. // date from string and format string
  18168. function makeDateFromStringAndFormat(config) {
  18169. config._a = [];
  18170. config._pf.empty = true;
  18171. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  18172. var lang = getLangDefinition(config._l),
  18173. string = '' + config._i,
  18174. i, parsedInput, tokens, token, skipped,
  18175. stringLength = string.length,
  18176. totalParsedInputLength = 0;
  18177. tokens = expandFormat(config._f, lang).match(formattingTokens) || [];
  18178. for (i = 0; i < tokens.length; i++) {
  18179. token = tokens[i];
  18180. parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
  18181. if (parsedInput) {
  18182. skipped = string.substr(0, string.indexOf(parsedInput));
  18183. if (skipped.length > 0) {
  18184. config._pf.unusedInput.push(skipped);
  18185. }
  18186. string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
  18187. totalParsedInputLength += parsedInput.length;
  18188. }
  18189. // don't parse if it's not a known token
  18190. if (formatTokenFunctions[token]) {
  18191. if (parsedInput) {
  18192. config._pf.empty = false;
  18193. }
  18194. else {
  18195. config._pf.unusedTokens.push(token);
  18196. }
  18197. addTimeToArrayFromToken(token, parsedInput, config);
  18198. }
  18199. else if (config._strict && !parsedInput) {
  18200. config._pf.unusedTokens.push(token);
  18201. }
  18202. }
  18203. // add remaining unparsed input length to the string
  18204. config._pf.charsLeftOver = stringLength - totalParsedInputLength;
  18205. if (string.length > 0) {
  18206. config._pf.unusedInput.push(string);
  18207. }
  18208. // handle am pm
  18209. if (config._isPm && config._a[HOUR] < 12) {
  18210. config._a[HOUR] += 12;
  18211. }
  18212. // if is 12 am, change hours to 0
  18213. if (config._isPm === false && config._a[HOUR] === 12) {
  18214. config._a[HOUR] = 0;
  18215. }
  18216. dateFromConfig(config);
  18217. checkOverflow(config);
  18218. }
  18219. function unescapeFormat(s) {
  18220. return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
  18221. return p1 || p2 || p3 || p4;
  18222. });
  18223. }
  18224. // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  18225. function regexpEscape(s) {
  18226. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  18227. }
  18228. // date from string and array of format strings
  18229. function makeDateFromStringAndArray(config) {
  18230. var tempConfig,
  18231. bestMoment,
  18232. scoreToBeat,
  18233. i,
  18234. currentScore;
  18235. if (config._f.length === 0) {
  18236. config._pf.invalidFormat = true;
  18237. config._d = new Date(NaN);
  18238. return;
  18239. }
  18240. for (i = 0; i < config._f.length; i++) {
  18241. currentScore = 0;
  18242. tempConfig = extend({}, config);
  18243. tempConfig._pf = defaultParsingFlags();
  18244. tempConfig._f = config._f[i];
  18245. makeDateFromStringAndFormat(tempConfig);
  18246. if (!isValid(tempConfig)) {
  18247. continue;
  18248. }
  18249. // if there is any input that was not parsed add a penalty for that format
  18250. currentScore += tempConfig._pf.charsLeftOver;
  18251. //or tokens
  18252. currentScore += tempConfig._pf.unusedTokens.length * 10;
  18253. tempConfig._pf.score = currentScore;
  18254. if (scoreToBeat == null || currentScore < scoreToBeat) {
  18255. scoreToBeat = currentScore;
  18256. bestMoment = tempConfig;
  18257. }
  18258. }
  18259. extend(config, bestMoment || tempConfig);
  18260. }
  18261. // date from iso format
  18262. function makeDateFromString(config) {
  18263. var i, l,
  18264. string = config._i,
  18265. match = isoRegex.exec(string);
  18266. if (match) {
  18267. config._pf.iso = true;
  18268. for (i = 0, l = isoDates.length; i < l; i++) {
  18269. if (isoDates[i][1].exec(string)) {
  18270. // match[5] should be "T" or undefined
  18271. config._f = isoDates[i][0] + (match[6] || " ");
  18272. break;
  18273. }
  18274. }
  18275. for (i = 0, l = isoTimes.length; i < l; i++) {
  18276. if (isoTimes[i][1].exec(string)) {
  18277. config._f += isoTimes[i][0];
  18278. break;
  18279. }
  18280. }
  18281. if (string.match(parseTokenTimezone)) {
  18282. config._f += "Z";
  18283. }
  18284. makeDateFromStringAndFormat(config);
  18285. }
  18286. else {
  18287. moment.createFromInputFallback(config);
  18288. }
  18289. }
  18290. function makeDateFromInput(config) {
  18291. var input = config._i,
  18292. matched = aspNetJsonRegex.exec(input);
  18293. if (input === undefined) {
  18294. config._d = new Date();
  18295. } else if (matched) {
  18296. config._d = new Date(+matched[1]);
  18297. } else if (typeof input === 'string') {
  18298. makeDateFromString(config);
  18299. } else if (isArray(input)) {
  18300. config._a = input.slice(0);
  18301. dateFromConfig(config);
  18302. } else if (isDate(input)) {
  18303. config._d = new Date(+input);
  18304. } else if (typeof(input) === 'object') {
  18305. dateFromObject(config);
  18306. } else if (typeof(input) === 'number') {
  18307. // from milliseconds
  18308. config._d = new Date(input);
  18309. } else {
  18310. moment.createFromInputFallback(config);
  18311. }
  18312. }
  18313. function makeDate(y, m, d, h, M, s, ms) {
  18314. //can't just apply() to create a date:
  18315. //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply
  18316. var date = new Date(y, m, d, h, M, s, ms);
  18317. //the date constructor doesn't accept years < 1970
  18318. if (y < 1970) {
  18319. date.setFullYear(y);
  18320. }
  18321. return date;
  18322. }
  18323. function makeUTCDate(y) {
  18324. var date = new Date(Date.UTC.apply(null, arguments));
  18325. if (y < 1970) {
  18326. date.setUTCFullYear(y);
  18327. }
  18328. return date;
  18329. }
  18330. function parseWeekday(input, language) {
  18331. if (typeof input === 'string') {
  18332. if (!isNaN(input)) {
  18333. input = parseInt(input, 10);
  18334. }
  18335. else {
  18336. input = language.weekdaysParse(input);
  18337. if (typeof input !== 'number') {
  18338. return null;
  18339. }
  18340. }
  18341. }
  18342. return input;
  18343. }
  18344. /************************************
  18345. Relative Time
  18346. ************************************/
  18347. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  18348. function substituteTimeAgo(string, number, withoutSuffix, isFuture, lang) {
  18349. return lang.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  18350. }
  18351. function relativeTime(milliseconds, withoutSuffix, lang) {
  18352. var seconds = round(Math.abs(milliseconds) / 1000),
  18353. minutes = round(seconds / 60),
  18354. hours = round(minutes / 60),
  18355. days = round(hours / 24),
  18356. years = round(days / 365),
  18357. args = seconds < 45 && ['s', seconds] ||
  18358. minutes === 1 && ['m'] ||
  18359. minutes < 45 && ['mm', minutes] ||
  18360. hours === 1 && ['h'] ||
  18361. hours < 22 && ['hh', hours] ||
  18362. days === 1 && ['d'] ||
  18363. days <= 25 && ['dd', days] ||
  18364. days <= 45 && ['M'] ||
  18365. days < 345 && ['MM', round(days / 30)] ||
  18366. years === 1 && ['y'] || ['yy', years];
  18367. args[2] = withoutSuffix;
  18368. args[3] = milliseconds > 0;
  18369. args[4] = lang;
  18370. return substituteTimeAgo.apply({}, args);
  18371. }
  18372. /************************************
  18373. Week of Year
  18374. ************************************/
  18375. // firstDayOfWeek 0 = sun, 6 = sat
  18376. // the day of the week that starts the week
  18377. // (usually sunday or monday)
  18378. // firstDayOfWeekOfYear 0 = sun, 6 = sat
  18379. // the first week is the week that contains the first
  18380. // of this day of the week
  18381. // (eg. ISO weeks use thursday (4))
  18382. function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) {
  18383. var end = firstDayOfWeekOfYear - firstDayOfWeek,
  18384. daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(),
  18385. adjustedMoment;
  18386. if (daysToDayOfWeek > end) {
  18387. daysToDayOfWeek -= 7;
  18388. }
  18389. if (daysToDayOfWeek < end - 7) {
  18390. daysToDayOfWeek += 7;
  18391. }
  18392. adjustedMoment = moment(mom).add('d', daysToDayOfWeek);
  18393. return {
  18394. week: Math.ceil(adjustedMoment.dayOfYear() / 7),
  18395. year: adjustedMoment.year()
  18396. };
  18397. }
  18398. //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
  18399. function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) {
  18400. var d = makeUTCDate(year, 0, 1).getUTCDay(), daysToAdd, dayOfYear;
  18401. weekday = weekday != null ? weekday : firstDayOfWeek;
  18402. daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0);
  18403. dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1;
  18404. return {
  18405. year: dayOfYear > 0 ? year : year - 1,
  18406. dayOfYear: dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear
  18407. };
  18408. }
  18409. /************************************
  18410. Top Level Functions
  18411. ************************************/
  18412. function makeMoment(config) {
  18413. var input = config._i,
  18414. format = config._f;
  18415. if (input === null || (format === undefined && input === '')) {
  18416. return moment.invalid({nullInput: true});
  18417. }
  18418. if (typeof input === 'string') {
  18419. config._i = input = getLangDefinition().preparse(input);
  18420. }
  18421. if (moment.isMoment(input)) {
  18422. config = cloneMoment(input);
  18423. config._d = new Date(+input._d);
  18424. } else if (format) {
  18425. if (isArray(format)) {
  18426. makeDateFromStringAndArray(config);
  18427. } else {
  18428. makeDateFromStringAndFormat(config);
  18429. }
  18430. } else {
  18431. makeDateFromInput(config);
  18432. }
  18433. return new Moment(config);
  18434. }
  18435. moment = function (input, format, lang, strict) {
  18436. var c;
  18437. if (typeof(lang) === "boolean") {
  18438. strict = lang;
  18439. lang = undefined;
  18440. }
  18441. // object construction must be done this way.
  18442. // https://github.com/moment/moment/issues/1423
  18443. c = {};
  18444. c._isAMomentObject = true;
  18445. c._i = input;
  18446. c._f = format;
  18447. c._l = lang;
  18448. c._strict = strict;
  18449. c._isUTC = false;
  18450. c._pf = defaultParsingFlags();
  18451. return makeMoment(c);
  18452. };
  18453. moment.suppressDeprecationWarnings = false;
  18454. moment.createFromInputFallback = deprecate(
  18455. "moment construction falls back to js Date. This is " +
  18456. "discouraged and will be removed in upcoming major " +
  18457. "release. Please refer to " +
  18458. "https://github.com/moment/moment/issues/1407 for more info.",
  18459. function (config) {
  18460. config._d = new Date(config._i);
  18461. });
  18462. // creating with utc
  18463. moment.utc = function (input, format, lang, strict) {
  18464. var c;
  18465. if (typeof(lang) === "boolean") {
  18466. strict = lang;
  18467. lang = undefined;
  18468. }
  18469. // object construction must be done this way.
  18470. // https://github.com/moment/moment/issues/1423
  18471. c = {};
  18472. c._isAMomentObject = true;
  18473. c._useUTC = true;
  18474. c._isUTC = true;
  18475. c._l = lang;
  18476. c._i = input;
  18477. c._f = format;
  18478. c._strict = strict;
  18479. c._pf = defaultParsingFlags();
  18480. return makeMoment(c).utc();
  18481. };
  18482. // creating with unix timestamp (in seconds)
  18483. moment.unix = function (input) {
  18484. return moment(input * 1000);
  18485. };
  18486. // duration
  18487. moment.duration = function (input, key) {
  18488. var duration = input,
  18489. // matching against regexp is expensive, do it on demand
  18490. match = null,
  18491. sign,
  18492. ret,
  18493. parseIso;
  18494. if (moment.isDuration(input)) {
  18495. duration = {
  18496. ms: input._milliseconds,
  18497. d: input._days,
  18498. M: input._months
  18499. };
  18500. } else if (typeof input === 'number') {
  18501. duration = {};
  18502. if (key) {
  18503. duration[key] = input;
  18504. } else {
  18505. duration.milliseconds = input;
  18506. }
  18507. } else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) {
  18508. sign = (match[1] === "-") ? -1 : 1;
  18509. duration = {
  18510. y: 0,
  18511. d: toInt(match[DATE]) * sign,
  18512. h: toInt(match[HOUR]) * sign,
  18513. m: toInt(match[MINUTE]) * sign,
  18514. s: toInt(match[SECOND]) * sign,
  18515. ms: toInt(match[MILLISECOND]) * sign
  18516. };
  18517. } else if (!!(match = isoDurationRegex.exec(input))) {
  18518. sign = (match[1] === "-") ? -1 : 1;
  18519. parseIso = function (inp) {
  18520. // We'd normally use ~~inp for this, but unfortunately it also
  18521. // converts floats to ints.
  18522. // inp may be undefined, so careful calling replace on it.
  18523. var res = inp && parseFloat(inp.replace(',', '.'));
  18524. // apply sign while we're at it
  18525. return (isNaN(res) ? 0 : res) * sign;
  18526. };
  18527. duration = {
  18528. y: parseIso(match[2]),
  18529. M: parseIso(match[3]),
  18530. d: parseIso(match[4]),
  18531. h: parseIso(match[5]),
  18532. m: parseIso(match[6]),
  18533. s: parseIso(match[7]),
  18534. w: parseIso(match[8])
  18535. };
  18536. }
  18537. ret = new Duration(duration);
  18538. if (moment.isDuration(input) && input.hasOwnProperty('_lang')) {
  18539. ret._lang = input._lang;
  18540. }
  18541. return ret;
  18542. };
  18543. // version number
  18544. moment.version = VERSION;
  18545. // default format
  18546. moment.defaultFormat = isoFormat;
  18547. // Plugins that add properties should also add the key here (null value),
  18548. // so we can properly clone ourselves.
  18549. moment.momentProperties = momentProperties;
  18550. // This function will be called whenever a moment is mutated.
  18551. // It is intended to keep the offset in sync with the timezone.
  18552. moment.updateOffset = function () {};
  18553. // This function will load languages and then set the global language. If
  18554. // no arguments are passed in, it will simply return the current global
  18555. // language key.
  18556. moment.lang = function (key, values) {
  18557. var r;
  18558. if (!key) {
  18559. return moment.fn._lang._abbr;
  18560. }
  18561. if (values) {
  18562. loadLang(normalizeLanguage(key), values);
  18563. } else if (values === null) {
  18564. unloadLang(key);
  18565. key = 'en';
  18566. } else if (!languages[key]) {
  18567. getLangDefinition(key);
  18568. }
  18569. r = moment.duration.fn._lang = moment.fn._lang = getLangDefinition(key);
  18570. return r._abbr;
  18571. };
  18572. // returns language data
  18573. moment.langData = function (key) {
  18574. if (key && key._lang && key._lang._abbr) {
  18575. key = key._lang._abbr;
  18576. }
  18577. return getLangDefinition(key);
  18578. };
  18579. // compare moment object
  18580. moment.isMoment = function (obj) {
  18581. return obj instanceof Moment ||
  18582. (obj != null && obj.hasOwnProperty('_isAMomentObject'));
  18583. };
  18584. // for typechecking Duration objects
  18585. moment.isDuration = function (obj) {
  18586. return obj instanceof Duration;
  18587. };
  18588. for (i = lists.length - 1; i >= 0; --i) {
  18589. makeList(lists[i]);
  18590. }
  18591. moment.normalizeUnits = function (units) {
  18592. return normalizeUnits(units);
  18593. };
  18594. moment.invalid = function (flags) {
  18595. var m = moment.utc(NaN);
  18596. if (flags != null) {
  18597. extend(m._pf, flags);
  18598. }
  18599. else {
  18600. m._pf.userInvalidated = true;
  18601. }
  18602. return m;
  18603. };
  18604. moment.parseZone = function () {
  18605. return moment.apply(null, arguments).parseZone();
  18606. };
  18607. moment.parseTwoDigitYear = function (input) {
  18608. return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
  18609. };
  18610. /************************************
  18611. Moment Prototype
  18612. ************************************/
  18613. extend(moment.fn = Moment.prototype, {
  18614. clone : function () {
  18615. return moment(this);
  18616. },
  18617. valueOf : function () {
  18618. return +this._d + ((this._offset || 0) * 60000);
  18619. },
  18620. unix : function () {
  18621. return Math.floor(+this / 1000);
  18622. },
  18623. toString : function () {
  18624. return this.clone().lang('en').format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ");
  18625. },
  18626. toDate : function () {
  18627. return this._offset ? new Date(+this) : this._d;
  18628. },
  18629. toISOString : function () {
  18630. var m = moment(this).utc();
  18631. if (0 < m.year() && m.year() <= 9999) {
  18632. return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  18633. } else {
  18634. return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  18635. }
  18636. },
  18637. toArray : function () {
  18638. var m = this;
  18639. return [
  18640. m.year(),
  18641. m.month(),
  18642. m.date(),
  18643. m.hours(),
  18644. m.minutes(),
  18645. m.seconds(),
  18646. m.milliseconds()
  18647. ];
  18648. },
  18649. isValid : function () {
  18650. return isValid(this);
  18651. },
  18652. isDSTShifted : function () {
  18653. if (this._a) {
  18654. return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0;
  18655. }
  18656. return false;
  18657. },
  18658. parsingFlags : function () {
  18659. return extend({}, this._pf);
  18660. },
  18661. invalidAt: function () {
  18662. return this._pf.overflow;
  18663. },
  18664. utc : function () {
  18665. return this.zone(0);
  18666. },
  18667. local : function () {
  18668. this.zone(0);
  18669. this._isUTC = false;
  18670. return this;
  18671. },
  18672. format : function (inputString) {
  18673. var output = formatMoment(this, inputString || moment.defaultFormat);
  18674. return this.lang().postformat(output);
  18675. },
  18676. add : function (input, val) {
  18677. var dur;
  18678. // switch args to support add('s', 1) and add(1, 's')
  18679. if (typeof input === 'string') {
  18680. dur = moment.duration(+val, input);
  18681. } else {
  18682. dur = moment.duration(input, val);
  18683. }
  18684. addOrSubtractDurationFromMoment(this, dur, 1);
  18685. return this;
  18686. },
  18687. subtract : function (input, val) {
  18688. var dur;
  18689. // switch args to support subtract('s', 1) and subtract(1, 's')
  18690. if (typeof input === 'string') {
  18691. dur = moment.duration(+val, input);
  18692. } else {
  18693. dur = moment.duration(input, val);
  18694. }
  18695. addOrSubtractDurationFromMoment(this, dur, -1);
  18696. return this;
  18697. },
  18698. diff : function (input, units, asFloat) {
  18699. var that = makeAs(input, this),
  18700. zoneDiff = (this.zone() - that.zone()) * 6e4,
  18701. diff, output;
  18702. units = normalizeUnits(units);
  18703. if (units === 'year' || units === 'month') {
  18704. // average number of days in the months in the given dates
  18705. diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2
  18706. // difference in months
  18707. output = ((this.year() - that.year()) * 12) + (this.month() - that.month());
  18708. // adjust by taking difference in days, average number of days
  18709. // and dst in the given months.
  18710. output += ((this - moment(this).startOf('month')) -
  18711. (that - moment(that).startOf('month'))) / diff;
  18712. // same as above but with zones, to negate all dst
  18713. output -= ((this.zone() - moment(this).startOf('month').zone()) -
  18714. (that.zone() - moment(that).startOf('month').zone())) * 6e4 / diff;
  18715. if (units === 'year') {
  18716. output = output / 12;
  18717. }
  18718. } else {
  18719. diff = (this - that);
  18720. output = units === 'second' ? diff / 1e3 : // 1000
  18721. units === 'minute' ? diff / 6e4 : // 1000 * 60
  18722. units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60
  18723. units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
  18724. units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
  18725. diff;
  18726. }
  18727. return asFloat ? output : absRound(output);
  18728. },
  18729. from : function (time, withoutSuffix) {
  18730. return moment.duration(this.diff(time)).lang(this.lang()._abbr).humanize(!withoutSuffix);
  18731. },
  18732. fromNow : function (withoutSuffix) {
  18733. return this.from(moment(), withoutSuffix);
  18734. },
  18735. calendar : function () {
  18736. // We want to compare the start of today, vs this.
  18737. // Getting start-of-today depends on whether we're zone'd or not.
  18738. var sod = makeAs(moment(), this).startOf('day'),
  18739. diff = this.diff(sod, 'days', true),
  18740. format = diff < -6 ? 'sameElse' :
  18741. diff < -1 ? 'lastWeek' :
  18742. diff < 0 ? 'lastDay' :
  18743. diff < 1 ? 'sameDay' :
  18744. diff < 2 ? 'nextDay' :
  18745. diff < 7 ? 'nextWeek' : 'sameElse';
  18746. return this.format(this.lang().calendar(format, this));
  18747. },
  18748. isLeapYear : function () {
  18749. return isLeapYear(this.year());
  18750. },
  18751. isDST : function () {
  18752. return (this.zone() < this.clone().month(0).zone() ||
  18753. this.zone() < this.clone().month(5).zone());
  18754. },
  18755. day : function (input) {
  18756. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  18757. if (input != null) {
  18758. input = parseWeekday(input, this.lang());
  18759. return this.add({ d : input - day });
  18760. } else {
  18761. return day;
  18762. }
  18763. },
  18764. month : makeAccessor('Month', true),
  18765. startOf: function (units) {
  18766. units = normalizeUnits(units);
  18767. // the following switch intentionally omits break keywords
  18768. // to utilize falling through the cases.
  18769. switch (units) {
  18770. case 'year':
  18771. this.month(0);
  18772. /* falls through */
  18773. case 'quarter':
  18774. case 'month':
  18775. this.date(1);
  18776. /* falls through */
  18777. case 'week':
  18778. case 'isoWeek':
  18779. case 'day':
  18780. this.hours(0);
  18781. /* falls through */
  18782. case 'hour':
  18783. this.minutes(0);
  18784. /* falls through */
  18785. case 'minute':
  18786. this.seconds(0);
  18787. /* falls through */
  18788. case 'second':
  18789. this.milliseconds(0);
  18790. /* falls through */
  18791. }
  18792. // weeks are a special case
  18793. if (units === 'week') {
  18794. this.weekday(0);
  18795. } else if (units === 'isoWeek') {
  18796. this.isoWeekday(1);
  18797. }
  18798. // quarters are also special
  18799. if (units === 'quarter') {
  18800. this.month(Math.floor(this.month() / 3) * 3);
  18801. }
  18802. return this;
  18803. },
  18804. endOf: function (units) {
  18805. units = normalizeUnits(units);
  18806. return this.startOf(units).add((units === 'isoWeek' ? 'week' : units), 1).subtract('ms', 1);
  18807. },
  18808. isAfter: function (input, units) {
  18809. units = typeof units !== 'undefined' ? units : 'millisecond';
  18810. return +this.clone().startOf(units) > +moment(input).startOf(units);
  18811. },
  18812. isBefore: function (input, units) {
  18813. units = typeof units !== 'undefined' ? units : 'millisecond';
  18814. return +this.clone().startOf(units) < +moment(input).startOf(units);
  18815. },
  18816. isSame: function (input, units) {
  18817. units = units || 'ms';
  18818. return +this.clone().startOf(units) === +makeAs(input, this).startOf(units);
  18819. },
  18820. min: function (other) {
  18821. other = moment.apply(null, arguments);
  18822. return other < this ? this : other;
  18823. },
  18824. max: function (other) {
  18825. other = moment.apply(null, arguments);
  18826. return other > this ? this : other;
  18827. },
  18828. // keepTime = true means only change the timezone, without affecting
  18829. // the local hour. So 5:31:26 +0300 --[zone(2, true)]--> 5:31:26 +0200
  18830. // It is possible that 5:31:26 doesn't exist int zone +0200, so we
  18831. // adjust the time as needed, to be valid.
  18832. //
  18833. // Keeping the time actually adds/subtracts (one hour)
  18834. // from the actual represented time. That is why we call updateOffset
  18835. // a second time. In case it wants us to change the offset again
  18836. // _changeInProgress == true case, then we have to adjust, because
  18837. // there is no such time in the given timezone.
  18838. zone : function (input, keepTime) {
  18839. var offset = this._offset || 0;
  18840. if (input != null) {
  18841. if (typeof input === "string") {
  18842. input = timezoneMinutesFromString(input);
  18843. }
  18844. if (Math.abs(input) < 16) {
  18845. input = input * 60;
  18846. }
  18847. this._offset = input;
  18848. this._isUTC = true;
  18849. if (offset !== input) {
  18850. if (!keepTime || this._changeInProgress) {
  18851. addOrSubtractDurationFromMoment(this,
  18852. moment.duration(offset - input, 'm'), 1, false);
  18853. } else if (!this._changeInProgress) {
  18854. this._changeInProgress = true;
  18855. moment.updateOffset(this, true);
  18856. this._changeInProgress = null;
  18857. }
  18858. }
  18859. } else {
  18860. return this._isUTC ? offset : this._d.getTimezoneOffset();
  18861. }
  18862. return this;
  18863. },
  18864. zoneAbbr : function () {
  18865. return this._isUTC ? "UTC" : "";
  18866. },
  18867. zoneName : function () {
  18868. return this._isUTC ? "Coordinated Universal Time" : "";
  18869. },
  18870. parseZone : function () {
  18871. if (this._tzm) {
  18872. this.zone(this._tzm);
  18873. } else if (typeof this._i === 'string') {
  18874. this.zone(this._i);
  18875. }
  18876. return this;
  18877. },
  18878. hasAlignedHourOffset : function (input) {
  18879. if (!input) {
  18880. input = 0;
  18881. }
  18882. else {
  18883. input = moment(input).zone();
  18884. }
  18885. return (this.zone() - input) % 60 === 0;
  18886. },
  18887. daysInMonth : function () {
  18888. return daysInMonth(this.year(), this.month());
  18889. },
  18890. dayOfYear : function (input) {
  18891. var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1;
  18892. return input == null ? dayOfYear : this.add("d", (input - dayOfYear));
  18893. },
  18894. quarter : function (input) {
  18895. return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
  18896. },
  18897. weekYear : function (input) {
  18898. var year = weekOfYear(this, this.lang()._week.dow, this.lang()._week.doy).year;
  18899. return input == null ? year : this.add("y", (input - year));
  18900. },
  18901. isoWeekYear : function (input) {
  18902. var year = weekOfYear(this, 1, 4).year;
  18903. return input == null ? year : this.add("y", (input - year));
  18904. },
  18905. week : function (input) {
  18906. var week = this.lang().week(this);
  18907. return input == null ? week : this.add("d", (input - week) * 7);
  18908. },
  18909. isoWeek : function (input) {
  18910. var week = weekOfYear(this, 1, 4).week;
  18911. return input == null ? week : this.add("d", (input - week) * 7);
  18912. },
  18913. weekday : function (input) {
  18914. var weekday = (this.day() + 7 - this.lang()._week.dow) % 7;
  18915. return input == null ? weekday : this.add("d", input - weekday);
  18916. },
  18917. isoWeekday : function (input) {
  18918. // behaves the same as moment#day except
  18919. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  18920. // as a setter, sunday should belong to the previous week.
  18921. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7);
  18922. },
  18923. isoWeeksInYear : function () {
  18924. return weeksInYear(this.year(), 1, 4);
  18925. },
  18926. weeksInYear : function () {
  18927. var weekInfo = this._lang._week;
  18928. return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
  18929. },
  18930. get : function (units) {
  18931. units = normalizeUnits(units);
  18932. return this[units]();
  18933. },
  18934. set : function (units, value) {
  18935. units = normalizeUnits(units);
  18936. if (typeof this[units] === 'function') {
  18937. this[units](value);
  18938. }
  18939. return this;
  18940. },
  18941. // If passed a language key, it will set the language for this
  18942. // instance. Otherwise, it will return the language configuration
  18943. // variables for this instance.
  18944. lang : function (key) {
  18945. if (key === undefined) {
  18946. return this._lang;
  18947. } else {
  18948. this._lang = getLangDefinition(key);
  18949. return this;
  18950. }
  18951. }
  18952. });
  18953. function rawMonthSetter(mom, value) {
  18954. var dayOfMonth;
  18955. // TODO: Move this out of here!
  18956. if (typeof value === 'string') {
  18957. value = mom.lang().monthsParse(value);
  18958. // TODO: Another silent failure?
  18959. if (typeof value !== 'number') {
  18960. return mom;
  18961. }
  18962. }
  18963. dayOfMonth = Math.min(mom.date(),
  18964. daysInMonth(mom.year(), value));
  18965. mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
  18966. return mom;
  18967. }
  18968. function rawGetter(mom, unit) {
  18969. return mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]();
  18970. }
  18971. function rawSetter(mom, unit, value) {
  18972. if (unit === 'Month') {
  18973. return rawMonthSetter(mom, value);
  18974. } else {
  18975. return mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
  18976. }
  18977. }
  18978. function makeAccessor(unit, keepTime) {
  18979. return function (value) {
  18980. if (value != null) {
  18981. rawSetter(this, unit, value);
  18982. moment.updateOffset(this, keepTime);
  18983. return this;
  18984. } else {
  18985. return rawGetter(this, unit);
  18986. }
  18987. };
  18988. }
  18989. moment.fn.millisecond = moment.fn.milliseconds = makeAccessor('Milliseconds', false);
  18990. moment.fn.second = moment.fn.seconds = makeAccessor('Seconds', false);
  18991. moment.fn.minute = moment.fn.minutes = makeAccessor('Minutes', false);
  18992. // Setting the hour should keep the time, because the user explicitly
  18993. // specified which hour he wants. So trying to maintain the same hour (in
  18994. // a new timezone) makes sense. Adding/subtracting hours does not follow
  18995. // this rule.
  18996. moment.fn.hour = moment.fn.hours = makeAccessor('Hours', true);
  18997. // moment.fn.month is defined separately
  18998. moment.fn.date = makeAccessor('Date', true);
  18999. moment.fn.dates = deprecate("dates accessor is deprecated. Use date instead.", makeAccessor('Date', true));
  19000. moment.fn.year = makeAccessor('FullYear', true);
  19001. moment.fn.years = deprecate("years accessor is deprecated. Use year instead.", makeAccessor('FullYear', true));
  19002. // add plural methods
  19003. moment.fn.days = moment.fn.day;
  19004. moment.fn.months = moment.fn.month;
  19005. moment.fn.weeks = moment.fn.week;
  19006. moment.fn.isoWeeks = moment.fn.isoWeek;
  19007. moment.fn.quarters = moment.fn.quarter;
  19008. // add aliased format methods
  19009. moment.fn.toJSON = moment.fn.toISOString;
  19010. /************************************
  19011. Duration Prototype
  19012. ************************************/
  19013. extend(moment.duration.fn = Duration.prototype, {
  19014. _bubble : function () {
  19015. var milliseconds = this._milliseconds,
  19016. days = this._days,
  19017. months = this._months,
  19018. data = this._data,
  19019. seconds, minutes, hours, years;
  19020. // The following code bubbles up values, see the tests for
  19021. // examples of what that means.
  19022. data.milliseconds = milliseconds % 1000;
  19023. seconds = absRound(milliseconds / 1000);
  19024. data.seconds = seconds % 60;
  19025. minutes = absRound(seconds / 60);
  19026. data.minutes = minutes % 60;
  19027. hours = absRound(minutes / 60);
  19028. data.hours = hours % 24;
  19029. days += absRound(hours / 24);
  19030. data.days = days % 30;
  19031. months += absRound(days / 30);
  19032. data.months = months % 12;
  19033. years = absRound(months / 12);
  19034. data.years = years;
  19035. },
  19036. weeks : function () {
  19037. return absRound(this.days() / 7);
  19038. },
  19039. valueOf : function () {
  19040. return this._milliseconds +
  19041. this._days * 864e5 +
  19042. (this._months % 12) * 2592e6 +
  19043. toInt(this._months / 12) * 31536e6;
  19044. },
  19045. humanize : function (withSuffix) {
  19046. var difference = +this,
  19047. output = relativeTime(difference, !withSuffix, this.lang());
  19048. if (withSuffix) {
  19049. output = this.lang().pastFuture(difference, output);
  19050. }
  19051. return this.lang().postformat(output);
  19052. },
  19053. add : function (input, val) {
  19054. // supports only 2.0-style add(1, 's') or add(moment)
  19055. var dur = moment.duration(input, val);
  19056. this._milliseconds += dur._milliseconds;
  19057. this._days += dur._days;
  19058. this._months += dur._months;
  19059. this._bubble();
  19060. return this;
  19061. },
  19062. subtract : function (input, val) {
  19063. var dur = moment.duration(input, val);
  19064. this._milliseconds -= dur._milliseconds;
  19065. this._days -= dur._days;
  19066. this._months -= dur._months;
  19067. this._bubble();
  19068. return this;
  19069. },
  19070. get : function (units) {
  19071. units = normalizeUnits(units);
  19072. return this[units.toLowerCase() + 's']();
  19073. },
  19074. as : function (units) {
  19075. units = normalizeUnits(units);
  19076. return this['as' + units.charAt(0).toUpperCase() + units.slice(1) + 's']();
  19077. },
  19078. lang : moment.fn.lang,
  19079. toIsoString : function () {
  19080. // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
  19081. var years = Math.abs(this.years()),
  19082. months = Math.abs(this.months()),
  19083. days = Math.abs(this.days()),
  19084. hours = Math.abs(this.hours()),
  19085. minutes = Math.abs(this.minutes()),
  19086. seconds = Math.abs(this.seconds() + this.milliseconds() / 1000);
  19087. if (!this.asSeconds()) {
  19088. // this is the same as C#'s (Noda) and python (isodate)...
  19089. // but not other JS (goog.date)
  19090. return 'P0D';
  19091. }
  19092. return (this.asSeconds() < 0 ? '-' : '') +
  19093. 'P' +
  19094. (years ? years + 'Y' : '') +
  19095. (months ? months + 'M' : '') +
  19096. (days ? days + 'D' : '') +
  19097. ((hours || minutes || seconds) ? 'T' : '') +
  19098. (hours ? hours + 'H' : '') +
  19099. (minutes ? minutes + 'M' : '') +
  19100. (seconds ? seconds + 'S' : '');
  19101. }
  19102. });
  19103. function makeDurationGetter(name) {
  19104. moment.duration.fn[name] = function () {
  19105. return this._data[name];
  19106. };
  19107. }
  19108. function makeDurationAsGetter(name, factor) {
  19109. moment.duration.fn['as' + name] = function () {
  19110. return +this / factor;
  19111. };
  19112. }
  19113. for (i in unitMillisecondFactors) {
  19114. if (unitMillisecondFactors.hasOwnProperty(i)) {
  19115. makeDurationAsGetter(i, unitMillisecondFactors[i]);
  19116. makeDurationGetter(i.toLowerCase());
  19117. }
  19118. }
  19119. makeDurationAsGetter('Weeks', 6048e5);
  19120. moment.duration.fn.asMonths = function () {
  19121. return (+this - this.years() * 31536e6) / 2592e6 + this.years() * 12;
  19122. };
  19123. /************************************
  19124. Default Lang
  19125. ************************************/
  19126. // Set default language, other languages will inherit from English.
  19127. moment.lang('en', {
  19128. ordinal : function (number) {
  19129. var b = number % 10,
  19130. output = (toInt(number % 100 / 10) === 1) ? 'th' :
  19131. (b === 1) ? 'st' :
  19132. (b === 2) ? 'nd' :
  19133. (b === 3) ? 'rd' : 'th';
  19134. return number + output;
  19135. }
  19136. });
  19137. /* EMBED_LANGUAGES */
  19138. /************************************
  19139. Exposing Moment
  19140. ************************************/
  19141. function makeGlobal(shouldDeprecate) {
  19142. /*global ender:false */
  19143. if (typeof ender !== 'undefined') {
  19144. return;
  19145. }
  19146. oldGlobalMoment = globalScope.moment;
  19147. if (shouldDeprecate) {
  19148. globalScope.moment = deprecate(
  19149. "Accessing Moment through the global scope is " +
  19150. "deprecated, and will be removed in an upcoming " +
  19151. "release.",
  19152. moment);
  19153. } else {
  19154. globalScope.moment = moment;
  19155. }
  19156. }
  19157. // CommonJS module is defined
  19158. if (hasModule) {
  19159. module.exports = moment;
  19160. } else if (typeof define === "function" && define.amd) {
  19161. define("moment", function (require, exports, module) {
  19162. if (module.config && module.config() && module.config().noGlobal === true) {
  19163. // release the global variable
  19164. globalScope.moment = oldGlobalMoment;
  19165. }
  19166. return moment;
  19167. });
  19168. makeGlobal(true);
  19169. } else {
  19170. makeGlobal();
  19171. }
  19172. }).call(this);
  19173. },{}],5:[function(require,module,exports){
  19174. /**
  19175. * Copyright 2012 Craig Campbell
  19176. *
  19177. * Licensed under the Apache License, Version 2.0 (the "License");
  19178. * you may not use this file except in compliance with the License.
  19179. * You may obtain a copy of the License at
  19180. *
  19181. * http://www.apache.org/licenses/LICENSE-2.0
  19182. *
  19183. * Unless required by applicable law or agreed to in writing, software
  19184. * distributed under the License is distributed on an "AS IS" BASIS,
  19185. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19186. * See the License for the specific language governing permissions and
  19187. * limitations under the License.
  19188. *
  19189. * Mousetrap is a simple keyboard shortcut library for Javascript with
  19190. * no external dependencies
  19191. *
  19192. * @version 1.1.2
  19193. * @url craig.is/killing/mice
  19194. */
  19195. /**
  19196. * mapping of special keycodes to their corresponding keys
  19197. *
  19198. * everything in this dictionary cannot use keypress events
  19199. * so it has to be here to map to the correct keycodes for
  19200. * keyup/keydown events
  19201. *
  19202. * @type {Object}
  19203. */
  19204. var _MAP = {
  19205. 8: 'backspace',
  19206. 9: 'tab',
  19207. 13: 'enter',
  19208. 16: 'shift',
  19209. 17: 'ctrl',
  19210. 18: 'alt',
  19211. 20: 'capslock',
  19212. 27: 'esc',
  19213. 32: 'space',
  19214. 33: 'pageup',
  19215. 34: 'pagedown',
  19216. 35: 'end',
  19217. 36: 'home',
  19218. 37: 'left',
  19219. 38: 'up',
  19220. 39: 'right',
  19221. 40: 'down',
  19222. 45: 'ins',
  19223. 46: 'del',
  19224. 91: 'meta',
  19225. 93: 'meta',
  19226. 224: 'meta'
  19227. },
  19228. /**
  19229. * mapping for special characters so they can support
  19230. *
  19231. * this dictionary is only used incase you want to bind a
  19232. * keyup or keydown event to one of these keys
  19233. *
  19234. * @type {Object}
  19235. */
  19236. _KEYCODE_MAP = {
  19237. 106: '*',
  19238. 107: '+',
  19239. 109: '-',
  19240. 110: '.',
  19241. 111 : '/',
  19242. 186: ';',
  19243. 187: '=',
  19244. 188: ',',
  19245. 189: '-',
  19246. 190: '.',
  19247. 191: '/',
  19248. 192: '`',
  19249. 219: '[',
  19250. 220: '\\',
  19251. 221: ']',
  19252. 222: '\''
  19253. },
  19254. /**
  19255. * this is a mapping of keys that require shift on a US keypad
  19256. * back to the non shift equivelents
  19257. *
  19258. * this is so you can use keyup events with these keys
  19259. *
  19260. * note that this will only work reliably on US keyboards
  19261. *
  19262. * @type {Object}
  19263. */
  19264. _SHIFT_MAP = {
  19265. '~': '`',
  19266. '!': '1',
  19267. '@': '2',
  19268. '#': '3',
  19269. '$': '4',
  19270. '%': '5',
  19271. '^': '6',
  19272. '&': '7',
  19273. '*': '8',
  19274. '(': '9',
  19275. ')': '0',
  19276. '_': '-',
  19277. '+': '=',
  19278. ':': ';',
  19279. '\"': '\'',
  19280. '<': ',',
  19281. '>': '.',
  19282. '?': '/',
  19283. '|': '\\'
  19284. },
  19285. /**
  19286. * this is a list of special strings you can use to map
  19287. * to modifier keys when you specify your keyboard shortcuts
  19288. *
  19289. * @type {Object}
  19290. */
  19291. _SPECIAL_ALIASES = {
  19292. 'option': 'alt',
  19293. 'command': 'meta',
  19294. 'return': 'enter',
  19295. 'escape': 'esc'
  19296. },
  19297. /**
  19298. * variable to store the flipped version of _MAP from above
  19299. * needed to check if we should use keypress or not when no action
  19300. * is specified
  19301. *
  19302. * @type {Object|undefined}
  19303. */
  19304. _REVERSE_MAP,
  19305. /**
  19306. * a list of all the callbacks setup via Mousetrap.bind()
  19307. *
  19308. * @type {Object}
  19309. */
  19310. _callbacks = {},
  19311. /**
  19312. * direct map of string combinations to callbacks used for trigger()
  19313. *
  19314. * @type {Object}
  19315. */
  19316. _direct_map = {},
  19317. /**
  19318. * keeps track of what level each sequence is at since multiple
  19319. * sequences can start out with the same sequence
  19320. *
  19321. * @type {Object}
  19322. */
  19323. _sequence_levels = {},
  19324. /**
  19325. * variable to store the setTimeout call
  19326. *
  19327. * @type {null|number}
  19328. */
  19329. _reset_timer,
  19330. /**
  19331. * temporary state where we will ignore the next keyup
  19332. *
  19333. * @type {boolean|string}
  19334. */
  19335. _ignore_next_keyup = false,
  19336. /**
  19337. * are we currently inside of a sequence?
  19338. * type of action ("keyup" or "keydown" or "keypress") or false
  19339. *
  19340. * @type {boolean|string}
  19341. */
  19342. _inside_sequence = false;
  19343. /**
  19344. * loop through the f keys, f1 to f19 and add them to the map
  19345. * programatically
  19346. */
  19347. for (var i = 1; i < 20; ++i) {
  19348. _MAP[111 + i] = 'f' + i;
  19349. }
  19350. /**
  19351. * loop through to map numbers on the numeric keypad
  19352. */
  19353. for (i = 0; i <= 9; ++i) {
  19354. _MAP[i + 96] = i;
  19355. }
  19356. /**
  19357. * cross browser add event method
  19358. *
  19359. * @param {Element|HTMLDocument} object
  19360. * @param {string} type
  19361. * @param {Function} callback
  19362. * @returns void
  19363. */
  19364. function _addEvent(object, type, callback) {
  19365. if (object.addEventListener) {
  19366. return object.addEventListener(type, callback, false);
  19367. }
  19368. object.attachEvent('on' + type, callback);
  19369. }
  19370. /**
  19371. * takes the event and returns the key character
  19372. *
  19373. * @param {Event} e
  19374. * @return {string}
  19375. */
  19376. function _characterFromEvent(e) {
  19377. // for keypress events we should return the character as is
  19378. if (e.type == 'keypress') {
  19379. return String.fromCharCode(e.which);
  19380. }
  19381. // for non keypress events the special maps are needed
  19382. if (_MAP[e.which]) {
  19383. return _MAP[e.which];
  19384. }
  19385. if (_KEYCODE_MAP[e.which]) {
  19386. return _KEYCODE_MAP[e.which];
  19387. }
  19388. // if it is not in the special map
  19389. return String.fromCharCode(e.which).toLowerCase();
  19390. }
  19391. /**
  19392. * should we stop this event before firing off callbacks
  19393. *
  19394. * @param {Event} e
  19395. * @return {boolean}
  19396. */
  19397. function _stop(e) {
  19398. var element = e.target || e.srcElement,
  19399. tag_name = element.tagName;
  19400. // if the element has the class "mousetrap" then no need to stop
  19401. if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {
  19402. return false;
  19403. }
  19404. // stop for input, select, and textarea
  19405. return tag_name == 'INPUT' || tag_name == 'SELECT' || tag_name == 'TEXTAREA' || (element.contentEditable && element.contentEditable == 'true');
  19406. }
  19407. /**
  19408. * checks if two arrays are equal
  19409. *
  19410. * @param {Array} modifiers1
  19411. * @param {Array} modifiers2
  19412. * @returns {boolean}
  19413. */
  19414. function _modifiersMatch(modifiers1, modifiers2) {
  19415. return modifiers1.sort().join(',') === modifiers2.sort().join(',');
  19416. }
  19417. /**
  19418. * resets all sequence counters except for the ones passed in
  19419. *
  19420. * @param {Object} do_not_reset
  19421. * @returns void
  19422. */
  19423. function _resetSequences(do_not_reset) {
  19424. do_not_reset = do_not_reset || {};
  19425. var active_sequences = false,
  19426. key;
  19427. for (key in _sequence_levels) {
  19428. if (do_not_reset[key]) {
  19429. active_sequences = true;
  19430. continue;
  19431. }
  19432. _sequence_levels[key] = 0;
  19433. }
  19434. if (!active_sequences) {
  19435. _inside_sequence = false;
  19436. }
  19437. }
  19438. /**
  19439. * finds all callbacks that match based on the keycode, modifiers,
  19440. * and action
  19441. *
  19442. * @param {string} character
  19443. * @param {Array} modifiers
  19444. * @param {string} action
  19445. * @param {boolean=} remove - should we remove any matches
  19446. * @param {string=} combination
  19447. * @returns {Array}
  19448. */
  19449. function _getMatches(character, modifiers, action, remove, combination) {
  19450. var i,
  19451. callback,
  19452. matches = [];
  19453. // if there are no events related to this keycode
  19454. if (!_callbacks[character]) {
  19455. return [];
  19456. }
  19457. // if a modifier key is coming up on its own we should allow it
  19458. if (action == 'keyup' && _isModifier(character)) {
  19459. modifiers = [character];
  19460. }
  19461. // loop through all callbacks for the key that was pressed
  19462. // and see if any of them match
  19463. for (i = 0; i < _callbacks[character].length; ++i) {
  19464. callback = _callbacks[character][i];
  19465. // if this is a sequence but it is not at the right level
  19466. // then move onto the next match
  19467. if (callback.seq && _sequence_levels[callback.seq] != callback.level) {
  19468. continue;
  19469. }
  19470. // if the action we are looking for doesn't match the action we got
  19471. // then we should keep going
  19472. if (action != callback.action) {
  19473. continue;
  19474. }
  19475. // if this is a keypress event that means that we need to only
  19476. // look at the character, otherwise check the modifiers as
  19477. // well
  19478. if (action == 'keypress' || _modifiersMatch(modifiers, callback.modifiers)) {
  19479. // remove is used so if you change your mind and call bind a
  19480. // second time with a new function the first one is overwritten
  19481. if (remove && callback.combo == combination) {
  19482. _callbacks[character].splice(i, 1);
  19483. }
  19484. matches.push(callback);
  19485. }
  19486. }
  19487. return matches;
  19488. }
  19489. /**
  19490. * takes a key event and figures out what the modifiers are
  19491. *
  19492. * @param {Event} e
  19493. * @returns {Array}
  19494. */
  19495. function _eventModifiers(e) {
  19496. var modifiers = [];
  19497. if (e.shiftKey) {
  19498. modifiers.push('shift');
  19499. }
  19500. if (e.altKey) {
  19501. modifiers.push('alt');
  19502. }
  19503. if (e.ctrlKey) {
  19504. modifiers.push('ctrl');
  19505. }
  19506. if (e.metaKey) {
  19507. modifiers.push('meta');
  19508. }
  19509. return modifiers;
  19510. }
  19511. /**
  19512. * actually calls the callback function
  19513. *
  19514. * if your callback function returns false this will use the jquery
  19515. * convention - prevent default and stop propogation on the event
  19516. *
  19517. * @param {Function} callback
  19518. * @param {Event} e
  19519. * @returns void
  19520. */
  19521. function _fireCallback(callback, e) {
  19522. if (callback(e) === false) {
  19523. if (e.preventDefault) {
  19524. e.preventDefault();
  19525. }
  19526. if (e.stopPropagation) {
  19527. e.stopPropagation();
  19528. }
  19529. e.returnValue = false;
  19530. e.cancelBubble = true;
  19531. }
  19532. }
  19533. /**
  19534. * handles a character key event
  19535. *
  19536. * @param {string} character
  19537. * @param {Event} e
  19538. * @returns void
  19539. */
  19540. function _handleCharacter(character, e) {
  19541. // if this event should not happen stop here
  19542. if (_stop(e)) {
  19543. return;
  19544. }
  19545. var callbacks = _getMatches(character, _eventModifiers(e), e.type),
  19546. i,
  19547. do_not_reset = {},
  19548. processed_sequence_callback = false;
  19549. // loop through matching callbacks for this key event
  19550. for (i = 0; i < callbacks.length; ++i) {
  19551. // fire for all sequence callbacks
  19552. // this is because if for example you have multiple sequences
  19553. // bound such as "g i" and "g t" they both need to fire the
  19554. // callback for matching g cause otherwise you can only ever
  19555. // match the first one
  19556. if (callbacks[i].seq) {
  19557. processed_sequence_callback = true;
  19558. // keep a list of which sequences were matches for later
  19559. do_not_reset[callbacks[i].seq] = 1;
  19560. _fireCallback(callbacks[i].callback, e);
  19561. continue;
  19562. }
  19563. // if there were no sequence matches but we are still here
  19564. // that means this is a regular match so we should fire that
  19565. if (!processed_sequence_callback && !_inside_sequence) {
  19566. _fireCallback(callbacks[i].callback, e);
  19567. }
  19568. }
  19569. // if you are inside of a sequence and the key you are pressing
  19570. // is not a modifier key then we should reset all sequences
  19571. // that were not matched by this key event
  19572. if (e.type == _inside_sequence && !_isModifier(character)) {
  19573. _resetSequences(do_not_reset);
  19574. }
  19575. }
  19576. /**
  19577. * handles a keydown event
  19578. *
  19579. * @param {Event} e
  19580. * @returns void
  19581. */
  19582. function _handleKey(e) {
  19583. // normalize e.which for key events
  19584. // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion
  19585. e.which = typeof e.which == "number" ? e.which : e.keyCode;
  19586. var character = _characterFromEvent(e);
  19587. // no character found then stop
  19588. if (!character) {
  19589. return;
  19590. }
  19591. if (e.type == 'keyup' && _ignore_next_keyup == character) {
  19592. _ignore_next_keyup = false;
  19593. return;
  19594. }
  19595. _handleCharacter(character, e);
  19596. }
  19597. /**
  19598. * determines if the keycode specified is a modifier key or not
  19599. *
  19600. * @param {string} key
  19601. * @returns {boolean}
  19602. */
  19603. function _isModifier(key) {
  19604. return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta';
  19605. }
  19606. /**
  19607. * called to set a 1 second timeout on the specified sequence
  19608. *
  19609. * this is so after each key press in the sequence you have 1 second
  19610. * to press the next key before you have to start over
  19611. *
  19612. * @returns void
  19613. */
  19614. function _resetSequenceTimer() {
  19615. clearTimeout(_reset_timer);
  19616. _reset_timer = setTimeout(_resetSequences, 1000);
  19617. }
  19618. /**
  19619. * reverses the map lookup so that we can look for specific keys
  19620. * to see what can and can't use keypress
  19621. *
  19622. * @return {Object}
  19623. */
  19624. function _getReverseMap() {
  19625. if (!_REVERSE_MAP) {
  19626. _REVERSE_MAP = {};
  19627. for (var key in _MAP) {
  19628. // pull out the numeric keypad from here cause keypress should
  19629. // be able to detect the keys from the character
  19630. if (key > 95 && key < 112) {
  19631. continue;
  19632. }
  19633. if (_MAP.hasOwnProperty(key)) {
  19634. _REVERSE_MAP[_MAP[key]] = key;
  19635. }
  19636. }
  19637. }
  19638. return _REVERSE_MAP;
  19639. }
  19640. /**
  19641. * picks the best action based on the key combination
  19642. *
  19643. * @param {string} key - character for key
  19644. * @param {Array} modifiers
  19645. * @param {string=} action passed in
  19646. */
  19647. function _pickBestAction(key, modifiers, action) {
  19648. // if no action was picked in we should try to pick the one
  19649. // that we think would work best for this key
  19650. if (!action) {
  19651. action = _getReverseMap()[key] ? 'keydown' : 'keypress';
  19652. }
  19653. // modifier keys don't work as expected with keypress,
  19654. // switch to keydown
  19655. if (action == 'keypress' && modifiers.length) {
  19656. action = 'keydown';
  19657. }
  19658. return action;
  19659. }
  19660. /**
  19661. * binds a key sequence to an event
  19662. *
  19663. * @param {string} combo - combo specified in bind call
  19664. * @param {Array} keys
  19665. * @param {Function} callback
  19666. * @param {string=} action
  19667. * @returns void
  19668. */
  19669. function _bindSequence(combo, keys, callback, action) {
  19670. // start off by adding a sequence level record for this combination
  19671. // and setting the level to 0
  19672. _sequence_levels[combo] = 0;
  19673. // if there is no action pick the best one for the first key
  19674. // in the sequence
  19675. if (!action) {
  19676. action = _pickBestAction(keys[0], []);
  19677. }
  19678. /**
  19679. * callback to increase the sequence level for this sequence and reset
  19680. * all other sequences that were active
  19681. *
  19682. * @param {Event} e
  19683. * @returns void
  19684. */
  19685. var _increaseSequence = function(e) {
  19686. _inside_sequence = action;
  19687. ++_sequence_levels[combo];
  19688. _resetSequenceTimer();
  19689. },
  19690. /**
  19691. * wraps the specified callback inside of another function in order
  19692. * to reset all sequence counters as soon as this sequence is done
  19693. *
  19694. * @param {Event} e
  19695. * @returns void
  19696. */
  19697. _callbackAndReset = function(e) {
  19698. _fireCallback(callback, e);
  19699. // we should ignore the next key up if the action is key down
  19700. // or keypress. this is so if you finish a sequence and
  19701. // release the key the final key will not trigger a keyup
  19702. if (action !== 'keyup') {
  19703. _ignore_next_keyup = _characterFromEvent(e);
  19704. }
  19705. // weird race condition if a sequence ends with the key
  19706. // another sequence begins with
  19707. setTimeout(_resetSequences, 10);
  19708. },
  19709. i;
  19710. // loop through keys one at a time and bind the appropriate callback
  19711. // function. for any key leading up to the final one it should
  19712. // increase the sequence. after the final, it should reset all sequences
  19713. for (i = 0; i < keys.length; ++i) {
  19714. _bindSingle(keys[i], i < keys.length - 1 ? _increaseSequence : _callbackAndReset, action, combo, i);
  19715. }
  19716. }
  19717. /**
  19718. * binds a single keyboard combination
  19719. *
  19720. * @param {string} combination
  19721. * @param {Function} callback
  19722. * @param {string=} action
  19723. * @param {string=} sequence_name - name of sequence if part of sequence
  19724. * @param {number=} level - what part of the sequence the command is
  19725. * @returns void
  19726. */
  19727. function _bindSingle(combination, callback, action, sequence_name, level) {
  19728. // make sure multiple spaces in a row become a single space
  19729. combination = combination.replace(/\s+/g, ' ');
  19730. var sequence = combination.split(' '),
  19731. i,
  19732. key,
  19733. keys,
  19734. modifiers = [];
  19735. // if this pattern is a sequence of keys then run through this method
  19736. // to reprocess each pattern one key at a time
  19737. if (sequence.length > 1) {
  19738. return _bindSequence(combination, sequence, callback, action);
  19739. }
  19740. // take the keys from this pattern and figure out what the actual
  19741. // pattern is all about
  19742. keys = combination === '+' ? ['+'] : combination.split('+');
  19743. for (i = 0; i < keys.length; ++i) {
  19744. key = keys[i];
  19745. // normalize key names
  19746. if (_SPECIAL_ALIASES[key]) {
  19747. key = _SPECIAL_ALIASES[key];
  19748. }
  19749. // if this is not a keypress event then we should
  19750. // be smart about using shift keys
  19751. // this will only work for US keyboards however
  19752. if (action && action != 'keypress' && _SHIFT_MAP[key]) {
  19753. key = _SHIFT_MAP[key];
  19754. modifiers.push('shift');
  19755. }
  19756. // if this key is a modifier then add it to the list of modifiers
  19757. if (_isModifier(key)) {
  19758. modifiers.push(key);
  19759. }
  19760. }
  19761. // depending on what the key combination is
  19762. // we will try to pick the best event for it
  19763. action = _pickBestAction(key, modifiers, action);
  19764. // make sure to initialize array if this is the first time
  19765. // a callback is added for this key
  19766. if (!_callbacks[key]) {
  19767. _callbacks[key] = [];
  19768. }
  19769. // remove an existing match if there is one
  19770. _getMatches(key, modifiers, action, !sequence_name, combination);
  19771. // add this call back to the array
  19772. // if it is a sequence put it at the beginning
  19773. // if not put it at the end
  19774. //
  19775. // this is important because the way these are processed expects
  19776. // the sequence ones to come first
  19777. _callbacks[key][sequence_name ? 'unshift' : 'push']({
  19778. callback: callback,
  19779. modifiers: modifiers,
  19780. action: action,
  19781. seq: sequence_name,
  19782. level: level,
  19783. combo: combination
  19784. });
  19785. }
  19786. /**
  19787. * binds multiple combinations to the same callback
  19788. *
  19789. * @param {Array} combinations
  19790. * @param {Function} callback
  19791. * @param {string|undefined} action
  19792. * @returns void
  19793. */
  19794. function _bindMultiple(combinations, callback, action) {
  19795. for (var i = 0; i < combinations.length; ++i) {
  19796. _bindSingle(combinations[i], callback, action);
  19797. }
  19798. }
  19799. // start!
  19800. _addEvent(document, 'keypress', _handleKey);
  19801. _addEvent(document, 'keydown', _handleKey);
  19802. _addEvent(document, 'keyup', _handleKey);
  19803. var mousetrap = {
  19804. /**
  19805. * binds an event to mousetrap
  19806. *
  19807. * can be a single key, a combination of keys separated with +,
  19808. * a comma separated list of keys, an array of keys, or
  19809. * a sequence of keys separated by spaces
  19810. *
  19811. * be sure to list the modifier keys first to make sure that the
  19812. * correct key ends up getting bound (the last key in the pattern)
  19813. *
  19814. * @param {string|Array} keys
  19815. * @param {Function} callback
  19816. * @param {string=} action - 'keypress', 'keydown', or 'keyup'
  19817. * @returns void
  19818. */
  19819. bind: function(keys, callback, action) {
  19820. _bindMultiple(keys instanceof Array ? keys : [keys], callback, action);
  19821. _direct_map[keys + ':' + action] = callback;
  19822. return this;
  19823. },
  19824. /**
  19825. * unbinds an event to mousetrap
  19826. *
  19827. * the unbinding sets the callback function of the specified key combo
  19828. * to an empty function and deletes the corresponding key in the
  19829. * _direct_map dict.
  19830. *
  19831. * the keycombo+action has to be exactly the same as
  19832. * it was defined in the bind method
  19833. *
  19834. * TODO: actually remove this from the _callbacks dictionary instead
  19835. * of binding an empty function
  19836. *
  19837. * @param {string|Array} keys
  19838. * @param {string} action
  19839. * @returns void
  19840. */
  19841. unbind: function(keys, action) {
  19842. if (_direct_map[keys + ':' + action]) {
  19843. delete _direct_map[keys + ':' + action];
  19844. this.bind(keys, function() {}, action);
  19845. }
  19846. return this;
  19847. },
  19848. /**
  19849. * triggers an event that has already been bound
  19850. *
  19851. * @param {string} keys
  19852. * @param {string=} action
  19853. * @returns void
  19854. */
  19855. trigger: function(keys, action) {
  19856. _direct_map[keys + ':' + action]();
  19857. return this;
  19858. },
  19859. /**
  19860. * resets the library back to its initial state. this is useful
  19861. * if you want to clear out the current keyboard shortcuts and bind
  19862. * new ones - for example if you switch to another page
  19863. *
  19864. * @returns void
  19865. */
  19866. reset: function() {
  19867. _callbacks = {};
  19868. _direct_map = {};
  19869. return this;
  19870. }
  19871. };
  19872. module.exports = mousetrap;
  19873. },{}]},{},[1])
  19874. (1)
  19875. });