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.

22964 lines
680 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
10 years ago
10 years ago
  1. /**
  2. * vis.js
  3. * https://github.com/almende/vis
  4. *
  5. * A dynamic, browser-based visualization library.
  6. *
  7. * @version 1.0.1-SNAPSHOT
  8. * @date 2014-05-09
  9. *
  10. * @license
  11. * Copyright (C) 2011-2014 Almende B.V, http://almende.com
  12. *
  13. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  14. * use this file except in compliance with the License. You may obtain a copy
  15. * of the License at
  16. *
  17. * http://www.apache.org/licenses/LICENSE-2.0
  18. *
  19. * Unless required by applicable law or agreed to in writing, software
  20. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  21. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  22. * License for the specific language governing permissions and limitations under
  23. * the License.
  24. */
  25. !function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.vis=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  26. /**
  27. * vis.js module imports
  28. */
  29. // Try to load dependencies from the global window object.
  30. // If not available there, load via require.
  31. var moment = (typeof window !== 'undefined') && window['moment'] || require('moment');
  32. var Emitter = require('emitter-component');
  33. var Hammer;
  34. if (typeof window !== 'undefined') {
  35. // load hammer.js only when running in a browser (where window is available)
  36. Hammer = window['Hammer'] || require('hammerjs');
  37. }
  38. else {
  39. Hammer = function () {
  40. throw Error('hammer.js is only available in a browser, not in node.js.');
  41. }
  42. }
  43. var mousetrap;
  44. if (typeof window !== 'undefined') {
  45. // load mousetrap.js only when running in a browser (where window is available)
  46. mousetrap = window['mousetrap'] || require('mousetrap');
  47. }
  48. else {
  49. mousetrap = function () {
  50. throw Error('mouseTrap is only available in a browser, not in node.js.');
  51. }
  52. }
  53. // Internet Explorer 8 and older does not support Array.indexOf, so we define
  54. // it here in that case.
  55. // http://soledadpenades.com/2007/05/17/arrayindexof-in-internet-explorer/
  56. if(!Array.prototype.indexOf) {
  57. Array.prototype.indexOf = function(obj){
  58. for(var i = 0; i < this.length; i++){
  59. if(this[i] == obj){
  60. return i;
  61. }
  62. }
  63. return -1;
  64. };
  65. try {
  66. console.log("Warning: Ancient browser detected. Please update your browser");
  67. }
  68. catch (err) {
  69. }
  70. }
  71. // Internet Explorer 8 and older does not support Array.forEach, so we define
  72. // it here in that case.
  73. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach
  74. if (!Array.prototype.forEach) {
  75. Array.prototype.forEach = function(fn, scope) {
  76. for(var i = 0, len = this.length; i < len; ++i) {
  77. fn.call(scope || this, this[i], i, this);
  78. }
  79. }
  80. }
  81. // Internet Explorer 8 and older does not support Array.map, so we define it
  82. // here in that case.
  83. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map
  84. // Production steps of ECMA-262, Edition 5, 15.4.4.19
  85. // Reference: http://es5.github.com/#x15.4.4.19
  86. if (!Array.prototype.map) {
  87. Array.prototype.map = function(callback, thisArg) {
  88. var T, A, k;
  89. if (this == null) {
  90. throw new TypeError(" this is null or not defined");
  91. }
  92. // 1. Let O be the result of calling ToObject passing the |this| value as the argument.
  93. var O = Object(this);
  94. // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
  95. // 3. Let len be ToUint32(lenValue).
  96. var len = O.length >>> 0;
  97. // 4. If IsCallable(callback) is false, throw a TypeError exception.
  98. // See: http://es5.github.com/#x9.11
  99. if (typeof callback !== "function") {
  100. throw new TypeError(callback + " is not a function");
  101. }
  102. // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
  103. if (thisArg) {
  104. T = thisArg;
  105. }
  106. // 6. Let A be a new array created as if by the expression new Array(len) where Array is
  107. // the standard built-in constructor with that name and len is the value of len.
  108. A = new Array(len);
  109. // 7. Let k be 0
  110. k = 0;
  111. // 8. Repeat, while k < len
  112. while(k < len) {
  113. var kValue, mappedValue;
  114. // a. Let Pk be ToString(k).
  115. // This is implicit for LHS operands of the in operator
  116. // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
  117. // This step can be combined with c
  118. // c. If kPresent is true, then
  119. if (k in O) {
  120. // i. Let kValue be the result of calling the Get internal method of O with argument Pk.
  121. kValue = O[ k ];
  122. // ii. Let mappedValue be the result of calling the Call internal method of callback
  123. // with T as the this value and argument list containing kValue, k, and O.
  124. mappedValue = callback.call(T, kValue, k, O);
  125. // iii. Call the DefineOwnProperty internal method of A with arguments
  126. // Pk, Property Descriptor {Value: mappedValue, : true, Enumerable: true, Configurable: true},
  127. // and false.
  128. // In browsers that support Object.defineProperty, use the following:
  129. // Object.defineProperty(A, Pk, { value: mappedValue, writable: true, enumerable: true, configurable: true });
  130. // For best browser support, use the following:
  131. A[ k ] = mappedValue;
  132. }
  133. // d. Increase k by 1.
  134. k++;
  135. }
  136. // 9. return A
  137. return A;
  138. };
  139. }
  140. // Internet Explorer 8 and older does not support Array.filter, so we define it
  141. // here in that case.
  142. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter
  143. if (!Array.prototype.filter) {
  144. Array.prototype.filter = function(fun /*, thisp */) {
  145. "use strict";
  146. if (this == null) {
  147. throw new TypeError();
  148. }
  149. var t = Object(this);
  150. var len = t.length >>> 0;
  151. if (typeof fun != "function") {
  152. throw new TypeError();
  153. }
  154. var res = [];
  155. var thisp = arguments[1];
  156. for (var i = 0; i < len; i++) {
  157. if (i in t) {
  158. var val = t[i]; // in case fun mutates this
  159. if (fun.call(thisp, val, i, t))
  160. res.push(val);
  161. }
  162. }
  163. return res;
  164. };
  165. }
  166. // Internet Explorer 8 and older does not support Object.keys, so we define it
  167. // here in that case.
  168. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/keys
  169. if (!Object.keys) {
  170. Object.keys = (function () {
  171. var hasOwnProperty = Object.prototype.hasOwnProperty,
  172. hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
  173. dontEnums = [
  174. 'toString',
  175. 'toLocaleString',
  176. 'valueOf',
  177. 'hasOwnProperty',
  178. 'isPrototypeOf',
  179. 'propertyIsEnumerable',
  180. 'constructor'
  181. ],
  182. dontEnumsLength = dontEnums.length;
  183. return function (obj) {
  184. if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) {
  185. throw new TypeError('Object.keys called on non-object');
  186. }
  187. var result = [];
  188. for (var prop in obj) {
  189. if (hasOwnProperty.call(obj, prop)) result.push(prop);
  190. }
  191. if (hasDontEnumBug) {
  192. for (var i=0; i < dontEnumsLength; i++) {
  193. if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
  194. }
  195. }
  196. return result;
  197. }
  198. })()
  199. }
  200. // Internet Explorer 8 and older does not support Array.isArray,
  201. // so we define it here in that case.
  202. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/isArray
  203. if(!Array.isArray) {
  204. Array.isArray = function (vArg) {
  205. return Object.prototype.toString.call(vArg) === "[object Array]";
  206. };
  207. }
  208. // Internet Explorer 8 and older does not support Function.bind,
  209. // so we define it here in that case.
  210. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind
  211. if (!Function.prototype.bind) {
  212. Function.prototype.bind = function (oThis) {
  213. if (typeof this !== "function") {
  214. // closest thing possible to the ECMAScript 5 internal IsCallable function
  215. throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
  216. }
  217. var aArgs = Array.prototype.slice.call(arguments, 1),
  218. fToBind = this,
  219. fNOP = function () {},
  220. fBound = function () {
  221. return fToBind.apply(this instanceof fNOP && oThis
  222. ? this
  223. : oThis,
  224. aArgs.concat(Array.prototype.slice.call(arguments)));
  225. };
  226. fNOP.prototype = this.prototype;
  227. fBound.prototype = new fNOP();
  228. return fBound;
  229. };
  230. }
  231. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create
  232. if (!Object.create) {
  233. Object.create = function (o) {
  234. if (arguments.length > 1) {
  235. throw new Error('Object.create implementation only accepts the first parameter.');
  236. }
  237. function F() {}
  238. F.prototype = o;
  239. return new F();
  240. };
  241. }
  242. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
  243. if (!Function.prototype.bind) {
  244. Function.prototype.bind = function (oThis) {
  245. if (typeof this !== "function") {
  246. // closest thing possible to the ECMAScript 5 internal IsCallable function
  247. throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
  248. }
  249. var aArgs = Array.prototype.slice.call(arguments, 1),
  250. fToBind = this,
  251. fNOP = function () {},
  252. fBound = function () {
  253. return fToBind.apply(this instanceof fNOP && oThis
  254. ? this
  255. : oThis,
  256. aArgs.concat(Array.prototype.slice.call(arguments)));
  257. };
  258. fNOP.prototype = this.prototype;
  259. fBound.prototype = new fNOP();
  260. return fBound;
  261. };
  262. }
  263. /**
  264. * utility functions
  265. */
  266. var util = {};
  267. /**
  268. * Test whether given object is a number
  269. * @param {*} object
  270. * @return {Boolean} isNumber
  271. */
  272. util.isNumber = function isNumber(object) {
  273. return (object instanceof Number || typeof object == 'number');
  274. };
  275. /**
  276. * Test whether given object is a string
  277. * @param {*} object
  278. * @return {Boolean} isString
  279. */
  280. util.isString = function isString(object) {
  281. return (object instanceof String || typeof object == 'string');
  282. };
  283. /**
  284. * Test whether given object is a Date, or a String containing a Date
  285. * @param {Date | String} object
  286. * @return {Boolean} isDate
  287. */
  288. util.isDate = function isDate(object) {
  289. if (object instanceof Date) {
  290. return true;
  291. }
  292. else if (util.isString(object)) {
  293. // test whether this string contains a date
  294. var match = ASPDateRegex.exec(object);
  295. if (match) {
  296. return true;
  297. }
  298. else if (!isNaN(Date.parse(object))) {
  299. return true;
  300. }
  301. }
  302. return false;
  303. };
  304. /**
  305. * Test whether given object is an instance of google.visualization.DataTable
  306. * @param {*} object
  307. * @return {Boolean} isDataTable
  308. */
  309. util.isDataTable = function isDataTable(object) {
  310. return (typeof (google) !== 'undefined') &&
  311. (google.visualization) &&
  312. (google.visualization.DataTable) &&
  313. (object instanceof google.visualization.DataTable);
  314. };
  315. /**
  316. * Create a semi UUID
  317. * source: http://stackoverflow.com/a/105074/1262753
  318. * @return {String} uuid
  319. */
  320. util.randomUUID = function randomUUID () {
  321. var S4 = function () {
  322. return Math.floor(
  323. Math.random() * 0x10000 /* 65536 */
  324. ).toString(16);
  325. };
  326. return (
  327. S4() + S4() + '-' +
  328. S4() + '-' +
  329. S4() + '-' +
  330. S4() + '-' +
  331. S4() + S4() + S4()
  332. );
  333. };
  334. /**
  335. * Extend object a with the properties of object b or a series of objects
  336. * Only properties with defined values are copied
  337. * @param {Object} a
  338. * @param {... Object} b
  339. * @return {Object} a
  340. */
  341. util.extend = function (a, b) {
  342. for (var i = 1, len = arguments.length; i < len; i++) {
  343. var other = arguments[i];
  344. for (var prop in other) {
  345. if (other.hasOwnProperty(prop) && other[prop] !== undefined) {
  346. a[prop] = other[prop];
  347. }
  348. }
  349. }
  350. return a;
  351. };
  352. /**
  353. * Test whether all elements in two arrays are equal.
  354. * @param {Array} a
  355. * @param {Array} b
  356. * @return {boolean} Returns true if both arrays have the same length and same
  357. * elements.
  358. */
  359. util.equalArray = function (a, b) {
  360. if (a.length != b.length) return false;
  361. for (var i = 0, len = a.length; i < len; i++) {
  362. if (a[i] != b[i]) return false;
  363. }
  364. return true;
  365. };
  366. /**
  367. * Convert an object to another type
  368. * @param {Boolean | Number | String | Date | Moment | Null | undefined} object
  369. * @param {String | undefined} type Name of the type. Available types:
  370. * 'Boolean', 'Number', 'String',
  371. * 'Date', 'Moment', ISODate', 'ASPDate'.
  372. * @return {*} object
  373. * @throws Error
  374. */
  375. util.convert = function convert(object, type) {
  376. var match;
  377. if (object === undefined) {
  378. return undefined;
  379. }
  380. if (object === null) {
  381. return null;
  382. }
  383. if (!type) {
  384. return object;
  385. }
  386. if (!(typeof type === 'string') && !(type instanceof String)) {
  387. throw new Error('Type must be a string');
  388. }
  389. //noinspection FallthroughInSwitchStatementJS
  390. switch (type) {
  391. case 'boolean':
  392. case 'Boolean':
  393. return Boolean(object);
  394. case 'number':
  395. case 'Number':
  396. return Number(object.valueOf());
  397. case 'string':
  398. case 'String':
  399. return String(object);
  400. case 'Date':
  401. if (util.isNumber(object)) {
  402. return new Date(object);
  403. }
  404. if (object instanceof Date) {
  405. return new Date(object.valueOf());
  406. }
  407. else if (moment.isMoment(object)) {
  408. return new Date(object.valueOf());
  409. }
  410. if (util.isString(object)) {
  411. match = ASPDateRegex.exec(object);
  412. if (match) {
  413. // object is an ASP date
  414. return new Date(Number(match[1])); // parse number
  415. }
  416. else {
  417. return moment(object).toDate(); // parse string
  418. }
  419. }
  420. else {
  421. throw new Error(
  422. 'Cannot convert object of type ' + util.getType(object) +
  423. ' to type Date');
  424. }
  425. case 'Moment':
  426. if (util.isNumber(object)) {
  427. return moment(object);
  428. }
  429. if (object instanceof Date) {
  430. return moment(object.valueOf());
  431. }
  432. else if (moment.isMoment(object)) {
  433. return moment(object);
  434. }
  435. if (util.isString(object)) {
  436. match = ASPDateRegex.exec(object);
  437. if (match) {
  438. // object is an ASP date
  439. return moment(Number(match[1])); // parse number
  440. }
  441. else {
  442. return moment(object); // parse string
  443. }
  444. }
  445. else {
  446. throw new Error(
  447. 'Cannot convert object of type ' + util.getType(object) +
  448. ' to type Date');
  449. }
  450. case 'ISODate':
  451. if (util.isNumber(object)) {
  452. return new Date(object);
  453. }
  454. else if (object instanceof Date) {
  455. return object.toISOString();
  456. }
  457. else if (moment.isMoment(object)) {
  458. return object.toDate().toISOString();
  459. }
  460. else if (util.isString(object)) {
  461. match = ASPDateRegex.exec(object);
  462. if (match) {
  463. // object is an ASP date
  464. return new Date(Number(match[1])).toISOString(); // parse number
  465. }
  466. else {
  467. return new Date(object).toISOString(); // parse string
  468. }
  469. }
  470. else {
  471. throw new Error(
  472. 'Cannot convert object of type ' + util.getType(object) +
  473. ' to type ISODate');
  474. }
  475. case 'ASPDate':
  476. if (util.isNumber(object)) {
  477. return '/Date(' + object + ')/';
  478. }
  479. else if (object instanceof Date) {
  480. return '/Date(' + object.valueOf() + ')/';
  481. }
  482. else if (util.isString(object)) {
  483. match = ASPDateRegex.exec(object);
  484. var value;
  485. if (match) {
  486. // object is an ASP date
  487. value = new Date(Number(match[1])).valueOf(); // parse number
  488. }
  489. else {
  490. value = new Date(object).valueOf(); // parse string
  491. }
  492. return '/Date(' + value + ')/';
  493. }
  494. else {
  495. throw new Error(
  496. 'Cannot convert object of type ' + util.getType(object) +
  497. ' to type ASPDate');
  498. }
  499. default:
  500. throw new Error('Cannot convert object of type ' + util.getType(object) +
  501. ' to type "' + type + '"');
  502. }
  503. };
  504. // parse ASP.Net Date pattern,
  505. // for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/'
  506. // code from http://momentjs.com/
  507. var ASPDateRegex = /^\/?Date\((\-?\d+)/i;
  508. /**
  509. * Get the type of an object, for example util.getType([]) returns 'Array'
  510. * @param {*} object
  511. * @return {String} type
  512. */
  513. util.getType = function getType(object) {
  514. var type = typeof object;
  515. if (type == 'object') {
  516. if (object == null) {
  517. return 'null';
  518. }
  519. if (object instanceof Boolean) {
  520. return 'Boolean';
  521. }
  522. if (object instanceof Number) {
  523. return 'Number';
  524. }
  525. if (object instanceof String) {
  526. return 'String';
  527. }
  528. if (object instanceof Array) {
  529. return 'Array';
  530. }
  531. if (object instanceof Date) {
  532. return 'Date';
  533. }
  534. return 'Object';
  535. }
  536. else if (type == 'number') {
  537. return 'Number';
  538. }
  539. else if (type == 'boolean') {
  540. return 'Boolean';
  541. }
  542. else if (type == 'string') {
  543. return 'String';
  544. }
  545. return type;
  546. };
  547. /**
  548. * Retrieve the absolute left value of a DOM element
  549. * @param {Element} elem A dom element, for example a div
  550. * @return {number} left The absolute left position of this element
  551. * in the browser page.
  552. */
  553. util.getAbsoluteLeft = function getAbsoluteLeft (elem) {
  554. var doc = document.documentElement;
  555. var body = document.body;
  556. var left = elem.offsetLeft;
  557. var e = elem.offsetParent;
  558. while (e != null && e != body && e != doc) {
  559. left += e.offsetLeft;
  560. left -= e.scrollLeft;
  561. e = e.offsetParent;
  562. }
  563. return left;
  564. };
  565. /**
  566. * Retrieve the absolute top value of a DOM element
  567. * @param {Element} elem A dom element, for example a div
  568. * @return {number} top The absolute top position of this element
  569. * in the browser page.
  570. */
  571. util.getAbsoluteTop = function getAbsoluteTop (elem) {
  572. var doc = document.documentElement;
  573. var body = document.body;
  574. var top = elem.offsetTop;
  575. var e = elem.offsetParent;
  576. while (e != null && e != body && e != doc) {
  577. top += e.offsetTop;
  578. top -= e.scrollTop;
  579. e = e.offsetParent;
  580. }
  581. return top;
  582. };
  583. /**
  584. * Get the absolute, vertical mouse position from an event.
  585. * @param {Event} event
  586. * @return {Number} pageY
  587. */
  588. util.getPageY = function getPageY (event) {
  589. if ('pageY' in event) {
  590. return event.pageY;
  591. }
  592. else {
  593. var clientY;
  594. if (('targetTouches' in event) && event.targetTouches.length) {
  595. clientY = event.targetTouches[0].clientY;
  596. }
  597. else {
  598. clientY = event.clientY;
  599. }
  600. var doc = document.documentElement;
  601. var body = document.body;
  602. return clientY +
  603. ( doc && doc.scrollTop || body && body.scrollTop || 0 ) -
  604. ( doc && doc.clientTop || body && body.clientTop || 0 );
  605. }
  606. };
  607. /**
  608. * Get the absolute, horizontal mouse position from an event.
  609. * @param {Event} event
  610. * @return {Number} pageX
  611. */
  612. util.getPageX = function getPageX (event) {
  613. if ('pageY' in event) {
  614. return event.pageX;
  615. }
  616. else {
  617. var clientX;
  618. if (('targetTouches' in event) && event.targetTouches.length) {
  619. clientX = event.targetTouches[0].clientX;
  620. }
  621. else {
  622. clientX = event.clientX;
  623. }
  624. var doc = document.documentElement;
  625. var body = document.body;
  626. return clientX +
  627. ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) -
  628. ( doc && doc.clientLeft || body && body.clientLeft || 0 );
  629. }
  630. };
  631. /**
  632. * add a className to the given elements style
  633. * @param {Element} elem
  634. * @param {String} className
  635. */
  636. util.addClassName = function addClassName(elem, className) {
  637. var classes = elem.className.split(' ');
  638. if (classes.indexOf(className) == -1) {
  639. classes.push(className); // add the class to the array
  640. elem.className = classes.join(' ');
  641. }
  642. };
  643. /**
  644. * add a className to the given elements style
  645. * @param {Element} elem
  646. * @param {String} className
  647. */
  648. util.removeClassName = function removeClassname(elem, className) {
  649. var classes = elem.className.split(' ');
  650. var index = classes.indexOf(className);
  651. if (index != -1) {
  652. classes.splice(index, 1); // remove the class from the array
  653. elem.className = classes.join(' ');
  654. }
  655. };
  656. /**
  657. * For each method for both arrays and objects.
  658. * In case of an array, the built-in Array.forEach() is applied.
  659. * In case of an Object, the method loops over all properties of the object.
  660. * @param {Object | Array} object An Object or Array
  661. * @param {function} callback Callback method, called for each item in
  662. * the object or array with three parameters:
  663. * callback(value, index, object)
  664. */
  665. util.forEach = function forEach (object, callback) {
  666. var i,
  667. len;
  668. if (object instanceof Array) {
  669. // array
  670. for (i = 0, len = object.length; i < len; i++) {
  671. callback(object[i], i, object);
  672. }
  673. }
  674. else {
  675. // object
  676. for (i in object) {
  677. if (object.hasOwnProperty(i)) {
  678. callback(object[i], i, object);
  679. }
  680. }
  681. }
  682. };
  683. /**
  684. * Convert an object into an array: all objects properties are put into the
  685. * array. The resulting array is unordered.
  686. * @param {Object} object
  687. * @param {Array} array
  688. */
  689. util.toArray = function toArray(object) {
  690. var array = [];
  691. for (var prop in object) {
  692. if (object.hasOwnProperty(prop)) array.push(object[prop]);
  693. }
  694. return array;
  695. }
  696. /**
  697. * Update a property in an object
  698. * @param {Object} object
  699. * @param {String} key
  700. * @param {*} value
  701. * @return {Boolean} changed
  702. */
  703. util.updateProperty = function updateProperty (object, key, value) {
  704. if (object[key] !== value) {
  705. object[key] = value;
  706. return true;
  707. }
  708. else {
  709. return false;
  710. }
  711. };
  712. /**
  713. * Add and event listener. Works for all browsers
  714. * @param {Element} element An html element
  715. * @param {string} action The action, for example "click",
  716. * without the prefix "on"
  717. * @param {function} listener The callback function to be executed
  718. * @param {boolean} [useCapture]
  719. */
  720. util.addEventListener = function addEventListener(element, action, listener, useCapture) {
  721. if (element.addEventListener) {
  722. if (useCapture === undefined)
  723. useCapture = false;
  724. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  725. action = "DOMMouseScroll"; // For Firefox
  726. }
  727. element.addEventListener(action, listener, useCapture);
  728. } else {
  729. element.attachEvent("on" + action, listener); // IE browsers
  730. }
  731. };
  732. /**
  733. * Remove an event listener from an element
  734. * @param {Element} element An html dom element
  735. * @param {string} action The name of the event, for example "mousedown"
  736. * @param {function} listener The listener function
  737. * @param {boolean} [useCapture]
  738. */
  739. util.removeEventListener = function removeEventListener(element, action, listener, useCapture) {
  740. if (element.removeEventListener) {
  741. // non-IE browsers
  742. if (useCapture === undefined)
  743. useCapture = false;
  744. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  745. action = "DOMMouseScroll"; // For Firefox
  746. }
  747. element.removeEventListener(action, listener, useCapture);
  748. } else {
  749. // IE browsers
  750. element.detachEvent("on" + action, listener);
  751. }
  752. };
  753. /**
  754. * Get HTML element which is the target of the event
  755. * @param {Event} event
  756. * @return {Element} target element
  757. */
  758. util.getTarget = function getTarget(event) {
  759. // code from http://www.quirksmode.org/js/events_properties.html
  760. if (!event) {
  761. event = window.event;
  762. }
  763. var target;
  764. if (event.target) {
  765. target = event.target;
  766. }
  767. else if (event.srcElement) {
  768. target = event.srcElement;
  769. }
  770. if (target.nodeType != undefined && target.nodeType == 3) {
  771. // defeat Safari bug
  772. target = target.parentNode;
  773. }
  774. return target;
  775. };
  776. /**
  777. * Fake a hammer.js gesture. Event can be a ScrollEvent or MouseMoveEvent
  778. * @param {Element} element
  779. * @param {Event} event
  780. */
  781. util.fakeGesture = function fakeGesture (element, event) {
  782. var eventType = null;
  783. // for hammer.js 1.0.5
  784. var gesture = Hammer.event.collectEventData(this, eventType, event);
  785. // for hammer.js 1.0.6
  786. //var touches = Hammer.event.getTouchList(event, eventType);
  787. // var gesture = Hammer.event.collectEventData(this, eventType, touches, event);
  788. // on IE in standards mode, no touches are recognized by hammer.js,
  789. // resulting in NaN values for center.pageX and center.pageY
  790. if (isNaN(gesture.center.pageX)) {
  791. gesture.center.pageX = event.pageX;
  792. }
  793. if (isNaN(gesture.center.pageY)) {
  794. gesture.center.pageY = event.pageY;
  795. }
  796. return gesture;
  797. };
  798. util.option = {};
  799. /**
  800. * Convert a value into a boolean
  801. * @param {Boolean | function | undefined} value
  802. * @param {Boolean} [defaultValue]
  803. * @returns {Boolean} bool
  804. */
  805. util.option.asBoolean = function (value, defaultValue) {
  806. if (typeof value == 'function') {
  807. value = value();
  808. }
  809. if (value != null) {
  810. return (value != false);
  811. }
  812. return defaultValue || null;
  813. };
  814. /**
  815. * Convert a value into a number
  816. * @param {Boolean | function | undefined} value
  817. * @param {Number} [defaultValue]
  818. * @returns {Number} number
  819. */
  820. util.option.asNumber = function (value, defaultValue) {
  821. if (typeof value == 'function') {
  822. value = value();
  823. }
  824. if (value != null) {
  825. return Number(value) || defaultValue || null;
  826. }
  827. return defaultValue || null;
  828. };
  829. /**
  830. * Convert a value into a string
  831. * @param {String | function | undefined} value
  832. * @param {String} [defaultValue]
  833. * @returns {String} str
  834. */
  835. util.option.asString = function (value, defaultValue) {
  836. if (typeof value == 'function') {
  837. value = value();
  838. }
  839. if (value != null) {
  840. return String(value);
  841. }
  842. return defaultValue || null;
  843. };
  844. /**
  845. * Convert a size or location into a string with pixels or a percentage
  846. * @param {String | Number | function | undefined} value
  847. * @param {String} [defaultValue]
  848. * @returns {String} size
  849. */
  850. util.option.asSize = function (value, defaultValue) {
  851. if (typeof value == 'function') {
  852. value = value();
  853. }
  854. if (util.isString(value)) {
  855. return value;
  856. }
  857. else if (util.isNumber(value)) {
  858. return value + 'px';
  859. }
  860. else {
  861. return defaultValue || null;
  862. }
  863. };
  864. /**
  865. * Convert a value into a DOM element
  866. * @param {HTMLElement | function | undefined} value
  867. * @param {HTMLElement} [defaultValue]
  868. * @returns {HTMLElement | null} dom
  869. */
  870. util.option.asElement = function (value, defaultValue) {
  871. if (typeof value == 'function') {
  872. value = value();
  873. }
  874. return value || defaultValue || null;
  875. };
  876. util.GiveDec = function GiveDec(Hex) {
  877. var Value;
  878. if (Hex == "A")
  879. Value = 10;
  880. else if (Hex == "B")
  881. Value = 11;
  882. else if (Hex == "C")
  883. Value = 12;
  884. else if (Hex == "D")
  885. Value = 13;
  886. else if (Hex == "E")
  887. Value = 14;
  888. else if (Hex == "F")
  889. Value = 15;
  890. else
  891. Value = eval(Hex);
  892. return Value;
  893. };
  894. util.GiveHex = function GiveHex(Dec) {
  895. var Value;
  896. if(Dec == 10)
  897. Value = "A";
  898. else if (Dec == 11)
  899. Value = "B";
  900. else if (Dec == 12)
  901. Value = "C";
  902. else if (Dec == 13)
  903. Value = "D";
  904. else if (Dec == 14)
  905. Value = "E";
  906. else if (Dec == 15)
  907. Value = "F";
  908. else
  909. Value = "" + Dec;
  910. return Value;
  911. };
  912. /**
  913. * Parse a color property into an object with border, background, and
  914. * highlight colors
  915. * @param {Object | String} color
  916. * @return {Object} colorObject
  917. */
  918. util.parseColor = function(color) {
  919. var c;
  920. if (util.isString(color)) {
  921. if (util.isValidHex(color)) {
  922. var hsv = util.hexToHSV(color);
  923. var lighterColorHSV = {h:hsv.h,s:hsv.s * 0.45,v:Math.min(1,hsv.v * 1.05)};
  924. var darkerColorHSV = {h:hsv.h,s:Math.min(1,hsv.v * 1.25),v:hsv.v*0.6};
  925. var darkerColorHex = util.HSVToHex(darkerColorHSV.h ,darkerColorHSV.h ,darkerColorHSV.v);
  926. var lighterColorHex = util.HSVToHex(lighterColorHSV.h,lighterColorHSV.s,lighterColorHSV.v);
  927. c = {
  928. background: color,
  929. border:darkerColorHex,
  930. highlight: {
  931. background:lighterColorHex,
  932. border:darkerColorHex
  933. }
  934. };
  935. }
  936. else {
  937. c = {
  938. background:color,
  939. border:color,
  940. highlight: {
  941. background:color,
  942. border:color
  943. }
  944. };
  945. }
  946. }
  947. else {
  948. c = {};
  949. c.background = color.background || 'white';
  950. c.border = color.border || c.background;
  951. if (util.isString(color.highlight)) {
  952. c.highlight = {
  953. border: color.highlight,
  954. background: color.highlight
  955. }
  956. }
  957. else {
  958. c.highlight = {};
  959. c.highlight.background = color.highlight && color.highlight.background || c.background;
  960. c.highlight.border = color.highlight && color.highlight.border || c.border;
  961. }
  962. }
  963. return c;
  964. };
  965. /**
  966. * http://www.yellowpipe.com/yis/tools/hex-to-rgb/color-converter.php
  967. *
  968. * @param {String} hex
  969. * @returns {{r: *, g: *, b: *}}
  970. */
  971. util.hexToRGB = function hexToRGB(hex) {
  972. hex = hex.replace("#","").toUpperCase();
  973. var a = util.GiveDec(hex.substring(0, 1));
  974. var b = util.GiveDec(hex.substring(1, 2));
  975. var c = util.GiveDec(hex.substring(2, 3));
  976. var d = util.GiveDec(hex.substring(3, 4));
  977. var e = util.GiveDec(hex.substring(4, 5));
  978. var f = util.GiveDec(hex.substring(5, 6));
  979. var r = (a * 16) + b;
  980. var g = (c * 16) + d;
  981. var b = (e * 16) + f;
  982. return {r:r,g:g,b:b};
  983. };
  984. util.RGBToHex = function RGBToHex(red,green,blue) {
  985. var a = util.GiveHex(Math.floor(red / 16));
  986. var b = util.GiveHex(red % 16);
  987. var c = util.GiveHex(Math.floor(green / 16));
  988. var d = util.GiveHex(green % 16);
  989. var e = util.GiveHex(Math.floor(blue / 16));
  990. var f = util.GiveHex(blue % 16);
  991. var hex = a + b + c + d + e + f;
  992. return "#" + hex;
  993. };
  994. /**
  995. * http://www.javascripter.net/faq/rgb2hsv.htm
  996. *
  997. * @param red
  998. * @param green
  999. * @param blue
  1000. * @returns {*}
  1001. * @constructor
  1002. */
  1003. util.RGBToHSV = function RGBToHSV (red,green,blue) {
  1004. red=red/255; green=green/255; blue=blue/255;
  1005. var minRGB = Math.min(red,Math.min(green,blue));
  1006. var maxRGB = Math.max(red,Math.max(green,blue));
  1007. // Black-gray-white
  1008. if (minRGB == maxRGB) {
  1009. return {h:0,s:0,v:minRGB};
  1010. }
  1011. // Colors other than black-gray-white:
  1012. var d = (red==minRGB) ? green-blue : ((blue==minRGB) ? red-green : blue-red);
  1013. var h = (red==minRGB) ? 3 : ((blue==minRGB) ? 1 : 5);
  1014. var hue = 60*(h - d/(maxRGB - minRGB))/360;
  1015. var saturation = (maxRGB - minRGB)/maxRGB;
  1016. var value = maxRGB;
  1017. return {h:hue,s:saturation,v:value};
  1018. };
  1019. /**
  1020. * https://gist.github.com/mjijackson/5311256
  1021. * @param hue
  1022. * @param saturation
  1023. * @param value
  1024. * @returns {{r: number, g: number, b: number}}
  1025. * @constructor
  1026. */
  1027. util.HSVToRGB = function HSVToRGB(h, s, v) {
  1028. var r, g, b;
  1029. var i = Math.floor(h * 6);
  1030. var f = h * 6 - i;
  1031. var p = v * (1 - s);
  1032. var q = v * (1 - f * s);
  1033. var t = v * (1 - (1 - f) * s);
  1034. switch (i % 6) {
  1035. case 0: r = v, g = t, b = p; break;
  1036. case 1: r = q, g = v, b = p; break;
  1037. case 2: r = p, g = v, b = t; break;
  1038. case 3: r = p, g = q, b = v; break;
  1039. case 4: r = t, g = p, b = v; break;
  1040. case 5: r = v, g = p, b = q; break;
  1041. }
  1042. return {r:Math.floor(r * 255), g:Math.floor(g * 255), b:Math.floor(b * 255) };
  1043. };
  1044. util.HSVToHex = function HSVToHex(h, s, v) {
  1045. var rgb = util.HSVToRGB(h, s, v);
  1046. return util.RGBToHex(rgb.r, rgb.g, rgb.b);
  1047. };
  1048. util.hexToHSV = function hexToHSV(hex) {
  1049. var rgb = util.hexToRGB(hex);
  1050. return util.RGBToHSV(rgb.r, rgb.g, rgb.b);
  1051. };
  1052. util.isValidHex = function isValidHex(hex) {
  1053. var isOk = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(hex);
  1054. return isOk;
  1055. };
  1056. util.copyObject = function copyObject(objectFrom, objectTo) {
  1057. for (var i in objectFrom) {
  1058. if (objectFrom.hasOwnProperty(i)) {
  1059. if (typeof objectFrom[i] == "object") {
  1060. objectTo[i] = {};
  1061. util.copyObject(objectFrom[i], objectTo[i]);
  1062. }
  1063. else {
  1064. objectTo[i] = objectFrom[i];
  1065. }
  1066. }
  1067. }
  1068. };
  1069. /**
  1070. * DataSet
  1071. *
  1072. * Usage:
  1073. * var dataSet = new DataSet({
  1074. * fieldId: '_id',
  1075. * convert: {
  1076. * // ...
  1077. * }
  1078. * });
  1079. *
  1080. * dataSet.add(item);
  1081. * dataSet.add(data);
  1082. * dataSet.update(item);
  1083. * dataSet.update(data);
  1084. * dataSet.remove(id);
  1085. * dataSet.remove(ids);
  1086. * var data = dataSet.get();
  1087. * var data = dataSet.get(id);
  1088. * var data = dataSet.get(ids);
  1089. * var data = dataSet.get(ids, options, data);
  1090. * dataSet.clear();
  1091. *
  1092. * A data set can:
  1093. * - add/remove/update data
  1094. * - gives triggers upon changes in the data
  1095. * - can import/export data in various data formats
  1096. *
  1097. * @param {Array | DataTable} [data] Optional array with initial data
  1098. * @param {Object} [options] Available options:
  1099. * {String} fieldId Field name of the id in the
  1100. * items, 'id' by default.
  1101. * {Object.<String, String} convert
  1102. * A map with field names as key,
  1103. * and the field type as value.
  1104. * @constructor DataSet
  1105. */
  1106. // TODO: add a DataSet constructor DataSet(data, options)
  1107. function DataSet (data, options) {
  1108. this.id = util.randomUUID();
  1109. // correctly read optional arguments
  1110. if (data && !Array.isArray(data) && !util.isDataTable(data)) {
  1111. options = data;
  1112. data = null;
  1113. }
  1114. this.options = options || {};
  1115. this.data = {}; // map with data indexed by id
  1116. this.fieldId = this.options.fieldId || 'id'; // name of the field containing id
  1117. this.convert = {}; // field types by field name
  1118. this.showInternalIds = this.options.showInternalIds || false; // show internal ids with the get function
  1119. if (this.options.convert) {
  1120. for (var field in this.options.convert) {
  1121. if (this.options.convert.hasOwnProperty(field)) {
  1122. var value = this.options.convert[field];
  1123. if (value == 'Date' || value == 'ISODate' || value == 'ASPDate') {
  1124. this.convert[field] = 'Date';
  1125. }
  1126. else {
  1127. this.convert[field] = value;
  1128. }
  1129. }
  1130. }
  1131. }
  1132. this.subscribers = {}; // event subscribers
  1133. this.internalIds = {}; // internally generated id's
  1134. // add initial data when provided
  1135. if (data) {
  1136. this.add(data);
  1137. }
  1138. }
  1139. /**
  1140. * Subscribe to an event, add an event listener
  1141. * @param {String} event Event name. Available events: 'put', 'update',
  1142. * 'remove'
  1143. * @param {function} callback Callback method. Called with three parameters:
  1144. * {String} event
  1145. * {Object | null} params
  1146. * {String | Number} senderId
  1147. */
  1148. DataSet.prototype.on = function on (event, callback) {
  1149. var subscribers = this.subscribers[event];
  1150. if (!subscribers) {
  1151. subscribers = [];
  1152. this.subscribers[event] = subscribers;
  1153. }
  1154. subscribers.push({
  1155. callback: callback
  1156. });
  1157. };
  1158. // TODO: make this function deprecated (replaced with `on` since version 0.5)
  1159. DataSet.prototype.subscribe = DataSet.prototype.on;
  1160. /**
  1161. * Unsubscribe from an event, remove an event listener
  1162. * @param {String} event
  1163. * @param {function} callback
  1164. */
  1165. DataSet.prototype.off = function off(event, callback) {
  1166. var subscribers = this.subscribers[event];
  1167. if (subscribers) {
  1168. this.subscribers[event] = subscribers.filter(function (listener) {
  1169. return (listener.callback != callback);
  1170. });
  1171. }
  1172. };
  1173. // TODO: make this function deprecated (replaced with `on` since version 0.5)
  1174. DataSet.prototype.unsubscribe = DataSet.prototype.off;
  1175. /**
  1176. * Trigger an event
  1177. * @param {String} event
  1178. * @param {Object | null} params
  1179. * @param {String} [senderId] Optional id of the sender.
  1180. * @private
  1181. */
  1182. DataSet.prototype._trigger = function (event, params, senderId) {
  1183. if (event == '*') {
  1184. throw new Error('Cannot trigger event *');
  1185. }
  1186. var subscribers = [];
  1187. if (event in this.subscribers) {
  1188. subscribers = subscribers.concat(this.subscribers[event]);
  1189. }
  1190. if ('*' in this.subscribers) {
  1191. subscribers = subscribers.concat(this.subscribers['*']);
  1192. }
  1193. for (var i = 0; i < subscribers.length; i++) {
  1194. var subscriber = subscribers[i];
  1195. if (subscriber.callback) {
  1196. subscriber.callback(event, params, senderId || null);
  1197. }
  1198. }
  1199. };
  1200. /**
  1201. * Add data.
  1202. * Adding an item will fail when there already is an item with the same id.
  1203. * @param {Object | Array | DataTable} data
  1204. * @param {String} [senderId] Optional sender id
  1205. * @return {Array} addedIds Array with the ids of the added items
  1206. */
  1207. DataSet.prototype.add = function (data, senderId) {
  1208. var addedIds = [],
  1209. id,
  1210. me = this;
  1211. if (data instanceof Array) {
  1212. // Array
  1213. for (var i = 0, len = data.length; i < len; i++) {
  1214. id = me._addItem(data[i]);
  1215. addedIds.push(id);
  1216. }
  1217. }
  1218. else if (util.isDataTable(data)) {
  1219. // Google DataTable
  1220. var columns = this._getColumnNames(data);
  1221. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1222. var item = {};
  1223. for (var col = 0, cols = columns.length; col < cols; col++) {
  1224. var field = columns[col];
  1225. item[field] = data.getValue(row, col);
  1226. }
  1227. id = me._addItem(item);
  1228. addedIds.push(id);
  1229. }
  1230. }
  1231. else if (data instanceof Object) {
  1232. // Single item
  1233. id = me._addItem(data);
  1234. addedIds.push(id);
  1235. }
  1236. else {
  1237. throw new Error('Unknown dataType');
  1238. }
  1239. if (addedIds.length) {
  1240. this._trigger('add', {items: addedIds}, senderId);
  1241. }
  1242. return addedIds;
  1243. };
  1244. /**
  1245. * Update existing items. When an item does not exist, it will be created
  1246. * @param {Object | Array | DataTable} data
  1247. * @param {String} [senderId] Optional sender id
  1248. * @return {Array} updatedIds The ids of the added or updated items
  1249. */
  1250. DataSet.prototype.update = function (data, senderId) {
  1251. var addedIds = [],
  1252. updatedIds = [],
  1253. me = this,
  1254. fieldId = me.fieldId;
  1255. var addOrUpdate = function (item) {
  1256. var id = item[fieldId];
  1257. if (me.data[id]) {
  1258. // update item
  1259. id = me._updateItem(item);
  1260. updatedIds.push(id);
  1261. }
  1262. else {
  1263. // add new item
  1264. id = me._addItem(item);
  1265. addedIds.push(id);
  1266. }
  1267. };
  1268. if (data instanceof Array) {
  1269. // Array
  1270. for (var i = 0, len = data.length; i < len; i++) {
  1271. addOrUpdate(data[i]);
  1272. }
  1273. }
  1274. else if (util.isDataTable(data)) {
  1275. // Google DataTable
  1276. var columns = this._getColumnNames(data);
  1277. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1278. var item = {};
  1279. for (var col = 0, cols = columns.length; col < cols; col++) {
  1280. var field = columns[col];
  1281. item[field] = data.getValue(row, col);
  1282. }
  1283. addOrUpdate(item);
  1284. }
  1285. }
  1286. else if (data instanceof Object) {
  1287. // Single item
  1288. addOrUpdate(data);
  1289. }
  1290. else {
  1291. throw new Error('Unknown dataType');
  1292. }
  1293. if (addedIds.length) {
  1294. this._trigger('add', {items: addedIds}, senderId);
  1295. }
  1296. if (updatedIds.length) {
  1297. this._trigger('update', {items: updatedIds}, senderId);
  1298. }
  1299. return addedIds.concat(updatedIds);
  1300. };
  1301. /**
  1302. * Get a data item or multiple items.
  1303. *
  1304. * Usage:
  1305. *
  1306. * get()
  1307. * get(options: Object)
  1308. * get(options: Object, data: Array | DataTable)
  1309. *
  1310. * get(id: Number | String)
  1311. * get(id: Number | String, options: Object)
  1312. * get(id: Number | String, options: Object, data: Array | DataTable)
  1313. *
  1314. * get(ids: Number[] | String[])
  1315. * get(ids: Number[] | String[], options: Object)
  1316. * get(ids: Number[] | String[], options: Object, data: Array | DataTable)
  1317. *
  1318. * Where:
  1319. *
  1320. * {Number | String} id The id of an item
  1321. * {Number[] | String{}} ids An array with ids of items
  1322. * {Object} options An Object with options. Available options:
  1323. * {String} [type] Type of data to be returned. Can
  1324. * be 'DataTable' or 'Array' (default)
  1325. * {Object.<String, String>} [convert]
  1326. * {String[]} [fields] field names to be returned
  1327. * {function} [filter] filter items
  1328. * {String | function} [order] Order the items by
  1329. * a field name or custom sort function.
  1330. * {Array | DataTable} [data] If provided, items will be appended to this
  1331. * array or table. Required in case of Google
  1332. * DataTable.
  1333. *
  1334. * @throws Error
  1335. */
  1336. DataSet.prototype.get = function (args) {
  1337. var me = this;
  1338. var globalShowInternalIds = this.showInternalIds;
  1339. // parse the arguments
  1340. var id, ids, options, data;
  1341. var firstType = util.getType(arguments[0]);
  1342. if (firstType == 'String' || firstType == 'Number') {
  1343. // get(id [, options] [, data])
  1344. id = arguments[0];
  1345. options = arguments[1];
  1346. data = arguments[2];
  1347. }
  1348. else if (firstType == 'Array') {
  1349. // get(ids [, options] [, data])
  1350. ids = arguments[0];
  1351. options = arguments[1];
  1352. data = arguments[2];
  1353. }
  1354. else {
  1355. // get([, options] [, data])
  1356. options = arguments[0];
  1357. data = arguments[1];
  1358. }
  1359. // determine the return type
  1360. var type;
  1361. if (options && options.type) {
  1362. type = (options.type == 'DataTable') ? 'DataTable' : 'Array';
  1363. if (data && (type != util.getType(data))) {
  1364. throw new Error('Type of parameter "data" (' + util.getType(data) + ') ' +
  1365. 'does not correspond with specified options.type (' + options.type + ')');
  1366. }
  1367. if (type == 'DataTable' && !util.isDataTable(data)) {
  1368. throw new Error('Parameter "data" must be a DataTable ' +
  1369. 'when options.type is "DataTable"');
  1370. }
  1371. }
  1372. else if (data) {
  1373. type = (util.getType(data) == 'DataTable') ? 'DataTable' : 'Array';
  1374. }
  1375. else {
  1376. type = 'Array';
  1377. }
  1378. // we allow the setting of this value for a single get request.
  1379. if (options != undefined) {
  1380. if (options.showInternalIds != undefined) {
  1381. this.showInternalIds = options.showInternalIds;
  1382. }
  1383. }
  1384. // build options
  1385. var convert = options && options.convert || this.options.convert;
  1386. var filter = options && options.filter;
  1387. var items = [], item, itemId, i, len;
  1388. // convert items
  1389. if (id != undefined) {
  1390. // return a single item
  1391. item = me._getItem(id, convert);
  1392. if (filter && !filter(item)) {
  1393. item = null;
  1394. }
  1395. }
  1396. else if (ids != undefined) {
  1397. // return a subset of items
  1398. for (i = 0, len = ids.length; i < len; i++) {
  1399. item = me._getItem(ids[i], convert);
  1400. if (!filter || filter(item)) {
  1401. items.push(item);
  1402. }
  1403. }
  1404. }
  1405. else {
  1406. // return all items
  1407. for (itemId in this.data) {
  1408. if (this.data.hasOwnProperty(itemId)) {
  1409. item = me._getItem(itemId, convert);
  1410. if (!filter || filter(item)) {
  1411. items.push(item);
  1412. }
  1413. }
  1414. }
  1415. }
  1416. // restore the global value of showInternalIds
  1417. this.showInternalIds = globalShowInternalIds;
  1418. // order the results
  1419. if (options && options.order && id == undefined) {
  1420. this._sort(items, options.order);
  1421. }
  1422. // filter fields of the items
  1423. if (options && options.fields) {
  1424. var fields = options.fields;
  1425. if (id != undefined) {
  1426. item = this._filterFields(item, fields);
  1427. }
  1428. else {
  1429. for (i = 0, len = items.length; i < len; i++) {
  1430. items[i] = this._filterFields(items[i], fields);
  1431. }
  1432. }
  1433. }
  1434. // return the results
  1435. if (type == 'DataTable') {
  1436. var columns = this._getColumnNames(data);
  1437. if (id != undefined) {
  1438. // append a single item to the data table
  1439. me._appendRow(data, columns, item);
  1440. }
  1441. else {
  1442. // copy the items to the provided data table
  1443. for (i = 0, len = items.length; i < len; i++) {
  1444. me._appendRow(data, columns, items[i]);
  1445. }
  1446. }
  1447. return data;
  1448. }
  1449. else {
  1450. // return an array
  1451. if (id != undefined) {
  1452. // a single item
  1453. return item;
  1454. }
  1455. else {
  1456. // multiple items
  1457. if (data) {
  1458. // copy the items to the provided array
  1459. for (i = 0, len = items.length; i < len; i++) {
  1460. data.push(items[i]);
  1461. }
  1462. return data;
  1463. }
  1464. else {
  1465. // just return our array
  1466. return items;
  1467. }
  1468. }
  1469. }
  1470. };
  1471. /**
  1472. * Get ids of all items or from a filtered set of items.
  1473. * @param {Object} [options] An Object with options. Available options:
  1474. * {function} [filter] filter items
  1475. * {String | function} [order] Order the items by
  1476. * a field name or custom sort function.
  1477. * @return {Array} ids
  1478. */
  1479. DataSet.prototype.getIds = function (options) {
  1480. var data = this.data,
  1481. filter = options && options.filter,
  1482. order = options && options.order,
  1483. convert = options && options.convert || this.options.convert,
  1484. i,
  1485. len,
  1486. id,
  1487. item,
  1488. items,
  1489. ids = [];
  1490. if (filter) {
  1491. // get filtered items
  1492. if (order) {
  1493. // create ordered list
  1494. items = [];
  1495. for (id in data) {
  1496. if (data.hasOwnProperty(id)) {
  1497. item = this._getItem(id, convert);
  1498. if (filter(item)) {
  1499. items.push(item);
  1500. }
  1501. }
  1502. }
  1503. this._sort(items, order);
  1504. for (i = 0, len = items.length; i < len; i++) {
  1505. ids[i] = items[i][this.fieldId];
  1506. }
  1507. }
  1508. else {
  1509. // create unordered list
  1510. for (id in data) {
  1511. if (data.hasOwnProperty(id)) {
  1512. item = this._getItem(id, convert);
  1513. if (filter(item)) {
  1514. ids.push(item[this.fieldId]);
  1515. }
  1516. }
  1517. }
  1518. }
  1519. }
  1520. else {
  1521. // get all items
  1522. if (order) {
  1523. // create an ordered list
  1524. items = [];
  1525. for (id in data) {
  1526. if (data.hasOwnProperty(id)) {
  1527. items.push(data[id]);
  1528. }
  1529. }
  1530. this._sort(items, order);
  1531. for (i = 0, len = items.length; i < len; i++) {
  1532. ids[i] = items[i][this.fieldId];
  1533. }
  1534. }
  1535. else {
  1536. // create unordered list
  1537. for (id in data) {
  1538. if (data.hasOwnProperty(id)) {
  1539. item = data[id];
  1540. ids.push(item[this.fieldId]);
  1541. }
  1542. }
  1543. }
  1544. }
  1545. return ids;
  1546. };
  1547. /**
  1548. * Execute a callback function for every item in the dataset.
  1549. * @param {function} callback
  1550. * @param {Object} [options] Available options:
  1551. * {Object.<String, String>} [convert]
  1552. * {String[]} [fields] filter fields
  1553. * {function} [filter] filter items
  1554. * {String | function} [order] Order the items by
  1555. * a field name or custom sort function.
  1556. */
  1557. DataSet.prototype.forEach = function (callback, options) {
  1558. var filter = options && options.filter,
  1559. convert = options && options.convert || this.options.convert,
  1560. data = this.data,
  1561. item,
  1562. id;
  1563. if (options && options.order) {
  1564. // execute forEach on ordered list
  1565. var items = this.get(options);
  1566. for (var i = 0, len = items.length; i < len; i++) {
  1567. item = items[i];
  1568. id = item[this.fieldId];
  1569. callback(item, id);
  1570. }
  1571. }
  1572. else {
  1573. // unordered
  1574. for (id in data) {
  1575. if (data.hasOwnProperty(id)) {
  1576. item = this._getItem(id, convert);
  1577. if (!filter || filter(item)) {
  1578. callback(item, id);
  1579. }
  1580. }
  1581. }
  1582. }
  1583. };
  1584. /**
  1585. * Map every item in the dataset.
  1586. * @param {function} callback
  1587. * @param {Object} [options] Available options:
  1588. * {Object.<String, String>} [convert]
  1589. * {String[]} [fields] filter fields
  1590. * {function} [filter] filter items
  1591. * {String | function} [order] Order the items by
  1592. * a field name or custom sort function.
  1593. * @return {Object[]} mappedItems
  1594. */
  1595. DataSet.prototype.map = function (callback, options) {
  1596. var filter = options && options.filter,
  1597. convert = options && options.convert || this.options.convert,
  1598. mappedItems = [],
  1599. data = this.data,
  1600. item;
  1601. // convert and filter items
  1602. for (var id in data) {
  1603. if (data.hasOwnProperty(id)) {
  1604. item = this._getItem(id, convert);
  1605. if (!filter || filter(item)) {
  1606. mappedItems.push(callback(item, id));
  1607. }
  1608. }
  1609. }
  1610. // order items
  1611. if (options && options.order) {
  1612. this._sort(mappedItems, options.order);
  1613. }
  1614. return mappedItems;
  1615. };
  1616. /**
  1617. * Filter the fields of an item
  1618. * @param {Object} item
  1619. * @param {String[]} fields Field names
  1620. * @return {Object} filteredItem
  1621. * @private
  1622. */
  1623. DataSet.prototype._filterFields = function (item, fields) {
  1624. var filteredItem = {};
  1625. for (var field in item) {
  1626. if (item.hasOwnProperty(field) && (fields.indexOf(field) != -1)) {
  1627. filteredItem[field] = item[field];
  1628. }
  1629. }
  1630. return filteredItem;
  1631. };
  1632. /**
  1633. * Sort the provided array with items
  1634. * @param {Object[]} items
  1635. * @param {String | function} order A field name or custom sort function.
  1636. * @private
  1637. */
  1638. DataSet.prototype._sort = function (items, order) {
  1639. if (util.isString(order)) {
  1640. // order by provided field name
  1641. var name = order; // field name
  1642. items.sort(function (a, b) {
  1643. var av = a[name];
  1644. var bv = b[name];
  1645. return (av > bv) ? 1 : ((av < bv) ? -1 : 0);
  1646. });
  1647. }
  1648. else if (typeof order === 'function') {
  1649. // order by sort function
  1650. items.sort(order);
  1651. }
  1652. // TODO: extend order by an Object {field:String, direction:String}
  1653. // where direction can be 'asc' or 'desc'
  1654. else {
  1655. throw new TypeError('Order must be a function or a string');
  1656. }
  1657. };
  1658. /**
  1659. * Remove an object by pointer or by id
  1660. * @param {String | Number | Object | Array} id Object or id, or an array with
  1661. * objects or ids to be removed
  1662. * @param {String} [senderId] Optional sender id
  1663. * @return {Array} removedIds
  1664. */
  1665. DataSet.prototype.remove = function (id, senderId) {
  1666. var removedIds = [],
  1667. i, len, removedId;
  1668. if (id instanceof Array) {
  1669. for (i = 0, len = id.length; i < len; i++) {
  1670. removedId = this._remove(id[i]);
  1671. if (removedId != null) {
  1672. removedIds.push(removedId);
  1673. }
  1674. }
  1675. }
  1676. else {
  1677. removedId = this._remove(id);
  1678. if (removedId != null) {
  1679. removedIds.push(removedId);
  1680. }
  1681. }
  1682. if (removedIds.length) {
  1683. this._trigger('remove', {items: removedIds}, senderId);
  1684. }
  1685. return removedIds;
  1686. };
  1687. /**
  1688. * Remove an item by its id
  1689. * @param {Number | String | Object} id id or item
  1690. * @returns {Number | String | null} id
  1691. * @private
  1692. */
  1693. DataSet.prototype._remove = function (id) {
  1694. if (util.isNumber(id) || util.isString(id)) {
  1695. if (this.data[id]) {
  1696. delete this.data[id];
  1697. delete this.internalIds[id];
  1698. return id;
  1699. }
  1700. }
  1701. else if (id instanceof Object) {
  1702. var itemId = id[this.fieldId];
  1703. if (itemId && this.data[itemId]) {
  1704. delete this.data[itemId];
  1705. delete this.internalIds[itemId];
  1706. return itemId;
  1707. }
  1708. }
  1709. return null;
  1710. };
  1711. /**
  1712. * Clear the data
  1713. * @param {String} [senderId] Optional sender id
  1714. * @return {Array} removedIds The ids of all removed items
  1715. */
  1716. DataSet.prototype.clear = function (senderId) {
  1717. var ids = Object.keys(this.data);
  1718. this.data = {};
  1719. this.internalIds = {};
  1720. this._trigger('remove', {items: ids}, senderId);
  1721. return ids;
  1722. };
  1723. /**
  1724. * Find the item with maximum value of a specified field
  1725. * @param {String} field
  1726. * @return {Object | null} item Item containing max value, or null if no items
  1727. */
  1728. DataSet.prototype.max = function (field) {
  1729. var data = this.data,
  1730. max = null,
  1731. maxField = null;
  1732. for (var id in data) {
  1733. if (data.hasOwnProperty(id)) {
  1734. var item = data[id];
  1735. var itemField = item[field];
  1736. if (itemField != null && (!max || itemField > maxField)) {
  1737. max = item;
  1738. maxField = itemField;
  1739. }
  1740. }
  1741. }
  1742. return max;
  1743. };
  1744. /**
  1745. * Find the item with minimum value of a specified field
  1746. * @param {String} field
  1747. * @return {Object | null} item Item containing max value, or null if no items
  1748. */
  1749. DataSet.prototype.min = function (field) {
  1750. var data = this.data,
  1751. min = null,
  1752. minField = null;
  1753. for (var id in data) {
  1754. if (data.hasOwnProperty(id)) {
  1755. var item = data[id];
  1756. var itemField = item[field];
  1757. if (itemField != null && (!min || itemField < minField)) {
  1758. min = item;
  1759. minField = itemField;
  1760. }
  1761. }
  1762. }
  1763. return min;
  1764. };
  1765. /**
  1766. * Find all distinct values of a specified field
  1767. * @param {String} field
  1768. * @return {Array} values Array containing all distinct values. If data items
  1769. * do not contain the specified field are ignored.
  1770. * The returned array is unordered.
  1771. */
  1772. DataSet.prototype.distinct = function (field) {
  1773. var data = this.data,
  1774. values = [],
  1775. fieldType = this.options.convert[field],
  1776. count = 0;
  1777. for (var prop in data) {
  1778. if (data.hasOwnProperty(prop)) {
  1779. var item = data[prop];
  1780. var value = util.convert(item[field], fieldType);
  1781. var exists = false;
  1782. for (var i = 0; i < count; i++) {
  1783. if (values[i] == value) {
  1784. exists = true;
  1785. break;
  1786. }
  1787. }
  1788. if (!exists && (value !== undefined)) {
  1789. values[count] = value;
  1790. count++;
  1791. }
  1792. }
  1793. }
  1794. return values;
  1795. };
  1796. /**
  1797. * Add a single item. Will fail when an item with the same id already exists.
  1798. * @param {Object} item
  1799. * @return {String} id
  1800. * @private
  1801. */
  1802. DataSet.prototype._addItem = function (item) {
  1803. var id = item[this.fieldId];
  1804. if (id != undefined) {
  1805. // check whether this id is already taken
  1806. if (this.data[id]) {
  1807. // item already exists
  1808. throw new Error('Cannot add item: item with id ' + id + ' already exists');
  1809. }
  1810. }
  1811. else {
  1812. // generate an id
  1813. id = util.randomUUID();
  1814. item[this.fieldId] = id;
  1815. this.internalIds[id] = item;
  1816. }
  1817. var d = {};
  1818. for (var field in item) {
  1819. if (item.hasOwnProperty(field)) {
  1820. var fieldType = this.convert[field]; // type may be undefined
  1821. d[field] = util.convert(item[field], fieldType);
  1822. }
  1823. }
  1824. this.data[id] = d;
  1825. return id;
  1826. };
  1827. /**
  1828. * Get an item. Fields can be converted to a specific type
  1829. * @param {String} id
  1830. * @param {Object.<String, String>} [convert] field types to convert
  1831. * @return {Object | null} item
  1832. * @private
  1833. */
  1834. DataSet.prototype._getItem = function (id, convert) {
  1835. var field, value;
  1836. // get the item from the dataset
  1837. var raw = this.data[id];
  1838. if (!raw) {
  1839. return null;
  1840. }
  1841. // convert the items field types
  1842. var converted = {},
  1843. fieldId = this.fieldId,
  1844. internalIds = this.internalIds;
  1845. if (convert) {
  1846. for (field in raw) {
  1847. if (raw.hasOwnProperty(field)) {
  1848. value = raw[field];
  1849. // output all fields, except internal ids
  1850. if ((field != fieldId) || (!(value in internalIds) || this.showInternalIds)) {
  1851. converted[field] = util.convert(value, convert[field]);
  1852. }
  1853. }
  1854. }
  1855. }
  1856. else {
  1857. // no field types specified, no converting needed
  1858. for (field in raw) {
  1859. if (raw.hasOwnProperty(field)) {
  1860. value = raw[field];
  1861. // output all fields, except internal ids
  1862. if ((field != fieldId) || (!(value in internalIds) || this.showInternalIds)) {
  1863. converted[field] = value;
  1864. }
  1865. }
  1866. }
  1867. }
  1868. return converted;
  1869. };
  1870. /**
  1871. * Update a single item: merge with existing item.
  1872. * Will fail when the item has no id, or when there does not exist an item
  1873. * with the same id.
  1874. * @param {Object} item
  1875. * @return {String} id
  1876. * @private
  1877. */
  1878. DataSet.prototype._updateItem = function (item) {
  1879. var id = item[this.fieldId];
  1880. if (id == undefined) {
  1881. throw new Error('Cannot update item: item has no id (item: ' + JSON.stringify(item) + ')');
  1882. }
  1883. var d = this.data[id];
  1884. if (!d) {
  1885. // item doesn't exist
  1886. throw new Error('Cannot update item: no item with id ' + id + ' found');
  1887. }
  1888. // merge with current item
  1889. for (var field in item) {
  1890. if (item.hasOwnProperty(field)) {
  1891. var fieldType = this.convert[field]; // type may be undefined
  1892. d[field] = util.convert(item[field], fieldType);
  1893. }
  1894. }
  1895. return id;
  1896. };
  1897. /**
  1898. * check if an id is an internal or external id
  1899. * @param id
  1900. * @returns {boolean}
  1901. * @private
  1902. */
  1903. DataSet.prototype.isInternalId = function(id) {
  1904. return (id in this.internalIds);
  1905. };
  1906. /**
  1907. * Get an array with the column names of a Google DataTable
  1908. * @param {DataTable} dataTable
  1909. * @return {String[]} columnNames
  1910. * @private
  1911. */
  1912. DataSet.prototype._getColumnNames = function (dataTable) {
  1913. var columns = [];
  1914. for (var col = 0, cols = dataTable.getNumberOfColumns(); col < cols; col++) {
  1915. columns[col] = dataTable.getColumnId(col) || dataTable.getColumnLabel(col);
  1916. }
  1917. return columns;
  1918. };
  1919. /**
  1920. * Append an item as a row to the dataTable
  1921. * @param dataTable
  1922. * @param columns
  1923. * @param item
  1924. * @private
  1925. */
  1926. DataSet.prototype._appendRow = function (dataTable, columns, item) {
  1927. var row = dataTable.addRow();
  1928. for (var col = 0, cols = columns.length; col < cols; col++) {
  1929. var field = columns[col];
  1930. dataTable.setValue(row, col, item[field]);
  1931. }
  1932. };
  1933. /**
  1934. * DataView
  1935. *
  1936. * a dataview offers a filtered view on a dataset or an other dataview.
  1937. *
  1938. * @param {DataSet | DataView} data
  1939. * @param {Object} [options] Available options: see method get
  1940. *
  1941. * @constructor DataView
  1942. */
  1943. function DataView (data, options) {
  1944. this.id = util.randomUUID();
  1945. this.data = null;
  1946. this.ids = {}; // ids of the items currently in memory (just contains a boolean true)
  1947. this.options = options || {};
  1948. this.fieldId = 'id'; // name of the field containing id
  1949. this.subscribers = {}; // event subscribers
  1950. var me = this;
  1951. this.listener = function () {
  1952. me._onEvent.apply(me, arguments);
  1953. };
  1954. this.setData(data);
  1955. }
  1956. // TODO: implement a function .config() to dynamically update things like configured filter
  1957. // and trigger changes accordingly
  1958. /**
  1959. * Set a data source for the view
  1960. * @param {DataSet | DataView} data
  1961. */
  1962. DataView.prototype.setData = function (data) {
  1963. var ids, dataItems, i, len;
  1964. if (this.data) {
  1965. // unsubscribe from current dataset
  1966. if (this.data.unsubscribe) {
  1967. this.data.unsubscribe('*', this.listener);
  1968. }
  1969. // trigger a remove of all items in memory
  1970. ids = [];
  1971. for (var id in this.ids) {
  1972. if (this.ids.hasOwnProperty(id)) {
  1973. ids.push(id);
  1974. }
  1975. }
  1976. this.ids = {};
  1977. this._trigger('remove', {items: ids});
  1978. }
  1979. this.data = data;
  1980. if (this.data) {
  1981. // update fieldId
  1982. this.fieldId = this.options.fieldId ||
  1983. (this.data && this.data.options && this.data.options.fieldId) ||
  1984. 'id';
  1985. // trigger an add of all added items
  1986. ids = this.data.getIds({filter: this.options && this.options.filter});
  1987. for (i = 0, len = ids.length; i < len; i++) {
  1988. id = ids[i];
  1989. this.ids[id] = true;
  1990. }
  1991. this._trigger('add', {items: ids});
  1992. // subscribe to new dataset
  1993. if (this.data.on) {
  1994. this.data.on('*', this.listener);
  1995. }
  1996. }
  1997. };
  1998. /**
  1999. * Get data from the data view
  2000. *
  2001. * Usage:
  2002. *
  2003. * get()
  2004. * get(options: Object)
  2005. * get(options: Object, data: Array | DataTable)
  2006. *
  2007. * get(id: Number)
  2008. * get(id: Number, options: Object)
  2009. * get(id: Number, options: Object, data: Array | DataTable)
  2010. *
  2011. * get(ids: Number[])
  2012. * get(ids: Number[], options: Object)
  2013. * get(ids: Number[], options: Object, data: Array | DataTable)
  2014. *
  2015. * Where:
  2016. *
  2017. * {Number | String} id The id of an item
  2018. * {Number[] | String{}} ids An array with ids of items
  2019. * {Object} options An Object with options. Available options:
  2020. * {String} [type] Type of data to be returned. Can
  2021. * be 'DataTable' or 'Array' (default)
  2022. * {Object.<String, String>} [convert]
  2023. * {String[]} [fields] field names to be returned
  2024. * {function} [filter] filter items
  2025. * {String | function} [order] Order the items by
  2026. * a field name or custom sort function.
  2027. * {Array | DataTable} [data] If provided, items will be appended to this
  2028. * array or table. Required in case of Google
  2029. * DataTable.
  2030. * @param args
  2031. */
  2032. DataView.prototype.get = function (args) {
  2033. var me = this;
  2034. // parse the arguments
  2035. var ids, options, data;
  2036. var firstType = util.getType(arguments[0]);
  2037. if (firstType == 'String' || firstType == 'Number' || firstType == 'Array') {
  2038. // get(id(s) [, options] [, data])
  2039. ids = arguments[0]; // can be a single id or an array with ids
  2040. options = arguments[1];
  2041. data = arguments[2];
  2042. }
  2043. else {
  2044. // get([, options] [, data])
  2045. options = arguments[0];
  2046. data = arguments[1];
  2047. }
  2048. // extend the options with the default options and provided options
  2049. var viewOptions = util.extend({}, this.options, options);
  2050. // create a combined filter method when needed
  2051. if (this.options.filter && options && options.filter) {
  2052. viewOptions.filter = function (item) {
  2053. return me.options.filter(item) && options.filter(item);
  2054. }
  2055. }
  2056. // build up the call to the linked data set
  2057. var getArguments = [];
  2058. if (ids != undefined) {
  2059. getArguments.push(ids);
  2060. }
  2061. getArguments.push(viewOptions);
  2062. getArguments.push(data);
  2063. return this.data && this.data.get.apply(this.data, getArguments);
  2064. };
  2065. /**
  2066. * Get ids of all items or from a filtered set of items.
  2067. * @param {Object} [options] An Object with options. Available options:
  2068. * {function} [filter] filter items
  2069. * {String | function} [order] Order the items by
  2070. * a field name or custom sort function.
  2071. * @return {Array} ids
  2072. */
  2073. DataView.prototype.getIds = function (options) {
  2074. var ids;
  2075. if (this.data) {
  2076. var defaultFilter = this.options.filter;
  2077. var filter;
  2078. if (options && options.filter) {
  2079. if (defaultFilter) {
  2080. filter = function (item) {
  2081. return defaultFilter(item) && options.filter(item);
  2082. }
  2083. }
  2084. else {
  2085. filter = options.filter;
  2086. }
  2087. }
  2088. else {
  2089. filter = defaultFilter;
  2090. }
  2091. ids = this.data.getIds({
  2092. filter: filter,
  2093. order: options && options.order
  2094. });
  2095. }
  2096. else {
  2097. ids = [];
  2098. }
  2099. return ids;
  2100. };
  2101. /**
  2102. * Event listener. Will propagate all events from the connected data set to
  2103. * the subscribers of the DataView, but will filter the items and only trigger
  2104. * when there are changes in the filtered data set.
  2105. * @param {String} event
  2106. * @param {Object | null} params
  2107. * @param {String} senderId
  2108. * @private
  2109. */
  2110. DataView.prototype._onEvent = function (event, params, senderId) {
  2111. var i, len, id, item,
  2112. ids = params && params.items,
  2113. data = this.data,
  2114. added = [],
  2115. updated = [],
  2116. removed = [];
  2117. if (ids && data) {
  2118. switch (event) {
  2119. case 'add':
  2120. // filter the ids of the added items
  2121. for (i = 0, len = ids.length; i < len; i++) {
  2122. id = ids[i];
  2123. item = this.get(id);
  2124. if (item) {
  2125. this.ids[id] = true;
  2126. added.push(id);
  2127. }
  2128. }
  2129. break;
  2130. case 'update':
  2131. // determine the event from the views viewpoint: an updated
  2132. // item can be added, updated, or removed from this view.
  2133. for (i = 0, len = ids.length; i < len; i++) {
  2134. id = ids[i];
  2135. item = this.get(id);
  2136. if (item) {
  2137. if (this.ids[id]) {
  2138. updated.push(id);
  2139. }
  2140. else {
  2141. this.ids[id] = true;
  2142. added.push(id);
  2143. }
  2144. }
  2145. else {
  2146. if (this.ids[id]) {
  2147. delete this.ids[id];
  2148. removed.push(id);
  2149. }
  2150. else {
  2151. // nothing interesting for me :-(
  2152. }
  2153. }
  2154. }
  2155. break;
  2156. case 'remove':
  2157. // filter the ids of the removed items
  2158. for (i = 0, len = ids.length; i < len; i++) {
  2159. id = ids[i];
  2160. if (this.ids[id]) {
  2161. delete this.ids[id];
  2162. removed.push(id);
  2163. }
  2164. }
  2165. break;
  2166. }
  2167. if (added.length) {
  2168. this._trigger('add', {items: added}, senderId);
  2169. }
  2170. if (updated.length) {
  2171. this._trigger('update', {items: updated}, senderId);
  2172. }
  2173. if (removed.length) {
  2174. this._trigger('remove', {items: removed}, senderId);
  2175. }
  2176. }
  2177. };
  2178. // copy subscription functionality from DataSet
  2179. DataView.prototype.on = DataSet.prototype.on;
  2180. DataView.prototype.off = DataSet.prototype.off;
  2181. DataView.prototype._trigger = DataSet.prototype._trigger;
  2182. // TODO: make these functions deprecated (replaced with `on` and `off` since version 0.5)
  2183. DataView.prototype.subscribe = DataView.prototype.on;
  2184. DataView.prototype.unsubscribe = DataView.prototype.off;
  2185. /**
  2186. * Utility functions for ordering and stacking of items
  2187. */
  2188. var stack = {};
  2189. /**
  2190. * Order items by their start data
  2191. * @param {Item[]} items
  2192. */
  2193. stack.orderByStart = function orderByStart(items) {
  2194. items.sort(function (a, b) {
  2195. return a.data.start - b.data.start;
  2196. });
  2197. };
  2198. /**
  2199. * Order items by their end date. If they have no end date, their start date
  2200. * is used.
  2201. * @param {Item[]} items
  2202. */
  2203. stack.orderByEnd = function orderByEnd(items) {
  2204. items.sort(function (a, b) {
  2205. var aTime = ('end' in a.data) ? a.data.end : a.data.start,
  2206. bTime = ('end' in b.data) ? b.data.end : b.data.start;
  2207. return aTime - bTime;
  2208. });
  2209. };
  2210. /**
  2211. * Adjust vertical positions of the items such that they don't overlap each
  2212. * other.
  2213. * @param {Item[]} items
  2214. * All visible items
  2215. * @param {{item: number, axis: number}} margin
  2216. * Margins between items and between items and the axis.
  2217. * @param {boolean} [force=false]
  2218. * If true, all items will be repositioned. If false (default), only
  2219. * items having a top===null will be re-stacked
  2220. */
  2221. stack.stack = function _stack (items, margin, force) {
  2222. var i, iMax;
  2223. if (force) {
  2224. // reset top position of all items
  2225. for (i = 0, iMax = items.length; i < iMax; i++) {
  2226. items[i].top = null;
  2227. }
  2228. }
  2229. // calculate new, non-overlapping positions
  2230. for (i = 0, iMax = items.length; i < iMax; i++) {
  2231. var item = items[i];
  2232. if (item.top === null) {
  2233. // initialize top position
  2234. item.top = margin.axis;
  2235. do {
  2236. // TODO: optimize checking for overlap. when there is a gap without items,
  2237. // you only need to check for items from the next item on, not from zero
  2238. var collidingItem = null;
  2239. for (var j = 0, jj = items.length; j < jj; j++) {
  2240. var other = items[j];
  2241. if (other.top !== null && other !== item && stack.collision(item, other, margin.item)) {
  2242. collidingItem = other;
  2243. break;
  2244. }
  2245. }
  2246. if (collidingItem != null) {
  2247. // There is a collision. Reposition the items above the colliding element
  2248. item.top = collidingItem.top + collidingItem.height + margin.item;
  2249. }
  2250. } while (collidingItem);
  2251. }
  2252. }
  2253. };
  2254. /**
  2255. * Adjust vertical positions of the items without stacking them
  2256. * @param {Item[]} items
  2257. * All visible items
  2258. * @param {{item: number, axis: number}} margin
  2259. * Margins between items and between items and the axis.
  2260. */
  2261. stack.nostack = function nostack (items, margin) {
  2262. var i, iMax;
  2263. // reset top position of all items
  2264. for (i = 0, iMax = items.length; i < iMax; i++) {
  2265. items[i].top = margin.axis;
  2266. }
  2267. };
  2268. /**
  2269. * Test if the two provided items collide
  2270. * The items must have parameters left, width, top, and height.
  2271. * @param {Item} a The first item
  2272. * @param {Item} b The second item
  2273. * @param {Number} margin A minimum required margin.
  2274. * If margin is provided, the two items will be
  2275. * marked colliding when they overlap or
  2276. * when the margin between the two is smaller than
  2277. * the requested margin.
  2278. * @return {boolean} true if a and b collide, else false
  2279. */
  2280. stack.collision = function collision (a, b, margin) {
  2281. return ((a.left - margin) < (b.left + b.width) &&
  2282. (a.left + a.width + margin) > b.left &&
  2283. (a.top - margin) < (b.top + b.height) &&
  2284. (a.top + a.height + margin) > b.top);
  2285. };
  2286. /**
  2287. * @constructor TimeStep
  2288. * The class TimeStep is an iterator for dates. You provide a start date and an
  2289. * end date. The class itself determines the best scale (step size) based on the
  2290. * provided start Date, end Date, and minimumStep.
  2291. *
  2292. * If minimumStep is provided, the step size is chosen as close as possible
  2293. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2294. * provided, the scale is set to 1 DAY.
  2295. * The minimumStep should correspond with the onscreen size of about 6 characters
  2296. *
  2297. * Alternatively, you can set a scale by hand.
  2298. * After creation, you can initialize the class by executing first(). Then you
  2299. * can iterate from the start date to the end date via next(). You can check if
  2300. * the end date is reached with the function hasNext(). After each step, you can
  2301. * retrieve the current date via getCurrent().
  2302. * The TimeStep has scales ranging from milliseconds, seconds, minutes, hours,
  2303. * days, to years.
  2304. *
  2305. * Version: 1.2
  2306. *
  2307. * @param {Date} [start] The start date, for example new Date(2010, 9, 21)
  2308. * or new Date(2010, 9, 21, 23, 45, 00)
  2309. * @param {Date} [end] The end date
  2310. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  2311. */
  2312. function TimeStep(start, end, minimumStep) {
  2313. // variables
  2314. this.current = new Date();
  2315. this._start = new Date();
  2316. this._end = new Date();
  2317. this.autoScale = true;
  2318. this.scale = TimeStep.SCALE.DAY;
  2319. this.step = 1;
  2320. // initialize the range
  2321. this.setRange(start, end, minimumStep);
  2322. }
  2323. /// enum scale
  2324. TimeStep.SCALE = {
  2325. MILLISECOND: 1,
  2326. SECOND: 2,
  2327. MINUTE: 3,
  2328. HOUR: 4,
  2329. DAY: 5,
  2330. WEEKDAY: 6,
  2331. MONTH: 7,
  2332. YEAR: 8
  2333. };
  2334. /**
  2335. * Set a new range
  2336. * If minimumStep is provided, the step size is chosen as close as possible
  2337. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2338. * provided, the scale is set to 1 DAY.
  2339. * The minimumStep should correspond with the onscreen size of about 6 characters
  2340. * @param {Date} [start] The start date and time.
  2341. * @param {Date} [end] The end date and time.
  2342. * @param {int} [minimumStep] Optional. Minimum step size in milliseconds
  2343. */
  2344. TimeStep.prototype.setRange = function(start, end, minimumStep) {
  2345. if (!(start instanceof Date) || !(end instanceof Date)) {
  2346. throw "No legal start or end date in method setRange";
  2347. }
  2348. this._start = (start != undefined) ? new Date(start.valueOf()) : new Date();
  2349. this._end = (end != undefined) ? new Date(end.valueOf()) : new Date();
  2350. if (this.autoScale) {
  2351. this.setMinimumStep(minimumStep);
  2352. }
  2353. };
  2354. /**
  2355. * Set the range iterator to the start date.
  2356. */
  2357. TimeStep.prototype.first = function() {
  2358. this.current = new Date(this._start.valueOf());
  2359. this.roundToMinor();
  2360. };
  2361. /**
  2362. * Round the current date to the first minor date value
  2363. * This must be executed once when the current date is set to start Date
  2364. */
  2365. TimeStep.prototype.roundToMinor = function() {
  2366. // round to floor
  2367. // IMPORTANT: we have no breaks in this switch! (this is no bug)
  2368. //noinspection FallthroughInSwitchStatementJS
  2369. switch (this.scale) {
  2370. case TimeStep.SCALE.YEAR:
  2371. this.current.setFullYear(this.step * Math.floor(this.current.getFullYear() / this.step));
  2372. this.current.setMonth(0);
  2373. case TimeStep.SCALE.MONTH: this.current.setDate(1);
  2374. case TimeStep.SCALE.DAY: // intentional fall through
  2375. case TimeStep.SCALE.WEEKDAY: this.current.setHours(0);
  2376. case TimeStep.SCALE.HOUR: this.current.setMinutes(0);
  2377. case TimeStep.SCALE.MINUTE: this.current.setSeconds(0);
  2378. case TimeStep.SCALE.SECOND: this.current.setMilliseconds(0);
  2379. //case TimeStep.SCALE.MILLISECOND: // nothing to do for milliseconds
  2380. }
  2381. if (this.step != 1) {
  2382. // round down to the first minor value that is a multiple of the current step size
  2383. switch (this.scale) {
  2384. case TimeStep.SCALE.MILLISECOND: this.current.setMilliseconds(this.current.getMilliseconds() - this.current.getMilliseconds() % this.step); break;
  2385. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() - this.current.getSeconds() % this.step); break;
  2386. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() - this.current.getMinutes() % this.step); break;
  2387. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() - this.current.getHours() % this.step); break;
  2388. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2389. case TimeStep.SCALE.DAY: this.current.setDate((this.current.getDate()-1) - (this.current.getDate()-1) % this.step + 1); break;
  2390. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() - this.current.getMonth() % this.step); break;
  2391. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() - this.current.getFullYear() % this.step); break;
  2392. default: break;
  2393. }
  2394. }
  2395. };
  2396. /**
  2397. * Check if the there is a next step
  2398. * @return {boolean} true if the current date has not passed the end date
  2399. */
  2400. TimeStep.prototype.hasNext = function () {
  2401. return (this.current.valueOf() <= this._end.valueOf());
  2402. };
  2403. /**
  2404. * Do the next step
  2405. */
  2406. TimeStep.prototype.next = function() {
  2407. var prev = this.current.valueOf();
  2408. // Two cases, needed to prevent issues with switching daylight savings
  2409. // (end of March and end of October)
  2410. if (this.current.getMonth() < 6) {
  2411. switch (this.scale) {
  2412. case TimeStep.SCALE.MILLISECOND:
  2413. this.current = new Date(this.current.valueOf() + this.step); break;
  2414. case TimeStep.SCALE.SECOND: this.current = new Date(this.current.valueOf() + this.step * 1000); break;
  2415. case TimeStep.SCALE.MINUTE: this.current = new Date(this.current.valueOf() + this.step * 1000 * 60); break;
  2416. case TimeStep.SCALE.HOUR:
  2417. this.current = new Date(this.current.valueOf() + this.step * 1000 * 60 * 60);
  2418. // in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...)
  2419. var h = this.current.getHours();
  2420. this.current.setHours(h - (h % this.step));
  2421. break;
  2422. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2423. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2424. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2425. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2426. default: break;
  2427. }
  2428. }
  2429. else {
  2430. switch (this.scale) {
  2431. case TimeStep.SCALE.MILLISECOND: this.current = new Date(this.current.valueOf() + this.step); break;
  2432. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() + this.step); break;
  2433. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() + this.step); break;
  2434. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() + this.step); break;
  2435. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2436. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2437. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2438. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2439. default: break;
  2440. }
  2441. }
  2442. if (this.step != 1) {
  2443. // round down to the correct major value
  2444. switch (this.scale) {
  2445. case TimeStep.SCALE.MILLISECOND: if(this.current.getMilliseconds() < this.step) this.current.setMilliseconds(0); break;
  2446. case TimeStep.SCALE.SECOND: if(this.current.getSeconds() < this.step) this.current.setSeconds(0); break;
  2447. case TimeStep.SCALE.MINUTE: if(this.current.getMinutes() < this.step) this.current.setMinutes(0); break;
  2448. case TimeStep.SCALE.HOUR: if(this.current.getHours() < this.step) this.current.setHours(0); break;
  2449. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2450. case TimeStep.SCALE.DAY: if(this.current.getDate() < this.step+1) this.current.setDate(1); break;
  2451. case TimeStep.SCALE.MONTH: if(this.current.getMonth() < this.step) this.current.setMonth(0); break;
  2452. case TimeStep.SCALE.YEAR: break; // nothing to do for year
  2453. default: break;
  2454. }
  2455. }
  2456. // safety mechanism: if current time is still unchanged, move to the end
  2457. if (this.current.valueOf() == prev) {
  2458. this.current = new Date(this._end.valueOf());
  2459. }
  2460. };
  2461. /**
  2462. * Get the current datetime
  2463. * @return {Date} current The current date
  2464. */
  2465. TimeStep.prototype.getCurrent = function() {
  2466. return this.current;
  2467. };
  2468. /**
  2469. * Set a custom scale. Autoscaling will be disabled.
  2470. * For example setScale(SCALE.MINUTES, 5) will result
  2471. * in minor steps of 5 minutes, and major steps of an hour.
  2472. *
  2473. * @param {TimeStep.SCALE} newScale
  2474. * A scale. Choose from SCALE.MILLISECOND,
  2475. * SCALE.SECOND, SCALE.MINUTE, SCALE.HOUR,
  2476. * SCALE.WEEKDAY, SCALE.DAY, SCALE.MONTH,
  2477. * SCALE.YEAR.
  2478. * @param {Number} newStep A step size, by default 1. Choose for
  2479. * example 1, 2, 5, or 10.
  2480. */
  2481. TimeStep.prototype.setScale = function(newScale, newStep) {
  2482. this.scale = newScale;
  2483. if (newStep > 0) {
  2484. this.step = newStep;
  2485. }
  2486. this.autoScale = false;
  2487. };
  2488. /**
  2489. * Enable or disable autoscaling
  2490. * @param {boolean} enable If true, autoascaling is set true
  2491. */
  2492. TimeStep.prototype.setAutoScale = function (enable) {
  2493. this.autoScale = enable;
  2494. };
  2495. /**
  2496. * Automatically determine the scale that bests fits the provided minimum step
  2497. * @param {Number} [minimumStep] The minimum step size in milliseconds
  2498. */
  2499. TimeStep.prototype.setMinimumStep = function(minimumStep) {
  2500. if (minimumStep == undefined) {
  2501. return;
  2502. }
  2503. var stepYear = (1000 * 60 * 60 * 24 * 30 * 12);
  2504. var stepMonth = (1000 * 60 * 60 * 24 * 30);
  2505. var stepDay = (1000 * 60 * 60 * 24);
  2506. var stepHour = (1000 * 60 * 60);
  2507. var stepMinute = (1000 * 60);
  2508. var stepSecond = (1000);
  2509. var stepMillisecond= (1);
  2510. // find the smallest step that is larger than the provided minimumStep
  2511. if (stepYear*1000 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1000;}
  2512. if (stepYear*500 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 500;}
  2513. if (stepYear*100 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 100;}
  2514. if (stepYear*50 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 50;}
  2515. if (stepYear*10 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 10;}
  2516. if (stepYear*5 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 5;}
  2517. if (stepYear > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1;}
  2518. if (stepMonth*3 > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 3;}
  2519. if (stepMonth > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 1;}
  2520. if (stepDay*5 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 5;}
  2521. if (stepDay*2 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 2;}
  2522. if (stepDay > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 1;}
  2523. if (stepDay/2 > minimumStep) {this.scale = TimeStep.SCALE.WEEKDAY; this.step = 1;}
  2524. if (stepHour*4 > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 4;}
  2525. if (stepHour > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 1;}
  2526. if (stepMinute*15 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 15;}
  2527. if (stepMinute*10 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 10;}
  2528. if (stepMinute*5 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 5;}
  2529. if (stepMinute > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 1;}
  2530. if (stepSecond*15 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 15;}
  2531. if (stepSecond*10 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 10;}
  2532. if (stepSecond*5 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 5;}
  2533. if (stepSecond > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 1;}
  2534. if (stepMillisecond*200 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 200;}
  2535. if (stepMillisecond*100 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 100;}
  2536. if (stepMillisecond*50 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 50;}
  2537. if (stepMillisecond*10 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 10;}
  2538. if (stepMillisecond*5 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 5;}
  2539. if (stepMillisecond > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 1;}
  2540. };
  2541. /**
  2542. * Snap a date to a rounded value.
  2543. * The snap intervals are dependent on the current scale and step.
  2544. * @param {Date} date the date to be snapped.
  2545. * @return {Date} snappedDate
  2546. */
  2547. TimeStep.prototype.snap = function(date) {
  2548. var clone = new Date(date.valueOf());
  2549. if (this.scale == TimeStep.SCALE.YEAR) {
  2550. var year = clone.getFullYear() + Math.round(clone.getMonth() / 12);
  2551. clone.setFullYear(Math.round(year / this.step) * this.step);
  2552. clone.setMonth(0);
  2553. clone.setDate(0);
  2554. clone.setHours(0);
  2555. clone.setMinutes(0);
  2556. clone.setSeconds(0);
  2557. clone.setMilliseconds(0);
  2558. }
  2559. else if (this.scale == TimeStep.SCALE.MONTH) {
  2560. if (clone.getDate() > 15) {
  2561. clone.setDate(1);
  2562. clone.setMonth(clone.getMonth() + 1);
  2563. // important: first set Date to 1, after that change the month.
  2564. }
  2565. else {
  2566. clone.setDate(1);
  2567. }
  2568. clone.setHours(0);
  2569. clone.setMinutes(0);
  2570. clone.setSeconds(0);
  2571. clone.setMilliseconds(0);
  2572. }
  2573. else if (this.scale == TimeStep.SCALE.DAY ||
  2574. this.scale == TimeStep.SCALE.WEEKDAY) {
  2575. //noinspection FallthroughInSwitchStatementJS
  2576. switch (this.step) {
  2577. case 5:
  2578. case 2:
  2579. clone.setHours(Math.round(clone.getHours() / 24) * 24); break;
  2580. default:
  2581. clone.setHours(Math.round(clone.getHours() / 12) * 12); break;
  2582. }
  2583. clone.setMinutes(0);
  2584. clone.setSeconds(0);
  2585. clone.setMilliseconds(0);
  2586. }
  2587. else if (this.scale == TimeStep.SCALE.HOUR) {
  2588. switch (this.step) {
  2589. case 4:
  2590. clone.setMinutes(Math.round(clone.getMinutes() / 60) * 60); break;
  2591. default:
  2592. clone.setMinutes(Math.round(clone.getMinutes() / 30) * 30); break;
  2593. }
  2594. clone.setSeconds(0);
  2595. clone.setMilliseconds(0);
  2596. } else if (this.scale == TimeStep.SCALE.MINUTE) {
  2597. //noinspection FallthroughInSwitchStatementJS
  2598. switch (this.step) {
  2599. case 15:
  2600. case 10:
  2601. clone.setMinutes(Math.round(clone.getMinutes() / 5) * 5);
  2602. clone.setSeconds(0);
  2603. break;
  2604. case 5:
  2605. clone.setSeconds(Math.round(clone.getSeconds() / 60) * 60); break;
  2606. default:
  2607. clone.setSeconds(Math.round(clone.getSeconds() / 30) * 30); break;
  2608. }
  2609. clone.setMilliseconds(0);
  2610. }
  2611. else if (this.scale == TimeStep.SCALE.SECOND) {
  2612. //noinspection FallthroughInSwitchStatementJS
  2613. switch (this.step) {
  2614. case 15:
  2615. case 10:
  2616. clone.setSeconds(Math.round(clone.getSeconds() / 5) * 5);
  2617. clone.setMilliseconds(0);
  2618. break;
  2619. case 5:
  2620. clone.setMilliseconds(Math.round(clone.getMilliseconds() / 1000) * 1000); break;
  2621. default:
  2622. clone.setMilliseconds(Math.round(clone.getMilliseconds() / 500) * 500); break;
  2623. }
  2624. }
  2625. else if (this.scale == TimeStep.SCALE.MILLISECOND) {
  2626. var step = this.step > 5 ? this.step / 2 : 1;
  2627. clone.setMilliseconds(Math.round(clone.getMilliseconds() / step) * step);
  2628. }
  2629. return clone;
  2630. };
  2631. /**
  2632. * Check if the current value is a major value (for example when the step
  2633. * is DAY, a major value is each first day of the MONTH)
  2634. * @return {boolean} true if current date is major, else false.
  2635. */
  2636. TimeStep.prototype.isMajor = function() {
  2637. switch (this.scale) {
  2638. case TimeStep.SCALE.MILLISECOND:
  2639. return (this.current.getMilliseconds() == 0);
  2640. case TimeStep.SCALE.SECOND:
  2641. return (this.current.getSeconds() == 0);
  2642. case TimeStep.SCALE.MINUTE:
  2643. return (this.current.getHours() == 0) && (this.current.getMinutes() == 0);
  2644. // Note: this is no bug. Major label is equal for both minute and hour scale
  2645. case TimeStep.SCALE.HOUR:
  2646. return (this.current.getHours() == 0);
  2647. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2648. case TimeStep.SCALE.DAY:
  2649. return (this.current.getDate() == 1);
  2650. case TimeStep.SCALE.MONTH:
  2651. return (this.current.getMonth() == 0);
  2652. case TimeStep.SCALE.YEAR:
  2653. return false;
  2654. default:
  2655. return false;
  2656. }
  2657. };
  2658. /**
  2659. * Returns formatted text for the minor axislabel, depending on the current
  2660. * date and the scale. For example when scale is MINUTE, the current time is
  2661. * formatted as "hh:mm".
  2662. * @param {Date} [date] custom date. if not provided, current date is taken
  2663. */
  2664. TimeStep.prototype.getLabelMinor = function(date) {
  2665. if (date == undefined) {
  2666. date = this.current;
  2667. }
  2668. switch (this.scale) {
  2669. case TimeStep.SCALE.MILLISECOND: return moment(date).format('SSS');
  2670. case TimeStep.SCALE.SECOND: return moment(date).format('s');
  2671. case TimeStep.SCALE.MINUTE: return moment(date).format('HH:mm');
  2672. case TimeStep.SCALE.HOUR: return moment(date).format('HH:mm');
  2673. case TimeStep.SCALE.WEEKDAY: return moment(date).format('ddd D');
  2674. case TimeStep.SCALE.DAY: return moment(date).format('D');
  2675. case TimeStep.SCALE.MONTH: return moment(date).format('MMM');
  2676. case TimeStep.SCALE.YEAR: return moment(date).format('YYYY');
  2677. default: return '';
  2678. }
  2679. };
  2680. /**
  2681. * Returns formatted text for the major axis label, depending on the current
  2682. * date and the scale. For example when scale is MINUTE, the major scale is
  2683. * hours, and the hour will be formatted as "hh".
  2684. * @param {Date} [date] custom date. if not provided, current date is taken
  2685. */
  2686. TimeStep.prototype.getLabelMajor = function(date) {
  2687. if (date == undefined) {
  2688. date = this.current;
  2689. }
  2690. //noinspection FallthroughInSwitchStatementJS
  2691. switch (this.scale) {
  2692. case TimeStep.SCALE.MILLISECOND:return moment(date).format('HH:mm:ss');
  2693. case TimeStep.SCALE.SECOND: return moment(date).format('D MMMM HH:mm');
  2694. case TimeStep.SCALE.MINUTE:
  2695. case TimeStep.SCALE.HOUR: return moment(date).format('ddd D MMMM');
  2696. case TimeStep.SCALE.WEEKDAY:
  2697. case TimeStep.SCALE.DAY: return moment(date).format('MMMM YYYY');
  2698. case TimeStep.SCALE.MONTH: return moment(date).format('YYYY');
  2699. case TimeStep.SCALE.YEAR: return '';
  2700. default: return '';
  2701. }
  2702. };
  2703. /**
  2704. * @constructor Range
  2705. * A Range controls a numeric range with a start and end value.
  2706. * The Range adjusts the range based on mouse events or programmatic changes,
  2707. * and triggers events when the range is changing or has been changed.
  2708. * @param {RootPanel} root Root panel, used to subscribe to events
  2709. * @param {Panel} parent Parent panel, used to attach to the DOM
  2710. * @param {Object} [options] See description at Range.setOptions
  2711. */
  2712. function Range(root, parent, options) {
  2713. this.id = util.randomUUID();
  2714. this.start = null; // Number
  2715. this.end = null; // Number
  2716. this.root = root;
  2717. this.parent = parent;
  2718. this.options = options || {};
  2719. // drag listeners for dragging
  2720. this.root.on('dragstart', this._onDragStart.bind(this));
  2721. this.root.on('drag', this._onDrag.bind(this));
  2722. this.root.on('dragend', this._onDragEnd.bind(this));
  2723. // ignore dragging when holding
  2724. this.root.on('hold', this._onHold.bind(this));
  2725. // mouse wheel for zooming
  2726. this.root.on('mousewheel', this._onMouseWheel.bind(this));
  2727. this.root.on('DOMMouseScroll', this._onMouseWheel.bind(this)); // For FF
  2728. // pinch to zoom
  2729. this.root.on('touch', this._onTouch.bind(this));
  2730. this.root.on('pinch', this._onPinch.bind(this));
  2731. this.setOptions(options);
  2732. }
  2733. // turn Range into an event emitter
  2734. Emitter(Range.prototype);
  2735. /**
  2736. * Set options for the range controller
  2737. * @param {Object} options Available options:
  2738. * {Number} min Minimum value for start
  2739. * {Number} max Maximum value for end
  2740. * {Number} zoomMin Set a minimum value for
  2741. * (end - start).
  2742. * {Number} zoomMax Set a maximum value for
  2743. * (end - start).
  2744. */
  2745. Range.prototype.setOptions = function (options) {
  2746. util.extend(this.options, options);
  2747. // re-apply range with new limitations
  2748. if (this.start !== null && this.end !== null) {
  2749. this.setRange(this.start, this.end);
  2750. }
  2751. };
  2752. /**
  2753. * Test whether direction has a valid value
  2754. * @param {String} direction 'horizontal' or 'vertical'
  2755. */
  2756. function validateDirection (direction) {
  2757. if (direction != 'horizontal' && direction != 'vertical') {
  2758. throw new TypeError('Unknown direction "' + direction + '". ' +
  2759. 'Choose "horizontal" or "vertical".');
  2760. }
  2761. }
  2762. /**
  2763. * Set a new start and end range
  2764. * @param {Number} [start]
  2765. * @param {Number} [end]
  2766. */
  2767. Range.prototype.setRange = function(start, end) {
  2768. var changed = this._applyRange(start, end);
  2769. if (changed) {
  2770. var params = {
  2771. start: new Date(this.start),
  2772. end: new Date(this.end)
  2773. };
  2774. this.emit('rangechange', params);
  2775. this.emit('rangechanged', params);
  2776. }
  2777. };
  2778. /**
  2779. * Set a new start and end range. This method is the same as setRange, but
  2780. * does not trigger a range change and range changed event, and it returns
  2781. * true when the range is changed
  2782. * @param {Number} [start]
  2783. * @param {Number} [end]
  2784. * @return {Boolean} changed
  2785. * @private
  2786. */
  2787. Range.prototype._applyRange = function(start, end) {
  2788. var newStart = (start != null) ? util.convert(start, 'Date').valueOf() : this.start,
  2789. newEnd = (end != null) ? util.convert(end, 'Date').valueOf() : this.end,
  2790. max = (this.options.max != null) ? util.convert(this.options.max, 'Date').valueOf() : null,
  2791. min = (this.options.min != null) ? util.convert(this.options.min, 'Date').valueOf() : null,
  2792. diff;
  2793. // check for valid number
  2794. if (isNaN(newStart) || newStart === null) {
  2795. throw new Error('Invalid start "' + start + '"');
  2796. }
  2797. if (isNaN(newEnd) || newEnd === null) {
  2798. throw new Error('Invalid end "' + end + '"');
  2799. }
  2800. // prevent start < end
  2801. if (newEnd < newStart) {
  2802. newEnd = newStart;
  2803. }
  2804. // prevent start < min
  2805. if (min !== null) {
  2806. if (newStart < min) {
  2807. diff = (min - newStart);
  2808. newStart += diff;
  2809. newEnd += diff;
  2810. // prevent end > max
  2811. if (max != null) {
  2812. if (newEnd > max) {
  2813. newEnd = max;
  2814. }
  2815. }
  2816. }
  2817. }
  2818. // prevent end > max
  2819. if (max !== null) {
  2820. if (newEnd > max) {
  2821. diff = (newEnd - max);
  2822. newStart -= diff;
  2823. newEnd -= diff;
  2824. // prevent start < min
  2825. if (min != null) {
  2826. if (newStart < min) {
  2827. newStart = min;
  2828. }
  2829. }
  2830. }
  2831. }
  2832. // prevent (end-start) < zoomMin
  2833. if (this.options.zoomMin !== null) {
  2834. var zoomMin = parseFloat(this.options.zoomMin);
  2835. if (zoomMin < 0) {
  2836. zoomMin = 0;
  2837. }
  2838. if ((newEnd - newStart) < zoomMin) {
  2839. if ((this.end - this.start) === zoomMin) {
  2840. // ignore this action, we are already zoomed to the minimum
  2841. newStart = this.start;
  2842. newEnd = this.end;
  2843. }
  2844. else {
  2845. // zoom to the minimum
  2846. diff = (zoomMin - (newEnd - newStart));
  2847. newStart -= diff / 2;
  2848. newEnd += diff / 2;
  2849. }
  2850. }
  2851. }
  2852. // prevent (end-start) > zoomMax
  2853. if (this.options.zoomMax !== null) {
  2854. var zoomMax = parseFloat(this.options.zoomMax);
  2855. if (zoomMax < 0) {
  2856. zoomMax = 0;
  2857. }
  2858. if ((newEnd - newStart) > zoomMax) {
  2859. if ((this.end - this.start) === zoomMax) {
  2860. // ignore this action, we are already zoomed to the maximum
  2861. newStart = this.start;
  2862. newEnd = this.end;
  2863. }
  2864. else {
  2865. // zoom to the maximum
  2866. diff = ((newEnd - newStart) - zoomMax);
  2867. newStart += diff / 2;
  2868. newEnd -= diff / 2;
  2869. }
  2870. }
  2871. }
  2872. var changed = (this.start != newStart || this.end != newEnd);
  2873. this.start = newStart;
  2874. this.end = newEnd;
  2875. return changed;
  2876. };
  2877. /**
  2878. * Retrieve the current range.
  2879. * @return {Object} An object with start and end properties
  2880. */
  2881. Range.prototype.getRange = function() {
  2882. return {
  2883. start: this.start,
  2884. end: this.end
  2885. };
  2886. };
  2887. /**
  2888. * Calculate the conversion offset and scale for current range, based on
  2889. * the provided width
  2890. * @param {Number} width
  2891. * @returns {{offset: number, scale: number}} conversion
  2892. */
  2893. Range.prototype.conversion = function (width) {
  2894. return Range.conversion(this.start, this.end, width);
  2895. };
  2896. /**
  2897. * Static method to calculate the conversion offset and scale for a range,
  2898. * based on the provided start, end, and width
  2899. * @param {Number} start
  2900. * @param {Number} end
  2901. * @param {Number} width
  2902. * @returns {{offset: number, scale: number}} conversion
  2903. */
  2904. Range.conversion = function (start, end, width) {
  2905. if (width != 0 && (end - start != 0)) {
  2906. return {
  2907. offset: start,
  2908. scale: width / (end - start)
  2909. }
  2910. }
  2911. else {
  2912. return {
  2913. offset: 0,
  2914. scale: 1
  2915. };
  2916. }
  2917. };
  2918. // global (private) object to store drag params
  2919. var touchParams = {};
  2920. /**
  2921. * Start dragging horizontally or vertically
  2922. * @param {Event} event
  2923. * @private
  2924. */
  2925. Range.prototype._onDragStart = function(event) {
  2926. // refuse to drag when we where pinching to prevent the timeline make a jump
  2927. // when releasing the fingers in opposite order from the touch screen
  2928. if (touchParams.ignore) return;
  2929. // TODO: reckon with option movable
  2930. touchParams.start = this.start;
  2931. touchParams.end = this.end;
  2932. var frame = this.parent.frame;
  2933. if (frame) {
  2934. frame.style.cursor = 'move';
  2935. }
  2936. };
  2937. /**
  2938. * Perform dragging operating.
  2939. * @param {Event} event
  2940. * @private
  2941. */
  2942. Range.prototype._onDrag = function (event) {
  2943. var direction = this.options.direction;
  2944. validateDirection(direction);
  2945. // TODO: reckon with option movable
  2946. // refuse to drag when we where pinching to prevent the timeline make a jump
  2947. // when releasing the fingers in opposite order from the touch screen
  2948. if (touchParams.ignore) return;
  2949. var delta = (direction == 'horizontal') ? event.gesture.deltaX : event.gesture.deltaY,
  2950. interval = (touchParams.end - touchParams.start),
  2951. width = (direction == 'horizontal') ? this.parent.width : this.parent.height,
  2952. diffRange = -delta / width * interval;
  2953. this._applyRange(touchParams.start + diffRange, touchParams.end + diffRange);
  2954. this.emit('rangechange', {
  2955. start: new Date(this.start),
  2956. end: new Date(this.end)
  2957. });
  2958. };
  2959. /**
  2960. * Stop dragging operating.
  2961. * @param {event} event
  2962. * @private
  2963. */
  2964. Range.prototype._onDragEnd = function (event) {
  2965. // refuse to drag when we where pinching to prevent the timeline make a jump
  2966. // when releasing the fingers in opposite order from the touch screen
  2967. if (touchParams.ignore) return;
  2968. // TODO: reckon with option movable
  2969. if (this.parent.frame) {
  2970. this.parent.frame.style.cursor = 'auto';
  2971. }
  2972. // fire a rangechanged event
  2973. this.emit('rangechanged', {
  2974. start: new Date(this.start),
  2975. end: new Date(this.end)
  2976. });
  2977. };
  2978. /**
  2979. * Event handler for mouse wheel event, used to zoom
  2980. * Code from http://adomas.org/javascript-mouse-wheel/
  2981. * @param {Event} event
  2982. * @private
  2983. */
  2984. Range.prototype._onMouseWheel = function(event) {
  2985. // TODO: reckon with option zoomable
  2986. // retrieve delta
  2987. var delta = 0;
  2988. if (event.wheelDelta) { /* IE/Opera. */
  2989. delta = event.wheelDelta / 120;
  2990. } else if (event.detail) { /* Mozilla case. */
  2991. // In Mozilla, sign of delta is different than in IE.
  2992. // Also, delta is multiple of 3.
  2993. delta = -event.detail / 3;
  2994. }
  2995. // If delta is nonzero, handle it.
  2996. // Basically, delta is now positive if wheel was scrolled up,
  2997. // and negative, if wheel was scrolled down.
  2998. if (delta) {
  2999. // perform the zoom action. Delta is normally 1 or -1
  3000. // adjust a negative delta such that zooming in with delta 0.1
  3001. // equals zooming out with a delta -0.1
  3002. var scale;
  3003. if (delta < 0) {
  3004. scale = 1 - (delta / 5);
  3005. }
  3006. else {
  3007. scale = 1 / (1 + (delta / 5)) ;
  3008. }
  3009. // calculate center, the date to zoom around
  3010. var gesture = util.fakeGesture(this, event),
  3011. pointer = getPointer(gesture.center, this.parent.frame),
  3012. pointerDate = this._pointerToDate(pointer);
  3013. this.zoom(scale, pointerDate);
  3014. }
  3015. // Prevent default actions caused by mouse wheel
  3016. // (else the page and timeline both zoom and scroll)
  3017. event.preventDefault();
  3018. };
  3019. /**
  3020. * Start of a touch gesture
  3021. * @private
  3022. */
  3023. Range.prototype._onTouch = function (event) {
  3024. touchParams.start = this.start;
  3025. touchParams.end = this.end;
  3026. touchParams.ignore = false;
  3027. touchParams.center = null;
  3028. // don't move the range when dragging a selected event
  3029. // TODO: it's not so neat to have to know about the state of the ItemSet
  3030. var item = ItemSet.itemFromTarget(event);
  3031. if (item && item.selected && this.options.editable) {
  3032. touchParams.ignore = true;
  3033. }
  3034. };
  3035. /**
  3036. * On start of a hold gesture
  3037. * @private
  3038. */
  3039. Range.prototype._onHold = function () {
  3040. touchParams.ignore = true;
  3041. };
  3042. /**
  3043. * Handle pinch event
  3044. * @param {Event} event
  3045. * @private
  3046. */
  3047. Range.prototype._onPinch = function (event) {
  3048. var direction = this.options.direction;
  3049. touchParams.ignore = true;
  3050. // TODO: reckon with option zoomable
  3051. if (event.gesture.touches.length > 1) {
  3052. if (!touchParams.center) {
  3053. touchParams.center = getPointer(event.gesture.center, this.parent.frame);
  3054. }
  3055. var scale = 1 / event.gesture.scale,
  3056. initDate = this._pointerToDate(touchParams.center),
  3057. center = getPointer(event.gesture.center, this.parent.frame),
  3058. date = this._pointerToDate(this.parent, center),
  3059. delta = date - initDate; // TODO: utilize delta
  3060. // calculate new start and end
  3061. var newStart = parseInt(initDate + (touchParams.start - initDate) * scale);
  3062. var newEnd = parseInt(initDate + (touchParams.end - initDate) * scale);
  3063. // apply new range
  3064. this.setRange(newStart, newEnd);
  3065. }
  3066. };
  3067. /**
  3068. * Helper function to calculate the center date for zooming
  3069. * @param {{x: Number, y: Number}} pointer
  3070. * @return {number} date
  3071. * @private
  3072. */
  3073. Range.prototype._pointerToDate = function (pointer) {
  3074. var conversion;
  3075. var direction = this.options.direction;
  3076. validateDirection(direction);
  3077. if (direction == 'horizontal') {
  3078. var width = this.parent.width;
  3079. conversion = this.conversion(width);
  3080. return pointer.x / conversion.scale + conversion.offset;
  3081. }
  3082. else {
  3083. var height = this.parent.height;
  3084. conversion = this.conversion(height);
  3085. return pointer.y / conversion.scale + conversion.offset;
  3086. }
  3087. };
  3088. /**
  3089. * Get the pointer location relative to the location of the dom element
  3090. * @param {{pageX: Number, pageY: Number}} touch
  3091. * @param {Element} element HTML DOM element
  3092. * @return {{x: Number, y: Number}} pointer
  3093. * @private
  3094. */
  3095. function getPointer (touch, element) {
  3096. return {
  3097. x: touch.pageX - vis.util.getAbsoluteLeft(element),
  3098. y: touch.pageY - vis.util.getAbsoluteTop(element)
  3099. };
  3100. }
  3101. /**
  3102. * Zoom the range the given scale in or out. Start and end date will
  3103. * be adjusted, and the timeline will be redrawn. You can optionally give a
  3104. * date around which to zoom.
  3105. * For example, try scale = 0.9 or 1.1
  3106. * @param {Number} scale Scaling factor. Values above 1 will zoom out,
  3107. * values below 1 will zoom in.
  3108. * @param {Number} [center] Value representing a date around which will
  3109. * be zoomed.
  3110. */
  3111. Range.prototype.zoom = function(scale, center) {
  3112. // if centerDate is not provided, take it half between start Date and end Date
  3113. if (center == null) {
  3114. center = (this.start + this.end) / 2;
  3115. }
  3116. // calculate new start and end
  3117. var newStart = center + (this.start - center) * scale;
  3118. var newEnd = center + (this.end - center) * scale;
  3119. this.setRange(newStart, newEnd);
  3120. };
  3121. /**
  3122. * Move the range with a given delta to the left or right. Start and end
  3123. * value will be adjusted. For example, try delta = 0.1 or -0.1
  3124. * @param {Number} delta Moving amount. Positive value will move right,
  3125. * negative value will move left
  3126. */
  3127. Range.prototype.move = function(delta) {
  3128. // zoom start Date and end Date relative to the centerDate
  3129. var diff = (this.end - this.start);
  3130. // apply new values
  3131. var newStart = this.start + diff * delta;
  3132. var newEnd = this.end + diff * delta;
  3133. // TODO: reckon with min and max range
  3134. this.start = newStart;
  3135. this.end = newEnd;
  3136. };
  3137. /**
  3138. * Move the range to a new center point
  3139. * @param {Number} moveTo New center point of the range
  3140. */
  3141. Range.prototype.moveTo = function(moveTo) {
  3142. var center = (this.start + this.end) / 2;
  3143. var diff = center - moveTo;
  3144. // calculate new start and end
  3145. var newStart = this.start - diff;
  3146. var newEnd = this.end - diff;
  3147. this.setRange(newStart, newEnd);
  3148. };
  3149. /**
  3150. * Prototype for visual components
  3151. */
  3152. function Component () {
  3153. this.id = null;
  3154. this.parent = null;
  3155. this.childs = null;
  3156. this.options = null;
  3157. this.top = 0;
  3158. this.left = 0;
  3159. this.width = 0;
  3160. this.height = 0;
  3161. }
  3162. // Turn the Component into an event emitter
  3163. Emitter(Component.prototype);
  3164. /**
  3165. * Set parameters for the frame. Parameters will be merged in current parameter
  3166. * set.
  3167. * @param {Object} options Available parameters:
  3168. * {String | function} [className]
  3169. * {String | Number | function} [left]
  3170. * {String | Number | function} [top]
  3171. * {String | Number | function} [width]
  3172. * {String | Number | function} [height]
  3173. */
  3174. Component.prototype.setOptions = function setOptions(options) {
  3175. if (options) {
  3176. util.extend(this.options, options);
  3177. this.repaint();
  3178. }
  3179. };
  3180. /**
  3181. * Get an option value by name
  3182. * The function will first check this.options object, and else will check
  3183. * this.defaultOptions.
  3184. * @param {String} name
  3185. * @return {*} value
  3186. */
  3187. Component.prototype.getOption = function getOption(name) {
  3188. var value;
  3189. if (this.options) {
  3190. value = this.options[name];
  3191. }
  3192. if (value === undefined && this.defaultOptions) {
  3193. value = this.defaultOptions[name];
  3194. }
  3195. return value;
  3196. };
  3197. /**
  3198. * Get the frame element of the component, the outer HTML DOM element.
  3199. * @returns {HTMLElement | null} frame
  3200. */
  3201. Component.prototype.getFrame = function getFrame() {
  3202. // should be implemented by the component
  3203. return null;
  3204. };
  3205. /**
  3206. * Repaint the component
  3207. * @return {boolean} Returns true if the component is resized
  3208. */
  3209. Component.prototype.repaint = function repaint() {
  3210. // should be implemented by the component
  3211. return false;
  3212. };
  3213. /**
  3214. * Test whether the component is resized since the last time _isResized() was
  3215. * called.
  3216. * @return {Boolean} Returns true if the component is resized
  3217. * @protected
  3218. */
  3219. Component.prototype._isResized = function _isResized() {
  3220. var resized = (this._previousWidth !== this.width || this._previousHeight !== this.height);
  3221. this._previousWidth = this.width;
  3222. this._previousHeight = this.height;
  3223. return resized;
  3224. };
  3225. /**
  3226. * A panel can contain components
  3227. * @param {Object} [options] Available parameters:
  3228. * {String | Number | function} [left]
  3229. * {String | Number | function} [top]
  3230. * {String | Number | function} [width]
  3231. * {String | Number | function} [height]
  3232. * {String | function} [className]
  3233. * @constructor Panel
  3234. * @extends Component
  3235. */
  3236. function Panel(options) {
  3237. this.id = util.randomUUID();
  3238. this.parent = null;
  3239. this.childs = [];
  3240. this.options = options || {};
  3241. // create frame
  3242. this.frame = (typeof document !== 'undefined') ? document.createElement('div') : null;
  3243. }
  3244. Panel.prototype = new Component();
  3245. /**
  3246. * Set options. Will extend the current options.
  3247. * @param {Object} [options] Available parameters:
  3248. * {String | function} [className]
  3249. * {String | Number | function} [left]
  3250. * {String | Number | function} [top]
  3251. * {String | Number | function} [width]
  3252. * {String | Number | function} [height]
  3253. */
  3254. Panel.prototype.setOptions = Component.prototype.setOptions;
  3255. /**
  3256. * Get the outer frame of the panel
  3257. * @returns {HTMLElement} frame
  3258. */
  3259. Panel.prototype.getFrame = function () {
  3260. return this.frame;
  3261. };
  3262. /**
  3263. * Append a child to the panel
  3264. * @param {Component} child
  3265. */
  3266. Panel.prototype.appendChild = function (child) {
  3267. this.childs.push(child);
  3268. child.parent = this;
  3269. // attach to the DOM
  3270. var frame = child.getFrame();
  3271. if (frame) {
  3272. if (frame.parentNode) {
  3273. frame.parentNode.removeChild(frame);
  3274. }
  3275. this.frame.appendChild(frame);
  3276. }
  3277. };
  3278. /**
  3279. * Insert a child to the panel
  3280. * @param {Component} child
  3281. * @param {Component} beforeChild
  3282. */
  3283. Panel.prototype.insertBefore = function (child, beforeChild) {
  3284. var index = this.childs.indexOf(beforeChild);
  3285. if (index != -1) {
  3286. this.childs.splice(index, 0, child);
  3287. child.parent = this;
  3288. // attach to the DOM
  3289. var frame = child.getFrame();
  3290. if (frame) {
  3291. if (frame.parentNode) {
  3292. frame.parentNode.removeChild(frame);
  3293. }
  3294. var beforeFrame = beforeChild.getFrame();
  3295. if (beforeFrame) {
  3296. this.frame.insertBefore(frame, beforeFrame);
  3297. }
  3298. else {
  3299. this.frame.appendChild(frame);
  3300. }
  3301. }
  3302. }
  3303. };
  3304. /**
  3305. * Remove a child from the panel
  3306. * @param {Component} child
  3307. */
  3308. Panel.prototype.removeChild = function (child) {
  3309. var index = this.childs.indexOf(child);
  3310. if (index != -1) {
  3311. this.childs.splice(index, 1);
  3312. child.parent = null;
  3313. // remove from the DOM
  3314. var frame = child.getFrame();
  3315. if (frame && frame.parentNode) {
  3316. this.frame.removeChild(frame);
  3317. }
  3318. }
  3319. };
  3320. /**
  3321. * Test whether the panel contains given child
  3322. * @param {Component} child
  3323. */
  3324. Panel.prototype.hasChild = function (child) {
  3325. var index = this.childs.indexOf(child);
  3326. return (index != -1);
  3327. };
  3328. /**
  3329. * Repaint the component
  3330. * @return {boolean} Returns true if the component was resized since previous repaint
  3331. */
  3332. Panel.prototype.repaint = function () {
  3333. var asString = util.option.asString,
  3334. options = this.options,
  3335. frame = this.getFrame();
  3336. // update className
  3337. frame.className = 'vpanel' + (options.className ? (' ' + asString(options.className)) : '');
  3338. // repaint the child components
  3339. var childsResized = this._repaintChilds();
  3340. // update frame size
  3341. this._updateSize();
  3342. return this._isResized() || childsResized;
  3343. };
  3344. /**
  3345. * Repaint all childs of the panel
  3346. * @return {boolean} Returns true if the component is resized
  3347. * @private
  3348. */
  3349. Panel.prototype._repaintChilds = function () {
  3350. var resized = false;
  3351. for (var i = 0, ii = this.childs.length; i < ii; i++) {
  3352. resized = this.childs[i].repaint() || resized;
  3353. }
  3354. return resized;
  3355. };
  3356. /**
  3357. * Apply the size from options to the panel, and recalculate it's actual size.
  3358. * @private
  3359. */
  3360. Panel.prototype._updateSize = function () {
  3361. // apply size
  3362. this.frame.style.top = util.option.asSize(this.options.top);
  3363. this.frame.style.bottom = util.option.asSize(this.options.bottom);
  3364. this.frame.style.left = util.option.asSize(this.options.left);
  3365. this.frame.style.right = util.option.asSize(this.options.right);
  3366. this.frame.style.width = util.option.asSize(this.options.width, '100%');
  3367. this.frame.style.height = util.option.asSize(this.options.height, '');
  3368. // get actual size
  3369. this.top = this.frame.offsetTop;
  3370. this.left = this.frame.offsetLeft;
  3371. this.width = this.frame.offsetWidth;
  3372. this.height = this.frame.offsetHeight;
  3373. };
  3374. /**
  3375. * A root panel can hold components. The root panel must be initialized with
  3376. * a DOM element as container.
  3377. * @param {HTMLElement} container
  3378. * @param {Object} [options] Available parameters: see RootPanel.setOptions.
  3379. * @constructor RootPanel
  3380. * @extends Panel
  3381. */
  3382. function RootPanel(container, options) {
  3383. this.id = util.randomUUID();
  3384. this.container = container;
  3385. this.options = options || {};
  3386. this.defaultOptions = {
  3387. autoResize: true
  3388. };
  3389. // create the HTML DOM
  3390. this._create();
  3391. // attach the root panel to the provided container
  3392. if (!this.container) throw new Error('Cannot repaint root panel: no container attached');
  3393. this.container.appendChild(this.getFrame());
  3394. this._initWatch();
  3395. }
  3396. RootPanel.prototype = new Panel();
  3397. /**
  3398. * Create the HTML DOM for the root panel
  3399. */
  3400. RootPanel.prototype._create = function _create() {
  3401. // create frame
  3402. this.frame = document.createElement('div');
  3403. // create event listeners for all interesting events, these events will be
  3404. // emitted via emitter
  3405. this.hammer = Hammer(this.frame, {
  3406. prevent_default: true
  3407. });
  3408. this.listeners = {};
  3409. var me = this;
  3410. var events = [
  3411. 'touch', 'pinch', 'tap', 'doubletap', 'hold',
  3412. 'dragstart', 'drag', 'dragend',
  3413. 'mousewheel', 'DOMMouseScroll' // DOMMouseScroll is for Firefox
  3414. ];
  3415. events.forEach(function (event) {
  3416. var listener = function () {
  3417. var args = [event].concat(Array.prototype.slice.call(arguments, 0));
  3418. me.emit.apply(me, args);
  3419. };
  3420. me.hammer.on(event, listener);
  3421. me.listeners[event] = listener;
  3422. });
  3423. };
  3424. /**
  3425. * Set options. Will extend the current options.
  3426. * @param {Object} [options] Available parameters:
  3427. * {String | function} [className]
  3428. * {String | Number | function} [left]
  3429. * {String | Number | function} [top]
  3430. * {String | Number | function} [width]
  3431. * {String | Number | function} [height]
  3432. * {Boolean | function} [autoResize]
  3433. */
  3434. RootPanel.prototype.setOptions = function setOptions(options) {
  3435. if (options) {
  3436. util.extend(this.options, options);
  3437. this.repaint();
  3438. this._initWatch();
  3439. }
  3440. };
  3441. /**
  3442. * Get the frame of the root panel
  3443. */
  3444. RootPanel.prototype.getFrame = function getFrame() {
  3445. return this.frame;
  3446. };
  3447. /**
  3448. * Repaint the root panel
  3449. */
  3450. RootPanel.prototype.repaint = function repaint() {
  3451. // update class name
  3452. var options = this.options;
  3453. var editable = options.editable.updateTime || options.editable.updateGroup;
  3454. var className = 'vis timeline rootpanel ' + options.orientation + (editable ? ' editable' : '');
  3455. if (options.className) className += ' ' + util.option.asString(className);
  3456. this.frame.className = className;
  3457. // repaint the child components
  3458. var childsResized = this._repaintChilds();
  3459. // update frame size
  3460. this.frame.style.maxHeight = util.option.asSize(this.options.maxHeight, '');
  3461. this._updateSize();
  3462. // if the root panel or any of its childs is resized, repaint again,
  3463. // as other components may need to be resized accordingly
  3464. var resized = this._isResized() || childsResized;
  3465. if (resized) {
  3466. setTimeout(this.repaint.bind(this), 0);
  3467. }
  3468. };
  3469. /**
  3470. * Initialize watching when option autoResize is true
  3471. * @private
  3472. */
  3473. RootPanel.prototype._initWatch = function _initWatch() {
  3474. var autoResize = this.getOption('autoResize');
  3475. if (autoResize) {
  3476. this._watch();
  3477. }
  3478. else {
  3479. this._unwatch();
  3480. }
  3481. };
  3482. /**
  3483. * Watch for changes in the size of the frame. On resize, the Panel will
  3484. * automatically redraw itself.
  3485. * @private
  3486. */
  3487. RootPanel.prototype._watch = function _watch() {
  3488. var me = this;
  3489. this._unwatch();
  3490. var checkSize = function checkSize() {
  3491. var autoResize = me.getOption('autoResize');
  3492. if (!autoResize) {
  3493. // stop watching when the option autoResize is changed to false
  3494. me._unwatch();
  3495. return;
  3496. }
  3497. if (me.frame) {
  3498. // check whether the frame is resized
  3499. if ((me.frame.clientWidth != me.lastWidth) ||
  3500. (me.frame.clientHeight != me.lastHeight)) {
  3501. me.lastWidth = me.frame.clientWidth;
  3502. me.lastHeight = me.frame.clientHeight;
  3503. me.repaint();
  3504. // TODO: emit a resize event instead?
  3505. }
  3506. }
  3507. };
  3508. // TODO: automatically cleanup the event listener when the frame is deleted
  3509. util.addEventListener(window, 'resize', checkSize);
  3510. this.watchTimer = setInterval(checkSize, 1000);
  3511. };
  3512. /**
  3513. * Stop watching for a resize of the frame.
  3514. * @private
  3515. */
  3516. RootPanel.prototype._unwatch = function _unwatch() {
  3517. if (this.watchTimer) {
  3518. clearInterval(this.watchTimer);
  3519. this.watchTimer = undefined;
  3520. }
  3521. // TODO: remove event listener on window.resize
  3522. };
  3523. /**
  3524. * A horizontal time axis
  3525. * @param {Object} [options] See TimeAxis.setOptions for the available
  3526. * options.
  3527. * @constructor TimeAxis
  3528. * @extends Component
  3529. */
  3530. function TimeAxis (options) {
  3531. this.id = util.randomUUID();
  3532. this.dom = {
  3533. majorLines: [],
  3534. majorTexts: [],
  3535. minorLines: [],
  3536. minorTexts: [],
  3537. redundant: {
  3538. majorLines: [],
  3539. majorTexts: [],
  3540. minorLines: [],
  3541. minorTexts: []
  3542. }
  3543. };
  3544. this.props = {
  3545. range: {
  3546. start: 0,
  3547. end: 0,
  3548. minimumStep: 0
  3549. },
  3550. lineTop: 0
  3551. };
  3552. this.options = options || {};
  3553. this.defaultOptions = {
  3554. orientation: 'bottom', // supported: 'top', 'bottom'
  3555. // TODO: implement timeaxis orientations 'left' and 'right'
  3556. showMinorLabels: true,
  3557. showMajorLabels: true
  3558. };
  3559. this.range = null;
  3560. // create the HTML DOM
  3561. this._create();
  3562. }
  3563. TimeAxis.prototype = new Component();
  3564. // TODO: comment options
  3565. TimeAxis.prototype.setOptions = Component.prototype.setOptions;
  3566. /**
  3567. * Create the HTML DOM for the TimeAxis
  3568. */
  3569. TimeAxis.prototype._create = function _create() {
  3570. this.frame = document.createElement('div');
  3571. };
  3572. /**
  3573. * Set a range (start and end)
  3574. * @param {Range | Object} range A Range or an object containing start and end.
  3575. */
  3576. TimeAxis.prototype.setRange = function (range) {
  3577. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  3578. throw new TypeError('Range must be an instance of Range, ' +
  3579. 'or an object containing start and end.');
  3580. }
  3581. this.range = range;
  3582. };
  3583. /**
  3584. * Get the outer frame of the time axis
  3585. * @return {HTMLElement} frame
  3586. */
  3587. TimeAxis.prototype.getFrame = function getFrame() {
  3588. return this.frame;
  3589. };
  3590. /**
  3591. * Repaint the component
  3592. * @return {boolean} Returns true if the component is resized
  3593. */
  3594. TimeAxis.prototype.repaint = function () {
  3595. var asSize = util.option.asSize,
  3596. options = this.options,
  3597. props = this.props,
  3598. frame = this.frame;
  3599. // update classname
  3600. frame.className = 'timeaxis'; // TODO: add className from options if defined
  3601. var parent = frame.parentNode;
  3602. if (parent) {
  3603. // calculate character width and height
  3604. this._calculateCharSize();
  3605. // TODO: recalculate sizes only needed when parent is resized or options is changed
  3606. var orientation = this.getOption('orientation'),
  3607. showMinorLabels = this.getOption('showMinorLabels'),
  3608. showMajorLabels = this.getOption('showMajorLabels');
  3609. // determine the width and height of the elemens for the axis
  3610. var parentHeight = this.parent.height;
  3611. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  3612. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  3613. this.height = props.minorLabelHeight + props.majorLabelHeight;
  3614. this.width = frame.offsetWidth; // TODO: only update the width when the frame is resized?
  3615. props.minorLineHeight = parentHeight + props.minorLabelHeight;
  3616. props.minorLineWidth = 1; // TODO: really calculate width
  3617. props.majorLineHeight = parentHeight + this.height;
  3618. props.majorLineWidth = 1; // TODO: really calculate width
  3619. // take frame offline while updating (is almost twice as fast)
  3620. var beforeChild = frame.nextSibling;
  3621. parent.removeChild(frame);
  3622. // TODO: top/bottom positioning should be determined by options set in the Timeline, not here
  3623. if (orientation == 'top') {
  3624. frame.style.top = '0';
  3625. frame.style.left = '0';
  3626. frame.style.bottom = '';
  3627. frame.style.width = asSize(options.width, '100%');
  3628. frame.style.height = this.height + 'px';
  3629. }
  3630. else { // bottom
  3631. frame.style.top = '';
  3632. frame.style.bottom = '0';
  3633. frame.style.left = '0';
  3634. frame.style.width = asSize(options.width, '100%');
  3635. frame.style.height = this.height + 'px';
  3636. }
  3637. this._repaintLabels();
  3638. this._repaintLine();
  3639. // put frame online again
  3640. if (beforeChild) {
  3641. parent.insertBefore(frame, beforeChild);
  3642. }
  3643. else {
  3644. parent.appendChild(frame)
  3645. }
  3646. }
  3647. return this._isResized();
  3648. };
  3649. /**
  3650. * Repaint major and minor text labels and vertical grid lines
  3651. * @private
  3652. */
  3653. TimeAxis.prototype._repaintLabels = function () {
  3654. var orientation = this.getOption('orientation');
  3655. // calculate range and step (step such that we have space for 7 characters per label)
  3656. var start = util.convert(this.range.start, 'Number'),
  3657. end = util.convert(this.range.end, 'Number'),
  3658. minimumStep = this.options.toTime((this.props.minorCharWidth || 10) * 7).valueOf()
  3659. -this.options.toTime(0).valueOf();
  3660. var step = new TimeStep(new Date(start), new Date(end), minimumStep);
  3661. this.step = step;
  3662. // Move all DOM elements to a "redundant" list, where they
  3663. // can be picked for re-use, and clear the lists with lines and texts.
  3664. // At the end of the function _repaintLabels, left over elements will be cleaned up
  3665. var dom = this.dom;
  3666. dom.redundant.majorLines = dom.majorLines;
  3667. dom.redundant.majorTexts = dom.majorTexts;
  3668. dom.redundant.minorLines = dom.minorLines;
  3669. dom.redundant.minorTexts = dom.minorTexts;
  3670. dom.majorLines = [];
  3671. dom.majorTexts = [];
  3672. dom.minorLines = [];
  3673. dom.minorTexts = [];
  3674. step.first();
  3675. var xFirstMajorLabel = undefined;
  3676. var max = 0;
  3677. while (step.hasNext() && max < 1000) {
  3678. max++;
  3679. var cur = step.getCurrent(),
  3680. x = this.options.toScreen(cur),
  3681. isMajor = step.isMajor();
  3682. // TODO: lines must have a width, such that we can create css backgrounds
  3683. if (this.getOption('showMinorLabels')) {
  3684. this._repaintMinorText(x, step.getLabelMinor(), orientation);
  3685. }
  3686. if (isMajor && this.getOption('showMajorLabels')) {
  3687. if (x > 0) {
  3688. if (xFirstMajorLabel == undefined) {
  3689. xFirstMajorLabel = x;
  3690. }
  3691. this._repaintMajorText(x, step.getLabelMajor(), orientation);
  3692. }
  3693. this._repaintMajorLine(x, orientation);
  3694. }
  3695. else {
  3696. this._repaintMinorLine(x, orientation);
  3697. }
  3698. step.next();
  3699. }
  3700. // create a major label on the left when needed
  3701. if (this.getOption('showMajorLabels')) {
  3702. var leftTime = this.options.toTime(0),
  3703. leftText = step.getLabelMajor(leftTime),
  3704. widthText = leftText.length * (this.props.majorCharWidth || 10) + 10; // upper bound estimation
  3705. if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) {
  3706. this._repaintMajorText(0, leftText, orientation);
  3707. }
  3708. }
  3709. // Cleanup leftover DOM elements from the redundant list
  3710. util.forEach(this.dom.redundant, function (arr) {
  3711. while (arr.length) {
  3712. var elem = arr.pop();
  3713. if (elem && elem.parentNode) {
  3714. elem.parentNode.removeChild(elem);
  3715. }
  3716. }
  3717. });
  3718. };
  3719. /**
  3720. * Create a minor label for the axis at position x
  3721. * @param {Number} x
  3722. * @param {String} text
  3723. * @param {String} orientation "top" or "bottom" (default)
  3724. * @private
  3725. */
  3726. TimeAxis.prototype._repaintMinorText = function (x, text, orientation) {
  3727. // reuse redundant label
  3728. var label = this.dom.redundant.minorTexts.shift();
  3729. if (!label) {
  3730. // create new label
  3731. var content = document.createTextNode('');
  3732. label = document.createElement('div');
  3733. label.appendChild(content);
  3734. label.className = 'text minor';
  3735. this.frame.appendChild(label);
  3736. }
  3737. this.dom.minorTexts.push(label);
  3738. label.childNodes[0].nodeValue = text;
  3739. if (orientation == 'top') {
  3740. label.style.top = this.props.majorLabelHeight + 'px';
  3741. label.style.bottom = '';
  3742. }
  3743. else {
  3744. label.style.top = '';
  3745. label.style.bottom = this.props.majorLabelHeight + 'px';
  3746. }
  3747. label.style.left = x + 'px';
  3748. //label.title = title; // TODO: this is a heavy operation
  3749. };
  3750. /**
  3751. * Create a Major label for the axis at position x
  3752. * @param {Number} x
  3753. * @param {String} text
  3754. * @param {String} orientation "top" or "bottom" (default)
  3755. * @private
  3756. */
  3757. TimeAxis.prototype._repaintMajorText = function (x, text, orientation) {
  3758. // reuse redundant label
  3759. var label = this.dom.redundant.majorTexts.shift();
  3760. if (!label) {
  3761. // create label
  3762. var content = document.createTextNode(text);
  3763. label = document.createElement('div');
  3764. label.className = 'text major';
  3765. label.appendChild(content);
  3766. this.frame.appendChild(label);
  3767. }
  3768. this.dom.majorTexts.push(label);
  3769. label.childNodes[0].nodeValue = text;
  3770. //label.title = title; // TODO: this is a heavy operation
  3771. if (orientation == 'top') {
  3772. label.style.top = '0px';
  3773. label.style.bottom = '';
  3774. }
  3775. else {
  3776. label.style.top = '';
  3777. label.style.bottom = '0px';
  3778. }
  3779. label.style.left = x + 'px';
  3780. };
  3781. /**
  3782. * Create a minor line for the axis at position x
  3783. * @param {Number} x
  3784. * @param {String} orientation "top" or "bottom" (default)
  3785. * @private
  3786. */
  3787. TimeAxis.prototype._repaintMinorLine = function (x, orientation) {
  3788. // reuse redundant line
  3789. var line = this.dom.redundant.minorLines.shift();
  3790. if (!line) {
  3791. // create vertical line
  3792. line = document.createElement('div');
  3793. line.className = 'grid vertical minor';
  3794. this.frame.appendChild(line);
  3795. }
  3796. this.dom.minorLines.push(line);
  3797. var props = this.props;
  3798. if (orientation == 'top') {
  3799. line.style.top = this.props.majorLabelHeight + 'px';
  3800. line.style.bottom = '';
  3801. }
  3802. else {
  3803. line.style.top = '';
  3804. line.style.bottom = this.props.majorLabelHeight + 'px';
  3805. }
  3806. line.style.height = props.minorLineHeight + 'px';
  3807. line.style.left = (x - props.minorLineWidth / 2) + 'px';
  3808. };
  3809. /**
  3810. * Create a Major line for the axis at position x
  3811. * @param {Number} x
  3812. * @param {String} orientation "top" or "bottom" (default)
  3813. * @private
  3814. */
  3815. TimeAxis.prototype._repaintMajorLine = function (x, orientation) {
  3816. // reuse redundant line
  3817. var line = this.dom.redundant.majorLines.shift();
  3818. if (!line) {
  3819. // create vertical line
  3820. line = document.createElement('DIV');
  3821. line.className = 'grid vertical major';
  3822. this.frame.appendChild(line);
  3823. }
  3824. this.dom.majorLines.push(line);
  3825. var props = this.props;
  3826. if (orientation == 'top') {
  3827. line.style.top = '0px';
  3828. line.style.bottom = '';
  3829. }
  3830. else {
  3831. line.style.top = '';
  3832. line.style.bottom = '0px';
  3833. }
  3834. line.style.left = (x - props.majorLineWidth / 2) + 'px';
  3835. line.style.height = props.majorLineHeight + 'px';
  3836. };
  3837. /**
  3838. * Repaint the horizontal line for the axis
  3839. * @private
  3840. */
  3841. TimeAxis.prototype._repaintLine = function() {
  3842. var line = this.dom.line,
  3843. frame = this.frame,
  3844. orientation = this.getOption('orientation');
  3845. // line before all axis elements
  3846. if (this.getOption('showMinorLabels') || this.getOption('showMajorLabels')) {
  3847. if (line) {
  3848. // put this line at the end of all childs
  3849. frame.removeChild(line);
  3850. frame.appendChild(line);
  3851. }
  3852. else {
  3853. // create the axis line
  3854. line = document.createElement('div');
  3855. line.className = 'grid horizontal major';
  3856. frame.appendChild(line);
  3857. this.dom.line = line;
  3858. }
  3859. if (orientation == 'top') {
  3860. line.style.top = this.height + 'px';
  3861. line.style.bottom = '';
  3862. }
  3863. else {
  3864. line.style.top = '';
  3865. line.style.bottom = this.height + 'px';
  3866. }
  3867. }
  3868. else {
  3869. if (line && line.parentNode) {
  3870. line.parentNode.removeChild(line);
  3871. delete this.dom.line;
  3872. }
  3873. }
  3874. };
  3875. /**
  3876. * Determine the size of text on the axis (both major and minor axis).
  3877. * The size is calculated only once and then cached in this.props.
  3878. * @private
  3879. */
  3880. TimeAxis.prototype._calculateCharSize = function () {
  3881. // determine the char width and height on the minor axis
  3882. if (!('minorCharHeight' in this.props)) {
  3883. var textMinor = document.createTextNode('0');
  3884. var measureCharMinor = document.createElement('DIV');
  3885. measureCharMinor.className = 'text minor measure';
  3886. measureCharMinor.appendChild(textMinor);
  3887. this.frame.appendChild(measureCharMinor);
  3888. this.props.minorCharHeight = measureCharMinor.clientHeight;
  3889. this.props.minorCharWidth = measureCharMinor.clientWidth;
  3890. this.frame.removeChild(measureCharMinor);
  3891. }
  3892. if (!('majorCharHeight' in this.props)) {
  3893. var textMajor = document.createTextNode('0');
  3894. var measureCharMajor = document.createElement('DIV');
  3895. measureCharMajor.className = 'text major measure';
  3896. measureCharMajor.appendChild(textMajor);
  3897. this.frame.appendChild(measureCharMajor);
  3898. this.props.majorCharHeight = measureCharMajor.clientHeight;
  3899. this.props.majorCharWidth = measureCharMajor.clientWidth;
  3900. this.frame.removeChild(measureCharMajor);
  3901. }
  3902. };
  3903. /**
  3904. * Snap a date to a rounded value.
  3905. * The snap intervals are dependent on the current scale and step.
  3906. * @param {Date} date the date to be snapped.
  3907. * @return {Date} snappedDate
  3908. */
  3909. TimeAxis.prototype.snap = function snap (date) {
  3910. return this.step.snap(date);
  3911. };
  3912. /**
  3913. * A current time bar
  3914. * @param {Range} range
  3915. * @param {Object} [options] Available parameters:
  3916. * {Boolean} [showCurrentTime]
  3917. * @constructor CurrentTime
  3918. * @extends Component
  3919. */
  3920. function CurrentTime (range, options) {
  3921. this.id = util.randomUUID();
  3922. this.range = range;
  3923. this.options = options || {};
  3924. this.defaultOptions = {
  3925. showCurrentTime: false
  3926. };
  3927. this._create();
  3928. }
  3929. CurrentTime.prototype = new Component();
  3930. CurrentTime.prototype.setOptions = Component.prototype.setOptions;
  3931. /**
  3932. * Create the HTML DOM for the current time bar
  3933. * @private
  3934. */
  3935. CurrentTime.prototype._create = function _create () {
  3936. var bar = document.createElement('div');
  3937. bar.className = 'currenttime';
  3938. bar.style.position = 'absolute';
  3939. bar.style.top = '0px';
  3940. bar.style.height = '100%';
  3941. this.bar = bar;
  3942. };
  3943. /**
  3944. * Get the frame element of the current time bar
  3945. * @returns {HTMLElement} frame
  3946. */
  3947. CurrentTime.prototype.getFrame = function getFrame() {
  3948. return this.bar;
  3949. };
  3950. /**
  3951. * Repaint the component
  3952. * @return {boolean} Returns true if the component is resized
  3953. */
  3954. CurrentTime.prototype.repaint = function repaint() {
  3955. var parent = this.parent;
  3956. var now = new Date();
  3957. var x = this.options.toScreen(now);
  3958. this.bar.style.left = x + 'px';
  3959. this.bar.title = 'Current time: ' + now;
  3960. return false;
  3961. };
  3962. /**
  3963. * Start auto refreshing the current time bar
  3964. */
  3965. CurrentTime.prototype.start = function start() {
  3966. var me = this;
  3967. function update () {
  3968. me.stop();
  3969. // determine interval to refresh
  3970. var scale = me.range.conversion(me.parent.width).scale;
  3971. var interval = 1 / scale / 10;
  3972. if (interval < 30) interval = 30;
  3973. if (interval > 1000) interval = 1000;
  3974. me.repaint();
  3975. // start a timer to adjust for the new time
  3976. me.currentTimeTimer = setTimeout(update, interval);
  3977. }
  3978. update();
  3979. };
  3980. /**
  3981. * Stop auto refreshing the current time bar
  3982. */
  3983. CurrentTime.prototype.stop = function stop() {
  3984. if (this.currentTimeTimer !== undefined) {
  3985. clearTimeout(this.currentTimeTimer);
  3986. delete this.currentTimeTimer;
  3987. }
  3988. };
  3989. /**
  3990. * A custom time bar
  3991. * @param {Object} [options] Available parameters:
  3992. * {Boolean} [showCustomTime]
  3993. * @constructor CustomTime
  3994. * @extends Component
  3995. */
  3996. function CustomTime (options) {
  3997. this.id = util.randomUUID();
  3998. this.options = options || {};
  3999. this.defaultOptions = {
  4000. showCustomTime: false
  4001. };
  4002. this.customTime = new Date();
  4003. this.eventParams = {}; // stores state parameters while dragging the bar
  4004. // create the DOM
  4005. this._create();
  4006. }
  4007. CustomTime.prototype = new Component();
  4008. CustomTime.prototype.setOptions = Component.prototype.setOptions;
  4009. /**
  4010. * Create the DOM for the custom time
  4011. * @private
  4012. */
  4013. CustomTime.prototype._create = function _create () {
  4014. var bar = document.createElement('div');
  4015. bar.className = 'customtime';
  4016. bar.style.position = 'absolute';
  4017. bar.style.top = '0px';
  4018. bar.style.height = '100%';
  4019. this.bar = bar;
  4020. var drag = document.createElement('div');
  4021. drag.style.position = 'relative';
  4022. drag.style.top = '0px';
  4023. drag.style.left = '-10px';
  4024. drag.style.height = '100%';
  4025. drag.style.width = '20px';
  4026. bar.appendChild(drag);
  4027. // attach event listeners
  4028. this.hammer = Hammer(bar, {
  4029. prevent_default: true
  4030. });
  4031. this.hammer.on('dragstart', this._onDragStart.bind(this));
  4032. this.hammer.on('drag', this._onDrag.bind(this));
  4033. this.hammer.on('dragend', this._onDragEnd.bind(this));
  4034. };
  4035. /**
  4036. * Get the frame element of the custom time bar
  4037. * @returns {HTMLElement} frame
  4038. */
  4039. CustomTime.prototype.getFrame = function getFrame() {
  4040. return this.bar;
  4041. };
  4042. /**
  4043. * Repaint the component
  4044. * @return {boolean} Returns true if the component is resized
  4045. */
  4046. CustomTime.prototype.repaint = function () {
  4047. var x = this.options.toScreen(this.customTime);
  4048. this.bar.style.left = x + 'px';
  4049. this.bar.title = 'Time: ' + this.customTime;
  4050. return false;
  4051. };
  4052. /**
  4053. * Set custom time.
  4054. * @param {Date} time
  4055. */
  4056. CustomTime.prototype.setCustomTime = function(time) {
  4057. this.customTime = new Date(time.valueOf());
  4058. this.repaint();
  4059. };
  4060. /**
  4061. * Retrieve the current custom time.
  4062. * @return {Date} customTime
  4063. */
  4064. CustomTime.prototype.getCustomTime = function() {
  4065. return new Date(this.customTime.valueOf());
  4066. };
  4067. /**
  4068. * Start moving horizontally
  4069. * @param {Event} event
  4070. * @private
  4071. */
  4072. CustomTime.prototype._onDragStart = function(event) {
  4073. this.eventParams.dragging = true;
  4074. this.eventParams.customTime = this.customTime;
  4075. event.stopPropagation();
  4076. event.preventDefault();
  4077. };
  4078. /**
  4079. * Perform moving operating.
  4080. * @param {Event} event
  4081. * @private
  4082. */
  4083. CustomTime.prototype._onDrag = function (event) {
  4084. if (!this.eventParams.dragging) return;
  4085. var deltaX = event.gesture.deltaX,
  4086. x = this.options.toScreen(this.eventParams.customTime) + deltaX,
  4087. time = this.options.toTime(x);
  4088. this.setCustomTime(time);
  4089. // fire a timechange event
  4090. this.emit('timechange', {
  4091. time: new Date(this.customTime.valueOf())
  4092. });
  4093. event.stopPropagation();
  4094. event.preventDefault();
  4095. };
  4096. /**
  4097. * Stop moving operating.
  4098. * @param {event} event
  4099. * @private
  4100. */
  4101. CustomTime.prototype._onDragEnd = function (event) {
  4102. if (!this.eventParams.dragging) return;
  4103. // fire a timechanged event
  4104. this.emit('timechanged', {
  4105. time: new Date(this.customTime.valueOf())
  4106. });
  4107. event.stopPropagation();
  4108. event.preventDefault();
  4109. };
  4110. /**
  4111. * Created by Alex on 5/6/14.
  4112. */
  4113. var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items
  4114. /**
  4115. * An ItemSet holds a set of items and ranges which can be displayed in a
  4116. * range. The width is determined by the parent of the ItemSet, and the height
  4117. * is determined by the size of the items.
  4118. * @param {Panel} backgroundPanel Panel which can be used to display the
  4119. * vertical lines of box items.
  4120. * @param {Panel} axisPanel Panel on the axis where the dots of box-items
  4121. * can be displayed.
  4122. * @param {Panel} sidePanel Left side panel holding labels
  4123. * @param {Object} [options] See ItemSet.setOptions for the available options.
  4124. * @constructor ItemSet
  4125. * @extends Panel
  4126. */
  4127. function Linegraph(backgroundPanel, axisPanel, sidePanel, options) {
  4128. this.id = util.randomUUID();
  4129. // one options object is shared by this itemset and all its items
  4130. this.options = options || {};
  4131. this.backgroundPanel = backgroundPanel;
  4132. this.axisPanel = axisPanel;
  4133. this.sidePanel = sidePanel;
  4134. this.itemOptions = Object.create(this.options);
  4135. this.dom = {};
  4136. this.hammer = null;
  4137. var me = this;
  4138. this.itemsData = null; // DataSet
  4139. this.groupsData = null; // DataSet
  4140. this.range = null; // Range or Object {start: number, end: number}
  4141. // listeners for the DataSet of the items
  4142. // this.itemListeners = {
  4143. // 'add': function (event, params, senderId) {
  4144. // if (senderId != me.id) me._onAdd(params.items);
  4145. // },
  4146. // 'update': function (event, params, senderId) {
  4147. // if (senderId != me.id) me._onUpdate(params.items);
  4148. // },
  4149. // 'remove': function (event, params, senderId) {
  4150. // if (senderId != me.id) me._onRemove(params.items);
  4151. // }
  4152. // };
  4153. //
  4154. // // listeners for the DataSet of the groups
  4155. // this.groupListeners = {
  4156. // 'add': function (event, params, senderId) {
  4157. // if (senderId != me.id) me._onAddGroups(params.items);
  4158. // },
  4159. // 'update': function (event, params, senderId) {
  4160. // if (senderId != me.id) me._onUpdateGroups(params.items);
  4161. // },
  4162. // 'remove': function (event, params, senderId) {
  4163. // if (senderId != me.id) me._onRemoveGroups(params.items);
  4164. // }
  4165. // };
  4166. this.items = {}; // object with an Item for every data item
  4167. this.groups = {}; // Group object for every group
  4168. this.groupIds = [];
  4169. this.selection = []; // list with the ids of all selected nodes
  4170. this.stackDirty = true; // if true, all items will be restacked on next repaint
  4171. this.touchParams = {}; // stores properties while dragging
  4172. // create the HTML DOM
  4173. this._create();
  4174. }
  4175. Linegraph.prototype = new Panel();
  4176. /**
  4177. * Create the HTML DOM for the ItemSet
  4178. */
  4179. Linegraph.prototype._create = function _create(){
  4180. var frame = document.createElement('div');
  4181. frame['timeline-linegraph'] = this;
  4182. this.frame = frame;
  4183. this.frame.className = 'itemset';
  4184. // create background panel
  4185. var background = document.createElement('div');
  4186. background.className = 'background';
  4187. this.backgroundPanel.frame.appendChild(background);
  4188. this.dom.background = background;
  4189. // create foreground panel
  4190. var foreground = document.createElement('div');
  4191. foreground.className = 'foreground';
  4192. frame.appendChild(foreground);
  4193. this.dom.foreground = foreground;
  4194. // // create axis panel
  4195. // var axis = document.createElement('div');
  4196. // axis.className = 'axis';
  4197. // this.dom.axis = axis;
  4198. // this.axisPanel.frame.appendChild(axis);
  4199. //
  4200. // // create labelset
  4201. // var labelSet = document.createElement('div');
  4202. // labelSet.className = 'labelset';
  4203. // this.dom.labelSet = labelSet;
  4204. // this.sidePanel.frame.appendChild(labelSet);
  4205. console.log(this.frame,this.frame.offsetWidth);
  4206. this.svg = document.createElementNS('http://www.w3.org/2000/svg',"svg");
  4207. this.svg.style.position = "relative"
  4208. this.svg.style.height = "300px";
  4209. this.path = document.createElementNS('http://www.w3.org/2000/svg',"path");
  4210. this.path.setAttributeNS(null, "fill","none");
  4211. this.path.setAttributeNS(null, "stroke","blue");
  4212. this.path.setAttributeNS(null, "stroke-width","1");
  4213. this.path2 = document.createElementNS('http://www.w3.org/2000/svg',"path");
  4214. this.path2.setAttributeNS(null, "fill","none");
  4215. this.path2.setAttributeNS(null, "stroke","red");
  4216. this.path2.setAttributeNS(null, "stroke-width","2");
  4217. this.dom.foreground.appendChild(this.svg);
  4218. this.svg.appendChild(this.path2);
  4219. this.svg.appendChild(this.path);
  4220. };
  4221. Linegraph.prototype.setData = function setData() {
  4222. console.log(this.frame,this.frame.offsetWidth);
  4223. var data = [];
  4224. this.startTime = this.range.start;
  4225. var min = 0;
  4226. var max = 1920;
  4227. var count = 10;
  4228. var scale = 30;
  4229. var offset = 0;
  4230. var step = (max-min) / count;
  4231. for (var i = 0; i < count; i++) {
  4232. data.push({x:Date.now() + i*step, y: 300*(i%2)})
  4233. }
  4234. console.log(data, this.width, this._previousWidth);
  4235. // catmull rom
  4236. var p0, p1, p2, p3, bp1, bp2, bp3;
  4237. var d2 = "M" + data[0].x + "," + data[0].y + " ";
  4238. for (var i = 0; i < data.length - 2; i++) {
  4239. if (i == 0) {
  4240. p0 = data[0]
  4241. }
  4242. else {
  4243. p0 = data[i-1];
  4244. }
  4245. p1 = data[i];
  4246. p2 = data[i+1];
  4247. p3 = data[i+2];
  4248. // Catmull-Rom to Cubic Bezier conversion matrix
  4249. // 0 1 0 0
  4250. // -1/6 1 1/6 0
  4251. // 0 1/6 1 -1/6
  4252. // 0 0 1 0
  4253. // bp0 = { x: p1.x, y: p1.y };
  4254. bp1 = { x: ((-p0.x + 6*p1.x + p2.x) / 6), y: ((-p0.y + 6*p1.y + p2.y) / 6)};
  4255. bp2 = { x: ((p1.x + 6*p2.x - p3.x) / 6), y: ((p1.y + 6*p2.y - p3.y) / 6)};
  4256. bp3 = { x: p2.x, y: p2.y };
  4257. d2 += "C" + bp1.x + "," + bp1.y + " " + bp2.x + "," + bp2.y + " " + bp3.x + "," + bp3.y + " ";
  4258. }
  4259. // linear
  4260. var d = "";
  4261. for (var i = 0; i < data.length - 1; i++) {
  4262. if (i == 0) {
  4263. d += "M" + data[i].x + "," + data[i].y;
  4264. }
  4265. else {
  4266. d += " " + data[i].x + "," + data[i].y;
  4267. }
  4268. }
  4269. this.path.setAttributeNS(null, "d",d);
  4270. this.path2.setAttributeNS(null, "d",d2);
  4271. //
  4272. }
  4273. /**
  4274. * Set options for the Linegraph. Existing options will be extended/overwritten.
  4275. * @param {Object} [options] The following options are available:
  4276. * {String | function} [className]
  4277. * class name for the itemset
  4278. * {String} [type]
  4279. * Default type for the items. Choose from 'box'
  4280. * (default), 'point', or 'range'. The default
  4281. * Style can be overwritten by individual items.
  4282. * {String} align
  4283. * Alignment for the items, only applicable for
  4284. * ItemBox. Choose 'center' (default), 'left', or
  4285. * 'right'.
  4286. * {String} orientation
  4287. * Orientation of the item set. Choose 'top' or
  4288. * 'bottom' (default).
  4289. * {Number} margin.axis
  4290. * Margin between the axis and the items in pixels.
  4291. * Default is 20.
  4292. * {Number} margin.item
  4293. * Margin between items in pixels. Default is 10.
  4294. * {Number} padding
  4295. * Padding of the contents of an item in pixels.
  4296. * Must correspond with the items css. Default is 5.
  4297. * {Function} snap
  4298. * Function to let items snap to nice dates when
  4299. * dragging items.
  4300. */
  4301. Linegraph.prototype.setOptions = function setOptions(options) {
  4302. Component.prototype.setOptions.call(this, options);
  4303. };
  4304. /**
  4305. * Set range (start and end).
  4306. * @param {Range | Object} range A Range or an object containing start and end.
  4307. */
  4308. Linegraph.prototype.setRange = function setRange(range) {
  4309. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  4310. throw new TypeError('Range must be an instance of Range, ' +
  4311. 'or an object containing start and end.');
  4312. }
  4313. this.range = range;
  4314. };
  4315. Linegraph.prototype.repaint = function repaint() {
  4316. var margin = this.options.margin,
  4317. range = this.range,
  4318. asSize = util.option.asSize,
  4319. asString = util.option.asString,
  4320. options = this.options,
  4321. orientation = this.getOption('orientation'),
  4322. resized = false,
  4323. frame = this.frame;
  4324. // TODO: document this feature to specify one margin for both item and axis distance
  4325. if (typeof margin === 'number') {
  4326. margin = {
  4327. item: margin,
  4328. axis: margin
  4329. };
  4330. }
  4331. // update className
  4332. this.frame.className = 'itemset' + (options.className ? (' ' + asString(options.className)) : '');
  4333. // check whether zoomed (in that case we need to re-stack everything)
  4334. // TODO: would be nicer to get this as a trigger from Range
  4335. var visibleInterval = this.range.end - this.range.start;
  4336. var zoomed = (visibleInterval != this.lastVisibleInterval) || (this.width != this.lastWidth);
  4337. if (zoomed) this.stackDirty = true;
  4338. this.lastVisibleInterval = visibleInterval;
  4339. this.lastWidth = this.width;
  4340. // reposition frame
  4341. this.frame.style.left = asSize(options.left, '');
  4342. this.frame.style.right = asSize(options.right, '');
  4343. this.frame.style.top = asSize((orientation == 'top') ? '0' : '');
  4344. this.frame.style.bottom = asSize((orientation == 'top') ? '' : '0');
  4345. this.frame.style.width = asSize(options.width, '100%');
  4346. // frame.style.height = asSize(height);
  4347. //frame.style.height = asSize('height' in options ? options.height : height); // TODO: reckon with height
  4348. // calculate actual size and position
  4349. this.top = this.frame.offsetTop;
  4350. this.left = this.frame.offsetLeft;
  4351. this.width = this.frame.offsetWidth;
  4352. // this.height = height;
  4353. // check if this component is resized
  4354. resized = this._isResized() || resized;
  4355. if (resized) {
  4356. this.svg.style.width = asSize(3*this.width)
  4357. }
  4358. this.setData();
  4359. }
  4360. var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items
  4361. /**
  4362. * An ItemSet holds a set of items and ranges which can be displayed in a
  4363. * range. The width is determined by the parent of the ItemSet, and the height
  4364. * is determined by the size of the items.
  4365. * @param {Panel} backgroundPanel Panel which can be used to display the
  4366. * vertical lines of box items.
  4367. * @param {Panel} axisPanel Panel on the axis where the dots of box-items
  4368. * can be displayed.
  4369. * @param {Panel} sidePanel Left side panel holding labels
  4370. * @param {Object} [options] See ItemSet.setOptions for the available options.
  4371. * @constructor ItemSet
  4372. * @extends Panel
  4373. */
  4374. function ItemSet(backgroundPanel, axisPanel, sidePanel, options) {
  4375. this.id = util.randomUUID();
  4376. // one options object is shared by this itemset and all its items
  4377. this.options = options || {};
  4378. this.backgroundPanel = backgroundPanel;
  4379. this.axisPanel = axisPanel;
  4380. this.sidePanel = sidePanel;
  4381. this.itemOptions = Object.create(this.options);
  4382. this.dom = {};
  4383. this.hammer = null;
  4384. var me = this;
  4385. this.itemsData = null; // DataSet
  4386. this.groupsData = null; // DataSet
  4387. this.range = null; // Range or Object {start: number, end: number}
  4388. // listeners for the DataSet of the items
  4389. this.itemListeners = {
  4390. 'add': function (event, params, senderId) {
  4391. if (senderId != me.id) me._onAdd(params.items);
  4392. },
  4393. 'update': function (event, params, senderId) {
  4394. if (senderId != me.id) me._onUpdate(params.items);
  4395. },
  4396. 'remove': function (event, params, senderId) {
  4397. if (senderId != me.id) me._onRemove(params.items);
  4398. }
  4399. };
  4400. // listeners for the DataSet of the groups
  4401. this.groupListeners = {
  4402. 'add': function (event, params, senderId) {
  4403. if (senderId != me.id) me._onAddGroups(params.items);
  4404. },
  4405. 'update': function (event, params, senderId) {
  4406. if (senderId != me.id) me._onUpdateGroups(params.items);
  4407. },
  4408. 'remove': function (event, params, senderId) {
  4409. if (senderId != me.id) me._onRemoveGroups(params.items);
  4410. }
  4411. };
  4412. this.items = {}; // object with an Item for every data item
  4413. this.groups = {}; // Group object for every group
  4414. this.groupIds = [];
  4415. this.selection = []; // list with the ids of all selected nodes
  4416. this.stackDirty = true; // if true, all items will be restacked on next repaint
  4417. this.touchParams = {}; // stores properties while dragging
  4418. // create the HTML DOM
  4419. this._create();
  4420. }
  4421. ItemSet.prototype = new Panel();
  4422. // available item types will be registered here
  4423. ItemSet.types = {
  4424. box: ItemBox,
  4425. range: ItemRange,
  4426. rangeoverflow: ItemRangeOverflow,
  4427. point: ItemPoint
  4428. };
  4429. /**
  4430. * Create the HTML DOM for the ItemSet
  4431. */
  4432. ItemSet.prototype._create = function _create(){
  4433. var frame = document.createElement('div');
  4434. frame['timeline-itemset'] = this;
  4435. this.frame = frame;
  4436. // create background panel
  4437. var background = document.createElement('div');
  4438. background.className = 'background';
  4439. this.backgroundPanel.frame.appendChild(background);
  4440. this.dom.background = background;
  4441. // create foreground panel
  4442. var foreground = document.createElement('div');
  4443. foreground.className = 'foreground';
  4444. frame.appendChild(foreground);
  4445. this.dom.foreground = foreground;
  4446. // create axis panel
  4447. var axis = document.createElement('div');
  4448. axis.className = 'axis';
  4449. this.dom.axis = axis;
  4450. this.axisPanel.frame.appendChild(axis);
  4451. // create labelset
  4452. var labelSet = document.createElement('div');
  4453. labelSet.className = 'labelset';
  4454. this.dom.labelSet = labelSet;
  4455. this.sidePanel.frame.appendChild(labelSet);
  4456. // create ungrouped Group
  4457. this._updateUngrouped();
  4458. // attach event listeners
  4459. // TODO: use event listeners from the rootpanel to improve performance?
  4460. this.hammer = Hammer(frame, {
  4461. prevent_default: true
  4462. });
  4463. this.hammer.on('dragstart', this._onDragStart.bind(this));
  4464. this.hammer.on('drag', this._onDrag.bind(this));
  4465. this.hammer.on('dragend', this._onDragEnd.bind(this));
  4466. };
  4467. /**
  4468. * Set options for the ItemSet. Existing options will be extended/overwritten.
  4469. * @param {Object} [options] The following options are available:
  4470. * {String | function} [className]
  4471. * class name for the itemset
  4472. * {String} [type]
  4473. * Default type for the items. Choose from 'box'
  4474. * (default), 'point', or 'range'. The default
  4475. * Style can be overwritten by individual items.
  4476. * {String} align
  4477. * Alignment for the items, only applicable for
  4478. * ItemBox. Choose 'center' (default), 'left', or
  4479. * 'right'.
  4480. * {String} orientation
  4481. * Orientation of the item set. Choose 'top' or
  4482. * 'bottom' (default).
  4483. * {Number} margin.axis
  4484. * Margin between the axis and the items in pixels.
  4485. * Default is 20.
  4486. * {Number} margin.item
  4487. * Margin between items in pixels. Default is 10.
  4488. * {Number} padding
  4489. * Padding of the contents of an item in pixels.
  4490. * Must correspond with the items css. Default is 5.
  4491. * {Function} snap
  4492. * Function to let items snap to nice dates when
  4493. * dragging items.
  4494. */
  4495. ItemSet.prototype.setOptions = function setOptions(options) {
  4496. Component.prototype.setOptions.call(this, options);
  4497. };
  4498. /**
  4499. * Mark the ItemSet dirty so it will refresh everything with next repaint
  4500. */
  4501. ItemSet.prototype.markDirty = function markDirty() {
  4502. this.groupIds = [];
  4503. this.stackDirty = true;
  4504. };
  4505. /**
  4506. * Hide the component from the DOM
  4507. */
  4508. ItemSet.prototype.hide = function hide() {
  4509. // remove the axis with dots
  4510. if (this.dom.axis.parentNode) {
  4511. this.dom.axis.parentNode.removeChild(this.dom.axis);
  4512. }
  4513. // remove the background with vertical lines
  4514. if (this.dom.background.parentNode) {
  4515. this.dom.background.parentNode.removeChild(this.dom.background);
  4516. }
  4517. // remove the labelset containing all group labels
  4518. if (this.dom.labelSet.parentNode) {
  4519. this.dom.labelSet.parentNode.removeChild(this.dom.labelSet);
  4520. }
  4521. };
  4522. /**
  4523. * Show the component in the DOM (when not already visible).
  4524. * @return {Boolean} changed
  4525. */
  4526. ItemSet.prototype.show = function show() {
  4527. // show axis with dots
  4528. if (!this.dom.axis.parentNode) {
  4529. this.axisPanel.frame.appendChild(this.dom.axis);
  4530. }
  4531. // show background with vertical lines
  4532. if (!this.dom.background.parentNode) {
  4533. this.backgroundPanel.frame.appendChild(this.dom.background);
  4534. }
  4535. // show labelset containing labels
  4536. if (!this.dom.labelSet.parentNode) {
  4537. this.sidePanel.frame.appendChild(this.dom.labelSet);
  4538. }
  4539. };
  4540. /**
  4541. * Set range (start and end).
  4542. * @param {Range | Object} range A Range or an object containing start and end.
  4543. */
  4544. ItemSet.prototype.setRange = function setRange(range) {
  4545. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  4546. throw new TypeError('Range must be an instance of Range, ' +
  4547. 'or an object containing start and end.');
  4548. }
  4549. this.range = range;
  4550. };
  4551. /**
  4552. * Set selected items by their id. Replaces the current selection
  4553. * Unknown id's are silently ignored.
  4554. * @param {Array} [ids] An array with zero or more id's of the items to be
  4555. * selected. If ids is an empty array, all items will be
  4556. * unselected.
  4557. */
  4558. ItemSet.prototype.setSelection = function setSelection(ids) {
  4559. var i, ii, id, item;
  4560. if (ids) {
  4561. if (!Array.isArray(ids)) {
  4562. throw new TypeError('Array expected');
  4563. }
  4564. // unselect currently selected items
  4565. for (i = 0, ii = this.selection.length; i < ii; i++) {
  4566. id = this.selection[i];
  4567. item = this.items[id];
  4568. if (item) item.unselect();
  4569. }
  4570. // select items
  4571. this.selection = [];
  4572. for (i = 0, ii = ids.length; i < ii; i++) {
  4573. id = ids[i];
  4574. item = this.items[id];
  4575. if (item) {
  4576. this.selection.push(id);
  4577. item.select();
  4578. }
  4579. }
  4580. }
  4581. };
  4582. /**
  4583. * Get the selected items by their id
  4584. * @return {Array} ids The ids of the selected items
  4585. */
  4586. ItemSet.prototype.getSelection = function getSelection() {
  4587. return this.selection.concat([]);
  4588. };
  4589. /**
  4590. * Deselect a selected item
  4591. * @param {String | Number} id
  4592. * @private
  4593. */
  4594. ItemSet.prototype._deselect = function _deselect(id) {
  4595. var selection = this.selection;
  4596. for (var i = 0, ii = selection.length; i < ii; i++) {
  4597. if (selection[i] == id) { // non-strict comparison!
  4598. selection.splice(i, 1);
  4599. break;
  4600. }
  4601. }
  4602. };
  4603. /**
  4604. * Return the item sets frame
  4605. * @returns {HTMLElement} frame
  4606. */
  4607. ItemSet.prototype.getFrame = function getFrame() {
  4608. return this.frame;
  4609. };
  4610. /**
  4611. * Repaint the component
  4612. * @return {boolean} Returns true if the component is resized
  4613. */
  4614. ItemSet.prototype.repaint = function repaint() {
  4615. var margin = this.options.margin,
  4616. range = this.range,
  4617. asSize = util.option.asSize,
  4618. asString = util.option.asString,
  4619. options = this.options,
  4620. orientation = this.getOption('orientation'),
  4621. resized = false,
  4622. frame = this.frame;
  4623. // TODO: document this feature to specify one margin for both item and axis distance
  4624. if (typeof margin === 'number') {
  4625. margin = {
  4626. item: margin,
  4627. axis: margin
  4628. };
  4629. }
  4630. // update className
  4631. frame.className = 'itemset' + (options.className ? (' ' + asString(options.className)) : '');
  4632. // reorder the groups (if needed)
  4633. resized = this._orderGroups() || resized;
  4634. // check whether zoomed (in that case we need to re-stack everything)
  4635. // TODO: would be nicer to get this as a trigger from Range
  4636. var visibleInterval = this.range.end - this.range.start;
  4637. var zoomed = (visibleInterval != this.lastVisibleInterval) || (this.width != this.lastWidth);
  4638. if (zoomed) this.stackDirty = true;
  4639. this.lastVisibleInterval = visibleInterval;
  4640. this.lastWidth = this.width;
  4641. // repaint all groups
  4642. var restack = this.stackDirty,
  4643. firstGroup = this._firstGroup(),
  4644. firstMargin = {
  4645. item: margin.item,
  4646. axis: margin.axis
  4647. },
  4648. nonFirstMargin = {
  4649. item: margin.item,
  4650. axis: margin.item / 2
  4651. },
  4652. height = 0,
  4653. minHeight = margin.axis + margin.item;
  4654. util.forEach(this.groups, function (group) {
  4655. var groupMargin = (group == firstGroup) ? firstMargin : nonFirstMargin;
  4656. resized = group.repaint(range, groupMargin, restack) || resized;
  4657. height += group.height;
  4658. });
  4659. height = Math.max(height, minHeight);
  4660. this.stackDirty = false;
  4661. // reposition frame
  4662. frame.style.left = asSize(options.left, '');
  4663. frame.style.right = asSize(options.right, '');
  4664. frame.style.top = asSize((orientation == 'top') ? '0' : '');
  4665. frame.style.bottom = asSize((orientation == 'top') ? '' : '0');
  4666. frame.style.width = asSize(options.width, '100%');
  4667. frame.style.height = asSize(height);
  4668. //frame.style.height = asSize('height' in options ? options.height : height); // TODO: reckon with height
  4669. // calculate actual size and position
  4670. this.top = frame.offsetTop;
  4671. this.left = frame.offsetLeft;
  4672. this.width = frame.offsetWidth;
  4673. this.height = height;
  4674. // reposition axis
  4675. this.dom.axis.style.left = asSize(options.left, '0');
  4676. this.dom.axis.style.right = asSize(options.right, '');
  4677. this.dom.axis.style.width = asSize(options.width, '100%');
  4678. this.dom.axis.style.height = asSize(0);
  4679. this.dom.axis.style.top = asSize((orientation == 'top') ? '0' : '');
  4680. this.dom.axis.style.bottom = asSize((orientation == 'top') ? '' : '0');
  4681. // check if this component is resized
  4682. resized = this._isResized() || resized;
  4683. return resized;
  4684. };
  4685. /**
  4686. * Get the first group, aligned with the axis
  4687. * @return {Group | null} firstGroup
  4688. * @private
  4689. */
  4690. ItemSet.prototype._firstGroup = function _firstGroup() {
  4691. var firstGroupIndex = (this.options.orientation == 'top') ? 0 : (this.groupIds.length - 1);
  4692. var firstGroupId = this.groupIds[firstGroupIndex];
  4693. var firstGroup = this.groups[firstGroupId] || this.groups[UNGROUPED];
  4694. return firstGroup || null;
  4695. };
  4696. /**
  4697. * Create or delete the group holding all ungrouped items. This group is used when
  4698. * there are no groups specified.
  4699. * @protected
  4700. */
  4701. ItemSet.prototype._updateUngrouped = function _updateUngrouped() {
  4702. var ungrouped = this.groups[UNGROUPED];
  4703. if (this.groupsData) {
  4704. // remove the group holding all ungrouped items
  4705. if (ungrouped) {
  4706. ungrouped.hide();
  4707. delete this.groups[UNGROUPED];
  4708. }
  4709. }
  4710. else {
  4711. // create a group holding all (unfiltered) items
  4712. if (!ungrouped) {
  4713. var id = null;
  4714. var data = null;
  4715. ungrouped = new Group(id, data, this);
  4716. this.groups[UNGROUPED] = ungrouped;
  4717. for (var itemId in this.items) {
  4718. if (this.items.hasOwnProperty(itemId)) {
  4719. ungrouped.add(this.items[itemId]);
  4720. }
  4721. }
  4722. ungrouped.show();
  4723. }
  4724. }
  4725. };
  4726. /**
  4727. * Get the foreground container element
  4728. * @return {HTMLElement} foreground
  4729. */
  4730. ItemSet.prototype.getForeground = function getForeground() {
  4731. return this.dom.foreground;
  4732. };
  4733. /**
  4734. * Get the background container element
  4735. * @return {HTMLElement} background
  4736. */
  4737. ItemSet.prototype.getBackground = function getBackground() {
  4738. return this.dom.background;
  4739. };
  4740. /**
  4741. * Get the axis container element
  4742. * @return {HTMLElement} axis
  4743. */
  4744. ItemSet.prototype.getAxis = function getAxis() {
  4745. return this.dom.axis;
  4746. };
  4747. /**
  4748. * Get the element for the labelset
  4749. * @return {HTMLElement} labelSet
  4750. */
  4751. ItemSet.prototype.getLabelSet = function getLabelSet() {
  4752. return this.dom.labelSet;
  4753. };
  4754. /**
  4755. * Set items
  4756. * @param {vis.DataSet | null} items
  4757. */
  4758. ItemSet.prototype.setItems = function setItems(items) {
  4759. var me = this,
  4760. ids,
  4761. oldItemsData = this.itemsData;
  4762. // replace the dataset
  4763. if (!items) {
  4764. this.itemsData = null;
  4765. }
  4766. else if (items instanceof DataSet || items instanceof DataView) {
  4767. this.itemsData = items;
  4768. }
  4769. else {
  4770. throw new TypeError('Data must be an instance of DataSet or DataView');
  4771. }
  4772. if (oldItemsData) {
  4773. // unsubscribe from old dataset
  4774. util.forEach(this.itemListeners, function (callback, event) {
  4775. oldItemsData.unsubscribe(event, callback);
  4776. });
  4777. // remove all drawn items
  4778. ids = oldItemsData.getIds();
  4779. this._onRemove(ids);
  4780. }
  4781. if (this.itemsData) {
  4782. // subscribe to new dataset
  4783. var id = this.id;
  4784. util.forEach(this.itemListeners, function (callback, event) {
  4785. me.itemsData.on(event, callback, id);
  4786. });
  4787. // add all new items
  4788. ids = this.itemsData.getIds();
  4789. this._onAdd(ids);
  4790. // update the group holding all ungrouped items
  4791. this._updateUngrouped();
  4792. }
  4793. };
  4794. /**
  4795. * Get the current items
  4796. * @returns {vis.DataSet | null}
  4797. */
  4798. ItemSet.prototype.getItems = function getItems() {
  4799. return this.itemsData;
  4800. };
  4801. /**
  4802. * Set groups
  4803. * @param {vis.DataSet} groups
  4804. */
  4805. ItemSet.prototype.setGroups = function setGroups(groups) {
  4806. var me = this,
  4807. ids;
  4808. // unsubscribe from current dataset
  4809. if (this.groupsData) {
  4810. util.forEach(this.groupListeners, function (callback, event) {
  4811. me.groupsData.unsubscribe(event, callback);
  4812. });
  4813. // remove all drawn groups
  4814. ids = this.groupsData.getIds();
  4815. this._onRemoveGroups(ids);
  4816. }
  4817. // replace the dataset
  4818. if (!groups) {
  4819. this.groupsData = null;
  4820. }
  4821. else if (groups instanceof DataSet || groups instanceof DataView) {
  4822. this.groupsData = groups;
  4823. }
  4824. else {
  4825. throw new TypeError('Data must be an instance of DataSet or DataView');
  4826. }
  4827. if (this.groupsData) {
  4828. // subscribe to new dataset
  4829. var id = this.id;
  4830. util.forEach(this.groupListeners, function (callback, event) {
  4831. me.groupsData.on(event, callback, id);
  4832. });
  4833. // draw all ms
  4834. ids = this.groupsData.getIds();
  4835. this._onAddGroups(ids);
  4836. }
  4837. // update the group holding all ungrouped items
  4838. this._updateUngrouped();
  4839. // update the order of all items in each group
  4840. this._order();
  4841. this.emit('change');
  4842. };
  4843. /**
  4844. * Get the current groups
  4845. * @returns {vis.DataSet | null} groups
  4846. */
  4847. ItemSet.prototype.getGroups = function getGroups() {
  4848. return this.groupsData;
  4849. };
  4850. /**
  4851. * Remove an item by its id
  4852. * @param {String | Number} id
  4853. */
  4854. ItemSet.prototype.removeItem = function removeItem (id) {
  4855. var item = this.itemsData.get(id),
  4856. dataset = this._myDataSet();
  4857. if (item) {
  4858. // confirm deletion
  4859. this.options.onRemove(item, function (item) {
  4860. if (item) {
  4861. // remove by id here, it is possible that an item has no id defined
  4862. // itself, so better not delete by the item itself
  4863. dataset.remove(id);
  4864. }
  4865. });
  4866. }
  4867. };
  4868. /**
  4869. * Handle updated items
  4870. * @param {Number[]} ids
  4871. * @protected
  4872. */
  4873. ItemSet.prototype._onUpdate = function _onUpdate(ids) {
  4874. var me = this,
  4875. items = this.items,
  4876. itemOptions = this.itemOptions;
  4877. ids.forEach(function (id) {
  4878. var itemData = me.itemsData.get(id),
  4879. item = items[id],
  4880. type = itemData.type ||
  4881. (itemData.start && itemData.end && 'range') ||
  4882. me.options.type ||
  4883. 'box';
  4884. var constructor = ItemSet.types[type];
  4885. if (item) {
  4886. // update item
  4887. if (!constructor || !(item instanceof constructor)) {
  4888. // item type has changed, delete the item and recreate it
  4889. me._removeItem(item);
  4890. item = null;
  4891. }
  4892. else {
  4893. me._updateItem(item, itemData);
  4894. }
  4895. }
  4896. if (!item) {
  4897. // create item
  4898. if (constructor) {
  4899. item = new constructor(itemData, me.options, itemOptions);
  4900. item.id = id; // TODO: not so nice setting id afterwards
  4901. me._addItem(item);
  4902. }
  4903. else {
  4904. throw new TypeError('Unknown item type "' + type + '"');
  4905. }
  4906. }
  4907. });
  4908. this._order();
  4909. this.stackDirty = true; // force re-stacking of all items next repaint
  4910. this.emit('change');
  4911. };
  4912. /**
  4913. * Handle added items
  4914. * @param {Number[]} ids
  4915. * @protected
  4916. */
  4917. ItemSet.prototype._onAdd = ItemSet.prototype._onUpdate;
  4918. /**
  4919. * Handle removed items
  4920. * @param {Number[]} ids
  4921. * @protected
  4922. */
  4923. ItemSet.prototype._onRemove = function _onRemove(ids) {
  4924. var count = 0;
  4925. var me = this;
  4926. ids.forEach(function (id) {
  4927. var item = me.items[id];
  4928. if (item) {
  4929. count++;
  4930. me._removeItem(item);
  4931. }
  4932. });
  4933. if (count) {
  4934. // update order
  4935. this._order();
  4936. this.stackDirty = true; // force re-stacking of all items next repaint
  4937. this.emit('change');
  4938. }
  4939. };
  4940. /**
  4941. * Update the order of item in all groups
  4942. * @private
  4943. */
  4944. ItemSet.prototype._order = function _order() {
  4945. // reorder the items in all groups
  4946. // TODO: optimization: only reorder groups affected by the changed items
  4947. util.forEach(this.groups, function (group) {
  4948. group.order();
  4949. });
  4950. };
  4951. /**
  4952. * Handle updated groups
  4953. * @param {Number[]} ids
  4954. * @private
  4955. */
  4956. ItemSet.prototype._onUpdateGroups = function _onUpdateGroups(ids) {
  4957. this._onAddGroups(ids);
  4958. };
  4959. /**
  4960. * Handle changed groups
  4961. * @param {Number[]} ids
  4962. * @private
  4963. */
  4964. ItemSet.prototype._onAddGroups = function _onAddGroups(ids) {
  4965. var me = this;
  4966. ids.forEach(function (id) {
  4967. var groupData = me.groupsData.get(id);
  4968. var group = me.groups[id];
  4969. if (!group) {
  4970. // check for reserved ids
  4971. if (id == UNGROUPED) {
  4972. throw new Error('Illegal group id. ' + id + ' is a reserved id.');
  4973. }
  4974. var groupOptions = Object.create(me.options);
  4975. util.extend(groupOptions, {
  4976. height: null
  4977. });
  4978. group = new Group(id, groupData, me);
  4979. me.groups[id] = group;
  4980. // add items with this groupId to the new group
  4981. for (var itemId in me.items) {
  4982. if (me.items.hasOwnProperty(itemId)) {
  4983. var item = me.items[itemId];
  4984. if (item.data.group == id) {
  4985. group.add(item);
  4986. }
  4987. }
  4988. }
  4989. group.order();
  4990. group.show();
  4991. }
  4992. else {
  4993. // update group
  4994. group.setData(groupData);
  4995. }
  4996. });
  4997. this.emit('change');
  4998. };
  4999. /**
  5000. * Handle removed groups
  5001. * @param {Number[]} ids
  5002. * @private
  5003. */
  5004. ItemSet.prototype._onRemoveGroups = function _onRemoveGroups(ids) {
  5005. var groups = this.groups;
  5006. ids.forEach(function (id) {
  5007. var group = groups[id];
  5008. if (group) {
  5009. group.hide();
  5010. delete groups[id];
  5011. }
  5012. });
  5013. this.markDirty();
  5014. this.emit('change');
  5015. };
  5016. /**
  5017. * Reorder the groups if needed
  5018. * @return {boolean} changed
  5019. * @private
  5020. */
  5021. ItemSet.prototype._orderGroups = function () {
  5022. if (this.groupsData) {
  5023. // reorder the groups
  5024. var groupIds = this.groupsData.getIds({
  5025. order: this.options.groupOrder
  5026. });
  5027. var changed = !util.equalArray(groupIds, this.groupIds);
  5028. if (changed) {
  5029. // hide all groups, removes them from the DOM
  5030. var groups = this.groups;
  5031. groupIds.forEach(function (groupId) {
  5032. var group = groups[groupId];
  5033. group.hide();
  5034. });
  5035. // show the groups again, attach them to the DOM in correct order
  5036. groupIds.forEach(function (groupId) {
  5037. groups[groupId].show();
  5038. });
  5039. this.groupIds = groupIds;
  5040. }
  5041. return changed;
  5042. }
  5043. else {
  5044. return false;
  5045. }
  5046. };
  5047. /**
  5048. * Add a new item
  5049. * @param {Item} item
  5050. * @private
  5051. */
  5052. ItemSet.prototype._addItem = function _addItem(item) {
  5053. this.items[item.id] = item;
  5054. // add to group
  5055. var groupId = this.groupsData ? item.data.group : UNGROUPED;
  5056. var group = this.groups[groupId];
  5057. if (group) group.add(item);
  5058. };
  5059. /**
  5060. * Update an existing item
  5061. * @param {Item} item
  5062. * @param {Object} itemData
  5063. * @private
  5064. */
  5065. ItemSet.prototype._updateItem = function _updateItem(item, itemData) {
  5066. var oldGroupId = item.data.group;
  5067. item.data = itemData;
  5068. if (item.displayed) {
  5069. item.repaint();
  5070. }
  5071. // update group
  5072. if (oldGroupId != item.data.group) {
  5073. var oldGroup = this.groups[oldGroupId];
  5074. if (oldGroup) oldGroup.remove(item);
  5075. var groupId = this.groupsData ? item.data.group : UNGROUPED;
  5076. var group = this.groups[groupId];
  5077. if (group) group.add(item);
  5078. }
  5079. };
  5080. /**
  5081. * Delete an item from the ItemSet: remove it from the DOM, from the map
  5082. * with items, and from the map with visible items, and from the selection
  5083. * @param {Item} item
  5084. * @private
  5085. */
  5086. ItemSet.prototype._removeItem = function _removeItem(item) {
  5087. // remove from DOM
  5088. item.hide();
  5089. // remove from items
  5090. delete this.items[item.id];
  5091. // remove from selection
  5092. var index = this.selection.indexOf(item.id);
  5093. if (index != -1) this.selection.splice(index, 1);
  5094. // remove from group
  5095. var groupId = this.groupsData ? item.data.group : UNGROUPED;
  5096. var group = this.groups[groupId];
  5097. if (group) group.remove(item);
  5098. };
  5099. /**
  5100. * Create an array containing all items being a range (having an end date)
  5101. * @param array
  5102. * @returns {Array}
  5103. * @private
  5104. */
  5105. ItemSet.prototype._constructByEndArray = function _constructByEndArray(array) {
  5106. var endArray = [];
  5107. for (var i = 0; i < array.length; i++) {
  5108. if (array[i] instanceof ItemRange) {
  5109. endArray.push(array[i]);
  5110. }
  5111. }
  5112. return endArray;
  5113. };
  5114. /**
  5115. * Get the width of the group labels
  5116. * @return {Number} width
  5117. */
  5118. ItemSet.prototype.getLabelsWidth = function getLabelsWidth() {
  5119. var width = 0;
  5120. util.forEach(this.groups, function (group) {
  5121. width = Math.max(width, group.getLabelWidth());
  5122. });
  5123. return width;
  5124. };
  5125. /**
  5126. * Get the height of the itemsets background
  5127. * @return {Number} height
  5128. */
  5129. ItemSet.prototype.getBackgroundHeight = function getBackgroundHeight() {
  5130. return this.height;
  5131. };
  5132. /**
  5133. * Start dragging the selected events
  5134. * @param {Event} event
  5135. * @private
  5136. */
  5137. ItemSet.prototype._onDragStart = function (event) {
  5138. if (!this.options.editable.updateTime && !this.options.editable.updateGroup) {
  5139. return;
  5140. }
  5141. var item = ItemSet.itemFromTarget(event),
  5142. me = this,
  5143. props;
  5144. if (item && item.selected) {
  5145. var dragLeftItem = event.target.dragLeftItem;
  5146. var dragRightItem = event.target.dragRightItem;
  5147. if (dragLeftItem) {
  5148. props = {
  5149. item: dragLeftItem
  5150. };
  5151. if (me.options.editable.updateTime) {
  5152. props.start = item.data.start.valueOf();
  5153. }
  5154. if (me.options.editable.updateGroup) {
  5155. if ('group' in item.data) props.group = item.data.group;
  5156. }
  5157. this.touchParams.itemProps = [props];
  5158. }
  5159. else if (dragRightItem) {
  5160. props = {
  5161. item: dragRightItem
  5162. };
  5163. if (me.options.editable.updateTime) {
  5164. props.end = item.data.end.valueOf();
  5165. }
  5166. if (me.options.editable.updateGroup) {
  5167. if ('group' in item.data) props.group = item.data.group;
  5168. }
  5169. this.touchParams.itemProps = [props];
  5170. }
  5171. else {
  5172. this.touchParams.itemProps = this.getSelection().map(function (id) {
  5173. var item = me.items[id];
  5174. var props = {
  5175. item: item
  5176. };
  5177. if (me.options.editable.updateTime) {
  5178. if ('start' in item.data) props.start = item.data.start.valueOf();
  5179. if ('end' in item.data) props.end = item.data.end.valueOf();
  5180. }
  5181. if (me.options.editable.updateGroup) {
  5182. if ('group' in item.data) props.group = item.data.group;
  5183. }
  5184. return props;
  5185. });
  5186. }
  5187. event.stopPropagation();
  5188. }
  5189. };
  5190. /**
  5191. * Drag selected items
  5192. * @param {Event} event
  5193. * @private
  5194. */
  5195. ItemSet.prototype._onDrag = function (event) {
  5196. if (this.touchParams.itemProps) {
  5197. var snap = this.options.snap || null,
  5198. deltaX = event.gesture.deltaX,
  5199. scale = (this.width / (this.range.end - this.range.start)),
  5200. offset = deltaX / scale;
  5201. // move
  5202. this.touchParams.itemProps.forEach(function (props) {
  5203. if ('start' in props) {
  5204. var start = new Date(props.start + offset);
  5205. props.item.data.start = snap ? snap(start) : start;
  5206. }
  5207. if ('end' in props) {
  5208. var end = new Date(props.end + offset);
  5209. props.item.data.end = snap ? snap(end) : end;
  5210. }
  5211. if ('group' in props) {
  5212. // drag from one group to another
  5213. var group = ItemSet.groupFromTarget(event);
  5214. if (group && group.groupId != props.item.data.group) {
  5215. var oldGroup = props.item.parent;
  5216. oldGroup.remove(props.item);
  5217. oldGroup.order();
  5218. group.add(props.item);
  5219. group.order();
  5220. props.item.data.group = group.groupId;
  5221. }
  5222. }
  5223. });
  5224. // TODO: implement onMoving handler
  5225. this.stackDirty = true; // force re-stacking of all items next repaint
  5226. this.emit('change');
  5227. event.stopPropagation();
  5228. }
  5229. };
  5230. /**
  5231. * End of dragging selected items
  5232. * @param {Event} event
  5233. * @private
  5234. */
  5235. ItemSet.prototype._onDragEnd = function (event) {
  5236. if (this.touchParams.itemProps) {
  5237. // prepare a change set for the changed items
  5238. var changes = [],
  5239. me = this,
  5240. dataset = this._myDataSet();
  5241. this.touchParams.itemProps.forEach(function (props) {
  5242. var id = props.item.id,
  5243. itemData = me.itemsData.get(id);
  5244. var changed = false;
  5245. if ('start' in props.item.data) {
  5246. changed = (props.start != props.item.data.start.valueOf());
  5247. itemData.start = util.convert(props.item.data.start, dataset.convert['start']);
  5248. }
  5249. if ('end' in props.item.data) {
  5250. changed = changed || (props.end != props.item.data.end.valueOf());
  5251. itemData.end = util.convert(props.item.data.end, dataset.convert['end']);
  5252. }
  5253. if ('group' in props.item.data) {
  5254. changed = changed || (props.group != props.item.data.group);
  5255. itemData.group = props.item.data.group;
  5256. }
  5257. // only apply changes when start or end is actually changed
  5258. if (changed) {
  5259. me.options.onMove(itemData, function (itemData) {
  5260. if (itemData) {
  5261. // apply changes
  5262. itemData[dataset.fieldId] = id; // ensure the item contains its id (can be undefined)
  5263. changes.push(itemData);
  5264. }
  5265. else {
  5266. // restore original values
  5267. if ('start' in props) props.item.data.start = props.start;
  5268. if ('end' in props) props.item.data.end = props.end;
  5269. me.stackDirty = true; // force re-stacking of all items next repaint
  5270. me.emit('change');
  5271. }
  5272. });
  5273. }
  5274. });
  5275. this.touchParams.itemProps = null;
  5276. // apply the changes to the data (if there are changes)
  5277. if (changes.length) {
  5278. dataset.update(changes);
  5279. }
  5280. event.stopPropagation();
  5281. }
  5282. };
  5283. /**
  5284. * Find an item from an event target:
  5285. * searches for the attribute 'timeline-item' in the event target's element tree
  5286. * @param {Event} event
  5287. * @return {Item | null} item
  5288. */
  5289. ItemSet.itemFromTarget = function itemFromTarget (event) {
  5290. var target = event.target;
  5291. while (target) {
  5292. if (target.hasOwnProperty('timeline-item')) {
  5293. return target['timeline-item'];
  5294. }
  5295. target = target.parentNode;
  5296. }
  5297. return null;
  5298. };
  5299. /**
  5300. * Find the Group from an event target:
  5301. * searches for the attribute 'timeline-group' in the event target's element tree
  5302. * @param {Event} event
  5303. * @return {Group | null} group
  5304. */
  5305. ItemSet.groupFromTarget = function groupFromTarget (event) {
  5306. var target = event.target;
  5307. while (target) {
  5308. if (target.hasOwnProperty('timeline-group')) {
  5309. return target['timeline-group'];
  5310. }
  5311. target = target.parentNode;
  5312. }
  5313. return null;
  5314. };
  5315. /**
  5316. * Find the ItemSet from an event target:
  5317. * searches for the attribute 'timeline-itemset' in the event target's element tree
  5318. * @param {Event} event
  5319. * @return {ItemSet | null} item
  5320. */
  5321. ItemSet.itemSetFromTarget = function itemSetFromTarget (event) {
  5322. var target = event.target;
  5323. while (target) {
  5324. if (target.hasOwnProperty('timeline-itemset')) {
  5325. return target['timeline-itemset'];
  5326. }
  5327. target = target.parentNode;
  5328. }
  5329. return null;
  5330. };
  5331. /**
  5332. * Find the DataSet to which this ItemSet is connected
  5333. * @returns {null | DataSet} dataset
  5334. * @private
  5335. */
  5336. ItemSet.prototype._myDataSet = function _myDataSet() {
  5337. // find the root DataSet
  5338. var dataset = this.itemsData;
  5339. while (dataset instanceof DataView) {
  5340. dataset = dataset.data;
  5341. }
  5342. return dataset;
  5343. };
  5344. /**
  5345. * @constructor Item
  5346. * @param {Object} data Object containing (optional) parameters type,
  5347. * start, end, content, group, className.
  5348. * @param {Object} [options] Options to set initial property values
  5349. * @param {Object} [defaultOptions] default options
  5350. * // TODO: describe available options
  5351. */
  5352. function Item (data, options, defaultOptions) {
  5353. this.id = null;
  5354. this.parent = null;
  5355. this.data = data;
  5356. this.dom = null;
  5357. this.options = options || {};
  5358. this.defaultOptions = defaultOptions || {};
  5359. this.selected = false;
  5360. this.displayed = false;
  5361. this.dirty = true;
  5362. this.top = null;
  5363. this.left = null;
  5364. this.width = null;
  5365. this.height = null;
  5366. }
  5367. /**
  5368. * Select current item
  5369. */
  5370. Item.prototype.select = function select() {
  5371. this.selected = true;
  5372. if (this.displayed) this.repaint();
  5373. };
  5374. /**
  5375. * Unselect current item
  5376. */
  5377. Item.prototype.unselect = function unselect() {
  5378. this.selected = false;
  5379. if (this.displayed) this.repaint();
  5380. };
  5381. /**
  5382. * Set a parent for the item
  5383. * @param {ItemSet | Group} parent
  5384. */
  5385. Item.prototype.setParent = function setParent(parent) {
  5386. if (this.displayed) {
  5387. this.hide();
  5388. this.parent = parent;
  5389. if (this.parent) {
  5390. this.show();
  5391. }
  5392. }
  5393. else {
  5394. this.parent = parent;
  5395. }
  5396. };
  5397. /**
  5398. * Check whether this item is visible inside given range
  5399. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  5400. * @returns {boolean} True if visible
  5401. */
  5402. Item.prototype.isVisible = function isVisible (range) {
  5403. // Should be implemented by Item implementations
  5404. return false;
  5405. };
  5406. /**
  5407. * Show the Item in the DOM (when not already visible)
  5408. * @return {Boolean} changed
  5409. */
  5410. Item.prototype.show = function show() {
  5411. return false;
  5412. };
  5413. /**
  5414. * Hide the Item from the DOM (when visible)
  5415. * @return {Boolean} changed
  5416. */
  5417. Item.prototype.hide = function hide() {
  5418. return false;
  5419. };
  5420. /**
  5421. * Repaint the item
  5422. */
  5423. Item.prototype.repaint = function repaint() {
  5424. // should be implemented by the item
  5425. };
  5426. /**
  5427. * Reposition the Item horizontally
  5428. */
  5429. Item.prototype.repositionX = function repositionX() {
  5430. // should be implemented by the item
  5431. };
  5432. /**
  5433. * Reposition the Item vertically
  5434. */
  5435. Item.prototype.repositionY = function repositionY() {
  5436. // should be implemented by the item
  5437. };
  5438. /**
  5439. * Repaint a delete button on the top right of the item when the item is selected
  5440. * @param {HTMLElement} anchor
  5441. * @protected
  5442. */
  5443. Item.prototype._repaintDeleteButton = function (anchor) {
  5444. if (this.selected && this.options.editable.remove && !this.dom.deleteButton) {
  5445. // create and show button
  5446. var me = this;
  5447. var deleteButton = document.createElement('div');
  5448. deleteButton.className = 'delete';
  5449. deleteButton.title = 'Delete this item';
  5450. Hammer(deleteButton, {
  5451. preventDefault: true
  5452. }).on('tap', function (event) {
  5453. me.parent.removeFromDataSet(me);
  5454. event.stopPropagation();
  5455. });
  5456. anchor.appendChild(deleteButton);
  5457. this.dom.deleteButton = deleteButton;
  5458. }
  5459. else if (!this.selected && this.dom.deleteButton) {
  5460. // remove button
  5461. if (this.dom.deleteButton.parentNode) {
  5462. this.dom.deleteButton.parentNode.removeChild(this.dom.deleteButton);
  5463. }
  5464. this.dom.deleteButton = null;
  5465. }
  5466. };
  5467. /**
  5468. * @constructor ItemBox
  5469. * @extends Item
  5470. * @param {Object} data Object containing parameters start
  5471. * content, className.
  5472. * @param {Object} [options] Options to set initial property values
  5473. * @param {Object} [defaultOptions] default options
  5474. * // TODO: describe available options
  5475. */
  5476. function ItemBox (data, options, defaultOptions) {
  5477. this.props = {
  5478. dot: {
  5479. width: 0,
  5480. height: 0
  5481. },
  5482. line: {
  5483. width: 0,
  5484. height: 0
  5485. }
  5486. };
  5487. // validate data
  5488. if (data) {
  5489. if (data.start == undefined) {
  5490. throw new Error('Property "start" missing in item ' + data);
  5491. }
  5492. }
  5493. Item.call(this, data, options, defaultOptions);
  5494. }
  5495. ItemBox.prototype = new Item (null);
  5496. /**
  5497. * Check whether this item is visible inside given range
  5498. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  5499. * @returns {boolean} True if visible
  5500. */
  5501. ItemBox.prototype.isVisible = function isVisible (range) {
  5502. // determine visibility
  5503. // TODO: account for the real width of the item. Right now we just add 1/4 to the window
  5504. var interval = (range.end - range.start) / 4;
  5505. return (this.data.start > range.start - interval) && (this.data.start < range.end + interval);
  5506. };
  5507. /**
  5508. * Repaint the item
  5509. */
  5510. ItemBox.prototype.repaint = function repaint() {
  5511. var dom = this.dom;
  5512. if (!dom) {
  5513. // create DOM
  5514. this.dom = {};
  5515. dom = this.dom;
  5516. // create main box
  5517. dom.box = document.createElement('DIV');
  5518. // contents box (inside the background box). used for making margins
  5519. dom.content = document.createElement('DIV');
  5520. dom.content.className = 'content';
  5521. dom.box.appendChild(dom.content);
  5522. // line to axis
  5523. dom.line = document.createElement('DIV');
  5524. dom.line.className = 'line';
  5525. // dot on axis
  5526. dom.dot = document.createElement('DIV');
  5527. dom.dot.className = 'dot';
  5528. // attach this item as attribute
  5529. dom.box['timeline-item'] = this;
  5530. }
  5531. // append DOM to parent DOM
  5532. if (!this.parent) {
  5533. throw new Error('Cannot repaint item: no parent attached');
  5534. }
  5535. if (!dom.box.parentNode) {
  5536. var foreground = this.parent.getForeground();
  5537. if (!foreground) throw new Error('Cannot repaint time axis: parent has no foreground container element');
  5538. foreground.appendChild(dom.box);
  5539. }
  5540. if (!dom.line.parentNode) {
  5541. var background = this.parent.getBackground();
  5542. if (!background) throw new Error('Cannot repaint time axis: parent has no background container element');
  5543. background.appendChild(dom.line);
  5544. }
  5545. if (!dom.dot.parentNode) {
  5546. var axis = this.parent.getAxis();
  5547. if (!background) throw new Error('Cannot repaint time axis: parent has no axis container element');
  5548. axis.appendChild(dom.dot);
  5549. }
  5550. this.displayed = true;
  5551. // update contents
  5552. if (this.data.content != this.content) {
  5553. this.content = this.data.content;
  5554. if (this.content instanceof Element) {
  5555. dom.content.innerHTML = '';
  5556. dom.content.appendChild(this.content);
  5557. }
  5558. else if (this.data.content != undefined) {
  5559. dom.content.innerHTML = this.content;
  5560. }
  5561. else {
  5562. throw new Error('Property "content" missing in item ' + this.data.id);
  5563. }
  5564. this.dirty = true;
  5565. }
  5566. // update class
  5567. var className = (this.data.className? ' ' + this.data.className : '') +
  5568. (this.selected ? ' selected' : '');
  5569. if (this.className != className) {
  5570. this.className = className;
  5571. dom.box.className = 'item box' + className;
  5572. dom.line.className = 'item line' + className;
  5573. dom.dot.className = 'item dot' + className;
  5574. this.dirty = true;
  5575. }
  5576. // recalculate size
  5577. if (this.dirty) {
  5578. this.props.dot.height = dom.dot.offsetHeight;
  5579. this.props.dot.width = dom.dot.offsetWidth;
  5580. this.props.line.width = dom.line.offsetWidth;
  5581. this.width = dom.box.offsetWidth;
  5582. this.height = dom.box.offsetHeight;
  5583. this.dirty = false;
  5584. }
  5585. this._repaintDeleteButton(dom.box);
  5586. };
  5587. /**
  5588. * Show the item in the DOM (when not already displayed). The items DOM will
  5589. * be created when needed.
  5590. */
  5591. ItemBox.prototype.show = function show() {
  5592. if (!this.displayed) {
  5593. this.repaint();
  5594. }
  5595. };
  5596. /**
  5597. * Hide the item from the DOM (when visible)
  5598. */
  5599. ItemBox.prototype.hide = function hide() {
  5600. if (this.displayed) {
  5601. var dom = this.dom;
  5602. if (dom.box.parentNode) dom.box.parentNode.removeChild(dom.box);
  5603. if (dom.line.parentNode) dom.line.parentNode.removeChild(dom.line);
  5604. if (dom.dot.parentNode) dom.dot.parentNode.removeChild(dom.dot);
  5605. this.top = null;
  5606. this.left = null;
  5607. this.displayed = false;
  5608. }
  5609. };
  5610. /**
  5611. * Reposition the item horizontally
  5612. * @Override
  5613. */
  5614. ItemBox.prototype.repositionX = function repositionX() {
  5615. var start = this.defaultOptions.toScreen(this.data.start),
  5616. align = this.options.align || this.defaultOptions.align,
  5617. left,
  5618. box = this.dom.box,
  5619. line = this.dom.line,
  5620. dot = this.dom.dot;
  5621. // calculate left position of the box
  5622. if (align == 'right') {
  5623. this.left = start - this.width;
  5624. }
  5625. else if (align == 'left') {
  5626. this.left = start;
  5627. }
  5628. else {
  5629. // default or 'center'
  5630. this.left = start - this.width / 2;
  5631. }
  5632. // reposition box
  5633. box.style.left = this.left + 'px';
  5634. // reposition line
  5635. line.style.left = (start - this.props.line.width / 2) + 'px';
  5636. // reposition dot
  5637. dot.style.left = (start - this.props.dot.width / 2) + 'px';
  5638. };
  5639. /**
  5640. * Reposition the item vertically
  5641. * @Override
  5642. */
  5643. ItemBox.prototype.repositionY = function repositionY () {
  5644. var orientation = this.options.orientation || this.defaultOptions.orientation,
  5645. box = this.dom.box,
  5646. line = this.dom.line,
  5647. dot = this.dom.dot;
  5648. if (orientation == 'top') {
  5649. box.style.top = (this.top || 0) + 'px';
  5650. box.style.bottom = '';
  5651. line.style.top = '0';
  5652. line.style.bottom = '';
  5653. line.style.height = (this.parent.top + this.top + 1) + 'px';
  5654. }
  5655. else { // orientation 'bottom'
  5656. box.style.top = '';
  5657. box.style.bottom = (this.top || 0) + 'px';
  5658. line.style.top = (this.parent.top + this.parent.height - this.top - 1) + 'px';
  5659. line.style.bottom = '0';
  5660. line.style.height = '';
  5661. }
  5662. dot.style.top = (-this.props.dot.height / 2) + 'px';
  5663. };
  5664. /**
  5665. * @constructor ItemPoint
  5666. * @extends Item
  5667. * @param {Object} data Object containing parameters start
  5668. * content, className.
  5669. * @param {Object} [options] Options to set initial property values
  5670. * @param {Object} [defaultOptions] default options
  5671. * // TODO: describe available options
  5672. */
  5673. function ItemPoint (data, options, defaultOptions) {
  5674. this.props = {
  5675. dot: {
  5676. top: 0,
  5677. width: 0,
  5678. height: 0
  5679. },
  5680. content: {
  5681. height: 0,
  5682. marginLeft: 0
  5683. }
  5684. };
  5685. // validate data
  5686. if (data) {
  5687. if (data.start == undefined) {
  5688. throw new Error('Property "start" missing in item ' + data);
  5689. }
  5690. }
  5691. Item.call(this, data, options, defaultOptions);
  5692. }
  5693. ItemPoint.prototype = new Item (null);
  5694. /**
  5695. * Check whether this item is visible inside given range
  5696. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  5697. * @returns {boolean} True if visible
  5698. */
  5699. ItemPoint.prototype.isVisible = function isVisible (range) {
  5700. // determine visibility
  5701. // TODO: account for the real width of the item. Right now we just add 1/4 to the window
  5702. var interval = (range.end - range.start) / 4;
  5703. return (this.data.start > range.start - interval) && (this.data.start < range.end + interval);
  5704. };
  5705. /**
  5706. * Repaint the item
  5707. */
  5708. ItemPoint.prototype.repaint = function repaint() {
  5709. var dom = this.dom;
  5710. if (!dom) {
  5711. // create DOM
  5712. this.dom = {};
  5713. dom = this.dom;
  5714. // background box
  5715. dom.point = document.createElement('div');
  5716. // className is updated in repaint()
  5717. // contents box, right from the dot
  5718. dom.content = document.createElement('div');
  5719. dom.content.className = 'content';
  5720. dom.point.appendChild(dom.content);
  5721. // dot at start
  5722. dom.dot = document.createElement('div');
  5723. dom.point.appendChild(dom.dot);
  5724. // attach this item as attribute
  5725. dom.point['timeline-item'] = this;
  5726. }
  5727. // append DOM to parent DOM
  5728. if (!this.parent) {
  5729. throw new Error('Cannot repaint item: no parent attached');
  5730. }
  5731. if (!dom.point.parentNode) {
  5732. var foreground = this.parent.getForeground();
  5733. if (!foreground) {
  5734. throw new Error('Cannot repaint time axis: parent has no foreground container element');
  5735. }
  5736. foreground.appendChild(dom.point);
  5737. }
  5738. this.displayed = true;
  5739. // update contents
  5740. if (this.data.content != this.content) {
  5741. this.content = this.data.content;
  5742. if (this.content instanceof Element) {
  5743. dom.content.innerHTML = '';
  5744. dom.content.appendChild(this.content);
  5745. }
  5746. else if (this.data.content != undefined) {
  5747. dom.content.innerHTML = this.content;
  5748. }
  5749. else {
  5750. throw new Error('Property "content" missing in item ' + this.data.id);
  5751. }
  5752. this.dirty = true;
  5753. }
  5754. // update class
  5755. var className = (this.data.className? ' ' + this.data.className : '') +
  5756. (this.selected ? ' selected' : '');
  5757. if (this.className != className) {
  5758. this.className = className;
  5759. dom.point.className = 'item point' + className;
  5760. dom.dot.className = 'item dot' + className;
  5761. this.dirty = true;
  5762. }
  5763. // recalculate size
  5764. if (this.dirty) {
  5765. this.width = dom.point.offsetWidth;
  5766. this.height = dom.point.offsetHeight;
  5767. this.props.dot.width = dom.dot.offsetWidth;
  5768. this.props.dot.height = dom.dot.offsetHeight;
  5769. this.props.content.height = dom.content.offsetHeight;
  5770. // resize contents
  5771. dom.content.style.marginLeft = 2 * this.props.dot.width + 'px';
  5772. //dom.content.style.marginRight = ... + 'px'; // TODO: margin right
  5773. dom.dot.style.top = ((this.height - this.props.dot.height) / 2) + 'px';
  5774. dom.dot.style.left = (this.props.dot.width / 2) + 'px';
  5775. this.dirty = false;
  5776. }
  5777. this._repaintDeleteButton(dom.point);
  5778. };
  5779. /**
  5780. * Show the item in the DOM (when not already visible). The items DOM will
  5781. * be created when needed.
  5782. */
  5783. ItemPoint.prototype.show = function show() {
  5784. if (!this.displayed) {
  5785. this.repaint();
  5786. }
  5787. };
  5788. /**
  5789. * Hide the item from the DOM (when visible)
  5790. */
  5791. ItemPoint.prototype.hide = function hide() {
  5792. if (this.displayed) {
  5793. if (this.dom.point.parentNode) {
  5794. this.dom.point.parentNode.removeChild(this.dom.point);
  5795. }
  5796. this.top = null;
  5797. this.left = null;
  5798. this.displayed = false;
  5799. }
  5800. };
  5801. /**
  5802. * Reposition the item horizontally
  5803. * @Override
  5804. */
  5805. ItemPoint.prototype.repositionX = function repositionX() {
  5806. var start = this.defaultOptions.toScreen(this.data.start);
  5807. this.left = start - this.props.dot.width;
  5808. // reposition point
  5809. this.dom.point.style.left = this.left + 'px';
  5810. };
  5811. /**
  5812. * Reposition the item vertically
  5813. * @Override
  5814. */
  5815. ItemPoint.prototype.repositionY = function repositionY () {
  5816. var orientation = this.options.orientation || this.defaultOptions.orientation,
  5817. point = this.dom.point;
  5818. if (orientation == 'top') {
  5819. point.style.top = this.top + 'px';
  5820. point.style.bottom = '';
  5821. }
  5822. else {
  5823. point.style.top = '';
  5824. point.style.bottom = this.top + 'px';
  5825. }
  5826. };
  5827. /**
  5828. * @constructor ItemRange
  5829. * @extends Item
  5830. * @param {Object} data Object containing parameters start, end
  5831. * content, className.
  5832. * @param {Object} [options] Options to set initial property values
  5833. * @param {Object} [defaultOptions] default options
  5834. * // TODO: describe available options
  5835. */
  5836. function ItemRange (data, options, defaultOptions) {
  5837. this.props = {
  5838. content: {
  5839. width: 0
  5840. }
  5841. };
  5842. // validate data
  5843. if (data) {
  5844. if (data.start == undefined) {
  5845. throw new Error('Property "start" missing in item ' + data.id);
  5846. }
  5847. if (data.end == undefined) {
  5848. throw new Error('Property "end" missing in item ' + data.id);
  5849. }
  5850. }
  5851. Item.call(this, data, options, defaultOptions);
  5852. }
  5853. ItemRange.prototype = new Item (null);
  5854. ItemRange.prototype.baseClassName = 'item range';
  5855. /**
  5856. * Check whether this item is visible inside given range
  5857. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  5858. * @returns {boolean} True if visible
  5859. */
  5860. ItemRange.prototype.isVisible = function isVisible (range) {
  5861. // determine visibility
  5862. return (this.data.start < range.end) && (this.data.end > range.start);
  5863. };
  5864. /**
  5865. * Repaint the item
  5866. */
  5867. ItemRange.prototype.repaint = function repaint() {
  5868. var dom = this.dom;
  5869. if (!dom) {
  5870. // create DOM
  5871. this.dom = {};
  5872. dom = this.dom;
  5873. // background box
  5874. dom.box = document.createElement('div');
  5875. // className is updated in repaint()
  5876. // contents box
  5877. dom.content = document.createElement('div');
  5878. dom.content.className = 'content';
  5879. dom.box.appendChild(dom.content);
  5880. // attach this item as attribute
  5881. dom.box['timeline-item'] = this;
  5882. }
  5883. // append DOM to parent DOM
  5884. if (!this.parent) {
  5885. throw new Error('Cannot repaint item: no parent attached');
  5886. }
  5887. if (!dom.box.parentNode) {
  5888. var foreground = this.parent.getForeground();
  5889. if (!foreground) {
  5890. throw new Error('Cannot repaint time axis: parent has no foreground container element');
  5891. }
  5892. foreground.appendChild(dom.box);
  5893. }
  5894. this.displayed = true;
  5895. // update contents
  5896. if (this.data.content != this.content) {
  5897. this.content = this.data.content;
  5898. if (this.content instanceof Element) {
  5899. dom.content.innerHTML = '';
  5900. dom.content.appendChild(this.content);
  5901. }
  5902. else if (this.data.content != undefined) {
  5903. dom.content.innerHTML = this.content;
  5904. }
  5905. else {
  5906. throw new Error('Property "content" missing in item ' + this.data.id);
  5907. }
  5908. this.dirty = true;
  5909. }
  5910. // update class
  5911. var className = (this.data.className ? (' ' + this.data.className) : '') +
  5912. (this.selected ? ' selected' : '');
  5913. if (this.className != className) {
  5914. this.className = className;
  5915. dom.box.className = this.baseClassName + className;
  5916. this.dirty = true;
  5917. }
  5918. // recalculate size
  5919. if (this.dirty) {
  5920. this.props.content.width = this.dom.content.offsetWidth;
  5921. this.height = this.dom.box.offsetHeight;
  5922. this.dirty = false;
  5923. }
  5924. this._repaintDeleteButton(dom.box);
  5925. this._repaintDragLeft();
  5926. this._repaintDragRight();
  5927. };
  5928. /**
  5929. * Show the item in the DOM (when not already visible). The items DOM will
  5930. * be created when needed.
  5931. */
  5932. ItemRange.prototype.show = function show() {
  5933. if (!this.displayed) {
  5934. this.repaint();
  5935. }
  5936. };
  5937. /**
  5938. * Hide the item from the DOM (when visible)
  5939. * @return {Boolean} changed
  5940. */
  5941. ItemRange.prototype.hide = function hide() {
  5942. if (this.displayed) {
  5943. var box = this.dom.box;
  5944. if (box.parentNode) {
  5945. box.parentNode.removeChild(box);
  5946. }
  5947. this.top = null;
  5948. this.left = null;
  5949. this.displayed = false;
  5950. }
  5951. };
  5952. /**
  5953. * Reposition the item horizontally
  5954. * @Override
  5955. */
  5956. ItemRange.prototype.repositionX = function repositionX() {
  5957. var props = this.props,
  5958. parentWidth = this.parent.width,
  5959. start = this.defaultOptions.toScreen(this.data.start),
  5960. end = this.defaultOptions.toScreen(this.data.end),
  5961. padding = 'padding' in this.options ? this.options.padding : this.defaultOptions.padding,
  5962. contentLeft;
  5963. // limit the width of the this, as browsers cannot draw very wide divs
  5964. if (start < -parentWidth) {
  5965. start = -parentWidth;
  5966. }
  5967. if (end > 2 * parentWidth) {
  5968. end = 2 * parentWidth;
  5969. }
  5970. // when range exceeds left of the window, position the contents at the left of the visible area
  5971. if (start < 0) {
  5972. contentLeft = Math.min(-start,
  5973. (end - start - props.content.width - 2 * padding));
  5974. // TODO: remove the need for options.padding. it's terrible.
  5975. }
  5976. else {
  5977. contentLeft = 0;
  5978. }
  5979. this.left = start;
  5980. this.width = Math.max(end - start, 1);
  5981. this.dom.box.style.left = this.left + 'px';
  5982. this.dom.box.style.width = this.width + 'px';
  5983. this.dom.content.style.left = contentLeft + 'px';
  5984. };
  5985. /**
  5986. * Reposition the item vertically
  5987. * @Override
  5988. */
  5989. ItemRange.prototype.repositionY = function repositionY() {
  5990. var orientation = this.options.orientation || this.defaultOptions.orientation,
  5991. box = this.dom.box;
  5992. if (orientation == 'top') {
  5993. box.style.top = this.top + 'px';
  5994. box.style.bottom = '';
  5995. }
  5996. else {
  5997. box.style.top = '';
  5998. box.style.bottom = this.top + 'px';
  5999. }
  6000. };
  6001. /**
  6002. * Repaint a drag area on the left side of the range when the range is selected
  6003. * @protected
  6004. */
  6005. ItemRange.prototype._repaintDragLeft = function () {
  6006. if (this.selected && this.options.editable.updateTime && !this.dom.dragLeft) {
  6007. // create and show drag area
  6008. var dragLeft = document.createElement('div');
  6009. dragLeft.className = 'drag-left';
  6010. dragLeft.dragLeftItem = this;
  6011. // TODO: this should be redundant?
  6012. Hammer(dragLeft, {
  6013. preventDefault: true
  6014. }).on('drag', function () {
  6015. //console.log('drag left')
  6016. });
  6017. this.dom.box.appendChild(dragLeft);
  6018. this.dom.dragLeft = dragLeft;
  6019. }
  6020. else if (!this.selected && this.dom.dragLeft) {
  6021. // delete drag area
  6022. if (this.dom.dragLeft.parentNode) {
  6023. this.dom.dragLeft.parentNode.removeChild(this.dom.dragLeft);
  6024. }
  6025. this.dom.dragLeft = null;
  6026. }
  6027. };
  6028. /**
  6029. * Repaint a drag area on the right side of the range when the range is selected
  6030. * @protected
  6031. */
  6032. ItemRange.prototype._repaintDragRight = function () {
  6033. if (this.selected && this.options.editable.updateTime && !this.dom.dragRight) {
  6034. // create and show drag area
  6035. var dragRight = document.createElement('div');
  6036. dragRight.className = 'drag-right';
  6037. dragRight.dragRightItem = this;
  6038. // TODO: this should be redundant?
  6039. Hammer(dragRight, {
  6040. preventDefault: true
  6041. }).on('drag', function () {
  6042. //console.log('drag right')
  6043. });
  6044. this.dom.box.appendChild(dragRight);
  6045. this.dom.dragRight = dragRight;
  6046. }
  6047. else if (!this.selected && this.dom.dragRight) {
  6048. // delete drag area
  6049. if (this.dom.dragRight.parentNode) {
  6050. this.dom.dragRight.parentNode.removeChild(this.dom.dragRight);
  6051. }
  6052. this.dom.dragRight = null;
  6053. }
  6054. };
  6055. /**
  6056. * @constructor ItemRangeOverflow
  6057. * @extends ItemRange
  6058. * @param {Object} data Object containing parameters start, end
  6059. * content, className.
  6060. * @param {Object} [options] Options to set initial property values
  6061. * @param {Object} [defaultOptions] default options
  6062. * // TODO: describe available options
  6063. */
  6064. function ItemRangeOverflow (data, options, defaultOptions) {
  6065. this.props = {
  6066. content: {
  6067. left: 0,
  6068. width: 0
  6069. }
  6070. };
  6071. ItemRange.call(this, data, options, defaultOptions);
  6072. }
  6073. ItemRangeOverflow.prototype = new ItemRange (null);
  6074. ItemRangeOverflow.prototype.baseClassName = 'item rangeoverflow';
  6075. /**
  6076. * Reposition the item horizontally
  6077. * @Override
  6078. */
  6079. ItemRangeOverflow.prototype.repositionX = function repositionX() {
  6080. var parentWidth = this.parent.width,
  6081. start = this.defaultOptions.toScreen(this.data.start),
  6082. end = this.defaultOptions.toScreen(this.data.end),
  6083. padding = 'padding' in this.options ? this.options.padding : this.defaultOptions.padding,
  6084. contentLeft;
  6085. // limit the width of the this, as browsers cannot draw very wide divs
  6086. if (start < -parentWidth) {
  6087. start = -parentWidth;
  6088. }
  6089. if (end > 2 * parentWidth) {
  6090. end = 2 * parentWidth;
  6091. }
  6092. // when range exceeds left of the window, position the contents at the left of the visible area
  6093. contentLeft = Math.max(-start, 0);
  6094. this.left = start;
  6095. var boxWidth = Math.max(end - start, 1);
  6096. this.width = boxWidth + this.props.content.width;
  6097. // Note: The calculation of width is an optimistic calculation, giving
  6098. // a width which will not change when moving the Timeline
  6099. // So no restacking needed, which is nicer for the eye
  6100. this.dom.box.style.left = this.left + 'px';
  6101. this.dom.box.style.width = boxWidth + 'px';
  6102. this.dom.content.style.left = contentLeft + 'px';
  6103. };
  6104. /**
  6105. * @constructor Group
  6106. * @param {Number | String} groupId
  6107. * @param {Object} data
  6108. * @param {ItemSet} itemSet
  6109. */
  6110. function Group (groupId, data, itemSet) {
  6111. this.groupId = groupId;
  6112. this.itemSet = itemSet;
  6113. this.dom = {};
  6114. this.props = {
  6115. label: {
  6116. width: 0,
  6117. height: 0
  6118. }
  6119. };
  6120. this.items = {}; // items filtered by groupId of this group
  6121. this.visibleItems = []; // items currently visible in window
  6122. this.orderedItems = { // items sorted by start and by end
  6123. byStart: [],
  6124. byEnd: []
  6125. };
  6126. this._create();
  6127. this.setData(data);
  6128. }
  6129. /**
  6130. * Create DOM elements for the group
  6131. * @private
  6132. */
  6133. Group.prototype._create = function() {
  6134. var label = document.createElement('div');
  6135. label.className = 'vlabel';
  6136. this.dom.label = label;
  6137. var inner = document.createElement('div');
  6138. inner.className = 'inner';
  6139. label.appendChild(inner);
  6140. this.dom.inner = inner;
  6141. var foreground = document.createElement('div');
  6142. foreground.className = 'group';
  6143. foreground['timeline-group'] = this;
  6144. this.dom.foreground = foreground;
  6145. this.dom.background = document.createElement('div');
  6146. this.dom.axis = document.createElement('div');
  6147. };
  6148. /**
  6149. * Set the group data for this group
  6150. * @param {Object} data Group data, can contain properties content and className
  6151. */
  6152. Group.prototype.setData = function setData(data) {
  6153. // update contents
  6154. var content = data && data.content;
  6155. if (content instanceof Element) {
  6156. this.dom.inner.appendChild(content);
  6157. }
  6158. else if (content != undefined) {
  6159. this.dom.inner.innerHTML = content;
  6160. }
  6161. else {
  6162. this.dom.inner.innerHTML = this.groupId;
  6163. }
  6164. // update className
  6165. var className = data && data.className;
  6166. if (className) {
  6167. util.addClassName(this.dom.label, className);
  6168. }
  6169. };
  6170. /**
  6171. * Get the foreground container element
  6172. * @return {HTMLElement} foreground
  6173. */
  6174. Group.prototype.getForeground = function getForeground() {
  6175. return this.dom.foreground;
  6176. };
  6177. /**
  6178. * Get the background container element
  6179. * @return {HTMLElement} background
  6180. */
  6181. Group.prototype.getBackground = function getBackground() {
  6182. return this.dom.background;
  6183. };
  6184. /**
  6185. * Get the axis container element
  6186. * @return {HTMLElement} axis
  6187. */
  6188. Group.prototype.getAxis = function getAxis() {
  6189. return this.dom.axis;
  6190. };
  6191. /**
  6192. * Get the width of the group label
  6193. * @return {number} width
  6194. */
  6195. Group.prototype.getLabelWidth = function getLabelWidth() {
  6196. return this.props.label.width;
  6197. };
  6198. /**
  6199. * Repaint this group
  6200. * @param {{start: number, end: number}} range
  6201. * @param {{item: number, axis: number}} margin
  6202. * @param {boolean} [restack=false] Force restacking of all items
  6203. * @return {boolean} Returns true if the group is resized
  6204. */
  6205. Group.prototype.repaint = function repaint(range, margin, restack) {
  6206. var resized = false;
  6207. this.visibleItems = this._updateVisibleItems(this.orderedItems, this.visibleItems, range);
  6208. // reposition visible items vertically
  6209. if (this.itemSet.options.stack) { // TODO: ugly way to access options...
  6210. stack.stack(this.visibleItems, margin, restack);
  6211. }
  6212. else { // no stacking
  6213. stack.nostack(this.visibleItems, margin);
  6214. }
  6215. this.stackDirty = false;
  6216. for (var i = 0, ii = this.visibleItems.length; i < ii; i++) {
  6217. var item = this.visibleItems[i];
  6218. item.repositionY();
  6219. }
  6220. // recalculate the height of the group
  6221. var height;
  6222. var visibleItems = this.visibleItems;
  6223. if (visibleItems.length) {
  6224. var min = visibleItems[0].top;
  6225. var max = visibleItems[0].top + visibleItems[0].height;
  6226. util.forEach(visibleItems, function (item) {
  6227. min = Math.min(min, item.top);
  6228. max = Math.max(max, (item.top + item.height));
  6229. });
  6230. height = (max - min) + margin.axis + margin.item;
  6231. }
  6232. else {
  6233. height = margin.axis + margin.item;
  6234. }
  6235. height = Math.max(height, this.props.label.height);
  6236. // calculate actual size and position
  6237. var foreground = this.dom.foreground;
  6238. this.top = foreground.offsetTop;
  6239. this.left = foreground.offsetLeft;
  6240. this.width = foreground.offsetWidth;
  6241. resized = util.updateProperty(this, 'height', height) || resized;
  6242. // recalculate size of label
  6243. resized = util.updateProperty(this.props.label, 'width', this.dom.inner.clientWidth) || resized;
  6244. resized = util.updateProperty(this.props.label, 'height', this.dom.inner.clientHeight) || resized;
  6245. // apply new height
  6246. foreground.style.height = height + 'px';
  6247. this.dom.label.style.height = height + 'px';
  6248. return resized;
  6249. };
  6250. /**
  6251. * Show this group: attach to the DOM
  6252. */
  6253. Group.prototype.show = function show() {
  6254. if (!this.dom.label.parentNode) {
  6255. this.itemSet.getLabelSet().appendChild(this.dom.label);
  6256. }
  6257. if (!this.dom.foreground.parentNode) {
  6258. this.itemSet.getForeground().appendChild(this.dom.foreground);
  6259. }
  6260. if (!this.dom.background.parentNode) {
  6261. this.itemSet.getBackground().appendChild(this.dom.background);
  6262. }
  6263. if (!this.dom.axis.parentNode) {
  6264. this.itemSet.getAxis().appendChild(this.dom.axis);
  6265. }
  6266. };
  6267. /**
  6268. * Hide this group: remove from the DOM
  6269. */
  6270. Group.prototype.hide = function hide() {
  6271. var label = this.dom.label;
  6272. if (label.parentNode) {
  6273. label.parentNode.removeChild(label);
  6274. }
  6275. var foreground = this.dom.foreground;
  6276. if (foreground.parentNode) {
  6277. foreground.parentNode.removeChild(foreground);
  6278. }
  6279. var background = this.dom.background;
  6280. if (background.parentNode) {
  6281. background.parentNode.removeChild(background);
  6282. }
  6283. var axis = this.dom.axis;
  6284. if (axis.parentNode) {
  6285. axis.parentNode.removeChild(axis);
  6286. }
  6287. };
  6288. /**
  6289. * Add an item to the group
  6290. * @param {Item} item
  6291. */
  6292. Group.prototype.add = function add(item) {
  6293. this.items[item.id] = item;
  6294. item.setParent(this);
  6295. if (item instanceof ItemRange && this.visibleItems.indexOf(item) == -1) {
  6296. var range = this.itemSet.range; // TODO: not nice accessing the range like this
  6297. this._checkIfVisible(item, this.visibleItems, range);
  6298. }
  6299. };
  6300. /**
  6301. * Remove an item from the group
  6302. * @param {Item} item
  6303. */
  6304. Group.prototype.remove = function remove(item) {
  6305. delete this.items[item.id];
  6306. item.setParent(this.itemSet);
  6307. // remove from visible items
  6308. var index = this.visibleItems.indexOf(item);
  6309. if (index != -1) this.visibleItems.splice(index, 1);
  6310. // TODO: also remove from ordered items?
  6311. };
  6312. /**
  6313. * Remove an item from the corresponding DataSet
  6314. * @param {Item} item
  6315. */
  6316. Group.prototype.removeFromDataSet = function removeFromDataSet(item) {
  6317. this.itemSet.removeItem(item.id);
  6318. };
  6319. /**
  6320. * Reorder the items
  6321. */
  6322. Group.prototype.order = function order() {
  6323. var array = util.toArray(this.items);
  6324. this.orderedItems.byStart = array;
  6325. this.orderedItems.byEnd = this._constructByEndArray(array);
  6326. stack.orderByStart(this.orderedItems.byStart);
  6327. stack.orderByEnd(this.orderedItems.byEnd);
  6328. };
  6329. /**
  6330. * Create an array containing all items being a range (having an end date)
  6331. * @param {Item[]} array
  6332. * @returns {ItemRange[]}
  6333. * @private
  6334. */
  6335. Group.prototype._constructByEndArray = function _constructByEndArray(array) {
  6336. var endArray = [];
  6337. for (var i = 0; i < array.length; i++) {
  6338. if (array[i] instanceof ItemRange) {
  6339. endArray.push(array[i]);
  6340. }
  6341. }
  6342. return endArray;
  6343. };
  6344. /**
  6345. * Update the visible items
  6346. * @param {{byStart: Item[], byEnd: Item[]}} orderedItems All items ordered by start date and by end date
  6347. * @param {Item[]} visibleItems The previously visible items.
  6348. * @param {{start: number, end: number}} range Visible range
  6349. * @return {Item[]} visibleItems The new visible items.
  6350. * @private
  6351. */
  6352. Group.prototype._updateVisibleItems = function _updateVisibleItems(orderedItems, visibleItems, range) {
  6353. var initialPosByStart,
  6354. newVisibleItems = [],
  6355. i;
  6356. // first check if the items that were in view previously are still in view.
  6357. // this handles the case for the ItemRange that is both before and after the current one.
  6358. if (visibleItems.length > 0) {
  6359. for (i = 0; i < visibleItems.length; i++) {
  6360. this._checkIfVisible(visibleItems[i], newVisibleItems, range);
  6361. }
  6362. }
  6363. // If there were no visible items previously, use binarySearch to find a visible ItemPoint or ItemRange (based on startTime)
  6364. if (newVisibleItems.length == 0) {
  6365. initialPosByStart = this._binarySearch(orderedItems, range, false);
  6366. }
  6367. else {
  6368. initialPosByStart = orderedItems.byStart.indexOf(newVisibleItems[0]);
  6369. }
  6370. // use visible search to find a visible ItemRange (only based on endTime)
  6371. var initialPosByEnd = this._binarySearch(orderedItems, range, true);
  6372. // if we found a initial ID to use, trace it up and down until we meet an invisible item.
  6373. if (initialPosByStart != -1) {
  6374. for (i = initialPosByStart; i >= 0; i--) {
  6375. if (this._checkIfInvisible(orderedItems.byStart[i], newVisibleItems, range)) {break;}
  6376. }
  6377. for (i = initialPosByStart + 1; i < orderedItems.byStart.length; i++) {
  6378. if (this._checkIfInvisible(orderedItems.byStart[i], newVisibleItems, range)) {break;}
  6379. }
  6380. }
  6381. // if we found a initial ID to use, trace it up and down until we meet an invisible item.
  6382. if (initialPosByEnd != -1) {
  6383. for (i = initialPosByEnd; i >= 0; i--) {
  6384. if (this._checkIfInvisible(orderedItems.byEnd[i], newVisibleItems, range)) {break;}
  6385. }
  6386. for (i = initialPosByEnd + 1; i < orderedItems.byEnd.length; i++) {
  6387. if (this._checkIfInvisible(orderedItems.byEnd[i], newVisibleItems, range)) {break;}
  6388. }
  6389. }
  6390. return newVisibleItems;
  6391. };
  6392. /**
  6393. * This function does a binary search for a visible item. The user can select either the this.orderedItems.byStart or .byEnd
  6394. * arrays. This is done by giving a boolean value true if you want to use the byEnd.
  6395. * 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
  6396. * if the time we selected (start or end) is within the current range).
  6397. *
  6398. * 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
  6399. * 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,
  6400. * either the start OR end time has to be in the range.
  6401. *
  6402. * @param {{byStart: Item[], byEnd: Item[]}} orderedItems
  6403. * @param {{start: number, end: number}} range
  6404. * @param {Boolean} byEnd
  6405. * @returns {number}
  6406. * @private
  6407. */
  6408. Group.prototype._binarySearch = function _binarySearch(orderedItems, range, byEnd) {
  6409. var array = [];
  6410. var byTime = byEnd ? 'end' : 'start';
  6411. if (byEnd == true) {array = orderedItems.byEnd; }
  6412. else {array = orderedItems.byStart;}
  6413. var interval = range.end - range.start;
  6414. var found = false;
  6415. var low = 0;
  6416. var high = array.length;
  6417. var guess = Math.floor(0.5*(high+low));
  6418. var newGuess;
  6419. if (high == 0) {guess = -1;}
  6420. else if (high == 1) {
  6421. if ((array[guess].data[byTime] > range.start - interval) && (array[guess].data[byTime] < range.end)) {
  6422. guess = 0;
  6423. }
  6424. else {
  6425. guess = -1;
  6426. }
  6427. }
  6428. else {
  6429. high -= 1;
  6430. while (found == false) {
  6431. if ((array[guess].data[byTime] > range.start - interval) && (array[guess].data[byTime] < range.end)) {
  6432. found = true;
  6433. }
  6434. else {
  6435. if (array[guess].data[byTime] < range.start - interval) { // it is too small --> increase low
  6436. low = Math.floor(0.5*(high+low));
  6437. }
  6438. else { // it is too big --> decrease high
  6439. high = Math.floor(0.5*(high+low));
  6440. }
  6441. newGuess = Math.floor(0.5*(high+low));
  6442. // not in list;
  6443. if (guess == newGuess) {
  6444. guess = -1;
  6445. found = true;
  6446. }
  6447. else {
  6448. guess = newGuess;
  6449. }
  6450. }
  6451. }
  6452. }
  6453. return guess;
  6454. };
  6455. /**
  6456. * this function checks if an item is invisible. If it is NOT we make it visible
  6457. * and add it to the global visible items. If it is, return true.
  6458. *
  6459. * @param {Item} item
  6460. * @param {Item[]} visibleItems
  6461. * @param {{start:number, end:number}} range
  6462. * @returns {boolean}
  6463. * @private
  6464. */
  6465. Group.prototype._checkIfInvisible = function _checkIfInvisible(item, visibleItems, range) {
  6466. if (item.isVisible(range)) {
  6467. if (!item.displayed) item.show();
  6468. item.repositionX();
  6469. if (visibleItems.indexOf(item) == -1) {
  6470. visibleItems.push(item);
  6471. }
  6472. return false;
  6473. }
  6474. else {
  6475. return true;
  6476. }
  6477. };
  6478. /**
  6479. * this function is very similar to the _checkIfInvisible() but it does not
  6480. * return booleans, hides the item if it should not be seen and always adds to
  6481. * the visibleItems.
  6482. * this one is for brute forcing and hiding.
  6483. *
  6484. * @param {Item} item
  6485. * @param {Array} visibleItems
  6486. * @param {{start:number, end:number}} range
  6487. * @private
  6488. */
  6489. Group.prototype._checkIfVisible = function _checkIfVisible(item, visibleItems, range) {
  6490. if (item.isVisible(range)) {
  6491. if (!item.displayed) item.show();
  6492. // reposition item horizontally
  6493. item.repositionX();
  6494. visibleItems.push(item);
  6495. }
  6496. else {
  6497. if (item.displayed) item.hide();
  6498. }
  6499. };
  6500. /**
  6501. * Create a timeline visualization
  6502. * @param {HTMLElement} container
  6503. * @param {vis.DataSet | Array | google.visualization.DataTable} [items]
  6504. * @param {Object} [options] See Timeline.setOptions for the available options.
  6505. * @constructor
  6506. */
  6507. function Timeline (container, items, options) {
  6508. // validate arguments
  6509. if (!container) throw new Error('No container element provided');
  6510. var me = this;
  6511. var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0);
  6512. this.options = {
  6513. orientation: 'bottom',
  6514. direction: 'horizontal', // 'horizontal' or 'vertical'
  6515. autoResize: true,
  6516. stack: true,
  6517. editable: {
  6518. updateTime: false,
  6519. updateGroup: false,
  6520. add: false,
  6521. remove: false
  6522. },
  6523. selectable: true,
  6524. snap: null, // will be specified after timeaxis is created
  6525. min: null,
  6526. max: null,
  6527. zoomMin: 10, // milliseconds
  6528. zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000, // milliseconds
  6529. // moveable: true, // TODO: option moveable
  6530. // zoomable: true, // TODO: option zoomable
  6531. showMinorLabels: true,
  6532. showMajorLabels: true,
  6533. showCurrentTime: false,
  6534. showCustomTime: false,
  6535. type: 'box',
  6536. align: 'center',
  6537. margin: {
  6538. axis: 20,
  6539. item: 10
  6540. },
  6541. padding: 5,
  6542. onAdd: function (item, callback) {
  6543. callback(item);
  6544. },
  6545. onUpdate: function (item, callback) {
  6546. callback(item);
  6547. },
  6548. onMove: function (item, callback) {
  6549. callback(item);
  6550. },
  6551. onRemove: function (item, callback) {
  6552. callback(item);
  6553. },
  6554. toScreen: me._toScreen.bind(me),
  6555. toTime: me._toTime.bind(me)
  6556. };
  6557. // root panel
  6558. var rootOptions = util.extend(Object.create(this.options), {
  6559. height: function () {
  6560. if (me.options.height) {
  6561. // fixed height
  6562. return me.options.height;
  6563. }
  6564. else {
  6565. // auto height
  6566. // TODO: implement a css based solution to automatically have the right hight
  6567. return (me.timeAxis.height + me.contentPanel.height) + 'px';
  6568. }
  6569. }
  6570. });
  6571. this.rootPanel = new RootPanel(container, rootOptions);
  6572. // single select (or unselect) when tapping an item
  6573. this.rootPanel.on('tap', this._onSelectItem.bind(this));
  6574. // multi select when holding mouse/touch, or on ctrl+click
  6575. this.rootPanel.on('hold', this._onMultiSelectItem.bind(this));
  6576. // add item on doubletap
  6577. this.rootPanel.on('doubletap', this._onAddItem.bind(this));
  6578. // side panel
  6579. var sideOptions = util.extend(Object.create(this.options), {
  6580. top: function () {
  6581. return (sideOptions.orientation == 'top') ? '0' : '';
  6582. },
  6583. bottom: function () {
  6584. return (sideOptions.orientation == 'top') ? '' : '0';
  6585. },
  6586. left: '0',
  6587. right: null,
  6588. height: '100%',
  6589. width: function () {
  6590. if (me.itemSet) {
  6591. return me.itemSet.getLabelsWidth();
  6592. }
  6593. else {
  6594. return 0;
  6595. }
  6596. },
  6597. className: function () {
  6598. return 'side' + (me.groupsData ? '' : ' hidden');
  6599. }
  6600. });
  6601. this.sidePanel = new Panel(sideOptions);
  6602. this.rootPanel.appendChild(this.sidePanel);
  6603. // main panel (contains time axis and itemsets)
  6604. var mainOptions = util.extend(Object.create(this.options), {
  6605. left: function () {
  6606. // we align left to enable a smooth resizing of the window
  6607. return me.sidePanel.width;
  6608. },
  6609. right: null,
  6610. height: '100%',
  6611. width: function () {
  6612. return me.rootPanel.width - me.sidePanel.width;
  6613. },
  6614. className: 'main'
  6615. });
  6616. this.mainPanel = new Panel(mainOptions);
  6617. this.rootPanel.appendChild(this.mainPanel);
  6618. // range
  6619. // TODO: move range inside rootPanel?
  6620. var rangeOptions = Object.create(this.options);
  6621. this.range = new Range(this.rootPanel, this.mainPanel, rangeOptions);
  6622. this.range.setRange(
  6623. now.clone().add('days', -3).valueOf(),
  6624. now.clone().add('days', 4).valueOf()
  6625. );
  6626. this.range.on('rangechange', function (properties) {
  6627. me.rootPanel.repaint();
  6628. me.emit('rangechange', properties);
  6629. });
  6630. this.range.on('rangechanged', function (properties) {
  6631. me.rootPanel.repaint();
  6632. me.emit('rangechanged', properties);
  6633. });
  6634. // panel with time axis
  6635. var timeAxisOptions = util.extend(Object.create(rootOptions), {
  6636. range: this.range,
  6637. left: null,
  6638. top: null,
  6639. width: null,
  6640. height: null
  6641. });
  6642. this.timeAxis = new TimeAxis(timeAxisOptions);
  6643. this.timeAxis.setRange(this.range);
  6644. this.options.snap = this.timeAxis.snap.bind(this.timeAxis);
  6645. this.mainPanel.appendChild(this.timeAxis);
  6646. // content panel (contains itemset(s))
  6647. var contentOptions = util.extend(Object.create(this.options), {
  6648. top: function () {
  6649. return (me.options.orientation == 'top') ? (me.timeAxis.height + 'px') : '';
  6650. },
  6651. bottom: function () {
  6652. return (me.options.orientation == 'top') ? '' : (me.timeAxis.height + 'px');
  6653. },
  6654. left: null,
  6655. right: null,
  6656. height: null,
  6657. width: null,
  6658. className: 'content'
  6659. });
  6660. this.contentPanel = new Panel(contentOptions);
  6661. this.mainPanel.appendChild(this.contentPanel);
  6662. // content panel (contains the vertical lines of box items)
  6663. var backgroundOptions = util.extend(Object.create(this.options), {
  6664. top: function () {
  6665. return (me.options.orientation == 'top') ? (me.timeAxis.height + 'px') : '';
  6666. },
  6667. bottom: function () {
  6668. return (me.options.orientation == 'top') ? '' : (me.timeAxis.height + 'px');
  6669. },
  6670. left: null,
  6671. right: null,
  6672. height: function () {
  6673. return me.contentPanel.height;
  6674. },
  6675. width: null,
  6676. className: 'background'
  6677. });
  6678. this.backgroundPanel = new Panel(backgroundOptions);
  6679. this.mainPanel.insertBefore(this.backgroundPanel, this.contentPanel);
  6680. // panel with axis holding the dots of item boxes
  6681. var axisPanelOptions = util.extend(Object.create(rootOptions), {
  6682. left: 0,
  6683. top: function () {
  6684. return (me.options.orientation == 'top') ? (me.timeAxis.height + 'px') : '';
  6685. },
  6686. bottom: function () {
  6687. return (me.options.orientation == 'top') ? '' : (me.timeAxis.height + 'px');
  6688. },
  6689. width: '100%',
  6690. height: 0,
  6691. className: 'axis'
  6692. });
  6693. this.axisPanel = new Panel(axisPanelOptions);
  6694. this.mainPanel.appendChild(this.axisPanel);
  6695. // content panel (contains itemset(s))
  6696. var sideContentOptions = util.extend(Object.create(this.options), {
  6697. top: function () {
  6698. return (me.options.orientation == 'top') ? (me.timeAxis.height + 'px') : '';
  6699. },
  6700. bottom: function () {
  6701. return (me.options.orientation == 'top') ? '' : (me.timeAxis.height + 'px');
  6702. },
  6703. left: null,
  6704. right: null,
  6705. height: null,
  6706. width: null,
  6707. className: 'side-content'
  6708. });
  6709. this.sideContentPanel = new Panel(sideContentOptions);
  6710. this.sidePanel.appendChild(this.sideContentPanel);
  6711. // current time bar
  6712. // Note: time bar will be attached in this.setOptions when selected
  6713. this.currentTime = new CurrentTime(this.range, rootOptions);
  6714. // custom time bar
  6715. // Note: time bar will be attached in this.setOptions when selected
  6716. this.customTime = new CustomTime(rootOptions);
  6717. this.customTime.on('timechange', function (time) {
  6718. me.emit('timechange', time);
  6719. });
  6720. this.customTime.on('timechanged', function (time) {
  6721. me.emit('timechanged', time);
  6722. });
  6723. // itemset containing items and groups
  6724. var itemOptions = util.extend(Object.create(this.options), {
  6725. left: null,
  6726. right: null,
  6727. top: null,
  6728. bottom: null,
  6729. width: null,
  6730. height: null
  6731. });
  6732. this.itemSet = new ItemSet(this.backgroundPanel, this.axisPanel, this.sideContentPanel, itemOptions);
  6733. this.itemSet.setRange(this.range);
  6734. this.itemSet.on('change', me.rootPanel.repaint.bind(me.rootPanel));
  6735. this.contentPanel.appendChild(this.itemSet);
  6736. this.linegraph = new Linegraph(this.backgroundPanel, this.axisPanel, this.sideContentPanel, itemOptions);
  6737. this.linegraph.setRange(this.range);
  6738. this.linegraph.on('change', me.rootPanel.repaint.bind(me.rootPanel));
  6739. this.contentPanel.appendChild(this.linegraph);
  6740. this.itemsData = null; // DataSet
  6741. this.groupsData = null; // DataSet
  6742. // apply options
  6743. if (options) {
  6744. this.setOptions(options);
  6745. }
  6746. // create itemset
  6747. if (items) {
  6748. this.setItems(items);
  6749. }
  6750. }
  6751. // turn Timeline into an event emitter
  6752. Emitter(Timeline.prototype);
  6753. /**
  6754. * Set options
  6755. * @param {Object} options TODO: describe the available options
  6756. */
  6757. Timeline.prototype.setOptions = function (options) {
  6758. util.extend(this.options, options);
  6759. if ('editable' in options) {
  6760. var isBoolean = typeof options.editable === 'boolean';
  6761. this.options.editable = {
  6762. updateTime: isBoolean ? options.editable : (options.editable.updateTime || false),
  6763. updateGroup: isBoolean ? options.editable : (options.editable.updateGroup || false),
  6764. add: isBoolean ? options.editable : (options.editable.add || false),
  6765. remove: isBoolean ? options.editable : (options.editable.remove || false)
  6766. };
  6767. }
  6768. // force update of range (apply new min/max etc.)
  6769. // both start and end are optional
  6770. this.range.setRange(options.start, options.end);
  6771. if ('editable' in options || 'selectable' in options) {
  6772. if (this.options.selectable) {
  6773. // force update of selection
  6774. this.setSelection(this.getSelection());
  6775. }
  6776. else {
  6777. // remove selection
  6778. this.setSelection([]);
  6779. }
  6780. }
  6781. // force the itemSet to refresh: options like orientation and margins may be changed
  6782. this.itemSet.markDirty();
  6783. // validate the callback functions
  6784. var validateCallback = (function (fn) {
  6785. if (!(this.options[fn] instanceof Function) || this.options[fn].length != 2) {
  6786. throw new Error('option ' + fn + ' must be a function ' + fn + '(item, callback)');
  6787. }
  6788. }).bind(this);
  6789. ['onAdd', 'onUpdate', 'onRemove', 'onMove'].forEach(validateCallback);
  6790. // add/remove the current time bar
  6791. if (this.options.showCurrentTime) {
  6792. if (!this.mainPanel.hasChild(this.currentTime)) {
  6793. this.mainPanel.appendChild(this.currentTime);
  6794. this.currentTime.start();
  6795. }
  6796. }
  6797. else {
  6798. if (this.mainPanel.hasChild(this.currentTime)) {
  6799. this.currentTime.stop();
  6800. this.mainPanel.removeChild(this.currentTime);
  6801. }
  6802. }
  6803. // add/remove the custom time bar
  6804. if (this.options.showCustomTime) {
  6805. if (!this.mainPanel.hasChild(this.customTime)) {
  6806. this.mainPanel.appendChild(this.customTime);
  6807. }
  6808. }
  6809. else {
  6810. if (this.mainPanel.hasChild(this.customTime)) {
  6811. this.mainPanel.removeChild(this.customTime);
  6812. }
  6813. }
  6814. // TODO: remove deprecation error one day (deprecated since version 0.8.0)
  6815. if (options && options.order) {
  6816. throw new Error('Option order is deprecated. There is no replacement for this feature.');
  6817. }
  6818. // repaint everything
  6819. this.rootPanel.repaint();
  6820. };
  6821. /**
  6822. * Set a custom time bar
  6823. * @param {Date} time
  6824. */
  6825. Timeline.prototype.setCustomTime = function (time) {
  6826. if (!this.customTime) {
  6827. throw new Error('Cannot get custom time: Custom time bar is not enabled');
  6828. }
  6829. this.customTime.setCustomTime(time);
  6830. };
  6831. /**
  6832. * Retrieve the current custom time.
  6833. * @return {Date} customTime
  6834. */
  6835. Timeline.prototype.getCustomTime = function() {
  6836. if (!this.customTime) {
  6837. throw new Error('Cannot get custom time: Custom time bar is not enabled');
  6838. }
  6839. return this.customTime.getCustomTime();
  6840. };
  6841. /**
  6842. * Set items
  6843. * @param {vis.DataSet | Array | google.visualization.DataTable | null} items
  6844. */
  6845. Timeline.prototype.setItems = function(items) {
  6846. var initialLoad = (this.itemsData == null);
  6847. // convert to type DataSet when needed
  6848. var newDataSet;
  6849. if (!items) {
  6850. newDataSet = null;
  6851. }
  6852. else if (items instanceof DataSet || items instanceof DataView) {
  6853. newDataSet = items;
  6854. }
  6855. else {
  6856. // turn an array into a dataset
  6857. newDataSet = new DataSet(items, {
  6858. convert: {
  6859. start: 'Date',
  6860. end: 'Date'
  6861. }
  6862. });
  6863. }
  6864. // set items
  6865. this.itemsData = newDataSet;
  6866. this.itemSet.setItems(newDataSet);
  6867. if (initialLoad && (this.options.start == undefined || this.options.end == undefined)) {
  6868. this.fit();
  6869. var start = (this.options.start != undefined) ? util.convert(this.options.start, 'Date') : null;
  6870. var end = (this.options.end != undefined) ? util.convert(this.options.end, 'Date') : null;
  6871. this.setWindow(start, end);
  6872. }
  6873. };
  6874. /**
  6875. * Set groups
  6876. * @param {vis.DataSet | Array | google.visualization.DataTable} groups
  6877. */
  6878. Timeline.prototype.setGroups = function setGroups(groups) {
  6879. // convert to type DataSet when needed
  6880. var newDataSet;
  6881. if (!groups) {
  6882. newDataSet = null;
  6883. }
  6884. else if (groups instanceof DataSet || groups instanceof DataView) {
  6885. newDataSet = groups;
  6886. }
  6887. else {
  6888. // turn an array into a dataset
  6889. newDataSet = new DataSet(groups);
  6890. }
  6891. this.groupsData = newDataSet;
  6892. this.itemSet.setGroups(newDataSet);
  6893. };
  6894. /**
  6895. * Set Timeline window such that it fits all items
  6896. */
  6897. Timeline.prototype.fit = function fit() {
  6898. // apply the data range as range
  6899. var dataRange = this.getItemRange();
  6900. // add 5% space on both sides
  6901. var start = dataRange.min;
  6902. var end = dataRange.max;
  6903. if (start != null && end != null) {
  6904. var interval = (end.valueOf() - start.valueOf());
  6905. if (interval <= 0) {
  6906. // prevent an empty interval
  6907. interval = 24 * 60 * 60 * 1000; // 1 day
  6908. }
  6909. start = new Date(start.valueOf() - interval * 0.05);
  6910. end = new Date(end.valueOf() + interval * 0.05);
  6911. }
  6912. // skip range set if there is no start and end date
  6913. if (start === null && end === null) {
  6914. return;
  6915. }
  6916. this.range.setRange(start, end);
  6917. };
  6918. /**
  6919. * Get the data range of the item set.
  6920. * @returns {{min: Date, max: Date}} range A range with a start and end Date.
  6921. * When no minimum is found, min==null
  6922. * When no maximum is found, max==null
  6923. */
  6924. Timeline.prototype.getItemRange = function getItemRange() {
  6925. // calculate min from start filed
  6926. var itemsData = this.itemsData,
  6927. min = null,
  6928. max = null;
  6929. if (itemsData) {
  6930. // calculate the minimum value of the field 'start'
  6931. var minItem = itemsData.min('start');
  6932. min = minItem ? minItem.start.valueOf() : null;
  6933. // calculate maximum value of fields 'start' and 'end'
  6934. var maxStartItem = itemsData.max('start');
  6935. if (maxStartItem) {
  6936. max = maxStartItem.start.valueOf();
  6937. }
  6938. var maxEndItem = itemsData.max('end');
  6939. if (maxEndItem) {
  6940. if (max == null) {
  6941. max = maxEndItem.end.valueOf();
  6942. }
  6943. else {
  6944. max = Math.max(max, maxEndItem.end.valueOf());
  6945. }
  6946. }
  6947. }
  6948. return {
  6949. min: (min != null) ? new Date(min) : null,
  6950. max: (max != null) ? new Date(max) : null
  6951. };
  6952. };
  6953. /**
  6954. * Set selected items by their id. Replaces the current selection
  6955. * Unknown id's are silently ignored.
  6956. * @param {Array} [ids] An array with zero or more id's of the items to be
  6957. * selected. If ids is an empty array, all items will be
  6958. * unselected.
  6959. */
  6960. Timeline.prototype.setSelection = function setSelection (ids) {
  6961. this.itemSet.setSelection(ids);
  6962. };
  6963. /**
  6964. * Get the selected items by their id
  6965. * @return {Array} ids The ids of the selected items
  6966. */
  6967. Timeline.prototype.getSelection = function getSelection() {
  6968. return this.itemSet.getSelection();
  6969. };
  6970. /**
  6971. * Set the visible window. Both parameters are optional, you can change only
  6972. * start or only end. Syntax:
  6973. *
  6974. * TimeLine.setWindow(start, end)
  6975. * TimeLine.setWindow(range)
  6976. *
  6977. * Where start and end can be a Date, number, or string, and range is an
  6978. * object with properties start and end.
  6979. *
  6980. * @param {Date | Number | String} [start] Start date of visible window
  6981. * @param {Date | Number | String} [end] End date of visible window
  6982. */
  6983. Timeline.prototype.setWindow = function setWindow(start, end) {
  6984. if (arguments.length == 1) {
  6985. var range = arguments[0];
  6986. this.range.setRange(range.start, range.end);
  6987. }
  6988. else {
  6989. this.range.setRange(start, end);
  6990. }
  6991. };
  6992. /**
  6993. * Get the visible window
  6994. * @return {{start: Date, end: Date}} Visible range
  6995. */
  6996. Timeline.prototype.getWindow = function setWindow() {
  6997. var range = this.range.getRange();
  6998. return {
  6999. start: new Date(range.start),
  7000. end: new Date(range.end)
  7001. };
  7002. };
  7003. /**
  7004. * Handle selecting/deselecting an item when tapping it
  7005. * @param {Event} event
  7006. * @private
  7007. */
  7008. // TODO: move this function to ItemSet
  7009. Timeline.prototype._onSelectItem = function (event) {
  7010. if (!this.options.selectable) return;
  7011. var ctrlKey = event.gesture.srcEvent && event.gesture.srcEvent.ctrlKey;
  7012. var shiftKey = event.gesture.srcEvent && event.gesture.srcEvent.shiftKey;
  7013. if (ctrlKey || shiftKey) {
  7014. this._onMultiSelectItem(event);
  7015. return;
  7016. }
  7017. var oldSelection = this.getSelection();
  7018. var item = ItemSet.itemFromTarget(event);
  7019. var selection = item ? [item.id] : [];
  7020. this.setSelection(selection);
  7021. var newSelection = this.getSelection();
  7022. // if selection is changed, emit a select event
  7023. if (!util.equalArray(oldSelection, newSelection)) {
  7024. this.emit('select', {
  7025. items: this.getSelection()
  7026. });
  7027. }
  7028. event.stopPropagation();
  7029. };
  7030. /**
  7031. * Handle creation and updates of an item on double tap
  7032. * @param event
  7033. * @private
  7034. */
  7035. Timeline.prototype._onAddItem = function (event) {
  7036. if (!this.options.selectable) return;
  7037. if (!this.options.editable.add) return;
  7038. var me = this,
  7039. item = ItemSet.itemFromTarget(event);
  7040. if (item) {
  7041. // update item
  7042. // execute async handler to update the item (or cancel it)
  7043. var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset
  7044. this.options.onUpdate(itemData, function (itemData) {
  7045. if (itemData) {
  7046. me.itemsData.update(itemData);
  7047. }
  7048. });
  7049. }
  7050. else {
  7051. // add item
  7052. var xAbs = vis.util.getAbsoluteLeft(this.contentPanel.frame);
  7053. var x = event.gesture.center.pageX - xAbs;
  7054. var newItem = {
  7055. start: this.timeAxis.snap(this._toTime(x)),
  7056. content: 'new item'
  7057. };
  7058. var id = util.randomUUID();
  7059. newItem[this.itemsData.fieldId] = id;
  7060. var group = ItemSet.groupFromTarget(event);
  7061. if (group) {
  7062. newItem.group = group.groupId;
  7063. }
  7064. // execute async handler to customize (or cancel) adding an item
  7065. this.options.onAdd(newItem, function (item) {
  7066. if (item) {
  7067. me.itemsData.add(newItem);
  7068. // TODO: need to trigger a repaint?
  7069. }
  7070. });
  7071. }
  7072. };
  7073. /**
  7074. * Handle selecting/deselecting multiple items when holding an item
  7075. * @param {Event} event
  7076. * @private
  7077. */
  7078. // TODO: move this function to ItemSet
  7079. Timeline.prototype._onMultiSelectItem = function (event) {
  7080. if (!this.options.selectable) return;
  7081. var selection,
  7082. item = ItemSet.itemFromTarget(event);
  7083. if (item) {
  7084. // multi select items
  7085. selection = this.getSelection(); // current selection
  7086. var index = selection.indexOf(item.id);
  7087. if (index == -1) {
  7088. // item is not yet selected -> select it
  7089. selection.push(item.id);
  7090. }
  7091. else {
  7092. // item is already selected -> deselect it
  7093. selection.splice(index, 1);
  7094. }
  7095. this.setSelection(selection);
  7096. this.emit('select', {
  7097. items: this.getSelection()
  7098. });
  7099. event.stopPropagation();
  7100. }
  7101. };
  7102. /**
  7103. * Convert a position on screen (pixels) to a datetime
  7104. * @param {int} x Position on the screen in pixels
  7105. * @return {Date} time The datetime the corresponds with given position x
  7106. * @private
  7107. */
  7108. Timeline.prototype._toTime = function _toTime(x) {
  7109. var conversion = this.range.conversion(this.mainPanel.width);
  7110. return new Date(x / conversion.scale + conversion.offset);
  7111. };
  7112. /**
  7113. * Convert a datetime (Date object) into a position on the screen
  7114. * @param {Date} time A date
  7115. * @return {int} x The position on the screen in pixels which corresponds
  7116. * with the given date.
  7117. * @private
  7118. */
  7119. Timeline.prototype._toScreen = function _toScreen(time) {
  7120. var conversion = this.range.conversion(this.mainPanel.width);
  7121. return (time.valueOf() - conversion.offset) * conversion.scale;
  7122. };
  7123. (function(exports) {
  7124. /**
  7125. * Parse a text source containing data in DOT language into a JSON object.
  7126. * The object contains two lists: one with nodes and one with edges.
  7127. *
  7128. * DOT language reference: http://www.graphviz.org/doc/info/lang.html
  7129. *
  7130. * @param {String} data Text containing a graph in DOT-notation
  7131. * @return {Object} graph An object containing two parameters:
  7132. * {Object[]} nodes
  7133. * {Object[]} edges
  7134. */
  7135. function parseDOT (data) {
  7136. dot = data;
  7137. return parseGraph();
  7138. }
  7139. // token types enumeration
  7140. var TOKENTYPE = {
  7141. NULL : 0,
  7142. DELIMITER : 1,
  7143. IDENTIFIER: 2,
  7144. UNKNOWN : 3
  7145. };
  7146. // map with all delimiters
  7147. var DELIMITERS = {
  7148. '{': true,
  7149. '}': true,
  7150. '[': true,
  7151. ']': true,
  7152. ';': true,
  7153. '=': true,
  7154. ',': true,
  7155. '->': true,
  7156. '--': true
  7157. };
  7158. var dot = ''; // current dot file
  7159. var index = 0; // current index in dot file
  7160. var c = ''; // current token character in expr
  7161. var token = ''; // current token
  7162. var tokenType = TOKENTYPE.NULL; // type of the token
  7163. /**
  7164. * Get the first character from the dot file.
  7165. * The character is stored into the char c. If the end of the dot file is
  7166. * reached, the function puts an empty string in c.
  7167. */
  7168. function first() {
  7169. index = 0;
  7170. c = dot.charAt(0);
  7171. }
  7172. /**
  7173. * Get the next character from the dot file.
  7174. * The character is stored into the char c. If the end of the dot file is
  7175. * reached, the function puts an empty string in c.
  7176. */
  7177. function next() {
  7178. index++;
  7179. c = dot.charAt(index);
  7180. }
  7181. /**
  7182. * Preview the next character from the dot file.
  7183. * @return {String} cNext
  7184. */
  7185. function nextPreview() {
  7186. return dot.charAt(index + 1);
  7187. }
  7188. /**
  7189. * Test whether given character is alphabetic or numeric
  7190. * @param {String} c
  7191. * @return {Boolean} isAlphaNumeric
  7192. */
  7193. var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/;
  7194. function isAlphaNumeric(c) {
  7195. return regexAlphaNumeric.test(c);
  7196. }
  7197. /**
  7198. * Merge all properties of object b into object b
  7199. * @param {Object} a
  7200. * @param {Object} b
  7201. * @return {Object} a
  7202. */
  7203. function merge (a, b) {
  7204. if (!a) {
  7205. a = {};
  7206. }
  7207. if (b) {
  7208. for (var name in b) {
  7209. if (b.hasOwnProperty(name)) {
  7210. a[name] = b[name];
  7211. }
  7212. }
  7213. }
  7214. return a;
  7215. }
  7216. /**
  7217. * Set a value in an object, where the provided parameter name can be a
  7218. * path with nested parameters. For example:
  7219. *
  7220. * var obj = {a: 2};
  7221. * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}}
  7222. *
  7223. * @param {Object} obj
  7224. * @param {String} path A parameter name or dot-separated parameter path,
  7225. * like "color.highlight.border".
  7226. * @param {*} value
  7227. */
  7228. function setValue(obj, path, value) {
  7229. var keys = path.split('.');
  7230. var o = obj;
  7231. while (keys.length) {
  7232. var key = keys.shift();
  7233. if (keys.length) {
  7234. // this isn't the end point
  7235. if (!o[key]) {
  7236. o[key] = {};
  7237. }
  7238. o = o[key];
  7239. }
  7240. else {
  7241. // this is the end point
  7242. o[key] = value;
  7243. }
  7244. }
  7245. }
  7246. /**
  7247. * Add a node to a graph object. If there is already a node with
  7248. * the same id, their attributes will be merged.
  7249. * @param {Object} graph
  7250. * @param {Object} node
  7251. */
  7252. function addNode(graph, node) {
  7253. var i, len;
  7254. var current = null;
  7255. // find root graph (in case of subgraph)
  7256. var graphs = [graph]; // list with all graphs from current graph to root graph
  7257. var root = graph;
  7258. while (root.parent) {
  7259. graphs.push(root.parent);
  7260. root = root.parent;
  7261. }
  7262. // find existing node (at root level) by its id
  7263. if (root.nodes) {
  7264. for (i = 0, len = root.nodes.length; i < len; i++) {
  7265. if (node.id === root.nodes[i].id) {
  7266. current = root.nodes[i];
  7267. break;
  7268. }
  7269. }
  7270. }
  7271. if (!current) {
  7272. // this is a new node
  7273. current = {
  7274. id: node.id
  7275. };
  7276. if (graph.node) {
  7277. // clone default attributes
  7278. current.attr = merge(current.attr, graph.node);
  7279. }
  7280. }
  7281. // add node to this (sub)graph and all its parent graphs
  7282. for (i = graphs.length - 1; i >= 0; i--) {
  7283. var g = graphs[i];
  7284. if (!g.nodes) {
  7285. g.nodes = [];
  7286. }
  7287. if (g.nodes.indexOf(current) == -1) {
  7288. g.nodes.push(current);
  7289. }
  7290. }
  7291. // merge attributes
  7292. if (node.attr) {
  7293. current.attr = merge(current.attr, node.attr);
  7294. }
  7295. }
  7296. /**
  7297. * Add an edge to a graph object
  7298. * @param {Object} graph
  7299. * @param {Object} edge
  7300. */
  7301. function addEdge(graph, edge) {
  7302. if (!graph.edges) {
  7303. graph.edges = [];
  7304. }
  7305. graph.edges.push(edge);
  7306. if (graph.edge) {
  7307. var attr = merge({}, graph.edge); // clone default attributes
  7308. edge.attr = merge(attr, edge.attr); // merge attributes
  7309. }
  7310. }
  7311. /**
  7312. * Create an edge to a graph object
  7313. * @param {Object} graph
  7314. * @param {String | Number | Object} from
  7315. * @param {String | Number | Object} to
  7316. * @param {String} type
  7317. * @param {Object | null} attr
  7318. * @return {Object} edge
  7319. */
  7320. function createEdge(graph, from, to, type, attr) {
  7321. var edge = {
  7322. from: from,
  7323. to: to,
  7324. type: type
  7325. };
  7326. if (graph.edge) {
  7327. edge.attr = merge({}, graph.edge); // clone default attributes
  7328. }
  7329. edge.attr = merge(edge.attr || {}, attr); // merge attributes
  7330. return edge;
  7331. }
  7332. /**
  7333. * Get next token in the current dot file.
  7334. * The token and token type are available as token and tokenType
  7335. */
  7336. function getToken() {
  7337. tokenType = TOKENTYPE.NULL;
  7338. token = '';
  7339. // skip over whitespaces
  7340. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  7341. next();
  7342. }
  7343. do {
  7344. var isComment = false;
  7345. // skip comment
  7346. if (c == '#') {
  7347. // find the previous non-space character
  7348. var i = index - 1;
  7349. while (dot.charAt(i) == ' ' || dot.charAt(i) == '\t') {
  7350. i--;
  7351. }
  7352. if (dot.charAt(i) == '\n' || dot.charAt(i) == '') {
  7353. // the # is at the start of a line, this is indeed a line comment
  7354. while (c != '' && c != '\n') {
  7355. next();
  7356. }
  7357. isComment = true;
  7358. }
  7359. }
  7360. if (c == '/' && nextPreview() == '/') {
  7361. // skip line comment
  7362. while (c != '' && c != '\n') {
  7363. next();
  7364. }
  7365. isComment = true;
  7366. }
  7367. if (c == '/' && nextPreview() == '*') {
  7368. // skip block comment
  7369. while (c != '') {
  7370. if (c == '*' && nextPreview() == '/') {
  7371. // end of block comment found. skip these last two characters
  7372. next();
  7373. next();
  7374. break;
  7375. }
  7376. else {
  7377. next();
  7378. }
  7379. }
  7380. isComment = true;
  7381. }
  7382. // skip over whitespaces
  7383. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  7384. next();
  7385. }
  7386. }
  7387. while (isComment);
  7388. // check for end of dot file
  7389. if (c == '') {
  7390. // token is still empty
  7391. tokenType = TOKENTYPE.DELIMITER;
  7392. return;
  7393. }
  7394. // check for delimiters consisting of 2 characters
  7395. var c2 = c + nextPreview();
  7396. if (DELIMITERS[c2]) {
  7397. tokenType = TOKENTYPE.DELIMITER;
  7398. token = c2;
  7399. next();
  7400. next();
  7401. return;
  7402. }
  7403. // check for delimiters consisting of 1 character
  7404. if (DELIMITERS[c]) {
  7405. tokenType = TOKENTYPE.DELIMITER;
  7406. token = c;
  7407. next();
  7408. return;
  7409. }
  7410. // check for an identifier (number or string)
  7411. // TODO: more precise parsing of numbers/strings (and the port separator ':')
  7412. if (isAlphaNumeric(c) || c == '-') {
  7413. token += c;
  7414. next();
  7415. while (isAlphaNumeric(c)) {
  7416. token += c;
  7417. next();
  7418. }
  7419. if (token == 'false') {
  7420. token = false; // convert to boolean
  7421. }
  7422. else if (token == 'true') {
  7423. token = true; // convert to boolean
  7424. }
  7425. else if (!isNaN(Number(token))) {
  7426. token = Number(token); // convert to number
  7427. }
  7428. tokenType = TOKENTYPE.IDENTIFIER;
  7429. return;
  7430. }
  7431. // check for a string enclosed by double quotes
  7432. if (c == '"') {
  7433. next();
  7434. while (c != '' && (c != '"' || (c == '"' && nextPreview() == '"'))) {
  7435. token += c;
  7436. if (c == '"') { // skip the escape character
  7437. next();
  7438. }
  7439. next();
  7440. }
  7441. if (c != '"') {
  7442. throw newSyntaxError('End of string " expected');
  7443. }
  7444. next();
  7445. tokenType = TOKENTYPE.IDENTIFIER;
  7446. return;
  7447. }
  7448. // something unknown is found, wrong characters, a syntax error
  7449. tokenType = TOKENTYPE.UNKNOWN;
  7450. while (c != '') {
  7451. token += c;
  7452. next();
  7453. }
  7454. throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"');
  7455. }
  7456. /**
  7457. * Parse a graph.
  7458. * @returns {Object} graph
  7459. */
  7460. function parseGraph() {
  7461. var graph = {};
  7462. first();
  7463. getToken();
  7464. // optional strict keyword
  7465. if (token == 'strict') {
  7466. graph.strict = true;
  7467. getToken();
  7468. }
  7469. // graph or digraph keyword
  7470. if (token == 'graph' || token == 'digraph') {
  7471. graph.type = token;
  7472. getToken();
  7473. }
  7474. // optional graph id
  7475. if (tokenType == TOKENTYPE.IDENTIFIER) {
  7476. graph.id = token;
  7477. getToken();
  7478. }
  7479. // open angle bracket
  7480. if (token != '{') {
  7481. throw newSyntaxError('Angle bracket { expected');
  7482. }
  7483. getToken();
  7484. // statements
  7485. parseStatements(graph);
  7486. // close angle bracket
  7487. if (token != '}') {
  7488. throw newSyntaxError('Angle bracket } expected');
  7489. }
  7490. getToken();
  7491. // end of file
  7492. if (token !== '') {
  7493. throw newSyntaxError('End of file expected');
  7494. }
  7495. getToken();
  7496. // remove temporary default properties
  7497. delete graph.node;
  7498. delete graph.edge;
  7499. delete graph.graph;
  7500. return graph;
  7501. }
  7502. /**
  7503. * Parse a list with statements.
  7504. * @param {Object} graph
  7505. */
  7506. function parseStatements (graph) {
  7507. while (token !== '' && token != '}') {
  7508. parseStatement(graph);
  7509. if (token == ';') {
  7510. getToken();
  7511. }
  7512. }
  7513. }
  7514. /**
  7515. * Parse a single statement. Can be a an attribute statement, node
  7516. * statement, a series of node statements and edge statements, or a
  7517. * parameter.
  7518. * @param {Object} graph
  7519. */
  7520. function parseStatement(graph) {
  7521. // parse subgraph
  7522. var subgraph = parseSubgraph(graph);
  7523. if (subgraph) {
  7524. // edge statements
  7525. parseEdge(graph, subgraph);
  7526. return;
  7527. }
  7528. // parse an attribute statement
  7529. var attr = parseAttributeStatement(graph);
  7530. if (attr) {
  7531. return;
  7532. }
  7533. // parse node
  7534. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7535. throw newSyntaxError('Identifier expected');
  7536. }
  7537. var id = token; // id can be a string or a number
  7538. getToken();
  7539. if (token == '=') {
  7540. // id statement
  7541. getToken();
  7542. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7543. throw newSyntaxError('Identifier expected');
  7544. }
  7545. graph[id] = token;
  7546. getToken();
  7547. // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] "
  7548. }
  7549. else {
  7550. parseNodeStatement(graph, id);
  7551. }
  7552. }
  7553. /**
  7554. * Parse a subgraph
  7555. * @param {Object} graph parent graph object
  7556. * @return {Object | null} subgraph
  7557. */
  7558. function parseSubgraph (graph) {
  7559. var subgraph = null;
  7560. // optional subgraph keyword
  7561. if (token == 'subgraph') {
  7562. subgraph = {};
  7563. subgraph.type = 'subgraph';
  7564. getToken();
  7565. // optional graph id
  7566. if (tokenType == TOKENTYPE.IDENTIFIER) {
  7567. subgraph.id = token;
  7568. getToken();
  7569. }
  7570. }
  7571. // open angle bracket
  7572. if (token == '{') {
  7573. getToken();
  7574. if (!subgraph) {
  7575. subgraph = {};
  7576. }
  7577. subgraph.parent = graph;
  7578. subgraph.node = graph.node;
  7579. subgraph.edge = graph.edge;
  7580. subgraph.graph = graph.graph;
  7581. // statements
  7582. parseStatements(subgraph);
  7583. // close angle bracket
  7584. if (token != '}') {
  7585. throw newSyntaxError('Angle bracket } expected');
  7586. }
  7587. getToken();
  7588. // remove temporary default properties
  7589. delete subgraph.node;
  7590. delete subgraph.edge;
  7591. delete subgraph.graph;
  7592. delete subgraph.parent;
  7593. // register at the parent graph
  7594. if (!graph.subgraphs) {
  7595. graph.subgraphs = [];
  7596. }
  7597. graph.subgraphs.push(subgraph);
  7598. }
  7599. return subgraph;
  7600. }
  7601. /**
  7602. * parse an attribute statement like "node [shape=circle fontSize=16]".
  7603. * Available keywords are 'node', 'edge', 'graph'.
  7604. * The previous list with default attributes will be replaced
  7605. * @param {Object} graph
  7606. * @returns {String | null} keyword Returns the name of the parsed attribute
  7607. * (node, edge, graph), or null if nothing
  7608. * is parsed.
  7609. */
  7610. function parseAttributeStatement (graph) {
  7611. // attribute statements
  7612. if (token == 'node') {
  7613. getToken();
  7614. // node attributes
  7615. graph.node = parseAttributeList();
  7616. return 'node';
  7617. }
  7618. else if (token == 'edge') {
  7619. getToken();
  7620. // edge attributes
  7621. graph.edge = parseAttributeList();
  7622. return 'edge';
  7623. }
  7624. else if (token == 'graph') {
  7625. getToken();
  7626. // graph attributes
  7627. graph.graph = parseAttributeList();
  7628. return 'graph';
  7629. }
  7630. return null;
  7631. }
  7632. /**
  7633. * parse a node statement
  7634. * @param {Object} graph
  7635. * @param {String | Number} id
  7636. */
  7637. function parseNodeStatement(graph, id) {
  7638. // node statement
  7639. var node = {
  7640. id: id
  7641. };
  7642. var attr = parseAttributeList();
  7643. if (attr) {
  7644. node.attr = attr;
  7645. }
  7646. addNode(graph, node);
  7647. // edge statements
  7648. parseEdge(graph, id);
  7649. }
  7650. /**
  7651. * Parse an edge or a series of edges
  7652. * @param {Object} graph
  7653. * @param {String | Number} from Id of the from node
  7654. */
  7655. function parseEdge(graph, from) {
  7656. while (token == '->' || token == '--') {
  7657. var to;
  7658. var type = token;
  7659. getToken();
  7660. var subgraph = parseSubgraph(graph);
  7661. if (subgraph) {
  7662. to = subgraph;
  7663. }
  7664. else {
  7665. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7666. throw newSyntaxError('Identifier or subgraph expected');
  7667. }
  7668. to = token;
  7669. addNode(graph, {
  7670. id: to
  7671. });
  7672. getToken();
  7673. }
  7674. // parse edge attributes
  7675. var attr = parseAttributeList();
  7676. // create edge
  7677. var edge = createEdge(graph, from, to, type, attr);
  7678. addEdge(graph, edge);
  7679. from = to;
  7680. }
  7681. }
  7682. /**
  7683. * Parse a set with attributes,
  7684. * for example [label="1.000", shape=solid]
  7685. * @return {Object | null} attr
  7686. */
  7687. function parseAttributeList() {
  7688. var attr = null;
  7689. while (token == '[') {
  7690. getToken();
  7691. attr = {};
  7692. while (token !== '' && token != ']') {
  7693. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7694. throw newSyntaxError('Attribute name expected');
  7695. }
  7696. var name = token;
  7697. getToken();
  7698. if (token != '=') {
  7699. throw newSyntaxError('Equal sign = expected');
  7700. }
  7701. getToken();
  7702. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7703. throw newSyntaxError('Attribute value expected');
  7704. }
  7705. var value = token;
  7706. setValue(attr, name, value); // name can be a path
  7707. getToken();
  7708. if (token ==',') {
  7709. getToken();
  7710. }
  7711. }
  7712. if (token != ']') {
  7713. throw newSyntaxError('Bracket ] expected');
  7714. }
  7715. getToken();
  7716. }
  7717. return attr;
  7718. }
  7719. /**
  7720. * Create a syntax error with extra information on current token and index.
  7721. * @param {String} message
  7722. * @returns {SyntaxError} err
  7723. */
  7724. function newSyntaxError(message) {
  7725. return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')');
  7726. }
  7727. /**
  7728. * Chop off text after a maximum length
  7729. * @param {String} text
  7730. * @param {Number} maxLength
  7731. * @returns {String}
  7732. */
  7733. function chop (text, maxLength) {
  7734. return (text.length <= maxLength) ? text : (text.substr(0, 27) + '...');
  7735. }
  7736. /**
  7737. * Execute a function fn for each pair of elements in two arrays
  7738. * @param {Array | *} array1
  7739. * @param {Array | *} array2
  7740. * @param {function} fn
  7741. */
  7742. function forEach2(array1, array2, fn) {
  7743. if (array1 instanceof Array) {
  7744. array1.forEach(function (elem1) {
  7745. if (array2 instanceof Array) {
  7746. array2.forEach(function (elem2) {
  7747. fn(elem1, elem2);
  7748. });
  7749. }
  7750. else {
  7751. fn(elem1, array2);
  7752. }
  7753. });
  7754. }
  7755. else {
  7756. if (array2 instanceof Array) {
  7757. array2.forEach(function (elem2) {
  7758. fn(array1, elem2);
  7759. });
  7760. }
  7761. else {
  7762. fn(array1, array2);
  7763. }
  7764. }
  7765. }
  7766. /**
  7767. * Convert a string containing a graph in DOT language into a map containing
  7768. * with nodes and edges in the format of graph.
  7769. * @param {String} data Text containing a graph in DOT-notation
  7770. * @return {Object} graphData
  7771. */
  7772. function DOTToGraph (data) {
  7773. // parse the DOT file
  7774. var dotData = parseDOT(data);
  7775. var graphData = {
  7776. nodes: [],
  7777. edges: [],
  7778. options: {}
  7779. };
  7780. // copy the nodes
  7781. if (dotData.nodes) {
  7782. dotData.nodes.forEach(function (dotNode) {
  7783. var graphNode = {
  7784. id: dotNode.id,
  7785. label: String(dotNode.label || dotNode.id)
  7786. };
  7787. merge(graphNode, dotNode.attr);
  7788. if (graphNode.image) {
  7789. graphNode.shape = 'image';
  7790. }
  7791. graphData.nodes.push(graphNode);
  7792. });
  7793. }
  7794. // copy the edges
  7795. if (dotData.edges) {
  7796. /**
  7797. * Convert an edge in DOT format to an edge with VisGraph format
  7798. * @param {Object} dotEdge
  7799. * @returns {Object} graphEdge
  7800. */
  7801. function convertEdge(dotEdge) {
  7802. var graphEdge = {
  7803. from: dotEdge.from,
  7804. to: dotEdge.to
  7805. };
  7806. merge(graphEdge, dotEdge.attr);
  7807. graphEdge.style = (dotEdge.type == '->') ? 'arrow' : 'line';
  7808. return graphEdge;
  7809. }
  7810. dotData.edges.forEach(function (dotEdge) {
  7811. var from, to;
  7812. if (dotEdge.from instanceof Object) {
  7813. from = dotEdge.from.nodes;
  7814. }
  7815. else {
  7816. from = {
  7817. id: dotEdge.from
  7818. }
  7819. }
  7820. if (dotEdge.to instanceof Object) {
  7821. to = dotEdge.to.nodes;
  7822. }
  7823. else {
  7824. to = {
  7825. id: dotEdge.to
  7826. }
  7827. }
  7828. if (dotEdge.from instanceof Object && dotEdge.from.edges) {
  7829. dotEdge.from.edges.forEach(function (subEdge) {
  7830. var graphEdge = convertEdge(subEdge);
  7831. graphData.edges.push(graphEdge);
  7832. });
  7833. }
  7834. forEach2(from, to, function (from, to) {
  7835. var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr);
  7836. var graphEdge = convertEdge(subEdge);
  7837. graphData.edges.push(graphEdge);
  7838. });
  7839. if (dotEdge.to instanceof Object && dotEdge.to.edges) {
  7840. dotEdge.to.edges.forEach(function (subEdge) {
  7841. var graphEdge = convertEdge(subEdge);
  7842. graphData.edges.push(graphEdge);
  7843. });
  7844. }
  7845. });
  7846. }
  7847. // copy the options
  7848. if (dotData.attr) {
  7849. graphData.options = dotData.attr;
  7850. }
  7851. return graphData;
  7852. }
  7853. // exports
  7854. exports.parseDOT = parseDOT;
  7855. exports.DOTToGraph = DOTToGraph;
  7856. })(typeof util !== 'undefined' ? util : exports);
  7857. /**
  7858. * Canvas shapes used by the Graph
  7859. */
  7860. if (typeof CanvasRenderingContext2D !== 'undefined') {
  7861. /**
  7862. * Draw a circle shape
  7863. */
  7864. CanvasRenderingContext2D.prototype.circle = function(x, y, r) {
  7865. this.beginPath();
  7866. this.arc(x, y, r, 0, 2*Math.PI, false);
  7867. };
  7868. /**
  7869. * Draw a square shape
  7870. * @param {Number} x horizontal center
  7871. * @param {Number} y vertical center
  7872. * @param {Number} r size, width and height of the square
  7873. */
  7874. CanvasRenderingContext2D.prototype.square = function(x, y, r) {
  7875. this.beginPath();
  7876. this.rect(x - r, y - r, r * 2, r * 2);
  7877. };
  7878. /**
  7879. * Draw a triangle shape
  7880. * @param {Number} x horizontal center
  7881. * @param {Number} y vertical center
  7882. * @param {Number} r radius, half the length of the sides of the triangle
  7883. */
  7884. CanvasRenderingContext2D.prototype.triangle = function(x, y, r) {
  7885. // http://en.wikipedia.org/wiki/Equilateral_triangle
  7886. this.beginPath();
  7887. var s = r * 2;
  7888. var s2 = s / 2;
  7889. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  7890. var h = Math.sqrt(s * s - s2 * s2); // height
  7891. this.moveTo(x, y - (h - ir));
  7892. this.lineTo(x + s2, y + ir);
  7893. this.lineTo(x - s2, y + ir);
  7894. this.lineTo(x, y - (h - ir));
  7895. this.closePath();
  7896. };
  7897. /**
  7898. * Draw a triangle shape in downward orientation
  7899. * @param {Number} x horizontal center
  7900. * @param {Number} y vertical center
  7901. * @param {Number} r radius
  7902. */
  7903. CanvasRenderingContext2D.prototype.triangleDown = function(x, y, r) {
  7904. // http://en.wikipedia.org/wiki/Equilateral_triangle
  7905. this.beginPath();
  7906. var s = r * 2;
  7907. var s2 = s / 2;
  7908. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  7909. var h = Math.sqrt(s * s - s2 * s2); // height
  7910. this.moveTo(x, y + (h - ir));
  7911. this.lineTo(x + s2, y - ir);
  7912. this.lineTo(x - s2, y - ir);
  7913. this.lineTo(x, y + (h - ir));
  7914. this.closePath();
  7915. };
  7916. /**
  7917. * Draw a star shape, a star with 5 points
  7918. * @param {Number} x horizontal center
  7919. * @param {Number} y vertical center
  7920. * @param {Number} r radius, half the length of the sides of the triangle
  7921. */
  7922. CanvasRenderingContext2D.prototype.star = function(x, y, r) {
  7923. // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/
  7924. this.beginPath();
  7925. for (var n = 0; n < 10; n++) {
  7926. var radius = (n % 2 === 0) ? r * 1.3 : r * 0.5;
  7927. this.lineTo(
  7928. x + radius * Math.sin(n * 2 * Math.PI / 10),
  7929. y - radius * Math.cos(n * 2 * Math.PI / 10)
  7930. );
  7931. }
  7932. this.closePath();
  7933. };
  7934. /**
  7935. * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas
  7936. */
  7937. CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) {
  7938. var r2d = Math.PI/180;
  7939. if( w - ( 2 * r ) < 0 ) { r = ( w / 2 ); } //ensure that the radius isn't too large for x
  7940. if( h - ( 2 * r ) < 0 ) { r = ( h / 2 ); } //ensure that the radius isn't too large for y
  7941. this.beginPath();
  7942. this.moveTo(x+r,y);
  7943. this.lineTo(x+w-r,y);
  7944. this.arc(x+w-r,y+r,r,r2d*270,r2d*360,false);
  7945. this.lineTo(x+w,y+h-r);
  7946. this.arc(x+w-r,y+h-r,r,0,r2d*90,false);
  7947. this.lineTo(x+r,y+h);
  7948. this.arc(x+r,y+h-r,r,r2d*90,r2d*180,false);
  7949. this.lineTo(x,y+r);
  7950. this.arc(x+r,y+r,r,r2d*180,r2d*270,false);
  7951. };
  7952. /**
  7953. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  7954. */
  7955. CanvasRenderingContext2D.prototype.ellipse = function(x, y, w, h) {
  7956. var kappa = .5522848,
  7957. ox = (w / 2) * kappa, // control point offset horizontal
  7958. oy = (h / 2) * kappa, // control point offset vertical
  7959. xe = x + w, // x-end
  7960. ye = y + h, // y-end
  7961. xm = x + w / 2, // x-middle
  7962. ym = y + h / 2; // y-middle
  7963. this.beginPath();
  7964. this.moveTo(x, ym);
  7965. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  7966. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  7967. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  7968. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  7969. };
  7970. /**
  7971. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  7972. */
  7973. CanvasRenderingContext2D.prototype.database = function(x, y, w, h) {
  7974. var f = 1/3;
  7975. var wEllipse = w;
  7976. var hEllipse = h * f;
  7977. var kappa = .5522848,
  7978. ox = (wEllipse / 2) * kappa, // control point offset horizontal
  7979. oy = (hEllipse / 2) * kappa, // control point offset vertical
  7980. xe = x + wEllipse, // x-end
  7981. ye = y + hEllipse, // y-end
  7982. xm = x + wEllipse / 2, // x-middle
  7983. ym = y + hEllipse / 2, // y-middle
  7984. ymb = y + (h - hEllipse/2), // y-midlle, bottom ellipse
  7985. yeb = y + h; // y-end, bottom ellipse
  7986. this.beginPath();
  7987. this.moveTo(xe, ym);
  7988. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  7989. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  7990. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  7991. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  7992. this.lineTo(xe, ymb);
  7993. this.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb);
  7994. this.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb);
  7995. this.lineTo(x, ym);
  7996. };
  7997. /**
  7998. * Draw an arrow point (no line)
  7999. */
  8000. CanvasRenderingContext2D.prototype.arrow = function(x, y, angle, length) {
  8001. // tail
  8002. var xt = x - length * Math.cos(angle);
  8003. var yt = y - length * Math.sin(angle);
  8004. // inner tail
  8005. // TODO: allow to customize different shapes
  8006. var xi = x - length * 0.9 * Math.cos(angle);
  8007. var yi = y - length * 0.9 * Math.sin(angle);
  8008. // left
  8009. var xl = xt + length / 3 * Math.cos(angle + 0.5 * Math.PI);
  8010. var yl = yt + length / 3 * Math.sin(angle + 0.5 * Math.PI);
  8011. // right
  8012. var xr = xt + length / 3 * Math.cos(angle - 0.5 * Math.PI);
  8013. var yr = yt + length / 3 * Math.sin(angle - 0.5 * Math.PI);
  8014. this.beginPath();
  8015. this.moveTo(x, y);
  8016. this.lineTo(xl, yl);
  8017. this.lineTo(xi, yi);
  8018. this.lineTo(xr, yr);
  8019. this.closePath();
  8020. };
  8021. /**
  8022. * Sets up the dashedLine functionality for drawing
  8023. * Original code came from http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
  8024. * @author David Jordan
  8025. * @date 2012-08-08
  8026. */
  8027. CanvasRenderingContext2D.prototype.dashedLine = function(x,y,x2,y2,dashArray){
  8028. if (!dashArray) dashArray=[10,5];
  8029. if (dashLength==0) dashLength = 0.001; // Hack for Safari
  8030. var dashCount = dashArray.length;
  8031. this.moveTo(x, y);
  8032. var dx = (x2-x), dy = (y2-y);
  8033. var slope = dy/dx;
  8034. var distRemaining = Math.sqrt( dx*dx + dy*dy );
  8035. var dashIndex=0, draw=true;
  8036. while (distRemaining>=0.1){
  8037. var dashLength = dashArray[dashIndex++%dashCount];
  8038. if (dashLength > distRemaining) dashLength = distRemaining;
  8039. var xStep = Math.sqrt( dashLength*dashLength / (1 + slope*slope) );
  8040. if (dx<0) xStep = -xStep;
  8041. x += xStep;
  8042. y += slope*xStep;
  8043. this[draw ? 'lineTo' : 'moveTo'](x,y);
  8044. distRemaining -= dashLength;
  8045. draw = !draw;
  8046. }
  8047. };
  8048. // TODO: add diamond shape
  8049. }
  8050. /**
  8051. * @class Node
  8052. * A node. A node can be connected to other nodes via one or multiple edges.
  8053. * @param {object} properties An object containing properties for the node. All
  8054. * properties are optional, except for the id.
  8055. * {number} id Id of the node. Required
  8056. * {string} label Text label for the node
  8057. * {number} x Horizontal position of the node
  8058. * {number} y Vertical position of the node
  8059. * {string} shape Node shape, available:
  8060. * "database", "circle", "ellipse",
  8061. * "box", "image", "text", "dot",
  8062. * "star", "triangle", "triangleDown",
  8063. * "square"
  8064. * {string} image An image url
  8065. * {string} title An title text, can be HTML
  8066. * {anytype} group A group name or number
  8067. * @param {Graph.Images} imagelist A list with images. Only needed
  8068. * when the node has an image
  8069. * @param {Graph.Groups} grouplist A list with groups. Needed for
  8070. * retrieving group properties
  8071. * @param {Object} constants An object with default values for
  8072. * example for the color
  8073. *
  8074. */
  8075. function Node(properties, imagelist, grouplist, constants) {
  8076. this.selected = false;
  8077. this.edges = []; // all edges connected to this node
  8078. this.dynamicEdges = [];
  8079. this.reroutedEdges = {};
  8080. this.group = constants.nodes.group;
  8081. this.fontSize = constants.nodes.fontSize;
  8082. this.fontFace = constants.nodes.fontFace;
  8083. this.fontColor = constants.nodes.fontColor;
  8084. this.fontDrawThreshold = 3;
  8085. this.color = constants.nodes.color;
  8086. // set defaults for the properties
  8087. this.id = undefined;
  8088. this.shape = constants.nodes.shape;
  8089. this.image = constants.nodes.image;
  8090. this.x = null;
  8091. this.y = null;
  8092. this.xFixed = false;
  8093. this.yFixed = false;
  8094. this.horizontalAlignLeft = true; // these are for the navigation controls
  8095. this.verticalAlignTop = true; // these are for the navigation controls
  8096. this.radius = constants.nodes.radius;
  8097. this.baseRadiusValue = constants.nodes.radius;
  8098. this.radiusFixed = false;
  8099. this.radiusMin = constants.nodes.radiusMin;
  8100. this.radiusMax = constants.nodes.radiusMax;
  8101. this.level = -1;
  8102. this.preassignedLevel = false;
  8103. this.imagelist = imagelist;
  8104. this.grouplist = grouplist;
  8105. // physics properties
  8106. this.fx = 0.0; // external force x
  8107. this.fy = 0.0; // external force y
  8108. this.vx = 0.0; // velocity x
  8109. this.vy = 0.0; // velocity y
  8110. this.minForce = constants.minForce;
  8111. this.damping = constants.physics.damping;
  8112. this.mass = 1; // kg
  8113. this.fixedData = {x:null,y:null};
  8114. this.setProperties(properties, constants);
  8115. // creating the variables for clustering
  8116. this.resetCluster();
  8117. this.dynamicEdgesLength = 0;
  8118. this.clusterSession = 0;
  8119. this.clusterSizeWidthFactor = constants.clustering.nodeScaling.width;
  8120. this.clusterSizeHeightFactor = constants.clustering.nodeScaling.height;
  8121. this.clusterSizeRadiusFactor = constants.clustering.nodeScaling.radius;
  8122. this.maxNodeSizeIncrements = constants.clustering.maxNodeSizeIncrements;
  8123. this.growthIndicator = 0;
  8124. // variables to tell the node about the graph.
  8125. this.graphScaleInv = 1;
  8126. this.graphScale = 1;
  8127. this.canvasTopLeft = {"x": -300, "y": -300};
  8128. this.canvasBottomRight = {"x": 300, "y": 300};
  8129. this.parentEdgeId = null;
  8130. }
  8131. /**
  8132. * (re)setting the clustering variables and objects
  8133. */
  8134. Node.prototype.resetCluster = function() {
  8135. // clustering variables
  8136. this.formationScale = undefined; // this is used to determine when to open the cluster
  8137. this.clusterSize = 1; // this signifies the total amount of nodes in this cluster
  8138. this.containedNodes = {};
  8139. this.containedEdges = {};
  8140. this.clusterSessions = [];
  8141. };
  8142. /**
  8143. * Attach a edge to the node
  8144. * @param {Edge} edge
  8145. */
  8146. Node.prototype.attachEdge = function(edge) {
  8147. if (this.edges.indexOf(edge) == -1) {
  8148. this.edges.push(edge);
  8149. }
  8150. if (this.dynamicEdges.indexOf(edge) == -1) {
  8151. this.dynamicEdges.push(edge);
  8152. }
  8153. this.dynamicEdgesLength = this.dynamicEdges.length;
  8154. };
  8155. /**
  8156. * Detach a edge from the node
  8157. * @param {Edge} edge
  8158. */
  8159. Node.prototype.detachEdge = function(edge) {
  8160. var index = this.edges.indexOf(edge);
  8161. if (index != -1) {
  8162. this.edges.splice(index, 1);
  8163. this.dynamicEdges.splice(index, 1);
  8164. }
  8165. this.dynamicEdgesLength = this.dynamicEdges.length;
  8166. };
  8167. /**
  8168. * Set or overwrite properties for the node
  8169. * @param {Object} properties an object with properties
  8170. * @param {Object} constants and object with default, global properties
  8171. */
  8172. Node.prototype.setProperties = function(properties, constants) {
  8173. if (!properties) {
  8174. return;
  8175. }
  8176. this.originalLabel = undefined;
  8177. // basic properties
  8178. if (properties.id !== undefined) {this.id = properties.id;}
  8179. if (properties.label !== undefined) {this.label = properties.label; this.originalLabel = properties.label;}
  8180. if (properties.title !== undefined) {this.title = properties.title;}
  8181. if (properties.group !== undefined) {this.group = properties.group;}
  8182. if (properties.x !== undefined) {this.x = properties.x;}
  8183. if (properties.y !== undefined) {this.y = properties.y;}
  8184. if (properties.value !== undefined) {this.value = properties.value;}
  8185. if (properties.level !== undefined) {this.level = properties.level; this.preassignedLevel = true;}
  8186. // physics
  8187. if (properties.mass !== undefined) {this.mass = properties.mass;}
  8188. // navigation controls properties
  8189. if (properties.horizontalAlignLeft !== undefined) {this.horizontalAlignLeft = properties.horizontalAlignLeft;}
  8190. if (properties.verticalAlignTop !== undefined) {this.verticalAlignTop = properties.verticalAlignTop;}
  8191. if (properties.triggerFunction !== undefined) {this.triggerFunction = properties.triggerFunction;}
  8192. if (this.id === undefined) {
  8193. throw "Node must have an id";
  8194. }
  8195. // copy group properties
  8196. if (this.group) {
  8197. var groupObj = this.grouplist.get(this.group);
  8198. for (var prop in groupObj) {
  8199. if (groupObj.hasOwnProperty(prop)) {
  8200. this[prop] = groupObj[prop];
  8201. }
  8202. }
  8203. }
  8204. // individual shape properties
  8205. if (properties.shape !== undefined) {this.shape = properties.shape;}
  8206. if (properties.image !== undefined) {this.image = properties.image;}
  8207. if (properties.radius !== undefined) {this.radius = properties.radius;}
  8208. if (properties.color !== undefined) {this.color = util.parseColor(properties.color);}
  8209. if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;}
  8210. if (properties.fontSize !== undefined) {this.fontSize = properties.fontSize;}
  8211. if (properties.fontFace !== undefined) {this.fontFace = properties.fontFace;}
  8212. if (this.image !== undefined && this.image != "") {
  8213. if (this.imagelist) {
  8214. this.imageObj = this.imagelist.load(this.image);
  8215. }
  8216. else {
  8217. throw "No imagelist provided";
  8218. }
  8219. }
  8220. this.xFixed = this.xFixed || (properties.x !== undefined && !properties.allowedToMoveX);
  8221. this.yFixed = this.yFixed || (properties.y !== undefined && !properties.allowedToMoveY);
  8222. this.radiusFixed = this.radiusFixed || (properties.radius !== undefined);
  8223. if (this.shape == 'image') {
  8224. this.radiusMin = constants.nodes.widthMin;
  8225. this.radiusMax = constants.nodes.widthMax;
  8226. }
  8227. // choose draw method depending on the shape
  8228. switch (this.shape) {
  8229. case 'database': this.draw = this._drawDatabase; this.resize = this._resizeDatabase; break;
  8230. case 'box': this.draw = this._drawBox; this.resize = this._resizeBox; break;
  8231. case 'circle': this.draw = this._drawCircle; this.resize = this._resizeCircle; break;
  8232. case 'ellipse': this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  8233. // TODO: add diamond shape
  8234. case 'image': this.draw = this._drawImage; this.resize = this._resizeImage; break;
  8235. case 'text': this.draw = this._drawText; this.resize = this._resizeText; break;
  8236. case 'dot': this.draw = this._drawDot; this.resize = this._resizeShape; break;
  8237. case 'square': this.draw = this._drawSquare; this.resize = this._resizeShape; break;
  8238. case 'triangle': this.draw = this._drawTriangle; this.resize = this._resizeShape; break;
  8239. case 'triangleDown': this.draw = this._drawTriangleDown; this.resize = this._resizeShape; break;
  8240. case 'star': this.draw = this._drawStar; this.resize = this._resizeShape; break;
  8241. default: this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  8242. }
  8243. // reset the size of the node, this can be changed
  8244. this._reset();
  8245. };
  8246. /**
  8247. * select this node
  8248. */
  8249. Node.prototype.select = function() {
  8250. this.selected = true;
  8251. this._reset();
  8252. };
  8253. /**
  8254. * unselect this node
  8255. */
  8256. Node.prototype.unselect = function() {
  8257. this.selected = false;
  8258. this._reset();
  8259. };
  8260. /**
  8261. * Reset the calculated size of the node, forces it to recalculate its size
  8262. */
  8263. Node.prototype.clearSizeCache = function() {
  8264. this._reset();
  8265. };
  8266. /**
  8267. * Reset the calculated size of the node, forces it to recalculate its size
  8268. * @private
  8269. */
  8270. Node.prototype._reset = function() {
  8271. this.width = undefined;
  8272. this.height = undefined;
  8273. };
  8274. /**
  8275. * get the title of this node.
  8276. * @return {string} title The title of the node, or undefined when no title
  8277. * has been set.
  8278. */
  8279. Node.prototype.getTitle = function() {
  8280. return typeof this.title === "function" ? this.title() : this.title;
  8281. };
  8282. /**
  8283. * Calculate the distance to the border of the Node
  8284. * @param {CanvasRenderingContext2D} ctx
  8285. * @param {Number} angle Angle in radians
  8286. * @returns {number} distance Distance to the border in pixels
  8287. */
  8288. Node.prototype.distanceToBorder = function (ctx, angle) {
  8289. var borderWidth = 1;
  8290. if (!this.width) {
  8291. this.resize(ctx);
  8292. }
  8293. switch (this.shape) {
  8294. case 'circle':
  8295. case 'dot':
  8296. return this.radius + borderWidth;
  8297. case 'ellipse':
  8298. var a = this.width / 2;
  8299. var b = this.height / 2;
  8300. var w = (Math.sin(angle) * a);
  8301. var h = (Math.cos(angle) * b);
  8302. return a * b / Math.sqrt(w * w + h * h);
  8303. // TODO: implement distanceToBorder for database
  8304. // TODO: implement distanceToBorder for triangle
  8305. // TODO: implement distanceToBorder for triangleDown
  8306. case 'box':
  8307. case 'image':
  8308. case 'text':
  8309. default:
  8310. if (this.width) {
  8311. return Math.min(
  8312. Math.abs(this.width / 2 / Math.cos(angle)),
  8313. Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth;
  8314. // TODO: reckon with border radius too in case of box
  8315. }
  8316. else {
  8317. return 0;
  8318. }
  8319. }
  8320. // TODO: implement calculation of distance to border for all shapes
  8321. };
  8322. /**
  8323. * Set forces acting on the node
  8324. * @param {number} fx Force in horizontal direction
  8325. * @param {number} fy Force in vertical direction
  8326. */
  8327. Node.prototype._setForce = function(fx, fy) {
  8328. this.fx = fx;
  8329. this.fy = fy;
  8330. };
  8331. /**
  8332. * Add forces acting on the node
  8333. * @param {number} fx Force in horizontal direction
  8334. * @param {number} fy Force in vertical direction
  8335. * @private
  8336. */
  8337. Node.prototype._addForce = function(fx, fy) {
  8338. this.fx += fx;
  8339. this.fy += fy;
  8340. };
  8341. /**
  8342. * Perform one discrete step for the node
  8343. * @param {number} interval Time interval in seconds
  8344. */
  8345. Node.prototype.discreteStep = function(interval) {
  8346. if (!this.xFixed) {
  8347. var dx = this.damping * this.vx; // damping force
  8348. var ax = (this.fx - dx) / this.mass; // acceleration
  8349. this.vx += ax * interval; // velocity
  8350. this.x += this.vx * interval; // position
  8351. }
  8352. if (!this.yFixed) {
  8353. var dy = this.damping * this.vy; // damping force
  8354. var ay = (this.fy - dy) / this.mass; // acceleration
  8355. this.vy += ay * interval; // velocity
  8356. this.y += this.vy * interval; // position
  8357. }
  8358. };
  8359. /**
  8360. * Perform one discrete step for the node
  8361. * @param {number} interval Time interval in seconds
  8362. * @param {number} maxVelocity The speed limit imposed on the velocity
  8363. */
  8364. Node.prototype.discreteStepLimited = function(interval, maxVelocity) {
  8365. if (!this.xFixed) {
  8366. var dx = this.damping * this.vx; // damping force
  8367. var ax = (this.fx - dx) / this.mass; // acceleration
  8368. this.vx += ax * interval; // velocity
  8369. this.vx = (Math.abs(this.vx) > maxVelocity) ? ((this.vx > 0) ? maxVelocity : -maxVelocity) : this.vx;
  8370. this.x += this.vx * interval; // position
  8371. }
  8372. else {
  8373. this.fx = 0;
  8374. }
  8375. if (!this.yFixed) {
  8376. var dy = this.damping * this.vy; // damping force
  8377. var ay = (this.fy - dy) / this.mass; // acceleration
  8378. this.vy += ay * interval; // velocity
  8379. this.vy = (Math.abs(this.vy) > maxVelocity) ? ((this.vy > 0) ? maxVelocity : -maxVelocity) : this.vy;
  8380. this.y += this.vy * interval; // position
  8381. }
  8382. else {
  8383. this.fy = 0;
  8384. }
  8385. };
  8386. /**
  8387. * Check if this node has a fixed x and y position
  8388. * @return {boolean} true if fixed, false if not
  8389. */
  8390. Node.prototype.isFixed = function() {
  8391. return (this.xFixed && this.yFixed);
  8392. };
  8393. /**
  8394. * Check if this node is moving
  8395. * @param {number} vmin the minimum velocity considered as "moving"
  8396. * @return {boolean} true if moving, false if it has no velocity
  8397. */
  8398. // TODO: replace this method with calculating the kinetic energy
  8399. Node.prototype.isMoving = function(vmin) {
  8400. return (Math.abs(this.vx) > vmin || Math.abs(this.vy) > vmin);
  8401. };
  8402. /**
  8403. * check if this node is selecte
  8404. * @return {boolean} selected True if node is selected, else false
  8405. */
  8406. Node.prototype.isSelected = function() {
  8407. return this.selected;
  8408. };
  8409. /**
  8410. * Retrieve the value of the node. Can be undefined
  8411. * @return {Number} value
  8412. */
  8413. Node.prototype.getValue = function() {
  8414. return this.value;
  8415. };
  8416. /**
  8417. * Calculate the distance from the nodes location to the given location (x,y)
  8418. * @param {Number} x
  8419. * @param {Number} y
  8420. * @return {Number} value
  8421. */
  8422. Node.prototype.getDistance = function(x, y) {
  8423. var dx = this.x - x,
  8424. dy = this.y - y;
  8425. return Math.sqrt(dx * dx + dy * dy);
  8426. };
  8427. /**
  8428. * Adjust the value range of the node. The node will adjust it's radius
  8429. * based on its value.
  8430. * @param {Number} min
  8431. * @param {Number} max
  8432. */
  8433. Node.prototype.setValueRange = function(min, max) {
  8434. if (!this.radiusFixed && this.value !== undefined) {
  8435. if (max == min) {
  8436. this.radius = (this.radiusMin + this.radiusMax) / 2;
  8437. }
  8438. else {
  8439. var scale = (this.radiusMax - this.radiusMin) / (max - min);
  8440. this.radius = (this.value - min) * scale + this.radiusMin;
  8441. }
  8442. }
  8443. this.baseRadiusValue = this.radius;
  8444. };
  8445. /**
  8446. * Draw this node in the given canvas
  8447. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8448. * @param {CanvasRenderingContext2D} ctx
  8449. */
  8450. Node.prototype.draw = function(ctx) {
  8451. throw "Draw method not initialized for node";
  8452. };
  8453. /**
  8454. * Recalculate the size of this node in the given canvas
  8455. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8456. * @param {CanvasRenderingContext2D} ctx
  8457. */
  8458. Node.prototype.resize = function(ctx) {
  8459. throw "Resize method not initialized for node";
  8460. };
  8461. /**
  8462. * Check if this object is overlapping with the provided object
  8463. * @param {Object} obj an object with parameters left, top, right, bottom
  8464. * @return {boolean} True if location is located on node
  8465. */
  8466. Node.prototype.isOverlappingWith = function(obj) {
  8467. return (this.left < obj.right &&
  8468. this.left + this.width > obj.left &&
  8469. this.top < obj.bottom &&
  8470. this.top + this.height > obj.top);
  8471. };
  8472. Node.prototype._resizeImage = function (ctx) {
  8473. // TODO: pre calculate the image size
  8474. if (!this.width || !this.height) { // undefined or 0
  8475. var width, height;
  8476. if (this.value) {
  8477. this.radius = this.baseRadiusValue;
  8478. var scale = this.imageObj.height / this.imageObj.width;
  8479. if (scale !== undefined) {
  8480. width = this.radius || this.imageObj.width;
  8481. height = this.radius * scale || this.imageObj.height;
  8482. }
  8483. else {
  8484. width = 0;
  8485. height = 0;
  8486. }
  8487. }
  8488. else {
  8489. width = this.imageObj.width;
  8490. height = this.imageObj.height;
  8491. }
  8492. this.width = width;
  8493. this.height = height;
  8494. this.growthIndicator = 0;
  8495. if (this.width > 0 && this.height > 0) {
  8496. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8497. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8498. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8499. this.growthIndicator = this.width - width;
  8500. }
  8501. }
  8502. };
  8503. Node.prototype._drawImage = function (ctx) {
  8504. this._resizeImage(ctx);
  8505. this.left = this.x - this.width / 2;
  8506. this.top = this.y - this.height / 2;
  8507. var yLabel;
  8508. if (this.imageObj.width != 0 ) {
  8509. // draw the shade
  8510. if (this.clusterSize > 1) {
  8511. var lineWidth = ((this.clusterSize > 1) ? 10 : 0.0);
  8512. lineWidth *= this.graphScaleInv;
  8513. lineWidth = Math.min(0.2 * this.width,lineWidth);
  8514. ctx.globalAlpha = 0.5;
  8515. ctx.drawImage(this.imageObj, this.left - lineWidth, this.top - lineWidth, this.width + 2*lineWidth, this.height + 2*lineWidth);
  8516. }
  8517. // draw the image
  8518. ctx.globalAlpha = 1.0;
  8519. ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height);
  8520. yLabel = this.y + this.height / 2;
  8521. }
  8522. else {
  8523. // image still loading... just draw the label for now
  8524. yLabel = this.y;
  8525. }
  8526. this._label(ctx, this.label, this.x, yLabel, undefined, "top");
  8527. };
  8528. Node.prototype._resizeBox = function (ctx) {
  8529. if (!this.width) {
  8530. var margin = 5;
  8531. var textSize = this.getTextSize(ctx);
  8532. this.width = textSize.width + 2 * margin;
  8533. this.height = textSize.height + 2 * margin;
  8534. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  8535. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  8536. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  8537. // this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8538. }
  8539. };
  8540. Node.prototype._drawBox = function (ctx) {
  8541. this._resizeBox(ctx);
  8542. this.left = this.x - this.width / 2;
  8543. this.top = this.y - this.height / 2;
  8544. var clusterLineWidth = 2.5;
  8545. var selectionLineWidth = 2;
  8546. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8547. // draw the outer border
  8548. if (this.clusterSize > 1) {
  8549. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8550. ctx.lineWidth *= this.graphScaleInv;
  8551. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8552. ctx.roundRect(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth, this.radius);
  8553. ctx.stroke();
  8554. }
  8555. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8556. ctx.lineWidth *= this.graphScaleInv;
  8557. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8558. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8559. ctx.roundRect(this.left, this.top, this.width, this.height, this.radius);
  8560. ctx.fill();
  8561. ctx.stroke();
  8562. this._label(ctx, this.label, this.x, this.y);
  8563. };
  8564. Node.prototype._resizeDatabase = function (ctx) {
  8565. if (!this.width) {
  8566. var margin = 5;
  8567. var textSize = this.getTextSize(ctx);
  8568. var size = textSize.width + 2 * margin;
  8569. this.width = size;
  8570. this.height = size;
  8571. // scaling used for clustering
  8572. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8573. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8574. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8575. this.growthIndicator = this.width - size;
  8576. }
  8577. };
  8578. Node.prototype._drawDatabase = function (ctx) {
  8579. this._resizeDatabase(ctx);
  8580. this.left = this.x - this.width / 2;
  8581. this.top = this.y - this.height / 2;
  8582. var clusterLineWidth = 2.5;
  8583. var selectionLineWidth = 2;
  8584. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8585. // draw the outer border
  8586. if (this.clusterSize > 1) {
  8587. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8588. ctx.lineWidth *= this.graphScaleInv;
  8589. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8590. 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);
  8591. ctx.stroke();
  8592. }
  8593. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8594. ctx.lineWidth *= this.graphScaleInv;
  8595. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8596. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8597. ctx.database(this.x - this.width/2, this.y - this.height*0.5, this.width, this.height);
  8598. ctx.fill();
  8599. ctx.stroke();
  8600. this._label(ctx, this.label, this.x, this.y);
  8601. };
  8602. Node.prototype._resizeCircle = function (ctx) {
  8603. if (!this.width) {
  8604. var margin = 5;
  8605. var textSize = this.getTextSize(ctx);
  8606. var diameter = Math.max(textSize.width, textSize.height) + 2 * margin;
  8607. this.radius = diameter / 2;
  8608. this.width = diameter;
  8609. this.height = diameter;
  8610. // scaling used for clustering
  8611. // this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  8612. // this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  8613. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8614. this.growthIndicator = this.radius - 0.5*diameter;
  8615. }
  8616. };
  8617. Node.prototype._drawCircle = function (ctx) {
  8618. this._resizeCircle(ctx);
  8619. this.left = this.x - this.width / 2;
  8620. this.top = this.y - this.height / 2;
  8621. var clusterLineWidth = 2.5;
  8622. var selectionLineWidth = 2;
  8623. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8624. // draw the outer border
  8625. if (this.clusterSize > 1) {
  8626. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8627. ctx.lineWidth *= this.graphScaleInv;
  8628. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8629. ctx.circle(this.x, this.y, this.radius+2*ctx.lineWidth);
  8630. ctx.stroke();
  8631. }
  8632. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8633. ctx.lineWidth *= this.graphScaleInv;
  8634. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8635. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8636. ctx.circle(this.x, this.y, this.radius);
  8637. ctx.fill();
  8638. ctx.stroke();
  8639. this._label(ctx, this.label, this.x, this.y);
  8640. };
  8641. Node.prototype._resizeEllipse = function (ctx) {
  8642. if (!this.width) {
  8643. var textSize = this.getTextSize(ctx);
  8644. this.width = textSize.width * 1.5;
  8645. this.height = textSize.height * 2;
  8646. if (this.width < this.height) {
  8647. this.width = this.height;
  8648. }
  8649. var defaultSize = this.width;
  8650. // scaling used for clustering
  8651. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8652. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8653. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8654. this.growthIndicator = this.width - defaultSize;
  8655. }
  8656. };
  8657. Node.prototype._drawEllipse = function (ctx) {
  8658. this._resizeEllipse(ctx);
  8659. this.left = this.x - this.width / 2;
  8660. this.top = this.y - this.height / 2;
  8661. var clusterLineWidth = 2.5;
  8662. var selectionLineWidth = 2;
  8663. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8664. // draw the outer border
  8665. if (this.clusterSize > 1) {
  8666. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8667. ctx.lineWidth *= this.graphScaleInv;
  8668. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8669. ctx.ellipse(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth);
  8670. ctx.stroke();
  8671. }
  8672. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8673. ctx.lineWidth *= this.graphScaleInv;
  8674. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8675. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8676. ctx.ellipse(this.left, this.top, this.width, this.height);
  8677. ctx.fill();
  8678. ctx.stroke();
  8679. this._label(ctx, this.label, this.x, this.y);
  8680. };
  8681. Node.prototype._drawDot = function (ctx) {
  8682. this._drawShape(ctx, 'circle');
  8683. };
  8684. Node.prototype._drawTriangle = function (ctx) {
  8685. this._drawShape(ctx, 'triangle');
  8686. };
  8687. Node.prototype._drawTriangleDown = function (ctx) {
  8688. this._drawShape(ctx, 'triangleDown');
  8689. };
  8690. Node.prototype._drawSquare = function (ctx) {
  8691. this._drawShape(ctx, 'square');
  8692. };
  8693. Node.prototype._drawStar = function (ctx) {
  8694. this._drawShape(ctx, 'star');
  8695. };
  8696. Node.prototype._resizeShape = function (ctx) {
  8697. if (!this.width) {
  8698. this.radius = this.baseRadiusValue;
  8699. var size = 2 * this.radius;
  8700. this.width = size;
  8701. this.height = size;
  8702. // scaling used for clustering
  8703. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8704. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8705. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8706. this.growthIndicator = this.width - size;
  8707. }
  8708. };
  8709. Node.prototype._drawShape = function (ctx, shape) {
  8710. this._resizeShape(ctx);
  8711. this.left = this.x - this.width / 2;
  8712. this.top = this.y - this.height / 2;
  8713. var clusterLineWidth = 2.5;
  8714. var selectionLineWidth = 2;
  8715. var radiusMultiplier = 2;
  8716. // choose draw method depending on the shape
  8717. switch (shape) {
  8718. case 'dot': radiusMultiplier = 2; break;
  8719. case 'square': radiusMultiplier = 2; break;
  8720. case 'triangle': radiusMultiplier = 3; break;
  8721. case 'triangleDown': radiusMultiplier = 3; break;
  8722. case 'star': radiusMultiplier = 4; break;
  8723. }
  8724. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8725. // draw the outer border
  8726. if (this.clusterSize > 1) {
  8727. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8728. ctx.lineWidth *= this.graphScaleInv;
  8729. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8730. ctx[shape](this.x, this.y, this.radius + radiusMultiplier * ctx.lineWidth);
  8731. ctx.stroke();
  8732. }
  8733. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8734. ctx.lineWidth *= this.graphScaleInv;
  8735. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8736. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8737. ctx[shape](this.x, this.y, this.radius);
  8738. ctx.fill();
  8739. ctx.stroke();
  8740. if (this.label) {
  8741. this._label(ctx, this.label, this.x, this.y + this.height / 2, undefined, 'top');
  8742. }
  8743. };
  8744. Node.prototype._resizeText = function (ctx) {
  8745. if (!this.width) {
  8746. var margin = 5;
  8747. var textSize = this.getTextSize(ctx);
  8748. this.width = textSize.width + 2 * margin;
  8749. this.height = textSize.height + 2 * margin;
  8750. // scaling used for clustering
  8751. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8752. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8753. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8754. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  8755. }
  8756. };
  8757. Node.prototype._drawText = function (ctx) {
  8758. this._resizeText(ctx);
  8759. this.left = this.x - this.width / 2;
  8760. this.top = this.y - this.height / 2;
  8761. this._label(ctx, this.label, this.x, this.y);
  8762. };
  8763. Node.prototype._label = function (ctx, text, x, y, align, baseline) {
  8764. if (text && this.fontSize * this.graphScale > this.fontDrawThreshold) {
  8765. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  8766. ctx.fillStyle = this.fontColor || "black";
  8767. ctx.textAlign = align || "center";
  8768. ctx.textBaseline = baseline || "middle";
  8769. var lines = text.split('\n'),
  8770. lineCount = lines.length,
  8771. fontSize = (this.fontSize + 4),
  8772. yLine = y + (1 - lineCount) / 2 * fontSize;
  8773. for (var i = 0; i < lineCount; i++) {
  8774. ctx.fillText(lines[i], x, yLine);
  8775. yLine += fontSize;
  8776. }
  8777. }
  8778. };
  8779. Node.prototype.getTextSize = function(ctx) {
  8780. if (this.label !== undefined) {
  8781. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  8782. var lines = this.label.split('\n'),
  8783. height = (this.fontSize + 4) * lines.length,
  8784. width = 0;
  8785. for (var i = 0, iMax = lines.length; i < iMax; i++) {
  8786. width = Math.max(width, ctx.measureText(lines[i]).width);
  8787. }
  8788. return {"width": width, "height": height};
  8789. }
  8790. else {
  8791. return {"width": 0, "height": 0};
  8792. }
  8793. };
  8794. /**
  8795. * this is used to determine if a node is visible at all. this is used to determine when it needs to be drawn.
  8796. * there is a safety margin of 0.3 * width;
  8797. *
  8798. * @returns {boolean}
  8799. */
  8800. Node.prototype.inArea = function() {
  8801. if (this.width !== undefined) {
  8802. return (this.x + this.width*this.graphScaleInv >= this.canvasTopLeft.x &&
  8803. this.x - this.width*this.graphScaleInv < this.canvasBottomRight.x &&
  8804. this.y + this.height*this.graphScaleInv >= this.canvasTopLeft.y &&
  8805. this.y - this.height*this.graphScaleInv < this.canvasBottomRight.y);
  8806. }
  8807. else {
  8808. return true;
  8809. }
  8810. };
  8811. /**
  8812. * checks if the core of the node is in the display area, this is used for opening clusters around zoom
  8813. * @returns {boolean}
  8814. */
  8815. Node.prototype.inView = function() {
  8816. return (this.x >= this.canvasTopLeft.x &&
  8817. this.x < this.canvasBottomRight.x &&
  8818. this.y >= this.canvasTopLeft.y &&
  8819. this.y < this.canvasBottomRight.y);
  8820. };
  8821. /**
  8822. * This allows the zoom level of the graph to influence the rendering
  8823. * We store the inverted scale and the coordinates of the top left, and bottom right points of the canvas
  8824. *
  8825. * @param scale
  8826. * @param canvasTopLeft
  8827. * @param canvasBottomRight
  8828. */
  8829. Node.prototype.setScaleAndPos = function(scale,canvasTopLeft,canvasBottomRight) {
  8830. this.graphScaleInv = 1.0/scale;
  8831. this.graphScale = scale;
  8832. this.canvasTopLeft = canvasTopLeft;
  8833. this.canvasBottomRight = canvasBottomRight;
  8834. };
  8835. /**
  8836. * This allows the zoom level of the graph to influence the rendering
  8837. *
  8838. * @param scale
  8839. */
  8840. Node.prototype.setScale = function(scale) {
  8841. this.graphScaleInv = 1.0/scale;
  8842. this.graphScale = scale;
  8843. };
  8844. /**
  8845. * set the velocity at 0. Is called when this node is contained in another during clustering
  8846. */
  8847. Node.prototype.clearVelocity = function() {
  8848. this.vx = 0;
  8849. this.vy = 0;
  8850. };
  8851. /**
  8852. * Basic preservation of (kinectic) energy
  8853. *
  8854. * @param massBeforeClustering
  8855. */
  8856. Node.prototype.updateVelocity = function(massBeforeClustering) {
  8857. var energyBefore = this.vx * this.vx * massBeforeClustering;
  8858. //this.vx = (this.vx < 0) ? -Math.sqrt(energyBefore/this.mass) : Math.sqrt(energyBefore/this.mass);
  8859. this.vx = Math.sqrt(energyBefore/this.mass);
  8860. energyBefore = this.vy * this.vy * massBeforeClustering;
  8861. //this.vy = (this.vy < 0) ? -Math.sqrt(energyBefore/this.mass) : Math.sqrt(energyBefore/this.mass);
  8862. this.vy = Math.sqrt(energyBefore/this.mass);
  8863. };
  8864. /**
  8865. * @class Edge
  8866. *
  8867. * A edge connects two nodes
  8868. * @param {Object} properties Object with properties. Must contain
  8869. * At least properties from and to.
  8870. * Available properties: from (number),
  8871. * to (number), label (string, color (string),
  8872. * width (number), style (string),
  8873. * length (number), title (string)
  8874. * @param {Graph} graph A graph object, used to find and edge to
  8875. * nodes.
  8876. * @param {Object} constants An object with default values for
  8877. * example for the color
  8878. */
  8879. function Edge (properties, graph, constants) {
  8880. if (!graph) {
  8881. throw "No graph provided";
  8882. }
  8883. this.graph = graph;
  8884. // initialize constants
  8885. this.widthMin = constants.edges.widthMin;
  8886. this.widthMax = constants.edges.widthMax;
  8887. // initialize variables
  8888. this.id = undefined;
  8889. this.fromId = undefined;
  8890. this.toId = undefined;
  8891. this.style = constants.edges.style;
  8892. this.title = undefined;
  8893. this.width = constants.edges.width;
  8894. this.value = undefined;
  8895. this.length = constants.physics.springLength;
  8896. this.customLength = false;
  8897. this.selected = false;
  8898. this.smooth = constants.smoothCurves;
  8899. this.arrowScaleFactor = constants.edges.arrowScaleFactor;
  8900. this.from = null; // a node
  8901. this.to = null; // a node
  8902. this.via = null; // a temp node
  8903. // we use this to be able to reconnect the edge to a cluster if its node is put into a cluster
  8904. // by storing the original information we can revert to the original connection when the cluser is opened.
  8905. this.originalFromId = [];
  8906. this.originalToId = [];
  8907. this.connected = false;
  8908. // Added to support dashed lines
  8909. // David Jordan
  8910. // 2012-08-08
  8911. this.dash = util.extend({}, constants.edges.dash); // contains properties length, gap, altLength
  8912. this.color = {color:constants.edges.color.color,
  8913. highlight:constants.edges.color.highlight};
  8914. this.widthFixed = false;
  8915. this.lengthFixed = false;
  8916. this.setProperties(properties, constants);
  8917. }
  8918. /**
  8919. * Set or overwrite properties for the edge
  8920. * @param {Object} properties an object with properties
  8921. * @param {Object} constants and object with default, global properties
  8922. */
  8923. Edge.prototype.setProperties = function(properties, constants) {
  8924. if (!properties) {
  8925. return;
  8926. }
  8927. if (properties.from !== undefined) {this.fromId = properties.from;}
  8928. if (properties.to !== undefined) {this.toId = properties.to;}
  8929. if (properties.id !== undefined) {this.id = properties.id;}
  8930. if (properties.style !== undefined) {this.style = properties.style;}
  8931. if (properties.label !== undefined) {this.label = properties.label;}
  8932. if (this.label) {
  8933. this.fontSize = constants.edges.fontSize;
  8934. this.fontFace = constants.edges.fontFace;
  8935. this.fontColor = constants.edges.fontColor;
  8936. this.fontFill = constants.edges.fontFill;
  8937. if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;}
  8938. if (properties.fontSize !== undefined) {this.fontSize = properties.fontSize;}
  8939. if (properties.fontFace !== undefined) {this.fontFace = properties.fontFace;}
  8940. if (properties.fontFill !== undefined) {this.fontFill = properties.fontFill;}
  8941. }
  8942. if (properties.title !== undefined) {this.title = properties.title;}
  8943. if (properties.width !== undefined) {this.width = properties.width;}
  8944. if (properties.value !== undefined) {this.value = properties.value;}
  8945. if (properties.length !== undefined) {this.length = properties.length;
  8946. this.customLength = true;}
  8947. // scale the arrow
  8948. if (properties.arrowScaleFactor !== undefined) {this.arrowScaleFactor = properties.arrowScaleFactor;}
  8949. // Added to support dashed lines
  8950. // David Jordan
  8951. // 2012-08-08
  8952. if (properties.dash) {
  8953. if (properties.dash.length !== undefined) {this.dash.length = properties.dash.length;}
  8954. if (properties.dash.gap !== undefined) {this.dash.gap = properties.dash.gap;}
  8955. if (properties.dash.altLength !== undefined) {this.dash.altLength = properties.dash.altLength;}
  8956. }
  8957. if (properties.color !== undefined) {
  8958. if (util.isString(properties.color)) {
  8959. this.color.color = properties.color;
  8960. this.color.highlight = properties.color;
  8961. }
  8962. else {
  8963. if (properties.color.color !== undefined) {this.color.color = properties.color.color;}
  8964. if (properties.color.highlight !== undefined) {this.color.highlight = properties.color.highlight;}
  8965. }
  8966. }
  8967. // A node is connected when it has a from and to node.
  8968. this.connect();
  8969. this.widthFixed = this.widthFixed || (properties.width !== undefined);
  8970. this.lengthFixed = this.lengthFixed || (properties.length !== undefined);
  8971. // set draw method based on style
  8972. switch (this.style) {
  8973. case 'line': this.draw = this._drawLine; break;
  8974. case 'arrow': this.draw = this._drawArrow; break;
  8975. case 'arrow-center': this.draw = this._drawArrowCenter; break;
  8976. case 'dash-line': this.draw = this._drawDashLine; break;
  8977. default: this.draw = this._drawLine; break;
  8978. }
  8979. };
  8980. /**
  8981. * Connect an edge to its nodes
  8982. */
  8983. Edge.prototype.connect = function () {
  8984. this.disconnect();
  8985. this.from = this.graph.nodes[this.fromId] || null;
  8986. this.to = this.graph.nodes[this.toId] || null;
  8987. this.connected = (this.from && this.to);
  8988. if (this.connected) {
  8989. this.from.attachEdge(this);
  8990. this.to.attachEdge(this);
  8991. }
  8992. else {
  8993. if (this.from) {
  8994. this.from.detachEdge(this);
  8995. }
  8996. if (this.to) {
  8997. this.to.detachEdge(this);
  8998. }
  8999. }
  9000. };
  9001. /**
  9002. * Disconnect an edge from its nodes
  9003. */
  9004. Edge.prototype.disconnect = function () {
  9005. if (this.from) {
  9006. this.from.detachEdge(this);
  9007. this.from = null;
  9008. }
  9009. if (this.to) {
  9010. this.to.detachEdge(this);
  9011. this.to = null;
  9012. }
  9013. this.connected = false;
  9014. };
  9015. /**
  9016. * get the title of this edge.
  9017. * @return {string} title The title of the edge, or undefined when no title
  9018. * has been set.
  9019. */
  9020. Edge.prototype.getTitle = function() {
  9021. return typeof this.title === "function" ? this.title() : this.title;
  9022. };
  9023. /**
  9024. * Retrieve the value of the edge. Can be undefined
  9025. * @return {Number} value
  9026. */
  9027. Edge.prototype.getValue = function() {
  9028. return this.value;
  9029. };
  9030. /**
  9031. * Adjust the value range of the edge. The edge will adjust it's width
  9032. * based on its value.
  9033. * @param {Number} min
  9034. * @param {Number} max
  9035. */
  9036. Edge.prototype.setValueRange = function(min, max) {
  9037. if (!this.widthFixed && this.value !== undefined) {
  9038. var scale = (this.widthMax - this.widthMin) / (max - min);
  9039. this.width = (this.value - min) * scale + this.widthMin;
  9040. }
  9041. };
  9042. /**
  9043. * Redraw a edge
  9044. * Draw this edge in the given canvas
  9045. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9046. * @param {CanvasRenderingContext2D} ctx
  9047. */
  9048. Edge.prototype.draw = function(ctx) {
  9049. throw "Method draw not initialized in edge";
  9050. };
  9051. /**
  9052. * Check if this object is overlapping with the provided object
  9053. * @param {Object} obj an object with parameters left, top
  9054. * @return {boolean} True if location is located on the edge
  9055. */
  9056. Edge.prototype.isOverlappingWith = function(obj) {
  9057. if (this.connected) {
  9058. var distMax = 10;
  9059. var xFrom = this.from.x;
  9060. var yFrom = this.from.y;
  9061. var xTo = this.to.x;
  9062. var yTo = this.to.y;
  9063. var xObj = obj.left;
  9064. var yObj = obj.top;
  9065. var dist = this._getDistanceToEdge(xFrom, yFrom, xTo, yTo, xObj, yObj);
  9066. return (dist < distMax);
  9067. }
  9068. else {
  9069. return false
  9070. }
  9071. };
  9072. /**
  9073. * Redraw a edge as a line
  9074. * Draw this edge in the given canvas
  9075. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9076. * @param {CanvasRenderingContext2D} ctx
  9077. * @private
  9078. */
  9079. Edge.prototype._drawLine = function(ctx) {
  9080. // set style
  9081. if (this.selected == true) {ctx.strokeStyle = this.color.highlight;}
  9082. else {ctx.strokeStyle = this.color.color;}
  9083. ctx.lineWidth = this._getLineWidth();
  9084. if (this.from != this.to) {
  9085. // draw line
  9086. this._line(ctx);
  9087. // draw label
  9088. var point;
  9089. if (this.label) {
  9090. if (this.smooth == true) {
  9091. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9092. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9093. point = {x:midpointX, y:midpointY};
  9094. }
  9095. else {
  9096. point = this._pointOnLine(0.5);
  9097. }
  9098. this._label(ctx, this.label, point.x, point.y);
  9099. }
  9100. }
  9101. else {
  9102. var x, y;
  9103. var radius = this.length / 4;
  9104. var node = this.from;
  9105. if (!node.width) {
  9106. node.resize(ctx);
  9107. }
  9108. if (node.width > node.height) {
  9109. x = node.x + node.width / 2;
  9110. y = node.y - radius;
  9111. }
  9112. else {
  9113. x = node.x + radius;
  9114. y = node.y - node.height / 2;
  9115. }
  9116. this._circle(ctx, x, y, radius);
  9117. point = this._pointOnCircle(x, y, radius, 0.5);
  9118. this._label(ctx, this.label, point.x, point.y);
  9119. }
  9120. };
  9121. /**
  9122. * Get the line width of the edge. Depends on width and whether one of the
  9123. * connected nodes is selected.
  9124. * @return {Number} width
  9125. * @private
  9126. */
  9127. Edge.prototype._getLineWidth = function() {
  9128. if (this.selected == true) {
  9129. return Math.min(this.width * 2, this.widthMax)*this.graphScaleInv;
  9130. }
  9131. else {
  9132. return this.width*this.graphScaleInv;
  9133. }
  9134. };
  9135. /**
  9136. * Draw a line between two nodes
  9137. * @param {CanvasRenderingContext2D} ctx
  9138. * @private
  9139. */
  9140. Edge.prototype._line = function (ctx) {
  9141. // draw a straight line
  9142. ctx.beginPath();
  9143. ctx.moveTo(this.from.x, this.from.y);
  9144. if (this.smooth == true) {
  9145. ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y);
  9146. }
  9147. else {
  9148. ctx.lineTo(this.to.x, this.to.y);
  9149. }
  9150. ctx.stroke();
  9151. };
  9152. /**
  9153. * Draw a line from a node to itself, a circle
  9154. * @param {CanvasRenderingContext2D} ctx
  9155. * @param {Number} x
  9156. * @param {Number} y
  9157. * @param {Number} radius
  9158. * @private
  9159. */
  9160. Edge.prototype._circle = function (ctx, x, y, radius) {
  9161. // draw a circle
  9162. ctx.beginPath();
  9163. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  9164. ctx.stroke();
  9165. };
  9166. /**
  9167. * Draw label with white background and with the middle at (x, y)
  9168. * @param {CanvasRenderingContext2D} ctx
  9169. * @param {String} text
  9170. * @param {Number} x
  9171. * @param {Number} y
  9172. * @private
  9173. */
  9174. Edge.prototype._label = function (ctx, text, x, y) {
  9175. if (text) {
  9176. // TODO: cache the calculated size
  9177. ctx.font = ((this.from.selected || this.to.selected) ? "bold " : "") +
  9178. this.fontSize + "px " + this.fontFace;
  9179. ctx.fillStyle = this.fontFill;
  9180. var width = ctx.measureText(text).width;
  9181. var height = this.fontSize;
  9182. var left = x - width / 2;
  9183. var top = y - height / 2;
  9184. ctx.fillRect(left, top, width, height);
  9185. // draw text
  9186. ctx.fillStyle = this.fontColor || "black";
  9187. ctx.textAlign = "left";
  9188. ctx.textBaseline = "top";
  9189. ctx.fillText(text, left, top);
  9190. }
  9191. };
  9192. /**
  9193. * Redraw a edge as a dashed line
  9194. * Draw this edge in the given canvas
  9195. * @author David Jordan
  9196. * @date 2012-08-08
  9197. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9198. * @param {CanvasRenderingContext2D} ctx
  9199. * @private
  9200. */
  9201. Edge.prototype._drawDashLine = function(ctx) {
  9202. // set style
  9203. if (this.selected == true) {ctx.strokeStyle = this.color.highlight;}
  9204. else {ctx.strokeStyle = this.color.color;}
  9205. ctx.lineWidth = this._getLineWidth();
  9206. // only firefox and chrome support this method, else we use the legacy one.
  9207. if (ctx.mozDash !== undefined || ctx.setLineDash !== undefined) {
  9208. ctx.beginPath();
  9209. ctx.moveTo(this.from.x, this.from.y);
  9210. // configure the dash pattern
  9211. var pattern = [0];
  9212. if (this.dash.length !== undefined && this.dash.gap !== undefined) {
  9213. pattern = [this.dash.length,this.dash.gap];
  9214. }
  9215. else {
  9216. pattern = [5,5];
  9217. }
  9218. // set dash settings for chrome or firefox
  9219. if (typeof ctx.setLineDash !== 'undefined') { //Chrome
  9220. ctx.setLineDash(pattern);
  9221. ctx.lineDashOffset = 0;
  9222. } else { //Firefox
  9223. ctx.mozDash = pattern;
  9224. ctx.mozDashOffset = 0;
  9225. }
  9226. // draw the line
  9227. if (this.smooth == true) {
  9228. ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y);
  9229. }
  9230. else {
  9231. ctx.lineTo(this.to.x, this.to.y);
  9232. }
  9233. ctx.stroke();
  9234. // restore the dash settings.
  9235. if (typeof ctx.setLineDash !== 'undefined') { //Chrome
  9236. ctx.setLineDash([0]);
  9237. ctx.lineDashOffset = 0;
  9238. } else { //Firefox
  9239. ctx.mozDash = [0];
  9240. ctx.mozDashOffset = 0;
  9241. }
  9242. }
  9243. else { // unsupporting smooth lines
  9244. // draw dashed line
  9245. ctx.beginPath();
  9246. ctx.lineCap = 'round';
  9247. if (this.dash.altLength !== undefined) //If an alt dash value has been set add to the array this value
  9248. {
  9249. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  9250. [this.dash.length,this.dash.gap,this.dash.altLength,this.dash.gap]);
  9251. }
  9252. 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
  9253. {
  9254. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  9255. [this.dash.length,this.dash.gap]);
  9256. }
  9257. else //If all else fails draw a line
  9258. {
  9259. ctx.moveTo(this.from.x, this.from.y);
  9260. ctx.lineTo(this.to.x, this.to.y);
  9261. }
  9262. ctx.stroke();
  9263. }
  9264. // draw label
  9265. if (this.label) {
  9266. var point;
  9267. if (this.smooth == true) {
  9268. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9269. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9270. point = {x:midpointX, y:midpointY};
  9271. }
  9272. else {
  9273. point = this._pointOnLine(0.5);
  9274. }
  9275. this._label(ctx, this.label, point.x, point.y);
  9276. }
  9277. };
  9278. /**
  9279. * Get a point on a line
  9280. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  9281. * @return {Object} point
  9282. * @private
  9283. */
  9284. Edge.prototype._pointOnLine = function (percentage) {
  9285. return {
  9286. x: (1 - percentage) * this.from.x + percentage * this.to.x,
  9287. y: (1 - percentage) * this.from.y + percentage * this.to.y
  9288. }
  9289. };
  9290. /**
  9291. * Get a point on a circle
  9292. * @param {Number} x
  9293. * @param {Number} y
  9294. * @param {Number} radius
  9295. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  9296. * @return {Object} point
  9297. * @private
  9298. */
  9299. Edge.prototype._pointOnCircle = function (x, y, radius, percentage) {
  9300. var angle = (percentage - 3/8) * 2 * Math.PI;
  9301. return {
  9302. x: x + radius * Math.cos(angle),
  9303. y: y - radius * Math.sin(angle)
  9304. }
  9305. };
  9306. /**
  9307. * Redraw a edge as a line with an arrow halfway the line
  9308. * Draw this edge in the given canvas
  9309. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9310. * @param {CanvasRenderingContext2D} ctx
  9311. * @private
  9312. */
  9313. Edge.prototype._drawArrowCenter = function(ctx) {
  9314. var point;
  9315. // set style
  9316. if (this.selected == true) {ctx.strokeStyle = this.color.highlight; ctx.fillStyle = this.color.highlight;}
  9317. else {ctx.strokeStyle = this.color.color; ctx.fillStyle = this.color.color;}
  9318. ctx.lineWidth = this._getLineWidth();
  9319. if (this.from != this.to) {
  9320. // draw line
  9321. this._line(ctx);
  9322. var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  9323. var length = (10 + 5 * this.width) * this.arrowScaleFactor;
  9324. // draw an arrow halfway the line
  9325. if (this.smooth == true) {
  9326. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9327. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9328. point = {x:midpointX, y:midpointY};
  9329. }
  9330. else {
  9331. point = this._pointOnLine(0.5);
  9332. }
  9333. ctx.arrow(point.x, point.y, angle, length);
  9334. ctx.fill();
  9335. ctx.stroke();
  9336. // draw label
  9337. if (this.label) {
  9338. this._label(ctx, this.label, point.x, point.y);
  9339. }
  9340. }
  9341. else {
  9342. // draw circle
  9343. var x, y;
  9344. var radius = 0.25 * Math.max(100,this.length);
  9345. var node = this.from;
  9346. if (!node.width) {
  9347. node.resize(ctx);
  9348. }
  9349. if (node.width > node.height) {
  9350. x = node.x + node.width * 0.5;
  9351. y = node.y - radius;
  9352. }
  9353. else {
  9354. x = node.x + radius;
  9355. y = node.y - node.height * 0.5;
  9356. }
  9357. this._circle(ctx, x, y, radius);
  9358. // draw all arrows
  9359. var angle = 0.2 * Math.PI;
  9360. var length = (10 + 5 * this.width) * this.arrowScaleFactor;
  9361. point = this._pointOnCircle(x, y, radius, 0.5);
  9362. ctx.arrow(point.x, point.y, angle, length);
  9363. ctx.fill();
  9364. ctx.stroke();
  9365. // draw label
  9366. if (this.label) {
  9367. point = this._pointOnCircle(x, y, radius, 0.5);
  9368. this._label(ctx, this.label, point.x, point.y);
  9369. }
  9370. }
  9371. };
  9372. /**
  9373. * Redraw a edge as a line with an arrow
  9374. * Draw this edge in the given canvas
  9375. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9376. * @param {CanvasRenderingContext2D} ctx
  9377. * @private
  9378. */
  9379. Edge.prototype._drawArrow = function(ctx) {
  9380. // set style
  9381. if (this.selected == true) {ctx.strokeStyle = this.color.highlight; ctx.fillStyle = this.color.highlight;}
  9382. else {ctx.strokeStyle = this.color.color; ctx.fillStyle = this.color.color;}
  9383. ctx.lineWidth = this._getLineWidth();
  9384. var angle, length;
  9385. //draw a line
  9386. if (this.from != this.to) {
  9387. angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  9388. var dx = (this.to.x - this.from.x);
  9389. var dy = (this.to.y - this.from.y);
  9390. var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  9391. var fromBorderDist = this.from.distanceToBorder(ctx, angle + Math.PI);
  9392. var fromBorderPoint = (edgeSegmentLength - fromBorderDist) / edgeSegmentLength;
  9393. var xFrom = (fromBorderPoint) * this.from.x + (1 - fromBorderPoint) * this.to.x;
  9394. var yFrom = (fromBorderPoint) * this.from.y + (1 - fromBorderPoint) * this.to.y;
  9395. if (this.smooth == true) {
  9396. angle = Math.atan2((this.to.y - this.via.y), (this.to.x - this.via.x));
  9397. dx = (this.to.x - this.via.x);
  9398. dy = (this.to.y - this.via.y);
  9399. edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  9400. }
  9401. var toBorderDist = this.to.distanceToBorder(ctx, angle);
  9402. var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength;
  9403. var xTo,yTo;
  9404. if (this.smooth == true) {
  9405. xTo = (1 - toBorderPoint) * this.via.x + toBorderPoint * this.to.x;
  9406. yTo = (1 - toBorderPoint) * this.via.y + toBorderPoint * this.to.y;
  9407. }
  9408. else {
  9409. xTo = (1 - toBorderPoint) * this.from.x + toBorderPoint * this.to.x;
  9410. yTo = (1 - toBorderPoint) * this.from.y + toBorderPoint * this.to.y;
  9411. }
  9412. ctx.beginPath();
  9413. ctx.moveTo(xFrom,yFrom);
  9414. if (this.smooth == true) {
  9415. ctx.quadraticCurveTo(this.via.x,this.via.y,xTo, yTo);
  9416. }
  9417. else {
  9418. ctx.lineTo(xTo, yTo);
  9419. }
  9420. ctx.stroke();
  9421. // draw arrow at the end of the line
  9422. length = (10 + 5 * this.width) * this.arrowScaleFactor;
  9423. ctx.arrow(xTo, yTo, angle, length);
  9424. ctx.fill();
  9425. ctx.stroke();
  9426. // draw label
  9427. if (this.label) {
  9428. var point;
  9429. if (this.smooth == true) {
  9430. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9431. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9432. point = {x:midpointX, y:midpointY};
  9433. }
  9434. else {
  9435. point = this._pointOnLine(0.5);
  9436. }
  9437. this._label(ctx, this.label, point.x, point.y);
  9438. }
  9439. }
  9440. else {
  9441. // draw circle
  9442. var node = this.from;
  9443. var x, y, arrow;
  9444. var radius = 0.25 * Math.max(100,this.length);
  9445. if (!node.width) {
  9446. node.resize(ctx);
  9447. }
  9448. if (node.width > node.height) {
  9449. x = node.x + node.width * 0.5;
  9450. y = node.y - radius;
  9451. arrow = {
  9452. x: x,
  9453. y: node.y,
  9454. angle: 0.9 * Math.PI
  9455. };
  9456. }
  9457. else {
  9458. x = node.x + radius;
  9459. y = node.y - node.height * 0.5;
  9460. arrow = {
  9461. x: node.x,
  9462. y: y,
  9463. angle: 0.6 * Math.PI
  9464. };
  9465. }
  9466. ctx.beginPath();
  9467. // TODO: similarly, for a line without arrows, draw to the border of the nodes instead of the center
  9468. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  9469. ctx.stroke();
  9470. // draw all arrows
  9471. var length = (10 + 5 * this.width) * this.arrowScaleFactor;
  9472. ctx.arrow(arrow.x, arrow.y, arrow.angle, length);
  9473. ctx.fill();
  9474. ctx.stroke();
  9475. // draw label
  9476. if (this.label) {
  9477. point = this._pointOnCircle(x, y, radius, 0.5);
  9478. this._label(ctx, this.label, point.x, point.y);
  9479. }
  9480. }
  9481. };
  9482. /**
  9483. * Calculate the distance between a point (x3,y3) and a line segment from
  9484. * (x1,y1) to (x2,y2).
  9485. * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
  9486. * @param {number} x1
  9487. * @param {number} y1
  9488. * @param {number} x2
  9489. * @param {number} y2
  9490. * @param {number} x3
  9491. * @param {number} y3
  9492. * @private
  9493. */
  9494. Edge.prototype._getDistanceToEdge = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is the point
  9495. if (this.smooth == true) {
  9496. var minDistance = 1e9;
  9497. var i,t,x,y,dx,dy;
  9498. for (i = 0; i < 10; i++) {
  9499. t = 0.1*i;
  9500. x = Math.pow(1-t,2)*x1 + (2*t*(1 - t))*this.via.x + Math.pow(t,2)*x2;
  9501. y = Math.pow(1-t,2)*y1 + (2*t*(1 - t))*this.via.y + Math.pow(t,2)*y2;
  9502. dx = Math.abs(x3-x);
  9503. dy = Math.abs(y3-y);
  9504. minDistance = Math.min(minDistance,Math.sqrt(dx*dx + dy*dy));
  9505. }
  9506. return minDistance
  9507. }
  9508. else {
  9509. var px = x2-x1,
  9510. py = y2-y1,
  9511. something = px*px + py*py,
  9512. u = ((x3 - x1) * px + (y3 - y1) * py) / something;
  9513. if (u > 1) {
  9514. u = 1;
  9515. }
  9516. else if (u < 0) {
  9517. u = 0;
  9518. }
  9519. var x = x1 + u * px,
  9520. y = y1 + u * py,
  9521. dx = x - x3,
  9522. dy = y - y3;
  9523. //# Note: If the actual distance does not matter,
  9524. //# if you only want to compare what this function
  9525. //# returns to other results of this function, you
  9526. //# can just return the squared distance instead
  9527. //# (i.e. remove the sqrt) to gain a little performance
  9528. return Math.sqrt(dx*dx + dy*dy);
  9529. }
  9530. };
  9531. /**
  9532. * This allows the zoom level of the graph to influence the rendering
  9533. *
  9534. * @param scale
  9535. */
  9536. Edge.prototype.setScale = function(scale) {
  9537. this.graphScaleInv = 1.0/scale;
  9538. };
  9539. Edge.prototype.select = function() {
  9540. this.selected = true;
  9541. };
  9542. Edge.prototype.unselect = function() {
  9543. this.selected = false;
  9544. };
  9545. Edge.prototype.positionBezierNode = function() {
  9546. if (this.via !== null) {
  9547. this.via.x = 0.5 * (this.from.x + this.to.x);
  9548. this.via.y = 0.5 * (this.from.y + this.to.y);
  9549. }
  9550. };
  9551. /**
  9552. * Popup is a class to create a popup window with some text
  9553. * @param {Element} container The container object.
  9554. * @param {Number} [x]
  9555. * @param {Number} [y]
  9556. * @param {String} [text]
  9557. * @param {Object} [style] An object containing borderColor,
  9558. * backgroundColor, etc.
  9559. */
  9560. function Popup(container, x, y, text, style) {
  9561. if (container) {
  9562. this.container = container;
  9563. }
  9564. else {
  9565. this.container = document.body;
  9566. }
  9567. // x, y and text are optional, see if a style object was passed in their place
  9568. if (style === undefined) {
  9569. if (typeof x === "object") {
  9570. style = x;
  9571. x = undefined;
  9572. } else if (typeof text === "object") {
  9573. style = text;
  9574. text = undefined;
  9575. } else {
  9576. // for backwards compatibility, in case clients other than Graph are creating Popup directly
  9577. style = {
  9578. fontColor: 'black',
  9579. fontSize: 14, // px
  9580. fontFace: 'verdana',
  9581. color: {
  9582. border: '#666',
  9583. background: '#FFFFC6'
  9584. }
  9585. }
  9586. }
  9587. }
  9588. this.x = 0;
  9589. this.y = 0;
  9590. this.padding = 5;
  9591. if (x !== undefined && y !== undefined ) {
  9592. this.setPosition(x, y);
  9593. }
  9594. if (text !== undefined) {
  9595. this.setText(text);
  9596. }
  9597. // create the frame
  9598. this.frame = document.createElement("div");
  9599. var styleAttr = this.frame.style;
  9600. styleAttr.position = "absolute";
  9601. styleAttr.visibility = "hidden";
  9602. styleAttr.border = "1px solid " + style.color.border;
  9603. styleAttr.color = style.fontColor;
  9604. styleAttr.fontSize = style.fontSize + "px";
  9605. styleAttr.fontFamily = style.fontFace;
  9606. styleAttr.padding = this.padding + "px";
  9607. styleAttr.backgroundColor = style.color.background;
  9608. styleAttr.borderRadius = "3px";
  9609. styleAttr.MozBorderRadius = "3px";
  9610. styleAttr.WebkitBorderRadius = "3px";
  9611. styleAttr.boxShadow = "3px 3px 10px rgba(128, 128, 128, 0.5)";
  9612. styleAttr.whiteSpace = "nowrap";
  9613. this.container.appendChild(this.frame);
  9614. }
  9615. /**
  9616. * @param {number} x Horizontal position of the popup window
  9617. * @param {number} y Vertical position of the popup window
  9618. */
  9619. Popup.prototype.setPosition = function(x, y) {
  9620. this.x = parseInt(x);
  9621. this.y = parseInt(y);
  9622. };
  9623. /**
  9624. * Set the text for the popup window. This can be HTML code
  9625. * @param {string} text
  9626. */
  9627. Popup.prototype.setText = function(text) {
  9628. this.frame.innerHTML = text;
  9629. };
  9630. /**
  9631. * Show the popup window
  9632. * @param {boolean} show Optional. Show or hide the window
  9633. */
  9634. Popup.prototype.show = function (show) {
  9635. if (show === undefined) {
  9636. show = true;
  9637. }
  9638. if (show) {
  9639. var height = this.frame.clientHeight;
  9640. var width = this.frame.clientWidth;
  9641. var maxHeight = this.frame.parentNode.clientHeight;
  9642. var maxWidth = this.frame.parentNode.clientWidth;
  9643. var top = (this.y - height);
  9644. if (top + height + this.padding > maxHeight) {
  9645. top = maxHeight - height - this.padding;
  9646. }
  9647. if (top < this.padding) {
  9648. top = this.padding;
  9649. }
  9650. var left = this.x;
  9651. if (left + width + this.padding > maxWidth) {
  9652. left = maxWidth - width - this.padding;
  9653. }
  9654. if (left < this.padding) {
  9655. left = this.padding;
  9656. }
  9657. this.frame.style.left = left + "px";
  9658. this.frame.style.top = top + "px";
  9659. this.frame.style.visibility = "visible";
  9660. }
  9661. else {
  9662. this.hide();
  9663. }
  9664. };
  9665. /**
  9666. * Hide the popup window
  9667. */
  9668. Popup.prototype.hide = function () {
  9669. this.frame.style.visibility = "hidden";
  9670. };
  9671. /**
  9672. * @class Groups
  9673. * This class can store groups and properties specific for groups.
  9674. */
  9675. function Groups() {
  9676. this.clear();
  9677. this.defaultIndex = 0;
  9678. }
  9679. /**
  9680. * default constants for group colors
  9681. */
  9682. Groups.DEFAULT = [
  9683. {border: "#2B7CE9", background: "#97C2FC", highlight: {border: "#2B7CE9", background: "#D2E5FF"}}, // blue
  9684. {border: "#FFA500", background: "#FFFF00", highlight: {border: "#FFA500", background: "#FFFFA3"}}, // yellow
  9685. {border: "#FA0A10", background: "#FB7E81", highlight: {border: "#FA0A10", background: "#FFAFB1"}}, // red
  9686. {border: "#41A906", background: "#7BE141", highlight: {border: "#41A906", background: "#A1EC76"}}, // green
  9687. {border: "#E129F0", background: "#EB7DF4", highlight: {border: "#E129F0", background: "#F0B3F5"}}, // magenta
  9688. {border: "#7C29F0", background: "#AD85E4", highlight: {border: "#7C29F0", background: "#D3BDF0"}}, // purple
  9689. {border: "#C37F00", background: "#FFA807", highlight: {border: "#C37F00", background: "#FFCA66"}}, // orange
  9690. {border: "#4220FB", background: "#6E6EFD", highlight: {border: "#4220FB", background: "#9B9BFD"}}, // darkblue
  9691. {border: "#FD5A77", background: "#FFC0CB", highlight: {border: "#FD5A77", background: "#FFD1D9"}}, // pink
  9692. {border: "#4AD63A", background: "#C2FABC", highlight: {border: "#4AD63A", background: "#E6FFE3"}} // mint
  9693. ];
  9694. /**
  9695. * Clear all groups
  9696. */
  9697. Groups.prototype.clear = function () {
  9698. this.groups = {};
  9699. this.groups.length = function()
  9700. {
  9701. var i = 0;
  9702. for ( var p in this ) {
  9703. if (this.hasOwnProperty(p)) {
  9704. i++;
  9705. }
  9706. }
  9707. return i;
  9708. }
  9709. };
  9710. /**
  9711. * get group properties of a groupname. If groupname is not found, a new group
  9712. * is added.
  9713. * @param {*} groupname Can be a number, string, Date, etc.
  9714. * @return {Object} group The created group, containing all group properties
  9715. */
  9716. Groups.prototype.get = function (groupname) {
  9717. var group = this.groups[groupname];
  9718. if (group == undefined) {
  9719. // create new group
  9720. var index = this.defaultIndex % Groups.DEFAULT.length;
  9721. this.defaultIndex++;
  9722. group = {};
  9723. group.color = Groups.DEFAULT[index];
  9724. this.groups[groupname] = group;
  9725. }
  9726. return group;
  9727. };
  9728. /**
  9729. * Add a custom group style
  9730. * @param {String} groupname
  9731. * @param {Object} style An object containing borderColor,
  9732. * backgroundColor, etc.
  9733. * @return {Object} group The created group object
  9734. */
  9735. Groups.prototype.add = function (groupname, style) {
  9736. this.groups[groupname] = style;
  9737. if (style.color) {
  9738. style.color = util.parseColor(style.color);
  9739. }
  9740. return style;
  9741. };
  9742. /**
  9743. * @class Images
  9744. * This class loads images and keeps them stored.
  9745. */
  9746. function Images() {
  9747. this.images = {};
  9748. this.callback = undefined;
  9749. }
  9750. /**
  9751. * Set an onload callback function. This will be called each time an image
  9752. * is loaded
  9753. * @param {function} callback
  9754. */
  9755. Images.prototype.setOnloadCallback = function(callback) {
  9756. this.callback = callback;
  9757. };
  9758. /**
  9759. *
  9760. * @param {string} url Url of the image
  9761. * @return {Image} img The image object
  9762. */
  9763. Images.prototype.load = function(url) {
  9764. var img = this.images[url];
  9765. if (img == undefined) {
  9766. // create the image
  9767. var images = this;
  9768. img = new Image();
  9769. this.images[url] = img;
  9770. img.onload = function() {
  9771. if (images.callback) {
  9772. images.callback(this);
  9773. }
  9774. };
  9775. img.src = url;
  9776. }
  9777. return img;
  9778. };
  9779. /**
  9780. * Created by Alex on 2/6/14.
  9781. */
  9782. var physicsMixin = {
  9783. /**
  9784. * Toggling barnes Hut calculation on and off.
  9785. *
  9786. * @private
  9787. */
  9788. _toggleBarnesHut: function () {
  9789. this.constants.physics.barnesHut.enabled = !this.constants.physics.barnesHut.enabled;
  9790. this._loadSelectedForceSolver();
  9791. this.moving = true;
  9792. this.start();
  9793. },
  9794. /**
  9795. * This loads the node force solver based on the barnes hut or repulsion algorithm
  9796. *
  9797. * @private
  9798. */
  9799. _loadSelectedForceSolver: function () {
  9800. // this overloads the this._calculateNodeForces
  9801. if (this.constants.physics.barnesHut.enabled == true) {
  9802. this._clearMixin(repulsionMixin);
  9803. this._clearMixin(hierarchalRepulsionMixin);
  9804. this.constants.physics.centralGravity = this.constants.physics.barnesHut.centralGravity;
  9805. this.constants.physics.springLength = this.constants.physics.barnesHut.springLength;
  9806. this.constants.physics.springConstant = this.constants.physics.barnesHut.springConstant;
  9807. this.constants.physics.damping = this.constants.physics.barnesHut.damping;
  9808. this._loadMixin(barnesHutMixin);
  9809. }
  9810. else if (this.constants.physics.hierarchicalRepulsion.enabled == true) {
  9811. this._clearMixin(barnesHutMixin);
  9812. this._clearMixin(repulsionMixin);
  9813. this.constants.physics.centralGravity = this.constants.physics.hierarchicalRepulsion.centralGravity;
  9814. this.constants.physics.springLength = this.constants.physics.hierarchicalRepulsion.springLength;
  9815. this.constants.physics.springConstant = this.constants.physics.hierarchicalRepulsion.springConstant;
  9816. this.constants.physics.damping = this.constants.physics.hierarchicalRepulsion.damping;
  9817. this._loadMixin(hierarchalRepulsionMixin);
  9818. }
  9819. else {
  9820. this._clearMixin(barnesHutMixin);
  9821. this._clearMixin(hierarchalRepulsionMixin);
  9822. this.barnesHutTree = undefined;
  9823. this.constants.physics.centralGravity = this.constants.physics.repulsion.centralGravity;
  9824. this.constants.physics.springLength = this.constants.physics.repulsion.springLength;
  9825. this.constants.physics.springConstant = this.constants.physics.repulsion.springConstant;
  9826. this.constants.physics.damping = this.constants.physics.repulsion.damping;
  9827. this._loadMixin(repulsionMixin);
  9828. }
  9829. },
  9830. /**
  9831. * Before calculating the forces, we check if we need to cluster to keep up performance and we check
  9832. * if there is more than one node. If it is just one node, we dont calculate anything.
  9833. *
  9834. * @private
  9835. */
  9836. _initializeForceCalculation: function () {
  9837. // stop calculation if there is only one node
  9838. if (this.nodeIndices.length == 1) {
  9839. this.nodes[this.nodeIndices[0]]._setForce(0, 0);
  9840. }
  9841. else {
  9842. // if there are too many nodes on screen, we cluster without repositioning
  9843. if (this.nodeIndices.length > this.constants.clustering.clusterThreshold && this.constants.clustering.enabled == true) {
  9844. this.clusterToFit(this.constants.clustering.reduceToNodes, false);
  9845. }
  9846. // we now start the force calculation
  9847. this._calculateForces();
  9848. }
  9849. },
  9850. /**
  9851. * Calculate the external forces acting on the nodes
  9852. * Forces are caused by: edges, repulsing forces between nodes, gravity
  9853. * @private
  9854. */
  9855. _calculateForces: function () {
  9856. // Gravity is required to keep separated groups from floating off
  9857. // the forces are reset to zero in this loop by using _setForce instead
  9858. // of _addForce
  9859. this._calculateGravitationalForces();
  9860. this._calculateNodeForces();
  9861. if (this.constants.smoothCurves == true) {
  9862. this._calculateSpringForcesWithSupport();
  9863. }
  9864. else {
  9865. this._calculateSpringForces();
  9866. }
  9867. },
  9868. /**
  9869. * Smooth curves are created by adding invisible nodes in the center of the edges. These nodes are also
  9870. * handled in the calculateForces function. We then use a quadratic curve with the center node as control.
  9871. * This function joins the datanodes and invisible (called support) nodes into one object.
  9872. * We do this so we do not contaminate this.nodes with the support nodes.
  9873. *
  9874. * @private
  9875. */
  9876. _updateCalculationNodes: function () {
  9877. if (this.constants.smoothCurves == true) {
  9878. this.calculationNodes = {};
  9879. this.calculationNodeIndices = [];
  9880. for (var nodeId in this.nodes) {
  9881. if (this.nodes.hasOwnProperty(nodeId)) {
  9882. this.calculationNodes[nodeId] = this.nodes[nodeId];
  9883. }
  9884. }
  9885. var supportNodes = this.sectors['support']['nodes'];
  9886. for (var supportNodeId in supportNodes) {
  9887. if (supportNodes.hasOwnProperty(supportNodeId)) {
  9888. if (this.edges.hasOwnProperty(supportNodes[supportNodeId].parentEdgeId)) {
  9889. this.calculationNodes[supportNodeId] = supportNodes[supportNodeId];
  9890. }
  9891. else {
  9892. supportNodes[supportNodeId]._setForce(0, 0);
  9893. }
  9894. }
  9895. }
  9896. for (var idx in this.calculationNodes) {
  9897. if (this.calculationNodes.hasOwnProperty(idx)) {
  9898. this.calculationNodeIndices.push(idx);
  9899. }
  9900. }
  9901. }
  9902. else {
  9903. this.calculationNodes = this.nodes;
  9904. this.calculationNodeIndices = this.nodeIndices;
  9905. }
  9906. },
  9907. /**
  9908. * this function applies the central gravity effect to keep groups from floating off
  9909. *
  9910. * @private
  9911. */
  9912. _calculateGravitationalForces: function () {
  9913. var dx, dy, distance, node, i;
  9914. var nodes = this.calculationNodes;
  9915. var gravity = this.constants.physics.centralGravity;
  9916. var gravityForce = 0;
  9917. for (i = 0; i < this.calculationNodeIndices.length; i++) {
  9918. node = nodes[this.calculationNodeIndices[i]];
  9919. node.damping = this.constants.physics.damping; // possibly add function to alter damping properties of clusters.
  9920. // gravity does not apply when we are in a pocket sector
  9921. if (this._sector() == "default" && gravity != 0) {
  9922. dx = -node.x;
  9923. dy = -node.y;
  9924. distance = Math.sqrt(dx * dx + dy * dy);
  9925. gravityForce = (distance == 0) ? 0 : (gravity / distance);
  9926. node.fx = dx * gravityForce;
  9927. node.fy = dy * gravityForce;
  9928. }
  9929. else {
  9930. node.fx = 0;
  9931. node.fy = 0;
  9932. }
  9933. }
  9934. },
  9935. /**
  9936. * this function calculates the effects of the springs in the case of unsmooth curves.
  9937. *
  9938. * @private
  9939. */
  9940. _calculateSpringForces: function () {
  9941. var edgeLength, edge, edgeId;
  9942. var dx, dy, fx, fy, springForce, length;
  9943. var edges = this.edges;
  9944. // forces caused by the edges, modelled as springs
  9945. for (edgeId in edges) {
  9946. if (edges.hasOwnProperty(edgeId)) {
  9947. edge = edges[edgeId];
  9948. if (edge.connected) {
  9949. // only calculate forces if nodes are in the same sector
  9950. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  9951. edgeLength = edge.customLength ? edge.length : this.constants.physics.springLength;
  9952. // this implies that the edges between big clusters are longer
  9953. edgeLength += (edge.to.clusterSize + edge.from.clusterSize - 2) * this.constants.clustering.edgeGrowth;
  9954. dx = (edge.from.x - edge.to.x);
  9955. dy = (edge.from.y - edge.to.y);
  9956. length = Math.sqrt(dx * dx + dy * dy);
  9957. if (length == 0) {
  9958. length = 0.01;
  9959. }
  9960. springForce = this.constants.physics.springConstant * (edgeLength - length) / length;
  9961. fx = dx * springForce;
  9962. fy = dy * springForce;
  9963. edge.from.fx += fx;
  9964. edge.from.fy += fy;
  9965. edge.to.fx -= fx;
  9966. edge.to.fy -= fy;
  9967. }
  9968. }
  9969. }
  9970. }
  9971. },
  9972. /**
  9973. * This function calculates the springforces on the nodes, accounting for the support nodes.
  9974. *
  9975. * @private
  9976. */
  9977. _calculateSpringForcesWithSupport: function () {
  9978. var edgeLength, edge, edgeId, combinedClusterSize;
  9979. var edges = this.edges;
  9980. // forces caused by the edges, modelled as springs
  9981. for (edgeId in edges) {
  9982. if (edges.hasOwnProperty(edgeId)) {
  9983. edge = edges[edgeId];
  9984. if (edge.connected) {
  9985. // only calculate forces if nodes are in the same sector
  9986. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  9987. if (edge.via != null) {
  9988. var node1 = edge.to;
  9989. var node2 = edge.via;
  9990. var node3 = edge.from;
  9991. edgeLength = edge.customLength ? edge.length : this.constants.physics.springLength;
  9992. combinedClusterSize = node1.clusterSize + node3.clusterSize - 2;
  9993. // this implies that the edges between big clusters are longer
  9994. edgeLength += combinedClusterSize * this.constants.clustering.edgeGrowth;
  9995. this._calculateSpringForce(node1, node2, 0.5 * edgeLength);
  9996. this._calculateSpringForce(node2, node3, 0.5 * edgeLength);
  9997. }
  9998. }
  9999. }
  10000. }
  10001. }
  10002. },
  10003. /**
  10004. * This is the code actually performing the calculation for the function above. It is split out to avoid repetition.
  10005. *
  10006. * @param node1
  10007. * @param node2
  10008. * @param edgeLength
  10009. * @private
  10010. */
  10011. _calculateSpringForce: function (node1, node2, edgeLength) {
  10012. var dx, dy, fx, fy, springForce, length;
  10013. dx = (node1.x - node2.x);
  10014. dy = (node1.y - node2.y);
  10015. length = Math.sqrt(dx * dx + dy * dy);
  10016. if (length == 0) {
  10017. length = 0.01;
  10018. }
  10019. springForce = this.constants.physics.springConstant * (edgeLength - length) / length;
  10020. fx = dx * springForce;
  10021. fy = dy * springForce;
  10022. node1.fx += fx;
  10023. node1.fy += fy;
  10024. node2.fx -= fx;
  10025. node2.fy -= fy;
  10026. },
  10027. /**
  10028. * Load the HTML for the physics config and bind it
  10029. * @private
  10030. */
  10031. _loadPhysicsConfiguration: function () {
  10032. if (this.physicsConfiguration === undefined) {
  10033. this.backupConstants = {};
  10034. util.copyObject(this.constants, this.backupConstants);
  10035. var hierarchicalLayoutDirections = ["LR", "RL", "UD", "DU"];
  10036. this.physicsConfiguration = document.createElement('div');
  10037. this.physicsConfiguration.className = "PhysicsConfiguration";
  10038. this.physicsConfiguration.innerHTML = '' +
  10039. '<table><tr><td><b>Simulation Mode:</b></td></tr>' +
  10040. '<tr>' +
  10041. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod1" value="BH" checked="checked">Barnes Hut</td>' +
  10042. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod2" value="R">Repulsion</td>' +
  10043. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod3" value="H">Hierarchical</td>' +
  10044. '</tr>' +
  10045. '</table>' +
  10046. '<table id="graph_BH_table" style="display:none">' +
  10047. '<tr><td><b>Barnes Hut</b></td></tr>' +
  10048. '<tr>' +
  10049. '<td width="150px">gravitationalConstant</td><td>0</td><td><input type="range" min="500" max="20000" value="' + (-1 * this.constants.physics.barnesHut.gravitationalConstant) + '" step="25" style="width:300px" id="graph_BH_gc"></td><td width="50px">-20000</td><td><input value="' + (-1 * this.constants.physics.barnesHut.gravitationalConstant) + '" id="graph_BH_gc_value" style="width:60px"></td>' +
  10050. '</tr>' +
  10051. '<tr>' +
  10052. '<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>' +
  10053. '</tr>' +
  10054. '<tr>' +
  10055. '<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>' +
  10056. '</tr>' +
  10057. '<tr>' +
  10058. '<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>' +
  10059. '</tr>' +
  10060. '<tr>' +
  10061. '<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>' +
  10062. '</tr>' +
  10063. '</table>' +
  10064. '<table id="graph_R_table" style="display:none">' +
  10065. '<tr><td><b>Repulsion</b></td></tr>' +
  10066. '<tr>' +
  10067. '<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>' +
  10068. '</tr>' +
  10069. '<tr>' +
  10070. '<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>' +
  10071. '</tr>' +
  10072. '<tr>' +
  10073. '<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>' +
  10074. '</tr>' +
  10075. '<tr>' +
  10076. '<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>' +
  10077. '</tr>' +
  10078. '<tr>' +
  10079. '<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>' +
  10080. '</tr>' +
  10081. '</table>' +
  10082. '<table id="graph_H_table" style="display:none">' +
  10083. '<tr><td width="150"><b>Hierarchical</b></td></tr>' +
  10084. '<tr>' +
  10085. '<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>' +
  10086. '</tr>' +
  10087. '<tr>' +
  10088. '<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>' +
  10089. '</tr>' +
  10090. '<tr>' +
  10091. '<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>' +
  10092. '</tr>' +
  10093. '<tr>' +
  10094. '<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>' +
  10095. '</tr>' +
  10096. '<tr>' +
  10097. '<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>' +
  10098. '</tr>' +
  10099. '<tr>' +
  10100. '<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>' +
  10101. '</tr>' +
  10102. '<tr>' +
  10103. '<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>' +
  10104. '</tr>' +
  10105. '<tr>' +
  10106. '<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>' +
  10107. '</tr>' +
  10108. '</table>' +
  10109. '<table><tr><td><b>Options:</b></td></tr>' +
  10110. '<tr>' +
  10111. '<td width="180px"><input type="button" id="graph_toggleSmooth" value="Toggle smoothCurves" style="width:150px"></td>' +
  10112. '<td width="180px"><input type="button" id="graph_repositionNodes" value="Reinitialize" style="width:150px"></td>' +
  10113. '<td width="180px"><input type="button" id="graph_generateOptions" value="Generate Options" style="width:150px"></td>' +
  10114. '</tr>' +
  10115. '</table>'
  10116. this.containerElement.parentElement.insertBefore(this.physicsConfiguration, this.containerElement);
  10117. this.optionsDiv = document.createElement("div");
  10118. this.optionsDiv.style.fontSize = "14px";
  10119. this.optionsDiv.style.fontFamily = "verdana";
  10120. this.containerElement.parentElement.insertBefore(this.optionsDiv, this.containerElement);
  10121. var rangeElement;
  10122. rangeElement = document.getElementById('graph_BH_gc');
  10123. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_gc', -1, "physics_barnesHut_gravitationalConstant");
  10124. rangeElement = document.getElementById('graph_BH_cg');
  10125. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_cg', 1, "physics_centralGravity");
  10126. rangeElement = document.getElementById('graph_BH_sc');
  10127. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_sc', 1, "physics_springConstant");
  10128. rangeElement = document.getElementById('graph_BH_sl');
  10129. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_sl', 1, "physics_springLength");
  10130. rangeElement = document.getElementById('graph_BH_damp');
  10131. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_damp', 1, "physics_damping");
  10132. rangeElement = document.getElementById('graph_R_nd');
  10133. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_nd', 1, "physics_repulsion_nodeDistance");
  10134. rangeElement = document.getElementById('graph_R_cg');
  10135. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_cg', 1, "physics_centralGravity");
  10136. rangeElement = document.getElementById('graph_R_sc');
  10137. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_sc', 1, "physics_springConstant");
  10138. rangeElement = document.getElementById('graph_R_sl');
  10139. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_sl', 1, "physics_springLength");
  10140. rangeElement = document.getElementById('graph_R_damp');
  10141. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_damp', 1, "physics_damping");
  10142. rangeElement = document.getElementById('graph_H_nd');
  10143. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_nd', 1, "physics_hierarchicalRepulsion_nodeDistance");
  10144. rangeElement = document.getElementById('graph_H_cg');
  10145. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_cg', 1, "physics_centralGravity");
  10146. rangeElement = document.getElementById('graph_H_sc');
  10147. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_sc', 1, "physics_springConstant");
  10148. rangeElement = document.getElementById('graph_H_sl');
  10149. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_sl', 1, "physics_springLength");
  10150. rangeElement = document.getElementById('graph_H_damp');
  10151. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_damp', 1, "physics_damping");
  10152. rangeElement = document.getElementById('graph_H_direction');
  10153. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_direction', hierarchicalLayoutDirections, "hierarchicalLayout_direction");
  10154. rangeElement = document.getElementById('graph_H_levsep');
  10155. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_levsep', 1, "hierarchicalLayout_levelSeparation");
  10156. rangeElement = document.getElementById('graph_H_nspac');
  10157. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_nspac', 1, "hierarchicalLayout_nodeSpacing");
  10158. var radioButton1 = document.getElementById("graph_physicsMethod1");
  10159. var radioButton2 = document.getElementById("graph_physicsMethod2");
  10160. var radioButton3 = document.getElementById("graph_physicsMethod3");
  10161. radioButton2.checked = true;
  10162. if (this.constants.physics.barnesHut.enabled) {
  10163. radioButton1.checked = true;
  10164. }
  10165. if (this.constants.hierarchicalLayout.enabled) {
  10166. radioButton3.checked = true;
  10167. }
  10168. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  10169. var graph_repositionNodes = document.getElementById("graph_repositionNodes");
  10170. var graph_generateOptions = document.getElementById("graph_generateOptions");
  10171. graph_toggleSmooth.onclick = graphToggleSmoothCurves.bind(this);
  10172. graph_repositionNodes.onclick = graphRepositionNodes.bind(this);
  10173. graph_generateOptions.onclick = graphGenerateOptions.bind(this);
  10174. if (this.constants.smoothCurves == true) {
  10175. graph_toggleSmooth.style.background = "#A4FF56";
  10176. }
  10177. else {
  10178. graph_toggleSmooth.style.background = "#FF8532";
  10179. }
  10180. switchConfigurations.apply(this);
  10181. radioButton1.onchange = switchConfigurations.bind(this);
  10182. radioButton2.onchange = switchConfigurations.bind(this);
  10183. radioButton3.onchange = switchConfigurations.bind(this);
  10184. }
  10185. },
  10186. /**
  10187. * This overwrites the this.constants.
  10188. *
  10189. * @param constantsVariableName
  10190. * @param value
  10191. * @private
  10192. */
  10193. _overWriteGraphConstants: function (constantsVariableName, value) {
  10194. var nameArray = constantsVariableName.split("_");
  10195. if (nameArray.length == 1) {
  10196. this.constants[nameArray[0]] = value;
  10197. }
  10198. else if (nameArray.length == 2) {
  10199. this.constants[nameArray[0]][nameArray[1]] = value;
  10200. }
  10201. else if (nameArray.length == 3) {
  10202. this.constants[nameArray[0]][nameArray[1]][nameArray[2]] = value;
  10203. }
  10204. }
  10205. };
  10206. /**
  10207. * this function is bound to the toggle smooth curves button. That is also why it is not in the prototype.
  10208. */
  10209. function graphToggleSmoothCurves () {
  10210. this.constants.smoothCurves = !this.constants.smoothCurves;
  10211. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  10212. if (this.constants.smoothCurves == true) {graph_toggleSmooth.style.background = "#A4FF56";}
  10213. else {graph_toggleSmooth.style.background = "#FF8532";}
  10214. this._configureSmoothCurves(false);
  10215. };
  10216. /**
  10217. * this function is used to scramble the nodes
  10218. *
  10219. */
  10220. function graphRepositionNodes () {
  10221. for (var nodeId in this.calculationNodes) {
  10222. if (this.calculationNodes.hasOwnProperty(nodeId)) {
  10223. this.calculationNodes[nodeId].vx = 0; this.calculationNodes[nodeId].vy = 0;
  10224. this.calculationNodes[nodeId].fx = 0; this.calculationNodes[nodeId].fy = 0;
  10225. }
  10226. }
  10227. if (this.constants.hierarchicalLayout.enabled == true) {
  10228. this._setupHierarchicalLayout();
  10229. }
  10230. else {
  10231. this.repositionNodes();
  10232. }
  10233. this.moving = true;
  10234. this.start();
  10235. };
  10236. /**
  10237. * this is used to generate an options file from the playing with physics system.
  10238. */
  10239. function graphGenerateOptions () {
  10240. var options = "No options are required, default values used.";
  10241. var optionsSpecific = [];
  10242. var radioButton1 = document.getElementById("graph_physicsMethod1");
  10243. var radioButton2 = document.getElementById("graph_physicsMethod2");
  10244. if (radioButton1.checked == true) {
  10245. if (this.constants.physics.barnesHut.gravitationalConstant != this.backupConstants.physics.barnesHut.gravitationalConstant) {optionsSpecific.push("gravitationalConstant: " + this.constants.physics.barnesHut.gravitationalConstant);}
  10246. if (this.constants.physics.centralGravity != this.backupConstants.physics.barnesHut.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  10247. if (this.constants.physics.springLength != this.backupConstants.physics.barnesHut.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  10248. if (this.constants.physics.springConstant != this.backupConstants.physics.barnesHut.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  10249. if (this.constants.physics.damping != this.backupConstants.physics.barnesHut.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  10250. if (optionsSpecific.length != 0) {
  10251. options = "var options = {";
  10252. options += "physics: {barnesHut: {";
  10253. for (var i = 0; i < optionsSpecific.length; i++) {
  10254. options += optionsSpecific[i];
  10255. if (i < optionsSpecific.length - 1) {
  10256. options += ", "
  10257. }
  10258. }
  10259. options += '}}'
  10260. }
  10261. if (this.constants.smoothCurves != this.backupConstants.smoothCurves) {
  10262. if (optionsSpecific.length == 0) {options = "var options = {";}
  10263. else {options += ", "}
  10264. options += "smoothCurves: " + this.constants.smoothCurves;
  10265. }
  10266. if (options != "No options are required, default values used.") {
  10267. options += '};'
  10268. }
  10269. }
  10270. else if (radioButton2.checked == true) {
  10271. options = "var options = {";
  10272. options += "physics: {barnesHut: {enabled: false}";
  10273. if (this.constants.physics.repulsion.nodeDistance != this.backupConstants.physics.repulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.repulsion.nodeDistance);}
  10274. if (this.constants.physics.centralGravity != this.backupConstants.physics.repulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  10275. if (this.constants.physics.springLength != this.backupConstants.physics.repulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  10276. if (this.constants.physics.springConstant != this.backupConstants.physics.repulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  10277. if (this.constants.physics.damping != this.backupConstants.physics.repulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  10278. if (optionsSpecific.length != 0) {
  10279. options += ", repulsion: {";
  10280. for (var i = 0; i < optionsSpecific.length; i++) {
  10281. options += optionsSpecific[i];
  10282. if (i < optionsSpecific.length - 1) {
  10283. options += ", "
  10284. }
  10285. }
  10286. options += '}}'
  10287. }
  10288. if (optionsSpecific.length == 0) {options += "}"}
  10289. if (this.constants.smoothCurves != this.backupConstants.smoothCurves) {
  10290. options += ", smoothCurves: " + this.constants.smoothCurves;
  10291. }
  10292. options += '};'
  10293. }
  10294. else {
  10295. options = "var options = {";
  10296. if (this.constants.physics.hierarchicalRepulsion.nodeDistance != this.backupConstants.physics.hierarchicalRepulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.hierarchicalRepulsion.nodeDistance);}
  10297. if (this.constants.physics.centralGravity != this.backupConstants.physics.hierarchicalRepulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  10298. if (this.constants.physics.springLength != this.backupConstants.physics.hierarchicalRepulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  10299. if (this.constants.physics.springConstant != this.backupConstants.physics.hierarchicalRepulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  10300. if (this.constants.physics.damping != this.backupConstants.physics.hierarchicalRepulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  10301. if (optionsSpecific.length != 0) {
  10302. options += "physics: {hierarchicalRepulsion: {";
  10303. for (var i = 0; i < optionsSpecific.length; i++) {
  10304. options += optionsSpecific[i];
  10305. if (i < optionsSpecific.length - 1) {
  10306. options += ", ";
  10307. }
  10308. }
  10309. options += '}},';
  10310. }
  10311. options += 'hierarchicalLayout: {';
  10312. optionsSpecific = [];
  10313. if (this.constants.hierarchicalLayout.direction != this.backupConstants.hierarchicalLayout.direction) {optionsSpecific.push("direction: " + this.constants.hierarchicalLayout.direction);}
  10314. if (Math.abs(this.constants.hierarchicalLayout.levelSeparation) != this.backupConstants.hierarchicalLayout.levelSeparation) {optionsSpecific.push("levelSeparation: " + this.constants.hierarchicalLayout.levelSeparation);}
  10315. if (this.constants.hierarchicalLayout.nodeSpacing != this.backupConstants.hierarchicalLayout.nodeSpacing) {optionsSpecific.push("nodeSpacing: " + this.constants.hierarchicalLayout.nodeSpacing);}
  10316. if (optionsSpecific.length != 0) {
  10317. for (var i = 0; i < optionsSpecific.length; i++) {
  10318. options += optionsSpecific[i];
  10319. if (i < optionsSpecific.length - 1) {
  10320. options += ", "
  10321. }
  10322. }
  10323. options += '}'
  10324. }
  10325. else {
  10326. options += "enabled:true}";
  10327. }
  10328. options += '};'
  10329. }
  10330. this.optionsDiv.innerHTML = options;
  10331. };
  10332. /**
  10333. * this is used to switch between barnesHut, repulsion and hierarchical.
  10334. *
  10335. */
  10336. function switchConfigurations () {
  10337. var ids = ["graph_BH_table", "graph_R_table", "graph_H_table"];
  10338. var radioButton = document.querySelector('input[name="graph_physicsMethod"]:checked').value;
  10339. var tableId = "graph_" + radioButton + "_table";
  10340. var table = document.getElementById(tableId);
  10341. table.style.display = "block";
  10342. for (var i = 0; i < ids.length; i++) {
  10343. if (ids[i] != tableId) {
  10344. table = document.getElementById(ids[i]);
  10345. table.style.display = "none";
  10346. }
  10347. }
  10348. this._restoreNodes();
  10349. if (radioButton == "R") {
  10350. this.constants.hierarchicalLayout.enabled = false;
  10351. this.constants.physics.hierarchicalRepulsion.enabled = false;
  10352. this.constants.physics.barnesHut.enabled = false;
  10353. }
  10354. else if (radioButton == "H") {
  10355. if (this.constants.hierarchicalLayout.enabled == false) {
  10356. this.constants.hierarchicalLayout.enabled = true;
  10357. this.constants.physics.hierarchicalRepulsion.enabled = true;
  10358. this.constants.physics.barnesHut.enabled = false;
  10359. this._setupHierarchicalLayout();
  10360. }
  10361. }
  10362. else {
  10363. this.constants.hierarchicalLayout.enabled = false;
  10364. this.constants.physics.hierarchicalRepulsion.enabled = false;
  10365. this.constants.physics.barnesHut.enabled = true;
  10366. }
  10367. this._loadSelectedForceSolver();
  10368. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  10369. if (this.constants.smoothCurves == true) {graph_toggleSmooth.style.background = "#A4FF56";}
  10370. else {graph_toggleSmooth.style.background = "#FF8532";}
  10371. this.moving = true;
  10372. this.start();
  10373. }
  10374. /**
  10375. * this generates the ranges depending on the iniital values.
  10376. *
  10377. * @param id
  10378. * @param map
  10379. * @param constantsVariableName
  10380. */
  10381. function showValueOfRange (id,map,constantsVariableName) {
  10382. var valueId = id + "_value";
  10383. var rangeValue = document.getElementById(id).value;
  10384. if (map instanceof Array) {
  10385. document.getElementById(valueId).value = map[parseInt(rangeValue)];
  10386. this._overWriteGraphConstants(constantsVariableName,map[parseInt(rangeValue)]);
  10387. }
  10388. else {
  10389. document.getElementById(valueId).value = parseInt(map) * parseFloat(rangeValue);
  10390. this._overWriteGraphConstants(constantsVariableName, parseInt(map) * parseFloat(rangeValue));
  10391. }
  10392. if (constantsVariableName == "hierarchicalLayout_direction" ||
  10393. constantsVariableName == "hierarchicalLayout_levelSeparation" ||
  10394. constantsVariableName == "hierarchicalLayout_nodeSpacing") {
  10395. this._setupHierarchicalLayout();
  10396. }
  10397. this.moving = true;
  10398. this.start();
  10399. };
  10400. /**
  10401. * Created by Alex on 2/10/14.
  10402. */
  10403. var hierarchalRepulsionMixin = {
  10404. /**
  10405. * Calculate the forces the nodes apply on eachother based on a repulsion field.
  10406. * This field is linearly approximated.
  10407. *
  10408. * @private
  10409. */
  10410. _calculateNodeForces: function () {
  10411. var dx, dy, distance, fx, fy, combinedClusterSize,
  10412. repulsingForce, node1, node2, i, j;
  10413. var nodes = this.calculationNodes;
  10414. var nodeIndices = this.calculationNodeIndices;
  10415. // approximation constants
  10416. var b = 5;
  10417. var a_base = 0.5 * -b;
  10418. // repulsing forces between nodes
  10419. var nodeDistance = this.constants.physics.hierarchicalRepulsion.nodeDistance;
  10420. var minimumDistance = nodeDistance;
  10421. // we loop from i over all but the last entree in the array
  10422. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  10423. for (i = 0; i < nodeIndices.length - 1; i++) {
  10424. node1 = nodes[nodeIndices[i]];
  10425. for (j = i + 1; j < nodeIndices.length; j++) {
  10426. node2 = nodes[nodeIndices[j]];
  10427. dx = node2.x - node1.x;
  10428. dy = node2.y - node1.y;
  10429. distance = Math.sqrt(dx * dx + dy * dy);
  10430. var a = a_base / minimumDistance;
  10431. if (distance < 2 * minimumDistance) {
  10432. repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness))
  10433. // normalize force with
  10434. if (distance == 0) {
  10435. distance = 0.01;
  10436. }
  10437. else {
  10438. repulsingForce = repulsingForce / distance;
  10439. }
  10440. fx = dx * repulsingForce;
  10441. fy = dy * repulsingForce;
  10442. node1.fx -= fx;
  10443. node1.fy -= fy;
  10444. node2.fx += fx;
  10445. node2.fy += fy;
  10446. }
  10447. }
  10448. }
  10449. }
  10450. };
  10451. /**
  10452. * Created by Alex on 2/10/14.
  10453. */
  10454. var barnesHutMixin = {
  10455. /**
  10456. * This function calculates the forces the nodes apply on eachother based on a gravitational model.
  10457. * The Barnes Hut method is used to speed up this N-body simulation.
  10458. *
  10459. * @private
  10460. */
  10461. _calculateNodeForces : function() {
  10462. if (this.constants.physics.barnesHut.gravitationalConstant != 0) {
  10463. var node;
  10464. var nodes = this.calculationNodes;
  10465. var nodeIndices = this.calculationNodeIndices;
  10466. var nodeCount = nodeIndices.length;
  10467. this._formBarnesHutTree(nodes,nodeIndices);
  10468. var barnesHutTree = this.barnesHutTree;
  10469. // place the nodes one by one recursively
  10470. for (var i = 0; i < nodeCount; i++) {
  10471. node = nodes[nodeIndices[i]];
  10472. // starting with root is irrelevant, it never passes the BarnesHut condition
  10473. this._getForceContribution(barnesHutTree.root.children.NW,node);
  10474. this._getForceContribution(barnesHutTree.root.children.NE,node);
  10475. this._getForceContribution(barnesHutTree.root.children.SW,node);
  10476. this._getForceContribution(barnesHutTree.root.children.SE,node);
  10477. }
  10478. }
  10479. },
  10480. /**
  10481. * This function traverses the barnesHutTree. It checks when it can approximate distant nodes with their center of mass.
  10482. * If a region contains a single node, we check if it is not itself, then we apply the force.
  10483. *
  10484. * @param parentBranch
  10485. * @param node
  10486. * @private
  10487. */
  10488. _getForceContribution : function(parentBranch,node) {
  10489. // we get no force contribution from an empty region
  10490. if (parentBranch.childrenCount > 0) {
  10491. var dx,dy,distance;
  10492. // get the distance from the center of mass to the node.
  10493. dx = parentBranch.centerOfMass.x - node.x;
  10494. dy = parentBranch.centerOfMass.y - node.y;
  10495. distance = Math.sqrt(dx * dx + dy * dy);
  10496. // BarnesHut condition
  10497. // original condition : s/d < theta = passed === d/s > 1/theta = passed
  10498. // calcSize = 1/s --> d * 1/s > 1/theta = passed
  10499. if (distance * parentBranch.calcSize > this.constants.physics.barnesHut.theta) {
  10500. // duplicate code to reduce function calls to speed up program
  10501. if (distance == 0) {
  10502. distance = 0.1*Math.random();
  10503. dx = distance;
  10504. }
  10505. var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.mass / (distance * distance * distance);
  10506. var fx = dx * gravityForce;
  10507. var fy = dy * gravityForce;
  10508. node.fx += fx;
  10509. node.fy += fy;
  10510. }
  10511. else {
  10512. // Did not pass the condition, go into children if available
  10513. if (parentBranch.childrenCount == 4) {
  10514. this._getForceContribution(parentBranch.children.NW,node);
  10515. this._getForceContribution(parentBranch.children.NE,node);
  10516. this._getForceContribution(parentBranch.children.SW,node);
  10517. this._getForceContribution(parentBranch.children.SE,node);
  10518. }
  10519. else { // parentBranch must have only one node, if it was empty we wouldnt be here
  10520. if (parentBranch.children.data.id != node.id) { // if it is not self
  10521. // duplicate code to reduce function calls to speed up program
  10522. if (distance == 0) {
  10523. distance = 0.5*Math.random();
  10524. dx = distance;
  10525. }
  10526. var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.mass / (distance * distance * distance);
  10527. var fx = dx * gravityForce;
  10528. var fy = dy * gravityForce;
  10529. node.fx += fx;
  10530. node.fy += fy;
  10531. }
  10532. }
  10533. }
  10534. }
  10535. },
  10536. /**
  10537. * This function constructs the barnesHut tree recursively. It creates the root, splits it and starts placing the nodes.
  10538. *
  10539. * @param nodes
  10540. * @param nodeIndices
  10541. * @private
  10542. */
  10543. _formBarnesHutTree : function(nodes,nodeIndices) {
  10544. var node;
  10545. var nodeCount = nodeIndices.length;
  10546. var minX = Number.MAX_VALUE,
  10547. minY = Number.MAX_VALUE,
  10548. maxX =-Number.MAX_VALUE,
  10549. maxY =-Number.MAX_VALUE;
  10550. // get the range of the nodes
  10551. for (var i = 0; i < nodeCount; i++) {
  10552. var x = nodes[nodeIndices[i]].x;
  10553. var y = nodes[nodeIndices[i]].y;
  10554. if (x < minX) { minX = x; }
  10555. if (x > maxX) { maxX = x; }
  10556. if (y < minY) { minY = y; }
  10557. if (y > maxY) { maxY = y; }
  10558. }
  10559. // make the range a square
  10560. var sizeDiff = Math.abs(maxX - minX) - Math.abs(maxY - minY); // difference between X and Y
  10561. if (sizeDiff > 0) {minY -= 0.5 * sizeDiff; maxY += 0.5 * sizeDiff;} // xSize > ySize
  10562. else {minX += 0.5 * sizeDiff; maxX -= 0.5 * sizeDiff;} // xSize < ySize
  10563. var minimumTreeSize = 1e-5;
  10564. var rootSize = Math.max(minimumTreeSize,Math.abs(maxX - minX));
  10565. var halfRootSize = 0.5 * rootSize;
  10566. var centerX = 0.5 * (minX + maxX), centerY = 0.5 * (minY + maxY);
  10567. // construct the barnesHutTree
  10568. var barnesHutTree = {root:{
  10569. centerOfMass:{x:0,y:0}, // Center of Mass
  10570. mass:0,
  10571. range: {minX:centerX-halfRootSize,maxX:centerX+halfRootSize,
  10572. minY:centerY-halfRootSize,maxY:centerY+halfRootSize},
  10573. size: rootSize,
  10574. calcSize: 1 / rootSize,
  10575. children: {data:null},
  10576. maxWidth: 0,
  10577. level: 0,
  10578. childrenCount: 4
  10579. }};
  10580. this._splitBranch(barnesHutTree.root);
  10581. // place the nodes one by one recursively
  10582. for (i = 0; i < nodeCount; i++) {
  10583. node = nodes[nodeIndices[i]];
  10584. this._placeInTree(barnesHutTree.root,node);
  10585. }
  10586. // make global
  10587. this.barnesHutTree = barnesHutTree
  10588. },
  10589. /**
  10590. * this updates the mass of a branch. this is increased by adding a node.
  10591. *
  10592. * @param parentBranch
  10593. * @param node
  10594. * @private
  10595. */
  10596. _updateBranchMass : function(parentBranch, node) {
  10597. var totalMass = parentBranch.mass + node.mass;
  10598. var totalMassInv = 1/totalMass;
  10599. parentBranch.centerOfMass.x = parentBranch.centerOfMass.x * parentBranch.mass + node.x * node.mass;
  10600. parentBranch.centerOfMass.x *= totalMassInv;
  10601. parentBranch.centerOfMass.y = parentBranch.centerOfMass.y * parentBranch.mass + node.y * node.mass;
  10602. parentBranch.centerOfMass.y *= totalMassInv;
  10603. parentBranch.mass = totalMass;
  10604. var biggestSize = Math.max(Math.max(node.height,node.radius),node.width);
  10605. parentBranch.maxWidth = (parentBranch.maxWidth < biggestSize) ? biggestSize : parentBranch.maxWidth;
  10606. },
  10607. /**
  10608. * determine in which branch the node will be placed.
  10609. *
  10610. * @param parentBranch
  10611. * @param node
  10612. * @param skipMassUpdate
  10613. * @private
  10614. */
  10615. _placeInTree : function(parentBranch,node,skipMassUpdate) {
  10616. if (skipMassUpdate != true || skipMassUpdate === undefined) {
  10617. // update the mass of the branch.
  10618. this._updateBranchMass(parentBranch,node);
  10619. }
  10620. if (parentBranch.children.NW.range.maxX > node.x) { // in NW or SW
  10621. if (parentBranch.children.NW.range.maxY > node.y) { // in NW
  10622. this._placeInRegion(parentBranch,node,"NW");
  10623. }
  10624. else { // in SW
  10625. this._placeInRegion(parentBranch,node,"SW");
  10626. }
  10627. }
  10628. else { // in NE or SE
  10629. if (parentBranch.children.NW.range.maxY > node.y) { // in NE
  10630. this._placeInRegion(parentBranch,node,"NE");
  10631. }
  10632. else { // in SE
  10633. this._placeInRegion(parentBranch,node,"SE");
  10634. }
  10635. }
  10636. },
  10637. /**
  10638. * actually place the node in a region (or branch)
  10639. *
  10640. * @param parentBranch
  10641. * @param node
  10642. * @param region
  10643. * @private
  10644. */
  10645. _placeInRegion : function(parentBranch,node,region) {
  10646. switch (parentBranch.children[region].childrenCount) {
  10647. case 0: // place node here
  10648. parentBranch.children[region].children.data = node;
  10649. parentBranch.children[region].childrenCount = 1;
  10650. this._updateBranchMass(parentBranch.children[region],node);
  10651. break;
  10652. case 1: // convert into children
  10653. // if there are two nodes exactly overlapping (on init, on opening of cluster etc.)
  10654. // we move one node a pixel and we do not put it in the tree.
  10655. if (parentBranch.children[region].children.data.x == node.x &&
  10656. parentBranch.children[region].children.data.y == node.y) {
  10657. node.x += Math.random();
  10658. node.y += Math.random();
  10659. }
  10660. else {
  10661. this._splitBranch(parentBranch.children[region]);
  10662. this._placeInTree(parentBranch.children[region],node);
  10663. }
  10664. break;
  10665. case 4: // place in branch
  10666. this._placeInTree(parentBranch.children[region],node);
  10667. break;
  10668. }
  10669. },
  10670. /**
  10671. * this function splits a branch into 4 sub branches. If the branch contained a node, we place it in the subbranch
  10672. * after the split is complete.
  10673. *
  10674. * @param parentBranch
  10675. * @private
  10676. */
  10677. _splitBranch : function(parentBranch) {
  10678. // if the branch is filled with a node, replace the node in the new subset.
  10679. var containedNode = null;
  10680. if (parentBranch.childrenCount == 1) {
  10681. containedNode = parentBranch.children.data;
  10682. parentBranch.mass = 0; parentBranch.centerOfMass.x = 0; parentBranch.centerOfMass.y = 0;
  10683. }
  10684. parentBranch.childrenCount = 4;
  10685. parentBranch.children.data = null;
  10686. this._insertRegion(parentBranch,"NW");
  10687. this._insertRegion(parentBranch,"NE");
  10688. this._insertRegion(parentBranch,"SW");
  10689. this._insertRegion(parentBranch,"SE");
  10690. if (containedNode != null) {
  10691. this._placeInTree(parentBranch,containedNode);
  10692. }
  10693. },
  10694. /**
  10695. * This function subdivides the region into four new segments.
  10696. * Specifically, this inserts a single new segment.
  10697. * It fills the children section of the parentBranch
  10698. *
  10699. * @param parentBranch
  10700. * @param region
  10701. * @param parentRange
  10702. * @private
  10703. */
  10704. _insertRegion : function(parentBranch, region) {
  10705. var minX,maxX,minY,maxY;
  10706. var childSize = 0.5 * parentBranch.size;
  10707. switch (region) {
  10708. case "NW":
  10709. minX = parentBranch.range.minX;
  10710. maxX = parentBranch.range.minX + childSize;
  10711. minY = parentBranch.range.minY;
  10712. maxY = parentBranch.range.minY + childSize;
  10713. break;
  10714. case "NE":
  10715. minX = parentBranch.range.minX + childSize;
  10716. maxX = parentBranch.range.maxX;
  10717. minY = parentBranch.range.minY;
  10718. maxY = parentBranch.range.minY + childSize;
  10719. break;
  10720. case "SW":
  10721. minX = parentBranch.range.minX;
  10722. maxX = parentBranch.range.minX + childSize;
  10723. minY = parentBranch.range.minY + childSize;
  10724. maxY = parentBranch.range.maxY;
  10725. break;
  10726. case "SE":
  10727. minX = parentBranch.range.minX + childSize;
  10728. maxX = parentBranch.range.maxX;
  10729. minY = parentBranch.range.minY + childSize;
  10730. maxY = parentBranch.range.maxY;
  10731. break;
  10732. }
  10733. parentBranch.children[region] = {
  10734. centerOfMass:{x:0,y:0},
  10735. mass:0,
  10736. range:{minX:minX,maxX:maxX,minY:minY,maxY:maxY},
  10737. size: 0.5 * parentBranch.size,
  10738. calcSize: 2 * parentBranch.calcSize,
  10739. children: {data:null},
  10740. maxWidth: 0,
  10741. level: parentBranch.level+1,
  10742. childrenCount: 0
  10743. };
  10744. },
  10745. /**
  10746. * This function is for debugging purposed, it draws the tree.
  10747. *
  10748. * @param ctx
  10749. * @param color
  10750. * @private
  10751. */
  10752. _drawTree : function(ctx,color) {
  10753. if (this.barnesHutTree !== undefined) {
  10754. ctx.lineWidth = 1;
  10755. this._drawBranch(this.barnesHutTree.root,ctx,color);
  10756. }
  10757. },
  10758. /**
  10759. * This function is for debugging purposes. It draws the branches recursively.
  10760. *
  10761. * @param branch
  10762. * @param ctx
  10763. * @param color
  10764. * @private
  10765. */
  10766. _drawBranch : function(branch,ctx,color) {
  10767. if (color === undefined) {
  10768. color = "#FF0000";
  10769. }
  10770. if (branch.childrenCount == 4) {
  10771. this._drawBranch(branch.children.NW,ctx);
  10772. this._drawBranch(branch.children.NE,ctx);
  10773. this._drawBranch(branch.children.SE,ctx);
  10774. this._drawBranch(branch.children.SW,ctx);
  10775. }
  10776. ctx.strokeStyle = color;
  10777. ctx.beginPath();
  10778. ctx.moveTo(branch.range.minX,branch.range.minY);
  10779. ctx.lineTo(branch.range.maxX,branch.range.minY);
  10780. ctx.stroke();
  10781. ctx.beginPath();
  10782. ctx.moveTo(branch.range.maxX,branch.range.minY);
  10783. ctx.lineTo(branch.range.maxX,branch.range.maxY);
  10784. ctx.stroke();
  10785. ctx.beginPath();
  10786. ctx.moveTo(branch.range.maxX,branch.range.maxY);
  10787. ctx.lineTo(branch.range.minX,branch.range.maxY);
  10788. ctx.stroke();
  10789. ctx.beginPath();
  10790. ctx.moveTo(branch.range.minX,branch.range.maxY);
  10791. ctx.lineTo(branch.range.minX,branch.range.minY);
  10792. ctx.stroke();
  10793. /*
  10794. if (branch.mass > 0) {
  10795. ctx.circle(branch.centerOfMass.x, branch.centerOfMass.y, 3*branch.mass);
  10796. ctx.stroke();
  10797. }
  10798. */
  10799. }
  10800. };
  10801. /**
  10802. * Created by Alex on 2/10/14.
  10803. */
  10804. var repulsionMixin = {
  10805. /**
  10806. * Calculate the forces the nodes apply on eachother based on a repulsion field.
  10807. * This field is linearly approximated.
  10808. *
  10809. * @private
  10810. */
  10811. _calculateNodeForces: function () {
  10812. var dx, dy, angle, distance, fx, fy, combinedClusterSize,
  10813. repulsingForce, node1, node2, i, j;
  10814. var nodes = this.calculationNodes;
  10815. var nodeIndices = this.calculationNodeIndices;
  10816. // approximation constants
  10817. var a_base = -2 / 3;
  10818. var b = 4 / 3;
  10819. // repulsing forces between nodes
  10820. var nodeDistance = this.constants.physics.repulsion.nodeDistance;
  10821. var minimumDistance = nodeDistance;
  10822. // we loop from i over all but the last entree in the array
  10823. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  10824. for (i = 0; i < nodeIndices.length - 1; i++) {
  10825. node1 = nodes[nodeIndices[i]];
  10826. for (j = i + 1; j < nodeIndices.length; j++) {
  10827. node2 = nodes[nodeIndices[j]];
  10828. combinedClusterSize = node1.clusterSize + node2.clusterSize - 2;
  10829. dx = node2.x - node1.x;
  10830. dy = node2.y - node1.y;
  10831. distance = Math.sqrt(dx * dx + dy * dy);
  10832. minimumDistance = (combinedClusterSize == 0) ? nodeDistance : (nodeDistance * (1 + combinedClusterSize * this.constants.clustering.distanceAmplification));
  10833. var a = a_base / minimumDistance;
  10834. if (distance < 2 * minimumDistance) {
  10835. if (distance < 0.5 * minimumDistance) {
  10836. repulsingForce = 1.0;
  10837. }
  10838. else {
  10839. repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness))
  10840. }
  10841. // amplify the repulsion for clusters.
  10842. repulsingForce *= (combinedClusterSize == 0) ? 1 : 1 + combinedClusterSize * this.constants.clustering.forceAmplification;
  10843. repulsingForce = repulsingForce / distance;
  10844. fx = dx * repulsingForce;
  10845. fy = dy * repulsingForce;
  10846. node1.fx -= fx;
  10847. node1.fy -= fy;
  10848. node2.fx += fx;
  10849. node2.fy += fy;
  10850. }
  10851. }
  10852. }
  10853. }
  10854. };
  10855. var HierarchicalLayoutMixin = {
  10856. _resetLevels : function() {
  10857. for (var nodeId in this.nodes) {
  10858. if (this.nodes.hasOwnProperty(nodeId)) {
  10859. var node = this.nodes[nodeId];
  10860. if (node.preassignedLevel == false) {
  10861. node.level = -1;
  10862. }
  10863. }
  10864. }
  10865. },
  10866. /**
  10867. * This is the main function to layout the nodes in a hierarchical way.
  10868. * It checks if the node details are supplied correctly
  10869. *
  10870. * @private
  10871. */
  10872. _setupHierarchicalLayout : function() {
  10873. if (this.constants.hierarchicalLayout.enabled == true) {
  10874. if (this.constants.hierarchicalLayout.direction == "RL" || this.constants.hierarchicalLayout.direction == "DU") {
  10875. this.constants.hierarchicalLayout.levelSeparation *= -1;
  10876. }
  10877. else {
  10878. this.constants.hierarchicalLayout.levelSeparation = Math.abs(this.constants.hierarchicalLayout.levelSeparation);
  10879. }
  10880. // get the size of the largest hubs and check if the user has defined a level for a node.
  10881. var hubsize = 0;
  10882. var node, nodeId;
  10883. var definedLevel = false;
  10884. var undefinedLevel = false;
  10885. for (nodeId in this.nodes) {
  10886. if (this.nodes.hasOwnProperty(nodeId)) {
  10887. node = this.nodes[nodeId];
  10888. if (node.level != -1) {
  10889. definedLevel = true;
  10890. }
  10891. else {
  10892. undefinedLevel = true;
  10893. }
  10894. if (hubsize < node.edges.length) {
  10895. hubsize = node.edges.length;
  10896. }
  10897. }
  10898. }
  10899. // if the user defined some levels but not all, alert and run without hierarchical layout
  10900. if (undefinedLevel == true && definedLevel == true) {
  10901. alert("To use the hierarchical layout, nodes require either no predefined levels or levels have to be defined for all nodes.");
  10902. this.zoomExtent(true,this.constants.clustering.enabled);
  10903. if (!this.constants.clustering.enabled) {
  10904. this.start();
  10905. }
  10906. }
  10907. else {
  10908. // setup the system to use hierarchical method.
  10909. this._changeConstants();
  10910. // define levels if undefined by the users. Based on hubsize
  10911. if (undefinedLevel == true) {
  10912. this._determineLevels(hubsize);
  10913. }
  10914. // check the distribution of the nodes per level.
  10915. var distribution = this._getDistribution();
  10916. // place the nodes on the canvas. This also stablilizes the system.
  10917. this._placeNodesByHierarchy(distribution);
  10918. // start the simulation.
  10919. this.start();
  10920. }
  10921. }
  10922. },
  10923. /**
  10924. * This function places the nodes on the canvas based on the hierarchial distribution.
  10925. *
  10926. * @param {Object} distribution | obtained by the function this._getDistribution()
  10927. * @private
  10928. */
  10929. _placeNodesByHierarchy : function(distribution) {
  10930. var nodeId, node;
  10931. // start placing all the level 0 nodes first. Then recursively position their branches.
  10932. for (nodeId in distribution[0].nodes) {
  10933. if (distribution[0].nodes.hasOwnProperty(nodeId)) {
  10934. node = distribution[0].nodes[nodeId];
  10935. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  10936. if (node.xFixed) {
  10937. node.x = distribution[0].minPos;
  10938. node.xFixed = false;
  10939. distribution[0].minPos += distribution[0].nodeSpacing;
  10940. }
  10941. }
  10942. else {
  10943. if (node.yFixed) {
  10944. node.y = distribution[0].minPos;
  10945. node.yFixed = false;
  10946. distribution[0].minPos += distribution[0].nodeSpacing;
  10947. }
  10948. }
  10949. this._placeBranchNodes(node.edges,node.id,distribution,node.level);
  10950. }
  10951. }
  10952. // stabilize the system after positioning. This function calls zoomExtent.
  10953. this._stabilize();
  10954. },
  10955. /**
  10956. * This function get the distribution of levels based on hubsize
  10957. *
  10958. * @returns {Object}
  10959. * @private
  10960. */
  10961. _getDistribution : function() {
  10962. var distribution = {};
  10963. var nodeId, node, level;
  10964. // 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.
  10965. // the fix of X is removed after the x value has been set.
  10966. for (nodeId in this.nodes) {
  10967. if (this.nodes.hasOwnProperty(nodeId)) {
  10968. node = this.nodes[nodeId];
  10969. node.xFixed = true;
  10970. node.yFixed = true;
  10971. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  10972. node.y = this.constants.hierarchicalLayout.levelSeparation*node.level;
  10973. }
  10974. else {
  10975. node.x = this.constants.hierarchicalLayout.levelSeparation*node.level;
  10976. }
  10977. if (!distribution.hasOwnProperty(node.level)) {
  10978. distribution[node.level] = {amount: 0, nodes: {}, minPos:0, nodeSpacing:0};
  10979. }
  10980. distribution[node.level].amount += 1;
  10981. distribution[node.level].nodes[node.id] = node;
  10982. }
  10983. }
  10984. // determine the largest amount of nodes of all levels
  10985. var maxCount = 0;
  10986. for (level in distribution) {
  10987. if (distribution.hasOwnProperty(level)) {
  10988. if (maxCount < distribution[level].amount) {
  10989. maxCount = distribution[level].amount;
  10990. }
  10991. }
  10992. }
  10993. // set the initial position and spacing of each nodes accordingly
  10994. for (level in distribution) {
  10995. if (distribution.hasOwnProperty(level)) {
  10996. distribution[level].nodeSpacing = (maxCount + 1) * this.constants.hierarchicalLayout.nodeSpacing;
  10997. distribution[level].nodeSpacing /= (distribution[level].amount + 1);
  10998. distribution[level].minPos = distribution[level].nodeSpacing - (0.5 * (distribution[level].amount + 1) * distribution[level].nodeSpacing);
  10999. }
  11000. }
  11001. return distribution;
  11002. },
  11003. /**
  11004. * this function allocates nodes in levels based on the recursive branching from the largest hubs.
  11005. *
  11006. * @param hubsize
  11007. * @private
  11008. */
  11009. _determineLevels : function(hubsize) {
  11010. var nodeId, node;
  11011. // determine hubs
  11012. for (nodeId in this.nodes) {
  11013. if (this.nodes.hasOwnProperty(nodeId)) {
  11014. node = this.nodes[nodeId];
  11015. if (node.edges.length == hubsize) {
  11016. node.level = 0;
  11017. }
  11018. }
  11019. }
  11020. // branch from hubs
  11021. for (nodeId in this.nodes) {
  11022. if (this.nodes.hasOwnProperty(nodeId)) {
  11023. node = this.nodes[nodeId];
  11024. if (node.level == 0) {
  11025. this._setLevel(1,node.edges,node.id);
  11026. }
  11027. }
  11028. }
  11029. },
  11030. /**
  11031. * Since hierarchical layout does not support:
  11032. * - smooth curves (based on the physics),
  11033. * - clustering (based on dynamic node counts)
  11034. *
  11035. * We disable both features so there will be no problems.
  11036. *
  11037. * @private
  11038. */
  11039. _changeConstants : function() {
  11040. this.constants.clustering.enabled = false;
  11041. this.constants.physics.barnesHut.enabled = false;
  11042. this.constants.physics.hierarchicalRepulsion.enabled = true;
  11043. this._loadSelectedForceSolver();
  11044. this.constants.smoothCurves = false;
  11045. this._configureSmoothCurves();
  11046. },
  11047. /**
  11048. * This is a recursively called function to enumerate the branches from the largest hubs and place the nodes
  11049. * on a X position that ensures there will be no overlap.
  11050. *
  11051. * @param edges
  11052. * @param parentId
  11053. * @param distribution
  11054. * @param parentLevel
  11055. * @private
  11056. */
  11057. _placeBranchNodes : function(edges, parentId, distribution, parentLevel) {
  11058. for (var i = 0; i < edges.length; i++) {
  11059. var childNode = null;
  11060. if (edges[i].toId == parentId) {
  11061. childNode = edges[i].from;
  11062. }
  11063. else {
  11064. childNode = edges[i].to;
  11065. }
  11066. // if a node is conneceted to another node on the same level (or higher (means lower level))!, this is not handled here.
  11067. var nodeMoved = false;
  11068. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  11069. if (childNode.xFixed && childNode.level > parentLevel) {
  11070. childNode.xFixed = false;
  11071. childNode.x = distribution[childNode.level].minPos;
  11072. nodeMoved = true;
  11073. }
  11074. }
  11075. else {
  11076. if (childNode.yFixed && childNode.level > parentLevel) {
  11077. childNode.yFixed = false;
  11078. childNode.y = distribution[childNode.level].minPos;
  11079. nodeMoved = true;
  11080. }
  11081. }
  11082. if (nodeMoved == true) {
  11083. distribution[childNode.level].minPos += distribution[childNode.level].nodeSpacing;
  11084. if (childNode.edges.length > 1) {
  11085. this._placeBranchNodes(childNode.edges,childNode.id,distribution,childNode.level);
  11086. }
  11087. }
  11088. }
  11089. },
  11090. /**
  11091. * this function is called recursively to enumerate the barnches of the largest hubs and give each node a level.
  11092. *
  11093. * @param level
  11094. * @param edges
  11095. * @param parentId
  11096. * @private
  11097. */
  11098. _setLevel : function(level, edges, parentId) {
  11099. for (var i = 0; i < edges.length; i++) {
  11100. var childNode = null;
  11101. if (edges[i].toId == parentId) {
  11102. childNode = edges[i].from;
  11103. }
  11104. else {
  11105. childNode = edges[i].to;
  11106. }
  11107. if (childNode.level == -1 || childNode.level > level) {
  11108. childNode.level = level;
  11109. if (edges.length > 1) {
  11110. this._setLevel(level+1, childNode.edges, childNode.id);
  11111. }
  11112. }
  11113. }
  11114. },
  11115. /**
  11116. * Unfix nodes
  11117. *
  11118. * @private
  11119. */
  11120. _restoreNodes : function() {
  11121. for (nodeId in this.nodes) {
  11122. if (this.nodes.hasOwnProperty(nodeId)) {
  11123. this.nodes[nodeId].xFixed = false;
  11124. this.nodes[nodeId].yFixed = false;
  11125. }
  11126. }
  11127. }
  11128. };
  11129. /**
  11130. * Created by Alex on 2/4/14.
  11131. */
  11132. var manipulationMixin = {
  11133. /**
  11134. * clears the toolbar div element of children
  11135. *
  11136. * @private
  11137. */
  11138. _clearManipulatorBar : function() {
  11139. while (this.manipulationDiv.hasChildNodes()) {
  11140. this.manipulationDiv.removeChild(this.manipulationDiv.firstChild);
  11141. }
  11142. },
  11143. /**
  11144. * Manipulation UI temporarily overloads certain functions to extend or replace them. To be able to restore
  11145. * these functions to their original functionality, we saved them in this.cachedFunctions.
  11146. * This function restores these functions to their original function.
  11147. *
  11148. * @private
  11149. */
  11150. _restoreOverloadedFunctions : function() {
  11151. for (var functionName in this.cachedFunctions) {
  11152. if (this.cachedFunctions.hasOwnProperty(functionName)) {
  11153. this[functionName] = this.cachedFunctions[functionName];
  11154. }
  11155. }
  11156. },
  11157. /**
  11158. * Enable or disable edit-mode.
  11159. *
  11160. * @private
  11161. */
  11162. _toggleEditMode : function() {
  11163. this.editMode = !this.editMode;
  11164. var toolbar = document.getElementById("graph-manipulationDiv");
  11165. var closeDiv = document.getElementById("graph-manipulation-closeDiv");
  11166. var editModeDiv = document.getElementById("graph-manipulation-editMode");
  11167. if (this.editMode == true) {
  11168. toolbar.style.display="block";
  11169. closeDiv.style.display="block";
  11170. editModeDiv.style.display="none";
  11171. closeDiv.onclick = this._toggleEditMode.bind(this);
  11172. }
  11173. else {
  11174. toolbar.style.display="none";
  11175. closeDiv.style.display="none";
  11176. editModeDiv.style.display="block";
  11177. closeDiv.onclick = null;
  11178. }
  11179. this._createManipulatorBar()
  11180. },
  11181. /**
  11182. * main function, creates the main toolbar. Removes functions bound to the select event. Binds all the buttons of the toolbar.
  11183. *
  11184. * @private
  11185. */
  11186. _createManipulatorBar : function() {
  11187. // remove bound functions
  11188. if (this.boundFunction) {
  11189. this.off('select', this.boundFunction);
  11190. }
  11191. // restore overloaded functions
  11192. this._restoreOverloadedFunctions();
  11193. // resume calculation
  11194. this.freezeSimulation = false;
  11195. // reset global variables
  11196. this.blockConnectingEdgeSelection = false;
  11197. this.forceAppendSelection = false;
  11198. if (this.editMode == true) {
  11199. while (this.manipulationDiv.hasChildNodes()) {
  11200. this.manipulationDiv.removeChild(this.manipulationDiv.firstChild);
  11201. }
  11202. // add the icons to the manipulator div
  11203. this.manipulationDiv.innerHTML = "" +
  11204. "<span class='graph-manipulationUI add' id='graph-manipulate-addNode'>" +
  11205. "<span class='graph-manipulationLabel'>"+this.constants.labels['add'] +"</span></span>" +
  11206. "<div class='graph-seperatorLine'></div>" +
  11207. "<span class='graph-manipulationUI connect' id='graph-manipulate-connectNode'>" +
  11208. "<span class='graph-manipulationLabel'>"+this.constants.labels['link'] +"</span></span>";
  11209. if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
  11210. this.manipulationDiv.innerHTML += "" +
  11211. "<div class='graph-seperatorLine'></div>" +
  11212. "<span class='graph-manipulationUI edit' id='graph-manipulate-editNode'>" +
  11213. "<span class='graph-manipulationLabel'>"+this.constants.labels['editNode'] +"</span></span>";
  11214. }
  11215. if (this._selectionIsEmpty() == false) {
  11216. this.manipulationDiv.innerHTML += "" +
  11217. "<div class='graph-seperatorLine'></div>" +
  11218. "<span class='graph-manipulationUI delete' id='graph-manipulate-delete'>" +
  11219. "<span class='graph-manipulationLabel'>"+this.constants.labels['del'] +"</span></span>";
  11220. }
  11221. // bind the icons
  11222. var addNodeButton = document.getElementById("graph-manipulate-addNode");
  11223. addNodeButton.onclick = this._createAddNodeToolbar.bind(this);
  11224. var addEdgeButton = document.getElementById("graph-manipulate-connectNode");
  11225. addEdgeButton.onclick = this._createAddEdgeToolbar.bind(this);
  11226. if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
  11227. var editButton = document.getElementById("graph-manipulate-editNode");
  11228. editButton.onclick = this._editNode.bind(this);
  11229. }
  11230. if (this._selectionIsEmpty() == false) {
  11231. var deleteButton = document.getElementById("graph-manipulate-delete");
  11232. deleteButton.onclick = this._deleteSelected.bind(this);
  11233. }
  11234. var closeDiv = document.getElementById("graph-manipulation-closeDiv");
  11235. closeDiv.onclick = this._toggleEditMode.bind(this);
  11236. this.boundFunction = this._createManipulatorBar.bind(this);
  11237. this.on('select', this.boundFunction);
  11238. }
  11239. else {
  11240. this.editModeDiv.innerHTML = "" +
  11241. "<span class='graph-manipulationUI edit editmode' id='graph-manipulate-editModeButton'>" +
  11242. "<span class='graph-manipulationLabel'>" + this.constants.labels['edit'] + "</span></span>";
  11243. var editModeButton = document.getElementById("graph-manipulate-editModeButton");
  11244. editModeButton.onclick = this._toggleEditMode.bind(this);
  11245. }
  11246. },
  11247. /**
  11248. * Create the toolbar for adding Nodes
  11249. *
  11250. * @private
  11251. */
  11252. _createAddNodeToolbar : function() {
  11253. // clear the toolbar
  11254. this._clearManipulatorBar();
  11255. if (this.boundFunction) {
  11256. this.off('select', this.boundFunction);
  11257. }
  11258. // create the toolbar contents
  11259. this.manipulationDiv.innerHTML = "" +
  11260. "<span class='graph-manipulationUI back' id='graph-manipulate-back'>" +
  11261. "<span class='graph-manipulationLabel'>" + this.constants.labels['back'] + " </span></span>" +
  11262. "<div class='graph-seperatorLine'></div>" +
  11263. "<span class='graph-manipulationUI none' id='graph-manipulate-back'>" +
  11264. "<span id='graph-manipulatorLabel' class='graph-manipulationLabel'>" + this.constants.labels['addDescription'] + "</span></span>";
  11265. // bind the icon
  11266. var backButton = document.getElementById("graph-manipulate-back");
  11267. backButton.onclick = this._createManipulatorBar.bind(this);
  11268. // we use the boundFunction so we can reference it when we unbind it from the "select" event.
  11269. this.boundFunction = this._addNode.bind(this);
  11270. this.on('select', this.boundFunction);
  11271. },
  11272. /**
  11273. * create the toolbar to connect nodes
  11274. *
  11275. * @private
  11276. */
  11277. _createAddEdgeToolbar : function() {
  11278. // clear the toolbar
  11279. this._clearManipulatorBar();
  11280. this._unselectAll(true);
  11281. this.freezeSimulation = true;
  11282. if (this.boundFunction) {
  11283. this.off('select', this.boundFunction);
  11284. }
  11285. this._unselectAll();
  11286. this.forceAppendSelection = false;
  11287. this.blockConnectingEdgeSelection = true;
  11288. this.manipulationDiv.innerHTML = "" +
  11289. "<span class='graph-manipulationUI back' id='graph-manipulate-back'>" +
  11290. "<span class='graph-manipulationLabel'>" + this.constants.labels['back'] + " </span></span>" +
  11291. "<div class='graph-seperatorLine'></div>" +
  11292. "<span class='graph-manipulationUI none' id='graph-manipulate-back'>" +
  11293. "<span id='graph-manipulatorLabel' class='graph-manipulationLabel'>" + this.constants.labels['linkDescription'] + "</span></span>";
  11294. // bind the icon
  11295. var backButton = document.getElementById("graph-manipulate-back");
  11296. backButton.onclick = this._createManipulatorBar.bind(this);
  11297. // we use the boundFunction so we can reference it when we unbind it from the "select" event.
  11298. this.boundFunction = this._handleConnect.bind(this);
  11299. this.on('select', this.boundFunction);
  11300. // temporarily overload functions
  11301. this.cachedFunctions["_handleTouch"] = this._handleTouch;
  11302. this.cachedFunctions["_handleOnRelease"] = this._handleOnRelease;
  11303. this._handleTouch = this._handleConnect;
  11304. this._handleOnRelease = this._finishConnect;
  11305. // redraw to show the unselect
  11306. this._redraw();
  11307. },
  11308. /**
  11309. * the function bound to the selection event. It checks if you want to connect a cluster and changes the description
  11310. * to walk the user through the process.
  11311. *
  11312. * @private
  11313. */
  11314. _handleConnect : function(pointer) {
  11315. if (this._getSelectedNodeCount() == 0) {
  11316. var node = this._getNodeAt(pointer);
  11317. if (node != null) {
  11318. if (node.clusterSize > 1) {
  11319. alert("Cannot create edges to a cluster.")
  11320. }
  11321. else {
  11322. this._selectObject(node,false);
  11323. // create a node the temporary line can look at
  11324. this.sectors['support']['nodes']['targetNode'] = new Node({id:'targetNode'},{},{},this.constants);
  11325. this.sectors['support']['nodes']['targetNode'].x = node.x;
  11326. this.sectors['support']['nodes']['targetNode'].y = node.y;
  11327. this.sectors['support']['nodes']['targetViaNode'] = new Node({id:'targetViaNode'},{},{},this.constants);
  11328. this.sectors['support']['nodes']['targetViaNode'].x = node.x;
  11329. this.sectors['support']['nodes']['targetViaNode'].y = node.y;
  11330. this.sectors['support']['nodes']['targetViaNode'].parentEdgeId = "connectionEdge";
  11331. // create a temporary edge
  11332. this.edges['connectionEdge'] = new Edge({id:"connectionEdge",from:node.id,to:this.sectors['support']['nodes']['targetNode'].id}, this, this.constants);
  11333. this.edges['connectionEdge'].from = node;
  11334. this.edges['connectionEdge'].connected = true;
  11335. this.edges['connectionEdge'].smooth = true;
  11336. this.edges['connectionEdge'].selected = true;
  11337. this.edges['connectionEdge'].to = this.sectors['support']['nodes']['targetNode'];
  11338. this.edges['connectionEdge'].via = this.sectors['support']['nodes']['targetViaNode'];
  11339. this.cachedFunctions["_handleOnDrag"] = this._handleOnDrag;
  11340. this._handleOnDrag = function(event) {
  11341. var pointer = this._getPointer(event.gesture.center);
  11342. this.sectors['support']['nodes']['targetNode'].x = this._canvasToX(pointer.x);
  11343. this.sectors['support']['nodes']['targetNode'].y = this._canvasToY(pointer.y);
  11344. this.sectors['support']['nodes']['targetViaNode'].x = 0.5 * (this._canvasToX(pointer.x) + this.edges['connectionEdge'].from.x);
  11345. this.sectors['support']['nodes']['targetViaNode'].y = this._canvasToY(pointer.y);
  11346. };
  11347. this.moving = true;
  11348. this.start();
  11349. }
  11350. }
  11351. }
  11352. },
  11353. _finishConnect : function(pointer) {
  11354. if (this._getSelectedNodeCount() == 1) {
  11355. // restore the drag function
  11356. this._handleOnDrag = this.cachedFunctions["_handleOnDrag"];
  11357. delete this.cachedFunctions["_handleOnDrag"];
  11358. // remember the edge id
  11359. var connectFromId = this.edges['connectionEdge'].fromId;
  11360. // remove the temporary nodes and edge
  11361. delete this.edges['connectionEdge'];
  11362. delete this.sectors['support']['nodes']['targetNode'];
  11363. delete this.sectors['support']['nodes']['targetViaNode'];
  11364. var node = this._getNodeAt(pointer);
  11365. if (node != null) {
  11366. if (node.clusterSize > 1) {
  11367. alert("Cannot create edges to a cluster.")
  11368. }
  11369. else {
  11370. this._createEdge(connectFromId,node.id);
  11371. this._createManipulatorBar();
  11372. }
  11373. }
  11374. this._unselectAll();
  11375. }
  11376. },
  11377. /**
  11378. * Adds a node on the specified location
  11379. */
  11380. _addNode : function() {
  11381. if (this._selectionIsEmpty() && this.editMode == true) {
  11382. var positionObject = this._pointerToPositionObject(this.pointerPosition);
  11383. var defaultData = {id:util.randomUUID(),x:positionObject.left,y:positionObject.top,label:"new",allowedToMoveX:true,allowedToMoveY:true};
  11384. if (this.triggerFunctions.add) {
  11385. if (this.triggerFunctions.add.length == 2) {
  11386. var me = this;
  11387. this.triggerFunctions.add(defaultData, function(finalizedData) {
  11388. me.nodesData.add(finalizedData);
  11389. me._createManipulatorBar();
  11390. me.moving = true;
  11391. me.start();
  11392. });
  11393. }
  11394. else {
  11395. alert(this.constants.labels['addError']);
  11396. this._createManipulatorBar();
  11397. this.moving = true;
  11398. this.start();
  11399. }
  11400. }
  11401. else {
  11402. this.nodesData.add(defaultData);
  11403. this._createManipulatorBar();
  11404. this.moving = true;
  11405. this.start();
  11406. }
  11407. }
  11408. },
  11409. /**
  11410. * connect two nodes with a new edge.
  11411. *
  11412. * @private
  11413. */
  11414. _createEdge : function(sourceNodeId,targetNodeId) {
  11415. if (this.editMode == true) {
  11416. var defaultData = {from:sourceNodeId, to:targetNodeId};
  11417. if (this.triggerFunctions.connect) {
  11418. if (this.triggerFunctions.connect.length == 2) {
  11419. var me = this;
  11420. this.triggerFunctions.connect(defaultData, function(finalizedData) {
  11421. me.edgesData.add(finalizedData);
  11422. me.moving = true;
  11423. me.start();
  11424. });
  11425. }
  11426. else {
  11427. alert(this.constants.labels["linkError"]);
  11428. this.moving = true;
  11429. this.start();
  11430. }
  11431. }
  11432. else {
  11433. this.edgesData.add(defaultData);
  11434. this.moving = true;
  11435. this.start();
  11436. }
  11437. }
  11438. },
  11439. /**
  11440. * Create the toolbar to edit the selected node. The label and the color can be changed. Other colors are derived from the chosen color.
  11441. *
  11442. * @private
  11443. */
  11444. _editNode : function() {
  11445. if (this.triggerFunctions.edit && this.editMode == true) {
  11446. var node = this._getSelectedNode();
  11447. var data = {id:node.id,
  11448. label: node.label,
  11449. group: node.group,
  11450. shape: node.shape,
  11451. color: {
  11452. background:node.color.background,
  11453. border:node.color.border,
  11454. highlight: {
  11455. background:node.color.highlight.background,
  11456. border:node.color.highlight.border
  11457. }
  11458. }};
  11459. if (this.triggerFunctions.edit.length == 2) {
  11460. var me = this;
  11461. this.triggerFunctions.edit(data, function (finalizedData) {
  11462. me.nodesData.update(finalizedData);
  11463. me._createManipulatorBar();
  11464. me.moving = true;
  11465. me.start();
  11466. });
  11467. }
  11468. else {
  11469. alert(this.constants.labels["editError"]);
  11470. }
  11471. }
  11472. else {
  11473. alert(this.constants.labels["editBoundError"]);
  11474. }
  11475. },
  11476. /**
  11477. * delete everything in the selection
  11478. *
  11479. * @private
  11480. */
  11481. _deleteSelected : function() {
  11482. if (!this._selectionIsEmpty() && this.editMode == true) {
  11483. if (!this._clusterInSelection()) {
  11484. var selectedNodes = this.getSelectedNodes();
  11485. var selectedEdges = this.getSelectedEdges();
  11486. if (this.triggerFunctions.del) {
  11487. var me = this;
  11488. var data = {nodes: selectedNodes, edges: selectedEdges};
  11489. if (this.triggerFunctions.del.length = 2) {
  11490. this.triggerFunctions.del(data, function (finalizedData) {
  11491. me.edgesData.remove(finalizedData.edges);
  11492. me.nodesData.remove(finalizedData.nodes);
  11493. me._unselectAll();
  11494. me.moving = true;
  11495. me.start();
  11496. });
  11497. }
  11498. else {
  11499. alert(this.constants.labels["deleteError"])
  11500. }
  11501. }
  11502. else {
  11503. this.edgesData.remove(selectedEdges);
  11504. this.nodesData.remove(selectedNodes);
  11505. this._unselectAll();
  11506. this.moving = true;
  11507. this.start();
  11508. }
  11509. }
  11510. else {
  11511. alert(this.constants.labels["deleteClusterError"]);
  11512. }
  11513. }
  11514. }
  11515. };
  11516. /**
  11517. * Creation of the SectorMixin var.
  11518. *
  11519. * This contains all the functions the Graph object can use to employ the sector system.
  11520. * The sector system is always used by Graph, though the benefits only apply to the use of clustering.
  11521. * If clustering is not used, there is no overhead except for a duplicate object with references to nodes and edges.
  11522. *
  11523. * Alex de Mulder
  11524. * 21-01-2013
  11525. */
  11526. var SectorMixin = {
  11527. /**
  11528. * This function is only called by the setData function of the Graph object.
  11529. * This loads the global references into the active sector. This initializes the sector.
  11530. *
  11531. * @private
  11532. */
  11533. _putDataInSector : function() {
  11534. this.sectors["active"][this._sector()].nodes = this.nodes;
  11535. this.sectors["active"][this._sector()].edges = this.edges;
  11536. this.sectors["active"][this._sector()].nodeIndices = this.nodeIndices;
  11537. },
  11538. /**
  11539. * /**
  11540. * This function sets the global references to nodes, edges and nodeIndices back to
  11541. * those of the supplied (active) sector. If a type is defined, do the specific type
  11542. *
  11543. * @param {String} sectorId
  11544. * @param {String} [sectorType] | "active" or "frozen"
  11545. * @private
  11546. */
  11547. _switchToSector : function(sectorId, sectorType) {
  11548. if (sectorType === undefined || sectorType == "active") {
  11549. this._switchToActiveSector(sectorId);
  11550. }
  11551. else {
  11552. this._switchToFrozenSector(sectorId);
  11553. }
  11554. },
  11555. /**
  11556. * This function sets the global references to nodes, edges and nodeIndices back to
  11557. * those of the supplied active sector.
  11558. *
  11559. * @param sectorId
  11560. * @private
  11561. */
  11562. _switchToActiveSector : function(sectorId) {
  11563. this.nodeIndices = this.sectors["active"][sectorId]["nodeIndices"];
  11564. this.nodes = this.sectors["active"][sectorId]["nodes"];
  11565. this.edges = this.sectors["active"][sectorId]["edges"];
  11566. },
  11567. /**
  11568. * This function sets the global references to nodes, edges and nodeIndices back to
  11569. * those of the supplied active sector.
  11570. *
  11571. * @param sectorId
  11572. * @private
  11573. */
  11574. _switchToSupportSector : function() {
  11575. this.nodeIndices = this.sectors["support"]["nodeIndices"];
  11576. this.nodes = this.sectors["support"]["nodes"];
  11577. this.edges = this.sectors["support"]["edges"];
  11578. },
  11579. /**
  11580. * This function sets the global references to nodes, edges and nodeIndices back to
  11581. * those of the supplied frozen sector.
  11582. *
  11583. * @param sectorId
  11584. * @private
  11585. */
  11586. _switchToFrozenSector : function(sectorId) {
  11587. this.nodeIndices = this.sectors["frozen"][sectorId]["nodeIndices"];
  11588. this.nodes = this.sectors["frozen"][sectorId]["nodes"];
  11589. this.edges = this.sectors["frozen"][sectorId]["edges"];
  11590. },
  11591. /**
  11592. * This function sets the global references to nodes, edges and nodeIndices back to
  11593. * those of the currently active sector.
  11594. *
  11595. * @private
  11596. */
  11597. _loadLatestSector : function() {
  11598. this._switchToSector(this._sector());
  11599. },
  11600. /**
  11601. * This function returns the currently active sector Id
  11602. *
  11603. * @returns {String}
  11604. * @private
  11605. */
  11606. _sector : function() {
  11607. return this.activeSector[this.activeSector.length-1];
  11608. },
  11609. /**
  11610. * This function returns the previously active sector Id
  11611. *
  11612. * @returns {String}
  11613. * @private
  11614. */
  11615. _previousSector : function() {
  11616. if (this.activeSector.length > 1) {
  11617. return this.activeSector[this.activeSector.length-2];
  11618. }
  11619. else {
  11620. throw new TypeError('there are not enough sectors in the this.activeSector array.');
  11621. }
  11622. },
  11623. /**
  11624. * We add the active sector at the end of the this.activeSector array
  11625. * This ensures it is the currently active sector returned by _sector() and it reaches the top
  11626. * of the activeSector stack. When we reverse our steps we move from the end to the beginning of this stack.
  11627. *
  11628. * @param newId
  11629. * @private
  11630. */
  11631. _setActiveSector : function(newId) {
  11632. this.activeSector.push(newId);
  11633. },
  11634. /**
  11635. * We remove the currently active sector id from the active sector stack. This happens when
  11636. * we reactivate the previously active sector
  11637. *
  11638. * @private
  11639. */
  11640. _forgetLastSector : function() {
  11641. this.activeSector.pop();
  11642. },
  11643. /**
  11644. * This function creates a new active sector with the supplied newId. This newId
  11645. * is the expanding node id.
  11646. *
  11647. * @param {String} newId | Id of the new active sector
  11648. * @private
  11649. */
  11650. _createNewSector : function(newId) {
  11651. // create the new sector
  11652. this.sectors["active"][newId] = {"nodes":{},
  11653. "edges":{},
  11654. "nodeIndices":[],
  11655. "formationScale": this.scale,
  11656. "drawingNode": undefined};
  11657. // create the new sector render node. This gives visual feedback that you are in a new sector.
  11658. this.sectors["active"][newId]['drawingNode'] = new Node(
  11659. {id:newId,
  11660. color: {
  11661. background: "#eaefef",
  11662. border: "495c5e"
  11663. }
  11664. },{},{},this.constants);
  11665. this.sectors["active"][newId]['drawingNode'].clusterSize = 2;
  11666. },
  11667. /**
  11668. * This function removes the currently active sector. This is called when we create a new
  11669. * active sector.
  11670. *
  11671. * @param {String} sectorId | Id of the active sector that will be removed
  11672. * @private
  11673. */
  11674. _deleteActiveSector : function(sectorId) {
  11675. delete this.sectors["active"][sectorId];
  11676. },
  11677. /**
  11678. * This function removes the currently active sector. This is called when we reactivate
  11679. * the previously active sector.
  11680. *
  11681. * @param {String} sectorId | Id of the active sector that will be removed
  11682. * @private
  11683. */
  11684. _deleteFrozenSector : function(sectorId) {
  11685. delete this.sectors["frozen"][sectorId];
  11686. },
  11687. /**
  11688. * Freezing an active sector means moving it from the "active" object to the "frozen" object.
  11689. * We copy the references, then delete the active entree.
  11690. *
  11691. * @param sectorId
  11692. * @private
  11693. */
  11694. _freezeSector : function(sectorId) {
  11695. // we move the set references from the active to the frozen stack.
  11696. this.sectors["frozen"][sectorId] = this.sectors["active"][sectorId];
  11697. // we have moved the sector data into the frozen set, we now remove it from the active set
  11698. this._deleteActiveSector(sectorId);
  11699. },
  11700. /**
  11701. * This is the reverse operation of _freezeSector. Activating means moving the sector from the "frozen"
  11702. * object to the "active" object.
  11703. *
  11704. * @param sectorId
  11705. * @private
  11706. */
  11707. _activateSector : function(sectorId) {
  11708. // we move the set references from the frozen to the active stack.
  11709. this.sectors["active"][sectorId] = this.sectors["frozen"][sectorId];
  11710. // we have moved the sector data into the active set, we now remove it from the frozen stack
  11711. this._deleteFrozenSector(sectorId);
  11712. },
  11713. /**
  11714. * This function merges the data from the currently active sector with a frozen sector. This is used
  11715. * in the process of reverting back to the previously active sector.
  11716. * The data that is placed in the frozen (the previously active) sector is the node that has been removed from it
  11717. * upon the creation of a new active sector.
  11718. *
  11719. * @param sectorId
  11720. * @private
  11721. */
  11722. _mergeThisWithFrozen : function(sectorId) {
  11723. // copy all nodes
  11724. for (var nodeId in this.nodes) {
  11725. if (this.nodes.hasOwnProperty(nodeId)) {
  11726. this.sectors["frozen"][sectorId]["nodes"][nodeId] = this.nodes[nodeId];
  11727. }
  11728. }
  11729. // copy all edges (if not fully clustered, else there are no edges)
  11730. for (var edgeId in this.edges) {
  11731. if (this.edges.hasOwnProperty(edgeId)) {
  11732. this.sectors["frozen"][sectorId]["edges"][edgeId] = this.edges[edgeId];
  11733. }
  11734. }
  11735. // merge the nodeIndices
  11736. for (var i = 0; i < this.nodeIndices.length; i++) {
  11737. this.sectors["frozen"][sectorId]["nodeIndices"].push(this.nodeIndices[i]);
  11738. }
  11739. },
  11740. /**
  11741. * This clusters the sector to one cluster. It was a single cluster before this process started so
  11742. * we revert to that state. The clusterToFit function with a maximum size of 1 node does this.
  11743. *
  11744. * @private
  11745. */
  11746. _collapseThisToSingleCluster : function() {
  11747. this.clusterToFit(1,false);
  11748. },
  11749. /**
  11750. * We create a new active sector from the node that we want to open.
  11751. *
  11752. * @param node
  11753. * @private
  11754. */
  11755. _addSector : function(node) {
  11756. // this is the currently active sector
  11757. var sector = this._sector();
  11758. // // this should allow me to select nodes from a frozen set.
  11759. // if (this.sectors['active'][sector]["nodes"].hasOwnProperty(node.id)) {
  11760. // console.log("the node is part of the active sector");
  11761. // }
  11762. // else {
  11763. // console.log("I dont know what the fuck happened!!");
  11764. // }
  11765. // when we switch to a new sector, we remove the node that will be expanded from the current nodes list.
  11766. delete this.nodes[node.id];
  11767. var unqiueIdentifier = util.randomUUID();
  11768. // we fully freeze the currently active sector
  11769. this._freezeSector(sector);
  11770. // we create a new active sector. This sector has the Id of the node to ensure uniqueness
  11771. this._createNewSector(unqiueIdentifier);
  11772. // we add the active sector to the sectors array to be able to revert these steps later on
  11773. this._setActiveSector(unqiueIdentifier);
  11774. // we redirect the global references to the new sector's references. this._sector() now returns unqiueIdentifier
  11775. this._switchToSector(this._sector());
  11776. // finally we add the node we removed from our previous active sector to the new active sector
  11777. this.nodes[node.id] = node;
  11778. },
  11779. /**
  11780. * We close the sector that is currently open and revert back to the one before.
  11781. * If the active sector is the "default" sector, nothing happens.
  11782. *
  11783. * @private
  11784. */
  11785. _collapseSector : function() {
  11786. // the currently active sector
  11787. var sector = this._sector();
  11788. // we cannot collapse the default sector
  11789. if (sector != "default") {
  11790. if ((this.nodeIndices.length == 1) ||
  11791. (this.sectors["active"][sector]["drawingNode"].width*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  11792. (this.sectors["active"][sector]["drawingNode"].height*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  11793. var previousSector = this._previousSector();
  11794. // we collapse the sector back to a single cluster
  11795. this._collapseThisToSingleCluster();
  11796. // we move the remaining nodes, edges and nodeIndices to the previous sector.
  11797. // This previous sector is the one we will reactivate
  11798. this._mergeThisWithFrozen(previousSector);
  11799. // the previously active (frozen) sector now has all the data from the currently active sector.
  11800. // we can now delete the active sector.
  11801. this._deleteActiveSector(sector);
  11802. // we activate the previously active (and currently frozen) sector.
  11803. this._activateSector(previousSector);
  11804. // we load the references from the newly active sector into the global references
  11805. this._switchToSector(previousSector);
  11806. // we forget the previously active sector because we reverted to the one before
  11807. this._forgetLastSector();
  11808. // finally, we update the node index list.
  11809. this._updateNodeIndexList();
  11810. // we refresh the list with calulation nodes and calculation node indices.
  11811. this._updateCalculationNodes();
  11812. }
  11813. }
  11814. },
  11815. /**
  11816. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  11817. *
  11818. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11819. * | we dont pass the function itself because then the "this" is the window object
  11820. * | instead of the Graph object
  11821. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11822. * @private
  11823. */
  11824. _doInAllActiveSectors : function(runFunction,argument) {
  11825. if (argument === undefined) {
  11826. for (var sector in this.sectors["active"]) {
  11827. if (this.sectors["active"].hasOwnProperty(sector)) {
  11828. // switch the global references to those of this sector
  11829. this._switchToActiveSector(sector);
  11830. this[runFunction]();
  11831. }
  11832. }
  11833. }
  11834. else {
  11835. for (var sector in this.sectors["active"]) {
  11836. if (this.sectors["active"].hasOwnProperty(sector)) {
  11837. // switch the global references to those of this sector
  11838. this._switchToActiveSector(sector);
  11839. var args = Array.prototype.splice.call(arguments, 1);
  11840. if (args.length > 1) {
  11841. this[runFunction](args[0],args[1]);
  11842. }
  11843. else {
  11844. this[runFunction](argument);
  11845. }
  11846. }
  11847. }
  11848. }
  11849. // we revert the global references back to our active sector
  11850. this._loadLatestSector();
  11851. },
  11852. /**
  11853. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  11854. *
  11855. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11856. * | we dont pass the function itself because then the "this" is the window object
  11857. * | instead of the Graph object
  11858. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11859. * @private
  11860. */
  11861. _doInSupportSector : function(runFunction,argument) {
  11862. if (argument === undefined) {
  11863. this._switchToSupportSector();
  11864. this[runFunction]();
  11865. }
  11866. else {
  11867. this._switchToSupportSector();
  11868. var args = Array.prototype.splice.call(arguments, 1);
  11869. if (args.length > 1) {
  11870. this[runFunction](args[0],args[1]);
  11871. }
  11872. else {
  11873. this[runFunction](argument);
  11874. }
  11875. }
  11876. // we revert the global references back to our active sector
  11877. this._loadLatestSector();
  11878. },
  11879. /**
  11880. * This runs a function in all frozen sectors. This is used in the _redraw().
  11881. *
  11882. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11883. * | we don't pass the function itself because then the "this" is the window object
  11884. * | instead of the Graph object
  11885. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11886. * @private
  11887. */
  11888. _doInAllFrozenSectors : function(runFunction,argument) {
  11889. if (argument === undefined) {
  11890. for (var sector in this.sectors["frozen"]) {
  11891. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  11892. // switch the global references to those of this sector
  11893. this._switchToFrozenSector(sector);
  11894. this[runFunction]();
  11895. }
  11896. }
  11897. }
  11898. else {
  11899. for (var sector in this.sectors["frozen"]) {
  11900. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  11901. // switch the global references to those of this sector
  11902. this._switchToFrozenSector(sector);
  11903. var args = Array.prototype.splice.call(arguments, 1);
  11904. if (args.length > 1) {
  11905. this[runFunction](args[0],args[1]);
  11906. }
  11907. else {
  11908. this[runFunction](argument);
  11909. }
  11910. }
  11911. }
  11912. }
  11913. this._loadLatestSector();
  11914. },
  11915. /**
  11916. * This runs a function in all sectors. This is used in the _redraw().
  11917. *
  11918. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11919. * | we don't pass the function itself because then the "this" is the window object
  11920. * | instead of the Graph object
  11921. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11922. * @private
  11923. */
  11924. _doInAllSectors : function(runFunction,argument) {
  11925. var args = Array.prototype.splice.call(arguments, 1);
  11926. if (argument === undefined) {
  11927. this._doInAllActiveSectors(runFunction);
  11928. this._doInAllFrozenSectors(runFunction);
  11929. }
  11930. else {
  11931. if (args.length > 1) {
  11932. this._doInAllActiveSectors(runFunction,args[0],args[1]);
  11933. this._doInAllFrozenSectors(runFunction,args[0],args[1]);
  11934. }
  11935. else {
  11936. this._doInAllActiveSectors(runFunction,argument);
  11937. this._doInAllFrozenSectors(runFunction,argument);
  11938. }
  11939. }
  11940. },
  11941. /**
  11942. * This clears the nodeIndices list. We cannot use this.nodeIndices = [] because we would break the link with the
  11943. * active sector. Thus we clear the nodeIndices in the active sector, then reconnect the this.nodeIndices to it.
  11944. *
  11945. * @private
  11946. */
  11947. _clearNodeIndexList : function() {
  11948. var sector = this._sector();
  11949. this.sectors["active"][sector]["nodeIndices"] = [];
  11950. this.nodeIndices = this.sectors["active"][sector]["nodeIndices"];
  11951. },
  11952. /**
  11953. * Draw the encompassing sector node
  11954. *
  11955. * @param ctx
  11956. * @param sectorType
  11957. * @private
  11958. */
  11959. _drawSectorNodes : function(ctx,sectorType) {
  11960. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  11961. for (var sector in this.sectors[sectorType]) {
  11962. if (this.sectors[sectorType].hasOwnProperty(sector)) {
  11963. if (this.sectors[sectorType][sector]["drawingNode"] !== undefined) {
  11964. this._switchToSector(sector,sectorType);
  11965. minY = 1e9; maxY = -1e9; minX = 1e9; maxX = -1e9;
  11966. for (var nodeId in this.nodes) {
  11967. if (this.nodes.hasOwnProperty(nodeId)) {
  11968. node = this.nodes[nodeId];
  11969. node.resize(ctx);
  11970. if (minX > node.x - 0.5 * node.width) {minX = node.x - 0.5 * node.width;}
  11971. if (maxX < node.x + 0.5 * node.width) {maxX = node.x + 0.5 * node.width;}
  11972. if (minY > node.y - 0.5 * node.height) {minY = node.y - 0.5 * node.height;}
  11973. if (maxY < node.y + 0.5 * node.height) {maxY = node.y + 0.5 * node.height;}
  11974. }
  11975. }
  11976. node = this.sectors[sectorType][sector]["drawingNode"];
  11977. node.x = 0.5 * (maxX + minX);
  11978. node.y = 0.5 * (maxY + minY);
  11979. node.width = 2 * (node.x - minX);
  11980. node.height = 2 * (node.y - minY);
  11981. node.radius = Math.sqrt(Math.pow(0.5*node.width,2) + Math.pow(0.5*node.height,2));
  11982. node.setScale(this.scale);
  11983. node._drawCircle(ctx);
  11984. }
  11985. }
  11986. }
  11987. },
  11988. _drawAllSectorNodes : function(ctx) {
  11989. this._drawSectorNodes(ctx,"frozen");
  11990. this._drawSectorNodes(ctx,"active");
  11991. this._loadLatestSector();
  11992. }
  11993. };
  11994. /**
  11995. * Creation of the ClusterMixin var.
  11996. *
  11997. * This contains all the functions the Graph object can use to employ clustering
  11998. *
  11999. * Alex de Mulder
  12000. * 21-01-2013
  12001. */
  12002. var ClusterMixin = {
  12003. /**
  12004. * This is only called in the constructor of the graph object
  12005. *
  12006. */
  12007. startWithClustering : function() {
  12008. // cluster if the data set is big
  12009. this.clusterToFit(this.constants.clustering.initialMaxNodes, true);
  12010. // updates the lables after clustering
  12011. this.updateLabels();
  12012. // this is called here because if clusterin is disabled, the start and stabilize are called in
  12013. // the setData function.
  12014. if (this.stabilize) {
  12015. this._stabilize();
  12016. }
  12017. this.start();
  12018. },
  12019. /**
  12020. * This function clusters until the initialMaxNodes has been reached
  12021. *
  12022. * @param {Number} maxNumberOfNodes
  12023. * @param {Boolean} reposition
  12024. */
  12025. clusterToFit : function(maxNumberOfNodes, reposition) {
  12026. var numberOfNodes = this.nodeIndices.length;
  12027. var maxLevels = 50;
  12028. var level = 0;
  12029. // we first cluster the hubs, then we pull in the outliers, repeat
  12030. while (numberOfNodes > maxNumberOfNodes && level < maxLevels) {
  12031. if (level % 3 == 0) {
  12032. this.forceAggregateHubs(true);
  12033. this.normalizeClusterLevels();
  12034. }
  12035. else {
  12036. this.increaseClusterLevel(); // this also includes a cluster normalization
  12037. }
  12038. numberOfNodes = this.nodeIndices.length;
  12039. level += 1;
  12040. }
  12041. // after the clustering we reposition the nodes to reduce the initial chaos
  12042. if (level > 0 && reposition == true) {
  12043. this.repositionNodes();
  12044. }
  12045. this._updateCalculationNodes();
  12046. },
  12047. /**
  12048. * This function can be called to open up a specific cluster. It is only called by
  12049. * It will unpack the cluster back one level.
  12050. *
  12051. * @param node | Node object: cluster to open.
  12052. */
  12053. openCluster : function(node) {
  12054. var isMovingBeforeClustering = this.moving;
  12055. if (node.clusterSize > this.constants.clustering.sectorThreshold && this._nodeInActiveArea(node) &&
  12056. !(this._sector() == "default" && this.nodeIndices.length == 1)) {
  12057. // this loads a new sector, loads the nodes and edges and nodeIndices of it.
  12058. this._addSector(node);
  12059. var level = 0;
  12060. // we decluster until we reach a decent number of nodes
  12061. while ((this.nodeIndices.length < this.constants.clustering.initialMaxNodes) && (level < 10)) {
  12062. this.decreaseClusterLevel();
  12063. level += 1;
  12064. }
  12065. }
  12066. else {
  12067. this._expandClusterNode(node,false,true);
  12068. // update the index list, dynamic edges and labels
  12069. this._updateNodeIndexList();
  12070. this._updateDynamicEdges();
  12071. this._updateCalculationNodes();
  12072. this.updateLabels();
  12073. }
  12074. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  12075. if (this.moving != isMovingBeforeClustering) {
  12076. this.start();
  12077. }
  12078. },
  12079. /**
  12080. * This calls the updateClustes with default arguments
  12081. */
  12082. updateClustersDefault : function() {
  12083. if (this.constants.clustering.enabled == true) {
  12084. this.updateClusters(0,false,false);
  12085. }
  12086. },
  12087. /**
  12088. * This function can be called to increase the cluster level. This means that the nodes with only one edge connection will
  12089. * be clustered with their connected node. This can be repeated as many times as needed.
  12090. * This can be called externally (by a keybind for instance) to reduce the complexity of big datasets.
  12091. */
  12092. increaseClusterLevel : function() {
  12093. this.updateClusters(-1,false,true);
  12094. },
  12095. /**
  12096. * This function can be called to decrease the cluster level. This means that the nodes with only one edge connection will
  12097. * be unpacked if they are a cluster. This can be repeated as many times as needed.
  12098. * This can be called externally (by a key-bind for instance) to look into clusters without zooming.
  12099. */
  12100. decreaseClusterLevel : function() {
  12101. this.updateClusters(1,false,true);
  12102. },
  12103. /**
  12104. * This is the main clustering function. It clusters and declusters on zoom or forced
  12105. * This function clusters on zoom, it can be called with a predefined zoom direction
  12106. * If out, check if we can form clusters, if in, check if we can open clusters.
  12107. * This function is only called from _zoom()
  12108. *
  12109. * @param {Number} zoomDirection | -1 / 0 / +1 for zoomOut / determineByZoom / zoomIn
  12110. * @param {Boolean} recursive | enabled or disable recursive calling of the opening of clusters
  12111. * @param {Boolean} force | enabled or disable forcing
  12112. * @param {Boolean} doNotStart | if true do not call start
  12113. *
  12114. */
  12115. updateClusters : function(zoomDirection,recursive,force,doNotStart) {
  12116. var isMovingBeforeClustering = this.moving;
  12117. var amountOfNodes = this.nodeIndices.length;
  12118. // on zoom out collapse the sector if the scale is at the level the sector was made
  12119. if (this.previousScale > this.scale && zoomDirection == 0) {
  12120. this._collapseSector();
  12121. }
  12122. // check if we zoom in or out
  12123. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  12124. // forming clusters when forced pulls outliers in. When not forced, the edge length of the
  12125. // outer nodes determines if it is being clustered
  12126. this._formClusters(force);
  12127. }
  12128. else if (this.previousScale < this.scale || zoomDirection == 1) { // zoom in
  12129. if (force == true) {
  12130. // _openClusters checks for each node if the formationScale of the cluster is smaller than
  12131. // the current scale and if so, declusters. When forced, all clusters are reduced by one step
  12132. this._openClusters(recursive,force);
  12133. }
  12134. else {
  12135. // if a cluster takes up a set percentage of the active window
  12136. this._openClustersBySize();
  12137. }
  12138. }
  12139. this._updateNodeIndexList();
  12140. // if a cluster was NOT formed and the user zoomed out, we try clustering by hubs
  12141. if (this.nodeIndices.length == amountOfNodes && (this.previousScale > this.scale || zoomDirection == -1)) {
  12142. this._aggregateHubs(force);
  12143. this._updateNodeIndexList();
  12144. }
  12145. // we now reduce chains.
  12146. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  12147. this.handleChains();
  12148. this._updateNodeIndexList();
  12149. }
  12150. this.previousScale = this.scale;
  12151. // rest of the update the index list, dynamic edges and labels
  12152. this._updateDynamicEdges();
  12153. this.updateLabels();
  12154. // if a cluster was formed, we increase the clusterSession
  12155. if (this.nodeIndices.length < amountOfNodes) { // this means a clustering operation has taken place
  12156. this.clusterSession += 1;
  12157. // if clusters have been made, we normalize the cluster level
  12158. this.normalizeClusterLevels();
  12159. }
  12160. if (doNotStart == false || doNotStart === undefined) {
  12161. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  12162. if (this.moving != isMovingBeforeClustering) {
  12163. this.start();
  12164. }
  12165. }
  12166. this._updateCalculationNodes();
  12167. },
  12168. /**
  12169. * This function handles the chains. It is called on every updateClusters().
  12170. */
  12171. handleChains : function() {
  12172. // after clustering we check how many chains there are
  12173. var chainPercentage = this._getChainFraction();
  12174. if (chainPercentage > this.constants.clustering.chainThreshold) {
  12175. this._reduceAmountOfChains(1 - this.constants.clustering.chainThreshold / chainPercentage)
  12176. }
  12177. },
  12178. /**
  12179. * this functions starts clustering by hubs
  12180. * The minimum hub threshold is set globally
  12181. *
  12182. * @private
  12183. */
  12184. _aggregateHubs : function(force) {
  12185. this._getHubSize();
  12186. this._formClustersByHub(force,false);
  12187. },
  12188. /**
  12189. * This function is fired by keypress. It forces hubs to form.
  12190. *
  12191. */
  12192. forceAggregateHubs : function(doNotStart) {
  12193. var isMovingBeforeClustering = this.moving;
  12194. var amountOfNodes = this.nodeIndices.length;
  12195. this._aggregateHubs(true);
  12196. // update the index list, dynamic edges and labels
  12197. this._updateNodeIndexList();
  12198. this._updateDynamicEdges();
  12199. this.updateLabels();
  12200. // if a cluster was formed, we increase the clusterSession
  12201. if (this.nodeIndices.length != amountOfNodes) {
  12202. this.clusterSession += 1;
  12203. }
  12204. if (doNotStart == false || doNotStart === undefined) {
  12205. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  12206. if (this.moving != isMovingBeforeClustering) {
  12207. this.start();
  12208. }
  12209. }
  12210. },
  12211. /**
  12212. * If a cluster takes up more than a set percentage of the screen, open the cluster
  12213. *
  12214. * @private
  12215. */
  12216. _openClustersBySize : function() {
  12217. for (var nodeId in this.nodes) {
  12218. if (this.nodes.hasOwnProperty(nodeId)) {
  12219. var node = this.nodes[nodeId];
  12220. if (node.inView() == true) {
  12221. if ((node.width*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  12222. (node.height*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  12223. this.openCluster(node);
  12224. }
  12225. }
  12226. }
  12227. }
  12228. },
  12229. /**
  12230. * This function loops over all nodes in the nodeIndices list. For each node it checks if it is a cluster and if it
  12231. * has to be opened based on the current zoom level.
  12232. *
  12233. * @private
  12234. */
  12235. _openClusters : function(recursive,force) {
  12236. for (var i = 0; i < this.nodeIndices.length; i++) {
  12237. var node = this.nodes[this.nodeIndices[i]];
  12238. this._expandClusterNode(node,recursive,force);
  12239. this._updateCalculationNodes();
  12240. }
  12241. },
  12242. /**
  12243. * This function checks if a node has to be opened. This is done by checking the zoom level.
  12244. * If the node contains child nodes, this function is recursively called on the child nodes as well.
  12245. * This recursive behaviour is optional and can be set by the recursive argument.
  12246. *
  12247. * @param {Node} parentNode | to check for cluster and expand
  12248. * @param {Boolean} recursive | enabled or disable recursive calling
  12249. * @param {Boolean} force | enabled or disable forcing
  12250. * @param {Boolean} [openAll] | This will recursively force all nodes in the parent to be released
  12251. * @private
  12252. */
  12253. _expandClusterNode : function(parentNode, recursive, force, openAll) {
  12254. // first check if node is a cluster
  12255. if (parentNode.clusterSize > 1) {
  12256. // this means that on a double tap event or a zoom event, the cluster fully unpacks if it is smaller than 20
  12257. if (parentNode.clusterSize < this.constants.clustering.sectorThreshold) {
  12258. openAll = true;
  12259. }
  12260. recursive = openAll ? true : recursive;
  12261. // if the last child has been added on a smaller scale than current scale decluster
  12262. if (parentNode.formationScale < this.scale || force == true) {
  12263. // we will check if any of the contained child nodes should be removed from the cluster
  12264. for (var containedNodeId in parentNode.containedNodes) {
  12265. if (parentNode.containedNodes.hasOwnProperty(containedNodeId)) {
  12266. var childNode = parentNode.containedNodes[containedNodeId];
  12267. // force expand will expand the largest cluster size clusters. Since we cluster from outside in, we assume that
  12268. // the largest cluster is the one that comes from outside
  12269. if (force == true) {
  12270. if (childNode.clusterSession == parentNode.clusterSessions[parentNode.clusterSessions.length-1]
  12271. || openAll) {
  12272. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  12273. }
  12274. }
  12275. else {
  12276. if (this._nodeInActiveArea(parentNode)) {
  12277. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  12278. }
  12279. }
  12280. }
  12281. }
  12282. }
  12283. }
  12284. },
  12285. /**
  12286. * ONLY CALLED FROM _expandClusterNode
  12287. *
  12288. * This function will expel a child_node from a parent_node. This is to de-cluster the node. This function will remove
  12289. * the child node from the parent contained_node object and put it back into the global nodes object.
  12290. * The same holds for the edge that was connected to the child node. It is moved back into the global edges object.
  12291. *
  12292. * @param {Node} parentNode | the parent node
  12293. * @param {String} containedNodeId | child_node id as it is contained in the containedNodes object of the parent node
  12294. * @param {Boolean} recursive | This will also check if the child needs to be expanded.
  12295. * With force and recursive both true, the entire cluster is unpacked
  12296. * @param {Boolean} force | This will disregard the zoom level and will expel this child from the parent
  12297. * @param {Boolean} openAll | This will recursively force all nodes in the parent to be released
  12298. * @private
  12299. */
  12300. _expelChildFromParent : function(parentNode, containedNodeId, recursive, force, openAll) {
  12301. var childNode = parentNode.containedNodes[containedNodeId];
  12302. // if child node has been added on smaller scale than current, kick out
  12303. if (childNode.formationScale < this.scale || force == true) {
  12304. // unselect all selected items
  12305. this._unselectAll();
  12306. // put the child node back in the global nodes object
  12307. this.nodes[containedNodeId] = childNode;
  12308. // release the contained edges from this childNode back into the global edges
  12309. this._releaseContainedEdges(parentNode,childNode);
  12310. // reconnect rerouted edges to the childNode
  12311. this._connectEdgeBackToChild(parentNode,childNode);
  12312. // validate all edges in dynamicEdges
  12313. this._validateEdges(parentNode);
  12314. // undo the changes from the clustering operation on the parent node
  12315. parentNode.mass -= childNode.mass;
  12316. parentNode.clusterSize -= childNode.clusterSize;
  12317. parentNode.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize);
  12318. parentNode.dynamicEdgesLength = parentNode.dynamicEdges.length;
  12319. // place the child node near the parent, not at the exact same location to avoid chaos in the system
  12320. childNode.x = parentNode.x + parentNode.growthIndicator * (0.5 - Math.random());
  12321. childNode.y = parentNode.y + parentNode.growthIndicator * (0.5 - Math.random());
  12322. // remove node from the list
  12323. delete parentNode.containedNodes[containedNodeId];
  12324. // check if there are other childs with this clusterSession in the parent.
  12325. var othersPresent = false;
  12326. for (var childNodeId in parentNode.containedNodes) {
  12327. if (parentNode.containedNodes.hasOwnProperty(childNodeId)) {
  12328. if (parentNode.containedNodes[childNodeId].clusterSession == childNode.clusterSession) {
  12329. othersPresent = true;
  12330. break;
  12331. }
  12332. }
  12333. }
  12334. // if there are no others, remove the cluster session from the list
  12335. if (othersPresent == false) {
  12336. parentNode.clusterSessions.pop();
  12337. }
  12338. this._repositionBezierNodes(childNode);
  12339. // this._repositionBezierNodes(parentNode);
  12340. // remove the clusterSession from the child node
  12341. childNode.clusterSession = 0;
  12342. // recalculate the size of the node on the next time the node is rendered
  12343. parentNode.clearSizeCache();
  12344. // restart the simulation to reorganise all nodes
  12345. this.moving = true;
  12346. }
  12347. // check if a further expansion step is possible if recursivity is enabled
  12348. if (recursive == true) {
  12349. this._expandClusterNode(childNode,recursive,force,openAll);
  12350. }
  12351. },
  12352. /**
  12353. * position the bezier nodes at the center of the edges
  12354. *
  12355. * @param node
  12356. * @private
  12357. */
  12358. _repositionBezierNodes : function(node) {
  12359. for (var i = 0; i < node.dynamicEdges.length; i++) {
  12360. node.dynamicEdges[i].positionBezierNode();
  12361. }
  12362. },
  12363. /**
  12364. * This function checks if any nodes at the end of their trees have edges below a threshold length
  12365. * This function is called only from updateClusters()
  12366. * forceLevelCollapse ignores the length of the edge and collapses one level
  12367. * This means that a node with only one edge will be clustered with its connected node
  12368. *
  12369. * @private
  12370. * @param {Boolean} force
  12371. */
  12372. _formClusters : function(force) {
  12373. if (force == false) {
  12374. this._formClustersByZoom();
  12375. }
  12376. else {
  12377. this._forceClustersByZoom();
  12378. }
  12379. },
  12380. /**
  12381. * This function handles the clustering by zooming out, this is based on a minimum edge distance
  12382. *
  12383. * @private
  12384. */
  12385. _formClustersByZoom : function() {
  12386. var dx,dy,length,
  12387. minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  12388. // check if any edges are shorter than minLength and start the clustering
  12389. // the clustering favours the node with the larger mass
  12390. for (var edgeId in this.edges) {
  12391. if (this.edges.hasOwnProperty(edgeId)) {
  12392. var edge = this.edges[edgeId];
  12393. if (edge.connected) {
  12394. if (edge.toId != edge.fromId) {
  12395. dx = (edge.to.x - edge.from.x);
  12396. dy = (edge.to.y - edge.from.y);
  12397. length = Math.sqrt(dx * dx + dy * dy);
  12398. if (length < minLength) {
  12399. // first check which node is larger
  12400. var parentNode = edge.from;
  12401. var childNode = edge.to;
  12402. if (edge.to.mass > edge.from.mass) {
  12403. parentNode = edge.to;
  12404. childNode = edge.from;
  12405. }
  12406. if (childNode.dynamicEdgesLength == 1) {
  12407. this._addToCluster(parentNode,childNode,false);
  12408. }
  12409. else if (parentNode.dynamicEdgesLength == 1) {
  12410. this._addToCluster(childNode,parentNode,false);
  12411. }
  12412. }
  12413. }
  12414. }
  12415. }
  12416. }
  12417. },
  12418. /**
  12419. * This function forces the graph to cluster all nodes with only one connecting edge to their
  12420. * connected node.
  12421. *
  12422. * @private
  12423. */
  12424. _forceClustersByZoom : function() {
  12425. for (var nodeId in this.nodes) {
  12426. // another node could have absorbed this child.
  12427. if (this.nodes.hasOwnProperty(nodeId)) {
  12428. var childNode = this.nodes[nodeId];
  12429. // the edges can be swallowed by another decrease
  12430. if (childNode.dynamicEdgesLength == 1 && childNode.dynamicEdges.length != 0) {
  12431. var edge = childNode.dynamicEdges[0];
  12432. var parentNode = (edge.toId == childNode.id) ? this.nodes[edge.fromId] : this.nodes[edge.toId];
  12433. // group to the largest node
  12434. if (childNode.id != parentNode.id) {
  12435. if (parentNode.mass > childNode.mass) {
  12436. this._addToCluster(parentNode,childNode,true);
  12437. }
  12438. else {
  12439. this._addToCluster(childNode,parentNode,true);
  12440. }
  12441. }
  12442. }
  12443. }
  12444. }
  12445. },
  12446. /**
  12447. * To keep the nodes of roughly equal size we normalize the cluster levels.
  12448. * This function clusters a node to its smallest connected neighbour.
  12449. *
  12450. * @param node
  12451. * @private
  12452. */
  12453. _clusterToSmallestNeighbour : function(node) {
  12454. var smallestNeighbour = -1;
  12455. var smallestNeighbourNode = null;
  12456. for (var i = 0; i < node.dynamicEdges.length; i++) {
  12457. if (node.dynamicEdges[i] !== undefined) {
  12458. var neighbour = null;
  12459. if (node.dynamicEdges[i].fromId != node.id) {
  12460. neighbour = node.dynamicEdges[i].from;
  12461. }
  12462. else if (node.dynamicEdges[i].toId != node.id) {
  12463. neighbour = node.dynamicEdges[i].to;
  12464. }
  12465. if (neighbour != null && smallestNeighbour > neighbour.clusterSessions.length) {
  12466. smallestNeighbour = neighbour.clusterSessions.length;
  12467. smallestNeighbourNode = neighbour;
  12468. }
  12469. }
  12470. }
  12471. if (neighbour != null && this.nodes[neighbour.id] !== undefined) {
  12472. this._addToCluster(neighbour, node, true);
  12473. }
  12474. },
  12475. /**
  12476. * This function forms clusters from hubs, it loops over all nodes
  12477. *
  12478. * @param {Boolean} force | Disregard zoom level
  12479. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  12480. * @private
  12481. */
  12482. _formClustersByHub : function(force, onlyEqual) {
  12483. // we loop over all nodes in the list
  12484. for (var nodeId in this.nodes) {
  12485. // we check if it is still available since it can be used by the clustering in this loop
  12486. if (this.nodes.hasOwnProperty(nodeId)) {
  12487. this._formClusterFromHub(this.nodes[nodeId],force,onlyEqual);
  12488. }
  12489. }
  12490. },
  12491. /**
  12492. * This function forms a cluster from a specific preselected hub node
  12493. *
  12494. * @param {Node} hubNode | the node we will cluster as a hub
  12495. * @param {Boolean} force | Disregard zoom level
  12496. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  12497. * @param {Number} [absorptionSizeOffset] |
  12498. * @private
  12499. */
  12500. _formClusterFromHub : function(hubNode, force, onlyEqual, absorptionSizeOffset) {
  12501. if (absorptionSizeOffset === undefined) {
  12502. absorptionSizeOffset = 0;
  12503. }
  12504. // we decide if the node is a hub
  12505. if ((hubNode.dynamicEdgesLength >= this.hubThreshold && onlyEqual == false) ||
  12506. (hubNode.dynamicEdgesLength == this.hubThreshold && onlyEqual == true)) {
  12507. // initialize variables
  12508. var dx,dy,length;
  12509. var minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  12510. var allowCluster = false;
  12511. // we create a list of edges because the dynamicEdges change over the course of this loop
  12512. var edgesIdarray = [];
  12513. var amountOfInitialEdges = hubNode.dynamicEdges.length;
  12514. for (var j = 0; j < amountOfInitialEdges; j++) {
  12515. edgesIdarray.push(hubNode.dynamicEdges[j].id);
  12516. }
  12517. // if the hub clustering is not forces, we check if one of the edges connected
  12518. // to a cluster is small enough based on the constants.clustering.clusterEdgeThreshold
  12519. if (force == false) {
  12520. allowCluster = false;
  12521. for (j = 0; j < amountOfInitialEdges; j++) {
  12522. var edge = this.edges[edgesIdarray[j]];
  12523. if (edge !== undefined) {
  12524. if (edge.connected) {
  12525. if (edge.toId != edge.fromId) {
  12526. dx = (edge.to.x - edge.from.x);
  12527. dy = (edge.to.y - edge.from.y);
  12528. length = Math.sqrt(dx * dx + dy * dy);
  12529. if (length < minLength) {
  12530. allowCluster = true;
  12531. break;
  12532. }
  12533. }
  12534. }
  12535. }
  12536. }
  12537. }
  12538. // start the clustering if allowed
  12539. if ((!force && allowCluster) || force) {
  12540. // we loop over all edges INITIALLY connected to this hub
  12541. for (j = 0; j < amountOfInitialEdges; j++) {
  12542. edge = this.edges[edgesIdarray[j]];
  12543. // the edge can be clustered by this function in a previous loop
  12544. if (edge !== undefined) {
  12545. var childNode = this.nodes[(edge.fromId == hubNode.id) ? edge.toId : edge.fromId];
  12546. // we do not want hubs to merge with other hubs nor do we want to cluster itself.
  12547. if ((childNode.dynamicEdges.length <= (this.hubThreshold + absorptionSizeOffset)) &&
  12548. (childNode.id != hubNode.id)) {
  12549. this._addToCluster(hubNode,childNode,force);
  12550. }
  12551. }
  12552. }
  12553. }
  12554. }
  12555. },
  12556. /**
  12557. * This function adds the child node to the parent node, creating a cluster if it is not already.
  12558. *
  12559. * @param {Node} parentNode | this is the node that will house the child node
  12560. * @param {Node} childNode | this node will be deleted from the global this.nodes and stored in the parent node
  12561. * @param {Boolean} force | true will only update the remainingEdges at the very end of the clustering, ensuring single level collapse
  12562. * @private
  12563. */
  12564. _addToCluster : function(parentNode, childNode, force) {
  12565. // join child node in the parent node
  12566. parentNode.containedNodes[childNode.id] = childNode;
  12567. // manage all the edges connected to the child and parent nodes
  12568. for (var i = 0; i < childNode.dynamicEdges.length; i++) {
  12569. var edge = childNode.dynamicEdges[i];
  12570. if (edge.toId == parentNode.id || edge.fromId == parentNode.id) { // edge connected to parentNode
  12571. this._addToContainedEdges(parentNode,childNode,edge);
  12572. }
  12573. else {
  12574. this._connectEdgeToCluster(parentNode,childNode,edge);
  12575. }
  12576. }
  12577. // a contained node has no dynamic edges.
  12578. childNode.dynamicEdges = [];
  12579. // remove circular edges from clusters
  12580. this._containCircularEdgesFromNode(parentNode,childNode);
  12581. // remove the childNode from the global nodes object
  12582. delete this.nodes[childNode.id];
  12583. // update the properties of the child and parent
  12584. var massBefore = parentNode.mass;
  12585. childNode.clusterSession = this.clusterSession;
  12586. parentNode.mass += childNode.mass;
  12587. parentNode.clusterSize += childNode.clusterSize;
  12588. parentNode.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize);
  12589. // keep track of the clustersessions so we can open the cluster up as it has been formed.
  12590. if (parentNode.clusterSessions[parentNode.clusterSessions.length - 1] != this.clusterSession) {
  12591. parentNode.clusterSessions.push(this.clusterSession);
  12592. }
  12593. // forced clusters only open from screen size and double tap
  12594. if (force == true) {
  12595. // parentNode.formationScale = Math.pow(1 - (1.0/11.0),this.clusterSession+3);
  12596. parentNode.formationScale = 0;
  12597. }
  12598. else {
  12599. parentNode.formationScale = this.scale; // The latest child has been added on this scale
  12600. }
  12601. // recalculate the size of the node on the next time the node is rendered
  12602. parentNode.clearSizeCache();
  12603. // set the pop-out scale for the childnode
  12604. parentNode.containedNodes[childNode.id].formationScale = parentNode.formationScale;
  12605. // nullify the movement velocity of the child, this is to avoid hectic behaviour
  12606. childNode.clearVelocity();
  12607. // the mass has altered, preservation of energy dictates the velocity to be updated
  12608. parentNode.updateVelocity(massBefore);
  12609. // restart the simulation to reorganise all nodes
  12610. this.moving = true;
  12611. },
  12612. /**
  12613. * This function will apply the changes made to the remainingEdges during the formation of the clusters.
  12614. * This is a seperate function to allow for level-wise collapsing of the node barnesHutTree.
  12615. * It has to be called if a level is collapsed. It is called by _formClusters().
  12616. * @private
  12617. */
  12618. _updateDynamicEdges : function() {
  12619. for (var i = 0; i < this.nodeIndices.length; i++) {
  12620. var node = this.nodes[this.nodeIndices[i]];
  12621. node.dynamicEdgesLength = node.dynamicEdges.length;
  12622. // this corrects for multiple edges pointing at the same other node
  12623. var correction = 0;
  12624. if (node.dynamicEdgesLength > 1) {
  12625. for (var j = 0; j < node.dynamicEdgesLength - 1; j++) {
  12626. var edgeToId = node.dynamicEdges[j].toId;
  12627. var edgeFromId = node.dynamicEdges[j].fromId;
  12628. for (var k = j+1; k < node.dynamicEdgesLength; k++) {
  12629. if ((node.dynamicEdges[k].toId == edgeToId && node.dynamicEdges[k].fromId == edgeFromId) ||
  12630. (node.dynamicEdges[k].fromId == edgeToId && node.dynamicEdges[k].toId == edgeFromId)) {
  12631. correction += 1;
  12632. }
  12633. }
  12634. }
  12635. }
  12636. node.dynamicEdgesLength -= correction;
  12637. }
  12638. },
  12639. /**
  12640. * This adds an edge from the childNode to the contained edges of the parent node
  12641. *
  12642. * @param parentNode | Node object
  12643. * @param childNode | Node object
  12644. * @param edge | Edge object
  12645. * @private
  12646. */
  12647. _addToContainedEdges : function(parentNode, childNode, edge) {
  12648. // create an array object if it does not yet exist for this childNode
  12649. if (!(parentNode.containedEdges.hasOwnProperty(childNode.id))) {
  12650. parentNode.containedEdges[childNode.id] = []
  12651. }
  12652. // add this edge to the list
  12653. parentNode.containedEdges[childNode.id].push(edge);
  12654. // remove the edge from the global edges object
  12655. delete this.edges[edge.id];
  12656. // remove the edge from the parent object
  12657. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12658. if (parentNode.dynamicEdges[i].id == edge.id) {
  12659. parentNode.dynamicEdges.splice(i,1);
  12660. break;
  12661. }
  12662. }
  12663. },
  12664. /**
  12665. * This function connects an edge that was connected to a child node to the parent node.
  12666. * It keeps track of which nodes it has been connected to with the originalId array.
  12667. *
  12668. * @param {Node} parentNode | Node object
  12669. * @param {Node} childNode | Node object
  12670. * @param {Edge} edge | Edge object
  12671. * @private
  12672. */
  12673. _connectEdgeToCluster : function(parentNode, childNode, edge) {
  12674. // handle circular edges
  12675. if (edge.toId == edge.fromId) {
  12676. this._addToContainedEdges(parentNode, childNode, edge);
  12677. }
  12678. else {
  12679. if (edge.toId == childNode.id) { // edge connected to other node on the "to" side
  12680. edge.originalToId.push(childNode.id);
  12681. edge.to = parentNode;
  12682. edge.toId = parentNode.id;
  12683. }
  12684. else { // edge connected to other node with the "from" side
  12685. edge.originalFromId.push(childNode.id);
  12686. edge.from = parentNode;
  12687. edge.fromId = parentNode.id;
  12688. }
  12689. this._addToReroutedEdges(parentNode,childNode,edge);
  12690. }
  12691. },
  12692. /**
  12693. * If a node is connected to itself, a circular edge is drawn. When clustering we want to contain
  12694. * these edges inside of the cluster.
  12695. *
  12696. * @param parentNode
  12697. * @param childNode
  12698. * @private
  12699. */
  12700. _containCircularEdgesFromNode : function(parentNode, childNode) {
  12701. // manage all the edges connected to the child and parent nodes
  12702. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12703. var edge = parentNode.dynamicEdges[i];
  12704. // handle circular edges
  12705. if (edge.toId == edge.fromId) {
  12706. this._addToContainedEdges(parentNode, childNode, edge);
  12707. }
  12708. }
  12709. },
  12710. /**
  12711. * This adds an edge from the childNode to the rerouted edges of the parent node
  12712. *
  12713. * @param parentNode | Node object
  12714. * @param childNode | Node object
  12715. * @param edge | Edge object
  12716. * @private
  12717. */
  12718. _addToReroutedEdges : function(parentNode, childNode, edge) {
  12719. // create an array object if it does not yet exist for this childNode
  12720. // we store the edge in the rerouted edges so we can restore it when the cluster pops open
  12721. if (!(parentNode.reroutedEdges.hasOwnProperty(childNode.id))) {
  12722. parentNode.reroutedEdges[childNode.id] = [];
  12723. }
  12724. parentNode.reroutedEdges[childNode.id].push(edge);
  12725. // this edge becomes part of the dynamicEdges of the cluster node
  12726. parentNode.dynamicEdges.push(edge);
  12727. },
  12728. /**
  12729. * This function connects an edge that was connected to a cluster node back to the child node.
  12730. *
  12731. * @param parentNode | Node object
  12732. * @param childNode | Node object
  12733. * @private
  12734. */
  12735. _connectEdgeBackToChild : function(parentNode, childNode) {
  12736. if (parentNode.reroutedEdges.hasOwnProperty(childNode.id)) {
  12737. for (var i = 0; i < parentNode.reroutedEdges[childNode.id].length; i++) {
  12738. var edge = parentNode.reroutedEdges[childNode.id][i];
  12739. if (edge.originalFromId[edge.originalFromId.length-1] == childNode.id) {
  12740. edge.originalFromId.pop();
  12741. edge.fromId = childNode.id;
  12742. edge.from = childNode;
  12743. }
  12744. else {
  12745. edge.originalToId.pop();
  12746. edge.toId = childNode.id;
  12747. edge.to = childNode;
  12748. }
  12749. // append this edge to the list of edges connecting to the childnode
  12750. childNode.dynamicEdges.push(edge);
  12751. // remove the edge from the parent object
  12752. for (var j = 0; j < parentNode.dynamicEdges.length; j++) {
  12753. if (parentNode.dynamicEdges[j].id == edge.id) {
  12754. parentNode.dynamicEdges.splice(j,1);
  12755. break;
  12756. }
  12757. }
  12758. }
  12759. // remove the entry from the rerouted edges
  12760. delete parentNode.reroutedEdges[childNode.id];
  12761. }
  12762. },
  12763. /**
  12764. * When loops are clustered, an edge can be both in the rerouted array and the contained array.
  12765. * This function is called last to verify that all edges in dynamicEdges are in fact connected to the
  12766. * parentNode
  12767. *
  12768. * @param parentNode | Node object
  12769. * @private
  12770. */
  12771. _validateEdges : function(parentNode) {
  12772. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12773. var edge = parentNode.dynamicEdges[i];
  12774. if (parentNode.id != edge.toId && parentNode.id != edge.fromId) {
  12775. parentNode.dynamicEdges.splice(i,1);
  12776. }
  12777. }
  12778. },
  12779. /**
  12780. * This function released the contained edges back into the global domain and puts them back into the
  12781. * dynamic edges of both parent and child.
  12782. *
  12783. * @param {Node} parentNode |
  12784. * @param {Node} childNode |
  12785. * @private
  12786. */
  12787. _releaseContainedEdges : function(parentNode, childNode) {
  12788. for (var i = 0; i < parentNode.containedEdges[childNode.id].length; i++) {
  12789. var edge = parentNode.containedEdges[childNode.id][i];
  12790. // put the edge back in the global edges object
  12791. this.edges[edge.id] = edge;
  12792. // put the edge back in the dynamic edges of the child and parent
  12793. childNode.dynamicEdges.push(edge);
  12794. parentNode.dynamicEdges.push(edge);
  12795. }
  12796. // remove the entry from the contained edges
  12797. delete parentNode.containedEdges[childNode.id];
  12798. },
  12799. // ------------------- UTILITY FUNCTIONS ---------------------------- //
  12800. /**
  12801. * This updates the node labels for all nodes (for debugging purposes)
  12802. */
  12803. updateLabels : function() {
  12804. var nodeId;
  12805. // update node labels
  12806. for (nodeId in this.nodes) {
  12807. if (this.nodes.hasOwnProperty(nodeId)) {
  12808. var node = this.nodes[nodeId];
  12809. if (node.clusterSize > 1) {
  12810. node.label = "[".concat(String(node.clusterSize),"]");
  12811. }
  12812. }
  12813. }
  12814. // update node labels
  12815. for (nodeId in this.nodes) {
  12816. if (this.nodes.hasOwnProperty(nodeId)) {
  12817. node = this.nodes[nodeId];
  12818. if (node.clusterSize == 1) {
  12819. if (node.originalLabel !== undefined) {
  12820. node.label = node.originalLabel;
  12821. }
  12822. else {
  12823. node.label = String(node.id);
  12824. }
  12825. }
  12826. }
  12827. }
  12828. // /* Debug Override */
  12829. // for (nodeId in this.nodes) {
  12830. // if (this.nodes.hasOwnProperty(nodeId)) {
  12831. // node = this.nodes[nodeId];
  12832. // node.label = String(node.level);
  12833. // }
  12834. // }
  12835. },
  12836. /**
  12837. * We want to keep the cluster level distribution rather small. This means we do not want unclustered nodes
  12838. * if the rest of the nodes are already a few cluster levels in.
  12839. * To fix this we use this function. It determines the min and max cluster level and sends nodes that have not
  12840. * clustered enough to the clusterToSmallestNeighbours function.
  12841. */
  12842. normalizeClusterLevels : function() {
  12843. var maxLevel = 0;
  12844. var minLevel = 1e9;
  12845. var clusterLevel = 0;
  12846. var nodeId;
  12847. // we loop over all nodes in the list
  12848. for (nodeId in this.nodes) {
  12849. if (this.nodes.hasOwnProperty(nodeId)) {
  12850. clusterLevel = this.nodes[nodeId].clusterSessions.length;
  12851. if (maxLevel < clusterLevel) {maxLevel = clusterLevel;}
  12852. if (minLevel > clusterLevel) {minLevel = clusterLevel;}
  12853. }
  12854. }
  12855. if (maxLevel - minLevel > this.constants.clustering.clusterLevelDifference) {
  12856. var amountOfNodes = this.nodeIndices.length;
  12857. var targetLevel = maxLevel - this.constants.clustering.clusterLevelDifference;
  12858. // we loop over all nodes in the list
  12859. for (nodeId in this.nodes) {
  12860. if (this.nodes.hasOwnProperty(nodeId)) {
  12861. if (this.nodes[nodeId].clusterSessions.length < targetLevel) {
  12862. this._clusterToSmallestNeighbour(this.nodes[nodeId]);
  12863. }
  12864. }
  12865. }
  12866. this._updateNodeIndexList();
  12867. this._updateDynamicEdges();
  12868. // if a cluster was formed, we increase the clusterSession
  12869. if (this.nodeIndices.length != amountOfNodes) {
  12870. this.clusterSession += 1;
  12871. }
  12872. }
  12873. },
  12874. /**
  12875. * This function determines if the cluster we want to decluster is in the active area
  12876. * this means around the zoom center
  12877. *
  12878. * @param {Node} node
  12879. * @returns {boolean}
  12880. * @private
  12881. */
  12882. _nodeInActiveArea : function(node) {
  12883. return (
  12884. Math.abs(node.x - this.areaCenter.x) <= this.constants.clustering.activeAreaBoxSize/this.scale
  12885. &&
  12886. Math.abs(node.y - this.areaCenter.y) <= this.constants.clustering.activeAreaBoxSize/this.scale
  12887. )
  12888. },
  12889. /**
  12890. * This is an adaptation of the original repositioning function. This is called if the system is clustered initially
  12891. * It puts large clusters away from the center and randomizes the order.
  12892. *
  12893. */
  12894. repositionNodes : function() {
  12895. for (var i = 0; i < this.nodeIndices.length; i++) {
  12896. var node = this.nodes[this.nodeIndices[i]];
  12897. if ((node.xFixed == false || node.yFixed == false)) {
  12898. var radius = 10 * 0.1*this.nodeIndices.length * Math.min(100,node.mass);
  12899. var angle = 2 * Math.PI * Math.random();
  12900. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  12901. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  12902. this._repositionBezierNodes(node);
  12903. }
  12904. }
  12905. },
  12906. /**
  12907. * We determine how many connections denote an important hub.
  12908. * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%)
  12909. *
  12910. * @private
  12911. */
  12912. _getHubSize : function() {
  12913. var average = 0;
  12914. var averageSquared = 0;
  12915. var hubCounter = 0;
  12916. var largestHub = 0;
  12917. for (var i = 0; i < this.nodeIndices.length; i++) {
  12918. var node = this.nodes[this.nodeIndices[i]];
  12919. if (node.dynamicEdgesLength > largestHub) {
  12920. largestHub = node.dynamicEdgesLength;
  12921. }
  12922. average += node.dynamicEdgesLength;
  12923. averageSquared += Math.pow(node.dynamicEdgesLength,2);
  12924. hubCounter += 1;
  12925. }
  12926. average = average / hubCounter;
  12927. averageSquared = averageSquared / hubCounter;
  12928. var variance = averageSquared - Math.pow(average,2);
  12929. var standardDeviation = Math.sqrt(variance);
  12930. this.hubThreshold = Math.floor(average + 2*standardDeviation);
  12931. // always have at least one to cluster
  12932. if (this.hubThreshold > largestHub) {
  12933. this.hubThreshold = largestHub;
  12934. }
  12935. // console.log("average",average,"averageSQ",averageSquared,"var",variance,"std",standardDeviation);
  12936. // console.log("hubThreshold:",this.hubThreshold);
  12937. },
  12938. /**
  12939. * We reduce the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  12940. * with this amount we can cluster specifically on these chains.
  12941. *
  12942. * @param {Number} fraction | between 0 and 1, the percentage of chains to reduce
  12943. * @private
  12944. */
  12945. _reduceAmountOfChains : function(fraction) {
  12946. this.hubThreshold = 2;
  12947. var reduceAmount = Math.floor(this.nodeIndices.length * fraction);
  12948. for (var nodeId in this.nodes) {
  12949. if (this.nodes.hasOwnProperty(nodeId)) {
  12950. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  12951. if (reduceAmount > 0) {
  12952. this._formClusterFromHub(this.nodes[nodeId],true,true,1);
  12953. reduceAmount -= 1;
  12954. }
  12955. }
  12956. }
  12957. }
  12958. },
  12959. /**
  12960. * We get the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  12961. * with this amount we can cluster specifically on these chains.
  12962. *
  12963. * @private
  12964. */
  12965. _getChainFraction : function() {
  12966. var chains = 0;
  12967. var total = 0;
  12968. for (var nodeId in this.nodes) {
  12969. if (this.nodes.hasOwnProperty(nodeId)) {
  12970. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  12971. chains += 1;
  12972. }
  12973. total += 1;
  12974. }
  12975. }
  12976. return chains/total;
  12977. }
  12978. };
  12979. var SelectionMixin = {
  12980. /**
  12981. * This function can be called from the _doInAllSectors function
  12982. *
  12983. * @param object
  12984. * @param overlappingNodes
  12985. * @private
  12986. */
  12987. _getNodesOverlappingWith : function(object, overlappingNodes) {
  12988. var nodes = this.nodes;
  12989. for (var nodeId in nodes) {
  12990. if (nodes.hasOwnProperty(nodeId)) {
  12991. if (nodes[nodeId].isOverlappingWith(object)) {
  12992. overlappingNodes.push(nodeId);
  12993. }
  12994. }
  12995. }
  12996. },
  12997. /**
  12998. * retrieve all nodes overlapping with given object
  12999. * @param {Object} object An object with parameters left, top, right, bottom
  13000. * @return {Number[]} An array with id's of the overlapping nodes
  13001. * @private
  13002. */
  13003. _getAllNodesOverlappingWith : function (object) {
  13004. var overlappingNodes = [];
  13005. this._doInAllActiveSectors("_getNodesOverlappingWith",object,overlappingNodes);
  13006. return overlappingNodes;
  13007. },
  13008. /**
  13009. * Return a position object in canvasspace from a single point in screenspace
  13010. *
  13011. * @param pointer
  13012. * @returns {{left: number, top: number, right: number, bottom: number}}
  13013. * @private
  13014. */
  13015. _pointerToPositionObject : function(pointer) {
  13016. var x = this._canvasToX(pointer.x);
  13017. var y = this._canvasToY(pointer.y);
  13018. return {left: x,
  13019. top: y,
  13020. right: x,
  13021. bottom: y};
  13022. },
  13023. /**
  13024. * Get the top node at the a specific point (like a click)
  13025. *
  13026. * @param {{x: Number, y: Number}} pointer
  13027. * @return {Node | null} node
  13028. * @private
  13029. */
  13030. _getNodeAt : function (pointer) {
  13031. // we first check if this is an navigation controls element
  13032. var positionObject = this._pointerToPositionObject(pointer);
  13033. var overlappingNodes = this._getAllNodesOverlappingWith(positionObject);
  13034. // if there are overlapping nodes, select the last one, this is the
  13035. // one which is drawn on top of the others
  13036. if (overlappingNodes.length > 0) {
  13037. return this.nodes[overlappingNodes[overlappingNodes.length - 1]];
  13038. }
  13039. else {
  13040. return null;
  13041. }
  13042. },
  13043. /**
  13044. * retrieve all edges overlapping with given object, selector is around center
  13045. * @param {Object} object An object with parameters left, top, right, bottom
  13046. * @return {Number[]} An array with id's of the overlapping nodes
  13047. * @private
  13048. */
  13049. _getEdgesOverlappingWith : function (object, overlappingEdges) {
  13050. var edges = this.edges;
  13051. for (var edgeId in edges) {
  13052. if (edges.hasOwnProperty(edgeId)) {
  13053. if (edges[edgeId].isOverlappingWith(object)) {
  13054. overlappingEdges.push(edgeId);
  13055. }
  13056. }
  13057. }
  13058. },
  13059. /**
  13060. * retrieve all nodes overlapping with given object
  13061. * @param {Object} object An object with parameters left, top, right, bottom
  13062. * @return {Number[]} An array with id's of the overlapping nodes
  13063. * @private
  13064. */
  13065. _getAllEdgesOverlappingWith : function (object) {
  13066. var overlappingEdges = [];
  13067. this._doInAllActiveSectors("_getEdgesOverlappingWith",object,overlappingEdges);
  13068. return overlappingEdges;
  13069. },
  13070. /**
  13071. * Place holder. To implement change the _getNodeAt to a _getObjectAt. Have the _getObjectAt call
  13072. * _getNodeAt and _getEdgesAt, then priortize the selection to user preferences.
  13073. *
  13074. * @param pointer
  13075. * @returns {null}
  13076. * @private
  13077. */
  13078. _getEdgeAt : function(pointer) {
  13079. var positionObject = this._pointerToPositionObject(pointer);
  13080. var overlappingEdges = this._getAllEdgesOverlappingWith(positionObject);
  13081. if (overlappingEdges.length > 0) {
  13082. return this.edges[overlappingEdges[overlappingEdges.length - 1]];
  13083. }
  13084. else {
  13085. return null;
  13086. }
  13087. },
  13088. /**
  13089. * Add object to the selection array.
  13090. *
  13091. * @param obj
  13092. * @private
  13093. */
  13094. _addToSelection : function(obj) {
  13095. if (obj instanceof Node) {
  13096. this.selectionObj.nodes[obj.id] = obj;
  13097. }
  13098. else {
  13099. this.selectionObj.edges[obj.id] = obj;
  13100. }
  13101. },
  13102. /**
  13103. * Remove a single option from selection.
  13104. *
  13105. * @param {Object} obj
  13106. * @private
  13107. */
  13108. _removeFromSelection : function(obj) {
  13109. if (obj instanceof Node) {
  13110. delete this.selectionObj.nodes[obj.id];
  13111. }
  13112. else {
  13113. delete this.selectionObj.edges[obj.id];
  13114. }
  13115. },
  13116. /**
  13117. * Unselect all. The selectionObj is useful for this.
  13118. *
  13119. * @param {Boolean} [doNotTrigger] | ignore trigger
  13120. * @private
  13121. */
  13122. _unselectAll : function(doNotTrigger) {
  13123. if (doNotTrigger === undefined) {
  13124. doNotTrigger = false;
  13125. }
  13126. for(var nodeId in this.selectionObj.nodes) {
  13127. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13128. this.selectionObj.nodes[nodeId].unselect();
  13129. }
  13130. }
  13131. for(var edgeId in this.selectionObj.edges) {
  13132. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13133. this.selectionObj.edges[edgeId].unselect();
  13134. }
  13135. }
  13136. this.selectionObj = {nodes:{},edges:{}};
  13137. if (doNotTrigger == false) {
  13138. this.emit('select', this.getSelection());
  13139. }
  13140. },
  13141. /**
  13142. * Unselect all clusters. The selectionObj is useful for this.
  13143. *
  13144. * @param {Boolean} [doNotTrigger] | ignore trigger
  13145. * @private
  13146. */
  13147. _unselectClusters : function(doNotTrigger) {
  13148. if (doNotTrigger === undefined) {
  13149. doNotTrigger = false;
  13150. }
  13151. for (var nodeId in this.selectionObj.nodes) {
  13152. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13153. if (this.selectionObj.nodes[nodeId].clusterSize > 1) {
  13154. this.selectionObj.nodes[nodeId].unselect();
  13155. this._removeFromSelection(this.selectionObj.nodes[nodeId]);
  13156. }
  13157. }
  13158. }
  13159. if (doNotTrigger == false) {
  13160. this.emit('select', this.getSelection());
  13161. }
  13162. },
  13163. /**
  13164. * return the number of selected nodes
  13165. *
  13166. * @returns {number}
  13167. * @private
  13168. */
  13169. _getSelectedNodeCount : function() {
  13170. var count = 0;
  13171. for (var nodeId in this.selectionObj.nodes) {
  13172. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13173. count += 1;
  13174. }
  13175. }
  13176. return count;
  13177. },
  13178. /**
  13179. * return the number of selected nodes
  13180. *
  13181. * @returns {number}
  13182. * @private
  13183. */
  13184. _getSelectedNode : function() {
  13185. for (var nodeId in this.selectionObj.nodes) {
  13186. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13187. return this.selectionObj.nodes[nodeId];
  13188. }
  13189. }
  13190. return null;
  13191. },
  13192. /**
  13193. * return the number of selected edges
  13194. *
  13195. * @returns {number}
  13196. * @private
  13197. */
  13198. _getSelectedEdgeCount : function() {
  13199. var count = 0;
  13200. for (var edgeId in this.selectionObj.edges) {
  13201. if (this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13202. count += 1;
  13203. }
  13204. }
  13205. return count;
  13206. },
  13207. /**
  13208. * return the number of selected objects.
  13209. *
  13210. * @returns {number}
  13211. * @private
  13212. */
  13213. _getSelectedObjectCount : function() {
  13214. var count = 0;
  13215. for(var nodeId in this.selectionObj.nodes) {
  13216. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13217. count += 1;
  13218. }
  13219. }
  13220. for(var edgeId in this.selectionObj.edges) {
  13221. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13222. count += 1;
  13223. }
  13224. }
  13225. return count;
  13226. },
  13227. /**
  13228. * Check if anything is selected
  13229. *
  13230. * @returns {boolean}
  13231. * @private
  13232. */
  13233. _selectionIsEmpty : function() {
  13234. for(var nodeId in this.selectionObj.nodes) {
  13235. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13236. return false;
  13237. }
  13238. }
  13239. for(var edgeId in this.selectionObj.edges) {
  13240. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13241. return false;
  13242. }
  13243. }
  13244. return true;
  13245. },
  13246. /**
  13247. * check if one of the selected nodes is a cluster.
  13248. *
  13249. * @returns {boolean}
  13250. * @private
  13251. */
  13252. _clusterInSelection : function() {
  13253. for(var nodeId in this.selectionObj.nodes) {
  13254. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13255. if (this.selectionObj.nodes[nodeId].clusterSize > 1) {
  13256. return true;
  13257. }
  13258. }
  13259. }
  13260. return false;
  13261. },
  13262. /**
  13263. * select the edges connected to the node that is being selected
  13264. *
  13265. * @param {Node} node
  13266. * @private
  13267. */
  13268. _selectConnectedEdges : function(node) {
  13269. for (var i = 0; i < node.dynamicEdges.length; i++) {
  13270. var edge = node.dynamicEdges[i];
  13271. edge.select();
  13272. this._addToSelection(edge);
  13273. }
  13274. },
  13275. /**
  13276. * unselect the edges connected to the node that is being selected
  13277. *
  13278. * @param {Node} node
  13279. * @private
  13280. */
  13281. _unselectConnectedEdges : function(node) {
  13282. for (var i = 0; i < node.dynamicEdges.length; i++) {
  13283. var edge = node.dynamicEdges[i];
  13284. edge.unselect();
  13285. this._removeFromSelection(edge);
  13286. }
  13287. },
  13288. /**
  13289. * This is called when someone clicks on a node. either select or deselect it.
  13290. * If there is an existing selection and we don't want to append to it, clear the existing selection
  13291. *
  13292. * @param {Node || Edge} object
  13293. * @param {Boolean} append
  13294. * @param {Boolean} [doNotTrigger] | ignore trigger
  13295. * @private
  13296. */
  13297. _selectObject : function(object, append, doNotTrigger) {
  13298. if (doNotTrigger === undefined) {
  13299. doNotTrigger = false;
  13300. }
  13301. if (this._selectionIsEmpty() == false && append == false && this.forceAppendSelection == false) {
  13302. this._unselectAll(true);
  13303. }
  13304. if (object.selected == false) {
  13305. object.select();
  13306. this._addToSelection(object);
  13307. if (object instanceof Node && this.blockConnectingEdgeSelection == false) {
  13308. this._selectConnectedEdges(object);
  13309. }
  13310. }
  13311. else {
  13312. object.unselect();
  13313. this._removeFromSelection(object);
  13314. }
  13315. if (doNotTrigger == false) {
  13316. this.emit('select', this.getSelection());
  13317. }
  13318. },
  13319. /**
  13320. * handles the selection part of the touch, only for navigation controls elements;
  13321. * Touch is triggered before tap, also before hold. Hold triggers after a while.
  13322. * This is the most responsive solution
  13323. *
  13324. * @param {Object} pointer
  13325. * @private
  13326. */
  13327. _handleTouch : function(pointer) {
  13328. },
  13329. /**
  13330. * handles the selection part of the tap;
  13331. *
  13332. * @param {Object} pointer
  13333. * @private
  13334. */
  13335. _handleTap : function(pointer) {
  13336. var node = this._getNodeAt(pointer);
  13337. if (node != null) {
  13338. this._selectObject(node,false);
  13339. }
  13340. else {
  13341. var edge = this._getEdgeAt(pointer);
  13342. if (edge != null) {
  13343. this._selectObject(edge,false);
  13344. }
  13345. else {
  13346. this._unselectAll();
  13347. }
  13348. }
  13349. this.emit("click", this.getSelection());
  13350. this._redraw();
  13351. },
  13352. /**
  13353. * handles the selection part of the double tap and opens a cluster if needed
  13354. *
  13355. * @param {Object} pointer
  13356. * @private
  13357. */
  13358. _handleDoubleTap : function(pointer) {
  13359. var node = this._getNodeAt(pointer);
  13360. if (node != null && node !== undefined) {
  13361. // we reset the areaCenter here so the opening of the node will occur
  13362. this.areaCenter = {"x" : this._canvasToX(pointer.x),
  13363. "y" : this._canvasToY(pointer.y)};
  13364. this.openCluster(node);
  13365. }
  13366. this.emit("doubleClick", this.getSelection());
  13367. },
  13368. /**
  13369. * Handle the onHold selection part
  13370. *
  13371. * @param pointer
  13372. * @private
  13373. */
  13374. _handleOnHold : function(pointer) {
  13375. var node = this._getNodeAt(pointer);
  13376. if (node != null) {
  13377. this._selectObject(node,true);
  13378. }
  13379. else {
  13380. var edge = this._getEdgeAt(pointer);
  13381. if (edge != null) {
  13382. this._selectObject(edge,true);
  13383. }
  13384. }
  13385. this._redraw();
  13386. },
  13387. /**
  13388. * handle the onRelease event. These functions are here for the navigation controls module.
  13389. *
  13390. * @private
  13391. */
  13392. _handleOnRelease : function(pointer) {
  13393. },
  13394. /**
  13395. *
  13396. * retrieve the currently selected objects
  13397. * @return {Number[] | String[]} selection An array with the ids of the
  13398. * selected nodes.
  13399. */
  13400. getSelection : function() {
  13401. var nodeIds = this.getSelectedNodes();
  13402. var edgeIds = this.getSelectedEdges();
  13403. return {nodes:nodeIds, edges:edgeIds};
  13404. },
  13405. /**
  13406. *
  13407. * retrieve the currently selected nodes
  13408. * @return {String} selection An array with the ids of the
  13409. * selected nodes.
  13410. */
  13411. getSelectedNodes : function() {
  13412. var idArray = [];
  13413. for(var nodeId in this.selectionObj.nodes) {
  13414. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13415. idArray.push(nodeId);
  13416. }
  13417. }
  13418. return idArray
  13419. },
  13420. /**
  13421. *
  13422. * retrieve the currently selected edges
  13423. * @return {Array} selection An array with the ids of the
  13424. * selected nodes.
  13425. */
  13426. getSelectedEdges : function() {
  13427. var idArray = [];
  13428. for(var edgeId in this.selectionObj.edges) {
  13429. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13430. idArray.push(edgeId);
  13431. }
  13432. }
  13433. return idArray;
  13434. },
  13435. /**
  13436. * select zero or more nodes
  13437. * @param {Number[] | String[]} selection An array with the ids of the
  13438. * selected nodes.
  13439. */
  13440. setSelection : function(selection) {
  13441. var i, iMax, id;
  13442. if (!selection || (selection.length == undefined))
  13443. throw 'Selection must be an array with ids';
  13444. // first unselect any selected node
  13445. this._unselectAll(true);
  13446. for (i = 0, iMax = selection.length; i < iMax; i++) {
  13447. id = selection[i];
  13448. var node = this.nodes[id];
  13449. if (!node) {
  13450. throw new RangeError('Node with id "' + id + '" not found');
  13451. }
  13452. this._selectObject(node,true,true);
  13453. }
  13454. this.redraw();
  13455. },
  13456. /**
  13457. * Validate the selection: remove ids of nodes which no longer exist
  13458. * @private
  13459. */
  13460. _updateSelection : function () {
  13461. for(var nodeId in this.selectionObj.nodes) {
  13462. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13463. if (!this.nodes.hasOwnProperty(nodeId)) {
  13464. delete this.selectionObj.nodes[nodeId];
  13465. }
  13466. }
  13467. }
  13468. for(var edgeId in this.selectionObj.edges) {
  13469. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13470. if (!this.edges.hasOwnProperty(edgeId)) {
  13471. delete this.selectionObj.edges[edgeId];
  13472. }
  13473. }
  13474. }
  13475. }
  13476. };
  13477. /**
  13478. * Created by Alex on 1/22/14.
  13479. */
  13480. var NavigationMixin = {
  13481. _cleanNavigation : function() {
  13482. // clean up previosu navigation items
  13483. var wrapper = document.getElementById('graph-navigation_wrapper');
  13484. if (wrapper != null) {
  13485. this.containerElement.removeChild(wrapper);
  13486. }
  13487. document.onmouseup = null;
  13488. },
  13489. /**
  13490. * Creation of the navigation controls nodes. They are drawn over the rest of the nodes and are not affected by scale and translation
  13491. * they have a triggerFunction which is called on click. If the position of the navigation controls is dependent
  13492. * on this.frame.canvas.clientWidth or this.frame.canvas.clientHeight, we flag horizontalAlignLeft and verticalAlignTop false.
  13493. * This means that the location will be corrected by the _relocateNavigation function on a size change of the canvas.
  13494. *
  13495. * @private
  13496. */
  13497. _loadNavigationElements : function() {
  13498. this._cleanNavigation();
  13499. this.navigationDivs = {};
  13500. var navigationDivs = ['up','down','left','right','zoomIn','zoomOut','zoomExtends'];
  13501. var navigationDivActions = ['_moveUp','_moveDown','_moveLeft','_moveRight','_zoomIn','_zoomOut','zoomExtent'];
  13502. this.navigationDivs['wrapper'] = document.createElement('div');
  13503. this.navigationDivs['wrapper'].id = "graph-navigation_wrapper";
  13504. this.navigationDivs['wrapper'].style.position = "absolute";
  13505. this.navigationDivs['wrapper'].style.width = this.frame.canvas.clientWidth + "px";
  13506. this.navigationDivs['wrapper'].style.height = this.frame.canvas.clientHeight + "px";
  13507. this.containerElement.insertBefore(this.navigationDivs['wrapper'],this.frame);
  13508. for (var i = 0; i < navigationDivs.length; i++) {
  13509. this.navigationDivs[navigationDivs[i]] = document.createElement('div');
  13510. this.navigationDivs[navigationDivs[i]].id = "graph-navigation_" + navigationDivs[i];
  13511. this.navigationDivs[navigationDivs[i]].className = "graph-navigation " + navigationDivs[i];
  13512. this.navigationDivs['wrapper'].appendChild(this.navigationDivs[navigationDivs[i]]);
  13513. this.navigationDivs[navigationDivs[i]].onmousedown = this[navigationDivActions[i]].bind(this);
  13514. }
  13515. document.onmouseup = this._stopMovement.bind(this);
  13516. },
  13517. /**
  13518. * this stops all movement induced by the navigation buttons
  13519. *
  13520. * @private
  13521. */
  13522. _stopMovement : function() {
  13523. this._xStopMoving();
  13524. this._yStopMoving();
  13525. this._stopZoom();
  13526. },
  13527. /**
  13528. * stops the actions performed by page up and down etc.
  13529. *
  13530. * @param event
  13531. * @private
  13532. */
  13533. _preventDefault : function(event) {
  13534. if (event !== undefined) {
  13535. if (event.preventDefault) {
  13536. event.preventDefault();
  13537. } else {
  13538. event.returnValue = false;
  13539. }
  13540. }
  13541. },
  13542. /**
  13543. * move the screen up
  13544. * By using the increments, instead of adding a fixed number to the translation, we keep fluent and
  13545. * instant movement. The onKeypress event triggers immediately, then pauses, then triggers frequently
  13546. * To avoid this behaviour, we do the translation in the start loop.
  13547. *
  13548. * @private
  13549. */
  13550. _moveUp : function(event) {
  13551. this.yIncrement = this.constants.keyboard.speed.y;
  13552. this.start(); // if there is no node movement, the calculation wont be done
  13553. this._preventDefault(event);
  13554. if (this.navigationDivs) {
  13555. this.navigationDivs['up'].className += " active";
  13556. }
  13557. },
  13558. /**
  13559. * move the screen down
  13560. * @private
  13561. */
  13562. _moveDown : function(event) {
  13563. this.yIncrement = -this.constants.keyboard.speed.y;
  13564. this.start(); // if there is no node movement, the calculation wont be done
  13565. this._preventDefault(event);
  13566. if (this.navigationDivs) {
  13567. this.navigationDivs['down'].className += " active";
  13568. }
  13569. },
  13570. /**
  13571. * move the screen left
  13572. * @private
  13573. */
  13574. _moveLeft : function(event) {
  13575. this.xIncrement = this.constants.keyboard.speed.x;
  13576. this.start(); // if there is no node movement, the calculation wont be done
  13577. this._preventDefault(event);
  13578. if (this.navigationDivs) {
  13579. this.navigationDivs['left'].className += " active";
  13580. }
  13581. },
  13582. /**
  13583. * move the screen right
  13584. * @private
  13585. */
  13586. _moveRight : function(event) {
  13587. this.xIncrement = -this.constants.keyboard.speed.y;
  13588. this.start(); // if there is no node movement, the calculation wont be done
  13589. this._preventDefault(event);
  13590. if (this.navigationDivs) {
  13591. this.navigationDivs['right'].className += " active";
  13592. }
  13593. },
  13594. /**
  13595. * Zoom in, using the same method as the movement.
  13596. * @private
  13597. */
  13598. _zoomIn : function(event) {
  13599. this.zoomIncrement = this.constants.keyboard.speed.zoom;
  13600. this.start(); // if there is no node movement, the calculation wont be done
  13601. this._preventDefault(event);
  13602. if (this.navigationDivs) {
  13603. this.navigationDivs['zoomIn'].className += " active";
  13604. }
  13605. },
  13606. /**
  13607. * Zoom out
  13608. * @private
  13609. */
  13610. _zoomOut : function() {
  13611. this.zoomIncrement = -this.constants.keyboard.speed.zoom;
  13612. this.start(); // if there is no node movement, the calculation wont be done
  13613. this._preventDefault(event);
  13614. if (this.navigationDivs) {
  13615. this.navigationDivs['zoomOut'].className += " active";
  13616. }
  13617. },
  13618. /**
  13619. * Stop zooming and unhighlight the zoom controls
  13620. * @private
  13621. */
  13622. _stopZoom : function() {
  13623. this.zoomIncrement = 0;
  13624. if (this.navigationDivs) {
  13625. this.navigationDivs['zoomIn'].className = this.navigationDivs['zoomIn'].className.replace(" active","");
  13626. this.navigationDivs['zoomOut'].className = this.navigationDivs['zoomOut'].className.replace(" active","");
  13627. }
  13628. },
  13629. /**
  13630. * Stop moving in the Y direction and unHighlight the up and down
  13631. * @private
  13632. */
  13633. _yStopMoving : function() {
  13634. this.yIncrement = 0;
  13635. if (this.navigationDivs) {
  13636. this.navigationDivs['up'].className = this.navigationDivs['up'].className.replace(" active","");
  13637. this.navigationDivs['down'].className = this.navigationDivs['down'].className.replace(" active","");
  13638. }
  13639. },
  13640. /**
  13641. * Stop moving in the X direction and unHighlight left and right.
  13642. * @private
  13643. */
  13644. _xStopMoving : function() {
  13645. this.xIncrement = 0;
  13646. if (this.navigationDivs) {
  13647. this.navigationDivs['left'].className = this.navigationDivs['left'].className.replace(" active","");
  13648. this.navigationDivs['right'].className = this.navigationDivs['right'].className.replace(" active","");
  13649. }
  13650. }
  13651. };
  13652. /**
  13653. * Created by Alex on 2/10/14.
  13654. */
  13655. var graphMixinLoaders = {
  13656. /**
  13657. * Load a mixin into the graph object
  13658. *
  13659. * @param {Object} sourceVariable | this object has to contain functions.
  13660. * @private
  13661. */
  13662. _loadMixin: function (sourceVariable) {
  13663. for (var mixinFunction in sourceVariable) {
  13664. if (sourceVariable.hasOwnProperty(mixinFunction)) {
  13665. Graph.prototype[mixinFunction] = sourceVariable[mixinFunction];
  13666. }
  13667. }
  13668. },
  13669. /**
  13670. * removes a mixin from the graph object.
  13671. *
  13672. * @param {Object} sourceVariable | this object has to contain functions.
  13673. * @private
  13674. */
  13675. _clearMixin: function (sourceVariable) {
  13676. for (var mixinFunction in sourceVariable) {
  13677. if (sourceVariable.hasOwnProperty(mixinFunction)) {
  13678. Graph.prototype[mixinFunction] = undefined;
  13679. }
  13680. }
  13681. },
  13682. /**
  13683. * Mixin the physics system and initialize the parameters required.
  13684. *
  13685. * @private
  13686. */
  13687. _loadPhysicsSystem: function () {
  13688. this._loadMixin(physicsMixin);
  13689. this._loadSelectedForceSolver();
  13690. if (this.constants.configurePhysics == true) {
  13691. this._loadPhysicsConfiguration();
  13692. }
  13693. },
  13694. /**
  13695. * Mixin the cluster system and initialize the parameters required.
  13696. *
  13697. * @private
  13698. */
  13699. _loadClusterSystem: function () {
  13700. this.clusterSession = 0;
  13701. this.hubThreshold = 5;
  13702. this._loadMixin(ClusterMixin);
  13703. },
  13704. /**
  13705. * Mixin the sector system and initialize the parameters required
  13706. *
  13707. * @private
  13708. */
  13709. _loadSectorSystem: function () {
  13710. this.sectors = {};
  13711. this.activeSector = ["default"];
  13712. this.sectors["active"] = {};
  13713. this.sectors["active"]["default"] = {"nodes": {},
  13714. "edges": {},
  13715. "nodeIndices": [],
  13716. "formationScale": 1.0,
  13717. "drawingNode": undefined };
  13718. this.sectors["frozen"] = {};
  13719. this.sectors["support"] = {"nodes": {},
  13720. "edges": {},
  13721. "nodeIndices": [],
  13722. "formationScale": 1.0,
  13723. "drawingNode": undefined };
  13724. this.nodeIndices = this.sectors["active"]["default"]["nodeIndices"]; // the node indices list is used to speed up the computation of the repulsion fields
  13725. this._loadMixin(SectorMixin);
  13726. },
  13727. /**
  13728. * Mixin the selection system and initialize the parameters required
  13729. *
  13730. * @private
  13731. */
  13732. _loadSelectionSystem: function () {
  13733. this.selectionObj = {nodes: {}, edges: {}};
  13734. this._loadMixin(SelectionMixin);
  13735. },
  13736. /**
  13737. * Mixin the navigationUI (User Interface) system and initialize the parameters required
  13738. *
  13739. * @private
  13740. */
  13741. _loadManipulationSystem: function () {
  13742. // reset global variables -- these are used by the selection of nodes and edges.
  13743. this.blockConnectingEdgeSelection = false;
  13744. this.forceAppendSelection = false;
  13745. if (this.constants.dataManipulation.enabled == true) {
  13746. // load the manipulator HTML elements. All styling done in css.
  13747. if (this.manipulationDiv === undefined) {
  13748. this.manipulationDiv = document.createElement('div');
  13749. this.manipulationDiv.className = 'graph-manipulationDiv';
  13750. this.manipulationDiv.id = 'graph-manipulationDiv';
  13751. if (this.editMode == true) {
  13752. this.manipulationDiv.style.display = "block";
  13753. }
  13754. else {
  13755. this.manipulationDiv.style.display = "none";
  13756. }
  13757. this.containerElement.insertBefore(this.manipulationDiv, this.frame);
  13758. }
  13759. if (this.editModeDiv === undefined) {
  13760. this.editModeDiv = document.createElement('div');
  13761. this.editModeDiv.className = 'graph-manipulation-editMode';
  13762. this.editModeDiv.id = 'graph-manipulation-editMode';
  13763. if (this.editMode == true) {
  13764. this.editModeDiv.style.display = "none";
  13765. }
  13766. else {
  13767. this.editModeDiv.style.display = "block";
  13768. }
  13769. this.containerElement.insertBefore(this.editModeDiv, this.frame);
  13770. }
  13771. if (this.closeDiv === undefined) {
  13772. this.closeDiv = document.createElement('div');
  13773. this.closeDiv.className = 'graph-manipulation-closeDiv';
  13774. this.closeDiv.id = 'graph-manipulation-closeDiv';
  13775. this.closeDiv.style.display = this.manipulationDiv.style.display;
  13776. this.containerElement.insertBefore(this.closeDiv, this.frame);
  13777. }
  13778. // load the manipulation functions
  13779. this._loadMixin(manipulationMixin);
  13780. // create the manipulator toolbar
  13781. this._createManipulatorBar();
  13782. }
  13783. else {
  13784. if (this.manipulationDiv !== undefined) {
  13785. // removes all the bindings and overloads
  13786. this._createManipulatorBar();
  13787. // remove the manipulation divs
  13788. this.containerElement.removeChild(this.manipulationDiv);
  13789. this.containerElement.removeChild(this.editModeDiv);
  13790. this.containerElement.removeChild(this.closeDiv);
  13791. this.manipulationDiv = undefined;
  13792. this.editModeDiv = undefined;
  13793. this.closeDiv = undefined;
  13794. // remove the mixin functions
  13795. this._clearMixin(manipulationMixin);
  13796. }
  13797. }
  13798. },
  13799. /**
  13800. * Mixin the navigation (User Interface) system and initialize the parameters required
  13801. *
  13802. * @private
  13803. */
  13804. _loadNavigationControls: function () {
  13805. this._loadMixin(NavigationMixin);
  13806. // the clean function removes the button divs, this is done to remove the bindings.
  13807. this._cleanNavigation();
  13808. if (this.constants.navigation.enabled == true) {
  13809. this._loadNavigationElements();
  13810. }
  13811. },
  13812. /**
  13813. * Mixin the hierarchical layout system.
  13814. *
  13815. * @private
  13816. */
  13817. _loadHierarchySystem: function () {
  13818. this._loadMixin(HierarchicalLayoutMixin);
  13819. }
  13820. };
  13821. /**
  13822. * @constructor Graph
  13823. * Create a graph visualization, displaying nodes and edges.
  13824. *
  13825. * @param {Element} container The DOM element in which the Graph will
  13826. * be created. Normally a div element.
  13827. * @param {Object} data An object containing parameters
  13828. * {Array} nodes
  13829. * {Array} edges
  13830. * @param {Object} options Options
  13831. */
  13832. function Graph (container, data, options) {
  13833. this._initializeMixinLoaders();
  13834. // create variables and set default values
  13835. this.containerElement = container;
  13836. this.width = '100%';
  13837. this.height = '100%';
  13838. // render and calculation settings
  13839. this.renderRefreshRate = 60; // hz (fps)
  13840. this.renderTimestep = 1000 / this.renderRefreshRate; // ms -- saves calculation later on
  13841. this.renderTime = 0.5 * this.renderTimestep; // measured time it takes to render a frame
  13842. this.maxPhysicsTicksPerRender = 3; // max amount of physics ticks per render step.
  13843. this.physicsDiscreteStepsize = 0.65; // discrete stepsize of the simulation
  13844. this.stabilize = true; // stabilize before displaying the graph
  13845. this.selectable = true;
  13846. this.initializing = true;
  13847. // these functions are triggered when the dataset is edited
  13848. this.triggerFunctions = {add:null,edit:null,connect:null,del:null};
  13849. // set constant values
  13850. this.constants = {
  13851. nodes: {
  13852. radiusMin: 5,
  13853. radiusMax: 20,
  13854. radius: 5,
  13855. shape: 'ellipse',
  13856. image: undefined,
  13857. widthMin: 16, // px
  13858. widthMax: 64, // px
  13859. fixed: false,
  13860. fontColor: 'black',
  13861. fontSize: 14, // px
  13862. fontFace: 'verdana',
  13863. level: -1,
  13864. color: {
  13865. border: '#2B7CE9',
  13866. background: '#97C2FC',
  13867. highlight: {
  13868. border: '#2B7CE9',
  13869. background: '#D2E5FF'
  13870. }
  13871. },
  13872. borderColor: '#2B7CE9',
  13873. backgroundColor: '#97C2FC',
  13874. highlightColor: '#D2E5FF',
  13875. group: undefined
  13876. },
  13877. edges: {
  13878. widthMin: 1,
  13879. widthMax: 15,
  13880. width: 1,
  13881. style: 'line',
  13882. color: {
  13883. color:'#848484',
  13884. highlight:'#848484'
  13885. },
  13886. fontColor: '#343434',
  13887. fontSize: 14, // px
  13888. fontFace: 'arial',
  13889. fontFill: 'white',
  13890. arrowScaleFactor: 1,
  13891. dash: {
  13892. length: 10,
  13893. gap: 5,
  13894. altLength: undefined
  13895. }
  13896. },
  13897. configurePhysics:false,
  13898. physics: {
  13899. barnesHut: {
  13900. enabled: true,
  13901. theta: 1 / 0.6, // inverted to save time during calculation
  13902. gravitationalConstant: -2000,
  13903. centralGravity: 0.3,
  13904. springLength: 95,
  13905. springConstant: 0.04,
  13906. damping: 0.09
  13907. },
  13908. repulsion: {
  13909. centralGravity: 0.1,
  13910. springLength: 200,
  13911. springConstant: 0.05,
  13912. nodeDistance: 100,
  13913. damping: 0.09
  13914. },
  13915. hierarchicalRepulsion: {
  13916. enabled: false,
  13917. centralGravity: 0.0,
  13918. springLength: 100,
  13919. springConstant: 0.01,
  13920. nodeDistance: 60,
  13921. damping: 0.09
  13922. },
  13923. damping: null,
  13924. centralGravity: null,
  13925. springLength: null,
  13926. springConstant: null
  13927. },
  13928. clustering: { // Per Node in Cluster = PNiC
  13929. enabled: false, // (Boolean) | global on/off switch for clustering.
  13930. initialMaxNodes: 100, // (# nodes) | if the initial amount of nodes is larger than this, we cluster until the total number is less than this threshold.
  13931. 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
  13932. 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
  13933. chainThreshold: 0.4, // (% of all drawn nodes)| maximum percentage of allowed chainnodes (long strings of connected nodes) within all nodes. (lower means less chains).
  13934. clusterEdgeThreshold: 20, // (px) | edge length threshold. if smaller, this node is clustered.
  13935. sectorThreshold: 100, // (# nodes in cluster) | cluster size threshold. If larger, expanding in own sector.
  13936. 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.
  13937. fontSizeMultiplier: 4.0, // (px PNiC) | how much the cluster font size grows per node in cluster (in px).
  13938. maxFontSize: 1000,
  13939. forceAmplification: 0.1, // (multiplier PNiC) | factor of increase fo the repulsion force of a cluster (per node in cluster).
  13940. distanceAmplification: 0.1, // (multiplier PNiC) | factor how much the repulsion distance of a cluster increases (per node in cluster).
  13941. edgeGrowth: 20, // (px PNiC) | amount of clusterSize connected to the edge is multiplied with this and added to edgeLength.
  13942. nodeScaling: {width: 1, // (px PNiC) | growth of the width per node in cluster.
  13943. height: 1, // (px PNiC) | growth of the height per node in cluster.
  13944. radius: 1}, // (px PNiC) | growth of the radius per node in cluster.
  13945. maxNodeSizeIncrements: 600, // (# increments) | max growth of the width per node in cluster.
  13946. activeAreaBoxSize: 80, // (px) | box area around the curser where clusters are popped open.
  13947. clusterLevelDifference: 2
  13948. },
  13949. navigation: {
  13950. enabled: false
  13951. },
  13952. keyboard: {
  13953. enabled: false,
  13954. speed: {x: 10, y: 10, zoom: 0.02}
  13955. },
  13956. dataManipulation: {
  13957. enabled: false,
  13958. initiallyVisible: false
  13959. },
  13960. hierarchicalLayout: {
  13961. enabled:false,
  13962. levelSeparation: 150,
  13963. nodeSpacing: 100,
  13964. direction: "UD" // UD, DU, LR, RL
  13965. },
  13966. freezeForStabilization: false,
  13967. smoothCurves: true,
  13968. maxVelocity: 10,
  13969. minVelocity: 0.1, // px/s
  13970. stabilizationIterations: 1000, // maximum number of iteration to stabilize
  13971. labels:{
  13972. add:"Add Node",
  13973. edit:"Edit",
  13974. link:"Add Link",
  13975. del:"Delete selected",
  13976. editNode:"Edit Node",
  13977. back:"Back",
  13978. addDescription:"Click in an empty space to place a new node.",
  13979. linkDescription:"Click on a node and drag the edge to another node to connect them.",
  13980. addError:"The function for add does not support two arguments (data,callback).",
  13981. linkError:"The function for connect does not support two arguments (data,callback).",
  13982. editError:"The function for edit does not support two arguments (data, callback).",
  13983. editBoundError:"No edit function has been bound to this button.",
  13984. deleteError:"The function for delete does not support two arguments (data, callback).",
  13985. deleteClusterError:"Clusters cannot be deleted."
  13986. },
  13987. tooltip: {
  13988. delay: 300,
  13989. fontColor: 'black',
  13990. fontSize: 14, // px
  13991. fontFace: 'verdana',
  13992. color: {
  13993. border: '#666',
  13994. background: '#FFFFC6'
  13995. }
  13996. }
  13997. };
  13998. this.editMode = this.constants.dataManipulation.initiallyVisible;
  13999. // Node variables
  14000. var graph = this;
  14001. this.groups = new Groups(); // object with groups
  14002. this.images = new Images(); // object with images
  14003. this.images.setOnloadCallback(function () {
  14004. graph._redraw();
  14005. });
  14006. // keyboard navigation variables
  14007. this.xIncrement = 0;
  14008. this.yIncrement = 0;
  14009. this.zoomIncrement = 0;
  14010. // loading all the mixins:
  14011. // load the force calculation functions, grouped under the physics system.
  14012. this._loadPhysicsSystem();
  14013. // create a frame and canvas
  14014. this._create();
  14015. // load the sector system. (mandatory, fully integrated with Graph)
  14016. this._loadSectorSystem();
  14017. // load the cluster system. (mandatory, even when not using the cluster system, there are function calls to it)
  14018. this._loadClusterSystem();
  14019. // load the selection system. (mandatory, required by Graph)
  14020. this._loadSelectionSystem();
  14021. // load the selection system. (mandatory, required by Graph)
  14022. this._loadHierarchySystem();
  14023. // apply options
  14024. this.setOptions(options);
  14025. // other vars
  14026. this.freezeSimulation = false;// freeze the simulation
  14027. this.cachedFunctions = {};
  14028. // containers for nodes and edges
  14029. this.calculationNodes = {};
  14030. this.calculationNodeIndices = [];
  14031. this.nodeIndices = []; // array with all the indices of the nodes. Used to speed up forces calculation
  14032. this.nodes = {}; // object with Node objects
  14033. this.edges = {}; // object with Edge objects
  14034. // position and scale variables and objects
  14035. this.canvasTopLeft = {"x": 0,"y": 0}; // coordinates of the top left of the canvas. they will be set during _redraw.
  14036. this.canvasBottomRight = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  14037. this.pointerPosition = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  14038. this.areaCenter = {}; // object with x and y elements used for determining the center of the zoom action
  14039. this.scale = 1; // defining the global scale variable in the constructor
  14040. this.previousScale = this.scale; // this is used to check if the zoom operation is zooming in or out
  14041. // datasets or dataviews
  14042. this.nodesData = null; // A DataSet or DataView
  14043. this.edgesData = null; // A DataSet or DataView
  14044. // create event listeners used to subscribe on the DataSets of the nodes and edges
  14045. this.nodesListeners = {
  14046. 'add': function (event, params) {
  14047. graph._addNodes(params.items);
  14048. graph.start();
  14049. },
  14050. 'update': function (event, params) {
  14051. graph._updateNodes(params.items);
  14052. graph.start();
  14053. },
  14054. 'remove': function (event, params) {
  14055. graph._removeNodes(params.items);
  14056. graph.start();
  14057. }
  14058. };
  14059. this.edgesListeners = {
  14060. 'add': function (event, params) {
  14061. graph._addEdges(params.items);
  14062. graph.start();
  14063. },
  14064. 'update': function (event, params) {
  14065. graph._updateEdges(params.items);
  14066. graph.start();
  14067. },
  14068. 'remove': function (event, params) {
  14069. graph._removeEdges(params.items);
  14070. graph.start();
  14071. }
  14072. };
  14073. // properties for the animation
  14074. this.moving = true;
  14075. this.timer = undefined; // Scheduling function. Is definded in this.start();
  14076. // load data (the disable start variable will be the same as the enabled clustering)
  14077. this.setData(data,this.constants.clustering.enabled || this.constants.hierarchicalLayout.enabled);
  14078. // hierarchical layout
  14079. this.initializing = false;
  14080. if (this.constants.hierarchicalLayout.enabled == true) {
  14081. this._setupHierarchicalLayout();
  14082. }
  14083. else {
  14084. // zoom so all data will fit on the screen, if clustering is enabled, we do not want start to be called here.
  14085. if (this.stabilize == false) {
  14086. this.zoomExtent(true,this.constants.clustering.enabled);
  14087. }
  14088. }
  14089. // if clustering is disabled, the simulation will have started in the setData function
  14090. if (this.constants.clustering.enabled) {
  14091. this.startWithClustering();
  14092. }
  14093. }
  14094. // Extend Graph with an Emitter mixin
  14095. Emitter(Graph.prototype);
  14096. /**
  14097. * Get the script path where the vis.js library is located
  14098. *
  14099. * @returns {string | null} path Path or null when not found. Path does not
  14100. * end with a slash.
  14101. * @private
  14102. */
  14103. Graph.prototype._getScriptPath = function() {
  14104. var scripts = document.getElementsByTagName( 'script' );
  14105. // find script named vis.js or vis.min.js
  14106. for (var i = 0; i < scripts.length; i++) {
  14107. var src = scripts[i].src;
  14108. var match = src && /\/?vis(.min)?\.js$/.exec(src);
  14109. if (match) {
  14110. // return path without the script name
  14111. return src.substring(0, src.length - match[0].length);
  14112. }
  14113. }
  14114. return null;
  14115. };
  14116. /**
  14117. * Find the center position of the graph
  14118. * @private
  14119. */
  14120. Graph.prototype._getRange = function() {
  14121. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  14122. for (var nodeId in this.nodes) {
  14123. if (this.nodes.hasOwnProperty(nodeId)) {
  14124. node = this.nodes[nodeId];
  14125. if (minX > (node.x)) {minX = node.x;}
  14126. if (maxX < (node.x)) {maxX = node.x;}
  14127. if (minY > (node.y)) {minY = node.y;}
  14128. if (maxY < (node.y)) {maxY = node.y;}
  14129. }
  14130. }
  14131. if (minX == 1e9 && maxX == -1e9 && minY == 1e9 && maxY == -1e9) {
  14132. minY = 0, maxY = 0, minX = 0, maxX = 0;
  14133. }
  14134. return {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  14135. };
  14136. /**
  14137. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  14138. * @returns {{x: number, y: number}}
  14139. * @private
  14140. */
  14141. Graph.prototype._findCenter = function(range) {
  14142. return {x: (0.5 * (range.maxX + range.minX)),
  14143. y: (0.5 * (range.maxY + range.minY))};
  14144. };
  14145. /**
  14146. * center the graph
  14147. *
  14148. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  14149. */
  14150. Graph.prototype._centerGraph = function(range) {
  14151. var center = this._findCenter(range);
  14152. center.x *= this.scale;
  14153. center.y *= this.scale;
  14154. center.x -= 0.5 * this.frame.canvas.clientWidth;
  14155. center.y -= 0.5 * this.frame.canvas.clientHeight;
  14156. this._setTranslation(-center.x,-center.y); // set at 0,0
  14157. };
  14158. /**
  14159. * This function zooms out to fit all data on screen based on amount of nodes
  14160. *
  14161. * @param {Boolean} [initialZoom] | zoom based on fitted formula or range, true = fitted, default = false;
  14162. * @param {Boolean} [disableStart] | If true, start is not called.
  14163. */
  14164. Graph.prototype.zoomExtent = function(initialZoom, disableStart) {
  14165. if (initialZoom === undefined) {
  14166. initialZoom = false;
  14167. }
  14168. if (disableStart === undefined) {
  14169. disableStart = false;
  14170. }
  14171. var range = this._getRange();
  14172. var zoomLevel;
  14173. if (initialZoom == true) {
  14174. var numberOfNodes = this.nodeIndices.length;
  14175. if (this.constants.smoothCurves == true) {
  14176. if (this.constants.clustering.enabled == true &&
  14177. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  14178. 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.
  14179. }
  14180. else {
  14181. zoomLevel = 12.662 / (numberOfNodes + 7.4147) + 0.0964822; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  14182. }
  14183. }
  14184. else {
  14185. if (this.constants.clustering.enabled == true &&
  14186. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  14187. 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.
  14188. }
  14189. else {
  14190. zoomLevel = 30.5062972 / (numberOfNodes + 19.93597763) + 0.08413486; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  14191. }
  14192. }
  14193. // correct for larger canvasses.
  14194. var factor = Math.min(this.frame.canvas.clientWidth / 600, this.frame.canvas.clientHeight / 600);
  14195. zoomLevel *= factor;
  14196. }
  14197. else {
  14198. var xDistance = (Math.abs(range.minX) + Math.abs(range.maxX)) * 1.1;
  14199. var yDistance = (Math.abs(range.minY) + Math.abs(range.maxY)) * 1.1;
  14200. var xZoomLevel = this.frame.canvas.clientWidth / xDistance;
  14201. var yZoomLevel = this.frame.canvas.clientHeight / yDistance;
  14202. zoomLevel = (xZoomLevel <= yZoomLevel) ? xZoomLevel : yZoomLevel;
  14203. }
  14204. if (zoomLevel > 1.0) {
  14205. zoomLevel = 1.0;
  14206. }
  14207. this._setScale(zoomLevel);
  14208. this._centerGraph(range);
  14209. if (disableStart == false) {
  14210. this.moving = true;
  14211. this.start();
  14212. }
  14213. };
  14214. /**
  14215. * Update the this.nodeIndices with the most recent node index list
  14216. * @private
  14217. */
  14218. Graph.prototype._updateNodeIndexList = function() {
  14219. this._clearNodeIndexList();
  14220. for (var idx in this.nodes) {
  14221. if (this.nodes.hasOwnProperty(idx)) {
  14222. this.nodeIndices.push(idx);
  14223. }
  14224. }
  14225. };
  14226. /**
  14227. * Set nodes and edges, and optionally options as well.
  14228. *
  14229. * @param {Object} data Object containing parameters:
  14230. * {Array | DataSet | DataView} [nodes] Array with nodes
  14231. * {Array | DataSet | DataView} [edges] Array with edges
  14232. * {String} [dot] String containing data in DOT format
  14233. * {Options} [options] Object with options
  14234. * @param {Boolean} [disableStart] | optional: disable the calling of the start function.
  14235. */
  14236. Graph.prototype.setData = function(data, disableStart) {
  14237. if (disableStart === undefined) {
  14238. disableStart = false;
  14239. }
  14240. if (data && data.dot && (data.nodes || data.edges)) {
  14241. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  14242. ' parameter pair "nodes" and "edges", but not both.');
  14243. }
  14244. // set options
  14245. this.setOptions(data && data.options);
  14246. // set all data
  14247. if (data && data.dot) {
  14248. // parse DOT file
  14249. if(data && data.dot) {
  14250. var dotData = vis.util.DOTToGraph(data.dot);
  14251. this.setData(dotData);
  14252. return;
  14253. }
  14254. }
  14255. else {
  14256. this._setNodes(data && data.nodes);
  14257. this._setEdges(data && data.edges);
  14258. }
  14259. this._putDataInSector();
  14260. if (!disableStart) {
  14261. // find a stable position or start animating to a stable position
  14262. if (this.stabilize) {
  14263. this._stabilize();
  14264. }
  14265. this.start();
  14266. }
  14267. };
  14268. /**
  14269. * Set options
  14270. * @param {Object} options
  14271. */
  14272. Graph.prototype.setOptions = function (options) {
  14273. if (options) {
  14274. var prop;
  14275. // retrieve parameter values
  14276. if (options.width !== undefined) {this.width = options.width;}
  14277. if (options.height !== undefined) {this.height = options.height;}
  14278. if (options.stabilize !== undefined) {this.stabilize = options.stabilize;}
  14279. if (options.selectable !== undefined) {this.selectable = options.selectable;}
  14280. if (options.smoothCurves !== undefined) {this.constants.smoothCurves = options.smoothCurves;}
  14281. if (options.freezeForStabilization !== undefined) {this.constants.freezeForStabilization = options.freezeForStabilization;}
  14282. if (options.configurePhysics !== undefined){this.constants.configurePhysics = options.configurePhysics;}
  14283. if (options.stabilizationIterations !== undefined) {this.constants.stabilizationIterations = options.stabilizationIterations;}
  14284. if (options.labels !== undefined) {
  14285. for (prop in options.labels) {
  14286. if (options.labels.hasOwnProperty(prop)) {
  14287. this.constants.labels[prop] = options.labels[prop];
  14288. }
  14289. }
  14290. }
  14291. if (options.onAdd) {
  14292. this.triggerFunctions.add = options.onAdd;
  14293. }
  14294. if (options.onEdit) {
  14295. this.triggerFunctions.edit = options.onEdit;
  14296. }
  14297. if (options.onConnect) {
  14298. this.triggerFunctions.connect = options.onConnect;
  14299. }
  14300. if (options.onDelete) {
  14301. this.triggerFunctions.del = options.onDelete;
  14302. }
  14303. if (options.physics) {
  14304. if (options.physics.barnesHut) {
  14305. this.constants.physics.barnesHut.enabled = true;
  14306. for (prop in options.physics.barnesHut) {
  14307. if (options.physics.barnesHut.hasOwnProperty(prop)) {
  14308. this.constants.physics.barnesHut[prop] = options.physics.barnesHut[prop];
  14309. }
  14310. }
  14311. }
  14312. if (options.physics.repulsion) {
  14313. this.constants.physics.barnesHut.enabled = false;
  14314. for (prop in options.physics.repulsion) {
  14315. if (options.physics.repulsion.hasOwnProperty(prop)) {
  14316. this.constants.physics.repulsion[prop] = options.physics.repulsion[prop];
  14317. }
  14318. }
  14319. }
  14320. if (options.physics.hierarchicalRepulsion) {
  14321. this.constants.hierarchicalLayout.enabled = true;
  14322. this.constants.physics.hierarchicalRepulsion.enabled = true;
  14323. this.constants.physics.barnesHut.enabled = false;
  14324. for (prop in options.physics.hierarchicalRepulsion) {
  14325. if (options.physics.hierarchicalRepulsion.hasOwnProperty(prop)) {
  14326. this.constants.physics.hierarchicalRepulsion[prop] = options.physics.hierarchicalRepulsion[prop];
  14327. }
  14328. }
  14329. }
  14330. }
  14331. if (options.hierarchicalLayout) {
  14332. this.constants.hierarchicalLayout.enabled = true;
  14333. for (prop in options.hierarchicalLayout) {
  14334. if (options.hierarchicalLayout.hasOwnProperty(prop)) {
  14335. this.constants.hierarchicalLayout[prop] = options.hierarchicalLayout[prop];
  14336. }
  14337. }
  14338. }
  14339. else if (options.hierarchicalLayout !== undefined) {
  14340. this.constants.hierarchicalLayout.enabled = false;
  14341. }
  14342. if (options.clustering) {
  14343. this.constants.clustering.enabled = true;
  14344. for (prop in options.clustering) {
  14345. if (options.clustering.hasOwnProperty(prop)) {
  14346. this.constants.clustering[prop] = options.clustering[prop];
  14347. }
  14348. }
  14349. }
  14350. else if (options.clustering !== undefined) {
  14351. this.constants.clustering.enabled = false;
  14352. }
  14353. if (options.navigation) {
  14354. this.constants.navigation.enabled = true;
  14355. for (prop in options.navigation) {
  14356. if (options.navigation.hasOwnProperty(prop)) {
  14357. this.constants.navigation[prop] = options.navigation[prop];
  14358. }
  14359. }
  14360. }
  14361. else if (options.navigation !== undefined) {
  14362. this.constants.navigation.enabled = false;
  14363. }
  14364. if (options.keyboard) {
  14365. this.constants.keyboard.enabled = true;
  14366. for (prop in options.keyboard) {
  14367. if (options.keyboard.hasOwnProperty(prop)) {
  14368. this.constants.keyboard[prop] = options.keyboard[prop];
  14369. }
  14370. }
  14371. }
  14372. else if (options.keyboard !== undefined) {
  14373. this.constants.keyboard.enabled = false;
  14374. }
  14375. if (options.dataManipulation) {
  14376. this.constants.dataManipulation.enabled = true;
  14377. for (prop in options.dataManipulation) {
  14378. if (options.dataManipulation.hasOwnProperty(prop)) {
  14379. this.constants.dataManipulation[prop] = options.dataManipulation[prop];
  14380. }
  14381. }
  14382. }
  14383. else if (options.dataManipulation !== undefined) {
  14384. this.constants.dataManipulation.enabled = false;
  14385. }
  14386. // TODO: work out these options and document them
  14387. if (options.edges) {
  14388. for (prop in options.edges) {
  14389. if (options.edges.hasOwnProperty(prop)) {
  14390. if (typeof options.edges[prop] != "object") {
  14391. this.constants.edges[prop] = options.edges[prop];
  14392. }
  14393. }
  14394. }
  14395. if (options.edges.color !== undefined) {
  14396. if (util.isString(options.edges.color)) {
  14397. this.constants.edges.color = {};
  14398. this.constants.edges.color.color = options.edges.color;
  14399. this.constants.edges.color.highlight = options.edges.color;
  14400. }
  14401. else {
  14402. if (options.edges.color.color !== undefined) {this.constants.edges.color.color = options.edges.color.color;}
  14403. if (options.edges.color.highlight !== undefined) {this.constants.edges.color.highlight = options.edges.color.highlight;}
  14404. }
  14405. }
  14406. if (!options.edges.fontColor) {
  14407. if (options.edges.color !== undefined) {
  14408. if (util.isString(options.edges.color)) {this.constants.edges.fontColor = options.edges.color;}
  14409. else if (options.edges.color.color !== undefined) {this.constants.edges.fontColor = options.edges.color.color;}
  14410. }
  14411. }
  14412. // Added to support dashed lines
  14413. // David Jordan
  14414. // 2012-08-08
  14415. if (options.edges.dash) {
  14416. if (options.edges.dash.length !== undefined) {
  14417. this.constants.edges.dash.length = options.edges.dash.length;
  14418. }
  14419. if (options.edges.dash.gap !== undefined) {
  14420. this.constants.edges.dash.gap = options.edges.dash.gap;
  14421. }
  14422. if (options.edges.dash.altLength !== undefined) {
  14423. this.constants.edges.dash.altLength = options.edges.dash.altLength;
  14424. }
  14425. }
  14426. }
  14427. if (options.nodes) {
  14428. for (prop in options.nodes) {
  14429. if (options.nodes.hasOwnProperty(prop)) {
  14430. this.constants.nodes[prop] = options.nodes[prop];
  14431. }
  14432. }
  14433. if (options.nodes.color) {
  14434. this.constants.nodes.color = util.parseColor(options.nodes.color);
  14435. }
  14436. /*
  14437. if (options.nodes.widthMin) this.constants.nodes.radiusMin = options.nodes.widthMin;
  14438. if (options.nodes.widthMax) this.constants.nodes.radiusMax = options.nodes.widthMax;
  14439. */
  14440. }
  14441. if (options.groups) {
  14442. for (var groupname in options.groups) {
  14443. if (options.groups.hasOwnProperty(groupname)) {
  14444. var group = options.groups[groupname];
  14445. this.groups.add(groupname, group);
  14446. }
  14447. }
  14448. }
  14449. if (options.tooltip) {
  14450. for (prop in options.tooltip) {
  14451. if (options.tooltip.hasOwnProperty(prop)) {
  14452. this.constants.tooltip[prop] = options.tooltip[prop];
  14453. }
  14454. }
  14455. if (options.tooltip.color) {
  14456. this.constants.tooltip.color = util.parseColor(options.tooltip.color);
  14457. }
  14458. }
  14459. }
  14460. // (Re)loading the mixins that can be enabled or disabled in the options.
  14461. // load the force calculation functions, grouped under the physics system.
  14462. this._loadPhysicsSystem();
  14463. // load the navigation system.
  14464. this._loadNavigationControls();
  14465. // load the data manipulation system
  14466. this._loadManipulationSystem();
  14467. // configure the smooth curves
  14468. this._configureSmoothCurves();
  14469. // bind keys. If disabled, this will not do anything;
  14470. this._createKeyBinds();
  14471. this.setSize(this.width, this.height);
  14472. this._setTranslation(this.frame.clientWidth / 2, this.frame.clientHeight / 2);
  14473. this._setScale(1);
  14474. this._redraw();
  14475. };
  14476. /**
  14477. * Create the main frame for the Graph.
  14478. * This function is executed once when a Graph object is created. The frame
  14479. * contains a canvas, and this canvas contains all objects like the axis and
  14480. * nodes.
  14481. * @private
  14482. */
  14483. Graph.prototype._create = function () {
  14484. // remove all elements from the container element.
  14485. while (this.containerElement.hasChildNodes()) {
  14486. this.containerElement.removeChild(this.containerElement.firstChild);
  14487. }
  14488. this.frame = document.createElement('div');
  14489. this.frame.className = 'graph-frame';
  14490. this.frame.style.position = 'relative';
  14491. this.frame.style.overflow = 'hidden';
  14492. // create the graph canvas (HTML canvas element)
  14493. this.frame.canvas = document.createElement( 'canvas' );
  14494. this.frame.canvas.style.position = 'relative';
  14495. this.frame.appendChild(this.frame.canvas);
  14496. if (!this.frame.canvas.getContext) {
  14497. var noCanvas = document.createElement( 'DIV' );
  14498. noCanvas.style.color = 'red';
  14499. noCanvas.style.fontWeight = 'bold' ;
  14500. noCanvas.style.padding = '10px';
  14501. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  14502. this.frame.canvas.appendChild(noCanvas);
  14503. }
  14504. var me = this;
  14505. this.drag = {};
  14506. this.pinch = {};
  14507. this.hammer = Hammer(this.frame.canvas, {
  14508. prevent_default: true
  14509. });
  14510. this.hammer.on('tap', me._onTap.bind(me) );
  14511. this.hammer.on('doubletap', me._onDoubleTap.bind(me) );
  14512. this.hammer.on('hold', me._onHold.bind(me) );
  14513. this.hammer.on('pinch', me._onPinch.bind(me) );
  14514. this.hammer.on('touch', me._onTouch.bind(me) );
  14515. this.hammer.on('dragstart', me._onDragStart.bind(me) );
  14516. this.hammer.on('drag', me._onDrag.bind(me) );
  14517. this.hammer.on('dragend', me._onDragEnd.bind(me) );
  14518. this.hammer.on('release', me._onRelease.bind(me) );
  14519. this.hammer.on('mousewheel',me._onMouseWheel.bind(me) );
  14520. this.hammer.on('DOMMouseScroll',me._onMouseWheel.bind(me) ); // for FF
  14521. this.hammer.on('mousemove', me._onMouseMoveTitle.bind(me) );
  14522. // add the frame to the container element
  14523. this.containerElement.appendChild(this.frame);
  14524. };
  14525. /**
  14526. * Binding the keys for keyboard navigation. These functions are defined in the NavigationMixin
  14527. * @private
  14528. */
  14529. Graph.prototype._createKeyBinds = function() {
  14530. var me = this;
  14531. this.mousetrap = mousetrap;
  14532. this.mousetrap.reset();
  14533. if (this.constants.keyboard.enabled == true) {
  14534. this.mousetrap.bind("up", this._moveUp.bind(me) , "keydown");
  14535. this.mousetrap.bind("up", this._yStopMoving.bind(me), "keyup");
  14536. this.mousetrap.bind("down", this._moveDown.bind(me) , "keydown");
  14537. this.mousetrap.bind("down", this._yStopMoving.bind(me), "keyup");
  14538. this.mousetrap.bind("left", this._moveLeft.bind(me) , "keydown");
  14539. this.mousetrap.bind("left", this._xStopMoving.bind(me), "keyup");
  14540. this.mousetrap.bind("right",this._moveRight.bind(me), "keydown");
  14541. this.mousetrap.bind("right",this._xStopMoving.bind(me), "keyup");
  14542. this.mousetrap.bind("=", this._zoomIn.bind(me), "keydown");
  14543. this.mousetrap.bind("=", this._stopZoom.bind(me), "keyup");
  14544. this.mousetrap.bind("-", this._zoomOut.bind(me), "keydown");
  14545. this.mousetrap.bind("-", this._stopZoom.bind(me), "keyup");
  14546. this.mousetrap.bind("[", this._zoomIn.bind(me), "keydown");
  14547. this.mousetrap.bind("[", this._stopZoom.bind(me), "keyup");
  14548. this.mousetrap.bind("]", this._zoomOut.bind(me), "keydown");
  14549. this.mousetrap.bind("]", this._stopZoom.bind(me), "keyup");
  14550. this.mousetrap.bind("pageup",this._zoomIn.bind(me), "keydown");
  14551. this.mousetrap.bind("pageup",this._stopZoom.bind(me), "keyup");
  14552. this.mousetrap.bind("pagedown",this._zoomOut.bind(me),"keydown");
  14553. this.mousetrap.bind("pagedown",this._stopZoom.bind(me), "keyup");
  14554. }
  14555. if (this.constants.dataManipulation.enabled == true) {
  14556. this.mousetrap.bind("escape",this._createManipulatorBar.bind(me));
  14557. this.mousetrap.bind("del",this._deleteSelected.bind(me));
  14558. }
  14559. };
  14560. /**
  14561. * Get the pointer location from a touch location
  14562. * @param {{pageX: Number, pageY: Number}} touch
  14563. * @return {{x: Number, y: Number}} pointer
  14564. * @private
  14565. */
  14566. Graph.prototype._getPointer = function (touch) {
  14567. return {
  14568. x: touch.pageX - vis.util.getAbsoluteLeft(this.frame.canvas),
  14569. y: touch.pageY - vis.util.getAbsoluteTop(this.frame.canvas)
  14570. };
  14571. };
  14572. /**
  14573. * On start of a touch gesture, store the pointer
  14574. * @param event
  14575. * @private
  14576. */
  14577. Graph.prototype._onTouch = function (event) {
  14578. this.drag.pointer = this._getPointer(event.gesture.center);
  14579. this.drag.pinched = false;
  14580. this.pinch.scale = this._getScale();
  14581. this._handleTouch(this.drag.pointer);
  14582. };
  14583. /**
  14584. * handle drag start event
  14585. * @private
  14586. */
  14587. Graph.prototype._onDragStart = function () {
  14588. this._handleDragStart();
  14589. };
  14590. /**
  14591. * This function is called by _onDragStart.
  14592. * It is separated out because we can then overload it for the datamanipulation system.
  14593. *
  14594. * @private
  14595. */
  14596. Graph.prototype._handleDragStart = function() {
  14597. var drag = this.drag;
  14598. var node = this._getNodeAt(drag.pointer);
  14599. // note: drag.pointer is set in _onTouch to get the initial touch location
  14600. drag.dragging = true;
  14601. drag.selection = [];
  14602. drag.translation = this._getTranslation();
  14603. drag.nodeId = null;
  14604. if (node != null) {
  14605. drag.nodeId = node.id;
  14606. // select the clicked node if not yet selected
  14607. if (!node.isSelected()) {
  14608. this._selectObject(node,false);
  14609. }
  14610. // create an array with the selected nodes and their original location and status
  14611. for (var objectId in this.selectionObj.nodes) {
  14612. if (this.selectionObj.nodes.hasOwnProperty(objectId)) {
  14613. var object = this.selectionObj.nodes[objectId];
  14614. var s = {
  14615. id: object.id,
  14616. node: object,
  14617. // store original x, y, xFixed and yFixed, make the node temporarily Fixed
  14618. x: object.x,
  14619. y: object.y,
  14620. xFixed: object.xFixed,
  14621. yFixed: object.yFixed
  14622. };
  14623. object.xFixed = true;
  14624. object.yFixed = true;
  14625. drag.selection.push(s);
  14626. }
  14627. }
  14628. }
  14629. };
  14630. /**
  14631. * handle drag event
  14632. * @private
  14633. */
  14634. Graph.prototype._onDrag = function (event) {
  14635. this._handleOnDrag(event)
  14636. };
  14637. /**
  14638. * This function is called by _onDrag.
  14639. * It is separated out because we can then overload it for the datamanipulation system.
  14640. *
  14641. * @private
  14642. */
  14643. Graph.prototype._handleOnDrag = function(event) {
  14644. if (this.drag.pinched) {
  14645. return;
  14646. }
  14647. var pointer = this._getPointer(event.gesture.center);
  14648. var me = this,
  14649. drag = this.drag,
  14650. selection = drag.selection;
  14651. if (selection && selection.length) {
  14652. // calculate delta's and new location
  14653. var deltaX = pointer.x - drag.pointer.x,
  14654. deltaY = pointer.y - drag.pointer.y;
  14655. // update position of all selected nodes
  14656. selection.forEach(function (s) {
  14657. var node = s.node;
  14658. if (!s.xFixed) {
  14659. node.x = me._canvasToX(me._xToCanvas(s.x) + deltaX);
  14660. }
  14661. if (!s.yFixed) {
  14662. node.y = me._canvasToY(me._yToCanvas(s.y) + deltaY);
  14663. }
  14664. });
  14665. // start _animationStep if not yet running
  14666. if (!this.moving) {
  14667. this.moving = true;
  14668. this.start();
  14669. }
  14670. }
  14671. else {
  14672. // move the graph
  14673. var diffX = pointer.x - this.drag.pointer.x;
  14674. var diffY = pointer.y - this.drag.pointer.y;
  14675. this._setTranslation(
  14676. this.drag.translation.x + diffX,
  14677. this.drag.translation.y + diffY);
  14678. this._redraw();
  14679. this.moving = true;
  14680. this.start();
  14681. }
  14682. };
  14683. /**
  14684. * handle drag start event
  14685. * @private
  14686. */
  14687. Graph.prototype._onDragEnd = function () {
  14688. this.drag.dragging = false;
  14689. var selection = this.drag.selection;
  14690. if (selection) {
  14691. selection.forEach(function (s) {
  14692. // restore original xFixed and yFixed
  14693. s.node.xFixed = s.xFixed;
  14694. s.node.yFixed = s.yFixed;
  14695. });
  14696. }
  14697. };
  14698. /**
  14699. * handle tap/click event: select/unselect a node
  14700. * @private
  14701. */
  14702. Graph.prototype._onTap = function (event) {
  14703. var pointer = this._getPointer(event.gesture.center);
  14704. this.pointerPosition = pointer;
  14705. this._handleTap(pointer);
  14706. };
  14707. /**
  14708. * handle doubletap event
  14709. * @private
  14710. */
  14711. Graph.prototype._onDoubleTap = function (event) {
  14712. var pointer = this._getPointer(event.gesture.center);
  14713. this._handleDoubleTap(pointer);
  14714. };
  14715. /**
  14716. * handle long tap event: multi select nodes
  14717. * @private
  14718. */
  14719. Graph.prototype._onHold = function (event) {
  14720. var pointer = this._getPointer(event.gesture.center);
  14721. this.pointerPosition = pointer;
  14722. this._handleOnHold(pointer);
  14723. };
  14724. /**
  14725. * handle the release of the screen
  14726. *
  14727. * @private
  14728. */
  14729. Graph.prototype._onRelease = function (event) {
  14730. var pointer = this._getPointer(event.gesture.center);
  14731. this._handleOnRelease(pointer);
  14732. };
  14733. /**
  14734. * Handle pinch event
  14735. * @param event
  14736. * @private
  14737. */
  14738. Graph.prototype._onPinch = function (event) {
  14739. var pointer = this._getPointer(event.gesture.center);
  14740. this.drag.pinched = true;
  14741. if (!('scale' in this.pinch)) {
  14742. this.pinch.scale = 1;
  14743. }
  14744. // TODO: enabled moving while pinching?
  14745. var scale = this.pinch.scale * event.gesture.scale;
  14746. this._zoom(scale, pointer)
  14747. };
  14748. /**
  14749. * Zoom the graph in or out
  14750. * @param {Number} scale a number around 1, and between 0.01 and 10
  14751. * @param {{x: Number, y: Number}} pointer Position on screen
  14752. * @return {Number} appliedScale scale is limited within the boundaries
  14753. * @private
  14754. */
  14755. Graph.prototype._zoom = function(scale, pointer) {
  14756. var scaleOld = this._getScale();
  14757. if (scale < 0.00001) {
  14758. scale = 0.00001;
  14759. }
  14760. if (scale > 10) {
  14761. scale = 10;
  14762. }
  14763. // + this.frame.canvas.clientHeight / 2
  14764. var translation = this._getTranslation();
  14765. var scaleFrac = scale / scaleOld;
  14766. var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac;
  14767. var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac;
  14768. this.areaCenter = {"x" : this._canvasToX(pointer.x),
  14769. "y" : this._canvasToY(pointer.y)};
  14770. this._setScale(scale);
  14771. this._setTranslation(tx, ty);
  14772. this.updateClustersDefault();
  14773. this._redraw();
  14774. return scale;
  14775. };
  14776. /**
  14777. * Event handler for mouse wheel event, used to zoom the timeline
  14778. * See http://adomas.org/javascript-mouse-wheel/
  14779. * https://github.com/EightMedia/hammer.js/issues/256
  14780. * @param {MouseEvent} event
  14781. * @private
  14782. */
  14783. Graph.prototype._onMouseWheel = function(event) {
  14784. // retrieve delta
  14785. var delta = 0;
  14786. if (event.wheelDelta) { /* IE/Opera. */
  14787. delta = event.wheelDelta/120;
  14788. } else if (event.detail) { /* Mozilla case. */
  14789. // In Mozilla, sign of delta is different than in IE.
  14790. // Also, delta is multiple of 3.
  14791. delta = -event.detail/3;
  14792. }
  14793. // If delta is nonzero, handle it.
  14794. // Basically, delta is now positive if wheel was scrolled up,
  14795. // and negative, if wheel was scrolled down.
  14796. if (delta) {
  14797. // calculate the new scale
  14798. var scale = this._getScale();
  14799. var zoom = delta / 10;
  14800. if (delta < 0) {
  14801. zoom = zoom / (1 - zoom);
  14802. }
  14803. scale *= (1 + zoom);
  14804. // calculate the pointer location
  14805. var gesture = util.fakeGesture(this, event);
  14806. var pointer = this._getPointer(gesture.center);
  14807. // apply the new scale
  14808. this._zoom(scale, pointer);
  14809. }
  14810. // Prevent default actions caused by mouse wheel.
  14811. event.preventDefault();
  14812. };
  14813. /**
  14814. * Mouse move handler for checking whether the title moves over a node with a title.
  14815. * @param {Event} event
  14816. * @private
  14817. */
  14818. Graph.prototype._onMouseMoveTitle = function (event) {
  14819. var gesture = util.fakeGesture(this, event);
  14820. var pointer = this._getPointer(gesture.center);
  14821. // check if the previously selected node is still selected
  14822. if (this.popupNode) {
  14823. this._checkHidePopup(pointer);
  14824. }
  14825. // start a timeout that will check if the mouse is positioned above
  14826. // an element
  14827. var me = this;
  14828. var checkShow = function() {
  14829. me._checkShowPopup(pointer);
  14830. };
  14831. if (this.popupTimer) {
  14832. clearInterval(this.popupTimer); // stop any running calculationTimer
  14833. }
  14834. if (!this.drag.dragging) {
  14835. this.popupTimer = setTimeout(checkShow, this.constants.tooltip.delay);
  14836. }
  14837. };
  14838. /**
  14839. * Check if there is an element on the given position in the graph
  14840. * (a node or edge). If so, and if this element has a title,
  14841. * show a popup window with its title.
  14842. *
  14843. * @param {{x:Number, y:Number}} pointer
  14844. * @private
  14845. */
  14846. Graph.prototype._checkShowPopup = function (pointer) {
  14847. var obj = {
  14848. left: this._canvasToX(pointer.x),
  14849. top: this._canvasToY(pointer.y),
  14850. right: this._canvasToX(pointer.x),
  14851. bottom: this._canvasToY(pointer.y)
  14852. };
  14853. var id;
  14854. var lastPopupNode = this.popupNode;
  14855. if (this.popupNode == undefined) {
  14856. // search the nodes for overlap, select the top one in case of multiple nodes
  14857. var nodes = this.nodes;
  14858. for (id in nodes) {
  14859. if (nodes.hasOwnProperty(id)) {
  14860. var node = nodes[id];
  14861. if (node.getTitle() !== undefined && node.isOverlappingWith(obj)) {
  14862. this.popupNode = node;
  14863. break;
  14864. }
  14865. }
  14866. }
  14867. }
  14868. if (this.popupNode === undefined) {
  14869. // search the edges for overlap
  14870. var edges = this.edges;
  14871. for (id in edges) {
  14872. if (edges.hasOwnProperty(id)) {
  14873. var edge = edges[id];
  14874. if (edge.connected && (edge.getTitle() !== undefined) &&
  14875. edge.isOverlappingWith(obj)) {
  14876. this.popupNode = edge;
  14877. break;
  14878. }
  14879. }
  14880. }
  14881. }
  14882. if (this.popupNode) {
  14883. // show popup message window
  14884. if (this.popupNode != lastPopupNode) {
  14885. var me = this;
  14886. if (!me.popup) {
  14887. me.popup = new Popup(me.frame, me.constants.tooltip);
  14888. }
  14889. // adjust a small offset such that the mouse cursor is located in the
  14890. // bottom left location of the popup, and you can easily move over the
  14891. // popup area
  14892. me.popup.setPosition(pointer.x - 3, pointer.y - 3);
  14893. me.popup.setText(me.popupNode.getTitle());
  14894. me.popup.show();
  14895. }
  14896. }
  14897. else {
  14898. if (this.popup) {
  14899. this.popup.hide();
  14900. }
  14901. }
  14902. };
  14903. /**
  14904. * Check if the popup must be hided, which is the case when the mouse is no
  14905. * longer hovering on the object
  14906. * @param {{x:Number, y:Number}} pointer
  14907. * @private
  14908. */
  14909. Graph.prototype._checkHidePopup = function (pointer) {
  14910. if (!this.popupNode || !this._getNodeAt(pointer) ) {
  14911. this.popupNode = undefined;
  14912. if (this.popup) {
  14913. this.popup.hide();
  14914. }
  14915. }
  14916. };
  14917. /**
  14918. * Set a new size for the graph
  14919. * @param {string} width Width in pixels or percentage (for example '800px'
  14920. * or '50%')
  14921. * @param {string} height Height in pixels or percentage (for example '400px'
  14922. * or '30%')
  14923. */
  14924. Graph.prototype.setSize = function(width, height) {
  14925. this.frame.style.width = width;
  14926. this.frame.style.height = height;
  14927. this.frame.canvas.style.width = '100%';
  14928. this.frame.canvas.style.height = '100%';
  14929. this.frame.canvas.width = this.frame.canvas.clientWidth;
  14930. this.frame.canvas.height = this.frame.canvas.clientHeight;
  14931. if (this.manipulationDiv !== undefined) {
  14932. this.manipulationDiv.style.width = this.frame.canvas.clientWidth + "px";
  14933. }
  14934. if (this.navigationDivs !== undefined) {
  14935. if (this.navigationDivs['wrapper'] !== undefined) {
  14936. this.navigationDivs['wrapper'].style.width = this.frame.canvas.clientWidth + "px";
  14937. this.navigationDivs['wrapper'].style.height = this.frame.canvas.clientHeight + "px";
  14938. }
  14939. }
  14940. this.emit('resize', {width:this.frame.canvas.width,height:this.frame.canvas.height});
  14941. };
  14942. /**
  14943. * Set a data set with nodes for the graph
  14944. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  14945. * @private
  14946. */
  14947. Graph.prototype._setNodes = function(nodes) {
  14948. var oldNodesData = this.nodesData;
  14949. if (nodes instanceof DataSet || nodes instanceof DataView) {
  14950. this.nodesData = nodes;
  14951. }
  14952. else if (nodes instanceof Array) {
  14953. this.nodesData = new DataSet();
  14954. this.nodesData.add(nodes);
  14955. }
  14956. else if (!nodes) {
  14957. this.nodesData = new DataSet();
  14958. }
  14959. else {
  14960. throw new TypeError('Array or DataSet expected');
  14961. }
  14962. if (oldNodesData) {
  14963. // unsubscribe from old dataset
  14964. util.forEach(this.nodesListeners, function (callback, event) {
  14965. oldNodesData.off(event, callback);
  14966. });
  14967. }
  14968. // remove drawn nodes
  14969. this.nodes = {};
  14970. if (this.nodesData) {
  14971. // subscribe to new dataset
  14972. var me = this;
  14973. util.forEach(this.nodesListeners, function (callback, event) {
  14974. me.nodesData.on(event, callback);
  14975. });
  14976. // draw all new nodes
  14977. var ids = this.nodesData.getIds();
  14978. this._addNodes(ids);
  14979. }
  14980. this._updateSelection();
  14981. };
  14982. /**
  14983. * Add nodes
  14984. * @param {Number[] | String[]} ids
  14985. * @private
  14986. */
  14987. Graph.prototype._addNodes = function(ids) {
  14988. var id;
  14989. for (var i = 0, len = ids.length; i < len; i++) {
  14990. id = ids[i];
  14991. var data = this.nodesData.get(id);
  14992. var node = new Node(data, this.images, this.groups, this.constants);
  14993. this.nodes[id] = node; // note: this may replace an existing node
  14994. if ((node.xFixed == false || node.yFixed == false) && (node.x === null || node.y === null)) {
  14995. var radius = 10 * 0.1*ids.length;
  14996. var angle = 2 * Math.PI * Math.random();
  14997. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  14998. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  14999. }
  15000. this.moving = true;
  15001. }
  15002. this._updateNodeIndexList();
  15003. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  15004. this._resetLevels();
  15005. this._setupHierarchicalLayout();
  15006. }
  15007. this._updateCalculationNodes();
  15008. this._reconnectEdges();
  15009. this._updateValueRange(this.nodes);
  15010. this.updateLabels();
  15011. };
  15012. /**
  15013. * Update existing nodes, or create them when not yet existing
  15014. * @param {Number[] | String[]} ids
  15015. * @private
  15016. */
  15017. Graph.prototype._updateNodes = function(ids) {
  15018. var nodes = this.nodes,
  15019. nodesData = this.nodesData;
  15020. for (var i = 0, len = ids.length; i < len; i++) {
  15021. var id = ids[i];
  15022. var node = nodes[id];
  15023. var data = nodesData.get(id);
  15024. if (node) {
  15025. // update node
  15026. node.setProperties(data, this.constants);
  15027. }
  15028. else {
  15029. // create node
  15030. node = new Node(properties, this.images, this.groups, this.constants);
  15031. nodes[id] = node;
  15032. }
  15033. }
  15034. this.moving = true;
  15035. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  15036. this._resetLevels();
  15037. this._setupHierarchicalLayout();
  15038. }
  15039. this._updateNodeIndexList();
  15040. this._reconnectEdges();
  15041. this._updateValueRange(nodes);
  15042. };
  15043. /**
  15044. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  15045. * @param {Number[] | String[]} ids
  15046. * @private
  15047. */
  15048. Graph.prototype._removeNodes = function(ids) {
  15049. var nodes = this.nodes;
  15050. for (var i = 0, len = ids.length; i < len; i++) {
  15051. var id = ids[i];
  15052. delete nodes[id];
  15053. }
  15054. this._updateNodeIndexList();
  15055. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  15056. this._resetLevels();
  15057. this._setupHierarchicalLayout();
  15058. }
  15059. this._updateCalculationNodes();
  15060. this._reconnectEdges();
  15061. this._updateSelection();
  15062. this._updateValueRange(nodes);
  15063. };
  15064. /**
  15065. * Load edges by reading the data table
  15066. * @param {Array | DataSet | DataView} edges The data containing the edges.
  15067. * @private
  15068. * @private
  15069. */
  15070. Graph.prototype._setEdges = function(edges) {
  15071. var oldEdgesData = this.edgesData;
  15072. if (edges instanceof DataSet || edges instanceof DataView) {
  15073. this.edgesData = edges;
  15074. }
  15075. else if (edges instanceof Array) {
  15076. this.edgesData = new DataSet();
  15077. this.edgesData.add(edges);
  15078. }
  15079. else if (!edges) {
  15080. this.edgesData = new DataSet();
  15081. }
  15082. else {
  15083. throw new TypeError('Array or DataSet expected');
  15084. }
  15085. if (oldEdgesData) {
  15086. // unsubscribe from old dataset
  15087. util.forEach(this.edgesListeners, function (callback, event) {
  15088. oldEdgesData.off(event, callback);
  15089. });
  15090. }
  15091. // remove drawn edges
  15092. this.edges = {};
  15093. if (this.edgesData) {
  15094. // subscribe to new dataset
  15095. var me = this;
  15096. util.forEach(this.edgesListeners, function (callback, event) {
  15097. me.edgesData.on(event, callback);
  15098. });
  15099. // draw all new nodes
  15100. var ids = this.edgesData.getIds();
  15101. this._addEdges(ids);
  15102. }
  15103. this._reconnectEdges();
  15104. };
  15105. /**
  15106. * Add edges
  15107. * @param {Number[] | String[]} ids
  15108. * @private
  15109. */
  15110. Graph.prototype._addEdges = function (ids) {
  15111. var edges = this.edges,
  15112. edgesData = this.edgesData;
  15113. for (var i = 0, len = ids.length; i < len; i++) {
  15114. var id = ids[i];
  15115. var oldEdge = edges[id];
  15116. if (oldEdge) {
  15117. oldEdge.disconnect();
  15118. }
  15119. var data = edgesData.get(id, {"showInternalIds" : true});
  15120. edges[id] = new Edge(data, this, this.constants);
  15121. }
  15122. this.moving = true;
  15123. this._updateValueRange(edges);
  15124. this._createBezierNodes();
  15125. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  15126. this._resetLevels();
  15127. this._setupHierarchicalLayout();
  15128. }
  15129. this._updateCalculationNodes();
  15130. };
  15131. /**
  15132. * Update existing edges, or create them when not yet existing
  15133. * @param {Number[] | String[]} ids
  15134. * @private
  15135. */
  15136. Graph.prototype._updateEdges = function (ids) {
  15137. var edges = this.edges,
  15138. edgesData = this.edgesData;
  15139. for (var i = 0, len = ids.length; i < len; i++) {
  15140. var id = ids[i];
  15141. var data = edgesData.get(id);
  15142. var edge = edges[id];
  15143. if (edge) {
  15144. // update edge
  15145. edge.disconnect();
  15146. edge.setProperties(data, this.constants);
  15147. edge.connect();
  15148. }
  15149. else {
  15150. // create edge
  15151. edge = new Edge(data, this, this.constants);
  15152. this.edges[id] = edge;
  15153. }
  15154. }
  15155. this._createBezierNodes();
  15156. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  15157. this._resetLevels();
  15158. this._setupHierarchicalLayout();
  15159. }
  15160. this.moving = true;
  15161. this._updateValueRange(edges);
  15162. };
  15163. /**
  15164. * Remove existing edges. Non existing ids will be ignored
  15165. * @param {Number[] | String[]} ids
  15166. * @private
  15167. */
  15168. Graph.prototype._removeEdges = function (ids) {
  15169. var edges = this.edges;
  15170. for (var i = 0, len = ids.length; i < len; i++) {
  15171. var id = ids[i];
  15172. var edge = edges[id];
  15173. if (edge) {
  15174. if (edge.via != null) {
  15175. delete this.sectors['support']['nodes'][edge.via.id];
  15176. }
  15177. edge.disconnect();
  15178. delete edges[id];
  15179. }
  15180. }
  15181. this.moving = true;
  15182. this._updateValueRange(edges);
  15183. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  15184. this._resetLevels();
  15185. this._setupHierarchicalLayout();
  15186. }
  15187. this._updateCalculationNodes();
  15188. };
  15189. /**
  15190. * Reconnect all edges
  15191. * @private
  15192. */
  15193. Graph.prototype._reconnectEdges = function() {
  15194. var id,
  15195. nodes = this.nodes,
  15196. edges = this.edges;
  15197. for (id in nodes) {
  15198. if (nodes.hasOwnProperty(id)) {
  15199. nodes[id].edges = [];
  15200. }
  15201. }
  15202. for (id in edges) {
  15203. if (edges.hasOwnProperty(id)) {
  15204. var edge = edges[id];
  15205. edge.from = null;
  15206. edge.to = null;
  15207. edge.connect();
  15208. }
  15209. }
  15210. };
  15211. /**
  15212. * Update the values of all object in the given array according to the current
  15213. * value range of the objects in the array.
  15214. * @param {Object} obj An object containing a set of Edges or Nodes
  15215. * The objects must have a method getValue() and
  15216. * setValueRange(min, max).
  15217. * @private
  15218. */
  15219. Graph.prototype._updateValueRange = function(obj) {
  15220. var id;
  15221. // determine the range of the objects
  15222. var valueMin = undefined;
  15223. var valueMax = undefined;
  15224. for (id in obj) {
  15225. if (obj.hasOwnProperty(id)) {
  15226. var value = obj[id].getValue();
  15227. if (value !== undefined) {
  15228. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  15229. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  15230. }
  15231. }
  15232. }
  15233. // adjust the range of all objects
  15234. if (valueMin !== undefined && valueMax !== undefined) {
  15235. for (id in obj) {
  15236. if (obj.hasOwnProperty(id)) {
  15237. obj[id].setValueRange(valueMin, valueMax);
  15238. }
  15239. }
  15240. }
  15241. };
  15242. /**
  15243. * Redraw the graph with the current data
  15244. * chart will be resized too.
  15245. */
  15246. Graph.prototype.redraw = function() {
  15247. this.setSize(this.width, this.height);
  15248. this._redraw();
  15249. };
  15250. /**
  15251. * Redraw the graph with the current data
  15252. * @private
  15253. */
  15254. Graph.prototype._redraw = function() {
  15255. var ctx = this.frame.canvas.getContext('2d');
  15256. // clear the canvas
  15257. var w = this.frame.canvas.width;
  15258. var h = this.frame.canvas.height;
  15259. ctx.clearRect(0, 0, w, h);
  15260. // set scaling and translation
  15261. ctx.save();
  15262. ctx.translate(this.translation.x, this.translation.y);
  15263. ctx.scale(this.scale, this.scale);
  15264. this.canvasTopLeft = {
  15265. "x": this._canvasToX(0),
  15266. "y": this._canvasToY(0)
  15267. };
  15268. this.canvasBottomRight = {
  15269. "x": this._canvasToX(this.frame.canvas.clientWidth),
  15270. "y": this._canvasToY(this.frame.canvas.clientHeight)
  15271. };
  15272. this._doInAllSectors("_drawAllSectorNodes",ctx);
  15273. this._doInAllSectors("_drawEdges",ctx);
  15274. this._doInAllSectors("_drawNodes",ctx,false);
  15275. // this._doInSupportSector("_drawNodes",ctx,true);
  15276. // this._drawTree(ctx,"#F00F0F");
  15277. // restore original scaling and translation
  15278. ctx.restore();
  15279. };
  15280. /**
  15281. * Set the translation of the graph
  15282. * @param {Number} offsetX Horizontal offset
  15283. * @param {Number} offsetY Vertical offset
  15284. * @private
  15285. */
  15286. Graph.prototype._setTranslation = function(offsetX, offsetY) {
  15287. if (this.translation === undefined) {
  15288. this.translation = {
  15289. x: 0,
  15290. y: 0
  15291. };
  15292. }
  15293. if (offsetX !== undefined) {
  15294. this.translation.x = offsetX;
  15295. }
  15296. if (offsetY !== undefined) {
  15297. this.translation.y = offsetY;
  15298. }
  15299. };
  15300. /**
  15301. * Get the translation of the graph
  15302. * @return {Object} translation An object with parameters x and y, both a number
  15303. * @private
  15304. */
  15305. Graph.prototype._getTranslation = function() {
  15306. return {
  15307. x: this.translation.x,
  15308. y: this.translation.y
  15309. };
  15310. };
  15311. /**
  15312. * Scale the graph
  15313. * @param {Number} scale Scaling factor 1.0 is unscaled
  15314. * @private
  15315. */
  15316. Graph.prototype._setScale = function(scale) {
  15317. this.scale = scale;
  15318. };
  15319. /**
  15320. * Get the current scale of the graph
  15321. * @return {Number} scale Scaling factor 1.0 is unscaled
  15322. * @private
  15323. */
  15324. Graph.prototype._getScale = function() {
  15325. return this.scale;
  15326. };
  15327. /**
  15328. * Convert a horizontal point on the HTML canvas to the x-value of the model
  15329. * @param {number} x
  15330. * @returns {number}
  15331. * @private
  15332. */
  15333. Graph.prototype._canvasToX = function(x) {
  15334. return (x - this.translation.x) / this.scale;
  15335. };
  15336. /**
  15337. * Convert an x-value in the model to a horizontal point on the HTML canvas
  15338. * @param {number} x
  15339. * @returns {number}
  15340. * @private
  15341. */
  15342. Graph.prototype._xToCanvas = function(x) {
  15343. return x * this.scale + this.translation.x;
  15344. };
  15345. /**
  15346. * Convert a vertical point on the HTML canvas to the y-value of the model
  15347. * @param {number} y
  15348. * @returns {number}
  15349. * @private
  15350. */
  15351. Graph.prototype._canvasToY = function(y) {
  15352. return (y - this.translation.y) / this.scale;
  15353. };
  15354. /**
  15355. * Convert an y-value in the model to a vertical point on the HTML canvas
  15356. * @param {number} y
  15357. * @returns {number}
  15358. * @private
  15359. */
  15360. Graph.prototype._yToCanvas = function(y) {
  15361. return y * this.scale + this.translation.y ;
  15362. };
  15363. /**
  15364. *
  15365. * @param {object} pos = {x: number, y: number}
  15366. * @returns {{x: number, y: number}}
  15367. * @constructor
  15368. */
  15369. Graph.prototype.DOMtoCanvas = function(pos) {
  15370. return {x:this._xToCanvas(pos.x),y:this._yToCanvas(pos.y)};
  15371. }
  15372. /**
  15373. *
  15374. * @param {object} pos = {x: number, y: number}
  15375. * @returns {{x: number, y: number}}
  15376. * @constructor
  15377. */
  15378. Graph.prototype.canvasToDOM = function(pos) {
  15379. return {x:this._canvasToX(pos.x),y:this._canvasToY(pos.y)};
  15380. }
  15381. /**
  15382. * Redraw all nodes
  15383. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  15384. * @param {CanvasRenderingContext2D} ctx
  15385. * @param {Boolean} [alwaysShow]
  15386. * @private
  15387. */
  15388. Graph.prototype._drawNodes = function(ctx,alwaysShow) {
  15389. if (alwaysShow === undefined) {
  15390. alwaysShow = false;
  15391. }
  15392. // first draw the unselected nodes
  15393. var nodes = this.nodes;
  15394. var selected = [];
  15395. for (var id in nodes) {
  15396. if (nodes.hasOwnProperty(id)) {
  15397. nodes[id].setScaleAndPos(this.scale,this.canvasTopLeft,this.canvasBottomRight);
  15398. if (nodes[id].isSelected()) {
  15399. selected.push(id);
  15400. }
  15401. else {
  15402. if (nodes[id].inArea() || alwaysShow) {
  15403. nodes[id].draw(ctx);
  15404. }
  15405. }
  15406. }
  15407. }
  15408. // draw the selected nodes on top
  15409. for (var s = 0, sMax = selected.length; s < sMax; s++) {
  15410. if (nodes[selected[s]].inArea() || alwaysShow) {
  15411. nodes[selected[s]].draw(ctx);
  15412. }
  15413. }
  15414. };
  15415. /**
  15416. * Redraw all edges
  15417. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  15418. * @param {CanvasRenderingContext2D} ctx
  15419. * @private
  15420. */
  15421. Graph.prototype._drawEdges = function(ctx) {
  15422. var edges = this.edges;
  15423. for (var id in edges) {
  15424. if (edges.hasOwnProperty(id)) {
  15425. var edge = edges[id];
  15426. edge.setScale(this.scale);
  15427. if (edge.connected) {
  15428. edges[id].draw(ctx);
  15429. }
  15430. }
  15431. }
  15432. };
  15433. /**
  15434. * Find a stable position for all nodes
  15435. * @private
  15436. */
  15437. Graph.prototype._stabilize = function() {
  15438. if (this.constants.freezeForStabilization == true) {
  15439. this._freezeDefinedNodes();
  15440. }
  15441. // find stable position
  15442. var count = 0;
  15443. while (this.moving && count < this.constants.stabilizationIterations) {
  15444. this._physicsTick();
  15445. count++;
  15446. }
  15447. this.zoomExtent(false,true);
  15448. if (this.constants.freezeForStabilization == true) {
  15449. this._restoreFrozenNodes();
  15450. }
  15451. this.emit("stabilized",{iterations:count});
  15452. };
  15453. /**
  15454. * When initializing and stabilizing, we can freeze nodes with a predefined position. This greatly speeds up stabilization
  15455. * because only the supportnodes for the smoothCurves have to settle.
  15456. *
  15457. * @private
  15458. */
  15459. Graph.prototype._freezeDefinedNodes = function() {
  15460. var nodes = this.nodes;
  15461. for (var id in nodes) {
  15462. if (nodes.hasOwnProperty(id)) {
  15463. if (nodes[id].x != null && nodes[id].y != null) {
  15464. nodes[id].fixedData.x = nodes[id].xFixed;
  15465. nodes[id].fixedData.y = nodes[id].yFixed;
  15466. nodes[id].xFixed = true;
  15467. nodes[id].yFixed = true;
  15468. }
  15469. }
  15470. }
  15471. };
  15472. /**
  15473. * Unfreezes the nodes that have been frozen by _freezeDefinedNodes.
  15474. *
  15475. * @private
  15476. */
  15477. Graph.prototype._restoreFrozenNodes = function() {
  15478. var nodes = this.nodes;
  15479. for (var id in nodes) {
  15480. if (nodes.hasOwnProperty(id)) {
  15481. if (nodes[id].fixedData.x != null) {
  15482. nodes[id].xFixed = nodes[id].fixedData.x;
  15483. nodes[id].yFixed = nodes[id].fixedData.y;
  15484. }
  15485. }
  15486. }
  15487. };
  15488. /**
  15489. * Check if any of the nodes is still moving
  15490. * @param {number} vmin the minimum velocity considered as 'moving'
  15491. * @return {boolean} true if moving, false if non of the nodes is moving
  15492. * @private
  15493. */
  15494. Graph.prototype._isMoving = function(vmin) {
  15495. var nodes = this.nodes;
  15496. for (var id in nodes) {
  15497. if (nodes.hasOwnProperty(id) && nodes[id].isMoving(vmin)) {
  15498. return true;
  15499. }
  15500. }
  15501. return false;
  15502. };
  15503. /**
  15504. * /**
  15505. * Perform one discrete step for all nodes
  15506. *
  15507. * @private
  15508. */
  15509. Graph.prototype._discreteStepNodes = function() {
  15510. var interval = this.physicsDiscreteStepsize;
  15511. var nodes = this.nodes;
  15512. var nodeId;
  15513. var nodesPresent = false;
  15514. if (this.constants.maxVelocity > 0) {
  15515. for (nodeId in nodes) {
  15516. if (nodes.hasOwnProperty(nodeId)) {
  15517. nodes[nodeId].discreteStepLimited(interval, this.constants.maxVelocity);
  15518. nodesPresent = true;
  15519. }
  15520. }
  15521. }
  15522. else {
  15523. for (nodeId in nodes) {
  15524. if (nodes.hasOwnProperty(nodeId)) {
  15525. nodes[nodeId].discreteStep(interval);
  15526. nodesPresent = true;
  15527. }
  15528. }
  15529. }
  15530. if (nodesPresent == true) {
  15531. var vminCorrected = this.constants.minVelocity / Math.max(this.scale,0.05);
  15532. if (vminCorrected > 0.5*this.constants.maxVelocity) {
  15533. this.moving = true;
  15534. }
  15535. else {
  15536. this.moving = this._isMoving(vminCorrected);
  15537. }
  15538. }
  15539. };
  15540. /**
  15541. * A single simulation step (or "tick") in the physics simulation
  15542. *
  15543. * @private
  15544. */
  15545. Graph.prototype._physicsTick = function() {
  15546. if (!this.freezeSimulation) {
  15547. if (this.moving) {
  15548. this._doInAllActiveSectors("_initializeForceCalculation");
  15549. this._doInAllActiveSectors("_discreteStepNodes");
  15550. if (this.constants.smoothCurves) {
  15551. this._doInSupportSector("_discreteStepNodes");
  15552. }
  15553. this._findCenter(this._getRange())
  15554. }
  15555. }
  15556. };
  15557. /**
  15558. * This function runs one step of the animation. It calls an x amount of physics ticks and one render tick.
  15559. * It reschedules itself at the beginning of the function
  15560. *
  15561. * @private
  15562. */
  15563. Graph.prototype._animationStep = function() {
  15564. // reset the timer so a new scheduled animation step can be set
  15565. this.timer = undefined;
  15566. // handle the keyboad movement
  15567. this._handleNavigation();
  15568. // this schedules a new animation step
  15569. this.start();
  15570. // start the physics simulation
  15571. var calculationTime = Date.now();
  15572. var maxSteps = 1;
  15573. this._physicsTick();
  15574. var timeRequired = Date.now() - calculationTime;
  15575. while (timeRequired < (this.renderTimestep - this.renderTime) && maxSteps < this.maxPhysicsTicksPerRender) {
  15576. this._physicsTick();
  15577. timeRequired = Date.now() - calculationTime;
  15578. maxSteps++;
  15579. }
  15580. // start the rendering process
  15581. var renderTime = Date.now();
  15582. this._redraw();
  15583. this.renderTime = Date.now() - renderTime;
  15584. };
  15585. if (typeof window !== 'undefined') {
  15586. window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
  15587. window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
  15588. }
  15589. /**
  15590. * Schedule a animation step with the refreshrate interval.
  15591. */
  15592. Graph.prototype.start = function() {
  15593. if (this.moving || this.xIncrement != 0 || this.yIncrement != 0 || this.zoomIncrement != 0) {
  15594. if (!this.timer) {
  15595. var ua = navigator.userAgent.toLowerCase();
  15596. var requiresTimeout = false;
  15597. if (ua.indexOf('msie 9.0') != -1) { // IE 9
  15598. requiresTimeout = true;
  15599. }
  15600. else if (ua.indexOf('safari') != -1) { // safari
  15601. if (ua.indexOf('chrome') <= -1) {
  15602. requiresTimeout = true;
  15603. }
  15604. }
  15605. if (requiresTimeout == true) {
  15606. this.timer = window.setTimeout(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  15607. }
  15608. else{
  15609. this.timer = window.requestAnimationFrame(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  15610. }
  15611. }
  15612. }
  15613. else {
  15614. this._redraw();
  15615. }
  15616. };
  15617. /**
  15618. * Move the graph according to the keyboard presses.
  15619. *
  15620. * @private
  15621. */
  15622. Graph.prototype._handleNavigation = function() {
  15623. if (this.xIncrement != 0 || this.yIncrement != 0) {
  15624. var translation = this._getTranslation();
  15625. this._setTranslation(translation.x+this.xIncrement, translation.y+this.yIncrement);
  15626. }
  15627. if (this.zoomIncrement != 0) {
  15628. var center = {
  15629. x: this.frame.canvas.clientWidth / 2,
  15630. y: this.frame.canvas.clientHeight / 2
  15631. };
  15632. this._zoom(this.scale*(1 + this.zoomIncrement), center);
  15633. }
  15634. };
  15635. /**
  15636. * Freeze the _animationStep
  15637. */
  15638. Graph.prototype.toggleFreeze = function() {
  15639. if (this.freezeSimulation == false) {
  15640. this.freezeSimulation = true;
  15641. }
  15642. else {
  15643. this.freezeSimulation = false;
  15644. this.start();
  15645. }
  15646. };
  15647. /**
  15648. * This function cleans the support nodes if they are not needed and adds them when they are.
  15649. *
  15650. * @param {boolean} [disableStart]
  15651. * @private
  15652. */
  15653. Graph.prototype._configureSmoothCurves = function(disableStart) {
  15654. if (disableStart === undefined) {
  15655. disableStart = true;
  15656. }
  15657. if (this.constants.smoothCurves == true) {
  15658. this._createBezierNodes();
  15659. }
  15660. else {
  15661. // delete the support nodes
  15662. this.sectors['support']['nodes'] = {};
  15663. for (var edgeId in this.edges) {
  15664. if (this.edges.hasOwnProperty(edgeId)) {
  15665. this.edges[edgeId].smooth = false;
  15666. this.edges[edgeId].via = null;
  15667. }
  15668. }
  15669. }
  15670. this._updateCalculationNodes();
  15671. if (!disableStart) {
  15672. this.moving = true;
  15673. this.start();
  15674. }
  15675. };
  15676. /**
  15677. * Bezier curves require an anchor point to calculate the smooth flow. These points are nodes. These nodes are invisible but
  15678. * are used for the force calculation.
  15679. *
  15680. * @private
  15681. */
  15682. Graph.prototype._createBezierNodes = function() {
  15683. if (this.constants.smoothCurves == true) {
  15684. for (var edgeId in this.edges) {
  15685. if (this.edges.hasOwnProperty(edgeId)) {
  15686. var edge = this.edges[edgeId];
  15687. if (edge.via == null) {
  15688. edge.smooth = true;
  15689. var nodeId = "edgeId:".concat(edge.id);
  15690. this.sectors['support']['nodes'][nodeId] = new Node(
  15691. {id:nodeId,
  15692. mass:1,
  15693. shape:'circle',
  15694. image:"",
  15695. internalMultiplier:1
  15696. },{},{},this.constants);
  15697. edge.via = this.sectors['support']['nodes'][nodeId];
  15698. edge.via.parentEdgeId = edge.id;
  15699. edge.positionBezierNode();
  15700. }
  15701. }
  15702. }
  15703. }
  15704. };
  15705. /**
  15706. * load the functions that load the mixins into the prototype.
  15707. *
  15708. * @private
  15709. */
  15710. Graph.prototype._initializeMixinLoaders = function () {
  15711. for (var mixinFunction in graphMixinLoaders) {
  15712. if (graphMixinLoaders.hasOwnProperty(mixinFunction)) {
  15713. Graph.prototype[mixinFunction] = graphMixinLoaders[mixinFunction];
  15714. }
  15715. }
  15716. };
  15717. /**
  15718. * Load the XY positions of the nodes into the dataset.
  15719. */
  15720. Graph.prototype.storePosition = function() {
  15721. var dataArray = [];
  15722. for (var nodeId in this.nodes) {
  15723. if (this.nodes.hasOwnProperty(nodeId)) {
  15724. var node = this.nodes[nodeId];
  15725. var allowedToMoveX = !this.nodes.xFixed;
  15726. var allowedToMoveY = !this.nodes.yFixed;
  15727. if (this.nodesData.data[nodeId].x != Math.round(node.x) || this.nodesData.data[nodeId].y != Math.round(node.y)) {
  15728. dataArray.push({id:nodeId,x:Math.round(node.x),y:Math.round(node.y),allowedToMoveX:allowedToMoveX,allowedToMoveY:allowedToMoveY});
  15729. }
  15730. }
  15731. }
  15732. this.nodesData.update(dataArray);
  15733. };
  15734. /**
  15735. * vis.js module exports
  15736. */
  15737. var vis = {
  15738. util: util,
  15739. DataSet: DataSet,
  15740. DataView: DataView,
  15741. Range: Range,
  15742. stack: stack,
  15743. TimeStep: TimeStep,
  15744. components: {
  15745. items: {
  15746. Item: Item,
  15747. ItemBox: ItemBox,
  15748. ItemPoint: ItemPoint,
  15749. ItemRange: ItemRange
  15750. },
  15751. Component: Component,
  15752. Panel: Panel,
  15753. RootPanel: RootPanel,
  15754. ItemSet: ItemSet,
  15755. TimeAxis: TimeAxis
  15756. },
  15757. graph: {
  15758. Node: Node,
  15759. Edge: Edge,
  15760. Popup: Popup,
  15761. Groups: Groups,
  15762. Images: Images
  15763. },
  15764. Timeline: Timeline,
  15765. Graph: Graph
  15766. };
  15767. /**
  15768. * CommonJS module exports
  15769. */
  15770. if (typeof exports !== 'undefined') {
  15771. exports = vis;
  15772. }
  15773. if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  15774. module.exports = vis;
  15775. }
  15776. /**
  15777. * AMD module exports
  15778. */
  15779. if (typeof(define) === 'function') {
  15780. define(function () {
  15781. return vis;
  15782. });
  15783. }
  15784. /**
  15785. * Window exports
  15786. */
  15787. if (typeof window !== 'undefined') {
  15788. // attach the module to the window, load as a regular javascript file
  15789. window['vis'] = vis;
  15790. }
  15791. },{"emitter-component":2,"hammerjs":3,"moment":4,"mousetrap":5}],2:[function(require,module,exports){
  15792. /**
  15793. * Expose `Emitter`.
  15794. */
  15795. module.exports = Emitter;
  15796. /**
  15797. * Initialize a new `Emitter`.
  15798. *
  15799. * @api public
  15800. */
  15801. function Emitter(obj) {
  15802. if (obj) return mixin(obj);
  15803. };
  15804. /**
  15805. * Mixin the emitter properties.
  15806. *
  15807. * @param {Object} obj
  15808. * @return {Object}
  15809. * @api private
  15810. */
  15811. function mixin(obj) {
  15812. for (var key in Emitter.prototype) {
  15813. obj[key] = Emitter.prototype[key];
  15814. }
  15815. return obj;
  15816. }
  15817. /**
  15818. * Listen on the given `event` with `fn`.
  15819. *
  15820. * @param {String} event
  15821. * @param {Function} fn
  15822. * @return {Emitter}
  15823. * @api public
  15824. */
  15825. Emitter.prototype.on =
  15826. Emitter.prototype.addEventListener = function(event, fn){
  15827. this._callbacks = this._callbacks || {};
  15828. (this._callbacks[event] = this._callbacks[event] || [])
  15829. .push(fn);
  15830. return this;
  15831. };
  15832. /**
  15833. * Adds an `event` listener that will be invoked a single
  15834. * time then automatically removed.
  15835. *
  15836. * @param {String} event
  15837. * @param {Function} fn
  15838. * @return {Emitter}
  15839. * @api public
  15840. */
  15841. Emitter.prototype.once = function(event, fn){
  15842. var self = this;
  15843. this._callbacks = this._callbacks || {};
  15844. function on() {
  15845. self.off(event, on);
  15846. fn.apply(this, arguments);
  15847. }
  15848. on.fn = fn;
  15849. this.on(event, on);
  15850. return this;
  15851. };
  15852. /**
  15853. * Remove the given callback for `event` or all
  15854. * registered callbacks.
  15855. *
  15856. * @param {String} event
  15857. * @param {Function} fn
  15858. * @return {Emitter}
  15859. * @api public
  15860. */
  15861. Emitter.prototype.off =
  15862. Emitter.prototype.removeListener =
  15863. Emitter.prototype.removeAllListeners =
  15864. Emitter.prototype.removeEventListener = function(event, fn){
  15865. this._callbacks = this._callbacks || {};
  15866. // all
  15867. if (0 == arguments.length) {
  15868. this._callbacks = {};
  15869. return this;
  15870. }
  15871. // specific event
  15872. var callbacks = this._callbacks[event];
  15873. if (!callbacks) return this;
  15874. // remove all handlers
  15875. if (1 == arguments.length) {
  15876. delete this._callbacks[event];
  15877. return this;
  15878. }
  15879. // remove specific handler
  15880. var cb;
  15881. for (var i = 0; i < callbacks.length; i++) {
  15882. cb = callbacks[i];
  15883. if (cb === fn || cb.fn === fn) {
  15884. callbacks.splice(i, 1);
  15885. break;
  15886. }
  15887. }
  15888. return this;
  15889. };
  15890. /**
  15891. * Emit `event` with the given args.
  15892. *
  15893. * @param {String} event
  15894. * @param {Mixed} ...
  15895. * @return {Emitter}
  15896. */
  15897. Emitter.prototype.emit = function(event){
  15898. this._callbacks = this._callbacks || {};
  15899. var args = [].slice.call(arguments, 1)
  15900. , callbacks = this._callbacks[event];
  15901. if (callbacks) {
  15902. callbacks = callbacks.slice(0);
  15903. for (var i = 0, len = callbacks.length; i < len; ++i) {
  15904. callbacks[i].apply(this, args);
  15905. }
  15906. }
  15907. return this;
  15908. };
  15909. /**
  15910. * Return array of callbacks for `event`.
  15911. *
  15912. * @param {String} event
  15913. * @return {Array}
  15914. * @api public
  15915. */
  15916. Emitter.prototype.listeners = function(event){
  15917. this._callbacks = this._callbacks || {};
  15918. return this._callbacks[event] || [];
  15919. };
  15920. /**
  15921. * Check if this emitter has `event` handlers.
  15922. *
  15923. * @param {String} event
  15924. * @return {Boolean}
  15925. * @api public
  15926. */
  15927. Emitter.prototype.hasListeners = function(event){
  15928. return !! this.listeners(event).length;
  15929. };
  15930. },{}],3:[function(require,module,exports){
  15931. /*! Hammer.JS - v1.0.5 - 2013-04-07
  15932. * http://eightmedia.github.com/hammer.js
  15933. *
  15934. * Copyright (c) 2013 Jorik Tangelder <j.tangelder@gmail.com>;
  15935. * Licensed under the MIT license */
  15936. (function(window, undefined) {
  15937. 'use strict';
  15938. /**
  15939. * Hammer
  15940. * use this to create instances
  15941. * @param {HTMLElement} element
  15942. * @param {Object} options
  15943. * @returns {Hammer.Instance}
  15944. * @constructor
  15945. */
  15946. var Hammer = function(element, options) {
  15947. return new Hammer.Instance(element, options || {});
  15948. };
  15949. // default settings
  15950. Hammer.defaults = {
  15951. // add styles and attributes to the element to prevent the browser from doing
  15952. // its native behavior. this doesnt prevent the scrolling, but cancels
  15953. // the contextmenu, tap highlighting etc
  15954. // set to false to disable this
  15955. stop_browser_behavior: {
  15956. // this also triggers onselectstart=false for IE
  15957. userSelect: 'none',
  15958. // this makes the element blocking in IE10 >, you could experiment with the value
  15959. // see for more options this issue; https://github.com/EightMedia/hammer.js/issues/241
  15960. touchAction: 'none',
  15961. touchCallout: 'none',
  15962. contentZooming: 'none',
  15963. userDrag: 'none',
  15964. tapHighlightColor: 'rgba(0,0,0,0)'
  15965. }
  15966. // more settings are defined per gesture at gestures.js
  15967. };
  15968. // detect touchevents
  15969. Hammer.HAS_POINTEREVENTS = navigator.pointerEnabled || navigator.msPointerEnabled;
  15970. Hammer.HAS_TOUCHEVENTS = ('ontouchstart' in window);
  15971. // dont use mouseevents on mobile devices
  15972. Hammer.MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;
  15973. Hammer.NO_MOUSEEVENTS = Hammer.HAS_TOUCHEVENTS && navigator.userAgent.match(Hammer.MOBILE_REGEX);
  15974. // eventtypes per touchevent (start, move, end)
  15975. // are filled by Hammer.event.determineEventTypes on setup
  15976. Hammer.EVENT_TYPES = {};
  15977. // direction defines
  15978. Hammer.DIRECTION_DOWN = 'down';
  15979. Hammer.DIRECTION_LEFT = 'left';
  15980. Hammer.DIRECTION_UP = 'up';
  15981. Hammer.DIRECTION_RIGHT = 'right';
  15982. // pointer type
  15983. Hammer.POINTER_MOUSE = 'mouse';
  15984. Hammer.POINTER_TOUCH = 'touch';
  15985. Hammer.POINTER_PEN = 'pen';
  15986. // touch event defines
  15987. Hammer.EVENT_START = 'start';
  15988. Hammer.EVENT_MOVE = 'move';
  15989. Hammer.EVENT_END = 'end';
  15990. // hammer document where the base events are added at
  15991. Hammer.DOCUMENT = document;
  15992. // plugins namespace
  15993. Hammer.plugins = {};
  15994. // if the window events are set...
  15995. Hammer.READY = false;
  15996. /**
  15997. * setup events to detect gestures on the document
  15998. */
  15999. function setup() {
  16000. if(Hammer.READY) {
  16001. return;
  16002. }
  16003. // find what eventtypes we add listeners to
  16004. Hammer.event.determineEventTypes();
  16005. // Register all gestures inside Hammer.gestures
  16006. for(var name in Hammer.gestures) {
  16007. if(Hammer.gestures.hasOwnProperty(name)) {
  16008. Hammer.detection.register(Hammer.gestures[name]);
  16009. }
  16010. }
  16011. // Add touch events on the document
  16012. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_MOVE, Hammer.detection.detect);
  16013. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_END, Hammer.detection.detect);
  16014. // Hammer is ready...!
  16015. Hammer.READY = true;
  16016. }
  16017. /**
  16018. * create new hammer instance
  16019. * all methods should return the instance itself, so it is chainable.
  16020. * @param {HTMLElement} element
  16021. * @param {Object} [options={}]
  16022. * @returns {Hammer.Instance}
  16023. * @constructor
  16024. */
  16025. Hammer.Instance = function(element, options) {
  16026. var self = this;
  16027. // setup HammerJS window events and register all gestures
  16028. // this also sets up the default options
  16029. setup();
  16030. this.element = element;
  16031. // start/stop detection option
  16032. this.enabled = true;
  16033. // merge options
  16034. this.options = Hammer.utils.extend(
  16035. Hammer.utils.extend({}, Hammer.defaults),
  16036. options || {});
  16037. // add some css to the element to prevent the browser from doing its native behavoir
  16038. if(this.options.stop_browser_behavior) {
  16039. Hammer.utils.stopDefaultBrowserBehavior(this.element, this.options.stop_browser_behavior);
  16040. }
  16041. // start detection on touchstart
  16042. Hammer.event.onTouch(element, Hammer.EVENT_START, function(ev) {
  16043. if(self.enabled) {
  16044. Hammer.detection.startDetect(self, ev);
  16045. }
  16046. });
  16047. // return instance
  16048. return this;
  16049. };
  16050. Hammer.Instance.prototype = {
  16051. /**
  16052. * bind events to the instance
  16053. * @param {String} gesture
  16054. * @param {Function} handler
  16055. * @returns {Hammer.Instance}
  16056. */
  16057. on: function onEvent(gesture, handler){
  16058. var gestures = gesture.split(' ');
  16059. for(var t=0; t<gestures.length; t++) {
  16060. this.element.addEventListener(gestures[t], handler, false);
  16061. }
  16062. return this;
  16063. },
  16064. /**
  16065. * unbind events to the instance
  16066. * @param {String} gesture
  16067. * @param {Function} handler
  16068. * @returns {Hammer.Instance}
  16069. */
  16070. off: function offEvent(gesture, handler){
  16071. var gestures = gesture.split(' ');
  16072. for(var t=0; t<gestures.length; t++) {
  16073. this.element.removeEventListener(gestures[t], handler, false);
  16074. }
  16075. return this;
  16076. },
  16077. /**
  16078. * trigger gesture event
  16079. * @param {String} gesture
  16080. * @param {Object} eventData
  16081. * @returns {Hammer.Instance}
  16082. */
  16083. trigger: function triggerEvent(gesture, eventData){
  16084. // create DOM event
  16085. var event = Hammer.DOCUMENT.createEvent('Event');
  16086. event.initEvent(gesture, true, true);
  16087. event.gesture = eventData;
  16088. // trigger on the target if it is in the instance element,
  16089. // this is for event delegation tricks
  16090. var element = this.element;
  16091. if(Hammer.utils.hasParent(eventData.target, element)) {
  16092. element = eventData.target;
  16093. }
  16094. element.dispatchEvent(event);
  16095. return this;
  16096. },
  16097. /**
  16098. * enable of disable hammer.js detection
  16099. * @param {Boolean} state
  16100. * @returns {Hammer.Instance}
  16101. */
  16102. enable: function enable(state) {
  16103. this.enabled = state;
  16104. return this;
  16105. }
  16106. };
  16107. /**
  16108. * this holds the last move event,
  16109. * used to fix empty touchend issue
  16110. * see the onTouch event for an explanation
  16111. * @type {Object}
  16112. */
  16113. var last_move_event = null;
  16114. /**
  16115. * when the mouse is hold down, this is true
  16116. * @type {Boolean}
  16117. */
  16118. var enable_detect = false;
  16119. /**
  16120. * when touch events have been fired, this is true
  16121. * @type {Boolean}
  16122. */
  16123. var touch_triggered = false;
  16124. Hammer.event = {
  16125. /**
  16126. * simple addEventListener
  16127. * @param {HTMLElement} element
  16128. * @param {String} type
  16129. * @param {Function} handler
  16130. */
  16131. bindDom: function(element, type, handler) {
  16132. var types = type.split(' ');
  16133. for(var t=0; t<types.length; t++) {
  16134. element.addEventListener(types[t], handler, false);
  16135. }
  16136. },
  16137. /**
  16138. * touch events with mouse fallback
  16139. * @param {HTMLElement} element
  16140. * @param {String} eventType like Hammer.EVENT_MOVE
  16141. * @param {Function} handler
  16142. */
  16143. onTouch: function onTouch(element, eventType, handler) {
  16144. var self = this;
  16145. this.bindDom(element, Hammer.EVENT_TYPES[eventType], function bindDomOnTouch(ev) {
  16146. var sourceEventType = ev.type.toLowerCase();
  16147. // onmouseup, but when touchend has been fired we do nothing.
  16148. // this is for touchdevices which also fire a mouseup on touchend
  16149. if(sourceEventType.match(/mouse/) && touch_triggered) {
  16150. return;
  16151. }
  16152. // mousebutton must be down or a touch event
  16153. else if( sourceEventType.match(/touch/) || // touch events are always on screen
  16154. sourceEventType.match(/pointerdown/) || // pointerevents touch
  16155. (sourceEventType.match(/mouse/) && ev.which === 1) // mouse is pressed
  16156. ){
  16157. enable_detect = true;
  16158. }
  16159. // we are in a touch event, set the touch triggered bool to true,
  16160. // this for the conflicts that may occur on ios and android
  16161. if(sourceEventType.match(/touch|pointer/)) {
  16162. touch_triggered = true;
  16163. }
  16164. // count the total touches on the screen
  16165. var count_touches = 0;
  16166. // when touch has been triggered in this detection session
  16167. // and we are now handling a mouse event, we stop that to prevent conflicts
  16168. if(enable_detect) {
  16169. // update pointerevent
  16170. if(Hammer.HAS_POINTEREVENTS && eventType != Hammer.EVENT_END) {
  16171. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  16172. }
  16173. // touch
  16174. else if(sourceEventType.match(/touch/)) {
  16175. count_touches = ev.touches.length;
  16176. }
  16177. // mouse
  16178. else if(!touch_triggered) {
  16179. count_touches = sourceEventType.match(/up/) ? 0 : 1;
  16180. }
  16181. // if we are in a end event, but when we remove one touch and
  16182. // we still have enough, set eventType to move
  16183. if(count_touches > 0 && eventType == Hammer.EVENT_END) {
  16184. eventType = Hammer.EVENT_MOVE;
  16185. }
  16186. // no touches, force the end event
  16187. else if(!count_touches) {
  16188. eventType = Hammer.EVENT_END;
  16189. }
  16190. // because touchend has no touches, and we often want to use these in our gestures,
  16191. // we send the last move event as our eventData in touchend
  16192. if(!count_touches && last_move_event !== null) {
  16193. ev = last_move_event;
  16194. }
  16195. // store the last move event
  16196. else {
  16197. last_move_event = ev;
  16198. }
  16199. // trigger the handler
  16200. handler.call(Hammer.detection, self.collectEventData(element, eventType, ev));
  16201. // remove pointerevent from list
  16202. if(Hammer.HAS_POINTEREVENTS && eventType == Hammer.EVENT_END) {
  16203. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  16204. }
  16205. }
  16206. //debug(sourceEventType +" "+ eventType);
  16207. // on the end we reset everything
  16208. if(!count_touches) {
  16209. last_move_event = null;
  16210. enable_detect = false;
  16211. touch_triggered = false;
  16212. Hammer.PointerEvent.reset();
  16213. }
  16214. });
  16215. },
  16216. /**
  16217. * we have different events for each device/browser
  16218. * determine what we need and set them in the Hammer.EVENT_TYPES constant
  16219. */
  16220. determineEventTypes: function determineEventTypes() {
  16221. // determine the eventtype we want to set
  16222. var types;
  16223. // pointerEvents magic
  16224. if(Hammer.HAS_POINTEREVENTS) {
  16225. types = Hammer.PointerEvent.getEvents();
  16226. }
  16227. // on Android, iOS, blackberry, windows mobile we dont want any mouseevents
  16228. else if(Hammer.NO_MOUSEEVENTS) {
  16229. types = [
  16230. 'touchstart',
  16231. 'touchmove',
  16232. 'touchend touchcancel'];
  16233. }
  16234. // for non pointer events browsers and mixed browsers,
  16235. // like chrome on windows8 touch laptop
  16236. else {
  16237. types = [
  16238. 'touchstart mousedown',
  16239. 'touchmove mousemove',
  16240. 'touchend touchcancel mouseup'];
  16241. }
  16242. Hammer.EVENT_TYPES[Hammer.EVENT_START] = types[0];
  16243. Hammer.EVENT_TYPES[Hammer.EVENT_MOVE] = types[1];
  16244. Hammer.EVENT_TYPES[Hammer.EVENT_END] = types[2];
  16245. },
  16246. /**
  16247. * create touchlist depending on the event
  16248. * @param {Object} ev
  16249. * @param {String} eventType used by the fakemultitouch plugin
  16250. */
  16251. getTouchList: function getTouchList(ev/*, eventType*/) {
  16252. // get the fake pointerEvent touchlist
  16253. if(Hammer.HAS_POINTEREVENTS) {
  16254. return Hammer.PointerEvent.getTouchList();
  16255. }
  16256. // get the touchlist
  16257. else if(ev.touches) {
  16258. return ev.touches;
  16259. }
  16260. // make fake touchlist from mouse position
  16261. else {
  16262. return [{
  16263. identifier: 1,
  16264. pageX: ev.pageX,
  16265. pageY: ev.pageY,
  16266. target: ev.target
  16267. }];
  16268. }
  16269. },
  16270. /**
  16271. * collect event data for Hammer js
  16272. * @param {HTMLElement} element
  16273. * @param {String} eventType like Hammer.EVENT_MOVE
  16274. * @param {Object} eventData
  16275. */
  16276. collectEventData: function collectEventData(element, eventType, ev) {
  16277. var touches = this.getTouchList(ev, eventType);
  16278. // find out pointerType
  16279. var pointerType = Hammer.POINTER_TOUCH;
  16280. if(ev.type.match(/mouse/) || Hammer.PointerEvent.matchType(Hammer.POINTER_MOUSE, ev)) {
  16281. pointerType = Hammer.POINTER_MOUSE;
  16282. }
  16283. return {
  16284. center : Hammer.utils.getCenter(touches),
  16285. timeStamp : new Date().getTime(),
  16286. target : ev.target,
  16287. touches : touches,
  16288. eventType : eventType,
  16289. pointerType : pointerType,
  16290. srcEvent : ev,
  16291. /**
  16292. * prevent the browser default actions
  16293. * mostly used to disable scrolling of the browser
  16294. */
  16295. preventDefault: function() {
  16296. if(this.srcEvent.preventManipulation) {
  16297. this.srcEvent.preventManipulation();
  16298. }
  16299. if(this.srcEvent.preventDefault) {
  16300. this.srcEvent.preventDefault();
  16301. }
  16302. },
  16303. /**
  16304. * stop bubbling the event up to its parents
  16305. */
  16306. stopPropagation: function() {
  16307. this.srcEvent.stopPropagation();
  16308. },
  16309. /**
  16310. * immediately stop gesture detection
  16311. * might be useful after a swipe was detected
  16312. * @return {*}
  16313. */
  16314. stopDetect: function() {
  16315. return Hammer.detection.stopDetect();
  16316. }
  16317. };
  16318. }
  16319. };
  16320. Hammer.PointerEvent = {
  16321. /**
  16322. * holds all pointers
  16323. * @type {Object}
  16324. */
  16325. pointers: {},
  16326. /**
  16327. * get a list of pointers
  16328. * @returns {Array} touchlist
  16329. */
  16330. getTouchList: function() {
  16331. var self = this;
  16332. var touchlist = [];
  16333. // we can use forEach since pointerEvents only is in IE10
  16334. Object.keys(self.pointers).sort().forEach(function(id) {
  16335. touchlist.push(self.pointers[id]);
  16336. });
  16337. return touchlist;
  16338. },
  16339. /**
  16340. * update the position of a pointer
  16341. * @param {String} type Hammer.EVENT_END
  16342. * @param {Object} pointerEvent
  16343. */
  16344. updatePointer: function(type, pointerEvent) {
  16345. if(type == Hammer.EVENT_END) {
  16346. this.pointers = {};
  16347. }
  16348. else {
  16349. pointerEvent.identifier = pointerEvent.pointerId;
  16350. this.pointers[pointerEvent.pointerId] = pointerEvent;
  16351. }
  16352. return Object.keys(this.pointers).length;
  16353. },
  16354. /**
  16355. * check if ev matches pointertype
  16356. * @param {String} pointerType Hammer.POINTER_MOUSE
  16357. * @param {PointerEvent} ev
  16358. */
  16359. matchType: function(pointerType, ev) {
  16360. if(!ev.pointerType) {
  16361. return false;
  16362. }
  16363. var types = {};
  16364. types[Hammer.POINTER_MOUSE] = (ev.pointerType == ev.MSPOINTER_TYPE_MOUSE || ev.pointerType == Hammer.POINTER_MOUSE);
  16365. types[Hammer.POINTER_TOUCH] = (ev.pointerType == ev.MSPOINTER_TYPE_TOUCH || ev.pointerType == Hammer.POINTER_TOUCH);
  16366. types[Hammer.POINTER_PEN] = (ev.pointerType == ev.MSPOINTER_TYPE_PEN || ev.pointerType == Hammer.POINTER_PEN);
  16367. return types[pointerType];
  16368. },
  16369. /**
  16370. * get events
  16371. */
  16372. getEvents: function() {
  16373. return [
  16374. 'pointerdown MSPointerDown',
  16375. 'pointermove MSPointerMove',
  16376. 'pointerup pointercancel MSPointerUp MSPointerCancel'
  16377. ];
  16378. },
  16379. /**
  16380. * reset the list
  16381. */
  16382. reset: function() {
  16383. this.pointers = {};
  16384. }
  16385. };
  16386. Hammer.utils = {
  16387. /**
  16388. * extend method,
  16389. * also used for cloning when dest is an empty object
  16390. * @param {Object} dest
  16391. * @param {Object} src
  16392. * @parm {Boolean} merge do a merge
  16393. * @returns {Object} dest
  16394. */
  16395. extend: function extend(dest, src, merge) {
  16396. for (var key in src) {
  16397. if(dest[key] !== undefined && merge) {
  16398. continue;
  16399. }
  16400. dest[key] = src[key];
  16401. }
  16402. return dest;
  16403. },
  16404. /**
  16405. * find if a node is in the given parent
  16406. * used for event delegation tricks
  16407. * @param {HTMLElement} node
  16408. * @param {HTMLElement} parent
  16409. * @returns {boolean} has_parent
  16410. */
  16411. hasParent: function(node, parent) {
  16412. while(node){
  16413. if(node == parent) {
  16414. return true;
  16415. }
  16416. node = node.parentNode;
  16417. }
  16418. return false;
  16419. },
  16420. /**
  16421. * get the center of all the touches
  16422. * @param {Array} touches
  16423. * @returns {Object} center
  16424. */
  16425. getCenter: function getCenter(touches) {
  16426. var valuesX = [], valuesY = [];
  16427. for(var t= 0,len=touches.length; t<len; t++) {
  16428. valuesX.push(touches[t].pageX);
  16429. valuesY.push(touches[t].pageY);
  16430. }
  16431. return {
  16432. pageX: ((Math.min.apply(Math, valuesX) + Math.max.apply(Math, valuesX)) / 2),
  16433. pageY: ((Math.min.apply(Math, valuesY) + Math.max.apply(Math, valuesY)) / 2)
  16434. };
  16435. },
  16436. /**
  16437. * calculate the velocity between two points
  16438. * @param {Number} delta_time
  16439. * @param {Number} delta_x
  16440. * @param {Number} delta_y
  16441. * @returns {Object} velocity
  16442. */
  16443. getVelocity: function getVelocity(delta_time, delta_x, delta_y) {
  16444. return {
  16445. x: Math.abs(delta_x / delta_time) || 0,
  16446. y: Math.abs(delta_y / delta_time) || 0
  16447. };
  16448. },
  16449. /**
  16450. * calculate the angle between two coordinates
  16451. * @param {Touch} touch1
  16452. * @param {Touch} touch2
  16453. * @returns {Number} angle
  16454. */
  16455. getAngle: function getAngle(touch1, touch2) {
  16456. var y = touch2.pageY - touch1.pageY,
  16457. x = touch2.pageX - touch1.pageX;
  16458. return Math.atan2(y, x) * 180 / Math.PI;
  16459. },
  16460. /**
  16461. * angle to direction define
  16462. * @param {Touch} touch1
  16463. * @param {Touch} touch2
  16464. * @returns {String} direction constant, like Hammer.DIRECTION_LEFT
  16465. */
  16466. getDirection: function getDirection(touch1, touch2) {
  16467. var x = Math.abs(touch1.pageX - touch2.pageX),
  16468. y = Math.abs(touch1.pageY - touch2.pageY);
  16469. if(x >= y) {
  16470. return touch1.pageX - touch2.pageX > 0 ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  16471. }
  16472. else {
  16473. return touch1.pageY - touch2.pageY > 0 ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  16474. }
  16475. },
  16476. /**
  16477. * calculate the distance between two touches
  16478. * @param {Touch} touch1
  16479. * @param {Touch} touch2
  16480. * @returns {Number} distance
  16481. */
  16482. getDistance: function getDistance(touch1, touch2) {
  16483. var x = touch2.pageX - touch1.pageX,
  16484. y = touch2.pageY - touch1.pageY;
  16485. return Math.sqrt((x*x) + (y*y));
  16486. },
  16487. /**
  16488. * calculate the scale factor between two touchLists (fingers)
  16489. * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
  16490. * @param {Array} start
  16491. * @param {Array} end
  16492. * @returns {Number} scale
  16493. */
  16494. getScale: function getScale(start, end) {
  16495. // need two fingers...
  16496. if(start.length >= 2 && end.length >= 2) {
  16497. return this.getDistance(end[0], end[1]) /
  16498. this.getDistance(start[0], start[1]);
  16499. }
  16500. return 1;
  16501. },
  16502. /**
  16503. * calculate the rotation degrees between two touchLists (fingers)
  16504. * @param {Array} start
  16505. * @param {Array} end
  16506. * @returns {Number} rotation
  16507. */
  16508. getRotation: function getRotation(start, end) {
  16509. // need two fingers
  16510. if(start.length >= 2 && end.length >= 2) {
  16511. return this.getAngle(end[1], end[0]) -
  16512. this.getAngle(start[1], start[0]);
  16513. }
  16514. return 0;
  16515. },
  16516. /**
  16517. * boolean if the direction is vertical
  16518. * @param {String} direction
  16519. * @returns {Boolean} is_vertical
  16520. */
  16521. isVertical: function isVertical(direction) {
  16522. return (direction == Hammer.DIRECTION_UP || direction == Hammer.DIRECTION_DOWN);
  16523. },
  16524. /**
  16525. * stop browser default behavior with css props
  16526. * @param {HtmlElement} element
  16527. * @param {Object} css_props
  16528. */
  16529. stopDefaultBrowserBehavior: function stopDefaultBrowserBehavior(element, css_props) {
  16530. var prop,
  16531. vendors = ['webkit','khtml','moz','ms','o',''];
  16532. if(!css_props || !element.style) {
  16533. return;
  16534. }
  16535. // with css properties for modern browsers
  16536. for(var i = 0; i < vendors.length; i++) {
  16537. for(var p in css_props) {
  16538. if(css_props.hasOwnProperty(p)) {
  16539. prop = p;
  16540. // vender prefix at the property
  16541. if(vendors[i]) {
  16542. prop = vendors[i] + prop.substring(0, 1).toUpperCase() + prop.substring(1);
  16543. }
  16544. // set the style
  16545. element.style[prop] = css_props[p];
  16546. }
  16547. }
  16548. }
  16549. // also the disable onselectstart
  16550. if(css_props.userSelect == 'none') {
  16551. element.onselectstart = function() {
  16552. return false;
  16553. };
  16554. }
  16555. }
  16556. };
  16557. Hammer.detection = {
  16558. // contains all registred Hammer.gestures in the correct order
  16559. gestures: [],
  16560. // data of the current Hammer.gesture detection session
  16561. current: null,
  16562. // the previous Hammer.gesture session data
  16563. // is a full clone of the previous gesture.current object
  16564. previous: null,
  16565. // when this becomes true, no gestures are fired
  16566. stopped: false,
  16567. /**
  16568. * start Hammer.gesture detection
  16569. * @param {Hammer.Instance} inst
  16570. * @param {Object} eventData
  16571. */
  16572. startDetect: function startDetect(inst, eventData) {
  16573. // already busy with a Hammer.gesture detection on an element
  16574. if(this.current) {
  16575. return;
  16576. }
  16577. this.stopped = false;
  16578. this.current = {
  16579. inst : inst, // reference to HammerInstance we're working for
  16580. startEvent : Hammer.utils.extend({}, eventData), // start eventData for distances, timing etc
  16581. lastEvent : false, // last eventData
  16582. name : '' // current gesture we're in/detected, can be 'tap', 'hold' etc
  16583. };
  16584. this.detect(eventData);
  16585. },
  16586. /**
  16587. * Hammer.gesture detection
  16588. * @param {Object} eventData
  16589. * @param {Object} eventData
  16590. */
  16591. detect: function detect(eventData) {
  16592. if(!this.current || this.stopped) {
  16593. return;
  16594. }
  16595. // extend event data with calculations about scale, distance etc
  16596. eventData = this.extendEventData(eventData);
  16597. // instance options
  16598. var inst_options = this.current.inst.options;
  16599. // call Hammer.gesture handlers
  16600. for(var g=0,len=this.gestures.length; g<len; g++) {
  16601. var gesture = this.gestures[g];
  16602. // only when the instance options have enabled this gesture
  16603. if(!this.stopped && inst_options[gesture.name] !== false) {
  16604. // if a handler returns false, we stop with the detection
  16605. if(gesture.handler.call(gesture, eventData, this.current.inst) === false) {
  16606. this.stopDetect();
  16607. break;
  16608. }
  16609. }
  16610. }
  16611. // store as previous event event
  16612. if(this.current) {
  16613. this.current.lastEvent = eventData;
  16614. }
  16615. // endevent, but not the last touch, so dont stop
  16616. if(eventData.eventType == Hammer.EVENT_END && !eventData.touches.length-1) {
  16617. this.stopDetect();
  16618. }
  16619. return eventData;
  16620. },
  16621. /**
  16622. * clear the Hammer.gesture vars
  16623. * this is called on endDetect, but can also be used when a final Hammer.gesture has been detected
  16624. * to stop other Hammer.gestures from being fired
  16625. */
  16626. stopDetect: function stopDetect() {
  16627. // clone current data to the store as the previous gesture
  16628. // used for the double tap gesture, since this is an other gesture detect session
  16629. this.previous = Hammer.utils.extend({}, this.current);
  16630. // reset the current
  16631. this.current = null;
  16632. // stopped!
  16633. this.stopped = true;
  16634. },
  16635. /**
  16636. * extend eventData for Hammer.gestures
  16637. * @param {Object} ev
  16638. * @returns {Object} ev
  16639. */
  16640. extendEventData: function extendEventData(ev) {
  16641. var startEv = this.current.startEvent;
  16642. // if the touches change, set the new touches over the startEvent touches
  16643. // this because touchevents don't have all the touches on touchstart, or the
  16644. // user must place his fingers at the EXACT same time on the screen, which is not realistic
  16645. // but, sometimes it happens that both fingers are touching at the EXACT same time
  16646. if(startEv && (ev.touches.length != startEv.touches.length || ev.touches === startEv.touches)) {
  16647. // extend 1 level deep to get the touchlist with the touch objects
  16648. startEv.touches = [];
  16649. for(var i=0,len=ev.touches.length; i<len; i++) {
  16650. startEv.touches.push(Hammer.utils.extend({}, ev.touches[i]));
  16651. }
  16652. }
  16653. var delta_time = ev.timeStamp - startEv.timeStamp,
  16654. delta_x = ev.center.pageX - startEv.center.pageX,
  16655. delta_y = ev.center.pageY - startEv.center.pageY,
  16656. velocity = Hammer.utils.getVelocity(delta_time, delta_x, delta_y);
  16657. Hammer.utils.extend(ev, {
  16658. deltaTime : delta_time,
  16659. deltaX : delta_x,
  16660. deltaY : delta_y,
  16661. velocityX : velocity.x,
  16662. velocityY : velocity.y,
  16663. distance : Hammer.utils.getDistance(startEv.center, ev.center),
  16664. angle : Hammer.utils.getAngle(startEv.center, ev.center),
  16665. direction : Hammer.utils.getDirection(startEv.center, ev.center),
  16666. scale : Hammer.utils.getScale(startEv.touches, ev.touches),
  16667. rotation : Hammer.utils.getRotation(startEv.touches, ev.touches),
  16668. startEvent : startEv
  16669. });
  16670. return ev;
  16671. },
  16672. /**
  16673. * register new gesture
  16674. * @param {Object} gesture object, see gestures.js for documentation
  16675. * @returns {Array} gestures
  16676. */
  16677. register: function register(gesture) {
  16678. // add an enable gesture options if there is no given
  16679. var options = gesture.defaults || {};
  16680. if(options[gesture.name] === undefined) {
  16681. options[gesture.name] = true;
  16682. }
  16683. // extend Hammer default options with the Hammer.gesture options
  16684. Hammer.utils.extend(Hammer.defaults, options, true);
  16685. // set its index
  16686. gesture.index = gesture.index || 1000;
  16687. // add Hammer.gesture to the list
  16688. this.gestures.push(gesture);
  16689. // sort the list by index
  16690. this.gestures.sort(function(a, b) {
  16691. if (a.index < b.index) {
  16692. return -1;
  16693. }
  16694. if (a.index > b.index) {
  16695. return 1;
  16696. }
  16697. return 0;
  16698. });
  16699. return this.gestures;
  16700. }
  16701. };
  16702. Hammer.gestures = Hammer.gestures || {};
  16703. /**
  16704. * Custom gestures
  16705. * ==============================
  16706. *
  16707. * Gesture object
  16708. * --------------------
  16709. * The object structure of a gesture:
  16710. *
  16711. * { name: 'mygesture',
  16712. * index: 1337,
  16713. * defaults: {
  16714. * mygesture_option: true
  16715. * }
  16716. * handler: function(type, ev, inst) {
  16717. * // trigger gesture event
  16718. * inst.trigger(this.name, ev);
  16719. * }
  16720. * }
  16721. * @param {String} name
  16722. * this should be the name of the gesture, lowercase
  16723. * it is also being used to disable/enable the gesture per instance config.
  16724. *
  16725. * @param {Number} [index=1000]
  16726. * the index of the gesture, where it is going to be in the stack of gestures detection
  16727. * like when you build an gesture that depends on the drag gesture, it is a good
  16728. * idea to place it after the index of the drag gesture.
  16729. *
  16730. * @param {Object} [defaults={}]
  16731. * the default settings of the gesture. these are added to the instance settings,
  16732. * and can be overruled per instance. you can also add the name of the gesture,
  16733. * but this is also added by default (and set to true).
  16734. *
  16735. * @param {Function} handler
  16736. * this handles the gesture detection of your custom gesture and receives the
  16737. * following arguments:
  16738. *
  16739. * @param {Object} eventData
  16740. * event data containing the following properties:
  16741. * timeStamp {Number} time the event occurred
  16742. * target {HTMLElement} target element
  16743. * touches {Array} touches (fingers, pointers, mouse) on the screen
  16744. * pointerType {String} kind of pointer that was used. matches Hammer.POINTER_MOUSE|TOUCH
  16745. * center {Object} center position of the touches. contains pageX and pageY
  16746. * deltaTime {Number} the total time of the touches in the screen
  16747. * deltaX {Number} the delta on x axis we haved moved
  16748. * deltaY {Number} the delta on y axis we haved moved
  16749. * velocityX {Number} the velocity on the x
  16750. * velocityY {Number} the velocity on y
  16751. * angle {Number} the angle we are moving
  16752. * direction {String} the direction we are moving. matches Hammer.DIRECTION_UP|DOWN|LEFT|RIGHT
  16753. * distance {Number} the distance we haved moved
  16754. * scale {Number} scaling of the touches, needs 2 touches
  16755. * rotation {Number} rotation of the touches, needs 2 touches *
  16756. * eventType {String} matches Hammer.EVENT_START|MOVE|END
  16757. * srcEvent {Object} the source event, like TouchStart or MouseDown *
  16758. * startEvent {Object} contains the same properties as above,
  16759. * but from the first touch. this is used to calculate
  16760. * distances, deltaTime, scaling etc
  16761. *
  16762. * @param {Hammer.Instance} inst
  16763. * the instance we are doing the detection for. you can get the options from
  16764. * the inst.options object and trigger the gesture event by calling inst.trigger
  16765. *
  16766. *
  16767. * Handle gestures
  16768. * --------------------
  16769. * inside the handler you can get/set Hammer.detection.current. This is the current
  16770. * detection session. It has the following properties
  16771. * @param {String} name
  16772. * contains the name of the gesture we have detected. it has not a real function,
  16773. * only to check in other gestures if something is detected.
  16774. * like in the drag gesture we set it to 'drag' and in the swipe gesture we can
  16775. * check if the current gesture is 'drag' by accessing Hammer.detection.current.name
  16776. *
  16777. * @readonly
  16778. * @param {Hammer.Instance} inst
  16779. * the instance we do the detection for
  16780. *
  16781. * @readonly
  16782. * @param {Object} startEvent
  16783. * contains the properties of the first gesture detection in this session.
  16784. * Used for calculations about timing, distance, etc.
  16785. *
  16786. * @readonly
  16787. * @param {Object} lastEvent
  16788. * contains all the properties of the last gesture detect in this session.
  16789. *
  16790. * after the gesture detection session has been completed (user has released the screen)
  16791. * the Hammer.detection.current object is copied into Hammer.detection.previous,
  16792. * this is usefull for gestures like doubletap, where you need to know if the
  16793. * previous gesture was a tap
  16794. *
  16795. * options that have been set by the instance can be received by calling inst.options
  16796. *
  16797. * You can trigger a gesture event by calling inst.trigger("mygesture", event).
  16798. * The first param is the name of your gesture, the second the event argument
  16799. *
  16800. *
  16801. * Register gestures
  16802. * --------------------
  16803. * When an gesture is added to the Hammer.gestures object, it is auto registered
  16804. * at the setup of the first Hammer instance. You can also call Hammer.detection.register
  16805. * manually and pass your gesture object as a param
  16806. *
  16807. */
  16808. /**
  16809. * Hold
  16810. * Touch stays at the same place for x time
  16811. * @events hold
  16812. */
  16813. Hammer.gestures.Hold = {
  16814. name: 'hold',
  16815. index: 10,
  16816. defaults: {
  16817. hold_timeout : 500,
  16818. hold_threshold : 1
  16819. },
  16820. timer: null,
  16821. handler: function holdGesture(ev, inst) {
  16822. switch(ev.eventType) {
  16823. case Hammer.EVENT_START:
  16824. // clear any running timers
  16825. clearTimeout(this.timer);
  16826. // set the gesture so we can check in the timeout if it still is
  16827. Hammer.detection.current.name = this.name;
  16828. // set timer and if after the timeout it still is hold,
  16829. // we trigger the hold event
  16830. this.timer = setTimeout(function() {
  16831. if(Hammer.detection.current.name == 'hold') {
  16832. inst.trigger('hold', ev);
  16833. }
  16834. }, inst.options.hold_timeout);
  16835. break;
  16836. // when you move or end we clear the timer
  16837. case Hammer.EVENT_MOVE:
  16838. if(ev.distance > inst.options.hold_threshold) {
  16839. clearTimeout(this.timer);
  16840. }
  16841. break;
  16842. case Hammer.EVENT_END:
  16843. clearTimeout(this.timer);
  16844. break;
  16845. }
  16846. }
  16847. };
  16848. /**
  16849. * Tap/DoubleTap
  16850. * Quick touch at a place or double at the same place
  16851. * @events tap, doubletap
  16852. */
  16853. Hammer.gestures.Tap = {
  16854. name: 'tap',
  16855. index: 100,
  16856. defaults: {
  16857. tap_max_touchtime : 250,
  16858. tap_max_distance : 10,
  16859. tap_always : true,
  16860. doubletap_distance : 20,
  16861. doubletap_interval : 300
  16862. },
  16863. handler: function tapGesture(ev, inst) {
  16864. if(ev.eventType == Hammer.EVENT_END) {
  16865. // previous gesture, for the double tap since these are two different gesture detections
  16866. var prev = Hammer.detection.previous,
  16867. did_doubletap = false;
  16868. // when the touchtime is higher then the max touch time
  16869. // or when the moving distance is too much
  16870. if(ev.deltaTime > inst.options.tap_max_touchtime ||
  16871. ev.distance > inst.options.tap_max_distance) {
  16872. return;
  16873. }
  16874. // check if double tap
  16875. if(prev && prev.name == 'tap' &&
  16876. (ev.timeStamp - prev.lastEvent.timeStamp) < inst.options.doubletap_interval &&
  16877. ev.distance < inst.options.doubletap_distance) {
  16878. inst.trigger('doubletap', ev);
  16879. did_doubletap = true;
  16880. }
  16881. // do a single tap
  16882. if(!did_doubletap || inst.options.tap_always) {
  16883. Hammer.detection.current.name = 'tap';
  16884. inst.trigger(Hammer.detection.current.name, ev);
  16885. }
  16886. }
  16887. }
  16888. };
  16889. /**
  16890. * Swipe
  16891. * triggers swipe events when the end velocity is above the threshold
  16892. * @events swipe, swipeleft, swiperight, swipeup, swipedown
  16893. */
  16894. Hammer.gestures.Swipe = {
  16895. name: 'swipe',
  16896. index: 40,
  16897. defaults: {
  16898. // set 0 for unlimited, but this can conflict with transform
  16899. swipe_max_touches : 1,
  16900. swipe_velocity : 0.7
  16901. },
  16902. handler: function swipeGesture(ev, inst) {
  16903. if(ev.eventType == Hammer.EVENT_END) {
  16904. // max touches
  16905. if(inst.options.swipe_max_touches > 0 &&
  16906. ev.touches.length > inst.options.swipe_max_touches) {
  16907. return;
  16908. }
  16909. // when the distance we moved is too small we skip this gesture
  16910. // or we can be already in dragging
  16911. if(ev.velocityX > inst.options.swipe_velocity ||
  16912. ev.velocityY > inst.options.swipe_velocity) {
  16913. // trigger swipe events
  16914. inst.trigger(this.name, ev);
  16915. inst.trigger(this.name + ev.direction, ev);
  16916. }
  16917. }
  16918. }
  16919. };
  16920. /**
  16921. * Drag
  16922. * Move with x fingers (default 1) around on the page. Blocking the scrolling when
  16923. * moving left and right is a good practice. When all the drag events are blocking
  16924. * you disable scrolling on that area.
  16925. * @events drag, drapleft, dragright, dragup, dragdown
  16926. */
  16927. Hammer.gestures.Drag = {
  16928. name: 'drag',
  16929. index: 50,
  16930. defaults: {
  16931. drag_min_distance : 10,
  16932. // set 0 for unlimited, but this can conflict with transform
  16933. drag_max_touches : 1,
  16934. // prevent default browser behavior when dragging occurs
  16935. // be careful with it, it makes the element a blocking element
  16936. // when you are using the drag gesture, it is a good practice to set this true
  16937. drag_block_horizontal : false,
  16938. drag_block_vertical : false,
  16939. // drag_lock_to_axis keeps the drag gesture on the axis that it started on,
  16940. // It disallows vertical directions if the initial direction was horizontal, and vice versa.
  16941. drag_lock_to_axis : false,
  16942. // drag lock only kicks in when distance > drag_lock_min_distance
  16943. // This way, locking occurs only when the distance has become large enough to reliably determine the direction
  16944. drag_lock_min_distance : 25
  16945. },
  16946. triggered: false,
  16947. handler: function dragGesture(ev, inst) {
  16948. // current gesture isnt drag, but dragged is true
  16949. // this means an other gesture is busy. now call dragend
  16950. if(Hammer.detection.current.name != this.name && this.triggered) {
  16951. inst.trigger(this.name +'end', ev);
  16952. this.triggered = false;
  16953. return;
  16954. }
  16955. // max touches
  16956. if(inst.options.drag_max_touches > 0 &&
  16957. ev.touches.length > inst.options.drag_max_touches) {
  16958. return;
  16959. }
  16960. switch(ev.eventType) {
  16961. case Hammer.EVENT_START:
  16962. this.triggered = false;
  16963. break;
  16964. case Hammer.EVENT_MOVE:
  16965. // when the distance we moved is too small we skip this gesture
  16966. // or we can be already in dragging
  16967. if(ev.distance < inst.options.drag_min_distance &&
  16968. Hammer.detection.current.name != this.name) {
  16969. return;
  16970. }
  16971. // we are dragging!
  16972. Hammer.detection.current.name = this.name;
  16973. // lock drag to axis?
  16974. if(Hammer.detection.current.lastEvent.drag_locked_to_axis || (inst.options.drag_lock_to_axis && inst.options.drag_lock_min_distance<=ev.distance)) {
  16975. ev.drag_locked_to_axis = true;
  16976. }
  16977. var last_direction = Hammer.detection.current.lastEvent.direction;
  16978. if(ev.drag_locked_to_axis && last_direction !== ev.direction) {
  16979. // keep direction on the axis that the drag gesture started on
  16980. if(Hammer.utils.isVertical(last_direction)) {
  16981. ev.direction = (ev.deltaY < 0) ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  16982. }
  16983. else {
  16984. ev.direction = (ev.deltaX < 0) ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  16985. }
  16986. }
  16987. // first time, trigger dragstart event
  16988. if(!this.triggered) {
  16989. inst.trigger(this.name +'start', ev);
  16990. this.triggered = true;
  16991. }
  16992. // trigger normal event
  16993. inst.trigger(this.name, ev);
  16994. // direction event, like dragdown
  16995. inst.trigger(this.name + ev.direction, ev);
  16996. // block the browser events
  16997. if( (inst.options.drag_block_vertical && Hammer.utils.isVertical(ev.direction)) ||
  16998. (inst.options.drag_block_horizontal && !Hammer.utils.isVertical(ev.direction))) {
  16999. ev.preventDefault();
  17000. }
  17001. break;
  17002. case Hammer.EVENT_END:
  17003. // trigger dragend
  17004. if(this.triggered) {
  17005. inst.trigger(this.name +'end', ev);
  17006. }
  17007. this.triggered = false;
  17008. break;
  17009. }
  17010. }
  17011. };
  17012. /**
  17013. * Transform
  17014. * User want to scale or rotate with 2 fingers
  17015. * @events transform, pinch, pinchin, pinchout, rotate
  17016. */
  17017. Hammer.gestures.Transform = {
  17018. name: 'transform',
  17019. index: 45,
  17020. defaults: {
  17021. // factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1
  17022. transform_min_scale : 0.01,
  17023. // rotation in degrees
  17024. transform_min_rotation : 1,
  17025. // prevent default browser behavior when two touches are on the screen
  17026. // but it makes the element a blocking element
  17027. // when you are using the transform gesture, it is a good practice to set this true
  17028. transform_always_block : false
  17029. },
  17030. triggered: false,
  17031. handler: function transformGesture(ev, inst) {
  17032. // current gesture isnt drag, but dragged is true
  17033. // this means an other gesture is busy. now call dragend
  17034. if(Hammer.detection.current.name != this.name && this.triggered) {
  17035. inst.trigger(this.name +'end', ev);
  17036. this.triggered = false;
  17037. return;
  17038. }
  17039. // atleast multitouch
  17040. if(ev.touches.length < 2) {
  17041. return;
  17042. }
  17043. // prevent default when two fingers are on the screen
  17044. if(inst.options.transform_always_block) {
  17045. ev.preventDefault();
  17046. }
  17047. switch(ev.eventType) {
  17048. case Hammer.EVENT_START:
  17049. this.triggered = false;
  17050. break;
  17051. case Hammer.EVENT_MOVE:
  17052. var scale_threshold = Math.abs(1-ev.scale);
  17053. var rotation_threshold = Math.abs(ev.rotation);
  17054. // when the distance we moved is too small we skip this gesture
  17055. // or we can be already in dragging
  17056. if(scale_threshold < inst.options.transform_min_scale &&
  17057. rotation_threshold < inst.options.transform_min_rotation) {
  17058. return;
  17059. }
  17060. // we are transforming!
  17061. Hammer.detection.current.name = this.name;
  17062. // first time, trigger dragstart event
  17063. if(!this.triggered) {
  17064. inst.trigger(this.name +'start', ev);
  17065. this.triggered = true;
  17066. }
  17067. inst.trigger(this.name, ev); // basic transform event
  17068. // trigger rotate event
  17069. if(rotation_threshold > inst.options.transform_min_rotation) {
  17070. inst.trigger('rotate', ev);
  17071. }
  17072. // trigger pinch event
  17073. if(scale_threshold > inst.options.transform_min_scale) {
  17074. inst.trigger('pinch', ev);
  17075. inst.trigger('pinch'+ ((ev.scale < 1) ? 'in' : 'out'), ev);
  17076. }
  17077. break;
  17078. case Hammer.EVENT_END:
  17079. // trigger dragend
  17080. if(this.triggered) {
  17081. inst.trigger(this.name +'end', ev);
  17082. }
  17083. this.triggered = false;
  17084. break;
  17085. }
  17086. }
  17087. };
  17088. /**
  17089. * Touch
  17090. * Called as first, tells the user has touched the screen
  17091. * @events touch
  17092. */
  17093. Hammer.gestures.Touch = {
  17094. name: 'touch',
  17095. index: -Infinity,
  17096. defaults: {
  17097. // call preventDefault at touchstart, and makes the element blocking by
  17098. // disabling the scrolling of the page, but it improves gestures like
  17099. // transforming and dragging.
  17100. // be careful with using this, it can be very annoying for users to be stuck
  17101. // on the page
  17102. prevent_default: false,
  17103. // disable mouse events, so only touch (or pen!) input triggers events
  17104. prevent_mouseevents: false
  17105. },
  17106. handler: function touchGesture(ev, inst) {
  17107. if(inst.options.prevent_mouseevents && ev.pointerType == Hammer.POINTER_MOUSE) {
  17108. ev.stopDetect();
  17109. return;
  17110. }
  17111. if(inst.options.prevent_default) {
  17112. ev.preventDefault();
  17113. }
  17114. if(ev.eventType == Hammer.EVENT_START) {
  17115. inst.trigger(this.name, ev);
  17116. }
  17117. }
  17118. };
  17119. /**
  17120. * Release
  17121. * Called as last, tells the user has released the screen
  17122. * @events release
  17123. */
  17124. Hammer.gestures.Release = {
  17125. name: 'release',
  17126. index: Infinity,
  17127. handler: function releaseGesture(ev, inst) {
  17128. if(ev.eventType == Hammer.EVENT_END) {
  17129. inst.trigger(this.name, ev);
  17130. }
  17131. }
  17132. };
  17133. // node export
  17134. if(typeof module === 'object' && typeof module.exports === 'object'){
  17135. module.exports = Hammer;
  17136. }
  17137. // just window export
  17138. else {
  17139. window.Hammer = Hammer;
  17140. // requireJS module definition
  17141. if(typeof window.define === 'function' && window.define.amd) {
  17142. window.define('hammer', [], function() {
  17143. return Hammer;
  17144. });
  17145. }
  17146. }
  17147. })(this);
  17148. },{}],4:[function(require,module,exports){
  17149. var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};//! moment.js
  17150. //! version : 2.6.0
  17151. //! authors : Tim Wood, Iskren Chernev, Moment.js contributors
  17152. //! license : MIT
  17153. //! momentjs.com
  17154. (function (undefined) {
  17155. /************************************
  17156. Constants
  17157. ************************************/
  17158. var moment,
  17159. VERSION = "2.6.0",
  17160. // the global-scope this is NOT the global object in Node.js
  17161. globalScope = typeof global !== 'undefined' ? global : this,
  17162. oldGlobalMoment,
  17163. round = Math.round,
  17164. i,
  17165. YEAR = 0,
  17166. MONTH = 1,
  17167. DATE = 2,
  17168. HOUR = 3,
  17169. MINUTE = 4,
  17170. SECOND = 5,
  17171. MILLISECOND = 6,
  17172. // internal storage for language config files
  17173. languages = {},
  17174. // moment internal properties
  17175. momentProperties = {
  17176. _isAMomentObject: null,
  17177. _i : null,
  17178. _f : null,
  17179. _l : null,
  17180. _strict : null,
  17181. _isUTC : null,
  17182. _offset : null, // optional. Combine with _isUTC
  17183. _pf : null,
  17184. _lang : null // optional
  17185. },
  17186. // check for nodeJS
  17187. hasModule = (typeof module !== 'undefined' && module.exports),
  17188. // ASP.NET json date format regex
  17189. aspNetJsonRegex = /^\/?Date\((\-?\d+)/i,
  17190. aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,
  17191. // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
  17192. // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
  17193. isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/,
  17194. // format tokens
  17195. 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,
  17196. localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g,
  17197. // parsing token regexes
  17198. parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99
  17199. parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999
  17200. parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999
  17201. parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999
  17202. parseTokenDigits = /\d+/, // nonzero number of digits
  17203. 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.
  17204. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z
  17205. parseTokenT = /T/i, // T (ISO separator)
  17206. parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
  17207. parseTokenOrdinal = /\d{1,2}/,
  17208. //strict parsing regexes
  17209. parseTokenOneDigit = /\d/, // 0 - 9
  17210. parseTokenTwoDigits = /\d\d/, // 00 - 99
  17211. parseTokenThreeDigits = /\d{3}/, // 000 - 999
  17212. parseTokenFourDigits = /\d{4}/, // 0000 - 9999
  17213. parseTokenSixDigits = /[+-]?\d{6}/, // -999,999 - 999,999
  17214. parseTokenSignedNumber = /[+-]?\d+/, // -inf - inf
  17215. // iso 8601 regex
  17216. // 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)
  17217. 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)?)?$/,
  17218. isoFormat = 'YYYY-MM-DDTHH:mm:ssZ',
  17219. isoDates = [
  17220. ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/],
  17221. ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/],
  17222. ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/],
  17223. ['GGGG-[W]WW', /\d{4}-W\d{2}/],
  17224. ['YYYY-DDD', /\d{4}-\d{3}/]
  17225. ],
  17226. // iso time formats and regexes
  17227. isoTimes = [
  17228. ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d+/],
  17229. ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/],
  17230. ['HH:mm', /(T| )\d\d:\d\d/],
  17231. ['HH', /(T| )\d\d/]
  17232. ],
  17233. // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"]
  17234. parseTimezoneChunker = /([\+\-]|\d\d)/gi,
  17235. // getter and setter names
  17236. proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'),
  17237. unitMillisecondFactors = {
  17238. 'Milliseconds' : 1,
  17239. 'Seconds' : 1e3,
  17240. 'Minutes' : 6e4,
  17241. 'Hours' : 36e5,
  17242. 'Days' : 864e5,
  17243. 'Months' : 2592e6,
  17244. 'Years' : 31536e6
  17245. },
  17246. unitAliases = {
  17247. ms : 'millisecond',
  17248. s : 'second',
  17249. m : 'minute',
  17250. h : 'hour',
  17251. d : 'day',
  17252. D : 'date',
  17253. w : 'week',
  17254. W : 'isoWeek',
  17255. M : 'month',
  17256. Q : 'quarter',
  17257. y : 'year',
  17258. DDD : 'dayOfYear',
  17259. e : 'weekday',
  17260. E : 'isoWeekday',
  17261. gg: 'weekYear',
  17262. GG: 'isoWeekYear'
  17263. },
  17264. camelFunctions = {
  17265. dayofyear : 'dayOfYear',
  17266. isoweekday : 'isoWeekday',
  17267. isoweek : 'isoWeek',
  17268. weekyear : 'weekYear',
  17269. isoweekyear : 'isoWeekYear'
  17270. },
  17271. // format function strings
  17272. formatFunctions = {},
  17273. // tokens to ordinalize and pad
  17274. ordinalizeTokens = 'DDD w W M D d'.split(' '),
  17275. paddedTokens = 'M D H h m s w W'.split(' '),
  17276. formatTokenFunctions = {
  17277. M : function () {
  17278. return this.month() + 1;
  17279. },
  17280. MMM : function (format) {
  17281. return this.lang().monthsShort(this, format);
  17282. },
  17283. MMMM : function (format) {
  17284. return this.lang().months(this, format);
  17285. },
  17286. D : function () {
  17287. return this.date();
  17288. },
  17289. DDD : function () {
  17290. return this.dayOfYear();
  17291. },
  17292. d : function () {
  17293. return this.day();
  17294. },
  17295. dd : function (format) {
  17296. return this.lang().weekdaysMin(this, format);
  17297. },
  17298. ddd : function (format) {
  17299. return this.lang().weekdaysShort(this, format);
  17300. },
  17301. dddd : function (format) {
  17302. return this.lang().weekdays(this, format);
  17303. },
  17304. w : function () {
  17305. return this.week();
  17306. },
  17307. W : function () {
  17308. return this.isoWeek();
  17309. },
  17310. YY : function () {
  17311. return leftZeroFill(this.year() % 100, 2);
  17312. },
  17313. YYYY : function () {
  17314. return leftZeroFill(this.year(), 4);
  17315. },
  17316. YYYYY : function () {
  17317. return leftZeroFill(this.year(), 5);
  17318. },
  17319. YYYYYY : function () {
  17320. var y = this.year(), sign = y >= 0 ? '+' : '-';
  17321. return sign + leftZeroFill(Math.abs(y), 6);
  17322. },
  17323. gg : function () {
  17324. return leftZeroFill(this.weekYear() % 100, 2);
  17325. },
  17326. gggg : function () {
  17327. return leftZeroFill(this.weekYear(), 4);
  17328. },
  17329. ggggg : function () {
  17330. return leftZeroFill(this.weekYear(), 5);
  17331. },
  17332. GG : function () {
  17333. return leftZeroFill(this.isoWeekYear() % 100, 2);
  17334. },
  17335. GGGG : function () {
  17336. return leftZeroFill(this.isoWeekYear(), 4);
  17337. },
  17338. GGGGG : function () {
  17339. return leftZeroFill(this.isoWeekYear(), 5);
  17340. },
  17341. e : function () {
  17342. return this.weekday();
  17343. },
  17344. E : function () {
  17345. return this.isoWeekday();
  17346. },
  17347. a : function () {
  17348. return this.lang().meridiem(this.hours(), this.minutes(), true);
  17349. },
  17350. A : function () {
  17351. return this.lang().meridiem(this.hours(), this.minutes(), false);
  17352. },
  17353. H : function () {
  17354. return this.hours();
  17355. },
  17356. h : function () {
  17357. return this.hours() % 12 || 12;
  17358. },
  17359. m : function () {
  17360. return this.minutes();
  17361. },
  17362. s : function () {
  17363. return this.seconds();
  17364. },
  17365. S : function () {
  17366. return toInt(this.milliseconds() / 100);
  17367. },
  17368. SS : function () {
  17369. return leftZeroFill(toInt(this.milliseconds() / 10), 2);
  17370. },
  17371. SSS : function () {
  17372. return leftZeroFill(this.milliseconds(), 3);
  17373. },
  17374. SSSS : function () {
  17375. return leftZeroFill(this.milliseconds(), 3);
  17376. },
  17377. Z : function () {
  17378. var a = -this.zone(),
  17379. b = "+";
  17380. if (a < 0) {
  17381. a = -a;
  17382. b = "-";
  17383. }
  17384. return b + leftZeroFill(toInt(a / 60), 2) + ":" + leftZeroFill(toInt(a) % 60, 2);
  17385. },
  17386. ZZ : function () {
  17387. var a = -this.zone(),
  17388. b = "+";
  17389. if (a < 0) {
  17390. a = -a;
  17391. b = "-";
  17392. }
  17393. return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2);
  17394. },
  17395. z : function () {
  17396. return this.zoneAbbr();
  17397. },
  17398. zz : function () {
  17399. return this.zoneName();
  17400. },
  17401. X : function () {
  17402. return this.unix();
  17403. },
  17404. Q : function () {
  17405. return this.quarter();
  17406. }
  17407. },
  17408. lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin'];
  17409. function defaultParsingFlags() {
  17410. // We need to deep clone this object, and es5 standard is not very
  17411. // helpful.
  17412. return {
  17413. empty : false,
  17414. unusedTokens : [],
  17415. unusedInput : [],
  17416. overflow : -2,
  17417. charsLeftOver : 0,
  17418. nullInput : false,
  17419. invalidMonth : null,
  17420. invalidFormat : false,
  17421. userInvalidated : false,
  17422. iso: false
  17423. };
  17424. }
  17425. function deprecate(msg, fn) {
  17426. var firstTime = true;
  17427. function printMsg() {
  17428. if (moment.suppressDeprecationWarnings === false &&
  17429. typeof console !== 'undefined' && console.warn) {
  17430. console.warn("Deprecation warning: " + msg);
  17431. }
  17432. }
  17433. return extend(function () {
  17434. if (firstTime) {
  17435. printMsg();
  17436. firstTime = false;
  17437. }
  17438. return fn.apply(this, arguments);
  17439. }, fn);
  17440. }
  17441. function padToken(func, count) {
  17442. return function (a) {
  17443. return leftZeroFill(func.call(this, a), count);
  17444. };
  17445. }
  17446. function ordinalizeToken(func, period) {
  17447. return function (a) {
  17448. return this.lang().ordinal(func.call(this, a), period);
  17449. };
  17450. }
  17451. while (ordinalizeTokens.length) {
  17452. i = ordinalizeTokens.pop();
  17453. formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i);
  17454. }
  17455. while (paddedTokens.length) {
  17456. i = paddedTokens.pop();
  17457. formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2);
  17458. }
  17459. formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3);
  17460. /************************************
  17461. Constructors
  17462. ************************************/
  17463. function Language() {
  17464. }
  17465. // Moment prototype object
  17466. function Moment(config) {
  17467. checkOverflow(config);
  17468. extend(this, config);
  17469. }
  17470. // Duration Constructor
  17471. function Duration(duration) {
  17472. var normalizedInput = normalizeObjectUnits(duration),
  17473. years = normalizedInput.year || 0,
  17474. quarters = normalizedInput.quarter || 0,
  17475. months = normalizedInput.month || 0,
  17476. weeks = normalizedInput.week || 0,
  17477. days = normalizedInput.day || 0,
  17478. hours = normalizedInput.hour || 0,
  17479. minutes = normalizedInput.minute || 0,
  17480. seconds = normalizedInput.second || 0,
  17481. milliseconds = normalizedInput.millisecond || 0;
  17482. // representation for dateAddRemove
  17483. this._milliseconds = +milliseconds +
  17484. seconds * 1e3 + // 1000
  17485. minutes * 6e4 + // 1000 * 60
  17486. hours * 36e5; // 1000 * 60 * 60
  17487. // Because of dateAddRemove treats 24 hours as different from a
  17488. // day when working around DST, we need to store them separately
  17489. this._days = +days +
  17490. weeks * 7;
  17491. // It is impossible translate months into days without knowing
  17492. // which months you are are talking about, so we have to store
  17493. // it separately.
  17494. this._months = +months +
  17495. quarters * 3 +
  17496. years * 12;
  17497. this._data = {};
  17498. this._bubble();
  17499. }
  17500. /************************************
  17501. Helpers
  17502. ************************************/
  17503. function extend(a, b) {
  17504. for (var i in b) {
  17505. if (b.hasOwnProperty(i)) {
  17506. a[i] = b[i];
  17507. }
  17508. }
  17509. if (b.hasOwnProperty("toString")) {
  17510. a.toString = b.toString;
  17511. }
  17512. if (b.hasOwnProperty("valueOf")) {
  17513. a.valueOf = b.valueOf;
  17514. }
  17515. return a;
  17516. }
  17517. function cloneMoment(m) {
  17518. var result = {}, i;
  17519. for (i in m) {
  17520. if (m.hasOwnProperty(i) && momentProperties.hasOwnProperty(i)) {
  17521. result[i] = m[i];
  17522. }
  17523. }
  17524. return result;
  17525. }
  17526. function absRound(number) {
  17527. if (number < 0) {
  17528. return Math.ceil(number);
  17529. } else {
  17530. return Math.floor(number);
  17531. }
  17532. }
  17533. // left zero fill a number
  17534. // see http://jsperf.com/left-zero-filling for performance comparison
  17535. function leftZeroFill(number, targetLength, forceSign) {
  17536. var output = '' + Math.abs(number),
  17537. sign = number >= 0;
  17538. while (output.length < targetLength) {
  17539. output = '0' + output;
  17540. }
  17541. return (sign ? (forceSign ? '+' : '') : '-') + output;
  17542. }
  17543. // helper function for _.addTime and _.subtractTime
  17544. function addOrSubtractDurationFromMoment(mom, duration, isAdding, updateOffset) {
  17545. var milliseconds = duration._milliseconds,
  17546. days = duration._days,
  17547. months = duration._months;
  17548. updateOffset = updateOffset == null ? true : updateOffset;
  17549. if (milliseconds) {
  17550. mom._d.setTime(+mom._d + milliseconds * isAdding);
  17551. }
  17552. if (days) {
  17553. rawSetter(mom, 'Date', rawGetter(mom, 'Date') + days * isAdding);
  17554. }
  17555. if (months) {
  17556. rawMonthSetter(mom, rawGetter(mom, 'Month') + months * isAdding);
  17557. }
  17558. if (updateOffset) {
  17559. moment.updateOffset(mom, days || months);
  17560. }
  17561. }
  17562. // check if is an array
  17563. function isArray(input) {
  17564. return Object.prototype.toString.call(input) === '[object Array]';
  17565. }
  17566. function isDate(input) {
  17567. return Object.prototype.toString.call(input) === '[object Date]' ||
  17568. input instanceof Date;
  17569. }
  17570. // compare two arrays, return the number of differences
  17571. function compareArrays(array1, array2, dontConvert) {
  17572. var len = Math.min(array1.length, array2.length),
  17573. lengthDiff = Math.abs(array1.length - array2.length),
  17574. diffs = 0,
  17575. i;
  17576. for (i = 0; i < len; i++) {
  17577. if ((dontConvert && array1[i] !== array2[i]) ||
  17578. (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
  17579. diffs++;
  17580. }
  17581. }
  17582. return diffs + lengthDiff;
  17583. }
  17584. function normalizeUnits(units) {
  17585. if (units) {
  17586. var lowered = units.toLowerCase().replace(/(.)s$/, '$1');
  17587. units = unitAliases[units] || camelFunctions[lowered] || lowered;
  17588. }
  17589. return units;
  17590. }
  17591. function normalizeObjectUnits(inputObject) {
  17592. var normalizedInput = {},
  17593. normalizedProp,
  17594. prop;
  17595. for (prop in inputObject) {
  17596. if (inputObject.hasOwnProperty(prop)) {
  17597. normalizedProp = normalizeUnits(prop);
  17598. if (normalizedProp) {
  17599. normalizedInput[normalizedProp] = inputObject[prop];
  17600. }
  17601. }
  17602. }
  17603. return normalizedInput;
  17604. }
  17605. function makeList(field) {
  17606. var count, setter;
  17607. if (field.indexOf('week') === 0) {
  17608. count = 7;
  17609. setter = 'day';
  17610. }
  17611. else if (field.indexOf('month') === 0) {
  17612. count = 12;
  17613. setter = 'month';
  17614. }
  17615. else {
  17616. return;
  17617. }
  17618. moment[field] = function (format, index) {
  17619. var i, getter,
  17620. method = moment.fn._lang[field],
  17621. results = [];
  17622. if (typeof format === 'number') {
  17623. index = format;
  17624. format = undefined;
  17625. }
  17626. getter = function (i) {
  17627. var m = moment().utc().set(setter, i);
  17628. return method.call(moment.fn._lang, m, format || '');
  17629. };
  17630. if (index != null) {
  17631. return getter(index);
  17632. }
  17633. else {
  17634. for (i = 0; i < count; i++) {
  17635. results.push(getter(i));
  17636. }
  17637. return results;
  17638. }
  17639. };
  17640. }
  17641. function toInt(argumentForCoercion) {
  17642. var coercedNumber = +argumentForCoercion,
  17643. value = 0;
  17644. if (coercedNumber !== 0 && isFinite(coercedNumber)) {
  17645. if (coercedNumber >= 0) {
  17646. value = Math.floor(coercedNumber);
  17647. } else {
  17648. value = Math.ceil(coercedNumber);
  17649. }
  17650. }
  17651. return value;
  17652. }
  17653. function daysInMonth(year, month) {
  17654. return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
  17655. }
  17656. function weeksInYear(year, dow, doy) {
  17657. return weekOfYear(moment([year, 11, 31 + dow - doy]), dow, doy).week;
  17658. }
  17659. function daysInYear(year) {
  17660. return isLeapYear(year) ? 366 : 365;
  17661. }
  17662. function isLeapYear(year) {
  17663. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  17664. }
  17665. function checkOverflow(m) {
  17666. var overflow;
  17667. if (m._a && m._pf.overflow === -2) {
  17668. overflow =
  17669. m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH :
  17670. m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE :
  17671. m._a[HOUR] < 0 || m._a[HOUR] > 23 ? HOUR :
  17672. m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE :
  17673. m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND :
  17674. m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND :
  17675. -1;
  17676. if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
  17677. overflow = DATE;
  17678. }
  17679. m._pf.overflow = overflow;
  17680. }
  17681. }
  17682. function isValid(m) {
  17683. if (m._isValid == null) {
  17684. m._isValid = !isNaN(m._d.getTime()) &&
  17685. m._pf.overflow < 0 &&
  17686. !m._pf.empty &&
  17687. !m._pf.invalidMonth &&
  17688. !m._pf.nullInput &&
  17689. !m._pf.invalidFormat &&
  17690. !m._pf.userInvalidated;
  17691. if (m._strict) {
  17692. m._isValid = m._isValid &&
  17693. m._pf.charsLeftOver === 0 &&
  17694. m._pf.unusedTokens.length === 0;
  17695. }
  17696. }
  17697. return m._isValid;
  17698. }
  17699. function normalizeLanguage(key) {
  17700. return key ? key.toLowerCase().replace('_', '-') : key;
  17701. }
  17702. // Return a moment from input, that is local/utc/zone equivalent to model.
  17703. function makeAs(input, model) {
  17704. return model._isUTC ? moment(input).zone(model._offset || 0) :
  17705. moment(input).local();
  17706. }
  17707. /************************************
  17708. Languages
  17709. ************************************/
  17710. extend(Language.prototype, {
  17711. set : function (config) {
  17712. var prop, i;
  17713. for (i in config) {
  17714. prop = config[i];
  17715. if (typeof prop === 'function') {
  17716. this[i] = prop;
  17717. } else {
  17718. this['_' + i] = prop;
  17719. }
  17720. }
  17721. },
  17722. _months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
  17723. months : function (m) {
  17724. return this._months[m.month()];
  17725. },
  17726. _monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),
  17727. monthsShort : function (m) {
  17728. return this._monthsShort[m.month()];
  17729. },
  17730. monthsParse : function (monthName) {
  17731. var i, mom, regex;
  17732. if (!this._monthsParse) {
  17733. this._monthsParse = [];
  17734. }
  17735. for (i = 0; i < 12; i++) {
  17736. // make the regex if we don't have it already
  17737. if (!this._monthsParse[i]) {
  17738. mom = moment.utc([2000, i]);
  17739. regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  17740. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  17741. }
  17742. // test the regex
  17743. if (this._monthsParse[i].test(monthName)) {
  17744. return i;
  17745. }
  17746. }
  17747. },
  17748. _weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
  17749. weekdays : function (m) {
  17750. return this._weekdays[m.day()];
  17751. },
  17752. _weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),
  17753. weekdaysShort : function (m) {
  17754. return this._weekdaysShort[m.day()];
  17755. },
  17756. _weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"),
  17757. weekdaysMin : function (m) {
  17758. return this._weekdaysMin[m.day()];
  17759. },
  17760. weekdaysParse : function (weekdayName) {
  17761. var i, mom, regex;
  17762. if (!this._weekdaysParse) {
  17763. this._weekdaysParse = [];
  17764. }
  17765. for (i = 0; i < 7; i++) {
  17766. // make the regex if we don't have it already
  17767. if (!this._weekdaysParse[i]) {
  17768. mom = moment([2000, 1]).day(i);
  17769. regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
  17770. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  17771. }
  17772. // test the regex
  17773. if (this._weekdaysParse[i].test(weekdayName)) {
  17774. return i;
  17775. }
  17776. }
  17777. },
  17778. _longDateFormat : {
  17779. LT : "h:mm A",
  17780. L : "MM/DD/YYYY",
  17781. LL : "MMMM D YYYY",
  17782. LLL : "MMMM D YYYY LT",
  17783. LLLL : "dddd, MMMM D YYYY LT"
  17784. },
  17785. longDateFormat : function (key) {
  17786. var output = this._longDateFormat[key];
  17787. if (!output && this._longDateFormat[key.toUpperCase()]) {
  17788. output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) {
  17789. return val.slice(1);
  17790. });
  17791. this._longDateFormat[key] = output;
  17792. }
  17793. return output;
  17794. },
  17795. isPM : function (input) {
  17796. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  17797. // Using charAt should be more compatible.
  17798. return ((input + '').toLowerCase().charAt(0) === 'p');
  17799. },
  17800. _meridiemParse : /[ap]\.?m?\.?/i,
  17801. meridiem : function (hours, minutes, isLower) {
  17802. if (hours > 11) {
  17803. return isLower ? 'pm' : 'PM';
  17804. } else {
  17805. return isLower ? 'am' : 'AM';
  17806. }
  17807. },
  17808. _calendar : {
  17809. sameDay : '[Today at] LT',
  17810. nextDay : '[Tomorrow at] LT',
  17811. nextWeek : 'dddd [at] LT',
  17812. lastDay : '[Yesterday at] LT',
  17813. lastWeek : '[Last] dddd [at] LT',
  17814. sameElse : 'L'
  17815. },
  17816. calendar : function (key, mom) {
  17817. var output = this._calendar[key];
  17818. return typeof output === 'function' ? output.apply(mom) : output;
  17819. },
  17820. _relativeTime : {
  17821. future : "in %s",
  17822. past : "%s ago",
  17823. s : "a few seconds",
  17824. m : "a minute",
  17825. mm : "%d minutes",
  17826. h : "an hour",
  17827. hh : "%d hours",
  17828. d : "a day",
  17829. dd : "%d days",
  17830. M : "a month",
  17831. MM : "%d months",
  17832. y : "a year",
  17833. yy : "%d years"
  17834. },
  17835. relativeTime : function (number, withoutSuffix, string, isFuture) {
  17836. var output = this._relativeTime[string];
  17837. return (typeof output === 'function') ?
  17838. output(number, withoutSuffix, string, isFuture) :
  17839. output.replace(/%d/i, number);
  17840. },
  17841. pastFuture : function (diff, output) {
  17842. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  17843. return typeof format === 'function' ? format(output) : format.replace(/%s/i, output);
  17844. },
  17845. ordinal : function (number) {
  17846. return this._ordinal.replace("%d", number);
  17847. },
  17848. _ordinal : "%d",
  17849. preparse : function (string) {
  17850. return string;
  17851. },
  17852. postformat : function (string) {
  17853. return string;
  17854. },
  17855. week : function (mom) {
  17856. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  17857. },
  17858. _week : {
  17859. dow : 0, // Sunday is the first day of the week.
  17860. doy : 6 // The week that contains Jan 1st is the first week of the year.
  17861. },
  17862. _invalidDate: 'Invalid date',
  17863. invalidDate: function () {
  17864. return this._invalidDate;
  17865. }
  17866. });
  17867. // Loads a language definition into the `languages` cache. The function
  17868. // takes a key and optionally values. If not in the browser and no values
  17869. // are provided, it will load the language file module. As a convenience,
  17870. // this function also returns the language values.
  17871. function loadLang(key, values) {
  17872. values.abbr = key;
  17873. if (!languages[key]) {
  17874. languages[key] = new Language();
  17875. }
  17876. languages[key].set(values);
  17877. return languages[key];
  17878. }
  17879. // Remove a language from the `languages` cache. Mostly useful in tests.
  17880. function unloadLang(key) {
  17881. delete languages[key];
  17882. }
  17883. // Determines which language definition to use and returns it.
  17884. //
  17885. // With no parameters, it will return the global language. If you
  17886. // pass in a language key, such as 'en', it will return the
  17887. // definition for 'en', so long as 'en' has already been loaded using
  17888. // moment.lang.
  17889. function getLangDefinition(key) {
  17890. var i = 0, j, lang, next, split,
  17891. get = function (k) {
  17892. if (!languages[k] && hasModule) {
  17893. try {
  17894. require('./lang/' + k);
  17895. } catch (e) { }
  17896. }
  17897. return languages[k];
  17898. };
  17899. if (!key) {
  17900. return moment.fn._lang;
  17901. }
  17902. if (!isArray(key)) {
  17903. //short-circuit everything else
  17904. lang = get(key);
  17905. if (lang) {
  17906. return lang;
  17907. }
  17908. key = [key];
  17909. }
  17910. //pick the language from the array
  17911. //try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
  17912. //substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
  17913. while (i < key.length) {
  17914. split = normalizeLanguage(key[i]).split('-');
  17915. j = split.length;
  17916. next = normalizeLanguage(key[i + 1]);
  17917. next = next ? next.split('-') : null;
  17918. while (j > 0) {
  17919. lang = get(split.slice(0, j).join('-'));
  17920. if (lang) {
  17921. return lang;
  17922. }
  17923. if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
  17924. //the next array item is better than a shallower substring of this one
  17925. break;
  17926. }
  17927. j--;
  17928. }
  17929. i++;
  17930. }
  17931. return moment.fn._lang;
  17932. }
  17933. /************************************
  17934. Formatting
  17935. ************************************/
  17936. function removeFormattingTokens(input) {
  17937. if (input.match(/\[[\s\S]/)) {
  17938. return input.replace(/^\[|\]$/g, "");
  17939. }
  17940. return input.replace(/\\/g, "");
  17941. }
  17942. function makeFormatFunction(format) {
  17943. var array = format.match(formattingTokens), i, length;
  17944. for (i = 0, length = array.length; i < length; i++) {
  17945. if (formatTokenFunctions[array[i]]) {
  17946. array[i] = formatTokenFunctions[array[i]];
  17947. } else {
  17948. array[i] = removeFormattingTokens(array[i]);
  17949. }
  17950. }
  17951. return function (mom) {
  17952. var output = "";
  17953. for (i = 0; i < length; i++) {
  17954. output += array[i] instanceof Function ? array[i].call(mom, format) : array[i];
  17955. }
  17956. return output;
  17957. };
  17958. }
  17959. // format date using native date object
  17960. function formatMoment(m, format) {
  17961. if (!m.isValid()) {
  17962. return m.lang().invalidDate();
  17963. }
  17964. format = expandFormat(format, m.lang());
  17965. if (!formatFunctions[format]) {
  17966. formatFunctions[format] = makeFormatFunction(format);
  17967. }
  17968. return formatFunctions[format](m);
  17969. }
  17970. function expandFormat(format, lang) {
  17971. var i = 5;
  17972. function replaceLongDateFormatTokens(input) {
  17973. return lang.longDateFormat(input) || input;
  17974. }
  17975. localFormattingTokens.lastIndex = 0;
  17976. while (i >= 0 && localFormattingTokens.test(format)) {
  17977. format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
  17978. localFormattingTokens.lastIndex = 0;
  17979. i -= 1;
  17980. }
  17981. return format;
  17982. }
  17983. /************************************
  17984. Parsing
  17985. ************************************/
  17986. // get the regex to find the next token
  17987. function getParseRegexForToken(token, config) {
  17988. var a, strict = config._strict;
  17989. switch (token) {
  17990. case 'Q':
  17991. return parseTokenOneDigit;
  17992. case 'DDDD':
  17993. return parseTokenThreeDigits;
  17994. case 'YYYY':
  17995. case 'GGGG':
  17996. case 'gggg':
  17997. return strict ? parseTokenFourDigits : parseTokenOneToFourDigits;
  17998. case 'Y':
  17999. case 'G':
  18000. case 'g':
  18001. return parseTokenSignedNumber;
  18002. case 'YYYYYY':
  18003. case 'YYYYY':
  18004. case 'GGGGG':
  18005. case 'ggggg':
  18006. return strict ? parseTokenSixDigits : parseTokenOneToSixDigits;
  18007. case 'S':
  18008. if (strict) { return parseTokenOneDigit; }
  18009. /* falls through */
  18010. case 'SS':
  18011. if (strict) { return parseTokenTwoDigits; }
  18012. /* falls through */
  18013. case 'SSS':
  18014. if (strict) { return parseTokenThreeDigits; }
  18015. /* falls through */
  18016. case 'DDD':
  18017. return parseTokenOneToThreeDigits;
  18018. case 'MMM':
  18019. case 'MMMM':
  18020. case 'dd':
  18021. case 'ddd':
  18022. case 'dddd':
  18023. return parseTokenWord;
  18024. case 'a':
  18025. case 'A':
  18026. return getLangDefinition(config._l)._meridiemParse;
  18027. case 'X':
  18028. return parseTokenTimestampMs;
  18029. case 'Z':
  18030. case 'ZZ':
  18031. return parseTokenTimezone;
  18032. case 'T':
  18033. return parseTokenT;
  18034. case 'SSSS':
  18035. return parseTokenDigits;
  18036. case 'MM':
  18037. case 'DD':
  18038. case 'YY':
  18039. case 'GG':
  18040. case 'gg':
  18041. case 'HH':
  18042. case 'hh':
  18043. case 'mm':
  18044. case 'ss':
  18045. case 'ww':
  18046. case 'WW':
  18047. return strict ? parseTokenTwoDigits : parseTokenOneOrTwoDigits;
  18048. case 'M':
  18049. case 'D':
  18050. case 'd':
  18051. case 'H':
  18052. case 'h':
  18053. case 'm':
  18054. case 's':
  18055. case 'w':
  18056. case 'W':
  18057. case 'e':
  18058. case 'E':
  18059. return parseTokenOneOrTwoDigits;
  18060. case 'Do':
  18061. return parseTokenOrdinal;
  18062. default :
  18063. a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), "i"));
  18064. return a;
  18065. }
  18066. }
  18067. function timezoneMinutesFromString(string) {
  18068. string = string || "";
  18069. var possibleTzMatches = (string.match(parseTokenTimezone) || []),
  18070. tzChunk = possibleTzMatches[possibleTzMatches.length - 1] || [],
  18071. parts = (tzChunk + '').match(parseTimezoneChunker) || ['-', 0, 0],
  18072. minutes = +(parts[1] * 60) + toInt(parts[2]);
  18073. return parts[0] === '+' ? -minutes : minutes;
  18074. }
  18075. // function to convert string input to date
  18076. function addTimeToArrayFromToken(token, input, config) {
  18077. var a, datePartArray = config._a;
  18078. switch (token) {
  18079. // QUARTER
  18080. case 'Q':
  18081. if (input != null) {
  18082. datePartArray[MONTH] = (toInt(input) - 1) * 3;
  18083. }
  18084. break;
  18085. // MONTH
  18086. case 'M' : // fall through to MM
  18087. case 'MM' :
  18088. if (input != null) {
  18089. datePartArray[MONTH] = toInt(input) - 1;
  18090. }
  18091. break;
  18092. case 'MMM' : // fall through to MMMM
  18093. case 'MMMM' :
  18094. a = getLangDefinition(config._l).monthsParse(input);
  18095. // if we didn't find a month name, mark the date as invalid.
  18096. if (a != null) {
  18097. datePartArray[MONTH] = a;
  18098. } else {
  18099. config._pf.invalidMonth = input;
  18100. }
  18101. break;
  18102. // DAY OF MONTH
  18103. case 'D' : // fall through to DD
  18104. case 'DD' :
  18105. if (input != null) {
  18106. datePartArray[DATE] = toInt(input);
  18107. }
  18108. break;
  18109. case 'Do' :
  18110. if (input != null) {
  18111. datePartArray[DATE] = toInt(parseInt(input, 10));
  18112. }
  18113. break;
  18114. // DAY OF YEAR
  18115. case 'DDD' : // fall through to DDDD
  18116. case 'DDDD' :
  18117. if (input != null) {
  18118. config._dayOfYear = toInt(input);
  18119. }
  18120. break;
  18121. // YEAR
  18122. case 'YY' :
  18123. datePartArray[YEAR] = moment.parseTwoDigitYear(input);
  18124. break;
  18125. case 'YYYY' :
  18126. case 'YYYYY' :
  18127. case 'YYYYYY' :
  18128. datePartArray[YEAR] = toInt(input);
  18129. break;
  18130. // AM / PM
  18131. case 'a' : // fall through to A
  18132. case 'A' :
  18133. config._isPm = getLangDefinition(config._l).isPM(input);
  18134. break;
  18135. // 24 HOUR
  18136. case 'H' : // fall through to hh
  18137. case 'HH' : // fall through to hh
  18138. case 'h' : // fall through to hh
  18139. case 'hh' :
  18140. datePartArray[HOUR] = toInt(input);
  18141. break;
  18142. // MINUTE
  18143. case 'm' : // fall through to mm
  18144. case 'mm' :
  18145. datePartArray[MINUTE] = toInt(input);
  18146. break;
  18147. // SECOND
  18148. case 's' : // fall through to ss
  18149. case 'ss' :
  18150. datePartArray[SECOND] = toInt(input);
  18151. break;
  18152. // MILLISECOND
  18153. case 'S' :
  18154. case 'SS' :
  18155. case 'SSS' :
  18156. case 'SSSS' :
  18157. datePartArray[MILLISECOND] = toInt(('0.' + input) * 1000);
  18158. break;
  18159. // UNIX TIMESTAMP WITH MS
  18160. case 'X':
  18161. config._d = new Date(parseFloat(input) * 1000);
  18162. break;
  18163. // TIMEZONE
  18164. case 'Z' : // fall through to ZZ
  18165. case 'ZZ' :
  18166. config._useUTC = true;
  18167. config._tzm = timezoneMinutesFromString(input);
  18168. break;
  18169. case 'w':
  18170. case 'ww':
  18171. case 'W':
  18172. case 'WW':
  18173. case 'd':
  18174. case 'dd':
  18175. case 'ddd':
  18176. case 'dddd':
  18177. case 'e':
  18178. case 'E':
  18179. token = token.substr(0, 1);
  18180. /* falls through */
  18181. case 'gg':
  18182. case 'gggg':
  18183. case 'GG':
  18184. case 'GGGG':
  18185. case 'GGGGG':
  18186. token = token.substr(0, 2);
  18187. if (input) {
  18188. config._w = config._w || {};
  18189. config._w[token] = input;
  18190. }
  18191. break;
  18192. }
  18193. }
  18194. // convert an array to a date.
  18195. // the array should mirror the parameters below
  18196. // note: all values past the year are optional and will default to the lowest possible value.
  18197. // [year, month, day , hour, minute, second, millisecond]
  18198. function dateFromConfig(config) {
  18199. var i, date, input = [], currentDate,
  18200. yearToUse, fixYear, w, temp, lang, weekday, week;
  18201. if (config._d) {
  18202. return;
  18203. }
  18204. currentDate = currentDateArray(config);
  18205. //compute day of the year from weeks and weekdays
  18206. if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
  18207. fixYear = function (val) {
  18208. var intVal = parseInt(val, 10);
  18209. return val ?
  18210. (val.length < 3 ? (intVal > 68 ? 1900 + intVal : 2000 + intVal) : intVal) :
  18211. (config._a[YEAR] == null ? moment().weekYear() : config._a[YEAR]);
  18212. };
  18213. w = config._w;
  18214. if (w.GG != null || w.W != null || w.E != null) {
  18215. temp = dayOfYearFromWeeks(fixYear(w.GG), w.W || 1, w.E, 4, 1);
  18216. }
  18217. else {
  18218. lang = getLangDefinition(config._l);
  18219. weekday = w.d != null ? parseWeekday(w.d, lang) :
  18220. (w.e != null ? parseInt(w.e, 10) + lang._week.dow : 0);
  18221. week = parseInt(w.w, 10) || 1;
  18222. //if we're parsing 'd', then the low day numbers may be next week
  18223. if (w.d != null && weekday < lang._week.dow) {
  18224. week++;
  18225. }
  18226. temp = dayOfYearFromWeeks(fixYear(w.gg), week, weekday, lang._week.doy, lang._week.dow);
  18227. }
  18228. config._a[YEAR] = temp.year;
  18229. config._dayOfYear = temp.dayOfYear;
  18230. }
  18231. //if the day of the year is set, figure out what it is
  18232. if (config._dayOfYear) {
  18233. yearToUse = config._a[YEAR] == null ? currentDate[YEAR] : config._a[YEAR];
  18234. if (config._dayOfYear > daysInYear(yearToUse)) {
  18235. config._pf._overflowDayOfYear = true;
  18236. }
  18237. date = makeUTCDate(yearToUse, 0, config._dayOfYear);
  18238. config._a[MONTH] = date.getUTCMonth();
  18239. config._a[DATE] = date.getUTCDate();
  18240. }
  18241. // Default to current date.
  18242. // * if no year, month, day of month are given, default to today
  18243. // * if day of month is given, default month and year
  18244. // * if month is given, default only year
  18245. // * if year is given, don't default anything
  18246. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  18247. config._a[i] = input[i] = currentDate[i];
  18248. }
  18249. // Zero out whatever was not defaulted, including time
  18250. for (; i < 7; i++) {
  18251. config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
  18252. }
  18253. // add the offsets to the time to be parsed so that we can have a clean array for checking isValid
  18254. input[HOUR] += toInt((config._tzm || 0) / 60);
  18255. input[MINUTE] += toInt((config._tzm || 0) % 60);
  18256. config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input);
  18257. }
  18258. function dateFromObject(config) {
  18259. var normalizedInput;
  18260. if (config._d) {
  18261. return;
  18262. }
  18263. normalizedInput = normalizeObjectUnits(config._i);
  18264. config._a = [
  18265. normalizedInput.year,
  18266. normalizedInput.month,
  18267. normalizedInput.day,
  18268. normalizedInput.hour,
  18269. normalizedInput.minute,
  18270. normalizedInput.second,
  18271. normalizedInput.millisecond
  18272. ];
  18273. dateFromConfig(config);
  18274. }
  18275. function currentDateArray(config) {
  18276. var now = new Date();
  18277. if (config._useUTC) {
  18278. return [
  18279. now.getUTCFullYear(),
  18280. now.getUTCMonth(),
  18281. now.getUTCDate()
  18282. ];
  18283. } else {
  18284. return [now.getFullYear(), now.getMonth(), now.getDate()];
  18285. }
  18286. }
  18287. // date from string and format string
  18288. function makeDateFromStringAndFormat(config) {
  18289. config._a = [];
  18290. config._pf.empty = true;
  18291. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  18292. var lang = getLangDefinition(config._l),
  18293. string = '' + config._i,
  18294. i, parsedInput, tokens, token, skipped,
  18295. stringLength = string.length,
  18296. totalParsedInputLength = 0;
  18297. tokens = expandFormat(config._f, lang).match(formattingTokens) || [];
  18298. for (i = 0; i < tokens.length; i++) {
  18299. token = tokens[i];
  18300. parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
  18301. if (parsedInput) {
  18302. skipped = string.substr(0, string.indexOf(parsedInput));
  18303. if (skipped.length > 0) {
  18304. config._pf.unusedInput.push(skipped);
  18305. }
  18306. string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
  18307. totalParsedInputLength += parsedInput.length;
  18308. }
  18309. // don't parse if it's not a known token
  18310. if (formatTokenFunctions[token]) {
  18311. if (parsedInput) {
  18312. config._pf.empty = false;
  18313. }
  18314. else {
  18315. config._pf.unusedTokens.push(token);
  18316. }
  18317. addTimeToArrayFromToken(token, parsedInput, config);
  18318. }
  18319. else if (config._strict && !parsedInput) {
  18320. config._pf.unusedTokens.push(token);
  18321. }
  18322. }
  18323. // add remaining unparsed input length to the string
  18324. config._pf.charsLeftOver = stringLength - totalParsedInputLength;
  18325. if (string.length > 0) {
  18326. config._pf.unusedInput.push(string);
  18327. }
  18328. // handle am pm
  18329. if (config._isPm && config._a[HOUR] < 12) {
  18330. config._a[HOUR] += 12;
  18331. }
  18332. // if is 12 am, change hours to 0
  18333. if (config._isPm === false && config._a[HOUR] === 12) {
  18334. config._a[HOUR] = 0;
  18335. }
  18336. dateFromConfig(config);
  18337. checkOverflow(config);
  18338. }
  18339. function unescapeFormat(s) {
  18340. return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
  18341. return p1 || p2 || p3 || p4;
  18342. });
  18343. }
  18344. // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  18345. function regexpEscape(s) {
  18346. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  18347. }
  18348. // date from string and array of format strings
  18349. function makeDateFromStringAndArray(config) {
  18350. var tempConfig,
  18351. bestMoment,
  18352. scoreToBeat,
  18353. i,
  18354. currentScore;
  18355. if (config._f.length === 0) {
  18356. config._pf.invalidFormat = true;
  18357. config._d = new Date(NaN);
  18358. return;
  18359. }
  18360. for (i = 0; i < config._f.length; i++) {
  18361. currentScore = 0;
  18362. tempConfig = extend({}, config);
  18363. tempConfig._pf = defaultParsingFlags();
  18364. tempConfig._f = config._f[i];
  18365. makeDateFromStringAndFormat(tempConfig);
  18366. if (!isValid(tempConfig)) {
  18367. continue;
  18368. }
  18369. // if there is any input that was not parsed add a penalty for that format
  18370. currentScore += tempConfig._pf.charsLeftOver;
  18371. //or tokens
  18372. currentScore += tempConfig._pf.unusedTokens.length * 10;
  18373. tempConfig._pf.score = currentScore;
  18374. if (scoreToBeat == null || currentScore < scoreToBeat) {
  18375. scoreToBeat = currentScore;
  18376. bestMoment = tempConfig;
  18377. }
  18378. }
  18379. extend(config, bestMoment || tempConfig);
  18380. }
  18381. // date from iso format
  18382. function makeDateFromString(config) {
  18383. var i, l,
  18384. string = config._i,
  18385. match = isoRegex.exec(string);
  18386. if (match) {
  18387. config._pf.iso = true;
  18388. for (i = 0, l = isoDates.length; i < l; i++) {
  18389. if (isoDates[i][1].exec(string)) {
  18390. // match[5] should be "T" or undefined
  18391. config._f = isoDates[i][0] + (match[6] || " ");
  18392. break;
  18393. }
  18394. }
  18395. for (i = 0, l = isoTimes.length; i < l; i++) {
  18396. if (isoTimes[i][1].exec(string)) {
  18397. config._f += isoTimes[i][0];
  18398. break;
  18399. }
  18400. }
  18401. if (string.match(parseTokenTimezone)) {
  18402. config._f += "Z";
  18403. }
  18404. makeDateFromStringAndFormat(config);
  18405. }
  18406. else {
  18407. moment.createFromInputFallback(config);
  18408. }
  18409. }
  18410. function makeDateFromInput(config) {
  18411. var input = config._i,
  18412. matched = aspNetJsonRegex.exec(input);
  18413. if (input === undefined) {
  18414. config._d = new Date();
  18415. } else if (matched) {
  18416. config._d = new Date(+matched[1]);
  18417. } else if (typeof input === 'string') {
  18418. makeDateFromString(config);
  18419. } else if (isArray(input)) {
  18420. config._a = input.slice(0);
  18421. dateFromConfig(config);
  18422. } else if (isDate(input)) {
  18423. config._d = new Date(+input);
  18424. } else if (typeof(input) === 'object') {
  18425. dateFromObject(config);
  18426. } else if (typeof(input) === 'number') {
  18427. // from milliseconds
  18428. config._d = new Date(input);
  18429. } else {
  18430. moment.createFromInputFallback(config);
  18431. }
  18432. }
  18433. function makeDate(y, m, d, h, M, s, ms) {
  18434. //can't just apply() to create a date:
  18435. //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply
  18436. var date = new Date(y, m, d, h, M, s, ms);
  18437. //the date constructor doesn't accept years < 1970
  18438. if (y < 1970) {
  18439. date.setFullYear(y);
  18440. }
  18441. return date;
  18442. }
  18443. function makeUTCDate(y) {
  18444. var date = new Date(Date.UTC.apply(null, arguments));
  18445. if (y < 1970) {
  18446. date.setUTCFullYear(y);
  18447. }
  18448. return date;
  18449. }
  18450. function parseWeekday(input, language) {
  18451. if (typeof input === 'string') {
  18452. if (!isNaN(input)) {
  18453. input = parseInt(input, 10);
  18454. }
  18455. else {
  18456. input = language.weekdaysParse(input);
  18457. if (typeof input !== 'number') {
  18458. return null;
  18459. }
  18460. }
  18461. }
  18462. return input;
  18463. }
  18464. /************************************
  18465. Relative Time
  18466. ************************************/
  18467. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  18468. function substituteTimeAgo(string, number, withoutSuffix, isFuture, lang) {
  18469. return lang.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  18470. }
  18471. function relativeTime(milliseconds, withoutSuffix, lang) {
  18472. var seconds = round(Math.abs(milliseconds) / 1000),
  18473. minutes = round(seconds / 60),
  18474. hours = round(minutes / 60),
  18475. days = round(hours / 24),
  18476. years = round(days / 365),
  18477. args = seconds < 45 && ['s', seconds] ||
  18478. minutes === 1 && ['m'] ||
  18479. minutes < 45 && ['mm', minutes] ||
  18480. hours === 1 && ['h'] ||
  18481. hours < 22 && ['hh', hours] ||
  18482. days === 1 && ['d'] ||
  18483. days <= 25 && ['dd', days] ||
  18484. days <= 45 && ['M'] ||
  18485. days < 345 && ['MM', round(days / 30)] ||
  18486. years === 1 && ['y'] || ['yy', years];
  18487. args[2] = withoutSuffix;
  18488. args[3] = milliseconds > 0;
  18489. args[4] = lang;
  18490. return substituteTimeAgo.apply({}, args);
  18491. }
  18492. /************************************
  18493. Week of Year
  18494. ************************************/
  18495. // firstDayOfWeek 0 = sun, 6 = sat
  18496. // the day of the week that starts the week
  18497. // (usually sunday or monday)
  18498. // firstDayOfWeekOfYear 0 = sun, 6 = sat
  18499. // the first week is the week that contains the first
  18500. // of this day of the week
  18501. // (eg. ISO weeks use thursday (4))
  18502. function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) {
  18503. var end = firstDayOfWeekOfYear - firstDayOfWeek,
  18504. daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(),
  18505. adjustedMoment;
  18506. if (daysToDayOfWeek > end) {
  18507. daysToDayOfWeek -= 7;
  18508. }
  18509. if (daysToDayOfWeek < end - 7) {
  18510. daysToDayOfWeek += 7;
  18511. }
  18512. adjustedMoment = moment(mom).add('d', daysToDayOfWeek);
  18513. return {
  18514. week: Math.ceil(adjustedMoment.dayOfYear() / 7),
  18515. year: adjustedMoment.year()
  18516. };
  18517. }
  18518. //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
  18519. function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) {
  18520. var d = makeUTCDate(year, 0, 1).getUTCDay(), daysToAdd, dayOfYear;
  18521. weekday = weekday != null ? weekday : firstDayOfWeek;
  18522. daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0);
  18523. dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1;
  18524. return {
  18525. year: dayOfYear > 0 ? year : year - 1,
  18526. dayOfYear: dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear
  18527. };
  18528. }
  18529. /************************************
  18530. Top Level Functions
  18531. ************************************/
  18532. function makeMoment(config) {
  18533. var input = config._i,
  18534. format = config._f;
  18535. if (input === null || (format === undefined && input === '')) {
  18536. return moment.invalid({nullInput: true});
  18537. }
  18538. if (typeof input === 'string') {
  18539. config._i = input = getLangDefinition().preparse(input);
  18540. }
  18541. if (moment.isMoment(input)) {
  18542. config = cloneMoment(input);
  18543. config._d = new Date(+input._d);
  18544. } else if (format) {
  18545. if (isArray(format)) {
  18546. makeDateFromStringAndArray(config);
  18547. } else {
  18548. makeDateFromStringAndFormat(config);
  18549. }
  18550. } else {
  18551. makeDateFromInput(config);
  18552. }
  18553. return new Moment(config);
  18554. }
  18555. moment = function (input, format, lang, strict) {
  18556. var c;
  18557. if (typeof(lang) === "boolean") {
  18558. strict = lang;
  18559. lang = undefined;
  18560. }
  18561. // object construction must be done this way.
  18562. // https://github.com/moment/moment/issues/1423
  18563. c = {};
  18564. c._isAMomentObject = true;
  18565. c._i = input;
  18566. c._f = format;
  18567. c._l = lang;
  18568. c._strict = strict;
  18569. c._isUTC = false;
  18570. c._pf = defaultParsingFlags();
  18571. return makeMoment(c);
  18572. };
  18573. moment.suppressDeprecationWarnings = false;
  18574. moment.createFromInputFallback = deprecate(
  18575. "moment construction falls back to js Date. This is " +
  18576. "discouraged and will be removed in upcoming major " +
  18577. "release. Please refer to " +
  18578. "https://github.com/moment/moment/issues/1407 for more info.",
  18579. function (config) {
  18580. config._d = new Date(config._i);
  18581. });
  18582. // creating with utc
  18583. moment.utc = function (input, format, lang, strict) {
  18584. var c;
  18585. if (typeof(lang) === "boolean") {
  18586. strict = lang;
  18587. lang = undefined;
  18588. }
  18589. // object construction must be done this way.
  18590. // https://github.com/moment/moment/issues/1423
  18591. c = {};
  18592. c._isAMomentObject = true;
  18593. c._useUTC = true;
  18594. c._isUTC = true;
  18595. c._l = lang;
  18596. c._i = input;
  18597. c._f = format;
  18598. c._strict = strict;
  18599. c._pf = defaultParsingFlags();
  18600. return makeMoment(c).utc();
  18601. };
  18602. // creating with unix timestamp (in seconds)
  18603. moment.unix = function (input) {
  18604. return moment(input * 1000);
  18605. };
  18606. // duration
  18607. moment.duration = function (input, key) {
  18608. var duration = input,
  18609. // matching against regexp is expensive, do it on demand
  18610. match = null,
  18611. sign,
  18612. ret,
  18613. parseIso;
  18614. if (moment.isDuration(input)) {
  18615. duration = {
  18616. ms: input._milliseconds,
  18617. d: input._days,
  18618. M: input._months
  18619. };
  18620. } else if (typeof input === 'number') {
  18621. duration = {};
  18622. if (key) {
  18623. duration[key] = input;
  18624. } else {
  18625. duration.milliseconds = input;
  18626. }
  18627. } else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) {
  18628. sign = (match[1] === "-") ? -1 : 1;
  18629. duration = {
  18630. y: 0,
  18631. d: toInt(match[DATE]) * sign,
  18632. h: toInt(match[HOUR]) * sign,
  18633. m: toInt(match[MINUTE]) * sign,
  18634. s: toInt(match[SECOND]) * sign,
  18635. ms: toInt(match[MILLISECOND]) * sign
  18636. };
  18637. } else if (!!(match = isoDurationRegex.exec(input))) {
  18638. sign = (match[1] === "-") ? -1 : 1;
  18639. parseIso = function (inp) {
  18640. // We'd normally use ~~inp for this, but unfortunately it also
  18641. // converts floats to ints.
  18642. // inp may be undefined, so careful calling replace on it.
  18643. var res = inp && parseFloat(inp.replace(',', '.'));
  18644. // apply sign while we're at it
  18645. return (isNaN(res) ? 0 : res) * sign;
  18646. };
  18647. duration = {
  18648. y: parseIso(match[2]),
  18649. M: parseIso(match[3]),
  18650. d: parseIso(match[4]),
  18651. h: parseIso(match[5]),
  18652. m: parseIso(match[6]),
  18653. s: parseIso(match[7]),
  18654. w: parseIso(match[8])
  18655. };
  18656. }
  18657. ret = new Duration(duration);
  18658. if (moment.isDuration(input) && input.hasOwnProperty('_lang')) {
  18659. ret._lang = input._lang;
  18660. }
  18661. return ret;
  18662. };
  18663. // version number
  18664. moment.version = VERSION;
  18665. // default format
  18666. moment.defaultFormat = isoFormat;
  18667. // Plugins that add properties should also add the key here (null value),
  18668. // so we can properly clone ourselves.
  18669. moment.momentProperties = momentProperties;
  18670. // This function will be called whenever a moment is mutated.
  18671. // It is intended to keep the offset in sync with the timezone.
  18672. moment.updateOffset = function () {};
  18673. // This function will load languages and then set the global language. If
  18674. // no arguments are passed in, it will simply return the current global
  18675. // language key.
  18676. moment.lang = function (key, values) {
  18677. var r;
  18678. if (!key) {
  18679. return moment.fn._lang._abbr;
  18680. }
  18681. if (values) {
  18682. loadLang(normalizeLanguage(key), values);
  18683. } else if (values === null) {
  18684. unloadLang(key);
  18685. key = 'en';
  18686. } else if (!languages[key]) {
  18687. getLangDefinition(key);
  18688. }
  18689. r = moment.duration.fn._lang = moment.fn._lang = getLangDefinition(key);
  18690. return r._abbr;
  18691. };
  18692. // returns language data
  18693. moment.langData = function (key) {
  18694. if (key && key._lang && key._lang._abbr) {
  18695. key = key._lang._abbr;
  18696. }
  18697. return getLangDefinition(key);
  18698. };
  18699. // compare moment object
  18700. moment.isMoment = function (obj) {
  18701. return obj instanceof Moment ||
  18702. (obj != null && obj.hasOwnProperty('_isAMomentObject'));
  18703. };
  18704. // for typechecking Duration objects
  18705. moment.isDuration = function (obj) {
  18706. return obj instanceof Duration;
  18707. };
  18708. for (i = lists.length - 1; i >= 0; --i) {
  18709. makeList(lists[i]);
  18710. }
  18711. moment.normalizeUnits = function (units) {
  18712. return normalizeUnits(units);
  18713. };
  18714. moment.invalid = function (flags) {
  18715. var m = moment.utc(NaN);
  18716. if (flags != null) {
  18717. extend(m._pf, flags);
  18718. }
  18719. else {
  18720. m._pf.userInvalidated = true;
  18721. }
  18722. return m;
  18723. };
  18724. moment.parseZone = function () {
  18725. return moment.apply(null, arguments).parseZone();
  18726. };
  18727. moment.parseTwoDigitYear = function (input) {
  18728. return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
  18729. };
  18730. /************************************
  18731. Moment Prototype
  18732. ************************************/
  18733. extend(moment.fn = Moment.prototype, {
  18734. clone : function () {
  18735. return moment(this);
  18736. },
  18737. valueOf : function () {
  18738. return +this._d + ((this._offset || 0) * 60000);
  18739. },
  18740. unix : function () {
  18741. return Math.floor(+this / 1000);
  18742. },
  18743. toString : function () {
  18744. return this.clone().lang('en').format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ");
  18745. },
  18746. toDate : function () {
  18747. return this._offset ? new Date(+this) : this._d;
  18748. },
  18749. toISOString : function () {
  18750. var m = moment(this).utc();
  18751. if (0 < m.year() && m.year() <= 9999) {
  18752. return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  18753. } else {
  18754. return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  18755. }
  18756. },
  18757. toArray : function () {
  18758. var m = this;
  18759. return [
  18760. m.year(),
  18761. m.month(),
  18762. m.date(),
  18763. m.hours(),
  18764. m.minutes(),
  18765. m.seconds(),
  18766. m.milliseconds()
  18767. ];
  18768. },
  18769. isValid : function () {
  18770. return isValid(this);
  18771. },
  18772. isDSTShifted : function () {
  18773. if (this._a) {
  18774. return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0;
  18775. }
  18776. return false;
  18777. },
  18778. parsingFlags : function () {
  18779. return extend({}, this._pf);
  18780. },
  18781. invalidAt: function () {
  18782. return this._pf.overflow;
  18783. },
  18784. utc : function () {
  18785. return this.zone(0);
  18786. },
  18787. local : function () {
  18788. this.zone(0);
  18789. this._isUTC = false;
  18790. return this;
  18791. },
  18792. format : function (inputString) {
  18793. var output = formatMoment(this, inputString || moment.defaultFormat);
  18794. return this.lang().postformat(output);
  18795. },
  18796. add : function (input, val) {
  18797. var dur;
  18798. // switch args to support add('s', 1) and add(1, 's')
  18799. if (typeof input === 'string') {
  18800. dur = moment.duration(+val, input);
  18801. } else {
  18802. dur = moment.duration(input, val);
  18803. }
  18804. addOrSubtractDurationFromMoment(this, dur, 1);
  18805. return this;
  18806. },
  18807. subtract : function (input, val) {
  18808. var dur;
  18809. // switch args to support subtract('s', 1) and subtract(1, 's')
  18810. if (typeof input === 'string') {
  18811. dur = moment.duration(+val, input);
  18812. } else {
  18813. dur = moment.duration(input, val);
  18814. }
  18815. addOrSubtractDurationFromMoment(this, dur, -1);
  18816. return this;
  18817. },
  18818. diff : function (input, units, asFloat) {
  18819. var that = makeAs(input, this),
  18820. zoneDiff = (this.zone() - that.zone()) * 6e4,
  18821. diff, output;
  18822. units = normalizeUnits(units);
  18823. if (units === 'year' || units === 'month') {
  18824. // average number of days in the months in the given dates
  18825. diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2
  18826. // difference in months
  18827. output = ((this.year() - that.year()) * 12) + (this.month() - that.month());
  18828. // adjust by taking difference in days, average number of days
  18829. // and dst in the given months.
  18830. output += ((this - moment(this).startOf('month')) -
  18831. (that - moment(that).startOf('month'))) / diff;
  18832. // same as above but with zones, to negate all dst
  18833. output -= ((this.zone() - moment(this).startOf('month').zone()) -
  18834. (that.zone() - moment(that).startOf('month').zone())) * 6e4 / diff;
  18835. if (units === 'year') {
  18836. output = output / 12;
  18837. }
  18838. } else {
  18839. diff = (this - that);
  18840. output = units === 'second' ? diff / 1e3 : // 1000
  18841. units === 'minute' ? diff / 6e4 : // 1000 * 60
  18842. units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60
  18843. units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
  18844. units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
  18845. diff;
  18846. }
  18847. return asFloat ? output : absRound(output);
  18848. },
  18849. from : function (time, withoutSuffix) {
  18850. return moment.duration(this.diff(time)).lang(this.lang()._abbr).humanize(!withoutSuffix);
  18851. },
  18852. fromNow : function (withoutSuffix) {
  18853. return this.from(moment(), withoutSuffix);
  18854. },
  18855. calendar : function () {
  18856. // We want to compare the start of today, vs this.
  18857. // Getting start-of-today depends on whether we're zone'd or not.
  18858. var sod = makeAs(moment(), this).startOf('day'),
  18859. diff = this.diff(sod, 'days', true),
  18860. format = diff < -6 ? 'sameElse' :
  18861. diff < -1 ? 'lastWeek' :
  18862. diff < 0 ? 'lastDay' :
  18863. diff < 1 ? 'sameDay' :
  18864. diff < 2 ? 'nextDay' :
  18865. diff < 7 ? 'nextWeek' : 'sameElse';
  18866. return this.format(this.lang().calendar(format, this));
  18867. },
  18868. isLeapYear : function () {
  18869. return isLeapYear(this.year());
  18870. },
  18871. isDST : function () {
  18872. return (this.zone() < this.clone().month(0).zone() ||
  18873. this.zone() < this.clone().month(5).zone());
  18874. },
  18875. day : function (input) {
  18876. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  18877. if (input != null) {
  18878. input = parseWeekday(input, this.lang());
  18879. return this.add({ d : input - day });
  18880. } else {
  18881. return day;
  18882. }
  18883. },
  18884. month : makeAccessor('Month', true),
  18885. startOf: function (units) {
  18886. units = normalizeUnits(units);
  18887. // the following switch intentionally omits break keywords
  18888. // to utilize falling through the cases.
  18889. switch (units) {
  18890. case 'year':
  18891. this.month(0);
  18892. /* falls through */
  18893. case 'quarter':
  18894. case 'month':
  18895. this.date(1);
  18896. /* falls through */
  18897. case 'week':
  18898. case 'isoWeek':
  18899. case 'day':
  18900. this.hours(0);
  18901. /* falls through */
  18902. case 'hour':
  18903. this.minutes(0);
  18904. /* falls through */
  18905. case 'minute':
  18906. this.seconds(0);
  18907. /* falls through */
  18908. case 'second':
  18909. this.milliseconds(0);
  18910. /* falls through */
  18911. }
  18912. // weeks are a special case
  18913. if (units === 'week') {
  18914. this.weekday(0);
  18915. } else if (units === 'isoWeek') {
  18916. this.isoWeekday(1);
  18917. }
  18918. // quarters are also special
  18919. if (units === 'quarter') {
  18920. this.month(Math.floor(this.month() / 3) * 3);
  18921. }
  18922. return this;
  18923. },
  18924. endOf: function (units) {
  18925. units = normalizeUnits(units);
  18926. return this.startOf(units).add((units === 'isoWeek' ? 'week' : units), 1).subtract('ms', 1);
  18927. },
  18928. isAfter: function (input, units) {
  18929. units = typeof units !== 'undefined' ? units : 'millisecond';
  18930. return +this.clone().startOf(units) > +moment(input).startOf(units);
  18931. },
  18932. isBefore: function (input, units) {
  18933. units = typeof units !== 'undefined' ? units : 'millisecond';
  18934. return +this.clone().startOf(units) < +moment(input).startOf(units);
  18935. },
  18936. isSame: function (input, units) {
  18937. units = units || 'ms';
  18938. return +this.clone().startOf(units) === +makeAs(input, this).startOf(units);
  18939. },
  18940. min: function (other) {
  18941. other = moment.apply(null, arguments);
  18942. return other < this ? this : other;
  18943. },
  18944. max: function (other) {
  18945. other = moment.apply(null, arguments);
  18946. return other > this ? this : other;
  18947. },
  18948. // keepTime = true means only change the timezone, without affecting
  18949. // the local hour. So 5:31:26 +0300 --[zone(2, true)]--> 5:31:26 +0200
  18950. // It is possible that 5:31:26 doesn't exist int zone +0200, so we
  18951. // adjust the time as needed, to be valid.
  18952. //
  18953. // Keeping the time actually adds/subtracts (one hour)
  18954. // from the actual represented time. That is why we call updateOffset
  18955. // a second time. In case it wants us to change the offset again
  18956. // _changeInProgress == true case, then we have to adjust, because
  18957. // there is no such time in the given timezone.
  18958. zone : function (input, keepTime) {
  18959. var offset = this._offset || 0;
  18960. if (input != null) {
  18961. if (typeof input === "string") {
  18962. input = timezoneMinutesFromString(input);
  18963. }
  18964. if (Math.abs(input) < 16) {
  18965. input = input * 60;
  18966. }
  18967. this._offset = input;
  18968. this._isUTC = true;
  18969. if (offset !== input) {
  18970. if (!keepTime || this._changeInProgress) {
  18971. addOrSubtractDurationFromMoment(this,
  18972. moment.duration(offset - input, 'm'), 1, false);
  18973. } else if (!this._changeInProgress) {
  18974. this._changeInProgress = true;
  18975. moment.updateOffset(this, true);
  18976. this._changeInProgress = null;
  18977. }
  18978. }
  18979. } else {
  18980. return this._isUTC ? offset : this._d.getTimezoneOffset();
  18981. }
  18982. return this;
  18983. },
  18984. zoneAbbr : function () {
  18985. return this._isUTC ? "UTC" : "";
  18986. },
  18987. zoneName : function () {
  18988. return this._isUTC ? "Coordinated Universal Time" : "";
  18989. },
  18990. parseZone : function () {
  18991. if (this._tzm) {
  18992. this.zone(this._tzm);
  18993. } else if (typeof this._i === 'string') {
  18994. this.zone(this._i);
  18995. }
  18996. return this;
  18997. },
  18998. hasAlignedHourOffset : function (input) {
  18999. if (!input) {
  19000. input = 0;
  19001. }
  19002. else {
  19003. input = moment(input).zone();
  19004. }
  19005. return (this.zone() - input) % 60 === 0;
  19006. },
  19007. daysInMonth : function () {
  19008. return daysInMonth(this.year(), this.month());
  19009. },
  19010. dayOfYear : function (input) {
  19011. var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1;
  19012. return input == null ? dayOfYear : this.add("d", (input - dayOfYear));
  19013. },
  19014. quarter : function (input) {
  19015. return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
  19016. },
  19017. weekYear : function (input) {
  19018. var year = weekOfYear(this, this.lang()._week.dow, this.lang()._week.doy).year;
  19019. return input == null ? year : this.add("y", (input - year));
  19020. },
  19021. isoWeekYear : function (input) {
  19022. var year = weekOfYear(this, 1, 4).year;
  19023. return input == null ? year : this.add("y", (input - year));
  19024. },
  19025. week : function (input) {
  19026. var week = this.lang().week(this);
  19027. return input == null ? week : this.add("d", (input - week) * 7);
  19028. },
  19029. isoWeek : function (input) {
  19030. var week = weekOfYear(this, 1, 4).week;
  19031. return input == null ? week : this.add("d", (input - week) * 7);
  19032. },
  19033. weekday : function (input) {
  19034. var weekday = (this.day() + 7 - this.lang()._week.dow) % 7;
  19035. return input == null ? weekday : this.add("d", input - weekday);
  19036. },
  19037. isoWeekday : function (input) {
  19038. // behaves the same as moment#day except
  19039. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  19040. // as a setter, sunday should belong to the previous week.
  19041. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7);
  19042. },
  19043. isoWeeksInYear : function () {
  19044. return weeksInYear(this.year(), 1, 4);
  19045. },
  19046. weeksInYear : function () {
  19047. var weekInfo = this._lang._week;
  19048. return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
  19049. },
  19050. get : function (units) {
  19051. units = normalizeUnits(units);
  19052. return this[units]();
  19053. },
  19054. set : function (units, value) {
  19055. units = normalizeUnits(units);
  19056. if (typeof this[units] === 'function') {
  19057. this[units](value);
  19058. }
  19059. return this;
  19060. },
  19061. // If passed a language key, it will set the language for this
  19062. // instance. Otherwise, it will return the language configuration
  19063. // variables for this instance.
  19064. lang : function (key) {
  19065. if (key === undefined) {
  19066. return this._lang;
  19067. } else {
  19068. this._lang = getLangDefinition(key);
  19069. return this;
  19070. }
  19071. }
  19072. });
  19073. function rawMonthSetter(mom, value) {
  19074. var dayOfMonth;
  19075. // TODO: Move this out of here!
  19076. if (typeof value === 'string') {
  19077. value = mom.lang().monthsParse(value);
  19078. // TODO: Another silent failure?
  19079. if (typeof value !== 'number') {
  19080. return mom;
  19081. }
  19082. }
  19083. dayOfMonth = Math.min(mom.date(),
  19084. daysInMonth(mom.year(), value));
  19085. mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
  19086. return mom;
  19087. }
  19088. function rawGetter(mom, unit) {
  19089. return mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]();
  19090. }
  19091. function rawSetter(mom, unit, value) {
  19092. if (unit === 'Month') {
  19093. return rawMonthSetter(mom, value);
  19094. } else {
  19095. return mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
  19096. }
  19097. }
  19098. function makeAccessor(unit, keepTime) {
  19099. return function (value) {
  19100. if (value != null) {
  19101. rawSetter(this, unit, value);
  19102. moment.updateOffset(this, keepTime);
  19103. return this;
  19104. } else {
  19105. return rawGetter(this, unit);
  19106. }
  19107. };
  19108. }
  19109. moment.fn.millisecond = moment.fn.milliseconds = makeAccessor('Milliseconds', false);
  19110. moment.fn.second = moment.fn.seconds = makeAccessor('Seconds', false);
  19111. moment.fn.minute = moment.fn.minutes = makeAccessor('Minutes', false);
  19112. // Setting the hour should keep the time, because the user explicitly
  19113. // specified which hour he wants. So trying to maintain the same hour (in
  19114. // a new timezone) makes sense. Adding/subtracting hours does not follow
  19115. // this rule.
  19116. moment.fn.hour = moment.fn.hours = makeAccessor('Hours', true);
  19117. // moment.fn.month is defined separately
  19118. moment.fn.date = makeAccessor('Date', true);
  19119. moment.fn.dates = deprecate("dates accessor is deprecated. Use date instead.", makeAccessor('Date', true));
  19120. moment.fn.year = makeAccessor('FullYear', true);
  19121. moment.fn.years = deprecate("years accessor is deprecated. Use year instead.", makeAccessor('FullYear', true));
  19122. // add plural methods
  19123. moment.fn.days = moment.fn.day;
  19124. moment.fn.months = moment.fn.month;
  19125. moment.fn.weeks = moment.fn.week;
  19126. moment.fn.isoWeeks = moment.fn.isoWeek;
  19127. moment.fn.quarters = moment.fn.quarter;
  19128. // add aliased format methods
  19129. moment.fn.toJSON = moment.fn.toISOString;
  19130. /************************************
  19131. Duration Prototype
  19132. ************************************/
  19133. extend(moment.duration.fn = Duration.prototype, {
  19134. _bubble : function () {
  19135. var milliseconds = this._milliseconds,
  19136. days = this._days,
  19137. months = this._months,
  19138. data = this._data,
  19139. seconds, minutes, hours, years;
  19140. // The following code bubbles up values, see the tests for
  19141. // examples of what that means.
  19142. data.milliseconds = milliseconds % 1000;
  19143. seconds = absRound(milliseconds / 1000);
  19144. data.seconds = seconds % 60;
  19145. minutes = absRound(seconds / 60);
  19146. data.minutes = minutes % 60;
  19147. hours = absRound(minutes / 60);
  19148. data.hours = hours % 24;
  19149. days += absRound(hours / 24);
  19150. data.days = days % 30;
  19151. months += absRound(days / 30);
  19152. data.months = months % 12;
  19153. years = absRound(months / 12);
  19154. data.years = years;
  19155. },
  19156. weeks : function () {
  19157. return absRound(this.days() / 7);
  19158. },
  19159. valueOf : function () {
  19160. return this._milliseconds +
  19161. this._days * 864e5 +
  19162. (this._months % 12) * 2592e6 +
  19163. toInt(this._months / 12) * 31536e6;
  19164. },
  19165. humanize : function (withSuffix) {
  19166. var difference = +this,
  19167. output = relativeTime(difference, !withSuffix, this.lang());
  19168. if (withSuffix) {
  19169. output = this.lang().pastFuture(difference, output);
  19170. }
  19171. return this.lang().postformat(output);
  19172. },
  19173. add : function (input, val) {
  19174. // supports only 2.0-style add(1, 's') or add(moment)
  19175. var dur = moment.duration(input, val);
  19176. this._milliseconds += dur._milliseconds;
  19177. this._days += dur._days;
  19178. this._months += dur._months;
  19179. this._bubble();
  19180. return this;
  19181. },
  19182. subtract : function (input, val) {
  19183. var dur = moment.duration(input, val);
  19184. this._milliseconds -= dur._milliseconds;
  19185. this._days -= dur._days;
  19186. this._months -= dur._months;
  19187. this._bubble();
  19188. return this;
  19189. },
  19190. get : function (units) {
  19191. units = normalizeUnits(units);
  19192. return this[units.toLowerCase() + 's']();
  19193. },
  19194. as : function (units) {
  19195. units = normalizeUnits(units);
  19196. return this['as' + units.charAt(0).toUpperCase() + units.slice(1) + 's']();
  19197. },
  19198. lang : moment.fn.lang,
  19199. toIsoString : function () {
  19200. // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
  19201. var years = Math.abs(this.years()),
  19202. months = Math.abs(this.months()),
  19203. days = Math.abs(this.days()),
  19204. hours = Math.abs(this.hours()),
  19205. minutes = Math.abs(this.minutes()),
  19206. seconds = Math.abs(this.seconds() + this.milliseconds() / 1000);
  19207. if (!this.asSeconds()) {
  19208. // this is the same as C#'s (Noda) and python (isodate)...
  19209. // but not other JS (goog.date)
  19210. return 'P0D';
  19211. }
  19212. return (this.asSeconds() < 0 ? '-' : '') +
  19213. 'P' +
  19214. (years ? years + 'Y' : '') +
  19215. (months ? months + 'M' : '') +
  19216. (days ? days + 'D' : '') +
  19217. ((hours || minutes || seconds) ? 'T' : '') +
  19218. (hours ? hours + 'H' : '') +
  19219. (minutes ? minutes + 'M' : '') +
  19220. (seconds ? seconds + 'S' : '');
  19221. }
  19222. });
  19223. function makeDurationGetter(name) {
  19224. moment.duration.fn[name] = function () {
  19225. return this._data[name];
  19226. };
  19227. }
  19228. function makeDurationAsGetter(name, factor) {
  19229. moment.duration.fn['as' + name] = function () {
  19230. return +this / factor;
  19231. };
  19232. }
  19233. for (i in unitMillisecondFactors) {
  19234. if (unitMillisecondFactors.hasOwnProperty(i)) {
  19235. makeDurationAsGetter(i, unitMillisecondFactors[i]);
  19236. makeDurationGetter(i.toLowerCase());
  19237. }
  19238. }
  19239. makeDurationAsGetter('Weeks', 6048e5);
  19240. moment.duration.fn.asMonths = function () {
  19241. return (+this - this.years() * 31536e6) / 2592e6 + this.years() * 12;
  19242. };
  19243. /************************************
  19244. Default Lang
  19245. ************************************/
  19246. // Set default language, other languages will inherit from English.
  19247. moment.lang('en', {
  19248. ordinal : function (number) {
  19249. var b = number % 10,
  19250. output = (toInt(number % 100 / 10) === 1) ? 'th' :
  19251. (b === 1) ? 'st' :
  19252. (b === 2) ? 'nd' :
  19253. (b === 3) ? 'rd' : 'th';
  19254. return number + output;
  19255. }
  19256. });
  19257. /* EMBED_LANGUAGES */
  19258. /************************************
  19259. Exposing Moment
  19260. ************************************/
  19261. function makeGlobal(shouldDeprecate) {
  19262. /*global ender:false */
  19263. if (typeof ender !== 'undefined') {
  19264. return;
  19265. }
  19266. oldGlobalMoment = globalScope.moment;
  19267. if (shouldDeprecate) {
  19268. globalScope.moment = deprecate(
  19269. "Accessing Moment through the global scope is " +
  19270. "deprecated, and will be removed in an upcoming " +
  19271. "release.",
  19272. moment);
  19273. } else {
  19274. globalScope.moment = moment;
  19275. }
  19276. }
  19277. // CommonJS module is defined
  19278. if (hasModule) {
  19279. module.exports = moment;
  19280. } else if (typeof define === "function" && define.amd) {
  19281. define("moment", function (require, exports, module) {
  19282. if (module.config && module.config() && module.config().noGlobal === true) {
  19283. // release the global variable
  19284. globalScope.moment = oldGlobalMoment;
  19285. }
  19286. return moment;
  19287. });
  19288. makeGlobal(true);
  19289. } else {
  19290. makeGlobal();
  19291. }
  19292. }).call(this);
  19293. },{}],5:[function(require,module,exports){
  19294. /**
  19295. * Copyright 2012 Craig Campbell
  19296. *
  19297. * Licensed under the Apache License, Version 2.0 (the "License");
  19298. * you may not use this file except in compliance with the License.
  19299. * You may obtain a copy of the License at
  19300. *
  19301. * http://www.apache.org/licenses/LICENSE-2.0
  19302. *
  19303. * Unless required by applicable law or agreed to in writing, software
  19304. * distributed under the License is distributed on an "AS IS" BASIS,
  19305. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19306. * See the License for the specific language governing permissions and
  19307. * limitations under the License.
  19308. *
  19309. * Mousetrap is a simple keyboard shortcut library for Javascript with
  19310. * no external dependencies
  19311. *
  19312. * @version 1.1.2
  19313. * @url craig.is/killing/mice
  19314. */
  19315. /**
  19316. * mapping of special keycodes to their corresponding keys
  19317. *
  19318. * everything in this dictionary cannot use keypress events
  19319. * so it has to be here to map to the correct keycodes for
  19320. * keyup/keydown events
  19321. *
  19322. * @type {Object}
  19323. */
  19324. var _MAP = {
  19325. 8: 'backspace',
  19326. 9: 'tab',
  19327. 13: 'enter',
  19328. 16: 'shift',
  19329. 17: 'ctrl',
  19330. 18: 'alt',
  19331. 20: 'capslock',
  19332. 27: 'esc',
  19333. 32: 'space',
  19334. 33: 'pageup',
  19335. 34: 'pagedown',
  19336. 35: 'end',
  19337. 36: 'home',
  19338. 37: 'left',
  19339. 38: 'up',
  19340. 39: 'right',
  19341. 40: 'down',
  19342. 45: 'ins',
  19343. 46: 'del',
  19344. 91: 'meta',
  19345. 93: 'meta',
  19346. 224: 'meta'
  19347. },
  19348. /**
  19349. * mapping for special characters so they can support
  19350. *
  19351. * this dictionary is only used incase you want to bind a
  19352. * keyup or keydown event to one of these keys
  19353. *
  19354. * @type {Object}
  19355. */
  19356. _KEYCODE_MAP = {
  19357. 106: '*',
  19358. 107: '+',
  19359. 109: '-',
  19360. 110: '.',
  19361. 111 : '/',
  19362. 186: ';',
  19363. 187: '=',
  19364. 188: ',',
  19365. 189: '-',
  19366. 190: '.',
  19367. 191: '/',
  19368. 192: '`',
  19369. 219: '[',
  19370. 220: '\\',
  19371. 221: ']',
  19372. 222: '\''
  19373. },
  19374. /**
  19375. * this is a mapping of keys that require shift on a US keypad
  19376. * back to the non shift equivelents
  19377. *
  19378. * this is so you can use keyup events with these keys
  19379. *
  19380. * note that this will only work reliably on US keyboards
  19381. *
  19382. * @type {Object}
  19383. */
  19384. _SHIFT_MAP = {
  19385. '~': '`',
  19386. '!': '1',
  19387. '@': '2',
  19388. '#': '3',
  19389. '$': '4',
  19390. '%': '5',
  19391. '^': '6',
  19392. '&': '7',
  19393. '*': '8',
  19394. '(': '9',
  19395. ')': '0',
  19396. '_': '-',
  19397. '+': '=',
  19398. ':': ';',
  19399. '\"': '\'',
  19400. '<': ',',
  19401. '>': '.',
  19402. '?': '/',
  19403. '|': '\\'
  19404. },
  19405. /**
  19406. * this is a list of special strings you can use to map
  19407. * to modifier keys when you specify your keyboard shortcuts
  19408. *
  19409. * @type {Object}
  19410. */
  19411. _SPECIAL_ALIASES = {
  19412. 'option': 'alt',
  19413. 'command': 'meta',
  19414. 'return': 'enter',
  19415. 'escape': 'esc'
  19416. },
  19417. /**
  19418. * variable to store the flipped version of _MAP from above
  19419. * needed to check if we should use keypress or not when no action
  19420. * is specified
  19421. *
  19422. * @type {Object|undefined}
  19423. */
  19424. _REVERSE_MAP,
  19425. /**
  19426. * a list of all the callbacks setup via Mousetrap.bind()
  19427. *
  19428. * @type {Object}
  19429. */
  19430. _callbacks = {},
  19431. /**
  19432. * direct map of string combinations to callbacks used for trigger()
  19433. *
  19434. * @type {Object}
  19435. */
  19436. _direct_map = {},
  19437. /**
  19438. * keeps track of what level each sequence is at since multiple
  19439. * sequences can start out with the same sequence
  19440. *
  19441. * @type {Object}
  19442. */
  19443. _sequence_levels = {},
  19444. /**
  19445. * variable to store the setTimeout call
  19446. *
  19447. * @type {null|number}
  19448. */
  19449. _reset_timer,
  19450. /**
  19451. * temporary state where we will ignore the next keyup
  19452. *
  19453. * @type {boolean|string}
  19454. */
  19455. _ignore_next_keyup = false,
  19456. /**
  19457. * are we currently inside of a sequence?
  19458. * type of action ("keyup" or "keydown" or "keypress") or false
  19459. *
  19460. * @type {boolean|string}
  19461. */
  19462. _inside_sequence = false;
  19463. /**
  19464. * loop through the f keys, f1 to f19 and add them to the map
  19465. * programatically
  19466. */
  19467. for (var i = 1; i < 20; ++i) {
  19468. _MAP[111 + i] = 'f' + i;
  19469. }
  19470. /**
  19471. * loop through to map numbers on the numeric keypad
  19472. */
  19473. for (i = 0; i <= 9; ++i) {
  19474. _MAP[i + 96] = i;
  19475. }
  19476. /**
  19477. * cross browser add event method
  19478. *
  19479. * @param {Element|HTMLDocument} object
  19480. * @param {string} type
  19481. * @param {Function} callback
  19482. * @returns void
  19483. */
  19484. function _addEvent(object, type, callback) {
  19485. if (object.addEventListener) {
  19486. return object.addEventListener(type, callback, false);
  19487. }
  19488. object.attachEvent('on' + type, callback);
  19489. }
  19490. /**
  19491. * takes the event and returns the key character
  19492. *
  19493. * @param {Event} e
  19494. * @return {string}
  19495. */
  19496. function _characterFromEvent(e) {
  19497. // for keypress events we should return the character as is
  19498. if (e.type == 'keypress') {
  19499. return String.fromCharCode(e.which);
  19500. }
  19501. // for non keypress events the special maps are needed
  19502. if (_MAP[e.which]) {
  19503. return _MAP[e.which];
  19504. }
  19505. if (_KEYCODE_MAP[e.which]) {
  19506. return _KEYCODE_MAP[e.which];
  19507. }
  19508. // if it is not in the special map
  19509. return String.fromCharCode(e.which).toLowerCase();
  19510. }
  19511. /**
  19512. * should we stop this event before firing off callbacks
  19513. *
  19514. * @param {Event} e
  19515. * @return {boolean}
  19516. */
  19517. function _stop(e) {
  19518. var element = e.target || e.srcElement,
  19519. tag_name = element.tagName;
  19520. // if the element has the class "mousetrap" then no need to stop
  19521. if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {
  19522. return false;
  19523. }
  19524. // stop for input, select, and textarea
  19525. return tag_name == 'INPUT' || tag_name == 'SELECT' || tag_name == 'TEXTAREA' || (element.contentEditable && element.contentEditable == 'true');
  19526. }
  19527. /**
  19528. * checks if two arrays are equal
  19529. *
  19530. * @param {Array} modifiers1
  19531. * @param {Array} modifiers2
  19532. * @returns {boolean}
  19533. */
  19534. function _modifiersMatch(modifiers1, modifiers2) {
  19535. return modifiers1.sort().join(',') === modifiers2.sort().join(',');
  19536. }
  19537. /**
  19538. * resets all sequence counters except for the ones passed in
  19539. *
  19540. * @param {Object} do_not_reset
  19541. * @returns void
  19542. */
  19543. function _resetSequences(do_not_reset) {
  19544. do_not_reset = do_not_reset || {};
  19545. var active_sequences = false,
  19546. key;
  19547. for (key in _sequence_levels) {
  19548. if (do_not_reset[key]) {
  19549. active_sequences = true;
  19550. continue;
  19551. }
  19552. _sequence_levels[key] = 0;
  19553. }
  19554. if (!active_sequences) {
  19555. _inside_sequence = false;
  19556. }
  19557. }
  19558. /**
  19559. * finds all callbacks that match based on the keycode, modifiers,
  19560. * and action
  19561. *
  19562. * @param {string} character
  19563. * @param {Array} modifiers
  19564. * @param {string} action
  19565. * @param {boolean=} remove - should we remove any matches
  19566. * @param {string=} combination
  19567. * @returns {Array}
  19568. */
  19569. function _getMatches(character, modifiers, action, remove, combination) {
  19570. var i,
  19571. callback,
  19572. matches = [];
  19573. // if there are no events related to this keycode
  19574. if (!_callbacks[character]) {
  19575. return [];
  19576. }
  19577. // if a modifier key is coming up on its own we should allow it
  19578. if (action == 'keyup' && _isModifier(character)) {
  19579. modifiers = [character];
  19580. }
  19581. // loop through all callbacks for the key that was pressed
  19582. // and see if any of them match
  19583. for (i = 0; i < _callbacks[character].length; ++i) {
  19584. callback = _callbacks[character][i];
  19585. // if this is a sequence but it is not at the right level
  19586. // then move onto the next match
  19587. if (callback.seq && _sequence_levels[callback.seq] != callback.level) {
  19588. continue;
  19589. }
  19590. // if the action we are looking for doesn't match the action we got
  19591. // then we should keep going
  19592. if (action != callback.action) {
  19593. continue;
  19594. }
  19595. // if this is a keypress event that means that we need to only
  19596. // look at the character, otherwise check the modifiers as
  19597. // well
  19598. if (action == 'keypress' || _modifiersMatch(modifiers, callback.modifiers)) {
  19599. // remove is used so if you change your mind and call bind a
  19600. // second time with a new function the first one is overwritten
  19601. if (remove && callback.combo == combination) {
  19602. _callbacks[character].splice(i, 1);
  19603. }
  19604. matches.push(callback);
  19605. }
  19606. }
  19607. return matches;
  19608. }
  19609. /**
  19610. * takes a key event and figures out what the modifiers are
  19611. *
  19612. * @param {Event} e
  19613. * @returns {Array}
  19614. */
  19615. function _eventModifiers(e) {
  19616. var modifiers = [];
  19617. if (e.shiftKey) {
  19618. modifiers.push('shift');
  19619. }
  19620. if (e.altKey) {
  19621. modifiers.push('alt');
  19622. }
  19623. if (e.ctrlKey) {
  19624. modifiers.push('ctrl');
  19625. }
  19626. if (e.metaKey) {
  19627. modifiers.push('meta');
  19628. }
  19629. return modifiers;
  19630. }
  19631. /**
  19632. * actually calls the callback function
  19633. *
  19634. * if your callback function returns false this will use the jquery
  19635. * convention - prevent default and stop propogation on the event
  19636. *
  19637. * @param {Function} callback
  19638. * @param {Event} e
  19639. * @returns void
  19640. */
  19641. function _fireCallback(callback, e) {
  19642. if (callback(e) === false) {
  19643. if (e.preventDefault) {
  19644. e.preventDefault();
  19645. }
  19646. if (e.stopPropagation) {
  19647. e.stopPropagation();
  19648. }
  19649. e.returnValue = false;
  19650. e.cancelBubble = true;
  19651. }
  19652. }
  19653. /**
  19654. * handles a character key event
  19655. *
  19656. * @param {string} character
  19657. * @param {Event} e
  19658. * @returns void
  19659. */
  19660. function _handleCharacter(character, e) {
  19661. // if this event should not happen stop here
  19662. if (_stop(e)) {
  19663. return;
  19664. }
  19665. var callbacks = _getMatches(character, _eventModifiers(e), e.type),
  19666. i,
  19667. do_not_reset = {},
  19668. processed_sequence_callback = false;
  19669. // loop through matching callbacks for this key event
  19670. for (i = 0; i < callbacks.length; ++i) {
  19671. // fire for all sequence callbacks
  19672. // this is because if for example you have multiple sequences
  19673. // bound such as "g i" and "g t" they both need to fire the
  19674. // callback for matching g cause otherwise you can only ever
  19675. // match the first one
  19676. if (callbacks[i].seq) {
  19677. processed_sequence_callback = true;
  19678. // keep a list of which sequences were matches for later
  19679. do_not_reset[callbacks[i].seq] = 1;
  19680. _fireCallback(callbacks[i].callback, e);
  19681. continue;
  19682. }
  19683. // if there were no sequence matches but we are still here
  19684. // that means this is a regular match so we should fire that
  19685. if (!processed_sequence_callback && !_inside_sequence) {
  19686. _fireCallback(callbacks[i].callback, e);
  19687. }
  19688. }
  19689. // if you are inside of a sequence and the key you are pressing
  19690. // is not a modifier key then we should reset all sequences
  19691. // that were not matched by this key event
  19692. if (e.type == _inside_sequence && !_isModifier(character)) {
  19693. _resetSequences(do_not_reset);
  19694. }
  19695. }
  19696. /**
  19697. * handles a keydown event
  19698. *
  19699. * @param {Event} e
  19700. * @returns void
  19701. */
  19702. function _handleKey(e) {
  19703. // normalize e.which for key events
  19704. // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion
  19705. e.which = typeof e.which == "number" ? e.which : e.keyCode;
  19706. var character = _characterFromEvent(e);
  19707. // no character found then stop
  19708. if (!character) {
  19709. return;
  19710. }
  19711. if (e.type == 'keyup' && _ignore_next_keyup == character) {
  19712. _ignore_next_keyup = false;
  19713. return;
  19714. }
  19715. _handleCharacter(character, e);
  19716. }
  19717. /**
  19718. * determines if the keycode specified is a modifier key or not
  19719. *
  19720. * @param {string} key
  19721. * @returns {boolean}
  19722. */
  19723. function _isModifier(key) {
  19724. return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta';
  19725. }
  19726. /**
  19727. * called to set a 1 second timeout on the specified sequence
  19728. *
  19729. * this is so after each key press in the sequence you have 1 second
  19730. * to press the next key before you have to start over
  19731. *
  19732. * @returns void
  19733. */
  19734. function _resetSequenceTimer() {
  19735. clearTimeout(_reset_timer);
  19736. _reset_timer = setTimeout(_resetSequences, 1000);
  19737. }
  19738. /**
  19739. * reverses the map lookup so that we can look for specific keys
  19740. * to see what can and can't use keypress
  19741. *
  19742. * @return {Object}
  19743. */
  19744. function _getReverseMap() {
  19745. if (!_REVERSE_MAP) {
  19746. _REVERSE_MAP = {};
  19747. for (var key in _MAP) {
  19748. // pull out the numeric keypad from here cause keypress should
  19749. // be able to detect the keys from the character
  19750. if (key > 95 && key < 112) {
  19751. continue;
  19752. }
  19753. if (_MAP.hasOwnProperty(key)) {
  19754. _REVERSE_MAP[_MAP[key]] = key;
  19755. }
  19756. }
  19757. }
  19758. return _REVERSE_MAP;
  19759. }
  19760. /**
  19761. * picks the best action based on the key combination
  19762. *
  19763. * @param {string} key - character for key
  19764. * @param {Array} modifiers
  19765. * @param {string=} action passed in
  19766. */
  19767. function _pickBestAction(key, modifiers, action) {
  19768. // if no action was picked in we should try to pick the one
  19769. // that we think would work best for this key
  19770. if (!action) {
  19771. action = _getReverseMap()[key] ? 'keydown' : 'keypress';
  19772. }
  19773. // modifier keys don't work as expected with keypress,
  19774. // switch to keydown
  19775. if (action == 'keypress' && modifiers.length) {
  19776. action = 'keydown';
  19777. }
  19778. return action;
  19779. }
  19780. /**
  19781. * binds a key sequence to an event
  19782. *
  19783. * @param {string} combo - combo specified in bind call
  19784. * @param {Array} keys
  19785. * @param {Function} callback
  19786. * @param {string=} action
  19787. * @returns void
  19788. */
  19789. function _bindSequence(combo, keys, callback, action) {
  19790. // start off by adding a sequence level record for this combination
  19791. // and setting the level to 0
  19792. _sequence_levels[combo] = 0;
  19793. // if there is no action pick the best one for the first key
  19794. // in the sequence
  19795. if (!action) {
  19796. action = _pickBestAction(keys[0], []);
  19797. }
  19798. /**
  19799. * callback to increase the sequence level for this sequence and reset
  19800. * all other sequences that were active
  19801. *
  19802. * @param {Event} e
  19803. * @returns void
  19804. */
  19805. var _increaseSequence = function(e) {
  19806. _inside_sequence = action;
  19807. ++_sequence_levels[combo];
  19808. _resetSequenceTimer();
  19809. },
  19810. /**
  19811. * wraps the specified callback inside of another function in order
  19812. * to reset all sequence counters as soon as this sequence is done
  19813. *
  19814. * @param {Event} e
  19815. * @returns void
  19816. */
  19817. _callbackAndReset = function(e) {
  19818. _fireCallback(callback, e);
  19819. // we should ignore the next key up if the action is key down
  19820. // or keypress. this is so if you finish a sequence and
  19821. // release the key the final key will not trigger a keyup
  19822. if (action !== 'keyup') {
  19823. _ignore_next_keyup = _characterFromEvent(e);
  19824. }
  19825. // weird race condition if a sequence ends with the key
  19826. // another sequence begins with
  19827. setTimeout(_resetSequences, 10);
  19828. },
  19829. i;
  19830. // loop through keys one at a time and bind the appropriate callback
  19831. // function. for any key leading up to the final one it should
  19832. // increase the sequence. after the final, it should reset all sequences
  19833. for (i = 0; i < keys.length; ++i) {
  19834. _bindSingle(keys[i], i < keys.length - 1 ? _increaseSequence : _callbackAndReset, action, combo, i);
  19835. }
  19836. }
  19837. /**
  19838. * binds a single keyboard combination
  19839. *
  19840. * @param {string} combination
  19841. * @param {Function} callback
  19842. * @param {string=} action
  19843. * @param {string=} sequence_name - name of sequence if part of sequence
  19844. * @param {number=} level - what part of the sequence the command is
  19845. * @returns void
  19846. */
  19847. function _bindSingle(combination, callback, action, sequence_name, level) {
  19848. // make sure multiple spaces in a row become a single space
  19849. combination = combination.replace(/\s+/g, ' ');
  19850. var sequence = combination.split(' '),
  19851. i,
  19852. key,
  19853. keys,
  19854. modifiers = [];
  19855. // if this pattern is a sequence of keys then run through this method
  19856. // to reprocess each pattern one key at a time
  19857. if (sequence.length > 1) {
  19858. return _bindSequence(combination, sequence, callback, action);
  19859. }
  19860. // take the keys from this pattern and figure out what the actual
  19861. // pattern is all about
  19862. keys = combination === '+' ? ['+'] : combination.split('+');
  19863. for (i = 0; i < keys.length; ++i) {
  19864. key = keys[i];
  19865. // normalize key names
  19866. if (_SPECIAL_ALIASES[key]) {
  19867. key = _SPECIAL_ALIASES[key];
  19868. }
  19869. // if this is not a keypress event then we should
  19870. // be smart about using shift keys
  19871. // this will only work for US keyboards however
  19872. if (action && action != 'keypress' && _SHIFT_MAP[key]) {
  19873. key = _SHIFT_MAP[key];
  19874. modifiers.push('shift');
  19875. }
  19876. // if this key is a modifier then add it to the list of modifiers
  19877. if (_isModifier(key)) {
  19878. modifiers.push(key);
  19879. }
  19880. }
  19881. // depending on what the key combination is
  19882. // we will try to pick the best event for it
  19883. action = _pickBestAction(key, modifiers, action);
  19884. // make sure to initialize array if this is the first time
  19885. // a callback is added for this key
  19886. if (!_callbacks[key]) {
  19887. _callbacks[key] = [];
  19888. }
  19889. // remove an existing match if there is one
  19890. _getMatches(key, modifiers, action, !sequence_name, combination);
  19891. // add this call back to the array
  19892. // if it is a sequence put it at the beginning
  19893. // if not put it at the end
  19894. //
  19895. // this is important because the way these are processed expects
  19896. // the sequence ones to come first
  19897. _callbacks[key][sequence_name ? 'unshift' : 'push']({
  19898. callback: callback,
  19899. modifiers: modifiers,
  19900. action: action,
  19901. seq: sequence_name,
  19902. level: level,
  19903. combo: combination
  19904. });
  19905. }
  19906. /**
  19907. * binds multiple combinations to the same callback
  19908. *
  19909. * @param {Array} combinations
  19910. * @param {Function} callback
  19911. * @param {string|undefined} action
  19912. * @returns void
  19913. */
  19914. function _bindMultiple(combinations, callback, action) {
  19915. for (var i = 0; i < combinations.length; ++i) {
  19916. _bindSingle(combinations[i], callback, action);
  19917. }
  19918. }
  19919. // start!
  19920. _addEvent(document, 'keypress', _handleKey);
  19921. _addEvent(document, 'keydown', _handleKey);
  19922. _addEvent(document, 'keyup', _handleKey);
  19923. var mousetrap = {
  19924. /**
  19925. * binds an event to mousetrap
  19926. *
  19927. * can be a single key, a combination of keys separated with +,
  19928. * a comma separated list of keys, an array of keys, or
  19929. * a sequence of keys separated by spaces
  19930. *
  19931. * be sure to list the modifier keys first to make sure that the
  19932. * correct key ends up getting bound (the last key in the pattern)
  19933. *
  19934. * @param {string|Array} keys
  19935. * @param {Function} callback
  19936. * @param {string=} action - 'keypress', 'keydown', or 'keyup'
  19937. * @returns void
  19938. */
  19939. bind: function(keys, callback, action) {
  19940. _bindMultiple(keys instanceof Array ? keys : [keys], callback, action);
  19941. _direct_map[keys + ':' + action] = callback;
  19942. return this;
  19943. },
  19944. /**
  19945. * unbinds an event to mousetrap
  19946. *
  19947. * the unbinding sets the callback function of the specified key combo
  19948. * to an empty function and deletes the corresponding key in the
  19949. * _direct_map dict.
  19950. *
  19951. * the keycombo+action has to be exactly the same as
  19952. * it was defined in the bind method
  19953. *
  19954. * TODO: actually remove this from the _callbacks dictionary instead
  19955. * of binding an empty function
  19956. *
  19957. * @param {string|Array} keys
  19958. * @param {string} action
  19959. * @returns void
  19960. */
  19961. unbind: function(keys, action) {
  19962. if (_direct_map[keys + ':' + action]) {
  19963. delete _direct_map[keys + ':' + action];
  19964. this.bind(keys, function() {}, action);
  19965. }
  19966. return this;
  19967. },
  19968. /**
  19969. * triggers an event that has already been bound
  19970. *
  19971. * @param {string} keys
  19972. * @param {string=} action
  19973. * @returns void
  19974. */
  19975. trigger: function(keys, action) {
  19976. _direct_map[keys + ':' + action]();
  19977. return this;
  19978. },
  19979. /**
  19980. * resets the library back to its initial state. this is useful
  19981. * if you want to clear out the current keyboard shortcuts and bind
  19982. * new ones - for example if you switch to another page
  19983. *
  19984. * @returns void
  19985. */
  19986. reset: function() {
  19987. _callbacks = {};
  19988. _direct_map = {};
  19989. return this;
  19990. }
  19991. };
  19992. module.exports = mousetrap;
  19993. },{}]},{},[1])
  19994. (1)
  19995. });