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.

22627 lines
658 KiB

  1. /**
  2. * vis.js
  3. * https://github.com/almende/vis
  4. *
  5. * A dynamic, browser-based visualization library.
  6. *
  7. * @version @@version
  8. * @date @@date
  9. *
  10. * @license
  11. * Copyright (C) 2011-2014 Almende B.V, http://almende.com
  12. *
  13. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  14. * use this file except in compliance with the License. You may obtain a copy
  15. * of the License at
  16. *
  17. * http://www.apache.org/licenses/LICENSE-2.0
  18. *
  19. * Unless required by applicable law or agreed to in writing, software
  20. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  21. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  22. * License for the specific language governing permissions and limitations under
  23. * the License.
  24. */
  25. !function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.vis=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  26. /**
  27. * vis.js module imports
  28. */
  29. // Try to load dependencies from the global window object.
  30. // If not available there, load via require.
  31. var moment = (typeof window !== 'undefined') && window['moment'] || require('moment');
  32. var Emitter = require('emitter-component');
  33. var Hammer;
  34. if (typeof window !== 'undefined') {
  35. // load hammer.js only when running in a browser (where window is available)
  36. Hammer = window['Hammer'] || require('hammerjs');
  37. }
  38. else {
  39. Hammer = function () {
  40. throw Error('hammer.js is only available in a browser, not in node.js.');
  41. }
  42. }
  43. var mousetrap;
  44. if (typeof window !== 'undefined') {
  45. // load mousetrap.js only when running in a browser (where window is available)
  46. mousetrap = window['mousetrap'] || require('mousetrap');
  47. }
  48. else {
  49. mousetrap = function () {
  50. throw Error('mouseTrap is only available in a browser, not in node.js.');
  51. }
  52. }
  53. // Internet Explorer 8 and older does not support Array.indexOf, so we define
  54. // it here in that case.
  55. // http://soledadpenades.com/2007/05/17/arrayindexof-in-internet-explorer/
  56. if(!Array.prototype.indexOf) {
  57. Array.prototype.indexOf = function(obj){
  58. for(var i = 0; i < this.length; i++){
  59. if(this[i] == obj){
  60. return i;
  61. }
  62. }
  63. return -1;
  64. };
  65. try {
  66. console.log("Warning: Ancient browser detected. Please update your browser");
  67. }
  68. catch (err) {
  69. }
  70. }
  71. // Internet Explorer 8 and older does not support Array.forEach, so we define
  72. // it here in that case.
  73. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach
  74. if (!Array.prototype.forEach) {
  75. Array.prototype.forEach = function(fn, scope) {
  76. for(var i = 0, len = this.length; i < len; ++i) {
  77. fn.call(scope || this, this[i], i, this);
  78. }
  79. }
  80. }
  81. // Internet Explorer 8 and older does not support Array.map, so we define it
  82. // here in that case.
  83. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map
  84. // Production steps of ECMA-262, Edition 5, 15.4.4.19
  85. // Reference: http://es5.github.com/#x15.4.4.19
  86. if (!Array.prototype.map) {
  87. Array.prototype.map = function(callback, thisArg) {
  88. var T, A, k;
  89. if (this == null) {
  90. throw new TypeError(" this is null or not defined");
  91. }
  92. // 1. Let O be the result of calling ToObject passing the |this| value as the argument.
  93. var O = Object(this);
  94. // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
  95. // 3. Let len be ToUint32(lenValue).
  96. var len = O.length >>> 0;
  97. // 4. If IsCallable(callback) is false, throw a TypeError exception.
  98. // See: http://es5.github.com/#x9.11
  99. if (typeof callback !== "function") {
  100. throw new TypeError(callback + " is not a function");
  101. }
  102. // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
  103. if (thisArg) {
  104. T = thisArg;
  105. }
  106. // 6. Let A be a new array created as if by the expression new Array(len) where Array is
  107. // the standard built-in constructor with that name and len is the value of len.
  108. A = new Array(len);
  109. // 7. Let k be 0
  110. k = 0;
  111. // 8. Repeat, while k < len
  112. while(k < len) {
  113. var kValue, mappedValue;
  114. // a. Let Pk be ToString(k).
  115. // This is implicit for LHS operands of the in operator
  116. // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
  117. // This step can be combined with c
  118. // c. If kPresent is true, then
  119. if (k in O) {
  120. // i. Let kValue be the result of calling the Get internal method of O with argument Pk.
  121. kValue = O[ k ];
  122. // ii. Let mappedValue be the result of calling the Call internal method of callback
  123. // with T as the this value and argument list containing kValue, k, and O.
  124. mappedValue = callback.call(T, kValue, k, O);
  125. // iii. Call the DefineOwnProperty internal method of A with arguments
  126. // Pk, Property Descriptor {Value: mappedValue, : true, Enumerable: true, Configurable: true},
  127. // and false.
  128. // In browsers that support Object.defineProperty, use the following:
  129. // Object.defineProperty(A, Pk, { value: mappedValue, writable: true, enumerable: true, configurable: true });
  130. // For best browser support, use the following:
  131. A[ k ] = mappedValue;
  132. }
  133. // d. Increase k by 1.
  134. k++;
  135. }
  136. // 9. return A
  137. return A;
  138. };
  139. }
  140. // Internet Explorer 8 and older does not support Array.filter, so we define it
  141. // here in that case.
  142. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter
  143. if (!Array.prototype.filter) {
  144. Array.prototype.filter = function(fun /*, thisp */) {
  145. "use strict";
  146. if (this == null) {
  147. throw new TypeError();
  148. }
  149. var t = Object(this);
  150. var len = t.length >>> 0;
  151. if (typeof fun != "function") {
  152. throw new TypeError();
  153. }
  154. var res = [];
  155. var thisp = arguments[1];
  156. for (var i = 0; i < len; i++) {
  157. if (i in t) {
  158. var val = t[i]; // in case fun mutates this
  159. if (fun.call(thisp, val, i, t))
  160. res.push(val);
  161. }
  162. }
  163. return res;
  164. };
  165. }
  166. // Internet Explorer 8 and older does not support Object.keys, so we define it
  167. // here in that case.
  168. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/keys
  169. if (!Object.keys) {
  170. Object.keys = (function () {
  171. var hasOwnProperty = Object.prototype.hasOwnProperty,
  172. hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
  173. dontEnums = [
  174. 'toString',
  175. 'toLocaleString',
  176. 'valueOf',
  177. 'hasOwnProperty',
  178. 'isPrototypeOf',
  179. 'propertyIsEnumerable',
  180. 'constructor'
  181. ],
  182. dontEnumsLength = dontEnums.length;
  183. return function (obj) {
  184. if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) {
  185. throw new TypeError('Object.keys called on non-object');
  186. }
  187. var result = [];
  188. for (var prop in obj) {
  189. if (hasOwnProperty.call(obj, prop)) result.push(prop);
  190. }
  191. if (hasDontEnumBug) {
  192. for (var i=0; i < dontEnumsLength; i++) {
  193. if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
  194. }
  195. }
  196. return result;
  197. }
  198. })()
  199. }
  200. // Internet Explorer 8 and older does not support Array.isArray,
  201. // so we define it here in that case.
  202. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/isArray
  203. if(!Array.isArray) {
  204. Array.isArray = function (vArg) {
  205. return Object.prototype.toString.call(vArg) === "[object Array]";
  206. };
  207. }
  208. // Internet Explorer 8 and older does not support Function.bind,
  209. // so we define it here in that case.
  210. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind
  211. if (!Function.prototype.bind) {
  212. Function.prototype.bind = function (oThis) {
  213. if (typeof this !== "function") {
  214. // closest thing possible to the ECMAScript 5 internal IsCallable function
  215. throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
  216. }
  217. var aArgs = Array.prototype.slice.call(arguments, 1),
  218. fToBind = this,
  219. fNOP = function () {},
  220. fBound = function () {
  221. return fToBind.apply(this instanceof fNOP && oThis
  222. ? this
  223. : oThis,
  224. aArgs.concat(Array.prototype.slice.call(arguments)));
  225. };
  226. fNOP.prototype = this.prototype;
  227. fBound.prototype = new fNOP();
  228. return fBound;
  229. };
  230. }
  231. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create
  232. if (!Object.create) {
  233. Object.create = function (o) {
  234. if (arguments.length > 1) {
  235. throw new Error('Object.create implementation only accepts the first parameter.');
  236. }
  237. function F() {}
  238. F.prototype = o;
  239. return new F();
  240. };
  241. }
  242. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
  243. if (!Function.prototype.bind) {
  244. Function.prototype.bind = function (oThis) {
  245. if (typeof this !== "function") {
  246. // closest thing possible to the ECMAScript 5 internal IsCallable function
  247. throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
  248. }
  249. var aArgs = Array.prototype.slice.call(arguments, 1),
  250. fToBind = this,
  251. fNOP = function () {},
  252. fBound = function () {
  253. return fToBind.apply(this instanceof fNOP && oThis
  254. ? this
  255. : oThis,
  256. aArgs.concat(Array.prototype.slice.call(arguments)));
  257. };
  258. fNOP.prototype = this.prototype;
  259. fBound.prototype = new fNOP();
  260. return fBound;
  261. };
  262. }
  263. /**
  264. * utility functions
  265. */
  266. var util = {};
  267. /**
  268. * Test whether given object is a number
  269. * @param {*} object
  270. * @return {Boolean} isNumber
  271. */
  272. util.isNumber = function isNumber(object) {
  273. return (object instanceof Number || typeof object == 'number');
  274. };
  275. /**
  276. * Test whether given object is a string
  277. * @param {*} object
  278. * @return {Boolean} isString
  279. */
  280. util.isString = function isString(object) {
  281. return (object instanceof String || typeof object == 'string');
  282. };
  283. /**
  284. * Test whether given object is a Date, or a String containing a Date
  285. * @param {Date | String} object
  286. * @return {Boolean} isDate
  287. */
  288. util.isDate = function isDate(object) {
  289. if (object instanceof Date) {
  290. return true;
  291. }
  292. else if (util.isString(object)) {
  293. // test whether this string contains a date
  294. var match = ASPDateRegex.exec(object);
  295. if (match) {
  296. return true;
  297. }
  298. else if (!isNaN(Date.parse(object))) {
  299. return true;
  300. }
  301. }
  302. return false;
  303. };
  304. /**
  305. * Test whether given object is an instance of google.visualization.DataTable
  306. * @param {*} object
  307. * @return {Boolean} isDataTable
  308. */
  309. util.isDataTable = function isDataTable(object) {
  310. return (typeof (google) !== 'undefined') &&
  311. (google.visualization) &&
  312. (google.visualization.DataTable) &&
  313. (object instanceof google.visualization.DataTable);
  314. };
  315. /**
  316. * Create a semi UUID
  317. * source: http://stackoverflow.com/a/105074/1262753
  318. * @return {String} uuid
  319. */
  320. util.randomUUID = function randomUUID () {
  321. var S4 = function () {
  322. return Math.floor(
  323. Math.random() * 0x10000 /* 65536 */
  324. ).toString(16);
  325. };
  326. return (
  327. S4() + S4() + '-' +
  328. S4() + '-' +
  329. S4() + '-' +
  330. S4() + '-' +
  331. S4() + S4() + S4()
  332. );
  333. };
  334. /**
  335. * Extend object a with the properties of object b or a series of objects
  336. * Only properties with defined values are copied
  337. * @param {Object} a
  338. * @param {... Object} b
  339. * @return {Object} a
  340. */
  341. util.extend = function (a, b) {
  342. for (var i = 1, len = arguments.length; i < len; i++) {
  343. var other = arguments[i];
  344. for (var prop in other) {
  345. if (other.hasOwnProperty(prop) && other[prop] !== undefined) {
  346. a[prop] = other[prop];
  347. }
  348. }
  349. }
  350. return a;
  351. };
  352. /**
  353. * Convert an object to another type
  354. * @param {Boolean | Number | String | Date | Moment | Null | undefined} object
  355. * @param {String | undefined} type Name of the type. Available types:
  356. * 'Boolean', 'Number', 'String',
  357. * 'Date', 'Moment', ISODate', 'ASPDate'.
  358. * @return {*} object
  359. * @throws Error
  360. */
  361. util.convert = function convert(object, type) {
  362. var match;
  363. if (object === undefined) {
  364. return undefined;
  365. }
  366. if (object === null) {
  367. return null;
  368. }
  369. if (!type) {
  370. return object;
  371. }
  372. if (!(typeof type === 'string') && !(type instanceof String)) {
  373. throw new Error('Type must be a string');
  374. }
  375. //noinspection FallthroughInSwitchStatementJS
  376. switch (type) {
  377. case 'boolean':
  378. case 'Boolean':
  379. return Boolean(object);
  380. case 'number':
  381. case 'Number':
  382. return Number(object.valueOf());
  383. case 'string':
  384. case 'String':
  385. return String(object);
  386. case 'Date':
  387. if (util.isNumber(object)) {
  388. return new Date(object);
  389. }
  390. if (object instanceof Date) {
  391. return new Date(object.valueOf());
  392. }
  393. else if (moment.isMoment(object)) {
  394. return new Date(object.valueOf());
  395. }
  396. if (util.isString(object)) {
  397. match = ASPDateRegex.exec(object);
  398. if (match) {
  399. // object is an ASP date
  400. return new Date(Number(match[1])); // parse number
  401. }
  402. else {
  403. return moment(object).toDate(); // parse string
  404. }
  405. }
  406. else {
  407. throw new Error(
  408. 'Cannot convert object of type ' + util.getType(object) +
  409. ' to type Date');
  410. }
  411. case 'Moment':
  412. if (util.isNumber(object)) {
  413. return moment(object);
  414. }
  415. if (object instanceof Date) {
  416. return moment(object.valueOf());
  417. }
  418. else if (moment.isMoment(object)) {
  419. return moment(object);
  420. }
  421. if (util.isString(object)) {
  422. match = ASPDateRegex.exec(object);
  423. if (match) {
  424. // object is an ASP date
  425. return moment(Number(match[1])); // parse number
  426. }
  427. else {
  428. return moment(object); // parse string
  429. }
  430. }
  431. else {
  432. throw new Error(
  433. 'Cannot convert object of type ' + util.getType(object) +
  434. ' to type Date');
  435. }
  436. case 'ISODate':
  437. if (util.isNumber(object)) {
  438. return new Date(object);
  439. }
  440. else if (object instanceof Date) {
  441. return object.toISOString();
  442. }
  443. else if (moment.isMoment(object)) {
  444. return object.toDate().toISOString();
  445. }
  446. else if (util.isString(object)) {
  447. match = ASPDateRegex.exec(object);
  448. if (match) {
  449. // object is an ASP date
  450. return new Date(Number(match[1])).toISOString(); // parse number
  451. }
  452. else {
  453. return new Date(object).toISOString(); // parse string
  454. }
  455. }
  456. else {
  457. throw new Error(
  458. 'Cannot convert object of type ' + util.getType(object) +
  459. ' to type ISODate');
  460. }
  461. case 'ASPDate':
  462. if (util.isNumber(object)) {
  463. return '/Date(' + object + ')/';
  464. }
  465. else if (object instanceof Date) {
  466. return '/Date(' + object.valueOf() + ')/';
  467. }
  468. else if (util.isString(object)) {
  469. match = ASPDateRegex.exec(object);
  470. var value;
  471. if (match) {
  472. // object is an ASP date
  473. value = new Date(Number(match[1])).valueOf(); // parse number
  474. }
  475. else {
  476. value = new Date(object).valueOf(); // parse string
  477. }
  478. return '/Date(' + value + ')/';
  479. }
  480. else {
  481. throw new Error(
  482. 'Cannot convert object of type ' + util.getType(object) +
  483. ' to type ASPDate');
  484. }
  485. default:
  486. throw new Error('Cannot convert object of type ' + util.getType(object) +
  487. ' to type "' + type + '"');
  488. }
  489. };
  490. // parse ASP.Net Date pattern,
  491. // for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/'
  492. // code from http://momentjs.com/
  493. var ASPDateRegex = /^\/?Date\((\-?\d+)/i;
  494. /**
  495. * Get the type of an object, for example util.getType([]) returns 'Array'
  496. * @param {*} object
  497. * @return {String} type
  498. */
  499. util.getType = function getType(object) {
  500. var type = typeof object;
  501. if (type == 'object') {
  502. if (object == null) {
  503. return 'null';
  504. }
  505. if (object instanceof Boolean) {
  506. return 'Boolean';
  507. }
  508. if (object instanceof Number) {
  509. return 'Number';
  510. }
  511. if (object instanceof String) {
  512. return 'String';
  513. }
  514. if (object instanceof Array) {
  515. return 'Array';
  516. }
  517. if (object instanceof Date) {
  518. return 'Date';
  519. }
  520. return 'Object';
  521. }
  522. else if (type == 'number') {
  523. return 'Number';
  524. }
  525. else if (type == 'boolean') {
  526. return 'Boolean';
  527. }
  528. else if (type == 'string') {
  529. return 'String';
  530. }
  531. return type;
  532. };
  533. /**
  534. * Retrieve the absolute left value of a DOM element
  535. * @param {Element} elem A dom element, for example a div
  536. * @return {number} left The absolute left position of this element
  537. * in the browser page.
  538. */
  539. util.getAbsoluteLeft = function getAbsoluteLeft (elem) {
  540. var doc = document.documentElement;
  541. var body = document.body;
  542. var left = elem.offsetLeft;
  543. var e = elem.offsetParent;
  544. while (e != null && e != body && e != doc) {
  545. left += e.offsetLeft;
  546. left -= e.scrollLeft;
  547. e = e.offsetParent;
  548. }
  549. return left;
  550. };
  551. /**
  552. * Retrieve the absolute top value of a DOM element
  553. * @param {Element} elem A dom element, for example a div
  554. * @return {number} top The absolute top position of this element
  555. * in the browser page.
  556. */
  557. util.getAbsoluteTop = function getAbsoluteTop (elem) {
  558. var doc = document.documentElement;
  559. var body = document.body;
  560. var top = elem.offsetTop;
  561. var e = elem.offsetParent;
  562. while (e != null && e != body && e != doc) {
  563. top += e.offsetTop;
  564. top -= e.scrollTop;
  565. e = e.offsetParent;
  566. }
  567. return top;
  568. };
  569. /**
  570. * Get the absolute, vertical mouse position from an event.
  571. * @param {Event} event
  572. * @return {Number} pageY
  573. */
  574. util.getPageY = function getPageY (event) {
  575. if ('pageY' in event) {
  576. return event.pageY;
  577. }
  578. else {
  579. var clientY;
  580. if (('targetTouches' in event) && event.targetTouches.length) {
  581. clientY = event.targetTouches[0].clientY;
  582. }
  583. else {
  584. clientY = event.clientY;
  585. }
  586. var doc = document.documentElement;
  587. var body = document.body;
  588. return clientY +
  589. ( doc && doc.scrollTop || body && body.scrollTop || 0 ) -
  590. ( doc && doc.clientTop || body && body.clientTop || 0 );
  591. }
  592. };
  593. /**
  594. * Get the absolute, horizontal mouse position from an event.
  595. * @param {Event} event
  596. * @return {Number} pageX
  597. */
  598. util.getPageX = function getPageX (event) {
  599. if ('pageY' in event) {
  600. return event.pageX;
  601. }
  602. else {
  603. var clientX;
  604. if (('targetTouches' in event) && event.targetTouches.length) {
  605. clientX = event.targetTouches[0].clientX;
  606. }
  607. else {
  608. clientX = event.clientX;
  609. }
  610. var doc = document.documentElement;
  611. var body = document.body;
  612. return clientX +
  613. ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) -
  614. ( doc && doc.clientLeft || body && body.clientLeft || 0 );
  615. }
  616. };
  617. /**
  618. * add a className to the given elements style
  619. * @param {Element} elem
  620. * @param {String} className
  621. */
  622. util.addClassName = function addClassName(elem, className) {
  623. var classes = elem.className.split(' ');
  624. if (classes.indexOf(className) == -1) {
  625. classes.push(className); // add the class to the array
  626. elem.className = classes.join(' ');
  627. }
  628. };
  629. /**
  630. * add a className to the given elements style
  631. * @param {Element} elem
  632. * @param {String} className
  633. */
  634. util.removeClassName = function removeClassname(elem, className) {
  635. var classes = elem.className.split(' ');
  636. var index = classes.indexOf(className);
  637. if (index != -1) {
  638. classes.splice(index, 1); // remove the class from the array
  639. elem.className = classes.join(' ');
  640. }
  641. };
  642. /**
  643. * For each method for both arrays and objects.
  644. * In case of an array, the built-in Array.forEach() is applied.
  645. * In case of an Object, the method loops over all properties of the object.
  646. * @param {Object | Array} object An Object or Array
  647. * @param {function} callback Callback method, called for each item in
  648. * the object or array with three parameters:
  649. * callback(value, index, object)
  650. */
  651. util.forEach = function forEach (object, callback) {
  652. var i,
  653. len;
  654. if (object instanceof Array) {
  655. // array
  656. for (i = 0, len = object.length; i < len; i++) {
  657. callback(object[i], i, object);
  658. }
  659. }
  660. else {
  661. // object
  662. for (i in object) {
  663. if (object.hasOwnProperty(i)) {
  664. callback(object[i], i, object);
  665. }
  666. }
  667. }
  668. };
  669. /**
  670. * Update a property in an object
  671. * @param {Object} object
  672. * @param {String} key
  673. * @param {*} value
  674. * @return {Boolean} changed
  675. */
  676. util.updateProperty = function updateProp (object, key, value) {
  677. if (object[key] !== value) {
  678. object[key] = value;
  679. return true;
  680. }
  681. else {
  682. return false;
  683. }
  684. };
  685. /**
  686. * Add and event listener. Works for all browsers
  687. * @param {Element} element An html element
  688. * @param {string} action The action, for example "click",
  689. * without the prefix "on"
  690. * @param {function} listener The callback function to be executed
  691. * @param {boolean} [useCapture]
  692. */
  693. util.addEventListener = function addEventListener(element, action, listener, useCapture) {
  694. if (element.addEventListener) {
  695. if (useCapture === undefined)
  696. useCapture = false;
  697. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  698. action = "DOMMouseScroll"; // For Firefox
  699. }
  700. element.addEventListener(action, listener, useCapture);
  701. } else {
  702. element.attachEvent("on" + action, listener); // IE browsers
  703. }
  704. };
  705. /**
  706. * Remove an event listener from an element
  707. * @param {Element} element An html dom element
  708. * @param {string} action The name of the event, for example "mousedown"
  709. * @param {function} listener The listener function
  710. * @param {boolean} [useCapture]
  711. */
  712. util.removeEventListener = function removeEventListener(element, action, listener, useCapture) {
  713. if (element.removeEventListener) {
  714. // non-IE browsers
  715. if (useCapture === undefined)
  716. useCapture = false;
  717. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  718. action = "DOMMouseScroll"; // For Firefox
  719. }
  720. element.removeEventListener(action, listener, useCapture);
  721. } else {
  722. // IE browsers
  723. element.detachEvent("on" + action, listener);
  724. }
  725. };
  726. /**
  727. * Get HTML element which is the target of the event
  728. * @param {Event} event
  729. * @return {Element} target element
  730. */
  731. util.getTarget = function getTarget(event) {
  732. // code from http://www.quirksmode.org/js/events_properties.html
  733. if (!event) {
  734. event = window.event;
  735. }
  736. var target;
  737. if (event.target) {
  738. target = event.target;
  739. }
  740. else if (event.srcElement) {
  741. target = event.srcElement;
  742. }
  743. if (target.nodeType != undefined && target.nodeType == 3) {
  744. // defeat Safari bug
  745. target = target.parentNode;
  746. }
  747. return target;
  748. };
  749. /**
  750. * Fake a hammer.js gesture. Event can be a ScrollEvent or MouseMoveEvent
  751. * @param {Element} element
  752. * @param {Event} event
  753. */
  754. util.fakeGesture = function fakeGesture (element, event) {
  755. var eventType = null;
  756. // for hammer.js 1.0.5
  757. var gesture = Hammer.event.collectEventData(this, eventType, event);
  758. // for hammer.js 1.0.6
  759. //var touches = Hammer.event.getTouchList(event, eventType);
  760. // var gesture = Hammer.event.collectEventData(this, eventType, touches, event);
  761. // on IE in standards mode, no touches are recognized by hammer.js,
  762. // resulting in NaN values for center.pageX and center.pageY
  763. if (isNaN(gesture.center.pageX)) {
  764. gesture.center.pageX = event.pageX;
  765. }
  766. if (isNaN(gesture.center.pageY)) {
  767. gesture.center.pageY = event.pageY;
  768. }
  769. return gesture;
  770. };
  771. util.option = {};
  772. /**
  773. * Convert a value into a boolean
  774. * @param {Boolean | function | undefined} value
  775. * @param {Boolean} [defaultValue]
  776. * @returns {Boolean} bool
  777. */
  778. util.option.asBoolean = function (value, defaultValue) {
  779. if (typeof value == 'function') {
  780. value = value();
  781. }
  782. if (value != null) {
  783. return (value != false);
  784. }
  785. return defaultValue || null;
  786. };
  787. /**
  788. * Convert a value into a number
  789. * @param {Boolean | function | undefined} value
  790. * @param {Number} [defaultValue]
  791. * @returns {Number} number
  792. */
  793. util.option.asNumber = function (value, defaultValue) {
  794. if (typeof value == 'function') {
  795. value = value();
  796. }
  797. if (value != null) {
  798. return Number(value) || defaultValue || null;
  799. }
  800. return defaultValue || null;
  801. };
  802. /**
  803. * Convert a value into a string
  804. * @param {String | function | undefined} value
  805. * @param {String} [defaultValue]
  806. * @returns {String} str
  807. */
  808. util.option.asString = function (value, defaultValue) {
  809. if (typeof value == 'function') {
  810. value = value();
  811. }
  812. if (value != null) {
  813. return String(value);
  814. }
  815. return defaultValue || null;
  816. };
  817. /**
  818. * Convert a size or location into a string with pixels or a percentage
  819. * @param {String | Number | function | undefined} value
  820. * @param {String} [defaultValue]
  821. * @returns {String} size
  822. */
  823. util.option.asSize = function (value, defaultValue) {
  824. if (typeof value == 'function') {
  825. value = value();
  826. }
  827. if (util.isString(value)) {
  828. return value;
  829. }
  830. else if (util.isNumber(value)) {
  831. return value + 'px';
  832. }
  833. else {
  834. return defaultValue || null;
  835. }
  836. };
  837. /**
  838. * Convert a value into a DOM element
  839. * @param {HTMLElement | function | undefined} value
  840. * @param {HTMLElement} [defaultValue]
  841. * @returns {HTMLElement | null} dom
  842. */
  843. util.option.asElement = function (value, defaultValue) {
  844. if (typeof value == 'function') {
  845. value = value();
  846. }
  847. return value || defaultValue || null;
  848. };
  849. util.GiveDec = function GiveDec(Hex)
  850. {
  851. if(Hex == "A")
  852. Value = 10;
  853. else
  854. if(Hex == "B")
  855. Value = 11;
  856. else
  857. if(Hex == "C")
  858. Value = 12;
  859. else
  860. if(Hex == "D")
  861. Value = 13;
  862. else
  863. if(Hex == "E")
  864. Value = 14;
  865. else
  866. if(Hex == "F")
  867. Value = 15;
  868. else
  869. Value = eval(Hex)
  870. return Value;
  871. }
  872. util.GiveHex = function GiveHex(Dec)
  873. {
  874. if(Dec == 10)
  875. Value = "A";
  876. else
  877. if(Dec == 11)
  878. Value = "B";
  879. else
  880. if(Dec == 12)
  881. Value = "C";
  882. else
  883. if(Dec == 13)
  884. Value = "D";
  885. else
  886. if(Dec == 14)
  887. Value = "E";
  888. else
  889. if(Dec == 15)
  890. Value = "F";
  891. else
  892. Value = "" + Dec;
  893. return Value;
  894. }
  895. /**
  896. * http://www.yellowpipe.com/yis/tools/hex-to-rgb/color-converter.php
  897. *
  898. * @param {String} hex
  899. * @returns {{r: *, g: *, b: *}}
  900. */
  901. util.hexToRGB = function hexToRGB(hex) {
  902. hex = hex.replace("#","").toUpperCase();
  903. var a = util.GiveDec(hex.substring(0, 1));
  904. var b = util.GiveDec(hex.substring(1, 2));
  905. var c = util.GiveDec(hex.substring(2, 3));
  906. var d = util.GiveDec(hex.substring(3, 4));
  907. var e = util.GiveDec(hex.substring(4, 5));
  908. var f = util.GiveDec(hex.substring(5, 6));
  909. var r = (a * 16) + b;
  910. var g = (c * 16) + d;
  911. var b = (e * 16) + f;
  912. return {r:r,g:g,b:b};
  913. };
  914. util.RGBToHex = function RGBToHex(red,green,blue) {
  915. var a = util.GiveHex(Math.floor(red / 16));
  916. var b = util.GiveHex(red % 16);
  917. var c = util.GiveHex(Math.floor(green / 16));
  918. var d = util.GiveHex(green % 16);
  919. var e = util.GiveHex(Math.floor(blue / 16));
  920. var f = util.GiveHex(blue % 16);
  921. var hex = a + b + c + d + e + f;
  922. return "#" + hex;
  923. };
  924. /**
  925. * http://www.javascripter.net/faq/rgb2hsv.htm
  926. *
  927. * @param red
  928. * @param green
  929. * @param blue
  930. * @returns {*}
  931. * @constructor
  932. */
  933. util.RGBToHSV = function RGBToHSV (red,green,blue) {
  934. red=red/255; green=green/255; blue=blue/255;
  935. var minRGB = Math.min(red,Math.min(green,blue));
  936. var maxRGB = Math.max(red,Math.max(green,blue));
  937. // Black-gray-white
  938. if (minRGB == maxRGB) {
  939. return {h:0,s:0,v:minRGB};
  940. }
  941. // Colors other than black-gray-white:
  942. var d = (red==minRGB) ? green-blue : ((blue==minRGB) ? red-green : blue-red);
  943. var h = (red==minRGB) ? 3 : ((blue==minRGB) ? 1 : 5);
  944. var hue = 60*(h - d/(maxRGB - minRGB))/360;
  945. var saturation = (maxRGB - minRGB)/maxRGB;
  946. var value = maxRGB;
  947. return {h:hue,s:saturation,v:value};
  948. };
  949. /**
  950. * https://gist.github.com/mjijackson/5311256
  951. * @param hue
  952. * @param saturation
  953. * @param value
  954. * @returns {{r: number, g: number, b: number}}
  955. * @constructor
  956. */
  957. util.HSVToRGB = function HSVToRGB(h, s, v) {
  958. var r, g, b;
  959. var i = Math.floor(h * 6);
  960. var f = h * 6 - i;
  961. var p = v * (1 - s);
  962. var q = v * (1 - f * s);
  963. var t = v * (1 - (1 - f) * s);
  964. switch (i % 6) {
  965. case 0: r = v, g = t, b = p; break;
  966. case 1: r = q, g = v, b = p; break;
  967. case 2: r = p, g = v, b = t; break;
  968. case 3: r = p, g = q, b = v; break;
  969. case 4: r = t, g = p, b = v; break;
  970. case 5: r = v, g = p, b = q; break;
  971. }
  972. return {r:Math.floor(r * 255), g:Math.floor(g * 255), b:Math.floor(b * 255) };
  973. };
  974. util.HSVToHex = function HSVToHex(h,s,v) {
  975. var rgb = util.HSVToRGB(h,s,v);
  976. return util.RGBToHex(rgb.r,rgb.g,rgb.b);
  977. }
  978. util.hexToHSV = function hexToHSV(hex) {
  979. var rgb = util.hexToRGB(hex);
  980. return util.RGBToHSV(rgb.r,rgb.g,rgb.b);
  981. }
  982. util.isValidHex = function isValidHex(hex) {
  983. var isOk = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(hex);
  984. return isOk;
  985. }
  986. /**
  987. * DataSet
  988. *
  989. * Usage:
  990. * var dataSet = new DataSet({
  991. * fieldId: '_id',
  992. * convert: {
  993. * // ...
  994. * }
  995. * });
  996. *
  997. * dataSet.add(item);
  998. * dataSet.add(data);
  999. * dataSet.update(item);
  1000. * dataSet.update(data);
  1001. * dataSet.remove(id);
  1002. * dataSet.remove(ids);
  1003. * var data = dataSet.get();
  1004. * var data = dataSet.get(id);
  1005. * var data = dataSet.get(ids);
  1006. * var data = dataSet.get(ids, options, data);
  1007. * dataSet.clear();
  1008. *
  1009. * A data set can:
  1010. * - add/remove/update data
  1011. * - gives triggers upon changes in the data
  1012. * - can import/export data in various data formats
  1013. *
  1014. * @param {Object} [options] Available options:
  1015. * {String} fieldId Field name of the id in the
  1016. * items, 'id' by default.
  1017. * {Object.<String, String} convert
  1018. * A map with field names as key,
  1019. * and the field type as value.
  1020. * @constructor DataSet
  1021. */
  1022. // TODO: add a DataSet constructor DataSet(data, options)
  1023. function DataSet (options) {
  1024. this.id = util.randomUUID();
  1025. this.options = options || {};
  1026. this.data = {}; // map with data indexed by id
  1027. this.fieldId = this.options.fieldId || 'id'; // name of the field containing id
  1028. this.convert = {}; // field types by field name
  1029. this.showInternalIds = this.options.showInternalIds || false; // show internal ids with the get function
  1030. if (this.options.convert) {
  1031. for (var field in this.options.convert) {
  1032. if (this.options.convert.hasOwnProperty(field)) {
  1033. var value = this.options.convert[field];
  1034. if (value == 'Date' || value == 'ISODate' || value == 'ASPDate') {
  1035. this.convert[field] = 'Date';
  1036. }
  1037. else {
  1038. this.convert[field] = value;
  1039. }
  1040. }
  1041. }
  1042. }
  1043. // event subscribers
  1044. this.subscribers = {};
  1045. this.internalIds = {}; // internally generated id's
  1046. }
  1047. /**
  1048. * Subscribe to an event, add an event listener
  1049. * @param {String} event Event name. Available events: 'put', 'update',
  1050. * 'remove'
  1051. * @param {function} callback Callback method. Called with three parameters:
  1052. * {String} event
  1053. * {Object | null} params
  1054. * {String | Number} senderId
  1055. */
  1056. DataSet.prototype.on = function on (event, callback) {
  1057. var subscribers = this.subscribers[event];
  1058. if (!subscribers) {
  1059. subscribers = [];
  1060. this.subscribers[event] = subscribers;
  1061. }
  1062. subscribers.push({
  1063. callback: callback
  1064. });
  1065. };
  1066. // TODO: make this function deprecated (replaced with `on` since version 0.5)
  1067. DataSet.prototype.subscribe = DataSet.prototype.on;
  1068. /**
  1069. * Unsubscribe from an event, remove an event listener
  1070. * @param {String} event
  1071. * @param {function} callback
  1072. */
  1073. DataSet.prototype.off = function off(event, callback) {
  1074. var subscribers = this.subscribers[event];
  1075. if (subscribers) {
  1076. this.subscribers[event] = subscribers.filter(function (listener) {
  1077. return (listener.callback != callback);
  1078. });
  1079. }
  1080. };
  1081. // TODO: make this function deprecated (replaced with `on` since version 0.5)
  1082. DataSet.prototype.unsubscribe = DataSet.prototype.off;
  1083. /**
  1084. * Trigger an event
  1085. * @param {String} event
  1086. * @param {Object | null} params
  1087. * @param {String} [senderId] Optional id of the sender.
  1088. * @private
  1089. */
  1090. DataSet.prototype._trigger = function (event, params, senderId) {
  1091. if (event == '*') {
  1092. throw new Error('Cannot trigger event *');
  1093. }
  1094. var subscribers = [];
  1095. if (event in this.subscribers) {
  1096. subscribers = subscribers.concat(this.subscribers[event]);
  1097. }
  1098. if ('*' in this.subscribers) {
  1099. subscribers = subscribers.concat(this.subscribers['*']);
  1100. }
  1101. for (var i = 0; i < subscribers.length; i++) {
  1102. var subscriber = subscribers[i];
  1103. if (subscriber.callback) {
  1104. subscriber.callback(event, params, senderId || null);
  1105. }
  1106. }
  1107. };
  1108. /**
  1109. * Add data.
  1110. * Adding an item will fail when there already is an item with the same id.
  1111. * @param {Object | Array | DataTable} data
  1112. * @param {String} [senderId] Optional sender id
  1113. * @return {Array} addedIds Array with the ids of the added items
  1114. */
  1115. DataSet.prototype.add = function (data, senderId) {
  1116. var addedIds = [],
  1117. id,
  1118. me = this;
  1119. if (data instanceof Array) {
  1120. // Array
  1121. for (var i = 0, len = data.length; i < len; i++) {
  1122. id = me._addItem(data[i]);
  1123. addedIds.push(id);
  1124. }
  1125. }
  1126. else if (util.isDataTable(data)) {
  1127. // Google DataTable
  1128. var columns = this._getColumnNames(data);
  1129. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1130. var item = {};
  1131. for (var col = 0, cols = columns.length; col < cols; col++) {
  1132. var field = columns[col];
  1133. item[field] = data.getValue(row, col);
  1134. }
  1135. id = me._addItem(item);
  1136. addedIds.push(id);
  1137. }
  1138. }
  1139. else if (data instanceof Object) {
  1140. // Single item
  1141. id = me._addItem(data);
  1142. addedIds.push(id);
  1143. }
  1144. else {
  1145. throw new Error('Unknown dataType');
  1146. }
  1147. if (addedIds.length) {
  1148. this._trigger('add', {items: addedIds}, senderId);
  1149. }
  1150. return addedIds;
  1151. };
  1152. /**
  1153. * Update existing items. When an item does not exist, it will be created
  1154. * @param {Object | Array | DataTable} data
  1155. * @param {String} [senderId] Optional sender id
  1156. * @return {Array} updatedIds The ids of the added or updated items
  1157. */
  1158. DataSet.prototype.update = function (data, senderId) {
  1159. var addedIds = [],
  1160. updatedIds = [],
  1161. me = this,
  1162. fieldId = me.fieldId;
  1163. var addOrUpdate = function (item) {
  1164. var id = item[fieldId];
  1165. if (me.data[id]) {
  1166. // update item
  1167. id = me._updateItem(item);
  1168. updatedIds.push(id);
  1169. }
  1170. else {
  1171. // add new item
  1172. id = me._addItem(item);
  1173. addedIds.push(id);
  1174. }
  1175. };
  1176. if (data instanceof Array) {
  1177. // Array
  1178. for (var i = 0, len = data.length; i < len; i++) {
  1179. addOrUpdate(data[i]);
  1180. }
  1181. }
  1182. else if (util.isDataTable(data)) {
  1183. // Google DataTable
  1184. var columns = this._getColumnNames(data);
  1185. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1186. var item = {};
  1187. for (var col = 0, cols = columns.length; col < cols; col++) {
  1188. var field = columns[col];
  1189. item[field] = data.getValue(row, col);
  1190. }
  1191. addOrUpdate(item);
  1192. }
  1193. }
  1194. else if (data instanceof Object) {
  1195. // Single item
  1196. addOrUpdate(data);
  1197. }
  1198. else {
  1199. throw new Error('Unknown dataType');
  1200. }
  1201. if (addedIds.length) {
  1202. this._trigger('add', {items: addedIds}, senderId);
  1203. }
  1204. if (updatedIds.length) {
  1205. this._trigger('update', {items: updatedIds}, senderId);
  1206. }
  1207. return addedIds.concat(updatedIds);
  1208. };
  1209. /**
  1210. * Get a data item or multiple items.
  1211. *
  1212. * Usage:
  1213. *
  1214. * get()
  1215. * get(options: Object)
  1216. * get(options: Object, data: Array | DataTable)
  1217. *
  1218. * get(id: Number | String)
  1219. * get(id: Number | String, options: Object)
  1220. * get(id: Number | String, options: Object, data: Array | DataTable)
  1221. *
  1222. * get(ids: Number[] | String[])
  1223. * get(ids: Number[] | String[], options: Object)
  1224. * get(ids: Number[] | String[], options: Object, data: Array | DataTable)
  1225. *
  1226. * Where:
  1227. *
  1228. * {Number | String} id The id of an item
  1229. * {Number[] | String{}} ids An array with ids of items
  1230. * {Object} options An Object with options. Available options:
  1231. * {String} [type] Type of data to be returned. Can
  1232. * be 'DataTable' or 'Array' (default)
  1233. * {Object.<String, String>} [convert]
  1234. * {String[]} [fields] field names to be returned
  1235. * {function} [filter] filter items
  1236. * {String | function} [order] Order the items by
  1237. * a field name or custom sort function.
  1238. * {Array | DataTable} [data] If provided, items will be appended to this
  1239. * array or table. Required in case of Google
  1240. * DataTable.
  1241. *
  1242. * @throws Error
  1243. */
  1244. DataSet.prototype.get = function (args) {
  1245. var me = this;
  1246. var globalShowInternalIds = this.showInternalIds;
  1247. // parse the arguments
  1248. var id, ids, options, data;
  1249. var firstType = util.getType(arguments[0]);
  1250. if (firstType == 'String' || firstType == 'Number') {
  1251. // get(id [, options] [, data])
  1252. id = arguments[0];
  1253. options = arguments[1];
  1254. data = arguments[2];
  1255. }
  1256. else if (firstType == 'Array') {
  1257. // get(ids [, options] [, data])
  1258. ids = arguments[0];
  1259. options = arguments[1];
  1260. data = arguments[2];
  1261. }
  1262. else {
  1263. // get([, options] [, data])
  1264. options = arguments[0];
  1265. data = arguments[1];
  1266. }
  1267. // determine the return type
  1268. var type;
  1269. if (options && options.type) {
  1270. type = (options.type == 'DataTable') ? 'DataTable' : 'Array';
  1271. if (data && (type != util.getType(data))) {
  1272. throw new Error('Type of parameter "data" (' + util.getType(data) + ') ' +
  1273. 'does not correspond with specified options.type (' + options.type + ')');
  1274. }
  1275. if (type == 'DataTable' && !util.isDataTable(data)) {
  1276. throw new Error('Parameter "data" must be a DataTable ' +
  1277. 'when options.type is "DataTable"');
  1278. }
  1279. }
  1280. else if (data) {
  1281. type = (util.getType(data) == 'DataTable') ? 'DataTable' : 'Array';
  1282. }
  1283. else {
  1284. type = 'Array';
  1285. }
  1286. // we allow the setting of this value for a single get request.
  1287. if (options != undefined) {
  1288. if (options.showInternalIds != undefined) {
  1289. this.showInternalIds = options.showInternalIds;
  1290. }
  1291. }
  1292. // build options
  1293. var convert = options && options.convert || this.options.convert;
  1294. var filter = options && options.filter;
  1295. var items = [], item, itemId, i, len;
  1296. // convert items
  1297. if (id != undefined) {
  1298. // return a single item
  1299. item = me._getItem(id, convert);
  1300. if (filter && !filter(item)) {
  1301. item = null;
  1302. }
  1303. }
  1304. else if (ids != undefined) {
  1305. // return a subset of items
  1306. for (i = 0, len = ids.length; i < len; i++) {
  1307. item = me._getItem(ids[i], convert);
  1308. if (!filter || filter(item)) {
  1309. items.push(item);
  1310. }
  1311. }
  1312. }
  1313. else {
  1314. // return all items
  1315. for (itemId in this.data) {
  1316. if (this.data.hasOwnProperty(itemId)) {
  1317. item = me._getItem(itemId, convert);
  1318. if (!filter || filter(item)) {
  1319. items.push(item);
  1320. }
  1321. }
  1322. }
  1323. }
  1324. // restore the global value of showInternalIds
  1325. this.showInternalIds = globalShowInternalIds;
  1326. // order the results
  1327. if (options && options.order && id == undefined) {
  1328. this._sort(items, options.order);
  1329. }
  1330. // filter fields of the items
  1331. if (options && options.fields) {
  1332. var fields = options.fields;
  1333. if (id != undefined) {
  1334. item = this._filterFields(item, fields);
  1335. }
  1336. else {
  1337. for (i = 0, len = items.length; i < len; i++) {
  1338. items[i] = this._filterFields(items[i], fields);
  1339. }
  1340. }
  1341. }
  1342. // return the results
  1343. if (type == 'DataTable') {
  1344. var columns = this._getColumnNames(data);
  1345. if (id != undefined) {
  1346. // append a single item to the data table
  1347. me._appendRow(data, columns, item);
  1348. }
  1349. else {
  1350. // copy the items to the provided data table
  1351. for (i = 0, len = items.length; i < len; i++) {
  1352. me._appendRow(data, columns, items[i]);
  1353. }
  1354. }
  1355. return data;
  1356. }
  1357. else {
  1358. // return an array
  1359. if (id != undefined) {
  1360. // a single item
  1361. return item;
  1362. }
  1363. else {
  1364. // multiple items
  1365. if (data) {
  1366. // copy the items to the provided array
  1367. for (i = 0, len = items.length; i < len; i++) {
  1368. data.push(items[i]);
  1369. }
  1370. return data;
  1371. }
  1372. else {
  1373. // just return our array
  1374. return items;
  1375. }
  1376. }
  1377. }
  1378. };
  1379. /**
  1380. * Get ids of all items or from a filtered set of items.
  1381. * @param {Object} [options] An Object with options. Available options:
  1382. * {function} [filter] filter items
  1383. * {String | function} [order] Order the items by
  1384. * a field name or custom sort function.
  1385. * @return {Array} ids
  1386. */
  1387. DataSet.prototype.getIds = function (options) {
  1388. var data = this.data,
  1389. filter = options && options.filter,
  1390. order = options && options.order,
  1391. convert = options && options.convert || this.options.convert,
  1392. i,
  1393. len,
  1394. id,
  1395. item,
  1396. items,
  1397. ids = [];
  1398. if (filter) {
  1399. // get filtered items
  1400. if (order) {
  1401. // create ordered list
  1402. items = [];
  1403. for (id in data) {
  1404. if (data.hasOwnProperty(id)) {
  1405. item = this._getItem(id, convert);
  1406. if (filter(item)) {
  1407. items.push(item);
  1408. }
  1409. }
  1410. }
  1411. this._sort(items, order);
  1412. for (i = 0, len = items.length; i < len; i++) {
  1413. ids[i] = items[i][this.fieldId];
  1414. }
  1415. }
  1416. else {
  1417. // create unordered list
  1418. for (id in data) {
  1419. if (data.hasOwnProperty(id)) {
  1420. item = this._getItem(id, convert);
  1421. if (filter(item)) {
  1422. ids.push(item[this.fieldId]);
  1423. }
  1424. }
  1425. }
  1426. }
  1427. }
  1428. else {
  1429. // get all items
  1430. if (order) {
  1431. // create an ordered list
  1432. items = [];
  1433. for (id in data) {
  1434. if (data.hasOwnProperty(id)) {
  1435. items.push(data[id]);
  1436. }
  1437. }
  1438. this._sort(items, order);
  1439. for (i = 0, len = items.length; i < len; i++) {
  1440. ids[i] = items[i][this.fieldId];
  1441. }
  1442. }
  1443. else {
  1444. // create unordered list
  1445. for (id in data) {
  1446. if (data.hasOwnProperty(id)) {
  1447. item = data[id];
  1448. ids.push(item[this.fieldId]);
  1449. }
  1450. }
  1451. }
  1452. }
  1453. return ids;
  1454. };
  1455. /**
  1456. * Execute a callback function for every item in the dataset.
  1457. * The order of the items is not determined.
  1458. * @param {function} callback
  1459. * @param {Object} [options] Available options:
  1460. * {Object.<String, String>} [convert]
  1461. * {String[]} [fields] filter fields
  1462. * {function} [filter] filter items
  1463. * {String | function} [order] Order the items by
  1464. * a field name or custom sort function.
  1465. */
  1466. DataSet.prototype.forEach = function (callback, options) {
  1467. var filter = options && options.filter,
  1468. convert = options && options.convert || this.options.convert,
  1469. data = this.data,
  1470. item,
  1471. id;
  1472. if (options && options.order) {
  1473. // execute forEach on ordered list
  1474. var items = this.get(options);
  1475. for (var i = 0, len = items.length; i < len; i++) {
  1476. item = items[i];
  1477. id = item[this.fieldId];
  1478. callback(item, id);
  1479. }
  1480. }
  1481. else {
  1482. // unordered
  1483. for (id in data) {
  1484. if (data.hasOwnProperty(id)) {
  1485. item = this._getItem(id, convert);
  1486. if (!filter || filter(item)) {
  1487. callback(item, id);
  1488. }
  1489. }
  1490. }
  1491. }
  1492. };
  1493. /**
  1494. * Map every item in the dataset.
  1495. * @param {function} callback
  1496. * @param {Object} [options] Available options:
  1497. * {Object.<String, String>} [convert]
  1498. * {String[]} [fields] filter fields
  1499. * {function} [filter] filter items
  1500. * {String | function} [order] Order the items by
  1501. * a field name or custom sort function.
  1502. * @return {Object[]} mappedItems
  1503. */
  1504. DataSet.prototype.map = function (callback, options) {
  1505. var filter = options && options.filter,
  1506. convert = options && options.convert || this.options.convert,
  1507. mappedItems = [],
  1508. data = this.data,
  1509. item;
  1510. // convert and filter items
  1511. for (var id in data) {
  1512. if (data.hasOwnProperty(id)) {
  1513. item = this._getItem(id, convert);
  1514. if (!filter || filter(item)) {
  1515. mappedItems.push(callback(item, id));
  1516. }
  1517. }
  1518. }
  1519. // order items
  1520. if (options && options.order) {
  1521. this._sort(mappedItems, options.order);
  1522. }
  1523. return mappedItems;
  1524. };
  1525. /**
  1526. * Filter the fields of an item
  1527. * @param {Object} item
  1528. * @param {String[]} fields Field names
  1529. * @return {Object} filteredItem
  1530. * @private
  1531. */
  1532. DataSet.prototype._filterFields = function (item, fields) {
  1533. var filteredItem = {};
  1534. for (var field in item) {
  1535. if (item.hasOwnProperty(field) && (fields.indexOf(field) != -1)) {
  1536. filteredItem[field] = item[field];
  1537. }
  1538. }
  1539. return filteredItem;
  1540. };
  1541. /**
  1542. * Sort the provided array with items
  1543. * @param {Object[]} items
  1544. * @param {String | function} order A field name or custom sort function.
  1545. * @private
  1546. */
  1547. DataSet.prototype._sort = function (items, order) {
  1548. if (util.isString(order)) {
  1549. // order by provided field name
  1550. var name = order; // field name
  1551. items.sort(function (a, b) {
  1552. var av = a[name];
  1553. var bv = b[name];
  1554. return (av > bv) ? 1 : ((av < bv) ? -1 : 0);
  1555. });
  1556. }
  1557. else if (typeof order === 'function') {
  1558. // order by sort function
  1559. items.sort(order);
  1560. }
  1561. // TODO: extend order by an Object {field:String, direction:String}
  1562. // where direction can be 'asc' or 'desc'
  1563. else {
  1564. throw new TypeError('Order must be a function or a string');
  1565. }
  1566. };
  1567. /**
  1568. * Remove an object by pointer or by id
  1569. * @param {String | Number | Object | Array} id Object or id, or an array with
  1570. * objects or ids to be removed
  1571. * @param {String} [senderId] Optional sender id
  1572. * @return {Array} removedIds
  1573. */
  1574. DataSet.prototype.remove = function (id, senderId) {
  1575. var removedIds = [],
  1576. i, len, removedId;
  1577. if (id instanceof Array) {
  1578. for (i = 0, len = id.length; i < len; i++) {
  1579. removedId = this._remove(id[i]);
  1580. if (removedId != null) {
  1581. removedIds.push(removedId);
  1582. }
  1583. }
  1584. }
  1585. else {
  1586. removedId = this._remove(id);
  1587. if (removedId != null) {
  1588. removedIds.push(removedId);
  1589. }
  1590. }
  1591. if (removedIds.length) {
  1592. this._trigger('remove', {items: removedIds}, senderId);
  1593. }
  1594. return removedIds;
  1595. };
  1596. /**
  1597. * Remove an item by its id
  1598. * @param {Number | String | Object} id id or item
  1599. * @returns {Number | String | null} id
  1600. * @private
  1601. */
  1602. DataSet.prototype._remove = function (id) {
  1603. if (util.isNumber(id) || util.isString(id)) {
  1604. if (this.data[id]) {
  1605. delete this.data[id];
  1606. delete this.internalIds[id];
  1607. return id;
  1608. }
  1609. }
  1610. else if (id instanceof Object) {
  1611. var itemId = id[this.fieldId];
  1612. if (itemId && this.data[itemId]) {
  1613. delete this.data[itemId];
  1614. delete this.internalIds[itemId];
  1615. return itemId;
  1616. }
  1617. }
  1618. return null;
  1619. };
  1620. /**
  1621. * Clear the data
  1622. * @param {String} [senderId] Optional sender id
  1623. * @return {Array} removedIds The ids of all removed items
  1624. */
  1625. DataSet.prototype.clear = function (senderId) {
  1626. var ids = Object.keys(this.data);
  1627. this.data = {};
  1628. this.internalIds = {};
  1629. this._trigger('remove', {items: ids}, senderId);
  1630. return ids;
  1631. };
  1632. /**
  1633. * Find the item with maximum value of a specified field
  1634. * @param {String} field
  1635. * @return {Object | null} item Item containing max value, or null if no items
  1636. */
  1637. DataSet.prototype.max = function (field) {
  1638. var data = this.data,
  1639. max = null,
  1640. maxField = null;
  1641. for (var id in data) {
  1642. if (data.hasOwnProperty(id)) {
  1643. var item = data[id];
  1644. var itemField = item[field];
  1645. if (itemField != null && (!max || itemField > maxField)) {
  1646. max = item;
  1647. maxField = itemField;
  1648. }
  1649. }
  1650. }
  1651. return max;
  1652. };
  1653. /**
  1654. * Find the item with minimum value of a specified field
  1655. * @param {String} field
  1656. * @return {Object | null} item Item containing max value, or null if no items
  1657. */
  1658. DataSet.prototype.min = function (field) {
  1659. var data = this.data,
  1660. min = null,
  1661. minField = null;
  1662. for (var id in data) {
  1663. if (data.hasOwnProperty(id)) {
  1664. var item = data[id];
  1665. var itemField = item[field];
  1666. if (itemField != null && (!min || itemField < minField)) {
  1667. min = item;
  1668. minField = itemField;
  1669. }
  1670. }
  1671. }
  1672. return min;
  1673. };
  1674. /**
  1675. * Find all distinct values of a specified field
  1676. * @param {String} field
  1677. * @return {Array} values Array containing all distinct values. If the data
  1678. * items do not contain the specified field, an array
  1679. * containing a single value undefined is returned.
  1680. * The returned array is unordered.
  1681. */
  1682. DataSet.prototype.distinct = function (field) {
  1683. var data = this.data,
  1684. values = [],
  1685. fieldType = this.options.convert[field],
  1686. count = 0;
  1687. for (var prop in data) {
  1688. if (data.hasOwnProperty(prop)) {
  1689. var item = data[prop];
  1690. var value = util.convert(item[field], fieldType);
  1691. var exists = false;
  1692. for (var i = 0; i < count; i++) {
  1693. if (values[i] == value) {
  1694. exists = true;
  1695. break;
  1696. }
  1697. }
  1698. if (!exists) {
  1699. values[count] = value;
  1700. count++;
  1701. }
  1702. }
  1703. }
  1704. return values;
  1705. };
  1706. /**
  1707. * Add a single item. Will fail when an item with the same id already exists.
  1708. * @param {Object} item
  1709. * @return {String} id
  1710. * @private
  1711. */
  1712. DataSet.prototype._addItem = function (item) {
  1713. var id = item[this.fieldId];
  1714. if (id != undefined) {
  1715. // check whether this id is already taken
  1716. if (this.data[id]) {
  1717. // item already exists
  1718. throw new Error('Cannot add item: item with id ' + id + ' already exists');
  1719. }
  1720. }
  1721. else {
  1722. // generate an id
  1723. id = util.randomUUID();
  1724. item[this.fieldId] = id;
  1725. this.internalIds[id] = item;
  1726. }
  1727. var d = {};
  1728. for (var field in item) {
  1729. if (item.hasOwnProperty(field)) {
  1730. var fieldType = this.convert[field]; // type may be undefined
  1731. d[field] = util.convert(item[field], fieldType);
  1732. }
  1733. }
  1734. this.data[id] = d;
  1735. return id;
  1736. };
  1737. /**
  1738. * Get an item. Fields can be converted to a specific type
  1739. * @param {String} id
  1740. * @param {Object.<String, String>} [convert] field types to convert
  1741. * @return {Object | null} item
  1742. * @private
  1743. */
  1744. DataSet.prototype._getItem = function (id, convert) {
  1745. var field, value;
  1746. // get the item from the dataset
  1747. var raw = this.data[id];
  1748. if (!raw) {
  1749. return null;
  1750. }
  1751. // convert the items field types
  1752. var converted = {},
  1753. fieldId = this.fieldId,
  1754. internalIds = this.internalIds;
  1755. if (convert) {
  1756. for (field in raw) {
  1757. if (raw.hasOwnProperty(field)) {
  1758. value = raw[field];
  1759. // output all fields, except internal ids
  1760. if ((field != fieldId) || (!(value in internalIds) || this.showInternalIds)) {
  1761. converted[field] = util.convert(value, convert[field]);
  1762. }
  1763. }
  1764. }
  1765. }
  1766. else {
  1767. // no field types specified, no converting needed
  1768. for (field in raw) {
  1769. if (raw.hasOwnProperty(field)) {
  1770. value = raw[field];
  1771. // output all fields, except internal ids
  1772. if ((field != fieldId) || (!(value in internalIds) || this.showInternalIds)) {
  1773. converted[field] = value;
  1774. }
  1775. }
  1776. }
  1777. }
  1778. return converted;
  1779. };
  1780. /**
  1781. * Update a single item: merge with existing item.
  1782. * Will fail when the item has no id, or when there does not exist an item
  1783. * with the same id.
  1784. * @param {Object} item
  1785. * @return {String} id
  1786. * @private
  1787. */
  1788. DataSet.prototype._updateItem = function (item) {
  1789. var id = item[this.fieldId];
  1790. if (id == undefined) {
  1791. throw new Error('Cannot update item: item has no id (item: ' + JSON.stringify(item) + ')');
  1792. }
  1793. var d = this.data[id];
  1794. if (!d) {
  1795. // item doesn't exist
  1796. throw new Error('Cannot update item: no item with id ' + id + ' found');
  1797. }
  1798. // merge with current item
  1799. for (var field in item) {
  1800. if (item.hasOwnProperty(field)) {
  1801. var fieldType = this.convert[field]; // type may be undefined
  1802. d[field] = util.convert(item[field], fieldType);
  1803. }
  1804. }
  1805. return id;
  1806. };
  1807. /**
  1808. * check if an id is an internal or external id
  1809. * @param id
  1810. * @returns {boolean}
  1811. * @private
  1812. */
  1813. DataSet.prototype.isInternalId = function(id) {
  1814. return (id in this.internalIds);
  1815. };
  1816. /**
  1817. * Get an array with the column names of a Google DataTable
  1818. * @param {DataTable} dataTable
  1819. * @return {String[]} columnNames
  1820. * @private
  1821. */
  1822. DataSet.prototype._getColumnNames = function (dataTable) {
  1823. var columns = [];
  1824. for (var col = 0, cols = dataTable.getNumberOfColumns(); col < cols; col++) {
  1825. columns[col] = dataTable.getColumnId(col) || dataTable.getColumnLabel(col);
  1826. }
  1827. return columns;
  1828. };
  1829. /**
  1830. * Append an item as a row to the dataTable
  1831. * @param dataTable
  1832. * @param columns
  1833. * @param item
  1834. * @private
  1835. */
  1836. DataSet.prototype._appendRow = function (dataTable, columns, item) {
  1837. var row = dataTable.addRow();
  1838. for (var col = 0, cols = columns.length; col < cols; col++) {
  1839. var field = columns[col];
  1840. dataTable.setValue(row, col, item[field]);
  1841. }
  1842. };
  1843. /**
  1844. * DataView
  1845. *
  1846. * a dataview offers a filtered view on a dataset or an other dataview.
  1847. *
  1848. * @param {DataSet | DataView} data
  1849. * @param {Object} [options] Available options: see method get
  1850. *
  1851. * @constructor DataView
  1852. */
  1853. function DataView (data, options) {
  1854. this.id = util.randomUUID();
  1855. this.data = null;
  1856. this.ids = {}; // ids of the items currently in memory (just contains a boolean true)
  1857. this.options = options || {};
  1858. this.fieldId = 'id'; // name of the field containing id
  1859. this.subscribers = {}; // event subscribers
  1860. var me = this;
  1861. this.listener = function () {
  1862. me._onEvent.apply(me, arguments);
  1863. };
  1864. this.setData(data);
  1865. }
  1866. // TODO: implement a function .config() to dynamically update things like configured filter
  1867. // and trigger changes accordingly
  1868. /**
  1869. * Set a data source for the view
  1870. * @param {DataSet | DataView} data
  1871. */
  1872. DataView.prototype.setData = function (data) {
  1873. var ids, dataItems, i, len;
  1874. if (this.data) {
  1875. // unsubscribe from current dataset
  1876. if (this.data.unsubscribe) {
  1877. this.data.unsubscribe('*', this.listener);
  1878. }
  1879. // trigger a remove of all items in memory
  1880. ids = [];
  1881. for (var id in this.ids) {
  1882. if (this.ids.hasOwnProperty(id)) {
  1883. ids.push(id);
  1884. }
  1885. }
  1886. this.ids = {};
  1887. this._trigger('remove', {items: ids});
  1888. }
  1889. this.data = data;
  1890. if (this.data) {
  1891. // update fieldId
  1892. this.fieldId = this.options.fieldId ||
  1893. (this.data && this.data.options && this.data.options.fieldId) ||
  1894. 'id';
  1895. // trigger an add of all added items
  1896. ids = this.data.getIds({filter: this.options && this.options.filter});
  1897. for (i = 0, len = ids.length; i < len; i++) {
  1898. id = ids[i];
  1899. this.ids[id] = true;
  1900. }
  1901. this._trigger('add', {items: ids});
  1902. // subscribe to new dataset
  1903. if (this.data.on) {
  1904. this.data.on('*', this.listener);
  1905. }
  1906. }
  1907. };
  1908. /**
  1909. * Get data from the data view
  1910. *
  1911. * Usage:
  1912. *
  1913. * get()
  1914. * get(options: Object)
  1915. * get(options: Object, data: Array | DataTable)
  1916. *
  1917. * get(id: Number)
  1918. * get(id: Number, options: Object)
  1919. * get(id: Number, options: Object, data: Array | DataTable)
  1920. *
  1921. * get(ids: Number[])
  1922. * get(ids: Number[], options: Object)
  1923. * get(ids: Number[], options: Object, data: Array | DataTable)
  1924. *
  1925. * Where:
  1926. *
  1927. * {Number | String} id The id of an item
  1928. * {Number[] | String{}} ids An array with ids of items
  1929. * {Object} options An Object with options. Available options:
  1930. * {String} [type] Type of data to be returned. Can
  1931. * be 'DataTable' or 'Array' (default)
  1932. * {Object.<String, String>} [convert]
  1933. * {String[]} [fields] field names to be returned
  1934. * {function} [filter] filter items
  1935. * {String | function} [order] Order the items by
  1936. * a field name or custom sort function.
  1937. * {Array | DataTable} [data] If provided, items will be appended to this
  1938. * array or table. Required in case of Google
  1939. * DataTable.
  1940. * @param args
  1941. */
  1942. DataView.prototype.get = function (args) {
  1943. var me = this;
  1944. // parse the arguments
  1945. var ids, options, data;
  1946. var firstType = util.getType(arguments[0]);
  1947. if (firstType == 'String' || firstType == 'Number' || firstType == 'Array') {
  1948. // get(id(s) [, options] [, data])
  1949. ids = arguments[0]; // can be a single id or an array with ids
  1950. options = arguments[1];
  1951. data = arguments[2];
  1952. }
  1953. else {
  1954. // get([, options] [, data])
  1955. options = arguments[0];
  1956. data = arguments[1];
  1957. }
  1958. // extend the options with the default options and provided options
  1959. var viewOptions = util.extend({}, this.options, options);
  1960. // create a combined filter method when needed
  1961. if (this.options.filter && options && options.filter) {
  1962. viewOptions.filter = function (item) {
  1963. return me.options.filter(item) && options.filter(item);
  1964. }
  1965. }
  1966. // build up the call to the linked data set
  1967. var getArguments = [];
  1968. if (ids != undefined) {
  1969. getArguments.push(ids);
  1970. }
  1971. getArguments.push(viewOptions);
  1972. getArguments.push(data);
  1973. return this.data && this.data.get.apply(this.data, getArguments);
  1974. };
  1975. /**
  1976. * Get ids of all items or from a filtered set of items.
  1977. * @param {Object} [options] An Object with options. Available options:
  1978. * {function} [filter] filter items
  1979. * {String | function} [order] Order the items by
  1980. * a field name or custom sort function.
  1981. * @return {Array} ids
  1982. */
  1983. DataView.prototype.getIds = function (options) {
  1984. var ids;
  1985. if (this.data) {
  1986. var defaultFilter = this.options.filter;
  1987. var filter;
  1988. if (options && options.filter) {
  1989. if (defaultFilter) {
  1990. filter = function (item) {
  1991. return defaultFilter(item) && options.filter(item);
  1992. }
  1993. }
  1994. else {
  1995. filter = options.filter;
  1996. }
  1997. }
  1998. else {
  1999. filter = defaultFilter;
  2000. }
  2001. ids = this.data.getIds({
  2002. filter: filter,
  2003. order: options && options.order
  2004. });
  2005. }
  2006. else {
  2007. ids = [];
  2008. }
  2009. return ids;
  2010. };
  2011. /**
  2012. * Event listener. Will propagate all events from the connected data set to
  2013. * the subscribers of the DataView, but will filter the items and only trigger
  2014. * when there are changes in the filtered data set.
  2015. * @param {String} event
  2016. * @param {Object | null} params
  2017. * @param {String} senderId
  2018. * @private
  2019. */
  2020. DataView.prototype._onEvent = function (event, params, senderId) {
  2021. var i, len, id, item,
  2022. ids = params && params.items,
  2023. data = this.data,
  2024. added = [],
  2025. updated = [],
  2026. removed = [];
  2027. if (ids && data) {
  2028. switch (event) {
  2029. case 'add':
  2030. // filter the ids of the added items
  2031. for (i = 0, len = ids.length; i < len; i++) {
  2032. id = ids[i];
  2033. item = this.get(id);
  2034. if (item) {
  2035. this.ids[id] = true;
  2036. added.push(id);
  2037. }
  2038. }
  2039. break;
  2040. case 'update':
  2041. // determine the event from the views viewpoint: an updated
  2042. // item can be added, updated, or removed from this view.
  2043. for (i = 0, len = ids.length; i < len; i++) {
  2044. id = ids[i];
  2045. item = this.get(id);
  2046. if (item) {
  2047. if (this.ids[id]) {
  2048. updated.push(id);
  2049. }
  2050. else {
  2051. this.ids[id] = true;
  2052. added.push(id);
  2053. }
  2054. }
  2055. else {
  2056. if (this.ids[id]) {
  2057. delete this.ids[id];
  2058. removed.push(id);
  2059. }
  2060. else {
  2061. // nothing interesting for me :-(
  2062. }
  2063. }
  2064. }
  2065. break;
  2066. case 'remove':
  2067. // filter the ids of the removed items
  2068. for (i = 0, len = ids.length; i < len; i++) {
  2069. id = ids[i];
  2070. if (this.ids[id]) {
  2071. delete this.ids[id];
  2072. removed.push(id);
  2073. }
  2074. }
  2075. break;
  2076. }
  2077. if (added.length) {
  2078. this._trigger('add', {items: added}, senderId);
  2079. }
  2080. if (updated.length) {
  2081. this._trigger('update', {items: updated}, senderId);
  2082. }
  2083. if (removed.length) {
  2084. this._trigger('remove', {items: removed}, senderId);
  2085. }
  2086. }
  2087. };
  2088. // copy subscription functionality from DataSet
  2089. DataView.prototype.on = DataSet.prototype.on;
  2090. DataView.prototype.off = DataSet.prototype.off;
  2091. DataView.prototype._trigger = DataSet.prototype._trigger;
  2092. // TODO: make these functions deprecated (replaced with `on` and `off` since version 0.5)
  2093. DataView.prototype.subscribe = DataView.prototype.on;
  2094. DataView.prototype.unsubscribe = DataView.prototype.off;
  2095. /**
  2096. * @constructor TimeStep
  2097. * The class TimeStep is an iterator for dates. You provide a start date and an
  2098. * end date. The class itself determines the best scale (step size) based on the
  2099. * provided start Date, end Date, and minimumStep.
  2100. *
  2101. * If minimumStep is provided, the step size is chosen as close as possible
  2102. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2103. * provided, the scale is set to 1 DAY.
  2104. * The minimumStep should correspond with the onscreen size of about 6 characters
  2105. *
  2106. * Alternatively, you can set a scale by hand.
  2107. * After creation, you can initialize the class by executing first(). Then you
  2108. * can iterate from the start date to the end date via next(). You can check if
  2109. * the end date is reached with the function hasNext(). After each step, you can
  2110. * retrieve the current date via getCurrent().
  2111. * The TimeStep has scales ranging from milliseconds, seconds, minutes, hours,
  2112. * days, to years.
  2113. *
  2114. * Version: 1.2
  2115. *
  2116. * @param {Date} [start] The start date, for example new Date(2010, 9, 21)
  2117. * or new Date(2010, 9, 21, 23, 45, 00)
  2118. * @param {Date} [end] The end date
  2119. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  2120. */
  2121. TimeStep = function(start, end, minimumStep) {
  2122. // variables
  2123. this.current = new Date();
  2124. this._start = new Date();
  2125. this._end = new Date();
  2126. this.autoScale = true;
  2127. this.scale = TimeStep.SCALE.DAY;
  2128. this.step = 1;
  2129. // initialize the range
  2130. this.setRange(start, end, minimumStep);
  2131. };
  2132. /// enum scale
  2133. TimeStep.SCALE = {
  2134. MILLISECOND: 1,
  2135. SECOND: 2,
  2136. MINUTE: 3,
  2137. HOUR: 4,
  2138. DAY: 5,
  2139. WEEKDAY: 6,
  2140. MONTH: 7,
  2141. YEAR: 8
  2142. };
  2143. /**
  2144. * Set a new range
  2145. * If minimumStep is provided, the step size is chosen as close as possible
  2146. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2147. * provided, the scale is set to 1 DAY.
  2148. * The minimumStep should correspond with the onscreen size of about 6 characters
  2149. * @param {Date} [start] The start date and time.
  2150. * @param {Date} [end] The end date and time.
  2151. * @param {int} [minimumStep] Optional. Minimum step size in milliseconds
  2152. */
  2153. TimeStep.prototype.setRange = function(start, end, minimumStep) {
  2154. if (!(start instanceof Date) || !(end instanceof Date)) {
  2155. throw "No legal start or end date in method setRange";
  2156. }
  2157. this._start = (start != undefined) ? new Date(start.valueOf()) : new Date();
  2158. this._end = (end != undefined) ? new Date(end.valueOf()) : new Date();
  2159. if (this.autoScale) {
  2160. this.setMinimumStep(minimumStep);
  2161. }
  2162. };
  2163. /**
  2164. * Set the range iterator to the start date.
  2165. */
  2166. TimeStep.prototype.first = function() {
  2167. this.current = new Date(this._start.valueOf());
  2168. this.roundToMinor();
  2169. };
  2170. /**
  2171. * Round the current date to the first minor date value
  2172. * This must be executed once when the current date is set to start Date
  2173. */
  2174. TimeStep.prototype.roundToMinor = function() {
  2175. // round to floor
  2176. // IMPORTANT: we have no breaks in this switch! (this is no bug)
  2177. //noinspection FallthroughInSwitchStatementJS
  2178. switch (this.scale) {
  2179. case TimeStep.SCALE.YEAR:
  2180. this.current.setFullYear(this.step * Math.floor(this.current.getFullYear() / this.step));
  2181. this.current.setMonth(0);
  2182. case TimeStep.SCALE.MONTH: this.current.setDate(1);
  2183. case TimeStep.SCALE.DAY: // intentional fall through
  2184. case TimeStep.SCALE.WEEKDAY: this.current.setHours(0);
  2185. case TimeStep.SCALE.HOUR: this.current.setMinutes(0);
  2186. case TimeStep.SCALE.MINUTE: this.current.setSeconds(0);
  2187. case TimeStep.SCALE.SECOND: this.current.setMilliseconds(0);
  2188. //case TimeStep.SCALE.MILLISECOND: // nothing to do for milliseconds
  2189. }
  2190. if (this.step != 1) {
  2191. // round down to the first minor value that is a multiple of the current step size
  2192. switch (this.scale) {
  2193. case TimeStep.SCALE.MILLISECOND: this.current.setMilliseconds(this.current.getMilliseconds() - this.current.getMilliseconds() % this.step); break;
  2194. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() - this.current.getSeconds() % this.step); break;
  2195. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() - this.current.getMinutes() % this.step); break;
  2196. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() - this.current.getHours() % this.step); break;
  2197. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2198. case TimeStep.SCALE.DAY: this.current.setDate((this.current.getDate()-1) - (this.current.getDate()-1) % this.step + 1); break;
  2199. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() - this.current.getMonth() % this.step); break;
  2200. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() - this.current.getFullYear() % this.step); break;
  2201. default: break;
  2202. }
  2203. }
  2204. };
  2205. /**
  2206. * Check if the there is a next step
  2207. * @return {boolean} true if the current date has not passed the end date
  2208. */
  2209. TimeStep.prototype.hasNext = function () {
  2210. return (this.current.valueOf() <= this._end.valueOf());
  2211. };
  2212. /**
  2213. * Do the next step
  2214. */
  2215. TimeStep.prototype.next = function() {
  2216. var prev = this.current.valueOf();
  2217. // Two cases, needed to prevent issues with switching daylight savings
  2218. // (end of March and end of October)
  2219. if (this.current.getMonth() < 6) {
  2220. switch (this.scale) {
  2221. case TimeStep.SCALE.MILLISECOND:
  2222. this.current = new Date(this.current.valueOf() + this.step); break;
  2223. case TimeStep.SCALE.SECOND: this.current = new Date(this.current.valueOf() + this.step * 1000); break;
  2224. case TimeStep.SCALE.MINUTE: this.current = new Date(this.current.valueOf() + this.step * 1000 * 60); break;
  2225. case TimeStep.SCALE.HOUR:
  2226. this.current = new Date(this.current.valueOf() + this.step * 1000 * 60 * 60);
  2227. // in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...)
  2228. var h = this.current.getHours();
  2229. this.current.setHours(h - (h % this.step));
  2230. break;
  2231. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2232. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2233. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2234. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2235. default: break;
  2236. }
  2237. }
  2238. else {
  2239. switch (this.scale) {
  2240. case TimeStep.SCALE.MILLISECOND: this.current = new Date(this.current.valueOf() + this.step); break;
  2241. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() + this.step); break;
  2242. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() + this.step); break;
  2243. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() + this.step); break;
  2244. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2245. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2246. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2247. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2248. default: break;
  2249. }
  2250. }
  2251. if (this.step != 1) {
  2252. // round down to the correct major value
  2253. switch (this.scale) {
  2254. case TimeStep.SCALE.MILLISECOND: if(this.current.getMilliseconds() < this.step) this.current.setMilliseconds(0); break;
  2255. case TimeStep.SCALE.SECOND: if(this.current.getSeconds() < this.step) this.current.setSeconds(0); break;
  2256. case TimeStep.SCALE.MINUTE: if(this.current.getMinutes() < this.step) this.current.setMinutes(0); break;
  2257. case TimeStep.SCALE.HOUR: if(this.current.getHours() < this.step) this.current.setHours(0); break;
  2258. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2259. case TimeStep.SCALE.DAY: if(this.current.getDate() < this.step+1) this.current.setDate(1); break;
  2260. case TimeStep.SCALE.MONTH: if(this.current.getMonth() < this.step) this.current.setMonth(0); break;
  2261. case TimeStep.SCALE.YEAR: break; // nothing to do for year
  2262. default: break;
  2263. }
  2264. }
  2265. // safety mechanism: if current time is still unchanged, move to the end
  2266. if (this.current.valueOf() == prev) {
  2267. this.current = new Date(this._end.valueOf());
  2268. }
  2269. };
  2270. /**
  2271. * Get the current datetime
  2272. * @return {Date} current The current date
  2273. */
  2274. TimeStep.prototype.getCurrent = function() {
  2275. return this.current;
  2276. };
  2277. /**
  2278. * Set a custom scale. Autoscaling will be disabled.
  2279. * For example setScale(SCALE.MINUTES, 5) will result
  2280. * in minor steps of 5 minutes, and major steps of an hour.
  2281. *
  2282. * @param {TimeStep.SCALE} newScale
  2283. * A scale. Choose from SCALE.MILLISECOND,
  2284. * SCALE.SECOND, SCALE.MINUTE, SCALE.HOUR,
  2285. * SCALE.WEEKDAY, SCALE.DAY, SCALE.MONTH,
  2286. * SCALE.YEAR.
  2287. * @param {Number} newStep A step size, by default 1. Choose for
  2288. * example 1, 2, 5, or 10.
  2289. */
  2290. TimeStep.prototype.setScale = function(newScale, newStep) {
  2291. this.scale = newScale;
  2292. if (newStep > 0) {
  2293. this.step = newStep;
  2294. }
  2295. this.autoScale = false;
  2296. };
  2297. /**
  2298. * Enable or disable autoscaling
  2299. * @param {boolean} enable If true, autoascaling is set true
  2300. */
  2301. TimeStep.prototype.setAutoScale = function (enable) {
  2302. this.autoScale = enable;
  2303. };
  2304. /**
  2305. * Automatically determine the scale that bests fits the provided minimum step
  2306. * @param {Number} [minimumStep] The minimum step size in milliseconds
  2307. */
  2308. TimeStep.prototype.setMinimumStep = function(minimumStep) {
  2309. if (minimumStep == undefined) {
  2310. return;
  2311. }
  2312. var stepYear = (1000 * 60 * 60 * 24 * 30 * 12);
  2313. var stepMonth = (1000 * 60 * 60 * 24 * 30);
  2314. var stepDay = (1000 * 60 * 60 * 24);
  2315. var stepHour = (1000 * 60 * 60);
  2316. var stepMinute = (1000 * 60);
  2317. var stepSecond = (1000);
  2318. var stepMillisecond= (1);
  2319. // find the smallest step that is larger than the provided minimumStep
  2320. if (stepYear*1000 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1000;}
  2321. if (stepYear*500 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 500;}
  2322. if (stepYear*100 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 100;}
  2323. if (stepYear*50 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 50;}
  2324. if (stepYear*10 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 10;}
  2325. if (stepYear*5 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 5;}
  2326. if (stepYear > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1;}
  2327. if (stepMonth*3 > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 3;}
  2328. if (stepMonth > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 1;}
  2329. if (stepDay*5 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 5;}
  2330. if (stepDay*2 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 2;}
  2331. if (stepDay > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 1;}
  2332. if (stepDay/2 > minimumStep) {this.scale = TimeStep.SCALE.WEEKDAY; this.step = 1;}
  2333. if (stepHour*4 > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 4;}
  2334. if (stepHour > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 1;}
  2335. if (stepMinute*15 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 15;}
  2336. if (stepMinute*10 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 10;}
  2337. if (stepMinute*5 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 5;}
  2338. if (stepMinute > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 1;}
  2339. if (stepSecond*15 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 15;}
  2340. if (stepSecond*10 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 10;}
  2341. if (stepSecond*5 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 5;}
  2342. if (stepSecond > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 1;}
  2343. if (stepMillisecond*200 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 200;}
  2344. if (stepMillisecond*100 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 100;}
  2345. if (stepMillisecond*50 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 50;}
  2346. if (stepMillisecond*10 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 10;}
  2347. if (stepMillisecond*5 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 5;}
  2348. if (stepMillisecond > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 1;}
  2349. };
  2350. /**
  2351. * Snap a date to a rounded value.
  2352. * The snap intervals are dependent on the current scale and step.
  2353. * @param {Date} date the date to be snapped.
  2354. * @return {Date} snappedDate
  2355. */
  2356. TimeStep.prototype.snap = function(date) {
  2357. var clone = new Date(date.valueOf());
  2358. if (this.scale == TimeStep.SCALE.YEAR) {
  2359. var year = clone.getFullYear() + Math.round(clone.getMonth() / 12);
  2360. clone.setFullYear(Math.round(year / this.step) * this.step);
  2361. clone.setMonth(0);
  2362. clone.setDate(0);
  2363. clone.setHours(0);
  2364. clone.setMinutes(0);
  2365. clone.setSeconds(0);
  2366. clone.setMilliseconds(0);
  2367. }
  2368. else if (this.scale == TimeStep.SCALE.MONTH) {
  2369. if (clone.getDate() > 15) {
  2370. clone.setDate(1);
  2371. clone.setMonth(clone.getMonth() + 1);
  2372. // important: first set Date to 1, after that change the month.
  2373. }
  2374. else {
  2375. clone.setDate(1);
  2376. }
  2377. clone.setHours(0);
  2378. clone.setMinutes(0);
  2379. clone.setSeconds(0);
  2380. clone.setMilliseconds(0);
  2381. }
  2382. else if (this.scale == TimeStep.SCALE.DAY ||
  2383. this.scale == TimeStep.SCALE.WEEKDAY) {
  2384. //noinspection FallthroughInSwitchStatementJS
  2385. switch (this.step) {
  2386. case 5:
  2387. case 2:
  2388. clone.setHours(Math.round(clone.getHours() / 24) * 24); break;
  2389. default:
  2390. clone.setHours(Math.round(clone.getHours() / 12) * 12); break;
  2391. }
  2392. clone.setMinutes(0);
  2393. clone.setSeconds(0);
  2394. clone.setMilliseconds(0);
  2395. }
  2396. else if (this.scale == TimeStep.SCALE.HOUR) {
  2397. switch (this.step) {
  2398. case 4:
  2399. clone.setMinutes(Math.round(clone.getMinutes() / 60) * 60); break;
  2400. default:
  2401. clone.setMinutes(Math.round(clone.getMinutes() / 30) * 30); break;
  2402. }
  2403. clone.setSeconds(0);
  2404. clone.setMilliseconds(0);
  2405. } else if (this.scale == TimeStep.SCALE.MINUTE) {
  2406. //noinspection FallthroughInSwitchStatementJS
  2407. switch (this.step) {
  2408. case 15:
  2409. case 10:
  2410. clone.setMinutes(Math.round(clone.getMinutes() / 5) * 5);
  2411. clone.setSeconds(0);
  2412. break;
  2413. case 5:
  2414. clone.setSeconds(Math.round(clone.getSeconds() / 60) * 60); break;
  2415. default:
  2416. clone.setSeconds(Math.round(clone.getSeconds() / 30) * 30); break;
  2417. }
  2418. clone.setMilliseconds(0);
  2419. }
  2420. else if (this.scale == TimeStep.SCALE.SECOND) {
  2421. //noinspection FallthroughInSwitchStatementJS
  2422. switch (this.step) {
  2423. case 15:
  2424. case 10:
  2425. clone.setSeconds(Math.round(clone.getSeconds() / 5) * 5);
  2426. clone.setMilliseconds(0);
  2427. break;
  2428. case 5:
  2429. clone.setMilliseconds(Math.round(clone.getMilliseconds() / 1000) * 1000); break;
  2430. default:
  2431. clone.setMilliseconds(Math.round(clone.getMilliseconds() / 500) * 500); break;
  2432. }
  2433. }
  2434. else if (this.scale == TimeStep.SCALE.MILLISECOND) {
  2435. var step = this.step > 5 ? this.step / 2 : 1;
  2436. clone.setMilliseconds(Math.round(clone.getMilliseconds() / step) * step);
  2437. }
  2438. return clone;
  2439. };
  2440. /**
  2441. * Check if the current value is a major value (for example when the step
  2442. * is DAY, a major value is each first day of the MONTH)
  2443. * @return {boolean} true if current date is major, else false.
  2444. */
  2445. TimeStep.prototype.isMajor = function() {
  2446. switch (this.scale) {
  2447. case TimeStep.SCALE.MILLISECOND:
  2448. return (this.current.getMilliseconds() == 0);
  2449. case TimeStep.SCALE.SECOND:
  2450. return (this.current.getSeconds() == 0);
  2451. case TimeStep.SCALE.MINUTE:
  2452. return (this.current.getHours() == 0) && (this.current.getMinutes() == 0);
  2453. // Note: this is no bug. Major label is equal for both minute and hour scale
  2454. case TimeStep.SCALE.HOUR:
  2455. return (this.current.getHours() == 0);
  2456. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2457. case TimeStep.SCALE.DAY:
  2458. return (this.current.getDate() == 1);
  2459. case TimeStep.SCALE.MONTH:
  2460. return (this.current.getMonth() == 0);
  2461. case TimeStep.SCALE.YEAR:
  2462. return false;
  2463. default:
  2464. return false;
  2465. }
  2466. };
  2467. /**
  2468. * Returns formatted text for the minor axislabel, depending on the current
  2469. * date and the scale. For example when scale is MINUTE, the current time is
  2470. * formatted as "hh:mm".
  2471. * @param {Date} [date] custom date. if not provided, current date is taken
  2472. */
  2473. TimeStep.prototype.getLabelMinor = function(date) {
  2474. if (date == undefined) {
  2475. date = this.current;
  2476. }
  2477. switch (this.scale) {
  2478. case TimeStep.SCALE.MILLISECOND: return moment(date).format('SSS');
  2479. case TimeStep.SCALE.SECOND: return moment(date).format('s');
  2480. case TimeStep.SCALE.MINUTE: return moment(date).format('HH:mm');
  2481. case TimeStep.SCALE.HOUR: return moment(date).format('HH:mm');
  2482. case TimeStep.SCALE.WEEKDAY: return moment(date).format('ddd D');
  2483. case TimeStep.SCALE.DAY: return moment(date).format('D');
  2484. case TimeStep.SCALE.MONTH: return moment(date).format('MMM');
  2485. case TimeStep.SCALE.YEAR: return moment(date).format('YYYY');
  2486. default: return '';
  2487. }
  2488. };
  2489. /**
  2490. * Returns formatted text for the major axis label, depending on the current
  2491. * date and the scale. For example when scale is MINUTE, the major scale is
  2492. * hours, and the hour will be formatted as "hh".
  2493. * @param {Date} [date] custom date. if not provided, current date is taken
  2494. */
  2495. TimeStep.prototype.getLabelMajor = function(date) {
  2496. if (date == undefined) {
  2497. date = this.current;
  2498. }
  2499. //noinspection FallthroughInSwitchStatementJS
  2500. switch (this.scale) {
  2501. case TimeStep.SCALE.MILLISECOND:return moment(date).format('HH:mm:ss');
  2502. case TimeStep.SCALE.SECOND: return moment(date).format('D MMMM HH:mm');
  2503. case TimeStep.SCALE.MINUTE:
  2504. case TimeStep.SCALE.HOUR: return moment(date).format('ddd D MMMM');
  2505. case TimeStep.SCALE.WEEKDAY:
  2506. case TimeStep.SCALE.DAY: return moment(date).format('MMMM YYYY');
  2507. case TimeStep.SCALE.MONTH: return moment(date).format('YYYY');
  2508. case TimeStep.SCALE.YEAR: return '';
  2509. default: return '';
  2510. }
  2511. };
  2512. /**
  2513. * @constructor Stack
  2514. * Stacks items on top of each other.
  2515. * @param {ItemSet} itemset
  2516. * @param {Object} [options]
  2517. */
  2518. function Stack (itemset, options) {
  2519. this.itemset = itemset;
  2520. this.options = options || {};
  2521. this.defaultOptions = {
  2522. order: function (a, b) {
  2523. //return (b.width - a.width) || (a.left - b.left); // TODO: cleanup
  2524. // Order: ranges over non-ranges, ranged ordered by width, and
  2525. // lastly ordered by start.
  2526. if (a instanceof ItemRange) {
  2527. if (b instanceof ItemRange) {
  2528. var aInt = (a.data.end - a.data.start);
  2529. var bInt = (b.data.end - b.data.start);
  2530. return (aInt - bInt) || (a.data.start - b.data.start);
  2531. }
  2532. else {
  2533. return -1;
  2534. }
  2535. }
  2536. else {
  2537. if (b instanceof ItemRange) {
  2538. return 1;
  2539. }
  2540. else {
  2541. return (a.data.start - b.data.start);
  2542. }
  2543. }
  2544. },
  2545. margin: {
  2546. item: 10
  2547. }
  2548. };
  2549. this.ordered = []; // ordered items
  2550. }
  2551. /**
  2552. * Set options for the stack
  2553. * @param {Object} options Available options:
  2554. * {ItemSet} itemset
  2555. * {Number} margin
  2556. * {function} order Stacking order
  2557. */
  2558. Stack.prototype.setOptions = function setOptions (options) {
  2559. util.extend(this.options, options);
  2560. // TODO: register on data changes at the connected itemset, and update the changed part only and immediately
  2561. };
  2562. /**
  2563. * Stack the items such that they don't overlap. The items will have a minimal
  2564. * distance equal to options.margin.item.
  2565. */
  2566. Stack.prototype.update = function update() {
  2567. this._order();
  2568. this._stack();
  2569. };
  2570. /**
  2571. * Order the items. If a custom order function has been provided via the options,
  2572. * then this will be used.
  2573. * @private
  2574. */
  2575. Stack.prototype._order = function _order () {
  2576. var items = this.itemset.items;
  2577. if (!items) {
  2578. throw new Error('Cannot stack items: ItemSet does not contain items');
  2579. }
  2580. // TODO: store the sorted items, to have less work later on
  2581. var ordered = [];
  2582. var index = 0;
  2583. // items is a map (no array)
  2584. util.forEach(items, function (item) {
  2585. if (item.visible) {
  2586. ordered[index] = item;
  2587. index++;
  2588. }
  2589. });
  2590. //if a customer stack order function exists, use it.
  2591. var order = this.options.order || this.defaultOptions.order;
  2592. if (!(typeof order === 'function')) {
  2593. throw new Error('Option order must be a function');
  2594. }
  2595. ordered.sort(order);
  2596. this.ordered = ordered;
  2597. };
  2598. /**
  2599. * Adjust vertical positions of the events such that they don't overlap each
  2600. * other.
  2601. * @private
  2602. */
  2603. Stack.prototype._stack = function _stack () {
  2604. var i,
  2605. iMax,
  2606. ordered = this.ordered,
  2607. options = this.options,
  2608. orientation = options.orientation || this.defaultOptions.orientation,
  2609. axisOnTop = (orientation == 'top'),
  2610. margin;
  2611. if (options.margin && options.margin.item !== undefined) {
  2612. margin = options.margin.item;
  2613. }
  2614. else {
  2615. margin = this.defaultOptions.margin.item
  2616. }
  2617. // calculate new, non-overlapping positions
  2618. for (i = 0, iMax = ordered.length; i < iMax; i++) {
  2619. var item = ordered[i];
  2620. var collidingItem = null;
  2621. do {
  2622. // TODO: optimize checking for overlap. when there is a gap without items,
  2623. // you only need to check for items from the next item on, not from zero
  2624. collidingItem = this.checkOverlap(ordered, i, 0, i - 1, margin);
  2625. if (collidingItem != null) {
  2626. // There is a collision. Reposition the event above the colliding element
  2627. if (axisOnTop) {
  2628. item.top = collidingItem.top + collidingItem.height + margin;
  2629. }
  2630. else {
  2631. item.top = collidingItem.top - item.height - margin;
  2632. }
  2633. }
  2634. } while (collidingItem);
  2635. }
  2636. };
  2637. /**
  2638. * Check if the destiny position of given item overlaps with any
  2639. * of the other items from index itemStart to itemEnd.
  2640. * @param {Array} items Array with items
  2641. * @param {int} itemIndex Number of the item to be checked for overlap
  2642. * @param {int} itemStart First item to be checked.
  2643. * @param {int} itemEnd Last item to be checked.
  2644. * @return {Object | null} colliding item, or undefined when no collisions
  2645. * @param {Number} margin A minimum required margin.
  2646. * If margin is provided, the two items will be
  2647. * marked colliding when they overlap or
  2648. * when the margin between the two is smaller than
  2649. * the requested margin.
  2650. */
  2651. Stack.prototype.checkOverlap = function checkOverlap (items, itemIndex,
  2652. itemStart, itemEnd, margin) {
  2653. var collision = this.collision;
  2654. // we loop from end to start, as we suppose that the chance of a
  2655. // collision is larger for items at the end, so check these first.
  2656. var a = items[itemIndex];
  2657. for (var i = itemEnd; i >= itemStart; i--) {
  2658. var b = items[i];
  2659. if (collision(a, b, margin)) {
  2660. if (i != itemIndex) {
  2661. return b;
  2662. }
  2663. }
  2664. }
  2665. return null;
  2666. };
  2667. /**
  2668. * Test if the two provided items collide
  2669. * The items must have parameters left, width, top, and height.
  2670. * @param {Component} a The first item
  2671. * @param {Component} b The second item
  2672. * @param {Number} margin A minimum required margin.
  2673. * If margin is provided, the two items will be
  2674. * marked colliding when they overlap or
  2675. * when the margin between the two is smaller than
  2676. * the requested margin.
  2677. * @return {boolean} true if a and b collide, else false
  2678. */
  2679. Stack.prototype.collision = function collision (a, b, margin) {
  2680. return ((a.left - margin) < (b.left + b.width) &&
  2681. (a.left + a.width + margin) > b.left &&
  2682. (a.top - margin) < (b.top + b.height) &&
  2683. (a.top + a.height + margin) > b.top);
  2684. };
  2685. /**
  2686. * @constructor Range
  2687. * A Range controls a numeric range with a start and end value.
  2688. * The Range adjusts the range based on mouse events or programmatic changes,
  2689. * and triggers events when the range is changing or has been changed.
  2690. * @param {Object} [options] See description at Range.setOptions
  2691. * @extends Controller
  2692. */
  2693. function Range(options) {
  2694. this.id = util.randomUUID();
  2695. this.start = null; // Number
  2696. this.end = null; // Number
  2697. this.options = options || {};
  2698. this.setOptions(options);
  2699. }
  2700. // extend the Range prototype with an event emitter mixin
  2701. Emitter(Range.prototype);
  2702. /**
  2703. * Set options for the range controller
  2704. * @param {Object} options Available options:
  2705. * {Number} min Minimum value for start
  2706. * {Number} max Maximum value for end
  2707. * {Number} zoomMin Set a minimum value for
  2708. * (end - start).
  2709. * {Number} zoomMax Set a maximum value for
  2710. * (end - start).
  2711. */
  2712. Range.prototype.setOptions = function (options) {
  2713. util.extend(this.options, options);
  2714. // re-apply range with new limitations
  2715. if (this.start !== null && this.end !== null) {
  2716. this.setRange(this.start, this.end);
  2717. }
  2718. };
  2719. /**
  2720. * Test whether direction has a valid value
  2721. * @param {String} direction 'horizontal' or 'vertical'
  2722. */
  2723. function validateDirection (direction) {
  2724. if (direction != 'horizontal' && direction != 'vertical') {
  2725. throw new TypeError('Unknown direction "' + direction + '". ' +
  2726. 'Choose "horizontal" or "vertical".');
  2727. }
  2728. }
  2729. /**
  2730. * Add listeners for mouse and touch events to the component
  2731. * @param {Controller} controller
  2732. * @param {Component} component Should be a rootpanel
  2733. * @param {String} event Available events: 'move', 'zoom'
  2734. * @param {String} direction Available directions: 'horizontal', 'vertical'
  2735. */
  2736. Range.prototype.subscribe = function (controller, component, event, direction) {
  2737. var me = this;
  2738. if (event == 'move') {
  2739. // drag start listener
  2740. controller.on('dragstart', function (event) {
  2741. me._onDragStart(event, component);
  2742. });
  2743. // drag listener
  2744. controller.on('drag', function (event) {
  2745. me._onDrag(event, component, direction);
  2746. });
  2747. // drag end listener
  2748. controller.on('dragend', function (event) {
  2749. me._onDragEnd(event, component);
  2750. });
  2751. // ignore dragging when holding
  2752. controller.on('hold', function (event) {
  2753. me._onHold();
  2754. });
  2755. }
  2756. else if (event == 'zoom') {
  2757. // mouse wheel
  2758. function mousewheel (event) {
  2759. me._onMouseWheel(event, component, direction);
  2760. }
  2761. controller.on('mousewheel', mousewheel);
  2762. controller.on('DOMMouseScroll', mousewheel); // For FF
  2763. // pinch
  2764. controller.on('touch', function (event) {
  2765. me._onTouch(event);
  2766. });
  2767. controller.on('pinch', function (event) {
  2768. me._onPinch(event, component, direction);
  2769. });
  2770. }
  2771. else {
  2772. throw new TypeError('Unknown event "' + event + '". ' +
  2773. 'Choose "move" or "zoom".');
  2774. }
  2775. };
  2776. /**
  2777. * Set a new start and end range
  2778. * @param {Number} [start]
  2779. * @param {Number} [end]
  2780. */
  2781. Range.prototype.setRange = function(start, end) {
  2782. var changed = this._applyRange(start, end);
  2783. if (changed) {
  2784. var params = {
  2785. start: this.start,
  2786. end: this.end
  2787. };
  2788. this.emit('rangechange', params);
  2789. this.emit('rangechanged', params);
  2790. }
  2791. };
  2792. /**
  2793. * Set a new start and end range. This method is the same as setRange, but
  2794. * does not trigger a range change and range changed event, and it returns
  2795. * true when the range is changed
  2796. * @param {Number} [start]
  2797. * @param {Number} [end]
  2798. * @return {Boolean} changed
  2799. * @private
  2800. */
  2801. Range.prototype._applyRange = function(start, end) {
  2802. var newStart = (start != null) ? util.convert(start, 'Date').valueOf() : this.start,
  2803. newEnd = (end != null) ? util.convert(end, 'Date').valueOf() : this.end,
  2804. max = (this.options.max != null) ? util.convert(this.options.max, 'Date').valueOf() : null,
  2805. min = (this.options.min != null) ? util.convert(this.options.min, 'Date').valueOf() : null,
  2806. diff;
  2807. // check for valid number
  2808. if (isNaN(newStart) || newStart === null) {
  2809. throw new Error('Invalid start "' + start + '"');
  2810. }
  2811. if (isNaN(newEnd) || newEnd === null) {
  2812. throw new Error('Invalid end "' + end + '"');
  2813. }
  2814. // prevent start < end
  2815. if (newEnd < newStart) {
  2816. newEnd = newStart;
  2817. }
  2818. // prevent start < min
  2819. if (min !== null) {
  2820. if (newStart < min) {
  2821. diff = (min - newStart);
  2822. newStart += diff;
  2823. newEnd += diff;
  2824. // prevent end > max
  2825. if (max != null) {
  2826. if (newEnd > max) {
  2827. newEnd = max;
  2828. }
  2829. }
  2830. }
  2831. }
  2832. // prevent end > max
  2833. if (max !== null) {
  2834. if (newEnd > max) {
  2835. diff = (newEnd - max);
  2836. newStart -= diff;
  2837. newEnd -= diff;
  2838. // prevent start < min
  2839. if (min != null) {
  2840. if (newStart < min) {
  2841. newStart = min;
  2842. }
  2843. }
  2844. }
  2845. }
  2846. // prevent (end-start) < zoomMin
  2847. if (this.options.zoomMin !== null) {
  2848. var zoomMin = parseFloat(this.options.zoomMin);
  2849. if (zoomMin < 0) {
  2850. zoomMin = 0;
  2851. }
  2852. if ((newEnd - newStart) < zoomMin) {
  2853. if ((this.end - this.start) === zoomMin) {
  2854. // ignore this action, we are already zoomed to the minimum
  2855. newStart = this.start;
  2856. newEnd = this.end;
  2857. }
  2858. else {
  2859. // zoom to the minimum
  2860. diff = (zoomMin - (newEnd - newStart));
  2861. newStart -= diff / 2;
  2862. newEnd += diff / 2;
  2863. }
  2864. }
  2865. }
  2866. // prevent (end-start) > zoomMax
  2867. if (this.options.zoomMax !== null) {
  2868. var zoomMax = parseFloat(this.options.zoomMax);
  2869. if (zoomMax < 0) {
  2870. zoomMax = 0;
  2871. }
  2872. if ((newEnd - newStart) > zoomMax) {
  2873. if ((this.end - this.start) === zoomMax) {
  2874. // ignore this action, we are already zoomed to the maximum
  2875. newStart = this.start;
  2876. newEnd = this.end;
  2877. }
  2878. else {
  2879. // zoom to the maximum
  2880. diff = ((newEnd - newStart) - zoomMax);
  2881. newStart += diff / 2;
  2882. newEnd -= diff / 2;
  2883. }
  2884. }
  2885. }
  2886. var changed = (this.start != newStart || this.end != newEnd);
  2887. this.start = newStart;
  2888. this.end = newEnd;
  2889. return changed;
  2890. };
  2891. /**
  2892. * Retrieve the current range.
  2893. * @return {Object} An object with start and end properties
  2894. */
  2895. Range.prototype.getRange = function() {
  2896. return {
  2897. start: this.start,
  2898. end: this.end
  2899. };
  2900. };
  2901. /**
  2902. * Calculate the conversion offset and scale for current range, based on
  2903. * the provided width
  2904. * @param {Number} width
  2905. * @returns {{offset: number, scale: number}} conversion
  2906. */
  2907. Range.prototype.conversion = function (width) {
  2908. return Range.conversion(this.start, this.end, width);
  2909. };
  2910. /**
  2911. * Static method to calculate the conversion offset and scale for a range,
  2912. * based on the provided start, end, and width
  2913. * @param {Number} start
  2914. * @param {Number} end
  2915. * @param {Number} width
  2916. * @returns {{offset: number, scale: number}} conversion
  2917. */
  2918. Range.conversion = function (start, end, width) {
  2919. if (width != 0 && (end - start != 0)) {
  2920. return {
  2921. offset: start,
  2922. scale: width / (end - start)
  2923. }
  2924. }
  2925. else {
  2926. return {
  2927. offset: 0,
  2928. scale: 1
  2929. };
  2930. }
  2931. };
  2932. // global (private) object to store drag params
  2933. var touchParams = {};
  2934. /**
  2935. * Start dragging horizontally or vertically
  2936. * @param {Event} event
  2937. * @param {Object} component
  2938. * @private
  2939. */
  2940. Range.prototype._onDragStart = function(event, component) {
  2941. // refuse to drag when we where pinching to prevent the timeline make a jump
  2942. // when releasing the fingers in opposite order from the touch screen
  2943. if (touchParams.ignore) return;
  2944. // TODO: reckon with option movable
  2945. touchParams.start = this.start;
  2946. touchParams.end = this.end;
  2947. var frame = component.frame;
  2948. if (frame) {
  2949. frame.style.cursor = 'move';
  2950. }
  2951. };
  2952. /**
  2953. * Perform dragging operating.
  2954. * @param {Event} event
  2955. * @param {Component} component
  2956. * @param {String} direction 'horizontal' or 'vertical'
  2957. * @private
  2958. */
  2959. Range.prototype._onDrag = function (event, component, direction) {
  2960. validateDirection(direction);
  2961. // TODO: reckon with option movable
  2962. // refuse to drag when we where pinching to prevent the timeline make a jump
  2963. // when releasing the fingers in opposite order from the touch screen
  2964. if (touchParams.ignore) return;
  2965. var delta = (direction == 'horizontal') ? event.gesture.deltaX : event.gesture.deltaY,
  2966. interval = (touchParams.end - touchParams.start),
  2967. width = (direction == 'horizontal') ? component.width : component.height,
  2968. diffRange = -delta / width * interval;
  2969. this._applyRange(touchParams.start + diffRange, touchParams.end + diffRange);
  2970. this.emit('rangechange', {
  2971. start: this.start,
  2972. end: this.end
  2973. });
  2974. };
  2975. /**
  2976. * Stop dragging operating.
  2977. * @param {event} event
  2978. * @param {Component} component
  2979. * @private
  2980. */
  2981. Range.prototype._onDragEnd = function (event, component) {
  2982. // refuse to drag when we where pinching to prevent the timeline make a jump
  2983. // when releasing the fingers in opposite order from the touch screen
  2984. if (touchParams.ignore) return;
  2985. // TODO: reckon with option movable
  2986. if (component.frame) {
  2987. component.frame.style.cursor = 'auto';
  2988. }
  2989. // fire a rangechanged event
  2990. this.emit('rangechanged', {
  2991. start: this.start,
  2992. end: this.end
  2993. });
  2994. };
  2995. /**
  2996. * Event handler for mouse wheel event, used to zoom
  2997. * Code from http://adomas.org/javascript-mouse-wheel/
  2998. * @param {Event} event
  2999. * @param {Component} component
  3000. * @param {String} direction 'horizontal' or 'vertical'
  3001. * @private
  3002. */
  3003. Range.prototype._onMouseWheel = function(event, component, direction) {
  3004. validateDirection(direction);
  3005. // TODO: reckon with option zoomable
  3006. // retrieve delta
  3007. var delta = 0;
  3008. if (event.wheelDelta) { /* IE/Opera. */
  3009. delta = event.wheelDelta / 120;
  3010. } else if (event.detail) { /* Mozilla case. */
  3011. // In Mozilla, sign of delta is different than in IE.
  3012. // Also, delta is multiple of 3.
  3013. delta = -event.detail / 3;
  3014. }
  3015. // If delta is nonzero, handle it.
  3016. // Basically, delta is now positive if wheel was scrolled up,
  3017. // and negative, if wheel was scrolled down.
  3018. if (delta) {
  3019. // perform the zoom action. Delta is normally 1 or -1
  3020. // adjust a negative delta such that zooming in with delta 0.1
  3021. // equals zooming out with a delta -0.1
  3022. var scale;
  3023. if (delta < 0) {
  3024. scale = 1 - (delta / 5);
  3025. }
  3026. else {
  3027. scale = 1 / (1 + (delta / 5)) ;
  3028. }
  3029. // calculate center, the date to zoom around
  3030. var gesture = util.fakeGesture(this, event),
  3031. pointer = getPointer(gesture.center, component.frame),
  3032. pointerDate = this._pointerToDate(component, direction, pointer);
  3033. this.zoom(scale, pointerDate);
  3034. }
  3035. // Prevent default actions caused by mouse wheel
  3036. // (else the page and timeline both zoom and scroll)
  3037. event.preventDefault();
  3038. };
  3039. /**
  3040. * Start of a touch gesture
  3041. * @private
  3042. */
  3043. Range.prototype._onTouch = function (event) {
  3044. touchParams.start = this.start;
  3045. touchParams.end = this.end;
  3046. touchParams.ignore = false;
  3047. touchParams.center = null;
  3048. // don't move the range when dragging a selected event
  3049. // TODO: it's not so neat to have to know about the state of the ItemSet
  3050. var item = ItemSet.itemFromTarget(event);
  3051. if (item && item.selected && this.options.editable) {
  3052. touchParams.ignore = true;
  3053. }
  3054. };
  3055. /**
  3056. * On start of a hold gesture
  3057. * @private
  3058. */
  3059. Range.prototype._onHold = function () {
  3060. touchParams.ignore = true;
  3061. };
  3062. /**
  3063. * Handle pinch event
  3064. * @param {Event} event
  3065. * @param {Component} component
  3066. * @param {String} direction 'horizontal' or 'vertical'
  3067. * @private
  3068. */
  3069. Range.prototype._onPinch = function (event, component, direction) {
  3070. touchParams.ignore = true;
  3071. // TODO: reckon with option zoomable
  3072. if (event.gesture.touches.length > 1) {
  3073. if (!touchParams.center) {
  3074. touchParams.center = getPointer(event.gesture.center, component.frame);
  3075. }
  3076. var scale = 1 / event.gesture.scale,
  3077. initDate = this._pointerToDate(component, direction, touchParams.center),
  3078. center = getPointer(event.gesture.center, component.frame),
  3079. date = this._pointerToDate(component, direction, center),
  3080. delta = date - initDate; // TODO: utilize delta
  3081. // calculate new start and end
  3082. var newStart = parseInt(initDate + (touchParams.start - initDate) * scale);
  3083. var newEnd = parseInt(initDate + (touchParams.end - initDate) * scale);
  3084. // apply new range
  3085. this.setRange(newStart, newEnd);
  3086. }
  3087. };
  3088. /**
  3089. * Helper function to calculate the center date for zooming
  3090. * @param {Component} component
  3091. * @param {{x: Number, y: Number}} pointer
  3092. * @param {String} direction 'horizontal' or 'vertical'
  3093. * @return {number} date
  3094. * @private
  3095. */
  3096. Range.prototype._pointerToDate = function (component, direction, pointer) {
  3097. var conversion;
  3098. if (direction == 'horizontal') {
  3099. var width = component.width;
  3100. conversion = this.conversion(width);
  3101. return pointer.x / conversion.scale + conversion.offset;
  3102. }
  3103. else {
  3104. var height = component.height;
  3105. conversion = this.conversion(height);
  3106. return pointer.y / conversion.scale + conversion.offset;
  3107. }
  3108. };
  3109. /**
  3110. * Get the pointer location relative to the location of the dom element
  3111. * @param {{pageX: Number, pageY: Number}} touch
  3112. * @param {Element} element HTML DOM element
  3113. * @return {{x: Number, y: Number}} pointer
  3114. * @private
  3115. */
  3116. function getPointer (touch, element) {
  3117. return {
  3118. x: touch.pageX - vis.util.getAbsoluteLeft(element),
  3119. y: touch.pageY - vis.util.getAbsoluteTop(element)
  3120. };
  3121. }
  3122. /**
  3123. * Zoom the range the given scale in or out. Start and end date will
  3124. * be adjusted, and the timeline will be redrawn. You can optionally give a
  3125. * date around which to zoom.
  3126. * For example, try scale = 0.9 or 1.1
  3127. * @param {Number} scale Scaling factor. Values above 1 will zoom out,
  3128. * values below 1 will zoom in.
  3129. * @param {Number} [center] Value representing a date around which will
  3130. * be zoomed.
  3131. */
  3132. Range.prototype.zoom = function(scale, center) {
  3133. // if centerDate is not provided, take it half between start Date and end Date
  3134. if (center == null) {
  3135. center = (this.start + this.end) / 2;
  3136. }
  3137. // calculate new start and end
  3138. var newStart = center + (this.start - center) * scale;
  3139. var newEnd = center + (this.end - center) * scale;
  3140. this.setRange(newStart, newEnd);
  3141. };
  3142. /**
  3143. * Move the range with a given delta to the left or right. Start and end
  3144. * value will be adjusted. For example, try delta = 0.1 or -0.1
  3145. * @param {Number} delta Moving amount. Positive value will move right,
  3146. * negative value will move left
  3147. */
  3148. Range.prototype.move = function(delta) {
  3149. // zoom start Date and end Date relative to the centerDate
  3150. var diff = (this.end - this.start);
  3151. // apply new values
  3152. var newStart = this.start + diff * delta;
  3153. var newEnd = this.end + diff * delta;
  3154. // TODO: reckon with min and max range
  3155. this.start = newStart;
  3156. this.end = newEnd;
  3157. };
  3158. /**
  3159. * Move the range to a new center point
  3160. * @param {Number} moveTo New center point of the range
  3161. */
  3162. Range.prototype.moveTo = function(moveTo) {
  3163. var center = (this.start + this.end) / 2;
  3164. var diff = center - moveTo;
  3165. // calculate new start and end
  3166. var newStart = this.start - diff;
  3167. var newEnd = this.end - diff;
  3168. this.setRange(newStart, newEnd);
  3169. };
  3170. /**
  3171. * @constructor Controller
  3172. *
  3173. * A Controller controls the reflows and repaints of all components,
  3174. * and is used as an event bus for all components.
  3175. */
  3176. function Controller () {
  3177. var me = this;
  3178. this.id = util.randomUUID();
  3179. this.components = {};
  3180. /**
  3181. * Listen for a 'request-reflow' event. The controller will schedule a reflow
  3182. * @param {Boolean} [force] If true, an immediate reflow is forced. Default
  3183. * is false.
  3184. */
  3185. var reflowTimer = null;
  3186. this.on('request-reflow', function requestReflow(force) {
  3187. if (force) {
  3188. me.reflow();
  3189. }
  3190. else {
  3191. if (!reflowTimer) {
  3192. reflowTimer = setTimeout(function () {
  3193. reflowTimer = null;
  3194. me.reflow();
  3195. }, 0);
  3196. }
  3197. }
  3198. });
  3199. /**
  3200. * Request a repaint. The controller will schedule a repaint
  3201. * @param {Boolean} [force] If true, an immediate repaint is forced. Default
  3202. * is false.
  3203. */
  3204. var repaintTimer = null;
  3205. this.on('request-repaint', function requestRepaint(force) {
  3206. if (force) {
  3207. me.repaint();
  3208. }
  3209. else {
  3210. if (!repaintTimer) {
  3211. repaintTimer = setTimeout(function () {
  3212. repaintTimer = null;
  3213. me.repaint();
  3214. }, 0);
  3215. }
  3216. }
  3217. });
  3218. }
  3219. // Extend controller with Emitter mixin
  3220. Emitter(Controller.prototype);
  3221. /**
  3222. * Add a component to the controller
  3223. * @param {Component} component
  3224. */
  3225. Controller.prototype.add = function add(component) {
  3226. // validate the component
  3227. if (component.id == undefined) {
  3228. throw new Error('Component has no field id');
  3229. }
  3230. if (!(component instanceof Component) && !(component instanceof Controller)) {
  3231. throw new TypeError('Component must be an instance of ' +
  3232. 'prototype Component or Controller');
  3233. }
  3234. // add the component
  3235. component.setController(this);
  3236. this.components[component.id] = component;
  3237. };
  3238. /**
  3239. * Remove a component from the controller
  3240. * @param {Component | String} component
  3241. */
  3242. Controller.prototype.remove = function remove(component) {
  3243. var id;
  3244. for (id in this.components) {
  3245. if (this.components.hasOwnProperty(id)) {
  3246. if (id == component || this.components[id] === component) {
  3247. break;
  3248. }
  3249. }
  3250. }
  3251. if (id) {
  3252. // unregister the controller (gives the component the ability to unregister
  3253. // event listeners and clean up other stuff)
  3254. this.components[id].setController(null);
  3255. delete this.components[id];
  3256. }
  3257. };
  3258. /**
  3259. * Repaint all components
  3260. */
  3261. Controller.prototype.repaint = function repaint() {
  3262. var changed = false;
  3263. // cancel any running repaint request
  3264. if (this.repaintTimer) {
  3265. clearTimeout(this.repaintTimer);
  3266. this.repaintTimer = undefined;
  3267. }
  3268. var done = {};
  3269. function repaint(component, id) {
  3270. if (!(id in done)) {
  3271. // first repaint the components on which this component is dependent
  3272. if (component.depends) {
  3273. component.depends.forEach(function (dep) {
  3274. repaint(dep, dep.id);
  3275. });
  3276. }
  3277. if (component.parent) {
  3278. repaint(component.parent, component.parent.id);
  3279. }
  3280. // repaint the component itself and mark as done
  3281. changed = component.repaint() || changed;
  3282. done[id] = true;
  3283. }
  3284. }
  3285. util.forEach(this.components, repaint);
  3286. this.emit('repaint');
  3287. // immediately reflow when needed
  3288. if (changed) {
  3289. this.reflow();
  3290. }
  3291. // TODO: limit the number of nested reflows/repaints, prevent loop
  3292. };
  3293. /**
  3294. * Reflow all components
  3295. */
  3296. Controller.prototype.reflow = function reflow() {
  3297. var resized = false;
  3298. // cancel any running repaint request
  3299. if (this.reflowTimer) {
  3300. clearTimeout(this.reflowTimer);
  3301. this.reflowTimer = undefined;
  3302. }
  3303. var done = {};
  3304. function reflow(component, id) {
  3305. if (!(id in done)) {
  3306. // first reflow the components on which this component is dependent
  3307. if (component.depends) {
  3308. component.depends.forEach(function (dep) {
  3309. reflow(dep, dep.id);
  3310. });
  3311. }
  3312. if (component.parent) {
  3313. reflow(component.parent, component.parent.id);
  3314. }
  3315. // reflow the component itself and mark as done
  3316. resized = component.reflow() || resized;
  3317. done[id] = true;
  3318. }
  3319. }
  3320. util.forEach(this.components, reflow);
  3321. this.emit('reflow');
  3322. // immediately repaint when needed
  3323. if (resized) {
  3324. this.repaint();
  3325. }
  3326. // TODO: limit the number of nested reflows/repaints, prevent loop
  3327. };
  3328. /**
  3329. * Prototype for visual components
  3330. */
  3331. function Component () {
  3332. this.id = null;
  3333. this.parent = null;
  3334. this.depends = null;
  3335. this.controller = null;
  3336. this.options = null;
  3337. this.frame = null; // main DOM element
  3338. this.top = 0;
  3339. this.left = 0;
  3340. this.width = 0;
  3341. this.height = 0;
  3342. }
  3343. /**
  3344. * Set parameters for the frame. Parameters will be merged in current parameter
  3345. * set.
  3346. * @param {Object} options Available parameters:
  3347. * {String | function} [className]
  3348. * {String | Number | function} [left]
  3349. * {String | Number | function} [top]
  3350. * {String | Number | function} [width]
  3351. * {String | Number | function} [height]
  3352. */
  3353. Component.prototype.setOptions = function setOptions(options) {
  3354. if (options) {
  3355. util.extend(this.options, options);
  3356. if (this.controller) {
  3357. this.requestRepaint();
  3358. this.requestReflow();
  3359. }
  3360. }
  3361. };
  3362. /**
  3363. * Get an option value by name
  3364. * The function will first check this.options object, and else will check
  3365. * this.defaultOptions.
  3366. * @param {String} name
  3367. * @return {*} value
  3368. */
  3369. Component.prototype.getOption = function getOption(name) {
  3370. var value;
  3371. if (this.options) {
  3372. value = this.options[name];
  3373. }
  3374. if (value === undefined && this.defaultOptions) {
  3375. value = this.defaultOptions[name];
  3376. }
  3377. return value;
  3378. };
  3379. /**
  3380. * Set controller for this component, or remove current controller by passing
  3381. * null as parameter value.
  3382. * @param {Controller | null} controller
  3383. */
  3384. Component.prototype.setController = function setController (controller) {
  3385. this.controller = controller || null;
  3386. };
  3387. /**
  3388. * Get controller of this component
  3389. * @return {Controller} controller
  3390. */
  3391. Component.prototype.getController = function getController () {
  3392. return this.controller;
  3393. };
  3394. /**
  3395. * Get the container element of the component, which can be used by a child to
  3396. * add its own widgets. Not all components do have a container for childs, in
  3397. * that case null is returned.
  3398. * @returns {HTMLElement | null} container
  3399. */
  3400. // TODO: get rid of the getContainer and getFrame methods, provide these via the options
  3401. Component.prototype.getContainer = function getContainer() {
  3402. // should be implemented by the component
  3403. return null;
  3404. };
  3405. /**
  3406. * Get the frame element of the component, the outer HTML DOM element.
  3407. * @returns {HTMLElement | null} frame
  3408. */
  3409. Component.prototype.getFrame = function getFrame() {
  3410. return this.frame;
  3411. };
  3412. /**
  3413. * Repaint the component
  3414. * @return {Boolean} changed
  3415. */
  3416. Component.prototype.repaint = function repaint() {
  3417. // should be implemented by the component
  3418. return false;
  3419. };
  3420. /**
  3421. * Reflow the component
  3422. * @return {Boolean} resized
  3423. */
  3424. Component.prototype.reflow = function reflow() {
  3425. // should be implemented by the component
  3426. return false;
  3427. };
  3428. /**
  3429. * Hide the component from the DOM
  3430. * @return {Boolean} changed
  3431. */
  3432. Component.prototype.hide = function hide() {
  3433. if (this.frame && this.frame.parentNode) {
  3434. this.frame.parentNode.removeChild(this.frame);
  3435. return true;
  3436. }
  3437. else {
  3438. return false;
  3439. }
  3440. };
  3441. /**
  3442. * Show the component in the DOM (when not already visible).
  3443. * A repaint will be executed when the component is not visible
  3444. * @return {Boolean} changed
  3445. */
  3446. Component.prototype.show = function show() {
  3447. if (!this.frame || !this.frame.parentNode) {
  3448. return this.repaint();
  3449. }
  3450. else {
  3451. return false;
  3452. }
  3453. };
  3454. /**
  3455. * Request a repaint. The controller will schedule a repaint
  3456. */
  3457. Component.prototype.requestRepaint = function requestRepaint() {
  3458. if (this.controller) {
  3459. this.controller.emit('request-repaint');
  3460. }
  3461. else {
  3462. throw new Error('Cannot request a repaint: no controller configured');
  3463. // TODO: just do a repaint when no parent is configured?
  3464. }
  3465. };
  3466. /**
  3467. * Request a reflow. The controller will schedule a reflow
  3468. */
  3469. Component.prototype.requestReflow = function requestReflow() {
  3470. if (this.controller) {
  3471. this.controller.emit('request-reflow');
  3472. }
  3473. else {
  3474. throw new Error('Cannot request a reflow: no controller configured');
  3475. // TODO: just do a reflow when no parent is configured?
  3476. }
  3477. };
  3478. /**
  3479. * A panel can contain components
  3480. * @param {Component} [parent]
  3481. * @param {Component[]} [depends] Components on which this components depends
  3482. * (except for the parent)
  3483. * @param {Object} [options] Available parameters:
  3484. * {String | Number | function} [left]
  3485. * {String | Number | function} [top]
  3486. * {String | Number | function} [width]
  3487. * {String | Number | function} [height]
  3488. * {String | function} [className]
  3489. * @constructor Panel
  3490. * @extends Component
  3491. */
  3492. function Panel(parent, depends, options) {
  3493. this.id = util.randomUUID();
  3494. this.parent = parent;
  3495. this.depends = depends;
  3496. this.options = options || {};
  3497. }
  3498. Panel.prototype = new Component();
  3499. /**
  3500. * Set options. Will extend the current options.
  3501. * @param {Object} [options] Available parameters:
  3502. * {String | function} [className]
  3503. * {String | Number | function} [left]
  3504. * {String | Number | function} [top]
  3505. * {String | Number | function} [width]
  3506. * {String | Number | function} [height]
  3507. */
  3508. Panel.prototype.setOptions = Component.prototype.setOptions;
  3509. /**
  3510. * Get the container element of the panel, which can be used by a child to
  3511. * add its own widgets.
  3512. * @returns {HTMLElement} container
  3513. */
  3514. Panel.prototype.getContainer = function () {
  3515. return this.frame;
  3516. };
  3517. /**
  3518. * Repaint the component
  3519. * @return {Boolean} changed
  3520. */
  3521. Panel.prototype.repaint = function () {
  3522. var changed = 0,
  3523. update = util.updateProperty,
  3524. asSize = util.option.asSize,
  3525. options = this.options,
  3526. frame = this.frame;
  3527. if (!frame) {
  3528. frame = document.createElement('div');
  3529. frame.className = 'vpanel';
  3530. var className = options.className;
  3531. if (className) {
  3532. if (typeof className == 'function') {
  3533. util.addClassName(frame, String(className()));
  3534. }
  3535. else {
  3536. util.addClassName(frame, String(className));
  3537. }
  3538. }
  3539. this.frame = frame;
  3540. changed += 1;
  3541. }
  3542. if (!frame.parentNode) {
  3543. if (!this.parent) {
  3544. throw new Error('Cannot repaint panel: no parent attached');
  3545. }
  3546. var parentContainer = this.parent.getContainer();
  3547. if (!parentContainer) {
  3548. throw new Error('Cannot repaint panel: parent has no container element');
  3549. }
  3550. parentContainer.appendChild(frame);
  3551. changed += 1;
  3552. }
  3553. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  3554. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3555. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3556. changed += update(frame.style, 'height', asSize(options.height, '100%'));
  3557. return (changed > 0);
  3558. };
  3559. /**
  3560. * Reflow the component
  3561. * @return {Boolean} resized
  3562. */
  3563. Panel.prototype.reflow = function () {
  3564. var changed = 0,
  3565. update = util.updateProperty,
  3566. frame = this.frame;
  3567. if (frame) {
  3568. changed += update(this, 'top', frame.offsetTop);
  3569. changed += update(this, 'left', frame.offsetLeft);
  3570. changed += update(this, 'width', frame.offsetWidth);
  3571. changed += update(this, 'height', frame.offsetHeight);
  3572. }
  3573. else {
  3574. changed += 1;
  3575. }
  3576. return (changed > 0);
  3577. };
  3578. /**
  3579. * A root panel can hold components. The root panel must be initialized with
  3580. * a DOM element as container.
  3581. * @param {HTMLElement} container
  3582. * @param {Object} [options] Available parameters: see RootPanel.setOptions.
  3583. * @constructor RootPanel
  3584. * @extends Panel
  3585. */
  3586. function RootPanel(container, options) {
  3587. this.id = util.randomUUID();
  3588. this.container = container;
  3589. // create functions to be used as DOM event listeners
  3590. var me = this;
  3591. this.hammer = null;
  3592. // create listeners for all interesting events, these events will be emitted
  3593. // via the controller
  3594. var events = [
  3595. 'touch', 'pinch', 'tap', 'doubletap', 'hold',
  3596. 'dragstart', 'drag', 'dragend',
  3597. 'mousewheel', 'DOMMouseScroll' // DOMMouseScroll is for Firefox
  3598. ];
  3599. this.listeners = {};
  3600. events.forEach(function (event) {
  3601. me.listeners[event] = function () {
  3602. var args = [event].concat(Array.prototype.slice.call(arguments, 0));
  3603. me.controller.emit.apply(me.controller, args);
  3604. };
  3605. });
  3606. this.options = options || {};
  3607. this.defaultOptions = {
  3608. autoResize: true
  3609. };
  3610. }
  3611. RootPanel.prototype = new Panel();
  3612. /**
  3613. * Set options. Will extend the current options.
  3614. * @param {Object} [options] Available parameters:
  3615. * {String | function} [className]
  3616. * {String | Number | function} [left]
  3617. * {String | Number | function} [top]
  3618. * {String | Number | function} [width]
  3619. * {String | Number | function} [height]
  3620. * {Boolean | function} [autoResize]
  3621. */
  3622. RootPanel.prototype.setOptions = Component.prototype.setOptions;
  3623. /**
  3624. * Repaint the component
  3625. * @return {Boolean} changed
  3626. */
  3627. RootPanel.prototype.repaint = function () {
  3628. var changed = 0,
  3629. update = util.updateProperty,
  3630. asSize = util.option.asSize,
  3631. options = this.options,
  3632. frame = this.frame;
  3633. if (!frame) {
  3634. frame = document.createElement('div');
  3635. this.frame = frame;
  3636. this._registerListeners();
  3637. changed += 1;
  3638. }
  3639. if (!frame.parentNode) {
  3640. if (!this.container) {
  3641. throw new Error('Cannot repaint root panel: no container attached');
  3642. }
  3643. this.container.appendChild(frame);
  3644. changed += 1;
  3645. }
  3646. frame.className = 'vis timeline rootpanel ' + options.orientation +
  3647. (options.editable ? ' editable' : '');
  3648. var className = options.className;
  3649. if (className) {
  3650. util.addClassName(frame, util.option.asString(className));
  3651. }
  3652. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  3653. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3654. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3655. changed += update(frame.style, 'height', asSize(options.height, '100%'));
  3656. this._updateWatch();
  3657. return (changed > 0);
  3658. };
  3659. /**
  3660. * Reflow the component
  3661. * @return {Boolean} resized
  3662. */
  3663. RootPanel.prototype.reflow = function () {
  3664. var changed = 0,
  3665. update = util.updateProperty,
  3666. frame = this.frame;
  3667. if (frame) {
  3668. changed += update(this, 'top', frame.offsetTop);
  3669. changed += update(this, 'left', frame.offsetLeft);
  3670. changed += update(this, 'width', frame.offsetWidth);
  3671. changed += update(this, 'height', frame.offsetHeight);
  3672. }
  3673. else {
  3674. changed += 1;
  3675. }
  3676. return (changed > 0);
  3677. };
  3678. /**
  3679. * Update watching for resize, depending on the current option
  3680. * @private
  3681. */
  3682. RootPanel.prototype._updateWatch = function () {
  3683. var autoResize = this.getOption('autoResize');
  3684. if (autoResize) {
  3685. this._watch();
  3686. }
  3687. else {
  3688. this._unwatch();
  3689. }
  3690. };
  3691. /**
  3692. * Watch for changes in the size of the frame. On resize, the Panel will
  3693. * automatically redraw itself.
  3694. * @private
  3695. */
  3696. RootPanel.prototype._watch = function () {
  3697. var me = this;
  3698. this._unwatch();
  3699. var checkSize = function () {
  3700. var autoResize = me.getOption('autoResize');
  3701. if (!autoResize) {
  3702. // stop watching when the option autoResize is changed to false
  3703. me._unwatch();
  3704. return;
  3705. }
  3706. if (me.frame) {
  3707. // check whether the frame is resized
  3708. if ((me.frame.clientWidth != me.width) ||
  3709. (me.frame.clientHeight != me.height)) {
  3710. me.requestReflow();
  3711. }
  3712. }
  3713. };
  3714. // TODO: automatically cleanup the event listener when the frame is deleted
  3715. util.addEventListener(window, 'resize', checkSize);
  3716. this.watchTimer = setInterval(checkSize, 1000);
  3717. };
  3718. /**
  3719. * Stop watching for a resize of the frame.
  3720. * @private
  3721. */
  3722. RootPanel.prototype._unwatch = function () {
  3723. if (this.watchTimer) {
  3724. clearInterval(this.watchTimer);
  3725. this.watchTimer = undefined;
  3726. }
  3727. // TODO: remove event listener on window.resize
  3728. };
  3729. /**
  3730. * Set controller for this component, or remove current controller by passing
  3731. * null as parameter value.
  3732. * @param {Controller | null} controller
  3733. */
  3734. RootPanel.prototype.setController = function setController (controller) {
  3735. this.controller = controller || null;
  3736. if (this.controller) {
  3737. this._registerListeners();
  3738. }
  3739. else {
  3740. this._unregisterListeners();
  3741. }
  3742. };
  3743. /**
  3744. * Register event emitters emitted by the rootpanel
  3745. * @private
  3746. */
  3747. RootPanel.prototype._registerListeners = function () {
  3748. if (this.frame && this.controller && !this.hammer) {
  3749. this.hammer = Hammer(this.frame, {
  3750. prevent_default: true
  3751. });
  3752. for (var event in this.listeners) {
  3753. if (this.listeners.hasOwnProperty(event)) {
  3754. this.hammer.on(event, this.listeners[event]);
  3755. }
  3756. }
  3757. }
  3758. };
  3759. /**
  3760. * Unregister event emitters from the rootpanel
  3761. * @private
  3762. */
  3763. RootPanel.prototype._unregisterListeners = function () {
  3764. if (this.hammer) {
  3765. for (var event in this.listeners) {
  3766. if (this.listeners.hasOwnProperty(event)) {
  3767. this.hammer.off(event, this.listeners[event]);
  3768. }
  3769. }
  3770. this.hammer = null;
  3771. }
  3772. };
  3773. /**
  3774. * A horizontal time axis
  3775. * @param {Component} parent
  3776. * @param {Component[]} [depends] Components on which this components depends
  3777. * (except for the parent)
  3778. * @param {Object} [options] See TimeAxis.setOptions for the available
  3779. * options.
  3780. * @constructor TimeAxis
  3781. * @extends Component
  3782. */
  3783. function TimeAxis (parent, depends, options) {
  3784. this.id = util.randomUUID();
  3785. this.parent = parent;
  3786. this.depends = depends;
  3787. this.dom = {
  3788. majorLines: [],
  3789. majorTexts: [],
  3790. minorLines: [],
  3791. minorTexts: [],
  3792. redundant: {
  3793. majorLines: [],
  3794. majorTexts: [],
  3795. minorLines: [],
  3796. minorTexts: []
  3797. }
  3798. };
  3799. this.props = {
  3800. range: {
  3801. start: 0,
  3802. end: 0,
  3803. minimumStep: 0
  3804. },
  3805. lineTop: 0
  3806. };
  3807. this.options = options || {};
  3808. this.defaultOptions = {
  3809. orientation: 'bottom', // supported: 'top', 'bottom'
  3810. // TODO: implement timeaxis orientations 'left' and 'right'
  3811. showMinorLabels: true,
  3812. showMajorLabels: true
  3813. };
  3814. this.conversion = null;
  3815. this.range = null;
  3816. }
  3817. TimeAxis.prototype = new Component();
  3818. // TODO: comment options
  3819. TimeAxis.prototype.setOptions = Component.prototype.setOptions;
  3820. /**
  3821. * Set a range (start and end)
  3822. * @param {Range | Object} range A Range or an object containing start and end.
  3823. */
  3824. TimeAxis.prototype.setRange = function (range) {
  3825. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  3826. throw new TypeError('Range must be an instance of Range, ' +
  3827. 'or an object containing start and end.');
  3828. }
  3829. this.range = range;
  3830. };
  3831. /**
  3832. * Convert a position on screen (pixels) to a datetime
  3833. * @param {int} x Position on the screen in pixels
  3834. * @return {Date} time The datetime the corresponds with given position x
  3835. */
  3836. TimeAxis.prototype.toTime = function(x) {
  3837. var conversion = this.conversion;
  3838. return new Date(x / conversion.scale + conversion.offset);
  3839. };
  3840. /**
  3841. * Convert a datetime (Date object) into a position on the screen
  3842. * @param {Date} time A date
  3843. * @return {int} x The position on the screen in pixels which corresponds
  3844. * with the given date.
  3845. * @private
  3846. */
  3847. TimeAxis.prototype.toScreen = function(time) {
  3848. var conversion = this.conversion;
  3849. return (time.valueOf() - conversion.offset) * conversion.scale;
  3850. };
  3851. /**
  3852. * Repaint the component
  3853. * @return {Boolean} changed
  3854. */
  3855. TimeAxis.prototype.repaint = function () {
  3856. var changed = 0,
  3857. update = util.updateProperty,
  3858. asSize = util.option.asSize,
  3859. options = this.options,
  3860. orientation = this.getOption('orientation'),
  3861. props = this.props,
  3862. step = this.step;
  3863. var frame = this.frame;
  3864. if (!frame) {
  3865. frame = document.createElement('div');
  3866. this.frame = frame;
  3867. changed += 1;
  3868. }
  3869. frame.className = 'axis';
  3870. // TODO: custom className?
  3871. if (!frame.parentNode) {
  3872. if (!this.parent) {
  3873. throw new Error('Cannot repaint time axis: no parent attached');
  3874. }
  3875. var parentContainer = this.parent.getContainer();
  3876. if (!parentContainer) {
  3877. throw new Error('Cannot repaint time axis: parent has no container element');
  3878. }
  3879. parentContainer.appendChild(frame);
  3880. changed += 1;
  3881. }
  3882. var parent = frame.parentNode;
  3883. if (parent) {
  3884. var beforeChild = frame.nextSibling;
  3885. parent.removeChild(frame); // take frame offline while updating (is almost twice as fast)
  3886. var defaultTop = (orientation == 'bottom' && this.props.parentHeight && this.height) ?
  3887. (this.props.parentHeight - this.height) + 'px' :
  3888. '0px';
  3889. changed += update(frame.style, 'top', asSize(options.top, defaultTop));
  3890. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3891. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3892. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  3893. // get characters width and height
  3894. this._repaintMeasureChars();
  3895. if (this.step) {
  3896. this._repaintStart();
  3897. step.first();
  3898. var xFirstMajorLabel = undefined;
  3899. var max = 0;
  3900. while (step.hasNext() && max < 1000) {
  3901. max++;
  3902. var cur = step.getCurrent(),
  3903. x = this.toScreen(cur),
  3904. isMajor = step.isMajor();
  3905. // TODO: lines must have a width, such that we can create css backgrounds
  3906. if (this.getOption('showMinorLabels')) {
  3907. this._repaintMinorText(x, step.getLabelMinor());
  3908. }
  3909. if (isMajor && this.getOption('showMajorLabels')) {
  3910. if (x > 0) {
  3911. if (xFirstMajorLabel == undefined) {
  3912. xFirstMajorLabel = x;
  3913. }
  3914. this._repaintMajorText(x, step.getLabelMajor());
  3915. }
  3916. this._repaintMajorLine(x);
  3917. }
  3918. else {
  3919. this._repaintMinorLine(x);
  3920. }
  3921. step.next();
  3922. }
  3923. // create a major label on the left when needed
  3924. if (this.getOption('showMajorLabels')) {
  3925. var leftTime = this.toTime(0),
  3926. leftText = step.getLabelMajor(leftTime),
  3927. widthText = leftText.length * (props.majorCharWidth || 10) + 10; // upper bound estimation
  3928. if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) {
  3929. this._repaintMajorText(0, leftText);
  3930. }
  3931. }
  3932. this._repaintEnd();
  3933. }
  3934. this._repaintLine();
  3935. // put frame online again
  3936. if (beforeChild) {
  3937. parent.insertBefore(frame, beforeChild);
  3938. }
  3939. else {
  3940. parent.appendChild(frame)
  3941. }
  3942. }
  3943. return (changed > 0);
  3944. };
  3945. /**
  3946. * Start a repaint. Move all DOM elements to a redundant list, where they
  3947. * can be picked for re-use, or can be cleaned up in the end
  3948. * @private
  3949. */
  3950. TimeAxis.prototype._repaintStart = function () {
  3951. var dom = this.dom,
  3952. redundant = dom.redundant;
  3953. redundant.majorLines = dom.majorLines;
  3954. redundant.majorTexts = dom.majorTexts;
  3955. redundant.minorLines = dom.minorLines;
  3956. redundant.minorTexts = dom.minorTexts;
  3957. dom.majorLines = [];
  3958. dom.majorTexts = [];
  3959. dom.minorLines = [];
  3960. dom.minorTexts = [];
  3961. };
  3962. /**
  3963. * End a repaint. Cleanup leftover DOM elements in the redundant list
  3964. * @private
  3965. */
  3966. TimeAxis.prototype._repaintEnd = function () {
  3967. util.forEach(this.dom.redundant, function (arr) {
  3968. while (arr.length) {
  3969. var elem = arr.pop();
  3970. if (elem && elem.parentNode) {
  3971. elem.parentNode.removeChild(elem);
  3972. }
  3973. }
  3974. });
  3975. };
  3976. /**
  3977. * Create a minor label for the axis at position x
  3978. * @param {Number} x
  3979. * @param {String} text
  3980. * @private
  3981. */
  3982. TimeAxis.prototype._repaintMinorText = function (x, text) {
  3983. // reuse redundant label
  3984. var label = this.dom.redundant.minorTexts.shift();
  3985. if (!label) {
  3986. // create new label
  3987. var content = document.createTextNode('');
  3988. label = document.createElement('div');
  3989. label.appendChild(content);
  3990. label.className = 'text minor';
  3991. this.frame.appendChild(label);
  3992. }
  3993. this.dom.minorTexts.push(label);
  3994. label.childNodes[0].nodeValue = text;
  3995. label.style.left = x + 'px';
  3996. label.style.top = this.props.minorLabelTop + 'px';
  3997. //label.title = title; // TODO: this is a heavy operation
  3998. };
  3999. /**
  4000. * Create a Major label for the axis at position x
  4001. * @param {Number} x
  4002. * @param {String} text
  4003. * @private
  4004. */
  4005. TimeAxis.prototype._repaintMajorText = function (x, text) {
  4006. // reuse redundant label
  4007. var label = this.dom.redundant.majorTexts.shift();
  4008. if (!label) {
  4009. // create label
  4010. var content = document.createTextNode(text);
  4011. label = document.createElement('div');
  4012. label.className = 'text major';
  4013. label.appendChild(content);
  4014. this.frame.appendChild(label);
  4015. }
  4016. this.dom.majorTexts.push(label);
  4017. label.childNodes[0].nodeValue = text;
  4018. label.style.top = this.props.majorLabelTop + 'px';
  4019. label.style.left = x + 'px';
  4020. //label.title = title; // TODO: this is a heavy operation
  4021. };
  4022. /**
  4023. * Create a minor line for the axis at position x
  4024. * @param {Number} x
  4025. * @private
  4026. */
  4027. TimeAxis.prototype._repaintMinorLine = function (x) {
  4028. // reuse redundant line
  4029. var line = this.dom.redundant.minorLines.shift();
  4030. if (!line) {
  4031. // create vertical line
  4032. line = document.createElement('div');
  4033. line.className = 'grid vertical minor';
  4034. this.frame.appendChild(line);
  4035. }
  4036. this.dom.minorLines.push(line);
  4037. var props = this.props;
  4038. line.style.top = props.minorLineTop + 'px';
  4039. line.style.height = props.minorLineHeight + 'px';
  4040. line.style.left = (x - props.minorLineWidth / 2) + 'px';
  4041. };
  4042. /**
  4043. * Create a Major line for the axis at position x
  4044. * @param {Number} x
  4045. * @private
  4046. */
  4047. TimeAxis.prototype._repaintMajorLine = function (x) {
  4048. // reuse redundant line
  4049. var line = this.dom.redundant.majorLines.shift();
  4050. if (!line) {
  4051. // create vertical line
  4052. line = document.createElement('DIV');
  4053. line.className = 'grid vertical major';
  4054. this.frame.appendChild(line);
  4055. }
  4056. this.dom.majorLines.push(line);
  4057. var props = this.props;
  4058. line.style.top = props.majorLineTop + 'px';
  4059. line.style.left = (x - props.majorLineWidth / 2) + 'px';
  4060. line.style.height = props.majorLineHeight + 'px';
  4061. };
  4062. /**
  4063. * Repaint the horizontal line for the axis
  4064. * @private
  4065. */
  4066. TimeAxis.prototype._repaintLine = function() {
  4067. var line = this.dom.line,
  4068. frame = this.frame,
  4069. options = this.options;
  4070. // line before all axis elements
  4071. if (this.getOption('showMinorLabels') || this.getOption('showMajorLabels')) {
  4072. if (line) {
  4073. // put this line at the end of all childs
  4074. frame.removeChild(line);
  4075. frame.appendChild(line);
  4076. }
  4077. else {
  4078. // create the axis line
  4079. line = document.createElement('div');
  4080. line.className = 'grid horizontal major';
  4081. frame.appendChild(line);
  4082. this.dom.line = line;
  4083. }
  4084. line.style.top = this.props.lineTop + 'px';
  4085. }
  4086. else {
  4087. if (line && line.parentElement) {
  4088. frame.removeChild(line.line);
  4089. delete this.dom.line;
  4090. }
  4091. }
  4092. };
  4093. /**
  4094. * Create characters used to determine the size of text on the axis
  4095. * @private
  4096. */
  4097. TimeAxis.prototype._repaintMeasureChars = function () {
  4098. // calculate the width and height of a single character
  4099. // this is used to calculate the step size, and also the positioning of the
  4100. // axis
  4101. var dom = this.dom,
  4102. text;
  4103. if (!dom.measureCharMinor) {
  4104. text = document.createTextNode('0');
  4105. var measureCharMinor = document.createElement('DIV');
  4106. measureCharMinor.className = 'text minor measure';
  4107. measureCharMinor.appendChild(text);
  4108. this.frame.appendChild(measureCharMinor);
  4109. dom.measureCharMinor = measureCharMinor;
  4110. }
  4111. if (!dom.measureCharMajor) {
  4112. text = document.createTextNode('0');
  4113. var measureCharMajor = document.createElement('DIV');
  4114. measureCharMajor.className = 'text major measure';
  4115. measureCharMajor.appendChild(text);
  4116. this.frame.appendChild(measureCharMajor);
  4117. dom.measureCharMajor = measureCharMajor;
  4118. }
  4119. };
  4120. /**
  4121. * Reflow the component
  4122. * @return {Boolean} resized
  4123. */
  4124. TimeAxis.prototype.reflow = function () {
  4125. var changed = 0,
  4126. update = util.updateProperty,
  4127. frame = this.frame,
  4128. range = this.range;
  4129. if (!range) {
  4130. throw new Error('Cannot repaint time axis: no range configured');
  4131. }
  4132. if (frame) {
  4133. changed += update(this, 'top', frame.offsetTop);
  4134. changed += update(this, 'left', frame.offsetLeft);
  4135. // calculate size of a character
  4136. var props = this.props,
  4137. showMinorLabels = this.getOption('showMinorLabels'),
  4138. showMajorLabels = this.getOption('showMajorLabels'),
  4139. measureCharMinor = this.dom.measureCharMinor,
  4140. measureCharMajor = this.dom.measureCharMajor;
  4141. if (measureCharMinor) {
  4142. props.minorCharHeight = measureCharMinor.clientHeight;
  4143. props.minorCharWidth = measureCharMinor.clientWidth;
  4144. }
  4145. if (measureCharMajor) {
  4146. props.majorCharHeight = measureCharMajor.clientHeight;
  4147. props.majorCharWidth = measureCharMajor.clientWidth;
  4148. }
  4149. var parentHeight = frame.parentNode ? frame.parentNode.offsetHeight : 0;
  4150. if (parentHeight != props.parentHeight) {
  4151. props.parentHeight = parentHeight;
  4152. changed += 1;
  4153. }
  4154. switch (this.getOption('orientation')) {
  4155. case 'bottom':
  4156. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  4157. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  4158. props.minorLabelTop = 0;
  4159. props.majorLabelTop = props.minorLabelTop + props.minorLabelHeight;
  4160. props.minorLineTop = -this.top;
  4161. props.minorLineHeight = Math.max(this.top + props.majorLabelHeight, 0);
  4162. props.minorLineWidth = 1; // TODO: really calculate width
  4163. props.majorLineTop = -this.top;
  4164. props.majorLineHeight = Math.max(this.top + props.minorLabelHeight + props.majorLabelHeight, 0);
  4165. props.majorLineWidth = 1; // TODO: really calculate width
  4166. props.lineTop = 0;
  4167. break;
  4168. case 'top':
  4169. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  4170. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  4171. props.majorLabelTop = 0;
  4172. props.minorLabelTop = props.majorLabelTop + props.majorLabelHeight;
  4173. props.minorLineTop = props.minorLabelTop;
  4174. props.minorLineHeight = Math.max(parentHeight - props.majorLabelHeight - this.top);
  4175. props.minorLineWidth = 1; // TODO: really calculate width
  4176. props.majorLineTop = 0;
  4177. props.majorLineHeight = Math.max(parentHeight - this.top);
  4178. props.majorLineWidth = 1; // TODO: really calculate width
  4179. props.lineTop = props.majorLabelHeight + props.minorLabelHeight;
  4180. break;
  4181. default:
  4182. throw new Error('Unkown orientation "' + this.getOption('orientation') + '"');
  4183. }
  4184. var height = props.minorLabelHeight + props.majorLabelHeight;
  4185. changed += update(this, 'width', frame.offsetWidth);
  4186. changed += update(this, 'height', height);
  4187. // calculate range and step
  4188. this._updateConversion();
  4189. var start = util.convert(range.start, 'Number'),
  4190. end = util.convert(range.end, 'Number'),
  4191. minimumStep = this.toTime((props.minorCharWidth || 10) * 5).valueOf()
  4192. -this.toTime(0).valueOf();
  4193. this.step = new TimeStep(new Date(start), new Date(end), minimumStep);
  4194. changed += update(props.range, 'start', start);
  4195. changed += update(props.range, 'end', end);
  4196. changed += update(props.range, 'minimumStep', minimumStep.valueOf());
  4197. }
  4198. return (changed > 0);
  4199. };
  4200. /**
  4201. * Calculate the scale and offset to convert a position on screen to the
  4202. * corresponding date and vice versa.
  4203. * After the method _updateConversion is executed once, the methods toTime
  4204. * and toScreen can be used.
  4205. * @private
  4206. */
  4207. TimeAxis.prototype._updateConversion = function() {
  4208. var range = this.range;
  4209. if (!range) {
  4210. throw new Error('No range configured');
  4211. }
  4212. if (range.conversion) {
  4213. this.conversion = range.conversion(this.width);
  4214. }
  4215. else {
  4216. this.conversion = Range.conversion(range.start, range.end, this.width);
  4217. }
  4218. };
  4219. /**
  4220. * Snap a date to a rounded value.
  4221. * The snap intervals are dependent on the current scale and step.
  4222. * @param {Date} date the date to be snapped.
  4223. * @return {Date} snappedDate
  4224. */
  4225. TimeAxis.prototype.snap = function snap (date) {
  4226. return this.step.snap(date);
  4227. };
  4228. /**
  4229. * A current time bar
  4230. * @param {Component} parent
  4231. * @param {Component[]} [depends] Components on which this components depends
  4232. * (except for the parent)
  4233. * @param {Object} [options] Available parameters:
  4234. * {Boolean} [showCurrentTime]
  4235. * @constructor CurrentTime
  4236. * @extends Component
  4237. */
  4238. function CurrentTime (parent, depends, options) {
  4239. this.id = util.randomUUID();
  4240. this.parent = parent;
  4241. this.depends = depends;
  4242. this.options = options || {};
  4243. this.defaultOptions = {
  4244. showCurrentTime: false
  4245. };
  4246. }
  4247. CurrentTime.prototype = new Component();
  4248. CurrentTime.prototype.setOptions = Component.prototype.setOptions;
  4249. /**
  4250. * Get the container element of the bar, which can be used by a child to
  4251. * add its own widgets.
  4252. * @returns {HTMLElement} container
  4253. */
  4254. CurrentTime.prototype.getContainer = function () {
  4255. return this.frame;
  4256. };
  4257. /**
  4258. * Repaint the component
  4259. * @return {Boolean} changed
  4260. */
  4261. CurrentTime.prototype.repaint = function () {
  4262. var bar = this.frame,
  4263. parent = this.parent,
  4264. parentContainer = parent.parent.getContainer();
  4265. if (!parent) {
  4266. throw new Error('Cannot repaint bar: no parent attached');
  4267. }
  4268. if (!parentContainer) {
  4269. throw new Error('Cannot repaint bar: parent has no container element');
  4270. }
  4271. if (!this.getOption('showCurrentTime')) {
  4272. if (bar) {
  4273. parentContainer.removeChild(bar);
  4274. delete this.frame;
  4275. }
  4276. return false;
  4277. }
  4278. if (!bar) {
  4279. bar = document.createElement('div');
  4280. bar.className = 'currenttime';
  4281. bar.style.position = 'absolute';
  4282. bar.style.top = '0px';
  4283. bar.style.height = '100%';
  4284. parentContainer.appendChild(bar);
  4285. this.frame = bar;
  4286. }
  4287. if (!parent.conversion) {
  4288. parent._updateConversion();
  4289. }
  4290. var now = new Date();
  4291. var x = parent.toScreen(now);
  4292. bar.style.left = x + 'px';
  4293. bar.title = 'Current time: ' + now;
  4294. // start a timer to adjust for the new time
  4295. if (this.currentTimeTimer !== undefined) {
  4296. clearTimeout(this.currentTimeTimer);
  4297. delete this.currentTimeTimer;
  4298. }
  4299. var timeline = this;
  4300. var interval = 1 / parent.conversion.scale / 2;
  4301. if (interval < 30) {
  4302. interval = 30;
  4303. }
  4304. this.currentTimeTimer = setTimeout(function() {
  4305. timeline.repaint();
  4306. }, interval);
  4307. return false;
  4308. };
  4309. /**
  4310. * A custom time bar
  4311. * @param {Component} parent
  4312. * @param {Component[]} [depends] Components on which this components depends
  4313. * (except for the parent)
  4314. * @param {Object} [options] Available parameters:
  4315. * {Boolean} [showCustomTime]
  4316. * @constructor CustomTime
  4317. * @extends Component
  4318. */
  4319. function CustomTime (parent, depends, options) {
  4320. this.id = util.randomUUID();
  4321. this.parent = parent;
  4322. this.depends = depends;
  4323. this.options = options || {};
  4324. this.defaultOptions = {
  4325. showCustomTime: false
  4326. };
  4327. this.customTime = new Date();
  4328. this.eventParams = {}; // stores state parameters while dragging the bar
  4329. }
  4330. CustomTime.prototype = new Component();
  4331. Emitter(CustomTime.prototype);
  4332. CustomTime.prototype.setOptions = Component.prototype.setOptions;
  4333. /**
  4334. * Get the container element of the bar, which can be used by a child to
  4335. * add its own widgets.
  4336. * @returns {HTMLElement} container
  4337. */
  4338. CustomTime.prototype.getContainer = function () {
  4339. return this.frame;
  4340. };
  4341. /**
  4342. * Repaint the component
  4343. * @return {Boolean} changed
  4344. */
  4345. CustomTime.prototype.repaint = function () {
  4346. var bar = this.frame,
  4347. parent = this.parent;
  4348. if (!parent) {
  4349. throw new Error('Cannot repaint bar: no parent attached');
  4350. }
  4351. var parentContainer = parent.parent.getContainer();
  4352. if (!parentContainer) {
  4353. throw new Error('Cannot repaint bar: parent has no container element');
  4354. }
  4355. if (!this.getOption('showCustomTime')) {
  4356. if (bar) {
  4357. parentContainer.removeChild(bar);
  4358. delete this.frame;
  4359. }
  4360. return false;
  4361. }
  4362. if (!bar) {
  4363. bar = document.createElement('div');
  4364. bar.className = 'customtime';
  4365. bar.style.position = 'absolute';
  4366. bar.style.top = '0px';
  4367. bar.style.height = '100%';
  4368. parentContainer.appendChild(bar);
  4369. var drag = document.createElement('div');
  4370. drag.style.position = 'relative';
  4371. drag.style.top = '0px';
  4372. drag.style.left = '-10px';
  4373. drag.style.height = '100%';
  4374. drag.style.width = '20px';
  4375. bar.appendChild(drag);
  4376. this.frame = bar;
  4377. // attach event listeners
  4378. this.hammer = Hammer(bar, {
  4379. prevent_default: true
  4380. });
  4381. this.hammer.on('dragstart', this._onDragStart.bind(this));
  4382. this.hammer.on('drag', this._onDrag.bind(this));
  4383. this.hammer.on('dragend', this._onDragEnd.bind(this));
  4384. }
  4385. if (!parent.conversion) {
  4386. parent._updateConversion();
  4387. }
  4388. var x = parent.toScreen(this.customTime);
  4389. bar.style.left = x + 'px';
  4390. bar.title = 'Time: ' + this.customTime;
  4391. return false;
  4392. };
  4393. /**
  4394. * Set custom time.
  4395. * @param {Date} time
  4396. */
  4397. CustomTime.prototype.setCustomTime = function(time) {
  4398. this.customTime = new Date(time.valueOf());
  4399. this.repaint();
  4400. };
  4401. /**
  4402. * Retrieve the current custom time.
  4403. * @return {Date} customTime
  4404. */
  4405. CustomTime.prototype.getCustomTime = function() {
  4406. return new Date(this.customTime.valueOf());
  4407. };
  4408. /**
  4409. * Start moving horizontally
  4410. * @param {Event} event
  4411. * @private
  4412. */
  4413. CustomTime.prototype._onDragStart = function(event) {
  4414. this.eventParams.customTime = this.customTime;
  4415. event.stopPropagation();
  4416. event.preventDefault();
  4417. };
  4418. /**
  4419. * Perform moving operating.
  4420. * @param {Event} event
  4421. * @private
  4422. */
  4423. CustomTime.prototype._onDrag = function (event) {
  4424. var deltaX = event.gesture.deltaX,
  4425. x = this.parent.toScreen(this.eventParams.customTime) + deltaX,
  4426. time = this.parent.toTime(x);
  4427. this.setCustomTime(time);
  4428. // fire a timechange event
  4429. if (this.controller) {
  4430. this.controller.emit('timechange', {
  4431. time: this.customTime
  4432. })
  4433. }
  4434. event.stopPropagation();
  4435. event.preventDefault();
  4436. };
  4437. /**
  4438. * Stop moving operating.
  4439. * @param {event} event
  4440. * @private
  4441. */
  4442. CustomTime.prototype._onDragEnd = function (event) {
  4443. // fire a timechanged event
  4444. if (this.controller) {
  4445. this.controller.emit('timechanged', {
  4446. time: this.customTime
  4447. })
  4448. }
  4449. event.stopPropagation();
  4450. event.preventDefault();
  4451. };
  4452. /**
  4453. * An ItemSet holds a set of items and ranges which can be displayed in a
  4454. * range. The width is determined by the parent of the ItemSet, and the height
  4455. * is determined by the size of the items.
  4456. * @param {Component} parent
  4457. * @param {Component[]} [depends] Components on which this components depends
  4458. * (except for the parent)
  4459. * @param {Object} [options] See ItemSet.setOptions for the available
  4460. * options.
  4461. * @constructor ItemSet
  4462. * @extends Panel
  4463. */
  4464. // TODO: improve performance by replacing all Array.forEach with a for loop
  4465. function ItemSet(parent, depends, options) {
  4466. this.id = util.randomUUID();
  4467. this.parent = parent;
  4468. this.depends = depends;
  4469. // event listeners
  4470. this.eventListeners = {
  4471. dragstart: this._onDragStart.bind(this),
  4472. drag: this._onDrag.bind(this),
  4473. dragend: this._onDragEnd.bind(this)
  4474. };
  4475. // one options object is shared by this itemset and all its items
  4476. this.options = options || {};
  4477. this.defaultOptions = {
  4478. type: 'box',
  4479. align: 'center',
  4480. orientation: 'bottom',
  4481. margin: {
  4482. axis: 20,
  4483. item: 10
  4484. },
  4485. padding: 5
  4486. };
  4487. this.dom = {};
  4488. var me = this;
  4489. this.itemsData = null; // DataSet
  4490. this.range = null; // Range or Object {start: number, end: number}
  4491. // data change listeners
  4492. this.listeners = {
  4493. 'add': function (event, params, senderId) {
  4494. if (senderId != me.id) {
  4495. me._onAdd(params.items);
  4496. }
  4497. },
  4498. 'update': function (event, params, senderId) {
  4499. if (senderId != me.id) {
  4500. me._onUpdate(params.items);
  4501. }
  4502. },
  4503. 'remove': function (event, params, senderId) {
  4504. if (senderId != me.id) {
  4505. me._onRemove(params.items);
  4506. }
  4507. }
  4508. };
  4509. this.items = {}; // object with an Item for every data item
  4510. this.selection = []; // list with the ids of all selected nodes
  4511. this.queue = {}; // queue with id/actions: 'add', 'update', 'delete'
  4512. this.stack = new Stack(this, Object.create(this.options));
  4513. this.conversion = null;
  4514. this.touchParams = {}; // stores properties while dragging
  4515. // TODO: ItemSet should also attach event listeners for rangechange and rangechanged, like timeaxis
  4516. }
  4517. ItemSet.prototype = new Panel();
  4518. // available item types will be registered here
  4519. ItemSet.types = {
  4520. box: ItemBox,
  4521. range: ItemRange,
  4522. rangeoverflow: ItemRangeOverflow,
  4523. point: ItemPoint
  4524. };
  4525. /**
  4526. * Set options for the ItemSet. Existing options will be extended/overwritten.
  4527. * @param {Object} [options] The following options are available:
  4528. * {String | function} [className]
  4529. * class name for the itemset
  4530. * {String} [type]
  4531. * Default type for the items. Choose from 'box'
  4532. * (default), 'point', or 'range'. The default
  4533. * Style can be overwritten by individual items.
  4534. * {String} align
  4535. * Alignment for the items, only applicable for
  4536. * ItemBox. Choose 'center' (default), 'left', or
  4537. * 'right'.
  4538. * {String} orientation
  4539. * Orientation of the item set. Choose 'top' or
  4540. * 'bottom' (default).
  4541. * {Number} margin.axis
  4542. * Margin between the axis and the items in pixels.
  4543. * Default is 20.
  4544. * {Number} margin.item
  4545. * Margin between items in pixels. Default is 10.
  4546. * {Number} padding
  4547. * Padding of the contents of an item in pixels.
  4548. * Must correspond with the items css. Default is 5.
  4549. * {Function} snap
  4550. * Function to let items snap to nice dates when
  4551. * dragging items.
  4552. */
  4553. ItemSet.prototype.setOptions = Component.prototype.setOptions;
  4554. /**
  4555. * Set controller for this component
  4556. * @param {Controller | null} controller
  4557. */
  4558. ItemSet.prototype.setController = function setController (controller) {
  4559. var event;
  4560. // unregister old event listeners
  4561. if (this.controller) {
  4562. for (event in this.eventListeners) {
  4563. if (this.eventListeners.hasOwnProperty(event)) {
  4564. this.controller.off(event, this.eventListeners[event]);
  4565. }
  4566. }
  4567. }
  4568. this.controller = controller || null;
  4569. // register new event listeners
  4570. if (this.controller) {
  4571. for (event in this.eventListeners) {
  4572. if (this.eventListeners.hasOwnProperty(event)) {
  4573. this.controller.on(event, this.eventListeners[event]);
  4574. }
  4575. }
  4576. }
  4577. };
  4578. // attach event listeners for dragging items to the controller
  4579. (function (me) {
  4580. var _controller = null;
  4581. var _onDragStart = null;
  4582. var _onDrag = null;
  4583. var _onDragEnd = null;
  4584. Object.defineProperty(me, 'controller', {
  4585. get: function () {
  4586. return _controller;
  4587. },
  4588. set: function (controller) {
  4589. }
  4590. });
  4591. }) (this);
  4592. /**
  4593. * Set range (start and end).
  4594. * @param {Range | Object} range A Range or an object containing start and end.
  4595. */
  4596. ItemSet.prototype.setRange = function setRange(range) {
  4597. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  4598. throw new TypeError('Range must be an instance of Range, ' +
  4599. 'or an object containing start and end.');
  4600. }
  4601. this.range = range;
  4602. };
  4603. /**
  4604. * Set selected items by their id. Replaces the current selection
  4605. * Unknown id's are silently ignored.
  4606. * @param {Array} [ids] An array with zero or more id's of the items to be
  4607. * selected. If ids is an empty array, all items will be
  4608. * unselected.
  4609. */
  4610. ItemSet.prototype.setSelection = function setSelection(ids) {
  4611. var i, ii, id, item, selection;
  4612. if (ids) {
  4613. if (!Array.isArray(ids)) {
  4614. throw new TypeError('Array expected');
  4615. }
  4616. // unselect currently selected items
  4617. for (i = 0, ii = this.selection.length; i < ii; i++) {
  4618. id = this.selection[i];
  4619. item = this.items[id];
  4620. if (item) item.unselect();
  4621. }
  4622. // select items
  4623. this.selection = [];
  4624. for (i = 0, ii = ids.length; i < ii; i++) {
  4625. id = ids[i];
  4626. item = this.items[id];
  4627. if (item) {
  4628. this.selection.push(id);
  4629. item.select();
  4630. }
  4631. }
  4632. if (this.controller) {
  4633. this.requestRepaint();
  4634. }
  4635. }
  4636. };
  4637. /**
  4638. * Get the selected items by their id
  4639. * @return {Array} ids The ids of the selected items
  4640. */
  4641. ItemSet.prototype.getSelection = function getSelection() {
  4642. return this.selection.concat([]);
  4643. };
  4644. /**
  4645. * Deselect a selected item
  4646. * @param {String | Number} id
  4647. * @private
  4648. */
  4649. ItemSet.prototype._deselect = function _deselect(id) {
  4650. var selection = this.selection;
  4651. for (var i = 0, ii = selection.length; i < ii; i++) {
  4652. if (selection[i] == id) { // non-strict comparison!
  4653. selection.splice(i, 1);
  4654. break;
  4655. }
  4656. }
  4657. };
  4658. /**
  4659. * Repaint the component
  4660. * @return {Boolean} changed
  4661. */
  4662. ItemSet.prototype.repaint = function repaint() {
  4663. var changed = 0,
  4664. update = util.updateProperty,
  4665. asSize = util.option.asSize,
  4666. options = this.options,
  4667. orientation = this.getOption('orientation'),
  4668. defaultOptions = this.defaultOptions,
  4669. frame = this.frame;
  4670. if (!frame) {
  4671. frame = document.createElement('div');
  4672. frame.className = 'itemset';
  4673. frame['timeline-itemset'] = this;
  4674. var className = options.className;
  4675. if (className) {
  4676. util.addClassName(frame, util.option.asString(className));
  4677. }
  4678. // create background panel
  4679. var background = document.createElement('div');
  4680. background.className = 'background';
  4681. frame.appendChild(background);
  4682. this.dom.background = background;
  4683. // create foreground panel
  4684. var foreground = document.createElement('div');
  4685. foreground.className = 'foreground';
  4686. frame.appendChild(foreground);
  4687. this.dom.foreground = foreground;
  4688. // create axis panel
  4689. var axis = document.createElement('div');
  4690. axis.className = 'itemset-axis';
  4691. //frame.appendChild(axis);
  4692. this.dom.axis = axis;
  4693. this.frame = frame;
  4694. changed += 1;
  4695. }
  4696. if (!this.parent) {
  4697. throw new Error('Cannot repaint itemset: no parent attached');
  4698. }
  4699. var parentContainer = this.parent.getContainer();
  4700. if (!parentContainer) {
  4701. throw new Error('Cannot repaint itemset: parent has no container element');
  4702. }
  4703. if (!frame.parentNode) {
  4704. parentContainer.appendChild(frame);
  4705. changed += 1;
  4706. }
  4707. if (!this.dom.axis.parentNode) {
  4708. parentContainer.appendChild(this.dom.axis);
  4709. changed += 1;
  4710. }
  4711. // reposition frame
  4712. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  4713. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  4714. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  4715. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  4716. // reposition axis
  4717. changed += update(this.dom.axis.style, 'left', asSize(options.left, '0px'));
  4718. changed += update(this.dom.axis.style, 'width', asSize(options.width, '100%'));
  4719. if (orientation == 'bottom') {
  4720. changed += update(this.dom.axis.style, 'top', (this.height + this.top) + 'px');
  4721. }
  4722. else { // orientation == 'top'
  4723. changed += update(this.dom.axis.style, 'top', this.top + 'px');
  4724. }
  4725. this._updateConversion();
  4726. var me = this,
  4727. queue = this.queue,
  4728. itemsData = this.itemsData,
  4729. items = this.items,
  4730. dataOptions = {
  4731. // TODO: cleanup
  4732. // fields: [(itemsData && itemsData.fieldId || 'id'), 'start', 'end', 'content', 'type', 'className']
  4733. };
  4734. // show/hide added/changed/removed items
  4735. for (var id in queue) {
  4736. if (queue.hasOwnProperty(id)) {
  4737. var entry = queue[id],
  4738. item = items[id],
  4739. action = entry.action;
  4740. //noinspection FallthroughInSwitchStatementJS
  4741. switch (action) {
  4742. case 'add':
  4743. case 'update':
  4744. var itemData = itemsData && itemsData.get(id, dataOptions);
  4745. if (itemData) {
  4746. var type = itemData.type ||
  4747. (itemData.start && itemData.end && 'range') ||
  4748. options.type ||
  4749. 'box';
  4750. var constructor = ItemSet.types[type];
  4751. // TODO: how to handle items with invalid data? hide them and give a warning? or throw an error?
  4752. if (item) {
  4753. // update item
  4754. if (!constructor || !(item instanceof constructor)) {
  4755. // item type has changed, hide and delete the item
  4756. changed += item.hide();
  4757. item = null;
  4758. }
  4759. else {
  4760. item.data = itemData; // TODO: create a method item.setData ?
  4761. changed++;
  4762. }
  4763. }
  4764. if (!item) {
  4765. // create item
  4766. if (constructor) {
  4767. item = new constructor(me, itemData, options, defaultOptions);
  4768. item.id = entry.id; // we take entry.id, as id itself is stringified
  4769. changed++;
  4770. }
  4771. else {
  4772. throw new TypeError('Unknown item type "' + type + '"');
  4773. }
  4774. }
  4775. // force a repaint (not only a reposition)
  4776. item.repaint();
  4777. items[id] = item;
  4778. }
  4779. // update queue
  4780. delete queue[id];
  4781. break;
  4782. case 'remove':
  4783. if (item) {
  4784. // remove the item from the set selected items
  4785. if (item.selected) {
  4786. me._deselect(id);
  4787. }
  4788. // remove DOM of the item
  4789. changed += item.hide();
  4790. }
  4791. // update lists
  4792. delete items[id];
  4793. delete queue[id];
  4794. break;
  4795. default:
  4796. console.log('Error: unknown action "' + action + '"');
  4797. }
  4798. }
  4799. }
  4800. // reposition all items. Show items only when in the visible area
  4801. util.forEach(this.items, function (item) {
  4802. if (item.visible) {
  4803. changed += item.show();
  4804. item.reposition();
  4805. }
  4806. else {
  4807. changed += item.hide();
  4808. }
  4809. });
  4810. return (changed > 0);
  4811. };
  4812. /**
  4813. * Get the foreground container element
  4814. * @return {HTMLElement} foreground
  4815. */
  4816. ItemSet.prototype.getForeground = function getForeground() {
  4817. return this.dom.foreground;
  4818. };
  4819. /**
  4820. * Get the background container element
  4821. * @return {HTMLElement} background
  4822. */
  4823. ItemSet.prototype.getBackground = function getBackground() {
  4824. return this.dom.background;
  4825. };
  4826. /**
  4827. * Get the axis container element
  4828. * @return {HTMLElement} axis
  4829. */
  4830. ItemSet.prototype.getAxis = function getAxis() {
  4831. return this.dom.axis;
  4832. };
  4833. /**
  4834. * Reflow the component
  4835. * @return {Boolean} resized
  4836. */
  4837. ItemSet.prototype.reflow = function reflow () {
  4838. var changed = 0,
  4839. options = this.options,
  4840. marginAxis = (options.margin && 'axis' in options.margin) ? options.margin.axis : this.defaultOptions.margin.axis,
  4841. marginItem = (options.margin && 'item' in options.margin) ? options.margin.item : this.defaultOptions.margin.item,
  4842. update = util.updateProperty,
  4843. asNumber = util.option.asNumber,
  4844. asSize = util.option.asSize,
  4845. frame = this.frame;
  4846. if (frame) {
  4847. this._updateConversion();
  4848. util.forEach(this.items, function (item) {
  4849. changed += item.reflow();
  4850. });
  4851. // TODO: stack.update should be triggered via an event, in stack itself
  4852. // TODO: only update the stack when there are changed items
  4853. this.stack.update();
  4854. var maxHeight = asNumber(options.maxHeight);
  4855. var fixedHeight = (asSize(options.height) != null);
  4856. var height;
  4857. if (fixedHeight) {
  4858. height = frame.offsetHeight;
  4859. }
  4860. else {
  4861. // height is not specified, determine the height from the height and positioned items
  4862. var visibleItems = this.stack.ordered; // TODO: not so nice way to get the filtered items
  4863. if (visibleItems.length) {
  4864. var min = visibleItems[0].top;
  4865. var max = visibleItems[0].top + visibleItems[0].height;
  4866. util.forEach(visibleItems, function (item) {
  4867. min = Math.min(min, item.top);
  4868. max = Math.max(max, (item.top + item.height));
  4869. });
  4870. height = (max - min) + marginAxis + marginItem;
  4871. }
  4872. else {
  4873. height = marginAxis + marginItem;
  4874. }
  4875. }
  4876. if (maxHeight != null) {
  4877. height = Math.min(height, maxHeight);
  4878. }
  4879. changed += update(this, 'height', height);
  4880. // calculate height from items
  4881. changed += update(this, 'top', frame.offsetTop);
  4882. changed += update(this, 'left', frame.offsetLeft);
  4883. changed += update(this, 'width', frame.offsetWidth);
  4884. }
  4885. else {
  4886. changed += 1;
  4887. }
  4888. return (changed > 0);
  4889. };
  4890. /**
  4891. * Hide this component from the DOM
  4892. * @return {Boolean} changed
  4893. */
  4894. ItemSet.prototype.hide = function hide() {
  4895. var changed = false;
  4896. // remove the DOM
  4897. if (this.frame && this.frame.parentNode) {
  4898. this.frame.parentNode.removeChild(this.frame);
  4899. changed = true;
  4900. }
  4901. if (this.dom.axis && this.dom.axis.parentNode) {
  4902. this.dom.axis.parentNode.removeChild(this.dom.axis);
  4903. changed = true;
  4904. }
  4905. return changed;
  4906. };
  4907. /**
  4908. * Set items
  4909. * @param {vis.DataSet | null} items
  4910. */
  4911. ItemSet.prototype.setItems = function setItems(items) {
  4912. var me = this,
  4913. ids,
  4914. oldItemsData = this.itemsData;
  4915. // replace the dataset
  4916. if (!items) {
  4917. this.itemsData = null;
  4918. }
  4919. else if (items instanceof DataSet || items instanceof DataView) {
  4920. this.itemsData = items;
  4921. }
  4922. else {
  4923. throw new TypeError('Data must be an instance of DataSet');
  4924. }
  4925. if (oldItemsData) {
  4926. // unsubscribe from old dataset
  4927. util.forEach(this.listeners, function (callback, event) {
  4928. oldItemsData.unsubscribe(event, callback);
  4929. });
  4930. // remove all drawn items
  4931. ids = oldItemsData.getIds();
  4932. this._onRemove(ids);
  4933. }
  4934. if (this.itemsData) {
  4935. // subscribe to new dataset
  4936. var id = this.id;
  4937. util.forEach(this.listeners, function (callback, event) {
  4938. me.itemsData.on(event, callback, id);
  4939. });
  4940. // draw all new items
  4941. ids = this.itemsData.getIds();
  4942. this._onAdd(ids);
  4943. }
  4944. };
  4945. /**
  4946. * Get the current items items
  4947. * @returns {vis.DataSet | null}
  4948. */
  4949. ItemSet.prototype.getItems = function getItems() {
  4950. return this.itemsData;
  4951. };
  4952. /**
  4953. * Remove an item by its id
  4954. * @param {String | Number} id
  4955. */
  4956. ItemSet.prototype.removeItem = function removeItem (id) {
  4957. var item = this.itemsData.get(id),
  4958. dataset = this._myDataSet();
  4959. if (item) {
  4960. // confirm deletion
  4961. this.options.onRemove(item, function (item) {
  4962. if (item) {
  4963. dataset.remove(item);
  4964. }
  4965. });
  4966. }
  4967. };
  4968. /**
  4969. * Handle updated items
  4970. * @param {Number[]} ids
  4971. * @private
  4972. */
  4973. ItemSet.prototype._onUpdate = function _onUpdate(ids) {
  4974. this._toQueue('update', ids);
  4975. };
  4976. /**
  4977. * Handle changed items
  4978. * @param {Number[]} ids
  4979. * @private
  4980. */
  4981. ItemSet.prototype._onAdd = function _onAdd(ids) {
  4982. this._toQueue('add', ids);
  4983. };
  4984. /**
  4985. * Handle removed items
  4986. * @param {Number[]} ids
  4987. * @private
  4988. */
  4989. ItemSet.prototype._onRemove = function _onRemove(ids) {
  4990. this._toQueue('remove', ids);
  4991. };
  4992. /**
  4993. * Put items in the queue to be added/updated/remove
  4994. * @param {String} action can be 'add', 'update', 'remove'
  4995. * @param {Number[]} ids
  4996. */
  4997. ItemSet.prototype._toQueue = function _toQueue(action, ids) {
  4998. var queue = this.queue;
  4999. ids.forEach(function (id) {
  5000. queue[id] = {
  5001. id: id,
  5002. action: action
  5003. };
  5004. });
  5005. if (this.controller) {
  5006. //this.requestReflow();
  5007. this.requestRepaint();
  5008. }
  5009. };
  5010. /**
  5011. * Calculate the scale and offset to convert a position on screen to the
  5012. * corresponding date and vice versa.
  5013. * After the method _updateConversion is executed once, the methods toTime
  5014. * and toScreen can be used.
  5015. * @private
  5016. */
  5017. ItemSet.prototype._updateConversion = function _updateConversion() {
  5018. var range = this.range;
  5019. if (!range) {
  5020. throw new Error('No range configured');
  5021. }
  5022. if (range.conversion) {
  5023. this.conversion = range.conversion(this.width);
  5024. }
  5025. else {
  5026. this.conversion = Range.conversion(range.start, range.end, this.width);
  5027. }
  5028. };
  5029. /**
  5030. * Convert a position on screen (pixels) to a datetime
  5031. * Before this method can be used, the method _updateConversion must be
  5032. * executed once.
  5033. * @param {int} x Position on the screen in pixels
  5034. * @return {Date} time The datetime the corresponds with given position x
  5035. */
  5036. ItemSet.prototype.toTime = function toTime(x) {
  5037. var conversion = this.conversion;
  5038. return new Date(x / conversion.scale + conversion.offset);
  5039. };
  5040. /**
  5041. * Convert a datetime (Date object) into a position on the screen
  5042. * Before this method can be used, the method _updateConversion must be
  5043. * executed once.
  5044. * @param {Date} time A date
  5045. * @return {int} x The position on the screen in pixels which corresponds
  5046. * with the given date.
  5047. */
  5048. ItemSet.prototype.toScreen = function toScreen(time) {
  5049. var conversion = this.conversion;
  5050. return (time.valueOf() - conversion.offset) * conversion.scale;
  5051. };
  5052. /**
  5053. * Start dragging the selected events
  5054. * @param {Event} event
  5055. * @private
  5056. */
  5057. ItemSet.prototype._onDragStart = function (event) {
  5058. if (!this.options.editable) {
  5059. return;
  5060. }
  5061. var item = ItemSet.itemFromTarget(event),
  5062. me = this;
  5063. if (item && item.selected) {
  5064. var dragLeftItem = event.target.dragLeftItem;
  5065. var dragRightItem = event.target.dragRightItem;
  5066. if (dragLeftItem) {
  5067. this.touchParams.itemProps = [{
  5068. item: dragLeftItem,
  5069. start: item.data.start.valueOf()
  5070. }];
  5071. }
  5072. else if (dragRightItem) {
  5073. this.touchParams.itemProps = [{
  5074. item: dragRightItem,
  5075. end: item.data.end.valueOf()
  5076. }];
  5077. }
  5078. else {
  5079. this.touchParams.itemProps = this.getSelection().map(function (id) {
  5080. var item = me.items[id];
  5081. var props = {
  5082. item: item
  5083. };
  5084. if ('start' in item.data) {
  5085. props.start = item.data.start.valueOf()
  5086. }
  5087. if ('end' in item.data) {
  5088. props.end = item.data.end.valueOf()
  5089. }
  5090. return props;
  5091. });
  5092. }
  5093. event.stopPropagation();
  5094. }
  5095. };
  5096. /**
  5097. * Drag selected items
  5098. * @param {Event} event
  5099. * @private
  5100. */
  5101. ItemSet.prototype._onDrag = function (event) {
  5102. if (this.touchParams.itemProps) {
  5103. var snap = this.options.snap || null,
  5104. deltaX = event.gesture.deltaX,
  5105. offset = deltaX / this.conversion.scale;
  5106. // move
  5107. this.touchParams.itemProps.forEach(function (props) {
  5108. if ('start' in props) {
  5109. var start = new Date(props.start + offset);
  5110. props.item.data.start = snap ? snap(start) : start;
  5111. }
  5112. if ('end' in props) {
  5113. var end = new Date(props.end + offset);
  5114. props.item.data.end = snap ? snap(end) : end;
  5115. }
  5116. });
  5117. // TODO: implement onMoving handler
  5118. // TODO: implement dragging from one group to another
  5119. this.requestReflow();
  5120. event.stopPropagation();
  5121. }
  5122. };
  5123. /**
  5124. * End of dragging selected items
  5125. * @param {Event} event
  5126. * @private
  5127. */
  5128. ItemSet.prototype._onDragEnd = function (event) {
  5129. if (this.touchParams.itemProps) {
  5130. // prepare a change set for the changed items
  5131. var changes = [],
  5132. me = this,
  5133. dataset = this._myDataSet(),
  5134. type;
  5135. this.touchParams.itemProps.forEach(function (props) {
  5136. var id = props.item.id,
  5137. item = me.itemsData.get(id);
  5138. var changed = false;
  5139. if ('start' in props.item.data) {
  5140. changed = (props.start != props.item.data.start.valueOf());
  5141. item.start = util.convert(props.item.data.start, dataset.convert['start']);
  5142. }
  5143. if ('end' in props.item.data) {
  5144. changed = changed || (props.end != props.item.data.end.valueOf());
  5145. item.end = util.convert(props.item.data.end, dataset.convert['end']);
  5146. }
  5147. // only apply changes when start or end is actually changed
  5148. if (changed) {
  5149. me.options.onMove(item, function (item) {
  5150. if (item) {
  5151. // apply changes
  5152. changes.push(item);
  5153. }
  5154. else {
  5155. // restore original values
  5156. if ('start' in props) props.item.data.start = props.start;
  5157. if ('end' in props) props.item.data.end = props.end;
  5158. me.requestReflow();
  5159. }
  5160. });
  5161. }
  5162. });
  5163. this.touchParams.itemProps = null;
  5164. // apply the changes to the data (if there are changes)
  5165. if (changes.length) {
  5166. dataset.update(changes);
  5167. }
  5168. event.stopPropagation();
  5169. }
  5170. };
  5171. /**
  5172. * Find an item from an event target:
  5173. * searches for the attribute 'timeline-item' in the event target's element tree
  5174. * @param {Event} event
  5175. * @return {Item | null} item
  5176. */
  5177. ItemSet.itemFromTarget = function itemFromTarget (event) {
  5178. var target = event.target;
  5179. while (target) {
  5180. if (target.hasOwnProperty('timeline-item')) {
  5181. return target['timeline-item'];
  5182. }
  5183. target = target.parentNode;
  5184. }
  5185. return null;
  5186. };
  5187. /**
  5188. * Find the ItemSet from an event target:
  5189. * searches for the attribute 'timeline-itemset' in the event target's element tree
  5190. * @param {Event} event
  5191. * @return {ItemSet | null} item
  5192. */
  5193. ItemSet.itemSetFromTarget = function itemSetFromTarget (event) {
  5194. var target = event.target;
  5195. while (target) {
  5196. if (target.hasOwnProperty('timeline-itemset')) {
  5197. return target['timeline-itemset'];
  5198. }
  5199. target = target.parentNode;
  5200. }
  5201. return null;
  5202. };
  5203. /**
  5204. * Find the DataSet to which this ItemSet is connected
  5205. * @returns {null | DataSet} dataset
  5206. * @private
  5207. */
  5208. ItemSet.prototype._myDataSet = function _myDataSet() {
  5209. // find the root DataSet
  5210. var dataset = this.itemsData;
  5211. while (dataset instanceof DataView) {
  5212. dataset = dataset.data;
  5213. }
  5214. return dataset;
  5215. };
  5216. /**
  5217. * @constructor Item
  5218. * @param {ItemSet} parent
  5219. * @param {Object} data Object containing (optional) parameters type,
  5220. * start, end, content, group, className.
  5221. * @param {Object} [options] Options to set initial property values
  5222. * @param {Object} [defaultOptions] default options
  5223. * // TODO: describe available options
  5224. */
  5225. function Item (parent, data, options, defaultOptions) {
  5226. this.parent = parent;
  5227. this.data = data;
  5228. this.dom = null;
  5229. this.options = options || {};
  5230. this.defaultOptions = defaultOptions || {};
  5231. this.selected = false;
  5232. this.visible = false;
  5233. this.top = 0;
  5234. this.left = 0;
  5235. this.width = 0;
  5236. this.height = 0;
  5237. this.offset = 0;
  5238. }
  5239. /**
  5240. * Select current item
  5241. */
  5242. Item.prototype.select = function select() {
  5243. this.selected = true;
  5244. if (this.visible) this.repaint();
  5245. };
  5246. /**
  5247. * Unselect current item
  5248. */
  5249. Item.prototype.unselect = function unselect() {
  5250. this.selected = false;
  5251. if (this.visible) this.repaint();
  5252. };
  5253. /**
  5254. * Show the Item in the DOM (when not already visible)
  5255. * @return {Boolean} changed
  5256. */
  5257. Item.prototype.show = function show() {
  5258. return false;
  5259. };
  5260. /**
  5261. * Hide the Item from the DOM (when visible)
  5262. * @return {Boolean} changed
  5263. */
  5264. Item.prototype.hide = function hide() {
  5265. return false;
  5266. };
  5267. /**
  5268. * Repaint the item
  5269. * @return {Boolean} changed
  5270. */
  5271. Item.prototype.repaint = function repaint() {
  5272. // should be implemented by the item
  5273. return false;
  5274. };
  5275. /**
  5276. * Reflow the item
  5277. * @return {Boolean} resized
  5278. */
  5279. Item.prototype.reflow = function reflow() {
  5280. // should be implemented by the item
  5281. return false;
  5282. };
  5283. /**
  5284. * Give the item a display offset in pixels
  5285. * @param {Number} offset Offset on screen in pixels
  5286. */
  5287. Item.prototype.setOffset = function setOffset(offset) {
  5288. this.offset = offset;
  5289. };
  5290. /**
  5291. * Repaint a delete button on the top right of the item when the item is selected
  5292. * @param {HTMLElement} anchor
  5293. * @private
  5294. */
  5295. Item.prototype._repaintDeleteButton = function (anchor) {
  5296. if (this.selected && this.options.editable && !this.dom.deleteButton) {
  5297. // create and show button
  5298. var parent = this.parent;
  5299. var id = this.id;
  5300. var deleteButton = document.createElement('div');
  5301. deleteButton.className = 'delete';
  5302. deleteButton.title = 'Delete this item';
  5303. Hammer(deleteButton, {
  5304. preventDefault: true
  5305. }).on('tap', function (event) {
  5306. parent.removeItem(id);
  5307. event.stopPropagation();
  5308. });
  5309. anchor.appendChild(deleteButton);
  5310. this.dom.deleteButton = deleteButton;
  5311. }
  5312. else if (!this.selected && this.dom.deleteButton) {
  5313. // remove button
  5314. if (this.dom.deleteButton.parentNode) {
  5315. this.dom.deleteButton.parentNode.removeChild(this.dom.deleteButton);
  5316. }
  5317. this.dom.deleteButton = null;
  5318. }
  5319. };
  5320. /**
  5321. * @constructor ItemBox
  5322. * @extends Item
  5323. * @param {ItemSet} parent
  5324. * @param {Object} data Object containing parameters start
  5325. * content, className.
  5326. * @param {Object} [options] Options to set initial property values
  5327. * @param {Object} [defaultOptions] default options
  5328. * // TODO: describe available options
  5329. */
  5330. function ItemBox (parent, data, options, defaultOptions) {
  5331. this.props = {
  5332. dot: {
  5333. left: 0,
  5334. top: 0,
  5335. width: 0,
  5336. height: 0
  5337. },
  5338. line: {
  5339. top: 0,
  5340. left: 0,
  5341. width: 0,
  5342. height: 0
  5343. }
  5344. };
  5345. Item.call(this, parent, data, options, defaultOptions);
  5346. }
  5347. ItemBox.prototype = new Item (null, null);
  5348. /**
  5349. * Repaint the item
  5350. * @return {Boolean} changed
  5351. */
  5352. ItemBox.prototype.repaint = function repaint() {
  5353. // TODO: make an efficient repaint
  5354. var changed = false;
  5355. var dom = this.dom;
  5356. if (!dom) {
  5357. this._create();
  5358. dom = this.dom;
  5359. changed = true;
  5360. }
  5361. if (dom) {
  5362. if (!this.parent) {
  5363. throw new Error('Cannot repaint item: no parent attached');
  5364. }
  5365. if (!dom.box.parentNode) {
  5366. var foreground = this.parent.getForeground();
  5367. if (!foreground) {
  5368. throw new Error('Cannot repaint time axis: ' +
  5369. 'parent has no foreground container element');
  5370. }
  5371. foreground.appendChild(dom.box);
  5372. changed = true;
  5373. }
  5374. if (!dom.line.parentNode) {
  5375. var background = this.parent.getBackground();
  5376. if (!background) {
  5377. throw new Error('Cannot repaint time axis: ' +
  5378. 'parent has no background container element');
  5379. }
  5380. background.appendChild(dom.line);
  5381. changed = true;
  5382. }
  5383. if (!dom.dot.parentNode) {
  5384. var axis = this.parent.getAxis();
  5385. if (!background) {
  5386. throw new Error('Cannot repaint time axis: ' +
  5387. 'parent has no axis container element');
  5388. }
  5389. axis.appendChild(dom.dot);
  5390. changed = true;
  5391. }
  5392. this._repaintDeleteButton(dom.box);
  5393. // update contents
  5394. if (this.data.content != this.content) {
  5395. this.content = this.data.content;
  5396. if (this.content instanceof Element) {
  5397. dom.content.innerHTML = '';
  5398. dom.content.appendChild(this.content);
  5399. }
  5400. else if (this.data.content != undefined) {
  5401. dom.content.innerHTML = this.content;
  5402. }
  5403. else {
  5404. throw new Error('Property "content" missing in item ' + this.data.id);
  5405. }
  5406. changed = true;
  5407. }
  5408. // update class
  5409. var className = (this.data.className? ' ' + this.data.className : '') +
  5410. (this.selected ? ' selected' : '');
  5411. if (this.className != className) {
  5412. this.className = className;
  5413. dom.box.className = 'item box' + className;
  5414. dom.line.className = 'item line' + className;
  5415. dom.dot.className = 'item dot' + className;
  5416. changed = true;
  5417. }
  5418. }
  5419. return changed;
  5420. };
  5421. /**
  5422. * Show the item in the DOM (when not already visible). The items DOM will
  5423. * be created when needed.
  5424. * @return {Boolean} changed
  5425. */
  5426. ItemBox.prototype.show = function show() {
  5427. if (!this.dom || !this.dom.box.parentNode) {
  5428. return this.repaint();
  5429. }
  5430. else {
  5431. return false;
  5432. }
  5433. };
  5434. /**
  5435. * Hide the item from the DOM (when visible)
  5436. * @return {Boolean} changed
  5437. */
  5438. ItemBox.prototype.hide = function hide() {
  5439. var changed = false,
  5440. dom = this.dom;
  5441. if (dom) {
  5442. if (dom.box.parentNode) {
  5443. dom.box.parentNode.removeChild(dom.box);
  5444. changed = true;
  5445. }
  5446. if (dom.line.parentNode) {
  5447. dom.line.parentNode.removeChild(dom.line);
  5448. }
  5449. if (dom.dot.parentNode) {
  5450. dom.dot.parentNode.removeChild(dom.dot);
  5451. }
  5452. }
  5453. return changed;
  5454. };
  5455. /**
  5456. * Reflow the item: calculate its actual size and position from the DOM
  5457. * @return {boolean} resized returns true if the axis is resized
  5458. * @override
  5459. */
  5460. ItemBox.prototype.reflow = function reflow() {
  5461. var changed = 0,
  5462. update,
  5463. dom,
  5464. props,
  5465. options,
  5466. margin,
  5467. start,
  5468. align,
  5469. orientation,
  5470. top,
  5471. left,
  5472. data,
  5473. range;
  5474. if (this.data.start == undefined) {
  5475. throw new Error('Property "start" missing in item ' + this.data.id);
  5476. }
  5477. data = this.data;
  5478. range = this.parent && this.parent.range;
  5479. if (data && range) {
  5480. // TODO: account for the width of the item
  5481. var interval = (range.end - range.start);
  5482. this.visible = (data.start > range.start - interval) && (data.start < range.end + interval);
  5483. }
  5484. else {
  5485. this.visible = false;
  5486. }
  5487. if (this.visible) {
  5488. dom = this.dom;
  5489. if (dom) {
  5490. update = util.updateProperty;
  5491. props = this.props;
  5492. options = this.options;
  5493. start = this.parent.toScreen(this.data.start) + this.offset;
  5494. align = options.align || this.defaultOptions.align;
  5495. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  5496. orientation = options.orientation || this.defaultOptions.orientation;
  5497. changed += update(props.dot, 'height', dom.dot.offsetHeight);
  5498. changed += update(props.dot, 'width', dom.dot.offsetWidth);
  5499. changed += update(props.line, 'width', dom.line.offsetWidth);
  5500. changed += update(props.line, 'height', dom.line.offsetHeight);
  5501. changed += update(props.line, 'top', dom.line.offsetTop);
  5502. changed += update(this, 'width', dom.box.offsetWidth);
  5503. changed += update(this, 'height', dom.box.offsetHeight);
  5504. if (align == 'right') {
  5505. left = start - this.width;
  5506. }
  5507. else if (align == 'left') {
  5508. left = start;
  5509. }
  5510. else {
  5511. // default or 'center'
  5512. left = start - this.width / 2;
  5513. }
  5514. changed += update(this, 'left', left);
  5515. changed += update(props.line, 'left', start - props.line.width / 2);
  5516. changed += update(props.dot, 'left', start - props.dot.width / 2);
  5517. changed += update(props.dot, 'top', -props.dot.height / 2);
  5518. if (orientation == 'top') {
  5519. top = margin;
  5520. changed += update(this, 'top', top);
  5521. }
  5522. else {
  5523. // default or 'bottom'
  5524. var parentHeight = this.parent.height;
  5525. top = parentHeight - this.height - margin;
  5526. changed += update(this, 'top', top);
  5527. }
  5528. }
  5529. else {
  5530. changed += 1;
  5531. }
  5532. }
  5533. return (changed > 0);
  5534. };
  5535. /**
  5536. * Create an items DOM
  5537. * @private
  5538. */
  5539. ItemBox.prototype._create = function _create() {
  5540. var dom = this.dom;
  5541. if (!dom) {
  5542. this.dom = dom = {};
  5543. // create the box
  5544. dom.box = document.createElement('DIV');
  5545. // className is updated in repaint()
  5546. // contents box (inside the background box). used for making margins
  5547. dom.content = document.createElement('DIV');
  5548. dom.content.className = 'content';
  5549. dom.box.appendChild(dom.content);
  5550. // line to axis
  5551. dom.line = document.createElement('DIV');
  5552. dom.line.className = 'line';
  5553. // dot on axis
  5554. dom.dot = document.createElement('DIV');
  5555. dom.dot.className = 'dot';
  5556. // attach this item as attribute
  5557. dom.box['timeline-item'] = this;
  5558. }
  5559. };
  5560. /**
  5561. * Reposition the item, recalculate its left, top, and width, using the current
  5562. * range and size of the items itemset
  5563. * @override
  5564. */
  5565. ItemBox.prototype.reposition = function reposition() {
  5566. var dom = this.dom,
  5567. props = this.props,
  5568. orientation = this.options.orientation || this.defaultOptions.orientation;
  5569. if (dom) {
  5570. var box = dom.box,
  5571. line = dom.line,
  5572. dot = dom.dot;
  5573. box.style.left = this.left + 'px';
  5574. box.style.top = this.top + 'px';
  5575. line.style.left = props.line.left + 'px';
  5576. if (orientation == 'top') {
  5577. line.style.top = 0 + 'px';
  5578. line.style.height = this.top + 'px';
  5579. }
  5580. else {
  5581. // orientation 'bottom'
  5582. line.style.top = (this.top + this.height) + 'px';
  5583. line.style.height = Math.max(this.parent.height - this.top - this.height +
  5584. this.props.dot.height / 2, 0) + 'px';
  5585. }
  5586. dot.style.left = props.dot.left + 'px';
  5587. dot.style.top = props.dot.top + 'px';
  5588. }
  5589. };
  5590. /**
  5591. * @constructor ItemPoint
  5592. * @extends Item
  5593. * @param {ItemSet} parent
  5594. * @param {Object} data Object containing parameters start
  5595. * content, className.
  5596. * @param {Object} [options] Options to set initial property values
  5597. * @param {Object} [defaultOptions] default options
  5598. * // TODO: describe available options
  5599. */
  5600. function ItemPoint (parent, data, options, defaultOptions) {
  5601. this.props = {
  5602. dot: {
  5603. top: 0,
  5604. width: 0,
  5605. height: 0
  5606. },
  5607. content: {
  5608. height: 0,
  5609. marginLeft: 0
  5610. }
  5611. };
  5612. Item.call(this, parent, data, options, defaultOptions);
  5613. }
  5614. ItemPoint.prototype = new Item (null, null);
  5615. /**
  5616. * Repaint the item
  5617. * @return {Boolean} changed
  5618. */
  5619. ItemPoint.prototype.repaint = function repaint() {
  5620. // TODO: make an efficient repaint
  5621. var changed = false;
  5622. var dom = this.dom;
  5623. if (!dom) {
  5624. this._create();
  5625. dom = this.dom;
  5626. changed = true;
  5627. }
  5628. if (dom) {
  5629. if (!this.parent) {
  5630. throw new Error('Cannot repaint item: no parent attached');
  5631. }
  5632. var foreground = this.parent.getForeground();
  5633. if (!foreground) {
  5634. throw new Error('Cannot repaint time axis: ' +
  5635. 'parent has no foreground container element');
  5636. }
  5637. if (!dom.point.parentNode) {
  5638. foreground.appendChild(dom.point);
  5639. foreground.appendChild(dom.point);
  5640. changed = true;
  5641. }
  5642. // update contents
  5643. if (this.data.content != this.content) {
  5644. this.content = this.data.content;
  5645. if (this.content instanceof Element) {
  5646. dom.content.innerHTML = '';
  5647. dom.content.appendChild(this.content);
  5648. }
  5649. else if (this.data.content != undefined) {
  5650. dom.content.innerHTML = this.content;
  5651. }
  5652. else {
  5653. throw new Error('Property "content" missing in item ' + this.data.id);
  5654. }
  5655. changed = true;
  5656. }
  5657. this._repaintDeleteButton(dom.point);
  5658. // update class
  5659. var className = (this.data.className? ' ' + this.data.className : '') +
  5660. (this.selected ? ' selected' : '');
  5661. if (this.className != className) {
  5662. this.className = className;
  5663. dom.point.className = 'item point' + className;
  5664. changed = true;
  5665. }
  5666. }
  5667. return changed;
  5668. };
  5669. /**
  5670. * Show the item in the DOM (when not already visible). The items DOM will
  5671. * be created when needed.
  5672. * @return {Boolean} changed
  5673. */
  5674. ItemPoint.prototype.show = function show() {
  5675. if (!this.dom || !this.dom.point.parentNode) {
  5676. return this.repaint();
  5677. }
  5678. else {
  5679. return false;
  5680. }
  5681. };
  5682. /**
  5683. * Hide the item from the DOM (when visible)
  5684. * @return {Boolean} changed
  5685. */
  5686. ItemPoint.prototype.hide = function hide() {
  5687. var changed = false,
  5688. dom = this.dom;
  5689. if (dom) {
  5690. if (dom.point.parentNode) {
  5691. dom.point.parentNode.removeChild(dom.point);
  5692. changed = true;
  5693. }
  5694. }
  5695. return changed;
  5696. };
  5697. /**
  5698. * Reflow the item: calculate its actual size from the DOM
  5699. * @return {boolean} resized returns true if the axis is resized
  5700. * @override
  5701. */
  5702. ItemPoint.prototype.reflow = function reflow() {
  5703. var changed = 0,
  5704. update,
  5705. dom,
  5706. props,
  5707. options,
  5708. margin,
  5709. orientation,
  5710. start,
  5711. top,
  5712. data,
  5713. range;
  5714. if (this.data.start == undefined) {
  5715. throw new Error('Property "start" missing in item ' + this.data.id);
  5716. }
  5717. data = this.data;
  5718. range = this.parent && this.parent.range;
  5719. if (data && range) {
  5720. // TODO: account for the width of the item
  5721. var interval = (range.end - range.start);
  5722. this.visible = (data.start > range.start - interval) && (data.start < range.end);
  5723. }
  5724. else {
  5725. this.visible = false;
  5726. }
  5727. if (this.visible) {
  5728. dom = this.dom;
  5729. if (dom) {
  5730. update = util.updateProperty;
  5731. props = this.props;
  5732. options = this.options;
  5733. orientation = options.orientation || this.defaultOptions.orientation;
  5734. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  5735. start = this.parent.toScreen(this.data.start) + this.offset;
  5736. changed += update(this, 'width', dom.point.offsetWidth);
  5737. changed += update(this, 'height', dom.point.offsetHeight);
  5738. changed += update(props.dot, 'width', dom.dot.offsetWidth);
  5739. changed += update(props.dot, 'height', dom.dot.offsetHeight);
  5740. changed += update(props.content, 'height', dom.content.offsetHeight);
  5741. if (orientation == 'top') {
  5742. top = margin;
  5743. }
  5744. else {
  5745. // default or 'bottom'
  5746. var parentHeight = this.parent.height;
  5747. top = Math.max(parentHeight - this.height - margin, 0);
  5748. }
  5749. changed += update(this, 'top', top);
  5750. changed += update(this, 'left', start - props.dot.width / 2);
  5751. changed += update(props.content, 'marginLeft', 1.5 * props.dot.width);
  5752. //changed += update(props.content, 'marginRight', 0.5 * props.dot.width); // TODO
  5753. changed += update(props.dot, 'top', (this.height - props.dot.height) / 2);
  5754. }
  5755. else {
  5756. changed += 1;
  5757. }
  5758. }
  5759. return (changed > 0);
  5760. };
  5761. /**
  5762. * Create an items DOM
  5763. * @private
  5764. */
  5765. ItemPoint.prototype._create = function _create() {
  5766. var dom = this.dom;
  5767. if (!dom) {
  5768. this.dom = dom = {};
  5769. // background box
  5770. dom.point = document.createElement('div');
  5771. // className is updated in repaint()
  5772. // contents box, right from the dot
  5773. dom.content = document.createElement('div');
  5774. dom.content.className = 'content';
  5775. dom.point.appendChild(dom.content);
  5776. // dot at start
  5777. dom.dot = document.createElement('div');
  5778. dom.dot.className = 'dot';
  5779. dom.point.appendChild(dom.dot);
  5780. // attach this item as attribute
  5781. dom.point['timeline-item'] = this;
  5782. }
  5783. };
  5784. /**
  5785. * Reposition the item, recalculate its left, top, and width, using the current
  5786. * range and size of the items itemset
  5787. * @override
  5788. */
  5789. ItemPoint.prototype.reposition = function reposition() {
  5790. var dom = this.dom,
  5791. props = this.props;
  5792. if (dom) {
  5793. dom.point.style.top = this.top + 'px';
  5794. dom.point.style.left = this.left + 'px';
  5795. dom.content.style.marginLeft = props.content.marginLeft + 'px';
  5796. //dom.content.style.marginRight = props.content.marginRight + 'px'; // TODO
  5797. dom.dot.style.top = props.dot.top + 'px';
  5798. }
  5799. };
  5800. /**
  5801. * @constructor ItemRange
  5802. * @extends Item
  5803. * @param {ItemSet} parent
  5804. * @param {Object} data Object containing parameters start, end
  5805. * content, className.
  5806. * @param {Object} [options] Options to set initial property values
  5807. * @param {Object} [defaultOptions] default options
  5808. * // TODO: describe available options
  5809. */
  5810. function ItemRange (parent, data, options, defaultOptions) {
  5811. this.props = {
  5812. content: {
  5813. left: 0,
  5814. width: 0
  5815. }
  5816. };
  5817. Item.call(this, parent, data, options, defaultOptions);
  5818. }
  5819. ItemRange.prototype = new Item (null, null);
  5820. /**
  5821. * Repaint the item
  5822. * @return {Boolean} changed
  5823. */
  5824. ItemRange.prototype.repaint = function repaint() {
  5825. // TODO: make an efficient repaint
  5826. var changed = false;
  5827. var dom = this.dom;
  5828. if (!dom) {
  5829. this._create();
  5830. dom = this.dom;
  5831. changed = true;
  5832. }
  5833. if (dom) {
  5834. if (!this.parent) {
  5835. throw new Error('Cannot repaint item: no parent attached');
  5836. }
  5837. var foreground = this.parent.getForeground();
  5838. if (!foreground) {
  5839. throw new Error('Cannot repaint time axis: ' +
  5840. 'parent has no foreground container element');
  5841. }
  5842. if (!dom.box.parentNode) {
  5843. foreground.appendChild(dom.box);
  5844. changed = true;
  5845. }
  5846. // update content
  5847. if (this.data.content != this.content) {
  5848. this.content = this.data.content;
  5849. if (this.content instanceof Element) {
  5850. dom.content.innerHTML = '';
  5851. dom.content.appendChild(this.content);
  5852. }
  5853. else if (this.data.content != undefined) {
  5854. dom.content.innerHTML = this.content;
  5855. }
  5856. else {
  5857. throw new Error('Property "content" missing in item ' + this.data.id);
  5858. }
  5859. changed = true;
  5860. }
  5861. this._repaintDeleteButton(dom.box);
  5862. this._repaintDragLeft();
  5863. this._repaintDragRight();
  5864. // update class
  5865. var className = (this.data.className ? (' ' + this.data.className) : '') +
  5866. (this.selected ? ' selected' : '');
  5867. if (this.className != className) {
  5868. this.className = className;
  5869. dom.box.className = 'item range' + className;
  5870. changed = true;
  5871. }
  5872. }
  5873. return changed;
  5874. };
  5875. /**
  5876. * Show the item in the DOM (when not already visible). The items DOM will
  5877. * be created when needed.
  5878. * @return {Boolean} changed
  5879. */
  5880. ItemRange.prototype.show = function show() {
  5881. if (!this.dom || !this.dom.box.parentNode) {
  5882. return this.repaint();
  5883. }
  5884. else {
  5885. return false;
  5886. }
  5887. };
  5888. /**
  5889. * Hide the item from the DOM (when visible)
  5890. * @return {Boolean} changed
  5891. */
  5892. ItemRange.prototype.hide = function hide() {
  5893. var changed = false,
  5894. dom = this.dom;
  5895. if (dom) {
  5896. if (dom.box.parentNode) {
  5897. dom.box.parentNode.removeChild(dom.box);
  5898. changed = true;
  5899. }
  5900. }
  5901. return changed;
  5902. };
  5903. /**
  5904. * Reflow the item: calculate its actual size from the DOM
  5905. * @return {boolean} resized returns true if the axis is resized
  5906. * @override
  5907. */
  5908. ItemRange.prototype.reflow = function reflow() {
  5909. var changed = 0,
  5910. dom,
  5911. props,
  5912. options,
  5913. margin,
  5914. padding,
  5915. parent,
  5916. start,
  5917. end,
  5918. data,
  5919. range,
  5920. update,
  5921. box,
  5922. parentWidth,
  5923. contentLeft,
  5924. orientation,
  5925. top;
  5926. if (this.data.start == undefined) {
  5927. throw new Error('Property "start" missing in item ' + this.data.id);
  5928. }
  5929. if (this.data.end == undefined) {
  5930. throw new Error('Property "end" missing in item ' + this.data.id);
  5931. }
  5932. data = this.data;
  5933. range = this.parent && this.parent.range;
  5934. if (data && range) {
  5935. // TODO: account for the width of the item. Take some margin
  5936. this.visible = (data.start < range.end) && (data.end > range.start);
  5937. }
  5938. else {
  5939. this.visible = false;
  5940. }
  5941. if (this.visible) {
  5942. dom = this.dom;
  5943. if (dom) {
  5944. props = this.props;
  5945. options = this.options;
  5946. parent = this.parent;
  5947. start = parent.toScreen(this.data.start) + this.offset;
  5948. end = parent.toScreen(this.data.end) + this.offset;
  5949. update = util.updateProperty;
  5950. box = dom.box;
  5951. parentWidth = parent.width;
  5952. orientation = options.orientation || this.defaultOptions.orientation;
  5953. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  5954. padding = options.padding || this.defaultOptions.padding;
  5955. changed += update(props.content, 'width', dom.content.offsetWidth);
  5956. changed += update(this, 'height', box.offsetHeight);
  5957. // limit the width of the this, as browsers cannot draw very wide divs
  5958. if (start < -parentWidth) {
  5959. start = -parentWidth;
  5960. }
  5961. if (end > 2 * parentWidth) {
  5962. end = 2 * parentWidth;
  5963. }
  5964. // when range exceeds left of the window, position the contents at the left of the visible area
  5965. if (start < 0) {
  5966. contentLeft = Math.min(-start,
  5967. (end - start - props.content.width - 2 * padding));
  5968. // TODO: remove the need for options.padding. it's terrible.
  5969. }
  5970. else {
  5971. contentLeft = 0;
  5972. }
  5973. changed += update(props.content, 'left', contentLeft);
  5974. if (orientation == 'top') {
  5975. top = margin;
  5976. changed += update(this, 'top', top);
  5977. }
  5978. else {
  5979. // default or 'bottom'
  5980. top = parent.height - this.height - margin;
  5981. changed += update(this, 'top', top);
  5982. }
  5983. changed += update(this, 'left', start);
  5984. changed += update(this, 'width', Math.max(end - start, 1)); // TODO: reckon with border width;
  5985. }
  5986. else {
  5987. changed += 1;
  5988. }
  5989. }
  5990. return (changed > 0);
  5991. };
  5992. /**
  5993. * Create an items DOM
  5994. * @private
  5995. */
  5996. ItemRange.prototype._create = function _create() {
  5997. var dom = this.dom;
  5998. if (!dom) {
  5999. this.dom = dom = {};
  6000. // background box
  6001. dom.box = document.createElement('div');
  6002. // className is updated in repaint()
  6003. // contents box
  6004. dom.content = document.createElement('div');
  6005. dom.content.className = 'content';
  6006. dom.box.appendChild(dom.content);
  6007. // attach this item as attribute
  6008. dom.box['timeline-item'] = this;
  6009. }
  6010. };
  6011. /**
  6012. * Reposition the item, recalculate its left, top, and width, using the current
  6013. * range and size of the items itemset
  6014. * @override
  6015. */
  6016. ItemRange.prototype.reposition = function reposition() {
  6017. var dom = this.dom,
  6018. props = this.props;
  6019. if (dom) {
  6020. dom.box.style.top = this.top + 'px';
  6021. dom.box.style.left = this.left + 'px';
  6022. dom.box.style.width = this.width + 'px';
  6023. dom.content.style.left = props.content.left + 'px';
  6024. }
  6025. };
  6026. /**
  6027. * Repaint a drag area on the left side of the range when the range is selected
  6028. * @private
  6029. */
  6030. ItemRange.prototype._repaintDragLeft = function () {
  6031. if (this.selected && this.options.editable && !this.dom.dragLeft) {
  6032. // create and show drag area
  6033. var dragLeft = document.createElement('div');
  6034. dragLeft.className = 'drag-left';
  6035. dragLeft.dragLeftItem = this;
  6036. // TODO: this should be redundant?
  6037. Hammer(dragLeft, {
  6038. preventDefault: true
  6039. }).on('drag', function () {
  6040. //console.log('drag left')
  6041. });
  6042. this.dom.box.appendChild(dragLeft);
  6043. this.dom.dragLeft = dragLeft;
  6044. }
  6045. else if (!this.selected && this.dom.dragLeft) {
  6046. // delete drag area
  6047. if (this.dom.dragLeft.parentNode) {
  6048. this.dom.dragLeft.parentNode.removeChild(this.dom.dragLeft);
  6049. }
  6050. this.dom.dragLeft = null;
  6051. }
  6052. };
  6053. /**
  6054. * Repaint a drag area on the right side of the range when the range is selected
  6055. * @private
  6056. */
  6057. ItemRange.prototype._repaintDragRight = function () {
  6058. if (this.selected && this.options.editable && !this.dom.dragRight) {
  6059. // create and show drag area
  6060. var dragRight = document.createElement('div');
  6061. dragRight.className = 'drag-right';
  6062. dragRight.dragRightItem = this;
  6063. // TODO: this should be redundant?
  6064. Hammer(dragRight, {
  6065. preventDefault: true
  6066. }).on('drag', function () {
  6067. //console.log('drag right')
  6068. });
  6069. this.dom.box.appendChild(dragRight);
  6070. this.dom.dragRight = dragRight;
  6071. }
  6072. else if (!this.selected && this.dom.dragRight) {
  6073. // delete drag area
  6074. if (this.dom.dragRight.parentNode) {
  6075. this.dom.dragRight.parentNode.removeChild(this.dom.dragRight);
  6076. }
  6077. this.dom.dragRight = null;
  6078. }
  6079. };
  6080. /**
  6081. * @constructor ItemRangeOverflow
  6082. * @extends ItemRange
  6083. * @param {ItemSet} parent
  6084. * @param {Object} data Object containing parameters start, end
  6085. * content, className.
  6086. * @param {Object} [options] Options to set initial property values
  6087. * @param {Object} [defaultOptions] default options
  6088. * // TODO: describe available options
  6089. */
  6090. function ItemRangeOverflow (parent, data, options, defaultOptions) {
  6091. this.props = {
  6092. content: {
  6093. left: 0,
  6094. width: 0
  6095. }
  6096. };
  6097. // define a private property _width, which is the with of the range box
  6098. // adhering to the ranges start and end date. The property width has a
  6099. // getter which returns the max of border width and content width
  6100. this._width = 0;
  6101. Object.defineProperty(this, 'width', {
  6102. get: function () {
  6103. return (this.props.content && this._width < this.props.content.width) ?
  6104. this.props.content.width :
  6105. this._width;
  6106. },
  6107. set: function (width) {
  6108. this._width = width;
  6109. }
  6110. });
  6111. ItemRange.call(this, parent, data, options, defaultOptions);
  6112. }
  6113. ItemRangeOverflow.prototype = new ItemRange (null, null);
  6114. /**
  6115. * Repaint the item
  6116. * @return {Boolean} changed
  6117. */
  6118. ItemRangeOverflow.prototype.repaint = function repaint() {
  6119. // TODO: make an efficient repaint
  6120. var changed = false;
  6121. var dom = this.dom;
  6122. if (!dom) {
  6123. this._create();
  6124. dom = this.dom;
  6125. changed = true;
  6126. }
  6127. if (dom) {
  6128. if (!this.parent) {
  6129. throw new Error('Cannot repaint item: no parent attached');
  6130. }
  6131. var foreground = this.parent.getForeground();
  6132. if (!foreground) {
  6133. throw new Error('Cannot repaint time axis: ' +
  6134. 'parent has no foreground container element');
  6135. }
  6136. if (!dom.box.parentNode) {
  6137. foreground.appendChild(dom.box);
  6138. changed = true;
  6139. }
  6140. // update content
  6141. if (this.data.content != this.content) {
  6142. this.content = this.data.content;
  6143. if (this.content instanceof Element) {
  6144. dom.content.innerHTML = '';
  6145. dom.content.appendChild(this.content);
  6146. }
  6147. else if (this.data.content != undefined) {
  6148. dom.content.innerHTML = this.content;
  6149. }
  6150. else {
  6151. throw new Error('Property "content" missing in item ' + this.id);
  6152. }
  6153. changed = true;
  6154. }
  6155. this._repaintDeleteButton(dom.box);
  6156. this._repaintDragLeft();
  6157. this._repaintDragRight();
  6158. // update class
  6159. var className = (this.data.className? ' ' + this.data.className : '') +
  6160. (this.selected ? ' selected' : '');
  6161. if (this.className != className) {
  6162. this.className = className;
  6163. dom.box.className = 'item rangeoverflow' + className;
  6164. changed = true;
  6165. }
  6166. }
  6167. return changed;
  6168. };
  6169. /**
  6170. * Reposition the item, recalculate its left, top, and width, using the current
  6171. * range and size of the items itemset
  6172. * @override
  6173. */
  6174. ItemRangeOverflow.prototype.reposition = function reposition() {
  6175. var dom = this.dom,
  6176. props = this.props;
  6177. if (dom) {
  6178. dom.box.style.top = this.top + 'px';
  6179. dom.box.style.left = this.left + 'px';
  6180. dom.box.style.width = this._width + 'px';
  6181. dom.content.style.left = props.content.left + 'px';
  6182. }
  6183. };
  6184. /**
  6185. * @constructor Group
  6186. * @param {GroupSet} parent
  6187. * @param {Number | String} groupId
  6188. * @param {Object} [options] Options to set initial property values
  6189. * // TODO: describe available options
  6190. * @extends Component
  6191. */
  6192. function Group (parent, groupId, options) {
  6193. this.id = util.randomUUID();
  6194. this.parent = parent;
  6195. this.groupId = groupId;
  6196. this.itemset = null; // ItemSet
  6197. this.options = options || {};
  6198. this.options.top = 0;
  6199. this.props = {
  6200. label: {
  6201. width: 0,
  6202. height: 0
  6203. }
  6204. };
  6205. this.top = 0;
  6206. this.left = 0;
  6207. this.width = 0;
  6208. this.height = 0;
  6209. }
  6210. Group.prototype = new Component();
  6211. // TODO: comment
  6212. Group.prototype.setOptions = Component.prototype.setOptions;
  6213. /**
  6214. * Get the container element of the panel, which can be used by a child to
  6215. * add its own widgets.
  6216. * @returns {HTMLElement} container
  6217. */
  6218. Group.prototype.getContainer = function () {
  6219. return this.parent.getContainer();
  6220. };
  6221. /**
  6222. * Set item set for the group. The group will create a view on the itemset,
  6223. * filtered by the groups id.
  6224. * @param {DataSet | DataView} items
  6225. */
  6226. Group.prototype.setItems = function setItems(items) {
  6227. if (this.itemset) {
  6228. // remove current item set
  6229. this.itemset.hide();
  6230. this.itemset.setItems();
  6231. this.parent.controller.remove(this.itemset);
  6232. this.itemset = null;
  6233. }
  6234. if (items) {
  6235. var groupId = this.groupId;
  6236. var itemsetOptions = Object.create(this.options);
  6237. this.itemset = new ItemSet(this, null, itemsetOptions);
  6238. this.itemset.setRange(this.parent.range);
  6239. this.view = new DataView(items, {
  6240. filter: function (item) {
  6241. return item.group == groupId;
  6242. }
  6243. });
  6244. this.itemset.setItems(this.view);
  6245. this.parent.controller.add(this.itemset);
  6246. }
  6247. };
  6248. /**
  6249. * Set selected items by their id. Replaces the current selection.
  6250. * Unknown id's are silently ignored.
  6251. * @param {Array} [ids] An array with zero or more id's of the items to be
  6252. * selected. If ids is an empty array, all items will be
  6253. * unselected.
  6254. */
  6255. Group.prototype.setSelection = function setSelection(ids) {
  6256. if (this.itemset) this.itemset.setSelection(ids);
  6257. };
  6258. /**
  6259. * Get the selected items by their id
  6260. * @return {Array} ids The ids of the selected items
  6261. */
  6262. Group.prototype.getSelection = function getSelection() {
  6263. return this.itemset ? this.itemset.getSelection() : [];
  6264. };
  6265. /**
  6266. * Repaint the item
  6267. * @return {Boolean} changed
  6268. */
  6269. Group.prototype.repaint = function repaint() {
  6270. return false;
  6271. };
  6272. /**
  6273. * Reflow the item
  6274. * @return {Boolean} resized
  6275. */
  6276. Group.prototype.reflow = function reflow() {
  6277. var changed = 0,
  6278. update = util.updateProperty;
  6279. changed += update(this, 'top', this.itemset ? this.itemset.top : 0);
  6280. changed += update(this, 'height', this.itemset ? this.itemset.height : 0);
  6281. // TODO: reckon with the height of the group label
  6282. if (this.label) {
  6283. var inner = this.label.firstChild;
  6284. changed += update(this.props.label, 'width', inner.clientWidth);
  6285. changed += update(this.props.label, 'height', inner.clientHeight);
  6286. }
  6287. else {
  6288. changed += update(this.props.label, 'width', 0);
  6289. changed += update(this.props.label, 'height', 0);
  6290. }
  6291. return (changed > 0);
  6292. };
  6293. /**
  6294. * An GroupSet holds a set of groups
  6295. * @param {Component} parent
  6296. * @param {Component[]} [depends] Components on which this components depends
  6297. * (except for the parent)
  6298. * @param {Object} [options] See GroupSet.setOptions for the available
  6299. * options.
  6300. * @constructor GroupSet
  6301. * @extends Panel
  6302. */
  6303. function GroupSet(parent, depends, options) {
  6304. this.id = util.randomUUID();
  6305. this.parent = parent;
  6306. this.depends = depends;
  6307. this.options = options || {};
  6308. this.range = null; // Range or Object {start: number, end: number}
  6309. this.itemsData = null; // DataSet with items
  6310. this.groupsData = null; // DataSet with groups
  6311. this.groups = {}; // map with groups
  6312. this.dom = {};
  6313. this.props = {
  6314. labels: {
  6315. width: 0
  6316. }
  6317. };
  6318. // TODO: implement right orientation of the labels
  6319. // changes in groups are queued key/value map containing id/action
  6320. this.queue = {};
  6321. var me = this;
  6322. this.listeners = {
  6323. 'add': function (event, params) {
  6324. me._onAdd(params.items);
  6325. },
  6326. 'update': function (event, params) {
  6327. me._onUpdate(params.items);
  6328. },
  6329. 'remove': function (event, params) {
  6330. me._onRemove(params.items);
  6331. }
  6332. };
  6333. }
  6334. GroupSet.prototype = new Panel();
  6335. /**
  6336. * Set options for the GroupSet. Existing options will be extended/overwritten.
  6337. * @param {Object} [options] The following options are available:
  6338. * {String | function} groupsOrder
  6339. * TODO: describe options
  6340. */
  6341. GroupSet.prototype.setOptions = Component.prototype.setOptions;
  6342. GroupSet.prototype.setRange = function (range) {
  6343. // TODO: implement setRange
  6344. };
  6345. /**
  6346. * Set items
  6347. * @param {vis.DataSet | null} items
  6348. */
  6349. GroupSet.prototype.setItems = function setItems(items) {
  6350. this.itemsData = items;
  6351. for (var id in this.groups) {
  6352. if (this.groups.hasOwnProperty(id)) {
  6353. var group = this.groups[id];
  6354. group.setItems(items);
  6355. }
  6356. }
  6357. };
  6358. /**
  6359. * Get items
  6360. * @return {vis.DataSet | null} items
  6361. */
  6362. GroupSet.prototype.getItems = function getItems() {
  6363. return this.itemsData;
  6364. };
  6365. /**
  6366. * Set range (start and end).
  6367. * @param {Range | Object} range A Range or an object containing start and end.
  6368. */
  6369. GroupSet.prototype.setRange = function setRange(range) {
  6370. this.range = range;
  6371. };
  6372. /**
  6373. * Set groups
  6374. * @param {vis.DataSet} groups
  6375. */
  6376. GroupSet.prototype.setGroups = function setGroups(groups) {
  6377. var me = this,
  6378. ids;
  6379. // unsubscribe from current dataset
  6380. if (this.groupsData) {
  6381. util.forEach(this.listeners, function (callback, event) {
  6382. me.groupsData.unsubscribe(event, callback);
  6383. });
  6384. // remove all drawn groups
  6385. ids = this.groupsData.getIds();
  6386. this._onRemove(ids);
  6387. }
  6388. // replace the dataset
  6389. if (!groups) {
  6390. this.groupsData = null;
  6391. }
  6392. else if (groups instanceof DataSet) {
  6393. this.groupsData = groups;
  6394. }
  6395. else {
  6396. this.groupsData = new DataSet({
  6397. convert: {
  6398. start: 'Date',
  6399. end: 'Date'
  6400. }
  6401. });
  6402. this.groupsData.add(groups);
  6403. }
  6404. if (this.groupsData) {
  6405. // subscribe to new dataset
  6406. var id = this.id;
  6407. util.forEach(this.listeners, function (callback, event) {
  6408. me.groupsData.on(event, callback, id);
  6409. });
  6410. // draw all new groups
  6411. ids = this.groupsData.getIds();
  6412. this._onAdd(ids);
  6413. }
  6414. };
  6415. /**
  6416. * Get groups
  6417. * @return {vis.DataSet | null} groups
  6418. */
  6419. GroupSet.prototype.getGroups = function getGroups() {
  6420. return this.groupsData;
  6421. };
  6422. /**
  6423. * Set selected items by their id. Replaces the current selection.
  6424. * Unknown id's are silently ignored.
  6425. * @param {Array} [ids] An array with zero or more id's of the items to be
  6426. * selected. If ids is an empty array, all items will be
  6427. * unselected.
  6428. */
  6429. GroupSet.prototype.setSelection = function setSelection(ids) {
  6430. var selection = [],
  6431. groups = this.groups;
  6432. // iterate over each of the groups
  6433. for (var id in groups) {
  6434. if (groups.hasOwnProperty(id)) {
  6435. var group = groups[id];
  6436. group.setSelection(ids);
  6437. }
  6438. }
  6439. return selection;
  6440. };
  6441. /**
  6442. * Get the selected items by their id
  6443. * @return {Array} ids The ids of the selected items
  6444. */
  6445. GroupSet.prototype.getSelection = function getSelection() {
  6446. var selection = [],
  6447. groups = this.groups;
  6448. // iterate over each of the groups
  6449. for (var id in groups) {
  6450. if (groups.hasOwnProperty(id)) {
  6451. var group = groups[id];
  6452. selection = selection.concat(group.getSelection());
  6453. }
  6454. }
  6455. return selection;
  6456. };
  6457. /**
  6458. * Repaint the component
  6459. * @return {Boolean} changed
  6460. */
  6461. GroupSet.prototype.repaint = function repaint() {
  6462. var changed = 0,
  6463. i, id, group, label,
  6464. update = util.updateProperty,
  6465. asSize = util.option.asSize,
  6466. asElement = util.option.asElement,
  6467. options = this.options,
  6468. frame = this.dom.frame,
  6469. labels = this.dom.labels,
  6470. labelSet = this.dom.labelSet;
  6471. // create frame
  6472. if (!this.parent) {
  6473. throw new Error('Cannot repaint groupset: no parent attached');
  6474. }
  6475. var parentContainer = this.parent.getContainer();
  6476. if (!parentContainer) {
  6477. throw new Error('Cannot repaint groupset: parent has no container element');
  6478. }
  6479. if (!frame) {
  6480. frame = document.createElement('div');
  6481. frame.className = 'groupset';
  6482. frame['timeline-groupset'] = this;
  6483. this.dom.frame = frame;
  6484. var className = options.className;
  6485. if (className) {
  6486. util.addClassName(frame, util.option.asString(className));
  6487. }
  6488. changed += 1;
  6489. }
  6490. if (!frame.parentNode) {
  6491. parentContainer.appendChild(frame);
  6492. changed += 1;
  6493. }
  6494. // create labels
  6495. var labelContainer = asElement(options.labelContainer);
  6496. if (!labelContainer) {
  6497. throw new Error('Cannot repaint groupset: option "labelContainer" not defined');
  6498. }
  6499. if (!labels) {
  6500. labels = document.createElement('div');
  6501. labels.className = 'labels';
  6502. this.dom.labels = labels;
  6503. }
  6504. if (!labelSet) {
  6505. labelSet = document.createElement('div');
  6506. labelSet.className = 'label-set';
  6507. labels.appendChild(labelSet);
  6508. this.dom.labelSet = labelSet;
  6509. }
  6510. if (!labels.parentNode || labels.parentNode != labelContainer) {
  6511. if (labels.parentNode) {
  6512. labels.parentNode.removeChild(labels.parentNode);
  6513. }
  6514. labelContainer.appendChild(labels);
  6515. }
  6516. // reposition frame
  6517. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  6518. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  6519. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  6520. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  6521. // reposition labels
  6522. changed += update(labelSet.style, 'top', asSize(options.top, '0px'));
  6523. changed += update(labelSet.style, 'height', asSize(options.height, this.height + 'px'));
  6524. var me = this,
  6525. queue = this.queue,
  6526. groups = this.groups,
  6527. groupsData = this.groupsData;
  6528. // show/hide added/changed/removed groups
  6529. var ids = Object.keys(queue);
  6530. if (ids.length) {
  6531. ids.forEach(function (id) {
  6532. var action = queue[id];
  6533. var group = groups[id];
  6534. //noinspection FallthroughInSwitchStatementJS
  6535. switch (action) {
  6536. case 'add':
  6537. case 'update':
  6538. if (!group) {
  6539. var groupOptions = Object.create(me.options);
  6540. util.extend(groupOptions, {
  6541. height: null,
  6542. maxHeight: null
  6543. });
  6544. group = new Group(me, id, groupOptions);
  6545. group.setItems(me.itemsData); // attach items data
  6546. groups[id] = group;
  6547. me.controller.add(group);
  6548. }
  6549. // TODO: update group data
  6550. group.data = groupsData.get(id);
  6551. delete queue[id];
  6552. break;
  6553. case 'remove':
  6554. if (group) {
  6555. group.setItems(); // detach items data
  6556. delete groups[id];
  6557. me.controller.remove(group);
  6558. }
  6559. // update lists
  6560. delete queue[id];
  6561. break;
  6562. default:
  6563. console.log('Error: unknown action "' + action + '"');
  6564. }
  6565. });
  6566. // the groupset depends on each of the groups
  6567. //this.depends = this.groups; // TODO: gives a circular reference through the parent
  6568. // TODO: apply dependencies of the groupset
  6569. // update the top positions of the groups in the correct order
  6570. var orderedGroups = this.groupsData.getIds({
  6571. order: this.options.groupOrder
  6572. });
  6573. for (i = 0; i < orderedGroups.length; i++) {
  6574. (function (group, prevGroup) {
  6575. var top = 0;
  6576. if (prevGroup) {
  6577. top = function () {
  6578. // TODO: top must reckon with options.maxHeight
  6579. return prevGroup.top + prevGroup.height;
  6580. }
  6581. }
  6582. group.setOptions({
  6583. top: top
  6584. });
  6585. })(groups[orderedGroups[i]], groups[orderedGroups[i - 1]]);
  6586. }
  6587. // (re)create the labels
  6588. while (labelSet.firstChild) {
  6589. labelSet.removeChild(labelSet.firstChild);
  6590. }
  6591. for (i = 0; i < orderedGroups.length; i++) {
  6592. id = orderedGroups[i];
  6593. label = this._createLabel(id);
  6594. labelSet.appendChild(label);
  6595. }
  6596. changed++;
  6597. }
  6598. // reposition the labels
  6599. // TODO: labels are not displayed correctly when orientation=='top'
  6600. // TODO: width of labelPanel is not immediately updated on a change in groups
  6601. for (id in groups) {
  6602. if (groups.hasOwnProperty(id)) {
  6603. group = groups[id];
  6604. label = group.label;
  6605. if (label) {
  6606. label.style.top = group.top + 'px';
  6607. label.style.height = group.height + 'px';
  6608. }
  6609. }
  6610. }
  6611. return (changed > 0);
  6612. };
  6613. /**
  6614. * Create a label for group with given id
  6615. * @param {Number} id
  6616. * @return {Element} label
  6617. * @private
  6618. */
  6619. GroupSet.prototype._createLabel = function(id) {
  6620. var group = this.groups[id];
  6621. var label = document.createElement('div');
  6622. label.className = 'vlabel';
  6623. var inner = document.createElement('div');
  6624. inner.className = 'inner';
  6625. label.appendChild(inner);
  6626. var content = group.data && group.data.content;
  6627. if (content instanceof Element) {
  6628. inner.appendChild(content);
  6629. }
  6630. else if (content != undefined) {
  6631. inner.innerHTML = content;
  6632. }
  6633. var className = group.data && group.data.className;
  6634. if (className) {
  6635. util.addClassName(label, className);
  6636. }
  6637. group.label = label; // TODO: not so nice, parking labels in the group this way!!!
  6638. return label;
  6639. };
  6640. /**
  6641. * Get container element
  6642. * @return {HTMLElement} container
  6643. */
  6644. GroupSet.prototype.getContainer = function getContainer() {
  6645. return this.dom.frame;
  6646. };
  6647. /**
  6648. * Get the width of the group labels
  6649. * @return {Number} width
  6650. */
  6651. GroupSet.prototype.getLabelsWidth = function getContainer() {
  6652. return this.props.labels.width;
  6653. };
  6654. /**
  6655. * Reflow the component
  6656. * @return {Boolean} resized
  6657. */
  6658. GroupSet.prototype.reflow = function reflow() {
  6659. var changed = 0,
  6660. id, group,
  6661. options = this.options,
  6662. update = util.updateProperty,
  6663. asNumber = util.option.asNumber,
  6664. asSize = util.option.asSize,
  6665. frame = this.dom.frame;
  6666. if (frame) {
  6667. var maxHeight = asNumber(options.maxHeight);
  6668. var fixedHeight = (asSize(options.height) != null);
  6669. var height;
  6670. if (fixedHeight) {
  6671. height = frame.offsetHeight;
  6672. }
  6673. else {
  6674. // height is not specified, calculate the sum of the height of all groups
  6675. height = 0;
  6676. for (id in this.groups) {
  6677. if (this.groups.hasOwnProperty(id)) {
  6678. group = this.groups[id];
  6679. height += group.height;
  6680. }
  6681. }
  6682. }
  6683. if (maxHeight != null) {
  6684. height = Math.min(height, maxHeight);
  6685. }
  6686. changed += update(this, 'height', height);
  6687. changed += update(this, 'top', frame.offsetTop);
  6688. changed += update(this, 'left', frame.offsetLeft);
  6689. changed += update(this, 'width', frame.offsetWidth);
  6690. }
  6691. // calculate the maximum width of the labels
  6692. var width = 0;
  6693. for (id in this.groups) {
  6694. if (this.groups.hasOwnProperty(id)) {
  6695. group = this.groups[id];
  6696. var labelWidth = group.props && group.props.label && group.props.label.width || 0;
  6697. width = Math.max(width, labelWidth);
  6698. }
  6699. }
  6700. changed += update(this.props.labels, 'width', width);
  6701. return (changed > 0);
  6702. };
  6703. /**
  6704. * Hide the component from the DOM
  6705. * @return {Boolean} changed
  6706. */
  6707. GroupSet.prototype.hide = function hide() {
  6708. if (this.dom.frame && this.dom.frame.parentNode) {
  6709. this.dom.frame.parentNode.removeChild(this.dom.frame);
  6710. return true;
  6711. }
  6712. else {
  6713. return false;
  6714. }
  6715. };
  6716. /**
  6717. * Show the component in the DOM (when not already visible).
  6718. * A repaint will be executed when the component is not visible
  6719. * @return {Boolean} changed
  6720. */
  6721. GroupSet.prototype.show = function show() {
  6722. if (!this.dom.frame || !this.dom.frame.parentNode) {
  6723. return this.repaint();
  6724. }
  6725. else {
  6726. return false;
  6727. }
  6728. };
  6729. /**
  6730. * Handle updated groups
  6731. * @param {Number[]} ids
  6732. * @private
  6733. */
  6734. GroupSet.prototype._onUpdate = function _onUpdate(ids) {
  6735. this._toQueue(ids, 'update');
  6736. };
  6737. /**
  6738. * Handle changed groups
  6739. * @param {Number[]} ids
  6740. * @private
  6741. */
  6742. GroupSet.prototype._onAdd = function _onAdd(ids) {
  6743. this._toQueue(ids, 'add');
  6744. };
  6745. /**
  6746. * Handle removed groups
  6747. * @param {Number[]} ids
  6748. * @private
  6749. */
  6750. GroupSet.prototype._onRemove = function _onRemove(ids) {
  6751. this._toQueue(ids, 'remove');
  6752. };
  6753. /**
  6754. * Put groups in the queue to be added/updated/remove
  6755. * @param {Number[]} ids
  6756. * @param {String} action can be 'add', 'update', 'remove'
  6757. */
  6758. GroupSet.prototype._toQueue = function _toQueue(ids, action) {
  6759. var queue = this.queue;
  6760. ids.forEach(function (id) {
  6761. queue[id] = action;
  6762. });
  6763. if (this.controller) {
  6764. //this.requestReflow();
  6765. this.requestRepaint();
  6766. }
  6767. };
  6768. /**
  6769. * Find the Group from an event target:
  6770. * searches for the attribute 'timeline-groupset' in the event target's element
  6771. * tree, then finds the right group in this groupset
  6772. * @param {Event} event
  6773. * @return {Group | null} group
  6774. */
  6775. GroupSet.groupFromTarget = function groupFromTarget (event) {
  6776. var groupset,
  6777. target = event.target;
  6778. while (target) {
  6779. if (target.hasOwnProperty('timeline-groupset')) {
  6780. groupset = target['timeline-groupset'];
  6781. break;
  6782. }
  6783. target = target.parentNode;
  6784. }
  6785. if (groupset) {
  6786. for (var groupId in groupset.groups) {
  6787. if (groupset.groups.hasOwnProperty(groupId)) {
  6788. var group = groupset.groups[groupId];
  6789. if (group.itemset && ItemSet.itemSetFromTarget(event) == group.itemset) {
  6790. return group;
  6791. }
  6792. }
  6793. }
  6794. }
  6795. return null;
  6796. };
  6797. /**
  6798. * Create a timeline visualization
  6799. * @param {HTMLElement} container
  6800. * @param {vis.DataSet | Array | google.visualization.DataTable} [items]
  6801. * @param {Object} [options] See Timeline.setOptions for the available options.
  6802. * @constructor
  6803. */
  6804. function Timeline (container, items, options) {
  6805. var me = this;
  6806. var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0);
  6807. this.options = {
  6808. orientation: 'bottom',
  6809. autoResize: true,
  6810. editable: false,
  6811. selectable: true,
  6812. snap: null, // will be specified after timeaxis is created
  6813. min: null,
  6814. max: null,
  6815. zoomMin: 10, // milliseconds
  6816. zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000, // milliseconds
  6817. // moveable: true, // TODO: option moveable
  6818. // zoomable: true, // TODO: option zoomable
  6819. showMinorLabels: true,
  6820. showMajorLabels: true,
  6821. showCurrentTime: false,
  6822. showCustomTime: false,
  6823. onAdd: function (item, callback) {
  6824. callback(item);
  6825. },
  6826. onUpdate: function (item, callback) {
  6827. callback(item);
  6828. },
  6829. onMove: function (item, callback) {
  6830. callback(item);
  6831. },
  6832. onRemove: function (item, callback) {
  6833. callback(item);
  6834. }
  6835. };
  6836. // controller
  6837. this.controller = new Controller();
  6838. // root panel
  6839. if (!container) {
  6840. throw new Error('No container element provided');
  6841. }
  6842. var rootOptions = Object.create(this.options);
  6843. rootOptions.height = function () {
  6844. // TODO: change to height
  6845. if (me.options.height) {
  6846. // fixed height
  6847. return me.options.height;
  6848. }
  6849. else {
  6850. // auto height
  6851. return (me.timeaxis.height + me.content.height) + 'px';
  6852. }
  6853. };
  6854. this.rootPanel = new RootPanel(container, rootOptions);
  6855. this.controller.add(this.rootPanel);
  6856. // single select (or unselect) when tapping an item
  6857. this.controller.on('tap', this._onSelectItem.bind(this));
  6858. // multi select when holding mouse/touch, or on ctrl+click
  6859. this.controller.on('hold', this._onMultiSelectItem.bind(this));
  6860. // add item on doubletap
  6861. this.controller.on('doubletap', this._onAddItem.bind(this));
  6862. // item panel
  6863. var itemOptions = Object.create(this.options);
  6864. itemOptions.left = function () {
  6865. return me.labelPanel.width;
  6866. };
  6867. itemOptions.width = function () {
  6868. return me.rootPanel.width - me.labelPanel.width;
  6869. };
  6870. itemOptions.top = null;
  6871. itemOptions.height = null;
  6872. this.itemPanel = new Panel(this.rootPanel, [], itemOptions);
  6873. this.controller.add(this.itemPanel);
  6874. // label panel
  6875. var labelOptions = Object.create(this.options);
  6876. labelOptions.top = null;
  6877. labelOptions.left = null;
  6878. labelOptions.height = null;
  6879. labelOptions.width = function () {
  6880. if (me.content && typeof me.content.getLabelsWidth === 'function') {
  6881. return me.content.getLabelsWidth();
  6882. }
  6883. else {
  6884. return 0;
  6885. }
  6886. };
  6887. this.labelPanel = new Panel(this.rootPanel, [], labelOptions);
  6888. this.controller.add(this.labelPanel);
  6889. // range
  6890. var rangeOptions = Object.create(this.options);
  6891. this.range = new Range(rangeOptions);
  6892. this.range.setRange(
  6893. now.clone().add('days', -3).valueOf(),
  6894. now.clone().add('days', 4).valueOf()
  6895. );
  6896. this.range.subscribe(this.controller, this.rootPanel, 'move', 'horizontal');
  6897. this.range.subscribe(this.controller, this.rootPanel, 'zoom', 'horizontal');
  6898. this.range.on('rangechange', function (properties) {
  6899. var force = true;
  6900. me.controller.emit('rangechange', properties);
  6901. me.controller.emit('request-reflow', force);
  6902. });
  6903. this.range.on('rangechanged', function (properties) {
  6904. var force = true;
  6905. me.controller.emit('rangechanged', properties);
  6906. me.controller.emit('request-reflow', force);
  6907. });
  6908. // time axis
  6909. var timeaxisOptions = Object.create(rootOptions);
  6910. timeaxisOptions.range = this.range;
  6911. timeaxisOptions.left = null;
  6912. timeaxisOptions.top = null;
  6913. timeaxisOptions.width = '100%';
  6914. timeaxisOptions.height = null;
  6915. this.timeaxis = new TimeAxis(this.itemPanel, [], timeaxisOptions);
  6916. this.timeaxis.setRange(this.range);
  6917. this.controller.add(this.timeaxis);
  6918. this.options.snap = this.timeaxis.snap.bind(this.timeaxis);
  6919. // current time bar
  6920. this.currenttime = new CurrentTime(this.timeaxis, [], rootOptions);
  6921. this.controller.add(this.currenttime);
  6922. // custom time bar
  6923. this.customtime = new CustomTime(this.timeaxis, [], rootOptions);
  6924. this.controller.add(this.customtime);
  6925. // create groupset
  6926. this.setGroups(null);
  6927. this.itemsData = null; // DataSet
  6928. this.groupsData = null; // DataSet
  6929. // apply options
  6930. if (options) {
  6931. this.setOptions(options);
  6932. }
  6933. // create itemset and groupset
  6934. if (items) {
  6935. this.setItems(items);
  6936. }
  6937. }
  6938. /**
  6939. * Add an event listener to the timeline
  6940. * @param {String} event Available events: select, rangechange, rangechanged,
  6941. * timechange, timechanged
  6942. * @param {function} callback
  6943. */
  6944. Timeline.prototype.on = function on (event, callback) {
  6945. this.controller.on(event, callback);
  6946. };
  6947. /**
  6948. * Add an event listener from the timeline
  6949. * @param {String} event
  6950. * @param {function} callback
  6951. */
  6952. Timeline.prototype.off = function off (event, callback) {
  6953. this.controller.off(event, callback);
  6954. };
  6955. /**
  6956. * Set options
  6957. * @param {Object} options TODO: describe the available options
  6958. */
  6959. Timeline.prototype.setOptions = function (options) {
  6960. util.extend(this.options, options);
  6961. // force update of range (apply new min/max etc.)
  6962. // both start and end are optional
  6963. this.range.setRange(options.start, options.end);
  6964. if ('editable' in options || 'selectable' in options) {
  6965. if (this.options.selectable) {
  6966. // force update of selection
  6967. this.setSelection(this.getSelection());
  6968. }
  6969. else {
  6970. // remove selection
  6971. this.setSelection([]);
  6972. }
  6973. }
  6974. // validate the callback functions
  6975. var validateCallback = (function (fn) {
  6976. if (!(this.options[fn] instanceof Function) || this.options[fn].length != 2) {
  6977. throw new Error('option ' + fn + ' must be a function ' + fn + '(item, callback)');
  6978. }
  6979. }).bind(this);
  6980. ['onAdd', 'onUpdate', 'onRemove', 'onMove'].forEach(validateCallback);
  6981. this.controller.reflow();
  6982. this.controller.repaint();
  6983. };
  6984. /**
  6985. * Set a custom time bar
  6986. * @param {Date} time
  6987. */
  6988. Timeline.prototype.setCustomTime = function (time) {
  6989. if (!this.customtime) {
  6990. throw new Error('Cannot get custom time: Custom time bar is not enabled');
  6991. }
  6992. this.customtime.setCustomTime(time);
  6993. };
  6994. /**
  6995. * Retrieve the current custom time.
  6996. * @return {Date} customTime
  6997. */
  6998. Timeline.prototype.getCustomTime = function() {
  6999. if (!this.customtime) {
  7000. throw new Error('Cannot get custom time: Custom time bar is not enabled');
  7001. }
  7002. return this.customtime.getCustomTime();
  7003. };
  7004. /**
  7005. * Set items
  7006. * @param {vis.DataSet | Array | google.visualization.DataTable | null} items
  7007. */
  7008. Timeline.prototype.setItems = function(items) {
  7009. var initialLoad = (this.itemsData == null);
  7010. // convert to type DataSet when needed
  7011. var newDataSet;
  7012. if (!items) {
  7013. newDataSet = null;
  7014. }
  7015. else if (items instanceof DataSet) {
  7016. newDataSet = items;
  7017. }
  7018. if (!(items instanceof DataSet)) {
  7019. newDataSet = new DataSet({
  7020. convert: {
  7021. start: 'Date',
  7022. end: 'Date'
  7023. }
  7024. });
  7025. newDataSet.add(items);
  7026. }
  7027. // set items
  7028. this.itemsData = newDataSet;
  7029. this.content.setItems(newDataSet);
  7030. if (initialLoad && (this.options.start == undefined || this.options.end == undefined)) {
  7031. // apply the data range as range
  7032. var dataRange = this.getItemRange();
  7033. // add 5% space on both sides
  7034. var start = dataRange.min;
  7035. var end = dataRange.max;
  7036. if (start != null && end != null) {
  7037. var interval = (end.valueOf() - start.valueOf());
  7038. if (interval <= 0) {
  7039. // prevent an empty interval
  7040. interval = 24 * 60 * 60 * 1000; // 1 day
  7041. }
  7042. start = new Date(start.valueOf() - interval * 0.05);
  7043. end = new Date(end.valueOf() + interval * 0.05);
  7044. }
  7045. // override specified start and/or end date
  7046. if (this.options.start != undefined) {
  7047. start = util.convert(this.options.start, 'Date');
  7048. }
  7049. if (this.options.end != undefined) {
  7050. end = util.convert(this.options.end, 'Date');
  7051. }
  7052. // apply range if there is a min or max available
  7053. if (start != null || end != null) {
  7054. this.range.setRange(start, end);
  7055. }
  7056. }
  7057. };
  7058. /**
  7059. * Set groups
  7060. * @param {vis.DataSet | Array | google.visualization.DataTable} groups
  7061. */
  7062. Timeline.prototype.setGroups = function(groups) {
  7063. var me = this;
  7064. this.groupsData = groups;
  7065. // switch content type between ItemSet or GroupSet when needed
  7066. var Type = this.groupsData ? GroupSet : ItemSet;
  7067. if (!(this.content instanceof Type)) {
  7068. // remove old content set
  7069. if (this.content) {
  7070. this.content.hide();
  7071. if (this.content.setItems) {
  7072. this.content.setItems(); // disconnect from items
  7073. }
  7074. if (this.content.setGroups) {
  7075. this.content.setGroups(); // disconnect from groups
  7076. }
  7077. this.controller.remove(this.content);
  7078. }
  7079. // create new content set
  7080. var options = Object.create(this.options);
  7081. util.extend(options, {
  7082. top: function () {
  7083. if (me.options.orientation == 'top') {
  7084. return me.timeaxis.height;
  7085. }
  7086. else {
  7087. return me.itemPanel.height - me.timeaxis.height - me.content.height;
  7088. }
  7089. },
  7090. left: null,
  7091. width: '100%',
  7092. height: function () {
  7093. if (me.options.height) {
  7094. // fixed height
  7095. return me.itemPanel.height - me.timeaxis.height;
  7096. }
  7097. else {
  7098. // auto height
  7099. return null;
  7100. }
  7101. },
  7102. maxHeight: function () {
  7103. // TODO: change maxHeight to be a css string like '100%' or '300px'
  7104. if (me.options.maxHeight) {
  7105. if (!util.isNumber(me.options.maxHeight)) {
  7106. throw new TypeError('Number expected for property maxHeight');
  7107. }
  7108. return me.options.maxHeight - me.timeaxis.height;
  7109. }
  7110. else {
  7111. return null;
  7112. }
  7113. },
  7114. labelContainer: function () {
  7115. return me.labelPanel.getContainer();
  7116. }
  7117. });
  7118. this.content = new Type(this.itemPanel, [this.timeaxis], options);
  7119. if (this.content.setRange) {
  7120. this.content.setRange(this.range);
  7121. }
  7122. if (this.content.setItems) {
  7123. this.content.setItems(this.itemsData);
  7124. }
  7125. if (this.content.setGroups) {
  7126. this.content.setGroups(this.groupsData);
  7127. }
  7128. this.controller.add(this.content);
  7129. }
  7130. };
  7131. /**
  7132. * Get the data range of the item set.
  7133. * @returns {{min: Date, max: Date}} range A range with a start and end Date.
  7134. * When no minimum is found, min==null
  7135. * When no maximum is found, max==null
  7136. */
  7137. Timeline.prototype.getItemRange = function getItemRange() {
  7138. // calculate min from start filed
  7139. var itemsData = this.itemsData,
  7140. min = null,
  7141. max = null;
  7142. if (itemsData) {
  7143. // calculate the minimum value of the field 'start'
  7144. var minItem = itemsData.min('start');
  7145. min = minItem ? minItem.start.valueOf() : null;
  7146. // calculate maximum value of fields 'start' and 'end'
  7147. var maxStartItem = itemsData.max('start');
  7148. if (maxStartItem) {
  7149. max = maxStartItem.start.valueOf();
  7150. }
  7151. var maxEndItem = itemsData.max('end');
  7152. if (maxEndItem) {
  7153. if (max == null) {
  7154. max = maxEndItem.end.valueOf();
  7155. }
  7156. else {
  7157. max = Math.max(max, maxEndItem.end.valueOf());
  7158. }
  7159. }
  7160. }
  7161. return {
  7162. min: (min != null) ? new Date(min) : null,
  7163. max: (max != null) ? new Date(max) : null
  7164. };
  7165. };
  7166. /**
  7167. * Set selected items by their id. Replaces the current selection
  7168. * Unknown id's are silently ignored.
  7169. * @param {Array} [ids] An array with zero or more id's of the items to be
  7170. * selected. If ids is an empty array, all items will be
  7171. * unselected.
  7172. */
  7173. Timeline.prototype.setSelection = function setSelection (ids) {
  7174. if (this.content) this.content.setSelection(ids);
  7175. };
  7176. /**
  7177. * Get the selected items by their id
  7178. * @return {Array} ids The ids of the selected items
  7179. */
  7180. Timeline.prototype.getSelection = function getSelection() {
  7181. return this.content ? this.content.getSelection() : [];
  7182. };
  7183. /**
  7184. * Set the visible window. Both parameters are optional, you can change only
  7185. * start or only end.
  7186. * @param {Date | Number | String} [start] Start date of visible window
  7187. * @param {Date | Number | String} [end] End date of visible window
  7188. */
  7189. Timeline.prototype.setWindow = function setWindow(start, end) {
  7190. this.range.setRange(start, end);
  7191. };
  7192. /**
  7193. * Get the visible window
  7194. * @return {{start: Date, end: Date}} Visible range
  7195. */
  7196. Timeline.prototype.getWindow = function setWindow() {
  7197. var range = this.range.getRange();
  7198. return {
  7199. start: new Date(range.start),
  7200. end: new Date(range.end)
  7201. };
  7202. };
  7203. /**
  7204. * Handle selecting/deselecting an item when tapping it
  7205. * @param {Event} event
  7206. * @private
  7207. */
  7208. // TODO: move this function to ItemSet
  7209. Timeline.prototype._onSelectItem = function (event) {
  7210. if (!this.options.selectable) return;
  7211. var ctrlKey = event.gesture.srcEvent && event.gesture.srcEvent.ctrlKey;
  7212. var shiftKey = event.gesture.srcEvent && event.gesture.srcEvent.shiftKey;
  7213. if (ctrlKey || shiftKey) {
  7214. this._onMultiSelectItem(event);
  7215. return;
  7216. }
  7217. var item = ItemSet.itemFromTarget(event);
  7218. var selection = item ? [item.id] : [];
  7219. this.setSelection(selection);
  7220. this.controller.emit('select', {
  7221. items: this.getSelection()
  7222. });
  7223. event.stopPropagation();
  7224. };
  7225. /**
  7226. * Handle creation and updates of an item on double tap
  7227. * @param event
  7228. * @private
  7229. */
  7230. Timeline.prototype._onAddItem = function (event) {
  7231. if (!this.options.selectable) return;
  7232. if (!this.options.editable) return;
  7233. var me = this,
  7234. item = ItemSet.itemFromTarget(event);
  7235. if (item) {
  7236. // update item
  7237. // execute async handler to update the item (or cancel it)
  7238. var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset
  7239. this.options.onUpdate(itemData, function (itemData) {
  7240. if (itemData) {
  7241. me.itemsData.update(itemData);
  7242. }
  7243. });
  7244. }
  7245. else {
  7246. // add item
  7247. var xAbs = vis.util.getAbsoluteLeft(this.rootPanel.frame);
  7248. var x = event.gesture.center.pageX - xAbs;
  7249. var newItem = {
  7250. start: this.timeaxis.snap(this._toTime(x)),
  7251. content: 'new item'
  7252. };
  7253. var id = util.randomUUID();
  7254. newItem[this.itemsData.fieldId] = id;
  7255. var group = GroupSet.groupFromTarget(event);
  7256. if (group) {
  7257. newItem.group = group.groupId;
  7258. }
  7259. // execute async handler to customize (or cancel) adding an item
  7260. this.options.onAdd(newItem, function (item) {
  7261. if (item) {
  7262. me.itemsData.add(newItem);
  7263. // select the created item after it is repainted
  7264. me.controller.once('repaint', function () {
  7265. me.setSelection([id]);
  7266. me.controller.emit('select', {
  7267. items: me.getSelection()
  7268. });
  7269. }.bind(me));
  7270. }
  7271. });
  7272. }
  7273. };
  7274. /**
  7275. * Handle selecting/deselecting multiple items when holding an item
  7276. * @param {Event} event
  7277. * @private
  7278. */
  7279. // TODO: move this function to ItemSet
  7280. Timeline.prototype._onMultiSelectItem = function (event) {
  7281. if (!this.options.selectable) return;
  7282. var selection,
  7283. item = ItemSet.itemFromTarget(event);
  7284. if (item) {
  7285. // multi select items
  7286. selection = this.getSelection(); // current selection
  7287. var index = selection.indexOf(item.id);
  7288. if (index == -1) {
  7289. // item is not yet selected -> select it
  7290. selection.push(item.id);
  7291. }
  7292. else {
  7293. // item is already selected -> deselect it
  7294. selection.splice(index, 1);
  7295. }
  7296. this.setSelection(selection);
  7297. this.controller.emit('select', {
  7298. items: this.getSelection()
  7299. });
  7300. event.stopPropagation();
  7301. }
  7302. };
  7303. /**
  7304. * Convert a position on screen (pixels) to a datetime
  7305. * @param {int} x Position on the screen in pixels
  7306. * @return {Date} time The datetime the corresponds with given position x
  7307. * @private
  7308. */
  7309. Timeline.prototype._toTime = function _toTime(x) {
  7310. var conversion = this.range.conversion(this.content.width);
  7311. return new Date(x / conversion.scale + conversion.offset);
  7312. };
  7313. /**
  7314. * Convert a datetime (Date object) into a position on the screen
  7315. * @param {Date} time A date
  7316. * @return {int} x The position on the screen in pixels which corresponds
  7317. * with the given date.
  7318. * @private
  7319. */
  7320. Timeline.prototype._toScreen = function _toScreen(time) {
  7321. var conversion = this.range.conversion(this.content.width);
  7322. return (time.valueOf() - conversion.offset) * conversion.scale;
  7323. };
  7324. (function(exports) {
  7325. /**
  7326. * Parse a text source containing data in DOT language into a JSON object.
  7327. * The object contains two lists: one with nodes and one with edges.
  7328. *
  7329. * DOT language reference: http://www.graphviz.org/doc/info/lang.html
  7330. *
  7331. * @param {String} data Text containing a graph in DOT-notation
  7332. * @return {Object} graph An object containing two parameters:
  7333. * {Object[]} nodes
  7334. * {Object[]} edges
  7335. */
  7336. function parseDOT (data) {
  7337. dot = data;
  7338. return parseGraph();
  7339. }
  7340. // token types enumeration
  7341. var TOKENTYPE = {
  7342. NULL : 0,
  7343. DELIMITER : 1,
  7344. IDENTIFIER: 2,
  7345. UNKNOWN : 3
  7346. };
  7347. // map with all delimiters
  7348. var DELIMITERS = {
  7349. '{': true,
  7350. '}': true,
  7351. '[': true,
  7352. ']': true,
  7353. ';': true,
  7354. '=': true,
  7355. ',': true,
  7356. '->': true,
  7357. '--': true
  7358. };
  7359. var dot = ''; // current dot file
  7360. var index = 0; // current index in dot file
  7361. var c = ''; // current token character in expr
  7362. var token = ''; // current token
  7363. var tokenType = TOKENTYPE.NULL; // type of the token
  7364. /**
  7365. * Get the first character from the dot file.
  7366. * The character is stored into the char c. If the end of the dot file is
  7367. * reached, the function puts an empty string in c.
  7368. */
  7369. function first() {
  7370. index = 0;
  7371. c = dot.charAt(0);
  7372. }
  7373. /**
  7374. * Get the next character from the dot file.
  7375. * The character is stored into the char c. If the end of the dot file is
  7376. * reached, the function puts an empty string in c.
  7377. */
  7378. function next() {
  7379. index++;
  7380. c = dot.charAt(index);
  7381. }
  7382. /**
  7383. * Preview the next character from the dot file.
  7384. * @return {String} cNext
  7385. */
  7386. function nextPreview() {
  7387. return dot.charAt(index + 1);
  7388. }
  7389. /**
  7390. * Test whether given character is alphabetic or numeric
  7391. * @param {String} c
  7392. * @return {Boolean} isAlphaNumeric
  7393. */
  7394. var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/;
  7395. function isAlphaNumeric(c) {
  7396. return regexAlphaNumeric.test(c);
  7397. }
  7398. /**
  7399. * Merge all properties of object b into object b
  7400. * @param {Object} a
  7401. * @param {Object} b
  7402. * @return {Object} a
  7403. */
  7404. function merge (a, b) {
  7405. if (!a) {
  7406. a = {};
  7407. }
  7408. if (b) {
  7409. for (var name in b) {
  7410. if (b.hasOwnProperty(name)) {
  7411. a[name] = b[name];
  7412. }
  7413. }
  7414. }
  7415. return a;
  7416. }
  7417. /**
  7418. * Set a value in an object, where the provided parameter name can be a
  7419. * path with nested parameters. For example:
  7420. *
  7421. * var obj = {a: 2};
  7422. * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}}
  7423. *
  7424. * @param {Object} obj
  7425. * @param {String} path A parameter name or dot-separated parameter path,
  7426. * like "color.highlight.border".
  7427. * @param {*} value
  7428. */
  7429. function setValue(obj, path, value) {
  7430. var keys = path.split('.');
  7431. var o = obj;
  7432. while (keys.length) {
  7433. var key = keys.shift();
  7434. if (keys.length) {
  7435. // this isn't the end point
  7436. if (!o[key]) {
  7437. o[key] = {};
  7438. }
  7439. o = o[key];
  7440. }
  7441. else {
  7442. // this is the end point
  7443. o[key] = value;
  7444. }
  7445. }
  7446. }
  7447. /**
  7448. * Add a node to a graph object. If there is already a node with
  7449. * the same id, their attributes will be merged.
  7450. * @param {Object} graph
  7451. * @param {Object} node
  7452. */
  7453. function addNode(graph, node) {
  7454. var i, len;
  7455. var current = null;
  7456. // find root graph (in case of subgraph)
  7457. var graphs = [graph]; // list with all graphs from current graph to root graph
  7458. var root = graph;
  7459. while (root.parent) {
  7460. graphs.push(root.parent);
  7461. root = root.parent;
  7462. }
  7463. // find existing node (at root level) by its id
  7464. if (root.nodes) {
  7465. for (i = 0, len = root.nodes.length; i < len; i++) {
  7466. if (node.id === root.nodes[i].id) {
  7467. current = root.nodes[i];
  7468. break;
  7469. }
  7470. }
  7471. }
  7472. if (!current) {
  7473. // this is a new node
  7474. current = {
  7475. id: node.id
  7476. };
  7477. if (graph.node) {
  7478. // clone default attributes
  7479. current.attr = merge(current.attr, graph.node);
  7480. }
  7481. }
  7482. // add node to this (sub)graph and all its parent graphs
  7483. for (i = graphs.length - 1; i >= 0; i--) {
  7484. var g = graphs[i];
  7485. if (!g.nodes) {
  7486. g.nodes = [];
  7487. }
  7488. if (g.nodes.indexOf(current) == -1) {
  7489. g.nodes.push(current);
  7490. }
  7491. }
  7492. // merge attributes
  7493. if (node.attr) {
  7494. current.attr = merge(current.attr, node.attr);
  7495. }
  7496. }
  7497. /**
  7498. * Add an edge to a graph object
  7499. * @param {Object} graph
  7500. * @param {Object} edge
  7501. */
  7502. function addEdge(graph, edge) {
  7503. if (!graph.edges) {
  7504. graph.edges = [];
  7505. }
  7506. graph.edges.push(edge);
  7507. if (graph.edge) {
  7508. var attr = merge({}, graph.edge); // clone default attributes
  7509. edge.attr = merge(attr, edge.attr); // merge attributes
  7510. }
  7511. }
  7512. /**
  7513. * Create an edge to a graph object
  7514. * @param {Object} graph
  7515. * @param {String | Number | Object} from
  7516. * @param {String | Number | Object} to
  7517. * @param {String} type
  7518. * @param {Object | null} attr
  7519. * @return {Object} edge
  7520. */
  7521. function createEdge(graph, from, to, type, attr) {
  7522. var edge = {
  7523. from: from,
  7524. to: to,
  7525. type: type
  7526. };
  7527. if (graph.edge) {
  7528. edge.attr = merge({}, graph.edge); // clone default attributes
  7529. }
  7530. edge.attr = merge(edge.attr || {}, attr); // merge attributes
  7531. return edge;
  7532. }
  7533. /**
  7534. * Get next token in the current dot file.
  7535. * The token and token type are available as token and tokenType
  7536. */
  7537. function getToken() {
  7538. tokenType = TOKENTYPE.NULL;
  7539. token = '';
  7540. // skip over whitespaces
  7541. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  7542. next();
  7543. }
  7544. do {
  7545. var isComment = false;
  7546. // skip comment
  7547. if (c == '#') {
  7548. // find the previous non-space character
  7549. var i = index - 1;
  7550. while (dot.charAt(i) == ' ' || dot.charAt(i) == '\t') {
  7551. i--;
  7552. }
  7553. if (dot.charAt(i) == '\n' || dot.charAt(i) == '') {
  7554. // the # is at the start of a line, this is indeed a line comment
  7555. while (c != '' && c != '\n') {
  7556. next();
  7557. }
  7558. isComment = true;
  7559. }
  7560. }
  7561. if (c == '/' && nextPreview() == '/') {
  7562. // skip line comment
  7563. while (c != '' && c != '\n') {
  7564. next();
  7565. }
  7566. isComment = true;
  7567. }
  7568. if (c == '/' && nextPreview() == '*') {
  7569. // skip block comment
  7570. while (c != '') {
  7571. if (c == '*' && nextPreview() == '/') {
  7572. // end of block comment found. skip these last two characters
  7573. next();
  7574. next();
  7575. break;
  7576. }
  7577. else {
  7578. next();
  7579. }
  7580. }
  7581. isComment = true;
  7582. }
  7583. // skip over whitespaces
  7584. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  7585. next();
  7586. }
  7587. }
  7588. while (isComment);
  7589. // check for end of dot file
  7590. if (c == '') {
  7591. // token is still empty
  7592. tokenType = TOKENTYPE.DELIMITER;
  7593. return;
  7594. }
  7595. // check for delimiters consisting of 2 characters
  7596. var c2 = c + nextPreview();
  7597. if (DELIMITERS[c2]) {
  7598. tokenType = TOKENTYPE.DELIMITER;
  7599. token = c2;
  7600. next();
  7601. next();
  7602. return;
  7603. }
  7604. // check for delimiters consisting of 1 character
  7605. if (DELIMITERS[c]) {
  7606. tokenType = TOKENTYPE.DELIMITER;
  7607. token = c;
  7608. next();
  7609. return;
  7610. }
  7611. // check for an identifier (number or string)
  7612. // TODO: more precise parsing of numbers/strings (and the port separator ':')
  7613. if (isAlphaNumeric(c) || c == '-') {
  7614. token += c;
  7615. next();
  7616. while (isAlphaNumeric(c)) {
  7617. token += c;
  7618. next();
  7619. }
  7620. if (token == 'false') {
  7621. token = false; // convert to boolean
  7622. }
  7623. else if (token == 'true') {
  7624. token = true; // convert to boolean
  7625. }
  7626. else if (!isNaN(Number(token))) {
  7627. token = Number(token); // convert to number
  7628. }
  7629. tokenType = TOKENTYPE.IDENTIFIER;
  7630. return;
  7631. }
  7632. // check for a string enclosed by double quotes
  7633. if (c == '"') {
  7634. next();
  7635. while (c != '' && (c != '"' || (c == '"' && nextPreview() == '"'))) {
  7636. token += c;
  7637. if (c == '"') { // skip the escape character
  7638. next();
  7639. }
  7640. next();
  7641. }
  7642. if (c != '"') {
  7643. throw newSyntaxError('End of string " expected');
  7644. }
  7645. next();
  7646. tokenType = TOKENTYPE.IDENTIFIER;
  7647. return;
  7648. }
  7649. // something unknown is found, wrong characters, a syntax error
  7650. tokenType = TOKENTYPE.UNKNOWN;
  7651. while (c != '') {
  7652. token += c;
  7653. next();
  7654. }
  7655. throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"');
  7656. }
  7657. /**
  7658. * Parse a graph.
  7659. * @returns {Object} graph
  7660. */
  7661. function parseGraph() {
  7662. var graph = {};
  7663. first();
  7664. getToken();
  7665. // optional strict keyword
  7666. if (token == 'strict') {
  7667. graph.strict = true;
  7668. getToken();
  7669. }
  7670. // graph or digraph keyword
  7671. if (token == 'graph' || token == 'digraph') {
  7672. graph.type = token;
  7673. getToken();
  7674. }
  7675. // optional graph id
  7676. if (tokenType == TOKENTYPE.IDENTIFIER) {
  7677. graph.id = token;
  7678. getToken();
  7679. }
  7680. // open angle bracket
  7681. if (token != '{') {
  7682. throw newSyntaxError('Angle bracket { expected');
  7683. }
  7684. getToken();
  7685. // statements
  7686. parseStatements(graph);
  7687. // close angle bracket
  7688. if (token != '}') {
  7689. throw newSyntaxError('Angle bracket } expected');
  7690. }
  7691. getToken();
  7692. // end of file
  7693. if (token !== '') {
  7694. throw newSyntaxError('End of file expected');
  7695. }
  7696. getToken();
  7697. // remove temporary default properties
  7698. delete graph.node;
  7699. delete graph.edge;
  7700. delete graph.graph;
  7701. return graph;
  7702. }
  7703. /**
  7704. * Parse a list with statements.
  7705. * @param {Object} graph
  7706. */
  7707. function parseStatements (graph) {
  7708. while (token !== '' && token != '}') {
  7709. parseStatement(graph);
  7710. if (token == ';') {
  7711. getToken();
  7712. }
  7713. }
  7714. }
  7715. /**
  7716. * Parse a single statement. Can be a an attribute statement, node
  7717. * statement, a series of node statements and edge statements, or a
  7718. * parameter.
  7719. * @param {Object} graph
  7720. */
  7721. function parseStatement(graph) {
  7722. // parse subgraph
  7723. var subgraph = parseSubgraph(graph);
  7724. if (subgraph) {
  7725. // edge statements
  7726. parseEdge(graph, subgraph);
  7727. return;
  7728. }
  7729. // parse an attribute statement
  7730. var attr = parseAttributeStatement(graph);
  7731. if (attr) {
  7732. return;
  7733. }
  7734. // parse node
  7735. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7736. throw newSyntaxError('Identifier expected');
  7737. }
  7738. var id = token; // id can be a string or a number
  7739. getToken();
  7740. if (token == '=') {
  7741. // id statement
  7742. getToken();
  7743. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7744. throw newSyntaxError('Identifier expected');
  7745. }
  7746. graph[id] = token;
  7747. getToken();
  7748. // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] "
  7749. }
  7750. else {
  7751. parseNodeStatement(graph, id);
  7752. }
  7753. }
  7754. /**
  7755. * Parse a subgraph
  7756. * @param {Object} graph parent graph object
  7757. * @return {Object | null} subgraph
  7758. */
  7759. function parseSubgraph (graph) {
  7760. var subgraph = null;
  7761. // optional subgraph keyword
  7762. if (token == 'subgraph') {
  7763. subgraph = {};
  7764. subgraph.type = 'subgraph';
  7765. getToken();
  7766. // optional graph id
  7767. if (tokenType == TOKENTYPE.IDENTIFIER) {
  7768. subgraph.id = token;
  7769. getToken();
  7770. }
  7771. }
  7772. // open angle bracket
  7773. if (token == '{') {
  7774. getToken();
  7775. if (!subgraph) {
  7776. subgraph = {};
  7777. }
  7778. subgraph.parent = graph;
  7779. subgraph.node = graph.node;
  7780. subgraph.edge = graph.edge;
  7781. subgraph.graph = graph.graph;
  7782. // statements
  7783. parseStatements(subgraph);
  7784. // close angle bracket
  7785. if (token != '}') {
  7786. throw newSyntaxError('Angle bracket } expected');
  7787. }
  7788. getToken();
  7789. // remove temporary default properties
  7790. delete subgraph.node;
  7791. delete subgraph.edge;
  7792. delete subgraph.graph;
  7793. delete subgraph.parent;
  7794. // register at the parent graph
  7795. if (!graph.subgraphs) {
  7796. graph.subgraphs = [];
  7797. }
  7798. graph.subgraphs.push(subgraph);
  7799. }
  7800. return subgraph;
  7801. }
  7802. /**
  7803. * parse an attribute statement like "node [shape=circle fontSize=16]".
  7804. * Available keywords are 'node', 'edge', 'graph'.
  7805. * The previous list with default attributes will be replaced
  7806. * @param {Object} graph
  7807. * @returns {String | null} keyword Returns the name of the parsed attribute
  7808. * (node, edge, graph), or null if nothing
  7809. * is parsed.
  7810. */
  7811. function parseAttributeStatement (graph) {
  7812. // attribute statements
  7813. if (token == 'node') {
  7814. getToken();
  7815. // node attributes
  7816. graph.node = parseAttributeList();
  7817. return 'node';
  7818. }
  7819. else if (token == 'edge') {
  7820. getToken();
  7821. // edge attributes
  7822. graph.edge = parseAttributeList();
  7823. return 'edge';
  7824. }
  7825. else if (token == 'graph') {
  7826. getToken();
  7827. // graph attributes
  7828. graph.graph = parseAttributeList();
  7829. return 'graph';
  7830. }
  7831. return null;
  7832. }
  7833. /**
  7834. * parse a node statement
  7835. * @param {Object} graph
  7836. * @param {String | Number} id
  7837. */
  7838. function parseNodeStatement(graph, id) {
  7839. // node statement
  7840. var node = {
  7841. id: id
  7842. };
  7843. var attr = parseAttributeList();
  7844. if (attr) {
  7845. node.attr = attr;
  7846. }
  7847. addNode(graph, node);
  7848. // edge statements
  7849. parseEdge(graph, id);
  7850. }
  7851. /**
  7852. * Parse an edge or a series of edges
  7853. * @param {Object} graph
  7854. * @param {String | Number} from Id of the from node
  7855. */
  7856. function parseEdge(graph, from) {
  7857. while (token == '->' || token == '--') {
  7858. var to;
  7859. var type = token;
  7860. getToken();
  7861. var subgraph = parseSubgraph(graph);
  7862. if (subgraph) {
  7863. to = subgraph;
  7864. }
  7865. else {
  7866. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7867. throw newSyntaxError('Identifier or subgraph expected');
  7868. }
  7869. to = token;
  7870. addNode(graph, {
  7871. id: to
  7872. });
  7873. getToken();
  7874. }
  7875. // parse edge attributes
  7876. var attr = parseAttributeList();
  7877. // create edge
  7878. var edge = createEdge(graph, from, to, type, attr);
  7879. addEdge(graph, edge);
  7880. from = to;
  7881. }
  7882. }
  7883. /**
  7884. * Parse a set with attributes,
  7885. * for example [label="1.000", shape=solid]
  7886. * @return {Object | null} attr
  7887. */
  7888. function parseAttributeList() {
  7889. var attr = null;
  7890. while (token == '[') {
  7891. getToken();
  7892. attr = {};
  7893. while (token !== '' && token != ']') {
  7894. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7895. throw newSyntaxError('Attribute name expected');
  7896. }
  7897. var name = token;
  7898. getToken();
  7899. if (token != '=') {
  7900. throw newSyntaxError('Equal sign = expected');
  7901. }
  7902. getToken();
  7903. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7904. throw newSyntaxError('Attribute value expected');
  7905. }
  7906. var value = token;
  7907. setValue(attr, name, value); // name can be a path
  7908. getToken();
  7909. if (token ==',') {
  7910. getToken();
  7911. }
  7912. }
  7913. if (token != ']') {
  7914. throw newSyntaxError('Bracket ] expected');
  7915. }
  7916. getToken();
  7917. }
  7918. return attr;
  7919. }
  7920. /**
  7921. * Create a syntax error with extra information on current token and index.
  7922. * @param {String} message
  7923. * @returns {SyntaxError} err
  7924. */
  7925. function newSyntaxError(message) {
  7926. return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')');
  7927. }
  7928. /**
  7929. * Chop off text after a maximum length
  7930. * @param {String} text
  7931. * @param {Number} maxLength
  7932. * @returns {String}
  7933. */
  7934. function chop (text, maxLength) {
  7935. return (text.length <= maxLength) ? text : (text.substr(0, 27) + '...');
  7936. }
  7937. /**
  7938. * Execute a function fn for each pair of elements in two arrays
  7939. * @param {Array | *} array1
  7940. * @param {Array | *} array2
  7941. * @param {function} fn
  7942. */
  7943. function forEach2(array1, array2, fn) {
  7944. if (array1 instanceof Array) {
  7945. array1.forEach(function (elem1) {
  7946. if (array2 instanceof Array) {
  7947. array2.forEach(function (elem2) {
  7948. fn(elem1, elem2);
  7949. });
  7950. }
  7951. else {
  7952. fn(elem1, array2);
  7953. }
  7954. });
  7955. }
  7956. else {
  7957. if (array2 instanceof Array) {
  7958. array2.forEach(function (elem2) {
  7959. fn(array1, elem2);
  7960. });
  7961. }
  7962. else {
  7963. fn(array1, array2);
  7964. }
  7965. }
  7966. }
  7967. /**
  7968. * Convert a string containing a graph in DOT language into a map containing
  7969. * with nodes and edges in the format of graph.
  7970. * @param {String} data Text containing a graph in DOT-notation
  7971. * @return {Object} graphData
  7972. */
  7973. function DOTToGraph (data) {
  7974. // parse the DOT file
  7975. var dotData = parseDOT(data);
  7976. var graphData = {
  7977. nodes: [],
  7978. edges: [],
  7979. options: {}
  7980. };
  7981. // copy the nodes
  7982. if (dotData.nodes) {
  7983. dotData.nodes.forEach(function (dotNode) {
  7984. var graphNode = {
  7985. id: dotNode.id,
  7986. label: String(dotNode.label || dotNode.id)
  7987. };
  7988. merge(graphNode, dotNode.attr);
  7989. if (graphNode.image) {
  7990. graphNode.shape = 'image';
  7991. }
  7992. graphData.nodes.push(graphNode);
  7993. });
  7994. }
  7995. // copy the edges
  7996. if (dotData.edges) {
  7997. /**
  7998. * Convert an edge in DOT format to an edge with VisGraph format
  7999. * @param {Object} dotEdge
  8000. * @returns {Object} graphEdge
  8001. */
  8002. function convertEdge(dotEdge) {
  8003. var graphEdge = {
  8004. from: dotEdge.from,
  8005. to: dotEdge.to
  8006. };
  8007. merge(graphEdge, dotEdge.attr);
  8008. graphEdge.style = (dotEdge.type == '->') ? 'arrow' : 'line';
  8009. return graphEdge;
  8010. }
  8011. dotData.edges.forEach(function (dotEdge) {
  8012. var from, to;
  8013. if (dotEdge.from instanceof Object) {
  8014. from = dotEdge.from.nodes;
  8015. }
  8016. else {
  8017. from = {
  8018. id: dotEdge.from
  8019. }
  8020. }
  8021. if (dotEdge.to instanceof Object) {
  8022. to = dotEdge.to.nodes;
  8023. }
  8024. else {
  8025. to = {
  8026. id: dotEdge.to
  8027. }
  8028. }
  8029. if (dotEdge.from instanceof Object && dotEdge.from.edges) {
  8030. dotEdge.from.edges.forEach(function (subEdge) {
  8031. var graphEdge = convertEdge(subEdge);
  8032. graphData.edges.push(graphEdge);
  8033. });
  8034. }
  8035. forEach2(from, to, function (from, to) {
  8036. var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr);
  8037. var graphEdge = convertEdge(subEdge);
  8038. graphData.edges.push(graphEdge);
  8039. });
  8040. if (dotEdge.to instanceof Object && dotEdge.to.edges) {
  8041. dotEdge.to.edges.forEach(function (subEdge) {
  8042. var graphEdge = convertEdge(subEdge);
  8043. graphData.edges.push(graphEdge);
  8044. });
  8045. }
  8046. });
  8047. }
  8048. // copy the options
  8049. if (dotData.attr) {
  8050. graphData.options = dotData.attr;
  8051. }
  8052. return graphData;
  8053. }
  8054. // exports
  8055. exports.parseDOT = parseDOT;
  8056. exports.DOTToGraph = DOTToGraph;
  8057. })(typeof util !== 'undefined' ? util : exports);
  8058. /**
  8059. * Canvas shapes used by the Graph
  8060. */
  8061. if (typeof CanvasRenderingContext2D !== 'undefined') {
  8062. /**
  8063. * Draw a circle shape
  8064. */
  8065. CanvasRenderingContext2D.prototype.circle = function(x, y, r) {
  8066. this.beginPath();
  8067. this.arc(x, y, r, 0, 2*Math.PI, false);
  8068. };
  8069. /**
  8070. * Draw a square shape
  8071. * @param {Number} x horizontal center
  8072. * @param {Number} y vertical center
  8073. * @param {Number} r size, width and height of the square
  8074. */
  8075. CanvasRenderingContext2D.prototype.square = function(x, y, r) {
  8076. this.beginPath();
  8077. this.rect(x - r, y - r, r * 2, r * 2);
  8078. };
  8079. /**
  8080. * Draw a triangle shape
  8081. * @param {Number} x horizontal center
  8082. * @param {Number} y vertical center
  8083. * @param {Number} r radius, half the length of the sides of the triangle
  8084. */
  8085. CanvasRenderingContext2D.prototype.triangle = function(x, y, r) {
  8086. // http://en.wikipedia.org/wiki/Equilateral_triangle
  8087. this.beginPath();
  8088. var s = r * 2;
  8089. var s2 = s / 2;
  8090. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  8091. var h = Math.sqrt(s * s - s2 * s2); // height
  8092. this.moveTo(x, y - (h - ir));
  8093. this.lineTo(x + s2, y + ir);
  8094. this.lineTo(x - s2, y + ir);
  8095. this.lineTo(x, y - (h - ir));
  8096. this.closePath();
  8097. };
  8098. /**
  8099. * Draw a triangle shape in downward orientation
  8100. * @param {Number} x horizontal center
  8101. * @param {Number} y vertical center
  8102. * @param {Number} r radius
  8103. */
  8104. CanvasRenderingContext2D.prototype.triangleDown = function(x, y, r) {
  8105. // http://en.wikipedia.org/wiki/Equilateral_triangle
  8106. this.beginPath();
  8107. var s = r * 2;
  8108. var s2 = s / 2;
  8109. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  8110. var h = Math.sqrt(s * s - s2 * s2); // height
  8111. this.moveTo(x, y + (h - ir));
  8112. this.lineTo(x + s2, y - ir);
  8113. this.lineTo(x - s2, y - ir);
  8114. this.lineTo(x, y + (h - ir));
  8115. this.closePath();
  8116. };
  8117. /**
  8118. * Draw a star shape, a star with 5 points
  8119. * @param {Number} x horizontal center
  8120. * @param {Number} y vertical center
  8121. * @param {Number} r radius, half the length of the sides of the triangle
  8122. */
  8123. CanvasRenderingContext2D.prototype.star = function(x, y, r) {
  8124. // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/
  8125. this.beginPath();
  8126. for (var n = 0; n < 10; n++) {
  8127. var radius = (n % 2 === 0) ? r * 1.3 : r * 0.5;
  8128. this.lineTo(
  8129. x + radius * Math.sin(n * 2 * Math.PI / 10),
  8130. y - radius * Math.cos(n * 2 * Math.PI / 10)
  8131. );
  8132. }
  8133. this.closePath();
  8134. };
  8135. /**
  8136. * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas
  8137. */
  8138. CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) {
  8139. var r2d = Math.PI/180;
  8140. if( w - ( 2 * r ) < 0 ) { r = ( w / 2 ); } //ensure that the radius isn't too large for x
  8141. if( h - ( 2 * r ) < 0 ) { r = ( h / 2 ); } //ensure that the radius isn't too large for y
  8142. this.beginPath();
  8143. this.moveTo(x+r,y);
  8144. this.lineTo(x+w-r,y);
  8145. this.arc(x+w-r,y+r,r,r2d*270,r2d*360,false);
  8146. this.lineTo(x+w,y+h-r);
  8147. this.arc(x+w-r,y+h-r,r,0,r2d*90,false);
  8148. this.lineTo(x+r,y+h);
  8149. this.arc(x+r,y+h-r,r,r2d*90,r2d*180,false);
  8150. this.lineTo(x,y+r);
  8151. this.arc(x+r,y+r,r,r2d*180,r2d*270,false);
  8152. };
  8153. /**
  8154. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  8155. */
  8156. CanvasRenderingContext2D.prototype.ellipse = function(x, y, w, h) {
  8157. var kappa = .5522848,
  8158. ox = (w / 2) * kappa, // control point offset horizontal
  8159. oy = (h / 2) * kappa, // control point offset vertical
  8160. xe = x + w, // x-end
  8161. ye = y + h, // y-end
  8162. xm = x + w / 2, // x-middle
  8163. ym = y + h / 2; // y-middle
  8164. this.beginPath();
  8165. this.moveTo(x, ym);
  8166. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  8167. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  8168. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  8169. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  8170. };
  8171. /**
  8172. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  8173. */
  8174. CanvasRenderingContext2D.prototype.database = function(x, y, w, h) {
  8175. var f = 1/3;
  8176. var wEllipse = w;
  8177. var hEllipse = h * f;
  8178. var kappa = .5522848,
  8179. ox = (wEllipse / 2) * kappa, // control point offset horizontal
  8180. oy = (hEllipse / 2) * kappa, // control point offset vertical
  8181. xe = x + wEllipse, // x-end
  8182. ye = y + hEllipse, // y-end
  8183. xm = x + wEllipse / 2, // x-middle
  8184. ym = y + hEllipse / 2, // y-middle
  8185. ymb = y + (h - hEllipse/2), // y-midlle, bottom ellipse
  8186. yeb = y + h; // y-end, bottom ellipse
  8187. this.beginPath();
  8188. this.moveTo(xe, ym);
  8189. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  8190. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  8191. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  8192. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  8193. this.lineTo(xe, ymb);
  8194. this.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb);
  8195. this.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb);
  8196. this.lineTo(x, ym);
  8197. };
  8198. /**
  8199. * Draw an arrow point (no line)
  8200. */
  8201. CanvasRenderingContext2D.prototype.arrow = function(x, y, angle, length) {
  8202. // tail
  8203. var xt = x - length * Math.cos(angle);
  8204. var yt = y - length * Math.sin(angle);
  8205. // inner tail
  8206. // TODO: allow to customize different shapes
  8207. var xi = x - length * 0.9 * Math.cos(angle);
  8208. var yi = y - length * 0.9 * Math.sin(angle);
  8209. // left
  8210. var xl = xt + length / 3 * Math.cos(angle + 0.5 * Math.PI);
  8211. var yl = yt + length / 3 * Math.sin(angle + 0.5 * Math.PI);
  8212. // right
  8213. var xr = xt + length / 3 * Math.cos(angle - 0.5 * Math.PI);
  8214. var yr = yt + length / 3 * Math.sin(angle - 0.5 * Math.PI);
  8215. this.beginPath();
  8216. this.moveTo(x, y);
  8217. this.lineTo(xl, yl);
  8218. this.lineTo(xi, yi);
  8219. this.lineTo(xr, yr);
  8220. this.closePath();
  8221. };
  8222. /**
  8223. * Sets up the dashedLine functionality for drawing
  8224. * Original code came from http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
  8225. * @author David Jordan
  8226. * @date 2012-08-08
  8227. */
  8228. CanvasRenderingContext2D.prototype.dashedLine = function(x,y,x2,y2,dashArray){
  8229. if (!dashArray) dashArray=[10,5];
  8230. if (dashLength==0) dashLength = 0.001; // Hack for Safari
  8231. var dashCount = dashArray.length;
  8232. this.moveTo(x, y);
  8233. var dx = (x2-x), dy = (y2-y);
  8234. var slope = dy/dx;
  8235. var distRemaining = Math.sqrt( dx*dx + dy*dy );
  8236. var dashIndex=0, draw=true;
  8237. while (distRemaining>=0.1){
  8238. var dashLength = dashArray[dashIndex++%dashCount];
  8239. if (dashLength > distRemaining) dashLength = distRemaining;
  8240. var xStep = Math.sqrt( dashLength*dashLength / (1 + slope*slope) );
  8241. if (dx<0) xStep = -xStep;
  8242. x += xStep;
  8243. y += slope*xStep;
  8244. this[draw ? 'lineTo' : 'moveTo'](x,y);
  8245. distRemaining -= dashLength;
  8246. draw = !draw;
  8247. }
  8248. };
  8249. // TODO: add diamond shape
  8250. }
  8251. /**
  8252. * @class Node
  8253. * A node. A node can be connected to other nodes via one or multiple edges.
  8254. * @param {object} properties An object containing properties for the node. All
  8255. * properties are optional, except for the id.
  8256. * {number} id Id of the node. Required
  8257. * {string} label Text label for the node
  8258. * {number} x Horizontal position of the node
  8259. * {number} y Vertical position of the node
  8260. * {string} shape Node shape, available:
  8261. * "database", "circle", "ellipse",
  8262. * "box", "image", "text", "dot",
  8263. * "star", "triangle", "triangleDown",
  8264. * "square"
  8265. * {string} image An image url
  8266. * {string} title An title text, can be HTML
  8267. * {anytype} group A group name or number
  8268. * @param {Graph.Images} imagelist A list with images. Only needed
  8269. * when the node has an image
  8270. * @param {Graph.Groups} grouplist A list with groups. Needed for
  8271. * retrieving group properties
  8272. * @param {Object} constants An object with default values for
  8273. * example for the color
  8274. *
  8275. */
  8276. function Node(properties, imagelist, grouplist, constants) {
  8277. this.selected = false;
  8278. this.edges = []; // all edges connected to this node
  8279. this.dynamicEdges = [];
  8280. this.reroutedEdges = {};
  8281. this.group = constants.nodes.group;
  8282. this.fontSize = constants.nodes.fontSize;
  8283. this.fontFace = constants.nodes.fontFace;
  8284. this.fontColor = constants.nodes.fontColor;
  8285. this.fontDrawThreshold = 3;
  8286. this.color = constants.nodes.color;
  8287. // set defaults for the properties
  8288. this.id = undefined;
  8289. this.shape = constants.nodes.shape;
  8290. this.image = constants.nodes.image;
  8291. this.x = null;
  8292. this.y = null;
  8293. this.xFixed = false;
  8294. this.yFixed = false;
  8295. this.horizontalAlignLeft = true; // these are for the navigation controls
  8296. this.verticalAlignTop = true; // these are for the navigation controls
  8297. this.radius = constants.nodes.radius;
  8298. this.baseRadiusValue = constants.nodes.radius;
  8299. this.radiusFixed = false;
  8300. this.radiusMin = constants.nodes.radiusMin;
  8301. this.radiusMax = constants.nodes.radiusMax;
  8302. this.level = -1;
  8303. this.imagelist = imagelist;
  8304. this.grouplist = grouplist;
  8305. // physics properties
  8306. this.fx = 0.0; // external force x
  8307. this.fy = 0.0; // external force y
  8308. this.vx = 0.0; // velocity x
  8309. this.vy = 0.0; // velocity y
  8310. this.minForce = constants.minForce;
  8311. this.damping = constants.physics.damping;
  8312. this.mass = 1; // kg
  8313. this.setProperties(properties, constants);
  8314. // creating the variables for clustering
  8315. this.resetCluster();
  8316. this.dynamicEdgesLength = 0;
  8317. this.clusterSession = 0;
  8318. this.clusterSizeWidthFactor = constants.clustering.nodeScaling.width;
  8319. this.clusterSizeHeightFactor = constants.clustering.nodeScaling.height;
  8320. this.clusterSizeRadiusFactor = constants.clustering.nodeScaling.radius;
  8321. this.maxNodeSizeIncrements = constants.clustering.maxNodeSizeIncrements;
  8322. this.growthIndicator = 0;
  8323. // variables to tell the node about the graph.
  8324. this.graphScaleInv = 1;
  8325. this.graphScale = 1;
  8326. this.canvasTopLeft = {"x": -300, "y": -300};
  8327. this.canvasBottomRight = {"x": 300, "y": 300};
  8328. this.parentEdgeId = null;
  8329. }
  8330. /**
  8331. * (re)setting the clustering variables and objects
  8332. */
  8333. Node.prototype.resetCluster = function() {
  8334. // clustering variables
  8335. this.formationScale = undefined; // this is used to determine when to open the cluster
  8336. this.clusterSize = 1; // this signifies the total amount of nodes in this cluster
  8337. this.containedNodes = {};
  8338. this.containedEdges = {};
  8339. this.clusterSessions = [];
  8340. };
  8341. /**
  8342. * Attach a edge to the node
  8343. * @param {Edge} edge
  8344. */
  8345. Node.prototype.attachEdge = function(edge) {
  8346. if (this.edges.indexOf(edge) == -1) {
  8347. this.edges.push(edge);
  8348. }
  8349. if (this.dynamicEdges.indexOf(edge) == -1) {
  8350. this.dynamicEdges.push(edge);
  8351. }
  8352. this.dynamicEdgesLength = this.dynamicEdges.length;
  8353. };
  8354. /**
  8355. * Detach a edge from the node
  8356. * @param {Edge} edge
  8357. */
  8358. Node.prototype.detachEdge = function(edge) {
  8359. var index = this.edges.indexOf(edge);
  8360. if (index != -1) {
  8361. this.edges.splice(index, 1);
  8362. this.dynamicEdges.splice(index, 1);
  8363. }
  8364. this.dynamicEdgesLength = this.dynamicEdges.length;
  8365. };
  8366. /**
  8367. * Set or overwrite properties for the node
  8368. * @param {Object} properties an object with properties
  8369. * @param {Object} constants and object with default, global properties
  8370. */
  8371. Node.prototype.setProperties = function(properties, constants) {
  8372. if (!properties) {
  8373. return;
  8374. }
  8375. this.originalLabel = undefined;
  8376. // basic properties
  8377. if (properties.id !== undefined) {this.id = properties.id;}
  8378. if (properties.label !== undefined) {this.label = properties.label; this.originalLabel = properties.label;}
  8379. if (properties.title !== undefined) {this.title = properties.title;}
  8380. if (properties.group !== undefined) {this.group = properties.group;}
  8381. if (properties.x !== undefined) {this.x = properties.x;}
  8382. if (properties.y !== undefined) {this.y = properties.y;}
  8383. if (properties.value !== undefined) {this.value = properties.value;}
  8384. if (properties.level !== undefined) {this.level = properties.level;}
  8385. // physics
  8386. if (properties.internalMultiplier !== undefined) {this.internalMultiplier = properties.internalMultiplier;}
  8387. if (properties.damping !== undefined) {this.dampingBase = properties.damping;}
  8388. if (properties.mass !== undefined) {this.mass = properties.mass;}
  8389. // navigation controls properties
  8390. if (properties.horizontalAlignLeft !== undefined) {this.horizontalAlignLeft = properties.horizontalAlignLeft;}
  8391. if (properties.verticalAlignTop !== undefined) {this.verticalAlignTop = properties.verticalAlignTop;}
  8392. if (properties.triggerFunction !== undefined) {this.triggerFunction = properties.triggerFunction;}
  8393. if (this.id === undefined) {
  8394. throw "Node must have an id";
  8395. }
  8396. // copy group properties
  8397. if (this.group) {
  8398. var groupObj = this.grouplist.get(this.group);
  8399. for (var prop in groupObj) {
  8400. if (groupObj.hasOwnProperty(prop)) {
  8401. this[prop] = groupObj[prop];
  8402. }
  8403. }
  8404. }
  8405. // individual shape properties
  8406. if (properties.shape !== undefined) {this.shape = properties.shape;}
  8407. if (properties.image !== undefined) {this.image = properties.image;}
  8408. if (properties.radius !== undefined) {this.radius = properties.radius;}
  8409. if (properties.color !== undefined) {this.color = Node.parseColor(properties.color);}
  8410. if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;}
  8411. if (properties.fontSize !== undefined) {this.fontSize = properties.fontSize;}
  8412. if (properties.fontFace !== undefined) {this.fontFace = properties.fontFace;}
  8413. if (this.image !== undefined) {
  8414. if (this.imagelist) {
  8415. this.imageObj = this.imagelist.load(this.image);
  8416. }
  8417. else {
  8418. throw "No imagelist provided";
  8419. }
  8420. }
  8421. this.xFixed = this.xFixed || (properties.x !== undefined && !properties.allowedToMoveX);
  8422. this.yFixed = this.yFixed || (properties.y !== undefined && !properties.allowedToMoveY);
  8423. this.radiusFixed = this.radiusFixed || (properties.radius !== undefined);
  8424. if (this.shape == 'image') {
  8425. this.radiusMin = constants.nodes.widthMin;
  8426. this.radiusMax = constants.nodes.widthMax;
  8427. }
  8428. // choose draw method depending on the shape
  8429. switch (this.shape) {
  8430. case 'database': this.draw = this._drawDatabase; this.resize = this._resizeDatabase; break;
  8431. case 'box': this.draw = this._drawBox; this.resize = this._resizeBox; break;
  8432. case 'circle': this.draw = this._drawCircle; this.resize = this._resizeCircle; break;
  8433. case 'ellipse': this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  8434. // TODO: add diamond shape
  8435. case 'image': this.draw = this._drawImage; this.resize = this._resizeImage; break;
  8436. case 'text': this.draw = this._drawText; this.resize = this._resizeText; break;
  8437. case 'dot': this.draw = this._drawDot; this.resize = this._resizeShape; break;
  8438. case 'square': this.draw = this._drawSquare; this.resize = this._resizeShape; break;
  8439. case 'triangle': this.draw = this._drawTriangle; this.resize = this._resizeShape; break;
  8440. case 'triangleDown': this.draw = this._drawTriangleDown; this.resize = this._resizeShape; break;
  8441. case 'star': this.draw = this._drawStar; this.resize = this._resizeShape; break;
  8442. default: this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  8443. }
  8444. // reset the size of the node, this can be changed
  8445. this._reset();
  8446. };
  8447. /**
  8448. * Parse a color property into an object with border, background, and
  8449. * hightlight colors
  8450. * @param {Object | String} color
  8451. * @return {Object} colorObject
  8452. */
  8453. Node.parseColor = function(color) {
  8454. var c;
  8455. if (util.isString(color)) {
  8456. if (util.isValidHex(color)) {
  8457. var hsv = util.hexToHSV(color);
  8458. var lighterColorHSV = {h:hsv.h,s:hsv.s * 0.45,v:Math.min(1,hsv.v * 1.05)};
  8459. var darkerColorHSV = {h:hsv.h,s:Math.min(1,hsv.v * 1.25),v:hsv.v*0.6};
  8460. var darkerColorHex = util.HSVToHex(darkerColorHSV.h ,darkerColorHSV.h ,darkerColorHSV.v);
  8461. var lighterColorHex = util.HSVToHex(lighterColorHSV.h,lighterColorHSV.s,lighterColorHSV.v);
  8462. c = {
  8463. background: color,
  8464. border:darkerColorHex,
  8465. highlight: {
  8466. background:lighterColorHex,
  8467. border:darkerColorHex
  8468. }
  8469. };
  8470. }
  8471. else {
  8472. c = {
  8473. background:color,
  8474. border:color,
  8475. highlight: {
  8476. background:color,
  8477. border:color
  8478. }
  8479. };
  8480. }
  8481. }
  8482. else {
  8483. c = {};
  8484. c.background = color.background || 'white';
  8485. c.border = color.border || c.background;
  8486. if (util.isString(color.highlight)) {
  8487. c.highlight = {
  8488. border: color.highlight,
  8489. background: color.highlight
  8490. }
  8491. }
  8492. else {
  8493. c.highlight = {};
  8494. c.highlight.background = color.highlight && color.highlight.background || c.background;
  8495. c.highlight.border = color.highlight && color.highlight.border || c.border;
  8496. }
  8497. }
  8498. return c;
  8499. };
  8500. /**
  8501. * select this node
  8502. */
  8503. Node.prototype.select = function() {
  8504. this.selected = true;
  8505. this._reset();
  8506. };
  8507. /**
  8508. * unselect this node
  8509. */
  8510. Node.prototype.unselect = function() {
  8511. this.selected = false;
  8512. this._reset();
  8513. };
  8514. /**
  8515. * Reset the calculated size of the node, forces it to recalculate its size
  8516. */
  8517. Node.prototype.clearSizeCache = function() {
  8518. this._reset();
  8519. };
  8520. /**
  8521. * Reset the calculated size of the node, forces it to recalculate its size
  8522. * @private
  8523. */
  8524. Node.prototype._reset = function() {
  8525. this.width = undefined;
  8526. this.height = undefined;
  8527. };
  8528. /**
  8529. * get the title of this node.
  8530. * @return {string} title The title of the node, or undefined when no title
  8531. * has been set.
  8532. */
  8533. Node.prototype.getTitle = function() {
  8534. return this.title;
  8535. };
  8536. /**
  8537. * Calculate the distance to the border of the Node
  8538. * @param {CanvasRenderingContext2D} ctx
  8539. * @param {Number} angle Angle in radians
  8540. * @returns {number} distance Distance to the border in pixels
  8541. */
  8542. Node.prototype.distanceToBorder = function (ctx, angle) {
  8543. var borderWidth = 1;
  8544. if (!this.width) {
  8545. this.resize(ctx);
  8546. }
  8547. switch (this.shape) {
  8548. case 'circle':
  8549. case 'dot':
  8550. return this.radius + borderWidth;
  8551. case 'ellipse':
  8552. var a = this.width / 2;
  8553. var b = this.height / 2;
  8554. var w = (Math.sin(angle) * a);
  8555. var h = (Math.cos(angle) * b);
  8556. return a * b / Math.sqrt(w * w + h * h);
  8557. // TODO: implement distanceToBorder for database
  8558. // TODO: implement distanceToBorder for triangle
  8559. // TODO: implement distanceToBorder for triangleDown
  8560. case 'box':
  8561. case 'image':
  8562. case 'text':
  8563. default:
  8564. if (this.width) {
  8565. return Math.min(
  8566. Math.abs(this.width / 2 / Math.cos(angle)),
  8567. Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth;
  8568. // TODO: reckon with border radius too in case of box
  8569. }
  8570. else {
  8571. return 0;
  8572. }
  8573. }
  8574. // TODO: implement calculation of distance to border for all shapes
  8575. };
  8576. /**
  8577. * Set forces acting on the node
  8578. * @param {number} fx Force in horizontal direction
  8579. * @param {number} fy Force in vertical direction
  8580. */
  8581. Node.prototype._setForce = function(fx, fy) {
  8582. this.fx = fx;
  8583. this.fy = fy;
  8584. };
  8585. /**
  8586. * Add forces acting on the node
  8587. * @param {number} fx Force in horizontal direction
  8588. * @param {number} fy Force in vertical direction
  8589. * @private
  8590. */
  8591. Node.prototype._addForce = function(fx, fy) {
  8592. this.fx += fx;
  8593. this.fy += fy;
  8594. };
  8595. /**
  8596. * Perform one discrete step for the node
  8597. * @param {number} interval Time interval in seconds
  8598. */
  8599. Node.prototype.discreteStep = function(interval) {
  8600. if (!this.xFixed) {
  8601. var dx = this.damping * this.vx; // damping force
  8602. var ax = (this.fx - dx) / this.mass; // acceleration
  8603. this.vx += ax * interval; // velocity
  8604. this.x += this.vx * interval; // position
  8605. }
  8606. if (!this.yFixed) {
  8607. var dy = this.damping * this.vy; // damping force
  8608. var ay = (this.fy - dy) / this.mass; // acceleration
  8609. this.vy += ay * interval; // velocity
  8610. this.y += this.vy * interval; // position
  8611. }
  8612. };
  8613. /**
  8614. * Perform one discrete step for the node
  8615. * @param {number} interval Time interval in seconds
  8616. */
  8617. Node.prototype.discreteStepLimited = function(interval, maxVelocity) {
  8618. if (!this.xFixed) {
  8619. var dx = this.damping * this.vx; // damping force
  8620. var ax = (this.fx - dx) / this.mass; // acceleration
  8621. this.vx += ax * interval; // velocity
  8622. this.vx = (Math.abs(this.vx) > maxVelocity) ? ((this.vx > 0) ? maxVelocity : -maxVelocity) : this.vx;
  8623. this.x += this.vx * interval; // position
  8624. }
  8625. if (!this.yFixed) {
  8626. var dy = this.damping * this.vy; // damping force
  8627. var ay = (this.fy - dy) / this.mass; // acceleration
  8628. this.vy += ay * interval; // velocity
  8629. this.vy = (Math.abs(this.vy) > maxVelocity) ? ((this.vy > 0) ? maxVelocity : -maxVelocity) : this.vy;
  8630. this.y += this.vy * interval; // position
  8631. }
  8632. };
  8633. /**
  8634. * Check if this node has a fixed x and y position
  8635. * @return {boolean} true if fixed, false if not
  8636. */
  8637. Node.prototype.isFixed = function() {
  8638. return (this.xFixed && this.yFixed);
  8639. };
  8640. /**
  8641. * Check if this node is moving
  8642. * @param {number} vmin the minimum velocity considered as "moving"
  8643. * @return {boolean} true if moving, false if it has no velocity
  8644. */
  8645. // TODO: replace this method with calculating the kinetic energy
  8646. Node.prototype.isMoving = function(vmin) {
  8647. return (Math.abs(this.vx) > vmin || Math.abs(this.vy) > vmin);
  8648. };
  8649. /**
  8650. * check if this node is selecte
  8651. * @return {boolean} selected True if node is selected, else false
  8652. */
  8653. Node.prototype.isSelected = function() {
  8654. return this.selected;
  8655. };
  8656. /**
  8657. * Retrieve the value of the node. Can be undefined
  8658. * @return {Number} value
  8659. */
  8660. Node.prototype.getValue = function() {
  8661. return this.value;
  8662. };
  8663. /**
  8664. * Calculate the distance from the nodes location to the given location (x,y)
  8665. * @param {Number} x
  8666. * @param {Number} y
  8667. * @return {Number} value
  8668. */
  8669. Node.prototype.getDistance = function(x, y) {
  8670. var dx = this.x - x,
  8671. dy = this.y - y;
  8672. return Math.sqrt(dx * dx + dy * dy);
  8673. };
  8674. /**
  8675. * Adjust the value range of the node. The node will adjust it's radius
  8676. * based on its value.
  8677. * @param {Number} min
  8678. * @param {Number} max
  8679. */
  8680. Node.prototype.setValueRange = function(min, max) {
  8681. if (!this.radiusFixed && this.value !== undefined) {
  8682. if (max == min) {
  8683. this.radius = (this.radiusMin + this.radiusMax) / 2;
  8684. }
  8685. else {
  8686. var scale = (this.radiusMax - this.radiusMin) / (max - min);
  8687. this.radius = (this.value - min) * scale + this.radiusMin;
  8688. }
  8689. }
  8690. this.baseRadiusValue = this.radius;
  8691. };
  8692. /**
  8693. * Draw this node in the given canvas
  8694. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8695. * @param {CanvasRenderingContext2D} ctx
  8696. */
  8697. Node.prototype.draw = function(ctx) {
  8698. throw "Draw method not initialized for node";
  8699. };
  8700. /**
  8701. * Recalculate the size of this node in the given canvas
  8702. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8703. * @param {CanvasRenderingContext2D} ctx
  8704. */
  8705. Node.prototype.resize = function(ctx) {
  8706. throw "Resize method not initialized for node";
  8707. };
  8708. /**
  8709. * Check if this object is overlapping with the provided object
  8710. * @param {Object} obj an object with parameters left, top, right, bottom
  8711. * @return {boolean} True if location is located on node
  8712. */
  8713. Node.prototype.isOverlappingWith = function(obj) {
  8714. return (this.left < obj.right &&
  8715. this.left + this.width > obj.left &&
  8716. this.top < obj.bottom &&
  8717. this.top + this.height > obj.top);
  8718. };
  8719. Node.prototype._resizeImage = function (ctx) {
  8720. // TODO: pre calculate the image size
  8721. if (!this.width || !this.height) { // undefined or 0
  8722. var width, height;
  8723. if (this.value) {
  8724. this.radius = this.baseRadiusValue;
  8725. var scale = this.imageObj.height / this.imageObj.width;
  8726. if (scale !== undefined) {
  8727. width = this.radius || this.imageObj.width;
  8728. height = this.radius * scale || this.imageObj.height;
  8729. }
  8730. else {
  8731. width = 0;
  8732. height = 0;
  8733. }
  8734. }
  8735. else {
  8736. width = this.imageObj.width;
  8737. height = this.imageObj.height;
  8738. }
  8739. this.width = width;
  8740. this.height = height;
  8741. this.growthIndicator = 0;
  8742. if (this.width > 0 && this.height > 0) {
  8743. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8744. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8745. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8746. this.growthIndicator = this.width - width;
  8747. }
  8748. }
  8749. };
  8750. Node.prototype._drawImage = function (ctx) {
  8751. this._resizeImage(ctx);
  8752. this.left = this.x - this.width / 2;
  8753. this.top = this.y - this.height / 2;
  8754. var yLabel;
  8755. if (this.imageObj.width != 0 ) {
  8756. // draw the shade
  8757. if (this.clusterSize > 1) {
  8758. var lineWidth = ((this.clusterSize > 1) ? 10 : 0.0);
  8759. lineWidth *= this.graphScaleInv;
  8760. lineWidth = Math.min(0.2 * this.width,lineWidth);
  8761. ctx.globalAlpha = 0.5;
  8762. ctx.drawImage(this.imageObj, this.left - lineWidth, this.top - lineWidth, this.width + 2*lineWidth, this.height + 2*lineWidth);
  8763. }
  8764. // draw the image
  8765. ctx.globalAlpha = 1.0;
  8766. ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height);
  8767. yLabel = this.y + this.height / 2;
  8768. }
  8769. else {
  8770. // image still loading... just draw the label for now
  8771. yLabel = this.y;
  8772. }
  8773. this._label(ctx, this.label, this.x, yLabel, undefined, "top");
  8774. };
  8775. Node.prototype._resizeBox = function (ctx) {
  8776. if (!this.width) {
  8777. var margin = 5;
  8778. var textSize = this.getTextSize(ctx);
  8779. this.width = textSize.width + 2 * margin;
  8780. this.height = textSize.height + 2 * margin;
  8781. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  8782. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  8783. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  8784. // this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8785. }
  8786. };
  8787. Node.prototype._drawBox = function (ctx) {
  8788. this._resizeBox(ctx);
  8789. this.left = this.x - this.width / 2;
  8790. this.top = this.y - this.height / 2;
  8791. var clusterLineWidth = 2.5;
  8792. var selectionLineWidth = 2;
  8793. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8794. // draw the outer border
  8795. if (this.clusterSize > 1) {
  8796. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8797. ctx.lineWidth *= this.graphScaleInv;
  8798. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8799. ctx.roundRect(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth, this.radius);
  8800. ctx.stroke();
  8801. }
  8802. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8803. ctx.lineWidth *= this.graphScaleInv;
  8804. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8805. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8806. ctx.roundRect(this.left, this.top, this.width, this.height, this.radius);
  8807. ctx.fill();
  8808. ctx.stroke();
  8809. this._label(ctx, this.label, this.x, this.y);
  8810. };
  8811. Node.prototype._resizeDatabase = function (ctx) {
  8812. if (!this.width) {
  8813. var margin = 5;
  8814. var textSize = this.getTextSize(ctx);
  8815. var size = textSize.width + 2 * margin;
  8816. this.width = size;
  8817. this.height = size;
  8818. // scaling used for clustering
  8819. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8820. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8821. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8822. this.growthIndicator = this.width - size;
  8823. }
  8824. };
  8825. Node.prototype._drawDatabase = function (ctx) {
  8826. this._resizeDatabase(ctx);
  8827. this.left = this.x - this.width / 2;
  8828. this.top = this.y - this.height / 2;
  8829. var clusterLineWidth = 2.5;
  8830. var selectionLineWidth = 2;
  8831. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8832. // draw the outer border
  8833. if (this.clusterSize > 1) {
  8834. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8835. ctx.lineWidth *= this.graphScaleInv;
  8836. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8837. ctx.database(this.x - this.width/2 - 2*ctx.lineWidth, this.y - this.height*0.5 - 2*ctx.lineWidth, this.width + 4*ctx.lineWidth, this.height + 4*ctx.lineWidth);
  8838. ctx.stroke();
  8839. }
  8840. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8841. ctx.lineWidth *= this.graphScaleInv;
  8842. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8843. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8844. ctx.database(this.x - this.width/2, this.y - this.height*0.5, this.width, this.height);
  8845. ctx.fill();
  8846. ctx.stroke();
  8847. this._label(ctx, this.label, this.x, this.y);
  8848. };
  8849. Node.prototype._resizeCircle = function (ctx) {
  8850. if (!this.width) {
  8851. var margin = 5;
  8852. var textSize = this.getTextSize(ctx);
  8853. var diameter = Math.max(textSize.width, textSize.height) + 2 * margin;
  8854. this.radius = diameter / 2;
  8855. this.width = diameter;
  8856. this.height = diameter;
  8857. // scaling used for clustering
  8858. // this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  8859. // this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  8860. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8861. this.growthIndicator = this.radius - 0.5*diameter;
  8862. }
  8863. };
  8864. Node.prototype._drawCircle = function (ctx) {
  8865. this._resizeCircle(ctx);
  8866. this.left = this.x - this.width / 2;
  8867. this.top = this.y - this.height / 2;
  8868. var clusterLineWidth = 2.5;
  8869. var selectionLineWidth = 2;
  8870. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8871. // draw the outer border
  8872. if (this.clusterSize > 1) {
  8873. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8874. ctx.lineWidth *= this.graphScaleInv;
  8875. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8876. ctx.circle(this.x, this.y, this.radius+2*ctx.lineWidth);
  8877. ctx.stroke();
  8878. }
  8879. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8880. ctx.lineWidth *= this.graphScaleInv;
  8881. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8882. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8883. ctx.circle(this.x, this.y, this.radius);
  8884. ctx.fill();
  8885. ctx.stroke();
  8886. this._label(ctx, this.label, this.x, this.y);
  8887. };
  8888. Node.prototype._resizeEllipse = function (ctx) {
  8889. if (!this.width) {
  8890. var textSize = this.getTextSize(ctx);
  8891. this.width = textSize.width * 1.5;
  8892. this.height = textSize.height * 2;
  8893. if (this.width < this.height) {
  8894. this.width = this.height;
  8895. }
  8896. var defaultSize = this.width;
  8897. // scaling used for clustering
  8898. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8899. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8900. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8901. this.growthIndicator = this.width - defaultSize;
  8902. }
  8903. };
  8904. Node.prototype._drawEllipse = function (ctx) {
  8905. this._resizeEllipse(ctx);
  8906. this.left = this.x - this.width / 2;
  8907. this.top = this.y - this.height / 2;
  8908. var clusterLineWidth = 2.5;
  8909. var selectionLineWidth = 2;
  8910. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8911. // draw the outer border
  8912. if (this.clusterSize > 1) {
  8913. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8914. ctx.lineWidth *= this.graphScaleInv;
  8915. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8916. ctx.ellipse(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth);
  8917. ctx.stroke();
  8918. }
  8919. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8920. ctx.lineWidth *= this.graphScaleInv;
  8921. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8922. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8923. ctx.ellipse(this.left, this.top, this.width, this.height);
  8924. ctx.fill();
  8925. ctx.stroke();
  8926. this._label(ctx, this.label, this.x, this.y);
  8927. };
  8928. Node.prototype._drawDot = function (ctx) {
  8929. this._drawShape(ctx, 'circle');
  8930. };
  8931. Node.prototype._drawTriangle = function (ctx) {
  8932. this._drawShape(ctx, 'triangle');
  8933. };
  8934. Node.prototype._drawTriangleDown = function (ctx) {
  8935. this._drawShape(ctx, 'triangleDown');
  8936. };
  8937. Node.prototype._drawSquare = function (ctx) {
  8938. this._drawShape(ctx, 'square');
  8939. };
  8940. Node.prototype._drawStar = function (ctx) {
  8941. this._drawShape(ctx, 'star');
  8942. };
  8943. Node.prototype._resizeShape = function (ctx) {
  8944. if (!this.width) {
  8945. this.radius = this.baseRadiusValue;
  8946. var size = 2 * this.radius;
  8947. this.width = size;
  8948. this.height = size;
  8949. // scaling used for clustering
  8950. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8951. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8952. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8953. this.growthIndicator = this.width - size;
  8954. }
  8955. };
  8956. Node.prototype._drawShape = function (ctx, shape) {
  8957. this._resizeShape(ctx);
  8958. this.left = this.x - this.width / 2;
  8959. this.top = this.y - this.height / 2;
  8960. var clusterLineWidth = 2.5;
  8961. var selectionLineWidth = 2;
  8962. var radiusMultiplier = 2;
  8963. // choose draw method depending on the shape
  8964. switch (shape) {
  8965. case 'dot': radiusMultiplier = 2; break;
  8966. case 'square': radiusMultiplier = 2; break;
  8967. case 'triangle': radiusMultiplier = 3; break;
  8968. case 'triangleDown': radiusMultiplier = 3; break;
  8969. case 'star': radiusMultiplier = 4; break;
  8970. }
  8971. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8972. // draw the outer border
  8973. if (this.clusterSize > 1) {
  8974. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8975. ctx.lineWidth *= this.graphScaleInv;
  8976. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8977. ctx[shape](this.x, this.y, this.radius + radiusMultiplier * ctx.lineWidth);
  8978. ctx.stroke();
  8979. }
  8980. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8981. ctx.lineWidth *= this.graphScaleInv;
  8982. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8983. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8984. ctx[shape](this.x, this.y, this.radius);
  8985. ctx.fill();
  8986. ctx.stroke();
  8987. if (this.label) {
  8988. this._label(ctx, this.label, this.x, this.y + this.height / 2, undefined, 'top');
  8989. }
  8990. };
  8991. Node.prototype._resizeText = function (ctx) {
  8992. if (!this.width) {
  8993. var margin = 5;
  8994. var textSize = this.getTextSize(ctx);
  8995. this.width = textSize.width + 2 * margin;
  8996. this.height = textSize.height + 2 * margin;
  8997. // scaling used for clustering
  8998. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8999. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  9000. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  9001. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  9002. }
  9003. };
  9004. Node.prototype._drawText = function (ctx) {
  9005. this._resizeText(ctx);
  9006. this.left = this.x - this.width / 2;
  9007. this.top = this.y - this.height / 2;
  9008. this._label(ctx, this.label, this.x, this.y);
  9009. };
  9010. Node.prototype._label = function (ctx, text, x, y, align, baseline) {
  9011. if (text && this.fontSize * this.graphScale > this.fontDrawThreshold) {
  9012. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  9013. ctx.fillStyle = this.fontColor || "black";
  9014. ctx.textAlign = align || "center";
  9015. ctx.textBaseline = baseline || "middle";
  9016. var lines = text.split('\n'),
  9017. lineCount = lines.length,
  9018. fontSize = (this.fontSize + 4),
  9019. yLine = y + (1 - lineCount) / 2 * fontSize;
  9020. for (var i = 0; i < lineCount; i++) {
  9021. ctx.fillText(lines[i], x, yLine);
  9022. yLine += fontSize;
  9023. }
  9024. }
  9025. };
  9026. Node.prototype.getTextSize = function(ctx) {
  9027. if (this.label !== undefined) {
  9028. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  9029. var lines = this.label.split('\n'),
  9030. height = (this.fontSize + 4) * lines.length,
  9031. width = 0;
  9032. for (var i = 0, iMax = lines.length; i < iMax; i++) {
  9033. width = Math.max(width, ctx.measureText(lines[i]).width);
  9034. }
  9035. return {"width": width, "height": height};
  9036. }
  9037. else {
  9038. return {"width": 0, "height": 0};
  9039. }
  9040. };
  9041. /**
  9042. * this is used to determine if a node is visible at all. this is used to determine when it needs to be drawn.
  9043. * there is a safety margin of 0.3 * width;
  9044. *
  9045. * @returns {boolean}
  9046. */
  9047. Node.prototype.inArea = function() {
  9048. if (this.width !== undefined) {
  9049. return (this.x + this.width*this.graphScaleInv >= this.canvasTopLeft.x &&
  9050. this.x - this.width*this.graphScaleInv < this.canvasBottomRight.x &&
  9051. this.y + this.height*this.graphScaleInv >= this.canvasTopLeft.y &&
  9052. this.y - this.height*this.graphScaleInv < this.canvasBottomRight.y);
  9053. }
  9054. else {
  9055. return true;
  9056. }
  9057. };
  9058. /**
  9059. * checks if the core of the node is in the display area, this is used for opening clusters around zoom
  9060. * @returns {boolean}
  9061. */
  9062. Node.prototype.inView = function() {
  9063. return (this.x >= this.canvasTopLeft.x &&
  9064. this.x < this.canvasBottomRight.x &&
  9065. this.y >= this.canvasTopLeft.y &&
  9066. this.y < this.canvasBottomRight.y);
  9067. };
  9068. /**
  9069. * This allows the zoom level of the graph to influence the rendering
  9070. * We store the inverted scale and the coordinates of the top left, and bottom right points of the canvas
  9071. *
  9072. * @param scale
  9073. * @param canvasTopLeft
  9074. * @param canvasBottomRight
  9075. */
  9076. Node.prototype.setScaleAndPos = function(scale,canvasTopLeft,canvasBottomRight) {
  9077. this.graphScaleInv = 1.0/scale;
  9078. this.graphScale = scale;
  9079. this.canvasTopLeft = canvasTopLeft;
  9080. this.canvasBottomRight = canvasBottomRight;
  9081. };
  9082. /**
  9083. * This allows the zoom level of the graph to influence the rendering
  9084. *
  9085. * @param scale
  9086. */
  9087. Node.prototype.setScale = function(scale) {
  9088. this.graphScaleInv = 1.0/scale;
  9089. this.graphScale = scale;
  9090. };
  9091. /**
  9092. * set the velocity at 0. Is called when this node is contained in another during clustering
  9093. */
  9094. Node.prototype.clearVelocity = function() {
  9095. this.vx = 0;
  9096. this.vy = 0;
  9097. };
  9098. /**
  9099. * Basic preservation of (kinectic) energy
  9100. *
  9101. * @param massBeforeClustering
  9102. */
  9103. Node.prototype.updateVelocity = function(massBeforeClustering) {
  9104. var energyBefore = this.vx * this.vx * massBeforeClustering;
  9105. //this.vx = (this.vx < 0) ? -Math.sqrt(energyBefore/this.mass) : Math.sqrt(energyBefore/this.mass);
  9106. this.vx = Math.sqrt(energyBefore/this.mass);
  9107. energyBefore = this.vy * this.vy * massBeforeClustering;
  9108. //this.vy = (this.vy < 0) ? -Math.sqrt(energyBefore/this.mass) : Math.sqrt(energyBefore/this.mass);
  9109. this.vy = Math.sqrt(energyBefore/this.mass);
  9110. };
  9111. /**
  9112. * @class Edge
  9113. *
  9114. * A edge connects two nodes
  9115. * @param {Object} properties Object with properties. Must contain
  9116. * At least properties from and to.
  9117. * Available properties: from (number),
  9118. * to (number), label (string, color (string),
  9119. * width (number), style (string),
  9120. * length (number), title (string)
  9121. * @param {Graph} graph A graph object, used to find and edge to
  9122. * nodes.
  9123. * @param {Object} constants An object with default values for
  9124. * example for the color
  9125. */
  9126. function Edge (properties, graph, constants) {
  9127. if (!graph) {
  9128. throw "No graph provided";
  9129. }
  9130. this.graph = graph;
  9131. // initialize constants
  9132. this.widthMin = constants.edges.widthMin;
  9133. this.widthMax = constants.edges.widthMax;
  9134. // initialize variables
  9135. this.id = undefined;
  9136. this.fromId = undefined;
  9137. this.toId = undefined;
  9138. this.style = constants.edges.style;
  9139. this.title = undefined;
  9140. this.width = constants.edges.width;
  9141. this.value = undefined;
  9142. this.length = constants.physics.springLength;
  9143. this.customLength = false;
  9144. this.selected = false;
  9145. this.smooth = constants.smoothCurves;
  9146. this.from = null; // a node
  9147. this.to = null; // a node
  9148. this.via = null; // a temp node
  9149. // we use this to be able to reconnect the edge to a cluster if its node is put into a cluster
  9150. // by storing the original information we can revert to the original connection when the cluser is opened.
  9151. this.originalFromId = [];
  9152. this.originalToId = [];
  9153. this.connected = false;
  9154. // Added to support dashed lines
  9155. // David Jordan
  9156. // 2012-08-08
  9157. this.dash = util.extend({}, constants.edges.dash); // contains properties length, gap, altLength
  9158. this.color = {color:constants.edges.color.color,
  9159. highlight:constants.edges.color.highlight};
  9160. this.widthFixed = false;
  9161. this.lengthFixed = false;
  9162. this.setProperties(properties, constants);
  9163. }
  9164. /**
  9165. * Set or overwrite properties for the edge
  9166. * @param {Object} properties an object with properties
  9167. * @param {Object} constants and object with default, global properties
  9168. */
  9169. Edge.prototype.setProperties = function(properties, constants) {
  9170. if (!properties) {
  9171. return;
  9172. }
  9173. if (properties.from !== undefined) {this.fromId = properties.from;}
  9174. if (properties.to !== undefined) {this.toId = properties.to;}
  9175. if (properties.id !== undefined) {this.id = properties.id;}
  9176. if (properties.style !== undefined) {this.style = properties.style;}
  9177. if (properties.label !== undefined) {this.label = properties.label;}
  9178. if (this.label) {
  9179. this.fontSize = constants.edges.fontSize;
  9180. this.fontFace = constants.edges.fontFace;
  9181. this.fontColor = constants.edges.fontColor;
  9182. if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;}
  9183. if (properties.fontSize !== undefined) {this.fontSize = properties.fontSize;}
  9184. if (properties.fontFace !== undefined) {this.fontFace = properties.fontFace;}
  9185. }
  9186. if (properties.title !== undefined) {this.title = properties.title;}
  9187. if (properties.width !== undefined) {this.width = properties.width;}
  9188. if (properties.value !== undefined) {this.value = properties.value;}
  9189. if (properties.length !== undefined) {this.length = properties.length;
  9190. this.customLength = true;}
  9191. // Added to support dashed lines
  9192. // David Jordan
  9193. // 2012-08-08
  9194. if (properties.dash) {
  9195. if (properties.dash.length !== undefined) {this.dash.length = properties.dash.length;}
  9196. if (properties.dash.gap !== undefined) {this.dash.gap = properties.dash.gap;}
  9197. if (properties.dash.altLength !== undefined) {this.dash.altLength = properties.dash.altLength;}
  9198. }
  9199. if (properties.color !== undefined) {
  9200. if (util.isString(properties.color)) {
  9201. this.color.color = properties.color;
  9202. this.color.highlight = properties.color;
  9203. }
  9204. else {
  9205. if (properties.color.color !== undefined) {this.color.color = properties.color.color;}
  9206. if (properties.color.highlight !== undefined) {this.color.highlight = properties.color.highlight;}
  9207. }
  9208. }
  9209. // A node is connected when it has a from and to node.
  9210. this.connect();
  9211. this.widthFixed = this.widthFixed || (properties.width !== undefined);
  9212. this.lengthFixed = this.lengthFixed || (properties.length !== undefined);
  9213. // set draw method based on style
  9214. switch (this.style) {
  9215. case 'line': this.draw = this._drawLine; break;
  9216. case 'arrow': this.draw = this._drawArrow; break;
  9217. case 'arrow-center': this.draw = this._drawArrowCenter; break;
  9218. case 'dash-line': this.draw = this._drawDashLine; break;
  9219. default: this.draw = this._drawLine; break;
  9220. }
  9221. };
  9222. /**
  9223. * Connect an edge to its nodes
  9224. */
  9225. Edge.prototype.connect = function () {
  9226. this.disconnect();
  9227. this.from = this.graph.nodes[this.fromId] || null;
  9228. this.to = this.graph.nodes[this.toId] || null;
  9229. this.connected = (this.from && this.to);
  9230. if (this.connected) {
  9231. this.from.attachEdge(this);
  9232. this.to.attachEdge(this);
  9233. }
  9234. else {
  9235. if (this.from) {
  9236. this.from.detachEdge(this);
  9237. }
  9238. if (this.to) {
  9239. this.to.detachEdge(this);
  9240. }
  9241. }
  9242. };
  9243. /**
  9244. * Disconnect an edge from its nodes
  9245. */
  9246. Edge.prototype.disconnect = function () {
  9247. if (this.from) {
  9248. this.from.detachEdge(this);
  9249. this.from = null;
  9250. }
  9251. if (this.to) {
  9252. this.to.detachEdge(this);
  9253. this.to = null;
  9254. }
  9255. this.connected = false;
  9256. };
  9257. /**
  9258. * get the title of this edge.
  9259. * @return {string} title The title of the edge, or undefined when no title
  9260. * has been set.
  9261. */
  9262. Edge.prototype.getTitle = function() {
  9263. return this.title;
  9264. };
  9265. /**
  9266. * Retrieve the value of the edge. Can be undefined
  9267. * @return {Number} value
  9268. */
  9269. Edge.prototype.getValue = function() {
  9270. return this.value;
  9271. };
  9272. /**
  9273. * Adjust the value range of the edge. The edge will adjust it's width
  9274. * based on its value.
  9275. * @param {Number} min
  9276. * @param {Number} max
  9277. */
  9278. Edge.prototype.setValueRange = function(min, max) {
  9279. if (!this.widthFixed && this.value !== undefined) {
  9280. var scale = (this.widthMax - this.widthMin) / (max - min);
  9281. this.width = (this.value - min) * scale + this.widthMin;
  9282. }
  9283. };
  9284. /**
  9285. * Redraw a edge
  9286. * Draw this edge in the given canvas
  9287. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9288. * @param {CanvasRenderingContext2D} ctx
  9289. */
  9290. Edge.prototype.draw = function(ctx) {
  9291. throw "Method draw not initialized in edge";
  9292. };
  9293. /**
  9294. * Check if this object is overlapping with the provided object
  9295. * @param {Object} obj an object with parameters left, top
  9296. * @return {boolean} True if location is located on the edge
  9297. */
  9298. Edge.prototype.isOverlappingWith = function(obj) {
  9299. var distMax = 10;
  9300. var xFrom = this.from.x;
  9301. var yFrom = this.from.y;
  9302. var xTo = this.to.x;
  9303. var yTo = this.to.y;
  9304. var xObj = obj.left;
  9305. var yObj = obj.top;
  9306. var dist = this._getDistanceToEdge(xFrom, yFrom, xTo, yTo, xObj, yObj);
  9307. return (dist < distMax);
  9308. };
  9309. /**
  9310. * Redraw a edge as a line
  9311. * Draw this edge in the given canvas
  9312. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9313. * @param {CanvasRenderingContext2D} ctx
  9314. * @private
  9315. */
  9316. Edge.prototype._drawLine = function(ctx) {
  9317. // set style
  9318. if (this.selected == true) {ctx.strokeStyle = this.color.highlight;}
  9319. else {ctx.strokeStyle = this.color.color;}
  9320. ctx.lineWidth = this._getLineWidth();
  9321. if (this.from != this.to) {
  9322. // draw line
  9323. this._line(ctx);
  9324. // draw label
  9325. var point;
  9326. if (this.label) {
  9327. if (this.smooth == true) {
  9328. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9329. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9330. point = {x:midpointX, y:midpointY};
  9331. }
  9332. else {
  9333. point = this._pointOnLine(0.5);
  9334. }
  9335. this._label(ctx, this.label, point.x, point.y);
  9336. }
  9337. }
  9338. else {
  9339. var x, y;
  9340. var radius = this.length / 4;
  9341. var node = this.from;
  9342. if (!node.width) {
  9343. node.resize(ctx);
  9344. }
  9345. if (node.width > node.height) {
  9346. x = node.x + node.width / 2;
  9347. y = node.y - radius;
  9348. }
  9349. else {
  9350. x = node.x + radius;
  9351. y = node.y - node.height / 2;
  9352. }
  9353. this._circle(ctx, x, y, radius);
  9354. point = this._pointOnCircle(x, y, radius, 0.5);
  9355. this._label(ctx, this.label, point.x, point.y);
  9356. }
  9357. };
  9358. /**
  9359. * Get the line width of the edge. Depends on width and whether one of the
  9360. * connected nodes is selected.
  9361. * @return {Number} width
  9362. * @private
  9363. */
  9364. Edge.prototype._getLineWidth = function() {
  9365. if (this.selected == true) {
  9366. return Math.min(this.width * 2, this.widthMax)*this.graphScaleInv;
  9367. }
  9368. else {
  9369. return this.width*this.graphScaleInv;
  9370. }
  9371. };
  9372. /**
  9373. * Draw a line between two nodes
  9374. * @param {CanvasRenderingContext2D} ctx
  9375. * @private
  9376. */
  9377. Edge.prototype._line = function (ctx) {
  9378. // draw a straight line
  9379. ctx.beginPath();
  9380. ctx.moveTo(this.from.x, this.from.y);
  9381. if (this.smooth == true) {
  9382. ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y);
  9383. }
  9384. else {
  9385. ctx.lineTo(this.to.x, this.to.y);
  9386. }
  9387. ctx.stroke();
  9388. };
  9389. /**
  9390. * Draw a line from a node to itself, a circle
  9391. * @param {CanvasRenderingContext2D} ctx
  9392. * @param {Number} x
  9393. * @param {Number} y
  9394. * @param {Number} radius
  9395. * @private
  9396. */
  9397. Edge.prototype._circle = function (ctx, x, y, radius) {
  9398. // draw a circle
  9399. ctx.beginPath();
  9400. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  9401. ctx.stroke();
  9402. };
  9403. /**
  9404. * Draw label with white background and with the middle at (x, y)
  9405. * @param {CanvasRenderingContext2D} ctx
  9406. * @param {String} text
  9407. * @param {Number} x
  9408. * @param {Number} y
  9409. * @private
  9410. */
  9411. Edge.prototype._label = function (ctx, text, x, y) {
  9412. if (text) {
  9413. // TODO: cache the calculated size
  9414. ctx.font = ((this.from.selected || this.to.selected) ? "bold " : "") +
  9415. this.fontSize + "px " + this.fontFace;
  9416. ctx.fillStyle = 'white';
  9417. var width = ctx.measureText(text).width;
  9418. var height = this.fontSize;
  9419. var left = x - width / 2;
  9420. var top = y - height / 2;
  9421. ctx.fillRect(left, top, width, height);
  9422. // draw text
  9423. ctx.fillStyle = this.fontColor || "black";
  9424. ctx.textAlign = "left";
  9425. ctx.textBaseline = "top";
  9426. ctx.fillText(text, left, top);
  9427. }
  9428. };
  9429. /**
  9430. * Redraw a edge as a dashed line
  9431. * Draw this edge in the given canvas
  9432. * @author David Jordan
  9433. * @date 2012-08-08
  9434. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9435. * @param {CanvasRenderingContext2D} ctx
  9436. * @private
  9437. */
  9438. Edge.prototype._drawDashLine = function(ctx) {
  9439. // set style
  9440. if (this.selected == true) {ctx.strokeStyle = this.color.highlight;}
  9441. else {ctx.strokeStyle = this.color.color;}
  9442. ctx.lineWidth = this._getLineWidth();
  9443. // only firefox and chrome support this method, else we use the legacy one.
  9444. if (ctx.mozDash !== undefined || ctx.setLineDash !== undefined) {
  9445. ctx.beginPath();
  9446. ctx.moveTo(this.from.x, this.from.y);
  9447. // configure the dash pattern
  9448. var pattern = [0];
  9449. if (this.dash.length !== undefined && this.dash.gap !== undefined) {
  9450. pattern = [this.dash.length,this.dash.gap];
  9451. }
  9452. else {
  9453. pattern = [5,5];
  9454. }
  9455. // set dash settings for chrome or firefox
  9456. if (typeof ctx.setLineDash !== 'undefined') { //Chrome
  9457. ctx.setLineDash(pattern);
  9458. ctx.lineDashOffset = 0;
  9459. } else { //Firefox
  9460. ctx.mozDash = pattern;
  9461. ctx.mozDashOffset = 0;
  9462. }
  9463. // draw the line
  9464. if (this.smooth == true) {
  9465. ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y);
  9466. }
  9467. else {
  9468. ctx.lineTo(this.to.x, this.to.y);
  9469. }
  9470. ctx.stroke();
  9471. // restore the dash settings.
  9472. if (typeof ctx.setLineDash !== 'undefined') { //Chrome
  9473. ctx.setLineDash([0]);
  9474. ctx.lineDashOffset = 0;
  9475. } else { //Firefox
  9476. ctx.mozDash = [0];
  9477. ctx.mozDashOffset = 0;
  9478. }
  9479. }
  9480. else { // unsupporting smooth lines
  9481. // draw dashed line
  9482. ctx.beginPath();
  9483. ctx.lineCap = 'round';
  9484. if (this.dash.altLength !== undefined) //If an alt dash value has been set add to the array this value
  9485. {
  9486. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  9487. [this.dash.length,this.dash.gap,this.dash.altLength,this.dash.gap]);
  9488. }
  9489. 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
  9490. {
  9491. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  9492. [this.dash.length,this.dash.gap]);
  9493. }
  9494. else //If all else fails draw a line
  9495. {
  9496. ctx.moveTo(this.from.x, this.from.y);
  9497. ctx.lineTo(this.to.x, this.to.y);
  9498. }
  9499. ctx.stroke();
  9500. }
  9501. // draw label
  9502. if (this.label) {
  9503. var point;
  9504. if (this.smooth == true) {
  9505. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9506. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9507. point = {x:midpointX, y:midpointY};
  9508. }
  9509. else {
  9510. point = this._pointOnLine(0.5);
  9511. }
  9512. this._label(ctx, this.label, point.x, point.y);
  9513. }
  9514. };
  9515. /**
  9516. * Get a point on a line
  9517. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  9518. * @return {Object} point
  9519. * @private
  9520. */
  9521. Edge.prototype._pointOnLine = function (percentage) {
  9522. return {
  9523. x: (1 - percentage) * this.from.x + percentage * this.to.x,
  9524. y: (1 - percentage) * this.from.y + percentage * this.to.y
  9525. }
  9526. };
  9527. /**
  9528. * Get a point on a circle
  9529. * @param {Number} x
  9530. * @param {Number} y
  9531. * @param {Number} radius
  9532. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  9533. * @return {Object} point
  9534. * @private
  9535. */
  9536. Edge.prototype._pointOnCircle = function (x, y, radius, percentage) {
  9537. var angle = (percentage - 3/8) * 2 * Math.PI;
  9538. return {
  9539. x: x + radius * Math.cos(angle),
  9540. y: y - radius * Math.sin(angle)
  9541. }
  9542. };
  9543. /**
  9544. * Redraw a edge as a line with an arrow halfway the line
  9545. * Draw this edge in the given canvas
  9546. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9547. * @param {CanvasRenderingContext2D} ctx
  9548. * @private
  9549. */
  9550. Edge.prototype._drawArrowCenter = function(ctx) {
  9551. var point;
  9552. // set style
  9553. if (this.selected == true) {ctx.strokeStyle = this.color.highlight; ctx.fillStyle = this.color.highlight;}
  9554. else {ctx.strokeStyle = this.color.color; ctx.fillStyle = this.color.color;}
  9555. ctx.lineWidth = this._getLineWidth();
  9556. if (this.from != this.to) {
  9557. // draw line
  9558. this._line(ctx);
  9559. var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  9560. var length = 10 + 5 * this.width; // TODO: make customizable?
  9561. // draw an arrow halfway the line
  9562. if (this.smooth == true) {
  9563. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9564. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9565. point = {x:midpointX, y:midpointY};
  9566. }
  9567. else {
  9568. point = this._pointOnLine(0.5);
  9569. }
  9570. ctx.arrow(point.x, point.y, angle, length);
  9571. ctx.fill();
  9572. ctx.stroke();
  9573. // draw label
  9574. if (this.label) {
  9575. this._label(ctx, this.label, point.x, point.y);
  9576. }
  9577. }
  9578. else {
  9579. // draw circle
  9580. var x, y;
  9581. var radius = 0.25 * Math.max(100,this.length);
  9582. var node = this.from;
  9583. if (!node.width) {
  9584. node.resize(ctx);
  9585. }
  9586. if (node.width > node.height) {
  9587. x = node.x + node.width * 0.5;
  9588. y = node.y - radius;
  9589. }
  9590. else {
  9591. x = node.x + radius;
  9592. y = node.y - node.height * 0.5;
  9593. }
  9594. this._circle(ctx, x, y, radius);
  9595. // draw all arrows
  9596. var angle = 0.2 * Math.PI;
  9597. var length = 10 + 5 * this.width; // TODO: make customizable?
  9598. point = this._pointOnCircle(x, y, radius, 0.5);
  9599. ctx.arrow(point.x, point.y, angle, length);
  9600. ctx.fill();
  9601. ctx.stroke();
  9602. // draw label
  9603. if (this.label) {
  9604. point = this._pointOnCircle(x, y, radius, 0.5);
  9605. this._label(ctx, this.label, point.x, point.y);
  9606. }
  9607. }
  9608. };
  9609. /**
  9610. * Redraw a edge as a line with an arrow
  9611. * Draw this edge in the given canvas
  9612. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9613. * @param {CanvasRenderingContext2D} ctx
  9614. * @private
  9615. */
  9616. Edge.prototype._drawArrow = function(ctx) {
  9617. // set style
  9618. if (this.selected == true) {ctx.strokeStyle = this.color.highlight; ctx.fillStyle = this.color.highlight;}
  9619. else {ctx.strokeStyle = this.color.color; ctx.fillStyle = this.color.color;}
  9620. ctx.lineWidth = this._getLineWidth();
  9621. var angle, length;
  9622. //draw a line
  9623. if (this.from != this.to) {
  9624. angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  9625. var dx = (this.to.x - this.from.x);
  9626. var dy = (this.to.y - this.from.y);
  9627. var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  9628. // var fromBorderDist = this.from.distanceToBorder(ctx, angle + Math.PI);
  9629. // var fromBorderPoint = (edgeSegmentLength - fromBorderDist) / edgeSegmentLength;
  9630. // var xFrom = (fromBorderPoint) * this.from.x + (1 - fromBorderPoint) * this.to.x;
  9631. // var yFrom = (fromBorderPoint) * this.from.y + (1 - fromBorderPoint) * this.to.y;
  9632. if (this.smooth == true) {
  9633. angle = Math.atan2((this.to.y - this.via.y), (this.to.x - this.via.x));
  9634. dx = (this.to.x - this.via.x);
  9635. dy = (this.to.y - this.via.y);
  9636. edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  9637. }
  9638. var toBorderDist = this.to.distanceToBorder(ctx, angle);
  9639. var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength;
  9640. var xTo,yTo;
  9641. if (this.smooth == true) {
  9642. xTo = (1 - toBorderPoint) * this.via.x + toBorderPoint * this.to.x;
  9643. yTo = (1 - toBorderPoint) * this.via.y + toBorderPoint * this.to.y;
  9644. }
  9645. else {
  9646. xTo = (1 - toBorderPoint) * this.from.x + toBorderPoint * this.to.x;
  9647. yTo = (1 - toBorderPoint) * this.from.y + toBorderPoint * this.to.y;
  9648. }
  9649. ctx.beginPath();
  9650. ctx.moveTo(this.from.x,this.from.y);
  9651. if (this.smooth == true) {
  9652. ctx.quadraticCurveTo(this.via.x,this.via.y,xTo, yTo);
  9653. }
  9654. else {
  9655. ctx.lineTo(xTo, yTo);
  9656. }
  9657. ctx.stroke();
  9658. // draw arrow at the end of the line
  9659. length = 10 + 5 * this.width;
  9660. ctx.arrow(xTo, yTo, angle, length);
  9661. ctx.fill();
  9662. ctx.stroke();
  9663. // draw label
  9664. if (this.label) {
  9665. var point;
  9666. if (this.smooth == true) {
  9667. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9668. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9669. point = {x:midpointX, y:midpointY};
  9670. }
  9671. else {
  9672. point = this._pointOnLine(0.5);
  9673. }
  9674. this._label(ctx, this.label, point.x, point.y);
  9675. }
  9676. }
  9677. else {
  9678. // draw circle
  9679. var node = this.from;
  9680. var x, y, arrow;
  9681. var radius = 0.25 * Math.max(100,this.length);
  9682. if (!node.width) {
  9683. node.resize(ctx);
  9684. }
  9685. if (node.width > node.height) {
  9686. x = node.x + node.width * 0.5;
  9687. y = node.y - radius;
  9688. arrow = {
  9689. x: x,
  9690. y: node.y,
  9691. angle: 0.9 * Math.PI
  9692. };
  9693. }
  9694. else {
  9695. x = node.x + radius;
  9696. y = node.y - node.height * 0.5;
  9697. arrow = {
  9698. x: node.x,
  9699. y: y,
  9700. angle: 0.6 * Math.PI
  9701. };
  9702. }
  9703. ctx.beginPath();
  9704. // TODO: similarly, for a line without arrows, draw to the border of the nodes instead of the center
  9705. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  9706. ctx.stroke();
  9707. // draw all arrows
  9708. length = 10 + 5 * this.width; // TODO: make customizable?
  9709. ctx.arrow(arrow.x, arrow.y, arrow.angle, length);
  9710. ctx.fill();
  9711. ctx.stroke();
  9712. // draw label
  9713. if (this.label) {
  9714. point = this._pointOnCircle(x, y, radius, 0.5);
  9715. this._label(ctx, this.label, point.x, point.y);
  9716. }
  9717. }
  9718. };
  9719. /**
  9720. * Calculate the distance between a point (x3,y3) and a line segment from
  9721. * (x1,y1) to (x2,y2).
  9722. * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
  9723. * @param {number} x1
  9724. * @param {number} y1
  9725. * @param {number} x2
  9726. * @param {number} y2
  9727. * @param {number} x3
  9728. * @param {number} y3
  9729. * @private
  9730. */
  9731. Edge.prototype._getDistanceToEdge = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is the point
  9732. if (this.smooth == true) {
  9733. var minDistance = 1e9;
  9734. var i,t,x,y,dx,dy;
  9735. for (i = 0; i < 10; i++) {
  9736. t = 0.1*i;
  9737. x = Math.pow(1-t,2)*x1 + (2*t*(1 - t))*this.via.x + Math.pow(t,2)*x2;
  9738. y = Math.pow(1-t,2)*y1 + (2*t*(1 - t))*this.via.y + Math.pow(t,2)*y2;
  9739. dx = Math.abs(x3-x);
  9740. dy = Math.abs(y3-y);
  9741. minDistance = Math.min(minDistance,Math.sqrt(dx*dx + dy*dy));
  9742. }
  9743. return minDistance
  9744. }
  9745. else {
  9746. var px = x2-x1,
  9747. py = y2-y1,
  9748. something = px*px + py*py,
  9749. u = ((x3 - x1) * px + (y3 - y1) * py) / something;
  9750. if (u > 1) {
  9751. u = 1;
  9752. }
  9753. else if (u < 0) {
  9754. u = 0;
  9755. }
  9756. var x = x1 + u * px,
  9757. y = y1 + u * py,
  9758. dx = x - x3,
  9759. dy = y - y3;
  9760. //# Note: If the actual distance does not matter,
  9761. //# if you only want to compare what this function
  9762. //# returns to other results of this function, you
  9763. //# can just return the squared distance instead
  9764. //# (i.e. remove the sqrt) to gain a little performance
  9765. return Math.sqrt(dx*dx + dy*dy);
  9766. }
  9767. };
  9768. /**
  9769. * This allows the zoom level of the graph to influence the rendering
  9770. *
  9771. * @param scale
  9772. */
  9773. Edge.prototype.setScale = function(scale) {
  9774. this.graphScaleInv = 1.0/scale;
  9775. };
  9776. Edge.prototype.select = function() {
  9777. this.selected = true;
  9778. };
  9779. Edge.prototype.unselect = function() {
  9780. this.selected = false;
  9781. };
  9782. Edge.prototype.positionBezierNode = function() {
  9783. if (this.via !== null) {
  9784. this.via.x = 0.5 * (this.from.x + this.to.x);
  9785. this.via.y = 0.5 * (this.from.y + this.to.y);
  9786. }
  9787. };
  9788. /**
  9789. * Popup is a class to create a popup window with some text
  9790. * @param {Element} container The container object.
  9791. * @param {Number} [x]
  9792. * @param {Number} [y]
  9793. * @param {String} [text]
  9794. */
  9795. function Popup(container, x, y, text) {
  9796. if (container) {
  9797. this.container = container;
  9798. }
  9799. else {
  9800. this.container = document.body;
  9801. }
  9802. this.x = 0;
  9803. this.y = 0;
  9804. this.padding = 5;
  9805. if (x !== undefined && y !== undefined ) {
  9806. this.setPosition(x, y);
  9807. }
  9808. if (text !== undefined) {
  9809. this.setText(text);
  9810. }
  9811. // create the frame
  9812. this.frame = document.createElement("div");
  9813. var style = this.frame.style;
  9814. style.position = "absolute";
  9815. style.visibility = "hidden";
  9816. style.border = "1px solid #666";
  9817. style.color = "black";
  9818. style.padding = this.padding + "px";
  9819. style.backgroundColor = "#FFFFC6";
  9820. style.borderRadius = "3px";
  9821. style.MozBorderRadius = "3px";
  9822. style.WebkitBorderRadius = "3px";
  9823. style.boxShadow = "3px 3px 10px rgba(128, 128, 128, 0.5)";
  9824. style.whiteSpace = "nowrap";
  9825. this.container.appendChild(this.frame);
  9826. }
  9827. /**
  9828. * @param {number} x Horizontal position of the popup window
  9829. * @param {number} y Vertical position of the popup window
  9830. */
  9831. Popup.prototype.setPosition = function(x, y) {
  9832. this.x = parseInt(x);
  9833. this.y = parseInt(y);
  9834. };
  9835. /**
  9836. * Set the text for the popup window. This can be HTML code
  9837. * @param {string} text
  9838. */
  9839. Popup.prototype.setText = function(text) {
  9840. this.frame.innerHTML = text;
  9841. };
  9842. /**
  9843. * Show the popup window
  9844. * @param {boolean} show Optional. Show or hide the window
  9845. */
  9846. Popup.prototype.show = function (show) {
  9847. if (show === undefined) {
  9848. show = true;
  9849. }
  9850. if (show) {
  9851. var height = this.frame.clientHeight;
  9852. var width = this.frame.clientWidth;
  9853. var maxHeight = this.frame.parentNode.clientHeight;
  9854. var maxWidth = this.frame.parentNode.clientWidth;
  9855. var top = (this.y - height);
  9856. if (top + height + this.padding > maxHeight) {
  9857. top = maxHeight - height - this.padding;
  9858. }
  9859. if (top < this.padding) {
  9860. top = this.padding;
  9861. }
  9862. var left = this.x;
  9863. if (left + width + this.padding > maxWidth) {
  9864. left = maxWidth - width - this.padding;
  9865. }
  9866. if (left < this.padding) {
  9867. left = this.padding;
  9868. }
  9869. this.frame.style.left = left + "px";
  9870. this.frame.style.top = top + "px";
  9871. this.frame.style.visibility = "visible";
  9872. }
  9873. else {
  9874. this.hide();
  9875. }
  9876. };
  9877. /**
  9878. * Hide the popup window
  9879. */
  9880. Popup.prototype.hide = function () {
  9881. this.frame.style.visibility = "hidden";
  9882. };
  9883. /**
  9884. * @class Groups
  9885. * This class can store groups and properties specific for groups.
  9886. */
  9887. Groups = function () {
  9888. this.clear();
  9889. this.defaultIndex = 0;
  9890. };
  9891. /**
  9892. * default constants for group colors
  9893. */
  9894. Groups.DEFAULT = [
  9895. {border: "#2B7CE9", background: "#97C2FC", highlight: {border: "#2B7CE9", background: "#D2E5FF"}}, // blue
  9896. {border: "#FFA500", background: "#FFFF00", highlight: {border: "#FFA500", background: "#FFFFA3"}}, // yellow
  9897. {border: "#FA0A10", background: "#FB7E81", highlight: {border: "#FA0A10", background: "#FFAFB1"}}, // red
  9898. {border: "#41A906", background: "#7BE141", highlight: {border: "#41A906", background: "#A1EC76"}}, // green
  9899. {border: "#E129F0", background: "#EB7DF4", highlight: {border: "#E129F0", background: "#F0B3F5"}}, // magenta
  9900. {border: "#7C29F0", background: "#AD85E4", highlight: {border: "#7C29F0", background: "#D3BDF0"}}, // purple
  9901. {border: "#C37F00", background: "#FFA807", highlight: {border: "#C37F00", background: "#FFCA66"}}, // orange
  9902. {border: "#4220FB", background: "#6E6EFD", highlight: {border: "#4220FB", background: "#9B9BFD"}}, // darkblue
  9903. {border: "#FD5A77", background: "#FFC0CB", highlight: {border: "#FD5A77", background: "#FFD1D9"}}, // pink
  9904. {border: "#4AD63A", background: "#C2FABC", highlight: {border: "#4AD63A", background: "#E6FFE3"}} // mint
  9905. ];
  9906. /**
  9907. * Clear all groups
  9908. */
  9909. Groups.prototype.clear = function () {
  9910. this.groups = {};
  9911. this.groups.length = function()
  9912. {
  9913. var i = 0;
  9914. for ( var p in this ) {
  9915. if (this.hasOwnProperty(p)) {
  9916. i++;
  9917. }
  9918. }
  9919. return i;
  9920. }
  9921. };
  9922. /**
  9923. * get group properties of a groupname. If groupname is not found, a new group
  9924. * is added.
  9925. * @param {*} groupname Can be a number, string, Date, etc.
  9926. * @return {Object} group The created group, containing all group properties
  9927. */
  9928. Groups.prototype.get = function (groupname) {
  9929. var group = this.groups[groupname];
  9930. if (group == undefined) {
  9931. // create new group
  9932. var index = this.defaultIndex % Groups.DEFAULT.length;
  9933. this.defaultIndex++;
  9934. group = {};
  9935. group.color = Groups.DEFAULT[index];
  9936. this.groups[groupname] = group;
  9937. }
  9938. return group;
  9939. };
  9940. /**
  9941. * Add a custom group style
  9942. * @param {String} groupname
  9943. * @param {Object} style An object containing borderColor,
  9944. * backgroundColor, etc.
  9945. * @return {Object} group The created group object
  9946. */
  9947. Groups.prototype.add = function (groupname, style) {
  9948. this.groups[groupname] = style;
  9949. if (style.color) {
  9950. style.color = Node.parseColor(style.color);
  9951. }
  9952. return style;
  9953. };
  9954. /**
  9955. * @class Images
  9956. * This class loads images and keeps them stored.
  9957. */
  9958. Images = function () {
  9959. this.images = {};
  9960. this.callback = undefined;
  9961. };
  9962. /**
  9963. * Set an onload callback function. This will be called each time an image
  9964. * is loaded
  9965. * @param {function} callback
  9966. */
  9967. Images.prototype.setOnloadCallback = function(callback) {
  9968. this.callback = callback;
  9969. };
  9970. /**
  9971. *
  9972. * @param {string} url Url of the image
  9973. * @return {Image} img The image object
  9974. */
  9975. Images.prototype.load = function(url) {
  9976. var img = this.images[url];
  9977. if (img == undefined) {
  9978. // create the image
  9979. var images = this;
  9980. img = new Image();
  9981. this.images[url] = img;
  9982. img.onload = function() {
  9983. if (images.callback) {
  9984. images.callback(this);
  9985. }
  9986. };
  9987. img.src = url;
  9988. }
  9989. return img;
  9990. };
  9991. /**
  9992. * Created by Alex on 2/6/14.
  9993. */
  9994. var physicsMixin = {
  9995. /**
  9996. * Toggling barnes Hut calculation on and off.
  9997. *
  9998. * @private
  9999. */
  10000. _toggleBarnesHut : function() {
  10001. this.constants.physics.barnesHut.enabled = !this.constants.physics.barnesHut.enabled;
  10002. this._loadSelectedForceSolver();
  10003. this.moving = true;
  10004. this.start();
  10005. },
  10006. /**
  10007. * This loads the node force solver based on the barnes hut or repulsion algorithm
  10008. *
  10009. * @private
  10010. */
  10011. _loadSelectedForceSolver : function() {
  10012. // this overloads the this._calculateNodeForces
  10013. if (this.constants.physics.barnesHut.enabled == true) {
  10014. this._clearMixin(repulsionMixin);
  10015. this._clearMixin(hierarchalRepulsionMixin);
  10016. this.constants.physics.centralGravity = this.constants.physics.barnesHut.centralGravity;
  10017. this.constants.physics.springLength = this.constants.physics.barnesHut.springLength;
  10018. this.constants.physics.springConstant = this.constants.physics.barnesHut.springConstant;
  10019. this.constants.physics.damping = this.constants.physics.barnesHut.damping;
  10020. this._loadMixin(barnesHutMixin);
  10021. }
  10022. else if (this.constants.physics.hierarchicalRepulsion.enabled == true) {
  10023. this._clearMixin(barnesHutMixin);
  10024. this._clearMixin(repulsionMixin);
  10025. this.constants.physics.centralGravity = this.constants.physics.hierarchicalRepulsion.centralGravity;
  10026. this.constants.physics.springLength = this.constants.physics.hierarchicalRepulsion.springLength;
  10027. this.constants.physics.springConstant = this.constants.physics.hierarchicalRepulsion.springConstant;
  10028. this.constants.physics.damping = this.constants.physics.hierarchicalRepulsion.damping;
  10029. this._loadMixin(hierarchalRepulsionMixin);
  10030. }
  10031. else {
  10032. this._clearMixin(barnesHutMixin);
  10033. this._clearMixin(hierarchalRepulsionMixin);
  10034. this.barnesHutTree = undefined;
  10035. this.constants.physics.centralGravity = this.constants.physics.repulsion.centralGravity;
  10036. this.constants.physics.springLength = this.constants.physics.repulsion.springLength;
  10037. this.constants.physics.springConstant = this.constants.physics.repulsion.springConstant;
  10038. this.constants.physics.damping = this.constants.physics.repulsion.damping;
  10039. this._loadMixin(repulsionMixin);
  10040. }
  10041. },
  10042. /**
  10043. * Before calculating the forces, we check if we need to cluster to keep up performance and we check
  10044. * if there is more than one node. If it is just one node, we dont calculate anything.
  10045. *
  10046. * @private
  10047. */
  10048. _initializeForceCalculation : function() {
  10049. // stop calculation if there is only one node
  10050. if (this.nodeIndices.length == 1) {
  10051. this.nodes[this.nodeIndices[0]]._setForce(0,0);
  10052. }
  10053. else {
  10054. // if there are too many nodes on screen, we cluster without repositioning
  10055. if (this.nodeIndices.length > this.constants.clustering.clusterThreshold && this.constants.clustering.enabled == true) {
  10056. this.clusterToFit(this.constants.clustering.reduceToNodes, false);
  10057. }
  10058. // we now start the force calculation
  10059. this._calculateForces();
  10060. }
  10061. },
  10062. /**
  10063. * Calculate the external forces acting on the nodes
  10064. * Forces are caused by: edges, repulsing forces between nodes, gravity
  10065. * @private
  10066. */
  10067. _calculateForces : function() {
  10068. // Gravity is required to keep separated groups from floating off
  10069. // the forces are reset to zero in this loop by using _setForce instead
  10070. // of _addForce
  10071. this._calculateGravitationalForces();
  10072. this._calculateNodeForces();
  10073. if (this.constants.smoothCurves == true) {
  10074. this._calculateSpringForcesWithSupport();
  10075. }
  10076. else {
  10077. this._calculateSpringForces();
  10078. }
  10079. },
  10080. /**
  10081. * Smooth curves are created by adding invisible nodes in the center of the edges. These nodes are also
  10082. * handled in the calculateForces function. We then use a quadratic curve with the center node as control.
  10083. * This function joins the datanodes and invisible (called support) nodes into one object.
  10084. * We do this so we do not contaminate this.nodes with the support nodes.
  10085. *
  10086. * @private
  10087. */
  10088. _updateCalculationNodes : function() {
  10089. if (this.constants.smoothCurves == true) {
  10090. this.calculationNodes = {};
  10091. this.calculationNodeIndices = [];
  10092. for (var nodeId in this.nodes) {
  10093. if (this.nodes.hasOwnProperty(nodeId)) {
  10094. this.calculationNodes[nodeId] = this.nodes[nodeId];
  10095. }
  10096. }
  10097. var supportNodes = this.sectors['support']['nodes'];
  10098. for (var supportNodeId in supportNodes) {
  10099. if (supportNodes.hasOwnProperty(supportNodeId)) {
  10100. if (this.edges.hasOwnProperty(supportNodes[supportNodeId].parentEdgeId)) {
  10101. this.calculationNodes[supportNodeId] = supportNodes[supportNodeId];
  10102. }
  10103. else {
  10104. supportNodes[supportNodeId]._setForce(0,0);
  10105. }
  10106. }
  10107. }
  10108. for (var idx in this.calculationNodes) {
  10109. if (this.calculationNodes.hasOwnProperty(idx)) {
  10110. this.calculationNodeIndices.push(idx);
  10111. }
  10112. }
  10113. }
  10114. else {
  10115. this.calculationNodes = this.nodes;
  10116. this.calculationNodeIndices = this.nodeIndices;
  10117. }
  10118. },
  10119. /**
  10120. * this function applies the central gravity effect to keep groups from floating off
  10121. *
  10122. * @private
  10123. */
  10124. _calculateGravitationalForces : function() {
  10125. var dx, dy, distance, node, i;
  10126. var nodes = this.calculationNodes;
  10127. var gravity = this.constants.physics.centralGravity;
  10128. var gravityForce = 0;
  10129. for (i = 0; i < this.calculationNodeIndices.length; i++) {
  10130. node = nodes[this.calculationNodeIndices[i]];
  10131. node.damping = this.constants.physics.damping; // possibly add function to alter damping properties of clusters.
  10132. // gravity does not apply when we are in a pocket sector
  10133. if (this._sector() == "default" && gravity != 0) {
  10134. dx = -node.x;
  10135. dy = -node.y;
  10136. distance = Math.sqrt(dx*dx + dy*dy);
  10137. gravityForce = (distance == 0) ? 0 : (gravity / distance);
  10138. node.fx = dx * gravityForce;
  10139. node.fy = dy * gravityForce;
  10140. }
  10141. else {
  10142. node.fx = 0;
  10143. node.fy = 0;
  10144. }
  10145. }
  10146. },
  10147. /**
  10148. * this function calculates the effects of the springs in the case of unsmooth curves.
  10149. *
  10150. * @private
  10151. */
  10152. _calculateSpringForces : function() {
  10153. var edgeLength, edge, edgeId;
  10154. var dx, dy, fx, fy, springForce, length;
  10155. var edges = this.edges;
  10156. // forces caused by the edges, modelled as springs
  10157. for (edgeId in edges) {
  10158. if (edges.hasOwnProperty(edgeId)) {
  10159. edge = edges[edgeId];
  10160. if (edge.connected) {
  10161. // only calculate forces if nodes are in the same sector
  10162. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  10163. edgeLength = edge.customLength ? edge.length : this.constants.physics.springLength;
  10164. // this implies that the edges between big clusters are longer
  10165. edgeLength += (edge.to.clusterSize + edge.from.clusterSize - 2) * this.constants.clustering.edgeGrowth;
  10166. dx = (edge.from.x - edge.to.x);
  10167. dy = (edge.from.y - edge.to.y);
  10168. length = Math.sqrt(dx * dx + dy * dy);
  10169. if (length == 0) {
  10170. length = 0.01;
  10171. }
  10172. springForce = this.constants.physics.springConstant * (edgeLength - length) / length;
  10173. fx = dx * springForce;
  10174. fy = dy * springForce;
  10175. edge.from.fx += fx;
  10176. edge.from.fy += fy;
  10177. edge.to.fx -= fx;
  10178. edge.to.fy -= fy;
  10179. }
  10180. }
  10181. }
  10182. }
  10183. },
  10184. /**
  10185. * This function calculates the springforces on the nodes, accounting for the support nodes.
  10186. *
  10187. * @private
  10188. */
  10189. _calculateSpringForcesWithSupport : function() {
  10190. var edgeLength, edge, edgeId, combinedClusterSize;
  10191. var edges = this.edges;
  10192. // forces caused by the edges, modelled as springs
  10193. for (edgeId in edges) {
  10194. if (edges.hasOwnProperty(edgeId)) {
  10195. edge = edges[edgeId];
  10196. if (edge.connected) {
  10197. // only calculate forces if nodes are in the same sector
  10198. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  10199. if (edge.via != null) {
  10200. var node1 = edge.to;
  10201. var node2 = edge.via;
  10202. var node3 = edge.from;
  10203. edgeLength = edge.customLength ? edge.length : this.constants.physics.springLength;
  10204. combinedClusterSize = node1.clusterSize + node3.clusterSize - 2;
  10205. // this implies that the edges between big clusters are longer
  10206. edgeLength += combinedClusterSize * this.constants.clustering.edgeGrowth;
  10207. this._calculateSpringForce(node1,node2,0.5*edgeLength);
  10208. this._calculateSpringForce(node2,node3,0.5*edgeLength);
  10209. }
  10210. }
  10211. }
  10212. }
  10213. }
  10214. },
  10215. /**
  10216. * This is the code actually performing the calculation for the function above. It is split out to avoid repetition.
  10217. *
  10218. * @param node1
  10219. * @param node2
  10220. * @param edgeLength
  10221. * @private
  10222. */
  10223. _calculateSpringForce : function(node1,node2,edgeLength) {
  10224. var dx, dy, fx, fy, springForce, length;
  10225. dx = (node1.x - node2.x);
  10226. dy = (node1.y - node2.y);
  10227. length = Math.sqrt(dx * dx + dy * dy);
  10228. if (length == 0) {
  10229. length = 0.01;
  10230. }
  10231. springForce = this.constants.physics.springConstant * (edgeLength - length) / length;
  10232. fx = dx * springForce;
  10233. fy = dy * springForce;
  10234. node1.fx += fx;
  10235. node1.fy += fy;
  10236. node2.fx -= fx;
  10237. node2.fy -= fy;
  10238. },
  10239. /**
  10240. * Load the HTML for the physics config and bind it
  10241. * @private
  10242. */
  10243. _loadPhysicsConfiguration : function() {
  10244. if (this.physicsConfiguration === undefined) {
  10245. var hierarchicalLayoutDirections = ["LR","RL","UD","DU"];
  10246. this.physicsConfiguration = document.createElement('div');
  10247. this.physicsConfiguration.className = "PhysicsConfiguration";
  10248. this.physicsConfiguration.innerHTML = '' +
  10249. '<table><tr><td><b>Simulation Mode:</b></td></tr>' +
  10250. '<tr>' +
  10251. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod1" value="BH" checked="checked">Barnes Hut</td>' +
  10252. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod2" value="R">Repulsion</td>'+
  10253. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod3" value="H">Hierarchical</td>' +
  10254. '</tr>'+
  10255. '</table>' +
  10256. '<table id="graph_BH_table" style="display:none">'+
  10257. '<tr><td><b>Barnes Hut</b></td></tr>'+
  10258. '<tr>'+
  10259. '<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>'+
  10260. '</tr>'+
  10261. '<tr>'+
  10262. '<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>'+
  10263. '</tr>'+
  10264. '<tr>'+
  10265. '<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>'+
  10266. '</tr>'+
  10267. '<tr>'+
  10268. '<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>'+
  10269. '</tr>'+
  10270. '<tr>'+
  10271. '<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>'+
  10272. '</tr>'+
  10273. '</table>'+
  10274. '<table id="graph_R_table" style="display:none">'+
  10275. '<tr><td><b>Repulsion</b></td></tr>'+
  10276. '<tr>'+
  10277. '<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>'+
  10278. '</tr>'+
  10279. '<tr>'+
  10280. '<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>'+
  10281. '</tr>'+
  10282. '<tr>'+
  10283. '<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>'+
  10284. '</tr>'+
  10285. '<tr>'+
  10286. '<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>'+
  10287. '</tr>'+
  10288. '<tr>'+
  10289. '<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>'+
  10290. '</tr>'+
  10291. '</table>'+
  10292. '<table id="graph_H_table" style="display:none">'+
  10293. '<tr><td width="150"><b>Hierarchical</b></td></tr>'+
  10294. '<tr>'+
  10295. '<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>'+
  10296. '</tr>'+
  10297. '<tr>'+
  10298. '<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>'+
  10299. '</tr>'+
  10300. '<tr>'+
  10301. '<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>'+
  10302. '</tr>'+
  10303. '<tr>'+
  10304. '<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>'+
  10305. '</tr>'+
  10306. '<tr>'+
  10307. '<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>'+
  10308. '</tr>'+
  10309. '<tr>'+
  10310. '<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>'+
  10311. '</tr>'+
  10312. '<tr>'+
  10313. '<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>'+
  10314. '</tr>'+
  10315. '<tr>'+
  10316. '<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>'+
  10317. '</tr>'+
  10318. '</table>'
  10319. this.containerElement.parentElement.insertBefore(this.physicsConfiguration,this.containerElement);
  10320. var rangeElement;
  10321. rangeElement = document.getElementById('graph_BH_gc');
  10322. rangeElement.onchange = showValueOfRange.bind(this,'graph_BH_gc',-1,"physics_barnesHut_gravitationalConstant");
  10323. rangeElement = document.getElementById('graph_BH_cg');
  10324. rangeElement.onchange = showValueOfRange.bind(this,'graph_BH_cg',1,"physics_centralGravity");
  10325. rangeElement = document.getElementById('graph_BH_sc');
  10326. rangeElement.onchange = showValueOfRange.bind(this,'graph_BH_sc',1,"physics_springConstant");
  10327. rangeElement = document.getElementById('graph_BH_sl');
  10328. rangeElement.onchange = showValueOfRange.bind(this,'graph_BH_sl',1,"physics_springLength");
  10329. rangeElement = document.getElementById('graph_BH_damp');
  10330. rangeElement.onchange = showValueOfRange.bind(this,'graph_BH_damp',1,"physics_damping");
  10331. rangeElement = document.getElementById('graph_R_nd');
  10332. rangeElement.onchange = showValueOfRange.bind(this,'graph_R_nd',1,"physics_repulsion_nodeDistance");
  10333. rangeElement = document.getElementById('graph_R_cg');
  10334. rangeElement.onchange = showValueOfRange.bind(this,'graph_R_cg',1,"physics_centralGravity");
  10335. rangeElement = document.getElementById('graph_R_sc');
  10336. rangeElement.onchange = showValueOfRange.bind(this,'graph_R_sc',1,"physics_springConstant");
  10337. rangeElement = document.getElementById('graph_R_sl');
  10338. rangeElement.onchange = showValueOfRange.bind(this,'graph_R_sl',1,"physics_springLength");
  10339. rangeElement = document.getElementById('graph_R_damp');
  10340. rangeElement.onchange = showValueOfRange.bind(this,'graph_R_damp',1,"physics_damping");
  10341. rangeElement = document.getElementById('graph_H_nd');
  10342. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_nd',1,"physics_hierarchicalRepulsion_nodeDistance");
  10343. rangeElement = document.getElementById('graph_H_cg');
  10344. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_cg',1,"physics_centralGravity");
  10345. rangeElement = document.getElementById('graph_H_sc');
  10346. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_sc',1,"physics_springConstant");
  10347. rangeElement = document.getElementById('graph_H_sl');
  10348. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_sl',1,"physics_springLength");
  10349. rangeElement = document.getElementById('graph_H_damp');
  10350. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_damp',1,"physics_damping");
  10351. rangeElement = document.getElementById('graph_H_direction');
  10352. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_direction',hierarchicalLayoutDirections,"hierarchicalLayout_direction");
  10353. rangeElement = document.getElementById('graph_H_levsep');
  10354. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_levsep',1,"hierarchicalLayout_levelSeparation");
  10355. rangeElement = document.getElementById('graph_H_nspac');
  10356. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_nspac',1,"hierarchicalLayout_nodeSpacing");
  10357. var radioButton1 = document.getElementById("graph_physicsMethod1");
  10358. var radioButton2 = document.getElementById("graph_physicsMethod2");
  10359. var radioButton3 = document.getElementById("graph_physicsMethod3");
  10360. radioButton2.checked = true;
  10361. if (this.constants.physics.barnesHut.enabled) {
  10362. radioButton1.checked = true;
  10363. }
  10364. if (this.constants.hierarchicalLayout.enabled) {
  10365. radioButton3.checked = true;
  10366. }
  10367. switchConfigurations.apply(this);
  10368. radioButton1.onchange = switchConfigurations.bind(this);
  10369. radioButton2.onchange = switchConfigurations.bind(this);
  10370. radioButton3.onchange = switchConfigurations.bind(this);
  10371. }
  10372. },
  10373. _overWriteGraphConstants : function(constantsVariableName, value) {
  10374. var nameArray = constantsVariableName.split("_");
  10375. if (nameArray.length == 1) {
  10376. this.constants[nameArray[0]] = value;
  10377. }
  10378. else if (nameArray.length == 2) {
  10379. this.constants[nameArray[0]][nameArray[1]] = value;
  10380. }
  10381. else if (nameArray.length == 3) {
  10382. this.constants[nameArray[0]][nameArray[1]][nameArray[2]] = value;
  10383. }
  10384. }
  10385. }
  10386. function switchConfigurations () {
  10387. var ids = ["graph_BH_table","graph_R_table","graph_H_table"]
  10388. var radioButton = document.querySelector('input[name="graph_physicsMethod"]:checked').value;
  10389. var tableId = "graph_" + radioButton + "_table";
  10390. var table = document.getElementById(tableId);
  10391. table.style.display = "block";
  10392. for (var i = 0; i < ids.length; i++) {
  10393. if (ids[i] != tableId) {
  10394. table = document.getElementById(ids[i]);
  10395. table.style.display = "none";
  10396. }
  10397. }
  10398. this._restoreNodes();
  10399. if (radioButton == "R") {
  10400. this.constants.hierarchicalLayout.enabled = false;
  10401. this.constants.physics.hierarchicalRepulsion.enabeled = false;
  10402. this.constants.physics.barnesHut.enabled = false;
  10403. }
  10404. else if (radioButton == "H") {
  10405. this.constants.hierarchicalLayout.enabled = true;
  10406. this.constants.physics.hierarchicalRepulsion.enabeled = true;
  10407. this.constants.physics.barnesHut.enabled = false;
  10408. this._setupHierarchicalLayout();
  10409. }
  10410. else {
  10411. this.constants.hierarchicalLayout.enabled = false;
  10412. this.constants.physics.hierarchicalRepulsion.enabeled = false;
  10413. this.constants.physics.barnesHut.enabled = true;
  10414. }
  10415. this._loadSelectedForceSolver();
  10416. this.moving = true;
  10417. this.start();
  10418. }
  10419. function showValueOfRange (id,map,constantsVariableName) {
  10420. var valueId = id + "_value";
  10421. var rangeValue = document.getElementById(id).value;
  10422. if (map instanceof Array) {
  10423. document.getElementById(valueId).value = map[parseInt(rangeValue)];
  10424. this._overWriteGraphConstants(constantsVariableName,map[parseInt(rangeValue)]);
  10425. }
  10426. else {
  10427. document.getElementById(valueId).value = parseInt(map) * parseFloat(rangeValue);
  10428. this._overWriteGraphConstants(constantsVariableName, parseInt(map) * parseFloat(rangeValue));
  10429. }
  10430. if (constantsVariableName == "hierarchicalLayout_direction" ||
  10431. constantsVariableName == "hierarchicalLayout_levelSeparation" ||
  10432. constantsVariableName == "hierarchicalLayout_nodeSpacing") {
  10433. this._setupHierarchicalLayout();
  10434. }
  10435. this.moving = true;
  10436. this.start();
  10437. };
  10438. /**
  10439. * Created by Alex on 2/10/14.
  10440. */
  10441. var hierarchalRepulsionMixin = {
  10442. /**
  10443. * Calculate the forces the nodes apply on eachother based on a repulsion field.
  10444. * This field is linearly approximated.
  10445. *
  10446. * @private
  10447. */
  10448. _calculateNodeForces : function() {
  10449. var dx, dy, distance, fx, fy, combinedClusterSize,
  10450. repulsingForce, node1, node2, i, j;
  10451. var nodes = this.calculationNodes;
  10452. var nodeIndices = this.calculationNodeIndices;
  10453. // approximation constants
  10454. var b = 5;
  10455. var a_base = 0.5*-b;
  10456. // repulsing forces between nodes
  10457. var nodeDistance = this.constants.physics.hierarchicalRepulsion.nodeDistance;
  10458. var minimumDistance = nodeDistance;
  10459. // we loop from i over all but the last entree in the array
  10460. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  10461. for (i = 0; i < nodeIndices.length-1; i++) {
  10462. node1 = nodes[nodeIndices[i]];
  10463. for (j = i+1; j < nodeIndices.length; j++) {
  10464. node2 = nodes[nodeIndices[j]];
  10465. dx = node2.x - node1.x;
  10466. dy = node2.y - node1.y;
  10467. distance = Math.sqrt(dx * dx + dy * dy);
  10468. var a = a_base / minimumDistance;
  10469. if (distance < 2*minimumDistance) {
  10470. repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness))
  10471. // normalize force with
  10472. if (distance == 0) {
  10473. distance = 0.01;
  10474. }
  10475. else {
  10476. repulsingForce = repulsingForce/distance;
  10477. }
  10478. fx = dx * repulsingForce;
  10479. fy = dy * repulsingForce;
  10480. node1.fx -= fx;
  10481. node1.fy -= fy;
  10482. node2.fx += fx;
  10483. node2.fy += fy;
  10484. }
  10485. }
  10486. }
  10487. }
  10488. }
  10489. /**
  10490. * Created by Alex on 2/10/14.
  10491. */
  10492. var barnesHutMixin = {
  10493. /**
  10494. * This function calculates the forces the nodes apply on eachother based on a gravitational model.
  10495. * The Barnes Hut method is used to speed up this N-body simulation.
  10496. *
  10497. * @private
  10498. */
  10499. _calculateNodeForces : function() {
  10500. var node;
  10501. var nodes = this.calculationNodes;
  10502. var nodeIndices = this.calculationNodeIndices;
  10503. var nodeCount = nodeIndices.length;
  10504. this._formBarnesHutTree(nodes,nodeIndices);
  10505. var barnesHutTree = this.barnesHutTree;
  10506. // place the nodes one by one recursively
  10507. for (var i = 0; i < nodeCount; i++) {
  10508. node = nodes[nodeIndices[i]];
  10509. // starting with root is irrelevant, it never passes the BarnesHut condition
  10510. this._getForceContribution(barnesHutTree.root.children.NW,node);
  10511. this._getForceContribution(barnesHutTree.root.children.NE,node);
  10512. this._getForceContribution(barnesHutTree.root.children.SW,node);
  10513. this._getForceContribution(barnesHutTree.root.children.SE,node);
  10514. }
  10515. },
  10516. /**
  10517. * This function traverses the barnesHutTree. It checks when it can approximate distant nodes with their center of mass.
  10518. * If a region contains a single node, we check if it is not itself, then we apply the force.
  10519. *
  10520. * @param parentBranch
  10521. * @param node
  10522. * @private
  10523. */
  10524. _getForceContribution : function(parentBranch,node) {
  10525. // we get no force contribution from an empty region
  10526. if (parentBranch.childrenCount > 0) {
  10527. var dx,dy,distance;
  10528. // get the distance from the center of mass to the node.
  10529. dx = parentBranch.centerOfMass.x - node.x;
  10530. dy = parentBranch.centerOfMass.y - node.y;
  10531. distance = Math.sqrt(dx * dx + dy * dy);
  10532. // BarnesHut condition
  10533. // original condition : s/d < theta = passed === d/s > 1/theta = passed
  10534. // calcSize = 1/s --> d * 1/s > 1/theta = passed
  10535. if (distance * parentBranch.calcSize > this.constants.physics.barnesHut.theta) {
  10536. // duplicate code to reduce function calls to speed up program
  10537. if (distance == 0) {
  10538. distance = 0.1*Math.random();
  10539. dx = distance;
  10540. }
  10541. var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.mass / (distance * distance * distance);
  10542. var fx = dx * gravityForce;
  10543. var fy = dy * gravityForce;
  10544. node.fx += fx;
  10545. node.fy += fy;
  10546. }
  10547. else {
  10548. // Did not pass the condition, go into children if available
  10549. if (parentBranch.childrenCount == 4) {
  10550. this._getForceContribution(parentBranch.children.NW,node);
  10551. this._getForceContribution(parentBranch.children.NE,node);
  10552. this._getForceContribution(parentBranch.children.SW,node);
  10553. this._getForceContribution(parentBranch.children.SE,node);
  10554. }
  10555. else { // parentBranch must have only one node, if it was empty we wouldnt be here
  10556. if (parentBranch.children.data.id != node.id) { // if it is not self
  10557. // duplicate code to reduce function calls to speed up program
  10558. if (distance == 0) {
  10559. distance = 0.5*Math.random();
  10560. dx = distance;
  10561. }
  10562. var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.mass / (distance * distance * distance);
  10563. var fx = dx * gravityForce;
  10564. var fy = dy * gravityForce;
  10565. node.fx += fx;
  10566. node.fy += fy;
  10567. }
  10568. }
  10569. }
  10570. }
  10571. },
  10572. /**
  10573. * This function constructs the barnesHut tree recursively. It creates the root, splits it and starts placing the nodes.
  10574. *
  10575. * @param nodes
  10576. * @param nodeIndices
  10577. * @private
  10578. */
  10579. _formBarnesHutTree : function(nodes,nodeIndices) {
  10580. var node;
  10581. var nodeCount = nodeIndices.length;
  10582. var minX = Number.MAX_VALUE,
  10583. minY = Number.MAX_VALUE,
  10584. maxX =-Number.MAX_VALUE,
  10585. maxY =-Number.MAX_VALUE;
  10586. // get the range of the nodes
  10587. for (var i = 0; i < nodeCount; i++) {
  10588. var x = nodes[nodeIndices[i]].x;
  10589. var y = nodes[nodeIndices[i]].y;
  10590. if (x < minX) { minX = x; }
  10591. if (x > maxX) { maxX = x; }
  10592. if (y < minY) { minY = y; }
  10593. if (y > maxY) { maxY = y; }
  10594. }
  10595. // make the range a square
  10596. var sizeDiff = Math.abs(maxX - minX) - Math.abs(maxY - minY); // difference between X and Y
  10597. if (sizeDiff > 0) {minY -= 0.5 * sizeDiff; maxY += 0.5 * sizeDiff;} // xSize > ySize
  10598. else {minX += 0.5 * sizeDiff; maxX -= 0.5 * sizeDiff;} // xSize < ySize
  10599. var minimumTreeSize = 1e-5;
  10600. var rootSize = Math.max(minimumTreeSize,Math.abs(maxX - minX));
  10601. var halfRootSize = 0.5 * rootSize;
  10602. var centerX = 0.5 * (minX + maxX), centerY = 0.5 * (minY + maxY);
  10603. // construct the barnesHutTree
  10604. var barnesHutTree = {root:{
  10605. centerOfMass:{x:0,y:0}, // Center of Mass
  10606. mass:0,
  10607. range: {minX:centerX-halfRootSize,maxX:centerX+halfRootSize,
  10608. minY:centerY-halfRootSize,maxY:centerY+halfRootSize},
  10609. size: rootSize,
  10610. calcSize: 1 / rootSize,
  10611. children: {data:null},
  10612. maxWidth: 0,
  10613. level: 0,
  10614. childrenCount: 4
  10615. }};
  10616. this._splitBranch(barnesHutTree.root);
  10617. // place the nodes one by one recursively
  10618. for (i = 0; i < nodeCount; i++) {
  10619. node = nodes[nodeIndices[i]];
  10620. this._placeInTree(barnesHutTree.root,node);
  10621. }
  10622. // make global
  10623. this.barnesHutTree = barnesHutTree
  10624. },
  10625. _updateBranchMass : function(parentBranch, node) {
  10626. var totalMass = parentBranch.mass + node.mass;
  10627. var totalMassInv = 1/totalMass;
  10628. parentBranch.centerOfMass.x = parentBranch.centerOfMass.x * parentBranch.mass + node.x * node.mass;
  10629. parentBranch.centerOfMass.x *= totalMassInv;
  10630. parentBranch.centerOfMass.y = parentBranch.centerOfMass.y * parentBranch.mass + node.y * node.mass;
  10631. parentBranch.centerOfMass.y *= totalMassInv;
  10632. parentBranch.mass = totalMass;
  10633. var biggestSize = Math.max(Math.max(node.height,node.radius),node.width);
  10634. parentBranch.maxWidth = (parentBranch.maxWidth < biggestSize) ? biggestSize : parentBranch.maxWidth;
  10635. },
  10636. _placeInTree : function(parentBranch,node,skipMassUpdate) {
  10637. if (skipMassUpdate != true || skipMassUpdate === undefined) {
  10638. // update the mass of the branch.
  10639. this._updateBranchMass(parentBranch,node);
  10640. }
  10641. if (parentBranch.children.NW.range.maxX > node.x) { // in NW or SW
  10642. if (parentBranch.children.NW.range.maxY > node.y) { // in NW
  10643. this._placeInRegion(parentBranch,node,"NW");
  10644. }
  10645. else { // in SW
  10646. this._placeInRegion(parentBranch,node,"SW");
  10647. }
  10648. }
  10649. else { // in NE or SE
  10650. if (parentBranch.children.NW.range.maxY > node.y) { // in NE
  10651. this._placeInRegion(parentBranch,node,"NE");
  10652. }
  10653. else { // in SE
  10654. this._placeInRegion(parentBranch,node,"SE");
  10655. }
  10656. }
  10657. },
  10658. _placeInRegion : function(parentBranch,node,region) {
  10659. switch (parentBranch.children[region].childrenCount) {
  10660. case 0: // place node here
  10661. parentBranch.children[region].children.data = node;
  10662. parentBranch.children[region].childrenCount = 1;
  10663. this._updateBranchMass(parentBranch.children[region],node);
  10664. break;
  10665. case 1: // convert into children
  10666. // if there are two nodes exactly overlapping (on init, on opening of cluster etc.)
  10667. // we move one node a pixel and we do not put it in the tree.
  10668. if (parentBranch.children[region].children.data.x == node.x &&
  10669. parentBranch.children[region].children.data.y == node.y) {
  10670. node.x += Math.random();
  10671. node.y += Math.random();
  10672. this._placeInTree(parentBranch,node, true);
  10673. }
  10674. else {
  10675. this._splitBranch(parentBranch.children[region]);
  10676. this._placeInTree(parentBranch.children[region],node);
  10677. }
  10678. break;
  10679. case 4: // place in branch
  10680. this._placeInTree(parentBranch.children[region],node);
  10681. break;
  10682. }
  10683. },
  10684. /**
  10685. * this function splits a branch into 4 sub branches. If the branch contained a node, we place it in the subbranch
  10686. * after the split is complete.
  10687. *
  10688. * @param parentBranch
  10689. * @private
  10690. */
  10691. _splitBranch : function(parentBranch) {
  10692. // if the branch is filled with a node, replace the node in the new subset.
  10693. var containedNode = null;
  10694. if (parentBranch.childrenCount == 1) {
  10695. containedNode = parentBranch.children.data;
  10696. parentBranch.mass = 0; parentBranch.centerOfMass.x = 0; parentBranch.centerOfMass.y = 0;
  10697. }
  10698. parentBranch.childrenCount = 4;
  10699. parentBranch.children.data = null;
  10700. this._insertRegion(parentBranch,"NW");
  10701. this._insertRegion(parentBranch,"NE");
  10702. this._insertRegion(parentBranch,"SW");
  10703. this._insertRegion(parentBranch,"SE");
  10704. if (containedNode != null) {
  10705. this._placeInTree(parentBranch,containedNode);
  10706. }
  10707. },
  10708. /**
  10709. * This function subdivides the region into four new segments.
  10710. * Specifically, this inserts a single new segment.
  10711. * It fills the children section of the parentBranch
  10712. *
  10713. * @param parentBranch
  10714. * @param region
  10715. * @param parentRange
  10716. * @private
  10717. */
  10718. _insertRegion : function(parentBranch, region) {
  10719. var minX,maxX,minY,maxY;
  10720. var childSize = 0.5 * parentBranch.size;
  10721. switch (region) {
  10722. case "NW":
  10723. minX = parentBranch.range.minX;
  10724. maxX = parentBranch.range.minX + childSize;
  10725. minY = parentBranch.range.minY;
  10726. maxY = parentBranch.range.minY + childSize;
  10727. break;
  10728. case "NE":
  10729. minX = parentBranch.range.minX + childSize;
  10730. maxX = parentBranch.range.maxX;
  10731. minY = parentBranch.range.minY;
  10732. maxY = parentBranch.range.minY + childSize;
  10733. break;
  10734. case "SW":
  10735. minX = parentBranch.range.minX;
  10736. maxX = parentBranch.range.minX + childSize;
  10737. minY = parentBranch.range.minY + childSize;
  10738. maxY = parentBranch.range.maxY;
  10739. break;
  10740. case "SE":
  10741. minX = parentBranch.range.minX + childSize;
  10742. maxX = parentBranch.range.maxX;
  10743. minY = parentBranch.range.minY + childSize;
  10744. maxY = parentBranch.range.maxY;
  10745. break;
  10746. }
  10747. parentBranch.children[region] = {
  10748. centerOfMass:{x:0,y:0},
  10749. mass:0,
  10750. range:{minX:minX,maxX:maxX,minY:minY,maxY:maxY},
  10751. size: 0.5 * parentBranch.size,
  10752. calcSize: 2 * parentBranch.calcSize,
  10753. children: {data:null},
  10754. maxWidth: 0,
  10755. level: parentBranch.level+1,
  10756. childrenCount: 0
  10757. };
  10758. },
  10759. /**
  10760. * This function is for debugging purposed, it draws the tree.
  10761. *
  10762. * @param ctx
  10763. * @param color
  10764. * @private
  10765. */
  10766. _drawTree : function(ctx,color) {
  10767. if (this.barnesHutTree !== undefined) {
  10768. ctx.lineWidth = 1;
  10769. this._drawBranch(this.barnesHutTree.root,ctx,color);
  10770. }
  10771. },
  10772. /**
  10773. * This function is for debugging purposes. It draws the branches recursively.
  10774. *
  10775. * @param branch
  10776. * @param ctx
  10777. * @param color
  10778. * @private
  10779. */
  10780. _drawBranch : function(branch,ctx,color) {
  10781. if (color === undefined) {
  10782. color = "#FF0000";
  10783. }
  10784. if (branch.childrenCount == 4) {
  10785. this._drawBranch(branch.children.NW,ctx);
  10786. this._drawBranch(branch.children.NE,ctx);
  10787. this._drawBranch(branch.children.SE,ctx);
  10788. this._drawBranch(branch.children.SW,ctx);
  10789. }
  10790. ctx.strokeStyle = color;
  10791. ctx.beginPath();
  10792. ctx.moveTo(branch.range.minX,branch.range.minY);
  10793. ctx.lineTo(branch.range.maxX,branch.range.minY);
  10794. ctx.stroke();
  10795. ctx.beginPath();
  10796. ctx.moveTo(branch.range.maxX,branch.range.minY);
  10797. ctx.lineTo(branch.range.maxX,branch.range.maxY);
  10798. ctx.stroke();
  10799. ctx.beginPath();
  10800. ctx.moveTo(branch.range.maxX,branch.range.maxY);
  10801. ctx.lineTo(branch.range.minX,branch.range.maxY);
  10802. ctx.stroke();
  10803. ctx.beginPath();
  10804. ctx.moveTo(branch.range.minX,branch.range.maxY);
  10805. ctx.lineTo(branch.range.minX,branch.range.minY);
  10806. ctx.stroke();
  10807. /*
  10808. if (branch.mass > 0) {
  10809. ctx.circle(branch.centerOfMass.x, branch.centerOfMass.y, 3*branch.mass);
  10810. ctx.stroke();
  10811. }
  10812. */
  10813. }
  10814. };
  10815. /**
  10816. * Created by Alex on 2/10/14.
  10817. */
  10818. var repulsionMixin = {
  10819. /**
  10820. * Calculate the forces the nodes apply on eachother based on a repulsion field.
  10821. * This field is linearly approximated.
  10822. *
  10823. * @private
  10824. */
  10825. _calculateNodeForces : function() {
  10826. var dx, dy, angle, distance, fx, fy, combinedClusterSize,
  10827. repulsingForce, node1, node2, i, j;
  10828. var nodes = this.calculationNodes;
  10829. var nodeIndices = this.calculationNodeIndices;
  10830. // approximation constants
  10831. var a_base = -2/3;
  10832. var b = 4/3;
  10833. // repulsing forces between nodes
  10834. var nodeDistance = this.constants.physics.repulsion.nodeDistance;
  10835. var minimumDistance = nodeDistance;
  10836. // we loop from i over all but the last entree in the array
  10837. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  10838. for (i = 0; i < nodeIndices.length-1; i++) {
  10839. node1 = nodes[nodeIndices[i]];
  10840. for (j = i+1; j < nodeIndices.length; j++) {
  10841. node2 = nodes[nodeIndices[j]];
  10842. combinedClusterSize = node1.clusterSize + node2.clusterSize - 2;
  10843. dx = node2.x - node1.x;
  10844. dy = node2.y - node1.y;
  10845. distance = Math.sqrt(dx * dx + dy * dy);
  10846. minimumDistance = (combinedClusterSize == 0) ? nodeDistance : (nodeDistance * (1 + combinedClusterSize * this.constants.clustering.distanceAmplification));
  10847. var a = a_base / minimumDistance;
  10848. if (distance < 2*minimumDistance) {
  10849. if (distance < 0.5*minimumDistance) {
  10850. repulsingForce = 1.0;
  10851. }
  10852. else {
  10853. repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness))
  10854. }
  10855. // amplify the repulsion for clusters.
  10856. repulsingForce *= (combinedClusterSize == 0) ? 1 : 1 + combinedClusterSize * this.constants.clustering.forceAmplification;
  10857. repulsingForce = repulsingForce/distance;
  10858. fx = dx * repulsingForce;
  10859. fy = dy * repulsingForce;
  10860. node1.fx -= fx;
  10861. node1.fy -= fy;
  10862. node2.fx += fx;
  10863. node2.fy += fy;
  10864. }
  10865. }
  10866. }
  10867. }
  10868. }
  10869. var HierarchicalLayoutMixin = {
  10870. /**
  10871. * This is the main function to layout the nodes in a hierarchical way.
  10872. * It checks if the node details are supplied correctly
  10873. *
  10874. * @private
  10875. */
  10876. _setupHierarchicalLayout : function() {
  10877. if (this.constants.hierarchicalLayout.enabled == true) {
  10878. if (this.constants.hierarchicalLayout.direction == "RL" || this.constants.hierarchicalLayout.direction == "DU") {
  10879. this.constants.hierarchicalLayout.levelSeparation *= -1;
  10880. }
  10881. else {
  10882. this.constants.hierarchicalLayout.levelSeparation = Math.abs(this.constants.hierarchicalLayout.levelSeparation);
  10883. }
  10884. // get the size of the largest hubs and check if the user has defined a level for a node.
  10885. var hubsize = 0;
  10886. var node, nodeId;
  10887. var definedLevel = false;
  10888. var undefinedLevel = false;
  10889. for (nodeId in this.nodes) {
  10890. if (this.nodes.hasOwnProperty(nodeId)) {
  10891. node = this.nodes[nodeId];
  10892. if (node.level != -1) {
  10893. definedLevel = true;
  10894. }
  10895. else {
  10896. undefinedLevel = true;
  10897. }
  10898. if (hubsize < node.edges.length) {
  10899. hubsize = node.edges.length;
  10900. }
  10901. }
  10902. }
  10903. // if the user defined some levels but not all, alert and run without hierarchical layout
  10904. if (undefinedLevel == true && definedLevel == true) {
  10905. alert("To use the hierarchical layout, nodes require either no predefined levels or levels have to be defined for all nodes.")
  10906. this.zoomExtent(true,this.constants.clustering.enabled);
  10907. if (!this.constants.clustering.enabled) {
  10908. this.start();
  10909. }
  10910. }
  10911. else {
  10912. // setup the system to use hierarchical method.
  10913. this._changeConstants();
  10914. // define levels if undefined by the users. Based on hubsize
  10915. if (undefinedLevel == true) {
  10916. this._determineLevels(hubsize);
  10917. }
  10918. // check the distribution of the nodes per level.
  10919. var distribution = this._getDistribution();
  10920. // place the nodes on the canvas. This also stablilizes the system.
  10921. this._placeNodesByHierarchy(distribution);
  10922. // start the simulation.
  10923. this.start();
  10924. }
  10925. }
  10926. },
  10927. /**
  10928. * This function places the nodes on the canvas based on the hierarchial distribution.
  10929. *
  10930. * @param {Object} distribution | obtained by the function this._getDistribution()
  10931. * @private
  10932. */
  10933. _placeNodesByHierarchy : function(distribution) {
  10934. var nodeId, node;
  10935. // start placing all the level 0 nodes first. Then recursively position their branches.
  10936. for (nodeId in distribution[0].nodes) {
  10937. if (distribution[0].nodes.hasOwnProperty(nodeId)) {
  10938. node = distribution[0].nodes[nodeId];
  10939. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  10940. if (node.xFixed) {
  10941. node.x = distribution[0].minPos;
  10942. node.xFixed = false;
  10943. distribution[0].minPos += distribution[0].nodeSpacing;
  10944. }
  10945. }
  10946. else {
  10947. if (node.yFixed) {
  10948. node.y = distribution[0].minPos;
  10949. node.yFixed = false;
  10950. distribution[0].minPos += distribution[0].nodeSpacing;
  10951. }
  10952. }
  10953. this._placeBranchNodes(node.edges,node.id,distribution,node.level);
  10954. }
  10955. }
  10956. // stabilize the system after positioning. This function calls zoomExtent.
  10957. this._stabilize();
  10958. },
  10959. /**
  10960. * This function get the distribution of levels based on hubsize
  10961. *
  10962. * @returns {Object}
  10963. * @private
  10964. */
  10965. _getDistribution : function() {
  10966. var distribution = {};
  10967. var nodeId, node;
  10968. // 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.
  10969. // the fix of X is removed after the x value has been set.
  10970. for (nodeId in this.nodes) {
  10971. if (this.nodes.hasOwnProperty(nodeId)) {
  10972. node = this.nodes[nodeId];
  10973. node.xFixed = true;
  10974. node.yFixed = true;
  10975. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  10976. node.y = this.constants.hierarchicalLayout.levelSeparation*node.level;
  10977. }
  10978. else {
  10979. node.x = this.constants.hierarchicalLayout.levelSeparation*node.level;
  10980. }
  10981. if (!distribution.hasOwnProperty(node.level)) {
  10982. distribution[node.level] = {amount: 0, nodes: {}, minPos:0, nodeSpacing:0};
  10983. }
  10984. distribution[node.level].amount += 1;
  10985. distribution[node.level].nodes[node.id] = node;
  10986. }
  10987. }
  10988. // determine the largest amount of nodes of all levels
  10989. var maxCount = 0;
  10990. for (var level in distribution) {
  10991. if (distribution.hasOwnProperty(level)) {
  10992. if (maxCount < distribution[level].amount) {
  10993. maxCount = distribution[level].amount;
  10994. }
  10995. }
  10996. }
  10997. // set the initial position and spacing of each nodes accordingly
  10998. for (var level in distribution) {
  10999. if (distribution.hasOwnProperty(level)) {
  11000. distribution[level].nodeSpacing = (maxCount + 1) * this.constants.hierarchicalLayout.nodeSpacing;
  11001. distribution[level].nodeSpacing /= (distribution[level].amount + 1);
  11002. distribution[level].minPos = distribution[level].nodeSpacing - (0.5 * (distribution[level].amount + 1) * distribution[level].nodeSpacing);
  11003. }
  11004. }
  11005. return distribution;
  11006. },
  11007. /**
  11008. * this function allocates nodes in levels based on the recursive branching from the largest hubs.
  11009. *
  11010. * @param hubsize
  11011. * @private
  11012. */
  11013. _determineLevels : function(hubsize) {
  11014. var nodeId, node;
  11015. // determine hubs
  11016. for (nodeId in this.nodes) {
  11017. if (this.nodes.hasOwnProperty(nodeId)) {
  11018. node = this.nodes[nodeId];
  11019. if (node.edges.length == hubsize) {
  11020. node.level = 0;
  11021. }
  11022. }
  11023. }
  11024. // branch from hubs
  11025. for (nodeId in this.nodes) {
  11026. if (this.nodes.hasOwnProperty(nodeId)) {
  11027. node = this.nodes[nodeId];
  11028. if (node.level == 0) {
  11029. this._setLevel(1,node.edges,node.id);
  11030. }
  11031. }
  11032. }
  11033. },
  11034. /**
  11035. * Since hierarchical layout does not support:
  11036. * - smooth curves (based on the physics),
  11037. * - clustering (based on dynamic node counts)
  11038. *
  11039. * We disable both features so there will be no problems.
  11040. *
  11041. * @private
  11042. */
  11043. _changeConstants : function() {
  11044. this.constants.clustering.enabled = false;
  11045. this.constants.physics.barnesHut.enabled = false;
  11046. this.constants.physics.hierarchicalRepulsion.enabled = true;
  11047. this._loadSelectedForceSolver();
  11048. this.constants.smoothCurves = false;
  11049. this._configureSmoothCurves();
  11050. },
  11051. /**
  11052. * This is a recursively called function to enumerate the branches from the largest hubs and place the nodes
  11053. * on a X position that ensures there will be no overlap.
  11054. *
  11055. * @param edges
  11056. * @param parentId
  11057. * @param distribution
  11058. * @param parentLevel
  11059. * @private
  11060. */
  11061. _placeBranchNodes : function(edges, parentId, distribution, parentLevel) {
  11062. for (var i = 0; i < edges.length; i++) {
  11063. var childNode = null;
  11064. if (edges[i].toId == parentId) {
  11065. childNode = edges[i].from;
  11066. }
  11067. else {
  11068. childNode = edges[i].to;
  11069. }
  11070. // if a node is conneceted to another node on the same level (or higher (means lower level))!, this is not handled here.
  11071. var nodeMoved = false;
  11072. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  11073. if (childNode.xFixed && childNode.level > parentLevel) {
  11074. childNode.xFixed = false;
  11075. childNode.x = distribution[childNode.level].minPos;
  11076. nodeMoved = true;
  11077. }
  11078. }
  11079. else {
  11080. if (childNode.yFixed && childNode.level > parentLevel) {
  11081. childNode.yFixed = false;
  11082. childNode.y = distribution[childNode.level].minPos;
  11083. nodeMoved = true;
  11084. }
  11085. }
  11086. if (nodeMoved == true) {
  11087. distribution[childNode.level].minPos += distribution[childNode.level].nodeSpacing;
  11088. if (childNode.edges.length > 1) {
  11089. this._placeBranchNodes(childNode.edges,childNode.id,distribution,childNode.level);
  11090. }
  11091. }
  11092. }
  11093. },
  11094. /**
  11095. * this function is called recursively to enumerate the barnches of the largest hubs and give each node a level.
  11096. *
  11097. * @param level
  11098. * @param edges
  11099. * @param parentId
  11100. * @private
  11101. */
  11102. _setLevel : function(level, edges, parentId) {
  11103. for (var i = 0; i < edges.length; i++) {
  11104. var childNode = null;
  11105. if (edges[i].toId == parentId) {
  11106. childNode = edges[i].from;
  11107. }
  11108. else {
  11109. childNode = edges[i].to;
  11110. }
  11111. if (childNode.level == -1 || childNode.level > level) {
  11112. childNode.level = level;
  11113. if (edges.length > 1) {
  11114. this._setLevel(level+1, childNode.edges, childNode.id);
  11115. }
  11116. }
  11117. }
  11118. },
  11119. /**
  11120. * Unfix nodes
  11121. *
  11122. * @private
  11123. */
  11124. _restoreNodes : function() {
  11125. for (nodeId in this.nodes) {
  11126. if (this.nodes.hasOwnProperty(nodeId)) {
  11127. this.nodes[nodeId].xFixed = false;
  11128. this.nodes[nodeId].yFixed = false;
  11129. }
  11130. }
  11131. }
  11132. };
  11133. /**
  11134. * Created by Alex on 2/4/14.
  11135. */
  11136. var manipulationMixin = {
  11137. /**
  11138. * clears the toolbar div element of children
  11139. *
  11140. * @private
  11141. */
  11142. _clearManipulatorBar : function() {
  11143. while (this.manipulationDiv.hasChildNodes()) {
  11144. this.manipulationDiv.removeChild(this.manipulationDiv.firstChild);
  11145. }
  11146. },
  11147. /**
  11148. * Manipulation UI temporarily overloads certain functions to extend or replace them. To be able to restore
  11149. * these functions to their original functionality, we saved them in this.cachedFunctions.
  11150. * This function restores these functions to their original function.
  11151. *
  11152. * @private
  11153. */
  11154. _restoreOverloadedFunctions : function() {
  11155. for (var functionName in this.cachedFunctions) {
  11156. if (this.cachedFunctions.hasOwnProperty(functionName)) {
  11157. this[functionName] = this.cachedFunctions[functionName];
  11158. }
  11159. }
  11160. },
  11161. /**
  11162. * Enable or disable edit-mode.
  11163. *
  11164. * @private
  11165. */
  11166. _toggleEditMode : function() {
  11167. this.editMode = !this.editMode;
  11168. var toolbar = document.getElementById("graph-manipulationDiv");
  11169. var closeDiv = document.getElementById("graph-manipulation-closeDiv");
  11170. var editModeDiv = document.getElementById("graph-manipulation-editMode");
  11171. if (this.editMode == true) {
  11172. toolbar.style.display="block";
  11173. closeDiv.style.display="block";
  11174. editModeDiv.style.display="none";
  11175. closeDiv.onclick = this._toggleEditMode.bind(this);
  11176. }
  11177. else {
  11178. toolbar.style.display="none";
  11179. closeDiv.style.display="none";
  11180. editModeDiv.style.display="block";
  11181. closeDiv.onclick = null;
  11182. }
  11183. this._createManipulatorBar()
  11184. },
  11185. /**
  11186. * main function, creates the main toolbar. Removes functions bound to the select event. Binds all the buttons of the toolbar.
  11187. *
  11188. * @private
  11189. */
  11190. _createManipulatorBar : function() {
  11191. // remove bound functions
  11192. if (this.boundFunction) {
  11193. this.off('select', this.boundFunction);
  11194. }
  11195. // restore overloaded functions
  11196. this._restoreOverloadedFunctions();
  11197. // resume calculation
  11198. this.freezeSimulation = false;
  11199. // reset global variables
  11200. this.blockConnectingEdgeSelection = false;
  11201. this.forceAppendSelection = false
  11202. if (this.editMode == true) {
  11203. while (this.manipulationDiv.hasChildNodes()) {
  11204. this.manipulationDiv.removeChild(this.manipulationDiv.firstChild);
  11205. }
  11206. // add the icons to the manipulator div
  11207. this.manipulationDiv.innerHTML = "" +
  11208. "<span class='graph-manipulationUI add' id='graph-manipulate-addNode'>" +
  11209. "<span class='graph-manipulationLabel'>Add Node</span></span>" +
  11210. "<div class='graph-seperatorLine'></div>" +
  11211. "<span class='graph-manipulationUI connect' id='graph-manipulate-connectNode'>" +
  11212. "<span class='graph-manipulationLabel'>Add Link</span></span>";
  11213. if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
  11214. this.manipulationDiv.innerHTML += "" +
  11215. "<div class='graph-seperatorLine'></div>" +
  11216. "<span class='graph-manipulationUI edit' id='graph-manipulate-editNode'>" +
  11217. "<span class='graph-manipulationLabel'>Edit Node</span></span>";
  11218. }
  11219. if (this._selectionIsEmpty() == false) {
  11220. this.manipulationDiv.innerHTML += "" +
  11221. "<div class='graph-seperatorLine'></div>" +
  11222. "<span class='graph-manipulationUI delete' id='graph-manipulate-delete'>" +
  11223. "<span class='graph-manipulationLabel'>Delete selected</span></span>";
  11224. }
  11225. // bind the icons
  11226. var addNodeButton = document.getElementById("graph-manipulate-addNode");
  11227. addNodeButton.onclick = this._createAddNodeToolbar.bind(this);
  11228. var addEdgeButton = document.getElementById("graph-manipulate-connectNode");
  11229. addEdgeButton.onclick = this._createAddEdgeToolbar.bind(this);
  11230. if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
  11231. var editButton = document.getElementById("graph-manipulate-editNode");
  11232. editButton.onclick = this._editNode.bind(this);
  11233. }
  11234. if (this._selectionIsEmpty() == false) {
  11235. var deleteButton = document.getElementById("graph-manipulate-delete");
  11236. deleteButton.onclick = this._deleteSelected.bind(this);
  11237. }
  11238. var closeDiv = document.getElementById("graph-manipulation-closeDiv");
  11239. closeDiv.onclick = this._toggleEditMode.bind(this);
  11240. this.boundFunction = this._createManipulatorBar.bind(this);
  11241. this.on('select', this.boundFunction);
  11242. }
  11243. else {
  11244. this.editModeDiv.innerHTML = "" +
  11245. "<span class='graph-manipulationUI edit editmode' id='graph-manipulate-editModeButton'>" +
  11246. "<span class='graph-manipulationLabel'>Edit</span></span>"
  11247. var editModeButton = document.getElementById("graph-manipulate-editModeButton");
  11248. editModeButton.onclick = this._toggleEditMode.bind(this);
  11249. }
  11250. },
  11251. /**
  11252. * Create the toolbar for adding Nodes
  11253. *
  11254. * @private
  11255. */
  11256. _createAddNodeToolbar : function() {
  11257. // clear the toolbar
  11258. this._clearManipulatorBar();
  11259. if (this.boundFunction) {
  11260. this.off('select', this.boundFunction);
  11261. }
  11262. // create the toolbar contents
  11263. this.manipulationDiv.innerHTML = "" +
  11264. "<span class='graph-manipulationUI back' id='graph-manipulate-back'>" +
  11265. "<span class='graph-manipulationLabel'>Back</span></span>" +
  11266. "<div class='graph-seperatorLine'></div>" +
  11267. "<span class='graph-manipulationUI none' id='graph-manipulate-back'>" +
  11268. "<span class='graph-manipulationLabel'>Click in an empty space to place a new node</span></span>";
  11269. // bind the icon
  11270. var backButton = document.getElementById("graph-manipulate-back");
  11271. backButton.onclick = this._createManipulatorBar.bind(this);
  11272. // we use the boundFunction so we can reference it when we unbind it from the "select" event.
  11273. this.boundFunction = this._addNode.bind(this);
  11274. this.on('select', this.boundFunction);
  11275. },
  11276. /**
  11277. * create the toolbar to connect nodes
  11278. *
  11279. * @private
  11280. */
  11281. _createAddEdgeToolbar : function() {
  11282. // clear the toolbar
  11283. this._clearManipulatorBar();
  11284. this._unselectAll(true);
  11285. this.freezeSimulation = true;
  11286. if (this.boundFunction) {
  11287. this.off('select', this.boundFunction);
  11288. }
  11289. this._unselectAll();
  11290. this.forceAppendSelection = false;
  11291. this.blockConnectingEdgeSelection = true;
  11292. this.manipulationDiv.innerHTML = "" +
  11293. "<span class='graph-manipulationUI back' id='graph-manipulate-back'>" +
  11294. "<span class='graph-manipulationLabel'>Back</span></span>" +
  11295. "<div class='graph-seperatorLine'></div>" +
  11296. "<span class='graph-manipulationUI none' id='graph-manipulate-back'>" +
  11297. "<span id='graph-manipulatorLabel' class='graph-manipulationLabel'>Click on a node and drag the edge to another node to connect them.</span></span>";
  11298. // bind the icon
  11299. var backButton = document.getElementById("graph-manipulate-back");
  11300. backButton.onclick = this._createManipulatorBar.bind(this);
  11301. // we use the boundFunction so we can reference it when we unbind it from the "select" event.
  11302. this.boundFunction = this._handleConnect.bind(this);
  11303. this.on('select', this.boundFunction);
  11304. // temporarily overload functions
  11305. this.cachedFunctions["_handleTouch"] = this._handleTouch;
  11306. this.cachedFunctions["_handleOnRelease"] = this._handleOnRelease;
  11307. this._handleTouch = this._handleConnect;
  11308. this._handleOnRelease = this._finishConnect;
  11309. // redraw to show the unselect
  11310. this._redraw();
  11311. },
  11312. /**
  11313. * the function bound to the selection event. It checks if you want to connect a cluster and changes the description
  11314. * to walk the user through the process.
  11315. *
  11316. * @private
  11317. */
  11318. _handleConnect : function(pointer) {
  11319. if (this._getSelectedNodeCount() == 0) {
  11320. var node = this._getNodeAt(pointer);
  11321. if (node != null) {
  11322. if (node.clusterSize > 1) {
  11323. alert("Cannot create edges to a cluster.")
  11324. }
  11325. else {
  11326. this._selectObject(node,false);
  11327. // create a node the temporary line can look at
  11328. this.sectors['support']['nodes']['targetNode'] = new Node({id:'targetNode'},{},{},this.constants);
  11329. this.sectors['support']['nodes']['targetNode'].x = node.x;
  11330. this.sectors['support']['nodes']['targetNode'].y = node.y;
  11331. this.sectors['support']['nodes']['targetViaNode'] = new Node({id:'targetViaNode'},{},{},this.constants);
  11332. this.sectors['support']['nodes']['targetViaNode'].x = node.x;
  11333. this.sectors['support']['nodes']['targetViaNode'].y = node.y;
  11334. this.sectors['support']['nodes']['targetViaNode'].parentEdgeId = "connectionEdge";
  11335. // create a temporary edge
  11336. this.edges['connectionEdge'] = new Edge({id:"connectionEdge",from:node.id,to:this.sectors['support']['nodes']['targetNode'].id}, this, this.constants);
  11337. this.edges['connectionEdge'].from = node;
  11338. this.edges['connectionEdge'].connected = true;
  11339. this.edges['connectionEdge'].smooth = true;
  11340. this.edges['connectionEdge'].selected = true;
  11341. this.edges['connectionEdge'].to = this.sectors['support']['nodes']['targetNode'];
  11342. this.edges['connectionEdge'].via = this.sectors['support']['nodes']['targetViaNode'];
  11343. this.cachedFunctions["_handleOnDrag"] = this._handleOnDrag;
  11344. this._handleOnDrag = function(event) {
  11345. var pointer = this._getPointer(event.gesture.center);
  11346. this.sectors['support']['nodes']['targetNode'].x = this._canvasToX(pointer.x);
  11347. this.sectors['support']['nodes']['targetNode'].y = this._canvasToY(pointer.y);
  11348. this.sectors['support']['nodes']['targetViaNode'].x = 0.5 * (this._canvasToX(pointer.x) + this.edges['connectionEdge'].from.x);
  11349. this.sectors['support']['nodes']['targetViaNode'].y = this._canvasToY(pointer.y);
  11350. };
  11351. this.moving = true;
  11352. this.start();
  11353. }
  11354. }
  11355. }
  11356. },
  11357. _finishConnect : function(pointer) {
  11358. if (this._getSelectedNodeCount() == 1) {
  11359. // restore the drag function
  11360. this._handleOnDrag = this.cachedFunctions["_handleOnDrag"];
  11361. delete this.cachedFunctions["_handleOnDrag"];
  11362. // remember the edge id
  11363. var connectFromId = this.edges['connectionEdge'].fromId;
  11364. // remove the temporary nodes and edge
  11365. delete this.edges['connectionEdge']
  11366. delete this.sectors['support']['nodes']['targetNode'];
  11367. delete this.sectors['support']['nodes']['targetViaNode'];
  11368. var node = this._getNodeAt(pointer);
  11369. if (node != null) {
  11370. if (node.clusterSize > 1) {
  11371. alert("Cannot create edges to a cluster.")
  11372. }
  11373. else {
  11374. this._createEdge(connectFromId,node.id);
  11375. this._createManipulatorBar();
  11376. }
  11377. }
  11378. this._unselectAll();
  11379. }
  11380. },
  11381. /**
  11382. * Adds a node on the specified location
  11383. *
  11384. * @param {Object} pointer
  11385. */
  11386. _addNode : function() {
  11387. if (this._selectionIsEmpty() && this.editMode == true) {
  11388. var positionObject = this._pointerToPositionObject(this.pointerPosition);
  11389. var defaultData = {id:util.randomUUID(),x:positionObject.left,y:positionObject.top,label:"new",allowedToMoveX:true,allowedToMoveY:true};
  11390. if (this.triggerFunctions.add) {
  11391. if (this.triggerFunctions.add.length == 2) {
  11392. var me = this;
  11393. this.triggerFunctions.add(defaultData, function(finalizedData) {
  11394. me.nodesData.add(finalizedData);
  11395. me._createManipulatorBar();
  11396. me.moving = true;
  11397. me.start();
  11398. });
  11399. }
  11400. else {
  11401. alert("The function for add does not support two arguments (data,callback).");
  11402. this._createManipulatorBar();
  11403. this.moving = true;
  11404. this.start();
  11405. }
  11406. }
  11407. else {
  11408. this.nodesData.add(defaultData);
  11409. this._createManipulatorBar();
  11410. this.moving = true;
  11411. this.start();
  11412. }
  11413. }
  11414. },
  11415. /**
  11416. * connect two nodes with a new edge.
  11417. *
  11418. * @private
  11419. */
  11420. _createEdge : function(sourceNodeId,targetNodeId) {
  11421. if (this.editMode == true) {
  11422. var defaultData = {from:sourceNodeId, to:targetNodeId};
  11423. if (this.triggerFunctions.connect) {
  11424. if (this.triggerFunctions.connect.length == 2) {
  11425. var me = this;
  11426. this.triggerFunctions.connect(defaultData, function(finalizedData) {
  11427. me.edgesData.add(finalizedData)
  11428. me.moving = true;
  11429. me.start();
  11430. });
  11431. }
  11432. else {
  11433. alert("The function for connect does not support two arguments (data,callback).");
  11434. this.moving = true;
  11435. this.start();
  11436. }
  11437. }
  11438. else {
  11439. this.edgesData.add(defaultData)
  11440. this.moving = true;
  11441. this.start();
  11442. }
  11443. }
  11444. },
  11445. /**
  11446. * Create the toolbar to edit the selected node. The label and the color can be changed. Other colors are derived from the chosen color.
  11447. *
  11448. * @private
  11449. */
  11450. _editNode : function() {
  11451. if (this.triggerFunctions.edit && this.editMode == true) {
  11452. var node = this._getSelectedNode();
  11453. var data = {id:node.id,
  11454. label: node.label,
  11455. group: node.group,
  11456. shape: node.shape,
  11457. color: {
  11458. background:node.color.background,
  11459. border:node.color.border,
  11460. highlight: {
  11461. background:node.color.highlight.background,
  11462. border:node.color.highlight.border
  11463. }
  11464. }};
  11465. if (this.triggerFunctions.edit.length == 2) {
  11466. var me = this;
  11467. this.triggerFunctions.edit(data, function (finalizedData) {
  11468. me.nodesData.update(finalizedData);
  11469. me._createManipulatorBar();
  11470. me.moving = true;
  11471. me.start();
  11472. });
  11473. }
  11474. else {
  11475. alert("The function for edit does not support two arguments (data, callback).")
  11476. }
  11477. }
  11478. else {
  11479. alert("No edit function has been bound to this button.")
  11480. }
  11481. },
  11482. /**
  11483. * delete everything in the selection
  11484. *
  11485. * @private
  11486. */
  11487. _deleteSelected : function() {
  11488. if (!this._selectionIsEmpty() && this.editMode == true) {
  11489. if (!this._clusterInSelection()) {
  11490. var selectedNodes = this.getSelectedNodes();
  11491. var selectedEdges = this.getSelectedEdges();
  11492. if (this.triggerFunctions.delete) {
  11493. var me = this;
  11494. var data = {nodes: selectedNodes, edges: selectedEdges};
  11495. if (this.triggerFunctions.delete.length = 2) {
  11496. this.triggerFunctions.delete(data, function (finalizedData) {
  11497. me.edgesData.remove(finalizedData.edges);
  11498. me.nodesData.remove(finalizedData.nodes);
  11499. this._unselectAll();
  11500. me.moving = true;
  11501. me.start();
  11502. });
  11503. }
  11504. else {
  11505. alert("The function for edit does not support two arguments (data, callback).")
  11506. }
  11507. }
  11508. else {
  11509. this.edgesData.remove(selectedEdges);
  11510. this.nodesData.remove(selectedNodes);
  11511. this._unselectAll();
  11512. this.moving = true;
  11513. this.start();
  11514. }
  11515. }
  11516. else {
  11517. alert("Clusters cannot be deleted.");
  11518. }
  11519. }
  11520. }
  11521. };
  11522. /**
  11523. * Creation of the SectorMixin var.
  11524. *
  11525. * This contains all the functions the Graph object can use to employ the sector system.
  11526. * The sector system is always used by Graph, though the benefits only apply to the use of clustering.
  11527. * If clustering is not used, there is no overhead except for a duplicate object with references to nodes and edges.
  11528. *
  11529. * Alex de Mulder
  11530. * 21-01-2013
  11531. */
  11532. var SectorMixin = {
  11533. /**
  11534. * This function is only called by the setData function of the Graph object.
  11535. * This loads the global references into the active sector. This initializes the sector.
  11536. *
  11537. * @private
  11538. */
  11539. _putDataInSector : function() {
  11540. this.sectors["active"][this._sector()].nodes = this.nodes;
  11541. this.sectors["active"][this._sector()].edges = this.edges;
  11542. this.sectors["active"][this._sector()].nodeIndices = this.nodeIndices;
  11543. },
  11544. /**
  11545. * /**
  11546. * This function sets the global references to nodes, edges and nodeIndices back to
  11547. * those of the supplied (active) sector. If a type is defined, do the specific type
  11548. *
  11549. * @param {String} sectorId
  11550. * @param {String} [sectorType] | "active" or "frozen"
  11551. * @private
  11552. */
  11553. _switchToSector : function(sectorId, sectorType) {
  11554. if (sectorType === undefined || sectorType == "active") {
  11555. this._switchToActiveSector(sectorId);
  11556. }
  11557. else {
  11558. this._switchToFrozenSector(sectorId);
  11559. }
  11560. },
  11561. /**
  11562. * This function sets the global references to nodes, edges and nodeIndices back to
  11563. * those of the supplied active sector.
  11564. *
  11565. * @param sectorId
  11566. * @private
  11567. */
  11568. _switchToActiveSector : function(sectorId) {
  11569. this.nodeIndices = this.sectors["active"][sectorId]["nodeIndices"];
  11570. this.nodes = this.sectors["active"][sectorId]["nodes"];
  11571. this.edges = this.sectors["active"][sectorId]["edges"];
  11572. },
  11573. /**
  11574. * This function sets the global references to nodes, edges and nodeIndices back to
  11575. * those of the supplied active sector.
  11576. *
  11577. * @param sectorId
  11578. * @private
  11579. */
  11580. _switchToSupportSector : function() {
  11581. this.nodeIndices = this.sectors["support"]["nodeIndices"];
  11582. this.nodes = this.sectors["support"]["nodes"];
  11583. this.edges = this.sectors["support"]["edges"];
  11584. },
  11585. /**
  11586. * This function sets the global references to nodes, edges and nodeIndices back to
  11587. * those of the supplied frozen sector.
  11588. *
  11589. * @param sectorId
  11590. * @private
  11591. */
  11592. _switchToFrozenSector : function(sectorId) {
  11593. this.nodeIndices = this.sectors["frozen"][sectorId]["nodeIndices"];
  11594. this.nodes = this.sectors["frozen"][sectorId]["nodes"];
  11595. this.edges = this.sectors["frozen"][sectorId]["edges"];
  11596. },
  11597. /**
  11598. * This function sets the global references to nodes, edges and nodeIndices back to
  11599. * those of the currently active sector.
  11600. *
  11601. * @private
  11602. */
  11603. _loadLatestSector : function() {
  11604. this._switchToSector(this._sector());
  11605. },
  11606. /**
  11607. * This function returns the currently active sector Id
  11608. *
  11609. * @returns {String}
  11610. * @private
  11611. */
  11612. _sector : function() {
  11613. return this.activeSector[this.activeSector.length-1];
  11614. },
  11615. /**
  11616. * This function returns the previously active sector Id
  11617. *
  11618. * @returns {String}
  11619. * @private
  11620. */
  11621. _previousSector : function() {
  11622. if (this.activeSector.length > 1) {
  11623. return this.activeSector[this.activeSector.length-2];
  11624. }
  11625. else {
  11626. throw new TypeError('there are not enough sectors in the this.activeSector array.');
  11627. }
  11628. },
  11629. /**
  11630. * We add the active sector at the end of the this.activeSector array
  11631. * This ensures it is the currently active sector returned by _sector() and it reaches the top
  11632. * of the activeSector stack. When we reverse our steps we move from the end to the beginning of this stack.
  11633. *
  11634. * @param newId
  11635. * @private
  11636. */
  11637. _setActiveSector : function(newId) {
  11638. this.activeSector.push(newId);
  11639. },
  11640. /**
  11641. * We remove the currently active sector id from the active sector stack. This happens when
  11642. * we reactivate the previously active sector
  11643. *
  11644. * @private
  11645. */
  11646. _forgetLastSector : function() {
  11647. this.activeSector.pop();
  11648. },
  11649. /**
  11650. * This function creates a new active sector with the supplied newId. This newId
  11651. * is the expanding node id.
  11652. *
  11653. * @param {String} newId | Id of the new active sector
  11654. * @private
  11655. */
  11656. _createNewSector : function(newId) {
  11657. // create the new sector
  11658. this.sectors["active"][newId] = {"nodes":{},
  11659. "edges":{},
  11660. "nodeIndices":[],
  11661. "formationScale": this.scale,
  11662. "drawingNode": undefined};
  11663. // create the new sector render node. This gives visual feedback that you are in a new sector.
  11664. this.sectors["active"][newId]['drawingNode'] = new Node(
  11665. {id:newId,
  11666. color: {
  11667. background: "#eaefef",
  11668. border: "495c5e"
  11669. }
  11670. },{},{},this.constants);
  11671. this.sectors["active"][newId]['drawingNode'].clusterSize = 2;
  11672. },
  11673. /**
  11674. * This function removes the currently active sector. This is called when we create a new
  11675. * active sector.
  11676. *
  11677. * @param {String} sectorId | Id of the active sector that will be removed
  11678. * @private
  11679. */
  11680. _deleteActiveSector : function(sectorId) {
  11681. delete this.sectors["active"][sectorId];
  11682. },
  11683. /**
  11684. * This function removes the currently active sector. This is called when we reactivate
  11685. * the previously active sector.
  11686. *
  11687. * @param {String} sectorId | Id of the active sector that will be removed
  11688. * @private
  11689. */
  11690. _deleteFrozenSector : function(sectorId) {
  11691. delete this.sectors["frozen"][sectorId];
  11692. },
  11693. /**
  11694. * Freezing an active sector means moving it from the "active" object to the "frozen" object.
  11695. * We copy the references, then delete the active entree.
  11696. *
  11697. * @param sectorId
  11698. * @private
  11699. */
  11700. _freezeSector : function(sectorId) {
  11701. // we move the set references from the active to the frozen stack.
  11702. this.sectors["frozen"][sectorId] = this.sectors["active"][sectorId];
  11703. // we have moved the sector data into the frozen set, we now remove it from the active set
  11704. this._deleteActiveSector(sectorId);
  11705. },
  11706. /**
  11707. * This is the reverse operation of _freezeSector. Activating means moving the sector from the "frozen"
  11708. * object to the "active" object.
  11709. *
  11710. * @param sectorId
  11711. * @private
  11712. */
  11713. _activateSector : function(sectorId) {
  11714. // we move the set references from the frozen to the active stack.
  11715. this.sectors["active"][sectorId] = this.sectors["frozen"][sectorId];
  11716. // we have moved the sector data into the active set, we now remove it from the frozen stack
  11717. this._deleteFrozenSector(sectorId);
  11718. },
  11719. /**
  11720. * This function merges the data from the currently active sector with a frozen sector. This is used
  11721. * in the process of reverting back to the previously active sector.
  11722. * The data that is placed in the frozen (the previously active) sector is the node that has been removed from it
  11723. * upon the creation of a new active sector.
  11724. *
  11725. * @param sectorId
  11726. * @private
  11727. */
  11728. _mergeThisWithFrozen : function(sectorId) {
  11729. // copy all nodes
  11730. for (var nodeId in this.nodes) {
  11731. if (this.nodes.hasOwnProperty(nodeId)) {
  11732. this.sectors["frozen"][sectorId]["nodes"][nodeId] = this.nodes[nodeId];
  11733. }
  11734. }
  11735. // copy all edges (if not fully clustered, else there are no edges)
  11736. for (var edgeId in this.edges) {
  11737. if (this.edges.hasOwnProperty(edgeId)) {
  11738. this.sectors["frozen"][sectorId]["edges"][edgeId] = this.edges[edgeId];
  11739. }
  11740. }
  11741. // merge the nodeIndices
  11742. for (var i = 0; i < this.nodeIndices.length; i++) {
  11743. this.sectors["frozen"][sectorId]["nodeIndices"].push(this.nodeIndices[i]);
  11744. }
  11745. },
  11746. /**
  11747. * This clusters the sector to one cluster. It was a single cluster before this process started so
  11748. * we revert to that state. The clusterToFit function with a maximum size of 1 node does this.
  11749. *
  11750. * @private
  11751. */
  11752. _collapseThisToSingleCluster : function() {
  11753. this.clusterToFit(1,false);
  11754. },
  11755. /**
  11756. * We create a new active sector from the node that we want to open.
  11757. *
  11758. * @param node
  11759. * @private
  11760. */
  11761. _addSector : function(node) {
  11762. // this is the currently active sector
  11763. var sector = this._sector();
  11764. // // this should allow me to select nodes from a frozen set.
  11765. // if (this.sectors['active'][sector]["nodes"].hasOwnProperty(node.id)) {
  11766. // console.log("the node is part of the active sector");
  11767. // }
  11768. // else {
  11769. // console.log("I dont know what the fuck happened!!");
  11770. // }
  11771. // when we switch to a new sector, we remove the node that will be expanded from the current nodes list.
  11772. delete this.nodes[node.id];
  11773. var unqiueIdentifier = util.randomUUID();
  11774. // we fully freeze the currently active sector
  11775. this._freezeSector(sector);
  11776. // we create a new active sector. This sector has the Id of the node to ensure uniqueness
  11777. this._createNewSector(unqiueIdentifier);
  11778. // we add the active sector to the sectors array to be able to revert these steps later on
  11779. this._setActiveSector(unqiueIdentifier);
  11780. // we redirect the global references to the new sector's references. this._sector() now returns unqiueIdentifier
  11781. this._switchToSector(this._sector());
  11782. // finally we add the node we removed from our previous active sector to the new active sector
  11783. this.nodes[node.id] = node;
  11784. },
  11785. /**
  11786. * We close the sector that is currently open and revert back to the one before.
  11787. * If the active sector is the "default" sector, nothing happens.
  11788. *
  11789. * @private
  11790. */
  11791. _collapseSector : function() {
  11792. // the currently active sector
  11793. var sector = this._sector();
  11794. // we cannot collapse the default sector
  11795. if (sector != "default") {
  11796. if ((this.nodeIndices.length == 1) ||
  11797. (this.sectors["active"][sector]["drawingNode"].width*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  11798. (this.sectors["active"][sector]["drawingNode"].height*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  11799. var previousSector = this._previousSector();
  11800. // we collapse the sector back to a single cluster
  11801. this._collapseThisToSingleCluster();
  11802. // we move the remaining nodes, edges and nodeIndices to the previous sector.
  11803. // This previous sector is the one we will reactivate
  11804. this._mergeThisWithFrozen(previousSector);
  11805. // the previously active (frozen) sector now has all the data from the currently active sector.
  11806. // we can now delete the active sector.
  11807. this._deleteActiveSector(sector);
  11808. // we activate the previously active (and currently frozen) sector.
  11809. this._activateSector(previousSector);
  11810. // we load the references from the newly active sector into the global references
  11811. this._switchToSector(previousSector);
  11812. // we forget the previously active sector because we reverted to the one before
  11813. this._forgetLastSector();
  11814. // finally, we update the node index list.
  11815. this._updateNodeIndexList();
  11816. // we refresh the list with calulation nodes and calculation node indices.
  11817. this._updateCalculationNodes();
  11818. }
  11819. }
  11820. },
  11821. /**
  11822. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  11823. *
  11824. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11825. * | we dont pass the function itself because then the "this" is the window object
  11826. * | instead of the Graph object
  11827. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11828. * @private
  11829. */
  11830. _doInAllActiveSectors : function(runFunction,argument) {
  11831. if (argument === undefined) {
  11832. for (var sector in this.sectors["active"]) {
  11833. if (this.sectors["active"].hasOwnProperty(sector)) {
  11834. // switch the global references to those of this sector
  11835. this._switchToActiveSector(sector);
  11836. this[runFunction]();
  11837. }
  11838. }
  11839. }
  11840. else {
  11841. for (var sector in this.sectors["active"]) {
  11842. if (this.sectors["active"].hasOwnProperty(sector)) {
  11843. // switch the global references to those of this sector
  11844. this._switchToActiveSector(sector);
  11845. var args = Array.prototype.splice.call(arguments, 1);
  11846. if (args.length > 1) {
  11847. this[runFunction](args[0],args[1]);
  11848. }
  11849. else {
  11850. this[runFunction](argument);
  11851. }
  11852. }
  11853. }
  11854. }
  11855. // we revert the global references back to our active sector
  11856. this._loadLatestSector();
  11857. },
  11858. /**
  11859. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  11860. *
  11861. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11862. * | we dont pass the function itself because then the "this" is the window object
  11863. * | instead of the Graph object
  11864. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11865. * @private
  11866. */
  11867. _doInSupportSector : function(runFunction,argument) {
  11868. if (argument === undefined) {
  11869. this._switchToSupportSector();
  11870. this[runFunction]();
  11871. }
  11872. else {
  11873. this._switchToSupportSector();
  11874. var args = Array.prototype.splice.call(arguments, 1);
  11875. if (args.length > 1) {
  11876. this[runFunction](args[0],args[1]);
  11877. }
  11878. else {
  11879. this[runFunction](argument);
  11880. }
  11881. }
  11882. // we revert the global references back to our active sector
  11883. this._loadLatestSector();
  11884. },
  11885. /**
  11886. * This runs a function in all frozen sectors. This is used in the _redraw().
  11887. *
  11888. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11889. * | we don't pass the function itself because then the "this" is the window object
  11890. * | instead of the Graph object
  11891. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11892. * @private
  11893. */
  11894. _doInAllFrozenSectors : function(runFunction,argument) {
  11895. if (argument === undefined) {
  11896. for (var sector in this.sectors["frozen"]) {
  11897. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  11898. // switch the global references to those of this sector
  11899. this._switchToFrozenSector(sector);
  11900. this[runFunction]();
  11901. }
  11902. }
  11903. }
  11904. else {
  11905. for (var sector in this.sectors["frozen"]) {
  11906. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  11907. // switch the global references to those of this sector
  11908. this._switchToFrozenSector(sector);
  11909. var args = Array.prototype.splice.call(arguments, 1);
  11910. if (args.length > 1) {
  11911. this[runFunction](args[0],args[1]);
  11912. }
  11913. else {
  11914. this[runFunction](argument);
  11915. }
  11916. }
  11917. }
  11918. }
  11919. this._loadLatestSector();
  11920. },
  11921. /**
  11922. * This runs a function in all sectors. This is used in the _redraw().
  11923. *
  11924. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11925. * | we don't pass the function itself because then the "this" is the window object
  11926. * | instead of the Graph object
  11927. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11928. * @private
  11929. */
  11930. _doInAllSectors : function(runFunction,argument) {
  11931. var args = Array.prototype.splice.call(arguments, 1);
  11932. if (argument === undefined) {
  11933. this._doInAllActiveSectors(runFunction);
  11934. this._doInAllFrozenSectors(runFunction);
  11935. }
  11936. else {
  11937. if (args.length > 1) {
  11938. this._doInAllActiveSectors(runFunction,args[0],args[1]);
  11939. this._doInAllFrozenSectors(runFunction,args[0],args[1]);
  11940. }
  11941. else {
  11942. this._doInAllActiveSectors(runFunction,argument);
  11943. this._doInAllFrozenSectors(runFunction,argument);
  11944. }
  11945. }
  11946. },
  11947. /**
  11948. * This clears the nodeIndices list. We cannot use this.nodeIndices = [] because we would break the link with the
  11949. * active sector. Thus we clear the nodeIndices in the active sector, then reconnect the this.nodeIndices to it.
  11950. *
  11951. * @private
  11952. */
  11953. _clearNodeIndexList : function() {
  11954. var sector = this._sector();
  11955. this.sectors["active"][sector]["nodeIndices"] = [];
  11956. this.nodeIndices = this.sectors["active"][sector]["nodeIndices"];
  11957. },
  11958. /**
  11959. * Draw the encompassing sector node
  11960. *
  11961. * @param ctx
  11962. * @param sectorType
  11963. * @private
  11964. */
  11965. _drawSectorNodes : function(ctx,sectorType) {
  11966. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  11967. for (var sector in this.sectors[sectorType]) {
  11968. if (this.sectors[sectorType].hasOwnProperty(sector)) {
  11969. if (this.sectors[sectorType][sector]["drawingNode"] !== undefined) {
  11970. this._switchToSector(sector,sectorType);
  11971. minY = 1e9; maxY = -1e9; minX = 1e9; maxX = -1e9;
  11972. for (var nodeId in this.nodes) {
  11973. if (this.nodes.hasOwnProperty(nodeId)) {
  11974. node = this.nodes[nodeId];
  11975. node.resize(ctx);
  11976. if (minX > node.x - 0.5 * node.width) {minX = node.x - 0.5 * node.width;}
  11977. if (maxX < node.x + 0.5 * node.width) {maxX = node.x + 0.5 * node.width;}
  11978. if (minY > node.y - 0.5 * node.height) {minY = node.y - 0.5 * node.height;}
  11979. if (maxY < node.y + 0.5 * node.height) {maxY = node.y + 0.5 * node.height;}
  11980. }
  11981. }
  11982. node = this.sectors[sectorType][sector]["drawingNode"];
  11983. node.x = 0.5 * (maxX + minX);
  11984. node.y = 0.5 * (maxY + minY);
  11985. node.width = 2 * (node.x - minX);
  11986. node.height = 2 * (node.y - minY);
  11987. node.radius = Math.sqrt(Math.pow(0.5*node.width,2) + Math.pow(0.5*node.height,2));
  11988. node.setScale(this.scale);
  11989. node._drawCircle(ctx);
  11990. }
  11991. }
  11992. }
  11993. },
  11994. _drawAllSectorNodes : function(ctx) {
  11995. this._drawSectorNodes(ctx,"frozen");
  11996. this._drawSectorNodes(ctx,"active");
  11997. this._loadLatestSector();
  11998. }
  11999. };
  12000. /**
  12001. * Creation of the ClusterMixin var.
  12002. *
  12003. * This contains all the functions the Graph object can use to employ clustering
  12004. *
  12005. * Alex de Mulder
  12006. * 21-01-2013
  12007. */
  12008. var ClusterMixin = {
  12009. /**
  12010. * This is only called in the constructor of the graph object
  12011. *
  12012. */
  12013. startWithClustering : function() {
  12014. // cluster if the data set is big
  12015. this.clusterToFit(this.constants.clustering.initialMaxNodes, true);
  12016. // updates the lables after clustering
  12017. this.updateLabels();
  12018. // this is called here because if clusterin is disabled, the start and stabilize are called in
  12019. // the setData function.
  12020. if (this.stabilize) {
  12021. this._stabilize();
  12022. }
  12023. this.start();
  12024. },
  12025. /**
  12026. * This function clusters until the initialMaxNodes has been reached
  12027. *
  12028. * @param {Number} maxNumberOfNodes
  12029. * @param {Boolean} reposition
  12030. */
  12031. clusterToFit : function(maxNumberOfNodes, reposition) {
  12032. var numberOfNodes = this.nodeIndices.length;
  12033. var maxLevels = 50;
  12034. var level = 0;
  12035. // we first cluster the hubs, then we pull in the outliers, repeat
  12036. while (numberOfNodes > maxNumberOfNodes && level < maxLevels) {
  12037. if (level % 3 == 0) {
  12038. this.forceAggregateHubs(true);
  12039. this.normalizeClusterLevels();
  12040. }
  12041. else {
  12042. this.increaseClusterLevel(); // this also includes a cluster normalization
  12043. }
  12044. numberOfNodes = this.nodeIndices.length;
  12045. level += 1;
  12046. }
  12047. // after the clustering we reposition the nodes to reduce the initial chaos
  12048. if (level > 0 && reposition == true) {
  12049. this.repositionNodes();
  12050. }
  12051. this._updateCalculationNodes();
  12052. },
  12053. /**
  12054. * This function can be called to open up a specific cluster. It is only called by
  12055. * It will unpack the cluster back one level.
  12056. *
  12057. * @param node | Node object: cluster to open.
  12058. */
  12059. openCluster : function(node) {
  12060. var isMovingBeforeClustering = this.moving;
  12061. if (node.clusterSize > this.constants.clustering.sectorThreshold && this._nodeInActiveArea(node) &&
  12062. !(this._sector() == "default" && this.nodeIndices.length == 1)) {
  12063. // this loads a new sector, loads the nodes and edges and nodeIndices of it.
  12064. this._addSector(node);
  12065. var level = 0;
  12066. // we decluster until we reach a decent number of nodes
  12067. while ((this.nodeIndices.length < this.constants.clustering.initialMaxNodes) && (level < 10)) {
  12068. this.decreaseClusterLevel();
  12069. level += 1;
  12070. }
  12071. }
  12072. else {
  12073. this._expandClusterNode(node,false,true);
  12074. // update the index list, dynamic edges and labels
  12075. this._updateNodeIndexList();
  12076. this._updateDynamicEdges();
  12077. this._updateCalculationNodes();
  12078. this.updateLabels();
  12079. }
  12080. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  12081. if (this.moving != isMovingBeforeClustering) {
  12082. this.start();
  12083. }
  12084. },
  12085. /**
  12086. * This calls the updateClustes with default arguments
  12087. */
  12088. updateClustersDefault : function() {
  12089. if (this.constants.clustering.enabled == true) {
  12090. this.updateClusters(0,false,false);
  12091. }
  12092. },
  12093. /**
  12094. * This function can be called to increase the cluster level. This means that the nodes with only one edge connection will
  12095. * be clustered with their connected node. This can be repeated as many times as needed.
  12096. * This can be called externally (by a keybind for instance) to reduce the complexity of big datasets.
  12097. */
  12098. increaseClusterLevel : function() {
  12099. this.updateClusters(-1,false,true);
  12100. },
  12101. /**
  12102. * This function can be called to decrease the cluster level. This means that the nodes with only one edge connection will
  12103. * be unpacked if they are a cluster. This can be repeated as many times as needed.
  12104. * This can be called externally (by a key-bind for instance) to look into clusters without zooming.
  12105. */
  12106. decreaseClusterLevel : function() {
  12107. this.updateClusters(1,false,true);
  12108. },
  12109. /**
  12110. * This is the main clustering function. It clusters and declusters on zoom or forced
  12111. * This function clusters on zoom, it can be called with a predefined zoom direction
  12112. * If out, check if we can form clusters, if in, check if we can open clusters.
  12113. * This function is only called from _zoom()
  12114. *
  12115. * @param {Number} zoomDirection | -1 / 0 / +1 for zoomOut / determineByZoom / zoomIn
  12116. * @param {Boolean} recursive | enabled or disable recursive calling of the opening of clusters
  12117. * @param {Boolean} force | enabled or disable forcing
  12118. *
  12119. */
  12120. updateClusters : function(zoomDirection,recursive,force,doNotStart) {
  12121. var isMovingBeforeClustering = this.moving;
  12122. var amountOfNodes = this.nodeIndices.length;
  12123. // on zoom out collapse the sector if the scale is at the level the sector was made
  12124. if (this.previousScale > this.scale && zoomDirection == 0) {
  12125. this._collapseSector();
  12126. }
  12127. // check if we zoom in or out
  12128. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  12129. // forming clusters when forced pulls outliers in. When not forced, the edge length of the
  12130. // outer nodes determines if it is being clustered
  12131. this._formClusters(force);
  12132. }
  12133. else if (this.previousScale < this.scale || zoomDirection == 1) { // zoom in
  12134. if (force == true) {
  12135. // _openClusters checks for each node if the formationScale of the cluster is smaller than
  12136. // the current scale and if so, declusters. When forced, all clusters are reduced by one step
  12137. this._openClusters(recursive,force);
  12138. }
  12139. else {
  12140. // if a cluster takes up a set percentage of the active window
  12141. this._openClustersBySize();
  12142. }
  12143. }
  12144. this._updateNodeIndexList();
  12145. // if a cluster was NOT formed and the user zoomed out, we try clustering by hubs
  12146. if (this.nodeIndices.length == amountOfNodes && (this.previousScale > this.scale || zoomDirection == -1)) {
  12147. this._aggregateHubs(force);
  12148. this._updateNodeIndexList();
  12149. }
  12150. // we now reduce chains.
  12151. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  12152. this.handleChains();
  12153. this._updateNodeIndexList();
  12154. }
  12155. this.previousScale = this.scale;
  12156. // rest of the update the index list, dynamic edges and labels
  12157. this._updateDynamicEdges();
  12158. this.updateLabels();
  12159. // if a cluster was formed, we increase the clusterSession
  12160. if (this.nodeIndices.length < amountOfNodes) { // this means a clustering operation has taken place
  12161. this.clusterSession += 1;
  12162. // if clusters have been made, we normalize the cluster level
  12163. this.normalizeClusterLevels();
  12164. }
  12165. if (doNotStart == false || doNotStart === undefined) {
  12166. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  12167. if (this.moving != isMovingBeforeClustering) {
  12168. this.start();
  12169. }
  12170. }
  12171. this._updateCalculationNodes();
  12172. },
  12173. /**
  12174. * This function handles the chains. It is called on every updateClusters().
  12175. */
  12176. handleChains : function() {
  12177. // after clustering we check how many chains there are
  12178. var chainPercentage = this._getChainFraction();
  12179. if (chainPercentage > this.constants.clustering.chainThreshold) {
  12180. this._reduceAmountOfChains(1 - this.constants.clustering.chainThreshold / chainPercentage)
  12181. }
  12182. },
  12183. /**
  12184. * this functions starts clustering by hubs
  12185. * The minimum hub threshold is set globally
  12186. *
  12187. * @private
  12188. */
  12189. _aggregateHubs : function(force) {
  12190. this._getHubSize();
  12191. this._formClustersByHub(force,false);
  12192. },
  12193. /**
  12194. * This function is fired by keypress. It forces hubs to form.
  12195. *
  12196. */
  12197. forceAggregateHubs : function(doNotStart) {
  12198. var isMovingBeforeClustering = this.moving;
  12199. var amountOfNodes = this.nodeIndices.length;
  12200. this._aggregateHubs(true);
  12201. // update the index list, dynamic edges and labels
  12202. this._updateNodeIndexList();
  12203. this._updateDynamicEdges();
  12204. this.updateLabels();
  12205. // if a cluster was formed, we increase the clusterSession
  12206. if (this.nodeIndices.length != amountOfNodes) {
  12207. this.clusterSession += 1;
  12208. }
  12209. if (doNotStart == false || doNotStart === undefined) {
  12210. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  12211. if (this.moving != isMovingBeforeClustering) {
  12212. this.start();
  12213. }
  12214. }
  12215. },
  12216. /**
  12217. * If a cluster takes up more than a set percentage of the screen, open the cluster
  12218. *
  12219. * @private
  12220. */
  12221. _openClustersBySize : function() {
  12222. for (var nodeId in this.nodes) {
  12223. if (this.nodes.hasOwnProperty(nodeId)) {
  12224. var node = this.nodes[nodeId];
  12225. if (node.inView() == true) {
  12226. if ((node.width*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  12227. (node.height*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  12228. this.openCluster(node);
  12229. }
  12230. }
  12231. }
  12232. }
  12233. },
  12234. /**
  12235. * This function loops over all nodes in the nodeIndices list. For each node it checks if it is a cluster and if it
  12236. * has to be opened based on the current zoom level.
  12237. *
  12238. * @private
  12239. */
  12240. _openClusters : function(recursive,force) {
  12241. for (var i = 0; i < this.nodeIndices.length; i++) {
  12242. var node = this.nodes[this.nodeIndices[i]];
  12243. this._expandClusterNode(node,recursive,force);
  12244. this._updateCalculationNodes();
  12245. }
  12246. },
  12247. /**
  12248. * This function checks if a node has to be opened. This is done by checking the zoom level.
  12249. * If the node contains child nodes, this function is recursively called on the child nodes as well.
  12250. * This recursive behaviour is optional and can be set by the recursive argument.
  12251. *
  12252. * @param {Node} parentNode | to check for cluster and expand
  12253. * @param {Boolean} recursive | enabled or disable recursive calling
  12254. * @param {Boolean} force | enabled or disable forcing
  12255. * @param {Boolean} [openAll] | This will recursively force all nodes in the parent to be released
  12256. * @private
  12257. */
  12258. _expandClusterNode : function(parentNode, recursive, force, openAll) {
  12259. // first check if node is a cluster
  12260. if (parentNode.clusterSize > 1) {
  12261. // this means that on a double tap event or a zoom event, the cluster fully unpacks if it is smaller than 20
  12262. if (parentNode.clusterSize < this.constants.clustering.sectorThreshold) {
  12263. openAll = true;
  12264. }
  12265. recursive = openAll ? true : recursive;
  12266. // if the last child has been added on a smaller scale than current scale decluster
  12267. if (parentNode.formationScale < this.scale || force == true) {
  12268. // we will check if any of the contained child nodes should be removed from the cluster
  12269. for (var containedNodeId in parentNode.containedNodes) {
  12270. if (parentNode.containedNodes.hasOwnProperty(containedNodeId)) {
  12271. var childNode = parentNode.containedNodes[containedNodeId];
  12272. // force expand will expand the largest cluster size clusters. Since we cluster from outside in, we assume that
  12273. // the largest cluster is the one that comes from outside
  12274. if (force == true) {
  12275. if (childNode.clusterSession == parentNode.clusterSessions[parentNode.clusterSessions.length-1]
  12276. || openAll) {
  12277. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  12278. }
  12279. }
  12280. else {
  12281. if (this._nodeInActiveArea(parentNode)) {
  12282. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  12283. }
  12284. }
  12285. }
  12286. }
  12287. }
  12288. }
  12289. },
  12290. /**
  12291. * ONLY CALLED FROM _expandClusterNode
  12292. *
  12293. * This function will expel a child_node from a parent_node. This is to de-cluster the node. This function will remove
  12294. * the child node from the parent contained_node object and put it back into the global nodes object.
  12295. * The same holds for the edge that was connected to the child node. It is moved back into the global edges object.
  12296. *
  12297. * @param {Node} parentNode | the parent node
  12298. * @param {String} containedNodeId | child_node id as it is contained in the containedNodes object of the parent node
  12299. * @param {Boolean} recursive | This will also check if the child needs to be expanded.
  12300. * With force and recursive both true, the entire cluster is unpacked
  12301. * @param {Boolean} force | This will disregard the zoom level and will expel this child from the parent
  12302. * @param {Boolean} openAll | This will recursively force all nodes in the parent to be released
  12303. * @private
  12304. */
  12305. _expelChildFromParent : function(parentNode, containedNodeId, recursive, force, openAll) {
  12306. var childNode = parentNode.containedNodes[containedNodeId];
  12307. // if child node has been added on smaller scale than current, kick out
  12308. if (childNode.formationScale < this.scale || force == true) {
  12309. // unselect all selected items
  12310. this._unselectAll();
  12311. // put the child node back in the global nodes object
  12312. this.nodes[containedNodeId] = childNode;
  12313. // release the contained edges from this childNode back into the global edges
  12314. this._releaseContainedEdges(parentNode,childNode);
  12315. // reconnect rerouted edges to the childNode
  12316. this._connectEdgeBackToChild(parentNode,childNode);
  12317. // validate all edges in dynamicEdges
  12318. this._validateEdges(parentNode);
  12319. // undo the changes from the clustering operation on the parent node
  12320. parentNode.mass -= childNode.mass;
  12321. parentNode.clusterSize -= childNode.clusterSize;
  12322. parentNode.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize);
  12323. parentNode.dynamicEdgesLength = parentNode.dynamicEdges.length;
  12324. // place the child node near the parent, not at the exact same location to avoid chaos in the system
  12325. childNode.x = parentNode.x + parentNode.growthIndicator * (0.5 - Math.random());
  12326. childNode.y = parentNode.y + parentNode.growthIndicator * (0.5 - Math.random());
  12327. // remove node from the list
  12328. delete parentNode.containedNodes[containedNodeId];
  12329. // check if there are other childs with this clusterSession in the parent.
  12330. var othersPresent = false;
  12331. for (var childNodeId in parentNode.containedNodes) {
  12332. if (parentNode.containedNodes.hasOwnProperty(childNodeId)) {
  12333. if (parentNode.containedNodes[childNodeId].clusterSession == childNode.clusterSession) {
  12334. othersPresent = true;
  12335. break;
  12336. }
  12337. }
  12338. }
  12339. // if there are no others, remove the cluster session from the list
  12340. if (othersPresent == false) {
  12341. parentNode.clusterSessions.pop();
  12342. }
  12343. this._repositionBezierNodes(childNode);
  12344. // this._repositionBezierNodes(parentNode);
  12345. // remove the clusterSession from the child node
  12346. childNode.clusterSession = 0;
  12347. // recalculate the size of the node on the next time the node is rendered
  12348. parentNode.clearSizeCache();
  12349. // restart the simulation to reorganise all nodes
  12350. this.moving = true;
  12351. }
  12352. // check if a further expansion step is possible if recursivity is enabled
  12353. if (recursive == true) {
  12354. this._expandClusterNode(childNode,recursive,force,openAll);
  12355. }
  12356. },
  12357. /**
  12358. * position the bezier nodes at the center of the edges
  12359. *
  12360. * @param node
  12361. * @private
  12362. */
  12363. _repositionBezierNodes : function(node) {
  12364. for (var i = 0; i < node.dynamicEdges.length; i++) {
  12365. node.dynamicEdges[i].positionBezierNode();
  12366. }
  12367. },
  12368. /**
  12369. * This function checks if any nodes at the end of their trees have edges below a threshold length
  12370. * This function is called only from updateClusters()
  12371. * forceLevelCollapse ignores the length of the edge and collapses one level
  12372. * This means that a node with only one edge will be clustered with its connected node
  12373. *
  12374. * @private
  12375. * @param {Boolean} force
  12376. */
  12377. _formClusters : function(force) {
  12378. if (force == false) {
  12379. this._formClustersByZoom();
  12380. }
  12381. else {
  12382. this._forceClustersByZoom();
  12383. }
  12384. },
  12385. /**
  12386. * This function handles the clustering by zooming out, this is based on a minimum edge distance
  12387. *
  12388. * @private
  12389. */
  12390. _formClustersByZoom : function() {
  12391. var dx,dy,length,
  12392. minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  12393. // check if any edges are shorter than minLength and start the clustering
  12394. // the clustering favours the node with the larger mass
  12395. for (var edgeId in this.edges) {
  12396. if (this.edges.hasOwnProperty(edgeId)) {
  12397. var edge = this.edges[edgeId];
  12398. if (edge.connected) {
  12399. if (edge.toId != edge.fromId) {
  12400. dx = (edge.to.x - edge.from.x);
  12401. dy = (edge.to.y - edge.from.y);
  12402. length = Math.sqrt(dx * dx + dy * dy);
  12403. if (length < minLength) {
  12404. // first check which node is larger
  12405. var parentNode = edge.from;
  12406. var childNode = edge.to;
  12407. if (edge.to.mass > edge.from.mass) {
  12408. parentNode = edge.to;
  12409. childNode = edge.from;
  12410. }
  12411. if (childNode.dynamicEdgesLength == 1) {
  12412. this._addToCluster(parentNode,childNode,false);
  12413. }
  12414. else if (parentNode.dynamicEdgesLength == 1) {
  12415. this._addToCluster(childNode,parentNode,false);
  12416. }
  12417. }
  12418. }
  12419. }
  12420. }
  12421. }
  12422. },
  12423. /**
  12424. * This function forces the graph to cluster all nodes with only one connecting edge to their
  12425. * connected node.
  12426. *
  12427. * @private
  12428. */
  12429. _forceClustersByZoom : function() {
  12430. for (var nodeId in this.nodes) {
  12431. // another node could have absorbed this child.
  12432. if (this.nodes.hasOwnProperty(nodeId)) {
  12433. var childNode = this.nodes[nodeId];
  12434. // the edges can be swallowed by another decrease
  12435. if (childNode.dynamicEdgesLength == 1 && childNode.dynamicEdges.length != 0) {
  12436. var edge = childNode.dynamicEdges[0];
  12437. var parentNode = (edge.toId == childNode.id) ? this.nodes[edge.fromId] : this.nodes[edge.toId];
  12438. // group to the largest node
  12439. if (childNode.id != parentNode.id) {
  12440. if (parentNode.mass > childNode.mass) {
  12441. this._addToCluster(parentNode,childNode,true);
  12442. }
  12443. else {
  12444. this._addToCluster(childNode,parentNode,true);
  12445. }
  12446. }
  12447. }
  12448. }
  12449. }
  12450. },
  12451. /**
  12452. * To keep the nodes of roughly equal size we normalize the cluster levels.
  12453. * This function clusters a node to its smallest connected neighbour.
  12454. *
  12455. * @param node
  12456. * @private
  12457. */
  12458. _clusterToSmallestNeighbour : function(node) {
  12459. var smallestNeighbour = -1;
  12460. var smallestNeighbourNode = null;
  12461. for (var i = 0; i < node.dynamicEdges.length; i++) {
  12462. if (node.dynamicEdges[i] !== undefined) {
  12463. var neighbour = null;
  12464. if (node.dynamicEdges[i].fromId != node.id) {
  12465. neighbour = node.dynamicEdges[i].from;
  12466. }
  12467. else if (node.dynamicEdges[i].toId != node.id) {
  12468. neighbour = node.dynamicEdges[i].to;
  12469. }
  12470. if (neighbour != null && smallestNeighbour > neighbour.clusterSessions.length) {
  12471. smallestNeighbour = neighbour.clusterSessions.length;
  12472. smallestNeighbourNode = neighbour;
  12473. }
  12474. }
  12475. }
  12476. if (neighbour != null && this.nodes[neighbour.id] !== undefined) {
  12477. this._addToCluster(neighbour, node, true);
  12478. }
  12479. },
  12480. /**
  12481. * This function forms clusters from hubs, it loops over all nodes
  12482. *
  12483. * @param {Boolean} force | Disregard zoom level
  12484. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  12485. * @private
  12486. */
  12487. _formClustersByHub : function(force, onlyEqual) {
  12488. // we loop over all nodes in the list
  12489. for (var nodeId in this.nodes) {
  12490. // we check if it is still available since it can be used by the clustering in this loop
  12491. if (this.nodes.hasOwnProperty(nodeId)) {
  12492. this._formClusterFromHub(this.nodes[nodeId],force,onlyEqual);
  12493. }
  12494. }
  12495. },
  12496. /**
  12497. * This function forms a cluster from a specific preselected hub node
  12498. *
  12499. * @param {Node} hubNode | the node we will cluster as a hub
  12500. * @param {Boolean} force | Disregard zoom level
  12501. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  12502. * @param {Number} [absorptionSizeOffset] |
  12503. * @private
  12504. */
  12505. _formClusterFromHub : function(hubNode, force, onlyEqual, absorptionSizeOffset) {
  12506. if (absorptionSizeOffset === undefined) {
  12507. absorptionSizeOffset = 0;
  12508. }
  12509. // we decide if the node is a hub
  12510. if ((hubNode.dynamicEdgesLength >= this.hubThreshold && onlyEqual == false) ||
  12511. (hubNode.dynamicEdgesLength == this.hubThreshold && onlyEqual == true)) {
  12512. // initialize variables
  12513. var dx,dy,length;
  12514. var minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  12515. var allowCluster = false;
  12516. // we create a list of edges because the dynamicEdges change over the course of this loop
  12517. var edgesIdarray = [];
  12518. var amountOfInitialEdges = hubNode.dynamicEdges.length;
  12519. for (var j = 0; j < amountOfInitialEdges; j++) {
  12520. edgesIdarray.push(hubNode.dynamicEdges[j].id);
  12521. }
  12522. // if the hub clustering is not forces, we check if one of the edges connected
  12523. // to a cluster is small enough based on the constants.clustering.clusterEdgeThreshold
  12524. if (force == false) {
  12525. allowCluster = false;
  12526. for (j = 0; j < amountOfInitialEdges; j++) {
  12527. var edge = this.edges[edgesIdarray[j]];
  12528. if (edge !== undefined) {
  12529. if (edge.connected) {
  12530. if (edge.toId != edge.fromId) {
  12531. dx = (edge.to.x - edge.from.x);
  12532. dy = (edge.to.y - edge.from.y);
  12533. length = Math.sqrt(dx * dx + dy * dy);
  12534. if (length < minLength) {
  12535. allowCluster = true;
  12536. break;
  12537. }
  12538. }
  12539. }
  12540. }
  12541. }
  12542. }
  12543. // start the clustering if allowed
  12544. if ((!force && allowCluster) || force) {
  12545. // we loop over all edges INITIALLY connected to this hub
  12546. for (j = 0; j < amountOfInitialEdges; j++) {
  12547. edge = this.edges[edgesIdarray[j]];
  12548. // the edge can be clustered by this function in a previous loop
  12549. if (edge !== undefined) {
  12550. var childNode = this.nodes[(edge.fromId == hubNode.id) ? edge.toId : edge.fromId];
  12551. // we do not want hubs to merge with other hubs nor do we want to cluster itself.
  12552. if ((childNode.dynamicEdges.length <= (this.hubThreshold + absorptionSizeOffset)) &&
  12553. (childNode.id != hubNode.id)) {
  12554. this._addToCluster(hubNode,childNode,force);
  12555. }
  12556. }
  12557. }
  12558. }
  12559. }
  12560. },
  12561. /**
  12562. * This function adds the child node to the parent node, creating a cluster if it is not already.
  12563. *
  12564. * @param {Node} parentNode | this is the node that will house the child node
  12565. * @param {Node} childNode | this node will be deleted from the global this.nodes and stored in the parent node
  12566. * @param {Boolean} force | true will only update the remainingEdges at the very end of the clustering, ensuring single level collapse
  12567. * @private
  12568. */
  12569. _addToCluster : function(parentNode, childNode, force) {
  12570. // join child node in the parent node
  12571. parentNode.containedNodes[childNode.id] = childNode;
  12572. // manage all the edges connected to the child and parent nodes
  12573. for (var i = 0; i < childNode.dynamicEdges.length; i++) {
  12574. var edge = childNode.dynamicEdges[i];
  12575. if (edge.toId == parentNode.id || edge.fromId == parentNode.id) { // edge connected to parentNode
  12576. this._addToContainedEdges(parentNode,childNode,edge);
  12577. }
  12578. else {
  12579. this._connectEdgeToCluster(parentNode,childNode,edge);
  12580. }
  12581. }
  12582. // a contained node has no dynamic edges.
  12583. childNode.dynamicEdges = [];
  12584. // remove circular edges from clusters
  12585. this._containCircularEdgesFromNode(parentNode,childNode);
  12586. // remove the childNode from the global nodes object
  12587. delete this.nodes[childNode.id];
  12588. // update the properties of the child and parent
  12589. var massBefore = parentNode.mass;
  12590. childNode.clusterSession = this.clusterSession;
  12591. parentNode.mass += childNode.mass;
  12592. parentNode.clusterSize += childNode.clusterSize;
  12593. parentNode.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize);
  12594. // keep track of the clustersessions so we can open the cluster up as it has been formed.
  12595. if (parentNode.clusterSessions[parentNode.clusterSessions.length - 1] != this.clusterSession) {
  12596. parentNode.clusterSessions.push(this.clusterSession);
  12597. }
  12598. // forced clusters only open from screen size and double tap
  12599. if (force == true) {
  12600. // parentNode.formationScale = Math.pow(1 - (1.0/11.0),this.clusterSession+3);
  12601. parentNode.formationScale = 0;
  12602. }
  12603. else {
  12604. parentNode.formationScale = this.scale; // The latest child has been added on this scale
  12605. }
  12606. // recalculate the size of the node on the next time the node is rendered
  12607. parentNode.clearSizeCache();
  12608. // set the pop-out scale for the childnode
  12609. parentNode.containedNodes[childNode.id].formationScale = parentNode.formationScale;
  12610. // nullify the movement velocity of the child, this is to avoid hectic behaviour
  12611. childNode.clearVelocity();
  12612. // the mass has altered, preservation of energy dictates the velocity to be updated
  12613. parentNode.updateVelocity(massBefore);
  12614. // restart the simulation to reorganise all nodes
  12615. this.moving = true;
  12616. },
  12617. /**
  12618. * This function will apply the changes made to the remainingEdges during the formation of the clusters.
  12619. * This is a seperate function to allow for level-wise collapsing of the node barnesHutTree.
  12620. * It has to be called if a level is collapsed. It is called by _formClusters().
  12621. * @private
  12622. */
  12623. _updateDynamicEdges : function() {
  12624. for (var i = 0; i < this.nodeIndices.length; i++) {
  12625. var node = this.nodes[this.nodeIndices[i]];
  12626. node.dynamicEdgesLength = node.dynamicEdges.length;
  12627. // this corrects for multiple edges pointing at the same other node
  12628. var correction = 0;
  12629. if (node.dynamicEdgesLength > 1) {
  12630. for (var j = 0; j < node.dynamicEdgesLength - 1; j++) {
  12631. var edgeToId = node.dynamicEdges[j].toId;
  12632. var edgeFromId = node.dynamicEdges[j].fromId;
  12633. for (var k = j+1; k < node.dynamicEdgesLength; k++) {
  12634. if ((node.dynamicEdges[k].toId == edgeToId && node.dynamicEdges[k].fromId == edgeFromId) ||
  12635. (node.dynamicEdges[k].fromId == edgeToId && node.dynamicEdges[k].toId == edgeFromId)) {
  12636. correction += 1;
  12637. }
  12638. }
  12639. }
  12640. }
  12641. node.dynamicEdgesLength -= correction;
  12642. }
  12643. },
  12644. /**
  12645. * This adds an edge from the childNode to the contained edges of the parent node
  12646. *
  12647. * @param parentNode | Node object
  12648. * @param childNode | Node object
  12649. * @param edge | Edge object
  12650. * @private
  12651. */
  12652. _addToContainedEdges : function(parentNode, childNode, edge) {
  12653. // create an array object if it does not yet exist for this childNode
  12654. if (!(parentNode.containedEdges.hasOwnProperty(childNode.id))) {
  12655. parentNode.containedEdges[childNode.id] = []
  12656. }
  12657. // add this edge to the list
  12658. parentNode.containedEdges[childNode.id].push(edge);
  12659. // remove the edge from the global edges object
  12660. delete this.edges[edge.id];
  12661. // remove the edge from the parent object
  12662. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12663. if (parentNode.dynamicEdges[i].id == edge.id) {
  12664. parentNode.dynamicEdges.splice(i,1);
  12665. break;
  12666. }
  12667. }
  12668. },
  12669. /**
  12670. * This function connects an edge that was connected to a child node to the parent node.
  12671. * It keeps track of which nodes it has been connected to with the originalId array.
  12672. *
  12673. * @param {Node} parentNode | Node object
  12674. * @param {Node} childNode | Node object
  12675. * @param {Edge} edge | Edge object
  12676. * @private
  12677. */
  12678. _connectEdgeToCluster : function(parentNode, childNode, edge) {
  12679. // handle circular edges
  12680. if (edge.toId == edge.fromId) {
  12681. this._addToContainedEdges(parentNode, childNode, edge);
  12682. }
  12683. else {
  12684. if (edge.toId == childNode.id) { // edge connected to other node on the "to" side
  12685. edge.originalToId.push(childNode.id);
  12686. edge.to = parentNode;
  12687. edge.toId = parentNode.id;
  12688. }
  12689. else { // edge connected to other node with the "from" side
  12690. edge.originalFromId.push(childNode.id);
  12691. edge.from = parentNode;
  12692. edge.fromId = parentNode.id;
  12693. }
  12694. this._addToReroutedEdges(parentNode,childNode,edge);
  12695. }
  12696. },
  12697. /**
  12698. * If a node is connected to itself, a circular edge is drawn. When clustering we want to contain
  12699. * these edges inside of the cluster.
  12700. *
  12701. * @param parentNode
  12702. * @param childNode
  12703. * @private
  12704. */
  12705. _containCircularEdgesFromNode : function(parentNode, childNode) {
  12706. // manage all the edges connected to the child and parent nodes
  12707. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12708. var edge = parentNode.dynamicEdges[i];
  12709. // handle circular edges
  12710. if (edge.toId == edge.fromId) {
  12711. this._addToContainedEdges(parentNode, childNode, edge);
  12712. }
  12713. }
  12714. },
  12715. /**
  12716. * This adds an edge from the childNode to the rerouted edges of the parent node
  12717. *
  12718. * @param parentNode | Node object
  12719. * @param childNode | Node object
  12720. * @param edge | Edge object
  12721. * @private
  12722. */
  12723. _addToReroutedEdges : function(parentNode, childNode, edge) {
  12724. // create an array object if it does not yet exist for this childNode
  12725. // we store the edge in the rerouted edges so we can restore it when the cluster pops open
  12726. if (!(parentNode.reroutedEdges.hasOwnProperty(childNode.id))) {
  12727. parentNode.reroutedEdges[childNode.id] = [];
  12728. }
  12729. parentNode.reroutedEdges[childNode.id].push(edge);
  12730. // this edge becomes part of the dynamicEdges of the cluster node
  12731. parentNode.dynamicEdges.push(edge);
  12732. },
  12733. /**
  12734. * This function connects an edge that was connected to a cluster node back to the child node.
  12735. *
  12736. * @param parentNode | Node object
  12737. * @param childNode | Node object
  12738. * @private
  12739. */
  12740. _connectEdgeBackToChild : function(parentNode, childNode) {
  12741. if (parentNode.reroutedEdges.hasOwnProperty(childNode.id)) {
  12742. for (var i = 0; i < parentNode.reroutedEdges[childNode.id].length; i++) {
  12743. var edge = parentNode.reroutedEdges[childNode.id][i];
  12744. if (edge.originalFromId[edge.originalFromId.length-1] == childNode.id) {
  12745. edge.originalFromId.pop();
  12746. edge.fromId = childNode.id;
  12747. edge.from = childNode;
  12748. }
  12749. else {
  12750. edge.originalToId.pop();
  12751. edge.toId = childNode.id;
  12752. edge.to = childNode;
  12753. }
  12754. // append this edge to the list of edges connecting to the childnode
  12755. childNode.dynamicEdges.push(edge);
  12756. // remove the edge from the parent object
  12757. for (var j = 0; j < parentNode.dynamicEdges.length; j++) {
  12758. if (parentNode.dynamicEdges[j].id == edge.id) {
  12759. parentNode.dynamicEdges.splice(j,1);
  12760. break;
  12761. }
  12762. }
  12763. }
  12764. // remove the entry from the rerouted edges
  12765. delete parentNode.reroutedEdges[childNode.id];
  12766. }
  12767. },
  12768. /**
  12769. * When loops are clustered, an edge can be both in the rerouted array and the contained array.
  12770. * This function is called last to verify that all edges in dynamicEdges are in fact connected to the
  12771. * parentNode
  12772. *
  12773. * @param parentNode | Node object
  12774. * @private
  12775. */
  12776. _validateEdges : function(parentNode) {
  12777. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12778. var edge = parentNode.dynamicEdges[i];
  12779. if (parentNode.id != edge.toId && parentNode.id != edge.fromId) {
  12780. parentNode.dynamicEdges.splice(i,1);
  12781. }
  12782. }
  12783. },
  12784. /**
  12785. * This function released the contained edges back into the global domain and puts them back into the
  12786. * dynamic edges of both parent and child.
  12787. *
  12788. * @param {Node} parentNode |
  12789. * @param {Node} childNode |
  12790. * @private
  12791. */
  12792. _releaseContainedEdges : function(parentNode, childNode) {
  12793. for (var i = 0; i < parentNode.containedEdges[childNode.id].length; i++) {
  12794. var edge = parentNode.containedEdges[childNode.id][i];
  12795. // put the edge back in the global edges object
  12796. this.edges[edge.id] = edge;
  12797. // put the edge back in the dynamic edges of the child and parent
  12798. childNode.dynamicEdges.push(edge);
  12799. parentNode.dynamicEdges.push(edge);
  12800. }
  12801. // remove the entry from the contained edges
  12802. delete parentNode.containedEdges[childNode.id];
  12803. },
  12804. // ------------------- UTILITY FUNCTIONS ---------------------------- //
  12805. /**
  12806. * This updates the node labels for all nodes (for debugging purposes)
  12807. */
  12808. updateLabels : function() {
  12809. var nodeId;
  12810. // update node labels
  12811. for (nodeId in this.nodes) {
  12812. if (this.nodes.hasOwnProperty(nodeId)) {
  12813. var node = this.nodes[nodeId];
  12814. if (node.clusterSize > 1) {
  12815. node.label = "[".concat(String(node.clusterSize),"]");
  12816. }
  12817. }
  12818. }
  12819. // update node labels
  12820. for (nodeId in this.nodes) {
  12821. if (this.nodes.hasOwnProperty(nodeId)) {
  12822. node = this.nodes[nodeId];
  12823. if (node.clusterSize == 1) {
  12824. if (node.originalLabel !== undefined) {
  12825. node.label = node.originalLabel;
  12826. }
  12827. else {
  12828. node.label = String(node.id);
  12829. }
  12830. }
  12831. }
  12832. }
  12833. // /* Debug Override */
  12834. // for (nodeId in this.nodes) {
  12835. // if (this.nodes.hasOwnProperty(nodeId)) {
  12836. // node = this.nodes[nodeId];
  12837. // node.label = String(node.level);
  12838. // }
  12839. // }
  12840. },
  12841. /**
  12842. * We want to keep the cluster level distribution rather small. This means we do not want unclustered nodes
  12843. * if the rest of the nodes are already a few cluster levels in.
  12844. * To fix this we use this function. It determines the min and max cluster level and sends nodes that have not
  12845. * clustered enough to the clusterToSmallestNeighbours function.
  12846. */
  12847. normalizeClusterLevels : function() {
  12848. var maxLevel = 0;
  12849. var minLevel = 1e9;
  12850. var clusterLevel = 0;
  12851. // we loop over all nodes in the list
  12852. for (var nodeId in this.nodes) {
  12853. if (this.nodes.hasOwnProperty(nodeId)) {
  12854. clusterLevel = this.nodes[nodeId].clusterSessions.length;
  12855. if (maxLevel < clusterLevel) {maxLevel = clusterLevel;}
  12856. if (minLevel > clusterLevel) {minLevel = clusterLevel;}
  12857. }
  12858. }
  12859. if (maxLevel - minLevel > this.constants.clustering.clusterLevelDifference) {
  12860. var amountOfNodes = this.nodeIndices.length;
  12861. var targetLevel = maxLevel - this.constants.clustering.clusterLevelDifference;
  12862. // we loop over all nodes in the list
  12863. for (var nodeId in this.nodes) {
  12864. if (this.nodes.hasOwnProperty(nodeId)) {
  12865. if (this.nodes[nodeId].clusterSessions.length < targetLevel) {
  12866. this._clusterToSmallestNeighbour(this.nodes[nodeId]);
  12867. }
  12868. }
  12869. }
  12870. this._updateNodeIndexList();
  12871. this._updateDynamicEdges();
  12872. // if a cluster was formed, we increase the clusterSession
  12873. if (this.nodeIndices.length != amountOfNodes) {
  12874. this.clusterSession += 1;
  12875. }
  12876. }
  12877. },
  12878. /**
  12879. * This function determines if the cluster we want to decluster is in the active area
  12880. * this means around the zoom center
  12881. *
  12882. * @param {Node} node
  12883. * @returns {boolean}
  12884. * @private
  12885. */
  12886. _nodeInActiveArea : function(node) {
  12887. return (
  12888. Math.abs(node.x - this.areaCenter.x) <= this.constants.clustering.activeAreaBoxSize/this.scale
  12889. &&
  12890. Math.abs(node.y - this.areaCenter.y) <= this.constants.clustering.activeAreaBoxSize/this.scale
  12891. )
  12892. },
  12893. /**
  12894. * This is an adaptation of the original repositioning function. This is called if the system is clustered initially
  12895. * It puts large clusters away from the center and randomizes the order.
  12896. *
  12897. */
  12898. repositionNodes : function() {
  12899. for (var i = 0; i < this.nodeIndices.length; i++) {
  12900. var node = this.nodes[this.nodeIndices[i]];
  12901. if ((node.xFixed == false || node.yFixed == false)) {
  12902. var radius = this.constants.physics.springLength * Math.min(100,node.mass);
  12903. var angle = 2 * Math.PI * Math.random();
  12904. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  12905. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  12906. this._repositionBezierNodes(node);
  12907. }
  12908. }
  12909. },
  12910. /**
  12911. * We determine how many connections denote an important hub.
  12912. * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%)
  12913. *
  12914. * @private
  12915. */
  12916. _getHubSize : function() {
  12917. var average = 0;
  12918. var averageSquared = 0;
  12919. var hubCounter = 0;
  12920. var largestHub = 0;
  12921. for (var i = 0; i < this.nodeIndices.length; i++) {
  12922. var node = this.nodes[this.nodeIndices[i]];
  12923. if (node.dynamicEdgesLength > largestHub) {
  12924. largestHub = node.dynamicEdgesLength;
  12925. }
  12926. average += node.dynamicEdgesLength;
  12927. averageSquared += Math.pow(node.dynamicEdgesLength,2);
  12928. hubCounter += 1;
  12929. }
  12930. average = average / hubCounter;
  12931. averageSquared = averageSquared / hubCounter;
  12932. var variance = averageSquared - Math.pow(average,2);
  12933. var standardDeviation = Math.sqrt(variance);
  12934. this.hubThreshold = Math.floor(average + 2*standardDeviation);
  12935. // always have at least one to cluster
  12936. if (this.hubThreshold > largestHub) {
  12937. this.hubThreshold = largestHub;
  12938. }
  12939. // console.log("average",average,"averageSQ",averageSquared,"var",variance,"std",standardDeviation);
  12940. // console.log("hubThreshold:",this.hubThreshold);
  12941. },
  12942. /**
  12943. * We reduce the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  12944. * with this amount we can cluster specifically on these chains.
  12945. *
  12946. * @param {Number} fraction | between 0 and 1, the percentage of chains to reduce
  12947. * @private
  12948. */
  12949. _reduceAmountOfChains : function(fraction) {
  12950. this.hubThreshold = 2;
  12951. var reduceAmount = Math.floor(this.nodeIndices.length * fraction);
  12952. for (var nodeId in this.nodes) {
  12953. if (this.nodes.hasOwnProperty(nodeId)) {
  12954. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  12955. if (reduceAmount > 0) {
  12956. this._formClusterFromHub(this.nodes[nodeId],true,true,1);
  12957. reduceAmount -= 1;
  12958. }
  12959. }
  12960. }
  12961. }
  12962. },
  12963. /**
  12964. * We get the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  12965. * with this amount we can cluster specifically on these chains.
  12966. *
  12967. * @private
  12968. */
  12969. _getChainFraction : function() {
  12970. var chains = 0;
  12971. var total = 0;
  12972. for (var nodeId in this.nodes) {
  12973. if (this.nodes.hasOwnProperty(nodeId)) {
  12974. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  12975. chains += 1;
  12976. }
  12977. total += 1;
  12978. }
  12979. }
  12980. return chains/total;
  12981. }
  12982. };
  12983. var SelectionMixin = {
  12984. /**
  12985. * This function can be called from the _doInAllSectors function
  12986. *
  12987. * @param object
  12988. * @param overlappingNodes
  12989. * @private
  12990. */
  12991. _getNodesOverlappingWith : function(object, overlappingNodes) {
  12992. var nodes = this.nodes;
  12993. for (var nodeId in nodes) {
  12994. if (nodes.hasOwnProperty(nodeId)) {
  12995. if (nodes[nodeId].isOverlappingWith(object)) {
  12996. overlappingNodes.push(nodeId);
  12997. }
  12998. }
  12999. }
  13000. },
  13001. /**
  13002. * retrieve all nodes overlapping with given object
  13003. * @param {Object} object An object with parameters left, top, right, bottom
  13004. * @return {Number[]} An array with id's of the overlapping nodes
  13005. * @private
  13006. */
  13007. _getAllNodesOverlappingWith : function (object) {
  13008. var overlappingNodes = [];
  13009. this._doInAllActiveSectors("_getNodesOverlappingWith",object,overlappingNodes);
  13010. return overlappingNodes;
  13011. },
  13012. /**
  13013. * Return a position object in canvasspace from a single point in screenspace
  13014. *
  13015. * @param pointer
  13016. * @returns {{left: number, top: number, right: number, bottom: number}}
  13017. * @private
  13018. */
  13019. _pointerToPositionObject : function(pointer) {
  13020. var x = this._canvasToX(pointer.x);
  13021. var y = this._canvasToY(pointer.y);
  13022. return {left: x,
  13023. top: y,
  13024. right: x,
  13025. bottom: y};
  13026. },
  13027. /**
  13028. * Get the top node at the a specific point (like a click)
  13029. *
  13030. * @param {{x: Number, y: Number}} pointer
  13031. * @return {Node | null} node
  13032. * @private
  13033. */
  13034. _getNodeAt : function (pointer) {
  13035. // we first check if this is an navigation controls element
  13036. var positionObject = this._pointerToPositionObject(pointer);
  13037. var overlappingNodes = this._getAllNodesOverlappingWith(positionObject);
  13038. // if there are overlapping nodes, select the last one, this is the
  13039. // one which is drawn on top of the others
  13040. if (overlappingNodes.length > 0) {
  13041. return this.nodes[overlappingNodes[overlappingNodes.length - 1]];
  13042. }
  13043. else {
  13044. return null;
  13045. }
  13046. },
  13047. /**
  13048. * retrieve all edges overlapping with given object, selector is around center
  13049. * @param {Object} object An object with parameters left, top, right, bottom
  13050. * @return {Number[]} An array with id's of the overlapping nodes
  13051. * @private
  13052. */
  13053. _getEdgesOverlappingWith : function (object, overlappingEdges) {
  13054. var edges = this.edges;
  13055. for (var edgeId in edges) {
  13056. if (edges.hasOwnProperty(edgeId)) {
  13057. if (edges[edgeId].isOverlappingWith(object)) {
  13058. overlappingEdges.push(edgeId);
  13059. }
  13060. }
  13061. }
  13062. },
  13063. /**
  13064. * retrieve all nodes overlapping with given object
  13065. * @param {Object} object An object with parameters left, top, right, bottom
  13066. * @return {Number[]} An array with id's of the overlapping nodes
  13067. * @private
  13068. */
  13069. _getAllEdgesOverlappingWith : function (object) {
  13070. var overlappingEdges = [];
  13071. this._doInAllActiveSectors("_getEdgesOverlappingWith",object,overlappingEdges);
  13072. return overlappingEdges;
  13073. },
  13074. /**
  13075. * Place holder. To implement change the _getNodeAt to a _getObjectAt. Have the _getObjectAt call
  13076. * _getNodeAt and _getEdgesAt, then priortize the selection to user preferences.
  13077. *
  13078. * @param pointer
  13079. * @returns {null}
  13080. * @private
  13081. */
  13082. _getEdgeAt : function(pointer) {
  13083. var positionObject = this._pointerToPositionObject(pointer);
  13084. var overlappingEdges = this._getAllEdgesOverlappingWith(positionObject);
  13085. if (overlappingEdges.length > 0) {
  13086. return this.edges[overlappingEdges[overlappingEdges.length - 1]];
  13087. }
  13088. else {
  13089. return null;
  13090. }
  13091. },
  13092. /**
  13093. * Add object to the selection array.
  13094. *
  13095. * @param obj
  13096. * @private
  13097. */
  13098. _addToSelection : function(obj) {
  13099. this.selectionObj[obj.id] = obj;
  13100. },
  13101. /**
  13102. * Remove a single option from selection.
  13103. *
  13104. * @param {Object} obj
  13105. * @private
  13106. */
  13107. _removeFromSelection : function(obj) {
  13108. delete this.selectionObj[obj.id];
  13109. },
  13110. /**
  13111. * Unselect all. The selectionObj is useful for this.
  13112. *
  13113. * @param {Boolean} [doNotTrigger] | ignore trigger
  13114. * @private
  13115. */
  13116. _unselectAll : function(doNotTrigger) {
  13117. if (doNotTrigger === undefined) {
  13118. doNotTrigger = false;
  13119. }
  13120. for (var objectId in this.selectionObj) {
  13121. if (this.selectionObj.hasOwnProperty(objectId)) {
  13122. this.selectionObj[objectId].unselect();
  13123. }
  13124. }
  13125. this.selectionObj = {};
  13126. if (doNotTrigger == false) {
  13127. this.emit('select', this.getSelection());
  13128. }
  13129. },
  13130. /**
  13131. * Unselect all clusters. The selectionObj is useful for this.
  13132. *
  13133. * @param {Boolean} [doNotTrigger] | ignore trigger
  13134. * @private
  13135. */
  13136. _unselectClusters : function(doNotTrigger) {
  13137. if (doNotTrigger === undefined) {
  13138. doNotTrigger = false;
  13139. }
  13140. for (var objectId in this.selectionObj) {
  13141. if (this.selectionObj.hasOwnProperty(objectId)) {
  13142. if (this.selectionObj[objectId] instanceof Node) {
  13143. if (this.selectionObj[objectId].clusterSize > 1) {
  13144. this.selectionObj[objectId].unselect();
  13145. this._removeFromSelection(this.selectionObj[objectId]);
  13146. }
  13147. }
  13148. }
  13149. }
  13150. if (doNotTrigger == false) {
  13151. this.emit('select', this.getSelection());
  13152. }
  13153. },
  13154. /**
  13155. * return the number of selected nodes
  13156. *
  13157. * @returns {number}
  13158. * @private
  13159. */
  13160. _getSelectedNodeCount : function() {
  13161. var count = 0;
  13162. for (var objectId in this.selectionObj) {
  13163. if (this.selectionObj.hasOwnProperty(objectId)) {
  13164. if (this.selectionObj[objectId] instanceof Node) {
  13165. count += 1;
  13166. }
  13167. }
  13168. }
  13169. return count;
  13170. },
  13171. /**
  13172. * return the number of selected nodes
  13173. *
  13174. * @returns {number}
  13175. * @private
  13176. */
  13177. _getSelectedNode : function() {
  13178. for (var objectId in this.selectionObj) {
  13179. if (this.selectionObj.hasOwnProperty(objectId)) {
  13180. if (this.selectionObj[objectId] instanceof Node) {
  13181. return this.selectionObj[objectId];
  13182. }
  13183. }
  13184. }
  13185. return null;
  13186. },
  13187. /**
  13188. * return the number of selected edges
  13189. *
  13190. * @returns {number}
  13191. * @private
  13192. */
  13193. _getSelectedEdgeCount : function() {
  13194. var count = 0;
  13195. for (var objectId in this.selectionObj) {
  13196. if (this.selectionObj.hasOwnProperty(objectId)) {
  13197. if (this.selectionObj[objectId] instanceof Edge) {
  13198. count += 1;
  13199. }
  13200. }
  13201. }
  13202. return count;
  13203. },
  13204. /**
  13205. * return the number of selected objects.
  13206. *
  13207. * @returns {number}
  13208. * @private
  13209. */
  13210. _getSelectedObjectCount : function() {
  13211. var count = 0;
  13212. for (var objectId in this.selectionObj) {
  13213. if (this.selectionObj.hasOwnProperty(objectId)) {
  13214. count += 1;
  13215. }
  13216. }
  13217. return count;
  13218. },
  13219. /**
  13220. * Check if anything is selected
  13221. *
  13222. * @returns {boolean}
  13223. * @private
  13224. */
  13225. _selectionIsEmpty : function() {
  13226. for(var objectId in this.selectionObj) {
  13227. if(this.selectionObj.hasOwnProperty(objectId)) {
  13228. return false;
  13229. }
  13230. }
  13231. return true;
  13232. },
  13233. /**
  13234. * check if one of the selected nodes is a cluster.
  13235. *
  13236. * @returns {boolean}
  13237. * @private
  13238. */
  13239. _clusterInSelection : function() {
  13240. for(var objectId in this.selectionObj) {
  13241. if(this.selectionObj.hasOwnProperty(objectId)) {
  13242. if (this.selectionObj[objectId] instanceof Node) {
  13243. if (this.selectionObj[objectId].clusterSize > 1) {
  13244. return true;
  13245. }
  13246. }
  13247. }
  13248. }
  13249. return false;
  13250. },
  13251. /**
  13252. * select the edges connected to the node that is being selected
  13253. *
  13254. * @param {Node} node
  13255. * @private
  13256. */
  13257. _selectConnectedEdges : function(node) {
  13258. for (var i = 0; i < node.dynamicEdges.length; i++) {
  13259. var edge = node.dynamicEdges[i];
  13260. edge.select();
  13261. this._addToSelection(edge);
  13262. }
  13263. },
  13264. /**
  13265. * unselect the edges connected to the node that is being selected
  13266. *
  13267. * @param {Node} node
  13268. * @private
  13269. */
  13270. _unselectConnectedEdges : function(node) {
  13271. for (var i = 0; i < node.dynamicEdges.length; i++) {
  13272. var edge = node.dynamicEdges[i];
  13273. edge.unselect();
  13274. this._removeFromSelection(edge);
  13275. }
  13276. },
  13277. /**
  13278. * This is called when someone clicks on a node. either select or deselect it.
  13279. * If there is an existing selection and we don't want to append to it, clear the existing selection
  13280. *
  13281. * @param {Node || Edge} object
  13282. * @param {Boolean} append
  13283. * @param {Boolean} [doNotTrigger] | ignore trigger
  13284. * @private
  13285. */
  13286. _selectObject : function(object, append, doNotTrigger) {
  13287. if (doNotTrigger === undefined) {
  13288. doNotTrigger = false;
  13289. }
  13290. if (this._selectionIsEmpty() == false && append == false && this.forceAppendSelection == false) {
  13291. this._unselectAll(true);
  13292. }
  13293. if (object.selected == false) {
  13294. object.select();
  13295. this._addToSelection(object);
  13296. if (object instanceof Node && this.blockConnectingEdgeSelection == false) {
  13297. this._selectConnectedEdges(object);
  13298. }
  13299. }
  13300. else {
  13301. object.unselect();
  13302. this._removeFromSelection(object);
  13303. }
  13304. if (doNotTrigger == false) {
  13305. this.emit('select', this.getSelection());
  13306. }
  13307. },
  13308. /**
  13309. * handles the selection part of the touch, only for navigation controls elements;
  13310. * Touch is triggered before tap, also before hold. Hold triggers after a while.
  13311. * This is the most responsive solution
  13312. *
  13313. * @param {Object} pointer
  13314. * @private
  13315. */
  13316. _handleTouch : function(pointer) {
  13317. },
  13318. /**
  13319. * handles the selection part of the tap;
  13320. *
  13321. * @param {Object} pointer
  13322. * @private
  13323. */
  13324. _handleTap : function(pointer) {
  13325. var node = this._getNodeAt(pointer);
  13326. if (node != null) {
  13327. this._selectObject(node,false);
  13328. }
  13329. else {
  13330. var edge = this._getEdgeAt(pointer);
  13331. if (edge != null) {
  13332. this._selectObject(edge,false);
  13333. }
  13334. else {
  13335. this._unselectAll();
  13336. }
  13337. }
  13338. this.emit("click", this.getSelection());
  13339. this._redraw();
  13340. },
  13341. /**
  13342. * handles the selection part of the double tap and opens a cluster if needed
  13343. *
  13344. * @param {Object} pointer
  13345. * @private
  13346. */
  13347. _handleDoubleTap : function(pointer) {
  13348. var node = this._getNodeAt(pointer);
  13349. if (node != null && node !== undefined) {
  13350. // we reset the areaCenter here so the opening of the node will occur
  13351. this.areaCenter = {"x" : this._canvasToX(pointer.x),
  13352. "y" : this._canvasToY(pointer.y)};
  13353. this.openCluster(node);
  13354. }
  13355. this.emit("doubleClick", this.getSelection());
  13356. },
  13357. /**
  13358. * Handle the onHold selection part
  13359. *
  13360. * @param pointer
  13361. * @private
  13362. */
  13363. _handleOnHold : function(pointer) {
  13364. var node = this._getNodeAt(pointer);
  13365. if (node != null) {
  13366. this._selectObject(node,true);
  13367. }
  13368. else {
  13369. var edge = this._getEdgeAt(pointer);
  13370. if (edge != null) {
  13371. this._selectObject(edge,true);
  13372. }
  13373. }
  13374. this._redraw();
  13375. },
  13376. /**
  13377. * handle the onRelease event. These functions are here for the navigation controls module.
  13378. *
  13379. * @private
  13380. */
  13381. _handleOnRelease : function(pointer) {
  13382. },
  13383. /**
  13384. *
  13385. * retrieve the currently selected objects
  13386. * @return {Number[] | String[]} selection An array with the ids of the
  13387. * selected nodes.
  13388. */
  13389. getSelection : function() {
  13390. var nodeIds = this.getSelectedNodes();
  13391. var edgeIds = this.getSelectedEdges();
  13392. return {nodes:nodeIds, edges:edgeIds};
  13393. },
  13394. /**
  13395. *
  13396. * retrieve the currently selected nodes
  13397. * @return {String} selection An array with the ids of the
  13398. * selected nodes.
  13399. */
  13400. getSelectedNodes : function() {
  13401. var idArray = [];
  13402. for(var objectId in this.selectionObj) {
  13403. if(this.selectionObj.hasOwnProperty(objectId)) {
  13404. if (this.selectionObj[objectId] instanceof Node) {
  13405. idArray.push(objectId);
  13406. }
  13407. }
  13408. }
  13409. return idArray
  13410. },
  13411. /**
  13412. *
  13413. * retrieve the currently selected edges
  13414. * @return {Array} selection An array with the ids of the
  13415. * selected nodes.
  13416. */
  13417. getSelectedEdges : function() {
  13418. var idArray = [];
  13419. for(var objectId in this.selectionObj) {
  13420. if(this.selectionObj.hasOwnProperty(objectId)) {
  13421. if (this.selectionObj[objectId] instanceof Edge) {
  13422. idArray.push(objectId);
  13423. }
  13424. }
  13425. }
  13426. return idArray
  13427. },
  13428. /**
  13429. * select zero or more nodes
  13430. * @param {Number[] | String[]} selection An array with the ids of the
  13431. * selected nodes.
  13432. */
  13433. setSelection : function(selection) {
  13434. var i, iMax, id;
  13435. if (!selection || (selection.length == undefined))
  13436. throw 'Selection must be an array with ids';
  13437. // first unselect any selected node
  13438. this._unselectAll(true);
  13439. for (i = 0, iMax = selection.length; i < iMax; i++) {
  13440. id = selection[i];
  13441. var node = this.nodes[id];
  13442. if (!node) {
  13443. throw new RangeError('Node with id "' + id + '" not found');
  13444. }
  13445. this._selectObject(node,true,true);
  13446. }
  13447. this.redraw();
  13448. },
  13449. /**
  13450. * Validate the selection: remove ids of nodes which no longer exist
  13451. * @private
  13452. */
  13453. _updateSelection : function () {
  13454. for(var objectId in this.selectionObj) {
  13455. if(this.selectionObj.hasOwnProperty(objectId)) {
  13456. if (this.selectionObj[objectId] instanceof Node) {
  13457. if (!this.nodes.hasOwnProperty(objectId)) {
  13458. delete this.selectionObj[objectId];
  13459. }
  13460. }
  13461. else { // assuming only edges and nodes are selected
  13462. if (!this.edges.hasOwnProperty(objectId)) {
  13463. delete this.selectionObj[objectId];
  13464. }
  13465. }
  13466. }
  13467. }
  13468. }
  13469. };
  13470. /**
  13471. * Created by Alex on 1/22/14.
  13472. */
  13473. var NavigationMixin = {
  13474. _cleanNavigation : function() {
  13475. // clean up previosu navigation items
  13476. var wrapper = document.getElementById('graph-navigation_wrapper');
  13477. if (wrapper != null) {
  13478. this.containerElement.removeChild(wrapper);
  13479. }
  13480. document.onmouseup = null;
  13481. },
  13482. /**
  13483. * Creation of the navigation controls nodes. They are drawn over the rest of the nodes and are not affected by scale and translation
  13484. * they have a triggerFunction which is called on click. If the position of the navigation controls is dependent
  13485. * on this.frame.canvas.clientWidth or this.frame.canvas.clientHeight, we flag horizontalAlignLeft and verticalAlignTop false.
  13486. * This means that the location will be corrected by the _relocateNavigation function on a size change of the canvas.
  13487. *
  13488. * @private
  13489. */
  13490. _loadNavigationElements : function() {
  13491. this._cleanNavigation();
  13492. this.navigationDivs = {};
  13493. var navigationDivs = ['up','down','left','right','zoomIn','zoomOut','zoomExtends'];
  13494. var navigationDivActions = ['_moveUp','_moveDown','_moveLeft','_moveRight','_zoomIn','_zoomOut','zoomExtent'];
  13495. this.navigationDivs['wrapper'] = document.createElement('div');
  13496. this.navigationDivs['wrapper'].id = "graph-navigation_wrapper";
  13497. this.navigationDivs['wrapper'].style.position = "absolute";
  13498. this.navigationDivs['wrapper'].style.width = this.frame.canvas.clientWidth + "px";
  13499. this.navigationDivs['wrapper'].style.height = this.frame.canvas.clientHeight + "px";
  13500. this.containerElement.insertBefore(this.navigationDivs['wrapper'],this.frame);
  13501. for (var i = 0; i < navigationDivs.length; i++) {
  13502. this.navigationDivs[navigationDivs[i]] = document.createElement('div');
  13503. this.navigationDivs[navigationDivs[i]].id = "graph-navigation_" + navigationDivs[i];
  13504. this.navigationDivs[navigationDivs[i]].className = "graph-navigation " + navigationDivs[i];
  13505. this.navigationDivs['wrapper'].appendChild(this.navigationDivs[navigationDivs[i]]);
  13506. this.navigationDivs[navigationDivs[i]].onmousedown = this[navigationDivActions[i]].bind(this);
  13507. }
  13508. document.onmouseup = this._stopMovement.bind(this);
  13509. },
  13510. /**
  13511. * this stops all movement induced by the navigation buttons
  13512. *
  13513. * @private
  13514. */
  13515. _stopMovement : function() {
  13516. this._xStopMoving();
  13517. this._yStopMoving();
  13518. this._stopZoom();
  13519. },
  13520. /**
  13521. * stops the actions performed by page up and down etc.
  13522. *
  13523. * @param event
  13524. * @private
  13525. */
  13526. _preventDefault : function(event) {
  13527. if (event !== undefined) {
  13528. if (event.preventDefault) {
  13529. event.preventDefault();
  13530. } else {
  13531. event.returnValue = false;
  13532. }
  13533. }
  13534. },
  13535. /**
  13536. * move the screen up
  13537. * By using the increments, instead of adding a fixed number to the translation, we keep fluent and
  13538. * instant movement. The onKeypress event triggers immediately, then pauses, then triggers frequently
  13539. * To avoid this behaviour, we do the translation in the start loop.
  13540. *
  13541. * @private
  13542. */
  13543. _moveUp : function(event) {
  13544. this.yIncrement = this.constants.keyboard.speed.y;
  13545. this.start(); // if there is no node movement, the calculation wont be done
  13546. this._preventDefault(event);
  13547. },
  13548. /**
  13549. * move the screen down
  13550. * @private
  13551. */
  13552. _moveDown : function(event) {
  13553. this.yIncrement = -this.constants.keyboard.speed.y;
  13554. this.start(); // if there is no node movement, the calculation wont be done
  13555. this._preventDefault(event);
  13556. },
  13557. /**
  13558. * move the screen left
  13559. * @private
  13560. */
  13561. _moveLeft : function(event) {
  13562. this.xIncrement = this.constants.keyboard.speed.x;
  13563. this.start(); // if there is no node movement, the calculation wont be done
  13564. this._preventDefault(event);
  13565. },
  13566. /**
  13567. * move the screen right
  13568. * @private
  13569. */
  13570. _moveRight : function(event) {
  13571. this.xIncrement = -this.constants.keyboard.speed.y;
  13572. this.start(); // if there is no node movement, the calculation wont be done
  13573. this._preventDefault(event);
  13574. },
  13575. /**
  13576. * Zoom in, using the same method as the movement.
  13577. * @private
  13578. */
  13579. _zoomIn : function(event) {
  13580. this.zoomIncrement = this.constants.keyboard.speed.zoom;
  13581. this.start(); // if there is no node movement, the calculation wont be done
  13582. this._preventDefault(event);
  13583. },
  13584. /**
  13585. * Zoom out
  13586. * @private
  13587. */
  13588. _zoomOut : function() {
  13589. this.zoomIncrement = -this.constants.keyboard.speed.zoom;
  13590. this.start(); // if there is no node movement, the calculation wont be done
  13591. this._preventDefault(event);
  13592. },
  13593. /**
  13594. * Stop zooming and unhighlight the zoom controls
  13595. * @private
  13596. */
  13597. _stopZoom : function() {
  13598. this.zoomIncrement = 0;
  13599. },
  13600. /**
  13601. * Stop moving in the Y direction and unHighlight the up and down
  13602. * @private
  13603. */
  13604. _yStopMoving : function() {
  13605. this.yIncrement = 0;
  13606. },
  13607. /**
  13608. * Stop moving in the X direction and unHighlight left and right.
  13609. * @private
  13610. */
  13611. _xStopMoving : function() {
  13612. this.xIncrement = 0;
  13613. }
  13614. };
  13615. /**
  13616. * Created by Alex on 2/10/14.
  13617. */
  13618. var graphMixinLoaders = {
  13619. /**
  13620. * Load a mixin into the graph object
  13621. *
  13622. * @param {Object} sourceVariable | this object has to contain functions.
  13623. * @private
  13624. */
  13625. _loadMixin : function(sourceVariable) {
  13626. for (var mixinFunction in sourceVariable) {
  13627. if (sourceVariable.hasOwnProperty(mixinFunction)) {
  13628. Graph.prototype[mixinFunction] = sourceVariable[mixinFunction];
  13629. }
  13630. }
  13631. },
  13632. /**
  13633. * removes a mixin from the graph object.
  13634. *
  13635. * @param {Object} sourceVariable | this object has to contain functions.
  13636. * @private
  13637. */
  13638. _clearMixin : function(sourceVariable) {
  13639. for (var mixinFunction in sourceVariable) {
  13640. if (sourceVariable.hasOwnProperty(mixinFunction)) {
  13641. Graph.prototype[mixinFunction] = undefined;
  13642. }
  13643. }
  13644. },
  13645. /**
  13646. * Mixin the physics system and initialize the parameters required.
  13647. *
  13648. * @private
  13649. */
  13650. _loadPhysicsSystem : function() {
  13651. this._loadMixin(physicsMixin);
  13652. this._loadSelectedForceSolver();
  13653. if (this.constants.configurePhysics == true) {
  13654. this._loadPhysicsConfiguration();
  13655. }
  13656. },
  13657. /**
  13658. * Mixin the cluster system and initialize the parameters required.
  13659. *
  13660. * @private
  13661. */
  13662. _loadClusterSystem : function() {
  13663. this.clusterSession = 0;
  13664. this.hubThreshold = 5;
  13665. this._loadMixin(ClusterMixin);
  13666. },
  13667. /**
  13668. * Mixin the sector system and initialize the parameters required
  13669. *
  13670. * @private
  13671. */
  13672. _loadSectorSystem : function() {
  13673. this.sectors = { },
  13674. this.activeSector = ["default"];
  13675. this.sectors["active"] = { },
  13676. this.sectors["active"]["default"] = {"nodes":{},
  13677. "edges":{},
  13678. "nodeIndices":[],
  13679. "formationScale": 1.0,
  13680. "drawingNode": undefined };
  13681. this.sectors["frozen"] = {},
  13682. this.sectors["support"] = {"nodes":{},
  13683. "edges":{},
  13684. "nodeIndices":[],
  13685. "formationScale": 1.0,
  13686. "drawingNode": undefined };
  13687. this.nodeIndices = this.sectors["active"]["default"]["nodeIndices"]; // the node indices list is used to speed up the computation of the repulsion fields
  13688. this._loadMixin(SectorMixin);
  13689. },
  13690. /**
  13691. * Mixin the selection system and initialize the parameters required
  13692. *
  13693. * @private
  13694. */
  13695. _loadSelectionSystem : function() {
  13696. this.selectionObj = { };
  13697. this._loadMixin(SelectionMixin);
  13698. },
  13699. /**
  13700. * Mixin the navigationUI (User Interface) system and initialize the parameters required
  13701. *
  13702. * @private
  13703. */
  13704. _loadManipulationSystem : function() {
  13705. // reset global variables -- these are used by the selection of nodes and edges.
  13706. this.blockConnectingEdgeSelection = false;
  13707. this.forceAppendSelection = false
  13708. if (this.constants.dataManipulation.enabled == true) {
  13709. // load the manipulator HTML elements. All styling done in css.
  13710. if (this.manipulationDiv === undefined) {
  13711. this.manipulationDiv = document.createElement('div');
  13712. this.manipulationDiv.className = 'graph-manipulationDiv';
  13713. this.manipulationDiv.id = 'graph-manipulationDiv';
  13714. if (this.editMode == true) {
  13715. this.manipulationDiv.style.display = "block";
  13716. }
  13717. else {
  13718. this.manipulationDiv.style.display = "none";
  13719. }
  13720. this.containerElement.insertBefore(this.manipulationDiv, this.frame);
  13721. }
  13722. if (this.editModeDiv === undefined) {
  13723. this.editModeDiv = document.createElement('div');
  13724. this.editModeDiv.className = 'graph-manipulation-editMode';
  13725. this.editModeDiv.id = 'graph-manipulation-editMode';
  13726. if (this.editMode == true) {
  13727. this.editModeDiv.style.display = "none";
  13728. }
  13729. else {
  13730. this.editModeDiv.style.display = "block";
  13731. }
  13732. this.containerElement.insertBefore(this.editModeDiv, this.frame);
  13733. }
  13734. if (this.closeDiv === undefined) {
  13735. this.closeDiv = document.createElement('div');
  13736. this.closeDiv.className = 'graph-manipulation-closeDiv';
  13737. this.closeDiv.id = 'graph-manipulation-closeDiv';
  13738. this.closeDiv.style.display = this.manipulationDiv.style.display;
  13739. this.containerElement.insertBefore(this.closeDiv, this.frame);
  13740. }
  13741. // load the manipulation functions
  13742. this._loadMixin(manipulationMixin);
  13743. // create the manipulator toolbar
  13744. this._createManipulatorBar();
  13745. }
  13746. else {
  13747. if (this.manipulationDiv !== undefined) {
  13748. // removes all the bindings and overloads
  13749. this._createManipulatorBar();
  13750. // remove the manipulation divs
  13751. this.containerElement.removeChild(this.manipulationDiv);
  13752. this.containerElement.removeChild(this.editModeDiv);
  13753. this.containerElement.removeChild(this.closeDiv);
  13754. this.manipulationDiv = undefined;
  13755. this.editModeDiv = undefined;
  13756. this.closeDiv = undefined;
  13757. // remove the mixin functions
  13758. this._clearMixin(manipulationMixin);
  13759. }
  13760. }
  13761. },
  13762. /**
  13763. * Mixin the navigation (User Interface) system and initialize the parameters required
  13764. *
  13765. * @private
  13766. */
  13767. _loadNavigationControls : function() {
  13768. this._loadMixin(NavigationMixin);
  13769. // the clean function removes the button divs, this is done to remove the bindings.
  13770. this._cleanNavigation();
  13771. if (this.constants.navigation.enabled == true) {
  13772. this._loadNavigationElements();
  13773. }
  13774. },
  13775. /**
  13776. * Mixin the hierarchical layout system.
  13777. *
  13778. * @private
  13779. */
  13780. _loadHierarchySystem : function() {
  13781. this._loadMixin(HierarchicalLayoutMixin);
  13782. }
  13783. }
  13784. /**
  13785. * @constructor Graph
  13786. * Create a graph visualization, displaying nodes and edges.
  13787. *
  13788. * @param {Element} container The DOM element in which the Graph will
  13789. * be created. Normally a div element.
  13790. * @param {Object} data An object containing parameters
  13791. * {Array} nodes
  13792. * {Array} edges
  13793. * @param {Object} options Options
  13794. */
  13795. function Graph (container, data, options) {
  13796. this._initializeMixinLoaders();
  13797. // create variables and set default values
  13798. this.containerElement = container;
  13799. this.width = '100%';
  13800. this.height = '100%';
  13801. // render and calculation settings
  13802. this.renderRefreshRate = 60; // hz (fps)
  13803. this.renderTimestep = 1000 / this.renderRefreshRate; // ms -- saves calculation later on
  13804. this.renderTime = 0.5 * this.renderTimestep; // measured time it takes to render a frame
  13805. this.maxPhysicsTicksPerRender = 3; // max amount of physics ticks per render step.
  13806. this.physicsDiscreteStepsize = 0.65; // discrete stepsize of the simulation
  13807. this.stabilize = true; // stabilize before displaying the graph
  13808. this.selectable = true;
  13809. // these functions are triggered when the dataset is edited
  13810. this.triggerFunctions = {add:null,edit:null,connect:null,delete:null};
  13811. // set constant values
  13812. this.constants = {
  13813. nodes: {
  13814. radiusMin: 5,
  13815. radiusMax: 20,
  13816. radius: 5,
  13817. shape: 'ellipse',
  13818. image: undefined,
  13819. widthMin: 16, // px
  13820. widthMax: 64, // px
  13821. fixed: false,
  13822. fontColor: 'black',
  13823. fontSize: 14, // px
  13824. fontFace: 'verdana',
  13825. level: -1,
  13826. color: {
  13827. border: '#2B7CE9',
  13828. background: '#97C2FC',
  13829. highlight: {
  13830. border: '#2B7CE9',
  13831. background: '#D2E5FF'
  13832. }
  13833. },
  13834. borderColor: '#2B7CE9',
  13835. backgroundColor: '#97C2FC',
  13836. highlightColor: '#D2E5FF',
  13837. group: undefined
  13838. },
  13839. edges: {
  13840. widthMin: 1,
  13841. widthMax: 15,
  13842. width: 1,
  13843. style: 'line',
  13844. color: {
  13845. color:'#848484',
  13846. highlight:'#848484'
  13847. },
  13848. fontColor: '#343434',
  13849. fontSize: 14, // px
  13850. fontFace: 'arial',
  13851. dash: {
  13852. length: 10,
  13853. gap: 5,
  13854. altLength: undefined
  13855. }
  13856. },
  13857. configurePhysics:false,
  13858. physics: {
  13859. barnesHut: {
  13860. enabled: true,
  13861. theta: 1 / 0.6, // inverted to save time during calculation
  13862. gravitationalConstant: -2000,
  13863. centralGravity: 0.3,
  13864. springLength: 95,
  13865. springConstant: 0.04,
  13866. damping: 0.09
  13867. },
  13868. repulsion: {
  13869. centralGravity: 0.1,
  13870. springLength: 200,
  13871. springConstant: 0.05,
  13872. nodeDistance: 100,
  13873. damping: 0.09
  13874. },
  13875. hierarchicalRepulsion: {
  13876. enabled: false,
  13877. centralGravity: 0.0,
  13878. springLength: 100,
  13879. springConstant: 0.01,
  13880. nodeDistance: 60,
  13881. damping: 0.09
  13882. },
  13883. damping: null,
  13884. centralGravity: null,
  13885. springLength: null,
  13886. springConstant: null
  13887. },
  13888. clustering: { // Per Node in Cluster = PNiC
  13889. enabled: false, // (Boolean) | global on/off switch for clustering.
  13890. initialMaxNodes: 100, // (# nodes) | if the initial amount of nodes is larger than this, we cluster until the total number is less than this threshold.
  13891. 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
  13892. 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
  13893. chainThreshold: 0.4, // (% of all drawn nodes)| maximum percentage of allowed chainnodes (long strings of connected nodes) within all nodes. (lower means less chains).
  13894. clusterEdgeThreshold: 20, // (px) | edge length threshold. if smaller, this node is clustered.
  13895. sectorThreshold: 100, // (# nodes in cluster) | cluster size threshold. If larger, expanding in own sector.
  13896. 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.
  13897. fontSizeMultiplier: 4.0, // (px PNiC) | how much the cluster font size grows per node in cluster (in px).
  13898. maxFontSize: 1000,
  13899. forceAmplification: 0.1, // (multiplier PNiC) | factor of increase fo the repulsion force of a cluster (per node in cluster).
  13900. distanceAmplification: 0.1, // (multiplier PNiC) | factor how much the repulsion distance of a cluster increases (per node in cluster).
  13901. edgeGrowth: 20, // (px PNiC) | amount of clusterSize connected to the edge is multiplied with this and added to edgeLength.
  13902. nodeScaling: {width: 1, // (px PNiC) | growth of the width per node in cluster.
  13903. height: 1, // (px PNiC) | growth of the height per node in cluster.
  13904. radius: 1}, // (px PNiC) | growth of the radius per node in cluster.
  13905. maxNodeSizeIncrements: 600, // (# increments) | max growth of the width per node in cluster.
  13906. activeAreaBoxSize: 80, // (px) | box area around the curser where clusters are popped open.
  13907. clusterLevelDifference: 2
  13908. },
  13909. navigation: {
  13910. enabled: false
  13911. },
  13912. keyboard: {
  13913. enabled: false,
  13914. speed: {x: 10, y: 10, zoom: 0.02}
  13915. },
  13916. dataManipulation: {
  13917. enabled: false,
  13918. initiallyVisible: false
  13919. },
  13920. hierarchicalLayout: {
  13921. enabled:false,
  13922. levelSeparation: 150,
  13923. nodeSpacing: 100,
  13924. direction: "UD" // UD, DU, LR, RL
  13925. },
  13926. smoothCurves: true,
  13927. maxVelocity: 10,
  13928. minVelocity: 0.1, // px/s
  13929. stabilizationIterations: 1000 // maximum number of iteration to stabilize
  13930. };
  13931. this.editMode = this.constants.dataManipulation.initiallyVisible;
  13932. // Node variables
  13933. var graph = this;
  13934. this.groups = new Groups(); // object with groups
  13935. this.images = new Images(); // object with images
  13936. this.images.setOnloadCallback(function () {
  13937. graph._redraw();
  13938. });
  13939. // keyboard navigation variables
  13940. this.xIncrement = 0;
  13941. this.yIncrement = 0;
  13942. this.zoomIncrement = 0;
  13943. // loading all the mixins:
  13944. // load the force calculation functions, grouped under the physics system.
  13945. this._loadPhysicsSystem();
  13946. // create a frame and canvas
  13947. this._create();
  13948. // load the sector system. (mandatory, fully integrated with Graph)
  13949. this._loadSectorSystem();
  13950. // load the cluster system. (mandatory, even when not using the cluster system, there are function calls to it)
  13951. this._loadClusterSystem();
  13952. // load the selection system. (mandatory, required by Graph)
  13953. this._loadSelectionSystem();
  13954. // load the selection system. (mandatory, required by Graph)
  13955. this._loadHierarchySystem();
  13956. // apply options
  13957. this.setOptions(options);
  13958. // other vars
  13959. this.freezeSimulation = false;// freeze the simulation
  13960. this.cachedFunctions = {};
  13961. // containers for nodes and edges
  13962. this.calculationNodes = {};
  13963. this.calculationNodeIndices = [];
  13964. this.nodeIndices = []; // array with all the indices of the nodes. Used to speed up forces calculation
  13965. this.nodes = {}; // object with Node objects
  13966. this.edges = {}; // object with Edge objects
  13967. // position and scale variables and objects
  13968. this.canvasTopLeft = {"x": 0,"y": 0}; // coordinates of the top left of the canvas. they will be set during _redraw.
  13969. this.canvasBottomRight = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  13970. this.pointerPosition = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  13971. this.areaCenter = {}; // object with x and y elements used for determining the center of the zoom action
  13972. this.scale = 1; // defining the global scale variable in the constructor
  13973. this.previousScale = this.scale; // this is used to check if the zoom operation is zooming in or out
  13974. // datasets or dataviews
  13975. this.nodesData = null; // A DataSet or DataView
  13976. this.edgesData = null; // A DataSet or DataView
  13977. // create event listeners used to subscribe on the DataSets of the nodes and edges
  13978. this.nodesListeners = {
  13979. 'add': function (event, params) {
  13980. graph._addNodes(params.items);
  13981. graph.start();
  13982. },
  13983. 'update': function (event, params) {
  13984. graph._updateNodes(params.items);
  13985. graph.start();
  13986. },
  13987. 'remove': function (event, params) {
  13988. graph._removeNodes(params.items);
  13989. graph.start();
  13990. }
  13991. };
  13992. this.edgesListeners = {
  13993. 'add': function (event, params) {
  13994. graph._addEdges(params.items);
  13995. graph.start();
  13996. },
  13997. 'update': function (event, params) {
  13998. graph._updateEdges(params.items);
  13999. graph.start();
  14000. },
  14001. 'remove': function (event, params) {
  14002. graph._removeEdges(params.items);
  14003. graph.start();
  14004. }
  14005. };
  14006. // properties for the animation
  14007. this.moving = true;
  14008. this.timer = undefined; // Scheduling function. Is definded in this.start();
  14009. // load data (the disable start variable will be the same as the enabled clustering)
  14010. this.setData(data,this.constants.clustering.enabled || this.constants.hierarchicalLayout.enabled);
  14011. // hierarchical layout
  14012. if (this.constants.hierarchicalLayout.enabled == true) {
  14013. this._setupHierarchicalLayout();
  14014. }
  14015. else {
  14016. // zoom so all data will fit on the screen, if clustering is enabled, we do not want start to be called here.
  14017. if (this.stabilize == false) {
  14018. this.zoomExtent(true,this.constants.clustering.enabled);
  14019. }
  14020. }
  14021. // if clustering is disabled, the simulation will have started in the setData function
  14022. if (this.constants.clustering.enabled) {
  14023. this.startWithClustering();
  14024. }
  14025. }
  14026. // Extend Graph with an Emitter mixin
  14027. Emitter(Graph.prototype);
  14028. /**
  14029. * Get the script path where the vis.js library is located
  14030. *
  14031. * @returns {string | null} path Path or null when not found. Path does not
  14032. * end with a slash.
  14033. * @private
  14034. */
  14035. Graph.prototype._getScriptPath = function() {
  14036. var scripts = document.getElementsByTagName( 'script' );
  14037. // find script named vis.js or vis.min.js
  14038. for (var i = 0; i < scripts.length; i++) {
  14039. var src = scripts[i].src;
  14040. var match = src && /\/?vis(.min)?\.js$/.exec(src);
  14041. if (match) {
  14042. // return path without the script name
  14043. return src.substring(0, src.length - match[0].length);
  14044. }
  14045. }
  14046. return null;
  14047. };
  14048. /**
  14049. * Find the center position of the graph
  14050. * @private
  14051. */
  14052. Graph.prototype._getRange = function() {
  14053. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  14054. for (var nodeId in this.nodes) {
  14055. if (this.nodes.hasOwnProperty(nodeId)) {
  14056. node = this.nodes[nodeId];
  14057. if (minX > (node.x)) {minX = node.x;}
  14058. if (maxX < (node.x)) {maxX = node.x;}
  14059. if (minY > (node.y)) {minY = node.y;}
  14060. if (maxY < (node.y)) {maxY = node.y;}
  14061. }
  14062. }
  14063. return {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  14064. };
  14065. /**
  14066. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  14067. * @returns {{x: number, y: number}}
  14068. * @private
  14069. */
  14070. Graph.prototype._findCenter = function(range) {
  14071. return {x: (0.5 * (range.maxX + range.minX)),
  14072. y: (0.5 * (range.maxY + range.minY))};
  14073. };
  14074. /**
  14075. * center the graph
  14076. *
  14077. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  14078. */
  14079. Graph.prototype._centerGraph = function(range) {
  14080. var center = this._findCenter(range);
  14081. center.x *= this.scale;
  14082. center.y *= this.scale;
  14083. center.x -= 0.5 * this.frame.canvas.clientWidth;
  14084. center.y -= 0.5 * this.frame.canvas.clientHeight;
  14085. this._setTranslation(-center.x,-center.y); // set at 0,0
  14086. };
  14087. /**
  14088. * This function zooms out to fit all data on screen based on amount of nodes
  14089. *
  14090. * @param {Boolean} [initialZoom] | zoom based on fitted formula or range, true = fitted, default = false;
  14091. */
  14092. Graph.prototype.zoomExtent = function(initialZoom, disableStart) {
  14093. if (initialZoom === undefined) {
  14094. initialZoom = false;
  14095. }
  14096. if (disableStart === undefined) {
  14097. disableStart = false;
  14098. }
  14099. var range = this._getRange();
  14100. var zoomLevel;
  14101. if (initialZoom == true) {
  14102. var numberOfNodes = this.nodeIndices.length;
  14103. if (this.constants.smoothCurves == true) {
  14104. if (this.constants.clustering.enabled == true &&
  14105. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  14106. 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.
  14107. }
  14108. else {
  14109. zoomLevel = 12.662 / (numberOfNodes + 7.4147) + 0.0964822; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  14110. }
  14111. }
  14112. else {
  14113. if (this.constants.clustering.enabled == true &&
  14114. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  14115. 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.
  14116. }
  14117. else {
  14118. zoomLevel = 30.5062972 / (numberOfNodes + 19.93597763) + 0.08413486; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  14119. }
  14120. }
  14121. // correct for larger canvasses.
  14122. var factor = Math.min(this.frame.canvas.clientWidth / 600, this.frame.canvas.clientHeight / 600);
  14123. zoomLevel *= factor;
  14124. }
  14125. else {
  14126. var xDistance = (Math.abs(range.minX) + Math.abs(range.maxX)) * 1.1;
  14127. var yDistance = (Math.abs(range.minY) + Math.abs(range.maxY)) * 1.1;
  14128. var xZoomLevel = this.frame.canvas.clientWidth / xDistance;
  14129. var yZoomLevel = this.frame.canvas.clientHeight / yDistance;
  14130. zoomLevel = (xZoomLevel <= yZoomLevel) ? xZoomLevel : yZoomLevel;
  14131. }
  14132. if (zoomLevel > 1.0) {
  14133. zoomLevel = 1.0;
  14134. }
  14135. this._setScale(zoomLevel);
  14136. this._centerGraph(range);
  14137. if (disableStart == false) {
  14138. this.moving = true;
  14139. this.start();
  14140. }
  14141. };
  14142. /**
  14143. * Update the this.nodeIndices with the most recent node index list
  14144. * @private
  14145. */
  14146. Graph.prototype._updateNodeIndexList = function() {
  14147. this._clearNodeIndexList();
  14148. for (var idx in this.nodes) {
  14149. if (this.nodes.hasOwnProperty(idx)) {
  14150. this.nodeIndices.push(idx);
  14151. }
  14152. }
  14153. };
  14154. /**
  14155. * Set nodes and edges, and optionally options as well.
  14156. *
  14157. * @param {Object} data Object containing parameters:
  14158. * {Array | DataSet | DataView} [nodes] Array with nodes
  14159. * {Array | DataSet | DataView} [edges] Array with edges
  14160. * {String} [dot] String containing data in DOT format
  14161. * {Options} [options] Object with options
  14162. * @param {Boolean} [disableStart] | optional: disable the calling of the start function.
  14163. */
  14164. Graph.prototype.setData = function(data, disableStart) {
  14165. if (disableStart === undefined) {
  14166. disableStart = false;
  14167. }
  14168. if (data && data.dot && (data.nodes || data.edges)) {
  14169. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  14170. ' parameter pair "nodes" and "edges", but not both.');
  14171. }
  14172. // set options
  14173. this.setOptions(data && data.options);
  14174. // set all data
  14175. if (data && data.dot) {
  14176. // parse DOT file
  14177. if(data && data.dot) {
  14178. var dotData = vis.util.DOTToGraph(data.dot);
  14179. this.setData(dotData);
  14180. return;
  14181. }
  14182. }
  14183. else {
  14184. this._setNodes(data && data.nodes);
  14185. this._setEdges(data && data.edges);
  14186. }
  14187. this._putDataInSector();
  14188. if (!disableStart) {
  14189. // find a stable position or start animating to a stable position
  14190. if (this.stabilize) {
  14191. this._stabilize();
  14192. }
  14193. this.start();
  14194. }
  14195. };
  14196. /**
  14197. * Set options
  14198. * @param {Object} options
  14199. */
  14200. Graph.prototype.setOptions = function (options) {
  14201. if (options) {
  14202. var prop;
  14203. // retrieve parameter values
  14204. if (options.width !== undefined) {this.width = options.width;}
  14205. if (options.height !== undefined) {this.height = options.height;}
  14206. if (options.stabilize !== undefined) {this.stabilize = options.stabilize;}
  14207. if (options.selectable !== undefined) {this.selectable = options.selectable;}
  14208. if (options.smoothCurves !== undefined) {this.constants.smoothCurves = options.smoothCurves;}
  14209. if (options.configurePhysics !== undefined){this.constants.configurePhysics = options.configurePhysics;}
  14210. if (options.stabilizationIterations !== undefined) {this.constants.stabilizationIterations = options.stabilizationIterations;}
  14211. if (options.onAdd) {
  14212. this.triggerFunctions.add = options.onAdd;
  14213. }
  14214. if (options.onEdit) {
  14215. this.triggerFunctions.edit = options.onEdit;
  14216. }
  14217. if (options.onConnect) {
  14218. this.triggerFunctions.connect = options.onConnect;
  14219. }
  14220. if (options.onDelete) {
  14221. this.triggerFunctions.delete = options.onDelete;
  14222. }
  14223. if (options.physics) {
  14224. if (options.physics.barnesHut) {
  14225. this.constants.physics.barnesHut.enabled = true;
  14226. for (prop in options.physics.barnesHut) {
  14227. if (options.physics.barnesHut.hasOwnProperty(prop)) {
  14228. this.constants.physics.barnesHut[prop] = options.physics.barnesHut[prop];
  14229. }
  14230. }
  14231. }
  14232. if (options.physics.repulsion) {
  14233. this.constants.physics.barnesHut.enabled = false;
  14234. for (prop in options.physics.repulsion) {
  14235. if (options.physics.repulsion.hasOwnProperty(prop)) {
  14236. this.constants.physics.repulsion[prop] = options.physics.repulsion[prop];
  14237. }
  14238. }
  14239. }
  14240. }
  14241. if (options.hierarchicalLayout) {
  14242. this.constants.hierarchicalLayout.enabled = true;
  14243. for (prop in options.hierarchicalLayout) {
  14244. if (options.hierarchicalLayout.hasOwnProperty(prop)) {
  14245. this.constants.hierarchicalLayout[prop] = options.hierarchicalLayout[prop];
  14246. }
  14247. }
  14248. }
  14249. else if (options.hierarchicalLayout !== undefined) {
  14250. this.constants.hierarchicalLayout.enabled = false;
  14251. }
  14252. if (options.clustering) {
  14253. this.constants.clustering.enabled = true;
  14254. for (prop in options.clustering) {
  14255. if (options.clustering.hasOwnProperty(prop)) {
  14256. this.constants.clustering[prop] = options.clustering[prop];
  14257. }
  14258. }
  14259. }
  14260. else if (options.clustering !== undefined) {
  14261. this.constants.clustering.enabled = false;
  14262. }
  14263. if (options.navigation) {
  14264. this.constants.navigation.enabled = true;
  14265. for (prop in options.navigation) {
  14266. if (options.navigation.hasOwnProperty(prop)) {
  14267. this.constants.navigation[prop] = options.navigation[prop];
  14268. }
  14269. }
  14270. }
  14271. else if (options.navigation !== undefined) {
  14272. this.constants.navigation.enabled = false;
  14273. }
  14274. if (options.keyboard) {
  14275. this.constants.keyboard.enabled = true;
  14276. for (prop in options.keyboard) {
  14277. if (options.keyboard.hasOwnProperty(prop)) {
  14278. this.constants.keyboard[prop] = options.keyboard[prop];
  14279. }
  14280. }
  14281. }
  14282. else if (options.keyboard !== undefined) {
  14283. this.constants.keyboard.enabled = false;
  14284. }
  14285. if (options.dataManipulation) {
  14286. this.constants.dataManipulation.enabled = true;
  14287. for (prop in options.dataManipulation) {
  14288. if (options.dataManipulation.hasOwnProperty(prop)) {
  14289. this.constants.dataManipulation[prop] = options.dataManipulation[prop];
  14290. }
  14291. }
  14292. }
  14293. else if (options.dataManipulation !== undefined) {
  14294. this.constants.dataManipulation.enabled = false;
  14295. }
  14296. // TODO: work out these options and document them
  14297. if (options.edges) {
  14298. for (prop in options.edges) {
  14299. if (options.edges.hasOwnProperty(prop)) {
  14300. if (typeof options.edges[prop] != "object") {
  14301. this.constants.edges[prop] = options.edges[prop];
  14302. }
  14303. }
  14304. }
  14305. if (options.edges.color !== undefined) {
  14306. if (util.isString(options.edges.color)) {
  14307. this.constants.edges.color.color = options.edges.color;
  14308. this.constants.edges.color.highlight = options.edges.color;
  14309. }
  14310. else {
  14311. if (options.edges.color.color !== undefined) {this.constants.edges.color.color = options.edges.color.color;}
  14312. if (options.edges.color.highlight !== undefined) {this.constants.edges.color.highlight = options.edges.color.highlight;}
  14313. }
  14314. }
  14315. if (!options.edges.fontColor) {
  14316. if (options.edges.color !== undefined) {
  14317. if (util.isString(options.edges.color)) {this.constants.edges.fontColor = options.edges.color;}
  14318. else if (options.edges.color.color !== undefined) {this.constants.edges.fontColor = options.edges.color.color;}
  14319. }
  14320. }
  14321. // Added to support dashed lines
  14322. // David Jordan
  14323. // 2012-08-08
  14324. if (options.edges.dash) {
  14325. if (options.edges.dash.length !== undefined) {
  14326. this.constants.edges.dash.length = options.edges.dash.length;
  14327. }
  14328. if (options.edges.dash.gap !== undefined) {
  14329. this.constants.edges.dash.gap = options.edges.dash.gap;
  14330. }
  14331. if (options.edges.dash.altLength !== undefined) {
  14332. this.constants.edges.dash.altLength = options.edges.dash.altLength;
  14333. }
  14334. }
  14335. }
  14336. if (options.nodes) {
  14337. for (prop in options.nodes) {
  14338. if (options.nodes.hasOwnProperty(prop)) {
  14339. this.constants.nodes[prop] = options.nodes[prop];
  14340. }
  14341. }
  14342. if (options.nodes.color) {
  14343. this.constants.nodes.color = Node.parseColor(options.nodes.color);
  14344. }
  14345. /*
  14346. if (options.nodes.widthMin) this.constants.nodes.radiusMin = options.nodes.widthMin;
  14347. if (options.nodes.widthMax) this.constants.nodes.radiusMax = options.nodes.widthMax;
  14348. */
  14349. }
  14350. if (options.groups) {
  14351. for (var groupname in options.groups) {
  14352. if (options.groups.hasOwnProperty(groupname)) {
  14353. var group = options.groups[groupname];
  14354. this.groups.add(groupname, group);
  14355. }
  14356. }
  14357. }
  14358. }
  14359. // (Re)loading the mixins that can be enabled or disabled in the options.
  14360. // load the force calculation functions, grouped under the physics system.
  14361. this._loadPhysicsSystem();
  14362. // load the navigation system.
  14363. this._loadNavigationControls();
  14364. // load the data manipulation system
  14365. this._loadManipulationSystem();
  14366. // configure the smooth curves
  14367. this._configureSmoothCurves();
  14368. // bind keys. If disabled, this will not do anything;
  14369. this._createKeyBinds();
  14370. this.setSize(this.width, this.height);
  14371. this._setTranslation(this.frame.clientWidth / 2, this.frame.clientHeight / 2);
  14372. this._setScale(1);
  14373. this._redraw();
  14374. };
  14375. /**
  14376. * Create the main frame for the Graph.
  14377. * This function is executed once when a Graph object is created. The frame
  14378. * contains a canvas, and this canvas contains all objects like the axis and
  14379. * nodes.
  14380. * @private
  14381. */
  14382. Graph.prototype._create = function () {
  14383. // remove all elements from the container element.
  14384. while (this.containerElement.hasChildNodes()) {
  14385. this.containerElement.removeChild(this.containerElement.firstChild);
  14386. }
  14387. this.frame = document.createElement('div');
  14388. this.frame.className = 'graph-frame';
  14389. this.frame.style.position = 'relative';
  14390. this.frame.style.overflow = 'hidden';
  14391. this.frame.style.zIndex = "1";
  14392. // create the graph canvas (HTML canvas element)
  14393. this.frame.canvas = document.createElement( 'canvas' );
  14394. this.frame.canvas.style.position = 'relative';
  14395. this.frame.appendChild(this.frame.canvas);
  14396. if (!this.frame.canvas.getContext) {
  14397. var noCanvas = document.createElement( 'DIV' );
  14398. noCanvas.style.color = 'red';
  14399. noCanvas.style.fontWeight = 'bold' ;
  14400. noCanvas.style.padding = '10px';
  14401. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  14402. this.frame.canvas.appendChild(noCanvas);
  14403. }
  14404. var me = this;
  14405. this.drag = {};
  14406. this.pinch = {};
  14407. this.hammer = Hammer(this.frame.canvas, {
  14408. prevent_default: true
  14409. });
  14410. this.hammer.on('tap', me._onTap.bind(me) );
  14411. this.hammer.on('doubletap', me._onDoubleTap.bind(me) );
  14412. this.hammer.on('hold', me._onHold.bind(me) );
  14413. this.hammer.on('pinch', me._onPinch.bind(me) );
  14414. this.hammer.on('touch', me._onTouch.bind(me) );
  14415. this.hammer.on('dragstart', me._onDragStart.bind(me) );
  14416. this.hammer.on('drag', me._onDrag.bind(me) );
  14417. this.hammer.on('dragend', me._onDragEnd.bind(me) );
  14418. this.hammer.on('release', me._onRelease.bind(me) );
  14419. this.hammer.on('mousewheel',me._onMouseWheel.bind(me) );
  14420. this.hammer.on('DOMMouseScroll',me._onMouseWheel.bind(me) ); // for FF
  14421. this.hammer.on('mousemove', me._onMouseMoveTitle.bind(me) );
  14422. // add the frame to the container element
  14423. this.containerElement.appendChild(this.frame);
  14424. };
  14425. /**
  14426. * Binding the keys for keyboard navigation. These functions are defined in the NavigationMixin
  14427. * @private
  14428. */
  14429. Graph.prototype._createKeyBinds = function() {
  14430. var me = this;
  14431. this.mousetrap = mousetrap;
  14432. this.mousetrap.reset();
  14433. if (this.constants.keyboard.enabled == true) {
  14434. this.mousetrap.bind("up", this._moveUp.bind(me) , "keydown");
  14435. this.mousetrap.bind("up", this._yStopMoving.bind(me), "keyup");
  14436. this.mousetrap.bind("down", this._moveDown.bind(me) , "keydown");
  14437. this.mousetrap.bind("down", this._yStopMoving.bind(me), "keyup");
  14438. this.mousetrap.bind("left", this._moveLeft.bind(me) , "keydown");
  14439. this.mousetrap.bind("left", this._xStopMoving.bind(me), "keyup");
  14440. this.mousetrap.bind("right",this._moveRight.bind(me), "keydown");
  14441. this.mousetrap.bind("right",this._xStopMoving.bind(me), "keyup");
  14442. this.mousetrap.bind("=", this._zoomIn.bind(me), "keydown");
  14443. this.mousetrap.bind("=", this._stopZoom.bind(me), "keyup");
  14444. this.mousetrap.bind("-", this._zoomOut.bind(me), "keydown");
  14445. this.mousetrap.bind("-", this._stopZoom.bind(me), "keyup");
  14446. this.mousetrap.bind("[", this._zoomIn.bind(me), "keydown");
  14447. this.mousetrap.bind("[", this._stopZoom.bind(me), "keyup");
  14448. this.mousetrap.bind("]", this._zoomOut.bind(me), "keydown");
  14449. this.mousetrap.bind("]", this._stopZoom.bind(me), "keyup");
  14450. this.mousetrap.bind("pageup",this._zoomIn.bind(me), "keydown");
  14451. this.mousetrap.bind("pageup",this._stopZoom.bind(me), "keyup");
  14452. this.mousetrap.bind("pagedown",this._zoomOut.bind(me),"keydown");
  14453. this.mousetrap.bind("pagedown",this._stopZoom.bind(me), "keyup");
  14454. }
  14455. if (this.constants.dataManipulation.enabled == true) {
  14456. this.mousetrap.bind("escape",this._createManipulatorBar.bind(me));
  14457. this.mousetrap.bind("del",this._deleteSelected.bind(me));
  14458. }
  14459. };
  14460. /**
  14461. * Get the pointer location from a touch location
  14462. * @param {{pageX: Number, pageY: Number}} touch
  14463. * @return {{x: Number, y: Number}} pointer
  14464. * @private
  14465. */
  14466. Graph.prototype._getPointer = function (touch) {
  14467. return {
  14468. x: touch.pageX - vis.util.getAbsoluteLeft(this.frame.canvas),
  14469. y: touch.pageY - vis.util.getAbsoluteTop(this.frame.canvas)
  14470. };
  14471. };
  14472. /**
  14473. * On start of a touch gesture, store the pointer
  14474. * @param event
  14475. * @private
  14476. */
  14477. Graph.prototype._onTouch = function (event) {
  14478. this.drag.pointer = this._getPointer(event.gesture.center);
  14479. this.drag.pinched = false;
  14480. this.pinch.scale = this._getScale();
  14481. this._handleTouch(this.drag.pointer);
  14482. };
  14483. /**
  14484. * handle drag start event
  14485. * @private
  14486. */
  14487. Graph.prototype._onDragStart = function () {
  14488. this._handleDragStart();
  14489. };
  14490. /**
  14491. * This function is called by _onDragStart.
  14492. * It is separated out because we can then overload it for the datamanipulation system.
  14493. *
  14494. * @private
  14495. */
  14496. Graph.prototype._handleDragStart = function() {
  14497. var drag = this.drag;
  14498. var node = this._getNodeAt(drag.pointer);
  14499. // note: drag.pointer is set in _onTouch to get the initial touch location
  14500. drag.dragging = true;
  14501. drag.selection = [];
  14502. drag.translation = this._getTranslation();
  14503. drag.nodeId = null;
  14504. if (node != null) {
  14505. drag.nodeId = node.id;
  14506. // select the clicked node if not yet selected
  14507. if (!node.isSelected()) {
  14508. this._selectObject(node,false);
  14509. }
  14510. // create an array with the selected nodes and their original location and status
  14511. for (var objectId in this.selectionObj) {
  14512. if (this.selectionObj.hasOwnProperty(objectId)) {
  14513. var object = this.selectionObj[objectId];
  14514. if (object instanceof Node) {
  14515. var s = {
  14516. id: object.id,
  14517. node: object,
  14518. // store original x, y, xFixed and yFixed, make the node temporarily Fixed
  14519. x: object.x,
  14520. y: object.y,
  14521. xFixed: object.xFixed,
  14522. yFixed: object.yFixed
  14523. };
  14524. object.xFixed = true;
  14525. object.yFixed = true;
  14526. drag.selection.push(s);
  14527. }
  14528. }
  14529. }
  14530. }
  14531. };
  14532. /**
  14533. * handle drag event
  14534. * @private
  14535. */
  14536. Graph.prototype._onDrag = function (event) {
  14537. this._handleOnDrag(event)
  14538. };
  14539. /**
  14540. * This function is called by _onDrag.
  14541. * It is separated out because we can then overload it for the datamanipulation system.
  14542. *
  14543. * @private
  14544. */
  14545. Graph.prototype._handleOnDrag = function(event) {
  14546. if (this.drag.pinched) {
  14547. return;
  14548. }
  14549. var pointer = this._getPointer(event.gesture.center);
  14550. var me = this,
  14551. drag = this.drag,
  14552. selection = drag.selection;
  14553. if (selection && selection.length) {
  14554. // calculate delta's and new location
  14555. var deltaX = pointer.x - drag.pointer.x,
  14556. deltaY = pointer.y - drag.pointer.y;
  14557. // update position of all selected nodes
  14558. selection.forEach(function (s) {
  14559. var node = s.node;
  14560. if (!s.xFixed) {
  14561. node.x = me._canvasToX(me._xToCanvas(s.x) + deltaX);
  14562. }
  14563. if (!s.yFixed) {
  14564. node.y = me._canvasToY(me._yToCanvas(s.y) + deltaY);
  14565. }
  14566. });
  14567. // start _animationStep if not yet running
  14568. if (!this.moving) {
  14569. this.moving = true;
  14570. this.start();
  14571. }
  14572. }
  14573. else {
  14574. // move the graph
  14575. var diffX = pointer.x - this.drag.pointer.x;
  14576. var diffY = pointer.y - this.drag.pointer.y;
  14577. this._setTranslation(
  14578. this.drag.translation.x + diffX,
  14579. this.drag.translation.y + diffY);
  14580. this._redraw();
  14581. this.moved = true;
  14582. }
  14583. };
  14584. /**
  14585. * handle drag start event
  14586. * @private
  14587. */
  14588. Graph.prototype._onDragEnd = function () {
  14589. this.drag.dragging = false;
  14590. var selection = this.drag.selection;
  14591. if (selection) {
  14592. selection.forEach(function (s) {
  14593. // restore original xFixed and yFixed
  14594. s.node.xFixed = s.xFixed;
  14595. s.node.yFixed = s.yFixed;
  14596. });
  14597. }
  14598. };
  14599. /**
  14600. * handle tap/click event: select/unselect a node
  14601. * @private
  14602. */
  14603. Graph.prototype._onTap = function (event) {
  14604. var pointer = this._getPointer(event.gesture.center);
  14605. this.pointerPosition = pointer;
  14606. this._handleTap(pointer);
  14607. };
  14608. /**
  14609. * handle doubletap event
  14610. * @private
  14611. */
  14612. Graph.prototype._onDoubleTap = function (event) {
  14613. var pointer = this._getPointer(event.gesture.center);
  14614. this._handleDoubleTap(pointer);
  14615. };
  14616. /**
  14617. * handle long tap event: multi select nodes
  14618. * @private
  14619. */
  14620. Graph.prototype._onHold = function (event) {
  14621. var pointer = this._getPointer(event.gesture.center);
  14622. this.pointerPosition = pointer;
  14623. this._handleOnHold(pointer);
  14624. };
  14625. /**
  14626. * handle the release of the screen
  14627. *
  14628. * @private
  14629. */
  14630. Graph.prototype._onRelease = function (event) {
  14631. var pointer = this._getPointer(event.gesture.center);
  14632. this._handleOnRelease(pointer);
  14633. };
  14634. /**
  14635. * Handle pinch event
  14636. * @param event
  14637. * @private
  14638. */
  14639. Graph.prototype._onPinch = function (event) {
  14640. var pointer = this._getPointer(event.gesture.center);
  14641. this.drag.pinched = true;
  14642. if (!('scale' in this.pinch)) {
  14643. this.pinch.scale = 1;
  14644. }
  14645. // TODO: enabled moving while pinching?
  14646. var scale = this.pinch.scale * event.gesture.scale;
  14647. this._zoom(scale, pointer)
  14648. };
  14649. /**
  14650. * Zoom the graph in or out
  14651. * @param {Number} scale a number around 1, and between 0.01 and 10
  14652. * @param {{x: Number, y: Number}} pointer Position on screen
  14653. * @return {Number} appliedScale scale is limited within the boundaries
  14654. * @private
  14655. */
  14656. Graph.prototype._zoom = function(scale, pointer) {
  14657. var scaleOld = this._getScale();
  14658. if (scale < 0.00001) {
  14659. scale = 0.00001;
  14660. }
  14661. if (scale > 10) {
  14662. scale = 10;
  14663. }
  14664. // + this.frame.canvas.clientHeight / 2
  14665. var translation = this._getTranslation();
  14666. var scaleFrac = scale / scaleOld;
  14667. var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac;
  14668. var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac;
  14669. this.areaCenter = {"x" : this._canvasToX(pointer.x),
  14670. "y" : this._canvasToY(pointer.y)};
  14671. this._setScale(scale);
  14672. this._setTranslation(tx, ty);
  14673. this.updateClustersDefault();
  14674. this._redraw();
  14675. return scale;
  14676. };
  14677. /**
  14678. * Event handler for mouse wheel event, used to zoom the timeline
  14679. * See http://adomas.org/javascript-mouse-wheel/
  14680. * https://github.com/EightMedia/hammer.js/issues/256
  14681. * @param {MouseEvent} event
  14682. * @private
  14683. */
  14684. Graph.prototype._onMouseWheel = function(event) {
  14685. // retrieve delta
  14686. var delta = 0;
  14687. if (event.wheelDelta) { /* IE/Opera. */
  14688. delta = event.wheelDelta/120;
  14689. } else if (event.detail) { /* Mozilla case. */
  14690. // In Mozilla, sign of delta is different than in IE.
  14691. // Also, delta is multiple of 3.
  14692. delta = -event.detail/3;
  14693. }
  14694. // If delta is nonzero, handle it.
  14695. // Basically, delta is now positive if wheel was scrolled up,
  14696. // and negative, if wheel was scrolled down.
  14697. if (delta) {
  14698. // calculate the new scale
  14699. var scale = this._getScale();
  14700. var zoom = delta / 10;
  14701. if (delta < 0) {
  14702. zoom = zoom / (1 - zoom);
  14703. }
  14704. scale *= (1 + zoom);
  14705. // calculate the pointer location
  14706. var gesture = util.fakeGesture(this, event);
  14707. var pointer = this._getPointer(gesture.center);
  14708. // apply the new scale
  14709. this._zoom(scale, pointer);
  14710. }
  14711. // Prevent default actions caused by mouse wheel.
  14712. event.preventDefault();
  14713. };
  14714. /**
  14715. * Mouse move handler for checking whether the title moves over a node with a title.
  14716. * @param {Event} event
  14717. * @private
  14718. */
  14719. Graph.prototype._onMouseMoveTitle = function (event) {
  14720. var gesture = util.fakeGesture(this, event);
  14721. var pointer = this._getPointer(gesture.center);
  14722. // check if the previously selected node is still selected
  14723. if (this.popupNode) {
  14724. this._checkHidePopup(pointer);
  14725. }
  14726. // start a timeout that will check if the mouse is positioned above
  14727. // an element
  14728. var me = this;
  14729. var checkShow = function() {
  14730. me._checkShowPopup(pointer);
  14731. };
  14732. if (this.popupTimer) {
  14733. clearInterval(this.popupTimer); // stop any running calculationTimer
  14734. }
  14735. if (!this.drag.dragging) {
  14736. this.popupTimer = setTimeout(checkShow, 300);
  14737. }
  14738. };
  14739. /**
  14740. * Check if there is an element on the given position in the graph
  14741. * (a node or edge). If so, and if this element has a title,
  14742. * show a popup window with its title.
  14743. *
  14744. * @param {{x:Number, y:Number}} pointer
  14745. * @private
  14746. */
  14747. Graph.prototype._checkShowPopup = function (pointer) {
  14748. var obj = {
  14749. left: this._canvasToX(pointer.x),
  14750. top: this._canvasToY(pointer.y),
  14751. right: this._canvasToX(pointer.x),
  14752. bottom: this._canvasToY(pointer.y)
  14753. };
  14754. var id;
  14755. var lastPopupNode = this.popupNode;
  14756. if (this.popupNode == undefined) {
  14757. // search the nodes for overlap, select the top one in case of multiple nodes
  14758. var nodes = this.nodes;
  14759. for (id in nodes) {
  14760. if (nodes.hasOwnProperty(id)) {
  14761. var node = nodes[id];
  14762. if (node.getTitle() !== undefined && node.isOverlappingWith(obj)) {
  14763. this.popupNode = node;
  14764. break;
  14765. }
  14766. }
  14767. }
  14768. }
  14769. if (this.popupNode === undefined) {
  14770. // search the edges for overlap
  14771. var edges = this.edges;
  14772. for (id in edges) {
  14773. if (edges.hasOwnProperty(id)) {
  14774. var edge = edges[id];
  14775. if (edge.connected && (edge.getTitle() !== undefined) &&
  14776. edge.isOverlappingWith(obj)) {
  14777. this.popupNode = edge;
  14778. break;
  14779. }
  14780. }
  14781. }
  14782. }
  14783. if (this.popupNode) {
  14784. // show popup message window
  14785. if (this.popupNode != lastPopupNode) {
  14786. var me = this;
  14787. if (!me.popup) {
  14788. me.popup = new Popup(me.frame);
  14789. }
  14790. // adjust a small offset such that the mouse cursor is located in the
  14791. // bottom left location of the popup, and you can easily move over the
  14792. // popup area
  14793. me.popup.setPosition(pointer.x - 3, pointer.y - 3);
  14794. me.popup.setText(me.popupNode.getTitle());
  14795. me.popup.show();
  14796. }
  14797. }
  14798. else {
  14799. if (this.popup) {
  14800. this.popup.hide();
  14801. }
  14802. }
  14803. };
  14804. /**
  14805. * Check if the popup must be hided, which is the case when the mouse is no
  14806. * longer hovering on the object
  14807. * @param {{x:Number, y:Number}} pointer
  14808. * @private
  14809. */
  14810. Graph.prototype._checkHidePopup = function (pointer) {
  14811. if (!this.popupNode || !this._getNodeAt(pointer) ) {
  14812. this.popupNode = undefined;
  14813. if (this.popup) {
  14814. this.popup.hide();
  14815. }
  14816. }
  14817. };
  14818. /**
  14819. * Set a new size for the graph
  14820. * @param {string} width Width in pixels or percentage (for example '800px'
  14821. * or '50%')
  14822. * @param {string} height Height in pixels or percentage (for example '400px'
  14823. * or '30%')
  14824. */
  14825. Graph.prototype.setSize = function(width, height) {
  14826. this.frame.style.width = width;
  14827. this.frame.style.height = height;
  14828. this.frame.canvas.style.width = '100%';
  14829. this.frame.canvas.style.height = '100%';
  14830. this.frame.canvas.width = this.frame.canvas.clientWidth;
  14831. this.frame.canvas.height = this.frame.canvas.clientHeight;
  14832. if (this.manipulationDiv !== undefined) {
  14833. this.manipulationDiv.style.width = this.frame.canvas.clientWidth + "px";
  14834. }
  14835. if (this.navigationDivs !== undefined) {
  14836. if (this.navigationDivs['wrapper'] !== undefined) {
  14837. this.navigationDivs['wrapper'].style.width = this.frame.canvas.clientWidth + "px";
  14838. this.navigationDivs['wrapper'].style.height = this.frame.canvas.clientHeight + "px";
  14839. }
  14840. }
  14841. this.emit('resize', {width:this.frame.canvas.width,height:this.frame.canvas.height});
  14842. };
  14843. /**
  14844. * Set a data set with nodes for the graph
  14845. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  14846. * @private
  14847. */
  14848. Graph.prototype._setNodes = function(nodes) {
  14849. var oldNodesData = this.nodesData;
  14850. if (nodes instanceof DataSet || nodes instanceof DataView) {
  14851. this.nodesData = nodes;
  14852. }
  14853. else if (nodes instanceof Array) {
  14854. this.nodesData = new DataSet();
  14855. this.nodesData.add(nodes);
  14856. }
  14857. else if (!nodes) {
  14858. this.nodesData = new DataSet();
  14859. }
  14860. else {
  14861. throw new TypeError('Array or DataSet expected');
  14862. }
  14863. if (oldNodesData) {
  14864. // unsubscribe from old dataset
  14865. util.forEach(this.nodesListeners, function (callback, event) {
  14866. oldNodesData.off(event, callback);
  14867. });
  14868. }
  14869. // remove drawn nodes
  14870. this.nodes = {};
  14871. if (this.nodesData) {
  14872. // subscribe to new dataset
  14873. var me = this;
  14874. util.forEach(this.nodesListeners, function (callback, event) {
  14875. me.nodesData.on(event, callback);
  14876. });
  14877. // draw all new nodes
  14878. var ids = this.nodesData.getIds();
  14879. this._addNodes(ids);
  14880. }
  14881. this._updateSelection();
  14882. };
  14883. /**
  14884. * Add nodes
  14885. * @param {Number[] | String[]} ids
  14886. * @private
  14887. */
  14888. Graph.prototype._addNodes = function(ids) {
  14889. var id;
  14890. for (var i = 0, len = ids.length; i < len; i++) {
  14891. id = ids[i];
  14892. var data = this.nodesData.get(id);
  14893. var node = new Node(data, this.images, this.groups, this.constants);
  14894. this.nodes[id] = node; // note: this may replace an existing node
  14895. if ((node.xFixed == false || node.yFixed == false) && (node.x === null || node.y === null)) {
  14896. var radius = 10 * 0.1*ids.length;
  14897. var angle = 2 * Math.PI * Math.random();
  14898. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  14899. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  14900. }
  14901. this.moving = true;
  14902. }
  14903. this._updateNodeIndexList();
  14904. this._updateCalculationNodes();
  14905. this._reconnectEdges();
  14906. this._updateValueRange(this.nodes);
  14907. this.updateLabels();
  14908. };
  14909. /**
  14910. * Update existing nodes, or create them when not yet existing
  14911. * @param {Number[] | String[]} ids
  14912. * @private
  14913. */
  14914. Graph.prototype._updateNodes = function(ids) {
  14915. var nodes = this.nodes,
  14916. nodesData = this.nodesData;
  14917. for (var i = 0, len = ids.length; i < len; i++) {
  14918. var id = ids[i];
  14919. var node = nodes[id];
  14920. var data = nodesData.get(id);
  14921. if (node) {
  14922. // update node
  14923. node.setProperties(data, this.constants);
  14924. }
  14925. else {
  14926. // create node
  14927. node = new Node(properties, this.images, this.groups, this.constants);
  14928. nodes[id] = node;
  14929. if (!node.isFixed()) {
  14930. this.moving = true;
  14931. }
  14932. }
  14933. }
  14934. this._updateNodeIndexList();
  14935. this._reconnectEdges();
  14936. this._updateValueRange(nodes);
  14937. };
  14938. /**
  14939. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  14940. * @param {Number[] | String[]} ids
  14941. * @private
  14942. */
  14943. Graph.prototype._removeNodes = function(ids) {
  14944. var nodes = this.nodes;
  14945. for (var i = 0, len = ids.length; i < len; i++) {
  14946. var id = ids[i];
  14947. delete nodes[id];
  14948. }
  14949. this._updateNodeIndexList();
  14950. this._reconnectEdges();
  14951. this._updateSelection();
  14952. this._updateValueRange(nodes);
  14953. };
  14954. /**
  14955. * Load edges by reading the data table
  14956. * @param {Array | DataSet | DataView} edges The data containing the edges.
  14957. * @private
  14958. * @private
  14959. */
  14960. Graph.prototype._setEdges = function(edges) {
  14961. var oldEdgesData = this.edgesData;
  14962. if (edges instanceof DataSet || edges instanceof DataView) {
  14963. this.edgesData = edges;
  14964. }
  14965. else if (edges instanceof Array) {
  14966. this.edgesData = new DataSet();
  14967. this.edgesData.add(edges);
  14968. }
  14969. else if (!edges) {
  14970. this.edgesData = new DataSet();
  14971. }
  14972. else {
  14973. throw new TypeError('Array or DataSet expected');
  14974. }
  14975. if (oldEdgesData) {
  14976. // unsubscribe from old dataset
  14977. util.forEach(this.edgesListeners, function (callback, event) {
  14978. oldEdgesData.off(event, callback);
  14979. });
  14980. }
  14981. // remove drawn edges
  14982. this.edges = {};
  14983. if (this.edgesData) {
  14984. // subscribe to new dataset
  14985. var me = this;
  14986. util.forEach(this.edgesListeners, function (callback, event) {
  14987. me.edgesData.on(event, callback);
  14988. });
  14989. // draw all new nodes
  14990. var ids = this.edgesData.getIds();
  14991. this._addEdges(ids);
  14992. }
  14993. this._reconnectEdges();
  14994. };
  14995. /**
  14996. * Add edges
  14997. * @param {Number[] | String[]} ids
  14998. * @private
  14999. */
  15000. Graph.prototype._addEdges = function (ids) {
  15001. var edges = this.edges,
  15002. edgesData = this.edgesData;
  15003. for (var i = 0, len = ids.length; i < len; i++) {
  15004. var id = ids[i];
  15005. var oldEdge = edges[id];
  15006. if (oldEdge) {
  15007. oldEdge.disconnect();
  15008. }
  15009. var data = edgesData.get(id, {"showInternalIds" : true});
  15010. edges[id] = new Edge(data, this, this.constants);
  15011. }
  15012. this.moving = true;
  15013. this._updateValueRange(edges);
  15014. this._createBezierNodes();
  15015. this._updateCalculationNodes();
  15016. };
  15017. /**
  15018. * Update existing edges, or create them when not yet existing
  15019. * @param {Number[] | String[]} ids
  15020. * @private
  15021. */
  15022. Graph.prototype._updateEdges = function (ids) {
  15023. var edges = this.edges,
  15024. edgesData = this.edgesData;
  15025. for (var i = 0, len = ids.length; i < len; i++) {
  15026. var id = ids[i];
  15027. var data = edgesData.get(id);
  15028. var edge = edges[id];
  15029. if (edge) {
  15030. // update edge
  15031. edge.disconnect();
  15032. edge.setProperties(data, this.constants);
  15033. edge.connect();
  15034. }
  15035. else {
  15036. // create edge
  15037. edge = new Edge(data, this, this.constants);
  15038. this.edges[id] = edge;
  15039. }
  15040. }
  15041. this._createBezierNodes();
  15042. this.moving = true;
  15043. this._updateValueRange(edges);
  15044. };
  15045. /**
  15046. * Remove existing edges. Non existing ids will be ignored
  15047. * @param {Number[] | String[]} ids
  15048. * @private
  15049. */
  15050. Graph.prototype._removeEdges = function (ids) {
  15051. var edges = this.edges;
  15052. for (var i = 0, len = ids.length; i < len; i++) {
  15053. var id = ids[i];
  15054. var edge = edges[id];
  15055. if (edge) {
  15056. if (edge.via != null) {
  15057. delete this.sectors['support']['nodes'][edge.via.id];
  15058. }
  15059. edge.disconnect();
  15060. delete edges[id];
  15061. }
  15062. }
  15063. this.moving = true;
  15064. this._updateValueRange(edges);
  15065. this._updateCalculationNodes();
  15066. };
  15067. /**
  15068. * Reconnect all edges
  15069. * @private
  15070. */
  15071. Graph.prototype._reconnectEdges = function() {
  15072. var id,
  15073. nodes = this.nodes,
  15074. edges = this.edges;
  15075. for (id in nodes) {
  15076. if (nodes.hasOwnProperty(id)) {
  15077. nodes[id].edges = [];
  15078. }
  15079. }
  15080. for (id in edges) {
  15081. if (edges.hasOwnProperty(id)) {
  15082. var edge = edges[id];
  15083. edge.from = null;
  15084. edge.to = null;
  15085. edge.connect();
  15086. }
  15087. }
  15088. };
  15089. /**
  15090. * Update the values of all object in the given array according to the current
  15091. * value range of the objects in the array.
  15092. * @param {Object} obj An object containing a set of Edges or Nodes
  15093. * The objects must have a method getValue() and
  15094. * setValueRange(min, max).
  15095. * @private
  15096. */
  15097. Graph.prototype._updateValueRange = function(obj) {
  15098. var id;
  15099. // determine the range of the objects
  15100. var valueMin = undefined;
  15101. var valueMax = undefined;
  15102. for (id in obj) {
  15103. if (obj.hasOwnProperty(id)) {
  15104. var value = obj[id].getValue();
  15105. if (value !== undefined) {
  15106. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  15107. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  15108. }
  15109. }
  15110. }
  15111. // adjust the range of all objects
  15112. if (valueMin !== undefined && valueMax !== undefined) {
  15113. for (id in obj) {
  15114. if (obj.hasOwnProperty(id)) {
  15115. obj[id].setValueRange(valueMin, valueMax);
  15116. }
  15117. }
  15118. }
  15119. };
  15120. /**
  15121. * Redraw the graph with the current data
  15122. * chart will be resized too.
  15123. */
  15124. Graph.prototype.redraw = function() {
  15125. this.setSize(this.width, this.height);
  15126. this._redraw();
  15127. };
  15128. /**
  15129. * Redraw the graph with the current data
  15130. * @private
  15131. */
  15132. Graph.prototype._redraw = function() {
  15133. var ctx = this.frame.canvas.getContext('2d');
  15134. // clear the canvas
  15135. var w = this.frame.canvas.width;
  15136. var h = this.frame.canvas.height;
  15137. ctx.clearRect(0, 0, w, h);
  15138. // set scaling and translation
  15139. ctx.save();
  15140. ctx.translate(this.translation.x, this.translation.y);
  15141. ctx.scale(this.scale, this.scale);
  15142. this.canvasTopLeft = {
  15143. "x": this._canvasToX(0),
  15144. "y": this._canvasToY(0)
  15145. };
  15146. this.canvasBottomRight = {
  15147. "x": this._canvasToX(this.frame.canvas.clientWidth),
  15148. "y": this._canvasToY(this.frame.canvas.clientHeight)
  15149. };
  15150. this._doInAllSectors("_drawAllSectorNodes",ctx);
  15151. this._doInAllSectors("_drawEdges",ctx);
  15152. this._doInAllSectors("_drawNodes",ctx,false);
  15153. // this._doInSupportSector("_drawNodes",ctx,true);
  15154. // this._drawTree(ctx,"#F00F0F");
  15155. // restore original scaling and translation
  15156. ctx.restore();
  15157. };
  15158. /**
  15159. * Set the translation of the graph
  15160. * @param {Number} offsetX Horizontal offset
  15161. * @param {Number} offsetY Vertical offset
  15162. * @private
  15163. */
  15164. Graph.prototype._setTranslation = function(offsetX, offsetY) {
  15165. if (this.translation === undefined) {
  15166. this.translation = {
  15167. x: 0,
  15168. y: 0
  15169. };
  15170. }
  15171. if (offsetX !== undefined) {
  15172. this.translation.x = offsetX;
  15173. }
  15174. if (offsetY !== undefined) {
  15175. this.translation.y = offsetY;
  15176. }
  15177. };
  15178. /**
  15179. * Get the translation of the graph
  15180. * @return {Object} translation An object with parameters x and y, both a number
  15181. * @private
  15182. */
  15183. Graph.prototype._getTranslation = function() {
  15184. return {
  15185. x: this.translation.x,
  15186. y: this.translation.y
  15187. };
  15188. };
  15189. /**
  15190. * Scale the graph
  15191. * @param {Number} scale Scaling factor 1.0 is unscaled
  15192. * @private
  15193. */
  15194. Graph.prototype._setScale = function(scale) {
  15195. this.scale = scale;
  15196. };
  15197. /**
  15198. * Get the current scale of the graph
  15199. * @return {Number} scale Scaling factor 1.0 is unscaled
  15200. * @private
  15201. */
  15202. Graph.prototype._getScale = function() {
  15203. return this.scale;
  15204. };
  15205. /**
  15206. * Convert a horizontal point on the HTML canvas to the x-value of the model
  15207. * @param {number} x
  15208. * @returns {number}
  15209. * @private
  15210. */
  15211. Graph.prototype._canvasToX = function(x) {
  15212. return (x - this.translation.x) / this.scale;
  15213. };
  15214. /**
  15215. * Convert an x-value in the model to a horizontal point on the HTML canvas
  15216. * @param {number} x
  15217. * @returns {number}
  15218. * @private
  15219. */
  15220. Graph.prototype._xToCanvas = function(x) {
  15221. return x * this.scale + this.translation.x;
  15222. };
  15223. /**
  15224. * Convert a vertical point on the HTML canvas to the y-value of the model
  15225. * @param {number} y
  15226. * @returns {number}
  15227. * @private
  15228. */
  15229. Graph.prototype._canvasToY = function(y) {
  15230. return (y - this.translation.y) / this.scale;
  15231. };
  15232. /**
  15233. * Convert an y-value in the model to a vertical point on the HTML canvas
  15234. * @param {number} y
  15235. * @returns {number}
  15236. * @private
  15237. */
  15238. Graph.prototype._yToCanvas = function(y) {
  15239. return y * this.scale + this.translation.y ;
  15240. };
  15241. /**
  15242. * Redraw all nodes
  15243. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  15244. * @param {CanvasRenderingContext2D} ctx
  15245. * @param {Boolean} [alwaysShow]
  15246. * @private
  15247. */
  15248. Graph.prototype._drawNodes = function(ctx,alwaysShow) {
  15249. if (alwaysShow === undefined) {
  15250. alwaysShow = false;
  15251. }
  15252. // first draw the unselected nodes
  15253. var nodes = this.nodes;
  15254. var selected = [];
  15255. for (var id in nodes) {
  15256. if (nodes.hasOwnProperty(id)) {
  15257. nodes[id].setScaleAndPos(this.scale,this.canvasTopLeft,this.canvasBottomRight);
  15258. if (nodes[id].isSelected()) {
  15259. selected.push(id);
  15260. }
  15261. else {
  15262. if (nodes[id].inArea() || alwaysShow) {
  15263. nodes[id].draw(ctx);
  15264. }
  15265. }
  15266. }
  15267. }
  15268. // draw the selected nodes on top
  15269. for (var s = 0, sMax = selected.length; s < sMax; s++) {
  15270. if (nodes[selected[s]].inArea() || alwaysShow) {
  15271. nodes[selected[s]].draw(ctx);
  15272. }
  15273. }
  15274. };
  15275. /**
  15276. * Redraw all edges
  15277. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  15278. * @param {CanvasRenderingContext2D} ctx
  15279. * @private
  15280. */
  15281. Graph.prototype._drawEdges = function(ctx) {
  15282. var edges = this.edges;
  15283. for (var id in edges) {
  15284. if (edges.hasOwnProperty(id)) {
  15285. var edge = edges[id];
  15286. edge.setScale(this.scale);
  15287. if (edge.connected) {
  15288. edges[id].draw(ctx);
  15289. }
  15290. }
  15291. }
  15292. };
  15293. /**
  15294. * Find a stable position for all nodes
  15295. * @private
  15296. */
  15297. Graph.prototype._stabilize = function() {
  15298. // find stable position
  15299. var count = 0;
  15300. while (this.moving && count < this.constants.stabilizationIterations) {
  15301. this._physicsTick();
  15302. count++;
  15303. }
  15304. this.zoomExtent(false,true);
  15305. };
  15306. /**
  15307. * Check if any of the nodes is still moving
  15308. * @param {number} vmin the minimum velocity considered as 'moving'
  15309. * @return {boolean} true if moving, false if non of the nodes is moving
  15310. * @private
  15311. */
  15312. Graph.prototype._isMoving = function(vmin) {
  15313. var nodes = this.nodes;
  15314. for (var id in nodes) {
  15315. if (nodes.hasOwnProperty(id) && nodes[id].isMoving(vmin)) {
  15316. return true;
  15317. }
  15318. }
  15319. return false;
  15320. };
  15321. /**
  15322. * /**
  15323. * Perform one discrete step for all nodes
  15324. *
  15325. * @private
  15326. */
  15327. Graph.prototype._discreteStepNodes = function() {
  15328. var interval = this.physicsDiscreteStepsize;
  15329. var nodes = this.nodes;
  15330. var nodeId;
  15331. if (this.constants.maxVelocity > 0) {
  15332. for (nodeId in nodes) {
  15333. if (nodes.hasOwnProperty(nodeId)) {
  15334. nodes[nodeId].discreteStepLimited(interval, this.constants.maxVelocity);
  15335. }
  15336. }
  15337. }
  15338. else {
  15339. for (nodeId in nodes) {
  15340. if (nodes.hasOwnProperty(nodeId)) {
  15341. nodes[nodeId].discreteStep(interval);
  15342. }
  15343. }
  15344. }
  15345. var vminCorrected = this.constants.minVelocity / Math.max(this.scale,0.05);
  15346. if (vminCorrected > 0.5*this.constants.maxVelocity) {
  15347. this.moving = true;
  15348. }
  15349. else {
  15350. this.moving = this._isMoving(vminCorrected);
  15351. }
  15352. };
  15353. Graph.prototype._physicsTick = function() {
  15354. if (!this.freezeSimulation) {
  15355. if (this.moving) {
  15356. this._doInAllActiveSectors("_initializeForceCalculation");
  15357. if (this.constants.smoothCurves) {
  15358. this._doInSupportSector("_discreteStepNodes");
  15359. }
  15360. this._doInAllActiveSectors("_discreteStepNodes");
  15361. this._findCenter(this._getRange())
  15362. }
  15363. }
  15364. };
  15365. /**
  15366. * This function runs one step of the animation. It calls an x amount of physics ticks and one render tick.
  15367. * It reschedules itself at the beginning of the function
  15368. *
  15369. * @private
  15370. */
  15371. Graph.prototype._animationStep = function() {
  15372. // reset the timer so a new scheduled animation step can be set
  15373. this.timer = undefined;
  15374. // handle the keyboad movement
  15375. this._handleNavigation();
  15376. // this schedules a new animation step
  15377. this.start();
  15378. // start the physics simulation
  15379. var calculationTime = Date.now();
  15380. var maxSteps = 1;
  15381. this._physicsTick();
  15382. var timeRequired = Date.now() - calculationTime;
  15383. while (timeRequired < (this.renderTimestep - this.renderTime) && maxSteps < this.maxPhysicsTicksPerRender) {
  15384. this._physicsTick();
  15385. timeRequired = Date.now() - calculationTime;
  15386. maxSteps++;
  15387. }
  15388. // start the rendering process
  15389. var renderTime = Date.now();
  15390. this._redraw();
  15391. this.renderTime = Date.now() - renderTime;
  15392. };
  15393. if (typeof window !== 'undefined') {
  15394. window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
  15395. window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
  15396. }
  15397. /**
  15398. * Schedule a animation step with the refreshrate interval.
  15399. *
  15400. * @poram {Boolean} runCalculationStep
  15401. */
  15402. Graph.prototype.start = function() {
  15403. if (this.moving || this.xIncrement != 0 || this.yIncrement != 0 || this.zoomIncrement != 0) {
  15404. if (!this.timer) {
  15405. this.timer = window.requestAnimationFrame(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  15406. }
  15407. }
  15408. else {
  15409. this._redraw();
  15410. }
  15411. };
  15412. /**
  15413. * Move the graph according to the keyboard presses.
  15414. *
  15415. * @private
  15416. */
  15417. Graph.prototype._handleNavigation = function() {
  15418. if (this.xIncrement != 0 || this.yIncrement != 0) {
  15419. var translation = this._getTranslation();
  15420. this._setTranslation(translation.x+this.xIncrement, translation.y+this.yIncrement);
  15421. }
  15422. if (this.zoomIncrement != 0) {
  15423. var center = {
  15424. x: this.frame.canvas.clientWidth / 2,
  15425. y: this.frame.canvas.clientHeight / 2
  15426. };
  15427. this._zoom(this.scale*(1 + this.zoomIncrement), center);
  15428. }
  15429. };
  15430. /**
  15431. * Freeze the _animationStep
  15432. */
  15433. Graph.prototype.toggleFreeze = function() {
  15434. if (this.freezeSimulation == false) {
  15435. this.freezeSimulation = true;
  15436. }
  15437. else {
  15438. this.freezeSimulation = false;
  15439. this.start();
  15440. }
  15441. };
  15442. Graph.prototype._configureSmoothCurves = function(disableStart) {
  15443. if (disableStart === undefined) {
  15444. disableStart = true;
  15445. }
  15446. if (this.constants.smoothCurves == true) {
  15447. this._createBezierNodes();
  15448. }
  15449. else {
  15450. // delete the support nodes
  15451. this.sectors['support']['nodes'] = {};
  15452. for (var edgeId in this.edges) {
  15453. if (this.edges.hasOwnProperty(edgeId)) {
  15454. this.edges[edgeId].smooth = false;
  15455. this.edges[edgeId].via = null;
  15456. }
  15457. }
  15458. }
  15459. this._updateCalculationNodes();
  15460. if (!disableStart) {
  15461. this.moving = true;
  15462. this.start();
  15463. }
  15464. };
  15465. Graph.prototype._createBezierNodes = function() {
  15466. if (this.constants.smoothCurves == true) {
  15467. for (var edgeId in this.edges) {
  15468. if (this.edges.hasOwnProperty(edgeId)) {
  15469. var edge = this.edges[edgeId];
  15470. if (edge.via == null) {
  15471. edge.smooth = true;
  15472. var nodeId = "edgeId:".concat(edge.id);
  15473. this.sectors['support']['nodes'][nodeId] = new Node(
  15474. {id:nodeId,
  15475. mass:1,
  15476. shape:'circle',
  15477. internalMultiplier:1
  15478. },{},{},this.constants);
  15479. edge.via = this.sectors['support']['nodes'][nodeId];
  15480. edge.via.parentEdgeId = edge.id;
  15481. edge.positionBezierNode();
  15482. }
  15483. }
  15484. }
  15485. }
  15486. };
  15487. Graph.prototype._initializeMixinLoaders = function () {
  15488. for (var mixinFunction in graphMixinLoaders) {
  15489. if (graphMixinLoaders.hasOwnProperty(mixinFunction)) {
  15490. Graph.prototype[mixinFunction] = graphMixinLoaders[mixinFunction];
  15491. }
  15492. }
  15493. };
  15494. /**
  15495. * Load the XY positions of the nodes into the dataset.
  15496. */
  15497. Graph.prototype.storePosition = function() {
  15498. var dataArray = [];
  15499. for (var nodeId in this.nodes) {
  15500. if (this.nodes.hasOwnProperty(nodeId)) {
  15501. var node = this.nodes[nodeId];
  15502. var allowedToMoveX = !this.nodes.xFixed;
  15503. var allowedToMoveY = !this.nodes.yFixed;
  15504. if (this.nodesData.data[nodeId].x != Math.round(node.x) || this.nodesData.data[nodeId].y != Math.round(node.y)) {
  15505. dataArray.push({id:nodeId,x:Math.round(node.x),y:Math.round(node.y),allowedToMoveX:allowedToMoveX,allowedToMoveY:allowedToMoveY});
  15506. }
  15507. }
  15508. }
  15509. this.nodesData.update(dataArray);
  15510. };
  15511. /**
  15512. * vis.js module exports
  15513. */
  15514. var vis = {
  15515. util: util,
  15516. Controller: Controller,
  15517. DataSet: DataSet,
  15518. DataView: DataView,
  15519. Range: Range,
  15520. Stack: Stack,
  15521. TimeStep: TimeStep,
  15522. components: {
  15523. items: {
  15524. Item: Item,
  15525. ItemBox: ItemBox,
  15526. ItemPoint: ItemPoint,
  15527. ItemRange: ItemRange
  15528. },
  15529. Component: Component,
  15530. Panel: Panel,
  15531. RootPanel: RootPanel,
  15532. ItemSet: ItemSet,
  15533. TimeAxis: TimeAxis
  15534. },
  15535. graph: {
  15536. Node: Node,
  15537. Edge: Edge,
  15538. Popup: Popup,
  15539. Groups: Groups,
  15540. Images: Images
  15541. },
  15542. Timeline: Timeline,
  15543. Graph: Graph
  15544. };
  15545. /**
  15546. * CommonJS module exports
  15547. */
  15548. if (typeof exports !== 'undefined') {
  15549. exports = vis;
  15550. }
  15551. if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  15552. module.exports = vis;
  15553. }
  15554. /**
  15555. * AMD module exports
  15556. */
  15557. if (typeof(define) === 'function') {
  15558. define(function () {
  15559. return vis;
  15560. });
  15561. }
  15562. /**
  15563. * Window exports
  15564. */
  15565. if (typeof window !== 'undefined') {
  15566. // attach the module to the window, load as a regular javascript file
  15567. window['vis'] = vis;
  15568. }
  15569. },{"emitter-component":2,"hammerjs":3,"moment":4,"mousetrap":5}],2:[function(require,module,exports){
  15570. /**
  15571. * Expose `Emitter`.
  15572. */
  15573. module.exports = Emitter;
  15574. /**
  15575. * Initialize a new `Emitter`.
  15576. *
  15577. * @api public
  15578. */
  15579. function Emitter(obj) {
  15580. if (obj) return mixin(obj);
  15581. };
  15582. /**
  15583. * Mixin the emitter properties.
  15584. *
  15585. * @param {Object} obj
  15586. * @return {Object}
  15587. * @api private
  15588. */
  15589. function mixin(obj) {
  15590. for (var key in Emitter.prototype) {
  15591. obj[key] = Emitter.prototype[key];
  15592. }
  15593. return obj;
  15594. }
  15595. /**
  15596. * Listen on the given `event` with `fn`.
  15597. *
  15598. * @param {String} event
  15599. * @param {Function} fn
  15600. * @return {Emitter}
  15601. * @api public
  15602. */
  15603. Emitter.prototype.on =
  15604. Emitter.prototype.addEventListener = function(event, fn){
  15605. this._callbacks = this._callbacks || {};
  15606. (this._callbacks[event] = this._callbacks[event] || [])
  15607. .push(fn);
  15608. return this;
  15609. };
  15610. /**
  15611. * Adds an `event` listener that will be invoked a single
  15612. * time then automatically removed.
  15613. *
  15614. * @param {String} event
  15615. * @param {Function} fn
  15616. * @return {Emitter}
  15617. * @api public
  15618. */
  15619. Emitter.prototype.once = function(event, fn){
  15620. var self = this;
  15621. this._callbacks = this._callbacks || {};
  15622. function on() {
  15623. self.off(event, on);
  15624. fn.apply(this, arguments);
  15625. }
  15626. on.fn = fn;
  15627. this.on(event, on);
  15628. return this;
  15629. };
  15630. /**
  15631. * Remove the given callback for `event` or all
  15632. * registered callbacks.
  15633. *
  15634. * @param {String} event
  15635. * @param {Function} fn
  15636. * @return {Emitter}
  15637. * @api public
  15638. */
  15639. Emitter.prototype.off =
  15640. Emitter.prototype.removeListener =
  15641. Emitter.prototype.removeAllListeners =
  15642. Emitter.prototype.removeEventListener = function(event, fn){
  15643. this._callbacks = this._callbacks || {};
  15644. // all
  15645. if (0 == arguments.length) {
  15646. this._callbacks = {};
  15647. return this;
  15648. }
  15649. // specific event
  15650. var callbacks = this._callbacks[event];
  15651. if (!callbacks) return this;
  15652. // remove all handlers
  15653. if (1 == arguments.length) {
  15654. delete this._callbacks[event];
  15655. return this;
  15656. }
  15657. // remove specific handler
  15658. var cb;
  15659. for (var i = 0; i < callbacks.length; i++) {
  15660. cb = callbacks[i];
  15661. if (cb === fn || cb.fn === fn) {
  15662. callbacks.splice(i, 1);
  15663. break;
  15664. }
  15665. }
  15666. return this;
  15667. };
  15668. /**
  15669. * Emit `event` with the given args.
  15670. *
  15671. * @param {String} event
  15672. * @param {Mixed} ...
  15673. * @return {Emitter}
  15674. */
  15675. Emitter.prototype.emit = function(event){
  15676. this._callbacks = this._callbacks || {};
  15677. var args = [].slice.call(arguments, 1)
  15678. , callbacks = this._callbacks[event];
  15679. if (callbacks) {
  15680. callbacks = callbacks.slice(0);
  15681. for (var i = 0, len = callbacks.length; i < len; ++i) {
  15682. callbacks[i].apply(this, args);
  15683. }
  15684. }
  15685. return this;
  15686. };
  15687. /**
  15688. * Return array of callbacks for `event`.
  15689. *
  15690. * @param {String} event
  15691. * @return {Array}
  15692. * @api public
  15693. */
  15694. Emitter.prototype.listeners = function(event){
  15695. this._callbacks = this._callbacks || {};
  15696. return this._callbacks[event] || [];
  15697. };
  15698. /**
  15699. * Check if this emitter has `event` handlers.
  15700. *
  15701. * @param {String} event
  15702. * @return {Boolean}
  15703. * @api public
  15704. */
  15705. Emitter.prototype.hasListeners = function(event){
  15706. return !! this.listeners(event).length;
  15707. };
  15708. },{}],3:[function(require,module,exports){
  15709. /*! Hammer.JS - v1.0.5 - 2013-04-07
  15710. * http://eightmedia.github.com/hammer.js
  15711. *
  15712. * Copyright (c) 2013 Jorik Tangelder <j.tangelder@gmail.com>;
  15713. * Licensed under the MIT license */
  15714. (function(window, undefined) {
  15715. 'use strict';
  15716. /**
  15717. * Hammer
  15718. * use this to create instances
  15719. * @param {HTMLElement} element
  15720. * @param {Object} options
  15721. * @returns {Hammer.Instance}
  15722. * @constructor
  15723. */
  15724. var Hammer = function(element, options) {
  15725. return new Hammer.Instance(element, options || {});
  15726. };
  15727. // default settings
  15728. Hammer.defaults = {
  15729. // add styles and attributes to the element to prevent the browser from doing
  15730. // its native behavior. this doesnt prevent the scrolling, but cancels
  15731. // the contextmenu, tap highlighting etc
  15732. // set to false to disable this
  15733. stop_browser_behavior: {
  15734. // this also triggers onselectstart=false for IE
  15735. userSelect: 'none',
  15736. // this makes the element blocking in IE10 >, you could experiment with the value
  15737. // see for more options this issue; https://github.com/EightMedia/hammer.js/issues/241
  15738. touchAction: 'none',
  15739. touchCallout: 'none',
  15740. contentZooming: 'none',
  15741. userDrag: 'none',
  15742. tapHighlightColor: 'rgba(0,0,0,0)'
  15743. }
  15744. // more settings are defined per gesture at gestures.js
  15745. };
  15746. // detect touchevents
  15747. Hammer.HAS_POINTEREVENTS = navigator.pointerEnabled || navigator.msPointerEnabled;
  15748. Hammer.HAS_TOUCHEVENTS = ('ontouchstart' in window);
  15749. // dont use mouseevents on mobile devices
  15750. Hammer.MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;
  15751. Hammer.NO_MOUSEEVENTS = Hammer.HAS_TOUCHEVENTS && navigator.userAgent.match(Hammer.MOBILE_REGEX);
  15752. // eventtypes per touchevent (start, move, end)
  15753. // are filled by Hammer.event.determineEventTypes on setup
  15754. Hammer.EVENT_TYPES = {};
  15755. // direction defines
  15756. Hammer.DIRECTION_DOWN = 'down';
  15757. Hammer.DIRECTION_LEFT = 'left';
  15758. Hammer.DIRECTION_UP = 'up';
  15759. Hammer.DIRECTION_RIGHT = 'right';
  15760. // pointer type
  15761. Hammer.POINTER_MOUSE = 'mouse';
  15762. Hammer.POINTER_TOUCH = 'touch';
  15763. Hammer.POINTER_PEN = 'pen';
  15764. // touch event defines
  15765. Hammer.EVENT_START = 'start';
  15766. Hammer.EVENT_MOVE = 'move';
  15767. Hammer.EVENT_END = 'end';
  15768. // hammer document where the base events are added at
  15769. Hammer.DOCUMENT = document;
  15770. // plugins namespace
  15771. Hammer.plugins = {};
  15772. // if the window events are set...
  15773. Hammer.READY = false;
  15774. /**
  15775. * setup events to detect gestures on the document
  15776. */
  15777. function setup() {
  15778. if(Hammer.READY) {
  15779. return;
  15780. }
  15781. // find what eventtypes we add listeners to
  15782. Hammer.event.determineEventTypes();
  15783. // Register all gestures inside Hammer.gestures
  15784. for(var name in Hammer.gestures) {
  15785. if(Hammer.gestures.hasOwnProperty(name)) {
  15786. Hammer.detection.register(Hammer.gestures[name]);
  15787. }
  15788. }
  15789. // Add touch events on the document
  15790. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_MOVE, Hammer.detection.detect);
  15791. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_END, Hammer.detection.detect);
  15792. // Hammer is ready...!
  15793. Hammer.READY = true;
  15794. }
  15795. /**
  15796. * create new hammer instance
  15797. * all methods should return the instance itself, so it is chainable.
  15798. * @param {HTMLElement} element
  15799. * @param {Object} [options={}]
  15800. * @returns {Hammer.Instance}
  15801. * @constructor
  15802. */
  15803. Hammer.Instance = function(element, options) {
  15804. var self = this;
  15805. // setup HammerJS window events and register all gestures
  15806. // this also sets up the default options
  15807. setup();
  15808. this.element = element;
  15809. // start/stop detection option
  15810. this.enabled = true;
  15811. // merge options
  15812. this.options = Hammer.utils.extend(
  15813. Hammer.utils.extend({}, Hammer.defaults),
  15814. options || {});
  15815. // add some css to the element to prevent the browser from doing its native behavoir
  15816. if(this.options.stop_browser_behavior) {
  15817. Hammer.utils.stopDefaultBrowserBehavior(this.element, this.options.stop_browser_behavior);
  15818. }
  15819. // start detection on touchstart
  15820. Hammer.event.onTouch(element, Hammer.EVENT_START, function(ev) {
  15821. if(self.enabled) {
  15822. Hammer.detection.startDetect(self, ev);
  15823. }
  15824. });
  15825. // return instance
  15826. return this;
  15827. };
  15828. Hammer.Instance.prototype = {
  15829. /**
  15830. * bind events to the instance
  15831. * @param {String} gesture
  15832. * @param {Function} handler
  15833. * @returns {Hammer.Instance}
  15834. */
  15835. on: function onEvent(gesture, handler){
  15836. var gestures = gesture.split(' ');
  15837. for(var t=0; t<gestures.length; t++) {
  15838. this.element.addEventListener(gestures[t], handler, false);
  15839. }
  15840. return this;
  15841. },
  15842. /**
  15843. * unbind events to the instance
  15844. * @param {String} gesture
  15845. * @param {Function} handler
  15846. * @returns {Hammer.Instance}
  15847. */
  15848. off: function offEvent(gesture, handler){
  15849. var gestures = gesture.split(' ');
  15850. for(var t=0; t<gestures.length; t++) {
  15851. this.element.removeEventListener(gestures[t], handler, false);
  15852. }
  15853. return this;
  15854. },
  15855. /**
  15856. * trigger gesture event
  15857. * @param {String} gesture
  15858. * @param {Object} eventData
  15859. * @returns {Hammer.Instance}
  15860. */
  15861. trigger: function triggerEvent(gesture, eventData){
  15862. // create DOM event
  15863. var event = Hammer.DOCUMENT.createEvent('Event');
  15864. event.initEvent(gesture, true, true);
  15865. event.gesture = eventData;
  15866. // trigger on the target if it is in the instance element,
  15867. // this is for event delegation tricks
  15868. var element = this.element;
  15869. if(Hammer.utils.hasParent(eventData.target, element)) {
  15870. element = eventData.target;
  15871. }
  15872. element.dispatchEvent(event);
  15873. return this;
  15874. },
  15875. /**
  15876. * enable of disable hammer.js detection
  15877. * @param {Boolean} state
  15878. * @returns {Hammer.Instance}
  15879. */
  15880. enable: function enable(state) {
  15881. this.enabled = state;
  15882. return this;
  15883. }
  15884. };
  15885. /**
  15886. * this holds the last move event,
  15887. * used to fix empty touchend issue
  15888. * see the onTouch event for an explanation
  15889. * @type {Object}
  15890. */
  15891. var last_move_event = null;
  15892. /**
  15893. * when the mouse is hold down, this is true
  15894. * @type {Boolean}
  15895. */
  15896. var enable_detect = false;
  15897. /**
  15898. * when touch events have been fired, this is true
  15899. * @type {Boolean}
  15900. */
  15901. var touch_triggered = false;
  15902. Hammer.event = {
  15903. /**
  15904. * simple addEventListener
  15905. * @param {HTMLElement} element
  15906. * @param {String} type
  15907. * @param {Function} handler
  15908. */
  15909. bindDom: function(element, type, handler) {
  15910. var types = type.split(' ');
  15911. for(var t=0; t<types.length; t++) {
  15912. element.addEventListener(types[t], handler, false);
  15913. }
  15914. },
  15915. /**
  15916. * touch events with mouse fallback
  15917. * @param {HTMLElement} element
  15918. * @param {String} eventType like Hammer.EVENT_MOVE
  15919. * @param {Function} handler
  15920. */
  15921. onTouch: function onTouch(element, eventType, handler) {
  15922. var self = this;
  15923. this.bindDom(element, Hammer.EVENT_TYPES[eventType], function bindDomOnTouch(ev) {
  15924. var sourceEventType = ev.type.toLowerCase();
  15925. // onmouseup, but when touchend has been fired we do nothing.
  15926. // this is for touchdevices which also fire a mouseup on touchend
  15927. if(sourceEventType.match(/mouse/) && touch_triggered) {
  15928. return;
  15929. }
  15930. // mousebutton must be down or a touch event
  15931. else if( sourceEventType.match(/touch/) || // touch events are always on screen
  15932. sourceEventType.match(/pointerdown/) || // pointerevents touch
  15933. (sourceEventType.match(/mouse/) && ev.which === 1) // mouse is pressed
  15934. ){
  15935. enable_detect = true;
  15936. }
  15937. // we are in a touch event, set the touch triggered bool to true,
  15938. // this for the conflicts that may occur on ios and android
  15939. if(sourceEventType.match(/touch|pointer/)) {
  15940. touch_triggered = true;
  15941. }
  15942. // count the total touches on the screen
  15943. var count_touches = 0;
  15944. // when touch has been triggered in this detection session
  15945. // and we are now handling a mouse event, we stop that to prevent conflicts
  15946. if(enable_detect) {
  15947. // update pointerevent
  15948. if(Hammer.HAS_POINTEREVENTS && eventType != Hammer.EVENT_END) {
  15949. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  15950. }
  15951. // touch
  15952. else if(sourceEventType.match(/touch/)) {
  15953. count_touches = ev.touches.length;
  15954. }
  15955. // mouse
  15956. else if(!touch_triggered) {
  15957. count_touches = sourceEventType.match(/up/) ? 0 : 1;
  15958. }
  15959. // if we are in a end event, but when we remove one touch and
  15960. // we still have enough, set eventType to move
  15961. if(count_touches > 0 && eventType == Hammer.EVENT_END) {
  15962. eventType = Hammer.EVENT_MOVE;
  15963. }
  15964. // no touches, force the end event
  15965. else if(!count_touches) {
  15966. eventType = Hammer.EVENT_END;
  15967. }
  15968. // because touchend has no touches, and we often want to use these in our gestures,
  15969. // we send the last move event as our eventData in touchend
  15970. if(!count_touches && last_move_event !== null) {
  15971. ev = last_move_event;
  15972. }
  15973. // store the last move event
  15974. else {
  15975. last_move_event = ev;
  15976. }
  15977. // trigger the handler
  15978. handler.call(Hammer.detection, self.collectEventData(element, eventType, ev));
  15979. // remove pointerevent from list
  15980. if(Hammer.HAS_POINTEREVENTS && eventType == Hammer.EVENT_END) {
  15981. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  15982. }
  15983. }
  15984. //debug(sourceEventType +" "+ eventType);
  15985. // on the end we reset everything
  15986. if(!count_touches) {
  15987. last_move_event = null;
  15988. enable_detect = false;
  15989. touch_triggered = false;
  15990. Hammer.PointerEvent.reset();
  15991. }
  15992. });
  15993. },
  15994. /**
  15995. * we have different events for each device/browser
  15996. * determine what we need and set them in the Hammer.EVENT_TYPES constant
  15997. */
  15998. determineEventTypes: function determineEventTypes() {
  15999. // determine the eventtype we want to set
  16000. var types;
  16001. // pointerEvents magic
  16002. if(Hammer.HAS_POINTEREVENTS) {
  16003. types = Hammer.PointerEvent.getEvents();
  16004. }
  16005. // on Android, iOS, blackberry, windows mobile we dont want any mouseevents
  16006. else if(Hammer.NO_MOUSEEVENTS) {
  16007. types = [
  16008. 'touchstart',
  16009. 'touchmove',
  16010. 'touchend touchcancel'];
  16011. }
  16012. // for non pointer events browsers and mixed browsers,
  16013. // like chrome on windows8 touch laptop
  16014. else {
  16015. types = [
  16016. 'touchstart mousedown',
  16017. 'touchmove mousemove',
  16018. 'touchend touchcancel mouseup'];
  16019. }
  16020. Hammer.EVENT_TYPES[Hammer.EVENT_START] = types[0];
  16021. Hammer.EVENT_TYPES[Hammer.EVENT_MOVE] = types[1];
  16022. Hammer.EVENT_TYPES[Hammer.EVENT_END] = types[2];
  16023. },
  16024. /**
  16025. * create touchlist depending on the event
  16026. * @param {Object} ev
  16027. * @param {String} eventType used by the fakemultitouch plugin
  16028. */
  16029. getTouchList: function getTouchList(ev/*, eventType*/) {
  16030. // get the fake pointerEvent touchlist
  16031. if(Hammer.HAS_POINTEREVENTS) {
  16032. return Hammer.PointerEvent.getTouchList();
  16033. }
  16034. // get the touchlist
  16035. else if(ev.touches) {
  16036. return ev.touches;
  16037. }
  16038. // make fake touchlist from mouse position
  16039. else {
  16040. return [{
  16041. identifier: 1,
  16042. pageX: ev.pageX,
  16043. pageY: ev.pageY,
  16044. target: ev.target
  16045. }];
  16046. }
  16047. },
  16048. /**
  16049. * collect event data for Hammer js
  16050. * @param {HTMLElement} element
  16051. * @param {String} eventType like Hammer.EVENT_MOVE
  16052. * @param {Object} eventData
  16053. */
  16054. collectEventData: function collectEventData(element, eventType, ev) {
  16055. var touches = this.getTouchList(ev, eventType);
  16056. // find out pointerType
  16057. var pointerType = Hammer.POINTER_TOUCH;
  16058. if(ev.type.match(/mouse/) || Hammer.PointerEvent.matchType(Hammer.POINTER_MOUSE, ev)) {
  16059. pointerType = Hammer.POINTER_MOUSE;
  16060. }
  16061. return {
  16062. center : Hammer.utils.getCenter(touches),
  16063. timeStamp : new Date().getTime(),
  16064. target : ev.target,
  16065. touches : touches,
  16066. eventType : eventType,
  16067. pointerType : pointerType,
  16068. srcEvent : ev,
  16069. /**
  16070. * prevent the browser default actions
  16071. * mostly used to disable scrolling of the browser
  16072. */
  16073. preventDefault: function() {
  16074. if(this.srcEvent.preventManipulation) {
  16075. this.srcEvent.preventManipulation();
  16076. }
  16077. if(this.srcEvent.preventDefault) {
  16078. this.srcEvent.preventDefault();
  16079. }
  16080. },
  16081. /**
  16082. * stop bubbling the event up to its parents
  16083. */
  16084. stopPropagation: function() {
  16085. this.srcEvent.stopPropagation();
  16086. },
  16087. /**
  16088. * immediately stop gesture detection
  16089. * might be useful after a swipe was detected
  16090. * @return {*}
  16091. */
  16092. stopDetect: function() {
  16093. return Hammer.detection.stopDetect();
  16094. }
  16095. };
  16096. }
  16097. };
  16098. Hammer.PointerEvent = {
  16099. /**
  16100. * holds all pointers
  16101. * @type {Object}
  16102. */
  16103. pointers: {},
  16104. /**
  16105. * get a list of pointers
  16106. * @returns {Array} touchlist
  16107. */
  16108. getTouchList: function() {
  16109. var self = this;
  16110. var touchlist = [];
  16111. // we can use forEach since pointerEvents only is in IE10
  16112. Object.keys(self.pointers).sort().forEach(function(id) {
  16113. touchlist.push(self.pointers[id]);
  16114. });
  16115. return touchlist;
  16116. },
  16117. /**
  16118. * update the position of a pointer
  16119. * @param {String} type Hammer.EVENT_END
  16120. * @param {Object} pointerEvent
  16121. */
  16122. updatePointer: function(type, pointerEvent) {
  16123. if(type == Hammer.EVENT_END) {
  16124. this.pointers = {};
  16125. }
  16126. else {
  16127. pointerEvent.identifier = pointerEvent.pointerId;
  16128. this.pointers[pointerEvent.pointerId] = pointerEvent;
  16129. }
  16130. return Object.keys(this.pointers).length;
  16131. },
  16132. /**
  16133. * check if ev matches pointertype
  16134. * @param {String} pointerType Hammer.POINTER_MOUSE
  16135. * @param {PointerEvent} ev
  16136. */
  16137. matchType: function(pointerType, ev) {
  16138. if(!ev.pointerType) {
  16139. return false;
  16140. }
  16141. var types = {};
  16142. types[Hammer.POINTER_MOUSE] = (ev.pointerType == ev.MSPOINTER_TYPE_MOUSE || ev.pointerType == Hammer.POINTER_MOUSE);
  16143. types[Hammer.POINTER_TOUCH] = (ev.pointerType == ev.MSPOINTER_TYPE_TOUCH || ev.pointerType == Hammer.POINTER_TOUCH);
  16144. types[Hammer.POINTER_PEN] = (ev.pointerType == ev.MSPOINTER_TYPE_PEN || ev.pointerType == Hammer.POINTER_PEN);
  16145. return types[pointerType];
  16146. },
  16147. /**
  16148. * get events
  16149. */
  16150. getEvents: function() {
  16151. return [
  16152. 'pointerdown MSPointerDown',
  16153. 'pointermove MSPointerMove',
  16154. 'pointerup pointercancel MSPointerUp MSPointerCancel'
  16155. ];
  16156. },
  16157. /**
  16158. * reset the list
  16159. */
  16160. reset: function() {
  16161. this.pointers = {};
  16162. }
  16163. };
  16164. Hammer.utils = {
  16165. /**
  16166. * extend method,
  16167. * also used for cloning when dest is an empty object
  16168. * @param {Object} dest
  16169. * @param {Object} src
  16170. * @parm {Boolean} merge do a merge
  16171. * @returns {Object} dest
  16172. */
  16173. extend: function extend(dest, src, merge) {
  16174. for (var key in src) {
  16175. if(dest[key] !== undefined && merge) {
  16176. continue;
  16177. }
  16178. dest[key] = src[key];
  16179. }
  16180. return dest;
  16181. },
  16182. /**
  16183. * find if a node is in the given parent
  16184. * used for event delegation tricks
  16185. * @param {HTMLElement} node
  16186. * @param {HTMLElement} parent
  16187. * @returns {boolean} has_parent
  16188. */
  16189. hasParent: function(node, parent) {
  16190. while(node){
  16191. if(node == parent) {
  16192. return true;
  16193. }
  16194. node = node.parentNode;
  16195. }
  16196. return false;
  16197. },
  16198. /**
  16199. * get the center of all the touches
  16200. * @param {Array} touches
  16201. * @returns {Object} center
  16202. */
  16203. getCenter: function getCenter(touches) {
  16204. var valuesX = [], valuesY = [];
  16205. for(var t= 0,len=touches.length; t<len; t++) {
  16206. valuesX.push(touches[t].pageX);
  16207. valuesY.push(touches[t].pageY);
  16208. }
  16209. return {
  16210. pageX: ((Math.min.apply(Math, valuesX) + Math.max.apply(Math, valuesX)) / 2),
  16211. pageY: ((Math.min.apply(Math, valuesY) + Math.max.apply(Math, valuesY)) / 2)
  16212. };
  16213. },
  16214. /**
  16215. * calculate the velocity between two points
  16216. * @param {Number} delta_time
  16217. * @param {Number} delta_x
  16218. * @param {Number} delta_y
  16219. * @returns {Object} velocity
  16220. */
  16221. getVelocity: function getVelocity(delta_time, delta_x, delta_y) {
  16222. return {
  16223. x: Math.abs(delta_x / delta_time) || 0,
  16224. y: Math.abs(delta_y / delta_time) || 0
  16225. };
  16226. },
  16227. /**
  16228. * calculate the angle between two coordinates
  16229. * @param {Touch} touch1
  16230. * @param {Touch} touch2
  16231. * @returns {Number} angle
  16232. */
  16233. getAngle: function getAngle(touch1, touch2) {
  16234. var y = touch2.pageY - touch1.pageY,
  16235. x = touch2.pageX - touch1.pageX;
  16236. return Math.atan2(y, x) * 180 / Math.PI;
  16237. },
  16238. /**
  16239. * angle to direction define
  16240. * @param {Touch} touch1
  16241. * @param {Touch} touch2
  16242. * @returns {String} direction constant, like Hammer.DIRECTION_LEFT
  16243. */
  16244. getDirection: function getDirection(touch1, touch2) {
  16245. var x = Math.abs(touch1.pageX - touch2.pageX),
  16246. y = Math.abs(touch1.pageY - touch2.pageY);
  16247. if(x >= y) {
  16248. return touch1.pageX - touch2.pageX > 0 ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  16249. }
  16250. else {
  16251. return touch1.pageY - touch2.pageY > 0 ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  16252. }
  16253. },
  16254. /**
  16255. * calculate the distance between two touches
  16256. * @param {Touch} touch1
  16257. * @param {Touch} touch2
  16258. * @returns {Number} distance
  16259. */
  16260. getDistance: function getDistance(touch1, touch2) {
  16261. var x = touch2.pageX - touch1.pageX,
  16262. y = touch2.pageY - touch1.pageY;
  16263. return Math.sqrt((x*x) + (y*y));
  16264. },
  16265. /**
  16266. * calculate the scale factor between two touchLists (fingers)
  16267. * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
  16268. * @param {Array} start
  16269. * @param {Array} end
  16270. * @returns {Number} scale
  16271. */
  16272. getScale: function getScale(start, end) {
  16273. // need two fingers...
  16274. if(start.length >= 2 && end.length >= 2) {
  16275. return this.getDistance(end[0], end[1]) /
  16276. this.getDistance(start[0], start[1]);
  16277. }
  16278. return 1;
  16279. },
  16280. /**
  16281. * calculate the rotation degrees between two touchLists (fingers)
  16282. * @param {Array} start
  16283. * @param {Array} end
  16284. * @returns {Number} rotation
  16285. */
  16286. getRotation: function getRotation(start, end) {
  16287. // need two fingers
  16288. if(start.length >= 2 && end.length >= 2) {
  16289. return this.getAngle(end[1], end[0]) -
  16290. this.getAngle(start[1], start[0]);
  16291. }
  16292. return 0;
  16293. },
  16294. /**
  16295. * boolean if the direction is vertical
  16296. * @param {String} direction
  16297. * @returns {Boolean} is_vertical
  16298. */
  16299. isVertical: function isVertical(direction) {
  16300. return (direction == Hammer.DIRECTION_UP || direction == Hammer.DIRECTION_DOWN);
  16301. },
  16302. /**
  16303. * stop browser default behavior with css props
  16304. * @param {HtmlElement} element
  16305. * @param {Object} css_props
  16306. */
  16307. stopDefaultBrowserBehavior: function stopDefaultBrowserBehavior(element, css_props) {
  16308. var prop,
  16309. vendors = ['webkit','khtml','moz','ms','o',''];
  16310. if(!css_props || !element.style) {
  16311. return;
  16312. }
  16313. // with css properties for modern browsers
  16314. for(var i = 0; i < vendors.length; i++) {
  16315. for(var p in css_props) {
  16316. if(css_props.hasOwnProperty(p)) {
  16317. prop = p;
  16318. // vender prefix at the property
  16319. if(vendors[i]) {
  16320. prop = vendors[i] + prop.substring(0, 1).toUpperCase() + prop.substring(1);
  16321. }
  16322. // set the style
  16323. element.style[prop] = css_props[p];
  16324. }
  16325. }
  16326. }
  16327. // also the disable onselectstart
  16328. if(css_props.userSelect == 'none') {
  16329. element.onselectstart = function() {
  16330. return false;
  16331. };
  16332. }
  16333. }
  16334. };
  16335. Hammer.detection = {
  16336. // contains all registred Hammer.gestures in the correct order
  16337. gestures: [],
  16338. // data of the current Hammer.gesture detection session
  16339. current: null,
  16340. // the previous Hammer.gesture session data
  16341. // is a full clone of the previous gesture.current object
  16342. previous: null,
  16343. // when this becomes true, no gestures are fired
  16344. stopped: false,
  16345. /**
  16346. * start Hammer.gesture detection
  16347. * @param {Hammer.Instance} inst
  16348. * @param {Object} eventData
  16349. */
  16350. startDetect: function startDetect(inst, eventData) {
  16351. // already busy with a Hammer.gesture detection on an element
  16352. if(this.current) {
  16353. return;
  16354. }
  16355. this.stopped = false;
  16356. this.current = {
  16357. inst : inst, // reference to HammerInstance we're working for
  16358. startEvent : Hammer.utils.extend({}, eventData), // start eventData for distances, timing etc
  16359. lastEvent : false, // last eventData
  16360. name : '' // current gesture we're in/detected, can be 'tap', 'hold' etc
  16361. };
  16362. this.detect(eventData);
  16363. },
  16364. /**
  16365. * Hammer.gesture detection
  16366. * @param {Object} eventData
  16367. * @param {Object} eventData
  16368. */
  16369. detect: function detect(eventData) {
  16370. if(!this.current || this.stopped) {
  16371. return;
  16372. }
  16373. // extend event data with calculations about scale, distance etc
  16374. eventData = this.extendEventData(eventData);
  16375. // instance options
  16376. var inst_options = this.current.inst.options;
  16377. // call Hammer.gesture handlers
  16378. for(var g=0,len=this.gestures.length; g<len; g++) {
  16379. var gesture = this.gestures[g];
  16380. // only when the instance options have enabled this gesture
  16381. if(!this.stopped && inst_options[gesture.name] !== false) {
  16382. // if a handler returns false, we stop with the detection
  16383. if(gesture.handler.call(gesture, eventData, this.current.inst) === false) {
  16384. this.stopDetect();
  16385. break;
  16386. }
  16387. }
  16388. }
  16389. // store as previous event event
  16390. if(this.current) {
  16391. this.current.lastEvent = eventData;
  16392. }
  16393. // endevent, but not the last touch, so dont stop
  16394. if(eventData.eventType == Hammer.EVENT_END && !eventData.touches.length-1) {
  16395. this.stopDetect();
  16396. }
  16397. return eventData;
  16398. },
  16399. /**
  16400. * clear the Hammer.gesture vars
  16401. * this is called on endDetect, but can also be used when a final Hammer.gesture has been detected
  16402. * to stop other Hammer.gestures from being fired
  16403. */
  16404. stopDetect: function stopDetect() {
  16405. // clone current data to the store as the previous gesture
  16406. // used for the double tap gesture, since this is an other gesture detect session
  16407. this.previous = Hammer.utils.extend({}, this.current);
  16408. // reset the current
  16409. this.current = null;
  16410. // stopped!
  16411. this.stopped = true;
  16412. },
  16413. /**
  16414. * extend eventData for Hammer.gestures
  16415. * @param {Object} ev
  16416. * @returns {Object} ev
  16417. */
  16418. extendEventData: function extendEventData(ev) {
  16419. var startEv = this.current.startEvent;
  16420. // if the touches change, set the new touches over the startEvent touches
  16421. // this because touchevents don't have all the touches on touchstart, or the
  16422. // user must place his fingers at the EXACT same time on the screen, which is not realistic
  16423. // but, sometimes it happens that both fingers are touching at the EXACT same time
  16424. if(startEv && (ev.touches.length != startEv.touches.length || ev.touches === startEv.touches)) {
  16425. // extend 1 level deep to get the touchlist with the touch objects
  16426. startEv.touches = [];
  16427. for(var i=0,len=ev.touches.length; i<len; i++) {
  16428. startEv.touches.push(Hammer.utils.extend({}, ev.touches[i]));
  16429. }
  16430. }
  16431. var delta_time = ev.timeStamp - startEv.timeStamp,
  16432. delta_x = ev.center.pageX - startEv.center.pageX,
  16433. delta_y = ev.center.pageY - startEv.center.pageY,
  16434. velocity = Hammer.utils.getVelocity(delta_time, delta_x, delta_y);
  16435. Hammer.utils.extend(ev, {
  16436. deltaTime : delta_time,
  16437. deltaX : delta_x,
  16438. deltaY : delta_y,
  16439. velocityX : velocity.x,
  16440. velocityY : velocity.y,
  16441. distance : Hammer.utils.getDistance(startEv.center, ev.center),
  16442. angle : Hammer.utils.getAngle(startEv.center, ev.center),
  16443. direction : Hammer.utils.getDirection(startEv.center, ev.center),
  16444. scale : Hammer.utils.getScale(startEv.touches, ev.touches),
  16445. rotation : Hammer.utils.getRotation(startEv.touches, ev.touches),
  16446. startEvent : startEv
  16447. });
  16448. return ev;
  16449. },
  16450. /**
  16451. * register new gesture
  16452. * @param {Object} gesture object, see gestures.js for documentation
  16453. * @returns {Array} gestures
  16454. */
  16455. register: function register(gesture) {
  16456. // add an enable gesture options if there is no given
  16457. var options = gesture.defaults || {};
  16458. if(options[gesture.name] === undefined) {
  16459. options[gesture.name] = true;
  16460. }
  16461. // extend Hammer default options with the Hammer.gesture options
  16462. Hammer.utils.extend(Hammer.defaults, options, true);
  16463. // set its index
  16464. gesture.index = gesture.index || 1000;
  16465. // add Hammer.gesture to the list
  16466. this.gestures.push(gesture);
  16467. // sort the list by index
  16468. this.gestures.sort(function(a, b) {
  16469. if (a.index < b.index) {
  16470. return -1;
  16471. }
  16472. if (a.index > b.index) {
  16473. return 1;
  16474. }
  16475. return 0;
  16476. });
  16477. return this.gestures;
  16478. }
  16479. };
  16480. Hammer.gestures = Hammer.gestures || {};
  16481. /**
  16482. * Custom gestures
  16483. * ==============================
  16484. *
  16485. * Gesture object
  16486. * --------------------
  16487. * The object structure of a gesture:
  16488. *
  16489. * { name: 'mygesture',
  16490. * index: 1337,
  16491. * defaults: {
  16492. * mygesture_option: true
  16493. * }
  16494. * handler: function(type, ev, inst) {
  16495. * // trigger gesture event
  16496. * inst.trigger(this.name, ev);
  16497. * }
  16498. * }
  16499. * @param {String} name
  16500. * this should be the name of the gesture, lowercase
  16501. * it is also being used to disable/enable the gesture per instance config.
  16502. *
  16503. * @param {Number} [index=1000]
  16504. * the index of the gesture, where it is going to be in the stack of gestures detection
  16505. * like when you build an gesture that depends on the drag gesture, it is a good
  16506. * idea to place it after the index of the drag gesture.
  16507. *
  16508. * @param {Object} [defaults={}]
  16509. * the default settings of the gesture. these are added to the instance settings,
  16510. * and can be overruled per instance. you can also add the name of the gesture,
  16511. * but this is also added by default (and set to true).
  16512. *
  16513. * @param {Function} handler
  16514. * this handles the gesture detection of your custom gesture and receives the
  16515. * following arguments:
  16516. *
  16517. * @param {Object} eventData
  16518. * event data containing the following properties:
  16519. * timeStamp {Number} time the event occurred
  16520. * target {HTMLElement} target element
  16521. * touches {Array} touches (fingers, pointers, mouse) on the screen
  16522. * pointerType {String} kind of pointer that was used. matches Hammer.POINTER_MOUSE|TOUCH
  16523. * center {Object} center position of the touches. contains pageX and pageY
  16524. * deltaTime {Number} the total time of the touches in the screen
  16525. * deltaX {Number} the delta on x axis we haved moved
  16526. * deltaY {Number} the delta on y axis we haved moved
  16527. * velocityX {Number} the velocity on the x
  16528. * velocityY {Number} the velocity on y
  16529. * angle {Number} the angle we are moving
  16530. * direction {String} the direction we are moving. matches Hammer.DIRECTION_UP|DOWN|LEFT|RIGHT
  16531. * distance {Number} the distance we haved moved
  16532. * scale {Number} scaling of the touches, needs 2 touches
  16533. * rotation {Number} rotation of the touches, needs 2 touches *
  16534. * eventType {String} matches Hammer.EVENT_START|MOVE|END
  16535. * srcEvent {Object} the source event, like TouchStart or MouseDown *
  16536. * startEvent {Object} contains the same properties as above,
  16537. * but from the first touch. this is used to calculate
  16538. * distances, deltaTime, scaling etc
  16539. *
  16540. * @param {Hammer.Instance} inst
  16541. * the instance we are doing the detection for. you can get the options from
  16542. * the inst.options object and trigger the gesture event by calling inst.trigger
  16543. *
  16544. *
  16545. * Handle gestures
  16546. * --------------------
  16547. * inside the handler you can get/set Hammer.detection.current. This is the current
  16548. * detection session. It has the following properties
  16549. * @param {String} name
  16550. * contains the name of the gesture we have detected. it has not a real function,
  16551. * only to check in other gestures if something is detected.
  16552. * like in the drag gesture we set it to 'drag' and in the swipe gesture we can
  16553. * check if the current gesture is 'drag' by accessing Hammer.detection.current.name
  16554. *
  16555. * @readonly
  16556. * @param {Hammer.Instance} inst
  16557. * the instance we do the detection for
  16558. *
  16559. * @readonly
  16560. * @param {Object} startEvent
  16561. * contains the properties of the first gesture detection in this session.
  16562. * Used for calculations about timing, distance, etc.
  16563. *
  16564. * @readonly
  16565. * @param {Object} lastEvent
  16566. * contains all the properties of the last gesture detect in this session.
  16567. *
  16568. * after the gesture detection session has been completed (user has released the screen)
  16569. * the Hammer.detection.current object is copied into Hammer.detection.previous,
  16570. * this is usefull for gestures like doubletap, where you need to know if the
  16571. * previous gesture was a tap
  16572. *
  16573. * options that have been set by the instance can be received by calling inst.options
  16574. *
  16575. * You can trigger a gesture event by calling inst.trigger("mygesture", event).
  16576. * The first param is the name of your gesture, the second the event argument
  16577. *
  16578. *
  16579. * Register gestures
  16580. * --------------------
  16581. * When an gesture is added to the Hammer.gestures object, it is auto registered
  16582. * at the setup of the first Hammer instance. You can also call Hammer.detection.register
  16583. * manually and pass your gesture object as a param
  16584. *
  16585. */
  16586. /**
  16587. * Hold
  16588. * Touch stays at the same place for x time
  16589. * @events hold
  16590. */
  16591. Hammer.gestures.Hold = {
  16592. name: 'hold',
  16593. index: 10,
  16594. defaults: {
  16595. hold_timeout : 500,
  16596. hold_threshold : 1
  16597. },
  16598. timer: null,
  16599. handler: function holdGesture(ev, inst) {
  16600. switch(ev.eventType) {
  16601. case Hammer.EVENT_START:
  16602. // clear any running timers
  16603. clearTimeout(this.timer);
  16604. // set the gesture so we can check in the timeout if it still is
  16605. Hammer.detection.current.name = this.name;
  16606. // set timer and if after the timeout it still is hold,
  16607. // we trigger the hold event
  16608. this.timer = setTimeout(function() {
  16609. if(Hammer.detection.current.name == 'hold') {
  16610. inst.trigger('hold', ev);
  16611. }
  16612. }, inst.options.hold_timeout);
  16613. break;
  16614. // when you move or end we clear the timer
  16615. case Hammer.EVENT_MOVE:
  16616. if(ev.distance > inst.options.hold_threshold) {
  16617. clearTimeout(this.timer);
  16618. }
  16619. break;
  16620. case Hammer.EVENT_END:
  16621. clearTimeout(this.timer);
  16622. break;
  16623. }
  16624. }
  16625. };
  16626. /**
  16627. * Tap/DoubleTap
  16628. * Quick touch at a place or double at the same place
  16629. * @events tap, doubletap
  16630. */
  16631. Hammer.gestures.Tap = {
  16632. name: 'tap',
  16633. index: 100,
  16634. defaults: {
  16635. tap_max_touchtime : 250,
  16636. tap_max_distance : 10,
  16637. tap_always : true,
  16638. doubletap_distance : 20,
  16639. doubletap_interval : 300
  16640. },
  16641. handler: function tapGesture(ev, inst) {
  16642. if(ev.eventType == Hammer.EVENT_END) {
  16643. // previous gesture, for the double tap since these are two different gesture detections
  16644. var prev = Hammer.detection.previous,
  16645. did_doubletap = false;
  16646. // when the touchtime is higher then the max touch time
  16647. // or when the moving distance is too much
  16648. if(ev.deltaTime > inst.options.tap_max_touchtime ||
  16649. ev.distance > inst.options.tap_max_distance) {
  16650. return;
  16651. }
  16652. // check if double tap
  16653. if(prev && prev.name == 'tap' &&
  16654. (ev.timeStamp - prev.lastEvent.timeStamp) < inst.options.doubletap_interval &&
  16655. ev.distance < inst.options.doubletap_distance) {
  16656. inst.trigger('doubletap', ev);
  16657. did_doubletap = true;
  16658. }
  16659. // do a single tap
  16660. if(!did_doubletap || inst.options.tap_always) {
  16661. Hammer.detection.current.name = 'tap';
  16662. inst.trigger(Hammer.detection.current.name, ev);
  16663. }
  16664. }
  16665. }
  16666. };
  16667. /**
  16668. * Swipe
  16669. * triggers swipe events when the end velocity is above the threshold
  16670. * @events swipe, swipeleft, swiperight, swipeup, swipedown
  16671. */
  16672. Hammer.gestures.Swipe = {
  16673. name: 'swipe',
  16674. index: 40,
  16675. defaults: {
  16676. // set 0 for unlimited, but this can conflict with transform
  16677. swipe_max_touches : 1,
  16678. swipe_velocity : 0.7
  16679. },
  16680. handler: function swipeGesture(ev, inst) {
  16681. if(ev.eventType == Hammer.EVENT_END) {
  16682. // max touches
  16683. if(inst.options.swipe_max_touches > 0 &&
  16684. ev.touches.length > inst.options.swipe_max_touches) {
  16685. return;
  16686. }
  16687. // when the distance we moved is too small we skip this gesture
  16688. // or we can be already in dragging
  16689. if(ev.velocityX > inst.options.swipe_velocity ||
  16690. ev.velocityY > inst.options.swipe_velocity) {
  16691. // trigger swipe events
  16692. inst.trigger(this.name, ev);
  16693. inst.trigger(this.name + ev.direction, ev);
  16694. }
  16695. }
  16696. }
  16697. };
  16698. /**
  16699. * Drag
  16700. * Move with x fingers (default 1) around on the page. Blocking the scrolling when
  16701. * moving left and right is a good practice. When all the drag events are blocking
  16702. * you disable scrolling on that area.
  16703. * @events drag, drapleft, dragright, dragup, dragdown
  16704. */
  16705. Hammer.gestures.Drag = {
  16706. name: 'drag',
  16707. index: 50,
  16708. defaults: {
  16709. drag_min_distance : 10,
  16710. // set 0 for unlimited, but this can conflict with transform
  16711. drag_max_touches : 1,
  16712. // prevent default browser behavior when dragging occurs
  16713. // be careful with it, it makes the element a blocking element
  16714. // when you are using the drag gesture, it is a good practice to set this true
  16715. drag_block_horizontal : false,
  16716. drag_block_vertical : false,
  16717. // drag_lock_to_axis keeps the drag gesture on the axis that it started on,
  16718. // It disallows vertical directions if the initial direction was horizontal, and vice versa.
  16719. drag_lock_to_axis : false,
  16720. // drag lock only kicks in when distance > drag_lock_min_distance
  16721. // This way, locking occurs only when the distance has become large enough to reliably determine the direction
  16722. drag_lock_min_distance : 25
  16723. },
  16724. triggered: false,
  16725. handler: function dragGesture(ev, inst) {
  16726. // current gesture isnt drag, but dragged is true
  16727. // this means an other gesture is busy. now call dragend
  16728. if(Hammer.detection.current.name != this.name && this.triggered) {
  16729. inst.trigger(this.name +'end', ev);
  16730. this.triggered = false;
  16731. return;
  16732. }
  16733. // max touches
  16734. if(inst.options.drag_max_touches > 0 &&
  16735. ev.touches.length > inst.options.drag_max_touches) {
  16736. return;
  16737. }
  16738. switch(ev.eventType) {
  16739. case Hammer.EVENT_START:
  16740. this.triggered = false;
  16741. break;
  16742. case Hammer.EVENT_MOVE:
  16743. // when the distance we moved is too small we skip this gesture
  16744. // or we can be already in dragging
  16745. if(ev.distance < inst.options.drag_min_distance &&
  16746. Hammer.detection.current.name != this.name) {
  16747. return;
  16748. }
  16749. // we are dragging!
  16750. Hammer.detection.current.name = this.name;
  16751. // lock drag to axis?
  16752. if(Hammer.detection.current.lastEvent.drag_locked_to_axis || (inst.options.drag_lock_to_axis && inst.options.drag_lock_min_distance<=ev.distance)) {
  16753. ev.drag_locked_to_axis = true;
  16754. }
  16755. var last_direction = Hammer.detection.current.lastEvent.direction;
  16756. if(ev.drag_locked_to_axis && last_direction !== ev.direction) {
  16757. // keep direction on the axis that the drag gesture started on
  16758. if(Hammer.utils.isVertical(last_direction)) {
  16759. ev.direction = (ev.deltaY < 0) ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  16760. }
  16761. else {
  16762. ev.direction = (ev.deltaX < 0) ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  16763. }
  16764. }
  16765. // first time, trigger dragstart event
  16766. if(!this.triggered) {
  16767. inst.trigger(this.name +'start', ev);
  16768. this.triggered = true;
  16769. }
  16770. // trigger normal event
  16771. inst.trigger(this.name, ev);
  16772. // direction event, like dragdown
  16773. inst.trigger(this.name + ev.direction, ev);
  16774. // block the browser events
  16775. if( (inst.options.drag_block_vertical && Hammer.utils.isVertical(ev.direction)) ||
  16776. (inst.options.drag_block_horizontal && !Hammer.utils.isVertical(ev.direction))) {
  16777. ev.preventDefault();
  16778. }
  16779. break;
  16780. case Hammer.EVENT_END:
  16781. // trigger dragend
  16782. if(this.triggered) {
  16783. inst.trigger(this.name +'end', ev);
  16784. }
  16785. this.triggered = false;
  16786. break;
  16787. }
  16788. }
  16789. };
  16790. /**
  16791. * Transform
  16792. * User want to scale or rotate with 2 fingers
  16793. * @events transform, pinch, pinchin, pinchout, rotate
  16794. */
  16795. Hammer.gestures.Transform = {
  16796. name: 'transform',
  16797. index: 45,
  16798. defaults: {
  16799. // factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1
  16800. transform_min_scale : 0.01,
  16801. // rotation in degrees
  16802. transform_min_rotation : 1,
  16803. // prevent default browser behavior when two touches are on the screen
  16804. // but it makes the element a blocking element
  16805. // when you are using the transform gesture, it is a good practice to set this true
  16806. transform_always_block : false
  16807. },
  16808. triggered: false,
  16809. handler: function transformGesture(ev, inst) {
  16810. // current gesture isnt drag, but dragged is true
  16811. // this means an other gesture is busy. now call dragend
  16812. if(Hammer.detection.current.name != this.name && this.triggered) {
  16813. inst.trigger(this.name +'end', ev);
  16814. this.triggered = false;
  16815. return;
  16816. }
  16817. // atleast multitouch
  16818. if(ev.touches.length < 2) {
  16819. return;
  16820. }
  16821. // prevent default when two fingers are on the screen
  16822. if(inst.options.transform_always_block) {
  16823. ev.preventDefault();
  16824. }
  16825. switch(ev.eventType) {
  16826. case Hammer.EVENT_START:
  16827. this.triggered = false;
  16828. break;
  16829. case Hammer.EVENT_MOVE:
  16830. var scale_threshold = Math.abs(1-ev.scale);
  16831. var rotation_threshold = Math.abs(ev.rotation);
  16832. // when the distance we moved is too small we skip this gesture
  16833. // or we can be already in dragging
  16834. if(scale_threshold < inst.options.transform_min_scale &&
  16835. rotation_threshold < inst.options.transform_min_rotation) {
  16836. return;
  16837. }
  16838. // we are transforming!
  16839. Hammer.detection.current.name = this.name;
  16840. // first time, trigger dragstart event
  16841. if(!this.triggered) {
  16842. inst.trigger(this.name +'start', ev);
  16843. this.triggered = true;
  16844. }
  16845. inst.trigger(this.name, ev); // basic transform event
  16846. // trigger rotate event
  16847. if(rotation_threshold > inst.options.transform_min_rotation) {
  16848. inst.trigger('rotate', ev);
  16849. }
  16850. // trigger pinch event
  16851. if(scale_threshold > inst.options.transform_min_scale) {
  16852. inst.trigger('pinch', ev);
  16853. inst.trigger('pinch'+ ((ev.scale < 1) ? 'in' : 'out'), ev);
  16854. }
  16855. break;
  16856. case Hammer.EVENT_END:
  16857. // trigger dragend
  16858. if(this.triggered) {
  16859. inst.trigger(this.name +'end', ev);
  16860. }
  16861. this.triggered = false;
  16862. break;
  16863. }
  16864. }
  16865. };
  16866. /**
  16867. * Touch
  16868. * Called as first, tells the user has touched the screen
  16869. * @events touch
  16870. */
  16871. Hammer.gestures.Touch = {
  16872. name: 'touch',
  16873. index: -Infinity,
  16874. defaults: {
  16875. // call preventDefault at touchstart, and makes the element blocking by
  16876. // disabling the scrolling of the page, but it improves gestures like
  16877. // transforming and dragging.
  16878. // be careful with using this, it can be very annoying for users to be stuck
  16879. // on the page
  16880. prevent_default: false,
  16881. // disable mouse events, so only touch (or pen!) input triggers events
  16882. prevent_mouseevents: false
  16883. },
  16884. handler: function touchGesture(ev, inst) {
  16885. if(inst.options.prevent_mouseevents && ev.pointerType == Hammer.POINTER_MOUSE) {
  16886. ev.stopDetect();
  16887. return;
  16888. }
  16889. if(inst.options.prevent_default) {
  16890. ev.preventDefault();
  16891. }
  16892. if(ev.eventType == Hammer.EVENT_START) {
  16893. inst.trigger(this.name, ev);
  16894. }
  16895. }
  16896. };
  16897. /**
  16898. * Release
  16899. * Called as last, tells the user has released the screen
  16900. * @events release
  16901. */
  16902. Hammer.gestures.Release = {
  16903. name: 'release',
  16904. index: Infinity,
  16905. handler: function releaseGesture(ev, inst) {
  16906. if(ev.eventType == Hammer.EVENT_END) {
  16907. inst.trigger(this.name, ev);
  16908. }
  16909. }
  16910. };
  16911. // node export
  16912. if(typeof module === 'object' && typeof module.exports === 'object'){
  16913. module.exports = Hammer;
  16914. }
  16915. // just window export
  16916. else {
  16917. window.Hammer = Hammer;
  16918. // requireJS module definition
  16919. if(typeof window.define === 'function' && window.define.amd) {
  16920. window.define('hammer', [], function() {
  16921. return Hammer;
  16922. });
  16923. }
  16924. }
  16925. })(this);
  16926. },{}],4:[function(require,module,exports){
  16927. //! moment.js
  16928. //! version : 2.5.1
  16929. //! authors : Tim Wood, Iskren Chernev, Moment.js contributors
  16930. //! license : MIT
  16931. //! momentjs.com
  16932. (function (undefined) {
  16933. /************************************
  16934. Constants
  16935. ************************************/
  16936. var moment,
  16937. VERSION = "2.5.1",
  16938. global = this,
  16939. round = Math.round,
  16940. i,
  16941. YEAR = 0,
  16942. MONTH = 1,
  16943. DATE = 2,
  16944. HOUR = 3,
  16945. MINUTE = 4,
  16946. SECOND = 5,
  16947. MILLISECOND = 6,
  16948. // internal storage for language config files
  16949. languages = {},
  16950. // moment internal properties
  16951. momentProperties = {
  16952. _isAMomentObject: null,
  16953. _i : null,
  16954. _f : null,
  16955. _l : null,
  16956. _strict : null,
  16957. _isUTC : null,
  16958. _offset : null, // optional. Combine with _isUTC
  16959. _pf : null,
  16960. _lang : null // optional
  16961. },
  16962. // check for nodeJS
  16963. hasModule = (typeof module !== 'undefined' && module.exports && typeof require !== 'undefined'),
  16964. // ASP.NET json date format regex
  16965. aspNetJsonRegex = /^\/?Date\((\-?\d+)/i,
  16966. aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,
  16967. // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
  16968. // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
  16969. isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/,
  16970. // format tokens
  16971. formattingTokens = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|X|zz?|ZZ?|.)/g,
  16972. localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g,
  16973. // parsing token regexes
  16974. parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99
  16975. parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999
  16976. parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999
  16977. parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999
  16978. parseTokenDigits = /\d+/, // nonzero number of digits
  16979. 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.
  16980. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z
  16981. parseTokenT = /T/i, // T (ISO separator)
  16982. parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
  16983. //strict parsing regexes
  16984. parseTokenOneDigit = /\d/, // 0 - 9
  16985. parseTokenTwoDigits = /\d\d/, // 00 - 99
  16986. parseTokenThreeDigits = /\d{3}/, // 000 - 999
  16987. parseTokenFourDigits = /\d{4}/, // 0000 - 9999
  16988. parseTokenSixDigits = /[+-]?\d{6}/, // -999,999 - 999,999
  16989. parseTokenSignedNumber = /[+-]?\d+/, // -inf - inf
  16990. // iso 8601 regex
  16991. // 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)
  16992. 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)?)?$/,
  16993. isoFormat = 'YYYY-MM-DDTHH:mm:ssZ',
  16994. isoDates = [
  16995. ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/],
  16996. ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/],
  16997. ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/],
  16998. ['GGGG-[W]WW', /\d{4}-W\d{2}/],
  16999. ['YYYY-DDD', /\d{4}-\d{3}/]
  17000. ],
  17001. // iso time formats and regexes
  17002. isoTimes = [
  17003. ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d{1,3}/],
  17004. ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/],
  17005. ['HH:mm', /(T| )\d\d:\d\d/],
  17006. ['HH', /(T| )\d\d/]
  17007. ],
  17008. // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"]
  17009. parseTimezoneChunker = /([\+\-]|\d\d)/gi,
  17010. // getter and setter names
  17011. proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'),
  17012. unitMillisecondFactors = {
  17013. 'Milliseconds' : 1,
  17014. 'Seconds' : 1e3,
  17015. 'Minutes' : 6e4,
  17016. 'Hours' : 36e5,
  17017. 'Days' : 864e5,
  17018. 'Months' : 2592e6,
  17019. 'Years' : 31536e6
  17020. },
  17021. unitAliases = {
  17022. ms : 'millisecond',
  17023. s : 'second',
  17024. m : 'minute',
  17025. h : 'hour',
  17026. d : 'day',
  17027. D : 'date',
  17028. w : 'week',
  17029. W : 'isoWeek',
  17030. M : 'month',
  17031. y : 'year',
  17032. DDD : 'dayOfYear',
  17033. e : 'weekday',
  17034. E : 'isoWeekday',
  17035. gg: 'weekYear',
  17036. GG: 'isoWeekYear'
  17037. },
  17038. camelFunctions = {
  17039. dayofyear : 'dayOfYear',
  17040. isoweekday : 'isoWeekday',
  17041. isoweek : 'isoWeek',
  17042. weekyear : 'weekYear',
  17043. isoweekyear : 'isoWeekYear'
  17044. },
  17045. // format function strings
  17046. formatFunctions = {},
  17047. // tokens to ordinalize and pad
  17048. ordinalizeTokens = 'DDD w W M D d'.split(' '),
  17049. paddedTokens = 'M D H h m s w W'.split(' '),
  17050. formatTokenFunctions = {
  17051. M : function () {
  17052. return this.month() + 1;
  17053. },
  17054. MMM : function (format) {
  17055. return this.lang().monthsShort(this, format);
  17056. },
  17057. MMMM : function (format) {
  17058. return this.lang().months(this, format);
  17059. },
  17060. D : function () {
  17061. return this.date();
  17062. },
  17063. DDD : function () {
  17064. return this.dayOfYear();
  17065. },
  17066. d : function () {
  17067. return this.day();
  17068. },
  17069. dd : function (format) {
  17070. return this.lang().weekdaysMin(this, format);
  17071. },
  17072. ddd : function (format) {
  17073. return this.lang().weekdaysShort(this, format);
  17074. },
  17075. dddd : function (format) {
  17076. return this.lang().weekdays(this, format);
  17077. },
  17078. w : function () {
  17079. return this.week();
  17080. },
  17081. W : function () {
  17082. return this.isoWeek();
  17083. },
  17084. YY : function () {
  17085. return leftZeroFill(this.year() % 100, 2);
  17086. },
  17087. YYYY : function () {
  17088. return leftZeroFill(this.year(), 4);
  17089. },
  17090. YYYYY : function () {
  17091. return leftZeroFill(this.year(), 5);
  17092. },
  17093. YYYYYY : function () {
  17094. var y = this.year(), sign = y >= 0 ? '+' : '-';
  17095. return sign + leftZeroFill(Math.abs(y), 6);
  17096. },
  17097. gg : function () {
  17098. return leftZeroFill(this.weekYear() % 100, 2);
  17099. },
  17100. gggg : function () {
  17101. return leftZeroFill(this.weekYear(), 4);
  17102. },
  17103. ggggg : function () {
  17104. return leftZeroFill(this.weekYear(), 5);
  17105. },
  17106. GG : function () {
  17107. return leftZeroFill(this.isoWeekYear() % 100, 2);
  17108. },
  17109. GGGG : function () {
  17110. return leftZeroFill(this.isoWeekYear(), 4);
  17111. },
  17112. GGGGG : function () {
  17113. return leftZeroFill(this.isoWeekYear(), 5);
  17114. },
  17115. e : function () {
  17116. return this.weekday();
  17117. },
  17118. E : function () {
  17119. return this.isoWeekday();
  17120. },
  17121. a : function () {
  17122. return this.lang().meridiem(this.hours(), this.minutes(), true);
  17123. },
  17124. A : function () {
  17125. return this.lang().meridiem(this.hours(), this.minutes(), false);
  17126. },
  17127. H : function () {
  17128. return this.hours();
  17129. },
  17130. h : function () {
  17131. return this.hours() % 12 || 12;
  17132. },
  17133. m : function () {
  17134. return this.minutes();
  17135. },
  17136. s : function () {
  17137. return this.seconds();
  17138. },
  17139. S : function () {
  17140. return toInt(this.milliseconds() / 100);
  17141. },
  17142. SS : function () {
  17143. return leftZeroFill(toInt(this.milliseconds() / 10), 2);
  17144. },
  17145. SSS : function () {
  17146. return leftZeroFill(this.milliseconds(), 3);
  17147. },
  17148. SSSS : function () {
  17149. return leftZeroFill(this.milliseconds(), 3);
  17150. },
  17151. Z : function () {
  17152. var a = -this.zone(),
  17153. b = "+";
  17154. if (a < 0) {
  17155. a = -a;
  17156. b = "-";
  17157. }
  17158. return b + leftZeroFill(toInt(a / 60), 2) + ":" + leftZeroFill(toInt(a) % 60, 2);
  17159. },
  17160. ZZ : function () {
  17161. var a = -this.zone(),
  17162. b = "+";
  17163. if (a < 0) {
  17164. a = -a;
  17165. b = "-";
  17166. }
  17167. return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2);
  17168. },
  17169. z : function () {
  17170. return this.zoneAbbr();
  17171. },
  17172. zz : function () {
  17173. return this.zoneName();
  17174. },
  17175. X : function () {
  17176. return this.unix();
  17177. },
  17178. Q : function () {
  17179. return this.quarter();
  17180. }
  17181. },
  17182. lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin'];
  17183. function defaultParsingFlags() {
  17184. // We need to deep clone this object, and es5 standard is not very
  17185. // helpful.
  17186. return {
  17187. empty : false,
  17188. unusedTokens : [],
  17189. unusedInput : [],
  17190. overflow : -2,
  17191. charsLeftOver : 0,
  17192. nullInput : false,
  17193. invalidMonth : null,
  17194. invalidFormat : false,
  17195. userInvalidated : false,
  17196. iso: false
  17197. };
  17198. }
  17199. function padToken(func, count) {
  17200. return function (a) {
  17201. return leftZeroFill(func.call(this, a), count);
  17202. };
  17203. }
  17204. function ordinalizeToken(func, period) {
  17205. return function (a) {
  17206. return this.lang().ordinal(func.call(this, a), period);
  17207. };
  17208. }
  17209. while (ordinalizeTokens.length) {
  17210. i = ordinalizeTokens.pop();
  17211. formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i);
  17212. }
  17213. while (paddedTokens.length) {
  17214. i = paddedTokens.pop();
  17215. formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2);
  17216. }
  17217. formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3);
  17218. /************************************
  17219. Constructors
  17220. ************************************/
  17221. function Language() {
  17222. }
  17223. // Moment prototype object
  17224. function Moment(config) {
  17225. checkOverflow(config);
  17226. extend(this, config);
  17227. }
  17228. // Duration Constructor
  17229. function Duration(duration) {
  17230. var normalizedInput = normalizeObjectUnits(duration),
  17231. years = normalizedInput.year || 0,
  17232. months = normalizedInput.month || 0,
  17233. weeks = normalizedInput.week || 0,
  17234. days = normalizedInput.day || 0,
  17235. hours = normalizedInput.hour || 0,
  17236. minutes = normalizedInput.minute || 0,
  17237. seconds = normalizedInput.second || 0,
  17238. milliseconds = normalizedInput.millisecond || 0;
  17239. // representation for dateAddRemove
  17240. this._milliseconds = +milliseconds +
  17241. seconds * 1e3 + // 1000
  17242. minutes * 6e4 + // 1000 * 60
  17243. hours * 36e5; // 1000 * 60 * 60
  17244. // Because of dateAddRemove treats 24 hours as different from a
  17245. // day when working around DST, we need to store them separately
  17246. this._days = +days +
  17247. weeks * 7;
  17248. // It is impossible translate months into days without knowing
  17249. // which months you are are talking about, so we have to store
  17250. // it separately.
  17251. this._months = +months +
  17252. years * 12;
  17253. this._data = {};
  17254. this._bubble();
  17255. }
  17256. /************************************
  17257. Helpers
  17258. ************************************/
  17259. function extend(a, b) {
  17260. for (var i in b) {
  17261. if (b.hasOwnProperty(i)) {
  17262. a[i] = b[i];
  17263. }
  17264. }
  17265. if (b.hasOwnProperty("toString")) {
  17266. a.toString = b.toString;
  17267. }
  17268. if (b.hasOwnProperty("valueOf")) {
  17269. a.valueOf = b.valueOf;
  17270. }
  17271. return a;
  17272. }
  17273. function cloneMoment(m) {
  17274. var result = {}, i;
  17275. for (i in m) {
  17276. if (m.hasOwnProperty(i) && momentProperties.hasOwnProperty(i)) {
  17277. result[i] = m[i];
  17278. }
  17279. }
  17280. return result;
  17281. }
  17282. function absRound(number) {
  17283. if (number < 0) {
  17284. return Math.ceil(number);
  17285. } else {
  17286. return Math.floor(number);
  17287. }
  17288. }
  17289. // left zero fill a number
  17290. // see http://jsperf.com/left-zero-filling for performance comparison
  17291. function leftZeroFill(number, targetLength, forceSign) {
  17292. var output = '' + Math.abs(number),
  17293. sign = number >= 0;
  17294. while (output.length < targetLength) {
  17295. output = '0' + output;
  17296. }
  17297. return (sign ? (forceSign ? '+' : '') : '-') + output;
  17298. }
  17299. // helper function for _.addTime and _.subtractTime
  17300. function addOrSubtractDurationFromMoment(mom, duration, isAdding, ignoreUpdateOffset) {
  17301. var milliseconds = duration._milliseconds,
  17302. days = duration._days,
  17303. months = duration._months,
  17304. minutes,
  17305. hours;
  17306. if (milliseconds) {
  17307. mom._d.setTime(+mom._d + milliseconds * isAdding);
  17308. }
  17309. // store the minutes and hours so we can restore them
  17310. if (days || months) {
  17311. minutes = mom.minute();
  17312. hours = mom.hour();
  17313. }
  17314. if (days) {
  17315. mom.date(mom.date() + days * isAdding);
  17316. }
  17317. if (months) {
  17318. mom.month(mom.month() + months * isAdding);
  17319. }
  17320. if (milliseconds && !ignoreUpdateOffset) {
  17321. moment.updateOffset(mom);
  17322. }
  17323. // restore the minutes and hours after possibly changing dst
  17324. if (days || months) {
  17325. mom.minute(minutes);
  17326. mom.hour(hours);
  17327. }
  17328. }
  17329. // check if is an array
  17330. function isArray(input) {
  17331. return Object.prototype.toString.call(input) === '[object Array]';
  17332. }
  17333. function isDate(input) {
  17334. return Object.prototype.toString.call(input) === '[object Date]' ||
  17335. input instanceof Date;
  17336. }
  17337. // compare two arrays, return the number of differences
  17338. function compareArrays(array1, array2, dontConvert) {
  17339. var len = Math.min(array1.length, array2.length),
  17340. lengthDiff = Math.abs(array1.length - array2.length),
  17341. diffs = 0,
  17342. i;
  17343. for (i = 0; i < len; i++) {
  17344. if ((dontConvert && array1[i] !== array2[i]) ||
  17345. (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
  17346. diffs++;
  17347. }
  17348. }
  17349. return diffs + lengthDiff;
  17350. }
  17351. function normalizeUnits(units) {
  17352. if (units) {
  17353. var lowered = units.toLowerCase().replace(/(.)s$/, '$1');
  17354. units = unitAliases[units] || camelFunctions[lowered] || lowered;
  17355. }
  17356. return units;
  17357. }
  17358. function normalizeObjectUnits(inputObject) {
  17359. var normalizedInput = {},
  17360. normalizedProp,
  17361. prop;
  17362. for (prop in inputObject) {
  17363. if (inputObject.hasOwnProperty(prop)) {
  17364. normalizedProp = normalizeUnits(prop);
  17365. if (normalizedProp) {
  17366. normalizedInput[normalizedProp] = inputObject[prop];
  17367. }
  17368. }
  17369. }
  17370. return normalizedInput;
  17371. }
  17372. function makeList(field) {
  17373. var count, setter;
  17374. if (field.indexOf('week') === 0) {
  17375. count = 7;
  17376. setter = 'day';
  17377. }
  17378. else if (field.indexOf('month') === 0) {
  17379. count = 12;
  17380. setter = 'month';
  17381. }
  17382. else {
  17383. return;
  17384. }
  17385. moment[field] = function (format, index) {
  17386. var i, getter,
  17387. method = moment.fn._lang[field],
  17388. results = [];
  17389. if (typeof format === 'number') {
  17390. index = format;
  17391. format = undefined;
  17392. }
  17393. getter = function (i) {
  17394. var m = moment().utc().set(setter, i);
  17395. return method.call(moment.fn._lang, m, format || '');
  17396. };
  17397. if (index != null) {
  17398. return getter(index);
  17399. }
  17400. else {
  17401. for (i = 0; i < count; i++) {
  17402. results.push(getter(i));
  17403. }
  17404. return results;
  17405. }
  17406. };
  17407. }
  17408. function toInt(argumentForCoercion) {
  17409. var coercedNumber = +argumentForCoercion,
  17410. value = 0;
  17411. if (coercedNumber !== 0 && isFinite(coercedNumber)) {
  17412. if (coercedNumber >= 0) {
  17413. value = Math.floor(coercedNumber);
  17414. } else {
  17415. value = Math.ceil(coercedNumber);
  17416. }
  17417. }
  17418. return value;
  17419. }
  17420. function daysInMonth(year, month) {
  17421. return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
  17422. }
  17423. function daysInYear(year) {
  17424. return isLeapYear(year) ? 366 : 365;
  17425. }
  17426. function isLeapYear(year) {
  17427. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  17428. }
  17429. function checkOverflow(m) {
  17430. var overflow;
  17431. if (m._a && m._pf.overflow === -2) {
  17432. overflow =
  17433. m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH :
  17434. m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE :
  17435. m._a[HOUR] < 0 || m._a[HOUR] > 23 ? HOUR :
  17436. m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE :
  17437. m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND :
  17438. m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND :
  17439. -1;
  17440. if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
  17441. overflow = DATE;
  17442. }
  17443. m._pf.overflow = overflow;
  17444. }
  17445. }
  17446. function isValid(m) {
  17447. if (m._isValid == null) {
  17448. m._isValid = !isNaN(m._d.getTime()) &&
  17449. m._pf.overflow < 0 &&
  17450. !m._pf.empty &&
  17451. !m._pf.invalidMonth &&
  17452. !m._pf.nullInput &&
  17453. !m._pf.invalidFormat &&
  17454. !m._pf.userInvalidated;
  17455. if (m._strict) {
  17456. m._isValid = m._isValid &&
  17457. m._pf.charsLeftOver === 0 &&
  17458. m._pf.unusedTokens.length === 0;
  17459. }
  17460. }
  17461. return m._isValid;
  17462. }
  17463. function normalizeLanguage(key) {
  17464. return key ? key.toLowerCase().replace('_', '-') : key;
  17465. }
  17466. // Return a moment from input, that is local/utc/zone equivalent to model.
  17467. function makeAs(input, model) {
  17468. return model._isUTC ? moment(input).zone(model._offset || 0) :
  17469. moment(input).local();
  17470. }
  17471. /************************************
  17472. Languages
  17473. ************************************/
  17474. extend(Language.prototype, {
  17475. set : function (config) {
  17476. var prop, i;
  17477. for (i in config) {
  17478. prop = config[i];
  17479. if (typeof prop === 'function') {
  17480. this[i] = prop;
  17481. } else {
  17482. this['_' + i] = prop;
  17483. }
  17484. }
  17485. },
  17486. _months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
  17487. months : function (m) {
  17488. return this._months[m.month()];
  17489. },
  17490. _monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),
  17491. monthsShort : function (m) {
  17492. return this._monthsShort[m.month()];
  17493. },
  17494. monthsParse : function (monthName) {
  17495. var i, mom, regex;
  17496. if (!this._monthsParse) {
  17497. this._monthsParse = [];
  17498. }
  17499. for (i = 0; i < 12; i++) {
  17500. // make the regex if we don't have it already
  17501. if (!this._monthsParse[i]) {
  17502. mom = moment.utc([2000, i]);
  17503. regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  17504. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  17505. }
  17506. // test the regex
  17507. if (this._monthsParse[i].test(monthName)) {
  17508. return i;
  17509. }
  17510. }
  17511. },
  17512. _weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
  17513. weekdays : function (m) {
  17514. return this._weekdays[m.day()];
  17515. },
  17516. _weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),
  17517. weekdaysShort : function (m) {
  17518. return this._weekdaysShort[m.day()];
  17519. },
  17520. _weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"),
  17521. weekdaysMin : function (m) {
  17522. return this._weekdaysMin[m.day()];
  17523. },
  17524. weekdaysParse : function (weekdayName) {
  17525. var i, mom, regex;
  17526. if (!this._weekdaysParse) {
  17527. this._weekdaysParse = [];
  17528. }
  17529. for (i = 0; i < 7; i++) {
  17530. // make the regex if we don't have it already
  17531. if (!this._weekdaysParse[i]) {
  17532. mom = moment([2000, 1]).day(i);
  17533. regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
  17534. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  17535. }
  17536. // test the regex
  17537. if (this._weekdaysParse[i].test(weekdayName)) {
  17538. return i;
  17539. }
  17540. }
  17541. },
  17542. _longDateFormat : {
  17543. LT : "h:mm A",
  17544. L : "MM/DD/YYYY",
  17545. LL : "MMMM D YYYY",
  17546. LLL : "MMMM D YYYY LT",
  17547. LLLL : "dddd, MMMM D YYYY LT"
  17548. },
  17549. longDateFormat : function (key) {
  17550. var output = this._longDateFormat[key];
  17551. if (!output && this._longDateFormat[key.toUpperCase()]) {
  17552. output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) {
  17553. return val.slice(1);
  17554. });
  17555. this._longDateFormat[key] = output;
  17556. }
  17557. return output;
  17558. },
  17559. isPM : function (input) {
  17560. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  17561. // Using charAt should be more compatible.
  17562. return ((input + '').toLowerCase().charAt(0) === 'p');
  17563. },
  17564. _meridiemParse : /[ap]\.?m?\.?/i,
  17565. meridiem : function (hours, minutes, isLower) {
  17566. if (hours > 11) {
  17567. return isLower ? 'pm' : 'PM';
  17568. } else {
  17569. return isLower ? 'am' : 'AM';
  17570. }
  17571. },
  17572. _calendar : {
  17573. sameDay : '[Today at] LT',
  17574. nextDay : '[Tomorrow at] LT',
  17575. nextWeek : 'dddd [at] LT',
  17576. lastDay : '[Yesterday at] LT',
  17577. lastWeek : '[Last] dddd [at] LT',
  17578. sameElse : 'L'
  17579. },
  17580. calendar : function (key, mom) {
  17581. var output = this._calendar[key];
  17582. return typeof output === 'function' ? output.apply(mom) : output;
  17583. },
  17584. _relativeTime : {
  17585. future : "in %s",
  17586. past : "%s ago",
  17587. s : "a few seconds",
  17588. m : "a minute",
  17589. mm : "%d minutes",
  17590. h : "an hour",
  17591. hh : "%d hours",
  17592. d : "a day",
  17593. dd : "%d days",
  17594. M : "a month",
  17595. MM : "%d months",
  17596. y : "a year",
  17597. yy : "%d years"
  17598. },
  17599. relativeTime : function (number, withoutSuffix, string, isFuture) {
  17600. var output = this._relativeTime[string];
  17601. return (typeof output === 'function') ?
  17602. output(number, withoutSuffix, string, isFuture) :
  17603. output.replace(/%d/i, number);
  17604. },
  17605. pastFuture : function (diff, output) {
  17606. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  17607. return typeof format === 'function' ? format(output) : format.replace(/%s/i, output);
  17608. },
  17609. ordinal : function (number) {
  17610. return this._ordinal.replace("%d", number);
  17611. },
  17612. _ordinal : "%d",
  17613. preparse : function (string) {
  17614. return string;
  17615. },
  17616. postformat : function (string) {
  17617. return string;
  17618. },
  17619. week : function (mom) {
  17620. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  17621. },
  17622. _week : {
  17623. dow : 0, // Sunday is the first day of the week.
  17624. doy : 6 // The week that contains Jan 1st is the first week of the year.
  17625. },
  17626. _invalidDate: 'Invalid date',
  17627. invalidDate: function () {
  17628. return this._invalidDate;
  17629. }
  17630. });
  17631. // Loads a language definition into the `languages` cache. The function
  17632. // takes a key and optionally values. If not in the browser and no values
  17633. // are provided, it will load the language file module. As a convenience,
  17634. // this function also returns the language values.
  17635. function loadLang(key, values) {
  17636. values.abbr = key;
  17637. if (!languages[key]) {
  17638. languages[key] = new Language();
  17639. }
  17640. languages[key].set(values);
  17641. return languages[key];
  17642. }
  17643. // Remove a language from the `languages` cache. Mostly useful in tests.
  17644. function unloadLang(key) {
  17645. delete languages[key];
  17646. }
  17647. // Determines which language definition to use and returns it.
  17648. //
  17649. // With no parameters, it will return the global language. If you
  17650. // pass in a language key, such as 'en', it will return the
  17651. // definition for 'en', so long as 'en' has already been loaded using
  17652. // moment.lang.
  17653. function getLangDefinition(key) {
  17654. var i = 0, j, lang, next, split,
  17655. get = function (k) {
  17656. if (!languages[k] && hasModule) {
  17657. try {
  17658. require('./lang/' + k);
  17659. } catch (e) { }
  17660. }
  17661. return languages[k];
  17662. };
  17663. if (!key) {
  17664. return moment.fn._lang;
  17665. }
  17666. if (!isArray(key)) {
  17667. //short-circuit everything else
  17668. lang = get(key);
  17669. if (lang) {
  17670. return lang;
  17671. }
  17672. key = [key];
  17673. }
  17674. //pick the language from the array
  17675. //try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
  17676. //substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
  17677. while (i < key.length) {
  17678. split = normalizeLanguage(key[i]).split('-');
  17679. j = split.length;
  17680. next = normalizeLanguage(key[i + 1]);
  17681. next = next ? next.split('-') : null;
  17682. while (j > 0) {
  17683. lang = get(split.slice(0, j).join('-'));
  17684. if (lang) {
  17685. return lang;
  17686. }
  17687. if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
  17688. //the next array item is better than a shallower substring of this one
  17689. break;
  17690. }
  17691. j--;
  17692. }
  17693. i++;
  17694. }
  17695. return moment.fn._lang;
  17696. }
  17697. /************************************
  17698. Formatting
  17699. ************************************/
  17700. function removeFormattingTokens(input) {
  17701. if (input.match(/\[[\s\S]/)) {
  17702. return input.replace(/^\[|\]$/g, "");
  17703. }
  17704. return input.replace(/\\/g, "");
  17705. }
  17706. function makeFormatFunction(format) {
  17707. var array = format.match(formattingTokens), i, length;
  17708. for (i = 0, length = array.length; i < length; i++) {
  17709. if (formatTokenFunctions[array[i]]) {
  17710. array[i] = formatTokenFunctions[array[i]];
  17711. } else {
  17712. array[i] = removeFormattingTokens(array[i]);
  17713. }
  17714. }
  17715. return function (mom) {
  17716. var output = "";
  17717. for (i = 0; i < length; i++) {
  17718. output += array[i] instanceof Function ? array[i].call(mom, format) : array[i];
  17719. }
  17720. return output;
  17721. };
  17722. }
  17723. // format date using native date object
  17724. function formatMoment(m, format) {
  17725. if (!m.isValid()) {
  17726. return m.lang().invalidDate();
  17727. }
  17728. format = expandFormat(format, m.lang());
  17729. if (!formatFunctions[format]) {
  17730. formatFunctions[format] = makeFormatFunction(format);
  17731. }
  17732. return formatFunctions[format](m);
  17733. }
  17734. function expandFormat(format, lang) {
  17735. var i = 5;
  17736. function replaceLongDateFormatTokens(input) {
  17737. return lang.longDateFormat(input) || input;
  17738. }
  17739. localFormattingTokens.lastIndex = 0;
  17740. while (i >= 0 && localFormattingTokens.test(format)) {
  17741. format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
  17742. localFormattingTokens.lastIndex = 0;
  17743. i -= 1;
  17744. }
  17745. return format;
  17746. }
  17747. /************************************
  17748. Parsing
  17749. ************************************/
  17750. // get the regex to find the next token
  17751. function getParseRegexForToken(token, config) {
  17752. var a, strict = config._strict;
  17753. switch (token) {
  17754. case 'DDDD':
  17755. return parseTokenThreeDigits;
  17756. case 'YYYY':
  17757. case 'GGGG':
  17758. case 'gggg':
  17759. return strict ? parseTokenFourDigits : parseTokenOneToFourDigits;
  17760. case 'Y':
  17761. case 'G':
  17762. case 'g':
  17763. return parseTokenSignedNumber;
  17764. case 'YYYYYY':
  17765. case 'YYYYY':
  17766. case 'GGGGG':
  17767. case 'ggggg':
  17768. return strict ? parseTokenSixDigits : parseTokenOneToSixDigits;
  17769. case 'S':
  17770. if (strict) { return parseTokenOneDigit; }
  17771. /* falls through */
  17772. case 'SS':
  17773. if (strict) { return parseTokenTwoDigits; }
  17774. /* falls through */
  17775. case 'SSS':
  17776. if (strict) { return parseTokenThreeDigits; }
  17777. /* falls through */
  17778. case 'DDD':
  17779. return parseTokenOneToThreeDigits;
  17780. case 'MMM':
  17781. case 'MMMM':
  17782. case 'dd':
  17783. case 'ddd':
  17784. case 'dddd':
  17785. return parseTokenWord;
  17786. case 'a':
  17787. case 'A':
  17788. return getLangDefinition(config._l)._meridiemParse;
  17789. case 'X':
  17790. return parseTokenTimestampMs;
  17791. case 'Z':
  17792. case 'ZZ':
  17793. return parseTokenTimezone;
  17794. case 'T':
  17795. return parseTokenT;
  17796. case 'SSSS':
  17797. return parseTokenDigits;
  17798. case 'MM':
  17799. case 'DD':
  17800. case 'YY':
  17801. case 'GG':
  17802. case 'gg':
  17803. case 'HH':
  17804. case 'hh':
  17805. case 'mm':
  17806. case 'ss':
  17807. case 'ww':
  17808. case 'WW':
  17809. return strict ? parseTokenTwoDigits : parseTokenOneOrTwoDigits;
  17810. case 'M':
  17811. case 'D':
  17812. case 'd':
  17813. case 'H':
  17814. case 'h':
  17815. case 'm':
  17816. case 's':
  17817. case 'w':
  17818. case 'W':
  17819. case 'e':
  17820. case 'E':
  17821. return parseTokenOneOrTwoDigits;
  17822. default :
  17823. a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), "i"));
  17824. return a;
  17825. }
  17826. }
  17827. function timezoneMinutesFromString(string) {
  17828. string = string || "";
  17829. var possibleTzMatches = (string.match(parseTokenTimezone) || []),
  17830. tzChunk = possibleTzMatches[possibleTzMatches.length - 1] || [],
  17831. parts = (tzChunk + '').match(parseTimezoneChunker) || ['-', 0, 0],
  17832. minutes = +(parts[1] * 60) + toInt(parts[2]);
  17833. return parts[0] === '+' ? -minutes : minutes;
  17834. }
  17835. // function to convert string input to date
  17836. function addTimeToArrayFromToken(token, input, config) {
  17837. var a, datePartArray = config._a;
  17838. switch (token) {
  17839. // MONTH
  17840. case 'M' : // fall through to MM
  17841. case 'MM' :
  17842. if (input != null) {
  17843. datePartArray[MONTH] = toInt(input) - 1;
  17844. }
  17845. break;
  17846. case 'MMM' : // fall through to MMMM
  17847. case 'MMMM' :
  17848. a = getLangDefinition(config._l).monthsParse(input);
  17849. // if we didn't find a month name, mark the date as invalid.
  17850. if (a != null) {
  17851. datePartArray[MONTH] = a;
  17852. } else {
  17853. config._pf.invalidMonth = input;
  17854. }
  17855. break;
  17856. // DAY OF MONTH
  17857. case 'D' : // fall through to DD
  17858. case 'DD' :
  17859. if (input != null) {
  17860. datePartArray[DATE] = toInt(input);
  17861. }
  17862. break;
  17863. // DAY OF YEAR
  17864. case 'DDD' : // fall through to DDDD
  17865. case 'DDDD' :
  17866. if (input != null) {
  17867. config._dayOfYear = toInt(input);
  17868. }
  17869. break;
  17870. // YEAR
  17871. case 'YY' :
  17872. datePartArray[YEAR] = toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
  17873. break;
  17874. case 'YYYY' :
  17875. case 'YYYYY' :
  17876. case 'YYYYYY' :
  17877. datePartArray[YEAR] = toInt(input);
  17878. break;
  17879. // AM / PM
  17880. case 'a' : // fall through to A
  17881. case 'A' :
  17882. config._isPm = getLangDefinition(config._l).isPM(input);
  17883. break;
  17884. // 24 HOUR
  17885. case 'H' : // fall through to hh
  17886. case 'HH' : // fall through to hh
  17887. case 'h' : // fall through to hh
  17888. case 'hh' :
  17889. datePartArray[HOUR] = toInt(input);
  17890. break;
  17891. // MINUTE
  17892. case 'm' : // fall through to mm
  17893. case 'mm' :
  17894. datePartArray[MINUTE] = toInt(input);
  17895. break;
  17896. // SECOND
  17897. case 's' : // fall through to ss
  17898. case 'ss' :
  17899. datePartArray[SECOND] = toInt(input);
  17900. break;
  17901. // MILLISECOND
  17902. case 'S' :
  17903. case 'SS' :
  17904. case 'SSS' :
  17905. case 'SSSS' :
  17906. datePartArray[MILLISECOND] = toInt(('0.' + input) * 1000);
  17907. break;
  17908. // UNIX TIMESTAMP WITH MS
  17909. case 'X':
  17910. config._d = new Date(parseFloat(input) * 1000);
  17911. break;
  17912. // TIMEZONE
  17913. case 'Z' : // fall through to ZZ
  17914. case 'ZZ' :
  17915. config._useUTC = true;
  17916. config._tzm = timezoneMinutesFromString(input);
  17917. break;
  17918. case 'w':
  17919. case 'ww':
  17920. case 'W':
  17921. case 'WW':
  17922. case 'd':
  17923. case 'dd':
  17924. case 'ddd':
  17925. case 'dddd':
  17926. case 'e':
  17927. case 'E':
  17928. token = token.substr(0, 1);
  17929. /* falls through */
  17930. case 'gg':
  17931. case 'gggg':
  17932. case 'GG':
  17933. case 'GGGG':
  17934. case 'GGGGG':
  17935. token = token.substr(0, 2);
  17936. if (input) {
  17937. config._w = config._w || {};
  17938. config._w[token] = input;
  17939. }
  17940. break;
  17941. }
  17942. }
  17943. // convert an array to a date.
  17944. // the array should mirror the parameters below
  17945. // note: all values past the year are optional and will default to the lowest possible value.
  17946. // [year, month, day , hour, minute, second, millisecond]
  17947. function dateFromConfig(config) {
  17948. var i, date, input = [], currentDate,
  17949. yearToUse, fixYear, w, temp, lang, weekday, week;
  17950. if (config._d) {
  17951. return;
  17952. }
  17953. currentDate = currentDateArray(config);
  17954. //compute day of the year from weeks and weekdays
  17955. if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
  17956. fixYear = function (val) {
  17957. var int_val = parseInt(val, 10);
  17958. return val ?
  17959. (val.length < 3 ? (int_val > 68 ? 1900 + int_val : 2000 + int_val) : int_val) :
  17960. (config._a[YEAR] == null ? moment().weekYear() : config._a[YEAR]);
  17961. };
  17962. w = config._w;
  17963. if (w.GG != null || w.W != null || w.E != null) {
  17964. temp = dayOfYearFromWeeks(fixYear(w.GG), w.W || 1, w.E, 4, 1);
  17965. }
  17966. else {
  17967. lang = getLangDefinition(config._l);
  17968. weekday = w.d != null ? parseWeekday(w.d, lang) :
  17969. (w.e != null ? parseInt(w.e, 10) + lang._week.dow : 0);
  17970. week = parseInt(w.w, 10) || 1;
  17971. //if we're parsing 'd', then the low day numbers may be next week
  17972. if (w.d != null && weekday < lang._week.dow) {
  17973. week++;
  17974. }
  17975. temp = dayOfYearFromWeeks(fixYear(w.gg), week, weekday, lang._week.doy, lang._week.dow);
  17976. }
  17977. config._a[YEAR] = temp.year;
  17978. config._dayOfYear = temp.dayOfYear;
  17979. }
  17980. //if the day of the year is set, figure out what it is
  17981. if (config._dayOfYear) {
  17982. yearToUse = config._a[YEAR] == null ? currentDate[YEAR] : config._a[YEAR];
  17983. if (config._dayOfYear > daysInYear(yearToUse)) {
  17984. config._pf._overflowDayOfYear = true;
  17985. }
  17986. date = makeUTCDate(yearToUse, 0, config._dayOfYear);
  17987. config._a[MONTH] = date.getUTCMonth();
  17988. config._a[DATE] = date.getUTCDate();
  17989. }
  17990. // Default to current date.
  17991. // * if no year, month, day of month are given, default to today
  17992. // * if day of month is given, default month and year
  17993. // * if month is given, default only year
  17994. // * if year is given, don't default anything
  17995. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  17996. config._a[i] = input[i] = currentDate[i];
  17997. }
  17998. // Zero out whatever was not defaulted, including time
  17999. for (; i < 7; i++) {
  18000. config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
  18001. }
  18002. // add the offsets to the time to be parsed so that we can have a clean array for checking isValid
  18003. input[HOUR] += toInt((config._tzm || 0) / 60);
  18004. input[MINUTE] += toInt((config._tzm || 0) % 60);
  18005. config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input);
  18006. }
  18007. function dateFromObject(config) {
  18008. var normalizedInput;
  18009. if (config._d) {
  18010. return;
  18011. }
  18012. normalizedInput = normalizeObjectUnits(config._i);
  18013. config._a = [
  18014. normalizedInput.year,
  18015. normalizedInput.month,
  18016. normalizedInput.day,
  18017. normalizedInput.hour,
  18018. normalizedInput.minute,
  18019. normalizedInput.second,
  18020. normalizedInput.millisecond
  18021. ];
  18022. dateFromConfig(config);
  18023. }
  18024. function currentDateArray(config) {
  18025. var now = new Date();
  18026. if (config._useUTC) {
  18027. return [
  18028. now.getUTCFullYear(),
  18029. now.getUTCMonth(),
  18030. now.getUTCDate()
  18031. ];
  18032. } else {
  18033. return [now.getFullYear(), now.getMonth(), now.getDate()];
  18034. }
  18035. }
  18036. // date from string and format string
  18037. function makeDateFromStringAndFormat(config) {
  18038. config._a = [];
  18039. config._pf.empty = true;
  18040. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  18041. var lang = getLangDefinition(config._l),
  18042. string = '' + config._i,
  18043. i, parsedInput, tokens, token, skipped,
  18044. stringLength = string.length,
  18045. totalParsedInputLength = 0;
  18046. tokens = expandFormat(config._f, lang).match(formattingTokens) || [];
  18047. for (i = 0; i < tokens.length; i++) {
  18048. token = tokens[i];
  18049. parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
  18050. if (parsedInput) {
  18051. skipped = string.substr(0, string.indexOf(parsedInput));
  18052. if (skipped.length > 0) {
  18053. config._pf.unusedInput.push(skipped);
  18054. }
  18055. string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
  18056. totalParsedInputLength += parsedInput.length;
  18057. }
  18058. // don't parse if it's not a known token
  18059. if (formatTokenFunctions[token]) {
  18060. if (parsedInput) {
  18061. config._pf.empty = false;
  18062. }
  18063. else {
  18064. config._pf.unusedTokens.push(token);
  18065. }
  18066. addTimeToArrayFromToken(token, parsedInput, config);
  18067. }
  18068. else if (config._strict && !parsedInput) {
  18069. config._pf.unusedTokens.push(token);
  18070. }
  18071. }
  18072. // add remaining unparsed input length to the string
  18073. config._pf.charsLeftOver = stringLength - totalParsedInputLength;
  18074. if (string.length > 0) {
  18075. config._pf.unusedInput.push(string);
  18076. }
  18077. // handle am pm
  18078. if (config._isPm && config._a[HOUR] < 12) {
  18079. config._a[HOUR] += 12;
  18080. }
  18081. // if is 12 am, change hours to 0
  18082. if (config._isPm === false && config._a[HOUR] === 12) {
  18083. config._a[HOUR] = 0;
  18084. }
  18085. dateFromConfig(config);
  18086. checkOverflow(config);
  18087. }
  18088. function unescapeFormat(s) {
  18089. return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
  18090. return p1 || p2 || p3 || p4;
  18091. });
  18092. }
  18093. // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  18094. function regexpEscape(s) {
  18095. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  18096. }
  18097. // date from string and array of format strings
  18098. function makeDateFromStringAndArray(config) {
  18099. var tempConfig,
  18100. bestMoment,
  18101. scoreToBeat,
  18102. i,
  18103. currentScore;
  18104. if (config._f.length === 0) {
  18105. config._pf.invalidFormat = true;
  18106. config._d = new Date(NaN);
  18107. return;
  18108. }
  18109. for (i = 0; i < config._f.length; i++) {
  18110. currentScore = 0;
  18111. tempConfig = extend({}, config);
  18112. tempConfig._pf = defaultParsingFlags();
  18113. tempConfig._f = config._f[i];
  18114. makeDateFromStringAndFormat(tempConfig);
  18115. if (!isValid(tempConfig)) {
  18116. continue;
  18117. }
  18118. // if there is any input that was not parsed add a penalty for that format
  18119. currentScore += tempConfig._pf.charsLeftOver;
  18120. //or tokens
  18121. currentScore += tempConfig._pf.unusedTokens.length * 10;
  18122. tempConfig._pf.score = currentScore;
  18123. if (scoreToBeat == null || currentScore < scoreToBeat) {
  18124. scoreToBeat = currentScore;
  18125. bestMoment = tempConfig;
  18126. }
  18127. }
  18128. extend(config, bestMoment || tempConfig);
  18129. }
  18130. // date from iso format
  18131. function makeDateFromString(config) {
  18132. var i, l,
  18133. string = config._i,
  18134. match = isoRegex.exec(string);
  18135. if (match) {
  18136. config._pf.iso = true;
  18137. for (i = 0, l = isoDates.length; i < l; i++) {
  18138. if (isoDates[i][1].exec(string)) {
  18139. // match[5] should be "T" or undefined
  18140. config._f = isoDates[i][0] + (match[6] || " ");
  18141. break;
  18142. }
  18143. }
  18144. for (i = 0, l = isoTimes.length; i < l; i++) {
  18145. if (isoTimes[i][1].exec(string)) {
  18146. config._f += isoTimes[i][0];
  18147. break;
  18148. }
  18149. }
  18150. if (string.match(parseTokenTimezone)) {
  18151. config._f += "Z";
  18152. }
  18153. makeDateFromStringAndFormat(config);
  18154. }
  18155. else {
  18156. config._d = new Date(string);
  18157. }
  18158. }
  18159. function makeDateFromInput(config) {
  18160. var input = config._i,
  18161. matched = aspNetJsonRegex.exec(input);
  18162. if (input === undefined) {
  18163. config._d = new Date();
  18164. } else if (matched) {
  18165. config._d = new Date(+matched[1]);
  18166. } else if (typeof input === 'string') {
  18167. makeDateFromString(config);
  18168. } else if (isArray(input)) {
  18169. config._a = input.slice(0);
  18170. dateFromConfig(config);
  18171. } else if (isDate(input)) {
  18172. config._d = new Date(+input);
  18173. } else if (typeof(input) === 'object') {
  18174. dateFromObject(config);
  18175. } else {
  18176. config._d = new Date(input);
  18177. }
  18178. }
  18179. function makeDate(y, m, d, h, M, s, ms) {
  18180. //can't just apply() to create a date:
  18181. //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply
  18182. var date = new Date(y, m, d, h, M, s, ms);
  18183. //the date constructor doesn't accept years < 1970
  18184. if (y < 1970) {
  18185. date.setFullYear(y);
  18186. }
  18187. return date;
  18188. }
  18189. function makeUTCDate(y) {
  18190. var date = new Date(Date.UTC.apply(null, arguments));
  18191. if (y < 1970) {
  18192. date.setUTCFullYear(y);
  18193. }
  18194. return date;
  18195. }
  18196. function parseWeekday(input, language) {
  18197. if (typeof input === 'string') {
  18198. if (!isNaN(input)) {
  18199. input = parseInt(input, 10);
  18200. }
  18201. else {
  18202. input = language.weekdaysParse(input);
  18203. if (typeof input !== 'number') {
  18204. return null;
  18205. }
  18206. }
  18207. }
  18208. return input;
  18209. }
  18210. /************************************
  18211. Relative Time
  18212. ************************************/
  18213. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  18214. function substituteTimeAgo(string, number, withoutSuffix, isFuture, lang) {
  18215. return lang.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  18216. }
  18217. function relativeTime(milliseconds, withoutSuffix, lang) {
  18218. var seconds = round(Math.abs(milliseconds) / 1000),
  18219. minutes = round(seconds / 60),
  18220. hours = round(minutes / 60),
  18221. days = round(hours / 24),
  18222. years = round(days / 365),
  18223. args = seconds < 45 && ['s', seconds] ||
  18224. minutes === 1 && ['m'] ||
  18225. minutes < 45 && ['mm', minutes] ||
  18226. hours === 1 && ['h'] ||
  18227. hours < 22 && ['hh', hours] ||
  18228. days === 1 && ['d'] ||
  18229. days <= 25 && ['dd', days] ||
  18230. days <= 45 && ['M'] ||
  18231. days < 345 && ['MM', round(days / 30)] ||
  18232. years === 1 && ['y'] || ['yy', years];
  18233. args[2] = withoutSuffix;
  18234. args[3] = milliseconds > 0;
  18235. args[4] = lang;
  18236. return substituteTimeAgo.apply({}, args);
  18237. }
  18238. /************************************
  18239. Week of Year
  18240. ************************************/
  18241. // firstDayOfWeek 0 = sun, 6 = sat
  18242. // the day of the week that starts the week
  18243. // (usually sunday or monday)
  18244. // firstDayOfWeekOfYear 0 = sun, 6 = sat
  18245. // the first week is the week that contains the first
  18246. // of this day of the week
  18247. // (eg. ISO weeks use thursday (4))
  18248. function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) {
  18249. var end = firstDayOfWeekOfYear - firstDayOfWeek,
  18250. daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(),
  18251. adjustedMoment;
  18252. if (daysToDayOfWeek > end) {
  18253. daysToDayOfWeek -= 7;
  18254. }
  18255. if (daysToDayOfWeek < end - 7) {
  18256. daysToDayOfWeek += 7;
  18257. }
  18258. adjustedMoment = moment(mom).add('d', daysToDayOfWeek);
  18259. return {
  18260. week: Math.ceil(adjustedMoment.dayOfYear() / 7),
  18261. year: adjustedMoment.year()
  18262. };
  18263. }
  18264. //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
  18265. function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) {
  18266. var d = makeUTCDate(year, 0, 1).getUTCDay(), daysToAdd, dayOfYear;
  18267. weekday = weekday != null ? weekday : firstDayOfWeek;
  18268. daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0);
  18269. dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1;
  18270. return {
  18271. year: dayOfYear > 0 ? year : year - 1,
  18272. dayOfYear: dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear
  18273. };
  18274. }
  18275. /************************************
  18276. Top Level Functions
  18277. ************************************/
  18278. function makeMoment(config) {
  18279. var input = config._i,
  18280. format = config._f;
  18281. if (input === null) {
  18282. return moment.invalid({nullInput: true});
  18283. }
  18284. if (typeof input === 'string') {
  18285. config._i = input = getLangDefinition().preparse(input);
  18286. }
  18287. if (moment.isMoment(input)) {
  18288. config = cloneMoment(input);
  18289. config._d = new Date(+input._d);
  18290. } else if (format) {
  18291. if (isArray(format)) {
  18292. makeDateFromStringAndArray(config);
  18293. } else {
  18294. makeDateFromStringAndFormat(config);
  18295. }
  18296. } else {
  18297. makeDateFromInput(config);
  18298. }
  18299. return new Moment(config);
  18300. }
  18301. moment = function (input, format, lang, strict) {
  18302. var c;
  18303. if (typeof(lang) === "boolean") {
  18304. strict = lang;
  18305. lang = undefined;
  18306. }
  18307. // object construction must be done this way.
  18308. // https://github.com/moment/moment/issues/1423
  18309. c = {};
  18310. c._isAMomentObject = true;
  18311. c._i = input;
  18312. c._f = format;
  18313. c._l = lang;
  18314. c._strict = strict;
  18315. c._isUTC = false;
  18316. c._pf = defaultParsingFlags();
  18317. return makeMoment(c);
  18318. };
  18319. // creating with utc
  18320. moment.utc = function (input, format, lang, strict) {
  18321. var c;
  18322. if (typeof(lang) === "boolean") {
  18323. strict = lang;
  18324. lang = undefined;
  18325. }
  18326. // object construction must be done this way.
  18327. // https://github.com/moment/moment/issues/1423
  18328. c = {};
  18329. c._isAMomentObject = true;
  18330. c._useUTC = true;
  18331. c._isUTC = true;
  18332. c._l = lang;
  18333. c._i = input;
  18334. c._f = format;
  18335. c._strict = strict;
  18336. c._pf = defaultParsingFlags();
  18337. return makeMoment(c).utc();
  18338. };
  18339. // creating with unix timestamp (in seconds)
  18340. moment.unix = function (input) {
  18341. return moment(input * 1000);
  18342. };
  18343. // duration
  18344. moment.duration = function (input, key) {
  18345. var duration = input,
  18346. // matching against regexp is expensive, do it on demand
  18347. match = null,
  18348. sign,
  18349. ret,
  18350. parseIso;
  18351. if (moment.isDuration(input)) {
  18352. duration = {
  18353. ms: input._milliseconds,
  18354. d: input._days,
  18355. M: input._months
  18356. };
  18357. } else if (typeof input === 'number') {
  18358. duration = {};
  18359. if (key) {
  18360. duration[key] = input;
  18361. } else {
  18362. duration.milliseconds = input;
  18363. }
  18364. } else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) {
  18365. sign = (match[1] === "-") ? -1 : 1;
  18366. duration = {
  18367. y: 0,
  18368. d: toInt(match[DATE]) * sign,
  18369. h: toInt(match[HOUR]) * sign,
  18370. m: toInt(match[MINUTE]) * sign,
  18371. s: toInt(match[SECOND]) * sign,
  18372. ms: toInt(match[MILLISECOND]) * sign
  18373. };
  18374. } else if (!!(match = isoDurationRegex.exec(input))) {
  18375. sign = (match[1] === "-") ? -1 : 1;
  18376. parseIso = function (inp) {
  18377. // We'd normally use ~~inp for this, but unfortunately it also
  18378. // converts floats to ints.
  18379. // inp may be undefined, so careful calling replace on it.
  18380. var res = inp && parseFloat(inp.replace(',', '.'));
  18381. // apply sign while we're at it
  18382. return (isNaN(res) ? 0 : res) * sign;
  18383. };
  18384. duration = {
  18385. y: parseIso(match[2]),
  18386. M: parseIso(match[3]),
  18387. d: parseIso(match[4]),
  18388. h: parseIso(match[5]),
  18389. m: parseIso(match[6]),
  18390. s: parseIso(match[7]),
  18391. w: parseIso(match[8])
  18392. };
  18393. }
  18394. ret = new Duration(duration);
  18395. if (moment.isDuration(input) && input.hasOwnProperty('_lang')) {
  18396. ret._lang = input._lang;
  18397. }
  18398. return ret;
  18399. };
  18400. // version number
  18401. moment.version = VERSION;
  18402. // default format
  18403. moment.defaultFormat = isoFormat;
  18404. // This function will be called whenever a moment is mutated.
  18405. // It is intended to keep the offset in sync with the timezone.
  18406. moment.updateOffset = function () {};
  18407. // This function will load languages and then set the global language. If
  18408. // no arguments are passed in, it will simply return the current global
  18409. // language key.
  18410. moment.lang = function (key, values) {
  18411. var r;
  18412. if (!key) {
  18413. return moment.fn._lang._abbr;
  18414. }
  18415. if (values) {
  18416. loadLang(normalizeLanguage(key), values);
  18417. } else if (values === null) {
  18418. unloadLang(key);
  18419. key = 'en';
  18420. } else if (!languages[key]) {
  18421. getLangDefinition(key);
  18422. }
  18423. r = moment.duration.fn._lang = moment.fn._lang = getLangDefinition(key);
  18424. return r._abbr;
  18425. };
  18426. // returns language data
  18427. moment.langData = function (key) {
  18428. if (key && key._lang && key._lang._abbr) {
  18429. key = key._lang._abbr;
  18430. }
  18431. return getLangDefinition(key);
  18432. };
  18433. // compare moment object
  18434. moment.isMoment = function (obj) {
  18435. return obj instanceof Moment ||
  18436. (obj != null && obj.hasOwnProperty('_isAMomentObject'));
  18437. };
  18438. // for typechecking Duration objects
  18439. moment.isDuration = function (obj) {
  18440. return obj instanceof Duration;
  18441. };
  18442. for (i = lists.length - 1; i >= 0; --i) {
  18443. makeList(lists[i]);
  18444. }
  18445. moment.normalizeUnits = function (units) {
  18446. return normalizeUnits(units);
  18447. };
  18448. moment.invalid = function (flags) {
  18449. var m = moment.utc(NaN);
  18450. if (flags != null) {
  18451. extend(m._pf, flags);
  18452. }
  18453. else {
  18454. m._pf.userInvalidated = true;
  18455. }
  18456. return m;
  18457. };
  18458. moment.parseZone = function (input) {
  18459. return moment(input).parseZone();
  18460. };
  18461. /************************************
  18462. Moment Prototype
  18463. ************************************/
  18464. extend(moment.fn = Moment.prototype, {
  18465. clone : function () {
  18466. return moment(this);
  18467. },
  18468. valueOf : function () {
  18469. return +this._d + ((this._offset || 0) * 60000);
  18470. },
  18471. unix : function () {
  18472. return Math.floor(+this / 1000);
  18473. },
  18474. toString : function () {
  18475. return this.clone().lang('en').format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ");
  18476. },
  18477. toDate : function () {
  18478. return this._offset ? new Date(+this) : this._d;
  18479. },
  18480. toISOString : function () {
  18481. var m = moment(this).utc();
  18482. if (0 < m.year() && m.year() <= 9999) {
  18483. return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  18484. } else {
  18485. return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  18486. }
  18487. },
  18488. toArray : function () {
  18489. var m = this;
  18490. return [
  18491. m.year(),
  18492. m.month(),
  18493. m.date(),
  18494. m.hours(),
  18495. m.minutes(),
  18496. m.seconds(),
  18497. m.milliseconds()
  18498. ];
  18499. },
  18500. isValid : function () {
  18501. return isValid(this);
  18502. },
  18503. isDSTShifted : function () {
  18504. if (this._a) {
  18505. return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0;
  18506. }
  18507. return false;
  18508. },
  18509. parsingFlags : function () {
  18510. return extend({}, this._pf);
  18511. },
  18512. invalidAt: function () {
  18513. return this._pf.overflow;
  18514. },
  18515. utc : function () {
  18516. return this.zone(0);
  18517. },
  18518. local : function () {
  18519. this.zone(0);
  18520. this._isUTC = false;
  18521. return this;
  18522. },
  18523. format : function (inputString) {
  18524. var output = formatMoment(this, inputString || moment.defaultFormat);
  18525. return this.lang().postformat(output);
  18526. },
  18527. add : function (input, val) {
  18528. var dur;
  18529. // switch args to support add('s', 1) and add(1, 's')
  18530. if (typeof input === 'string') {
  18531. dur = moment.duration(+val, input);
  18532. } else {
  18533. dur = moment.duration(input, val);
  18534. }
  18535. addOrSubtractDurationFromMoment(this, dur, 1);
  18536. return this;
  18537. },
  18538. subtract : function (input, val) {
  18539. var dur;
  18540. // switch args to support subtract('s', 1) and subtract(1, 's')
  18541. if (typeof input === 'string') {
  18542. dur = moment.duration(+val, input);
  18543. } else {
  18544. dur = moment.duration(input, val);
  18545. }
  18546. addOrSubtractDurationFromMoment(this, dur, -1);
  18547. return this;
  18548. },
  18549. diff : function (input, units, asFloat) {
  18550. var that = makeAs(input, this),
  18551. zoneDiff = (this.zone() - that.zone()) * 6e4,
  18552. diff, output;
  18553. units = normalizeUnits(units);
  18554. if (units === 'year' || units === 'month') {
  18555. // average number of days in the months in the given dates
  18556. diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2
  18557. // difference in months
  18558. output = ((this.year() - that.year()) * 12) + (this.month() - that.month());
  18559. // adjust by taking difference in days, average number of days
  18560. // and dst in the given months.
  18561. output += ((this - moment(this).startOf('month')) -
  18562. (that - moment(that).startOf('month'))) / diff;
  18563. // same as above but with zones, to negate all dst
  18564. output -= ((this.zone() - moment(this).startOf('month').zone()) -
  18565. (that.zone() - moment(that).startOf('month').zone())) * 6e4 / diff;
  18566. if (units === 'year') {
  18567. output = output / 12;
  18568. }
  18569. } else {
  18570. diff = (this - that);
  18571. output = units === 'second' ? diff / 1e3 : // 1000
  18572. units === 'minute' ? diff / 6e4 : // 1000 * 60
  18573. units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60
  18574. units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
  18575. units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
  18576. diff;
  18577. }
  18578. return asFloat ? output : absRound(output);
  18579. },
  18580. from : function (time, withoutSuffix) {
  18581. return moment.duration(this.diff(time)).lang(this.lang()._abbr).humanize(!withoutSuffix);
  18582. },
  18583. fromNow : function (withoutSuffix) {
  18584. return this.from(moment(), withoutSuffix);
  18585. },
  18586. calendar : function () {
  18587. // We want to compare the start of today, vs this.
  18588. // Getting start-of-today depends on whether we're zone'd or not.
  18589. var sod = makeAs(moment(), this).startOf('day'),
  18590. diff = this.diff(sod, 'days', true),
  18591. format = diff < -6 ? 'sameElse' :
  18592. diff < -1 ? 'lastWeek' :
  18593. diff < 0 ? 'lastDay' :
  18594. diff < 1 ? 'sameDay' :
  18595. diff < 2 ? 'nextDay' :
  18596. diff < 7 ? 'nextWeek' : 'sameElse';
  18597. return this.format(this.lang().calendar(format, this));
  18598. },
  18599. isLeapYear : function () {
  18600. return isLeapYear(this.year());
  18601. },
  18602. isDST : function () {
  18603. return (this.zone() < this.clone().month(0).zone() ||
  18604. this.zone() < this.clone().month(5).zone());
  18605. },
  18606. day : function (input) {
  18607. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  18608. if (input != null) {
  18609. input = parseWeekday(input, this.lang());
  18610. return this.add({ d : input - day });
  18611. } else {
  18612. return day;
  18613. }
  18614. },
  18615. month : function (input) {
  18616. var utc = this._isUTC ? 'UTC' : '',
  18617. dayOfMonth;
  18618. if (input != null) {
  18619. if (typeof input === 'string') {
  18620. input = this.lang().monthsParse(input);
  18621. if (typeof input !== 'number') {
  18622. return this;
  18623. }
  18624. }
  18625. dayOfMonth = this.date();
  18626. this.date(1);
  18627. this._d['set' + utc + 'Month'](input);
  18628. this.date(Math.min(dayOfMonth, this.daysInMonth()));
  18629. moment.updateOffset(this);
  18630. return this;
  18631. } else {
  18632. return this._d['get' + utc + 'Month']();
  18633. }
  18634. },
  18635. startOf: function (units) {
  18636. units = normalizeUnits(units);
  18637. // the following switch intentionally omits break keywords
  18638. // to utilize falling through the cases.
  18639. switch (units) {
  18640. case 'year':
  18641. this.month(0);
  18642. /* falls through */
  18643. case 'month':
  18644. this.date(1);
  18645. /* falls through */
  18646. case 'week':
  18647. case 'isoWeek':
  18648. case 'day':
  18649. this.hours(0);
  18650. /* falls through */
  18651. case 'hour':
  18652. this.minutes(0);
  18653. /* falls through */
  18654. case 'minute':
  18655. this.seconds(0);
  18656. /* falls through */
  18657. case 'second':
  18658. this.milliseconds(0);
  18659. /* falls through */
  18660. }
  18661. // weeks are a special case
  18662. if (units === 'week') {
  18663. this.weekday(0);
  18664. } else if (units === 'isoWeek') {
  18665. this.isoWeekday(1);
  18666. }
  18667. return this;
  18668. },
  18669. endOf: function (units) {
  18670. units = normalizeUnits(units);
  18671. return this.startOf(units).add((units === 'isoWeek' ? 'week' : units), 1).subtract('ms', 1);
  18672. },
  18673. isAfter: function (input, units) {
  18674. units = typeof units !== 'undefined' ? units : 'millisecond';
  18675. return +this.clone().startOf(units) > +moment(input).startOf(units);
  18676. },
  18677. isBefore: function (input, units) {
  18678. units = typeof units !== 'undefined' ? units : 'millisecond';
  18679. return +this.clone().startOf(units) < +moment(input).startOf(units);
  18680. },
  18681. isSame: function (input, units) {
  18682. units = units || 'ms';
  18683. return +this.clone().startOf(units) === +makeAs(input, this).startOf(units);
  18684. },
  18685. min: function (other) {
  18686. other = moment.apply(null, arguments);
  18687. return other < this ? this : other;
  18688. },
  18689. max: function (other) {
  18690. other = moment.apply(null, arguments);
  18691. return other > this ? this : other;
  18692. },
  18693. zone : function (input) {
  18694. var offset = this._offset || 0;
  18695. if (input != null) {
  18696. if (typeof input === "string") {
  18697. input = timezoneMinutesFromString(input);
  18698. }
  18699. if (Math.abs(input) < 16) {
  18700. input = input * 60;
  18701. }
  18702. this._offset = input;
  18703. this._isUTC = true;
  18704. if (offset !== input) {
  18705. addOrSubtractDurationFromMoment(this, moment.duration(offset - input, 'm'), 1, true);
  18706. }
  18707. } else {
  18708. return this._isUTC ? offset : this._d.getTimezoneOffset();
  18709. }
  18710. return this;
  18711. },
  18712. zoneAbbr : function () {
  18713. return this._isUTC ? "UTC" : "";
  18714. },
  18715. zoneName : function () {
  18716. return this._isUTC ? "Coordinated Universal Time" : "";
  18717. },
  18718. parseZone : function () {
  18719. if (this._tzm) {
  18720. this.zone(this._tzm);
  18721. } else if (typeof this._i === 'string') {
  18722. this.zone(this._i);
  18723. }
  18724. return this;
  18725. },
  18726. hasAlignedHourOffset : function (input) {
  18727. if (!input) {
  18728. input = 0;
  18729. }
  18730. else {
  18731. input = moment(input).zone();
  18732. }
  18733. return (this.zone() - input) % 60 === 0;
  18734. },
  18735. daysInMonth : function () {
  18736. return daysInMonth(this.year(), this.month());
  18737. },
  18738. dayOfYear : function (input) {
  18739. var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1;
  18740. return input == null ? dayOfYear : this.add("d", (input - dayOfYear));
  18741. },
  18742. quarter : function () {
  18743. return Math.ceil((this.month() + 1.0) / 3.0);
  18744. },
  18745. weekYear : function (input) {
  18746. var year = weekOfYear(this, this.lang()._week.dow, this.lang()._week.doy).year;
  18747. return input == null ? year : this.add("y", (input - year));
  18748. },
  18749. isoWeekYear : function (input) {
  18750. var year = weekOfYear(this, 1, 4).year;
  18751. return input == null ? year : this.add("y", (input - year));
  18752. },
  18753. week : function (input) {
  18754. var week = this.lang().week(this);
  18755. return input == null ? week : this.add("d", (input - week) * 7);
  18756. },
  18757. isoWeek : function (input) {
  18758. var week = weekOfYear(this, 1, 4).week;
  18759. return input == null ? week : this.add("d", (input - week) * 7);
  18760. },
  18761. weekday : function (input) {
  18762. var weekday = (this.day() + 7 - this.lang()._week.dow) % 7;
  18763. return input == null ? weekday : this.add("d", input - weekday);
  18764. },
  18765. isoWeekday : function (input) {
  18766. // behaves the same as moment#day except
  18767. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  18768. // as a setter, sunday should belong to the previous week.
  18769. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7);
  18770. },
  18771. get : function (units) {
  18772. units = normalizeUnits(units);
  18773. return this[units]();
  18774. },
  18775. set : function (units, value) {
  18776. units = normalizeUnits(units);
  18777. if (typeof this[units] === 'function') {
  18778. this[units](value);
  18779. }
  18780. return this;
  18781. },
  18782. // If passed a language key, it will set the language for this
  18783. // instance. Otherwise, it will return the language configuration
  18784. // variables for this instance.
  18785. lang : function (key) {
  18786. if (key === undefined) {
  18787. return this._lang;
  18788. } else {
  18789. this._lang = getLangDefinition(key);
  18790. return this;
  18791. }
  18792. }
  18793. });
  18794. // helper for adding shortcuts
  18795. function makeGetterAndSetter(name, key) {
  18796. moment.fn[name] = moment.fn[name + 's'] = function (input) {
  18797. var utc = this._isUTC ? 'UTC' : '';
  18798. if (input != null) {
  18799. this._d['set' + utc + key](input);
  18800. moment.updateOffset(this);
  18801. return this;
  18802. } else {
  18803. return this._d['get' + utc + key]();
  18804. }
  18805. };
  18806. }
  18807. // loop through and add shortcuts (Month, Date, Hours, Minutes, Seconds, Milliseconds)
  18808. for (i = 0; i < proxyGettersAndSetters.length; i ++) {
  18809. makeGetterAndSetter(proxyGettersAndSetters[i].toLowerCase().replace(/s$/, ''), proxyGettersAndSetters[i]);
  18810. }
  18811. // add shortcut for year (uses different syntax than the getter/setter 'year' == 'FullYear')
  18812. makeGetterAndSetter('year', 'FullYear');
  18813. // add plural methods
  18814. moment.fn.days = moment.fn.day;
  18815. moment.fn.months = moment.fn.month;
  18816. moment.fn.weeks = moment.fn.week;
  18817. moment.fn.isoWeeks = moment.fn.isoWeek;
  18818. // add aliased format methods
  18819. moment.fn.toJSON = moment.fn.toISOString;
  18820. /************************************
  18821. Duration Prototype
  18822. ************************************/
  18823. extend(moment.duration.fn = Duration.prototype, {
  18824. _bubble : function () {
  18825. var milliseconds = this._milliseconds,
  18826. days = this._days,
  18827. months = this._months,
  18828. data = this._data,
  18829. seconds, minutes, hours, years;
  18830. // The following code bubbles up values, see the tests for
  18831. // examples of what that means.
  18832. data.milliseconds = milliseconds % 1000;
  18833. seconds = absRound(milliseconds / 1000);
  18834. data.seconds = seconds % 60;
  18835. minutes = absRound(seconds / 60);
  18836. data.minutes = minutes % 60;
  18837. hours = absRound(minutes / 60);
  18838. data.hours = hours % 24;
  18839. days += absRound(hours / 24);
  18840. data.days = days % 30;
  18841. months += absRound(days / 30);
  18842. data.months = months % 12;
  18843. years = absRound(months / 12);
  18844. data.years = years;
  18845. },
  18846. weeks : function () {
  18847. return absRound(this.days() / 7);
  18848. },
  18849. valueOf : function () {
  18850. return this._milliseconds +
  18851. this._days * 864e5 +
  18852. (this._months % 12) * 2592e6 +
  18853. toInt(this._months / 12) * 31536e6;
  18854. },
  18855. humanize : function (withSuffix) {
  18856. var difference = +this,
  18857. output = relativeTime(difference, !withSuffix, this.lang());
  18858. if (withSuffix) {
  18859. output = this.lang().pastFuture(difference, output);
  18860. }
  18861. return this.lang().postformat(output);
  18862. },
  18863. add : function (input, val) {
  18864. // supports only 2.0-style add(1, 's') or add(moment)
  18865. var dur = moment.duration(input, val);
  18866. this._milliseconds += dur._milliseconds;
  18867. this._days += dur._days;
  18868. this._months += dur._months;
  18869. this._bubble();
  18870. return this;
  18871. },
  18872. subtract : function (input, val) {
  18873. var dur = moment.duration(input, val);
  18874. this._milliseconds -= dur._milliseconds;
  18875. this._days -= dur._days;
  18876. this._months -= dur._months;
  18877. this._bubble();
  18878. return this;
  18879. },
  18880. get : function (units) {
  18881. units = normalizeUnits(units);
  18882. return this[units.toLowerCase() + 's']();
  18883. },
  18884. as : function (units) {
  18885. units = normalizeUnits(units);
  18886. return this['as' + units.charAt(0).toUpperCase() + units.slice(1) + 's']();
  18887. },
  18888. lang : moment.fn.lang,
  18889. toIsoString : function () {
  18890. // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
  18891. var years = Math.abs(this.years()),
  18892. months = Math.abs(this.months()),
  18893. days = Math.abs(this.days()),
  18894. hours = Math.abs(this.hours()),
  18895. minutes = Math.abs(this.minutes()),
  18896. seconds = Math.abs(this.seconds() + this.milliseconds() / 1000);
  18897. if (!this.asSeconds()) {
  18898. // this is the same as C#'s (Noda) and python (isodate)...
  18899. // but not other JS (goog.date)
  18900. return 'P0D';
  18901. }
  18902. return (this.asSeconds() < 0 ? '-' : '') +
  18903. 'P' +
  18904. (years ? years + 'Y' : '') +
  18905. (months ? months + 'M' : '') +
  18906. (days ? days + 'D' : '') +
  18907. ((hours || minutes || seconds) ? 'T' : '') +
  18908. (hours ? hours + 'H' : '') +
  18909. (minutes ? minutes + 'M' : '') +
  18910. (seconds ? seconds + 'S' : '');
  18911. }
  18912. });
  18913. function makeDurationGetter(name) {
  18914. moment.duration.fn[name] = function () {
  18915. return this._data[name];
  18916. };
  18917. }
  18918. function makeDurationAsGetter(name, factor) {
  18919. moment.duration.fn['as' + name] = function () {
  18920. return +this / factor;
  18921. };
  18922. }
  18923. for (i in unitMillisecondFactors) {
  18924. if (unitMillisecondFactors.hasOwnProperty(i)) {
  18925. makeDurationAsGetter(i, unitMillisecondFactors[i]);
  18926. makeDurationGetter(i.toLowerCase());
  18927. }
  18928. }
  18929. makeDurationAsGetter('Weeks', 6048e5);
  18930. moment.duration.fn.asMonths = function () {
  18931. return (+this - this.years() * 31536e6) / 2592e6 + this.years() * 12;
  18932. };
  18933. /************************************
  18934. Default Lang
  18935. ************************************/
  18936. // Set default language, other languages will inherit from English.
  18937. moment.lang('en', {
  18938. ordinal : function (number) {
  18939. var b = number % 10,
  18940. output = (toInt(number % 100 / 10) === 1) ? 'th' :
  18941. (b === 1) ? 'st' :
  18942. (b === 2) ? 'nd' :
  18943. (b === 3) ? 'rd' : 'th';
  18944. return number + output;
  18945. }
  18946. });
  18947. /* EMBED_LANGUAGES */
  18948. /************************************
  18949. Exposing Moment
  18950. ************************************/
  18951. function makeGlobal(deprecate) {
  18952. var warned = false, local_moment = moment;
  18953. /*global ender:false */
  18954. if (typeof ender !== 'undefined') {
  18955. return;
  18956. }
  18957. // here, `this` means `window` in the browser, or `global` on the server
  18958. // add `moment` as a global object via a string identifier,
  18959. // for Closure Compiler "advanced" mode
  18960. if (deprecate) {
  18961. global.moment = function () {
  18962. if (!warned && console && console.warn) {
  18963. warned = true;
  18964. console.warn(
  18965. "Accessing Moment through the global scope is " +
  18966. "deprecated, and will be removed in an upcoming " +
  18967. "release.");
  18968. }
  18969. return local_moment.apply(null, arguments);
  18970. };
  18971. extend(global.moment, local_moment);
  18972. } else {
  18973. global['moment'] = moment;
  18974. }
  18975. }
  18976. // CommonJS module is defined
  18977. if (hasModule) {
  18978. module.exports = moment;
  18979. makeGlobal(true);
  18980. } else if (typeof define === "function" && define.amd) {
  18981. define("moment", function (require, exports, module) {
  18982. if (module.config && module.config() && module.config().noGlobal !== true) {
  18983. // If user provided noGlobal, he is aware of global
  18984. makeGlobal(module.config().noGlobal === undefined);
  18985. }
  18986. return moment;
  18987. });
  18988. } else {
  18989. makeGlobal();
  18990. }
  18991. }).call(this);
  18992. },{}],5:[function(require,module,exports){
  18993. /**
  18994. * Copyright 2012 Craig Campbell
  18995. *
  18996. * Licensed under the Apache License, Version 2.0 (the "License");
  18997. * you may not use this file except in compliance with the License.
  18998. * You may obtain a copy of the License at
  18999. *
  19000. * http://www.apache.org/licenses/LICENSE-2.0
  19001. *
  19002. * Unless required by applicable law or agreed to in writing, software
  19003. * distributed under the License is distributed on an "AS IS" BASIS,
  19004. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19005. * See the License for the specific language governing permissions and
  19006. * limitations under the License.
  19007. *
  19008. * Mousetrap is a simple keyboard shortcut library for Javascript with
  19009. * no external dependencies
  19010. *
  19011. * @version 1.1.2
  19012. * @url craig.is/killing/mice
  19013. */
  19014. /**
  19015. * mapping of special keycodes to their corresponding keys
  19016. *
  19017. * everything in this dictionary cannot use keypress events
  19018. * so it has to be here to map to the correct keycodes for
  19019. * keyup/keydown events
  19020. *
  19021. * @type {Object}
  19022. */
  19023. var _MAP = {
  19024. 8: 'backspace',
  19025. 9: 'tab',
  19026. 13: 'enter',
  19027. 16: 'shift',
  19028. 17: 'ctrl',
  19029. 18: 'alt',
  19030. 20: 'capslock',
  19031. 27: 'esc',
  19032. 32: 'space',
  19033. 33: 'pageup',
  19034. 34: 'pagedown',
  19035. 35: 'end',
  19036. 36: 'home',
  19037. 37: 'left',
  19038. 38: 'up',
  19039. 39: 'right',
  19040. 40: 'down',
  19041. 45: 'ins',
  19042. 46: 'del',
  19043. 91: 'meta',
  19044. 93: 'meta',
  19045. 224: 'meta'
  19046. },
  19047. /**
  19048. * mapping for special characters so they can support
  19049. *
  19050. * this dictionary is only used incase you want to bind a
  19051. * keyup or keydown event to one of these keys
  19052. *
  19053. * @type {Object}
  19054. */
  19055. _KEYCODE_MAP = {
  19056. 106: '*',
  19057. 107: '+',
  19058. 109: '-',
  19059. 110: '.',
  19060. 111 : '/',
  19061. 186: ';',
  19062. 187: '=',
  19063. 188: ',',
  19064. 189: '-',
  19065. 190: '.',
  19066. 191: '/',
  19067. 192: '`',
  19068. 219: '[',
  19069. 220: '\\',
  19070. 221: ']',
  19071. 222: '\''
  19072. },
  19073. /**
  19074. * this is a mapping of keys that require shift on a US keypad
  19075. * back to the non shift equivelents
  19076. *
  19077. * this is so you can use keyup events with these keys
  19078. *
  19079. * note that this will only work reliably on US keyboards
  19080. *
  19081. * @type {Object}
  19082. */
  19083. _SHIFT_MAP = {
  19084. '~': '`',
  19085. '!': '1',
  19086. '@': '2',
  19087. '#': '3',
  19088. '$': '4',
  19089. '%': '5',
  19090. '^': '6',
  19091. '&': '7',
  19092. '*': '8',
  19093. '(': '9',
  19094. ')': '0',
  19095. '_': '-',
  19096. '+': '=',
  19097. ':': ';',
  19098. '\"': '\'',
  19099. '<': ',',
  19100. '>': '.',
  19101. '?': '/',
  19102. '|': '\\'
  19103. },
  19104. /**
  19105. * this is a list of special strings you can use to map
  19106. * to modifier keys when you specify your keyboard shortcuts
  19107. *
  19108. * @type {Object}
  19109. */
  19110. _SPECIAL_ALIASES = {
  19111. 'option': 'alt',
  19112. 'command': 'meta',
  19113. 'return': 'enter',
  19114. 'escape': 'esc'
  19115. },
  19116. /**
  19117. * variable to store the flipped version of _MAP from above
  19118. * needed to check if we should use keypress or not when no action
  19119. * is specified
  19120. *
  19121. * @type {Object|undefined}
  19122. */
  19123. _REVERSE_MAP,
  19124. /**
  19125. * a list of all the callbacks setup via Mousetrap.bind()
  19126. *
  19127. * @type {Object}
  19128. */
  19129. _callbacks = {},
  19130. /**
  19131. * direct map of string combinations to callbacks used for trigger()
  19132. *
  19133. * @type {Object}
  19134. */
  19135. _direct_map = {},
  19136. /**
  19137. * keeps track of what level each sequence is at since multiple
  19138. * sequences can start out with the same sequence
  19139. *
  19140. * @type {Object}
  19141. */
  19142. _sequence_levels = {},
  19143. /**
  19144. * variable to store the setTimeout call
  19145. *
  19146. * @type {null|number}
  19147. */
  19148. _reset_timer,
  19149. /**
  19150. * temporary state where we will ignore the next keyup
  19151. *
  19152. * @type {boolean|string}
  19153. */
  19154. _ignore_next_keyup = false,
  19155. /**
  19156. * are we currently inside of a sequence?
  19157. * type of action ("keyup" or "keydown" or "keypress") or false
  19158. *
  19159. * @type {boolean|string}
  19160. */
  19161. _inside_sequence = false;
  19162. /**
  19163. * loop through the f keys, f1 to f19 and add them to the map
  19164. * programatically
  19165. */
  19166. for (var i = 1; i < 20; ++i) {
  19167. _MAP[111 + i] = 'f' + i;
  19168. }
  19169. /**
  19170. * loop through to map numbers on the numeric keypad
  19171. */
  19172. for (i = 0; i <= 9; ++i) {
  19173. _MAP[i + 96] = i;
  19174. }
  19175. /**
  19176. * cross browser add event method
  19177. *
  19178. * @param {Element|HTMLDocument} object
  19179. * @param {string} type
  19180. * @param {Function} callback
  19181. * @returns void
  19182. */
  19183. function _addEvent(object, type, callback) {
  19184. if (object.addEventListener) {
  19185. return object.addEventListener(type, callback, false);
  19186. }
  19187. object.attachEvent('on' + type, callback);
  19188. }
  19189. /**
  19190. * takes the event and returns the key character
  19191. *
  19192. * @param {Event} e
  19193. * @return {string}
  19194. */
  19195. function _characterFromEvent(e) {
  19196. // for keypress events we should return the character as is
  19197. if (e.type == 'keypress') {
  19198. return String.fromCharCode(e.which);
  19199. }
  19200. // for non keypress events the special maps are needed
  19201. if (_MAP[e.which]) {
  19202. return _MAP[e.which];
  19203. }
  19204. if (_KEYCODE_MAP[e.which]) {
  19205. return _KEYCODE_MAP[e.which];
  19206. }
  19207. // if it is not in the special map
  19208. return String.fromCharCode(e.which).toLowerCase();
  19209. }
  19210. /**
  19211. * should we stop this event before firing off callbacks
  19212. *
  19213. * @param {Event} e
  19214. * @return {boolean}
  19215. */
  19216. function _stop(e) {
  19217. var element = e.target || e.srcElement,
  19218. tag_name = element.tagName;
  19219. // if the element has the class "mousetrap" then no need to stop
  19220. if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {
  19221. return false;
  19222. }
  19223. // stop for input, select, and textarea
  19224. return tag_name == 'INPUT' || tag_name == 'SELECT' || tag_name == 'TEXTAREA' || (element.contentEditable && element.contentEditable == 'true');
  19225. }
  19226. /**
  19227. * checks if two arrays are equal
  19228. *
  19229. * @param {Array} modifiers1
  19230. * @param {Array} modifiers2
  19231. * @returns {boolean}
  19232. */
  19233. function _modifiersMatch(modifiers1, modifiers2) {
  19234. return modifiers1.sort().join(',') === modifiers2.sort().join(',');
  19235. }
  19236. /**
  19237. * resets all sequence counters except for the ones passed in
  19238. *
  19239. * @param {Object} do_not_reset
  19240. * @returns void
  19241. */
  19242. function _resetSequences(do_not_reset) {
  19243. do_not_reset = do_not_reset || {};
  19244. var active_sequences = false,
  19245. key;
  19246. for (key in _sequence_levels) {
  19247. if (do_not_reset[key]) {
  19248. active_sequences = true;
  19249. continue;
  19250. }
  19251. _sequence_levels[key] = 0;
  19252. }
  19253. if (!active_sequences) {
  19254. _inside_sequence = false;
  19255. }
  19256. }
  19257. /**
  19258. * finds all callbacks that match based on the keycode, modifiers,
  19259. * and action
  19260. *
  19261. * @param {string} character
  19262. * @param {Array} modifiers
  19263. * @param {string} action
  19264. * @param {boolean=} remove - should we remove any matches
  19265. * @param {string=} combination
  19266. * @returns {Array}
  19267. */
  19268. function _getMatches(character, modifiers, action, remove, combination) {
  19269. var i,
  19270. callback,
  19271. matches = [];
  19272. // if there are no events related to this keycode
  19273. if (!_callbacks[character]) {
  19274. return [];
  19275. }
  19276. // if a modifier key is coming up on its own we should allow it
  19277. if (action == 'keyup' && _isModifier(character)) {
  19278. modifiers = [character];
  19279. }
  19280. // loop through all callbacks for the key that was pressed
  19281. // and see if any of them match
  19282. for (i = 0; i < _callbacks[character].length; ++i) {
  19283. callback = _callbacks[character][i];
  19284. // if this is a sequence but it is not at the right level
  19285. // then move onto the next match
  19286. if (callback.seq && _sequence_levels[callback.seq] != callback.level) {
  19287. continue;
  19288. }
  19289. // if the action we are looking for doesn't match the action we got
  19290. // then we should keep going
  19291. if (action != callback.action) {
  19292. continue;
  19293. }
  19294. // if this is a keypress event that means that we need to only
  19295. // look at the character, otherwise check the modifiers as
  19296. // well
  19297. if (action == 'keypress' || _modifiersMatch(modifiers, callback.modifiers)) {
  19298. // remove is used so if you change your mind and call bind a
  19299. // second time with a new function the first one is overwritten
  19300. if (remove && callback.combo == combination) {
  19301. _callbacks[character].splice(i, 1);
  19302. }
  19303. matches.push(callback);
  19304. }
  19305. }
  19306. return matches;
  19307. }
  19308. /**
  19309. * takes a key event and figures out what the modifiers are
  19310. *
  19311. * @param {Event} e
  19312. * @returns {Array}
  19313. */
  19314. function _eventModifiers(e) {
  19315. var modifiers = [];
  19316. if (e.shiftKey) {
  19317. modifiers.push('shift');
  19318. }
  19319. if (e.altKey) {
  19320. modifiers.push('alt');
  19321. }
  19322. if (e.ctrlKey) {
  19323. modifiers.push('ctrl');
  19324. }
  19325. if (e.metaKey) {
  19326. modifiers.push('meta');
  19327. }
  19328. return modifiers;
  19329. }
  19330. /**
  19331. * actually calls the callback function
  19332. *
  19333. * if your callback function returns false this will use the jquery
  19334. * convention - prevent default and stop propogation on the event
  19335. *
  19336. * @param {Function} callback
  19337. * @param {Event} e
  19338. * @returns void
  19339. */
  19340. function _fireCallback(callback, e) {
  19341. if (callback(e) === false) {
  19342. if (e.preventDefault) {
  19343. e.preventDefault();
  19344. }
  19345. if (e.stopPropagation) {
  19346. e.stopPropagation();
  19347. }
  19348. e.returnValue = false;
  19349. e.cancelBubble = true;
  19350. }
  19351. }
  19352. /**
  19353. * handles a character key event
  19354. *
  19355. * @param {string} character
  19356. * @param {Event} e
  19357. * @returns void
  19358. */
  19359. function _handleCharacter(character, e) {
  19360. // if this event should not happen stop here
  19361. if (_stop(e)) {
  19362. return;
  19363. }
  19364. var callbacks = _getMatches(character, _eventModifiers(e), e.type),
  19365. i,
  19366. do_not_reset = {},
  19367. processed_sequence_callback = false;
  19368. // loop through matching callbacks for this key event
  19369. for (i = 0; i < callbacks.length; ++i) {
  19370. // fire for all sequence callbacks
  19371. // this is because if for example you have multiple sequences
  19372. // bound such as "g i" and "g t" they both need to fire the
  19373. // callback for matching g cause otherwise you can only ever
  19374. // match the first one
  19375. if (callbacks[i].seq) {
  19376. processed_sequence_callback = true;
  19377. // keep a list of which sequences were matches for later
  19378. do_not_reset[callbacks[i].seq] = 1;
  19379. _fireCallback(callbacks[i].callback, e);
  19380. continue;
  19381. }
  19382. // if there were no sequence matches but we are still here
  19383. // that means this is a regular match so we should fire that
  19384. if (!processed_sequence_callback && !_inside_sequence) {
  19385. _fireCallback(callbacks[i].callback, e);
  19386. }
  19387. }
  19388. // if you are inside of a sequence and the key you are pressing
  19389. // is not a modifier key then we should reset all sequences
  19390. // that were not matched by this key event
  19391. if (e.type == _inside_sequence && !_isModifier(character)) {
  19392. _resetSequences(do_not_reset);
  19393. }
  19394. }
  19395. /**
  19396. * handles a keydown event
  19397. *
  19398. * @param {Event} e
  19399. * @returns void
  19400. */
  19401. function _handleKey(e) {
  19402. // normalize e.which for key events
  19403. // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion
  19404. e.which = typeof e.which == "number" ? e.which : e.keyCode;
  19405. var character = _characterFromEvent(e);
  19406. // no character found then stop
  19407. if (!character) {
  19408. return;
  19409. }
  19410. if (e.type == 'keyup' && _ignore_next_keyup == character) {
  19411. _ignore_next_keyup = false;
  19412. return;
  19413. }
  19414. _handleCharacter(character, e);
  19415. }
  19416. /**
  19417. * determines if the keycode specified is a modifier key or not
  19418. *
  19419. * @param {string} key
  19420. * @returns {boolean}
  19421. */
  19422. function _isModifier(key) {
  19423. return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta';
  19424. }
  19425. /**
  19426. * called to set a 1 second timeout on the specified sequence
  19427. *
  19428. * this is so after each key press in the sequence you have 1 second
  19429. * to press the next key before you have to start over
  19430. *
  19431. * @returns void
  19432. */
  19433. function _resetSequenceTimer() {
  19434. clearTimeout(_reset_timer);
  19435. _reset_timer = setTimeout(_resetSequences, 1000);
  19436. }
  19437. /**
  19438. * reverses the map lookup so that we can look for specific keys
  19439. * to see what can and can't use keypress
  19440. *
  19441. * @return {Object}
  19442. */
  19443. function _getReverseMap() {
  19444. if (!_REVERSE_MAP) {
  19445. _REVERSE_MAP = {};
  19446. for (var key in _MAP) {
  19447. // pull out the numeric keypad from here cause keypress should
  19448. // be able to detect the keys from the character
  19449. if (key > 95 && key < 112) {
  19450. continue;
  19451. }
  19452. if (_MAP.hasOwnProperty(key)) {
  19453. _REVERSE_MAP[_MAP[key]] = key;
  19454. }
  19455. }
  19456. }
  19457. return _REVERSE_MAP;
  19458. }
  19459. /**
  19460. * picks the best action based on the key combination
  19461. *
  19462. * @param {string} key - character for key
  19463. * @param {Array} modifiers
  19464. * @param {string=} action passed in
  19465. */
  19466. function _pickBestAction(key, modifiers, action) {
  19467. // if no action was picked in we should try to pick the one
  19468. // that we think would work best for this key
  19469. if (!action) {
  19470. action = _getReverseMap()[key] ? 'keydown' : 'keypress';
  19471. }
  19472. // modifier keys don't work as expected with keypress,
  19473. // switch to keydown
  19474. if (action == 'keypress' && modifiers.length) {
  19475. action = 'keydown';
  19476. }
  19477. return action;
  19478. }
  19479. /**
  19480. * binds a key sequence to an event
  19481. *
  19482. * @param {string} combo - combo specified in bind call
  19483. * @param {Array} keys
  19484. * @param {Function} callback
  19485. * @param {string=} action
  19486. * @returns void
  19487. */
  19488. function _bindSequence(combo, keys, callback, action) {
  19489. // start off by adding a sequence level record for this combination
  19490. // and setting the level to 0
  19491. _sequence_levels[combo] = 0;
  19492. // if there is no action pick the best one for the first key
  19493. // in the sequence
  19494. if (!action) {
  19495. action = _pickBestAction(keys[0], []);
  19496. }
  19497. /**
  19498. * callback to increase the sequence level for this sequence and reset
  19499. * all other sequences that were active
  19500. *
  19501. * @param {Event} e
  19502. * @returns void
  19503. */
  19504. var _increaseSequence = function(e) {
  19505. _inside_sequence = action;
  19506. ++_sequence_levels[combo];
  19507. _resetSequenceTimer();
  19508. },
  19509. /**
  19510. * wraps the specified callback inside of another function in order
  19511. * to reset all sequence counters as soon as this sequence is done
  19512. *
  19513. * @param {Event} e
  19514. * @returns void
  19515. */
  19516. _callbackAndReset = function(e) {
  19517. _fireCallback(callback, e);
  19518. // we should ignore the next key up if the action is key down
  19519. // or keypress. this is so if you finish a sequence and
  19520. // release the key the final key will not trigger a keyup
  19521. if (action !== 'keyup') {
  19522. _ignore_next_keyup = _characterFromEvent(e);
  19523. }
  19524. // weird race condition if a sequence ends with the key
  19525. // another sequence begins with
  19526. setTimeout(_resetSequences, 10);
  19527. },
  19528. i;
  19529. // loop through keys one at a time and bind the appropriate callback
  19530. // function. for any key leading up to the final one it should
  19531. // increase the sequence. after the final, it should reset all sequences
  19532. for (i = 0; i < keys.length; ++i) {
  19533. _bindSingle(keys[i], i < keys.length - 1 ? _increaseSequence : _callbackAndReset, action, combo, i);
  19534. }
  19535. }
  19536. /**
  19537. * binds a single keyboard combination
  19538. *
  19539. * @param {string} combination
  19540. * @param {Function} callback
  19541. * @param {string=} action
  19542. * @param {string=} sequence_name - name of sequence if part of sequence
  19543. * @param {number=} level - what part of the sequence the command is
  19544. * @returns void
  19545. */
  19546. function _bindSingle(combination, callback, action, sequence_name, level) {
  19547. // make sure multiple spaces in a row become a single space
  19548. combination = combination.replace(/\s+/g, ' ');
  19549. var sequence = combination.split(' '),
  19550. i,
  19551. key,
  19552. keys,
  19553. modifiers = [];
  19554. // if this pattern is a sequence of keys then run through this method
  19555. // to reprocess each pattern one key at a time
  19556. if (sequence.length > 1) {
  19557. return _bindSequence(combination, sequence, callback, action);
  19558. }
  19559. // take the keys from this pattern and figure out what the actual
  19560. // pattern is all about
  19561. keys = combination === '+' ? ['+'] : combination.split('+');
  19562. for (i = 0; i < keys.length; ++i) {
  19563. key = keys[i];
  19564. // normalize key names
  19565. if (_SPECIAL_ALIASES[key]) {
  19566. key = _SPECIAL_ALIASES[key];
  19567. }
  19568. // if this is not a keypress event then we should
  19569. // be smart about using shift keys
  19570. // this will only work for US keyboards however
  19571. if (action && action != 'keypress' && _SHIFT_MAP[key]) {
  19572. key = _SHIFT_MAP[key];
  19573. modifiers.push('shift');
  19574. }
  19575. // if this key is a modifier then add it to the list of modifiers
  19576. if (_isModifier(key)) {
  19577. modifiers.push(key);
  19578. }
  19579. }
  19580. // depending on what the key combination is
  19581. // we will try to pick the best event for it
  19582. action = _pickBestAction(key, modifiers, action);
  19583. // make sure to initialize array if this is the first time
  19584. // a callback is added for this key
  19585. if (!_callbacks[key]) {
  19586. _callbacks[key] = [];
  19587. }
  19588. // remove an existing match if there is one
  19589. _getMatches(key, modifiers, action, !sequence_name, combination);
  19590. // add this call back to the array
  19591. // if it is a sequence put it at the beginning
  19592. // if not put it at the end
  19593. //
  19594. // this is important because the way these are processed expects
  19595. // the sequence ones to come first
  19596. _callbacks[key][sequence_name ? 'unshift' : 'push']({
  19597. callback: callback,
  19598. modifiers: modifiers,
  19599. action: action,
  19600. seq: sequence_name,
  19601. level: level,
  19602. combo: combination
  19603. });
  19604. }
  19605. /**
  19606. * binds multiple combinations to the same callback
  19607. *
  19608. * @param {Array} combinations
  19609. * @param {Function} callback
  19610. * @param {string|undefined} action
  19611. * @returns void
  19612. */
  19613. function _bindMultiple(combinations, callback, action) {
  19614. for (var i = 0; i < combinations.length; ++i) {
  19615. _bindSingle(combinations[i], callback, action);
  19616. }
  19617. }
  19618. // start!
  19619. _addEvent(document, 'keypress', _handleKey);
  19620. _addEvent(document, 'keydown', _handleKey);
  19621. _addEvent(document, 'keyup', _handleKey);
  19622. var mousetrap = {
  19623. /**
  19624. * binds an event to mousetrap
  19625. *
  19626. * can be a single key, a combination of keys separated with +,
  19627. * a comma separated list of keys, an array of keys, or
  19628. * a sequence of keys separated by spaces
  19629. *
  19630. * be sure to list the modifier keys first to make sure that the
  19631. * correct key ends up getting bound (the last key in the pattern)
  19632. *
  19633. * @param {string|Array} keys
  19634. * @param {Function} callback
  19635. * @param {string=} action - 'keypress', 'keydown', or 'keyup'
  19636. * @returns void
  19637. */
  19638. bind: function(keys, callback, action) {
  19639. _bindMultiple(keys instanceof Array ? keys : [keys], callback, action);
  19640. _direct_map[keys + ':' + action] = callback;
  19641. return this;
  19642. },
  19643. /**
  19644. * unbinds an event to mousetrap
  19645. *
  19646. * the unbinding sets the callback function of the specified key combo
  19647. * to an empty function and deletes the corresponding key in the
  19648. * _direct_map dict.
  19649. *
  19650. * the keycombo+action has to be exactly the same as
  19651. * it was defined in the bind method
  19652. *
  19653. * TODO: actually remove this from the _callbacks dictionary instead
  19654. * of binding an empty function
  19655. *
  19656. * @param {string|Array} keys
  19657. * @param {string} action
  19658. * @returns void
  19659. */
  19660. unbind: function(keys, action) {
  19661. if (_direct_map[keys + ':' + action]) {
  19662. delete _direct_map[keys + ':' + action];
  19663. this.bind(keys, function() {}, action);
  19664. }
  19665. return this;
  19666. },
  19667. /**
  19668. * triggers an event that has already been bound
  19669. *
  19670. * @param {string} keys
  19671. * @param {string=} action
  19672. * @returns void
  19673. */
  19674. trigger: function(keys, action) {
  19675. _direct_map[keys + ':' + action]();
  19676. return this;
  19677. },
  19678. /**
  19679. * resets the library back to its initial state. this is useful
  19680. * if you want to clear out the current keyboard shortcuts and bind
  19681. * new ones - for example if you switch to another page
  19682. *
  19683. * @returns void
  19684. */
  19685. reset: function() {
  19686. _callbacks = {};
  19687. _direct_map = {};
  19688. return this;
  19689. }
  19690. };
  19691. module.exports = mousetrap;
  19692. },{}]},{},[1])
  19693. (1)
  19694. });