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.

22278 lines
638 KiB

  1. /**
  2. * vis.js
  3. * https://github.com/almende/vis
  4. *
  5. * A dynamic, browser-based visualization library.
  6. *
  7. * @version 0.5.1
  8. * @date 2014-02-20
  9. *
  10. * @license
  11. * Copyright (C) 2011-2014 Almende B.V, http://almende.com
  12. *
  13. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  14. * use this file except in compliance with the License. You may obtain a copy
  15. * of the License at
  16. *
  17. * http://www.apache.org/licenses/LICENSE-2.0
  18. *
  19. * Unless required by applicable law or agreed to in writing, software
  20. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  21. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  22. * License for the specific language governing permissions and limitations under
  23. * the License.
  24. */
  25. !function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.vis=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  26. /**
  27. * vis.js module imports
  28. */
  29. // Try to load dependencies from the global window object.
  30. // If not available there, load via require.
  31. var moment = (typeof window !== 'undefined') && window['moment'] || require('moment');
  32. var Emitter = require('emitter-component');
  33. var Hammer;
  34. if (typeof window !== 'undefined') {
  35. // load hammer.js only when running in a browser (where window is available)
  36. Hammer = window['Hammer'] || require('hammerjs');
  37. }
  38. else {
  39. Hammer = function () {
  40. throw Error('hammer.js is only available in a browser, not in node.js.');
  41. }
  42. }
  43. var mousetrap;
  44. if (typeof window !== 'undefined') {
  45. // load mousetrap.js only when running in a browser (where window is available)
  46. mousetrap = window['mousetrap'] || require('mousetrap');
  47. }
  48. else {
  49. mousetrap = function () {
  50. throw Error('mouseTrap is only available in a browser, not in node.js.');
  51. }
  52. }
  53. // Internet Explorer 8 and older does not support Array.indexOf, so we define
  54. // it here in that case.
  55. // http://soledadpenades.com/2007/05/17/arrayindexof-in-internet-explorer/
  56. if(!Array.prototype.indexOf) {
  57. Array.prototype.indexOf = function(obj){
  58. for(var i = 0; i < this.length; i++){
  59. if(this[i] == obj){
  60. return i;
  61. }
  62. }
  63. return -1;
  64. };
  65. try {
  66. console.log("Warning: Ancient browser detected. Please update your browser");
  67. }
  68. catch (err) {
  69. }
  70. }
  71. // Internet Explorer 8 and older does not support Array.forEach, so we define
  72. // it here in that case.
  73. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach
  74. if (!Array.prototype.forEach) {
  75. Array.prototype.forEach = function(fn, scope) {
  76. for(var i = 0, len = this.length; i < len; ++i) {
  77. fn.call(scope || this, this[i], i, this);
  78. }
  79. }
  80. }
  81. // Internet Explorer 8 and older does not support Array.map, so we define it
  82. // here in that case.
  83. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map
  84. // Production steps of ECMA-262, Edition 5, 15.4.4.19
  85. // Reference: http://es5.github.com/#x15.4.4.19
  86. if (!Array.prototype.map) {
  87. Array.prototype.map = function(callback, thisArg) {
  88. var T, A, k;
  89. if (this == null) {
  90. throw new TypeError(" this is null or not defined");
  91. }
  92. // 1. Let O be the result of calling ToObject passing the |this| value as the argument.
  93. var O = Object(this);
  94. // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
  95. // 3. Let len be ToUint32(lenValue).
  96. var len = O.length >>> 0;
  97. // 4. If IsCallable(callback) is false, throw a TypeError exception.
  98. // See: http://es5.github.com/#x9.11
  99. if (typeof callback !== "function") {
  100. throw new TypeError(callback + " is not a function");
  101. }
  102. // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
  103. if (thisArg) {
  104. T = thisArg;
  105. }
  106. // 6. Let A be a new array created as if by the expression new Array(len) where Array is
  107. // the standard built-in constructor with that name and len is the value of len.
  108. A = new Array(len);
  109. // 7. Let k be 0
  110. k = 0;
  111. // 8. Repeat, while k < len
  112. while(k < len) {
  113. var kValue, mappedValue;
  114. // a. Let Pk be ToString(k).
  115. // This is implicit for LHS operands of the in operator
  116. // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
  117. // This step can be combined with c
  118. // c. If kPresent is true, then
  119. if (k in O) {
  120. // i. Let kValue be the result of calling the Get internal method of O with argument Pk.
  121. kValue = O[ k ];
  122. // ii. Let mappedValue be the result of calling the Call internal method of callback
  123. // with T as the this value and argument list containing kValue, k, and O.
  124. mappedValue = callback.call(T, kValue, k, O);
  125. // iii. Call the DefineOwnProperty internal method of A with arguments
  126. // Pk, Property Descriptor {Value: mappedValue, : true, Enumerable: true, Configurable: true},
  127. // and false.
  128. // In browsers that support Object.defineProperty, use the following:
  129. // Object.defineProperty(A, Pk, { value: mappedValue, writable: true, enumerable: true, configurable: true });
  130. // For best browser support, use the following:
  131. A[ k ] = mappedValue;
  132. }
  133. // d. Increase k by 1.
  134. k++;
  135. }
  136. // 9. return A
  137. return A;
  138. };
  139. }
  140. // Internet Explorer 8 and older does not support Array.filter, so we define it
  141. // here in that case.
  142. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter
  143. if (!Array.prototype.filter) {
  144. Array.prototype.filter = function(fun /*, thisp */) {
  145. "use strict";
  146. if (this == null) {
  147. throw new TypeError();
  148. }
  149. var t = Object(this);
  150. var len = t.length >>> 0;
  151. if (typeof fun != "function") {
  152. throw new TypeError();
  153. }
  154. var res = [];
  155. var thisp = arguments[1];
  156. for (var i = 0; i < len; i++) {
  157. if (i in t) {
  158. var val = t[i]; // in case fun mutates this
  159. if (fun.call(thisp, val, i, t))
  160. res.push(val);
  161. }
  162. }
  163. return res;
  164. };
  165. }
  166. // Internet Explorer 8 and older does not support Object.keys, so we define it
  167. // here in that case.
  168. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/keys
  169. if (!Object.keys) {
  170. Object.keys = (function () {
  171. var hasOwnProperty = Object.prototype.hasOwnProperty,
  172. hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
  173. dontEnums = [
  174. 'toString',
  175. 'toLocaleString',
  176. 'valueOf',
  177. 'hasOwnProperty',
  178. 'isPrototypeOf',
  179. 'propertyIsEnumerable',
  180. 'constructor'
  181. ],
  182. dontEnumsLength = dontEnums.length;
  183. return function (obj) {
  184. if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) {
  185. throw new TypeError('Object.keys called on non-object');
  186. }
  187. var result = [];
  188. for (var prop in obj) {
  189. if (hasOwnProperty.call(obj, prop)) result.push(prop);
  190. }
  191. if (hasDontEnumBug) {
  192. for (var i=0; i < dontEnumsLength; i++) {
  193. if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
  194. }
  195. }
  196. return result;
  197. }
  198. })()
  199. }
  200. // Internet Explorer 8 and older does not support Array.isArray,
  201. // so we define it here in that case.
  202. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/isArray
  203. if(!Array.isArray) {
  204. Array.isArray = function (vArg) {
  205. return Object.prototype.toString.call(vArg) === "[object Array]";
  206. };
  207. }
  208. // Internet Explorer 8 and older does not support Function.bind,
  209. // so we define it here in that case.
  210. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind
  211. if (!Function.prototype.bind) {
  212. Function.prototype.bind = function (oThis) {
  213. if (typeof this !== "function") {
  214. // closest thing possible to the ECMAScript 5 internal IsCallable function
  215. throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
  216. }
  217. var aArgs = Array.prototype.slice.call(arguments, 1),
  218. fToBind = this,
  219. fNOP = function () {},
  220. fBound = function () {
  221. return fToBind.apply(this instanceof fNOP && oThis
  222. ? this
  223. : oThis,
  224. aArgs.concat(Array.prototype.slice.call(arguments)));
  225. };
  226. fNOP.prototype = this.prototype;
  227. fBound.prototype = new fNOP();
  228. return fBound;
  229. };
  230. }
  231. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create
  232. if (!Object.create) {
  233. Object.create = function (o) {
  234. if (arguments.length > 1) {
  235. throw new Error('Object.create implementation only accepts the first parameter.');
  236. }
  237. function F() {}
  238. F.prototype = o;
  239. return new F();
  240. };
  241. }
  242. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
  243. if (!Function.prototype.bind) {
  244. Function.prototype.bind = function (oThis) {
  245. if (typeof this !== "function") {
  246. // closest thing possible to the ECMAScript 5 internal IsCallable function
  247. throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
  248. }
  249. var aArgs = Array.prototype.slice.call(arguments, 1),
  250. fToBind = this,
  251. fNOP = function () {},
  252. fBound = function () {
  253. return fToBind.apply(this instanceof fNOP && oThis
  254. ? this
  255. : oThis,
  256. aArgs.concat(Array.prototype.slice.call(arguments)));
  257. };
  258. fNOP.prototype = this.prototype;
  259. fBound.prototype = new fNOP();
  260. return fBound;
  261. };
  262. }
  263. /**
  264. * utility functions
  265. */
  266. var util = {};
  267. /**
  268. * Test whether given object is a number
  269. * @param {*} object
  270. * @return {Boolean} isNumber
  271. */
  272. util.isNumber = function isNumber(object) {
  273. return (object instanceof Number || typeof object == 'number');
  274. };
  275. /**
  276. * Test whether given object is a string
  277. * @param {*} object
  278. * @return {Boolean} isString
  279. */
  280. util.isString = function isString(object) {
  281. return (object instanceof String || typeof object == 'string');
  282. };
  283. /**
  284. * Test whether given object is a Date, or a String containing a Date
  285. * @param {Date | String} object
  286. * @return {Boolean} isDate
  287. */
  288. util.isDate = function isDate(object) {
  289. if (object instanceof Date) {
  290. return true;
  291. }
  292. else if (util.isString(object)) {
  293. // test whether this string contains a date
  294. var match = ASPDateRegex.exec(object);
  295. if (match) {
  296. return true;
  297. }
  298. else if (!isNaN(Date.parse(object))) {
  299. return true;
  300. }
  301. }
  302. return false;
  303. };
  304. /**
  305. * Test whether given object is an instance of google.visualization.DataTable
  306. * @param {*} object
  307. * @return {Boolean} isDataTable
  308. */
  309. util.isDataTable = function isDataTable(object) {
  310. return (typeof (google) !== 'undefined') &&
  311. (google.visualization) &&
  312. (google.visualization.DataTable) &&
  313. (object instanceof google.visualization.DataTable);
  314. };
  315. /**
  316. * Create a semi UUID
  317. * source: http://stackoverflow.com/a/105074/1262753
  318. * @return {String} uuid
  319. */
  320. util.randomUUID = function randomUUID () {
  321. var S4 = function () {
  322. return Math.floor(
  323. Math.random() * 0x10000 /* 65536 */
  324. ).toString(16);
  325. };
  326. return (
  327. S4() + S4() + '-' +
  328. S4() + '-' +
  329. S4() + '-' +
  330. S4() + '-' +
  331. S4() + S4() + S4()
  332. );
  333. };
  334. /**
  335. * Extend object a with the properties of object b or a series of objects
  336. * Only properties with defined values are copied
  337. * @param {Object} a
  338. * @param {... Object} b
  339. * @return {Object} a
  340. */
  341. util.extend = function (a, b) {
  342. for (var i = 1, len = arguments.length; i < len; i++) {
  343. var other = arguments[i];
  344. for (var prop in other) {
  345. if (other.hasOwnProperty(prop) && other[prop] !== undefined) {
  346. a[prop] = other[prop];
  347. }
  348. }
  349. }
  350. return a;
  351. };
  352. /**
  353. * Convert an object to another type
  354. * @param {Boolean | Number | String | Date | Moment | Null | undefined} object
  355. * @param {String | undefined} type Name of the type. Available types:
  356. * 'Boolean', 'Number', 'String',
  357. * 'Date', 'Moment', ISODate', 'ASPDate'.
  358. * @return {*} object
  359. * @throws Error
  360. */
  361. util.convert = function convert(object, type) {
  362. var match;
  363. if (object === undefined) {
  364. return undefined;
  365. }
  366. if (object === null) {
  367. return null;
  368. }
  369. if (!type) {
  370. return object;
  371. }
  372. if (!(typeof type === 'string') && !(type instanceof String)) {
  373. throw new Error('Type must be a string');
  374. }
  375. //noinspection FallthroughInSwitchStatementJS
  376. switch (type) {
  377. case 'boolean':
  378. case 'Boolean':
  379. return Boolean(object);
  380. case 'number':
  381. case 'Number':
  382. return Number(object.valueOf());
  383. case 'string':
  384. case 'String':
  385. return String(object);
  386. case 'Date':
  387. if (util.isNumber(object)) {
  388. return new Date(object);
  389. }
  390. if (object instanceof Date) {
  391. return new Date(object.valueOf());
  392. }
  393. else if (moment.isMoment(object)) {
  394. return new Date(object.valueOf());
  395. }
  396. if (util.isString(object)) {
  397. match = ASPDateRegex.exec(object);
  398. if (match) {
  399. // object is an ASP date
  400. return new Date(Number(match[1])); // parse number
  401. }
  402. else {
  403. return moment(object).toDate(); // parse string
  404. }
  405. }
  406. else {
  407. throw new Error(
  408. 'Cannot convert object of type ' + util.getType(object) +
  409. ' to type Date');
  410. }
  411. case 'Moment':
  412. if (util.isNumber(object)) {
  413. return moment(object);
  414. }
  415. if (object instanceof Date) {
  416. return moment(object.valueOf());
  417. }
  418. else if (moment.isMoment(object)) {
  419. return moment(object);
  420. }
  421. if (util.isString(object)) {
  422. match = ASPDateRegex.exec(object);
  423. if (match) {
  424. // object is an ASP date
  425. return moment(Number(match[1])); // parse number
  426. }
  427. else {
  428. return moment(object); // parse string
  429. }
  430. }
  431. else {
  432. throw new Error(
  433. 'Cannot convert object of type ' + util.getType(object) +
  434. ' to type Date');
  435. }
  436. case 'ISODate':
  437. if (util.isNumber(object)) {
  438. return new Date(object);
  439. }
  440. else if (object instanceof Date) {
  441. return object.toISOString();
  442. }
  443. else if (moment.isMoment(object)) {
  444. return object.toDate().toISOString();
  445. }
  446. else if (util.isString(object)) {
  447. match = ASPDateRegex.exec(object);
  448. if (match) {
  449. // object is an ASP date
  450. return new Date(Number(match[1])).toISOString(); // parse number
  451. }
  452. else {
  453. return new Date(object).toISOString(); // parse string
  454. }
  455. }
  456. else {
  457. throw new Error(
  458. 'Cannot convert object of type ' + util.getType(object) +
  459. ' to type ISODate');
  460. }
  461. case 'ASPDate':
  462. if (util.isNumber(object)) {
  463. return '/Date(' + object + ')/';
  464. }
  465. else if (object instanceof Date) {
  466. return '/Date(' + object.valueOf() + ')/';
  467. }
  468. else if (util.isString(object)) {
  469. match = ASPDateRegex.exec(object);
  470. var value;
  471. if (match) {
  472. // object is an ASP date
  473. value = new Date(Number(match[1])).valueOf(); // parse number
  474. }
  475. else {
  476. value = new Date(object).valueOf(); // parse string
  477. }
  478. return '/Date(' + value + ')/';
  479. }
  480. else {
  481. throw new Error(
  482. 'Cannot convert object of type ' + util.getType(object) +
  483. ' to type ASPDate');
  484. }
  485. default:
  486. throw new Error('Cannot convert object of type ' + util.getType(object) +
  487. ' to type "' + type + '"');
  488. }
  489. };
  490. // parse ASP.Net Date pattern,
  491. // for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/'
  492. // code from http://momentjs.com/
  493. var ASPDateRegex = /^\/?Date\((\-?\d+)/i;
  494. /**
  495. * Get the type of an object, for example util.getType([]) returns 'Array'
  496. * @param {*} object
  497. * @return {String} type
  498. */
  499. util.getType = function getType(object) {
  500. var type = typeof object;
  501. if (type == 'object') {
  502. if (object == null) {
  503. return 'null';
  504. }
  505. if (object instanceof Boolean) {
  506. return 'Boolean';
  507. }
  508. if (object instanceof Number) {
  509. return 'Number';
  510. }
  511. if (object instanceof String) {
  512. return 'String';
  513. }
  514. if (object instanceof Array) {
  515. return 'Array';
  516. }
  517. if (object instanceof Date) {
  518. return 'Date';
  519. }
  520. return 'Object';
  521. }
  522. else if (type == 'number') {
  523. return 'Number';
  524. }
  525. else if (type == 'boolean') {
  526. return 'Boolean';
  527. }
  528. else if (type == 'string') {
  529. return 'String';
  530. }
  531. return type;
  532. };
  533. /**
  534. * Retrieve the absolute left value of a DOM element
  535. * @param {Element} elem A dom element, for example a div
  536. * @return {number} left The absolute left position of this element
  537. * in the browser page.
  538. */
  539. util.getAbsoluteLeft = function getAbsoluteLeft (elem) {
  540. var doc = document.documentElement;
  541. var body = document.body;
  542. var left = elem.offsetLeft;
  543. var e = elem.offsetParent;
  544. while (e != null && e != body && e != doc) {
  545. left += e.offsetLeft;
  546. left -= e.scrollLeft;
  547. e = e.offsetParent;
  548. }
  549. return left;
  550. };
  551. /**
  552. * Retrieve the absolute top value of a DOM element
  553. * @param {Element} elem A dom element, for example a div
  554. * @return {number} top The absolute top position of this element
  555. * in the browser page.
  556. */
  557. util.getAbsoluteTop = function getAbsoluteTop (elem) {
  558. var doc = document.documentElement;
  559. var body = document.body;
  560. var top = elem.offsetTop;
  561. var e = elem.offsetParent;
  562. while (e != null && e != body && e != doc) {
  563. top += e.offsetTop;
  564. top -= e.scrollTop;
  565. e = e.offsetParent;
  566. }
  567. return top;
  568. };
  569. /**
  570. * Get the absolute, vertical mouse position from an event.
  571. * @param {Event} event
  572. * @return {Number} pageY
  573. */
  574. util.getPageY = function getPageY (event) {
  575. if ('pageY' in event) {
  576. return event.pageY;
  577. }
  578. else {
  579. var clientY;
  580. if (('targetTouches' in event) && event.targetTouches.length) {
  581. clientY = event.targetTouches[0].clientY;
  582. }
  583. else {
  584. clientY = event.clientY;
  585. }
  586. var doc = document.documentElement;
  587. var body = document.body;
  588. return clientY +
  589. ( doc && doc.scrollTop || body && body.scrollTop || 0 ) -
  590. ( doc && doc.clientTop || body && body.clientTop || 0 );
  591. }
  592. };
  593. /**
  594. * Get the absolute, horizontal mouse position from an event.
  595. * @param {Event} event
  596. * @return {Number} pageX
  597. */
  598. util.getPageX = function getPageX (event) {
  599. if ('pageY' in event) {
  600. return event.pageX;
  601. }
  602. else {
  603. var clientX;
  604. if (('targetTouches' in event) && event.targetTouches.length) {
  605. clientX = event.targetTouches[0].clientX;
  606. }
  607. else {
  608. clientX = event.clientX;
  609. }
  610. var doc = document.documentElement;
  611. var body = document.body;
  612. return clientX +
  613. ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) -
  614. ( doc && doc.clientLeft || body && body.clientLeft || 0 );
  615. }
  616. };
  617. /**
  618. * add a className to the given elements style
  619. * @param {Element} elem
  620. * @param {String} className
  621. */
  622. util.addClassName = function addClassName(elem, className) {
  623. var classes = elem.className.split(' ');
  624. if (classes.indexOf(className) == -1) {
  625. classes.push(className); // add the class to the array
  626. elem.className = classes.join(' ');
  627. }
  628. };
  629. /**
  630. * add a className to the given elements style
  631. * @param {Element} elem
  632. * @param {String} className
  633. */
  634. util.removeClassName = function removeClassname(elem, className) {
  635. var classes = elem.className.split(' ');
  636. var index = classes.indexOf(className);
  637. if (index != -1) {
  638. classes.splice(index, 1); // remove the class from the array
  639. elem.className = classes.join(' ');
  640. }
  641. };
  642. /**
  643. * For each method for both arrays and objects.
  644. * In case of an array, the built-in Array.forEach() is applied.
  645. * In case of an Object, the method loops over all properties of the object.
  646. * @param {Object | Array} object An Object or Array
  647. * @param {function} callback Callback method, called for each item in
  648. * the object or array with three parameters:
  649. * callback(value, index, object)
  650. */
  651. util.forEach = function forEach (object, callback) {
  652. var i,
  653. len;
  654. if (object instanceof Array) {
  655. // array
  656. for (i = 0, len = object.length; i < len; i++) {
  657. callback(object[i], i, object);
  658. }
  659. }
  660. else {
  661. // object
  662. for (i in object) {
  663. if (object.hasOwnProperty(i)) {
  664. callback(object[i], i, object);
  665. }
  666. }
  667. }
  668. };
  669. /**
  670. * Update a property in an object
  671. * @param {Object} object
  672. * @param {String} key
  673. * @param {*} value
  674. * @return {Boolean} changed
  675. */
  676. util.updateProperty = function updateProp (object, key, value) {
  677. if (object[key] !== value) {
  678. object[key] = value;
  679. return true;
  680. }
  681. else {
  682. return false;
  683. }
  684. };
  685. /**
  686. * Add and event listener. Works for all browsers
  687. * @param {Element} element An html element
  688. * @param {string} action The action, for example "click",
  689. * without the prefix "on"
  690. * @param {function} listener The callback function to be executed
  691. * @param {boolean} [useCapture]
  692. */
  693. util.addEventListener = function addEventListener(element, action, listener, useCapture) {
  694. if (element.addEventListener) {
  695. if (useCapture === undefined)
  696. useCapture = false;
  697. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  698. action = "DOMMouseScroll"; // For Firefox
  699. }
  700. element.addEventListener(action, listener, useCapture);
  701. } else {
  702. element.attachEvent("on" + action, listener); // IE browsers
  703. }
  704. };
  705. /**
  706. * Remove an event listener from an element
  707. * @param {Element} element An html dom element
  708. * @param {string} action The name of the event, for example "mousedown"
  709. * @param {function} listener The listener function
  710. * @param {boolean} [useCapture]
  711. */
  712. util.removeEventListener = function removeEventListener(element, action, listener, useCapture) {
  713. if (element.removeEventListener) {
  714. // non-IE browsers
  715. if (useCapture === undefined)
  716. useCapture = false;
  717. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  718. action = "DOMMouseScroll"; // For Firefox
  719. }
  720. element.removeEventListener(action, listener, useCapture);
  721. } else {
  722. // IE browsers
  723. element.detachEvent("on" + action, listener);
  724. }
  725. };
  726. /**
  727. * Get HTML element which is the target of the event
  728. * @param {Event} event
  729. * @return {Element} target element
  730. */
  731. util.getTarget = function getTarget(event) {
  732. // code from http://www.quirksmode.org/js/events_properties.html
  733. if (!event) {
  734. event = window.event;
  735. }
  736. var target;
  737. if (event.target) {
  738. target = event.target;
  739. }
  740. else if (event.srcElement) {
  741. target = event.srcElement;
  742. }
  743. if (target.nodeType != undefined && target.nodeType == 3) {
  744. // defeat Safari bug
  745. target = target.parentNode;
  746. }
  747. return target;
  748. };
  749. /**
  750. * Fake a hammer.js gesture. Event can be a ScrollEvent or MouseMoveEvent
  751. * @param {Element} element
  752. * @param {Event} event
  753. */
  754. util.fakeGesture = function fakeGesture (element, event) {
  755. var eventType = null;
  756. // for hammer.js 1.0.5
  757. var gesture = Hammer.event.collectEventData(this, eventType, event);
  758. // for hammer.js 1.0.6
  759. //var touches = Hammer.event.getTouchList(event, eventType);
  760. // var gesture = Hammer.event.collectEventData(this, eventType, touches, event);
  761. // on IE in standards mode, no touches are recognized by hammer.js,
  762. // resulting in NaN values for center.pageX and center.pageY
  763. if (isNaN(gesture.center.pageX)) {
  764. gesture.center.pageX = event.pageX;
  765. }
  766. if (isNaN(gesture.center.pageY)) {
  767. gesture.center.pageY = event.pageY;
  768. }
  769. return gesture;
  770. };
  771. util.option = {};
  772. /**
  773. * Convert a value into a boolean
  774. * @param {Boolean | function | undefined} value
  775. * @param {Boolean} [defaultValue]
  776. * @returns {Boolean} bool
  777. */
  778. util.option.asBoolean = function (value, defaultValue) {
  779. if (typeof value == 'function') {
  780. value = value();
  781. }
  782. if (value != null) {
  783. return (value != false);
  784. }
  785. return defaultValue || null;
  786. };
  787. /**
  788. * Convert a value into a number
  789. * @param {Boolean | function | undefined} value
  790. * @param {Number} [defaultValue]
  791. * @returns {Number} number
  792. */
  793. util.option.asNumber = function (value, defaultValue) {
  794. if (typeof value == 'function') {
  795. value = value();
  796. }
  797. if (value != null) {
  798. return Number(value) || defaultValue || null;
  799. }
  800. return defaultValue || null;
  801. };
  802. /**
  803. * Convert a value into a string
  804. * @param {String | function | undefined} value
  805. * @param {String} [defaultValue]
  806. * @returns {String} str
  807. */
  808. util.option.asString = function (value, defaultValue) {
  809. if (typeof value == 'function') {
  810. value = value();
  811. }
  812. if (value != null) {
  813. return String(value);
  814. }
  815. return defaultValue || null;
  816. };
  817. /**
  818. * Convert a size or location into a string with pixels or a percentage
  819. * @param {String | Number | function | undefined} value
  820. * @param {String} [defaultValue]
  821. * @returns {String} size
  822. */
  823. util.option.asSize = function (value, defaultValue) {
  824. if (typeof value == 'function') {
  825. value = value();
  826. }
  827. if (util.isString(value)) {
  828. return value;
  829. }
  830. else if (util.isNumber(value)) {
  831. return value + 'px';
  832. }
  833. else {
  834. return defaultValue || null;
  835. }
  836. };
  837. /**
  838. * Convert a value into a DOM element
  839. * @param {HTMLElement | function | undefined} value
  840. * @param {HTMLElement} [defaultValue]
  841. * @returns {HTMLElement | null} dom
  842. */
  843. util.option.asElement = function (value, defaultValue) {
  844. if (typeof value == 'function') {
  845. value = value();
  846. }
  847. return value || defaultValue || null;
  848. };
  849. util.GiveDec = function GiveDec(Hex)
  850. {
  851. if(Hex == "A")
  852. Value = 10;
  853. else
  854. if(Hex == "B")
  855. Value = 11;
  856. else
  857. if(Hex == "C")
  858. Value = 12;
  859. else
  860. if(Hex == "D")
  861. Value = 13;
  862. else
  863. if(Hex == "E")
  864. Value = 14;
  865. else
  866. if(Hex == "F")
  867. Value = 15;
  868. else
  869. Value = eval(Hex)
  870. return Value;
  871. }
  872. util.GiveHex = function GiveHex(Dec)
  873. {
  874. if(Dec == 10)
  875. Value = "A";
  876. else
  877. if(Dec == 11)
  878. Value = "B";
  879. else
  880. if(Dec == 12)
  881. Value = "C";
  882. else
  883. if(Dec == 13)
  884. Value = "D";
  885. else
  886. if(Dec == 14)
  887. Value = "E";
  888. else
  889. if(Dec == 15)
  890. Value = "F";
  891. else
  892. Value = "" + Dec;
  893. return Value;
  894. }
  895. /**
  896. * http://www.yellowpipe.com/yis/tools/hex-to-rgb/color-converter.php
  897. *
  898. * @param {String} hex
  899. * @returns {{r: *, g: *, b: *}}
  900. */
  901. util.hexToRGB = function hexToRGB(hex) {
  902. hex = hex.replace("#","").toUpperCase();
  903. var a = util.GiveDec(hex.substring(0, 1));
  904. var b = util.GiveDec(hex.substring(1, 2));
  905. var c = util.GiveDec(hex.substring(2, 3));
  906. var d = util.GiveDec(hex.substring(3, 4));
  907. var e = util.GiveDec(hex.substring(4, 5));
  908. var f = util.GiveDec(hex.substring(5, 6));
  909. var r = (a * 16) + b;
  910. var g = (c * 16) + d;
  911. var b = (e * 16) + f;
  912. return {r:r,g:g,b:b};
  913. };
  914. util.RGBToHex = function RGBToHex(red,green,blue) {
  915. var a = util.GiveHex(Math.floor(red / 16));
  916. var b = util.GiveHex(red % 16);
  917. var c = util.GiveHex(Math.floor(green / 16));
  918. var d = util.GiveHex(green % 16);
  919. var e = util.GiveHex(Math.floor(blue / 16));
  920. var f = util.GiveHex(blue % 16);
  921. var hex = a + b + c + d + e + f;
  922. return "#" + hex;
  923. };
  924. /**
  925. * http://www.javascripter.net/faq/rgb2hsv.htm
  926. *
  927. * @param red
  928. * @param green
  929. * @param blue
  930. * @returns {*}
  931. * @constructor
  932. */
  933. util.RGBToHSV = function RGBToHSV (red,green,blue) {
  934. red=red/255; green=green/255; blue=blue/255;
  935. var minRGB = Math.min(red,Math.min(green,blue));
  936. var maxRGB = Math.max(red,Math.max(green,blue));
  937. // Black-gray-white
  938. if (minRGB == maxRGB) {
  939. return {h:0,s:0,v:minRGB};
  940. }
  941. // Colors other than black-gray-white:
  942. var d = (red==minRGB) ? green-blue : ((blue==minRGB) ? red-green : blue-red);
  943. var h = (red==minRGB) ? 3 : ((blue==minRGB) ? 1 : 5);
  944. var hue = 60*(h - d/(maxRGB - minRGB))/360;
  945. var saturation = (maxRGB - minRGB)/maxRGB;
  946. var value = maxRGB;
  947. return {h:hue,s:saturation,v:value};
  948. };
  949. /**
  950. * https://gist.github.com/mjijackson/5311256
  951. * @param hue
  952. * @param saturation
  953. * @param value
  954. * @returns {{r: number, g: number, b: number}}
  955. * @constructor
  956. */
  957. util.HSVToRGB = function HSVToRGB(h, s, v) {
  958. var r, g, b;
  959. var i = Math.floor(h * 6);
  960. var f = h * 6 - i;
  961. var p = v * (1 - s);
  962. var q = v * (1 - f * s);
  963. var t = v * (1 - (1 - f) * s);
  964. switch (i % 6) {
  965. case 0: r = v, g = t, b = p; break;
  966. case 1: r = q, g = v, b = p; break;
  967. case 2: r = p, g = v, b = t; break;
  968. case 3: r = p, g = q, b = v; break;
  969. case 4: r = t, g = p, b = v; break;
  970. case 5: r = v, g = p, b = q; break;
  971. }
  972. return {r:Math.floor(r * 255), g:Math.floor(g * 255), b:Math.floor(b * 255) };
  973. };
  974. util.HSVToHex = function HSVToHex(h,s,v) {
  975. var rgb = util.HSVToRGB(h,s,v);
  976. return util.RGBToHex(rgb.r,rgb.g,rgb.b);
  977. }
  978. util.hexToHSV = function hexToHSV(hex) {
  979. var rgb = util.hexToRGB(hex);
  980. return util.RGBToHSV(rgb.r,rgb.g,rgb.b);
  981. }
  982. util.isValidHex = function isValidHex(hex) {
  983. var isOk = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(hex);
  984. return isOk;
  985. }
  986. /**
  987. * DataSet
  988. *
  989. * Usage:
  990. * var dataSet = new DataSet({
  991. * fieldId: '_id',
  992. * convert: {
  993. * // ...
  994. * }
  995. * });
  996. *
  997. * dataSet.add(item);
  998. * dataSet.add(data);
  999. * dataSet.update(item);
  1000. * dataSet.update(data);
  1001. * dataSet.remove(id);
  1002. * dataSet.remove(ids);
  1003. * var data = dataSet.get();
  1004. * var data = dataSet.get(id);
  1005. * var data = dataSet.get(ids);
  1006. * var data = dataSet.get(ids, options, data);
  1007. * dataSet.clear();
  1008. *
  1009. * A data set can:
  1010. * - add/remove/update data
  1011. * - gives triggers upon changes in the data
  1012. * - can import/export data in various data formats
  1013. *
  1014. * @param {Object} [options] Available options:
  1015. * {String} fieldId Field name of the id in the
  1016. * items, 'id' by default.
  1017. * {Object.<String, String} convert
  1018. * A map with field names as key,
  1019. * and the field type as value.
  1020. * @constructor DataSet
  1021. */
  1022. // TODO: add a DataSet constructor DataSet(data, options)
  1023. function DataSet (options) {
  1024. this.id = util.randomUUID();
  1025. this.options = options || {};
  1026. this.data = {}; // map with data indexed by id
  1027. this.fieldId = this.options.fieldId || 'id'; // name of the field containing id
  1028. this.convert = {}; // field types by field name
  1029. this.showInternalIds = this.options.showInternalIds || false; // show internal ids with the get function
  1030. if (this.options.convert) {
  1031. for (var field in this.options.convert) {
  1032. if (this.options.convert.hasOwnProperty(field)) {
  1033. var value = this.options.convert[field];
  1034. if (value == 'Date' || value == 'ISODate' || value == 'ASPDate') {
  1035. this.convert[field] = 'Date';
  1036. }
  1037. else {
  1038. this.convert[field] = value;
  1039. }
  1040. }
  1041. }
  1042. }
  1043. // event subscribers
  1044. this.subscribers = {};
  1045. this.internalIds = {}; // internally generated id's
  1046. }
  1047. /**
  1048. * Subscribe to an event, add an event listener
  1049. * @param {String} event Event name. Available events: 'put', 'update',
  1050. * 'remove'
  1051. * @param {function} callback Callback method. Called with three parameters:
  1052. * {String} event
  1053. * {Object | null} params
  1054. * {String | Number} senderId
  1055. */
  1056. DataSet.prototype.on = function on (event, callback) {
  1057. var subscribers = this.subscribers[event];
  1058. if (!subscribers) {
  1059. subscribers = [];
  1060. this.subscribers[event] = subscribers;
  1061. }
  1062. subscribers.push({
  1063. callback: callback
  1064. });
  1065. };
  1066. // TODO: make this function deprecated (replaced with `on` since version 0.5)
  1067. DataSet.prototype.subscribe = DataSet.prototype.on;
  1068. /**
  1069. * Unsubscribe from an event, remove an event listener
  1070. * @param {String} event
  1071. * @param {function} callback
  1072. */
  1073. DataSet.prototype.off = function off(event, callback) {
  1074. var subscribers = this.subscribers[event];
  1075. if (subscribers) {
  1076. this.subscribers[event] = subscribers.filter(function (listener) {
  1077. return (listener.callback != callback);
  1078. });
  1079. }
  1080. };
  1081. // TODO: make this function deprecated (replaced with `on` since version 0.5)
  1082. DataSet.prototype.unsubscribe = DataSet.prototype.off;
  1083. /**
  1084. * Trigger an event
  1085. * @param {String} event
  1086. * @param {Object | null} params
  1087. * @param {String} [senderId] Optional id of the sender.
  1088. * @private
  1089. */
  1090. DataSet.prototype._trigger = function (event, params, senderId) {
  1091. if (event == '*') {
  1092. throw new Error('Cannot trigger event *');
  1093. }
  1094. var subscribers = [];
  1095. if (event in this.subscribers) {
  1096. subscribers = subscribers.concat(this.subscribers[event]);
  1097. }
  1098. if ('*' in this.subscribers) {
  1099. subscribers = subscribers.concat(this.subscribers['*']);
  1100. }
  1101. for (var i = 0; i < subscribers.length; i++) {
  1102. var subscriber = subscribers[i];
  1103. if (subscriber.callback) {
  1104. subscriber.callback(event, params, senderId || null);
  1105. }
  1106. }
  1107. };
  1108. /**
  1109. * Add data.
  1110. * Adding an item will fail when there already is an item with the same id.
  1111. * @param {Object | Array | DataTable} data
  1112. * @param {String} [senderId] Optional sender id
  1113. * @return {Array} addedIds Array with the ids of the added items
  1114. */
  1115. DataSet.prototype.add = function (data, senderId) {
  1116. var addedIds = [],
  1117. id,
  1118. me = this;
  1119. if (data instanceof Array) {
  1120. // Array
  1121. for (var i = 0, len = data.length; i < len; i++) {
  1122. id = me._addItem(data[i]);
  1123. addedIds.push(id);
  1124. }
  1125. }
  1126. else if (util.isDataTable(data)) {
  1127. // Google DataTable
  1128. var columns = this._getColumnNames(data);
  1129. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1130. var item = {};
  1131. for (var col = 0, cols = columns.length; col < cols; col++) {
  1132. var field = columns[col];
  1133. item[field] = data.getValue(row, col);
  1134. }
  1135. id = me._addItem(item);
  1136. addedIds.push(id);
  1137. }
  1138. }
  1139. else if (data instanceof Object) {
  1140. // Single item
  1141. id = me._addItem(data);
  1142. addedIds.push(id);
  1143. }
  1144. else {
  1145. throw new Error('Unknown dataType');
  1146. }
  1147. if (addedIds.length) {
  1148. this._trigger('add', {items: addedIds}, senderId);
  1149. }
  1150. return addedIds;
  1151. };
  1152. /**
  1153. * Update existing items. When an item does not exist, it will be created
  1154. * @param {Object | Array | DataTable} data
  1155. * @param {String} [senderId] Optional sender id
  1156. * @return {Array} updatedIds The ids of the added or updated items
  1157. */
  1158. DataSet.prototype.update = function (data, senderId) {
  1159. var addedIds = [],
  1160. updatedIds = [],
  1161. me = this,
  1162. fieldId = me.fieldId;
  1163. var addOrUpdate = function (item) {
  1164. var id = item[fieldId];
  1165. if (me.data[id]) {
  1166. // update item
  1167. id = me._updateItem(item);
  1168. updatedIds.push(id);
  1169. }
  1170. else {
  1171. // add new item
  1172. id = me._addItem(item);
  1173. addedIds.push(id);
  1174. }
  1175. };
  1176. if (data instanceof Array) {
  1177. // Array
  1178. for (var i = 0, len = data.length; i < len; i++) {
  1179. addOrUpdate(data[i]);
  1180. }
  1181. }
  1182. else if (util.isDataTable(data)) {
  1183. // Google DataTable
  1184. var columns = this._getColumnNames(data);
  1185. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1186. var item = {};
  1187. for (var col = 0, cols = columns.length; col < cols; col++) {
  1188. var field = columns[col];
  1189. item[field] = data.getValue(row, col);
  1190. }
  1191. addOrUpdate(item);
  1192. }
  1193. }
  1194. else if (data instanceof Object) {
  1195. // Single item
  1196. addOrUpdate(data);
  1197. }
  1198. else {
  1199. throw new Error('Unknown dataType');
  1200. }
  1201. if (addedIds.length) {
  1202. this._trigger('add', {items: addedIds}, senderId);
  1203. }
  1204. if (updatedIds.length) {
  1205. this._trigger('update', {items: updatedIds}, senderId);
  1206. }
  1207. return addedIds.concat(updatedIds);
  1208. };
  1209. /**
  1210. * Get a data item or multiple items.
  1211. *
  1212. * Usage:
  1213. *
  1214. * get()
  1215. * get(options: Object)
  1216. * get(options: Object, data: Array | DataTable)
  1217. *
  1218. * get(id: Number | String)
  1219. * get(id: Number | String, options: Object)
  1220. * get(id: Number | String, options: Object, data: Array | DataTable)
  1221. *
  1222. * get(ids: Number[] | String[])
  1223. * get(ids: Number[] | String[], options: Object)
  1224. * get(ids: Number[] | String[], options: Object, data: Array | DataTable)
  1225. *
  1226. * Where:
  1227. *
  1228. * {Number | String} id The id of an item
  1229. * {Number[] | String{}} ids An array with ids of items
  1230. * {Object} options An Object with options. Available options:
  1231. * {String} [type] Type of data to be returned. Can
  1232. * be 'DataTable' or 'Array' (default)
  1233. * {Object.<String, String>} [convert]
  1234. * {String[]} [fields] field names to be returned
  1235. * {function} [filter] filter items
  1236. * {String | function} [order] Order the items by
  1237. * a field name or custom sort function.
  1238. * {Array | DataTable} [data] If provided, items will be appended to this
  1239. * array or table. Required in case of Google
  1240. * DataTable.
  1241. *
  1242. * @throws Error
  1243. */
  1244. DataSet.prototype.get = function (args) {
  1245. var me = this;
  1246. var globalShowInternalIds = this.showInternalIds;
  1247. // parse the arguments
  1248. var id, ids, options, data;
  1249. var firstType = util.getType(arguments[0]);
  1250. if (firstType == 'String' || firstType == 'Number') {
  1251. // get(id [, options] [, data])
  1252. id = arguments[0];
  1253. options = arguments[1];
  1254. data = arguments[2];
  1255. }
  1256. else if (firstType == 'Array') {
  1257. // get(ids [, options] [, data])
  1258. ids = arguments[0];
  1259. options = arguments[1];
  1260. data = arguments[2];
  1261. }
  1262. else {
  1263. // get([, options] [, data])
  1264. options = arguments[0];
  1265. data = arguments[1];
  1266. }
  1267. // determine the return type
  1268. var type;
  1269. if (options && options.type) {
  1270. type = (options.type == 'DataTable') ? 'DataTable' : 'Array';
  1271. if (data && (type != util.getType(data))) {
  1272. throw new Error('Type of parameter "data" (' + util.getType(data) + ') ' +
  1273. 'does not correspond with specified options.type (' + options.type + ')');
  1274. }
  1275. if (type == 'DataTable' && !util.isDataTable(data)) {
  1276. throw new Error('Parameter "data" must be a DataTable ' +
  1277. 'when options.type is "DataTable"');
  1278. }
  1279. }
  1280. else if (data) {
  1281. type = (util.getType(data) == 'DataTable') ? 'DataTable' : 'Array';
  1282. }
  1283. else {
  1284. type = 'Array';
  1285. }
  1286. // we allow the setting of this value for a single get request.
  1287. if (options != undefined) {
  1288. if (options.showInternalIds != undefined) {
  1289. this.showInternalIds = options.showInternalIds;
  1290. }
  1291. }
  1292. // build options
  1293. var convert = options && options.convert || this.options.convert;
  1294. var filter = options && options.filter;
  1295. var items = [], item, itemId, i, len;
  1296. // convert items
  1297. if (id != undefined) {
  1298. // return a single item
  1299. item = me._getItem(id, convert);
  1300. if (filter && !filter(item)) {
  1301. item = null;
  1302. }
  1303. }
  1304. else if (ids != undefined) {
  1305. // return a subset of items
  1306. for (i = 0, len = ids.length; i < len; i++) {
  1307. item = me._getItem(ids[i], convert);
  1308. if (!filter || filter(item)) {
  1309. items.push(item);
  1310. }
  1311. }
  1312. }
  1313. else {
  1314. // return all items
  1315. for (itemId in this.data) {
  1316. if (this.data.hasOwnProperty(itemId)) {
  1317. item = me._getItem(itemId, convert);
  1318. if (!filter || filter(item)) {
  1319. items.push(item);
  1320. }
  1321. }
  1322. }
  1323. }
  1324. // restore the global value of showInternalIds
  1325. this.showInternalIds = globalShowInternalIds;
  1326. // order the results
  1327. if (options && options.order && id == undefined) {
  1328. this._sort(items, options.order);
  1329. }
  1330. // filter fields of the items
  1331. if (options && options.fields) {
  1332. var fields = options.fields;
  1333. if (id != undefined) {
  1334. item = this._filterFields(item, fields);
  1335. }
  1336. else {
  1337. for (i = 0, len = items.length; i < len; i++) {
  1338. items[i] = this._filterFields(items[i], fields);
  1339. }
  1340. }
  1341. }
  1342. // return the results
  1343. if (type == 'DataTable') {
  1344. var columns = this._getColumnNames(data);
  1345. if (id != undefined) {
  1346. // append a single item to the data table
  1347. me._appendRow(data, columns, item);
  1348. }
  1349. else {
  1350. // copy the items to the provided data table
  1351. for (i = 0, len = items.length; i < len; i++) {
  1352. me._appendRow(data, columns, items[i]);
  1353. }
  1354. }
  1355. return data;
  1356. }
  1357. else {
  1358. // return an array
  1359. if (id != undefined) {
  1360. // a single item
  1361. return item;
  1362. }
  1363. else {
  1364. // multiple items
  1365. if (data) {
  1366. // copy the items to the provided array
  1367. for (i = 0, len = items.length; i < len; i++) {
  1368. data.push(items[i]);
  1369. }
  1370. return data;
  1371. }
  1372. else {
  1373. // just return our array
  1374. return items;
  1375. }
  1376. }
  1377. }
  1378. };
  1379. /**
  1380. * Get ids of all items or from a filtered set of items.
  1381. * @param {Object} [options] An Object with options. Available options:
  1382. * {function} [filter] filter items
  1383. * {String | function} [order] Order the items by
  1384. * a field name or custom sort function.
  1385. * @return {Array} ids
  1386. */
  1387. DataSet.prototype.getIds = function (options) {
  1388. var data = this.data,
  1389. filter = options && options.filter,
  1390. order = options && options.order,
  1391. convert = options && options.convert || this.options.convert,
  1392. i,
  1393. len,
  1394. id,
  1395. item,
  1396. items,
  1397. ids = [];
  1398. if (filter) {
  1399. // get filtered items
  1400. if (order) {
  1401. // create ordered list
  1402. items = [];
  1403. for (id in data) {
  1404. if (data.hasOwnProperty(id)) {
  1405. item = this._getItem(id, convert);
  1406. if (filter(item)) {
  1407. items.push(item);
  1408. }
  1409. }
  1410. }
  1411. this._sort(items, order);
  1412. for (i = 0, len = items.length; i < len; i++) {
  1413. ids[i] = items[i][this.fieldId];
  1414. }
  1415. }
  1416. else {
  1417. // create unordered list
  1418. for (id in data) {
  1419. if (data.hasOwnProperty(id)) {
  1420. item = this._getItem(id, convert);
  1421. if (filter(item)) {
  1422. ids.push(item[this.fieldId]);
  1423. }
  1424. }
  1425. }
  1426. }
  1427. }
  1428. else {
  1429. // get all items
  1430. if (order) {
  1431. // create an ordered list
  1432. items = [];
  1433. for (id in data) {
  1434. if (data.hasOwnProperty(id)) {
  1435. items.push(data[id]);
  1436. }
  1437. }
  1438. this._sort(items, order);
  1439. for (i = 0, len = items.length; i < len; i++) {
  1440. ids[i] = items[i][this.fieldId];
  1441. }
  1442. }
  1443. else {
  1444. // create unordered list
  1445. for (id in data) {
  1446. if (data.hasOwnProperty(id)) {
  1447. item = data[id];
  1448. ids.push(item[this.fieldId]);
  1449. }
  1450. }
  1451. }
  1452. }
  1453. return ids;
  1454. };
  1455. /**
  1456. * Execute a callback function for every item in the dataset.
  1457. * The order of the items is not determined.
  1458. * @param {function} callback
  1459. * @param {Object} [options] Available options:
  1460. * {Object.<String, String>} [convert]
  1461. * {String[]} [fields] filter fields
  1462. * {function} [filter] filter items
  1463. * {String | function} [order] Order the items by
  1464. * a field name or custom sort function.
  1465. */
  1466. DataSet.prototype.forEach = function (callback, options) {
  1467. var filter = options && options.filter,
  1468. convert = options && options.convert || this.options.convert,
  1469. data = this.data,
  1470. item,
  1471. id;
  1472. if (options && options.order) {
  1473. // execute forEach on ordered list
  1474. var items = this.get(options);
  1475. for (var i = 0, len = items.length; i < len; i++) {
  1476. item = items[i];
  1477. id = item[this.fieldId];
  1478. callback(item, id);
  1479. }
  1480. }
  1481. else {
  1482. // unordered
  1483. for (id in data) {
  1484. if (data.hasOwnProperty(id)) {
  1485. item = this._getItem(id, convert);
  1486. if (!filter || filter(item)) {
  1487. callback(item, id);
  1488. }
  1489. }
  1490. }
  1491. }
  1492. };
  1493. /**
  1494. * Map every item in the dataset.
  1495. * @param {function} callback
  1496. * @param {Object} [options] Available options:
  1497. * {Object.<String, String>} [convert]
  1498. * {String[]} [fields] filter fields
  1499. * {function} [filter] filter items
  1500. * {String | function} [order] Order the items by
  1501. * a field name or custom sort function.
  1502. * @return {Object[]} mappedItems
  1503. */
  1504. DataSet.prototype.map = function (callback, options) {
  1505. var filter = options && options.filter,
  1506. convert = options && options.convert || this.options.convert,
  1507. mappedItems = [],
  1508. data = this.data,
  1509. item;
  1510. // convert and filter items
  1511. for (var id in data) {
  1512. if (data.hasOwnProperty(id)) {
  1513. item = this._getItem(id, convert);
  1514. if (!filter || filter(item)) {
  1515. mappedItems.push(callback(item, id));
  1516. }
  1517. }
  1518. }
  1519. // order items
  1520. if (options && options.order) {
  1521. this._sort(mappedItems, options.order);
  1522. }
  1523. return mappedItems;
  1524. };
  1525. /**
  1526. * Filter the fields of an item
  1527. * @param {Object} item
  1528. * @param {String[]} fields Field names
  1529. * @return {Object} filteredItem
  1530. * @private
  1531. */
  1532. DataSet.prototype._filterFields = function (item, fields) {
  1533. var filteredItem = {};
  1534. for (var field in item) {
  1535. if (item.hasOwnProperty(field) && (fields.indexOf(field) != -1)) {
  1536. filteredItem[field] = item[field];
  1537. }
  1538. }
  1539. return filteredItem;
  1540. };
  1541. /**
  1542. * Sort the provided array with items
  1543. * @param {Object[]} items
  1544. * @param {String | function} order A field name or custom sort function.
  1545. * @private
  1546. */
  1547. DataSet.prototype._sort = function (items, order) {
  1548. if (util.isString(order)) {
  1549. // order by provided field name
  1550. var name = order; // field name
  1551. items.sort(function (a, b) {
  1552. var av = a[name];
  1553. var bv = b[name];
  1554. return (av > bv) ? 1 : ((av < bv) ? -1 : 0);
  1555. });
  1556. }
  1557. else if (typeof order === 'function') {
  1558. // order by sort function
  1559. items.sort(order);
  1560. }
  1561. // TODO: extend order by an Object {field:String, direction:String}
  1562. // where direction can be 'asc' or 'desc'
  1563. else {
  1564. throw new TypeError('Order must be a function or a string');
  1565. }
  1566. };
  1567. /**
  1568. * Remove an object by pointer or by id
  1569. * @param {String | Number | Object | Array} id Object or id, or an array with
  1570. * objects or ids to be removed
  1571. * @param {String} [senderId] Optional sender id
  1572. * @return {Array} removedIds
  1573. */
  1574. DataSet.prototype.remove = function (id, senderId) {
  1575. var removedIds = [],
  1576. i, len, removedId;
  1577. if (id instanceof Array) {
  1578. for (i = 0, len = id.length; i < len; i++) {
  1579. removedId = this._remove(id[i]);
  1580. if (removedId != null) {
  1581. removedIds.push(removedId);
  1582. }
  1583. }
  1584. }
  1585. else {
  1586. removedId = this._remove(id);
  1587. if (removedId != null) {
  1588. removedIds.push(removedId);
  1589. }
  1590. }
  1591. if (removedIds.length) {
  1592. this._trigger('remove', {items: removedIds}, senderId);
  1593. }
  1594. return removedIds;
  1595. };
  1596. /**
  1597. * Remove an item by its id
  1598. * @param {Number | String | Object} id id or item
  1599. * @returns {Number | String | null} id
  1600. * @private
  1601. */
  1602. DataSet.prototype._remove = function (id) {
  1603. if (util.isNumber(id) || util.isString(id)) {
  1604. if (this.data[id]) {
  1605. delete this.data[id];
  1606. delete this.internalIds[id];
  1607. return id;
  1608. }
  1609. }
  1610. else if (id instanceof Object) {
  1611. var itemId = id[this.fieldId];
  1612. if (itemId && this.data[itemId]) {
  1613. delete this.data[itemId];
  1614. delete this.internalIds[itemId];
  1615. return itemId;
  1616. }
  1617. }
  1618. return null;
  1619. };
  1620. /**
  1621. * Clear the data
  1622. * @param {String} [senderId] Optional sender id
  1623. * @return {Array} removedIds The ids of all removed items
  1624. */
  1625. DataSet.prototype.clear = function (senderId) {
  1626. var ids = Object.keys(this.data);
  1627. this.data = {};
  1628. this.internalIds = {};
  1629. this._trigger('remove', {items: ids}, senderId);
  1630. return ids;
  1631. };
  1632. /**
  1633. * Find the item with maximum value of a specified field
  1634. * @param {String} field
  1635. * @return {Object | null} item Item containing max value, or null if no items
  1636. */
  1637. DataSet.prototype.max = function (field) {
  1638. var data = this.data,
  1639. max = null,
  1640. maxField = null;
  1641. for (var id in data) {
  1642. if (data.hasOwnProperty(id)) {
  1643. var item = data[id];
  1644. var itemField = item[field];
  1645. if (itemField != null && (!max || itemField > maxField)) {
  1646. max = item;
  1647. maxField = itemField;
  1648. }
  1649. }
  1650. }
  1651. return max;
  1652. };
  1653. /**
  1654. * Find the item with minimum value of a specified field
  1655. * @param {String} field
  1656. * @return {Object | null} item Item containing max value, or null if no items
  1657. */
  1658. DataSet.prototype.min = function (field) {
  1659. var data = this.data,
  1660. min = null,
  1661. minField = null;
  1662. for (var id in data) {
  1663. if (data.hasOwnProperty(id)) {
  1664. var item = data[id];
  1665. var itemField = item[field];
  1666. if (itemField != null && (!min || itemField < minField)) {
  1667. min = item;
  1668. minField = itemField;
  1669. }
  1670. }
  1671. }
  1672. return min;
  1673. };
  1674. /**
  1675. * Find all distinct values of a specified field
  1676. * @param {String} field
  1677. * @return {Array} values Array containing all distinct values. If the data
  1678. * items do not contain the specified field, an array
  1679. * containing a single value undefined is returned.
  1680. * The returned array is unordered.
  1681. */
  1682. DataSet.prototype.distinct = function (field) {
  1683. var data = this.data,
  1684. values = [],
  1685. fieldType = this.options.convert[field],
  1686. count = 0;
  1687. for (var prop in data) {
  1688. if (data.hasOwnProperty(prop)) {
  1689. var item = data[prop];
  1690. var value = util.convert(item[field], fieldType);
  1691. var exists = false;
  1692. for (var i = 0; i < count; i++) {
  1693. if (values[i] == value) {
  1694. exists = true;
  1695. break;
  1696. }
  1697. }
  1698. if (!exists) {
  1699. values[count] = value;
  1700. count++;
  1701. }
  1702. }
  1703. }
  1704. return values;
  1705. };
  1706. /**
  1707. * Add a single item. Will fail when an item with the same id already exists.
  1708. * @param {Object} item
  1709. * @return {String} id
  1710. * @private
  1711. */
  1712. DataSet.prototype._addItem = function (item) {
  1713. var id = item[this.fieldId];
  1714. if (id != undefined) {
  1715. // check whether this id is already taken
  1716. if (this.data[id]) {
  1717. // item already exists
  1718. throw new Error('Cannot add item: item with id ' + id + ' already exists');
  1719. }
  1720. }
  1721. else {
  1722. // generate an id
  1723. id = util.randomUUID();
  1724. item[this.fieldId] = id;
  1725. this.internalIds[id] = item;
  1726. }
  1727. var d = {};
  1728. for (var field in item) {
  1729. if (item.hasOwnProperty(field)) {
  1730. var fieldType = this.convert[field]; // type may be undefined
  1731. d[field] = util.convert(item[field], fieldType);
  1732. }
  1733. }
  1734. this.data[id] = d;
  1735. return id;
  1736. };
  1737. /**
  1738. * Get an item. Fields can be converted to a specific type
  1739. * @param {String} id
  1740. * @param {Object.<String, String>} [convert] field types to convert
  1741. * @return {Object | null} item
  1742. * @private
  1743. */
  1744. DataSet.prototype._getItem = function (id, convert) {
  1745. var field, value;
  1746. // get the item from the dataset
  1747. var raw = this.data[id];
  1748. if (!raw) {
  1749. return null;
  1750. }
  1751. // convert the items field types
  1752. var converted = {},
  1753. fieldId = this.fieldId,
  1754. internalIds = this.internalIds;
  1755. if (convert) {
  1756. for (field in raw) {
  1757. if (raw.hasOwnProperty(field)) {
  1758. value = raw[field];
  1759. // output all fields, except internal ids
  1760. if ((field != fieldId) || (!(value in internalIds) || this.showInternalIds)) {
  1761. converted[field] = util.convert(value, convert[field]);
  1762. }
  1763. }
  1764. }
  1765. }
  1766. else {
  1767. // no field types specified, no converting needed
  1768. for (field in raw) {
  1769. if (raw.hasOwnProperty(field)) {
  1770. value = raw[field];
  1771. // output all fields, except internal ids
  1772. if ((field != fieldId) || (!(value in internalIds) || this.showInternalIds)) {
  1773. converted[field] = value;
  1774. }
  1775. }
  1776. }
  1777. }
  1778. return converted;
  1779. };
  1780. /**
  1781. * Update a single item: merge with existing item.
  1782. * Will fail when the item has no id, or when there does not exist an item
  1783. * with the same id.
  1784. * @param {Object} item
  1785. * @return {String} id
  1786. * @private
  1787. */
  1788. DataSet.prototype._updateItem = function (item) {
  1789. var id = item[this.fieldId];
  1790. if (id == undefined) {
  1791. throw new Error('Cannot update item: item has no id (item: ' + JSON.stringify(item) + ')');
  1792. }
  1793. var d = this.data[id];
  1794. if (!d) {
  1795. // item doesn't exist
  1796. throw new Error('Cannot update item: no item with id ' + id + ' found');
  1797. }
  1798. // merge with current item
  1799. for (var field in item) {
  1800. if (item.hasOwnProperty(field)) {
  1801. var fieldType = this.convert[field]; // type may be undefined
  1802. d[field] = util.convert(item[field], fieldType);
  1803. }
  1804. }
  1805. return id;
  1806. };
  1807. /**
  1808. * check if an id is an internal or external id
  1809. * @param id
  1810. * @returns {boolean}
  1811. * @private
  1812. */
  1813. DataSet.prototype.isInternalId = function(id) {
  1814. return (id in this.internalIds);
  1815. };
  1816. /**
  1817. * Get an array with the column names of a Google DataTable
  1818. * @param {DataTable} dataTable
  1819. * @return {String[]} columnNames
  1820. * @private
  1821. */
  1822. DataSet.prototype._getColumnNames = function (dataTable) {
  1823. var columns = [];
  1824. for (var col = 0, cols = dataTable.getNumberOfColumns(); col < cols; col++) {
  1825. columns[col] = dataTable.getColumnId(col) || dataTable.getColumnLabel(col);
  1826. }
  1827. return columns;
  1828. };
  1829. /**
  1830. * Append an item as a row to the dataTable
  1831. * @param dataTable
  1832. * @param columns
  1833. * @param item
  1834. * @private
  1835. */
  1836. DataSet.prototype._appendRow = function (dataTable, columns, item) {
  1837. var row = dataTable.addRow();
  1838. for (var col = 0, cols = columns.length; col < cols; col++) {
  1839. var field = columns[col];
  1840. dataTable.setValue(row, col, item[field]);
  1841. }
  1842. };
  1843. /**
  1844. * DataView
  1845. *
  1846. * a dataview offers a filtered view on a dataset or an other dataview.
  1847. *
  1848. * @param {DataSet | DataView} data
  1849. * @param {Object} [options] Available options: see method get
  1850. *
  1851. * @constructor DataView
  1852. */
  1853. function DataView (data, options) {
  1854. this.id = util.randomUUID();
  1855. this.data = null;
  1856. this.ids = {}; // ids of the items currently in memory (just contains a boolean true)
  1857. this.options = options || {};
  1858. this.fieldId = 'id'; // name of the field containing id
  1859. this.subscribers = {}; // event subscribers
  1860. var me = this;
  1861. this.listener = function () {
  1862. me._onEvent.apply(me, arguments);
  1863. };
  1864. this.setData(data);
  1865. }
  1866. // TODO: implement a function .config() to dynamically update things like configured filter
  1867. // and trigger changes accordingly
  1868. /**
  1869. * Set a data source for the view
  1870. * @param {DataSet | DataView} data
  1871. */
  1872. DataView.prototype.setData = function (data) {
  1873. var ids, dataItems, i, len;
  1874. if (this.data) {
  1875. // unsubscribe from current dataset
  1876. if (this.data.unsubscribe) {
  1877. this.data.unsubscribe('*', this.listener);
  1878. }
  1879. // trigger a remove of all items in memory
  1880. ids = [];
  1881. for (var id in this.ids) {
  1882. if (this.ids.hasOwnProperty(id)) {
  1883. ids.push(id);
  1884. }
  1885. }
  1886. this.ids = {};
  1887. this._trigger('remove', {items: ids});
  1888. }
  1889. this.data = data;
  1890. if (this.data) {
  1891. // update fieldId
  1892. this.fieldId = this.options.fieldId ||
  1893. (this.data && this.data.options && this.data.options.fieldId) ||
  1894. 'id';
  1895. // trigger an add of all added items
  1896. ids = this.data.getIds({filter: this.options && this.options.filter});
  1897. for (i = 0, len = ids.length; i < len; i++) {
  1898. id = ids[i];
  1899. this.ids[id] = true;
  1900. }
  1901. this._trigger('add', {items: ids});
  1902. // subscribe to new dataset
  1903. if (this.data.on) {
  1904. this.data.on('*', this.listener);
  1905. }
  1906. }
  1907. };
  1908. /**
  1909. * Get data from the data view
  1910. *
  1911. * Usage:
  1912. *
  1913. * get()
  1914. * get(options: Object)
  1915. * get(options: Object, data: Array | DataTable)
  1916. *
  1917. * get(id: Number)
  1918. * get(id: Number, options: Object)
  1919. * get(id: Number, options: Object, data: Array | DataTable)
  1920. *
  1921. * get(ids: Number[])
  1922. * get(ids: Number[], options: Object)
  1923. * get(ids: Number[], options: Object, data: Array | DataTable)
  1924. *
  1925. * Where:
  1926. *
  1927. * {Number | String} id The id of an item
  1928. * {Number[] | String{}} ids An array with ids of items
  1929. * {Object} options An Object with options. Available options:
  1930. * {String} [type] Type of data to be returned. Can
  1931. * be 'DataTable' or 'Array' (default)
  1932. * {Object.<String, String>} [convert]
  1933. * {String[]} [fields] field names to be returned
  1934. * {function} [filter] filter items
  1935. * {String | function} [order] Order the items by
  1936. * a field name or custom sort function.
  1937. * {Array | DataTable} [data] If provided, items will be appended to this
  1938. * array or table. Required in case of Google
  1939. * DataTable.
  1940. * @param args
  1941. */
  1942. DataView.prototype.get = function (args) {
  1943. var me = this;
  1944. // parse the arguments
  1945. var ids, options, data;
  1946. var firstType = util.getType(arguments[0]);
  1947. if (firstType == 'String' || firstType == 'Number' || firstType == 'Array') {
  1948. // get(id(s) [, options] [, data])
  1949. ids = arguments[0]; // can be a single id or an array with ids
  1950. options = arguments[1];
  1951. data = arguments[2];
  1952. }
  1953. else {
  1954. // get([, options] [, data])
  1955. options = arguments[0];
  1956. data = arguments[1];
  1957. }
  1958. // extend the options with the default options and provided options
  1959. var viewOptions = util.extend({}, this.options, options);
  1960. // create a combined filter method when needed
  1961. if (this.options.filter && options && options.filter) {
  1962. viewOptions.filter = function (item) {
  1963. return me.options.filter(item) && options.filter(item);
  1964. }
  1965. }
  1966. // build up the call to the linked data set
  1967. var getArguments = [];
  1968. if (ids != undefined) {
  1969. getArguments.push(ids);
  1970. }
  1971. getArguments.push(viewOptions);
  1972. getArguments.push(data);
  1973. return this.data && this.data.get.apply(this.data, getArguments);
  1974. };
  1975. /**
  1976. * Get ids of all items or from a filtered set of items.
  1977. * @param {Object} [options] An Object with options. Available options:
  1978. * {function} [filter] filter items
  1979. * {String | function} [order] Order the items by
  1980. * a field name or custom sort function.
  1981. * @return {Array} ids
  1982. */
  1983. DataView.prototype.getIds = function (options) {
  1984. var ids;
  1985. if (this.data) {
  1986. var defaultFilter = this.options.filter;
  1987. var filter;
  1988. if (options && options.filter) {
  1989. if (defaultFilter) {
  1990. filter = function (item) {
  1991. return defaultFilter(item) && options.filter(item);
  1992. }
  1993. }
  1994. else {
  1995. filter = options.filter;
  1996. }
  1997. }
  1998. else {
  1999. filter = defaultFilter;
  2000. }
  2001. ids = this.data.getIds({
  2002. filter: filter,
  2003. order: options && options.order
  2004. });
  2005. }
  2006. else {
  2007. ids = [];
  2008. }
  2009. return ids;
  2010. };
  2011. /**
  2012. * Event listener. Will propagate all events from the connected data set to
  2013. * the subscribers of the DataView, but will filter the items and only trigger
  2014. * when there are changes in the filtered data set.
  2015. * @param {String} event
  2016. * @param {Object | null} params
  2017. * @param {String} senderId
  2018. * @private
  2019. */
  2020. DataView.prototype._onEvent = function (event, params, senderId) {
  2021. var i, len, id, item,
  2022. ids = params && params.items,
  2023. data = this.data,
  2024. added = [],
  2025. updated = [],
  2026. removed = [];
  2027. if (ids && data) {
  2028. switch (event) {
  2029. case 'add':
  2030. // filter the ids of the added items
  2031. for (i = 0, len = ids.length; i < len; i++) {
  2032. id = ids[i];
  2033. item = this.get(id);
  2034. if (item) {
  2035. this.ids[id] = true;
  2036. added.push(id);
  2037. }
  2038. }
  2039. break;
  2040. case 'update':
  2041. // determine the event from the views viewpoint: an updated
  2042. // item can be added, updated, or removed from this view.
  2043. for (i = 0, len = ids.length; i < len; i++) {
  2044. id = ids[i];
  2045. item = this.get(id);
  2046. if (item) {
  2047. if (this.ids[id]) {
  2048. updated.push(id);
  2049. }
  2050. else {
  2051. this.ids[id] = true;
  2052. added.push(id);
  2053. }
  2054. }
  2055. else {
  2056. if (this.ids[id]) {
  2057. delete this.ids[id];
  2058. removed.push(id);
  2059. }
  2060. else {
  2061. // nothing interesting for me :-(
  2062. }
  2063. }
  2064. }
  2065. break;
  2066. case 'remove':
  2067. // filter the ids of the removed items
  2068. for (i = 0, len = ids.length; i < len; i++) {
  2069. id = ids[i];
  2070. if (this.ids[id]) {
  2071. delete this.ids[id];
  2072. removed.push(id);
  2073. }
  2074. }
  2075. break;
  2076. }
  2077. if (added.length) {
  2078. this._trigger('add', {items: added}, senderId);
  2079. }
  2080. if (updated.length) {
  2081. this._trigger('update', {items: updated}, senderId);
  2082. }
  2083. if (removed.length) {
  2084. this._trigger('remove', {items: removed}, senderId);
  2085. }
  2086. }
  2087. };
  2088. // copy subscription functionality from DataSet
  2089. DataView.prototype.on = DataSet.prototype.on;
  2090. DataView.prototype.off = DataSet.prototype.off;
  2091. DataView.prototype._trigger = DataSet.prototype._trigger;
  2092. // TODO: make these functions deprecated (replaced with `on` and `off` since version 0.5)
  2093. DataView.prototype.subscribe = DataView.prototype.on;
  2094. DataView.prototype.unsubscribe = DataView.prototype.off;
  2095. /**
  2096. * @constructor TimeStep
  2097. * The class TimeStep is an iterator for dates. You provide a start date and an
  2098. * end date. The class itself determines the best scale (step size) based on the
  2099. * provided start Date, end Date, and minimumStep.
  2100. *
  2101. * If minimumStep is provided, the step size is chosen as close as possible
  2102. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2103. * provided, the scale is set to 1 DAY.
  2104. * The minimumStep should correspond with the onscreen size of about 6 characters
  2105. *
  2106. * Alternatively, you can set a scale by hand.
  2107. * After creation, you can initialize the class by executing first(). Then you
  2108. * can iterate from the start date to the end date via next(). You can check if
  2109. * the end date is reached with the function hasNext(). After each step, you can
  2110. * retrieve the current date via getCurrent().
  2111. * The TimeStep has scales ranging from milliseconds, seconds, minutes, hours,
  2112. * days, to years.
  2113. *
  2114. * Version: 1.2
  2115. *
  2116. * @param {Date} [start] The start date, for example new Date(2010, 9, 21)
  2117. * or new Date(2010, 9, 21, 23, 45, 00)
  2118. * @param {Date} [end] The end date
  2119. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  2120. */
  2121. TimeStep = function(start, end, minimumStep) {
  2122. // variables
  2123. this.current = new Date();
  2124. this._start = new Date();
  2125. this._end = new Date();
  2126. this.autoScale = true;
  2127. this.scale = TimeStep.SCALE.DAY;
  2128. this.step = 1;
  2129. // initialize the range
  2130. this.setRange(start, end, minimumStep);
  2131. };
  2132. /// enum scale
  2133. TimeStep.SCALE = {
  2134. MILLISECOND: 1,
  2135. SECOND: 2,
  2136. MINUTE: 3,
  2137. HOUR: 4,
  2138. DAY: 5,
  2139. WEEKDAY: 6,
  2140. MONTH: 7,
  2141. YEAR: 8
  2142. };
  2143. /**
  2144. * Set a new range
  2145. * If minimumStep is provided, the step size is chosen as close as possible
  2146. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2147. * provided, the scale is set to 1 DAY.
  2148. * The minimumStep should correspond with the onscreen size of about 6 characters
  2149. * @param {Date} [start] The start date and time.
  2150. * @param {Date} [end] The end date and time.
  2151. * @param {int} [minimumStep] Optional. Minimum step size in milliseconds
  2152. */
  2153. TimeStep.prototype.setRange = function(start, end, minimumStep) {
  2154. if (!(start instanceof Date) || !(end instanceof Date)) {
  2155. throw "No legal start or end date in method setRange";
  2156. }
  2157. this._start = (start != undefined) ? new Date(start.valueOf()) : new Date();
  2158. this._end = (end != undefined) ? new Date(end.valueOf()) : new Date();
  2159. if (this.autoScale) {
  2160. this.setMinimumStep(minimumStep);
  2161. }
  2162. };
  2163. /**
  2164. * Set the range iterator to the start date.
  2165. */
  2166. TimeStep.prototype.first = function() {
  2167. this.current = new Date(this._start.valueOf());
  2168. this.roundToMinor();
  2169. };
  2170. /**
  2171. * Round the current date to the first minor date value
  2172. * This must be executed once when the current date is set to start Date
  2173. */
  2174. TimeStep.prototype.roundToMinor = function() {
  2175. // round to floor
  2176. // IMPORTANT: we have no breaks in this switch! (this is no bug)
  2177. //noinspection FallthroughInSwitchStatementJS
  2178. switch (this.scale) {
  2179. case TimeStep.SCALE.YEAR:
  2180. this.current.setFullYear(this.step * Math.floor(this.current.getFullYear() / this.step));
  2181. this.current.setMonth(0);
  2182. case TimeStep.SCALE.MONTH: this.current.setDate(1);
  2183. case TimeStep.SCALE.DAY: // intentional fall through
  2184. case TimeStep.SCALE.WEEKDAY: this.current.setHours(0);
  2185. case TimeStep.SCALE.HOUR: this.current.setMinutes(0);
  2186. case TimeStep.SCALE.MINUTE: this.current.setSeconds(0);
  2187. case TimeStep.SCALE.SECOND: this.current.setMilliseconds(0);
  2188. //case TimeStep.SCALE.MILLISECOND: // nothing to do for milliseconds
  2189. }
  2190. if (this.step != 1) {
  2191. // round down to the first minor value that is a multiple of the current step size
  2192. switch (this.scale) {
  2193. case TimeStep.SCALE.MILLISECOND: this.current.setMilliseconds(this.current.getMilliseconds() - this.current.getMilliseconds() % this.step); break;
  2194. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() - this.current.getSeconds() % this.step); break;
  2195. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() - this.current.getMinutes() % this.step); break;
  2196. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() - this.current.getHours() % this.step); break;
  2197. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2198. case TimeStep.SCALE.DAY: this.current.setDate((this.current.getDate()-1) - (this.current.getDate()-1) % this.step + 1); break;
  2199. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() - this.current.getMonth() % this.step); break;
  2200. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() - this.current.getFullYear() % this.step); break;
  2201. default: break;
  2202. }
  2203. }
  2204. };
  2205. /**
  2206. * Check if the there is a next step
  2207. * @return {boolean} true if the current date has not passed the end date
  2208. */
  2209. TimeStep.prototype.hasNext = function () {
  2210. return (this.current.valueOf() <= this._end.valueOf());
  2211. };
  2212. /**
  2213. * Do the next step
  2214. */
  2215. TimeStep.prototype.next = function() {
  2216. var prev = this.current.valueOf();
  2217. // Two cases, needed to prevent issues with switching daylight savings
  2218. // (end of March and end of October)
  2219. if (this.current.getMonth() < 6) {
  2220. switch (this.scale) {
  2221. case TimeStep.SCALE.MILLISECOND:
  2222. this.current = new Date(this.current.valueOf() + this.step); break;
  2223. case TimeStep.SCALE.SECOND: this.current = new Date(this.current.valueOf() + this.step * 1000); break;
  2224. case TimeStep.SCALE.MINUTE: this.current = new Date(this.current.valueOf() + this.step * 1000 * 60); break;
  2225. case TimeStep.SCALE.HOUR:
  2226. this.current = new Date(this.current.valueOf() + this.step * 1000 * 60 * 60);
  2227. // in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...)
  2228. var h = this.current.getHours();
  2229. this.current.setHours(h - (h % this.step));
  2230. break;
  2231. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2232. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2233. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2234. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2235. default: break;
  2236. }
  2237. }
  2238. else {
  2239. switch (this.scale) {
  2240. case TimeStep.SCALE.MILLISECOND: this.current = new Date(this.current.valueOf() + this.step); break;
  2241. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() + this.step); break;
  2242. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() + this.step); break;
  2243. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() + this.step); break;
  2244. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2245. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2246. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2247. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2248. default: break;
  2249. }
  2250. }
  2251. if (this.step != 1) {
  2252. // round down to the correct major value
  2253. switch (this.scale) {
  2254. case TimeStep.SCALE.MILLISECOND: if(this.current.getMilliseconds() < this.step) this.current.setMilliseconds(0); break;
  2255. case TimeStep.SCALE.SECOND: if(this.current.getSeconds() < this.step) this.current.setSeconds(0); break;
  2256. case TimeStep.SCALE.MINUTE: if(this.current.getMinutes() < this.step) this.current.setMinutes(0); break;
  2257. case TimeStep.SCALE.HOUR: if(this.current.getHours() < this.step) this.current.setHours(0); break;
  2258. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2259. case TimeStep.SCALE.DAY: if(this.current.getDate() < this.step+1) this.current.setDate(1); break;
  2260. case TimeStep.SCALE.MONTH: if(this.current.getMonth() < this.step) this.current.setMonth(0); break;
  2261. case TimeStep.SCALE.YEAR: break; // nothing to do for year
  2262. default: break;
  2263. }
  2264. }
  2265. // safety mechanism: if current time is still unchanged, move to the end
  2266. if (this.current.valueOf() == prev) {
  2267. this.current = new Date(this._end.valueOf());
  2268. }
  2269. };
  2270. /**
  2271. * Get the current datetime
  2272. * @return {Date} current The current date
  2273. */
  2274. TimeStep.prototype.getCurrent = function() {
  2275. return this.current;
  2276. };
  2277. /**
  2278. * Set a custom scale. Autoscaling will be disabled.
  2279. * For example setScale(SCALE.MINUTES, 5) will result
  2280. * in minor steps of 5 minutes, and major steps of an hour.
  2281. *
  2282. * @param {TimeStep.SCALE} newScale
  2283. * A scale. Choose from SCALE.MILLISECOND,
  2284. * SCALE.SECOND, SCALE.MINUTE, SCALE.HOUR,
  2285. * SCALE.WEEKDAY, SCALE.DAY, SCALE.MONTH,
  2286. * SCALE.YEAR.
  2287. * @param {Number} newStep A step size, by default 1. Choose for
  2288. * example 1, 2, 5, or 10.
  2289. */
  2290. TimeStep.prototype.setScale = function(newScale, newStep) {
  2291. this.scale = newScale;
  2292. if (newStep > 0) {
  2293. this.step = newStep;
  2294. }
  2295. this.autoScale = false;
  2296. };
  2297. /**
  2298. * Enable or disable autoscaling
  2299. * @param {boolean} enable If true, autoascaling is set true
  2300. */
  2301. TimeStep.prototype.setAutoScale = function (enable) {
  2302. this.autoScale = enable;
  2303. };
  2304. /**
  2305. * Automatically determine the scale that bests fits the provided minimum step
  2306. * @param {Number} [minimumStep] The minimum step size in milliseconds
  2307. */
  2308. TimeStep.prototype.setMinimumStep = function(minimumStep) {
  2309. if (minimumStep == undefined) {
  2310. return;
  2311. }
  2312. var stepYear = (1000 * 60 * 60 * 24 * 30 * 12);
  2313. var stepMonth = (1000 * 60 * 60 * 24 * 30);
  2314. var stepDay = (1000 * 60 * 60 * 24);
  2315. var stepHour = (1000 * 60 * 60);
  2316. var stepMinute = (1000 * 60);
  2317. var stepSecond = (1000);
  2318. var stepMillisecond= (1);
  2319. // find the smallest step that is larger than the provided minimumStep
  2320. if (stepYear*1000 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1000;}
  2321. if (stepYear*500 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 500;}
  2322. if (stepYear*100 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 100;}
  2323. if (stepYear*50 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 50;}
  2324. if (stepYear*10 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 10;}
  2325. if (stepYear*5 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 5;}
  2326. if (stepYear > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1;}
  2327. if (stepMonth*3 > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 3;}
  2328. if (stepMonth > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 1;}
  2329. if (stepDay*5 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 5;}
  2330. if (stepDay*2 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 2;}
  2331. if (stepDay > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 1;}
  2332. if (stepDay/2 > minimumStep) {this.scale = TimeStep.SCALE.WEEKDAY; this.step = 1;}
  2333. if (stepHour*4 > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 4;}
  2334. if (stepHour > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 1;}
  2335. if (stepMinute*15 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 15;}
  2336. if (stepMinute*10 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 10;}
  2337. if (stepMinute*5 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 5;}
  2338. if (stepMinute > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 1;}
  2339. if (stepSecond*15 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 15;}
  2340. if (stepSecond*10 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 10;}
  2341. if (stepSecond*5 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 5;}
  2342. if (stepSecond > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 1;}
  2343. if (stepMillisecond*200 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 200;}
  2344. if (stepMillisecond*100 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 100;}
  2345. if (stepMillisecond*50 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 50;}
  2346. if (stepMillisecond*10 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 10;}
  2347. if (stepMillisecond*5 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 5;}
  2348. if (stepMillisecond > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 1;}
  2349. };
  2350. /**
  2351. * Snap a date to a rounded value.
  2352. * The snap intervals are dependent on the current scale and step.
  2353. * @param {Date} date the date to be snapped.
  2354. * @return {Date} snappedDate
  2355. */
  2356. TimeStep.prototype.snap = function(date) {
  2357. var clone = new Date(date.valueOf());
  2358. if (this.scale == TimeStep.SCALE.YEAR) {
  2359. var year = clone.getFullYear() + Math.round(clone.getMonth() / 12);
  2360. clone.setFullYear(Math.round(year / this.step) * this.step);
  2361. clone.setMonth(0);
  2362. clone.setDate(0);
  2363. clone.setHours(0);
  2364. clone.setMinutes(0);
  2365. clone.setSeconds(0);
  2366. clone.setMilliseconds(0);
  2367. }
  2368. else if (this.scale == TimeStep.SCALE.MONTH) {
  2369. if (clone.getDate() > 15) {
  2370. clone.setDate(1);
  2371. clone.setMonth(clone.getMonth() + 1);
  2372. // important: first set Date to 1, after that change the month.
  2373. }
  2374. else {
  2375. clone.setDate(1);
  2376. }
  2377. clone.setHours(0);
  2378. clone.setMinutes(0);
  2379. clone.setSeconds(0);
  2380. clone.setMilliseconds(0);
  2381. }
  2382. else if (this.scale == TimeStep.SCALE.DAY ||
  2383. this.scale == TimeStep.SCALE.WEEKDAY) {
  2384. //noinspection FallthroughInSwitchStatementJS
  2385. switch (this.step) {
  2386. case 5:
  2387. case 2:
  2388. clone.setHours(Math.round(clone.getHours() / 24) * 24); break;
  2389. default:
  2390. clone.setHours(Math.round(clone.getHours() / 12) * 12); break;
  2391. }
  2392. clone.setMinutes(0);
  2393. clone.setSeconds(0);
  2394. clone.setMilliseconds(0);
  2395. }
  2396. else if (this.scale == TimeStep.SCALE.HOUR) {
  2397. switch (this.step) {
  2398. case 4:
  2399. clone.setMinutes(Math.round(clone.getMinutes() / 60) * 60); break;
  2400. default:
  2401. clone.setMinutes(Math.round(clone.getMinutes() / 30) * 30); break;
  2402. }
  2403. clone.setSeconds(0);
  2404. clone.setMilliseconds(0);
  2405. } else if (this.scale == TimeStep.SCALE.MINUTE) {
  2406. //noinspection FallthroughInSwitchStatementJS
  2407. switch (this.step) {
  2408. case 15:
  2409. case 10:
  2410. clone.setMinutes(Math.round(clone.getMinutes() / 5) * 5);
  2411. clone.setSeconds(0);
  2412. break;
  2413. case 5:
  2414. clone.setSeconds(Math.round(clone.getSeconds() / 60) * 60); break;
  2415. default:
  2416. clone.setSeconds(Math.round(clone.getSeconds() / 30) * 30); break;
  2417. }
  2418. clone.setMilliseconds(0);
  2419. }
  2420. else if (this.scale == TimeStep.SCALE.SECOND) {
  2421. //noinspection FallthroughInSwitchStatementJS
  2422. switch (this.step) {
  2423. case 15:
  2424. case 10:
  2425. clone.setSeconds(Math.round(clone.getSeconds() / 5) * 5);
  2426. clone.setMilliseconds(0);
  2427. break;
  2428. case 5:
  2429. clone.setMilliseconds(Math.round(clone.getMilliseconds() / 1000) * 1000); break;
  2430. default:
  2431. clone.setMilliseconds(Math.round(clone.getMilliseconds() / 500) * 500); break;
  2432. }
  2433. }
  2434. else if (this.scale == TimeStep.SCALE.MILLISECOND) {
  2435. var step = this.step > 5 ? this.step / 2 : 1;
  2436. clone.setMilliseconds(Math.round(clone.getMilliseconds() / step) * step);
  2437. }
  2438. return clone;
  2439. };
  2440. /**
  2441. * Check if the current value is a major value (for example when the step
  2442. * is DAY, a major value is each first day of the MONTH)
  2443. * @return {boolean} true if current date is major, else false.
  2444. */
  2445. TimeStep.prototype.isMajor = function() {
  2446. switch (this.scale) {
  2447. case TimeStep.SCALE.MILLISECOND:
  2448. return (this.current.getMilliseconds() == 0);
  2449. case TimeStep.SCALE.SECOND:
  2450. return (this.current.getSeconds() == 0);
  2451. case TimeStep.SCALE.MINUTE:
  2452. return (this.current.getHours() == 0) && (this.current.getMinutes() == 0);
  2453. // Note: this is no bug. Major label is equal for both minute and hour scale
  2454. case TimeStep.SCALE.HOUR:
  2455. return (this.current.getHours() == 0);
  2456. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2457. case TimeStep.SCALE.DAY:
  2458. return (this.current.getDate() == 1);
  2459. case TimeStep.SCALE.MONTH:
  2460. return (this.current.getMonth() == 0);
  2461. case TimeStep.SCALE.YEAR:
  2462. return false;
  2463. default:
  2464. return false;
  2465. }
  2466. };
  2467. /**
  2468. * Returns formatted text for the minor axislabel, depending on the current
  2469. * date and the scale. For example when scale is MINUTE, the current time is
  2470. * formatted as "hh:mm".
  2471. * @param {Date} [date] custom date. if not provided, current date is taken
  2472. */
  2473. TimeStep.prototype.getLabelMinor = function(date) {
  2474. if (date == undefined) {
  2475. date = this.current;
  2476. }
  2477. switch (this.scale) {
  2478. case TimeStep.SCALE.MILLISECOND: return moment(date).format('SSS');
  2479. case TimeStep.SCALE.SECOND: return moment(date).format('s');
  2480. case TimeStep.SCALE.MINUTE: return moment(date).format('HH:mm');
  2481. case TimeStep.SCALE.HOUR: return moment(date).format('HH:mm');
  2482. case TimeStep.SCALE.WEEKDAY: return moment(date).format('ddd D');
  2483. case TimeStep.SCALE.DAY: return moment(date).format('D');
  2484. case TimeStep.SCALE.MONTH: return moment(date).format('MMM');
  2485. case TimeStep.SCALE.YEAR: return moment(date).format('YYYY');
  2486. default: return '';
  2487. }
  2488. };
  2489. /**
  2490. * Returns formatted text for the major axis label, depending on the current
  2491. * date and the scale. For example when scale is MINUTE, the major scale is
  2492. * hours, and the hour will be formatted as "hh".
  2493. * @param {Date} [date] custom date. if not provided, current date is taken
  2494. */
  2495. TimeStep.prototype.getLabelMajor = function(date) {
  2496. if (date == undefined) {
  2497. date = this.current;
  2498. }
  2499. //noinspection FallthroughInSwitchStatementJS
  2500. switch (this.scale) {
  2501. case TimeStep.SCALE.MILLISECOND:return moment(date).format('HH:mm:ss');
  2502. case TimeStep.SCALE.SECOND: return moment(date).format('D MMMM HH:mm');
  2503. case TimeStep.SCALE.MINUTE:
  2504. case TimeStep.SCALE.HOUR: return moment(date).format('ddd D MMMM');
  2505. case TimeStep.SCALE.WEEKDAY:
  2506. case TimeStep.SCALE.DAY: return moment(date).format('MMMM YYYY');
  2507. case TimeStep.SCALE.MONTH: return moment(date).format('YYYY');
  2508. case TimeStep.SCALE.YEAR: return '';
  2509. default: return '';
  2510. }
  2511. };
  2512. /**
  2513. * @constructor Stack
  2514. * Stacks items on top of each other.
  2515. * @param {ItemSet} itemset
  2516. * @param {Object} [options]
  2517. */
  2518. function Stack (itemset, options) {
  2519. this.itemset = itemset;
  2520. this.options = options || {};
  2521. this.defaultOptions = {
  2522. order: function (a, b) {
  2523. //return (b.width - a.width) || (a.left - b.left); // TODO: cleanup
  2524. // Order: ranges over non-ranges, ranged ordered by width, and
  2525. // lastly ordered by start.
  2526. if (a instanceof ItemRange) {
  2527. if (b instanceof ItemRange) {
  2528. var aInt = (a.data.end - a.data.start);
  2529. var bInt = (b.data.end - b.data.start);
  2530. return (aInt - bInt) || (a.data.start - b.data.start);
  2531. }
  2532. else {
  2533. return -1;
  2534. }
  2535. }
  2536. else {
  2537. if (b instanceof ItemRange) {
  2538. return 1;
  2539. }
  2540. else {
  2541. return (a.data.start - b.data.start);
  2542. }
  2543. }
  2544. },
  2545. margin: {
  2546. item: 10
  2547. }
  2548. };
  2549. this.ordered = []; // ordered items
  2550. }
  2551. /**
  2552. * Set options for the stack
  2553. * @param {Object} options Available options:
  2554. * {ItemSet} itemset
  2555. * {Number} margin
  2556. * {function} order Stacking order
  2557. */
  2558. Stack.prototype.setOptions = function setOptions (options) {
  2559. util.extend(this.options, options);
  2560. // TODO: register on data changes at the connected itemset, and update the changed part only and immediately
  2561. };
  2562. /**
  2563. * Stack the items such that they don't overlap. The items will have a minimal
  2564. * distance equal to options.margin.item.
  2565. */
  2566. Stack.prototype.update = function update() {
  2567. this._order();
  2568. this._stack();
  2569. };
  2570. /**
  2571. * Order the items. If a custom order function has been provided via the options,
  2572. * then this will be used.
  2573. * @private
  2574. */
  2575. Stack.prototype._order = function _order () {
  2576. var items = this.itemset.items;
  2577. if (!items) {
  2578. throw new Error('Cannot stack items: ItemSet does not contain items');
  2579. }
  2580. // TODO: store the sorted items, to have less work later on
  2581. var ordered = [];
  2582. var index = 0;
  2583. // items is a map (no array)
  2584. util.forEach(items, function (item) {
  2585. if (item.visible) {
  2586. ordered[index] = item;
  2587. index++;
  2588. }
  2589. });
  2590. //if a customer stack order function exists, use it.
  2591. var order = this.options.order || this.defaultOptions.order;
  2592. if (!(typeof order === 'function')) {
  2593. throw new Error('Option order must be a function');
  2594. }
  2595. ordered.sort(order);
  2596. this.ordered = ordered;
  2597. };
  2598. /**
  2599. * Adjust vertical positions of the events such that they don't overlap each
  2600. * other.
  2601. * @private
  2602. */
  2603. Stack.prototype._stack = function _stack () {
  2604. var i,
  2605. iMax,
  2606. ordered = this.ordered,
  2607. options = this.options,
  2608. orientation = options.orientation || this.defaultOptions.orientation,
  2609. axisOnTop = (orientation == 'top'),
  2610. margin;
  2611. if (options.margin && options.margin.item !== undefined) {
  2612. margin = options.margin.item;
  2613. }
  2614. else {
  2615. margin = this.defaultOptions.margin.item
  2616. }
  2617. // calculate new, non-overlapping positions
  2618. for (i = 0, iMax = ordered.length; i < iMax; i++) {
  2619. var item = ordered[i];
  2620. var collidingItem = null;
  2621. do {
  2622. // TODO: optimize checking for overlap. when there is a gap without items,
  2623. // you only need to check for items from the next item on, not from zero
  2624. collidingItem = this.checkOverlap(ordered, i, 0, i - 1, margin);
  2625. if (collidingItem != null) {
  2626. // There is a collision. Reposition the event above the colliding element
  2627. if (axisOnTop) {
  2628. item.top = collidingItem.top + collidingItem.height + margin;
  2629. }
  2630. else {
  2631. item.top = collidingItem.top - item.height - margin;
  2632. }
  2633. }
  2634. } while (collidingItem);
  2635. }
  2636. };
  2637. /**
  2638. * Check if the destiny position of given item overlaps with any
  2639. * of the other items from index itemStart to itemEnd.
  2640. * @param {Array} items Array with items
  2641. * @param {int} itemIndex Number of the item to be checked for overlap
  2642. * @param {int} itemStart First item to be checked.
  2643. * @param {int} itemEnd Last item to be checked.
  2644. * @return {Object | null} colliding item, or undefined when no collisions
  2645. * @param {Number} margin A minimum required margin.
  2646. * If margin is provided, the two items will be
  2647. * marked colliding when they overlap or
  2648. * when the margin between the two is smaller than
  2649. * the requested margin.
  2650. */
  2651. Stack.prototype.checkOverlap = function checkOverlap (items, itemIndex,
  2652. itemStart, itemEnd, margin) {
  2653. var collision = this.collision;
  2654. // we loop from end to start, as we suppose that the chance of a
  2655. // collision is larger for items at the end, so check these first.
  2656. var a = items[itemIndex];
  2657. for (var i = itemEnd; i >= itemStart; i--) {
  2658. var b = items[i];
  2659. if (collision(a, b, margin)) {
  2660. if (i != itemIndex) {
  2661. return b;
  2662. }
  2663. }
  2664. }
  2665. return null;
  2666. };
  2667. /**
  2668. * Test if the two provided items collide
  2669. * The items must have parameters left, width, top, and height.
  2670. * @param {Component} a The first item
  2671. * @param {Component} b The second item
  2672. * @param {Number} margin A minimum required margin.
  2673. * If margin is provided, the two items will be
  2674. * marked colliding when they overlap or
  2675. * when the margin between the two is smaller than
  2676. * the requested margin.
  2677. * @return {boolean} true if a and b collide, else false
  2678. */
  2679. Stack.prototype.collision = function collision (a, b, margin) {
  2680. return ((a.left - margin) < (b.left + b.width) &&
  2681. (a.left + a.width + margin) > b.left &&
  2682. (a.top - margin) < (b.top + b.height) &&
  2683. (a.top + a.height + margin) > b.top);
  2684. };
  2685. /**
  2686. * @constructor Range
  2687. * A Range controls a numeric range with a start and end value.
  2688. * The Range adjusts the range based on mouse events or programmatic changes,
  2689. * and triggers events when the range is changing or has been changed.
  2690. * @param {Object} [options] See description at Range.setOptions
  2691. * @extends Controller
  2692. */
  2693. function Range(options) {
  2694. this.id = util.randomUUID();
  2695. this.start = null; // Number
  2696. this.end = null; // Number
  2697. this.options = options || {};
  2698. this.setOptions(options);
  2699. }
  2700. // extend the Range prototype with an event emitter mixin
  2701. Emitter(Range.prototype);
  2702. /**
  2703. * Set options for the range controller
  2704. * @param {Object} options Available options:
  2705. * {Number} min Minimum value for start
  2706. * {Number} max Maximum value for end
  2707. * {Number} zoomMin Set a minimum value for
  2708. * (end - start).
  2709. * {Number} zoomMax Set a maximum value for
  2710. * (end - start).
  2711. */
  2712. Range.prototype.setOptions = function (options) {
  2713. util.extend(this.options, options);
  2714. // re-apply range with new limitations
  2715. if (this.start !== null && this.end !== null) {
  2716. this.setRange(this.start, this.end);
  2717. }
  2718. };
  2719. /**
  2720. * Test whether direction has a valid value
  2721. * @param {String} direction 'horizontal' or 'vertical'
  2722. */
  2723. function validateDirection (direction) {
  2724. if (direction != 'horizontal' && direction != 'vertical') {
  2725. throw new TypeError('Unknown direction "' + direction + '". ' +
  2726. 'Choose "horizontal" or "vertical".');
  2727. }
  2728. }
  2729. /**
  2730. * Add listeners for mouse and touch events to the component
  2731. * @param {Controller} controller
  2732. * @param {Component} component Should be a rootpanel
  2733. * @param {String} event Available events: 'move', 'zoom'
  2734. * @param {String} direction Available directions: 'horizontal', 'vertical'
  2735. */
  2736. Range.prototype.subscribe = function (controller, component, event, direction) {
  2737. var me = this;
  2738. if (event == 'move') {
  2739. // drag start listener
  2740. controller.on('dragstart', function (event) {
  2741. me._onDragStart(event, component);
  2742. });
  2743. // drag listener
  2744. controller.on('drag', function (event) {
  2745. me._onDrag(event, component, direction);
  2746. });
  2747. // drag end listener
  2748. controller.on('dragend', function (event) {
  2749. me._onDragEnd(event, component);
  2750. });
  2751. // ignore dragging when holding
  2752. controller.on('hold', function (event) {
  2753. me._onHold();
  2754. });
  2755. }
  2756. else if (event == 'zoom') {
  2757. // mouse wheel
  2758. function mousewheel (event) {
  2759. me._onMouseWheel(event, component, direction);
  2760. }
  2761. controller.on('mousewheel', mousewheel);
  2762. controller.on('DOMMouseScroll', mousewheel); // For FF
  2763. // pinch
  2764. controller.on('touch', function (event) {
  2765. me._onTouch(event);
  2766. });
  2767. controller.on('pinch', function (event) {
  2768. me._onPinch(event, component, direction);
  2769. });
  2770. }
  2771. else {
  2772. throw new TypeError('Unknown event "' + event + '". ' +
  2773. 'Choose "move" or "zoom".');
  2774. }
  2775. };
  2776. /**
  2777. * Set a new start and end range
  2778. * @param {Number} [start]
  2779. * @param {Number} [end]
  2780. */
  2781. Range.prototype.setRange = function(start, end) {
  2782. var changed = this._applyRange(start, end);
  2783. if (changed) {
  2784. var params = {
  2785. start: this.start,
  2786. end: this.end
  2787. };
  2788. this.emit('rangechange', params);
  2789. this.emit('rangechanged', params);
  2790. }
  2791. };
  2792. /**
  2793. * Set a new start and end range. This method is the same as setRange, but
  2794. * does not trigger a range change and range changed event, and it returns
  2795. * true when the range is changed
  2796. * @param {Number} [start]
  2797. * @param {Number} [end]
  2798. * @return {Boolean} changed
  2799. * @private
  2800. */
  2801. Range.prototype._applyRange = function(start, end) {
  2802. var newStart = (start != null) ? util.convert(start, 'Date').valueOf() : this.start,
  2803. newEnd = (end != null) ? util.convert(end, 'Date').valueOf() : this.end,
  2804. max = (this.options.max != null) ? util.convert(this.options.max, 'Date').valueOf() : null,
  2805. min = (this.options.min != null) ? util.convert(this.options.min, 'Date').valueOf() : null,
  2806. diff;
  2807. // check for valid number
  2808. if (isNaN(newStart) || newStart === null) {
  2809. throw new Error('Invalid start "' + start + '"');
  2810. }
  2811. if (isNaN(newEnd) || newEnd === null) {
  2812. throw new Error('Invalid end "' + end + '"');
  2813. }
  2814. // prevent start < end
  2815. if (newEnd < newStart) {
  2816. newEnd = newStart;
  2817. }
  2818. // prevent start < min
  2819. if (min !== null) {
  2820. if (newStart < min) {
  2821. diff = (min - newStart);
  2822. newStart += diff;
  2823. newEnd += diff;
  2824. // prevent end > max
  2825. if (max != null) {
  2826. if (newEnd > max) {
  2827. newEnd = max;
  2828. }
  2829. }
  2830. }
  2831. }
  2832. // prevent end > max
  2833. if (max !== null) {
  2834. if (newEnd > max) {
  2835. diff = (newEnd - max);
  2836. newStart -= diff;
  2837. newEnd -= diff;
  2838. // prevent start < min
  2839. if (min != null) {
  2840. if (newStart < min) {
  2841. newStart = min;
  2842. }
  2843. }
  2844. }
  2845. }
  2846. // prevent (end-start) < zoomMin
  2847. if (this.options.zoomMin !== null) {
  2848. var zoomMin = parseFloat(this.options.zoomMin);
  2849. if (zoomMin < 0) {
  2850. zoomMin = 0;
  2851. }
  2852. if ((newEnd - newStart) < zoomMin) {
  2853. if ((this.end - this.start) === zoomMin) {
  2854. // ignore this action, we are already zoomed to the minimum
  2855. newStart = this.start;
  2856. newEnd = this.end;
  2857. }
  2858. else {
  2859. // zoom to the minimum
  2860. diff = (zoomMin - (newEnd - newStart));
  2861. newStart -= diff / 2;
  2862. newEnd += diff / 2;
  2863. }
  2864. }
  2865. }
  2866. // prevent (end-start) > zoomMax
  2867. if (this.options.zoomMax !== null) {
  2868. var zoomMax = parseFloat(this.options.zoomMax);
  2869. if (zoomMax < 0) {
  2870. zoomMax = 0;
  2871. }
  2872. if ((newEnd - newStart) > zoomMax) {
  2873. if ((this.end - this.start) === zoomMax) {
  2874. // ignore this action, we are already zoomed to the maximum
  2875. newStart = this.start;
  2876. newEnd = this.end;
  2877. }
  2878. else {
  2879. // zoom to the maximum
  2880. diff = ((newEnd - newStart) - zoomMax);
  2881. newStart += diff / 2;
  2882. newEnd -= diff / 2;
  2883. }
  2884. }
  2885. }
  2886. var changed = (this.start != newStart || this.end != newEnd);
  2887. this.start = newStart;
  2888. this.end = newEnd;
  2889. return changed;
  2890. };
  2891. /**
  2892. * Retrieve the current range.
  2893. * @return {Object} An object with start and end properties
  2894. */
  2895. Range.prototype.getRange = function() {
  2896. return {
  2897. start: this.start,
  2898. end: this.end
  2899. };
  2900. };
  2901. /**
  2902. * Calculate the conversion offset and scale for current range, based on
  2903. * the provided width
  2904. * @param {Number} width
  2905. * @returns {{offset: number, scale: number}} conversion
  2906. */
  2907. Range.prototype.conversion = function (width) {
  2908. return Range.conversion(this.start, this.end, width);
  2909. };
  2910. /**
  2911. * Static method to calculate the conversion offset and scale for a range,
  2912. * based on the provided start, end, and width
  2913. * @param {Number} start
  2914. * @param {Number} end
  2915. * @param {Number} width
  2916. * @returns {{offset: number, scale: number}} conversion
  2917. */
  2918. Range.conversion = function (start, end, width) {
  2919. if (width != 0 && (end - start != 0)) {
  2920. return {
  2921. offset: start,
  2922. scale: width / (end - start)
  2923. }
  2924. }
  2925. else {
  2926. return {
  2927. offset: 0,
  2928. scale: 1
  2929. };
  2930. }
  2931. };
  2932. // global (private) object to store drag params
  2933. var touchParams = {};
  2934. /**
  2935. * Start dragging horizontally or vertically
  2936. * @param {Event} event
  2937. * @param {Object} component
  2938. * @private
  2939. */
  2940. Range.prototype._onDragStart = function(event, component) {
  2941. // refuse to drag when we where pinching to prevent the timeline make a jump
  2942. // when releasing the fingers in opposite order from the touch screen
  2943. if (touchParams.ignore) return;
  2944. // TODO: reckon with option movable
  2945. touchParams.start = this.start;
  2946. touchParams.end = this.end;
  2947. var frame = component.frame;
  2948. if (frame) {
  2949. frame.style.cursor = 'move';
  2950. }
  2951. };
  2952. /**
  2953. * Perform dragging operating.
  2954. * @param {Event} event
  2955. * @param {Component} component
  2956. * @param {String} direction 'horizontal' or 'vertical'
  2957. * @private
  2958. */
  2959. Range.prototype._onDrag = function (event, component, direction) {
  2960. validateDirection(direction);
  2961. // TODO: reckon with option movable
  2962. // refuse to drag when we where pinching to prevent the timeline make a jump
  2963. // when releasing the fingers in opposite order from the touch screen
  2964. if (touchParams.ignore) return;
  2965. var delta = (direction == 'horizontal') ? event.gesture.deltaX : event.gesture.deltaY,
  2966. interval = (touchParams.end - touchParams.start),
  2967. width = (direction == 'horizontal') ? component.width : component.height,
  2968. diffRange = -delta / width * interval;
  2969. this._applyRange(touchParams.start + diffRange, touchParams.end + diffRange);
  2970. this.emit('rangechange', {
  2971. start: this.start,
  2972. end: this.end
  2973. });
  2974. };
  2975. /**
  2976. * Stop dragging operating.
  2977. * @param {event} event
  2978. * @param {Component} component
  2979. * @private
  2980. */
  2981. Range.prototype._onDragEnd = function (event, component) {
  2982. // refuse to drag when we where pinching to prevent the timeline make a jump
  2983. // when releasing the fingers in opposite order from the touch screen
  2984. if (touchParams.ignore) return;
  2985. // TODO: reckon with option movable
  2986. if (component.frame) {
  2987. component.frame.style.cursor = 'auto';
  2988. }
  2989. // fire a rangechanged event
  2990. this.emit('rangechanged', {
  2991. start: this.start,
  2992. end: this.end
  2993. });
  2994. };
  2995. /**
  2996. * Event handler for mouse wheel event, used to zoom
  2997. * Code from http://adomas.org/javascript-mouse-wheel/
  2998. * @param {Event} event
  2999. * @param {Component} component
  3000. * @param {String} direction 'horizontal' or 'vertical'
  3001. * @private
  3002. */
  3003. Range.prototype._onMouseWheel = function(event, component, direction) {
  3004. validateDirection(direction);
  3005. // TODO: reckon with option zoomable
  3006. // retrieve delta
  3007. var delta = 0;
  3008. if (event.wheelDelta) { /* IE/Opera. */
  3009. delta = event.wheelDelta / 120;
  3010. } else if (event.detail) { /* Mozilla case. */
  3011. // In Mozilla, sign of delta is different than in IE.
  3012. // Also, delta is multiple of 3.
  3013. delta = -event.detail / 3;
  3014. }
  3015. // If delta is nonzero, handle it.
  3016. // Basically, delta is now positive if wheel was scrolled up,
  3017. // and negative, if wheel was scrolled down.
  3018. if (delta) {
  3019. // perform the zoom action. Delta is normally 1 or -1
  3020. // adjust a negative delta such that zooming in with delta 0.1
  3021. // equals zooming out with a delta -0.1
  3022. var scale;
  3023. if (delta < 0) {
  3024. scale = 1 - (delta / 5);
  3025. }
  3026. else {
  3027. scale = 1 / (1 + (delta / 5)) ;
  3028. }
  3029. // calculate center, the date to zoom around
  3030. var gesture = util.fakeGesture(this, event),
  3031. pointer = getPointer(gesture.center, component.frame),
  3032. pointerDate = this._pointerToDate(component, direction, pointer);
  3033. this.zoom(scale, pointerDate);
  3034. }
  3035. // Prevent default actions caused by mouse wheel
  3036. // (else the page and timeline both zoom and scroll)
  3037. event.preventDefault();
  3038. };
  3039. /**
  3040. * Start of a touch gesture
  3041. * @private
  3042. */
  3043. Range.prototype._onTouch = function (event) {
  3044. touchParams.start = this.start;
  3045. touchParams.end = this.end;
  3046. touchParams.ignore = false;
  3047. touchParams.center = null;
  3048. // don't move the range when dragging a selected event
  3049. // TODO: it's not so neat to have to know about the state of the ItemSet
  3050. var item = ItemSet.itemFromTarget(event);
  3051. if (item && item.selected && this.options.editable) {
  3052. touchParams.ignore = true;
  3053. }
  3054. };
  3055. /**
  3056. * On start of a hold gesture
  3057. * @private
  3058. */
  3059. Range.prototype._onHold = function () {
  3060. touchParams.ignore = true;
  3061. };
  3062. /**
  3063. * Handle pinch event
  3064. * @param {Event} event
  3065. * @param {Component} component
  3066. * @param {String} direction 'horizontal' or 'vertical'
  3067. * @private
  3068. */
  3069. Range.prototype._onPinch = function (event, component, direction) {
  3070. touchParams.ignore = true;
  3071. // TODO: reckon with option zoomable
  3072. if (event.gesture.touches.length > 1) {
  3073. if (!touchParams.center) {
  3074. touchParams.center = getPointer(event.gesture.center, component.frame);
  3075. }
  3076. var scale = 1 / event.gesture.scale,
  3077. initDate = this._pointerToDate(component, direction, touchParams.center),
  3078. center = getPointer(event.gesture.center, component.frame),
  3079. date = this._pointerToDate(component, direction, center),
  3080. delta = date - initDate; // TODO: utilize delta
  3081. // calculate new start and end
  3082. var newStart = parseInt(initDate + (touchParams.start - initDate) * scale);
  3083. var newEnd = parseInt(initDate + (touchParams.end - initDate) * scale);
  3084. // apply new range
  3085. this.setRange(newStart, newEnd);
  3086. }
  3087. };
  3088. /**
  3089. * Helper function to calculate the center date for zooming
  3090. * @param {Component} component
  3091. * @param {{x: Number, y: Number}} pointer
  3092. * @param {String} direction 'horizontal' or 'vertical'
  3093. * @return {number} date
  3094. * @private
  3095. */
  3096. Range.prototype._pointerToDate = function (component, direction, pointer) {
  3097. var conversion;
  3098. if (direction == 'horizontal') {
  3099. var width = component.width;
  3100. conversion = this.conversion(width);
  3101. return pointer.x / conversion.scale + conversion.offset;
  3102. }
  3103. else {
  3104. var height = component.height;
  3105. conversion = this.conversion(height);
  3106. return pointer.y / conversion.scale + conversion.offset;
  3107. }
  3108. };
  3109. /**
  3110. * Get the pointer location relative to the location of the dom element
  3111. * @param {{pageX: Number, pageY: Number}} touch
  3112. * @param {Element} element HTML DOM element
  3113. * @return {{x: Number, y: Number}} pointer
  3114. * @private
  3115. */
  3116. function getPointer (touch, element) {
  3117. return {
  3118. x: touch.pageX - vis.util.getAbsoluteLeft(element),
  3119. y: touch.pageY - vis.util.getAbsoluteTop(element)
  3120. };
  3121. }
  3122. /**
  3123. * Zoom the range the given scale in or out. Start and end date will
  3124. * be adjusted, and the timeline will be redrawn. You can optionally give a
  3125. * date around which to zoom.
  3126. * For example, try scale = 0.9 or 1.1
  3127. * @param {Number} scale Scaling factor. Values above 1 will zoom out,
  3128. * values below 1 will zoom in.
  3129. * @param {Number} [center] Value representing a date around which will
  3130. * be zoomed.
  3131. */
  3132. Range.prototype.zoom = function(scale, center) {
  3133. // if centerDate is not provided, take it half between start Date and end Date
  3134. if (center == null) {
  3135. center = (this.start + this.end) / 2;
  3136. }
  3137. // calculate new start and end
  3138. var newStart = center + (this.start - center) * scale;
  3139. var newEnd = center + (this.end - center) * scale;
  3140. this.setRange(newStart, newEnd);
  3141. };
  3142. /**
  3143. * Move the range with a given delta to the left or right. Start and end
  3144. * value will be adjusted. For example, try delta = 0.1 or -0.1
  3145. * @param {Number} delta Moving amount. Positive value will move right,
  3146. * negative value will move left
  3147. */
  3148. Range.prototype.move = function(delta) {
  3149. // zoom start Date and end Date relative to the centerDate
  3150. var diff = (this.end - this.start);
  3151. // apply new values
  3152. var newStart = this.start + diff * delta;
  3153. var newEnd = this.end + diff * delta;
  3154. // TODO: reckon with min and max range
  3155. this.start = newStart;
  3156. this.end = newEnd;
  3157. };
  3158. /**
  3159. * Move the range to a new center point
  3160. * @param {Number} moveTo New center point of the range
  3161. */
  3162. Range.prototype.moveTo = function(moveTo) {
  3163. var center = (this.start + this.end) / 2;
  3164. var diff = center - moveTo;
  3165. // calculate new start and end
  3166. var newStart = this.start - diff;
  3167. var newEnd = this.end - diff;
  3168. this.setRange(newStart, newEnd);
  3169. };
  3170. /**
  3171. * @constructor Controller
  3172. *
  3173. * A Controller controls the reflows and repaints of all components,
  3174. * and is used as an event bus for all components.
  3175. */
  3176. function Controller () {
  3177. var me = this;
  3178. this.id = util.randomUUID();
  3179. this.components = {};
  3180. /**
  3181. * Listen for a 'request-reflow' event. The controller will schedule a reflow
  3182. * @param {Boolean} [force] If true, an immediate reflow is forced. Default
  3183. * is false.
  3184. */
  3185. var reflowTimer = null;
  3186. this.on('request-reflow', function requestReflow(force) {
  3187. if (force) {
  3188. me.reflow();
  3189. }
  3190. else {
  3191. if (!reflowTimer) {
  3192. reflowTimer = setTimeout(function () {
  3193. reflowTimer = null;
  3194. me.reflow();
  3195. }, 0);
  3196. }
  3197. }
  3198. });
  3199. /**
  3200. * Request a repaint. The controller will schedule a repaint
  3201. * @param {Boolean} [force] If true, an immediate repaint is forced. Default
  3202. * is false.
  3203. */
  3204. var repaintTimer = null;
  3205. this.on('request-repaint', function requestRepaint(force) {
  3206. if (force) {
  3207. me.repaint();
  3208. }
  3209. else {
  3210. if (!repaintTimer) {
  3211. repaintTimer = setTimeout(function () {
  3212. repaintTimer = null;
  3213. me.repaint();
  3214. }, 0);
  3215. }
  3216. }
  3217. });
  3218. }
  3219. // Extend controller with Emitter mixin
  3220. Emitter(Controller.prototype);
  3221. /**
  3222. * Add a component to the controller
  3223. * @param {Component} component
  3224. */
  3225. Controller.prototype.add = function add(component) {
  3226. // validate the component
  3227. if (component.id == undefined) {
  3228. throw new Error('Component has no field id');
  3229. }
  3230. if (!(component instanceof Component) && !(component instanceof Controller)) {
  3231. throw new TypeError('Component must be an instance of ' +
  3232. 'prototype Component or Controller');
  3233. }
  3234. // add the component
  3235. component.setController(this);
  3236. this.components[component.id] = component;
  3237. };
  3238. /**
  3239. * Remove a component from the controller
  3240. * @param {Component | String} component
  3241. */
  3242. Controller.prototype.remove = function remove(component) {
  3243. var id;
  3244. for (id in this.components) {
  3245. if (this.components.hasOwnProperty(id)) {
  3246. if (id == component || this.components[id] === component) {
  3247. break;
  3248. }
  3249. }
  3250. }
  3251. if (id) {
  3252. // unregister the controller (gives the component the ability to unregister
  3253. // event listeners and clean up other stuff)
  3254. this.components[id].setController(null);
  3255. delete this.components[id];
  3256. }
  3257. };
  3258. /**
  3259. * Repaint all components
  3260. */
  3261. Controller.prototype.repaint = function repaint() {
  3262. var changed = false;
  3263. // cancel any running repaint request
  3264. if (this.repaintTimer) {
  3265. clearTimeout(this.repaintTimer);
  3266. this.repaintTimer = undefined;
  3267. }
  3268. var done = {};
  3269. function repaint(component, id) {
  3270. if (!(id in done)) {
  3271. // first repaint the components on which this component is dependent
  3272. if (component.depends) {
  3273. component.depends.forEach(function (dep) {
  3274. repaint(dep, dep.id);
  3275. });
  3276. }
  3277. if (component.parent) {
  3278. repaint(component.parent, component.parent.id);
  3279. }
  3280. // repaint the component itself and mark as done
  3281. changed = component.repaint() || changed;
  3282. done[id] = true;
  3283. }
  3284. }
  3285. util.forEach(this.components, repaint);
  3286. this.emit('repaint');
  3287. // immediately reflow when needed
  3288. if (changed) {
  3289. this.reflow();
  3290. }
  3291. // TODO: limit the number of nested reflows/repaints, prevent loop
  3292. };
  3293. /**
  3294. * Reflow all components
  3295. */
  3296. Controller.prototype.reflow = function reflow() {
  3297. var resized = false;
  3298. // cancel any running repaint request
  3299. if (this.reflowTimer) {
  3300. clearTimeout(this.reflowTimer);
  3301. this.reflowTimer = undefined;
  3302. }
  3303. var done = {};
  3304. function reflow(component, id) {
  3305. if (!(id in done)) {
  3306. // first reflow the components on which this component is dependent
  3307. if (component.depends) {
  3308. component.depends.forEach(function (dep) {
  3309. reflow(dep, dep.id);
  3310. });
  3311. }
  3312. if (component.parent) {
  3313. reflow(component.parent, component.parent.id);
  3314. }
  3315. // reflow the component itself and mark as done
  3316. resized = component.reflow() || resized;
  3317. done[id] = true;
  3318. }
  3319. }
  3320. util.forEach(this.components, reflow);
  3321. this.emit('reflow');
  3322. // immediately repaint when needed
  3323. if (resized) {
  3324. this.repaint();
  3325. }
  3326. // TODO: limit the number of nested reflows/repaints, prevent loop
  3327. };
  3328. /**
  3329. * Prototype for visual components
  3330. */
  3331. function Component () {
  3332. this.id = null;
  3333. this.parent = null;
  3334. this.depends = null;
  3335. this.controller = null;
  3336. this.options = null;
  3337. this.frame = null; // main DOM element
  3338. this.top = 0;
  3339. this.left = 0;
  3340. this.width = 0;
  3341. this.height = 0;
  3342. }
  3343. /**
  3344. * Set parameters for the frame. Parameters will be merged in current parameter
  3345. * set.
  3346. * @param {Object} options Available parameters:
  3347. * {String | function} [className]
  3348. * {String | Number | function} [left]
  3349. * {String | Number | function} [top]
  3350. * {String | Number | function} [width]
  3351. * {String | Number | function} [height]
  3352. */
  3353. Component.prototype.setOptions = function setOptions(options) {
  3354. if (options) {
  3355. util.extend(this.options, options);
  3356. if (this.controller) {
  3357. this.requestRepaint();
  3358. this.requestReflow();
  3359. }
  3360. }
  3361. };
  3362. /**
  3363. * Get an option value by name
  3364. * The function will first check this.options object, and else will check
  3365. * this.defaultOptions.
  3366. * @param {String} name
  3367. * @return {*} value
  3368. */
  3369. Component.prototype.getOption = function getOption(name) {
  3370. var value;
  3371. if (this.options) {
  3372. value = this.options[name];
  3373. }
  3374. if (value === undefined && this.defaultOptions) {
  3375. value = this.defaultOptions[name];
  3376. }
  3377. return value;
  3378. };
  3379. /**
  3380. * Set controller for this component, or remove current controller by passing
  3381. * null as parameter value.
  3382. * @param {Controller | null} controller
  3383. */
  3384. Component.prototype.setController = function setController (controller) {
  3385. this.controller = controller || null;
  3386. };
  3387. /**
  3388. * Get controller of this component
  3389. * @return {Controller} controller
  3390. */
  3391. Component.prototype.getController = function getController () {
  3392. return this.controller;
  3393. };
  3394. /**
  3395. * Get the container element of the component, which can be used by a child to
  3396. * add its own widgets. Not all components do have a container for childs, in
  3397. * that case null is returned.
  3398. * @returns {HTMLElement | null} container
  3399. */
  3400. // TODO: get rid of the getContainer and getFrame methods, provide these via the options
  3401. Component.prototype.getContainer = function getContainer() {
  3402. // should be implemented by the component
  3403. return null;
  3404. };
  3405. /**
  3406. * Get the frame element of the component, the outer HTML DOM element.
  3407. * @returns {HTMLElement | null} frame
  3408. */
  3409. Component.prototype.getFrame = function getFrame() {
  3410. return this.frame;
  3411. };
  3412. /**
  3413. * Repaint the component
  3414. * @return {Boolean} changed
  3415. */
  3416. Component.prototype.repaint = function repaint() {
  3417. // should be implemented by the component
  3418. return false;
  3419. };
  3420. /**
  3421. * Reflow the component
  3422. * @return {Boolean} resized
  3423. */
  3424. Component.prototype.reflow = function reflow() {
  3425. // should be implemented by the component
  3426. return false;
  3427. };
  3428. /**
  3429. * Hide the component from the DOM
  3430. * @return {Boolean} changed
  3431. */
  3432. Component.prototype.hide = function hide() {
  3433. if (this.frame && this.frame.parentNode) {
  3434. this.frame.parentNode.removeChild(this.frame);
  3435. return true;
  3436. }
  3437. else {
  3438. return false;
  3439. }
  3440. };
  3441. /**
  3442. * Show the component in the DOM (when not already visible).
  3443. * A repaint will be executed when the component is not visible
  3444. * @return {Boolean} changed
  3445. */
  3446. Component.prototype.show = function show() {
  3447. if (!this.frame || !this.frame.parentNode) {
  3448. return this.repaint();
  3449. }
  3450. else {
  3451. return false;
  3452. }
  3453. };
  3454. /**
  3455. * Request a repaint. The controller will schedule a repaint
  3456. */
  3457. Component.prototype.requestRepaint = function requestRepaint() {
  3458. if (this.controller) {
  3459. this.controller.emit('request-repaint');
  3460. }
  3461. else {
  3462. throw new Error('Cannot request a repaint: no controller configured');
  3463. // TODO: just do a repaint when no parent is configured?
  3464. }
  3465. };
  3466. /**
  3467. * Request a reflow. The controller will schedule a reflow
  3468. */
  3469. Component.prototype.requestReflow = function requestReflow() {
  3470. if (this.controller) {
  3471. this.controller.emit('request-reflow');
  3472. }
  3473. else {
  3474. throw new Error('Cannot request a reflow: no controller configured');
  3475. // TODO: just do a reflow when no parent is configured?
  3476. }
  3477. };
  3478. /**
  3479. * A panel can contain components
  3480. * @param {Component} [parent]
  3481. * @param {Component[]} [depends] Components on which this components depends
  3482. * (except for the parent)
  3483. * @param {Object} [options] Available parameters:
  3484. * {String | Number | function} [left]
  3485. * {String | Number | function} [top]
  3486. * {String | Number | function} [width]
  3487. * {String | Number | function} [height]
  3488. * {String | function} [className]
  3489. * @constructor Panel
  3490. * @extends Component
  3491. */
  3492. function Panel(parent, depends, options) {
  3493. this.id = util.randomUUID();
  3494. this.parent = parent;
  3495. this.depends = depends;
  3496. this.options = options || {};
  3497. }
  3498. Panel.prototype = new Component();
  3499. /**
  3500. * Set options. Will extend the current options.
  3501. * @param {Object} [options] Available parameters:
  3502. * {String | function} [className]
  3503. * {String | Number | function} [left]
  3504. * {String | Number | function} [top]
  3505. * {String | Number | function} [width]
  3506. * {String | Number | function} [height]
  3507. */
  3508. Panel.prototype.setOptions = Component.prototype.setOptions;
  3509. /**
  3510. * Get the container element of the panel, which can be used by a child to
  3511. * add its own widgets.
  3512. * @returns {HTMLElement} container
  3513. */
  3514. Panel.prototype.getContainer = function () {
  3515. return this.frame;
  3516. };
  3517. /**
  3518. * Repaint the component
  3519. * @return {Boolean} changed
  3520. */
  3521. Panel.prototype.repaint = function () {
  3522. var changed = 0,
  3523. update = util.updateProperty,
  3524. asSize = util.option.asSize,
  3525. options = this.options,
  3526. frame = this.frame;
  3527. if (!frame) {
  3528. frame = document.createElement('div');
  3529. frame.className = 'vpanel';
  3530. var className = options.className;
  3531. if (className) {
  3532. if (typeof className == 'function') {
  3533. util.addClassName(frame, String(className()));
  3534. }
  3535. else {
  3536. util.addClassName(frame, String(className));
  3537. }
  3538. }
  3539. this.frame = frame;
  3540. changed += 1;
  3541. }
  3542. if (!frame.parentNode) {
  3543. if (!this.parent) {
  3544. throw new Error('Cannot repaint panel: no parent attached');
  3545. }
  3546. var parentContainer = this.parent.getContainer();
  3547. if (!parentContainer) {
  3548. throw new Error('Cannot repaint panel: parent has no container element');
  3549. }
  3550. parentContainer.appendChild(frame);
  3551. changed += 1;
  3552. }
  3553. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  3554. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3555. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3556. changed += update(frame.style, 'height', asSize(options.height, '100%'));
  3557. return (changed > 0);
  3558. };
  3559. /**
  3560. * Reflow the component
  3561. * @return {Boolean} resized
  3562. */
  3563. Panel.prototype.reflow = function () {
  3564. var changed = 0,
  3565. update = util.updateProperty,
  3566. frame = this.frame;
  3567. if (frame) {
  3568. changed += update(this, 'top', frame.offsetTop);
  3569. changed += update(this, 'left', frame.offsetLeft);
  3570. changed += update(this, 'width', frame.offsetWidth);
  3571. changed += update(this, 'height', frame.offsetHeight);
  3572. }
  3573. else {
  3574. changed += 1;
  3575. }
  3576. return (changed > 0);
  3577. };
  3578. /**
  3579. * A root panel can hold components. The root panel must be initialized with
  3580. * a DOM element as container.
  3581. * @param {HTMLElement} container
  3582. * @param {Object} [options] Available parameters: see RootPanel.setOptions.
  3583. * @constructor RootPanel
  3584. * @extends Panel
  3585. */
  3586. function RootPanel(container, options) {
  3587. this.id = util.randomUUID();
  3588. this.container = container;
  3589. // create functions to be used as DOM event listeners
  3590. var me = this;
  3591. this.hammer = null;
  3592. // create listeners for all interesting events, these events will be emitted
  3593. // via the controller
  3594. var events = [
  3595. 'touch', 'pinch', 'tap', 'doubletap', 'hold',
  3596. 'dragstart', 'drag', 'dragend',
  3597. 'mousewheel', 'DOMMouseScroll' // DOMMouseScroll is for Firefox
  3598. ];
  3599. this.listeners = {};
  3600. events.forEach(function (event) {
  3601. me.listeners[event] = function () {
  3602. var args = [event].concat(Array.prototype.slice.call(arguments, 0));
  3603. me.controller.emit.apply(me.controller, args);
  3604. };
  3605. });
  3606. this.options = options || {};
  3607. this.defaultOptions = {
  3608. autoResize: true
  3609. };
  3610. }
  3611. RootPanel.prototype = new Panel();
  3612. /**
  3613. * Set options. Will extend the current options.
  3614. * @param {Object} [options] Available parameters:
  3615. * {String | function} [className]
  3616. * {String | Number | function} [left]
  3617. * {String | Number | function} [top]
  3618. * {String | Number | function} [width]
  3619. * {String | Number | function} [height]
  3620. * {Boolean | function} [autoResize]
  3621. */
  3622. RootPanel.prototype.setOptions = Component.prototype.setOptions;
  3623. /**
  3624. * Repaint the component
  3625. * @return {Boolean} changed
  3626. */
  3627. RootPanel.prototype.repaint = function () {
  3628. var changed = 0,
  3629. update = util.updateProperty,
  3630. asSize = util.option.asSize,
  3631. options = this.options,
  3632. frame = this.frame;
  3633. if (!frame) {
  3634. frame = document.createElement('div');
  3635. this.frame = frame;
  3636. this._registerListeners();
  3637. changed += 1;
  3638. }
  3639. if (!frame.parentNode) {
  3640. if (!this.container) {
  3641. throw new Error('Cannot repaint root panel: no container attached');
  3642. }
  3643. this.container.appendChild(frame);
  3644. changed += 1;
  3645. }
  3646. frame.className = 'vis timeline rootpanel ' + options.orientation +
  3647. (options.editable ? ' editable' : '');
  3648. var className = options.className;
  3649. if (className) {
  3650. util.addClassName(frame, util.option.asString(className));
  3651. }
  3652. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  3653. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3654. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3655. changed += update(frame.style, 'height', asSize(options.height, '100%'));
  3656. this._updateWatch();
  3657. return (changed > 0);
  3658. };
  3659. /**
  3660. * Reflow the component
  3661. * @return {Boolean} resized
  3662. */
  3663. RootPanel.prototype.reflow = function () {
  3664. var changed = 0,
  3665. update = util.updateProperty,
  3666. frame = this.frame;
  3667. if (frame) {
  3668. changed += update(this, 'top', frame.offsetTop);
  3669. changed += update(this, 'left', frame.offsetLeft);
  3670. changed += update(this, 'width', frame.offsetWidth);
  3671. changed += update(this, 'height', frame.offsetHeight);
  3672. }
  3673. else {
  3674. changed += 1;
  3675. }
  3676. return (changed > 0);
  3677. };
  3678. /**
  3679. * Update watching for resize, depending on the current option
  3680. * @private
  3681. */
  3682. RootPanel.prototype._updateWatch = function () {
  3683. var autoResize = this.getOption('autoResize');
  3684. if (autoResize) {
  3685. this._watch();
  3686. }
  3687. else {
  3688. this._unwatch();
  3689. }
  3690. };
  3691. /**
  3692. * Watch for changes in the size of the frame. On resize, the Panel will
  3693. * automatically redraw itself.
  3694. * @private
  3695. */
  3696. RootPanel.prototype._watch = function () {
  3697. var me = this;
  3698. this._unwatch();
  3699. var checkSize = function () {
  3700. var autoResize = me.getOption('autoResize');
  3701. if (!autoResize) {
  3702. // stop watching when the option autoResize is changed to false
  3703. me._unwatch();
  3704. return;
  3705. }
  3706. if (me.frame) {
  3707. // check whether the frame is resized
  3708. if ((me.frame.clientWidth != me.width) ||
  3709. (me.frame.clientHeight != me.height)) {
  3710. me.requestReflow();
  3711. }
  3712. }
  3713. };
  3714. // TODO: automatically cleanup the event listener when the frame is deleted
  3715. util.addEventListener(window, 'resize', checkSize);
  3716. this.watchTimer = setInterval(checkSize, 1000);
  3717. };
  3718. /**
  3719. * Stop watching for a resize of the frame.
  3720. * @private
  3721. */
  3722. RootPanel.prototype._unwatch = function () {
  3723. if (this.watchTimer) {
  3724. clearInterval(this.watchTimer);
  3725. this.watchTimer = undefined;
  3726. }
  3727. // TODO: remove event listener on window.resize
  3728. };
  3729. /**
  3730. * Set controller for this component, or remove current controller by passing
  3731. * null as parameter value.
  3732. * @param {Controller | null} controller
  3733. */
  3734. RootPanel.prototype.setController = function setController (controller) {
  3735. this.controller = controller || null;
  3736. if (this.controller) {
  3737. this._registerListeners();
  3738. }
  3739. else {
  3740. this._unregisterListeners();
  3741. }
  3742. };
  3743. /**
  3744. * Register event emitters emitted by the rootpanel
  3745. * @private
  3746. */
  3747. RootPanel.prototype._registerListeners = function () {
  3748. if (this.frame && this.controller && !this.hammer) {
  3749. this.hammer = Hammer(this.frame, {
  3750. prevent_default: true
  3751. });
  3752. for (var event in this.listeners) {
  3753. if (this.listeners.hasOwnProperty(event)) {
  3754. this.hammer.on(event, this.listeners[event]);
  3755. }
  3756. }
  3757. }
  3758. };
  3759. /**
  3760. * Unregister event emitters from the rootpanel
  3761. * @private
  3762. */
  3763. RootPanel.prototype._unregisterListeners = function () {
  3764. if (this.hammer) {
  3765. for (var event in this.listeners) {
  3766. if (this.listeners.hasOwnProperty(event)) {
  3767. this.hammer.off(event, this.listeners[event]);
  3768. }
  3769. }
  3770. this.hammer = null;
  3771. }
  3772. };
  3773. /**
  3774. * A horizontal time axis
  3775. * @param {Component} parent
  3776. * @param {Component[]} [depends] Components on which this components depends
  3777. * (except for the parent)
  3778. * @param {Object} [options] See TimeAxis.setOptions for the available
  3779. * options.
  3780. * @constructor TimeAxis
  3781. * @extends Component
  3782. */
  3783. function TimeAxis (parent, depends, options) {
  3784. this.id = util.randomUUID();
  3785. this.parent = parent;
  3786. this.depends = depends;
  3787. this.dom = {
  3788. majorLines: [],
  3789. majorTexts: [],
  3790. minorLines: [],
  3791. minorTexts: [],
  3792. redundant: {
  3793. majorLines: [],
  3794. majorTexts: [],
  3795. minorLines: [],
  3796. minorTexts: []
  3797. }
  3798. };
  3799. this.props = {
  3800. range: {
  3801. start: 0,
  3802. end: 0,
  3803. minimumStep: 0
  3804. },
  3805. lineTop: 0
  3806. };
  3807. this.options = options || {};
  3808. this.defaultOptions = {
  3809. orientation: 'bottom', // supported: 'top', 'bottom'
  3810. // TODO: implement timeaxis orientations 'left' and 'right'
  3811. showMinorLabels: true,
  3812. showMajorLabels: true
  3813. };
  3814. this.conversion = null;
  3815. this.range = null;
  3816. }
  3817. TimeAxis.prototype = new Component();
  3818. // TODO: comment options
  3819. TimeAxis.prototype.setOptions = Component.prototype.setOptions;
  3820. /**
  3821. * Set a range (start and end)
  3822. * @param {Range | Object} range A Range or an object containing start and end.
  3823. */
  3824. TimeAxis.prototype.setRange = function (range) {
  3825. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  3826. throw new TypeError('Range must be an instance of Range, ' +
  3827. 'or an object containing start and end.');
  3828. }
  3829. this.range = range;
  3830. };
  3831. /**
  3832. * Convert a position on screen (pixels) to a datetime
  3833. * @param {int} x Position on the screen in pixels
  3834. * @return {Date} time The datetime the corresponds with given position x
  3835. */
  3836. TimeAxis.prototype.toTime = function(x) {
  3837. var conversion = this.conversion;
  3838. return new Date(x / conversion.scale + conversion.offset);
  3839. };
  3840. /**
  3841. * Convert a datetime (Date object) into a position on the screen
  3842. * @param {Date} time A date
  3843. * @return {int} x The position on the screen in pixels which corresponds
  3844. * with the given date.
  3845. * @private
  3846. */
  3847. TimeAxis.prototype.toScreen = function(time) {
  3848. var conversion = this.conversion;
  3849. return (time.valueOf() - conversion.offset) * conversion.scale;
  3850. };
  3851. /**
  3852. * Repaint the component
  3853. * @return {Boolean} changed
  3854. */
  3855. TimeAxis.prototype.repaint = function () {
  3856. var changed = 0,
  3857. update = util.updateProperty,
  3858. asSize = util.option.asSize,
  3859. options = this.options,
  3860. orientation = this.getOption('orientation'),
  3861. props = this.props,
  3862. step = this.step;
  3863. var frame = this.frame;
  3864. if (!frame) {
  3865. frame = document.createElement('div');
  3866. this.frame = frame;
  3867. changed += 1;
  3868. }
  3869. frame.className = 'axis';
  3870. // TODO: custom className?
  3871. if (!frame.parentNode) {
  3872. if (!this.parent) {
  3873. throw new Error('Cannot repaint time axis: no parent attached');
  3874. }
  3875. var parentContainer = this.parent.getContainer();
  3876. if (!parentContainer) {
  3877. throw new Error('Cannot repaint time axis: parent has no container element');
  3878. }
  3879. parentContainer.appendChild(frame);
  3880. changed += 1;
  3881. }
  3882. var parent = frame.parentNode;
  3883. if (parent) {
  3884. var beforeChild = frame.nextSibling;
  3885. parent.removeChild(frame); // take frame offline while updating (is almost twice as fast)
  3886. var defaultTop = (orientation == 'bottom' && this.props.parentHeight && this.height) ?
  3887. (this.props.parentHeight - this.height) + 'px' :
  3888. '0px';
  3889. changed += update(frame.style, 'top', asSize(options.top, defaultTop));
  3890. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3891. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3892. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  3893. // get characters width and height
  3894. this._repaintMeasureChars();
  3895. if (this.step) {
  3896. this._repaintStart();
  3897. step.first();
  3898. var xFirstMajorLabel = undefined;
  3899. var max = 0;
  3900. while (step.hasNext() && max < 1000) {
  3901. max++;
  3902. var cur = step.getCurrent(),
  3903. x = this.toScreen(cur),
  3904. isMajor = step.isMajor();
  3905. // TODO: lines must have a width, such that we can create css backgrounds
  3906. if (this.getOption('showMinorLabels')) {
  3907. this._repaintMinorText(x, step.getLabelMinor());
  3908. }
  3909. if (isMajor && this.getOption('showMajorLabels')) {
  3910. if (x > 0) {
  3911. if (xFirstMajorLabel == undefined) {
  3912. xFirstMajorLabel = x;
  3913. }
  3914. this._repaintMajorText(x, step.getLabelMajor());
  3915. }
  3916. this._repaintMajorLine(x);
  3917. }
  3918. else {
  3919. this._repaintMinorLine(x);
  3920. }
  3921. step.next();
  3922. }
  3923. // create a major label on the left when needed
  3924. if (this.getOption('showMajorLabels')) {
  3925. var leftTime = this.toTime(0),
  3926. leftText = step.getLabelMajor(leftTime),
  3927. widthText = leftText.length * (props.majorCharWidth || 10) + 10; // upper bound estimation
  3928. if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) {
  3929. this._repaintMajorText(0, leftText);
  3930. }
  3931. }
  3932. this._repaintEnd();
  3933. }
  3934. this._repaintLine();
  3935. // put frame online again
  3936. if (beforeChild) {
  3937. parent.insertBefore(frame, beforeChild);
  3938. }
  3939. else {
  3940. parent.appendChild(frame)
  3941. }
  3942. }
  3943. return (changed > 0);
  3944. };
  3945. /**
  3946. * Start a repaint. Move all DOM elements to a redundant list, where they
  3947. * can be picked for re-use, or can be cleaned up in the end
  3948. * @private
  3949. */
  3950. TimeAxis.prototype._repaintStart = function () {
  3951. var dom = this.dom,
  3952. redundant = dom.redundant;
  3953. redundant.majorLines = dom.majorLines;
  3954. redundant.majorTexts = dom.majorTexts;
  3955. redundant.minorLines = dom.minorLines;
  3956. redundant.minorTexts = dom.minorTexts;
  3957. dom.majorLines = [];
  3958. dom.majorTexts = [];
  3959. dom.minorLines = [];
  3960. dom.minorTexts = [];
  3961. };
  3962. /**
  3963. * End a repaint. Cleanup leftover DOM elements in the redundant list
  3964. * @private
  3965. */
  3966. TimeAxis.prototype._repaintEnd = function () {
  3967. util.forEach(this.dom.redundant, function (arr) {
  3968. while (arr.length) {
  3969. var elem = arr.pop();
  3970. if (elem && elem.parentNode) {
  3971. elem.parentNode.removeChild(elem);
  3972. }
  3973. }
  3974. });
  3975. };
  3976. /**
  3977. * Create a minor label for the axis at position x
  3978. * @param {Number} x
  3979. * @param {String} text
  3980. * @private
  3981. */
  3982. TimeAxis.prototype._repaintMinorText = function (x, text) {
  3983. // reuse redundant label
  3984. var label = this.dom.redundant.minorTexts.shift();
  3985. if (!label) {
  3986. // create new label
  3987. var content = document.createTextNode('');
  3988. label = document.createElement('div');
  3989. label.appendChild(content);
  3990. label.className = 'text minor';
  3991. this.frame.appendChild(label);
  3992. }
  3993. this.dom.minorTexts.push(label);
  3994. label.childNodes[0].nodeValue = text;
  3995. label.style.left = x + 'px';
  3996. label.style.top = this.props.minorLabelTop + 'px';
  3997. //label.title = title; // TODO: this is a heavy operation
  3998. };
  3999. /**
  4000. * Create a Major label for the axis at position x
  4001. * @param {Number} x
  4002. * @param {String} text
  4003. * @private
  4004. */
  4005. TimeAxis.prototype._repaintMajorText = function (x, text) {
  4006. // reuse redundant label
  4007. var label = this.dom.redundant.majorTexts.shift();
  4008. if (!label) {
  4009. // create label
  4010. var content = document.createTextNode(text);
  4011. label = document.createElement('div');
  4012. label.className = 'text major';
  4013. label.appendChild(content);
  4014. this.frame.appendChild(label);
  4015. }
  4016. this.dom.majorTexts.push(label);
  4017. label.childNodes[0].nodeValue = text;
  4018. label.style.top = this.props.majorLabelTop + 'px';
  4019. label.style.left = x + 'px';
  4020. //label.title = title; // TODO: this is a heavy operation
  4021. };
  4022. /**
  4023. * Create a minor line for the axis at position x
  4024. * @param {Number} x
  4025. * @private
  4026. */
  4027. TimeAxis.prototype._repaintMinorLine = function (x) {
  4028. // reuse redundant line
  4029. var line = this.dom.redundant.minorLines.shift();
  4030. if (!line) {
  4031. // create vertical line
  4032. line = document.createElement('div');
  4033. line.className = 'grid vertical minor';
  4034. this.frame.appendChild(line);
  4035. }
  4036. this.dom.minorLines.push(line);
  4037. var props = this.props;
  4038. line.style.top = props.minorLineTop + 'px';
  4039. line.style.height = props.minorLineHeight + 'px';
  4040. line.style.left = (x - props.minorLineWidth / 2) + 'px';
  4041. };
  4042. /**
  4043. * Create a Major line for the axis at position x
  4044. * @param {Number} x
  4045. * @private
  4046. */
  4047. TimeAxis.prototype._repaintMajorLine = function (x) {
  4048. // reuse redundant line
  4049. var line = this.dom.redundant.majorLines.shift();
  4050. if (!line) {
  4051. // create vertical line
  4052. line = document.createElement('DIV');
  4053. line.className = 'grid vertical major';
  4054. this.frame.appendChild(line);
  4055. }
  4056. this.dom.majorLines.push(line);
  4057. var props = this.props;
  4058. line.style.top = props.majorLineTop + 'px';
  4059. line.style.left = (x - props.majorLineWidth / 2) + 'px';
  4060. line.style.height = props.majorLineHeight + 'px';
  4061. };
  4062. /**
  4063. * Repaint the horizontal line for the axis
  4064. * @private
  4065. */
  4066. TimeAxis.prototype._repaintLine = function() {
  4067. var line = this.dom.line,
  4068. frame = this.frame,
  4069. options = this.options;
  4070. // line before all axis elements
  4071. if (this.getOption('showMinorLabels') || this.getOption('showMajorLabels')) {
  4072. if (line) {
  4073. // put this line at the end of all childs
  4074. frame.removeChild(line);
  4075. frame.appendChild(line);
  4076. }
  4077. else {
  4078. // create the axis line
  4079. line = document.createElement('div');
  4080. line.className = 'grid horizontal major';
  4081. frame.appendChild(line);
  4082. this.dom.line = line;
  4083. }
  4084. line.style.top = this.props.lineTop + 'px';
  4085. }
  4086. else {
  4087. if (line && line.parentElement) {
  4088. frame.removeChild(line.line);
  4089. delete this.dom.line;
  4090. }
  4091. }
  4092. };
  4093. /**
  4094. * Create characters used to determine the size of text on the axis
  4095. * @private
  4096. */
  4097. TimeAxis.prototype._repaintMeasureChars = function () {
  4098. // calculate the width and height of a single character
  4099. // this is used to calculate the step size, and also the positioning of the
  4100. // axis
  4101. var dom = this.dom,
  4102. text;
  4103. if (!dom.measureCharMinor) {
  4104. text = document.createTextNode('0');
  4105. var measureCharMinor = document.createElement('DIV');
  4106. measureCharMinor.className = 'text minor measure';
  4107. measureCharMinor.appendChild(text);
  4108. this.frame.appendChild(measureCharMinor);
  4109. dom.measureCharMinor = measureCharMinor;
  4110. }
  4111. if (!dom.measureCharMajor) {
  4112. text = document.createTextNode('0');
  4113. var measureCharMajor = document.createElement('DIV');
  4114. measureCharMajor.className = 'text major measure';
  4115. measureCharMajor.appendChild(text);
  4116. this.frame.appendChild(measureCharMajor);
  4117. dom.measureCharMajor = measureCharMajor;
  4118. }
  4119. };
  4120. /**
  4121. * Reflow the component
  4122. * @return {Boolean} resized
  4123. */
  4124. TimeAxis.prototype.reflow = function () {
  4125. var changed = 0,
  4126. update = util.updateProperty,
  4127. frame = this.frame,
  4128. range = this.range;
  4129. if (!range) {
  4130. throw new Error('Cannot repaint time axis: no range configured');
  4131. }
  4132. if (frame) {
  4133. changed += update(this, 'top', frame.offsetTop);
  4134. changed += update(this, 'left', frame.offsetLeft);
  4135. // calculate size of a character
  4136. var props = this.props,
  4137. showMinorLabels = this.getOption('showMinorLabels'),
  4138. showMajorLabels = this.getOption('showMajorLabels'),
  4139. measureCharMinor = this.dom.measureCharMinor,
  4140. measureCharMajor = this.dom.measureCharMajor;
  4141. if (measureCharMinor) {
  4142. props.minorCharHeight = measureCharMinor.clientHeight;
  4143. props.minorCharWidth = measureCharMinor.clientWidth;
  4144. }
  4145. if (measureCharMajor) {
  4146. props.majorCharHeight = measureCharMajor.clientHeight;
  4147. props.majorCharWidth = measureCharMajor.clientWidth;
  4148. }
  4149. var parentHeight = frame.parentNode ? frame.parentNode.offsetHeight : 0;
  4150. if (parentHeight != props.parentHeight) {
  4151. props.parentHeight = parentHeight;
  4152. changed += 1;
  4153. }
  4154. switch (this.getOption('orientation')) {
  4155. case 'bottom':
  4156. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  4157. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  4158. props.minorLabelTop = 0;
  4159. props.majorLabelTop = props.minorLabelTop + props.minorLabelHeight;
  4160. props.minorLineTop = -this.top;
  4161. props.minorLineHeight = Math.max(this.top + props.majorLabelHeight, 0);
  4162. props.minorLineWidth = 1; // TODO: really calculate width
  4163. props.majorLineTop = -this.top;
  4164. props.majorLineHeight = Math.max(this.top + props.minorLabelHeight + props.majorLabelHeight, 0);
  4165. props.majorLineWidth = 1; // TODO: really calculate width
  4166. props.lineTop = 0;
  4167. break;
  4168. case 'top':
  4169. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  4170. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  4171. props.majorLabelTop = 0;
  4172. props.minorLabelTop = props.majorLabelTop + props.majorLabelHeight;
  4173. props.minorLineTop = props.minorLabelTop;
  4174. props.minorLineHeight = Math.max(parentHeight - props.majorLabelHeight - this.top);
  4175. props.minorLineWidth = 1; // TODO: really calculate width
  4176. props.majorLineTop = 0;
  4177. props.majorLineHeight = Math.max(parentHeight - this.top);
  4178. props.majorLineWidth = 1; // TODO: really calculate width
  4179. props.lineTop = props.majorLabelHeight + props.minorLabelHeight;
  4180. break;
  4181. default:
  4182. throw new Error('Unkown orientation "' + this.getOption('orientation') + '"');
  4183. }
  4184. var height = props.minorLabelHeight + props.majorLabelHeight;
  4185. changed += update(this, 'width', frame.offsetWidth);
  4186. changed += update(this, 'height', height);
  4187. // calculate range and step
  4188. this._updateConversion();
  4189. var start = util.convert(range.start, 'Number'),
  4190. end = util.convert(range.end, 'Number'),
  4191. minimumStep = this.toTime((props.minorCharWidth || 10) * 5).valueOf()
  4192. -this.toTime(0).valueOf();
  4193. this.step = new TimeStep(new Date(start), new Date(end), minimumStep);
  4194. changed += update(props.range, 'start', start);
  4195. changed += update(props.range, 'end', end);
  4196. changed += update(props.range, 'minimumStep', minimumStep.valueOf());
  4197. }
  4198. return (changed > 0);
  4199. };
  4200. /**
  4201. * Calculate the scale and offset to convert a position on screen to the
  4202. * corresponding date and vice versa.
  4203. * After the method _updateConversion is executed once, the methods toTime
  4204. * and toScreen can be used.
  4205. * @private
  4206. */
  4207. TimeAxis.prototype._updateConversion = function() {
  4208. var range = this.range;
  4209. if (!range) {
  4210. throw new Error('No range configured');
  4211. }
  4212. if (range.conversion) {
  4213. this.conversion = range.conversion(this.width);
  4214. }
  4215. else {
  4216. this.conversion = Range.conversion(range.start, range.end, this.width);
  4217. }
  4218. };
  4219. /**
  4220. * Snap a date to a rounded value.
  4221. * The snap intervals are dependent on the current scale and step.
  4222. * @param {Date} date the date to be snapped.
  4223. * @return {Date} snappedDate
  4224. */
  4225. TimeAxis.prototype.snap = function snap (date) {
  4226. return this.step.snap(date);
  4227. };
  4228. /**
  4229. * A current time bar
  4230. * @param {Component} parent
  4231. * @param {Component[]} [depends] Components on which this components depends
  4232. * (except for the parent)
  4233. * @param {Object} [options] Available parameters:
  4234. * {Boolean} [showCurrentTime]
  4235. * @constructor CurrentTime
  4236. * @extends Component
  4237. */
  4238. function CurrentTime (parent, depends, options) {
  4239. this.id = util.randomUUID();
  4240. this.parent = parent;
  4241. this.depends = depends;
  4242. this.options = options || {};
  4243. this.defaultOptions = {
  4244. showCurrentTime: false
  4245. };
  4246. }
  4247. CurrentTime.prototype = new Component();
  4248. CurrentTime.prototype.setOptions = Component.prototype.setOptions;
  4249. /**
  4250. * Get the container element of the bar, which can be used by a child to
  4251. * add its own widgets.
  4252. * @returns {HTMLElement} container
  4253. */
  4254. CurrentTime.prototype.getContainer = function () {
  4255. return this.frame;
  4256. };
  4257. /**
  4258. * Repaint the component
  4259. * @return {Boolean} changed
  4260. */
  4261. CurrentTime.prototype.repaint = function () {
  4262. var bar = this.frame,
  4263. parent = this.parent,
  4264. parentContainer = parent.parent.getContainer();
  4265. if (!parent) {
  4266. throw new Error('Cannot repaint bar: no parent attached');
  4267. }
  4268. if (!parentContainer) {
  4269. throw new Error('Cannot repaint bar: parent has no container element');
  4270. }
  4271. if (!this.getOption('showCurrentTime')) {
  4272. if (bar) {
  4273. parentContainer.removeChild(bar);
  4274. delete this.frame;
  4275. }
  4276. return false;
  4277. }
  4278. if (!bar) {
  4279. bar = document.createElement('div');
  4280. bar.className = 'currenttime';
  4281. bar.style.position = 'absolute';
  4282. bar.style.top = '0px';
  4283. bar.style.height = '100%';
  4284. parentContainer.appendChild(bar);
  4285. this.frame = bar;
  4286. }
  4287. if (!parent.conversion) {
  4288. parent._updateConversion();
  4289. }
  4290. var now = new Date();
  4291. var x = parent.toScreen(now);
  4292. bar.style.left = x + 'px';
  4293. bar.title = 'Current time: ' + now;
  4294. // start a timer to adjust for the new time
  4295. if (this.currentTimeTimer !== undefined) {
  4296. clearTimeout(this.currentTimeTimer);
  4297. delete this.currentTimeTimer;
  4298. }
  4299. var timeline = this;
  4300. var interval = 1 / parent.conversion.scale / 2;
  4301. if (interval < 30) {
  4302. interval = 30;
  4303. }
  4304. this.currentTimeTimer = setTimeout(function() {
  4305. timeline.repaint();
  4306. }, interval);
  4307. return false;
  4308. };
  4309. /**
  4310. * A custom time bar
  4311. * @param {Component} parent
  4312. * @param {Component[]} [depends] Components on which this components depends
  4313. * (except for the parent)
  4314. * @param {Object} [options] Available parameters:
  4315. * {Boolean} [showCustomTime]
  4316. * @constructor CustomTime
  4317. * @extends Component
  4318. */
  4319. function CustomTime (parent, depends, options) {
  4320. this.id = util.randomUUID();
  4321. this.parent = parent;
  4322. this.depends = depends;
  4323. this.options = options || {};
  4324. this.defaultOptions = {
  4325. showCustomTime: false
  4326. };
  4327. this.customTime = new Date();
  4328. this.eventParams = {}; // stores state parameters while dragging the bar
  4329. }
  4330. CustomTime.prototype = new Component();
  4331. Emitter(CustomTime.prototype);
  4332. CustomTime.prototype.setOptions = Component.prototype.setOptions;
  4333. /**
  4334. * Get the container element of the bar, which can be used by a child to
  4335. * add its own widgets.
  4336. * @returns {HTMLElement} container
  4337. */
  4338. CustomTime.prototype.getContainer = function () {
  4339. return this.frame;
  4340. };
  4341. /**
  4342. * Repaint the component
  4343. * @return {Boolean} changed
  4344. */
  4345. CustomTime.prototype.repaint = function () {
  4346. var bar = this.frame,
  4347. parent = this.parent;
  4348. if (!parent) {
  4349. throw new Error('Cannot repaint bar: no parent attached');
  4350. }
  4351. var parentContainer = parent.parent.getContainer();
  4352. if (!parentContainer) {
  4353. throw new Error('Cannot repaint bar: parent has no container element');
  4354. }
  4355. if (!this.getOption('showCustomTime')) {
  4356. if (bar) {
  4357. parentContainer.removeChild(bar);
  4358. delete this.frame;
  4359. }
  4360. return false;
  4361. }
  4362. if (!bar) {
  4363. bar = document.createElement('div');
  4364. bar.className = 'customtime';
  4365. bar.style.position = 'absolute';
  4366. bar.style.top = '0px';
  4367. bar.style.height = '100%';
  4368. parentContainer.appendChild(bar);
  4369. var drag = document.createElement('div');
  4370. drag.style.position = 'relative';
  4371. drag.style.top = '0px';
  4372. drag.style.left = '-10px';
  4373. drag.style.height = '100%';
  4374. drag.style.width = '20px';
  4375. bar.appendChild(drag);
  4376. this.frame = bar;
  4377. // attach event listeners
  4378. this.hammer = Hammer(bar, {
  4379. prevent_default: true
  4380. });
  4381. this.hammer.on('dragstart', this._onDragStart.bind(this));
  4382. this.hammer.on('drag', this._onDrag.bind(this));
  4383. this.hammer.on('dragend', this._onDragEnd.bind(this));
  4384. }
  4385. if (!parent.conversion) {
  4386. parent._updateConversion();
  4387. }
  4388. var x = parent.toScreen(this.customTime);
  4389. bar.style.left = x + 'px';
  4390. bar.title = 'Time: ' + this.customTime;
  4391. return false;
  4392. };
  4393. /**
  4394. * Set custom time.
  4395. * @param {Date} time
  4396. */
  4397. CustomTime.prototype.setCustomTime = function(time) {
  4398. this.customTime = new Date(time.valueOf());
  4399. this.repaint();
  4400. };
  4401. /**
  4402. * Retrieve the current custom time.
  4403. * @return {Date} customTime
  4404. */
  4405. CustomTime.prototype.getCustomTime = function() {
  4406. return new Date(this.customTime.valueOf());
  4407. };
  4408. /**
  4409. * Start moving horizontally
  4410. * @param {Event} event
  4411. * @private
  4412. */
  4413. CustomTime.prototype._onDragStart = function(event) {
  4414. this.eventParams.customTime = this.customTime;
  4415. event.stopPropagation();
  4416. event.preventDefault();
  4417. };
  4418. /**
  4419. * Perform moving operating.
  4420. * @param {Event} event
  4421. * @private
  4422. */
  4423. CustomTime.prototype._onDrag = function (event) {
  4424. var deltaX = event.gesture.deltaX,
  4425. x = this.parent.toScreen(this.eventParams.customTime) + deltaX,
  4426. time = this.parent.toTime(x);
  4427. this.setCustomTime(time);
  4428. // fire a timechange event
  4429. if (this.controller) {
  4430. this.controller.emit('timechange', {
  4431. time: this.customTime
  4432. })
  4433. }
  4434. event.stopPropagation();
  4435. event.preventDefault();
  4436. };
  4437. /**
  4438. * Stop moving operating.
  4439. * @param {event} event
  4440. * @private
  4441. */
  4442. CustomTime.prototype._onDragEnd = function (event) {
  4443. // fire a timechanged event
  4444. if (this.controller) {
  4445. this.controller.emit('timechanged', {
  4446. time: this.customTime
  4447. })
  4448. }
  4449. event.stopPropagation();
  4450. event.preventDefault();
  4451. };
  4452. /**
  4453. * An ItemSet holds a set of items and ranges which can be displayed in a
  4454. * range. The width is determined by the parent of the ItemSet, and the height
  4455. * is determined by the size of the items.
  4456. * @param {Component} parent
  4457. * @param {Component[]} [depends] Components on which this components depends
  4458. * (except for the parent)
  4459. * @param {Object} [options] See ItemSet.setOptions for the available
  4460. * options.
  4461. * @constructor ItemSet
  4462. * @extends Panel
  4463. */
  4464. // TODO: improve performance by replacing all Array.forEach with a for loop
  4465. function ItemSet(parent, depends, options) {
  4466. this.id = util.randomUUID();
  4467. this.parent = parent;
  4468. this.depends = depends;
  4469. // event listeners
  4470. this.eventListeners = {
  4471. dragstart: this._onDragStart.bind(this),
  4472. drag: this._onDrag.bind(this),
  4473. dragend: this._onDragEnd.bind(this)
  4474. };
  4475. // one options object is shared by this itemset and all its items
  4476. this.options = options || {};
  4477. this.defaultOptions = {
  4478. type: 'box',
  4479. align: 'center',
  4480. orientation: 'bottom',
  4481. margin: {
  4482. axis: 20,
  4483. item: 10
  4484. },
  4485. padding: 5
  4486. };
  4487. this.dom = {};
  4488. var me = this;
  4489. this.itemsData = null; // DataSet
  4490. this.range = null; // Range or Object {start: number, end: number}
  4491. // data change listeners
  4492. this.listeners = {
  4493. 'add': function (event, params, senderId) {
  4494. if (senderId != me.id) {
  4495. me._onAdd(params.items);
  4496. }
  4497. },
  4498. 'update': function (event, params, senderId) {
  4499. if (senderId != me.id) {
  4500. me._onUpdate(params.items);
  4501. }
  4502. },
  4503. 'remove': function (event, params, senderId) {
  4504. if (senderId != me.id) {
  4505. me._onRemove(params.items);
  4506. }
  4507. }
  4508. };
  4509. this.items = {}; // object with an Item for every data item
  4510. this.selection = []; // list with the ids of all selected nodes
  4511. this.queue = {}; // queue with id/actions: 'add', 'update', 'delete'
  4512. this.stack = new Stack(this, Object.create(this.options));
  4513. this.conversion = null;
  4514. this.touchParams = {}; // stores properties while dragging
  4515. // TODO: ItemSet should also attach event listeners for rangechange and rangechanged, like timeaxis
  4516. }
  4517. ItemSet.prototype = new Panel();
  4518. // available item types will be registered here
  4519. ItemSet.types = {
  4520. box: ItemBox,
  4521. range: ItemRange,
  4522. rangeoverflow: ItemRangeOverflow,
  4523. point: ItemPoint
  4524. };
  4525. /**
  4526. * Set options for the ItemSet. Existing options will be extended/overwritten.
  4527. * @param {Object} [options] The following options are available:
  4528. * {String | function} [className]
  4529. * class name for the itemset
  4530. * {String} [type]
  4531. * Default type for the items. Choose from 'box'
  4532. * (default), 'point', or 'range'. The default
  4533. * Style can be overwritten by individual items.
  4534. * {String} align
  4535. * Alignment for the items, only applicable for
  4536. * ItemBox. Choose 'center' (default), 'left', or
  4537. * 'right'.
  4538. * {String} orientation
  4539. * Orientation of the item set. Choose 'top' or
  4540. * 'bottom' (default).
  4541. * {Number} margin.axis
  4542. * Margin between the axis and the items in pixels.
  4543. * Default is 20.
  4544. * {Number} margin.item
  4545. * Margin between items in pixels. Default is 10.
  4546. * {Number} padding
  4547. * Padding of the contents of an item in pixels.
  4548. * Must correspond with the items css. Default is 5.
  4549. * {Function} snap
  4550. * Function to let items snap to nice dates when
  4551. * dragging items.
  4552. */
  4553. ItemSet.prototype.setOptions = Component.prototype.setOptions;
  4554. /**
  4555. * Set controller for this component
  4556. * @param {Controller | null} controller
  4557. */
  4558. ItemSet.prototype.setController = function setController (controller) {
  4559. var event;
  4560. // unregister old event listeners
  4561. if (this.controller) {
  4562. for (event in this.eventListeners) {
  4563. if (this.eventListeners.hasOwnProperty(event)) {
  4564. this.controller.off(event, this.eventListeners[event]);
  4565. }
  4566. }
  4567. }
  4568. this.controller = controller || null;
  4569. // register new event listeners
  4570. if (this.controller) {
  4571. for (event in this.eventListeners) {
  4572. if (this.eventListeners.hasOwnProperty(event)) {
  4573. this.controller.on(event, this.eventListeners[event]);
  4574. }
  4575. }
  4576. }
  4577. };
  4578. // attach event listeners for dragging items to the controller
  4579. (function (me) {
  4580. var _controller = null;
  4581. var _onDragStart = null;
  4582. var _onDrag = null;
  4583. var _onDragEnd = null;
  4584. Object.defineProperty(me, 'controller', {
  4585. get: function () {
  4586. return _controller;
  4587. },
  4588. set: function (controller) {
  4589. }
  4590. });
  4591. }) (this);
  4592. /**
  4593. * Set range (start and end).
  4594. * @param {Range | Object} range A Range or an object containing start and end.
  4595. */
  4596. ItemSet.prototype.setRange = function setRange(range) {
  4597. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  4598. throw new TypeError('Range must be an instance of Range, ' +
  4599. 'or an object containing start and end.');
  4600. }
  4601. this.range = range;
  4602. };
  4603. /**
  4604. * Set selected items by their id. Replaces the current selection
  4605. * Unknown id's are silently ignored.
  4606. * @param {Array} [ids] An array with zero or more id's of the items to be
  4607. * selected. If ids is an empty array, all items will be
  4608. * unselected.
  4609. */
  4610. ItemSet.prototype.setSelection = function setSelection(ids) {
  4611. var i, ii, id, item, selection;
  4612. if (ids) {
  4613. if (!Array.isArray(ids)) {
  4614. throw new TypeError('Array expected');
  4615. }
  4616. // unselect currently selected items
  4617. for (i = 0, ii = this.selection.length; i < ii; i++) {
  4618. id = this.selection[i];
  4619. item = this.items[id];
  4620. if (item) item.unselect();
  4621. }
  4622. // select items
  4623. this.selection = [];
  4624. for (i = 0, ii = ids.length; i < ii; i++) {
  4625. id = ids[i];
  4626. item = this.items[id];
  4627. if (item) {
  4628. this.selection.push(id);
  4629. item.select();
  4630. }
  4631. }
  4632. if (this.controller) {
  4633. this.requestRepaint();
  4634. }
  4635. }
  4636. };
  4637. /**
  4638. * Get the selected items by their id
  4639. * @return {Array} ids The ids of the selected items
  4640. */
  4641. ItemSet.prototype.getSelection = function getSelection() {
  4642. return this.selection.concat([]);
  4643. };
  4644. /**
  4645. * Deselect a selected item
  4646. * @param {String | Number} id
  4647. * @private
  4648. */
  4649. ItemSet.prototype._deselect = function _deselect(id) {
  4650. var selection = this.selection;
  4651. for (var i = 0, ii = selection.length; i < ii; i++) {
  4652. if (selection[i] == id) { // non-strict comparison!
  4653. selection.splice(i, 1);
  4654. break;
  4655. }
  4656. }
  4657. };
  4658. /**
  4659. * Repaint the component
  4660. * @return {Boolean} changed
  4661. */
  4662. ItemSet.prototype.repaint = function repaint() {
  4663. var changed = 0,
  4664. update = util.updateProperty,
  4665. asSize = util.option.asSize,
  4666. options = this.options,
  4667. orientation = this.getOption('orientation'),
  4668. defaultOptions = this.defaultOptions,
  4669. frame = this.frame;
  4670. if (!frame) {
  4671. frame = document.createElement('div');
  4672. frame.className = 'itemset';
  4673. frame['timeline-itemset'] = this;
  4674. var className = options.className;
  4675. if (className) {
  4676. util.addClassName(frame, util.option.asString(className));
  4677. }
  4678. // create background panel
  4679. var background = document.createElement('div');
  4680. background.className = 'background';
  4681. frame.appendChild(background);
  4682. this.dom.background = background;
  4683. // create foreground panel
  4684. var foreground = document.createElement('div');
  4685. foreground.className = 'foreground';
  4686. frame.appendChild(foreground);
  4687. this.dom.foreground = foreground;
  4688. // create axis panel
  4689. var axis = document.createElement('div');
  4690. axis.className = 'itemset-axis';
  4691. //frame.appendChild(axis);
  4692. this.dom.axis = axis;
  4693. this.frame = frame;
  4694. changed += 1;
  4695. }
  4696. if (!this.parent) {
  4697. throw new Error('Cannot repaint itemset: no parent attached');
  4698. }
  4699. var parentContainer = this.parent.getContainer();
  4700. if (!parentContainer) {
  4701. throw new Error('Cannot repaint itemset: parent has no container element');
  4702. }
  4703. if (!frame.parentNode) {
  4704. parentContainer.appendChild(frame);
  4705. changed += 1;
  4706. }
  4707. if (!this.dom.axis.parentNode) {
  4708. parentContainer.appendChild(this.dom.axis);
  4709. changed += 1;
  4710. }
  4711. // reposition frame
  4712. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  4713. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  4714. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  4715. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  4716. // reposition axis
  4717. changed += update(this.dom.axis.style, 'left', asSize(options.left, '0px'));
  4718. changed += update(this.dom.axis.style, 'width', asSize(options.width, '100%'));
  4719. if (orientation == 'bottom') {
  4720. changed += update(this.dom.axis.style, 'top', (this.height + this.top) + 'px');
  4721. }
  4722. else { // orientation == 'top'
  4723. changed += update(this.dom.axis.style, 'top', this.top + 'px');
  4724. }
  4725. this._updateConversion();
  4726. var me = this,
  4727. queue = this.queue,
  4728. itemsData = this.itemsData,
  4729. items = this.items,
  4730. dataOptions = {
  4731. // TODO: cleanup
  4732. // fields: [(itemsData && itemsData.fieldId || 'id'), 'start', 'end', 'content', 'type', 'className']
  4733. };
  4734. // show/hide added/changed/removed items
  4735. for (var id in queue) {
  4736. if (queue.hasOwnProperty(id)) {
  4737. var entry = queue[id],
  4738. item = items[id],
  4739. action = entry.action;
  4740. //noinspection FallthroughInSwitchStatementJS
  4741. switch (action) {
  4742. case 'add':
  4743. case 'update':
  4744. var itemData = itemsData && itemsData.get(id, dataOptions);
  4745. if (itemData) {
  4746. var type = itemData.type ||
  4747. (itemData.start && itemData.end && 'range') ||
  4748. options.type ||
  4749. 'box';
  4750. var constructor = ItemSet.types[type];
  4751. // TODO: how to handle items with invalid data? hide them and give a warning? or throw an error?
  4752. if (item) {
  4753. // update item
  4754. if (!constructor || !(item instanceof constructor)) {
  4755. // item type has changed, hide and delete the item
  4756. changed += item.hide();
  4757. item = null;
  4758. }
  4759. else {
  4760. item.data = itemData; // TODO: create a method item.setData ?
  4761. changed++;
  4762. }
  4763. }
  4764. if (!item) {
  4765. // create item
  4766. if (constructor) {
  4767. item = new constructor(me, itemData, options, defaultOptions);
  4768. item.id = entry.id; // we take entry.id, as id itself is stringified
  4769. changed++;
  4770. }
  4771. else {
  4772. throw new TypeError('Unknown item type "' + type + '"');
  4773. }
  4774. }
  4775. // force a repaint (not only a reposition)
  4776. item.repaint();
  4777. items[id] = item;
  4778. }
  4779. // update queue
  4780. delete queue[id];
  4781. break;
  4782. case 'remove':
  4783. if (item) {
  4784. // remove the item from the set selected items
  4785. if (item.selected) {
  4786. me._deselect(id);
  4787. }
  4788. // remove DOM of the item
  4789. changed += item.hide();
  4790. }
  4791. // update lists
  4792. delete items[id];
  4793. delete queue[id];
  4794. break;
  4795. default:
  4796. console.log('Error: unknown action "' + action + '"');
  4797. }
  4798. }
  4799. }
  4800. // reposition all items. Show items only when in the visible area
  4801. util.forEach(this.items, function (item) {
  4802. if (item.visible) {
  4803. changed += item.show();
  4804. item.reposition();
  4805. }
  4806. else {
  4807. changed += item.hide();
  4808. }
  4809. });
  4810. return (changed > 0);
  4811. };
  4812. /**
  4813. * Get the foreground container element
  4814. * @return {HTMLElement} foreground
  4815. */
  4816. ItemSet.prototype.getForeground = function getForeground() {
  4817. return this.dom.foreground;
  4818. };
  4819. /**
  4820. * Get the background container element
  4821. * @return {HTMLElement} background
  4822. */
  4823. ItemSet.prototype.getBackground = function getBackground() {
  4824. return this.dom.background;
  4825. };
  4826. /**
  4827. * Get the axis container element
  4828. * @return {HTMLElement} axis
  4829. */
  4830. ItemSet.prototype.getAxis = function getAxis() {
  4831. return this.dom.axis;
  4832. };
  4833. /**
  4834. * Reflow the component
  4835. * @return {Boolean} resized
  4836. */
  4837. ItemSet.prototype.reflow = function reflow () {
  4838. var changed = 0,
  4839. options = this.options,
  4840. marginAxis = options.margin && options.margin.axis || this.defaultOptions.margin.axis,
  4841. marginItem = options.margin && options.margin.item || this.defaultOptions.margin.item,
  4842. update = util.updateProperty,
  4843. asNumber = util.option.asNumber,
  4844. asSize = util.option.asSize,
  4845. frame = this.frame;
  4846. if (frame) {
  4847. this._updateConversion();
  4848. util.forEach(this.items, function (item) {
  4849. changed += item.reflow();
  4850. });
  4851. // TODO: stack.update should be triggered via an event, in stack itself
  4852. // TODO: only update the stack when there are changed items
  4853. this.stack.update();
  4854. var maxHeight = asNumber(options.maxHeight);
  4855. var fixedHeight = (asSize(options.height) != null);
  4856. var height;
  4857. if (fixedHeight) {
  4858. height = frame.offsetHeight;
  4859. }
  4860. else {
  4861. // height is not specified, determine the height from the height and positioned items
  4862. var visibleItems = this.stack.ordered; // TODO: not so nice way to get the filtered items
  4863. if (visibleItems.length) {
  4864. var min = visibleItems[0].top;
  4865. var max = visibleItems[0].top + visibleItems[0].height;
  4866. util.forEach(visibleItems, function (item) {
  4867. min = Math.min(min, item.top);
  4868. max = Math.max(max, (item.top + item.height));
  4869. });
  4870. height = (max - min) + marginAxis + marginItem;
  4871. }
  4872. else {
  4873. height = marginAxis + marginItem;
  4874. }
  4875. }
  4876. if (maxHeight != null) {
  4877. height = Math.min(height, maxHeight);
  4878. }
  4879. changed += update(this, 'height', height);
  4880. // calculate height from items
  4881. changed += update(this, 'top', frame.offsetTop);
  4882. changed += update(this, 'left', frame.offsetLeft);
  4883. changed += update(this, 'width', frame.offsetWidth);
  4884. }
  4885. else {
  4886. changed += 1;
  4887. }
  4888. return (changed > 0);
  4889. };
  4890. /**
  4891. * Hide this component from the DOM
  4892. * @return {Boolean} changed
  4893. */
  4894. ItemSet.prototype.hide = function hide() {
  4895. var changed = false;
  4896. // remove the DOM
  4897. if (this.frame && this.frame.parentNode) {
  4898. this.frame.parentNode.removeChild(this.frame);
  4899. changed = true;
  4900. }
  4901. if (this.dom.axis && this.dom.axis.parentNode) {
  4902. this.dom.axis.parentNode.removeChild(this.dom.axis);
  4903. changed = true;
  4904. }
  4905. return changed;
  4906. };
  4907. /**
  4908. * Set items
  4909. * @param {vis.DataSet | null} items
  4910. */
  4911. ItemSet.prototype.setItems = function setItems(items) {
  4912. var me = this,
  4913. ids,
  4914. oldItemsData = this.itemsData;
  4915. // replace the dataset
  4916. if (!items) {
  4917. this.itemsData = null;
  4918. }
  4919. else if (items instanceof DataSet || items instanceof DataView) {
  4920. this.itemsData = items;
  4921. }
  4922. else {
  4923. throw new TypeError('Data must be an instance of DataSet');
  4924. }
  4925. if (oldItemsData) {
  4926. // unsubscribe from old dataset
  4927. util.forEach(this.listeners, function (callback, event) {
  4928. oldItemsData.unsubscribe(event, callback);
  4929. });
  4930. // remove all drawn items
  4931. ids = oldItemsData.getIds();
  4932. this._onRemove(ids);
  4933. }
  4934. if (this.itemsData) {
  4935. // subscribe to new dataset
  4936. var id = this.id;
  4937. util.forEach(this.listeners, function (callback, event) {
  4938. me.itemsData.on(event, callback, id);
  4939. });
  4940. // draw all new items
  4941. ids = this.itemsData.getIds();
  4942. this._onAdd(ids);
  4943. }
  4944. };
  4945. /**
  4946. * Get the current items items
  4947. * @returns {vis.DataSet | null}
  4948. */
  4949. ItemSet.prototype.getItems = function getItems() {
  4950. return this.itemsData;
  4951. };
  4952. /**
  4953. * Remove an item by its id
  4954. * @param {String | Number} id
  4955. */
  4956. ItemSet.prototype.removeItem = function removeItem (id) {
  4957. var item = this.itemsData.get(id),
  4958. dataset = this._myDataSet();
  4959. if (item) {
  4960. // confirm deletion
  4961. this.options.onRemove(item, function (item) {
  4962. if (item) {
  4963. dataset.remove(item);
  4964. }
  4965. });
  4966. }
  4967. };
  4968. /**
  4969. * Handle updated items
  4970. * @param {Number[]} ids
  4971. * @private
  4972. */
  4973. ItemSet.prototype._onUpdate = function _onUpdate(ids) {
  4974. this._toQueue('update', ids);
  4975. };
  4976. /**
  4977. * Handle changed items
  4978. * @param {Number[]} ids
  4979. * @private
  4980. */
  4981. ItemSet.prototype._onAdd = function _onAdd(ids) {
  4982. this._toQueue('add', ids);
  4983. };
  4984. /**
  4985. * Handle removed items
  4986. * @param {Number[]} ids
  4987. * @private
  4988. */
  4989. ItemSet.prototype._onRemove = function _onRemove(ids) {
  4990. this._toQueue('remove', ids);
  4991. };
  4992. /**
  4993. * Put items in the queue to be added/updated/remove
  4994. * @param {String} action can be 'add', 'update', 'remove'
  4995. * @param {Number[]} ids
  4996. */
  4997. ItemSet.prototype._toQueue = function _toQueue(action, ids) {
  4998. var queue = this.queue;
  4999. ids.forEach(function (id) {
  5000. queue[id] = {
  5001. id: id,
  5002. action: action
  5003. };
  5004. });
  5005. if (this.controller) {
  5006. //this.requestReflow();
  5007. this.requestRepaint();
  5008. }
  5009. };
  5010. /**
  5011. * Calculate the scale and offset to convert a position on screen to the
  5012. * corresponding date and vice versa.
  5013. * After the method _updateConversion is executed once, the methods toTime
  5014. * and toScreen can be used.
  5015. * @private
  5016. */
  5017. ItemSet.prototype._updateConversion = function _updateConversion() {
  5018. var range = this.range;
  5019. if (!range) {
  5020. throw new Error('No range configured');
  5021. }
  5022. if (range.conversion) {
  5023. this.conversion = range.conversion(this.width);
  5024. }
  5025. else {
  5026. this.conversion = Range.conversion(range.start, range.end, this.width);
  5027. }
  5028. };
  5029. /**
  5030. * Convert a position on screen (pixels) to a datetime
  5031. * Before this method can be used, the method _updateConversion must be
  5032. * executed once.
  5033. * @param {int} x Position on the screen in pixels
  5034. * @return {Date} time The datetime the corresponds with given position x
  5035. */
  5036. ItemSet.prototype.toTime = function toTime(x) {
  5037. var conversion = this.conversion;
  5038. return new Date(x / conversion.scale + conversion.offset);
  5039. };
  5040. /**
  5041. * Convert a datetime (Date object) into a position on the screen
  5042. * Before this method can be used, the method _updateConversion must be
  5043. * executed once.
  5044. * @param {Date} time A date
  5045. * @return {int} x The position on the screen in pixels which corresponds
  5046. * with the given date.
  5047. */
  5048. ItemSet.prototype.toScreen = function toScreen(time) {
  5049. var conversion = this.conversion;
  5050. return (time.valueOf() - conversion.offset) * conversion.scale;
  5051. };
  5052. /**
  5053. * Start dragging the selected events
  5054. * @param {Event} event
  5055. * @private
  5056. */
  5057. ItemSet.prototype._onDragStart = function (event) {
  5058. if (!this.options.editable) {
  5059. return;
  5060. }
  5061. var item = ItemSet.itemFromTarget(event),
  5062. me = this;
  5063. if (item && item.selected) {
  5064. var dragLeftItem = event.target.dragLeftItem;
  5065. var dragRightItem = event.target.dragRightItem;
  5066. if (dragLeftItem) {
  5067. this.touchParams.itemProps = [{
  5068. item: dragLeftItem,
  5069. start: item.data.start.valueOf()
  5070. }];
  5071. }
  5072. else if (dragRightItem) {
  5073. this.touchParams.itemProps = [{
  5074. item: dragRightItem,
  5075. end: item.data.end.valueOf()
  5076. }];
  5077. }
  5078. else {
  5079. this.touchParams.itemProps = this.getSelection().map(function (id) {
  5080. var item = me.items[id];
  5081. var props = {
  5082. item: item
  5083. };
  5084. if ('start' in item.data) {
  5085. props.start = item.data.start.valueOf()
  5086. }
  5087. if ('end' in item.data) {
  5088. props.end = item.data.end.valueOf()
  5089. }
  5090. return props;
  5091. });
  5092. }
  5093. event.stopPropagation();
  5094. }
  5095. };
  5096. /**
  5097. * Drag selected items
  5098. * @param {Event} event
  5099. * @private
  5100. */
  5101. ItemSet.prototype._onDrag = function (event) {
  5102. if (this.touchParams.itemProps) {
  5103. var snap = this.options.snap || null,
  5104. deltaX = event.gesture.deltaX,
  5105. offset = deltaX / this.conversion.scale;
  5106. // move
  5107. this.touchParams.itemProps.forEach(function (props) {
  5108. if ('start' in props) {
  5109. var start = new Date(props.start + offset);
  5110. props.item.data.start = snap ? snap(start) : start;
  5111. }
  5112. if ('end' in props) {
  5113. var end = new Date(props.end + offset);
  5114. props.item.data.end = snap ? snap(end) : end;
  5115. }
  5116. });
  5117. // TODO: implement onMoving handler
  5118. // TODO: implement dragging from one group to another
  5119. this.requestReflow();
  5120. event.stopPropagation();
  5121. }
  5122. };
  5123. /**
  5124. * End of dragging selected items
  5125. * @param {Event} event
  5126. * @private
  5127. */
  5128. ItemSet.prototype._onDragEnd = function (event) {
  5129. if (this.touchParams.itemProps) {
  5130. // prepare a change set for the changed items
  5131. var changes = [],
  5132. me = this,
  5133. dataset = this._myDataSet(),
  5134. type;
  5135. this.touchParams.itemProps.forEach(function (props) {
  5136. var id = props.item.id,
  5137. item = me.itemsData.get(id);
  5138. var changed = false;
  5139. if ('start' in props.item.data) {
  5140. changed = (props.start != props.item.data.start.valueOf());
  5141. item.start = util.convert(props.item.data.start, dataset.convert['start']);
  5142. }
  5143. if ('end' in props.item.data) {
  5144. changed = changed || (props.end != props.item.data.end.valueOf());
  5145. item.end = util.convert(props.item.data.end, dataset.convert['end']);
  5146. }
  5147. // only apply changes when start or end is actually changed
  5148. if (changed) {
  5149. me.options.onMove(item, function (item) {
  5150. if (item) {
  5151. // apply changes
  5152. changes.push(item);
  5153. }
  5154. else {
  5155. // restore original values
  5156. if ('start' in props) props.item.data.start = props.start;
  5157. if ('end' in props) props.item.data.end = props.end;
  5158. me.requestReflow();
  5159. }
  5160. });
  5161. }
  5162. });
  5163. this.touchParams.itemProps = null;
  5164. // apply the changes to the data (if there are changes)
  5165. if (changes.length) {
  5166. dataset.update(changes);
  5167. }
  5168. event.stopPropagation();
  5169. }
  5170. };
  5171. /**
  5172. * Find an item from an event target:
  5173. * searches for the attribute 'timeline-item' in the event target's element tree
  5174. * @param {Event} event
  5175. * @return {Item | null} item
  5176. */
  5177. ItemSet.itemFromTarget = function itemFromTarget (event) {
  5178. var target = event.target;
  5179. while (target) {
  5180. if (target.hasOwnProperty('timeline-item')) {
  5181. return target['timeline-item'];
  5182. }
  5183. target = target.parentNode;
  5184. }
  5185. return null;
  5186. };
  5187. /**
  5188. * Find the ItemSet from an event target:
  5189. * searches for the attribute 'timeline-itemset' in the event target's element tree
  5190. * @param {Event} event
  5191. * @return {ItemSet | null} item
  5192. */
  5193. ItemSet.itemSetFromTarget = function itemSetFromTarget (event) {
  5194. var target = event.target;
  5195. while (target) {
  5196. if (target.hasOwnProperty('timeline-itemset')) {
  5197. return target['timeline-itemset'];
  5198. }
  5199. target = target.parentNode;
  5200. }
  5201. return null;
  5202. };
  5203. /**
  5204. * Find the DataSet to which this ItemSet is connected
  5205. * @returns {null | DataSet} dataset
  5206. * @private
  5207. */
  5208. ItemSet.prototype._myDataSet = function _myDataSet() {
  5209. // find the root DataSet
  5210. var dataset = this.itemsData;
  5211. while (dataset instanceof DataView) {
  5212. dataset = dataset.data;
  5213. }
  5214. return dataset;
  5215. };
  5216. /**
  5217. * @constructor Item
  5218. * @param {ItemSet} parent
  5219. * @param {Object} data Object containing (optional) parameters type,
  5220. * start, end, content, group, className.
  5221. * @param {Object} [options] Options to set initial property values
  5222. * @param {Object} [defaultOptions] default options
  5223. * // TODO: describe available options
  5224. */
  5225. function Item (parent, data, options, defaultOptions) {
  5226. this.parent = parent;
  5227. this.data = data;
  5228. this.dom = null;
  5229. this.options = options || {};
  5230. this.defaultOptions = defaultOptions || {};
  5231. this.selected = false;
  5232. this.visible = false;
  5233. this.top = 0;
  5234. this.left = 0;
  5235. this.width = 0;
  5236. this.height = 0;
  5237. this.offset = 0;
  5238. }
  5239. /**
  5240. * Select current item
  5241. */
  5242. Item.prototype.select = function select() {
  5243. this.selected = true;
  5244. if (this.visible) this.repaint();
  5245. };
  5246. /**
  5247. * Unselect current item
  5248. */
  5249. Item.prototype.unselect = function unselect() {
  5250. this.selected = false;
  5251. if (this.visible) this.repaint();
  5252. };
  5253. /**
  5254. * Show the Item in the DOM (when not already visible)
  5255. * @return {Boolean} changed
  5256. */
  5257. Item.prototype.show = function show() {
  5258. return false;
  5259. };
  5260. /**
  5261. * Hide the Item from the DOM (when visible)
  5262. * @return {Boolean} changed
  5263. */
  5264. Item.prototype.hide = function hide() {
  5265. return false;
  5266. };
  5267. /**
  5268. * Repaint the item
  5269. * @return {Boolean} changed
  5270. */
  5271. Item.prototype.repaint = function repaint() {
  5272. // should be implemented by the item
  5273. return false;
  5274. };
  5275. /**
  5276. * Reflow the item
  5277. * @return {Boolean} resized
  5278. */
  5279. Item.prototype.reflow = function reflow() {
  5280. // should be implemented by the item
  5281. return false;
  5282. };
  5283. /**
  5284. * Give the item a display offset in pixels
  5285. * @param {Number} offset Offset on screen in pixels
  5286. */
  5287. Item.prototype.setOffset = function setOffset(offset) {
  5288. this.offset = offset;
  5289. };
  5290. /**
  5291. * Repaint a delete button on the top right of the item when the item is selected
  5292. * @param {HTMLElement} anchor
  5293. * @private
  5294. */
  5295. Item.prototype._repaintDeleteButton = function (anchor) {
  5296. if (this.selected && this.options.editable && !this.dom.deleteButton) {
  5297. // create and show button
  5298. var parent = this.parent;
  5299. var id = this.id;
  5300. var deleteButton = document.createElement('div');
  5301. deleteButton.className = 'delete';
  5302. deleteButton.title = 'Delete this item';
  5303. Hammer(deleteButton, {
  5304. preventDefault: true
  5305. }).on('tap', function (event) {
  5306. parent.removeItem(id);
  5307. event.stopPropagation();
  5308. });
  5309. anchor.appendChild(deleteButton);
  5310. this.dom.deleteButton = deleteButton;
  5311. }
  5312. else if (!this.selected && this.dom.deleteButton) {
  5313. // remove button
  5314. if (this.dom.deleteButton.parentNode) {
  5315. this.dom.deleteButton.parentNode.removeChild(this.dom.deleteButton);
  5316. }
  5317. this.dom.deleteButton = null;
  5318. }
  5319. };
  5320. /**
  5321. * @constructor ItemBox
  5322. * @extends Item
  5323. * @param {ItemSet} parent
  5324. * @param {Object} data Object containing parameters start
  5325. * content, className.
  5326. * @param {Object} [options] Options to set initial property values
  5327. * @param {Object} [defaultOptions] default options
  5328. * // TODO: describe available options
  5329. */
  5330. function ItemBox (parent, data, options, defaultOptions) {
  5331. this.props = {
  5332. dot: {
  5333. left: 0,
  5334. top: 0,
  5335. width: 0,
  5336. height: 0
  5337. },
  5338. line: {
  5339. top: 0,
  5340. left: 0,
  5341. width: 0,
  5342. height: 0
  5343. }
  5344. };
  5345. Item.call(this, parent, data, options, defaultOptions);
  5346. }
  5347. ItemBox.prototype = new Item (null, null);
  5348. /**
  5349. * Repaint the item
  5350. * @return {Boolean} changed
  5351. */
  5352. ItemBox.prototype.repaint = function repaint() {
  5353. // TODO: make an efficient repaint
  5354. var changed = false;
  5355. var dom = this.dom;
  5356. if (!dom) {
  5357. this._create();
  5358. dom = this.dom;
  5359. changed = true;
  5360. }
  5361. if (dom) {
  5362. if (!this.parent) {
  5363. throw new Error('Cannot repaint item: no parent attached');
  5364. }
  5365. if (!dom.box.parentNode) {
  5366. var foreground = this.parent.getForeground();
  5367. if (!foreground) {
  5368. throw new Error('Cannot repaint time axis: ' +
  5369. 'parent has no foreground container element');
  5370. }
  5371. foreground.appendChild(dom.box);
  5372. changed = true;
  5373. }
  5374. if (!dom.line.parentNode) {
  5375. var background = this.parent.getBackground();
  5376. if (!background) {
  5377. throw new Error('Cannot repaint time axis: ' +
  5378. 'parent has no background container element');
  5379. }
  5380. background.appendChild(dom.line);
  5381. changed = true;
  5382. }
  5383. if (!dom.dot.parentNode) {
  5384. var axis = this.parent.getAxis();
  5385. if (!background) {
  5386. throw new Error('Cannot repaint time axis: ' +
  5387. 'parent has no axis container element');
  5388. }
  5389. axis.appendChild(dom.dot);
  5390. changed = true;
  5391. }
  5392. this._repaintDeleteButton(dom.box);
  5393. // update contents
  5394. if (this.data.content != this.content) {
  5395. this.content = this.data.content;
  5396. if (this.content instanceof Element) {
  5397. dom.content.innerHTML = '';
  5398. dom.content.appendChild(this.content);
  5399. }
  5400. else if (this.data.content != undefined) {
  5401. dom.content.innerHTML = this.content;
  5402. }
  5403. else {
  5404. throw new Error('Property "content" missing in item ' + this.data.id);
  5405. }
  5406. changed = true;
  5407. }
  5408. // update class
  5409. var className = (this.data.className? ' ' + this.data.className : '') +
  5410. (this.selected ? ' selected' : '');
  5411. if (this.className != className) {
  5412. this.className = className;
  5413. dom.box.className = 'item box' + className;
  5414. dom.line.className = 'item line' + className;
  5415. dom.dot.className = 'item dot' + className;
  5416. changed = true;
  5417. }
  5418. }
  5419. return changed;
  5420. };
  5421. /**
  5422. * Show the item in the DOM (when not already visible). The items DOM will
  5423. * be created when needed.
  5424. * @return {Boolean} changed
  5425. */
  5426. ItemBox.prototype.show = function show() {
  5427. if (!this.dom || !this.dom.box.parentNode) {
  5428. return this.repaint();
  5429. }
  5430. else {
  5431. return false;
  5432. }
  5433. };
  5434. /**
  5435. * Hide the item from the DOM (when visible)
  5436. * @return {Boolean} changed
  5437. */
  5438. ItemBox.prototype.hide = function hide() {
  5439. var changed = false,
  5440. dom = this.dom;
  5441. if (dom) {
  5442. if (dom.box.parentNode) {
  5443. dom.box.parentNode.removeChild(dom.box);
  5444. changed = true;
  5445. }
  5446. if (dom.line.parentNode) {
  5447. dom.line.parentNode.removeChild(dom.line);
  5448. }
  5449. if (dom.dot.parentNode) {
  5450. dom.dot.parentNode.removeChild(dom.dot);
  5451. }
  5452. }
  5453. return changed;
  5454. };
  5455. /**
  5456. * Reflow the item: calculate its actual size and position from the DOM
  5457. * @return {boolean} resized returns true if the axis is resized
  5458. * @override
  5459. */
  5460. ItemBox.prototype.reflow = function reflow() {
  5461. var changed = 0,
  5462. update,
  5463. dom,
  5464. props,
  5465. options,
  5466. margin,
  5467. start,
  5468. align,
  5469. orientation,
  5470. top,
  5471. left,
  5472. data,
  5473. range;
  5474. if (this.data.start == undefined) {
  5475. throw new Error('Property "start" missing in item ' + this.data.id);
  5476. }
  5477. data = this.data;
  5478. range = this.parent && this.parent.range;
  5479. if (data && range) {
  5480. // TODO: account for the width of the item
  5481. var interval = (range.end - range.start);
  5482. this.visible = (data.start > range.start - interval) && (data.start < range.end + interval);
  5483. }
  5484. else {
  5485. this.visible = false;
  5486. }
  5487. if (this.visible) {
  5488. dom = this.dom;
  5489. if (dom) {
  5490. update = util.updateProperty;
  5491. props = this.props;
  5492. options = this.options;
  5493. start = this.parent.toScreen(this.data.start) + this.offset;
  5494. align = options.align || this.defaultOptions.align;
  5495. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  5496. orientation = options.orientation || this.defaultOptions.orientation;
  5497. changed += update(props.dot, 'height', dom.dot.offsetHeight);
  5498. changed += update(props.dot, 'width', dom.dot.offsetWidth);
  5499. changed += update(props.line, 'width', dom.line.offsetWidth);
  5500. changed += update(props.line, 'height', dom.line.offsetHeight);
  5501. changed += update(props.line, 'top', dom.line.offsetTop);
  5502. changed += update(this, 'width', dom.box.offsetWidth);
  5503. changed += update(this, 'height', dom.box.offsetHeight);
  5504. if (align == 'right') {
  5505. left = start - this.width;
  5506. }
  5507. else if (align == 'left') {
  5508. left = start;
  5509. }
  5510. else {
  5511. // default or 'center'
  5512. left = start - this.width / 2;
  5513. }
  5514. changed += update(this, 'left', left);
  5515. changed += update(props.line, 'left', start - props.line.width / 2);
  5516. changed += update(props.dot, 'left', start - props.dot.width / 2);
  5517. changed += update(props.dot, 'top', -props.dot.height / 2);
  5518. if (orientation == 'top') {
  5519. top = margin;
  5520. changed += update(this, 'top', top);
  5521. }
  5522. else {
  5523. // default or 'bottom'
  5524. var parentHeight = this.parent.height;
  5525. top = parentHeight - this.height - margin;
  5526. changed += update(this, 'top', top);
  5527. }
  5528. }
  5529. else {
  5530. changed += 1;
  5531. }
  5532. }
  5533. return (changed > 0);
  5534. };
  5535. /**
  5536. * Create an items DOM
  5537. * @private
  5538. */
  5539. ItemBox.prototype._create = function _create() {
  5540. var dom = this.dom;
  5541. if (!dom) {
  5542. this.dom = dom = {};
  5543. // create the box
  5544. dom.box = document.createElement('DIV');
  5545. // className is updated in repaint()
  5546. // contents box (inside the background box). used for making margins
  5547. dom.content = document.createElement('DIV');
  5548. dom.content.className = 'content';
  5549. dom.box.appendChild(dom.content);
  5550. // line to axis
  5551. dom.line = document.createElement('DIV');
  5552. dom.line.className = 'line';
  5553. // dot on axis
  5554. dom.dot = document.createElement('DIV');
  5555. dom.dot.className = 'dot';
  5556. // attach this item as attribute
  5557. dom.box['timeline-item'] = this;
  5558. }
  5559. };
  5560. /**
  5561. * Reposition the item, recalculate its left, top, and width, using the current
  5562. * range and size of the items itemset
  5563. * @override
  5564. */
  5565. ItemBox.prototype.reposition = function reposition() {
  5566. var dom = this.dom,
  5567. props = this.props,
  5568. orientation = this.options.orientation || this.defaultOptions.orientation;
  5569. if (dom) {
  5570. var box = dom.box,
  5571. line = dom.line,
  5572. dot = dom.dot;
  5573. box.style.left = this.left + 'px';
  5574. box.style.top = this.top + 'px';
  5575. line.style.left = props.line.left + 'px';
  5576. if (orientation == 'top') {
  5577. line.style.top = 0 + 'px';
  5578. line.style.height = this.top + 'px';
  5579. }
  5580. else {
  5581. // orientation 'bottom'
  5582. line.style.top = (this.top + this.height) + 'px';
  5583. line.style.height = Math.max(this.parent.height - this.top - this.height +
  5584. this.props.dot.height / 2, 0) + 'px';
  5585. }
  5586. dot.style.left = props.dot.left + 'px';
  5587. dot.style.top = props.dot.top + 'px';
  5588. }
  5589. };
  5590. /**
  5591. * @constructor ItemPoint
  5592. * @extends Item
  5593. * @param {ItemSet} parent
  5594. * @param {Object} data Object containing parameters start
  5595. * content, className.
  5596. * @param {Object} [options] Options to set initial property values
  5597. * @param {Object} [defaultOptions] default options
  5598. * // TODO: describe available options
  5599. */
  5600. function ItemPoint (parent, data, options, defaultOptions) {
  5601. this.props = {
  5602. dot: {
  5603. top: 0,
  5604. width: 0,
  5605. height: 0
  5606. },
  5607. content: {
  5608. height: 0,
  5609. marginLeft: 0
  5610. }
  5611. };
  5612. Item.call(this, parent, data, options, defaultOptions);
  5613. }
  5614. ItemPoint.prototype = new Item (null, null);
  5615. /**
  5616. * Repaint the item
  5617. * @return {Boolean} changed
  5618. */
  5619. ItemPoint.prototype.repaint = function repaint() {
  5620. // TODO: make an efficient repaint
  5621. var changed = false;
  5622. var dom = this.dom;
  5623. if (!dom) {
  5624. this._create();
  5625. dom = this.dom;
  5626. changed = true;
  5627. }
  5628. if (dom) {
  5629. if (!this.parent) {
  5630. throw new Error('Cannot repaint item: no parent attached');
  5631. }
  5632. var foreground = this.parent.getForeground();
  5633. if (!foreground) {
  5634. throw new Error('Cannot repaint time axis: ' +
  5635. 'parent has no foreground container element');
  5636. }
  5637. if (!dom.point.parentNode) {
  5638. foreground.appendChild(dom.point);
  5639. foreground.appendChild(dom.point);
  5640. changed = true;
  5641. }
  5642. // update contents
  5643. if (this.data.content != this.content) {
  5644. this.content = this.data.content;
  5645. if (this.content instanceof Element) {
  5646. dom.content.innerHTML = '';
  5647. dom.content.appendChild(this.content);
  5648. }
  5649. else if (this.data.content != undefined) {
  5650. dom.content.innerHTML = this.content;
  5651. }
  5652. else {
  5653. throw new Error('Property "content" missing in item ' + this.data.id);
  5654. }
  5655. changed = true;
  5656. }
  5657. this._repaintDeleteButton(dom.point);
  5658. // update class
  5659. var className = (this.data.className? ' ' + this.data.className : '') +
  5660. (this.selected ? ' selected' : '');
  5661. if (this.className != className) {
  5662. this.className = className;
  5663. dom.point.className = 'item point' + className;
  5664. changed = true;
  5665. }
  5666. }
  5667. return changed;
  5668. };
  5669. /**
  5670. * Show the item in the DOM (when not already visible). The items DOM will
  5671. * be created when needed.
  5672. * @return {Boolean} changed
  5673. */
  5674. ItemPoint.prototype.show = function show() {
  5675. if (!this.dom || !this.dom.point.parentNode) {
  5676. return this.repaint();
  5677. }
  5678. else {
  5679. return false;
  5680. }
  5681. };
  5682. /**
  5683. * Hide the item from the DOM (when visible)
  5684. * @return {Boolean} changed
  5685. */
  5686. ItemPoint.prototype.hide = function hide() {
  5687. var changed = false,
  5688. dom = this.dom;
  5689. if (dom) {
  5690. if (dom.point.parentNode) {
  5691. dom.point.parentNode.removeChild(dom.point);
  5692. changed = true;
  5693. }
  5694. }
  5695. return changed;
  5696. };
  5697. /**
  5698. * Reflow the item: calculate its actual size from the DOM
  5699. * @return {boolean} resized returns true if the axis is resized
  5700. * @override
  5701. */
  5702. ItemPoint.prototype.reflow = function reflow() {
  5703. var changed = 0,
  5704. update,
  5705. dom,
  5706. props,
  5707. options,
  5708. margin,
  5709. orientation,
  5710. start,
  5711. top,
  5712. data,
  5713. range;
  5714. if (this.data.start == undefined) {
  5715. throw new Error('Property "start" missing in item ' + this.data.id);
  5716. }
  5717. data = this.data;
  5718. range = this.parent && this.parent.range;
  5719. if (data && range) {
  5720. // TODO: account for the width of the item
  5721. var interval = (range.end - range.start);
  5722. this.visible = (data.start > range.start - interval) && (data.start < range.end);
  5723. }
  5724. else {
  5725. this.visible = false;
  5726. }
  5727. if (this.visible) {
  5728. dom = this.dom;
  5729. if (dom) {
  5730. update = util.updateProperty;
  5731. props = this.props;
  5732. options = this.options;
  5733. orientation = options.orientation || this.defaultOptions.orientation;
  5734. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  5735. start = this.parent.toScreen(this.data.start) + this.offset;
  5736. changed += update(this, 'width', dom.point.offsetWidth);
  5737. changed += update(this, 'height', dom.point.offsetHeight);
  5738. changed += update(props.dot, 'width', dom.dot.offsetWidth);
  5739. changed += update(props.dot, 'height', dom.dot.offsetHeight);
  5740. changed += update(props.content, 'height', dom.content.offsetHeight);
  5741. if (orientation == 'top') {
  5742. top = margin;
  5743. }
  5744. else {
  5745. // default or 'bottom'
  5746. var parentHeight = this.parent.height;
  5747. top = Math.max(parentHeight - this.height - margin, 0);
  5748. }
  5749. changed += update(this, 'top', top);
  5750. changed += update(this, 'left', start - props.dot.width / 2);
  5751. changed += update(props.content, 'marginLeft', 1.5 * props.dot.width);
  5752. //changed += update(props.content, 'marginRight', 0.5 * props.dot.width); // TODO
  5753. changed += update(props.dot, 'top', (this.height - props.dot.height) / 2);
  5754. }
  5755. else {
  5756. changed += 1;
  5757. }
  5758. }
  5759. return (changed > 0);
  5760. };
  5761. /**
  5762. * Create an items DOM
  5763. * @private
  5764. */
  5765. ItemPoint.prototype._create = function _create() {
  5766. var dom = this.dom;
  5767. if (!dom) {
  5768. this.dom = dom = {};
  5769. // background box
  5770. dom.point = document.createElement('div');
  5771. // className is updated in repaint()
  5772. // contents box, right from the dot
  5773. dom.content = document.createElement('div');
  5774. dom.content.className = 'content';
  5775. dom.point.appendChild(dom.content);
  5776. // dot at start
  5777. dom.dot = document.createElement('div');
  5778. dom.dot.className = 'dot';
  5779. dom.point.appendChild(dom.dot);
  5780. // attach this item as attribute
  5781. dom.point['timeline-item'] = this;
  5782. }
  5783. };
  5784. /**
  5785. * Reposition the item, recalculate its left, top, and width, using the current
  5786. * range and size of the items itemset
  5787. * @override
  5788. */
  5789. ItemPoint.prototype.reposition = function reposition() {
  5790. var dom = this.dom,
  5791. props = this.props;
  5792. if (dom) {
  5793. dom.point.style.top = this.top + 'px';
  5794. dom.point.style.left = this.left + 'px';
  5795. dom.content.style.marginLeft = props.content.marginLeft + 'px';
  5796. //dom.content.style.marginRight = props.content.marginRight + 'px'; // TODO
  5797. dom.dot.style.top = props.dot.top + 'px';
  5798. }
  5799. };
  5800. /**
  5801. * @constructor ItemRange
  5802. * @extends Item
  5803. * @param {ItemSet} parent
  5804. * @param {Object} data Object containing parameters start, end
  5805. * content, className.
  5806. * @param {Object} [options] Options to set initial property values
  5807. * @param {Object} [defaultOptions] default options
  5808. * // TODO: describe available options
  5809. */
  5810. function ItemRange (parent, data, options, defaultOptions) {
  5811. this.props = {
  5812. content: {
  5813. left: 0,
  5814. width: 0
  5815. }
  5816. };
  5817. Item.call(this, parent, data, options, defaultOptions);
  5818. }
  5819. ItemRange.prototype = new Item (null, null);
  5820. /**
  5821. * Repaint the item
  5822. * @return {Boolean} changed
  5823. */
  5824. ItemRange.prototype.repaint = function repaint() {
  5825. // TODO: make an efficient repaint
  5826. var changed = false;
  5827. var dom = this.dom;
  5828. if (!dom) {
  5829. this._create();
  5830. dom = this.dom;
  5831. changed = true;
  5832. }
  5833. if (dom) {
  5834. if (!this.parent) {
  5835. throw new Error('Cannot repaint item: no parent attached');
  5836. }
  5837. var foreground = this.parent.getForeground();
  5838. if (!foreground) {
  5839. throw new Error('Cannot repaint time axis: ' +
  5840. 'parent has no foreground container element');
  5841. }
  5842. if (!dom.box.parentNode) {
  5843. foreground.appendChild(dom.box);
  5844. changed = true;
  5845. }
  5846. // update content
  5847. if (this.data.content != this.content) {
  5848. this.content = this.data.content;
  5849. if (this.content instanceof Element) {
  5850. dom.content.innerHTML = '';
  5851. dom.content.appendChild(this.content);
  5852. }
  5853. else if (this.data.content != undefined) {
  5854. dom.content.innerHTML = this.content;
  5855. }
  5856. else {
  5857. throw new Error('Property "content" missing in item ' + this.data.id);
  5858. }
  5859. changed = true;
  5860. }
  5861. this._repaintDeleteButton(dom.box);
  5862. this._repaintDragLeft();
  5863. this._repaintDragRight();
  5864. // update class
  5865. var className = (this.data.className ? (' ' + this.data.className) : '') +
  5866. (this.selected ? ' selected' : '');
  5867. if (this.className != className) {
  5868. this.className = className;
  5869. dom.box.className = 'item range' + className;
  5870. changed = true;
  5871. }
  5872. }
  5873. return changed;
  5874. };
  5875. /**
  5876. * Show the item in the DOM (when not already visible). The items DOM will
  5877. * be created when needed.
  5878. * @return {Boolean} changed
  5879. */
  5880. ItemRange.prototype.show = function show() {
  5881. if (!this.dom || !this.dom.box.parentNode) {
  5882. return this.repaint();
  5883. }
  5884. else {
  5885. return false;
  5886. }
  5887. };
  5888. /**
  5889. * Hide the item from the DOM (when visible)
  5890. * @return {Boolean} changed
  5891. */
  5892. ItemRange.prototype.hide = function hide() {
  5893. var changed = false,
  5894. dom = this.dom;
  5895. if (dom) {
  5896. if (dom.box.parentNode) {
  5897. dom.box.parentNode.removeChild(dom.box);
  5898. changed = true;
  5899. }
  5900. }
  5901. return changed;
  5902. };
  5903. /**
  5904. * Reflow the item: calculate its actual size from the DOM
  5905. * @return {boolean} resized returns true if the axis is resized
  5906. * @override
  5907. */
  5908. ItemRange.prototype.reflow = function reflow() {
  5909. var changed = 0,
  5910. dom,
  5911. props,
  5912. options,
  5913. margin,
  5914. padding,
  5915. parent,
  5916. start,
  5917. end,
  5918. data,
  5919. range,
  5920. update,
  5921. box,
  5922. parentWidth,
  5923. contentLeft,
  5924. orientation,
  5925. top;
  5926. if (this.data.start == undefined) {
  5927. throw new Error('Property "start" missing in item ' + this.data.id);
  5928. }
  5929. if (this.data.end == undefined) {
  5930. throw new Error('Property "end" missing in item ' + this.data.id);
  5931. }
  5932. data = this.data;
  5933. range = this.parent && this.parent.range;
  5934. if (data && range) {
  5935. // TODO: account for the width of the item. Take some margin
  5936. this.visible = (data.start < range.end) && (data.end > range.start);
  5937. }
  5938. else {
  5939. this.visible = false;
  5940. }
  5941. if (this.visible) {
  5942. dom = this.dom;
  5943. if (dom) {
  5944. props = this.props;
  5945. options = this.options;
  5946. parent = this.parent;
  5947. start = parent.toScreen(this.data.start) + this.offset;
  5948. end = parent.toScreen(this.data.end) + this.offset;
  5949. update = util.updateProperty;
  5950. box = dom.box;
  5951. parentWidth = parent.width;
  5952. orientation = options.orientation || this.defaultOptions.orientation;
  5953. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  5954. padding = options.padding || this.defaultOptions.padding;
  5955. changed += update(props.content, 'width', dom.content.offsetWidth);
  5956. changed += update(this, 'height', box.offsetHeight);
  5957. // limit the width of the this, as browsers cannot draw very wide divs
  5958. if (start < -parentWidth) {
  5959. start = -parentWidth;
  5960. }
  5961. if (end > 2 * parentWidth) {
  5962. end = 2 * parentWidth;
  5963. }
  5964. // when range exceeds left of the window, position the contents at the left of the visible area
  5965. if (start < 0) {
  5966. contentLeft = Math.min(-start,
  5967. (end - start - props.content.width - 2 * padding));
  5968. // TODO: remove the need for options.padding. it's terrible.
  5969. }
  5970. else {
  5971. contentLeft = 0;
  5972. }
  5973. changed += update(props.content, 'left', contentLeft);
  5974. if (orientation == 'top') {
  5975. top = margin;
  5976. changed += update(this, 'top', top);
  5977. }
  5978. else {
  5979. // default or 'bottom'
  5980. top = parent.height - this.height - margin;
  5981. changed += update(this, 'top', top);
  5982. }
  5983. changed += update(this, 'left', start);
  5984. changed += update(this, 'width', Math.max(end - start, 1)); // TODO: reckon with border width;
  5985. }
  5986. else {
  5987. changed += 1;
  5988. }
  5989. }
  5990. return (changed > 0);
  5991. };
  5992. /**
  5993. * Create an items DOM
  5994. * @private
  5995. */
  5996. ItemRange.prototype._create = function _create() {
  5997. var dom = this.dom;
  5998. if (!dom) {
  5999. this.dom = dom = {};
  6000. // background box
  6001. dom.box = document.createElement('div');
  6002. // className is updated in repaint()
  6003. // contents box
  6004. dom.content = document.createElement('div');
  6005. dom.content.className = 'content';
  6006. dom.box.appendChild(dom.content);
  6007. // attach this item as attribute
  6008. dom.box['timeline-item'] = this;
  6009. }
  6010. };
  6011. /**
  6012. * Reposition the item, recalculate its left, top, and width, using the current
  6013. * range and size of the items itemset
  6014. * @override
  6015. */
  6016. ItemRange.prototype.reposition = function reposition() {
  6017. var dom = this.dom,
  6018. props = this.props;
  6019. if (dom) {
  6020. dom.box.style.top = this.top + 'px';
  6021. dom.box.style.left = this.left + 'px';
  6022. dom.box.style.width = this.width + 'px';
  6023. dom.content.style.left = props.content.left + 'px';
  6024. }
  6025. };
  6026. /**
  6027. * Repaint a drag area on the left side of the range when the range is selected
  6028. * @private
  6029. */
  6030. ItemRange.prototype._repaintDragLeft = function () {
  6031. if (this.selected && this.options.editable && !this.dom.dragLeft) {
  6032. // create and show drag area
  6033. var dragLeft = document.createElement('div');
  6034. dragLeft.className = 'drag-left';
  6035. dragLeft.dragLeftItem = this;
  6036. // TODO: this should be redundant?
  6037. Hammer(dragLeft, {
  6038. preventDefault: true
  6039. }).on('drag', function () {
  6040. //console.log('drag left')
  6041. });
  6042. this.dom.box.appendChild(dragLeft);
  6043. this.dom.dragLeft = dragLeft;
  6044. }
  6045. else if (!this.selected && this.dom.dragLeft) {
  6046. // delete drag area
  6047. if (this.dom.dragLeft.parentNode) {
  6048. this.dom.dragLeft.parentNode.removeChild(this.dom.dragLeft);
  6049. }
  6050. this.dom.dragLeft = null;
  6051. }
  6052. };
  6053. /**
  6054. * Repaint a drag area on the right side of the range when the range is selected
  6055. * @private
  6056. */
  6057. ItemRange.prototype._repaintDragRight = function () {
  6058. if (this.selected && this.options.editable && !this.dom.dragRight) {
  6059. // create and show drag area
  6060. var dragRight = document.createElement('div');
  6061. dragRight.className = 'drag-right';
  6062. dragRight.dragRightItem = this;
  6063. // TODO: this should be redundant?
  6064. Hammer(dragRight, {
  6065. preventDefault: true
  6066. }).on('drag', function () {
  6067. //console.log('drag right')
  6068. });
  6069. this.dom.box.appendChild(dragRight);
  6070. this.dom.dragRight = dragRight;
  6071. }
  6072. else if (!this.selected && this.dom.dragRight) {
  6073. // delete drag area
  6074. if (this.dom.dragRight.parentNode) {
  6075. this.dom.dragRight.parentNode.removeChild(this.dom.dragRight);
  6076. }
  6077. this.dom.dragRight = null;
  6078. }
  6079. };
  6080. /**
  6081. * @constructor ItemRangeOverflow
  6082. * @extends ItemRange
  6083. * @param {ItemSet} parent
  6084. * @param {Object} data Object containing parameters start, end
  6085. * content, className.
  6086. * @param {Object} [options] Options to set initial property values
  6087. * @param {Object} [defaultOptions] default options
  6088. * // TODO: describe available options
  6089. */
  6090. function ItemRangeOverflow (parent, data, options, defaultOptions) {
  6091. this.props = {
  6092. content: {
  6093. left: 0,
  6094. width: 0
  6095. }
  6096. };
  6097. // define a private property _width, which is the with of the range box
  6098. // adhering to the ranges start and end date. The property width has a
  6099. // getter which returns the max of border width and content width
  6100. this._width = 0;
  6101. Object.defineProperty(this, 'width', {
  6102. get: function () {
  6103. return (this.props.content && this._width < this.props.content.width) ?
  6104. this.props.content.width :
  6105. this._width;
  6106. },
  6107. set: function (width) {
  6108. this._width = width;
  6109. }
  6110. });
  6111. ItemRange.call(this, parent, data, options, defaultOptions);
  6112. }
  6113. ItemRangeOverflow.prototype = new ItemRange (null, null);
  6114. /**
  6115. * Repaint the item
  6116. * @return {Boolean} changed
  6117. */
  6118. ItemRangeOverflow.prototype.repaint = function repaint() {
  6119. // TODO: make an efficient repaint
  6120. var changed = false;
  6121. var dom = this.dom;
  6122. if (!dom) {
  6123. this._create();
  6124. dom = this.dom;
  6125. changed = true;
  6126. }
  6127. if (dom) {
  6128. if (!this.parent) {
  6129. throw new Error('Cannot repaint item: no parent attached');
  6130. }
  6131. var foreground = this.parent.getForeground();
  6132. if (!foreground) {
  6133. throw new Error('Cannot repaint time axis: ' +
  6134. 'parent has no foreground container element');
  6135. }
  6136. if (!dom.box.parentNode) {
  6137. foreground.appendChild(dom.box);
  6138. changed = true;
  6139. }
  6140. // update content
  6141. if (this.data.content != this.content) {
  6142. this.content = this.data.content;
  6143. if (this.content instanceof Element) {
  6144. dom.content.innerHTML = '';
  6145. dom.content.appendChild(this.content);
  6146. }
  6147. else if (this.data.content != undefined) {
  6148. dom.content.innerHTML = this.content;
  6149. }
  6150. else {
  6151. throw new Error('Property "content" missing in item ' + this.id);
  6152. }
  6153. changed = true;
  6154. }
  6155. this._repaintDeleteButton(dom.box);
  6156. this._repaintDragLeft();
  6157. this._repaintDragRight();
  6158. // update class
  6159. var className = (this.data.className? ' ' + this.data.className : '') +
  6160. (this.selected ? ' selected' : '');
  6161. if (this.className != className) {
  6162. this.className = className;
  6163. dom.box.className = 'item rangeoverflow' + className;
  6164. changed = true;
  6165. }
  6166. }
  6167. return changed;
  6168. };
  6169. /**
  6170. * Reposition the item, recalculate its left, top, and width, using the current
  6171. * range and size of the items itemset
  6172. * @override
  6173. */
  6174. ItemRangeOverflow.prototype.reposition = function reposition() {
  6175. var dom = this.dom,
  6176. props = this.props;
  6177. if (dom) {
  6178. dom.box.style.top = this.top + 'px';
  6179. dom.box.style.left = this.left + 'px';
  6180. dom.box.style.width = this._width + 'px';
  6181. dom.content.style.left = props.content.left + 'px';
  6182. }
  6183. };
  6184. /**
  6185. * @constructor Group
  6186. * @param {GroupSet} parent
  6187. * @param {Number | String} groupId
  6188. * @param {Object} [options] Options to set initial property values
  6189. * // TODO: describe available options
  6190. * @extends Component
  6191. */
  6192. function Group (parent, groupId, options) {
  6193. this.id = util.randomUUID();
  6194. this.parent = parent;
  6195. this.groupId = groupId;
  6196. this.itemset = null; // ItemSet
  6197. this.options = options || {};
  6198. this.options.top = 0;
  6199. this.props = {
  6200. label: {
  6201. width: 0,
  6202. height: 0
  6203. }
  6204. };
  6205. this.top = 0;
  6206. this.left = 0;
  6207. this.width = 0;
  6208. this.height = 0;
  6209. }
  6210. Group.prototype = new Component();
  6211. // TODO: comment
  6212. Group.prototype.setOptions = Component.prototype.setOptions;
  6213. /**
  6214. * Get the container element of the panel, which can be used by a child to
  6215. * add its own widgets.
  6216. * @returns {HTMLElement} container
  6217. */
  6218. Group.prototype.getContainer = function () {
  6219. return this.parent.getContainer();
  6220. };
  6221. /**
  6222. * Set item set for the group. The group will create a view on the itemset,
  6223. * filtered by the groups id.
  6224. * @param {DataSet | DataView} items
  6225. */
  6226. Group.prototype.setItems = function setItems(items) {
  6227. if (this.itemset) {
  6228. // remove current item set
  6229. this.itemset.hide();
  6230. this.itemset.setItems();
  6231. this.parent.controller.remove(this.itemset);
  6232. this.itemset = null;
  6233. }
  6234. if (items) {
  6235. var groupId = this.groupId;
  6236. var itemsetOptions = Object.create(this.options);
  6237. this.itemset = new ItemSet(this, null, itemsetOptions);
  6238. this.itemset.setRange(this.parent.range);
  6239. this.view = new DataView(items, {
  6240. filter: function (item) {
  6241. return item.group == groupId;
  6242. }
  6243. });
  6244. this.itemset.setItems(this.view);
  6245. this.parent.controller.add(this.itemset);
  6246. }
  6247. };
  6248. /**
  6249. * Set selected items by their id. Replaces the current selection.
  6250. * Unknown id's are silently ignored.
  6251. * @param {Array} [ids] An array with zero or more id's of the items to be
  6252. * selected. If ids is an empty array, all items will be
  6253. * unselected.
  6254. */
  6255. Group.prototype.setSelection = function setSelection(ids) {
  6256. if (this.itemset) this.itemset.setSelection(ids);
  6257. };
  6258. /**
  6259. * Get the selected items by their id
  6260. * @return {Array} ids The ids of the selected items
  6261. */
  6262. Group.prototype.getSelection = function getSelection() {
  6263. return this.itemset ? this.itemset.getSelection() : [];
  6264. };
  6265. /**
  6266. * Repaint the item
  6267. * @return {Boolean} changed
  6268. */
  6269. Group.prototype.repaint = function repaint() {
  6270. return false;
  6271. };
  6272. /**
  6273. * Reflow the item
  6274. * @return {Boolean} resized
  6275. */
  6276. Group.prototype.reflow = function reflow() {
  6277. var changed = 0,
  6278. update = util.updateProperty;
  6279. changed += update(this, 'top', this.itemset ? this.itemset.top : 0);
  6280. changed += update(this, 'height', this.itemset ? this.itemset.height : 0);
  6281. // TODO: reckon with the height of the group label
  6282. if (this.label) {
  6283. var inner = this.label.firstChild;
  6284. changed += update(this.props.label, 'width', inner.clientWidth);
  6285. changed += update(this.props.label, 'height', inner.clientHeight);
  6286. }
  6287. else {
  6288. changed += update(this.props.label, 'width', 0);
  6289. changed += update(this.props.label, 'height', 0);
  6290. }
  6291. return (changed > 0);
  6292. };
  6293. /**
  6294. * An GroupSet holds a set of groups
  6295. * @param {Component} parent
  6296. * @param {Component[]} [depends] Components on which this components depends
  6297. * (except for the parent)
  6298. * @param {Object} [options] See GroupSet.setOptions for the available
  6299. * options.
  6300. * @constructor GroupSet
  6301. * @extends Panel
  6302. */
  6303. function GroupSet(parent, depends, options) {
  6304. this.id = util.randomUUID();
  6305. this.parent = parent;
  6306. this.depends = depends;
  6307. this.options = options || {};
  6308. this.range = null; // Range or Object {start: number, end: number}
  6309. this.itemsData = null; // DataSet with items
  6310. this.groupsData = null; // DataSet with groups
  6311. this.groups = {}; // map with groups
  6312. this.dom = {};
  6313. this.props = {
  6314. labels: {
  6315. width: 0
  6316. }
  6317. };
  6318. // TODO: implement right orientation of the labels
  6319. // changes in groups are queued key/value map containing id/action
  6320. this.queue = {};
  6321. var me = this;
  6322. this.listeners = {
  6323. 'add': function (event, params) {
  6324. me._onAdd(params.items);
  6325. },
  6326. 'update': function (event, params) {
  6327. me._onUpdate(params.items);
  6328. },
  6329. 'remove': function (event, params) {
  6330. me._onRemove(params.items);
  6331. }
  6332. };
  6333. }
  6334. GroupSet.prototype = new Panel();
  6335. /**
  6336. * Set options for the GroupSet. Existing options will be extended/overwritten.
  6337. * @param {Object} [options] The following options are available:
  6338. * {String | function} groupsOrder
  6339. * TODO: describe options
  6340. */
  6341. GroupSet.prototype.setOptions = Component.prototype.setOptions;
  6342. GroupSet.prototype.setRange = function (range) {
  6343. // TODO: implement setRange
  6344. };
  6345. /**
  6346. * Set items
  6347. * @param {vis.DataSet | null} items
  6348. */
  6349. GroupSet.prototype.setItems = function setItems(items) {
  6350. this.itemsData = items;
  6351. for (var id in this.groups) {
  6352. if (this.groups.hasOwnProperty(id)) {
  6353. var group = this.groups[id];
  6354. group.setItems(items);
  6355. }
  6356. }
  6357. };
  6358. /**
  6359. * Get items
  6360. * @return {vis.DataSet | null} items
  6361. */
  6362. GroupSet.prototype.getItems = function getItems() {
  6363. return this.itemsData;
  6364. };
  6365. /**
  6366. * Set range (start and end).
  6367. * @param {Range | Object} range A Range or an object containing start and end.
  6368. */
  6369. GroupSet.prototype.setRange = function setRange(range) {
  6370. this.range = range;
  6371. };
  6372. /**
  6373. * Set groups
  6374. * @param {vis.DataSet} groups
  6375. */
  6376. GroupSet.prototype.setGroups = function setGroups(groups) {
  6377. var me = this,
  6378. ids;
  6379. // unsubscribe from current dataset
  6380. if (this.groupsData) {
  6381. util.forEach(this.listeners, function (callback, event) {
  6382. me.groupsData.unsubscribe(event, callback);
  6383. });
  6384. // remove all drawn groups
  6385. ids = this.groupsData.getIds();
  6386. this._onRemove(ids);
  6387. }
  6388. // replace the dataset
  6389. if (!groups) {
  6390. this.groupsData = null;
  6391. }
  6392. else if (groups instanceof DataSet) {
  6393. this.groupsData = groups;
  6394. }
  6395. else {
  6396. this.groupsData = new DataSet({
  6397. convert: {
  6398. start: 'Date',
  6399. end: 'Date'
  6400. }
  6401. });
  6402. this.groupsData.add(groups);
  6403. }
  6404. if (this.groupsData) {
  6405. // subscribe to new dataset
  6406. var id = this.id;
  6407. util.forEach(this.listeners, function (callback, event) {
  6408. me.groupsData.on(event, callback, id);
  6409. });
  6410. // draw all new groups
  6411. ids = this.groupsData.getIds();
  6412. this._onAdd(ids);
  6413. }
  6414. };
  6415. /**
  6416. * Get groups
  6417. * @return {vis.DataSet | null} groups
  6418. */
  6419. GroupSet.prototype.getGroups = function getGroups() {
  6420. return this.groupsData;
  6421. };
  6422. /**
  6423. * Set selected items by their id. Replaces the current selection.
  6424. * Unknown id's are silently ignored.
  6425. * @param {Array} [ids] An array with zero or more id's of the items to be
  6426. * selected. If ids is an empty array, all items will be
  6427. * unselected.
  6428. */
  6429. GroupSet.prototype.setSelection = function setSelection(ids) {
  6430. var selection = [],
  6431. groups = this.groups;
  6432. // iterate over each of the groups
  6433. for (var id in groups) {
  6434. if (groups.hasOwnProperty(id)) {
  6435. var group = groups[id];
  6436. group.setSelection(ids);
  6437. }
  6438. }
  6439. return selection;
  6440. };
  6441. /**
  6442. * Get the selected items by their id
  6443. * @return {Array} ids The ids of the selected items
  6444. */
  6445. GroupSet.prototype.getSelection = function getSelection() {
  6446. var selection = [],
  6447. groups = this.groups;
  6448. // iterate over each of the groups
  6449. for (var id in groups) {
  6450. if (groups.hasOwnProperty(id)) {
  6451. var group = groups[id];
  6452. selection = selection.concat(group.getSelection());
  6453. }
  6454. }
  6455. return selection;
  6456. };
  6457. /**
  6458. * Repaint the component
  6459. * @return {Boolean} changed
  6460. */
  6461. GroupSet.prototype.repaint = function repaint() {
  6462. var changed = 0,
  6463. i, id, group, label,
  6464. update = util.updateProperty,
  6465. asSize = util.option.asSize,
  6466. asElement = util.option.asElement,
  6467. options = this.options,
  6468. frame = this.dom.frame,
  6469. labels = this.dom.labels,
  6470. labelSet = this.dom.labelSet;
  6471. // create frame
  6472. if (!this.parent) {
  6473. throw new Error('Cannot repaint groupset: no parent attached');
  6474. }
  6475. var parentContainer = this.parent.getContainer();
  6476. if (!parentContainer) {
  6477. throw new Error('Cannot repaint groupset: parent has no container element');
  6478. }
  6479. if (!frame) {
  6480. frame = document.createElement('div');
  6481. frame.className = 'groupset';
  6482. frame['timeline-groupset'] = this;
  6483. this.dom.frame = frame;
  6484. var className = options.className;
  6485. if (className) {
  6486. util.addClassName(frame, util.option.asString(className));
  6487. }
  6488. changed += 1;
  6489. }
  6490. if (!frame.parentNode) {
  6491. parentContainer.appendChild(frame);
  6492. changed += 1;
  6493. }
  6494. // create labels
  6495. var labelContainer = asElement(options.labelContainer);
  6496. if (!labelContainer) {
  6497. throw new Error('Cannot repaint groupset: option "labelContainer" not defined');
  6498. }
  6499. if (!labels) {
  6500. labels = document.createElement('div');
  6501. labels.className = 'labels';
  6502. this.dom.labels = labels;
  6503. }
  6504. if (!labelSet) {
  6505. labelSet = document.createElement('div');
  6506. labelSet.className = 'label-set';
  6507. labels.appendChild(labelSet);
  6508. this.dom.labelSet = labelSet;
  6509. }
  6510. if (!labels.parentNode || labels.parentNode != labelContainer) {
  6511. if (labels.parentNode) {
  6512. labels.parentNode.removeChild(labels.parentNode);
  6513. }
  6514. labelContainer.appendChild(labels);
  6515. }
  6516. // reposition frame
  6517. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  6518. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  6519. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  6520. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  6521. // reposition labels
  6522. changed += update(labelSet.style, 'top', asSize(options.top, '0px'));
  6523. changed += update(labelSet.style, 'height', asSize(options.height, this.height + 'px'));
  6524. var me = this,
  6525. queue = this.queue,
  6526. groups = this.groups,
  6527. groupsData = this.groupsData;
  6528. // show/hide added/changed/removed groups
  6529. var ids = Object.keys(queue);
  6530. if (ids.length) {
  6531. ids.forEach(function (id) {
  6532. var action = queue[id];
  6533. var group = groups[id];
  6534. //noinspection FallthroughInSwitchStatementJS
  6535. switch (action) {
  6536. case 'add':
  6537. case 'update':
  6538. if (!group) {
  6539. var groupOptions = Object.create(me.options);
  6540. util.extend(groupOptions, {
  6541. height: null,
  6542. maxHeight: null
  6543. });
  6544. group = new Group(me, id, groupOptions);
  6545. group.setItems(me.itemsData); // attach items data
  6546. groups[id] = group;
  6547. me.controller.add(group);
  6548. }
  6549. // TODO: update group data
  6550. group.data = groupsData.get(id);
  6551. delete queue[id];
  6552. break;
  6553. case 'remove':
  6554. if (group) {
  6555. group.setItems(); // detach items data
  6556. delete groups[id];
  6557. me.controller.remove(group);
  6558. }
  6559. // update lists
  6560. delete queue[id];
  6561. break;
  6562. default:
  6563. console.log('Error: unknown action "' + action + '"');
  6564. }
  6565. });
  6566. // the groupset depends on each of the groups
  6567. //this.depends = this.groups; // TODO: gives a circular reference through the parent
  6568. // TODO: apply dependencies of the groupset
  6569. // update the top positions of the groups in the correct order
  6570. var orderedGroups = this.groupsData.getIds({
  6571. order: this.options.groupOrder
  6572. });
  6573. for (i = 0; i < orderedGroups.length; i++) {
  6574. (function (group, prevGroup) {
  6575. var top = 0;
  6576. if (prevGroup) {
  6577. top = function () {
  6578. // TODO: top must reckon with options.maxHeight
  6579. return prevGroup.top + prevGroup.height;
  6580. }
  6581. }
  6582. group.setOptions({
  6583. top: top
  6584. });
  6585. })(groups[orderedGroups[i]], groups[orderedGroups[i - 1]]);
  6586. }
  6587. // (re)create the labels
  6588. while (labelSet.firstChild) {
  6589. labelSet.removeChild(labelSet.firstChild);
  6590. }
  6591. for (i = 0; i < orderedGroups.length; i++) {
  6592. id = orderedGroups[i];
  6593. label = this._createLabel(id);
  6594. labelSet.appendChild(label);
  6595. }
  6596. changed++;
  6597. }
  6598. // reposition the labels
  6599. // TODO: labels are not displayed correctly when orientation=='top'
  6600. // TODO: width of labelPanel is not immediately updated on a change in groups
  6601. for (id in groups) {
  6602. if (groups.hasOwnProperty(id)) {
  6603. group = groups[id];
  6604. label = group.label;
  6605. if (label) {
  6606. label.style.top = group.top + 'px';
  6607. label.style.height = group.height + 'px';
  6608. }
  6609. }
  6610. }
  6611. return (changed > 0);
  6612. };
  6613. /**
  6614. * Create a label for group with given id
  6615. * @param {Number} id
  6616. * @return {Element} label
  6617. * @private
  6618. */
  6619. GroupSet.prototype._createLabel = function(id) {
  6620. var group = this.groups[id];
  6621. var label = document.createElement('div');
  6622. label.className = 'vlabel';
  6623. var inner = document.createElement('div');
  6624. inner.className = 'inner';
  6625. label.appendChild(inner);
  6626. var content = group.data && group.data.content;
  6627. if (content instanceof Element) {
  6628. inner.appendChild(content);
  6629. }
  6630. else if (content != undefined) {
  6631. inner.innerHTML = content;
  6632. }
  6633. var className = group.data && group.data.className;
  6634. if (className) {
  6635. util.addClassName(label, className);
  6636. }
  6637. group.label = label; // TODO: not so nice, parking labels in the group this way!!!
  6638. return label;
  6639. };
  6640. /**
  6641. * Get container element
  6642. * @return {HTMLElement} container
  6643. */
  6644. GroupSet.prototype.getContainer = function getContainer() {
  6645. return this.dom.frame;
  6646. };
  6647. /**
  6648. * Get the width of the group labels
  6649. * @return {Number} width
  6650. */
  6651. GroupSet.prototype.getLabelsWidth = function getContainer() {
  6652. return this.props.labels.width;
  6653. };
  6654. /**
  6655. * Reflow the component
  6656. * @return {Boolean} resized
  6657. */
  6658. GroupSet.prototype.reflow = function reflow() {
  6659. var changed = 0,
  6660. id, group,
  6661. options = this.options,
  6662. update = util.updateProperty,
  6663. asNumber = util.option.asNumber,
  6664. asSize = util.option.asSize,
  6665. frame = this.dom.frame;
  6666. if (frame) {
  6667. var maxHeight = asNumber(options.maxHeight);
  6668. var fixedHeight = (asSize(options.height) != null);
  6669. var height;
  6670. if (fixedHeight) {
  6671. height = frame.offsetHeight;
  6672. }
  6673. else {
  6674. // height is not specified, calculate the sum of the height of all groups
  6675. height = 0;
  6676. for (id in this.groups) {
  6677. if (this.groups.hasOwnProperty(id)) {
  6678. group = this.groups[id];
  6679. height += group.height;
  6680. }
  6681. }
  6682. }
  6683. if (maxHeight != null) {
  6684. height = Math.min(height, maxHeight);
  6685. }
  6686. changed += update(this, 'height', height);
  6687. changed += update(this, 'top', frame.offsetTop);
  6688. changed += update(this, 'left', frame.offsetLeft);
  6689. changed += update(this, 'width', frame.offsetWidth);
  6690. }
  6691. // calculate the maximum width of the labels
  6692. var width = 0;
  6693. for (id in this.groups) {
  6694. if (this.groups.hasOwnProperty(id)) {
  6695. group = this.groups[id];
  6696. var labelWidth = group.props && group.props.label && group.props.label.width || 0;
  6697. width = Math.max(width, labelWidth);
  6698. }
  6699. }
  6700. changed += update(this.props.labels, 'width', width);
  6701. return (changed > 0);
  6702. };
  6703. /**
  6704. * Hide the component from the DOM
  6705. * @return {Boolean} changed
  6706. */
  6707. GroupSet.prototype.hide = function hide() {
  6708. if (this.dom.frame && this.dom.frame.parentNode) {
  6709. this.dom.frame.parentNode.removeChild(this.dom.frame);
  6710. return true;
  6711. }
  6712. else {
  6713. return false;
  6714. }
  6715. };
  6716. /**
  6717. * Show the component in the DOM (when not already visible).
  6718. * A repaint will be executed when the component is not visible
  6719. * @return {Boolean} changed
  6720. */
  6721. GroupSet.prototype.show = function show() {
  6722. if (!this.dom.frame || !this.dom.frame.parentNode) {
  6723. return this.repaint();
  6724. }
  6725. else {
  6726. return false;
  6727. }
  6728. };
  6729. /**
  6730. * Handle updated groups
  6731. * @param {Number[]} ids
  6732. * @private
  6733. */
  6734. GroupSet.prototype._onUpdate = function _onUpdate(ids) {
  6735. this._toQueue(ids, 'update');
  6736. };
  6737. /**
  6738. * Handle changed groups
  6739. * @param {Number[]} ids
  6740. * @private
  6741. */
  6742. GroupSet.prototype._onAdd = function _onAdd(ids) {
  6743. this._toQueue(ids, 'add');
  6744. };
  6745. /**
  6746. * Handle removed groups
  6747. * @param {Number[]} ids
  6748. * @private
  6749. */
  6750. GroupSet.prototype._onRemove = function _onRemove(ids) {
  6751. this._toQueue(ids, 'remove');
  6752. };
  6753. /**
  6754. * Put groups in the queue to be added/updated/remove
  6755. * @param {Number[]} ids
  6756. * @param {String} action can be 'add', 'update', 'remove'
  6757. */
  6758. GroupSet.prototype._toQueue = function _toQueue(ids, action) {
  6759. var queue = this.queue;
  6760. ids.forEach(function (id) {
  6761. queue[id] = action;
  6762. });
  6763. if (this.controller) {
  6764. //this.requestReflow();
  6765. this.requestRepaint();
  6766. }
  6767. };
  6768. /**
  6769. * Find the Group from an event target:
  6770. * searches for the attribute 'timeline-groupset' in the event target's element
  6771. * tree, then finds the right group in this groupset
  6772. * @param {Event} event
  6773. * @return {Group | null} group
  6774. */
  6775. GroupSet.groupFromTarget = function groupFromTarget (event) {
  6776. var groupset,
  6777. target = event.target;
  6778. while (target) {
  6779. if (target.hasOwnProperty('timeline-groupset')) {
  6780. groupset = target['timeline-groupset'];
  6781. break;
  6782. }
  6783. target = target.parentNode;
  6784. }
  6785. if (groupset) {
  6786. for (var groupId in groupset.groups) {
  6787. if (groupset.groups.hasOwnProperty(groupId)) {
  6788. var group = groupset.groups[groupId];
  6789. if (group.itemset && ItemSet.itemSetFromTarget(event) == group.itemset) {
  6790. return group;
  6791. }
  6792. }
  6793. }
  6794. }
  6795. return null;
  6796. };
  6797. /**
  6798. * Create a timeline visualization
  6799. * @param {HTMLElement} container
  6800. * @param {vis.DataSet | Array | google.visualization.DataTable} [items]
  6801. * @param {Object} [options] See Timeline.setOptions for the available options.
  6802. * @constructor
  6803. */
  6804. function Timeline (container, items, options) {
  6805. var me = this;
  6806. var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0);
  6807. this.options = {
  6808. orientation: 'bottom',
  6809. autoResize: true,
  6810. editable: false,
  6811. selectable: true,
  6812. snap: null, // will be specified after timeaxis is created
  6813. min: null,
  6814. max: null,
  6815. zoomMin: 10, // milliseconds
  6816. zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000, // milliseconds
  6817. // moveable: true, // TODO: option moveable
  6818. // zoomable: true, // TODO: option zoomable
  6819. showMinorLabels: true,
  6820. showMajorLabels: true,
  6821. showCurrentTime: false,
  6822. showCustomTime: false,
  6823. onAdd: function (item, callback) {
  6824. callback(item);
  6825. },
  6826. onUpdate: function (item, callback) {
  6827. callback(item);
  6828. },
  6829. onMove: function (item, callback) {
  6830. callback(item);
  6831. },
  6832. onRemove: function (item, callback) {
  6833. callback(item);
  6834. }
  6835. };
  6836. // controller
  6837. this.controller = new Controller();
  6838. // root panel
  6839. if (!container) {
  6840. throw new Error('No container element provided');
  6841. }
  6842. var rootOptions = Object.create(this.options);
  6843. rootOptions.height = function () {
  6844. // TODO: change to height
  6845. if (me.options.height) {
  6846. // fixed height
  6847. return me.options.height;
  6848. }
  6849. else {
  6850. // auto height
  6851. return (me.timeaxis.height + me.content.height) + 'px';
  6852. }
  6853. };
  6854. this.rootPanel = new RootPanel(container, rootOptions);
  6855. this.controller.add(this.rootPanel);
  6856. // single select (or unselect) when tapping an item
  6857. this.controller.on('tap', this._onSelectItem.bind(this));
  6858. // multi select when holding mouse/touch, or on ctrl+click
  6859. this.controller.on('hold', this._onMultiSelectItem.bind(this));
  6860. // add item on doubletap
  6861. this.controller.on('doubletap', this._onAddItem.bind(this));
  6862. // item panel
  6863. var itemOptions = Object.create(this.options);
  6864. itemOptions.left = function () {
  6865. return me.labelPanel.width;
  6866. };
  6867. itemOptions.width = function () {
  6868. return me.rootPanel.width - me.labelPanel.width;
  6869. };
  6870. itemOptions.top = null;
  6871. itemOptions.height = null;
  6872. this.itemPanel = new Panel(this.rootPanel, [], itemOptions);
  6873. this.controller.add(this.itemPanel);
  6874. // label panel
  6875. var labelOptions = Object.create(this.options);
  6876. labelOptions.top = null;
  6877. labelOptions.left = null;
  6878. labelOptions.height = null;
  6879. labelOptions.width = function () {
  6880. if (me.content && typeof me.content.getLabelsWidth === 'function') {
  6881. return me.content.getLabelsWidth();
  6882. }
  6883. else {
  6884. return 0;
  6885. }
  6886. };
  6887. this.labelPanel = new Panel(this.rootPanel, [], labelOptions);
  6888. this.controller.add(this.labelPanel);
  6889. // range
  6890. var rangeOptions = Object.create(this.options);
  6891. this.range = new Range(rangeOptions);
  6892. this.range.setRange(
  6893. now.clone().add('days', -3).valueOf(),
  6894. now.clone().add('days', 4).valueOf()
  6895. );
  6896. this.range.subscribe(this.controller, this.rootPanel, 'move', 'horizontal');
  6897. this.range.subscribe(this.controller, this.rootPanel, 'zoom', 'horizontal');
  6898. this.range.on('rangechange', function (properties) {
  6899. var force = true;
  6900. me.controller.emit('rangechange', properties);
  6901. me.controller.emit('request-reflow', force);
  6902. });
  6903. this.range.on('rangechanged', function (properties) {
  6904. var force = true;
  6905. me.controller.emit('rangechanged', properties);
  6906. me.controller.emit('request-reflow', force);
  6907. });
  6908. // time axis
  6909. var timeaxisOptions = Object.create(rootOptions);
  6910. timeaxisOptions.range = this.range;
  6911. timeaxisOptions.left = null;
  6912. timeaxisOptions.top = null;
  6913. timeaxisOptions.width = '100%';
  6914. timeaxisOptions.height = null;
  6915. this.timeaxis = new TimeAxis(this.itemPanel, [], timeaxisOptions);
  6916. this.timeaxis.setRange(this.range);
  6917. this.controller.add(this.timeaxis);
  6918. this.options.snap = this.timeaxis.snap.bind(this.timeaxis);
  6919. // current time bar
  6920. this.currenttime = new CurrentTime(this.timeaxis, [], rootOptions);
  6921. this.controller.add(this.currenttime);
  6922. // custom time bar
  6923. this.customtime = new CustomTime(this.timeaxis, [], rootOptions);
  6924. this.controller.add(this.customtime);
  6925. // create groupset
  6926. this.setGroups(null);
  6927. this.itemsData = null; // DataSet
  6928. this.groupsData = null; // DataSet
  6929. // apply options
  6930. if (options) {
  6931. this.setOptions(options);
  6932. }
  6933. // create itemset and groupset
  6934. if (items) {
  6935. this.setItems(items);
  6936. }
  6937. }
  6938. /**
  6939. * Add an event listener to the timeline
  6940. * @param {String} event Available events: select, rangechange, rangechanged,
  6941. * timechange, timechanged
  6942. * @param {function} callback
  6943. */
  6944. Timeline.prototype.on = function on (event, callback) {
  6945. this.controller.on(event, callback);
  6946. };
  6947. /**
  6948. * Add an event listener from the timeline
  6949. * @param {String} event
  6950. * @param {function} callback
  6951. */
  6952. Timeline.prototype.off = function off (event, callback) {
  6953. this.controller.off(event, callback);
  6954. };
  6955. /**
  6956. * Set options
  6957. * @param {Object} options TODO: describe the available options
  6958. */
  6959. Timeline.prototype.setOptions = function (options) {
  6960. util.extend(this.options, options);
  6961. // force update of range (apply new min/max etc.)
  6962. // both start and end are optional
  6963. this.range.setRange(options.start, options.end);
  6964. if ('editable' in options || 'selectable' in options) {
  6965. if (this.options.selectable) {
  6966. // force update of selection
  6967. this.setSelection(this.getSelection());
  6968. }
  6969. else {
  6970. // remove selection
  6971. this.setSelection([]);
  6972. }
  6973. }
  6974. // validate the callback functions
  6975. var validateCallback = (function (fn) {
  6976. if (!(this.options[fn] instanceof Function) || this.options[fn].length != 2) {
  6977. throw new Error('option ' + fn + ' must be a function ' + fn + '(item, callback)');
  6978. }
  6979. }).bind(this);
  6980. ['onAdd', 'onUpdate', 'onRemove', 'onMove'].forEach(validateCallback);
  6981. this.controller.reflow();
  6982. this.controller.repaint();
  6983. };
  6984. /**
  6985. * Set a custom time bar
  6986. * @param {Date} time
  6987. */
  6988. Timeline.prototype.setCustomTime = function (time) {
  6989. if (!this.customtime) {
  6990. throw new Error('Cannot get custom time: Custom time bar is not enabled');
  6991. }
  6992. this.customtime.setCustomTime(time);
  6993. };
  6994. /**
  6995. * Retrieve the current custom time.
  6996. * @return {Date} customTime
  6997. */
  6998. Timeline.prototype.getCustomTime = function() {
  6999. if (!this.customtime) {
  7000. throw new Error('Cannot get custom time: Custom time bar is not enabled');
  7001. }
  7002. return this.customtime.getCustomTime();
  7003. };
  7004. /**
  7005. * Set items
  7006. * @param {vis.DataSet | Array | google.visualization.DataTable | null} items
  7007. */
  7008. Timeline.prototype.setItems = function(items) {
  7009. var initialLoad = (this.itemsData == null);
  7010. // convert to type DataSet when needed
  7011. var newDataSet;
  7012. if (!items) {
  7013. newDataSet = null;
  7014. }
  7015. else if (items instanceof DataSet) {
  7016. newDataSet = items;
  7017. }
  7018. if (!(items instanceof DataSet)) {
  7019. newDataSet = new DataSet({
  7020. convert: {
  7021. start: 'Date',
  7022. end: 'Date'
  7023. }
  7024. });
  7025. newDataSet.add(items);
  7026. }
  7027. // set items
  7028. this.itemsData = newDataSet;
  7029. this.content.setItems(newDataSet);
  7030. if (initialLoad && (this.options.start == undefined || this.options.end == undefined)) {
  7031. // apply the data range as range
  7032. var dataRange = this.getItemRange();
  7033. // add 5% space on both sides
  7034. var start = dataRange.min;
  7035. var end = dataRange.max;
  7036. if (start != null && end != null) {
  7037. var interval = (end.valueOf() - start.valueOf());
  7038. if (interval <= 0) {
  7039. // prevent an empty interval
  7040. interval = 24 * 60 * 60 * 1000; // 1 day
  7041. }
  7042. start = new Date(start.valueOf() - interval * 0.05);
  7043. end = new Date(end.valueOf() + interval * 0.05);
  7044. }
  7045. // override specified start and/or end date
  7046. if (this.options.start != undefined) {
  7047. start = util.convert(this.options.start, 'Date');
  7048. }
  7049. if (this.options.end != undefined) {
  7050. end = util.convert(this.options.end, 'Date');
  7051. }
  7052. // apply range if there is a min or max available
  7053. if (start != null || end != null) {
  7054. this.range.setRange(start, end);
  7055. }
  7056. }
  7057. };
  7058. /**
  7059. * Set groups
  7060. * @param {vis.DataSet | Array | google.visualization.DataTable} groups
  7061. */
  7062. Timeline.prototype.setGroups = function(groups) {
  7063. var me = this;
  7064. this.groupsData = groups;
  7065. // switch content type between ItemSet or GroupSet when needed
  7066. var Type = this.groupsData ? GroupSet : ItemSet;
  7067. if (!(this.content instanceof Type)) {
  7068. // remove old content set
  7069. if (this.content) {
  7070. this.content.hide();
  7071. if (this.content.setItems) {
  7072. this.content.setItems(); // disconnect from items
  7073. }
  7074. if (this.content.setGroups) {
  7075. this.content.setGroups(); // disconnect from groups
  7076. }
  7077. this.controller.remove(this.content);
  7078. }
  7079. // create new content set
  7080. var options = Object.create(this.options);
  7081. util.extend(options, {
  7082. top: function () {
  7083. if (me.options.orientation == 'top') {
  7084. return me.timeaxis.height;
  7085. }
  7086. else {
  7087. return me.itemPanel.height - me.timeaxis.height - me.content.height;
  7088. }
  7089. },
  7090. left: null,
  7091. width: '100%',
  7092. height: function () {
  7093. if (me.options.height) {
  7094. // fixed height
  7095. return me.itemPanel.height - me.timeaxis.height;
  7096. }
  7097. else {
  7098. // auto height
  7099. return null;
  7100. }
  7101. },
  7102. maxHeight: function () {
  7103. // TODO: change maxHeight to be a css string like '100%' or '300px'
  7104. if (me.options.maxHeight) {
  7105. if (!util.isNumber(me.options.maxHeight)) {
  7106. throw new TypeError('Number expected for property maxHeight');
  7107. }
  7108. return me.options.maxHeight - me.timeaxis.height;
  7109. }
  7110. else {
  7111. return null;
  7112. }
  7113. },
  7114. labelContainer: function () {
  7115. return me.labelPanel.getContainer();
  7116. }
  7117. });
  7118. this.content = new Type(this.itemPanel, [this.timeaxis], options);
  7119. if (this.content.setRange) {
  7120. this.content.setRange(this.range);
  7121. }
  7122. if (this.content.setItems) {
  7123. this.content.setItems(this.itemsData);
  7124. }
  7125. if (this.content.setGroups) {
  7126. this.content.setGroups(this.groupsData);
  7127. }
  7128. this.controller.add(this.content);
  7129. }
  7130. };
  7131. /**
  7132. * Get the data range of the item set.
  7133. * @returns {{min: Date, max: Date}} range A range with a start and end Date.
  7134. * When no minimum is found, min==null
  7135. * When no maximum is found, max==null
  7136. */
  7137. Timeline.prototype.getItemRange = function getItemRange() {
  7138. // calculate min from start filed
  7139. var itemsData = this.itemsData,
  7140. min = null,
  7141. max = null;
  7142. if (itemsData) {
  7143. // calculate the minimum value of the field 'start'
  7144. var minItem = itemsData.min('start');
  7145. min = minItem ? minItem.start.valueOf() : null;
  7146. // calculate maximum value of fields 'start' and 'end'
  7147. var maxStartItem = itemsData.max('start');
  7148. if (maxStartItem) {
  7149. max = maxStartItem.start.valueOf();
  7150. }
  7151. var maxEndItem = itemsData.max('end');
  7152. if (maxEndItem) {
  7153. if (max == null) {
  7154. max = maxEndItem.end.valueOf();
  7155. }
  7156. else {
  7157. max = Math.max(max, maxEndItem.end.valueOf());
  7158. }
  7159. }
  7160. }
  7161. return {
  7162. min: (min != null) ? new Date(min) : null,
  7163. max: (max != null) ? new Date(max) : null
  7164. };
  7165. };
  7166. /**
  7167. * Set selected items by their id. Replaces the current selection
  7168. * Unknown id's are silently ignored.
  7169. * @param {Array} [ids] An array with zero or more id's of the items to be
  7170. * selected. If ids is an empty array, all items will be
  7171. * unselected.
  7172. */
  7173. Timeline.prototype.setSelection = function setSelection (ids) {
  7174. if (this.content) this.content.setSelection(ids);
  7175. };
  7176. /**
  7177. * Get the selected items by their id
  7178. * @return {Array} ids The ids of the selected items
  7179. */
  7180. Timeline.prototype.getSelection = function getSelection() {
  7181. return this.content ? this.content.getSelection() : [];
  7182. };
  7183. /**
  7184. * Set the visible window. Both parameters are optional, you can change only
  7185. * start or only end.
  7186. * @param {Date | Number | String} [start] Start date of visible window
  7187. * @param {Date | Number | String} [end] End date of visible window
  7188. */
  7189. Timeline.prototype.setWindow = function setWindow(start, end) {
  7190. this.range.setRange(start, end);
  7191. };
  7192. /**
  7193. * Get the visible window
  7194. * @return {{start: Date, end: Date}} Visible range
  7195. */
  7196. Timeline.prototype.getWindow = function setWindow() {
  7197. var range = this.range.getRange();
  7198. return {
  7199. start: new Date(range.start),
  7200. end: new Date(range.end)
  7201. };
  7202. };
  7203. /**
  7204. * Handle selecting/deselecting an item when tapping it
  7205. * @param {Event} event
  7206. * @private
  7207. */
  7208. // TODO: move this function to ItemSet
  7209. Timeline.prototype._onSelectItem = function (event) {
  7210. if (!this.options.selectable) return;
  7211. var ctrlKey = event.gesture.srcEvent && event.gesture.srcEvent.ctrlKey;
  7212. var shiftKey = event.gesture.srcEvent && event.gesture.srcEvent.shiftKey;
  7213. if (ctrlKey || shiftKey) {
  7214. this._onMultiSelectItem(event);
  7215. return;
  7216. }
  7217. var item = ItemSet.itemFromTarget(event);
  7218. var selection = item ? [item.id] : [];
  7219. this.setSelection(selection);
  7220. this.controller.emit('select', {
  7221. items: this.getSelection()
  7222. });
  7223. event.stopPropagation();
  7224. };
  7225. /**
  7226. * Handle creation and updates of an item on double tap
  7227. * @param event
  7228. * @private
  7229. */
  7230. Timeline.prototype._onAddItem = function (event) {
  7231. if (!this.options.selectable) return;
  7232. if (!this.options.editable) return;
  7233. var me = this,
  7234. item = ItemSet.itemFromTarget(event);
  7235. if (item) {
  7236. // update item
  7237. // execute async handler to update the item (or cancel it)
  7238. var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset
  7239. this.options.onUpdate(itemData, function (itemData) {
  7240. if (itemData) {
  7241. me.itemsData.update(itemData);
  7242. }
  7243. });
  7244. }
  7245. else {
  7246. // add item
  7247. var xAbs = vis.util.getAbsoluteLeft(this.rootPanel.frame);
  7248. var x = event.gesture.center.pageX - xAbs;
  7249. var newItem = {
  7250. start: this.timeaxis.snap(this._toTime(x)),
  7251. content: 'new item'
  7252. };
  7253. var id = util.randomUUID();
  7254. newItem[this.itemsData.fieldId] = id;
  7255. var group = GroupSet.groupFromTarget(event);
  7256. if (group) {
  7257. newItem.group = group.groupId;
  7258. }
  7259. // execute async handler to customize (or cancel) adding an item
  7260. this.options.onAdd(newItem, function (item) {
  7261. if (item) {
  7262. me.itemsData.add(newItem);
  7263. // select the created item after it is repainted
  7264. me.controller.once('repaint', function () {
  7265. me.setSelection([id]);
  7266. me.controller.emit('select', {
  7267. items: me.getSelection()
  7268. });
  7269. }.bind(me));
  7270. }
  7271. });
  7272. }
  7273. };
  7274. /**
  7275. * Handle selecting/deselecting multiple items when holding an item
  7276. * @param {Event} event
  7277. * @private
  7278. */
  7279. // TODO: move this function to ItemSet
  7280. Timeline.prototype._onMultiSelectItem = function (event) {
  7281. if (!this.options.selectable) return;
  7282. var selection,
  7283. item = ItemSet.itemFromTarget(event);
  7284. if (item) {
  7285. // multi select items
  7286. selection = this.getSelection(); // current selection
  7287. var index = selection.indexOf(item.id);
  7288. if (index == -1) {
  7289. // item is not yet selected -> select it
  7290. selection.push(item.id);
  7291. }
  7292. else {
  7293. // item is already selected -> deselect it
  7294. selection.splice(index, 1);
  7295. }
  7296. this.setSelection(selection);
  7297. this.controller.emit('select', {
  7298. items: this.getSelection()
  7299. });
  7300. event.stopPropagation();
  7301. }
  7302. };
  7303. /**
  7304. * Convert a position on screen (pixels) to a datetime
  7305. * @param {int} x Position on the screen in pixels
  7306. * @return {Date} time The datetime the corresponds with given position x
  7307. * @private
  7308. */
  7309. Timeline.prototype._toTime = function _toTime(x) {
  7310. var conversion = this.range.conversion(this.content.width);
  7311. return new Date(x / conversion.scale + conversion.offset);
  7312. };
  7313. /**
  7314. * Convert a datetime (Date object) into a position on the screen
  7315. * @param {Date} time A date
  7316. * @return {int} x The position on the screen in pixels which corresponds
  7317. * with the given date.
  7318. * @private
  7319. */
  7320. Timeline.prototype._toScreen = function _toScreen(time) {
  7321. var conversion = this.range.conversion(this.content.width);
  7322. return (time.valueOf() - conversion.offset) * conversion.scale;
  7323. };
  7324. (function(exports) {
  7325. /**
  7326. * Parse a text source containing data in DOT language into a JSON object.
  7327. * The object contains two lists: one with nodes and one with edges.
  7328. *
  7329. * DOT language reference: http://www.graphviz.org/doc/info/lang.html
  7330. *
  7331. * @param {String} data Text containing a graph in DOT-notation
  7332. * @return {Object} graph An object containing two parameters:
  7333. * {Object[]} nodes
  7334. * {Object[]} edges
  7335. */
  7336. function parseDOT (data) {
  7337. dot = data;
  7338. return parseGraph();
  7339. }
  7340. // token types enumeration
  7341. var TOKENTYPE = {
  7342. NULL : 0,
  7343. DELIMITER : 1,
  7344. IDENTIFIER: 2,
  7345. UNKNOWN : 3
  7346. };
  7347. // map with all delimiters
  7348. var DELIMITERS = {
  7349. '{': true,
  7350. '}': true,
  7351. '[': true,
  7352. ']': true,
  7353. ';': true,
  7354. '=': true,
  7355. ',': true,
  7356. '->': true,
  7357. '--': true
  7358. };
  7359. var dot = ''; // current dot file
  7360. var index = 0; // current index in dot file
  7361. var c = ''; // current token character in expr
  7362. var token = ''; // current token
  7363. var tokenType = TOKENTYPE.NULL; // type of the token
  7364. /**
  7365. * Get the first character from the dot file.
  7366. * The character is stored into the char c. If the end of the dot file is
  7367. * reached, the function puts an empty string in c.
  7368. */
  7369. function first() {
  7370. index = 0;
  7371. c = dot.charAt(0);
  7372. }
  7373. /**
  7374. * Get the next character from the dot file.
  7375. * The character is stored into the char c. If the end of the dot file is
  7376. * reached, the function puts an empty string in c.
  7377. */
  7378. function next() {
  7379. index++;
  7380. c = dot.charAt(index);
  7381. }
  7382. /**
  7383. * Preview the next character from the dot file.
  7384. * @return {String} cNext
  7385. */
  7386. function nextPreview() {
  7387. return dot.charAt(index + 1);
  7388. }
  7389. /**
  7390. * Test whether given character is alphabetic or numeric
  7391. * @param {String} c
  7392. * @return {Boolean} isAlphaNumeric
  7393. */
  7394. var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/;
  7395. function isAlphaNumeric(c) {
  7396. return regexAlphaNumeric.test(c);
  7397. }
  7398. /**
  7399. * Merge all properties of object b into object b
  7400. * @param {Object} a
  7401. * @param {Object} b
  7402. * @return {Object} a
  7403. */
  7404. function merge (a, b) {
  7405. if (!a) {
  7406. a = {};
  7407. }
  7408. if (b) {
  7409. for (var name in b) {
  7410. if (b.hasOwnProperty(name)) {
  7411. a[name] = b[name];
  7412. }
  7413. }
  7414. }
  7415. return a;
  7416. }
  7417. /**
  7418. * Set a value in an object, where the provided parameter name can be a
  7419. * path with nested parameters. For example:
  7420. *
  7421. * var obj = {a: 2};
  7422. * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}}
  7423. *
  7424. * @param {Object} obj
  7425. * @param {String} path A parameter name or dot-separated parameter path,
  7426. * like "color.highlight.border".
  7427. * @param {*} value
  7428. */
  7429. function setValue(obj, path, value) {
  7430. var keys = path.split('.');
  7431. var o = obj;
  7432. while (keys.length) {
  7433. var key = keys.shift();
  7434. if (keys.length) {
  7435. // this isn't the end point
  7436. if (!o[key]) {
  7437. o[key] = {};
  7438. }
  7439. o = o[key];
  7440. }
  7441. else {
  7442. // this is the end point
  7443. o[key] = value;
  7444. }
  7445. }
  7446. }
  7447. /**
  7448. * Add a node to a graph object. If there is already a node with
  7449. * the same id, their attributes will be merged.
  7450. * @param {Object} graph
  7451. * @param {Object} node
  7452. */
  7453. function addNode(graph, node) {
  7454. var i, len;
  7455. var current = null;
  7456. // find root graph (in case of subgraph)
  7457. var graphs = [graph]; // list with all graphs from current graph to root graph
  7458. var root = graph;
  7459. while (root.parent) {
  7460. graphs.push(root.parent);
  7461. root = root.parent;
  7462. }
  7463. // find existing node (at root level) by its id
  7464. if (root.nodes) {
  7465. for (i = 0, len = root.nodes.length; i < len; i++) {
  7466. if (node.id === root.nodes[i].id) {
  7467. current = root.nodes[i];
  7468. break;
  7469. }
  7470. }
  7471. }
  7472. if (!current) {
  7473. // this is a new node
  7474. current = {
  7475. id: node.id
  7476. };
  7477. if (graph.node) {
  7478. // clone default attributes
  7479. current.attr = merge(current.attr, graph.node);
  7480. }
  7481. }
  7482. // add node to this (sub)graph and all its parent graphs
  7483. for (i = graphs.length - 1; i >= 0; i--) {
  7484. var g = graphs[i];
  7485. if (!g.nodes) {
  7486. g.nodes = [];
  7487. }
  7488. if (g.nodes.indexOf(current) == -1) {
  7489. g.nodes.push(current);
  7490. }
  7491. }
  7492. // merge attributes
  7493. if (node.attr) {
  7494. current.attr = merge(current.attr, node.attr);
  7495. }
  7496. }
  7497. /**
  7498. * Add an edge to a graph object
  7499. * @param {Object} graph
  7500. * @param {Object} edge
  7501. */
  7502. function addEdge(graph, edge) {
  7503. if (!graph.edges) {
  7504. graph.edges = [];
  7505. }
  7506. graph.edges.push(edge);
  7507. if (graph.edge) {
  7508. var attr = merge({}, graph.edge); // clone default attributes
  7509. edge.attr = merge(attr, edge.attr); // merge attributes
  7510. }
  7511. }
  7512. /**
  7513. * Create an edge to a graph object
  7514. * @param {Object} graph
  7515. * @param {String | Number | Object} from
  7516. * @param {String | Number | Object} to
  7517. * @param {String} type
  7518. * @param {Object | null} attr
  7519. * @return {Object} edge
  7520. */
  7521. function createEdge(graph, from, to, type, attr) {
  7522. var edge = {
  7523. from: from,
  7524. to: to,
  7525. type: type
  7526. };
  7527. if (graph.edge) {
  7528. edge.attr = merge({}, graph.edge); // clone default attributes
  7529. }
  7530. edge.attr = merge(edge.attr || {}, attr); // merge attributes
  7531. return edge;
  7532. }
  7533. /**
  7534. * Get next token in the current dot file.
  7535. * The token and token type are available as token and tokenType
  7536. */
  7537. function getToken() {
  7538. tokenType = TOKENTYPE.NULL;
  7539. token = '';
  7540. // skip over whitespaces
  7541. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  7542. next();
  7543. }
  7544. do {
  7545. var isComment = false;
  7546. // skip comment
  7547. if (c == '#') {
  7548. // find the previous non-space character
  7549. var i = index - 1;
  7550. while (dot.charAt(i) == ' ' || dot.charAt(i) == '\t') {
  7551. i--;
  7552. }
  7553. if (dot.charAt(i) == '\n' || dot.charAt(i) == '') {
  7554. // the # is at the start of a line, this is indeed a line comment
  7555. while (c != '' && c != '\n') {
  7556. next();
  7557. }
  7558. isComment = true;
  7559. }
  7560. }
  7561. if (c == '/' && nextPreview() == '/') {
  7562. // skip line comment
  7563. while (c != '' && c != '\n') {
  7564. next();
  7565. }
  7566. isComment = true;
  7567. }
  7568. if (c == '/' && nextPreview() == '*') {
  7569. // skip block comment
  7570. while (c != '') {
  7571. if (c == '*' && nextPreview() == '/') {
  7572. // end of block comment found. skip these last two characters
  7573. next();
  7574. next();
  7575. break;
  7576. }
  7577. else {
  7578. next();
  7579. }
  7580. }
  7581. isComment = true;
  7582. }
  7583. // skip over whitespaces
  7584. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  7585. next();
  7586. }
  7587. }
  7588. while (isComment);
  7589. // check for end of dot file
  7590. if (c == '') {
  7591. // token is still empty
  7592. tokenType = TOKENTYPE.DELIMITER;
  7593. return;
  7594. }
  7595. // check for delimiters consisting of 2 characters
  7596. var c2 = c + nextPreview();
  7597. if (DELIMITERS[c2]) {
  7598. tokenType = TOKENTYPE.DELIMITER;
  7599. token = c2;
  7600. next();
  7601. next();
  7602. return;
  7603. }
  7604. // check for delimiters consisting of 1 character
  7605. if (DELIMITERS[c]) {
  7606. tokenType = TOKENTYPE.DELIMITER;
  7607. token = c;
  7608. next();
  7609. return;
  7610. }
  7611. // check for an identifier (number or string)
  7612. // TODO: more precise parsing of numbers/strings (and the port separator ':')
  7613. if (isAlphaNumeric(c) || c == '-') {
  7614. token += c;
  7615. next();
  7616. while (isAlphaNumeric(c)) {
  7617. token += c;
  7618. next();
  7619. }
  7620. if (token == 'false') {
  7621. token = false; // convert to boolean
  7622. }
  7623. else if (token == 'true') {
  7624. token = true; // convert to boolean
  7625. }
  7626. else if (!isNaN(Number(token))) {
  7627. token = Number(token); // convert to number
  7628. }
  7629. tokenType = TOKENTYPE.IDENTIFIER;
  7630. return;
  7631. }
  7632. // check for a string enclosed by double quotes
  7633. if (c == '"') {
  7634. next();
  7635. while (c != '' && (c != '"' || (c == '"' && nextPreview() == '"'))) {
  7636. token += c;
  7637. if (c == '"') { // skip the escape character
  7638. next();
  7639. }
  7640. next();
  7641. }
  7642. if (c != '"') {
  7643. throw newSyntaxError('End of string " expected');
  7644. }
  7645. next();
  7646. tokenType = TOKENTYPE.IDENTIFIER;
  7647. return;
  7648. }
  7649. // something unknown is found, wrong characters, a syntax error
  7650. tokenType = TOKENTYPE.UNKNOWN;
  7651. while (c != '') {
  7652. token += c;
  7653. next();
  7654. }
  7655. throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"');
  7656. }
  7657. /**
  7658. * Parse a graph.
  7659. * @returns {Object} graph
  7660. */
  7661. function parseGraph() {
  7662. var graph = {};
  7663. first();
  7664. getToken();
  7665. // optional strict keyword
  7666. if (token == 'strict') {
  7667. graph.strict = true;
  7668. getToken();
  7669. }
  7670. // graph or digraph keyword
  7671. if (token == 'graph' || token == 'digraph') {
  7672. graph.type = token;
  7673. getToken();
  7674. }
  7675. // optional graph id
  7676. if (tokenType == TOKENTYPE.IDENTIFIER) {
  7677. graph.id = token;
  7678. getToken();
  7679. }
  7680. // open angle bracket
  7681. if (token != '{') {
  7682. throw newSyntaxError('Angle bracket { expected');
  7683. }
  7684. getToken();
  7685. // statements
  7686. parseStatements(graph);
  7687. // close angle bracket
  7688. if (token != '}') {
  7689. throw newSyntaxError('Angle bracket } expected');
  7690. }
  7691. getToken();
  7692. // end of file
  7693. if (token !== '') {
  7694. throw newSyntaxError('End of file expected');
  7695. }
  7696. getToken();
  7697. // remove temporary default properties
  7698. delete graph.node;
  7699. delete graph.edge;
  7700. delete graph.graph;
  7701. return graph;
  7702. }
  7703. /**
  7704. * Parse a list with statements.
  7705. * @param {Object} graph
  7706. */
  7707. function parseStatements (graph) {
  7708. while (token !== '' && token != '}') {
  7709. parseStatement(graph);
  7710. if (token == ';') {
  7711. getToken();
  7712. }
  7713. }
  7714. }
  7715. /**
  7716. * Parse a single statement. Can be a an attribute statement, node
  7717. * statement, a series of node statements and edge statements, or a
  7718. * parameter.
  7719. * @param {Object} graph
  7720. */
  7721. function parseStatement(graph) {
  7722. // parse subgraph
  7723. var subgraph = parseSubgraph(graph);
  7724. if (subgraph) {
  7725. // edge statements
  7726. parseEdge(graph, subgraph);
  7727. return;
  7728. }
  7729. // parse an attribute statement
  7730. var attr = parseAttributeStatement(graph);
  7731. if (attr) {
  7732. return;
  7733. }
  7734. // parse node
  7735. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7736. throw newSyntaxError('Identifier expected');
  7737. }
  7738. var id = token; // id can be a string or a number
  7739. getToken();
  7740. if (token == '=') {
  7741. // id statement
  7742. getToken();
  7743. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7744. throw newSyntaxError('Identifier expected');
  7745. }
  7746. graph[id] = token;
  7747. getToken();
  7748. // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] "
  7749. }
  7750. else {
  7751. parseNodeStatement(graph, id);
  7752. }
  7753. }
  7754. /**
  7755. * Parse a subgraph
  7756. * @param {Object} graph parent graph object
  7757. * @return {Object | null} subgraph
  7758. */
  7759. function parseSubgraph (graph) {
  7760. var subgraph = null;
  7761. // optional subgraph keyword
  7762. if (token == 'subgraph') {
  7763. subgraph = {};
  7764. subgraph.type = 'subgraph';
  7765. getToken();
  7766. // optional graph id
  7767. if (tokenType == TOKENTYPE.IDENTIFIER) {
  7768. subgraph.id = token;
  7769. getToken();
  7770. }
  7771. }
  7772. // open angle bracket
  7773. if (token == '{') {
  7774. getToken();
  7775. if (!subgraph) {
  7776. subgraph = {};
  7777. }
  7778. subgraph.parent = graph;
  7779. subgraph.node = graph.node;
  7780. subgraph.edge = graph.edge;
  7781. subgraph.graph = graph.graph;
  7782. // statements
  7783. parseStatements(subgraph);
  7784. // close angle bracket
  7785. if (token != '}') {
  7786. throw newSyntaxError('Angle bracket } expected');
  7787. }
  7788. getToken();
  7789. // remove temporary default properties
  7790. delete subgraph.node;
  7791. delete subgraph.edge;
  7792. delete subgraph.graph;
  7793. delete subgraph.parent;
  7794. // register at the parent graph
  7795. if (!graph.subgraphs) {
  7796. graph.subgraphs = [];
  7797. }
  7798. graph.subgraphs.push(subgraph);
  7799. }
  7800. return subgraph;
  7801. }
  7802. /**
  7803. * parse an attribute statement like "node [shape=circle fontSize=16]".
  7804. * Available keywords are 'node', 'edge', 'graph'.
  7805. * The previous list with default attributes will be replaced
  7806. * @param {Object} graph
  7807. * @returns {String | null} keyword Returns the name of the parsed attribute
  7808. * (node, edge, graph), or null if nothing
  7809. * is parsed.
  7810. */
  7811. function parseAttributeStatement (graph) {
  7812. // attribute statements
  7813. if (token == 'node') {
  7814. getToken();
  7815. // node attributes
  7816. graph.node = parseAttributeList();
  7817. return 'node';
  7818. }
  7819. else if (token == 'edge') {
  7820. getToken();
  7821. // edge attributes
  7822. graph.edge = parseAttributeList();
  7823. return 'edge';
  7824. }
  7825. else if (token == 'graph') {
  7826. getToken();
  7827. // graph attributes
  7828. graph.graph = parseAttributeList();
  7829. return 'graph';
  7830. }
  7831. return null;
  7832. }
  7833. /**
  7834. * parse a node statement
  7835. * @param {Object} graph
  7836. * @param {String | Number} id
  7837. */
  7838. function parseNodeStatement(graph, id) {
  7839. // node statement
  7840. var node = {
  7841. id: id
  7842. };
  7843. var attr = parseAttributeList();
  7844. if (attr) {
  7845. node.attr = attr;
  7846. }
  7847. addNode(graph, node);
  7848. // edge statements
  7849. parseEdge(graph, id);
  7850. }
  7851. /**
  7852. * Parse an edge or a series of edges
  7853. * @param {Object} graph
  7854. * @param {String | Number} from Id of the from node
  7855. */
  7856. function parseEdge(graph, from) {
  7857. while (token == '->' || token == '--') {
  7858. var to;
  7859. var type = token;
  7860. getToken();
  7861. var subgraph = parseSubgraph(graph);
  7862. if (subgraph) {
  7863. to = subgraph;
  7864. }
  7865. else {
  7866. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7867. throw newSyntaxError('Identifier or subgraph expected');
  7868. }
  7869. to = token;
  7870. addNode(graph, {
  7871. id: to
  7872. });
  7873. getToken();
  7874. }
  7875. // parse edge attributes
  7876. var attr = parseAttributeList();
  7877. // create edge
  7878. var edge = createEdge(graph, from, to, type, attr);
  7879. addEdge(graph, edge);
  7880. from = to;
  7881. }
  7882. }
  7883. /**
  7884. * Parse a set with attributes,
  7885. * for example [label="1.000", shape=solid]
  7886. * @return {Object | null} attr
  7887. */
  7888. function parseAttributeList() {
  7889. var attr = null;
  7890. while (token == '[') {
  7891. getToken();
  7892. attr = {};
  7893. while (token !== '' && token != ']') {
  7894. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7895. throw newSyntaxError('Attribute name expected');
  7896. }
  7897. var name = token;
  7898. getToken();
  7899. if (token != '=') {
  7900. throw newSyntaxError('Equal sign = expected');
  7901. }
  7902. getToken();
  7903. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7904. throw newSyntaxError('Attribute value expected');
  7905. }
  7906. var value = token;
  7907. setValue(attr, name, value); // name can be a path
  7908. getToken();
  7909. if (token ==',') {
  7910. getToken();
  7911. }
  7912. }
  7913. if (token != ']') {
  7914. throw newSyntaxError('Bracket ] expected');
  7915. }
  7916. getToken();
  7917. }
  7918. return attr;
  7919. }
  7920. /**
  7921. * Create a syntax error with extra information on current token and index.
  7922. * @param {String} message
  7923. * @returns {SyntaxError} err
  7924. */
  7925. function newSyntaxError(message) {
  7926. return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')');
  7927. }
  7928. /**
  7929. * Chop off text after a maximum length
  7930. * @param {String} text
  7931. * @param {Number} maxLength
  7932. * @returns {String}
  7933. */
  7934. function chop (text, maxLength) {
  7935. return (text.length <= maxLength) ? text : (text.substr(0, 27) + '...');
  7936. }
  7937. /**
  7938. * Execute a function fn for each pair of elements in two arrays
  7939. * @param {Array | *} array1
  7940. * @param {Array | *} array2
  7941. * @param {function} fn
  7942. */
  7943. function forEach2(array1, array2, fn) {
  7944. if (array1 instanceof Array) {
  7945. array1.forEach(function (elem1) {
  7946. if (array2 instanceof Array) {
  7947. array2.forEach(function (elem2) {
  7948. fn(elem1, elem2);
  7949. });
  7950. }
  7951. else {
  7952. fn(elem1, array2);
  7953. }
  7954. });
  7955. }
  7956. else {
  7957. if (array2 instanceof Array) {
  7958. array2.forEach(function (elem2) {
  7959. fn(array1, elem2);
  7960. });
  7961. }
  7962. else {
  7963. fn(array1, array2);
  7964. }
  7965. }
  7966. }
  7967. /**
  7968. * Convert a string containing a graph in DOT language into a map containing
  7969. * with nodes and edges in the format of graph.
  7970. * @param {String} data Text containing a graph in DOT-notation
  7971. * @return {Object} graphData
  7972. */
  7973. function DOTToGraph (data) {
  7974. // parse the DOT file
  7975. var dotData = parseDOT(data);
  7976. var graphData = {
  7977. nodes: [],
  7978. edges: [],
  7979. options: {}
  7980. };
  7981. // copy the nodes
  7982. if (dotData.nodes) {
  7983. dotData.nodes.forEach(function (dotNode) {
  7984. var graphNode = {
  7985. id: dotNode.id,
  7986. label: String(dotNode.label || dotNode.id)
  7987. };
  7988. merge(graphNode, dotNode.attr);
  7989. if (graphNode.image) {
  7990. graphNode.shape = 'image';
  7991. }
  7992. graphData.nodes.push(graphNode);
  7993. });
  7994. }
  7995. // copy the edges
  7996. if (dotData.edges) {
  7997. /**
  7998. * Convert an edge in DOT format to an edge with VisGraph format
  7999. * @param {Object} dotEdge
  8000. * @returns {Object} graphEdge
  8001. */
  8002. function convertEdge(dotEdge) {
  8003. var graphEdge = {
  8004. from: dotEdge.from,
  8005. to: dotEdge.to
  8006. };
  8007. merge(graphEdge, dotEdge.attr);
  8008. graphEdge.style = (dotEdge.type == '->') ? 'arrow' : 'line';
  8009. return graphEdge;
  8010. }
  8011. dotData.edges.forEach(function (dotEdge) {
  8012. var from, to;
  8013. if (dotEdge.from instanceof Object) {
  8014. from = dotEdge.from.nodes;
  8015. }
  8016. else {
  8017. from = {
  8018. id: dotEdge.from
  8019. }
  8020. }
  8021. if (dotEdge.to instanceof Object) {
  8022. to = dotEdge.to.nodes;
  8023. }
  8024. else {
  8025. to = {
  8026. id: dotEdge.to
  8027. }
  8028. }
  8029. if (dotEdge.from instanceof Object && dotEdge.from.edges) {
  8030. dotEdge.from.edges.forEach(function (subEdge) {
  8031. var graphEdge = convertEdge(subEdge);
  8032. graphData.edges.push(graphEdge);
  8033. });
  8034. }
  8035. forEach2(from, to, function (from, to) {
  8036. var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr);
  8037. var graphEdge = convertEdge(subEdge);
  8038. graphData.edges.push(graphEdge);
  8039. });
  8040. if (dotEdge.to instanceof Object && dotEdge.to.edges) {
  8041. dotEdge.to.edges.forEach(function (subEdge) {
  8042. var graphEdge = convertEdge(subEdge);
  8043. graphData.edges.push(graphEdge);
  8044. });
  8045. }
  8046. });
  8047. }
  8048. // copy the options
  8049. if (dotData.attr) {
  8050. graphData.options = dotData.attr;
  8051. }
  8052. return graphData;
  8053. }
  8054. // exports
  8055. exports.parseDOT = parseDOT;
  8056. exports.DOTToGraph = DOTToGraph;
  8057. })(typeof util !== 'undefined' ? util : exports);
  8058. /**
  8059. * Canvas shapes used by the Graph
  8060. */
  8061. if (typeof CanvasRenderingContext2D !== 'undefined') {
  8062. /**
  8063. * Draw a circle shape
  8064. */
  8065. CanvasRenderingContext2D.prototype.circle = function(x, y, r) {
  8066. this.beginPath();
  8067. this.arc(x, y, r, 0, 2*Math.PI, false);
  8068. };
  8069. /**
  8070. * Draw a square shape
  8071. * @param {Number} x horizontal center
  8072. * @param {Number} y vertical center
  8073. * @param {Number} r size, width and height of the square
  8074. */
  8075. CanvasRenderingContext2D.prototype.square = function(x, y, r) {
  8076. this.beginPath();
  8077. this.rect(x - r, y - r, r * 2, r * 2);
  8078. };
  8079. /**
  8080. * Draw a triangle shape
  8081. * @param {Number} x horizontal center
  8082. * @param {Number} y vertical center
  8083. * @param {Number} r radius, half the length of the sides of the triangle
  8084. */
  8085. CanvasRenderingContext2D.prototype.triangle = function(x, y, r) {
  8086. // http://en.wikipedia.org/wiki/Equilateral_triangle
  8087. this.beginPath();
  8088. var s = r * 2;
  8089. var s2 = s / 2;
  8090. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  8091. var h = Math.sqrt(s * s - s2 * s2); // height
  8092. this.moveTo(x, y - (h - ir));
  8093. this.lineTo(x + s2, y + ir);
  8094. this.lineTo(x - s2, y + ir);
  8095. this.lineTo(x, y - (h - ir));
  8096. this.closePath();
  8097. };
  8098. /**
  8099. * Draw a triangle shape in downward orientation
  8100. * @param {Number} x horizontal center
  8101. * @param {Number} y vertical center
  8102. * @param {Number} r radius
  8103. */
  8104. CanvasRenderingContext2D.prototype.triangleDown = function(x, y, r) {
  8105. // http://en.wikipedia.org/wiki/Equilateral_triangle
  8106. this.beginPath();
  8107. var s = r * 2;
  8108. var s2 = s / 2;
  8109. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  8110. var h = Math.sqrt(s * s - s2 * s2); // height
  8111. this.moveTo(x, y + (h - ir));
  8112. this.lineTo(x + s2, y - ir);
  8113. this.lineTo(x - s2, y - ir);
  8114. this.lineTo(x, y + (h - ir));
  8115. this.closePath();
  8116. };
  8117. /**
  8118. * Draw a star shape, a star with 5 points
  8119. * @param {Number} x horizontal center
  8120. * @param {Number} y vertical center
  8121. * @param {Number} r radius, half the length of the sides of the triangle
  8122. */
  8123. CanvasRenderingContext2D.prototype.star = function(x, y, r) {
  8124. // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/
  8125. this.beginPath();
  8126. for (var n = 0; n < 10; n++) {
  8127. var radius = (n % 2 === 0) ? r * 1.3 : r * 0.5;
  8128. this.lineTo(
  8129. x + radius * Math.sin(n * 2 * Math.PI / 10),
  8130. y - radius * Math.cos(n * 2 * Math.PI / 10)
  8131. );
  8132. }
  8133. this.closePath();
  8134. };
  8135. /**
  8136. * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas
  8137. */
  8138. CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) {
  8139. var r2d = Math.PI/180;
  8140. if( w - ( 2 * r ) < 0 ) { r = ( w / 2 ); } //ensure that the radius isn't too large for x
  8141. if( h - ( 2 * r ) < 0 ) { r = ( h / 2 ); } //ensure that the radius isn't too large for y
  8142. this.beginPath();
  8143. this.moveTo(x+r,y);
  8144. this.lineTo(x+w-r,y);
  8145. this.arc(x+w-r,y+r,r,r2d*270,r2d*360,false);
  8146. this.lineTo(x+w,y+h-r);
  8147. this.arc(x+w-r,y+h-r,r,0,r2d*90,false);
  8148. this.lineTo(x+r,y+h);
  8149. this.arc(x+r,y+h-r,r,r2d*90,r2d*180,false);
  8150. this.lineTo(x,y+r);
  8151. this.arc(x+r,y+r,r,r2d*180,r2d*270,false);
  8152. };
  8153. /**
  8154. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  8155. */
  8156. CanvasRenderingContext2D.prototype.ellipse = function(x, y, w, h) {
  8157. var kappa = .5522848,
  8158. ox = (w / 2) * kappa, // control point offset horizontal
  8159. oy = (h / 2) * kappa, // control point offset vertical
  8160. xe = x + w, // x-end
  8161. ye = y + h, // y-end
  8162. xm = x + w / 2, // x-middle
  8163. ym = y + h / 2; // y-middle
  8164. this.beginPath();
  8165. this.moveTo(x, ym);
  8166. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  8167. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  8168. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  8169. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  8170. };
  8171. /**
  8172. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  8173. */
  8174. CanvasRenderingContext2D.prototype.database = function(x, y, w, h) {
  8175. var f = 1/3;
  8176. var wEllipse = w;
  8177. var hEllipse = h * f;
  8178. var kappa = .5522848,
  8179. ox = (wEllipse / 2) * kappa, // control point offset horizontal
  8180. oy = (hEllipse / 2) * kappa, // control point offset vertical
  8181. xe = x + wEllipse, // x-end
  8182. ye = y + hEllipse, // y-end
  8183. xm = x + wEllipse / 2, // x-middle
  8184. ym = y + hEllipse / 2, // y-middle
  8185. ymb = y + (h - hEllipse/2), // y-midlle, bottom ellipse
  8186. yeb = y + h; // y-end, bottom ellipse
  8187. this.beginPath();
  8188. this.moveTo(xe, ym);
  8189. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  8190. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  8191. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  8192. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  8193. this.lineTo(xe, ymb);
  8194. this.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb);
  8195. this.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb);
  8196. this.lineTo(x, ym);
  8197. };
  8198. /**
  8199. * Draw an arrow point (no line)
  8200. */
  8201. CanvasRenderingContext2D.prototype.arrow = function(x, y, angle, length) {
  8202. // tail
  8203. var xt = x - length * Math.cos(angle);
  8204. var yt = y - length * Math.sin(angle);
  8205. // inner tail
  8206. // TODO: allow to customize different shapes
  8207. var xi = x - length * 0.9 * Math.cos(angle);
  8208. var yi = y - length * 0.9 * Math.sin(angle);
  8209. // left
  8210. var xl = xt + length / 3 * Math.cos(angle + 0.5 * Math.PI);
  8211. var yl = yt + length / 3 * Math.sin(angle + 0.5 * Math.PI);
  8212. // right
  8213. var xr = xt + length / 3 * Math.cos(angle - 0.5 * Math.PI);
  8214. var yr = yt + length / 3 * Math.sin(angle - 0.5 * Math.PI);
  8215. this.beginPath();
  8216. this.moveTo(x, y);
  8217. this.lineTo(xl, yl);
  8218. this.lineTo(xi, yi);
  8219. this.lineTo(xr, yr);
  8220. this.closePath();
  8221. };
  8222. /**
  8223. * Sets up the dashedLine functionality for drawing
  8224. * Original code came from http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
  8225. * @author David Jordan
  8226. * @date 2012-08-08
  8227. */
  8228. CanvasRenderingContext2D.prototype.dashedLine = function(x,y,x2,y2,dashArray){
  8229. if (!dashArray) dashArray=[10,5];
  8230. if (dashLength==0) dashLength = 0.001; // Hack for Safari
  8231. var dashCount = dashArray.length;
  8232. this.moveTo(x, y);
  8233. var dx = (x2-x), dy = (y2-y);
  8234. var slope = dy/dx;
  8235. var distRemaining = Math.sqrt( dx*dx + dy*dy );
  8236. var dashIndex=0, draw=true;
  8237. while (distRemaining>=0.1){
  8238. var dashLength = dashArray[dashIndex++%dashCount];
  8239. if (dashLength > distRemaining) dashLength = distRemaining;
  8240. var xStep = Math.sqrt( dashLength*dashLength / (1 + slope*slope) );
  8241. if (dx<0) xStep = -xStep;
  8242. x += xStep;
  8243. y += slope*xStep;
  8244. this[draw ? 'lineTo' : 'moveTo'](x,y);
  8245. distRemaining -= dashLength;
  8246. draw = !draw;
  8247. }
  8248. };
  8249. // TODO: add diamond shape
  8250. }
  8251. /**
  8252. * @class Node
  8253. * A node. A node can be connected to other nodes via one or multiple edges.
  8254. * @param {object} properties An object containing properties for the node. All
  8255. * properties are optional, except for the id.
  8256. * {number} id Id of the node. Required
  8257. * {string} label Text label for the node
  8258. * {number} x Horizontal position of the node
  8259. * {number} y Vertical position of the node
  8260. * {string} shape Node shape, available:
  8261. * "database", "circle", "ellipse",
  8262. * "box", "image", "text", "dot",
  8263. * "star", "triangle", "triangleDown",
  8264. * "square"
  8265. * {string} image An image url
  8266. * {string} title An title text, can be HTML
  8267. * {anytype} group A group name or number
  8268. * @param {Graph.Images} imagelist A list with images. Only needed
  8269. * when the node has an image
  8270. * @param {Graph.Groups} grouplist A list with groups. Needed for
  8271. * retrieving group properties
  8272. * @param {Object} constants An object with default values for
  8273. * example for the color
  8274. *
  8275. */
  8276. function Node(properties, imagelist, grouplist, constants) {
  8277. this.selected = false;
  8278. this.edges = []; // all edges connected to this node
  8279. this.dynamicEdges = [];
  8280. this.reroutedEdges = {};
  8281. this.group = constants.nodes.group;
  8282. this.fontSize = constants.nodes.fontSize;
  8283. this.fontFace = constants.nodes.fontFace;
  8284. this.fontColor = constants.nodes.fontColor;
  8285. this.fontDrawThreshold = 3;
  8286. this.color = constants.nodes.color;
  8287. // set defaults for the properties
  8288. this.id = undefined;
  8289. this.shape = constants.nodes.shape;
  8290. this.image = constants.nodes.image;
  8291. this.x = 0;
  8292. this.y = 0;
  8293. this.xFixed = false;
  8294. this.yFixed = false;
  8295. this.horizontalAlignLeft = true; // these are for the navigation controls
  8296. this.verticalAlignTop = true; // these are for the navigation controls
  8297. this.radius = constants.nodes.radius;
  8298. this.baseRadiusValue = constants.nodes.radius;
  8299. this.radiusFixed = false;
  8300. this.radiusMin = constants.nodes.radiusMin;
  8301. this.radiusMax = constants.nodes.radiusMax;
  8302. this.level = -1;
  8303. this.imagelist = imagelist;
  8304. this.grouplist = grouplist;
  8305. // physics properties
  8306. this.fx = 0.0; // external force x
  8307. this.fy = 0.0; // external force y
  8308. this.vx = 0.0; // velocity x
  8309. this.vy = 0.0; // velocity y
  8310. this.minForce = constants.minForce;
  8311. this.damping = constants.physics.damping;
  8312. this.mass = 1; // kg
  8313. this.setProperties(properties, constants);
  8314. // creating the variables for clustering
  8315. this.resetCluster();
  8316. this.dynamicEdgesLength = 0;
  8317. this.clusterSession = 0;
  8318. this.clusterSizeWidthFactor = constants.clustering.nodeScaling.width;
  8319. this.clusterSizeHeightFactor = constants.clustering.nodeScaling.height;
  8320. this.clusterSizeRadiusFactor = constants.clustering.nodeScaling.radius;
  8321. this.maxNodeSizeIncrements = constants.clustering.maxNodeSizeIncrements;
  8322. this.growthIndicator = 0;
  8323. // variables to tell the node about the graph.
  8324. this.graphScaleInv = 1;
  8325. this.graphScale = 1;
  8326. this.canvasTopLeft = {"x": -300, "y": -300};
  8327. this.canvasBottomRight = {"x": 300, "y": 300};
  8328. this.parentEdgeId = null;
  8329. }
  8330. /**
  8331. * (re)setting the clustering variables and objects
  8332. */
  8333. Node.prototype.resetCluster = function() {
  8334. // clustering variables
  8335. this.formationScale = undefined; // this is used to determine when to open the cluster
  8336. this.clusterSize = 1; // this signifies the total amount of nodes in this cluster
  8337. this.containedNodes = {};
  8338. this.containedEdges = {};
  8339. this.clusterSessions = [];
  8340. };
  8341. /**
  8342. * Attach a edge to the node
  8343. * @param {Edge} edge
  8344. */
  8345. Node.prototype.attachEdge = function(edge) {
  8346. if (this.edges.indexOf(edge) == -1) {
  8347. this.edges.push(edge);
  8348. }
  8349. if (this.dynamicEdges.indexOf(edge) == -1) {
  8350. this.dynamicEdges.push(edge);
  8351. }
  8352. this.dynamicEdgesLength = this.dynamicEdges.length;
  8353. };
  8354. /**
  8355. * Detach a edge from the node
  8356. * @param {Edge} edge
  8357. */
  8358. Node.prototype.detachEdge = function(edge) {
  8359. var index = this.edges.indexOf(edge);
  8360. if (index != -1) {
  8361. this.edges.splice(index, 1);
  8362. this.dynamicEdges.splice(index, 1);
  8363. }
  8364. this.dynamicEdgesLength = this.dynamicEdges.length;
  8365. };
  8366. /**
  8367. * Set or overwrite properties for the node
  8368. * @param {Object} properties an object with properties
  8369. * @param {Object} constants and object with default, global properties
  8370. */
  8371. Node.prototype.setProperties = function(properties, constants) {
  8372. if (!properties) {
  8373. return;
  8374. }
  8375. this.originalLabel = undefined;
  8376. // basic properties
  8377. if (properties.id !== undefined) {this.id = properties.id;}
  8378. if (properties.label !== undefined) {this.label = properties.label; this.originalLabel = properties.label;}
  8379. if (properties.title !== undefined) {this.title = properties.title;}
  8380. if (properties.group !== undefined) {this.group = properties.group;}
  8381. if (properties.x !== undefined) {this.x = properties.x;}
  8382. if (properties.y !== undefined) {this.y = properties.y;}
  8383. if (properties.value !== undefined) {this.value = properties.value;}
  8384. if (properties.level !== undefined) {this.level = properties.level;}
  8385. // physics
  8386. if (properties.internalMultiplier !== undefined) {this.internalMultiplier = properties.internalMultiplier;}
  8387. if (properties.damping !== undefined) {this.dampingBase = properties.damping;}
  8388. if (properties.mass !== undefined) {this.mass = properties.mass;}
  8389. // navigation controls properties
  8390. if (properties.horizontalAlignLeft !== undefined) {this.horizontalAlignLeft = properties.horizontalAlignLeft;}
  8391. if (properties.verticalAlignTop !== undefined) {this.verticalAlignTop = properties.verticalAlignTop;}
  8392. if (properties.triggerFunction !== undefined) {this.triggerFunction = properties.triggerFunction;}
  8393. if (this.id === undefined) {
  8394. throw "Node must have an id";
  8395. }
  8396. // copy group properties
  8397. if (this.group) {
  8398. var groupObj = this.grouplist.get(this.group);
  8399. for (var prop in groupObj) {
  8400. if (groupObj.hasOwnProperty(prop)) {
  8401. this[prop] = groupObj[prop];
  8402. }
  8403. }
  8404. }
  8405. // individual shape properties
  8406. if (properties.shape !== undefined) {this.shape = properties.shape;}
  8407. if (properties.image !== undefined) {this.image = properties.image;}
  8408. if (properties.radius !== undefined) {this.radius = properties.radius;}
  8409. if (properties.color !== undefined) {this.color = Node.parseColor(properties.color);}
  8410. if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;}
  8411. if (properties.fontSize !== undefined) {this.fontSize = properties.fontSize;}
  8412. if (properties.fontFace !== undefined) {this.fontFace = properties.fontFace;}
  8413. if (this.image !== undefined) {
  8414. if (this.imagelist) {
  8415. this.imageObj = this.imagelist.load(this.image);
  8416. }
  8417. else {
  8418. throw "No imagelist provided";
  8419. }
  8420. }
  8421. this.xFixed = this.xFixed || (properties.x !== undefined && !properties.allowedToMove);
  8422. this.yFixed = this.yFixed || (properties.y !== undefined && !properties.allowedToMove);
  8423. this.radiusFixed = this.radiusFixed || (properties.radius !== undefined);
  8424. if (this.shape == 'image') {
  8425. this.radiusMin = constants.nodes.widthMin;
  8426. this.radiusMax = constants.nodes.widthMax;
  8427. }
  8428. // choose draw method depending on the shape
  8429. switch (this.shape) {
  8430. case 'database': this.draw = this._drawDatabase; this.resize = this._resizeDatabase; break;
  8431. case 'box': this.draw = this._drawBox; this.resize = this._resizeBox; break;
  8432. case 'circle': this.draw = this._drawCircle; this.resize = this._resizeCircle; break;
  8433. case 'ellipse': this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  8434. // TODO: add diamond shape
  8435. case 'image': this.draw = this._drawImage; this.resize = this._resizeImage; break;
  8436. case 'text': this.draw = this._drawText; this.resize = this._resizeText; break;
  8437. case 'dot': this.draw = this._drawDot; this.resize = this._resizeShape; break;
  8438. case 'square': this.draw = this._drawSquare; this.resize = this._resizeShape; break;
  8439. case 'triangle': this.draw = this._drawTriangle; this.resize = this._resizeShape; break;
  8440. case 'triangleDown': this.draw = this._drawTriangleDown; this.resize = this._resizeShape; break;
  8441. case 'star': this.draw = this._drawStar; this.resize = this._resizeShape; break;
  8442. default: this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  8443. }
  8444. // reset the size of the node, this can be changed
  8445. this._reset();
  8446. };
  8447. /**
  8448. * Parse a color property into an object with border, background, and
  8449. * hightlight colors
  8450. * @param {Object | String} color
  8451. * @return {Object} colorObject
  8452. */
  8453. Node.parseColor = function(color) {
  8454. var c;
  8455. if (util.isString(color)) {
  8456. if (util.isValidHex(color)) {
  8457. var hsv = util.hexToHSV(color);
  8458. var lighterColorHSV = {h:hsv.h,s:hsv.s * 0.45,v:Math.min(1,hsv.v * 1.05)};
  8459. var darkerColorHSV = {h:hsv.h,s:Math.min(1,hsv.v * 1.25),v:hsv.v*0.6};
  8460. var darkerColorHex = util.HSVToHex(darkerColorHSV.h ,darkerColorHSV.h ,darkerColorHSV.v);
  8461. var lighterColorHex = util.HSVToHex(lighterColorHSV.h,lighterColorHSV.s,lighterColorHSV.v);
  8462. c = {
  8463. background: color,
  8464. border:darkerColorHex,
  8465. highlight: {
  8466. background:lighterColorHex,
  8467. border:darkerColorHex
  8468. }
  8469. };
  8470. }
  8471. else {
  8472. c = {
  8473. background:color,
  8474. border:color,
  8475. highlight: {
  8476. background:color,
  8477. border:color
  8478. }
  8479. };
  8480. }
  8481. }
  8482. else {
  8483. c = {};
  8484. c.background = color.background || 'white';
  8485. c.border = color.border || c.background;
  8486. if (util.isString(color.highlight)) {
  8487. c.highlight = {
  8488. border: color.highlight,
  8489. background: color.highlight
  8490. }
  8491. }
  8492. else {
  8493. c.highlight = {};
  8494. c.highlight.background = color.highlight && color.highlight.background || c.background;
  8495. c.highlight.border = color.highlight && color.highlight.border || c.border;
  8496. }
  8497. }
  8498. return c;
  8499. };
  8500. /**
  8501. * select this node
  8502. */
  8503. Node.prototype.select = function() {
  8504. this.selected = true;
  8505. this._reset();
  8506. };
  8507. /**
  8508. * unselect this node
  8509. */
  8510. Node.prototype.unselect = function() {
  8511. this.selected = false;
  8512. this._reset();
  8513. };
  8514. /**
  8515. * Reset the calculated size of the node, forces it to recalculate its size
  8516. */
  8517. Node.prototype.clearSizeCache = function() {
  8518. this._reset();
  8519. };
  8520. /**
  8521. * Reset the calculated size of the node, forces it to recalculate its size
  8522. * @private
  8523. */
  8524. Node.prototype._reset = function() {
  8525. this.width = undefined;
  8526. this.height = undefined;
  8527. };
  8528. /**
  8529. * get the title of this node.
  8530. * @return {string} title The title of the node, or undefined when no title
  8531. * has been set.
  8532. */
  8533. Node.prototype.getTitle = function() {
  8534. return this.title;
  8535. };
  8536. /**
  8537. * Calculate the distance to the border of the Node
  8538. * @param {CanvasRenderingContext2D} ctx
  8539. * @param {Number} angle Angle in radians
  8540. * @returns {number} distance Distance to the border in pixels
  8541. */
  8542. Node.prototype.distanceToBorder = function (ctx, angle) {
  8543. var borderWidth = 1;
  8544. if (!this.width) {
  8545. this.resize(ctx);
  8546. }
  8547. switch (this.shape) {
  8548. case 'circle':
  8549. case 'dot':
  8550. return this.radius + borderWidth;
  8551. case 'ellipse':
  8552. var a = this.width / 2;
  8553. var b = this.height / 2;
  8554. var w = (Math.sin(angle) * a);
  8555. var h = (Math.cos(angle) * b);
  8556. return a * b / Math.sqrt(w * w + h * h);
  8557. // TODO: implement distanceToBorder for database
  8558. // TODO: implement distanceToBorder for triangle
  8559. // TODO: implement distanceToBorder for triangleDown
  8560. case 'box':
  8561. case 'image':
  8562. case 'text':
  8563. default:
  8564. if (this.width) {
  8565. return Math.min(
  8566. Math.abs(this.width / 2 / Math.cos(angle)),
  8567. Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth;
  8568. // TODO: reckon with border radius too in case of box
  8569. }
  8570. else {
  8571. return 0;
  8572. }
  8573. }
  8574. // TODO: implement calculation of distance to border for all shapes
  8575. };
  8576. /**
  8577. * Set forces acting on the node
  8578. * @param {number} fx Force in horizontal direction
  8579. * @param {number} fy Force in vertical direction
  8580. */
  8581. Node.prototype._setForce = function(fx, fy) {
  8582. this.fx = fx;
  8583. this.fy = fy;
  8584. };
  8585. /**
  8586. * Add forces acting on the node
  8587. * @param {number} fx Force in horizontal direction
  8588. * @param {number} fy Force in vertical direction
  8589. * @private
  8590. */
  8591. Node.prototype._addForce = function(fx, fy) {
  8592. this.fx += fx;
  8593. this.fy += fy;
  8594. };
  8595. /**
  8596. * Perform one discrete step for the node
  8597. * @param {number} interval Time interval in seconds
  8598. */
  8599. Node.prototype.discreteStep = function(interval) {
  8600. if (!this.xFixed) {
  8601. var dx = this.damping * this.vx; // damping force
  8602. var ax = (this.fx - dx) / this.mass; // acceleration
  8603. this.vx += ax * interval; // velocity
  8604. this.x += this.vx * interval; // position
  8605. }
  8606. if (!this.yFixed) {
  8607. var dy = this.damping * this.vy; // damping force
  8608. var ay = (this.fy - dy) / this.mass; // acceleration
  8609. this.vy += ay * interval; // velocity
  8610. this.y += this.vy * interval; // position
  8611. }
  8612. };
  8613. /**
  8614. * Perform one discrete step for the node
  8615. * @param {number} interval Time interval in seconds
  8616. */
  8617. Node.prototype.discreteStepLimited = function(interval, maxVelocity) {
  8618. if (!this.xFixed) {
  8619. var dx = this.damping * this.vx; // damping force
  8620. var ax = (this.fx - dx) / this.mass; // acceleration
  8621. this.vx += ax * interval; // velocity
  8622. this.vx = (Math.abs(this.vx) > maxVelocity) ? ((this.vx > 0) ? maxVelocity : -maxVelocity) : this.vx;
  8623. this.x += this.vx * interval; // position
  8624. }
  8625. if (!this.yFixed) {
  8626. var dy = this.damping * this.vy; // damping force
  8627. var ay = (this.fy - dy) / this.mass; // acceleration
  8628. this.vy += ay * interval; // velocity
  8629. this.vy = (Math.abs(this.vy) > maxVelocity) ? ((this.vy > 0) ? maxVelocity : -maxVelocity) : this.vy;
  8630. this.y += this.vy * interval; // position
  8631. }
  8632. };
  8633. /**
  8634. * Check if this node has a fixed x and y position
  8635. * @return {boolean} true if fixed, false if not
  8636. */
  8637. Node.prototype.isFixed = function() {
  8638. return (this.xFixed && this.yFixed);
  8639. };
  8640. /**
  8641. * Check if this node is moving
  8642. * @param {number} vmin the minimum velocity considered as "moving"
  8643. * @return {boolean} true if moving, false if it has no velocity
  8644. */
  8645. // TODO: replace this method with calculating the kinetic energy
  8646. Node.prototype.isMoving = function(vmin) {
  8647. return (Math.abs(this.vx) > vmin || Math.abs(this.vy) > vmin);
  8648. };
  8649. /**
  8650. * check if this node is selecte
  8651. * @return {boolean} selected True if node is selected, else false
  8652. */
  8653. Node.prototype.isSelected = function() {
  8654. return this.selected;
  8655. };
  8656. /**
  8657. * Retrieve the value of the node. Can be undefined
  8658. * @return {Number} value
  8659. */
  8660. Node.prototype.getValue = function() {
  8661. return this.value;
  8662. };
  8663. /**
  8664. * Calculate the distance from the nodes location to the given location (x,y)
  8665. * @param {Number} x
  8666. * @param {Number} y
  8667. * @return {Number} value
  8668. */
  8669. Node.prototype.getDistance = function(x, y) {
  8670. var dx = this.x - x,
  8671. dy = this.y - y;
  8672. return Math.sqrt(dx * dx + dy * dy);
  8673. };
  8674. /**
  8675. * Adjust the value range of the node. The node will adjust it's radius
  8676. * based on its value.
  8677. * @param {Number} min
  8678. * @param {Number} max
  8679. */
  8680. Node.prototype.setValueRange = function(min, max) {
  8681. if (!this.radiusFixed && this.value !== undefined) {
  8682. if (max == min) {
  8683. this.radius = (this.radiusMin + this.radiusMax) / 2;
  8684. }
  8685. else {
  8686. var scale = (this.radiusMax - this.radiusMin) / (max - min);
  8687. this.radius = (this.value - min) * scale + this.radiusMin;
  8688. }
  8689. }
  8690. this.baseRadiusValue = this.radius;
  8691. };
  8692. /**
  8693. * Draw this node in the given canvas
  8694. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8695. * @param {CanvasRenderingContext2D} ctx
  8696. */
  8697. Node.prototype.draw = function(ctx) {
  8698. throw "Draw method not initialized for node";
  8699. };
  8700. /**
  8701. * Recalculate the size of this node in the given canvas
  8702. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8703. * @param {CanvasRenderingContext2D} ctx
  8704. */
  8705. Node.prototype.resize = function(ctx) {
  8706. throw "Resize method not initialized for node";
  8707. };
  8708. /**
  8709. * Check if this object is overlapping with the provided object
  8710. * @param {Object} obj an object with parameters left, top, right, bottom
  8711. * @return {boolean} True if location is located on node
  8712. */
  8713. Node.prototype.isOverlappingWith = function(obj) {
  8714. return (this.left < obj.right &&
  8715. this.left + this.width > obj.left &&
  8716. this.top < obj.bottom &&
  8717. this.top + this.height > obj.top);
  8718. };
  8719. Node.prototype._resizeImage = function (ctx) {
  8720. // TODO: pre calculate the image size
  8721. if (!this.width || !this.height) { // undefined or 0
  8722. var width, height;
  8723. if (this.value) {
  8724. this.radius = this.baseRadiusValue;
  8725. var scale = this.imageObj.height / this.imageObj.width;
  8726. if (scale !== undefined) {
  8727. width = this.radius || this.imageObj.width;
  8728. height = this.radius * scale || this.imageObj.height;
  8729. }
  8730. else {
  8731. width = 0;
  8732. height = 0;
  8733. }
  8734. }
  8735. else {
  8736. width = this.imageObj.width;
  8737. height = this.imageObj.height;
  8738. }
  8739. this.width = width;
  8740. this.height = height;
  8741. this.growthIndicator = 0;
  8742. if (this.width > 0 && this.height > 0) {
  8743. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8744. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8745. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8746. this.growthIndicator = this.width - width;
  8747. }
  8748. }
  8749. };
  8750. Node.prototype._drawImage = function (ctx) {
  8751. this._resizeImage(ctx);
  8752. this.left = this.x - this.width / 2;
  8753. this.top = this.y - this.height / 2;
  8754. var yLabel;
  8755. if (this.imageObj.width != 0 ) {
  8756. // draw the shade
  8757. if (this.clusterSize > 1) {
  8758. var lineWidth = ((this.clusterSize > 1) ? 10 : 0.0);
  8759. lineWidth *= this.graphScaleInv;
  8760. lineWidth = Math.min(0.2 * this.width,lineWidth);
  8761. ctx.globalAlpha = 0.5;
  8762. ctx.drawImage(this.imageObj, this.left - lineWidth, this.top - lineWidth, this.width + 2*lineWidth, this.height + 2*lineWidth);
  8763. }
  8764. // draw the image
  8765. ctx.globalAlpha = 1.0;
  8766. ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height);
  8767. yLabel = this.y + this.height / 2;
  8768. }
  8769. else {
  8770. // image still loading... just draw the label for now
  8771. yLabel = this.y;
  8772. }
  8773. this._label(ctx, this.label, this.x, yLabel, undefined, "top");
  8774. };
  8775. Node.prototype._resizeBox = function (ctx) {
  8776. if (!this.width) {
  8777. var margin = 5;
  8778. var textSize = this.getTextSize(ctx);
  8779. this.width = textSize.width + 2 * margin;
  8780. this.height = textSize.height + 2 * margin;
  8781. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  8782. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  8783. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  8784. // this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8785. }
  8786. };
  8787. Node.prototype._drawBox = function (ctx) {
  8788. this._resizeBox(ctx);
  8789. this.left = this.x - this.width / 2;
  8790. this.top = this.y - this.height / 2;
  8791. var clusterLineWidth = 2.5;
  8792. var selectionLineWidth = 2;
  8793. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8794. // draw the outer border
  8795. if (this.clusterSize > 1) {
  8796. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8797. ctx.lineWidth *= this.graphScaleInv;
  8798. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8799. ctx.roundRect(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth, this.radius);
  8800. ctx.stroke();
  8801. }
  8802. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8803. ctx.lineWidth *= this.graphScaleInv;
  8804. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8805. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8806. ctx.roundRect(this.left, this.top, this.width, this.height, this.radius);
  8807. ctx.fill();
  8808. ctx.stroke();
  8809. this._label(ctx, this.label, this.x, this.y);
  8810. };
  8811. Node.prototype._resizeDatabase = function (ctx) {
  8812. if (!this.width) {
  8813. var margin = 5;
  8814. var textSize = this.getTextSize(ctx);
  8815. var size = textSize.width + 2 * margin;
  8816. this.width = size;
  8817. this.height = size;
  8818. // scaling used for clustering
  8819. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8820. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8821. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8822. this.growthIndicator = this.width - size;
  8823. }
  8824. };
  8825. Node.prototype._drawDatabase = function (ctx) {
  8826. this._resizeDatabase(ctx);
  8827. this.left = this.x - this.width / 2;
  8828. this.top = this.y - this.height / 2;
  8829. var clusterLineWidth = 2.5;
  8830. var selectionLineWidth = 2;
  8831. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8832. // draw the outer border
  8833. if (this.clusterSize > 1) {
  8834. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8835. ctx.lineWidth *= this.graphScaleInv;
  8836. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8837. ctx.database(this.x - this.width/2 - 2*ctx.lineWidth, this.y - this.height*0.5 - 2*ctx.lineWidth, this.width + 4*ctx.lineWidth, this.height + 4*ctx.lineWidth);
  8838. ctx.stroke();
  8839. }
  8840. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8841. ctx.lineWidth *= this.graphScaleInv;
  8842. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8843. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8844. ctx.database(this.x - this.width/2, this.y - this.height*0.5, this.width, this.height);
  8845. ctx.fill();
  8846. ctx.stroke();
  8847. this._label(ctx, this.label, this.x, this.y);
  8848. };
  8849. Node.prototype._resizeCircle = function (ctx) {
  8850. if (!this.width) {
  8851. var margin = 5;
  8852. var textSize = this.getTextSize(ctx);
  8853. var diameter = Math.max(textSize.width, textSize.height) + 2 * margin;
  8854. this.radius = diameter / 2;
  8855. this.width = diameter;
  8856. this.height = diameter;
  8857. // scaling used for clustering
  8858. // this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  8859. // this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  8860. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8861. this.growthIndicator = this.radius - 0.5*diameter;
  8862. }
  8863. };
  8864. Node.prototype._drawCircle = function (ctx) {
  8865. this._resizeCircle(ctx);
  8866. this.left = this.x - this.width / 2;
  8867. this.top = this.y - this.height / 2;
  8868. var clusterLineWidth = 2.5;
  8869. var selectionLineWidth = 2;
  8870. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8871. // draw the outer border
  8872. if (this.clusterSize > 1) {
  8873. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8874. ctx.lineWidth *= this.graphScaleInv;
  8875. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8876. ctx.circle(this.x, this.y, this.radius+2*ctx.lineWidth);
  8877. ctx.stroke();
  8878. }
  8879. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8880. ctx.lineWidth *= this.graphScaleInv;
  8881. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8882. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8883. ctx.circle(this.x, this.y, this.radius);
  8884. ctx.fill();
  8885. ctx.stroke();
  8886. this._label(ctx, this.label, this.x, this.y);
  8887. };
  8888. Node.prototype._resizeEllipse = function (ctx) {
  8889. if (!this.width) {
  8890. var textSize = this.getTextSize(ctx);
  8891. this.width = textSize.width * 1.5;
  8892. this.height = textSize.height * 2;
  8893. if (this.width < this.height) {
  8894. this.width = this.height;
  8895. }
  8896. var defaultSize = this.width;
  8897. // scaling used for clustering
  8898. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8899. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8900. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8901. this.growthIndicator = this.width - defaultSize;
  8902. }
  8903. };
  8904. Node.prototype._drawEllipse = function (ctx) {
  8905. this._resizeEllipse(ctx);
  8906. this.left = this.x - this.width / 2;
  8907. this.top = this.y - this.height / 2;
  8908. var clusterLineWidth = 2.5;
  8909. var selectionLineWidth = 2;
  8910. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8911. // draw the outer border
  8912. if (this.clusterSize > 1) {
  8913. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8914. ctx.lineWidth *= this.graphScaleInv;
  8915. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8916. ctx.ellipse(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth);
  8917. ctx.stroke();
  8918. }
  8919. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8920. ctx.lineWidth *= this.graphScaleInv;
  8921. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8922. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8923. ctx.ellipse(this.left, this.top, this.width, this.height);
  8924. ctx.fill();
  8925. ctx.stroke();
  8926. this._label(ctx, this.label, this.x, this.y);
  8927. };
  8928. Node.prototype._drawDot = function (ctx) {
  8929. this._drawShape(ctx, 'circle');
  8930. };
  8931. Node.prototype._drawTriangle = function (ctx) {
  8932. this._drawShape(ctx, 'triangle');
  8933. };
  8934. Node.prototype._drawTriangleDown = function (ctx) {
  8935. this._drawShape(ctx, 'triangleDown');
  8936. };
  8937. Node.prototype._drawSquare = function (ctx) {
  8938. this._drawShape(ctx, 'square');
  8939. };
  8940. Node.prototype._drawStar = function (ctx) {
  8941. this._drawShape(ctx, 'star');
  8942. };
  8943. Node.prototype._resizeShape = function (ctx) {
  8944. if (!this.width) {
  8945. this.radius = this.baseRadiusValue;
  8946. var size = 2 * this.radius;
  8947. this.width = size;
  8948. this.height = size;
  8949. // scaling used for clustering
  8950. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8951. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8952. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8953. this.growthIndicator = this.width - size;
  8954. }
  8955. };
  8956. Node.prototype._drawShape = function (ctx, shape) {
  8957. this._resizeShape(ctx);
  8958. this.left = this.x - this.width / 2;
  8959. this.top = this.y - this.height / 2;
  8960. var clusterLineWidth = 2.5;
  8961. var selectionLineWidth = 2;
  8962. var radiusMultiplier = 2;
  8963. // choose draw method depending on the shape
  8964. switch (shape) {
  8965. case 'dot': radiusMultiplier = 2; break;
  8966. case 'square': radiusMultiplier = 2; break;
  8967. case 'triangle': radiusMultiplier = 3; break;
  8968. case 'triangleDown': radiusMultiplier = 3; break;
  8969. case 'star': radiusMultiplier = 4; break;
  8970. }
  8971. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8972. // draw the outer border
  8973. if (this.clusterSize > 1) {
  8974. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8975. ctx.lineWidth *= this.graphScaleInv;
  8976. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8977. ctx[shape](this.x, this.y, this.radius + radiusMultiplier * ctx.lineWidth);
  8978. ctx.stroke();
  8979. }
  8980. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8981. ctx.lineWidth *= this.graphScaleInv;
  8982. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8983. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8984. ctx[shape](this.x, this.y, this.radius);
  8985. ctx.fill();
  8986. ctx.stroke();
  8987. if (this.label) {
  8988. this._label(ctx, this.label, this.x, this.y + this.height / 2, undefined, 'top');
  8989. }
  8990. };
  8991. Node.prototype._resizeText = function (ctx) {
  8992. if (!this.width) {
  8993. var margin = 5;
  8994. var textSize = this.getTextSize(ctx);
  8995. this.width = textSize.width + 2 * margin;
  8996. this.height = textSize.height + 2 * margin;
  8997. // scaling used for clustering
  8998. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8999. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  9000. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  9001. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  9002. }
  9003. };
  9004. Node.prototype._drawText = function (ctx) {
  9005. this._resizeText(ctx);
  9006. this.left = this.x - this.width / 2;
  9007. this.top = this.y - this.height / 2;
  9008. this._label(ctx, this.label, this.x, this.y);
  9009. };
  9010. Node.prototype._label = function (ctx, text, x, y, align, baseline) {
  9011. if (text && this.fontSize * this.graphScale > this.fontDrawThreshold) {
  9012. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  9013. ctx.fillStyle = this.fontColor || "black";
  9014. ctx.textAlign = align || "center";
  9015. ctx.textBaseline = baseline || "middle";
  9016. var lines = text.split('\n'),
  9017. lineCount = lines.length,
  9018. fontSize = (this.fontSize + 4),
  9019. yLine = y + (1 - lineCount) / 2 * fontSize;
  9020. for (var i = 0; i < lineCount; i++) {
  9021. ctx.fillText(lines[i], x, yLine);
  9022. yLine += fontSize;
  9023. }
  9024. }
  9025. };
  9026. Node.prototype.getTextSize = function(ctx) {
  9027. if (this.label !== undefined) {
  9028. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  9029. var lines = this.label.split('\n'),
  9030. height = (this.fontSize + 4) * lines.length,
  9031. width = 0;
  9032. for (var i = 0, iMax = lines.length; i < iMax; i++) {
  9033. width = Math.max(width, ctx.measureText(lines[i]).width);
  9034. }
  9035. return {"width": width, "height": height};
  9036. }
  9037. else {
  9038. return {"width": 0, "height": 0};
  9039. }
  9040. };
  9041. /**
  9042. * this is used to determine if a node is visible at all. this is used to determine when it needs to be drawn.
  9043. * there is a safety margin of 0.3 * width;
  9044. *
  9045. * @returns {boolean}
  9046. */
  9047. Node.prototype.inArea = function() {
  9048. if (this.width !== undefined) {
  9049. return (this.x + this.width*this.graphScaleInv >= this.canvasTopLeft.x &&
  9050. this.x - this.width*this.graphScaleInv < this.canvasBottomRight.x &&
  9051. this.y + this.height*this.graphScaleInv >= this.canvasTopLeft.y &&
  9052. this.y - this.height*this.graphScaleInv < this.canvasBottomRight.y);
  9053. }
  9054. else {
  9055. return true;
  9056. }
  9057. };
  9058. /**
  9059. * checks if the core of the node is in the display area, this is used for opening clusters around zoom
  9060. * @returns {boolean}
  9061. */
  9062. Node.prototype.inView = function() {
  9063. return (this.x >= this.canvasTopLeft.x &&
  9064. this.x < this.canvasBottomRight.x &&
  9065. this.y >= this.canvasTopLeft.y &&
  9066. this.y < this.canvasBottomRight.y);
  9067. };
  9068. /**
  9069. * This allows the zoom level of the graph to influence the rendering
  9070. * We store the inverted scale and the coordinates of the top left, and bottom right points of the canvas
  9071. *
  9072. * @param scale
  9073. * @param canvasTopLeft
  9074. * @param canvasBottomRight
  9075. */
  9076. Node.prototype.setScaleAndPos = function(scale,canvasTopLeft,canvasBottomRight) {
  9077. this.graphScaleInv = 1.0/scale;
  9078. this.graphScale = scale;
  9079. this.canvasTopLeft = canvasTopLeft;
  9080. this.canvasBottomRight = canvasBottomRight;
  9081. };
  9082. /**
  9083. * This allows the zoom level of the graph to influence the rendering
  9084. *
  9085. * @param scale
  9086. */
  9087. Node.prototype.setScale = function(scale) {
  9088. this.graphScaleInv = 1.0/scale;
  9089. this.graphScale = scale;
  9090. };
  9091. /**
  9092. * set the velocity at 0. Is called when this node is contained in another during clustering
  9093. */
  9094. Node.prototype.clearVelocity = function() {
  9095. this.vx = 0;
  9096. this.vy = 0;
  9097. };
  9098. /**
  9099. * Basic preservation of (kinectic) energy
  9100. *
  9101. * @param massBeforeClustering
  9102. */
  9103. Node.prototype.updateVelocity = function(massBeforeClustering) {
  9104. var energyBefore = this.vx * this.vx * massBeforeClustering;
  9105. //this.vx = (this.vx < 0) ? -Math.sqrt(energyBefore/this.mass) : Math.sqrt(energyBefore/this.mass);
  9106. this.vx = Math.sqrt(energyBefore/this.mass);
  9107. energyBefore = this.vy * this.vy * massBeforeClustering;
  9108. //this.vy = (this.vy < 0) ? -Math.sqrt(energyBefore/this.mass) : Math.sqrt(energyBefore/this.mass);
  9109. this.vy = Math.sqrt(energyBefore/this.mass);
  9110. };
  9111. /**
  9112. * @class Edge
  9113. *
  9114. * A edge connects two nodes
  9115. * @param {Object} properties Object with properties. Must contain
  9116. * At least properties from and to.
  9117. * Available properties: from (number),
  9118. * to (number), label (string, color (string),
  9119. * width (number), style (string),
  9120. * length (number), title (string)
  9121. * @param {Graph} graph A graph object, used to find and edge to
  9122. * nodes.
  9123. * @param {Object} constants An object with default values for
  9124. * example for the color
  9125. */
  9126. function Edge (properties, graph, constants) {
  9127. if (!graph) {
  9128. throw "No graph provided";
  9129. }
  9130. this.graph = graph;
  9131. // initialize constants
  9132. this.widthMin = constants.edges.widthMin;
  9133. this.widthMax = constants.edges.widthMax;
  9134. // initialize variables
  9135. this.id = undefined;
  9136. this.fromId = undefined;
  9137. this.toId = undefined;
  9138. this.style = constants.edges.style;
  9139. this.title = undefined;
  9140. this.width = constants.edges.width;
  9141. this.value = undefined;
  9142. this.length = constants.physics.springLength;
  9143. this.selected = false;
  9144. this.smooth = constants.smoothCurves;
  9145. this.from = null; // a node
  9146. this.to = null; // a node
  9147. this.via = null; // a temp node
  9148. // we use this to be able to reconnect the edge to a cluster if its node is put into a cluster
  9149. // by storing the original information we can revert to the original connection when the cluser is opened.
  9150. this.originalFromId = [];
  9151. this.originalToId = [];
  9152. this.connected = false;
  9153. // Added to support dashed lines
  9154. // David Jordan
  9155. // 2012-08-08
  9156. this.dash = util.extend({}, constants.edges.dash); // contains properties length, gap, altLength
  9157. this.color = constants.edges.color;
  9158. this.widthFixed = false;
  9159. this.lengthFixed = false;
  9160. this.setProperties(properties, constants);
  9161. }
  9162. /**
  9163. * Set or overwrite properties for the edge
  9164. * @param {Object} properties an object with properties
  9165. * @param {Object} constants and object with default, global properties
  9166. */
  9167. Edge.prototype.setProperties = function(properties, constants) {
  9168. if (!properties) {
  9169. return;
  9170. }
  9171. if (properties.from !== undefined) {this.fromId = properties.from;}
  9172. if (properties.to !== undefined) {this.toId = properties.to;}
  9173. if (properties.id !== undefined) {this.id = properties.id;}
  9174. if (properties.style !== undefined) {this.style = properties.style;}
  9175. if (properties.label !== undefined) {this.label = properties.label;}
  9176. if (this.label) {
  9177. this.fontSize = constants.edges.fontSize;
  9178. this.fontFace = constants.edges.fontFace;
  9179. this.fontColor = constants.edges.fontColor;
  9180. if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;}
  9181. if (properties.fontSize !== undefined) {this.fontSize = properties.fontSize;}
  9182. if (properties.fontFace !== undefined) {this.fontFace = properties.fontFace;}
  9183. }
  9184. if (properties.title !== undefined) {this.title = properties.title;}
  9185. if (properties.width !== undefined) {this.width = properties.width;}
  9186. if (properties.value !== undefined) {this.value = properties.value;}
  9187. if (properties.length !== undefined) {this.length = properties.length;}
  9188. // Added to support dashed lines
  9189. // David Jordan
  9190. // 2012-08-08
  9191. if (properties.dash) {
  9192. if (properties.dash.length !== undefined) {this.dash.length = properties.dash.length;}
  9193. if (properties.dash.gap !== undefined) {this.dash.gap = properties.dash.gap;}
  9194. if (properties.dash.altLength !== undefined) {this.dash.altLength = properties.dash.altLength;}
  9195. }
  9196. if (properties.color !== undefined) {this.color = properties.color;}
  9197. // A node is connected when it has a from and to node.
  9198. this.connect();
  9199. this.widthFixed = this.widthFixed || (properties.width !== undefined);
  9200. this.lengthFixed = this.lengthFixed || (properties.length !== undefined);
  9201. // set draw method based on style
  9202. switch (this.style) {
  9203. case 'line': this.draw = this._drawLine; break;
  9204. case 'arrow': this.draw = this._drawArrow; break;
  9205. case 'arrow-center': this.draw = this._drawArrowCenter; break;
  9206. case 'dash-line': this.draw = this._drawDashLine; break;
  9207. default: this.draw = this._drawLine; break;
  9208. }
  9209. };
  9210. /**
  9211. * Connect an edge to its nodes
  9212. */
  9213. Edge.prototype.connect = function () {
  9214. this.disconnect();
  9215. this.from = this.graph.nodes[this.fromId] || null;
  9216. this.to = this.graph.nodes[this.toId] || null;
  9217. this.connected = (this.from && this.to);
  9218. if (this.connected) {
  9219. this.from.attachEdge(this);
  9220. this.to.attachEdge(this);
  9221. }
  9222. else {
  9223. if (this.from) {
  9224. this.from.detachEdge(this);
  9225. }
  9226. if (this.to) {
  9227. this.to.detachEdge(this);
  9228. }
  9229. }
  9230. };
  9231. /**
  9232. * Disconnect an edge from its nodes
  9233. */
  9234. Edge.prototype.disconnect = function () {
  9235. if (this.from) {
  9236. this.from.detachEdge(this);
  9237. this.from = null;
  9238. }
  9239. if (this.to) {
  9240. this.to.detachEdge(this);
  9241. this.to = null;
  9242. }
  9243. this.connected = false;
  9244. };
  9245. /**
  9246. * get the title of this edge.
  9247. * @return {string} title The title of the edge, or undefined when no title
  9248. * has been set.
  9249. */
  9250. Edge.prototype.getTitle = function() {
  9251. return this.title;
  9252. };
  9253. /**
  9254. * Retrieve the value of the edge. Can be undefined
  9255. * @return {Number} value
  9256. */
  9257. Edge.prototype.getValue = function() {
  9258. return this.value;
  9259. };
  9260. /**
  9261. * Adjust the value range of the edge. The edge will adjust it's width
  9262. * based on its value.
  9263. * @param {Number} min
  9264. * @param {Number} max
  9265. */
  9266. Edge.prototype.setValueRange = function(min, max) {
  9267. if (!this.widthFixed && this.value !== undefined) {
  9268. var scale = (this.widthMax - this.widthMin) / (max - min);
  9269. this.width = (this.value - min) * scale + this.widthMin;
  9270. }
  9271. };
  9272. /**
  9273. * Redraw a edge
  9274. * Draw this edge in the given canvas
  9275. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9276. * @param {CanvasRenderingContext2D} ctx
  9277. */
  9278. Edge.prototype.draw = function(ctx) {
  9279. throw "Method draw not initialized in edge";
  9280. };
  9281. /**
  9282. * Check if this object is overlapping with the provided object
  9283. * @param {Object} obj an object with parameters left, top
  9284. * @return {boolean} True if location is located on the edge
  9285. */
  9286. Edge.prototype.isOverlappingWith = function(obj) {
  9287. var distMax = 10;
  9288. var xFrom = this.from.x;
  9289. var yFrom = this.from.y;
  9290. var xTo = this.to.x;
  9291. var yTo = this.to.y;
  9292. var xObj = obj.left;
  9293. var yObj = obj.top;
  9294. var dist = this._getDistanceToEdge(xFrom, yFrom, xTo, yTo, xObj, yObj);
  9295. return (dist < distMax);
  9296. };
  9297. /**
  9298. * Redraw a edge as a line
  9299. * Draw this edge in the given canvas
  9300. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9301. * @param {CanvasRenderingContext2D} ctx
  9302. * @private
  9303. */
  9304. Edge.prototype._drawLine = function(ctx) {
  9305. // set style
  9306. ctx.strokeStyle = this.color;
  9307. ctx.lineWidth = this._getLineWidth();
  9308. var point;
  9309. if (this.from != this.to+9) {
  9310. // draw line
  9311. this._line(ctx);
  9312. // draw label
  9313. if (this.label) {
  9314. point = this._pointOnLine(0.5);
  9315. this._label(ctx, this.label, point.x, point.y);
  9316. }
  9317. }
  9318. else {
  9319. var x, y;
  9320. var radius = this.length / 4;
  9321. var node = this.from;
  9322. if (!node.width) {
  9323. node.resize(ctx);
  9324. }
  9325. if (node.width > node.height) {
  9326. x = node.x + node.width / 2;
  9327. y = node.y - radius;
  9328. }
  9329. else {
  9330. x = node.x + radius;
  9331. y = node.y - node.height / 2;
  9332. }
  9333. this._circle(ctx, x, y, radius);
  9334. point = this._pointOnCircle(x, y, radius, 0.5);
  9335. this._label(ctx, this.label, point.x, point.y);
  9336. }
  9337. };
  9338. /**
  9339. * Get the line width of the edge. Depends on width and whether one of the
  9340. * connected nodes is selected.
  9341. * @return {Number} width
  9342. * @private
  9343. */
  9344. Edge.prototype._getLineWidth = function() {
  9345. if (this.selected == true) {
  9346. return Math.min(this.width * 2, this.widthMax)*this.graphScaleInv;
  9347. }
  9348. else {
  9349. return this.width*this.graphScaleInv;
  9350. }
  9351. };
  9352. /**
  9353. * Draw a line between two nodes
  9354. * @param {CanvasRenderingContext2D} ctx
  9355. * @private
  9356. */
  9357. Edge.prototype._line = function (ctx) {
  9358. // draw a straight line
  9359. ctx.beginPath();
  9360. ctx.moveTo(this.from.x, this.from.y);
  9361. if (this.smooth == true) {
  9362. ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y);
  9363. }
  9364. else {
  9365. ctx.lineTo(this.to.x, this.to.y);
  9366. }
  9367. ctx.stroke();
  9368. };
  9369. /**
  9370. * Draw a line from a node to itself, a circle
  9371. * @param {CanvasRenderingContext2D} ctx
  9372. * @param {Number} x
  9373. * @param {Number} y
  9374. * @param {Number} radius
  9375. * @private
  9376. */
  9377. Edge.prototype._circle = function (ctx, x, y, radius) {
  9378. // draw a circle
  9379. ctx.beginPath();
  9380. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  9381. ctx.stroke();
  9382. };
  9383. /**
  9384. * Draw label with white background and with the middle at (x, y)
  9385. * @param {CanvasRenderingContext2D} ctx
  9386. * @param {String} text
  9387. * @param {Number} x
  9388. * @param {Number} y
  9389. * @private
  9390. */
  9391. Edge.prototype._label = function (ctx, text, x, y) {
  9392. if (text) {
  9393. // TODO: cache the calculated size
  9394. ctx.font = ((this.from.selected || this.to.selected) ? "bold " : "") +
  9395. this.fontSize + "px " + this.fontFace;
  9396. ctx.fillStyle = 'white';
  9397. var width = ctx.measureText(text).width;
  9398. var height = this.fontSize;
  9399. var left = x - width / 2;
  9400. var top = y - height / 2;
  9401. ctx.fillRect(left, top, width, height);
  9402. // draw text
  9403. ctx.fillStyle = this.fontColor || "black";
  9404. ctx.textAlign = "left";
  9405. ctx.textBaseline = "top";
  9406. ctx.fillText(text, left, top);
  9407. }
  9408. };
  9409. /**
  9410. * Redraw a edge as a dashed line
  9411. * Draw this edge in the given canvas
  9412. * @author David Jordan
  9413. * @date 2012-08-08
  9414. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9415. * @param {CanvasRenderingContext2D} ctx
  9416. * @private
  9417. */
  9418. Edge.prototype._drawDashLine = function(ctx) {
  9419. // set style
  9420. ctx.strokeStyle = this.color;
  9421. ctx.lineWidth = this._getLineWidth();
  9422. // only firefox and chrome support this method, else we use the legacy one.
  9423. if (ctx.mozDash !== undefined || ctx.setLineDash !== undefined) {
  9424. ctx.beginPath();
  9425. ctx.moveTo(this.from.x, this.from.y);
  9426. // configure the dash pattern
  9427. var pattern = [0];
  9428. if (this.dash.length !== undefined && this.dash.gap !== undefined) {
  9429. pattern = [this.dash.length,this.dash.gap];
  9430. }
  9431. else {
  9432. pattern = [5,5];
  9433. }
  9434. // set dash settings for chrome or firefox
  9435. if (typeof ctx.setLineDash !== 'undefined') { //Chrome
  9436. ctx.setLineDash(pattern);
  9437. ctx.lineDashOffset = 0;
  9438. } else { //Firefox
  9439. ctx.mozDash = pattern;
  9440. ctx.mozDashOffset = 0;
  9441. }
  9442. // draw the line
  9443. if (this.smooth == true) {
  9444. ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y);
  9445. }
  9446. else {
  9447. ctx.lineTo(this.to.x, this.to.y);
  9448. }
  9449. ctx.stroke();
  9450. // restore the dash settings.
  9451. if (typeof ctx.setLineDash !== 'undefined') { //Chrome
  9452. ctx.setLineDash([0]);
  9453. ctx.lineDashOffset = 0;
  9454. } else { //Firefox
  9455. ctx.mozDash = [0];
  9456. ctx.mozDashOffset = 0;
  9457. }
  9458. }
  9459. else { // unsupporting smooth lines
  9460. // draw dashed line
  9461. ctx.beginPath();
  9462. ctx.lineCap = 'round';
  9463. if (this.dash.altLength !== undefined) //If an alt dash value has been set add to the array this value
  9464. {
  9465. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  9466. [this.dash.length,this.dash.gap,this.dash.altLength,this.dash.gap]);
  9467. }
  9468. 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
  9469. {
  9470. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  9471. [this.dash.length,this.dash.gap]);
  9472. }
  9473. else //If all else fails draw a line
  9474. {
  9475. ctx.moveTo(this.from.x, this.from.y);
  9476. ctx.lineTo(this.to.x, this.to.y);
  9477. }
  9478. ctx.stroke();
  9479. }
  9480. // draw label
  9481. if (this.label) {
  9482. var point = this._pointOnLine(0.5);
  9483. this._label(ctx, this.label, point.x, point.y);
  9484. }
  9485. };
  9486. /**
  9487. * Get a point on a line
  9488. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  9489. * @return {Object} point
  9490. * @private
  9491. */
  9492. Edge.prototype._pointOnLine = function (percentage) {
  9493. return {
  9494. x: (1 - percentage) * this.from.x + percentage * this.to.x,
  9495. y: (1 - percentage) * this.from.y + percentage * this.to.y
  9496. }
  9497. };
  9498. /**
  9499. * Get a point on a circle
  9500. * @param {Number} x
  9501. * @param {Number} y
  9502. * @param {Number} radius
  9503. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  9504. * @return {Object} point
  9505. * @private
  9506. */
  9507. Edge.prototype._pointOnCircle = function (x, y, radius, percentage) {
  9508. var angle = (percentage - 3/8) * 2 * Math.PI;
  9509. return {
  9510. x: x + radius * Math.cos(angle),
  9511. y: y - radius * Math.sin(angle)
  9512. }
  9513. };
  9514. /**
  9515. * Redraw a edge as a line with an arrow halfway the line
  9516. * Draw this edge in the given canvas
  9517. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9518. * @param {CanvasRenderingContext2D} ctx
  9519. * @private
  9520. */
  9521. Edge.prototype._drawArrowCenter = function(ctx) {
  9522. var point;
  9523. // set style
  9524. ctx.strokeStyle = this.color;
  9525. ctx.fillStyle = this.color;
  9526. ctx.lineWidth = this._getLineWidth();
  9527. if (this.from != this.to) {
  9528. // draw line
  9529. this._line(ctx);
  9530. var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  9531. var length = 10 + 5 * this.width; // TODO: make customizable?
  9532. // draw an arrow halfway the line
  9533. if (this.smooth == true) {
  9534. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9535. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9536. point = {x:midpointX, y:midpointY};
  9537. }
  9538. else {
  9539. point = this._pointOnLine(0.5);
  9540. }
  9541. ctx.arrow(point.x, point.y, angle, length);
  9542. ctx.fill();
  9543. ctx.stroke();
  9544. // draw label
  9545. if (this.label) {
  9546. point = this._pointOnLine(0.5);
  9547. this._label(ctx, this.label, point.x, point.y);
  9548. }
  9549. }
  9550. else {
  9551. // draw circle
  9552. var x, y;
  9553. var radius = 0.25 * Math.max(100,this.length);
  9554. var node = this.from;
  9555. if (!node.width) {
  9556. node.resize(ctx);
  9557. }
  9558. if (node.width > node.height) {
  9559. x = node.x + node.width * 0.5;
  9560. y = node.y - radius;
  9561. }
  9562. else {
  9563. x = node.x + radius;
  9564. y = node.y - node.height * 0.5;
  9565. }
  9566. this._circle(ctx, x, y, radius);
  9567. // draw all arrows
  9568. var angle = 0.2 * Math.PI;
  9569. var length = 10 + 5 * this.width; // TODO: make customizable?
  9570. point = this._pointOnCircle(x, y, radius, 0.5);
  9571. ctx.arrow(point.x, point.y, angle, length);
  9572. ctx.fill();
  9573. ctx.stroke();
  9574. // draw label
  9575. if (this.label) {
  9576. point = this._pointOnCircle(x, y, radius, 0.5);
  9577. this._label(ctx, this.label, point.x, point.y);
  9578. }
  9579. }
  9580. };
  9581. /**
  9582. * Redraw a edge as a line with an arrow
  9583. * Draw this edge in the given canvas
  9584. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9585. * @param {CanvasRenderingContext2D} ctx
  9586. * @private
  9587. */
  9588. Edge.prototype._drawArrow = function(ctx) {
  9589. // set style
  9590. ctx.strokeStyle = this.color;
  9591. ctx.fillStyle = this.color;
  9592. ctx.lineWidth = this._getLineWidth();
  9593. var angle, length;
  9594. //draw a line
  9595. if (this.from != this.to) {
  9596. angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  9597. var dx = (this.to.x - this.from.x);
  9598. var dy = (this.to.y - this.from.y);
  9599. var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  9600. var fromBorderDist = this.from.distanceToBorder(ctx, angle + Math.PI);
  9601. var fromBorderPoint = (edgeSegmentLength - fromBorderDist) / edgeSegmentLength;
  9602. var xFrom = (fromBorderPoint) * this.from.x + (1 - fromBorderPoint) * this.to.x;
  9603. var yFrom = (fromBorderPoint) * this.from.y + (1 - fromBorderPoint) * this.to.y;
  9604. if (this.smooth == true) {
  9605. angle = Math.atan2((this.to.y - this.via.y), (this.to.x - this.via.x));
  9606. dx = (this.to.x - this.via.x);
  9607. dy = (this.to.y - this.via.y);
  9608. edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  9609. }
  9610. var toBorderDist = this.to.distanceToBorder(ctx, angle);
  9611. var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength;
  9612. var xTo,yTo;
  9613. if (this.smooth == true) {
  9614. xTo = (1 - toBorderPoint) * this.via.x + toBorderPoint * this.to.x;
  9615. yTo = (1 - toBorderPoint) * this.via.y + toBorderPoint * this.to.y;
  9616. }
  9617. else {
  9618. xTo = (1 - toBorderPoint) * this.from.x + toBorderPoint * this.to.x;
  9619. yTo = (1 - toBorderPoint) * this.from.y + toBorderPoint * this.to.y;
  9620. }
  9621. ctx.beginPath();
  9622. ctx.moveTo(xFrom,yFrom);
  9623. if (this.smooth == true) {
  9624. ctx.quadraticCurveTo(this.via.x,this.via.y,xTo, yTo);
  9625. }
  9626. else {
  9627. ctx.lineTo(xTo, yTo);
  9628. }
  9629. ctx.stroke();
  9630. // draw arrow at the end of the line
  9631. length = 10 + 5 * this.width;
  9632. ctx.arrow(xTo, yTo, angle, length);
  9633. ctx.fill();
  9634. ctx.stroke();
  9635. // draw label
  9636. if (this.label) {
  9637. var point = this._pointOnLine(0.5);
  9638. this._label(ctx, this.label, point.x, point.y);
  9639. }
  9640. }
  9641. else {
  9642. // draw circle
  9643. var node = this.from;
  9644. var x, y, arrow;
  9645. var radius = 0.25 * Math.max(100,this.length);
  9646. if (!node.width) {
  9647. node.resize(ctx);
  9648. }
  9649. if (node.width > node.height) {
  9650. x = node.x + node.width * 0.5;
  9651. y = node.y - radius;
  9652. arrow = {
  9653. x: x,
  9654. y: node.y,
  9655. angle: 0.9 * Math.PI
  9656. };
  9657. }
  9658. else {
  9659. x = node.x + radius;
  9660. y = node.y - node.height * 0.5;
  9661. arrow = {
  9662. x: node.x,
  9663. y: y,
  9664. angle: 0.6 * Math.PI
  9665. };
  9666. }
  9667. ctx.beginPath();
  9668. // TODO: similarly, for a line without arrows, draw to the border of the nodes instead of the center
  9669. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  9670. ctx.stroke();
  9671. // draw all arrows
  9672. length = 10 + 5 * this.width; // TODO: make customizable?
  9673. ctx.arrow(arrow.x, arrow.y, arrow.angle, length);
  9674. ctx.fill();
  9675. ctx.stroke();
  9676. // draw label
  9677. if (this.label) {
  9678. point = this._pointOnCircle(x, y, radius, 0.5);
  9679. this._label(ctx, this.label, point.x, point.y);
  9680. }
  9681. }
  9682. };
  9683. /**
  9684. * Calculate the distance between a point (x3,y3) and a line segment from
  9685. * (x1,y1) to (x2,y2).
  9686. * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
  9687. * @param {number} x1
  9688. * @param {number} y1
  9689. * @param {number} x2
  9690. * @param {number} y2
  9691. * @param {number} x3
  9692. * @param {number} y3
  9693. * @private
  9694. */
  9695. Edge.prototype._getDistanceToEdge = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is the point
  9696. if (this.smooth == true) {
  9697. var minDistance = 1e9;
  9698. var i,t,x,y,dx,dy;
  9699. for (i = 0; i < 10; i++) {
  9700. t = 0.1*i;
  9701. x = Math.pow(1-t,2)*x1 + (2*t*(1 - t))*this.via.x + Math.pow(t,2)*x2;
  9702. y = Math.pow(1-t,2)*y1 + (2*t*(1 - t))*this.via.y + Math.pow(t,2)*y2;
  9703. dx = Math.abs(x3-x);
  9704. dy = Math.abs(y3-y);
  9705. minDistance = Math.min(minDistance,Math.sqrt(dx*dx + dy*dy));
  9706. }
  9707. return minDistance
  9708. }
  9709. else {
  9710. var px = x2-x1,
  9711. py = y2-y1,
  9712. something = px*px + py*py,
  9713. u = ((x3 - x1) * px + (y3 - y1) * py) / something;
  9714. if (u > 1) {
  9715. u = 1;
  9716. }
  9717. else if (u < 0) {
  9718. u = 0;
  9719. }
  9720. var x = x1 + u * px,
  9721. y = y1 + u * py,
  9722. dx = x - x3,
  9723. dy = y - y3;
  9724. //# Note: If the actual distance does not matter,
  9725. //# if you only want to compare what this function
  9726. //# returns to other results of this function, you
  9727. //# can just return the squared distance instead
  9728. //# (i.e. remove the sqrt) to gain a little performance
  9729. return Math.sqrt(dx*dx + dy*dy);
  9730. }
  9731. };
  9732. /**
  9733. * This allows the zoom level of the graph to influence the rendering
  9734. *
  9735. * @param scale
  9736. */
  9737. Edge.prototype.setScale = function(scale) {
  9738. this.graphScaleInv = 1.0/scale;
  9739. };
  9740. Edge.prototype.select = function() {
  9741. this.selected = true;
  9742. };
  9743. Edge.prototype.unselect = function() {
  9744. this.selected = false;
  9745. };
  9746. Edge.prototype.positionBezierNode = function() {
  9747. if (this.via !== null) {
  9748. this.via.x = 0.5 * (this.from.x + this.to.x);
  9749. this.via.y = 0.5 * (this.from.y + this.to.y);
  9750. }
  9751. };
  9752. /**
  9753. * Popup is a class to create a popup window with some text
  9754. * @param {Element} container The container object.
  9755. * @param {Number} [x]
  9756. * @param {Number} [y]
  9757. * @param {String} [text]
  9758. */
  9759. function Popup(container, x, y, text) {
  9760. if (container) {
  9761. this.container = container;
  9762. }
  9763. else {
  9764. this.container = document.body;
  9765. }
  9766. this.x = 0;
  9767. this.y = 0;
  9768. this.padding = 5;
  9769. if (x !== undefined && y !== undefined ) {
  9770. this.setPosition(x, y);
  9771. }
  9772. if (text !== undefined) {
  9773. this.setText(text);
  9774. }
  9775. // create the frame
  9776. this.frame = document.createElement("div");
  9777. var style = this.frame.style;
  9778. style.position = "absolute";
  9779. style.visibility = "hidden";
  9780. style.border = "1px solid #666";
  9781. style.color = "black";
  9782. style.padding = this.padding + "px";
  9783. style.backgroundColor = "#FFFFC6";
  9784. style.borderRadius = "3px";
  9785. style.MozBorderRadius = "3px";
  9786. style.WebkitBorderRadius = "3px";
  9787. style.boxShadow = "3px 3px 10px rgba(128, 128, 128, 0.5)";
  9788. style.whiteSpace = "nowrap";
  9789. this.container.appendChild(this.frame);
  9790. }
  9791. /**
  9792. * @param {number} x Horizontal position of the popup window
  9793. * @param {number} y Vertical position of the popup window
  9794. */
  9795. Popup.prototype.setPosition = function(x, y) {
  9796. this.x = parseInt(x);
  9797. this.y = parseInt(y);
  9798. };
  9799. /**
  9800. * Set the text for the popup window. This can be HTML code
  9801. * @param {string} text
  9802. */
  9803. Popup.prototype.setText = function(text) {
  9804. this.frame.innerHTML = text;
  9805. };
  9806. /**
  9807. * Show the popup window
  9808. * @param {boolean} show Optional. Show or hide the window
  9809. */
  9810. Popup.prototype.show = function (show) {
  9811. if (show === undefined) {
  9812. show = true;
  9813. }
  9814. if (show) {
  9815. var height = this.frame.clientHeight;
  9816. var width = this.frame.clientWidth;
  9817. var maxHeight = this.frame.parentNode.clientHeight;
  9818. var maxWidth = this.frame.parentNode.clientWidth;
  9819. var top = (this.y - height);
  9820. if (top + height + this.padding > maxHeight) {
  9821. top = maxHeight - height - this.padding;
  9822. }
  9823. if (top < this.padding) {
  9824. top = this.padding;
  9825. }
  9826. var left = this.x;
  9827. if (left + width + this.padding > maxWidth) {
  9828. left = maxWidth - width - this.padding;
  9829. }
  9830. if (left < this.padding) {
  9831. left = this.padding;
  9832. }
  9833. this.frame.style.left = left + "px";
  9834. this.frame.style.top = top + "px";
  9835. this.frame.style.visibility = "visible";
  9836. }
  9837. else {
  9838. this.hide();
  9839. }
  9840. };
  9841. /**
  9842. * Hide the popup window
  9843. */
  9844. Popup.prototype.hide = function () {
  9845. this.frame.style.visibility = "hidden";
  9846. };
  9847. /**
  9848. * @class Groups
  9849. * This class can store groups and properties specific for groups.
  9850. */
  9851. Groups = function () {
  9852. this.clear();
  9853. this.defaultIndex = 0;
  9854. };
  9855. /**
  9856. * default constants for group colors
  9857. */
  9858. Groups.DEFAULT = [
  9859. {border: "#2B7CE9", background: "#97C2FC", highlight: {border: "#2B7CE9", background: "#D2E5FF"}}, // blue
  9860. {border: "#FFA500", background: "#FFFF00", highlight: {border: "#FFA500", background: "#FFFFA3"}}, // yellow
  9861. {border: "#FA0A10", background: "#FB7E81", highlight: {border: "#FA0A10", background: "#FFAFB1"}}, // red
  9862. {border: "#41A906", background: "#7BE141", highlight: {border: "#41A906", background: "#A1EC76"}}, // green
  9863. {border: "#E129F0", background: "#EB7DF4", highlight: {border: "#E129F0", background: "#F0B3F5"}}, // magenta
  9864. {border: "#7C29F0", background: "#AD85E4", highlight: {border: "#7C29F0", background: "#D3BDF0"}}, // purple
  9865. {border: "#C37F00", background: "#FFA807", highlight: {border: "#C37F00", background: "#FFCA66"}}, // orange
  9866. {border: "#4220FB", background: "#6E6EFD", highlight: {border: "#4220FB", background: "#9B9BFD"}}, // darkblue
  9867. {border: "#FD5A77", background: "#FFC0CB", highlight: {border: "#FD5A77", background: "#FFD1D9"}}, // pink
  9868. {border: "#4AD63A", background: "#C2FABC", highlight: {border: "#4AD63A", background: "#E6FFE3"}} // mint
  9869. ];
  9870. /**
  9871. * Clear all groups
  9872. */
  9873. Groups.prototype.clear = function () {
  9874. this.groups = {};
  9875. this.groups.length = function()
  9876. {
  9877. var i = 0;
  9878. for ( var p in this ) {
  9879. if (this.hasOwnProperty(p)) {
  9880. i++;
  9881. }
  9882. }
  9883. return i;
  9884. }
  9885. };
  9886. /**
  9887. * get group properties of a groupname. If groupname is not found, a new group
  9888. * is added.
  9889. * @param {*} groupname Can be a number, string, Date, etc.
  9890. * @return {Object} group The created group, containing all group properties
  9891. */
  9892. Groups.prototype.get = function (groupname) {
  9893. var group = this.groups[groupname];
  9894. if (group == undefined) {
  9895. // create new group
  9896. var index = this.defaultIndex % Groups.DEFAULT.length;
  9897. this.defaultIndex++;
  9898. group = {};
  9899. group.color = Groups.DEFAULT[index];
  9900. this.groups[groupname] = group;
  9901. }
  9902. return group;
  9903. };
  9904. /**
  9905. * Add a custom group style
  9906. * @param {String} groupname
  9907. * @param {Object} style An object containing borderColor,
  9908. * backgroundColor, etc.
  9909. * @return {Object} group The created group object
  9910. */
  9911. Groups.prototype.add = function (groupname, style) {
  9912. this.groups[groupname] = style;
  9913. if (style.color) {
  9914. style.color = Node.parseColor(style.color);
  9915. }
  9916. return style;
  9917. };
  9918. /**
  9919. * @class Images
  9920. * This class loads images and keeps them stored.
  9921. */
  9922. Images = function () {
  9923. this.images = {};
  9924. this.callback = undefined;
  9925. };
  9926. /**
  9927. * Set an onload callback function. This will be called each time an image
  9928. * is loaded
  9929. * @param {function} callback
  9930. */
  9931. Images.prototype.setOnloadCallback = function(callback) {
  9932. this.callback = callback;
  9933. };
  9934. /**
  9935. *
  9936. * @param {string} url Url of the image
  9937. * @return {Image} img The image object
  9938. */
  9939. Images.prototype.load = function(url) {
  9940. var img = this.images[url];
  9941. if (img == undefined) {
  9942. // create the image
  9943. var images = this;
  9944. img = new Image();
  9945. this.images[url] = img;
  9946. img.onload = function() {
  9947. if (images.callback) {
  9948. images.callback(this);
  9949. }
  9950. };
  9951. img.src = url;
  9952. }
  9953. return img;
  9954. };
  9955. /**
  9956. * Created by Alex on 2/6/14.
  9957. */
  9958. var physicsMixin = {
  9959. /**
  9960. * Toggling barnes Hut calculation on and off.
  9961. *
  9962. * @private
  9963. */
  9964. _toggleBarnesHut : function() {
  9965. this.constants.physics.barnesHut.enabled = !this.constants.physics.barnesHut.enabled;
  9966. this._loadSelectedForceSolver();
  9967. this.moving = true;
  9968. this.start();
  9969. },
  9970. /**
  9971. * Before calculating the forces, we check if we need to cluster to keep up performance and we check
  9972. * if there is more than one node. If it is just one node, we dont calculate anything.
  9973. *
  9974. * @private
  9975. */
  9976. _initializeForceCalculation : function() {
  9977. // stop calculation if there is only one node
  9978. if (this.nodeIndices.length == 1) {
  9979. this.nodes[this.nodeIndices[0]]._setForce(0,0);
  9980. }
  9981. else {
  9982. // if there are too many nodes on screen, we cluster without repositioning
  9983. if (this.nodeIndices.length > this.constants.clustering.clusterThreshold && this.constants.clustering.enabled == true) {
  9984. this.clusterToFit(this.constants.clustering.reduceToNodes, false);
  9985. }
  9986. // we now start the force calculation
  9987. this._calculateForces();
  9988. }
  9989. },
  9990. /**
  9991. * Calculate the external forces acting on the nodes
  9992. * Forces are caused by: edges, repulsing forces between nodes, gravity
  9993. * @private
  9994. */
  9995. _calculateForces : function() {
  9996. // Gravity is required to keep separated groups from floating off
  9997. // the forces are reset to zero in this loop by using _setForce instead
  9998. // of _addForce
  9999. this._calculateGravitationalForces();
  10000. this._calculateNodeForces();
  10001. if (this.constants.smoothCurves == true) {
  10002. this._calculateSpringForcesWithSupport();
  10003. }
  10004. else {
  10005. this._calculateSpringForces();
  10006. }
  10007. },
  10008. /**
  10009. * Smooth curves are created by adding invisible nodes in the center of the edges. These nodes are also
  10010. * handled in the calculateForces function. We then use a quadratic curve with the center node as control.
  10011. * This function joins the datanodes and invisible (called support) nodes into one object.
  10012. * We do this so we do not contaminate this.nodes with the support nodes.
  10013. *
  10014. * @private
  10015. */
  10016. _updateCalculationNodes : function() {
  10017. if (this.constants.smoothCurves == true) {
  10018. this.calculationNodes = {};
  10019. this.calculationNodeIndices = [];
  10020. for (var nodeId in this.nodes) {
  10021. if (this.nodes.hasOwnProperty(nodeId)) {
  10022. this.calculationNodes[nodeId] = this.nodes[nodeId];
  10023. }
  10024. }
  10025. var supportNodes = this.sectors['support']['nodes'];
  10026. for (var supportNodeId in supportNodes) {
  10027. if (supportNodes.hasOwnProperty(supportNodeId)) {
  10028. if (this.edges.hasOwnProperty(supportNodes[supportNodeId].parentEdgeId)) {
  10029. this.calculationNodes[supportNodeId] = supportNodes[supportNodeId];
  10030. }
  10031. else {
  10032. supportNodes[supportNodeId]._setForce(0,0);
  10033. }
  10034. }
  10035. }
  10036. for (var idx in this.calculationNodes) {
  10037. if (this.calculationNodes.hasOwnProperty(idx)) {
  10038. this.calculationNodeIndices.push(idx);
  10039. }
  10040. }
  10041. }
  10042. else {
  10043. this.calculationNodes = this.nodes;
  10044. this.calculationNodeIndices = this.nodeIndices;
  10045. }
  10046. },
  10047. /**
  10048. * this function applies the central gravity effect to keep groups from floating off
  10049. *
  10050. * @private
  10051. */
  10052. _calculateGravitationalForces : function() {
  10053. var dx, dy, distance, node, i;
  10054. var nodes = this.calculationNodes;
  10055. var gravity = this.constants.physics.centralGravity;
  10056. var gravityForce = 0;
  10057. for (i = 0; i < this.calculationNodeIndices.length; i++) {
  10058. node = nodes[this.calculationNodeIndices[i]];
  10059. node.damping = this.constants.physics.damping; // possibly add function to alter damping properties of clusters.
  10060. // gravity does not apply when we are in a pocket sector
  10061. if (this._sector() == "default" && gravity != 0) {
  10062. dx = -node.x;
  10063. dy = -node.y;
  10064. distance = Math.sqrt(dx*dx + dy*dy);
  10065. gravityForce = gravity / distance;
  10066. node.fx = dx * gravityForce;
  10067. node.fy = dy * gravityForce;
  10068. }
  10069. else {
  10070. node.fx = 0;
  10071. node.fy = 0;
  10072. }
  10073. }
  10074. },
  10075. /**
  10076. * this function calculates the effects of the springs in the case of unsmooth curves.
  10077. *
  10078. * @private
  10079. */
  10080. _calculateSpringForces : function() {
  10081. var edgeLength, edge, edgeId;
  10082. var dx, dy, fx, fy, springForce, length;
  10083. var edges = this.edges;
  10084. // forces caused by the edges, modelled as springs
  10085. for (edgeId in edges) {
  10086. if (edges.hasOwnProperty(edgeId)) {
  10087. edge = edges[edgeId];
  10088. if (edge.connected) {
  10089. // only calculate forces if nodes are in the same sector
  10090. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  10091. edgeLength = edge.length;
  10092. // this implies that the edges between big clusters are longer
  10093. edgeLength += (edge.to.clusterSize + edge.from.clusterSize - 2) * this.constants.clustering.edgeGrowth;
  10094. dx = (edge.from.x - edge.to.x);
  10095. dy = (edge.from.y - edge.to.y);
  10096. length = Math.sqrt(dx * dx + dy * dy);
  10097. if (length == 0) {
  10098. length = 0.01;
  10099. }
  10100. springForce = this.constants.physics.springConstant * (edgeLength - length) / length;
  10101. fx = dx * springForce;
  10102. fy = dy * springForce;
  10103. edge.from.fx += fx;
  10104. edge.from.fy += fy;
  10105. edge.to.fx -= fx;
  10106. edge.to.fy -= fy;
  10107. }
  10108. }
  10109. }
  10110. }
  10111. },
  10112. /**
  10113. * This function calculates the springforces on the nodes, accounting for the support nodes.
  10114. *
  10115. * @private
  10116. */
  10117. _calculateSpringForcesWithSupport : function() {
  10118. var edgeLength, edge, edgeId, combinedClusterSize;
  10119. var edges = this.edges;
  10120. // forces caused by the edges, modelled as springs
  10121. for (edgeId in edges) {
  10122. if (edges.hasOwnProperty(edgeId)) {
  10123. edge = edges[edgeId];
  10124. if (edge.connected) {
  10125. // only calculate forces if nodes are in the same sector
  10126. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  10127. if (edge.via != null) {
  10128. var node1 = edge.to;
  10129. var node2 = edge.via;
  10130. var node3 = edge.from;
  10131. edgeLength = edge.length;
  10132. combinedClusterSize = node1.clusterSize + node3.clusterSize - 2;
  10133. // this implies that the edges between big clusters are longer
  10134. edgeLength += combinedClusterSize * this.constants.clustering.edgeGrowth;
  10135. this._calculateSpringForce(node1,node2,0.5*edgeLength);
  10136. this._calculateSpringForce(node2,node3,0.5*edgeLength);
  10137. }
  10138. }
  10139. }
  10140. }
  10141. }
  10142. },
  10143. /**
  10144. * This is the code actually performing the calculation for the function above. It is split out to avoid repetition.
  10145. *
  10146. * @param node1
  10147. * @param node2
  10148. * @param edgeLength
  10149. * @private
  10150. */
  10151. _calculateSpringForce : function(node1,node2,edgeLength) {
  10152. var dx, dy, fx, fy, springForce, length;
  10153. dx = (node1.x - node2.x);
  10154. dy = (node1.y - node2.y);
  10155. length = Math.sqrt(dx * dx + dy * dy);
  10156. springForce = this.constants.physics.springConstant * (edgeLength - length) / length;
  10157. fx = dx * springForce;
  10158. fy = dy * springForce;
  10159. node1.fx += fx;
  10160. node1.fy += fy;
  10161. node2.fx -= fx;
  10162. node2.fy -= fy;
  10163. }
  10164. }
  10165. /**
  10166. * Created by Alex on 2/10/14.
  10167. */
  10168. var hierarchalRepulsionMixin = {
  10169. /**
  10170. * Calculate the forces the nodes apply on eachother based on a repulsion field.
  10171. * This field is linearly approximated.
  10172. *
  10173. * @private
  10174. */
  10175. _calculateNodeForces : function() {
  10176. var dx, dy, distance, fx, fy, combinedClusterSize,
  10177. repulsingForce, node1, node2, i, j;
  10178. var nodes = this.calculationNodes;
  10179. var nodeIndices = this.calculationNodeIndices;
  10180. // approximation constants
  10181. var b = 5;
  10182. var a_base = 0.5*-b;
  10183. // repulsing forces between nodes
  10184. var nodeDistance = this.constants.physics.repulsion.nodeDistance;
  10185. var minimumDistance = nodeDistance;
  10186. // we loop from i over all but the last entree in the array
  10187. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  10188. for (i = 0; i < nodeIndices.length-1; i++) {
  10189. node1 = nodes[nodeIndices[i]];
  10190. for (j = i+1; j < nodeIndices.length; j++) {
  10191. node2 = nodes[nodeIndices[j]];
  10192. dx = node2.x - node1.x;
  10193. dy = node2.y - node1.y;
  10194. distance = Math.sqrt(dx * dx + dy * dy);
  10195. var a = a_base / minimumDistance;
  10196. if (distance < 2*minimumDistance) {
  10197. repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness))
  10198. // normalize force with
  10199. if (distance == 0) {
  10200. distance = 0.01;
  10201. }
  10202. else {
  10203. repulsingForce = repulsingForce/distance;
  10204. }
  10205. fx = dx * repulsingForce;
  10206. fy = dy * repulsingForce;
  10207. node1.fx -= fx;
  10208. node1.fy -= fy;
  10209. node2.fx += fx;
  10210. node2.fy += fy;
  10211. }
  10212. }
  10213. }
  10214. }
  10215. }
  10216. /**
  10217. * Created by Alex on 2/10/14.
  10218. */
  10219. var barnesHutMixin = {
  10220. /**
  10221. * This function calculates the forces the nodes apply on eachother based on a gravitational model.
  10222. * The Barnes Hut method is used to speed up this N-body simulation.
  10223. *
  10224. * @private
  10225. */
  10226. _calculateNodeForces : function() {
  10227. var node;
  10228. var nodes = this.calculationNodes;
  10229. var nodeIndices = this.calculationNodeIndices;
  10230. var nodeCount = nodeIndices.length;
  10231. this._formBarnesHutTree(nodes,nodeIndices);
  10232. var barnesHutTree = this.barnesHutTree;
  10233. // place the nodes one by one recursively
  10234. for (var i = 0; i < nodeCount; i++) {
  10235. node = nodes[nodeIndices[i]];
  10236. // starting with root is irrelevant, it never passes the BarnesHut condition
  10237. this._getForceContribution(barnesHutTree.root.children.NW,node);
  10238. this._getForceContribution(barnesHutTree.root.children.NE,node);
  10239. this._getForceContribution(barnesHutTree.root.children.SW,node);
  10240. this._getForceContribution(barnesHutTree.root.children.SE,node);
  10241. }
  10242. },
  10243. /**
  10244. * This function traverses the barnesHutTree. It checks when it can approximate distant nodes with their center of mass.
  10245. * If a region contains a single node, we check if it is not itself, then we apply the force.
  10246. *
  10247. * @param parentBranch
  10248. * @param node
  10249. * @private
  10250. */
  10251. _getForceContribution : function(parentBranch,node) {
  10252. // we get no force contribution from an empty region
  10253. if (parentBranch.childrenCount > 0) {
  10254. var dx,dy,distance;
  10255. // get the distance from the center of mass to the node.
  10256. dx = parentBranch.centerOfMass.x - node.x;
  10257. dy = parentBranch.centerOfMass.y - node.y;
  10258. distance = Math.sqrt(dx * dx + dy * dy);
  10259. // BarnesHut condition
  10260. // original condition : s/d < theta = passed === d/s > 1/theta = passed
  10261. // calcSize = 1/s --> d * 1/s > 1/theta = passed
  10262. if (distance * parentBranch.calcSize > this.constants.physics.barnesHut.theta) {
  10263. // duplicate code to reduce function calls to speed up program
  10264. if (distance == 0) {
  10265. distance = 0.1*Math.random();
  10266. dx = distance;
  10267. }
  10268. var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.mass / (distance * distance * distance);
  10269. var fx = dx * gravityForce;
  10270. var fy = dy * gravityForce;
  10271. node.fx += fx;
  10272. node.fy += fy;
  10273. }
  10274. else {
  10275. // Did not pass the condition, go into children if available
  10276. if (parentBranch.childrenCount == 4) {
  10277. this._getForceContribution(parentBranch.children.NW,node);
  10278. this._getForceContribution(parentBranch.children.NE,node);
  10279. this._getForceContribution(parentBranch.children.SW,node);
  10280. this._getForceContribution(parentBranch.children.SE,node);
  10281. }
  10282. else { // parentBranch must have only one node, if it was empty we wouldnt be here
  10283. if (parentBranch.children.data.id != node.id) { // if it is not self
  10284. // duplicate code to reduce function calls to speed up program
  10285. if (distance == 0) {
  10286. distance = 0.5*Math.random();
  10287. dx = distance;
  10288. }
  10289. var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.mass / (distance * distance * distance);
  10290. var fx = dx * gravityForce;
  10291. var fy = dy * gravityForce;
  10292. node.fx += fx;
  10293. node.fy += fy;
  10294. }
  10295. }
  10296. }
  10297. }
  10298. },
  10299. /**
  10300. * This function constructs the barnesHut tree recursively. It creates the root, splits it and starts placing the nodes.
  10301. *
  10302. * @param nodes
  10303. * @param nodeIndices
  10304. * @private
  10305. */
  10306. _formBarnesHutTree : function(nodes,nodeIndices) {
  10307. var node;
  10308. var nodeCount = nodeIndices.length;
  10309. var minX = Number.MAX_VALUE,
  10310. minY = Number.MAX_VALUE,
  10311. maxX =-Number.MAX_VALUE,
  10312. maxY =-Number.MAX_VALUE;
  10313. // get the range of the nodes
  10314. for (var i = 0; i < nodeCount; i++) {
  10315. var x = nodes[nodeIndices[i]].x;
  10316. var y = nodes[nodeIndices[i]].y;
  10317. if (x < minX) { minX = x; }
  10318. if (x > maxX) { maxX = x; }
  10319. if (y < minY) { minY = y; }
  10320. if (y > maxY) { maxY = y; }
  10321. }
  10322. // make the range a square
  10323. var sizeDiff = Math.abs(maxX - minX) - Math.abs(maxY - minY); // difference between X and Y
  10324. if (sizeDiff > 0) {minY -= 0.5 * sizeDiff; maxY += 0.5 * sizeDiff;} // xSize > ySize
  10325. else {minX += 0.5 * sizeDiff; maxX -= 0.5 * sizeDiff;} // xSize < ySize
  10326. var minimumTreeSize = 1e-5;
  10327. var rootSize = Math.max(minimumTreeSize,Math.abs(maxX - minX));
  10328. var halfRootSize = 0.5 * rootSize;
  10329. var centerX = 0.5 * (minX + maxX), centerY = 0.5 * (minY + maxY);
  10330. // construct the barnesHutTree
  10331. var barnesHutTree = {root:{
  10332. centerOfMass:{x:0,y:0}, // Center of Mass
  10333. mass:0,
  10334. range: {minX:centerX-halfRootSize,maxX:centerX+halfRootSize,
  10335. minY:centerY-halfRootSize,maxY:centerY+halfRootSize},
  10336. size: rootSize,
  10337. calcSize: 1 / rootSize,
  10338. children: {data:null},
  10339. maxWidth: 0,
  10340. level: 0,
  10341. childrenCount: 4
  10342. }};
  10343. this._splitBranch(barnesHutTree.root);
  10344. // place the nodes one by one recursively
  10345. for (i = 0; i < nodeCount; i++) {
  10346. node = nodes[nodeIndices[i]];
  10347. this._placeInTree(barnesHutTree.root,node);
  10348. }
  10349. // make global
  10350. this.barnesHutTree = barnesHutTree
  10351. },
  10352. _updateBranchMass : function(parentBranch, node) {
  10353. var totalMass = parentBranch.mass + node.mass;
  10354. var totalMassInv = 1/totalMass;
  10355. parentBranch.centerOfMass.x = parentBranch.centerOfMass.x * parentBranch.mass + node.x * node.mass;
  10356. parentBranch.centerOfMass.x *= totalMassInv;
  10357. parentBranch.centerOfMass.y = parentBranch.centerOfMass.y * parentBranch.mass + node.y * node.mass;
  10358. parentBranch.centerOfMass.y *= totalMassInv;
  10359. parentBranch.mass = totalMass;
  10360. var biggestSize = Math.max(Math.max(node.height,node.radius),node.width);
  10361. parentBranch.maxWidth = (parentBranch.maxWidth < biggestSize) ? biggestSize : parentBranch.maxWidth;
  10362. },
  10363. _placeInTree : function(parentBranch,node,skipMassUpdate) {
  10364. if (skipMassUpdate != true || skipMassUpdate === undefined) {
  10365. // update the mass of the branch.
  10366. this._updateBranchMass(parentBranch,node);
  10367. }
  10368. if (parentBranch.children.NW.range.maxX > node.x) { // in NW or SW
  10369. if (parentBranch.children.NW.range.maxY > node.y) { // in NW
  10370. this._placeInRegion(parentBranch,node,"NW");
  10371. }
  10372. else { // in SW
  10373. this._placeInRegion(parentBranch,node,"SW");
  10374. }
  10375. }
  10376. else { // in NE or SE
  10377. if (parentBranch.children.NW.range.maxY > node.y) { // in NE
  10378. this._placeInRegion(parentBranch,node,"NE");
  10379. }
  10380. else { // in SE
  10381. this._placeInRegion(parentBranch,node,"SE");
  10382. }
  10383. }
  10384. },
  10385. _placeInRegion : function(parentBranch,node,region) {
  10386. switch (parentBranch.children[region].childrenCount) {
  10387. case 0: // place node here
  10388. parentBranch.children[region].children.data = node;
  10389. parentBranch.children[region].childrenCount = 1;
  10390. this._updateBranchMass(parentBranch.children[region],node);
  10391. break;
  10392. case 1: // convert into children
  10393. // if there are two nodes exactly overlapping (on init, on opening of cluster etc.)
  10394. // we move one node a pixel and we do not put it in the tree.
  10395. if (parentBranch.children[region].children.data.x == node.x &&
  10396. parentBranch.children[region].children.data.y == node.y) {
  10397. node.x += Math.random();
  10398. node.y += Math.random();
  10399. this._placeInTree(parentBranch,node, true);
  10400. }
  10401. else {
  10402. this._splitBranch(parentBranch.children[region]);
  10403. this._placeInTree(parentBranch.children[region],node);
  10404. }
  10405. break;
  10406. case 4: // place in branch
  10407. this._placeInTree(parentBranch.children[region],node);
  10408. break;
  10409. }
  10410. },
  10411. /**
  10412. * this function splits a branch into 4 sub branches. If the branch contained a node, we place it in the subbranch
  10413. * after the split is complete.
  10414. *
  10415. * @param parentBranch
  10416. * @private
  10417. */
  10418. _splitBranch : function(parentBranch) {
  10419. // if the branch is filled with a node, replace the node in the new subset.
  10420. var containedNode = null;
  10421. if (parentBranch.childrenCount == 1) {
  10422. containedNode = parentBranch.children.data;
  10423. parentBranch.mass = 0; parentBranch.centerOfMass.x = 0; parentBranch.centerOfMass.y = 0;
  10424. }
  10425. parentBranch.childrenCount = 4;
  10426. parentBranch.children.data = null;
  10427. this._insertRegion(parentBranch,"NW");
  10428. this._insertRegion(parentBranch,"NE");
  10429. this._insertRegion(parentBranch,"SW");
  10430. this._insertRegion(parentBranch,"SE");
  10431. if (containedNode != null) {
  10432. this._placeInTree(parentBranch,containedNode);
  10433. }
  10434. },
  10435. /**
  10436. * This function subdivides the region into four new segments.
  10437. * Specifically, this inserts a single new segment.
  10438. * It fills the children section of the parentBranch
  10439. *
  10440. * @param parentBranch
  10441. * @param region
  10442. * @param parentRange
  10443. * @private
  10444. */
  10445. _insertRegion : function(parentBranch, region) {
  10446. var minX,maxX,minY,maxY;
  10447. var childSize = 0.5 * parentBranch.size;
  10448. switch (region) {
  10449. case "NW":
  10450. minX = parentBranch.range.minX;
  10451. maxX = parentBranch.range.minX + childSize;
  10452. minY = parentBranch.range.minY;
  10453. maxY = parentBranch.range.minY + childSize;
  10454. break;
  10455. case "NE":
  10456. minX = parentBranch.range.minX + childSize;
  10457. maxX = parentBranch.range.maxX;
  10458. minY = parentBranch.range.minY;
  10459. maxY = parentBranch.range.minY + childSize;
  10460. break;
  10461. case "SW":
  10462. minX = parentBranch.range.minX;
  10463. maxX = parentBranch.range.minX + childSize;
  10464. minY = parentBranch.range.minY + childSize;
  10465. maxY = parentBranch.range.maxY;
  10466. break;
  10467. case "SE":
  10468. minX = parentBranch.range.minX + childSize;
  10469. maxX = parentBranch.range.maxX;
  10470. minY = parentBranch.range.minY + childSize;
  10471. maxY = parentBranch.range.maxY;
  10472. break;
  10473. }
  10474. parentBranch.children[region] = {
  10475. centerOfMass:{x:0,y:0},
  10476. mass:0,
  10477. range:{minX:minX,maxX:maxX,minY:minY,maxY:maxY},
  10478. size: 0.5 * parentBranch.size,
  10479. calcSize: 2 * parentBranch.calcSize,
  10480. children: {data:null},
  10481. maxWidth: 0,
  10482. level: parentBranch.level+1,
  10483. childrenCount: 0
  10484. };
  10485. },
  10486. /**
  10487. * This function is for debugging purposed, it draws the tree.
  10488. *
  10489. * @param ctx
  10490. * @param color
  10491. * @private
  10492. */
  10493. _drawTree : function(ctx,color) {
  10494. if (this.barnesHutTree !== undefined) {
  10495. ctx.lineWidth = 1;
  10496. this._drawBranch(this.barnesHutTree.root,ctx,color);
  10497. }
  10498. },
  10499. /**
  10500. * This function is for debugging purposes. It draws the branches recursively.
  10501. *
  10502. * @param branch
  10503. * @param ctx
  10504. * @param color
  10505. * @private
  10506. */
  10507. _drawBranch : function(branch,ctx,color) {
  10508. if (color === undefined) {
  10509. color = "#FF0000";
  10510. }
  10511. if (branch.childrenCount == 4) {
  10512. this._drawBranch(branch.children.NW,ctx);
  10513. this._drawBranch(branch.children.NE,ctx);
  10514. this._drawBranch(branch.children.SE,ctx);
  10515. this._drawBranch(branch.children.SW,ctx);
  10516. }
  10517. ctx.strokeStyle = color;
  10518. ctx.beginPath();
  10519. ctx.moveTo(branch.range.minX,branch.range.minY);
  10520. ctx.lineTo(branch.range.maxX,branch.range.minY);
  10521. ctx.stroke();
  10522. ctx.beginPath();
  10523. ctx.moveTo(branch.range.maxX,branch.range.minY);
  10524. ctx.lineTo(branch.range.maxX,branch.range.maxY);
  10525. ctx.stroke();
  10526. ctx.beginPath();
  10527. ctx.moveTo(branch.range.maxX,branch.range.maxY);
  10528. ctx.lineTo(branch.range.minX,branch.range.maxY);
  10529. ctx.stroke();
  10530. ctx.beginPath();
  10531. ctx.moveTo(branch.range.minX,branch.range.maxY);
  10532. ctx.lineTo(branch.range.minX,branch.range.minY);
  10533. ctx.stroke();
  10534. /*
  10535. if (branch.mass > 0) {
  10536. ctx.circle(branch.centerOfMass.x, branch.centerOfMass.y, 3*branch.mass);
  10537. ctx.stroke();
  10538. }
  10539. */
  10540. }
  10541. };
  10542. /**
  10543. * Created by Alex on 2/10/14.
  10544. */
  10545. var repulsionMixin = {
  10546. /**
  10547. * Calculate the forces the nodes apply on eachother based on a repulsion field.
  10548. * This field is linearly approximated.
  10549. *
  10550. * @private
  10551. */
  10552. _calculateNodeForces : function() {
  10553. var dx, dy, angle, distance, fx, fy, combinedClusterSize,
  10554. repulsingForce, node1, node2, i, j;
  10555. var nodes = this.calculationNodes;
  10556. var nodeIndices = this.calculationNodeIndices;
  10557. // approximation constants
  10558. var a_base = -2/3;
  10559. var b = 4/3;
  10560. // repulsing forces between nodes
  10561. var nodeDistance = this.constants.physics.repulsion.nodeDistance;
  10562. var minimumDistance = nodeDistance;
  10563. // we loop from i over all but the last entree in the array
  10564. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  10565. for (i = 0; i < nodeIndices.length-1; i++) {
  10566. node1 = nodes[nodeIndices[i]];
  10567. for (j = i+1; j < nodeIndices.length; j++) {
  10568. node2 = nodes[nodeIndices[j]];
  10569. combinedClusterSize = node1.clusterSize + node2.clusterSize - 2;
  10570. dx = node2.x - node1.x;
  10571. dy = node2.y - node1.y;
  10572. distance = Math.sqrt(dx * dx + dy * dy);
  10573. minimumDistance = (combinedClusterSize == 0) ? nodeDistance : (nodeDistance * (1 + combinedClusterSize * this.constants.clustering.distanceAmplification));
  10574. var a = a_base / minimumDistance;
  10575. if (distance < 2*minimumDistance) {
  10576. if (distance < 0.5*minimumDistance) {
  10577. repulsingForce = 1.0;
  10578. }
  10579. else {
  10580. repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness))
  10581. }
  10582. // amplify the repulsion for clusters.
  10583. repulsingForce *= (combinedClusterSize == 0) ? 1 : 1 + combinedClusterSize * this.constants.clustering.forceAmplification;
  10584. repulsingForce = repulsingForce/distance;
  10585. fx = dx * repulsingForce;
  10586. fy = dy * repulsingForce;
  10587. node1.fx -= fx;
  10588. node1.fy -= fy;
  10589. node2.fx += fx;
  10590. node2.fy += fy;
  10591. }
  10592. }
  10593. }
  10594. }
  10595. }
  10596. var HierarchicalLayoutMixin = {
  10597. /**
  10598. * This is the main function to layout the nodes in a hierarchical way.
  10599. * It checks if the node details are supplied correctly
  10600. *
  10601. * @private
  10602. */
  10603. _setupHierarchicalLayout : function() {
  10604. if (this.constants.hierarchicalLayout.enabled == true) {
  10605. // get the size of the largest hubs and check if the user has defined a level for a node.
  10606. var hubsize = 0;
  10607. var node, nodeId;
  10608. var definedLevel = false;
  10609. var undefinedLevel = false;
  10610. for (nodeId in this.nodes) {
  10611. if (this.nodes.hasOwnProperty(nodeId)) {
  10612. node = this.nodes[nodeId];
  10613. if (node.level != -1) {
  10614. definedLevel = true;
  10615. }
  10616. else {
  10617. undefinedLevel = true;
  10618. }
  10619. if (hubsize < node.edges.length) {
  10620. hubsize = node.edges.length;
  10621. }
  10622. }
  10623. }
  10624. // if the user defined some levels but not all, alert and run without hierarchical layout
  10625. if (undefinedLevel == true && definedLevel == true) {
  10626. alert("To use the hierarchical layout, nodes require either no predefined levels or levels have to be defined for all nodes.")
  10627. this.zoomToFit(true,this.constants.clustering.enabled);
  10628. if (!this.constants.clustering.enabled) {
  10629. this.start();
  10630. }
  10631. }
  10632. else {
  10633. // setup the system to use hierarchical method.
  10634. this._changeConstants();
  10635. // define levels if undefined by the users. Based on hubsize
  10636. if (undefinedLevel == true) {
  10637. this._determineLevels(hubsize);
  10638. }
  10639. // check the distribution of the nodes per level.
  10640. var distribution = this._getDistribution();
  10641. // place the nodes on the canvas. This also stablilizes the system.
  10642. this._placeNodesByHierarchy(distribution);
  10643. // start the simulation.
  10644. this.start();
  10645. }
  10646. }
  10647. },
  10648. /**
  10649. * This function places the nodes on the canvas based on the hierarchial distribution.
  10650. *
  10651. * @param {Object} distribution | obtained by the function this._getDistribution()
  10652. * @private
  10653. */
  10654. _placeNodesByHierarchy : function(distribution) {
  10655. var nodeId, node;
  10656. // start placing all the level 0 nodes first. Then recursively position their branches.
  10657. for (nodeId in distribution[0].nodes) {
  10658. if (distribution[0].nodes.hasOwnProperty(nodeId)) {
  10659. node = distribution[0].nodes[nodeId];
  10660. if (node.xFixed) {
  10661. node.x = distribution[0].minPos;
  10662. distribution[0].minPos += distribution[0].nodeSpacing;
  10663. node.xFixed = false;
  10664. }
  10665. this._placeBranchNodes(node.edges,node.id,distribution,node.level);
  10666. }
  10667. }
  10668. // give the nodes a defined width so the zoomToFit can be used. This size is arbitrary.
  10669. for (nodeId in this.nodes) {
  10670. if (this.nodes.hasOwnProperty(nodeId)) {
  10671. node = this.nodes[nodeId];
  10672. node.width = 100;
  10673. node.height = 100;
  10674. }
  10675. }
  10676. // stabilize the system after positioning. This function calls zoomToFit.
  10677. this._doStabilize();
  10678. // reset the arbitrary width and height we gave the nodes.
  10679. for (nodeId in this.nodes) {
  10680. if (this.nodes.hasOwnProperty(nodeId)) {
  10681. this.nodes[nodeId]._reset();
  10682. }
  10683. }
  10684. },
  10685. /**
  10686. * This function get the distribution of levels based on hubsize
  10687. *
  10688. * @returns {Object}
  10689. * @private
  10690. */
  10691. _getDistribution : function() {
  10692. var distribution = {};
  10693. var nodeId, node;
  10694. // 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.
  10695. // the fix of X is removed after the x value has been set.
  10696. for (nodeId in this.nodes) {
  10697. if (this.nodes.hasOwnProperty(nodeId)) {
  10698. node = this.nodes[nodeId];
  10699. node.xFixed = true;
  10700. node.yFixed = true;
  10701. node.y = this.constants.hierarchicalLayout.levelSeparation*node.level;
  10702. if (!distribution.hasOwnProperty(node.level)) {
  10703. distribution[node.level] = {amount: 0, nodes: {}, minPos:0, nodeSpacing:0};
  10704. }
  10705. distribution[node.level].amount += 1;
  10706. distribution[node.level].nodes[node.id] = node;
  10707. }
  10708. }
  10709. // determine the largest amount of nodes of all levels
  10710. var maxCount = 0;
  10711. for (var level in distribution) {
  10712. if (distribution.hasOwnProperty(level)) {
  10713. if (maxCount < distribution[level].amount) {
  10714. maxCount = distribution[level].amount;
  10715. }
  10716. }
  10717. }
  10718. // set the initial position and spacing of each nodes accordingly
  10719. for (var level in distribution) {
  10720. if (distribution.hasOwnProperty(level)) {
  10721. distribution[level].nodeSpacing = (maxCount + 1) * this.constants.hierarchicalLayout.nodeSpacing;
  10722. distribution[level].nodeSpacing /= (distribution[level].amount + 1);
  10723. distribution[level].minPos = distribution[level].nodeSpacing - (0.5 * (distribution[level].amount + 1) * distribution[level].nodeSpacing);
  10724. }
  10725. }
  10726. return distribution;
  10727. },
  10728. /**
  10729. * this function allocates nodes in levels based on the recursive branching from the largest hubs.
  10730. *
  10731. * @param hubsize
  10732. * @private
  10733. */
  10734. _determineLevels : function(hubsize) {
  10735. var nodeId, node;
  10736. // determine hubs
  10737. for (nodeId in this.nodes) {
  10738. if (this.nodes.hasOwnProperty(nodeId)) {
  10739. node = this.nodes[nodeId];
  10740. if (node.edges.length == hubsize) {
  10741. node.level = 0;
  10742. }
  10743. }
  10744. }
  10745. // branch from hubs
  10746. for (nodeId in this.nodes) {
  10747. if (this.nodes.hasOwnProperty(nodeId)) {
  10748. node = this.nodes[nodeId];
  10749. if (node.level == 0) {
  10750. this._setLevel(1,node.edges,node.id);
  10751. }
  10752. }
  10753. }
  10754. },
  10755. /**
  10756. * Since hierarchical layout does not support:
  10757. * - smooth curves (based on the physics),
  10758. * - clustering (based on dynamic node counts)
  10759. *
  10760. * We disable both features so there will be no problems.
  10761. *
  10762. * @private
  10763. */
  10764. _changeConstants : function() {
  10765. this.constants.clustering.enabled = false;
  10766. this.constants.physics.barnesHut.enabled = false;
  10767. this.constants.physics.hierarchicalRepulsion.enabled = true;
  10768. this._loadSelectedForceSolver();
  10769. this.constants.smoothCurves = false;
  10770. this._configureSmoothCurves();
  10771. },
  10772. /**
  10773. * This is a recursively called function to enumerate the branches from the largest hubs and place the nodes
  10774. * on a X position that ensures there will be no overlap.
  10775. *
  10776. * @param edges
  10777. * @param parentId
  10778. * @param distribution
  10779. * @param parentLevel
  10780. * @private
  10781. */
  10782. _placeBranchNodes : function(edges, parentId, distribution, parentLevel) {
  10783. for (var i = 0; i < edges.length; i++) {
  10784. var childNode = null;
  10785. if (edges[i].toId == parentId) {
  10786. childNode = edges[i].from;
  10787. }
  10788. else {
  10789. childNode = edges[i].to;
  10790. }
  10791. // if a node is conneceted to another node on the same level (or higher (means lower level))!, this is not handled here.
  10792. if (childNode.xFixed && childNode.level > parentLevel) {
  10793. childNode.xFixed = false;
  10794. childNode.x = distribution[childNode.level].minPos;
  10795. distribution[childNode.level].minPos += distribution[childNode.level].nodeSpacing;
  10796. if (childNode.edges.length > 1) {
  10797. this._placeBranchNodes(childNode.edges,childNode.id,distribution,childNode.level);
  10798. }
  10799. }
  10800. }
  10801. },
  10802. /**
  10803. * this function is called recursively to enumerate the barnches of the largest hubs and give each node a level.
  10804. *
  10805. * @param level
  10806. * @param edges
  10807. * @param parentId
  10808. * @private
  10809. */
  10810. _setLevel : function(level, edges, parentId) {
  10811. for (var i = 0; i < edges.length; i++) {
  10812. var childNode = null;
  10813. if (edges[i].toId == parentId) {
  10814. childNode = edges[i].from;
  10815. }
  10816. else {
  10817. childNode = edges[i].to;
  10818. }
  10819. if (childNode.level == -1 || childNode.level > level) {
  10820. childNode.level = level;
  10821. if (edges.length > 1) {
  10822. this._setLevel(level+1, childNode.edges, childNode.id);
  10823. }
  10824. }
  10825. }
  10826. }
  10827. };
  10828. /**
  10829. * Created by Alex on 2/4/14.
  10830. */
  10831. var manipulationMixin = {
  10832. /**
  10833. * clears the toolbar div element of children
  10834. *
  10835. * @private
  10836. */
  10837. _clearManipulatorBar : function() {
  10838. while (this.manipulationDiv.hasChildNodes()) {
  10839. this.manipulationDiv.removeChild(this.manipulationDiv.firstChild);
  10840. }
  10841. },
  10842. /**
  10843. * Manipulation UI temporarily overloads certain functions to extend or replace them. To be able to restore
  10844. * these functions to their original functionality, we saved them in this.cachedFunctions.
  10845. * This function restores these functions to their original function.
  10846. *
  10847. * @private
  10848. */
  10849. _restoreOverloadedFunctions : function() {
  10850. for (var functionName in this.cachedFunctions) {
  10851. if (this.cachedFunctions.hasOwnProperty(functionName)) {
  10852. this[functionName] = this.cachedFunctions[functionName];
  10853. }
  10854. }
  10855. },
  10856. /**
  10857. * Enable or disable edit-mode.
  10858. *
  10859. * @private
  10860. */
  10861. _toggleEditMode : function() {
  10862. this.editMode = !this.editMode;
  10863. var toolbar = document.getElementById("graph-manipulationDiv");
  10864. var closeDiv = document.getElementById("graph-manipulation-closeDiv");
  10865. var editModeDiv = document.getElementById("graph-manipulation-editMode");
  10866. if (this.editMode == true) {
  10867. toolbar.style.display="block";
  10868. closeDiv.style.display="block";
  10869. editModeDiv.style.display="none";
  10870. closeDiv.onclick = this._toggleEditMode.bind(this);
  10871. }
  10872. else {
  10873. toolbar.style.display="none";
  10874. closeDiv.style.display="none";
  10875. editModeDiv.style.display="block";
  10876. closeDiv.onclick = null;
  10877. }
  10878. this._createManipulatorBar()
  10879. },
  10880. /**
  10881. * main function, creates the main toolbar. Removes functions bound to the select event. Binds all the buttons of the toolbar.
  10882. *
  10883. * @private
  10884. */
  10885. _createManipulatorBar : function() {
  10886. // remove bound functions
  10887. this.off('select', this.boundFunction);
  10888. // restore overloaded functions
  10889. this._restoreOverloadedFunctions();
  10890. // resume calculation
  10891. this.freezeSimulation = false;
  10892. // reset global variables
  10893. this.blockConnectingEdgeSelection = false;
  10894. this.forceAppendSelection = false
  10895. if (this.editMode == true) {
  10896. while (this.manipulationDiv.hasChildNodes()) {
  10897. this.manipulationDiv.removeChild(this.manipulationDiv.firstChild);
  10898. }
  10899. // add the icons to the manipulator div
  10900. this.manipulationDiv.innerHTML = "" +
  10901. "<span class='graph-manipulationUI add' id='graph-manipulate-addNode'>" +
  10902. "<span class='graph-manipulationLabel'>Add Node</span></span>" +
  10903. "<div class='graph-seperatorLine'></div>" +
  10904. "<span class='graph-manipulationUI connect' id='graph-manipulate-connectNode'>" +
  10905. "<span class='graph-manipulationLabel'>Add Link</span></span>";
  10906. if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
  10907. this.manipulationDiv.innerHTML += "" +
  10908. "<div class='graph-seperatorLine'></div>" +
  10909. "<span class='graph-manipulationUI edit' id='graph-manipulate-editNode'>" +
  10910. "<span class='graph-manipulationLabel'>Edit Node</span></span>";
  10911. }
  10912. if (this._selectionIsEmpty() == false) {
  10913. this.manipulationDiv.innerHTML += "" +
  10914. "<div class='graph-seperatorLine'></div>" +
  10915. "<span class='graph-manipulationUI delete' id='graph-manipulate-delete'>" +
  10916. "<span class='graph-manipulationLabel'>Delete selected</span></span>";
  10917. }
  10918. // bind the icons
  10919. var addNodeButton = document.getElementById("graph-manipulate-addNode");
  10920. addNodeButton.onclick = this._createAddNodeToolbar.bind(this);
  10921. var addEdgeButton = document.getElementById("graph-manipulate-connectNode");
  10922. addEdgeButton.onclick = this._createAddEdgeToolbar.bind(this);
  10923. if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
  10924. var editButton = document.getElementById("graph-manipulate-editNode");
  10925. editButton.onclick = this._editNode.bind(this);
  10926. }
  10927. if (this._selectionIsEmpty() == false) {
  10928. var deleteButton = document.getElementById("graph-manipulate-delete");
  10929. deleteButton.onclick = this._deleteSelected.bind(this);
  10930. }
  10931. var closeDiv = document.getElementById("graph-manipulation-closeDiv");
  10932. closeDiv.onclick = this._toggleEditMode.bind(this);
  10933. this.boundFunction = this._createManipulatorBar.bind(this);
  10934. this.on('select', this.boundFunction);
  10935. }
  10936. else {
  10937. this.editModeDiv.innerHTML = "" +
  10938. "<span class='graph-manipulationUI edit editmode' id='graph-manipulate-editModeButton'>" +
  10939. "<span class='graph-manipulationLabel'>Edit</span></span>"
  10940. var editModeButton = document.getElementById("graph-manipulate-editModeButton");
  10941. editModeButton.onclick = this._toggleEditMode.bind(this);
  10942. }
  10943. },
  10944. /**
  10945. * Create the toolbar for adding Nodes
  10946. *
  10947. * @private
  10948. */
  10949. _createAddNodeToolbar : function() {
  10950. // clear the toolbar
  10951. this._clearManipulatorBar();
  10952. this.off('select', this.boundFunction);
  10953. // create the toolbar contents
  10954. this.manipulationDiv.innerHTML = "" +
  10955. "<span class='graph-manipulationUI back' id='graph-manipulate-back'>" +
  10956. "<span class='graph-manipulationLabel'>Back</span></span>" +
  10957. "<div class='graph-seperatorLine'></div>" +
  10958. "<span class='graph-manipulationUI none' id='graph-manipulate-back'>" +
  10959. "<span class='graph-manipulationLabel'>Click in an empty space to place a new node</span></span>";
  10960. // bind the icon
  10961. var backButton = document.getElementById("graph-manipulate-back");
  10962. backButton.onclick = this._createManipulatorBar.bind(this);
  10963. // we use the boundFunction so we can reference it when we unbind it from the "select" event.
  10964. this.boundFunction = this._addNode.bind(this);
  10965. this.on('select', this.boundFunction);
  10966. },
  10967. /**
  10968. * create the toolbar to connect nodes
  10969. *
  10970. * @private
  10971. */
  10972. _createAddEdgeToolbar : function() {
  10973. // clear the toolbar
  10974. this._clearManipulatorBar();
  10975. this._unselectAll(true);
  10976. this.freezeSimulation = true;
  10977. this.off('select', this.boundFunction);
  10978. this._unselectAll();
  10979. this.forceAppendSelection = false;
  10980. this.blockConnectingEdgeSelection = true;
  10981. this.manipulationDiv.innerHTML = "" +
  10982. "<span class='graph-manipulationUI back' id='graph-manipulate-back'>" +
  10983. "<span class='graph-manipulationLabel'>Back</span></span>" +
  10984. "<div class='graph-seperatorLine'></div>" +
  10985. "<span class='graph-manipulationUI none' id='graph-manipulate-back'>" +
  10986. "<span id='graph-manipulatorLabel' class='graph-manipulationLabel'>Click on a node and drag the edge to another node to connect them.</span></span>";
  10987. // bind the icon
  10988. var backButton = document.getElementById("graph-manipulate-back");
  10989. backButton.onclick = this._createManipulatorBar.bind(this);
  10990. // we use the boundFunction so we can reference it when we unbind it from the "select" event.
  10991. this.boundFunction = this._handleConnect.bind(this);
  10992. this.on('select', this.boundFunction);
  10993. // temporarily overload functions
  10994. this.cachedFunctions["_handleTouch"] = this._handleTouch;
  10995. this.cachedFunctions["_handleOnRelease"] = this._handleOnRelease;
  10996. this._handleTouch = this._handleConnect;
  10997. this._handleOnRelease = this._finishConnect;
  10998. // redraw to show the unselect
  10999. this._redraw();
  11000. },
  11001. /**
  11002. * the function bound to the selection event. It checks if you want to connect a cluster and changes the description
  11003. * to walk the user through the process.
  11004. *
  11005. * @private
  11006. */
  11007. _handleConnect : function(pointer) {
  11008. if (this._getSelectedNodeCount() == 0) {
  11009. var node = this._getNodeAt(pointer);
  11010. if (node != null) {
  11011. if (node.clusterSize > 1) {
  11012. alert("Cannot create edges to a cluster.")
  11013. }
  11014. else {
  11015. this._selectObject(node,false);
  11016. // create a node the temporary line can look at
  11017. this.sectors['support']['nodes']['targetNode'] = new Node({id:'targetNode'},{},{},this.constants);
  11018. this.sectors['support']['nodes']['targetNode'].x = node.x;
  11019. this.sectors['support']['nodes']['targetNode'].y = node.y;
  11020. this.sectors['support']['nodes']['targetViaNode'] = new Node({id:'targetViaNode'},{},{},this.constants);
  11021. this.sectors['support']['nodes']['targetViaNode'].x = node.x;
  11022. this.sectors['support']['nodes']['targetViaNode'].y = node.y;
  11023. this.sectors['support']['nodes']['targetViaNode'].parentEdgeId = "connectionEdge";
  11024. // create a temporary edge
  11025. this.edges['connectionEdge'] = new Edge({id:"connectionEdge",from:node.id,to:this.sectors['support']['nodes']['targetNode'].id}, this, this.constants);
  11026. this.edges['connectionEdge'].from = node;
  11027. this.edges['connectionEdge'].connected = true;
  11028. this.edges['connectionEdge'].smooth = true;
  11029. this.edges['connectionEdge'].selected = true;
  11030. this.edges['connectionEdge'].to = this.sectors['support']['nodes']['targetNode'];
  11031. this.edges['connectionEdge'].via = this.sectors['support']['nodes']['targetViaNode'];
  11032. this.cachedFunctions["_handleOnDrag"] = this._handleOnDrag;
  11033. this._handleOnDrag = function(event) {
  11034. var pointer = this._getPointer(event.gesture.center);
  11035. this.sectors['support']['nodes']['targetNode'].x = this._canvasToX(pointer.x);
  11036. this.sectors['support']['nodes']['targetNode'].y = this._canvasToY(pointer.y);
  11037. this.sectors['support']['nodes']['targetViaNode'].x = 0.5 * (this._canvasToX(pointer.x) + this.edges['connectionEdge'].from.x);
  11038. this.sectors['support']['nodes']['targetViaNode'].y = this._canvasToY(pointer.y);
  11039. };
  11040. this.moving = true;
  11041. this.start();
  11042. }
  11043. }
  11044. }
  11045. },
  11046. _finishConnect : function(pointer) {
  11047. if (this._getSelectedNodeCount() == 1) {
  11048. // restore the drag function
  11049. this._handleOnDrag = this.cachedFunctions["_handleOnDrag"];
  11050. delete this.cachedFunctions["_handleOnDrag"];
  11051. // remember the edge id
  11052. var connectFromId = this.edges['connectionEdge'].fromId;
  11053. // remove the temporary nodes and edge
  11054. delete this.edges['connectionEdge']
  11055. delete this.sectors['support']['nodes']['targetNode'];
  11056. delete this.sectors['support']['nodes']['targetViaNode'];
  11057. var node = this._getNodeAt(pointer);
  11058. if (node != null) {
  11059. if (node.clusterSize > 1) {
  11060. alert("Cannot create edges to a cluster.")
  11061. }
  11062. else {
  11063. this._createEdge(connectFromId,node.id);
  11064. this._createManipulatorBar();
  11065. }
  11066. }
  11067. this._unselectAll();
  11068. }
  11069. },
  11070. /**
  11071. * Adds a node on the specified location
  11072. *
  11073. * @param {Object} pointer
  11074. */
  11075. _addNode : function() {
  11076. if (this._selectionIsEmpty() && this.editMode == true) {
  11077. var positionObject = this._pointerToPositionObject(this.pointerPosition);
  11078. var defaultData = {id:util.randomUUID(),x:positionObject.left,y:positionObject.top,label:"new",allowedToMove:true};
  11079. if (this.triggerFunctions.add) {
  11080. if (this.triggerFunctions.add.length == 2) {
  11081. var me = this;
  11082. this.triggerFunctions.add(defaultData, function(finalizedData) {
  11083. me.createNodeOnClick = true;
  11084. me.nodesData.add(finalizedData);
  11085. me.createNodeOnClick = false;
  11086. me._createManipulatorBar();
  11087. me.moving = true;
  11088. me.start();
  11089. });
  11090. }
  11091. else {
  11092. alert("The function for add does not support two arguments (data,callback).");
  11093. this._createManipulatorBar();
  11094. this.moving = true;
  11095. this.start();
  11096. }
  11097. }
  11098. else {
  11099. this.createNodeOnClick = true;
  11100. this.nodesData.add(defaultData);
  11101. this.createNodeOnClick = false;
  11102. this._createManipulatorBar();
  11103. this.moving = true;
  11104. this.start();
  11105. }
  11106. }
  11107. },
  11108. /**
  11109. * connect two nodes with a new edge.
  11110. *
  11111. * @private
  11112. */
  11113. _createEdge : function(sourceNodeId,targetNodeId) {
  11114. if (this.editMode == true) {
  11115. var defaultData = {from:sourceNodeId, to:targetNodeId};
  11116. if (this.triggerFunctions.connect) {
  11117. if (this.triggerFunctions.connect.length == 2) {
  11118. var me = this;
  11119. this.triggerFunctions.connect(defaultData, function(finalizedData) {
  11120. me.edgesData.add(finalizedData)
  11121. me.moving = true;
  11122. me.start();
  11123. });
  11124. }
  11125. else {
  11126. alert("The function for connect does not support two arguments (data,callback).");
  11127. this.moving = true;
  11128. this.start();
  11129. }
  11130. }
  11131. else {
  11132. this.edgesData.add(defaultData)
  11133. this.moving = true;
  11134. this.start();
  11135. }
  11136. }
  11137. },
  11138. /**
  11139. * Create the toolbar to edit the selected node. The label and the color can be changed. Other colors are derived from the chosen color.
  11140. *
  11141. * @private
  11142. */
  11143. _editNode : function() {
  11144. if (this.triggerFunctions.edit && this.editMode == true) {
  11145. var node = this._getSelectedNode();
  11146. var data = {id:node.id,
  11147. label: node.label,
  11148. group: node.group,
  11149. shape: node.shape,
  11150. color: {
  11151. background:node.color.background,
  11152. border:node.color.border,
  11153. highlight: {
  11154. background:node.color.highlight.background,
  11155. border:node.color.highlight.border
  11156. }
  11157. }};
  11158. if (this.triggerFunctions.edit.length == 2) {
  11159. var me = this;
  11160. this.triggerFunctions.edit(data, function (finalizedData) {
  11161. me.nodesData.update(finalizedData);
  11162. me._createManipulatorBar();
  11163. me.moving = true;
  11164. me.start();
  11165. });
  11166. }
  11167. else {
  11168. alert("The function for edit does not support two arguments (data, callback).")
  11169. }
  11170. }
  11171. else {
  11172. alert("No edit function has been bound to this button.")
  11173. }
  11174. },
  11175. /**
  11176. * delete everything in the selection
  11177. *
  11178. * @private
  11179. */
  11180. _deleteSelected : function() {
  11181. if (!this._selectionIsEmpty() && this.editMode == true) {
  11182. if (!this._clusterInSelection()) {
  11183. var selectedNodes = this.getSelectedNodes();
  11184. var selectedEdges = this.getSelectedEdges();
  11185. if (this.triggerFunctions.delete) {
  11186. var me = this;
  11187. var data = {nodes: selectedNodes, edges: selectedEdges};
  11188. if (this.triggerFunctions.delete.length = 2) {
  11189. this.triggerFunctions.delete(data, function (finalizedData) {
  11190. me.edgesData.remove(finalizedData.edges);
  11191. me.nodesData.remove(finalizedData.nodes);
  11192. this._unselectAll();
  11193. me.moving = true;
  11194. me.start();
  11195. });
  11196. }
  11197. else {
  11198. alert("The function for edit does not support two arguments (data, callback).")
  11199. }
  11200. }
  11201. else {
  11202. this.edgesData.remove(selectedEdges);
  11203. this.nodesData.remove(selectedNodes);
  11204. this._unselectAll();
  11205. this.moving = true;
  11206. this.start();
  11207. }
  11208. }
  11209. else {
  11210. alert("Clusters cannot be deleted.");
  11211. }
  11212. }
  11213. }
  11214. };
  11215. /**
  11216. * Creation of the SectorMixin var.
  11217. *
  11218. * This contains all the functions the Graph object can use to employ the sector system.
  11219. * The sector system is always used by Graph, though the benefits only apply to the use of clustering.
  11220. * If clustering is not used, there is no overhead except for a duplicate object with references to nodes and edges.
  11221. *
  11222. * Alex de Mulder
  11223. * 21-01-2013
  11224. */
  11225. var SectorMixin = {
  11226. /**
  11227. * This function is only called by the setData function of the Graph object.
  11228. * This loads the global references into the active sector. This initializes the sector.
  11229. *
  11230. * @private
  11231. */
  11232. _putDataInSector : function() {
  11233. this.sectors["active"][this._sector()].nodes = this.nodes;
  11234. this.sectors["active"][this._sector()].edges = this.edges;
  11235. this.sectors["active"][this._sector()].nodeIndices = this.nodeIndices;
  11236. },
  11237. /**
  11238. * /**
  11239. * This function sets the global references to nodes, edges and nodeIndices back to
  11240. * those of the supplied (active) sector. If a type is defined, do the specific type
  11241. *
  11242. * @param {String} sectorId
  11243. * @param {String} [sectorType] | "active" or "frozen"
  11244. * @private
  11245. */
  11246. _switchToSector : function(sectorId, sectorType) {
  11247. if (sectorType === undefined || sectorType == "active") {
  11248. this._switchToActiveSector(sectorId);
  11249. }
  11250. else {
  11251. this._switchToFrozenSector(sectorId);
  11252. }
  11253. },
  11254. /**
  11255. * This function sets the global references to nodes, edges and nodeIndices back to
  11256. * those of the supplied active sector.
  11257. *
  11258. * @param sectorId
  11259. * @private
  11260. */
  11261. _switchToActiveSector : function(sectorId) {
  11262. this.nodeIndices = this.sectors["active"][sectorId]["nodeIndices"];
  11263. this.nodes = this.sectors["active"][sectorId]["nodes"];
  11264. this.edges = this.sectors["active"][sectorId]["edges"];
  11265. },
  11266. /**
  11267. * This function sets the global references to nodes, edges and nodeIndices back to
  11268. * those of the supplied active sector.
  11269. *
  11270. * @param sectorId
  11271. * @private
  11272. */
  11273. _switchToSupportSector : function() {
  11274. this.nodeIndices = this.sectors["support"]["nodeIndices"];
  11275. this.nodes = this.sectors["support"]["nodes"];
  11276. this.edges = this.sectors["support"]["edges"];
  11277. },
  11278. /**
  11279. * This function sets the global references to nodes, edges and nodeIndices back to
  11280. * those of the supplied frozen sector.
  11281. *
  11282. * @param sectorId
  11283. * @private
  11284. */
  11285. _switchToFrozenSector : function(sectorId) {
  11286. this.nodeIndices = this.sectors["frozen"][sectorId]["nodeIndices"];
  11287. this.nodes = this.sectors["frozen"][sectorId]["nodes"];
  11288. this.edges = this.sectors["frozen"][sectorId]["edges"];
  11289. },
  11290. /**
  11291. * This function sets the global references to nodes, edges and nodeIndices back to
  11292. * those of the currently active sector.
  11293. *
  11294. * @private
  11295. */
  11296. _loadLatestSector : function() {
  11297. this._switchToSector(this._sector());
  11298. },
  11299. /**
  11300. * This function returns the currently active sector Id
  11301. *
  11302. * @returns {String}
  11303. * @private
  11304. */
  11305. _sector : function() {
  11306. return this.activeSector[this.activeSector.length-1];
  11307. },
  11308. /**
  11309. * This function returns the previously active sector Id
  11310. *
  11311. * @returns {String}
  11312. * @private
  11313. */
  11314. _previousSector : function() {
  11315. if (this.activeSector.length > 1) {
  11316. return this.activeSector[this.activeSector.length-2];
  11317. }
  11318. else {
  11319. throw new TypeError('there are not enough sectors in the this.activeSector array.');
  11320. }
  11321. },
  11322. /**
  11323. * We add the active sector at the end of the this.activeSector array
  11324. * This ensures it is the currently active sector returned by _sector() and it reaches the top
  11325. * of the activeSector stack. When we reverse our steps we move from the end to the beginning of this stack.
  11326. *
  11327. * @param newId
  11328. * @private
  11329. */
  11330. _setActiveSector : function(newId) {
  11331. this.activeSector.push(newId);
  11332. },
  11333. /**
  11334. * We remove the currently active sector id from the active sector stack. This happens when
  11335. * we reactivate the previously active sector
  11336. *
  11337. * @private
  11338. */
  11339. _forgetLastSector : function() {
  11340. this.activeSector.pop();
  11341. },
  11342. /**
  11343. * This function creates a new active sector with the supplied newId. This newId
  11344. * is the expanding node id.
  11345. *
  11346. * @param {String} newId | Id of the new active sector
  11347. * @private
  11348. */
  11349. _createNewSector : function(newId) {
  11350. // create the new sector
  11351. this.sectors["active"][newId] = {"nodes":{},
  11352. "edges":{},
  11353. "nodeIndices":[],
  11354. "formationScale": this.scale,
  11355. "drawingNode": undefined};
  11356. // create the new sector render node. This gives visual feedback that you are in a new sector.
  11357. this.sectors["active"][newId]['drawingNode'] = new Node(
  11358. {id:newId,
  11359. color: {
  11360. background: "#eaefef",
  11361. border: "495c5e"
  11362. }
  11363. },{},{},this.constants);
  11364. this.sectors["active"][newId]['drawingNode'].clusterSize = 2;
  11365. },
  11366. /**
  11367. * This function removes the currently active sector. This is called when we create a new
  11368. * active sector.
  11369. *
  11370. * @param {String} sectorId | Id of the active sector that will be removed
  11371. * @private
  11372. */
  11373. _deleteActiveSector : function(sectorId) {
  11374. delete this.sectors["active"][sectorId];
  11375. },
  11376. /**
  11377. * This function removes the currently active sector. This is called when we reactivate
  11378. * the previously active sector.
  11379. *
  11380. * @param {String} sectorId | Id of the active sector that will be removed
  11381. * @private
  11382. */
  11383. _deleteFrozenSector : function(sectorId) {
  11384. delete this.sectors["frozen"][sectorId];
  11385. },
  11386. /**
  11387. * Freezing an active sector means moving it from the "active" object to the "frozen" object.
  11388. * We copy the references, then delete the active entree.
  11389. *
  11390. * @param sectorId
  11391. * @private
  11392. */
  11393. _freezeSector : function(sectorId) {
  11394. // we move the set references from the active to the frozen stack.
  11395. this.sectors["frozen"][sectorId] = this.sectors["active"][sectorId];
  11396. // we have moved the sector data into the frozen set, we now remove it from the active set
  11397. this._deleteActiveSector(sectorId);
  11398. },
  11399. /**
  11400. * This is the reverse operation of _freezeSector. Activating means moving the sector from the "frozen"
  11401. * object to the "active" object.
  11402. *
  11403. * @param sectorId
  11404. * @private
  11405. */
  11406. _activateSector : function(sectorId) {
  11407. // we move the set references from the frozen to the active stack.
  11408. this.sectors["active"][sectorId] = this.sectors["frozen"][sectorId];
  11409. // we have moved the sector data into the active set, we now remove it from the frozen stack
  11410. this._deleteFrozenSector(sectorId);
  11411. },
  11412. /**
  11413. * This function merges the data from the currently active sector with a frozen sector. This is used
  11414. * in the process of reverting back to the previously active sector.
  11415. * The data that is placed in the frozen (the previously active) sector is the node that has been removed from it
  11416. * upon the creation of a new active sector.
  11417. *
  11418. * @param sectorId
  11419. * @private
  11420. */
  11421. _mergeThisWithFrozen : function(sectorId) {
  11422. // copy all nodes
  11423. for (var nodeId in this.nodes) {
  11424. if (this.nodes.hasOwnProperty(nodeId)) {
  11425. this.sectors["frozen"][sectorId]["nodes"][nodeId] = this.nodes[nodeId];
  11426. }
  11427. }
  11428. // copy all edges (if not fully clustered, else there are no edges)
  11429. for (var edgeId in this.edges) {
  11430. if (this.edges.hasOwnProperty(edgeId)) {
  11431. this.sectors["frozen"][sectorId]["edges"][edgeId] = this.edges[edgeId];
  11432. }
  11433. }
  11434. // merge the nodeIndices
  11435. for (var i = 0; i < this.nodeIndices.length; i++) {
  11436. this.sectors["frozen"][sectorId]["nodeIndices"].push(this.nodeIndices[i]);
  11437. }
  11438. },
  11439. /**
  11440. * This clusters the sector to one cluster. It was a single cluster before this process started so
  11441. * we revert to that state. The clusterToFit function with a maximum size of 1 node does this.
  11442. *
  11443. * @private
  11444. */
  11445. _collapseThisToSingleCluster : function() {
  11446. this.clusterToFit(1,false);
  11447. },
  11448. /**
  11449. * We create a new active sector from the node that we want to open.
  11450. *
  11451. * @param node
  11452. * @private
  11453. */
  11454. _addSector : function(node) {
  11455. // this is the currently active sector
  11456. var sector = this._sector();
  11457. // // this should allow me to select nodes from a frozen set.
  11458. // if (this.sectors['active'][sector]["nodes"].hasOwnProperty(node.id)) {
  11459. // console.log("the node is part of the active sector");
  11460. // }
  11461. // else {
  11462. // console.log("I dont know what the fuck happened!!");
  11463. // }
  11464. // when we switch to a new sector, we remove the node that will be expanded from the current nodes list.
  11465. delete this.nodes[node.id];
  11466. var unqiueIdentifier = util.randomUUID();
  11467. // we fully freeze the currently active sector
  11468. this._freezeSector(sector);
  11469. // we create a new active sector. This sector has the Id of the node to ensure uniqueness
  11470. this._createNewSector(unqiueIdentifier);
  11471. // we add the active sector to the sectors array to be able to revert these steps later on
  11472. this._setActiveSector(unqiueIdentifier);
  11473. // we redirect the global references to the new sector's references. this._sector() now returns unqiueIdentifier
  11474. this._switchToSector(this._sector());
  11475. // finally we add the node we removed from our previous active sector to the new active sector
  11476. this.nodes[node.id] = node;
  11477. },
  11478. /**
  11479. * We close the sector that is currently open and revert back to the one before.
  11480. * If the active sector is the "default" sector, nothing happens.
  11481. *
  11482. * @private
  11483. */
  11484. _collapseSector : function() {
  11485. // the currently active sector
  11486. var sector = this._sector();
  11487. // we cannot collapse the default sector
  11488. if (sector != "default") {
  11489. if ((this.nodeIndices.length == 1) ||
  11490. (this.sectors["active"][sector]["drawingNode"].width*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  11491. (this.sectors["active"][sector]["drawingNode"].height*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  11492. var previousSector = this._previousSector();
  11493. // we collapse the sector back to a single cluster
  11494. this._collapseThisToSingleCluster();
  11495. // we move the remaining nodes, edges and nodeIndices to the previous sector.
  11496. // This previous sector is the one we will reactivate
  11497. this._mergeThisWithFrozen(previousSector);
  11498. // the previously active (frozen) sector now has all the data from the currently active sector.
  11499. // we can now delete the active sector.
  11500. this._deleteActiveSector(sector);
  11501. // we activate the previously active (and currently frozen) sector.
  11502. this._activateSector(previousSector);
  11503. // we load the references from the newly active sector into the global references
  11504. this._switchToSector(previousSector);
  11505. // we forget the previously active sector because we reverted to the one before
  11506. this._forgetLastSector();
  11507. // finally, we update the node index list.
  11508. this._updateNodeIndexList();
  11509. // we refresh the list with calulation nodes and calculation node indices.
  11510. this._updateCalculationNodes();
  11511. }
  11512. }
  11513. },
  11514. /**
  11515. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  11516. *
  11517. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11518. * | we dont pass the function itself because then the "this" is the window object
  11519. * | instead of the Graph object
  11520. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11521. * @private
  11522. */
  11523. _doInAllActiveSectors : function(runFunction,argument) {
  11524. if (argument === undefined) {
  11525. for (var sector in this.sectors["active"]) {
  11526. if (this.sectors["active"].hasOwnProperty(sector)) {
  11527. // switch the global references to those of this sector
  11528. this._switchToActiveSector(sector);
  11529. this[runFunction]();
  11530. }
  11531. }
  11532. }
  11533. else {
  11534. for (var sector in this.sectors["active"]) {
  11535. if (this.sectors["active"].hasOwnProperty(sector)) {
  11536. // switch the global references to those of this sector
  11537. this._switchToActiveSector(sector);
  11538. var args = Array.prototype.splice.call(arguments, 1);
  11539. if (args.length > 1) {
  11540. this[runFunction](args[0],args[1]);
  11541. }
  11542. else {
  11543. this[runFunction](argument);
  11544. }
  11545. }
  11546. }
  11547. }
  11548. // we revert the global references back to our active sector
  11549. this._loadLatestSector();
  11550. },
  11551. /**
  11552. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  11553. *
  11554. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11555. * | we dont pass the function itself because then the "this" is the window object
  11556. * | instead of the Graph object
  11557. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11558. * @private
  11559. */
  11560. _doInSupportSector : function(runFunction,argument) {
  11561. if (argument === undefined) {
  11562. this._switchToSupportSector();
  11563. this[runFunction]();
  11564. }
  11565. else {
  11566. this._switchToSupportSector();
  11567. var args = Array.prototype.splice.call(arguments, 1);
  11568. if (args.length > 1) {
  11569. this[runFunction](args[0],args[1]);
  11570. }
  11571. else {
  11572. this[runFunction](argument);
  11573. }
  11574. }
  11575. // we revert the global references back to our active sector
  11576. this._loadLatestSector();
  11577. },
  11578. /**
  11579. * This runs a function in all frozen sectors. This is used in the _redraw().
  11580. *
  11581. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11582. * | we don't pass the function itself because then the "this" is the window object
  11583. * | instead of the Graph object
  11584. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11585. * @private
  11586. */
  11587. _doInAllFrozenSectors : function(runFunction,argument) {
  11588. if (argument === undefined) {
  11589. for (var sector in this.sectors["frozen"]) {
  11590. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  11591. // switch the global references to those of this sector
  11592. this._switchToFrozenSector(sector);
  11593. this[runFunction]();
  11594. }
  11595. }
  11596. }
  11597. else {
  11598. for (var sector in this.sectors["frozen"]) {
  11599. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  11600. // switch the global references to those of this sector
  11601. this._switchToFrozenSector(sector);
  11602. var args = Array.prototype.splice.call(arguments, 1);
  11603. if (args.length > 1) {
  11604. this[runFunction](args[0],args[1]);
  11605. }
  11606. else {
  11607. this[runFunction](argument);
  11608. }
  11609. }
  11610. }
  11611. }
  11612. this._loadLatestSector();
  11613. },
  11614. /**
  11615. * This runs a function in all sectors. This is used in the _redraw().
  11616. *
  11617. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11618. * | we don't pass the function itself because then the "this" is the window object
  11619. * | instead of the Graph object
  11620. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11621. * @private
  11622. */
  11623. _doInAllSectors : function(runFunction,argument) {
  11624. var args = Array.prototype.splice.call(arguments, 1);
  11625. if (argument === undefined) {
  11626. this._doInAllActiveSectors(runFunction);
  11627. this._doInAllFrozenSectors(runFunction);
  11628. }
  11629. else {
  11630. if (args.length > 1) {
  11631. this._doInAllActiveSectors(runFunction,args[0],args[1]);
  11632. this._doInAllFrozenSectors(runFunction,args[0],args[1]);
  11633. }
  11634. else {
  11635. this._doInAllActiveSectors(runFunction,argument);
  11636. this._doInAllFrozenSectors(runFunction,argument);
  11637. }
  11638. }
  11639. },
  11640. /**
  11641. * This clears the nodeIndices list. We cannot use this.nodeIndices = [] because we would break the link with the
  11642. * active sector. Thus we clear the nodeIndices in the active sector, then reconnect the this.nodeIndices to it.
  11643. *
  11644. * @private
  11645. */
  11646. _clearNodeIndexList : function() {
  11647. var sector = this._sector();
  11648. this.sectors["active"][sector]["nodeIndices"] = [];
  11649. this.nodeIndices = this.sectors["active"][sector]["nodeIndices"];
  11650. },
  11651. /**
  11652. * Draw the encompassing sector node
  11653. *
  11654. * @param ctx
  11655. * @param sectorType
  11656. * @private
  11657. */
  11658. _drawSectorNodes : function(ctx,sectorType) {
  11659. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  11660. for (var sector in this.sectors[sectorType]) {
  11661. if (this.sectors[sectorType].hasOwnProperty(sector)) {
  11662. if (this.sectors[sectorType][sector]["drawingNode"] !== undefined) {
  11663. this._switchToSector(sector,sectorType);
  11664. minY = 1e9; maxY = -1e9; minX = 1e9; maxX = -1e9;
  11665. for (var nodeId in this.nodes) {
  11666. if (this.nodes.hasOwnProperty(nodeId)) {
  11667. node = this.nodes[nodeId];
  11668. node.resize(ctx);
  11669. if (minX > node.x - 0.5 * node.width) {minX = node.x - 0.5 * node.width;}
  11670. if (maxX < node.x + 0.5 * node.width) {maxX = node.x + 0.5 * node.width;}
  11671. if (minY > node.y - 0.5 * node.height) {minY = node.y - 0.5 * node.height;}
  11672. if (maxY < node.y + 0.5 * node.height) {maxY = node.y + 0.5 * node.height;}
  11673. }
  11674. }
  11675. node = this.sectors[sectorType][sector]["drawingNode"];
  11676. node.x = 0.5 * (maxX + minX);
  11677. node.y = 0.5 * (maxY + minY);
  11678. node.width = 2 * (node.x - minX);
  11679. node.height = 2 * (node.y - minY);
  11680. node.radius = Math.sqrt(Math.pow(0.5*node.width,2) + Math.pow(0.5*node.height,2));
  11681. node.setScale(this.scale);
  11682. node._drawCircle(ctx);
  11683. }
  11684. }
  11685. }
  11686. },
  11687. _drawAllSectorNodes : function(ctx) {
  11688. this._drawSectorNodes(ctx,"frozen");
  11689. this._drawSectorNodes(ctx,"active");
  11690. this._loadLatestSector();
  11691. }
  11692. };
  11693. /**
  11694. * Creation of the ClusterMixin var.
  11695. *
  11696. * This contains all the functions the Graph object can use to employ clustering
  11697. *
  11698. * Alex de Mulder
  11699. * 21-01-2013
  11700. */
  11701. var ClusterMixin = {
  11702. /**
  11703. * This is only called in the constructor of the graph object
  11704. *
  11705. */
  11706. startWithClustering : function() {
  11707. // cluster if the data set is big
  11708. this.clusterToFit(this.constants.clustering.initialMaxNodes, true);
  11709. // updates the lables after clustering
  11710. this.updateLabels();
  11711. // this is called here because if clusterin is disabled, the start and stabilize are called in
  11712. // the setData function.
  11713. if (this.stabilize) {
  11714. this._doStabilize();
  11715. }
  11716. this.start();
  11717. },
  11718. /**
  11719. * This function clusters until the initialMaxNodes has been reached
  11720. *
  11721. * @param {Number} maxNumberOfNodes
  11722. * @param {Boolean} reposition
  11723. */
  11724. clusterToFit : function(maxNumberOfNodes, reposition) {
  11725. var numberOfNodes = this.nodeIndices.length;
  11726. var maxLevels = 50;
  11727. var level = 0;
  11728. // we first cluster the hubs, then we pull in the outliers, repeat
  11729. while (numberOfNodes > maxNumberOfNodes && level < maxLevels) {
  11730. if (level % 3 == 0) {
  11731. this.forceAggregateHubs(true);
  11732. this.normalizeClusterLevels();
  11733. }
  11734. else {
  11735. this.increaseClusterLevel(); // this also includes a cluster normalization
  11736. }
  11737. numberOfNodes = this.nodeIndices.length;
  11738. level += 1;
  11739. }
  11740. // after the clustering we reposition the nodes to reduce the initial chaos
  11741. if (level > 0 && reposition == true) {
  11742. this.repositionNodes();
  11743. }
  11744. this._updateCalculationNodes();
  11745. },
  11746. /**
  11747. * This function can be called to open up a specific cluster. It is only called by
  11748. * It will unpack the cluster back one level.
  11749. *
  11750. * @param node | Node object: cluster to open.
  11751. */
  11752. openCluster : function(node) {
  11753. var isMovingBeforeClustering = this.moving;
  11754. if (node.clusterSize > this.constants.clustering.sectorThreshold && this._nodeInActiveArea(node) &&
  11755. !(this._sector() == "default" && this.nodeIndices.length == 1)) {
  11756. // this loads a new sector, loads the nodes and edges and nodeIndices of it.
  11757. this._addSector(node);
  11758. var level = 0;
  11759. // we decluster until we reach a decent number of nodes
  11760. while ((this.nodeIndices.length < this.constants.clustering.initialMaxNodes) && (level < 10)) {
  11761. this.decreaseClusterLevel();
  11762. level += 1;
  11763. }
  11764. }
  11765. else {
  11766. this._expandClusterNode(node,false,true);
  11767. // update the index list, dynamic edges and labels
  11768. this._updateNodeIndexList();
  11769. this._updateDynamicEdges();
  11770. this._updateCalculationNodes();
  11771. this.updateLabels();
  11772. }
  11773. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  11774. if (this.moving != isMovingBeforeClustering) {
  11775. this.start();
  11776. }
  11777. },
  11778. /**
  11779. * This calls the updateClustes with default arguments
  11780. */
  11781. updateClustersDefault : function() {
  11782. if (this.constants.clustering.enabled == true) {
  11783. this.updateClusters(0,false,false);
  11784. }
  11785. },
  11786. /**
  11787. * This function can be called to increase the cluster level. This means that the nodes with only one edge connection will
  11788. * be clustered with their connected node. This can be repeated as many times as needed.
  11789. * This can be called externally (by a keybind for instance) to reduce the complexity of big datasets.
  11790. */
  11791. increaseClusterLevel : function() {
  11792. this.updateClusters(-1,false,true);
  11793. },
  11794. /**
  11795. * This function can be called to decrease the cluster level. This means that the nodes with only one edge connection will
  11796. * be unpacked if they are a cluster. This can be repeated as many times as needed.
  11797. * This can be called externally (by a key-bind for instance) to look into clusters without zooming.
  11798. */
  11799. decreaseClusterLevel : function() {
  11800. this.updateClusters(1,false,true);
  11801. },
  11802. /**
  11803. * This is the main clustering function. It clusters and declusters on zoom or forced
  11804. * This function clusters on zoom, it can be called with a predefined zoom direction
  11805. * If out, check if we can form clusters, if in, check if we can open clusters.
  11806. * This function is only called from _zoom()
  11807. *
  11808. * @param {Number} zoomDirection | -1 / 0 / +1 for zoomOut / determineByZoom / zoomIn
  11809. * @param {Boolean} recursive | enabled or disable recursive calling of the opening of clusters
  11810. * @param {Boolean} force | enabled or disable forcing
  11811. *
  11812. */
  11813. updateClusters : function(zoomDirection,recursive,force,doNotStart) {
  11814. var isMovingBeforeClustering = this.moving;
  11815. var amountOfNodes = this.nodeIndices.length;
  11816. // on zoom out collapse the sector if the scale is at the level the sector was made
  11817. if (this.previousScale > this.scale && zoomDirection == 0) {
  11818. this._collapseSector();
  11819. }
  11820. // check if we zoom in or out
  11821. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  11822. // forming clusters when forced pulls outliers in. When not forced, the edge length of the
  11823. // outer nodes determines if it is being clustered
  11824. this._formClusters(force);
  11825. }
  11826. else if (this.previousScale < this.scale || zoomDirection == 1) { // zoom in
  11827. if (force == true) {
  11828. // _openClusters checks for each node if the formationScale of the cluster is smaller than
  11829. // the current scale and if so, declusters. When forced, all clusters are reduced by one step
  11830. this._openClusters(recursive,force);
  11831. }
  11832. else {
  11833. // if a cluster takes up a set percentage of the active window
  11834. this._openClustersBySize();
  11835. }
  11836. }
  11837. this._updateNodeIndexList();
  11838. // if a cluster was NOT formed and the user zoomed out, we try clustering by hubs
  11839. if (this.nodeIndices.length == amountOfNodes && (this.previousScale > this.scale || zoomDirection == -1)) {
  11840. this._aggregateHubs(force);
  11841. this._updateNodeIndexList();
  11842. }
  11843. // we now reduce chains.
  11844. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  11845. this.handleChains();
  11846. this._updateNodeIndexList();
  11847. }
  11848. this.previousScale = this.scale;
  11849. // rest of the update the index list, dynamic edges and labels
  11850. this._updateDynamicEdges();
  11851. this.updateLabels();
  11852. // if a cluster was formed, we increase the clusterSession
  11853. if (this.nodeIndices.length < amountOfNodes) { // this means a clustering operation has taken place
  11854. this.clusterSession += 1;
  11855. // if clusters have been made, we normalize the cluster level
  11856. this.normalizeClusterLevels();
  11857. }
  11858. if (doNotStart == false || doNotStart === undefined) {
  11859. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  11860. if (this.moving != isMovingBeforeClustering) {
  11861. this.start();
  11862. }
  11863. }
  11864. this._updateCalculationNodes();
  11865. },
  11866. /**
  11867. * This function handles the chains. It is called on every updateClusters().
  11868. */
  11869. handleChains : function() {
  11870. // after clustering we check how many chains there are
  11871. var chainPercentage = this._getChainFraction();
  11872. if (chainPercentage > this.constants.clustering.chainThreshold) {
  11873. this._reduceAmountOfChains(1 - this.constants.clustering.chainThreshold / chainPercentage)
  11874. }
  11875. },
  11876. /**
  11877. * this functions starts clustering by hubs
  11878. * The minimum hub threshold is set globally
  11879. *
  11880. * @private
  11881. */
  11882. _aggregateHubs : function(force) {
  11883. this._getHubSize();
  11884. this._formClustersByHub(force,false);
  11885. },
  11886. /**
  11887. * This function is fired by keypress. It forces hubs to form.
  11888. *
  11889. */
  11890. forceAggregateHubs : function(doNotStart) {
  11891. var isMovingBeforeClustering = this.moving;
  11892. var amountOfNodes = this.nodeIndices.length;
  11893. this._aggregateHubs(true);
  11894. // update the index list, dynamic edges and labels
  11895. this._updateNodeIndexList();
  11896. this._updateDynamicEdges();
  11897. this.updateLabels();
  11898. // if a cluster was formed, we increase the clusterSession
  11899. if (this.nodeIndices.length != amountOfNodes) {
  11900. this.clusterSession += 1;
  11901. }
  11902. if (doNotStart == false || doNotStart === undefined) {
  11903. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  11904. if (this.moving != isMovingBeforeClustering) {
  11905. this.start();
  11906. }
  11907. }
  11908. },
  11909. /**
  11910. * If a cluster takes up more than a set percentage of the screen, open the cluster
  11911. *
  11912. * @private
  11913. */
  11914. _openClustersBySize : function() {
  11915. for (var nodeId in this.nodes) {
  11916. if (this.nodes.hasOwnProperty(nodeId)) {
  11917. var node = this.nodes[nodeId];
  11918. if (node.inView() == true) {
  11919. if ((node.width*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  11920. (node.height*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  11921. this.openCluster(node);
  11922. }
  11923. }
  11924. }
  11925. }
  11926. },
  11927. /**
  11928. * This function loops over all nodes in the nodeIndices list. For each node it checks if it is a cluster and if it
  11929. * has to be opened based on the current zoom level.
  11930. *
  11931. * @private
  11932. */
  11933. _openClusters : function(recursive,force) {
  11934. for (var i = 0; i < this.nodeIndices.length; i++) {
  11935. var node = this.nodes[this.nodeIndices[i]];
  11936. this._expandClusterNode(node,recursive,force);
  11937. this._updateCalculationNodes();
  11938. }
  11939. },
  11940. /**
  11941. * This function checks if a node has to be opened. This is done by checking the zoom level.
  11942. * If the node contains child nodes, this function is recursively called on the child nodes as well.
  11943. * This recursive behaviour is optional and can be set by the recursive argument.
  11944. *
  11945. * @param {Node} parentNode | to check for cluster and expand
  11946. * @param {Boolean} recursive | enabled or disable recursive calling
  11947. * @param {Boolean} force | enabled or disable forcing
  11948. * @param {Boolean} [openAll] | This will recursively force all nodes in the parent to be released
  11949. * @private
  11950. */
  11951. _expandClusterNode : function(parentNode, recursive, force, openAll) {
  11952. // first check if node is a cluster
  11953. if (parentNode.clusterSize > 1) {
  11954. // this means that on a double tap event or a zoom event, the cluster fully unpacks if it is smaller than 20
  11955. if (parentNode.clusterSize < this.constants.clustering.sectorThreshold) {
  11956. openAll = true;
  11957. }
  11958. recursive = openAll ? true : recursive;
  11959. // if the last child has been added on a smaller scale than current scale decluster
  11960. if (parentNode.formationScale < this.scale || force == true) {
  11961. // we will check if any of the contained child nodes should be removed from the cluster
  11962. for (var containedNodeId in parentNode.containedNodes) {
  11963. if (parentNode.containedNodes.hasOwnProperty(containedNodeId)) {
  11964. var childNode = parentNode.containedNodes[containedNodeId];
  11965. // force expand will expand the largest cluster size clusters. Since we cluster from outside in, we assume that
  11966. // the largest cluster is the one that comes from outside
  11967. if (force == true) {
  11968. if (childNode.clusterSession == parentNode.clusterSessions[parentNode.clusterSessions.length-1]
  11969. || openAll) {
  11970. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  11971. }
  11972. }
  11973. else {
  11974. if (this._nodeInActiveArea(parentNode)) {
  11975. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  11976. }
  11977. }
  11978. }
  11979. }
  11980. }
  11981. }
  11982. },
  11983. /**
  11984. * ONLY CALLED FROM _expandClusterNode
  11985. *
  11986. * This function will expel a child_node from a parent_node. This is to de-cluster the node. This function will remove
  11987. * the child node from the parent contained_node object and put it back into the global nodes object.
  11988. * The same holds for the edge that was connected to the child node. It is moved back into the global edges object.
  11989. *
  11990. * @param {Node} parentNode | the parent node
  11991. * @param {String} containedNodeId | child_node id as it is contained in the containedNodes object of the parent node
  11992. * @param {Boolean} recursive | This will also check if the child needs to be expanded.
  11993. * With force and recursive both true, the entire cluster is unpacked
  11994. * @param {Boolean} force | This will disregard the zoom level and will expel this child from the parent
  11995. * @param {Boolean} openAll | This will recursively force all nodes in the parent to be released
  11996. * @private
  11997. */
  11998. _expelChildFromParent : function(parentNode, containedNodeId, recursive, force, openAll) {
  11999. var childNode = parentNode.containedNodes[containedNodeId];
  12000. // if child node has been added on smaller scale than current, kick out
  12001. if (childNode.formationScale < this.scale || force == true) {
  12002. // unselect all selected items
  12003. this._unselectAll();
  12004. // put the child node back in the global nodes object
  12005. this.nodes[containedNodeId] = childNode;
  12006. // release the contained edges from this childNode back into the global edges
  12007. this._releaseContainedEdges(parentNode,childNode);
  12008. // reconnect rerouted edges to the childNode
  12009. this._connectEdgeBackToChild(parentNode,childNode);
  12010. // validate all edges in dynamicEdges
  12011. this._validateEdges(parentNode);
  12012. // undo the changes from the clustering operation on the parent node
  12013. parentNode.mass -= childNode.mass;
  12014. parentNode.clusterSize -= childNode.clusterSize;
  12015. parentNode.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize);
  12016. parentNode.dynamicEdgesLength = parentNode.dynamicEdges.length;
  12017. // place the child node near the parent, not at the exact same location to avoid chaos in the system
  12018. childNode.x = parentNode.x + parentNode.growthIndicator * (0.5 - Math.random());
  12019. childNode.y = parentNode.y + parentNode.growthIndicator * (0.5 - Math.random());
  12020. // remove node from the list
  12021. delete parentNode.containedNodes[containedNodeId];
  12022. // check if there are other childs with this clusterSession in the parent.
  12023. var othersPresent = false;
  12024. for (var childNodeId in parentNode.containedNodes) {
  12025. if (parentNode.containedNodes.hasOwnProperty(childNodeId)) {
  12026. if (parentNode.containedNodes[childNodeId].clusterSession == childNode.clusterSession) {
  12027. othersPresent = true;
  12028. break;
  12029. }
  12030. }
  12031. }
  12032. // if there are no others, remove the cluster session from the list
  12033. if (othersPresent == false) {
  12034. parentNode.clusterSessions.pop();
  12035. }
  12036. this._repositionBezierNodes(childNode);
  12037. // this._repositionBezierNodes(parentNode);
  12038. // remove the clusterSession from the child node
  12039. childNode.clusterSession = 0;
  12040. // recalculate the size of the node on the next time the node is rendered
  12041. parentNode.clearSizeCache();
  12042. // restart the simulation to reorganise all nodes
  12043. this.moving = true;
  12044. }
  12045. // check if a further expansion step is possible if recursivity is enabled
  12046. if (recursive == true) {
  12047. this._expandClusterNode(childNode,recursive,force,openAll);
  12048. }
  12049. },
  12050. /**
  12051. * position the bezier nodes at the center of the edges
  12052. *
  12053. * @param node
  12054. * @private
  12055. */
  12056. _repositionBezierNodes : function(node) {
  12057. for (var i = 0; i < node.dynamicEdges.length; i++) {
  12058. node.dynamicEdges[i].positionBezierNode();
  12059. }
  12060. },
  12061. /**
  12062. * This function checks if any nodes at the end of their trees have edges below a threshold length
  12063. * This function is called only from updateClusters()
  12064. * forceLevelCollapse ignores the length of the edge and collapses one level
  12065. * This means that a node with only one edge will be clustered with its connected node
  12066. *
  12067. * @private
  12068. * @param {Boolean} force
  12069. */
  12070. _formClusters : function(force) {
  12071. if (force == false) {
  12072. this._formClustersByZoom();
  12073. }
  12074. else {
  12075. this._forceClustersByZoom();
  12076. }
  12077. },
  12078. /**
  12079. * This function handles the clustering by zooming out, this is based on a minimum edge distance
  12080. *
  12081. * @private
  12082. */
  12083. _formClustersByZoom : function() {
  12084. var dx,dy,length,
  12085. minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  12086. // check if any edges are shorter than minLength and start the clustering
  12087. // the clustering favours the node with the larger mass
  12088. for (var edgeId in this.edges) {
  12089. if (this.edges.hasOwnProperty(edgeId)) {
  12090. var edge = this.edges[edgeId];
  12091. if (edge.connected) {
  12092. if (edge.toId != edge.fromId) {
  12093. dx = (edge.to.x - edge.from.x);
  12094. dy = (edge.to.y - edge.from.y);
  12095. length = Math.sqrt(dx * dx + dy * dy);
  12096. if (length < minLength) {
  12097. // first check which node is larger
  12098. var parentNode = edge.from;
  12099. var childNode = edge.to;
  12100. if (edge.to.mass > edge.from.mass) {
  12101. parentNode = edge.to;
  12102. childNode = edge.from;
  12103. }
  12104. if (childNode.dynamicEdgesLength == 1) {
  12105. this._addToCluster(parentNode,childNode,false);
  12106. }
  12107. else if (parentNode.dynamicEdgesLength == 1) {
  12108. this._addToCluster(childNode,parentNode,false);
  12109. }
  12110. }
  12111. }
  12112. }
  12113. }
  12114. }
  12115. },
  12116. /**
  12117. * This function forces the graph to cluster all nodes with only one connecting edge to their
  12118. * connected node.
  12119. *
  12120. * @private
  12121. */
  12122. _forceClustersByZoom : function() {
  12123. for (var nodeId in this.nodes) {
  12124. // another node could have absorbed this child.
  12125. if (this.nodes.hasOwnProperty(nodeId)) {
  12126. var childNode = this.nodes[nodeId];
  12127. // the edges can be swallowed by another decrease
  12128. if (childNode.dynamicEdgesLength == 1 && childNode.dynamicEdges.length != 0) {
  12129. var edge = childNode.dynamicEdges[0];
  12130. var parentNode = (edge.toId == childNode.id) ? this.nodes[edge.fromId] : this.nodes[edge.toId];
  12131. // group to the largest node
  12132. if (childNode.id != parentNode.id) {
  12133. if (parentNode.mass > childNode.mass) {
  12134. this._addToCluster(parentNode,childNode,true);
  12135. }
  12136. else {
  12137. this._addToCluster(childNode,parentNode,true);
  12138. }
  12139. }
  12140. }
  12141. }
  12142. }
  12143. },
  12144. /**
  12145. * To keep the nodes of roughly equal size we normalize the cluster levels.
  12146. * This function clusters a node to its smallest connected neighbour.
  12147. *
  12148. * @param node
  12149. * @private
  12150. */
  12151. _clusterToSmallestNeighbour : function(node) {
  12152. var smallestNeighbour = -1;
  12153. var smallestNeighbourNode = null;
  12154. for (var i = 0; i < node.dynamicEdges.length; i++) {
  12155. if (node.dynamicEdges[i] !== undefined) {
  12156. var neighbour = null;
  12157. if (node.dynamicEdges[i].fromId != node.id) {
  12158. neighbour = node.dynamicEdges[i].from;
  12159. }
  12160. else if (node.dynamicEdges[i].toId != node.id) {
  12161. neighbour = node.dynamicEdges[i].to;
  12162. }
  12163. if (neighbour != null && smallestNeighbour > neighbour.clusterSessions.length) {
  12164. smallestNeighbour = neighbour.clusterSessions.length;
  12165. smallestNeighbourNode = neighbour;
  12166. }
  12167. }
  12168. }
  12169. if (neighbour != null && this.nodes[neighbour.id] !== undefined) {
  12170. this._addToCluster(neighbour, node, true);
  12171. }
  12172. },
  12173. /**
  12174. * This function forms clusters from hubs, it loops over all nodes
  12175. *
  12176. * @param {Boolean} force | Disregard zoom level
  12177. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  12178. * @private
  12179. */
  12180. _formClustersByHub : function(force, onlyEqual) {
  12181. // we loop over all nodes in the list
  12182. for (var nodeId in this.nodes) {
  12183. // we check if it is still available since it can be used by the clustering in this loop
  12184. if (this.nodes.hasOwnProperty(nodeId)) {
  12185. this._formClusterFromHub(this.nodes[nodeId],force,onlyEqual);
  12186. }
  12187. }
  12188. },
  12189. /**
  12190. * This function forms a cluster from a specific preselected hub node
  12191. *
  12192. * @param {Node} hubNode | the node we will cluster as a hub
  12193. * @param {Boolean} force | Disregard zoom level
  12194. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  12195. * @param {Number} [absorptionSizeOffset] |
  12196. * @private
  12197. */
  12198. _formClusterFromHub : function(hubNode, force, onlyEqual, absorptionSizeOffset) {
  12199. if (absorptionSizeOffset === undefined) {
  12200. absorptionSizeOffset = 0;
  12201. }
  12202. // we decide if the node is a hub
  12203. if ((hubNode.dynamicEdgesLength >= this.hubThreshold && onlyEqual == false) ||
  12204. (hubNode.dynamicEdgesLength == this.hubThreshold && onlyEqual == true)) {
  12205. // initialize variables
  12206. var dx,dy,length;
  12207. var minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  12208. var allowCluster = false;
  12209. // we create a list of edges because the dynamicEdges change over the course of this loop
  12210. var edgesIdarray = [];
  12211. var amountOfInitialEdges = hubNode.dynamicEdges.length;
  12212. for (var j = 0; j < amountOfInitialEdges; j++) {
  12213. edgesIdarray.push(hubNode.dynamicEdges[j].id);
  12214. }
  12215. // if the hub clustering is not forces, we check if one of the edges connected
  12216. // to a cluster is small enough based on the constants.clustering.clusterEdgeThreshold
  12217. if (force == false) {
  12218. allowCluster = false;
  12219. for (j = 0; j < amountOfInitialEdges; j++) {
  12220. var edge = this.edges[edgesIdarray[j]];
  12221. if (edge !== undefined) {
  12222. if (edge.connected) {
  12223. if (edge.toId != edge.fromId) {
  12224. dx = (edge.to.x - edge.from.x);
  12225. dy = (edge.to.y - edge.from.y);
  12226. length = Math.sqrt(dx * dx + dy * dy);
  12227. if (length < minLength) {
  12228. allowCluster = true;
  12229. break;
  12230. }
  12231. }
  12232. }
  12233. }
  12234. }
  12235. }
  12236. // start the clustering if allowed
  12237. if ((!force && allowCluster) || force) {
  12238. // we loop over all edges INITIALLY connected to this hub
  12239. for (j = 0; j < amountOfInitialEdges; j++) {
  12240. edge = this.edges[edgesIdarray[j]];
  12241. // the edge can be clustered by this function in a previous loop
  12242. if (edge !== undefined) {
  12243. var childNode = this.nodes[(edge.fromId == hubNode.id) ? edge.toId : edge.fromId];
  12244. // we do not want hubs to merge with other hubs nor do we want to cluster itself.
  12245. if ((childNode.dynamicEdges.length <= (this.hubThreshold + absorptionSizeOffset)) &&
  12246. (childNode.id != hubNode.id)) {
  12247. this._addToCluster(hubNode,childNode,force);
  12248. }
  12249. }
  12250. }
  12251. }
  12252. }
  12253. },
  12254. /**
  12255. * This function adds the child node to the parent node, creating a cluster if it is not already.
  12256. *
  12257. * @param {Node} parentNode | this is the node that will house the child node
  12258. * @param {Node} childNode | this node will be deleted from the global this.nodes and stored in the parent node
  12259. * @param {Boolean} force | true will only update the remainingEdges at the very end of the clustering, ensuring single level collapse
  12260. * @private
  12261. */
  12262. _addToCluster : function(parentNode, childNode, force) {
  12263. // join child node in the parent node
  12264. parentNode.containedNodes[childNode.id] = childNode;
  12265. // manage all the edges connected to the child and parent nodes
  12266. for (var i = 0; i < childNode.dynamicEdges.length; i++) {
  12267. var edge = childNode.dynamicEdges[i];
  12268. if (edge.toId == parentNode.id || edge.fromId == parentNode.id) { // edge connected to parentNode
  12269. this._addToContainedEdges(parentNode,childNode,edge);
  12270. }
  12271. else {
  12272. this._connectEdgeToCluster(parentNode,childNode,edge);
  12273. }
  12274. }
  12275. // a contained node has no dynamic edges.
  12276. childNode.dynamicEdges = [];
  12277. // remove circular edges from clusters
  12278. this._containCircularEdgesFromNode(parentNode,childNode);
  12279. // remove the childNode from the global nodes object
  12280. delete this.nodes[childNode.id];
  12281. // update the properties of the child and parent
  12282. var massBefore = parentNode.mass;
  12283. childNode.clusterSession = this.clusterSession;
  12284. parentNode.mass += childNode.mass;
  12285. parentNode.clusterSize += childNode.clusterSize;
  12286. parentNode.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize);
  12287. // keep track of the clustersessions so we can open the cluster up as it has been formed.
  12288. if (parentNode.clusterSessions[parentNode.clusterSessions.length - 1] != this.clusterSession) {
  12289. parentNode.clusterSessions.push(this.clusterSession);
  12290. }
  12291. // forced clusters only open from screen size and double tap
  12292. if (force == true) {
  12293. // parentNode.formationScale = Math.pow(1 - (1.0/11.0),this.clusterSession+3);
  12294. parentNode.formationScale = 0;
  12295. }
  12296. else {
  12297. parentNode.formationScale = this.scale; // The latest child has been added on this scale
  12298. }
  12299. // recalculate the size of the node on the next time the node is rendered
  12300. parentNode.clearSizeCache();
  12301. // set the pop-out scale for the childnode
  12302. parentNode.containedNodes[childNode.id].formationScale = parentNode.formationScale;
  12303. // nullify the movement velocity of the child, this is to avoid hectic behaviour
  12304. childNode.clearVelocity();
  12305. // the mass has altered, preservation of energy dictates the velocity to be updated
  12306. parentNode.updateVelocity(massBefore);
  12307. // restart the simulation to reorganise all nodes
  12308. this.moving = true;
  12309. },
  12310. /**
  12311. * This function will apply the changes made to the remainingEdges during the formation of the clusters.
  12312. * This is a seperate function to allow for level-wise collapsing of the node barnesHutTree.
  12313. * It has to be called if a level is collapsed. It is called by _formClusters().
  12314. * @private
  12315. */
  12316. _updateDynamicEdges : function() {
  12317. for (var i = 0; i < this.nodeIndices.length; i++) {
  12318. var node = this.nodes[this.nodeIndices[i]];
  12319. node.dynamicEdgesLength = node.dynamicEdges.length;
  12320. // this corrects for multiple edges pointing at the same other node
  12321. var correction = 0;
  12322. if (node.dynamicEdgesLength > 1) {
  12323. for (var j = 0; j < node.dynamicEdgesLength - 1; j++) {
  12324. var edgeToId = node.dynamicEdges[j].toId;
  12325. var edgeFromId = node.dynamicEdges[j].fromId;
  12326. for (var k = j+1; k < node.dynamicEdgesLength; k++) {
  12327. if ((node.dynamicEdges[k].toId == edgeToId && node.dynamicEdges[k].fromId == edgeFromId) ||
  12328. (node.dynamicEdges[k].fromId == edgeToId && node.dynamicEdges[k].toId == edgeFromId)) {
  12329. correction += 1;
  12330. }
  12331. }
  12332. }
  12333. }
  12334. node.dynamicEdgesLength -= correction;
  12335. }
  12336. },
  12337. /**
  12338. * This adds an edge from the childNode to the contained edges of the parent node
  12339. *
  12340. * @param parentNode | Node object
  12341. * @param childNode | Node object
  12342. * @param edge | Edge object
  12343. * @private
  12344. */
  12345. _addToContainedEdges : function(parentNode, childNode, edge) {
  12346. // create an array object if it does not yet exist for this childNode
  12347. if (!(parentNode.containedEdges.hasOwnProperty(childNode.id))) {
  12348. parentNode.containedEdges[childNode.id] = []
  12349. }
  12350. // add this edge to the list
  12351. parentNode.containedEdges[childNode.id].push(edge);
  12352. // remove the edge from the global edges object
  12353. delete this.edges[edge.id];
  12354. // remove the edge from the parent object
  12355. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12356. if (parentNode.dynamicEdges[i].id == edge.id) {
  12357. parentNode.dynamicEdges.splice(i,1);
  12358. break;
  12359. }
  12360. }
  12361. },
  12362. /**
  12363. * This function connects an edge that was connected to a child node to the parent node.
  12364. * It keeps track of which nodes it has been connected to with the originalId array.
  12365. *
  12366. * @param {Node} parentNode | Node object
  12367. * @param {Node} childNode | Node object
  12368. * @param {Edge} edge | Edge object
  12369. * @private
  12370. */
  12371. _connectEdgeToCluster : function(parentNode, childNode, edge) {
  12372. // handle circular edges
  12373. if (edge.toId == edge.fromId) {
  12374. this._addToContainedEdges(parentNode, childNode, edge);
  12375. }
  12376. else {
  12377. if (edge.toId == childNode.id) { // edge connected to other node on the "to" side
  12378. edge.originalToId.push(childNode.id);
  12379. edge.to = parentNode;
  12380. edge.toId = parentNode.id;
  12381. }
  12382. else { // edge connected to other node with the "from" side
  12383. edge.originalFromId.push(childNode.id);
  12384. edge.from = parentNode;
  12385. edge.fromId = parentNode.id;
  12386. }
  12387. this._addToReroutedEdges(parentNode,childNode,edge);
  12388. }
  12389. },
  12390. /**
  12391. * If a node is connected to itself, a circular edge is drawn. When clustering we want to contain
  12392. * these edges inside of the cluster.
  12393. *
  12394. * @param parentNode
  12395. * @param childNode
  12396. * @private
  12397. */
  12398. _containCircularEdgesFromNode : function(parentNode, childNode) {
  12399. // manage all the edges connected to the child and parent nodes
  12400. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12401. var edge = parentNode.dynamicEdges[i];
  12402. // handle circular edges
  12403. if (edge.toId == edge.fromId) {
  12404. this._addToContainedEdges(parentNode, childNode, edge);
  12405. }
  12406. }
  12407. },
  12408. /**
  12409. * This adds an edge from the childNode to the rerouted edges of the parent node
  12410. *
  12411. * @param parentNode | Node object
  12412. * @param childNode | Node object
  12413. * @param edge | Edge object
  12414. * @private
  12415. */
  12416. _addToReroutedEdges : function(parentNode, childNode, edge) {
  12417. // create an array object if it does not yet exist for this childNode
  12418. // we store the edge in the rerouted edges so we can restore it when the cluster pops open
  12419. if (!(parentNode.reroutedEdges.hasOwnProperty(childNode.id))) {
  12420. parentNode.reroutedEdges[childNode.id] = [];
  12421. }
  12422. parentNode.reroutedEdges[childNode.id].push(edge);
  12423. // this edge becomes part of the dynamicEdges of the cluster node
  12424. parentNode.dynamicEdges.push(edge);
  12425. },
  12426. /**
  12427. * This function connects an edge that was connected to a cluster node back to the child node.
  12428. *
  12429. * @param parentNode | Node object
  12430. * @param childNode | Node object
  12431. * @private
  12432. */
  12433. _connectEdgeBackToChild : function(parentNode, childNode) {
  12434. if (parentNode.reroutedEdges.hasOwnProperty(childNode.id)) {
  12435. for (var i = 0; i < parentNode.reroutedEdges[childNode.id].length; i++) {
  12436. var edge = parentNode.reroutedEdges[childNode.id][i];
  12437. if (edge.originalFromId[edge.originalFromId.length-1] == childNode.id) {
  12438. edge.originalFromId.pop();
  12439. edge.fromId = childNode.id;
  12440. edge.from = childNode;
  12441. }
  12442. else {
  12443. edge.originalToId.pop();
  12444. edge.toId = childNode.id;
  12445. edge.to = childNode;
  12446. }
  12447. // append this edge to the list of edges connecting to the childnode
  12448. childNode.dynamicEdges.push(edge);
  12449. // remove the edge from the parent object
  12450. for (var j = 0; j < parentNode.dynamicEdges.length; j++) {
  12451. if (parentNode.dynamicEdges[j].id == edge.id) {
  12452. parentNode.dynamicEdges.splice(j,1);
  12453. break;
  12454. }
  12455. }
  12456. }
  12457. // remove the entry from the rerouted edges
  12458. delete parentNode.reroutedEdges[childNode.id];
  12459. }
  12460. },
  12461. /**
  12462. * When loops are clustered, an edge can be both in the rerouted array and the contained array.
  12463. * This function is called last to verify that all edges in dynamicEdges are in fact connected to the
  12464. * parentNode
  12465. *
  12466. * @param parentNode | Node object
  12467. * @private
  12468. */
  12469. _validateEdges : function(parentNode) {
  12470. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12471. var edge = parentNode.dynamicEdges[i];
  12472. if (parentNode.id != edge.toId && parentNode.id != edge.fromId) {
  12473. parentNode.dynamicEdges.splice(i,1);
  12474. }
  12475. }
  12476. },
  12477. /**
  12478. * This function released the contained edges back into the global domain and puts them back into the
  12479. * dynamic edges of both parent and child.
  12480. *
  12481. * @param {Node} parentNode |
  12482. * @param {Node} childNode |
  12483. * @private
  12484. */
  12485. _releaseContainedEdges : function(parentNode, childNode) {
  12486. for (var i = 0; i < parentNode.containedEdges[childNode.id].length; i++) {
  12487. var edge = parentNode.containedEdges[childNode.id][i];
  12488. // put the edge back in the global edges object
  12489. this.edges[edge.id] = edge;
  12490. // put the edge back in the dynamic edges of the child and parent
  12491. childNode.dynamicEdges.push(edge);
  12492. parentNode.dynamicEdges.push(edge);
  12493. }
  12494. // remove the entry from the contained edges
  12495. delete parentNode.containedEdges[childNode.id];
  12496. },
  12497. // ------------------- UTILITY FUNCTIONS ---------------------------- //
  12498. /**
  12499. * This updates the node labels for all nodes (for debugging purposes)
  12500. */
  12501. updateLabels : function() {
  12502. var nodeId;
  12503. // update node labels
  12504. for (nodeId in this.nodes) {
  12505. if (this.nodes.hasOwnProperty(nodeId)) {
  12506. var node = this.nodes[nodeId];
  12507. if (node.clusterSize > 1) {
  12508. node.label = "[".concat(String(node.clusterSize),"]");
  12509. }
  12510. }
  12511. }
  12512. // update node labels
  12513. for (nodeId in this.nodes) {
  12514. if (this.nodes.hasOwnProperty(nodeId)) {
  12515. node = this.nodes[nodeId];
  12516. if (node.clusterSize == 1) {
  12517. if (node.originalLabel !== undefined) {
  12518. node.label = node.originalLabel;
  12519. }
  12520. else {
  12521. node.label = String(node.id);
  12522. }
  12523. }
  12524. }
  12525. }
  12526. // /* Debug Override */
  12527. // for (nodeId in this.nodes) {
  12528. // if (this.nodes.hasOwnProperty(nodeId)) {
  12529. // node = this.nodes[nodeId];
  12530. // node.label = String(node.level);
  12531. // }
  12532. // }
  12533. },
  12534. /**
  12535. * We want to keep the cluster level distribution rather small. This means we do not want unclustered nodes
  12536. * if the rest of the nodes are already a few cluster levels in.
  12537. * To fix this we use this function. It determines the min and max cluster level and sends nodes that have not
  12538. * clustered enough to the clusterToSmallestNeighbours function.
  12539. */
  12540. normalizeClusterLevels : function() {
  12541. var maxLevel = 0;
  12542. var minLevel = 1e9;
  12543. var clusterLevel = 0;
  12544. // we loop over all nodes in the list
  12545. for (var nodeId in this.nodes) {
  12546. if (this.nodes.hasOwnProperty(nodeId)) {
  12547. clusterLevel = this.nodes[nodeId].clusterSessions.length;
  12548. if (maxLevel < clusterLevel) {maxLevel = clusterLevel;}
  12549. if (minLevel > clusterLevel) {minLevel = clusterLevel;}
  12550. }
  12551. }
  12552. if (maxLevel - minLevel > this.constants.clustering.clusterLevelDifference) {
  12553. var amountOfNodes = this.nodeIndices.length;
  12554. var targetLevel = maxLevel - this.constants.clustering.clusterLevelDifference;
  12555. // we loop over all nodes in the list
  12556. for (var nodeId in this.nodes) {
  12557. if (this.nodes.hasOwnProperty(nodeId)) {
  12558. if (this.nodes[nodeId].clusterSessions.length < targetLevel) {
  12559. this._clusterToSmallestNeighbour(this.nodes[nodeId]);
  12560. }
  12561. }
  12562. }
  12563. this._updateNodeIndexList();
  12564. this._updateDynamicEdges();
  12565. // if a cluster was formed, we increase the clusterSession
  12566. if (this.nodeIndices.length != amountOfNodes) {
  12567. this.clusterSession += 1;
  12568. }
  12569. }
  12570. },
  12571. /**
  12572. * This function determines if the cluster we want to decluster is in the active area
  12573. * this means around the zoom center
  12574. *
  12575. * @param {Node} node
  12576. * @returns {boolean}
  12577. * @private
  12578. */
  12579. _nodeInActiveArea : function(node) {
  12580. return (
  12581. Math.abs(node.x - this.areaCenter.x) <= this.constants.clustering.activeAreaBoxSize/this.scale
  12582. &&
  12583. Math.abs(node.y - this.areaCenter.y) <= this.constants.clustering.activeAreaBoxSize/this.scale
  12584. )
  12585. },
  12586. /**
  12587. * This is an adaptation of the original repositioning function. This is called if the system is clustered initially
  12588. * It puts large clusters away from the center and randomizes the order.
  12589. *
  12590. */
  12591. repositionNodes : function() {
  12592. for (var i = 0; i < this.nodeIndices.length; i++) {
  12593. var node = this.nodes[this.nodeIndices[i]];
  12594. if ((node.xFixed == false || node.yFixed == false) && this.createNodeOnClick != true) {
  12595. var radius = this.constants.physics.springLength * Math.min(100,node.mass);
  12596. var angle = 2 * Math.PI * Math.random();
  12597. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  12598. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  12599. this._repositionBezierNodes(node);
  12600. }
  12601. }
  12602. },
  12603. /**
  12604. * We determine how many connections denote an important hub.
  12605. * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%)
  12606. *
  12607. * @private
  12608. */
  12609. _getHubSize : function() {
  12610. var average = 0;
  12611. var averageSquared = 0;
  12612. var hubCounter = 0;
  12613. var largestHub = 0;
  12614. for (var i = 0; i < this.nodeIndices.length; i++) {
  12615. var node = this.nodes[this.nodeIndices[i]];
  12616. if (node.dynamicEdgesLength > largestHub) {
  12617. largestHub = node.dynamicEdgesLength;
  12618. }
  12619. average += node.dynamicEdgesLength;
  12620. averageSquared += Math.pow(node.dynamicEdgesLength,2);
  12621. hubCounter += 1;
  12622. }
  12623. average = average / hubCounter;
  12624. averageSquared = averageSquared / hubCounter;
  12625. var variance = averageSquared - Math.pow(average,2);
  12626. var standardDeviation = Math.sqrt(variance);
  12627. this.hubThreshold = Math.floor(average + 2*standardDeviation);
  12628. // always have at least one to cluster
  12629. if (this.hubThreshold > largestHub) {
  12630. this.hubThreshold = largestHub;
  12631. }
  12632. // console.log("average",average,"averageSQ",averageSquared,"var",variance,"std",standardDeviation);
  12633. // console.log("hubThreshold:",this.hubThreshold);
  12634. },
  12635. /**
  12636. * We reduce the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  12637. * with this amount we can cluster specifically on these chains.
  12638. *
  12639. * @param {Number} fraction | between 0 and 1, the percentage of chains to reduce
  12640. * @private
  12641. */
  12642. _reduceAmountOfChains : function(fraction) {
  12643. this.hubThreshold = 2;
  12644. var reduceAmount = Math.floor(this.nodeIndices.length * fraction);
  12645. for (var nodeId in this.nodes) {
  12646. if (this.nodes.hasOwnProperty(nodeId)) {
  12647. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  12648. if (reduceAmount > 0) {
  12649. this._formClusterFromHub(this.nodes[nodeId],true,true,1);
  12650. reduceAmount -= 1;
  12651. }
  12652. }
  12653. }
  12654. }
  12655. },
  12656. /**
  12657. * We get the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  12658. * with this amount we can cluster specifically on these chains.
  12659. *
  12660. * @private
  12661. */
  12662. _getChainFraction : function() {
  12663. var chains = 0;
  12664. var total = 0;
  12665. for (var nodeId in this.nodes) {
  12666. if (this.nodes.hasOwnProperty(nodeId)) {
  12667. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  12668. chains += 1;
  12669. }
  12670. total += 1;
  12671. }
  12672. }
  12673. return chains/total;
  12674. }
  12675. };
  12676. var SelectionMixin = {
  12677. /**
  12678. * This function can be called from the _doInAllSectors function
  12679. *
  12680. * @param object
  12681. * @param overlappingNodes
  12682. * @private
  12683. */
  12684. _getNodesOverlappingWith : function(object, overlappingNodes) {
  12685. var nodes = this.nodes;
  12686. for (var nodeId in nodes) {
  12687. if (nodes.hasOwnProperty(nodeId)) {
  12688. if (nodes[nodeId].isOverlappingWith(object)) {
  12689. overlappingNodes.push(nodeId);
  12690. }
  12691. }
  12692. }
  12693. },
  12694. /**
  12695. * retrieve all nodes overlapping with given object
  12696. * @param {Object} object An object with parameters left, top, right, bottom
  12697. * @return {Number[]} An array with id's of the overlapping nodes
  12698. * @private
  12699. */
  12700. _getAllNodesOverlappingWith : function (object) {
  12701. var overlappingNodes = [];
  12702. this._doInAllActiveSectors("_getNodesOverlappingWith",object,overlappingNodes);
  12703. return overlappingNodes;
  12704. },
  12705. /**
  12706. * Return a position object in canvasspace from a single point in screenspace
  12707. *
  12708. * @param pointer
  12709. * @returns {{left: number, top: number, right: number, bottom: number}}
  12710. * @private
  12711. */
  12712. _pointerToPositionObject : function(pointer) {
  12713. var x = this._canvasToX(pointer.x);
  12714. var y = this._canvasToY(pointer.y);
  12715. return {left: x,
  12716. top: y,
  12717. right: x,
  12718. bottom: y};
  12719. },
  12720. /**
  12721. * Get the top node at the a specific point (like a click)
  12722. *
  12723. * @param {{x: Number, y: Number}} pointer
  12724. * @return {Node | null} node
  12725. * @private
  12726. */
  12727. _getNodeAt : function (pointer) {
  12728. // we first check if this is an navigation controls element
  12729. var positionObject = this._pointerToPositionObject(pointer);
  12730. var overlappingNodes = this._getAllNodesOverlappingWith(positionObject);
  12731. // if there are overlapping nodes, select the last one, this is the
  12732. // one which is drawn on top of the others
  12733. if (overlappingNodes.length > 0) {
  12734. return this.nodes[overlappingNodes[overlappingNodes.length - 1]];
  12735. }
  12736. else {
  12737. return null;
  12738. }
  12739. },
  12740. /**
  12741. * retrieve all edges overlapping with given object, selector is around center
  12742. * @param {Object} object An object with parameters left, top, right, bottom
  12743. * @return {Number[]} An array with id's of the overlapping nodes
  12744. * @private
  12745. */
  12746. _getEdgesOverlappingWith : function (object, overlappingEdges) {
  12747. var edges = this.edges;
  12748. for (var edgeId in edges) {
  12749. if (edges.hasOwnProperty(edgeId)) {
  12750. if (edges[edgeId].isOverlappingWith(object)) {
  12751. overlappingEdges.push(edgeId);
  12752. }
  12753. }
  12754. }
  12755. },
  12756. /**
  12757. * retrieve all nodes overlapping with given object
  12758. * @param {Object} object An object with parameters left, top, right, bottom
  12759. * @return {Number[]} An array with id's of the overlapping nodes
  12760. * @private
  12761. */
  12762. _getAllEdgesOverlappingWith : function (object) {
  12763. var overlappingEdges = [];
  12764. this._doInAllActiveSectors("_getEdgesOverlappingWith",object,overlappingEdges);
  12765. return overlappingEdges;
  12766. },
  12767. /**
  12768. * Place holder. To implement change the _getNodeAt to a _getObjectAt. Have the _getObjectAt call
  12769. * _getNodeAt and _getEdgesAt, then priortize the selection to user preferences.
  12770. *
  12771. * @param pointer
  12772. * @returns {null}
  12773. * @private
  12774. */
  12775. _getEdgeAt : function(pointer) {
  12776. var positionObject = this._pointerToPositionObject(pointer);
  12777. var overlappingEdges = this._getAllEdgesOverlappingWith(positionObject);
  12778. if (overlappingEdges.length > 0) {
  12779. return this.edges[overlappingEdges[overlappingEdges.length - 1]];
  12780. }
  12781. else {
  12782. return null;
  12783. }
  12784. },
  12785. /**
  12786. * Add object to the selection array.
  12787. *
  12788. * @param obj
  12789. * @private
  12790. */
  12791. _addToSelection : function(obj) {
  12792. this.selectionObj[obj.id] = obj;
  12793. },
  12794. /**
  12795. * Remove a single option from selection.
  12796. *
  12797. * @param {Object} obj
  12798. * @private
  12799. */
  12800. _removeFromSelection : function(obj) {
  12801. delete this.selectionObj[obj.id];
  12802. },
  12803. /**
  12804. * Unselect all. The selectionObj is useful for this.
  12805. *
  12806. * @param {Boolean} [doNotTrigger] | ignore trigger
  12807. * @private
  12808. */
  12809. _unselectAll : function(doNotTrigger) {
  12810. if (doNotTrigger === undefined) {
  12811. doNotTrigger = false;
  12812. }
  12813. for (var objectId in this.selectionObj) {
  12814. if (this.selectionObj.hasOwnProperty(objectId)) {
  12815. this.selectionObj[objectId].unselect();
  12816. }
  12817. }
  12818. this.selectionObj = {};
  12819. if (doNotTrigger == false) {
  12820. this.emit('select', this.getSelection());
  12821. }
  12822. },
  12823. /**
  12824. * Unselect all clusters. The selectionObj is useful for this.
  12825. *
  12826. * @param {Boolean} [doNotTrigger] | ignore trigger
  12827. * @private
  12828. */
  12829. _unselectClusters : function(doNotTrigger) {
  12830. if (doNotTrigger === undefined) {
  12831. doNotTrigger = false;
  12832. }
  12833. for (var objectId in this.selectionObj) {
  12834. if (this.selectionObj.hasOwnProperty(objectId)) {
  12835. if (this.selectionObj[objectId] instanceof Node) {
  12836. if (this.selectionObj[objectId].clusterSize > 1) {
  12837. this.selectionObj[objectId].unselect();
  12838. this._removeFromSelection(this.selectionObj[objectId]);
  12839. }
  12840. }
  12841. }
  12842. }
  12843. if (doNotTrigger == false) {
  12844. this.emit('select', this.getSelection());
  12845. }
  12846. },
  12847. /**
  12848. * return the number of selected nodes
  12849. *
  12850. * @returns {number}
  12851. * @private
  12852. */
  12853. _getSelectedNodeCount : function() {
  12854. var count = 0;
  12855. for (var objectId in this.selectionObj) {
  12856. if (this.selectionObj.hasOwnProperty(objectId)) {
  12857. if (this.selectionObj[objectId] instanceof Node) {
  12858. count += 1;
  12859. }
  12860. }
  12861. }
  12862. return count;
  12863. },
  12864. /**
  12865. * return the number of selected nodes
  12866. *
  12867. * @returns {number}
  12868. * @private
  12869. */
  12870. _getSelectedNode : function() {
  12871. for (var objectId in this.selectionObj) {
  12872. if (this.selectionObj.hasOwnProperty(objectId)) {
  12873. if (this.selectionObj[objectId] instanceof Node) {
  12874. return this.selectionObj[objectId];
  12875. }
  12876. }
  12877. }
  12878. return null;
  12879. },
  12880. /**
  12881. * return the number of selected edges
  12882. *
  12883. * @returns {number}
  12884. * @private
  12885. */
  12886. _getSelectedEdgeCount : function() {
  12887. var count = 0;
  12888. for (var objectId in this.selectionObj) {
  12889. if (this.selectionObj.hasOwnProperty(objectId)) {
  12890. if (this.selectionObj[objectId] instanceof Edge) {
  12891. count += 1;
  12892. }
  12893. }
  12894. }
  12895. return count;
  12896. },
  12897. /**
  12898. * return the number of selected objects.
  12899. *
  12900. * @returns {number}
  12901. * @private
  12902. */
  12903. _getSelectedObjectCount : function() {
  12904. var count = 0;
  12905. for (var objectId in this.selectionObj) {
  12906. if (this.selectionObj.hasOwnProperty(objectId)) {
  12907. count += 1;
  12908. }
  12909. }
  12910. return count;
  12911. },
  12912. /**
  12913. * Check if anything is selected
  12914. *
  12915. * @returns {boolean}
  12916. * @private
  12917. */
  12918. _selectionIsEmpty : function() {
  12919. for(var objectId in this.selectionObj) {
  12920. if(this.selectionObj.hasOwnProperty(objectId)) {
  12921. return false;
  12922. }
  12923. }
  12924. return true;
  12925. },
  12926. /**
  12927. * check if one of the selected nodes is a cluster.
  12928. *
  12929. * @returns {boolean}
  12930. * @private
  12931. */
  12932. _clusterInSelection : function() {
  12933. for(var objectId in this.selectionObj) {
  12934. if(this.selectionObj.hasOwnProperty(objectId)) {
  12935. if (this.selectionObj[objectId] instanceof Node) {
  12936. if (this.selectionObj[objectId].clusterSize > 1) {
  12937. return true;
  12938. }
  12939. }
  12940. }
  12941. }
  12942. return false;
  12943. },
  12944. /**
  12945. * select the edges connected to the node that is being selected
  12946. *
  12947. * @param {Node} node
  12948. * @private
  12949. */
  12950. _selectConnectedEdges : function(node) {
  12951. for (var i = 0; i < node.dynamicEdges.length; i++) {
  12952. var edge = node.dynamicEdges[i];
  12953. edge.select();
  12954. this._addToSelection(edge);
  12955. }
  12956. },
  12957. /**
  12958. * unselect the edges connected to the node that is being selected
  12959. *
  12960. * @param {Node} node
  12961. * @private
  12962. */
  12963. _unselectConnectedEdges : function(node) {
  12964. for (var i = 0; i < node.dynamicEdges.length; i++) {
  12965. var edge = node.dynamicEdges[i];
  12966. edge.unselect();
  12967. this._removeFromSelection(edge);
  12968. }
  12969. },
  12970. /**
  12971. * This is called when someone clicks on a node. either select or deselect it.
  12972. * If there is an existing selection and we don't want to append to it, clear the existing selection
  12973. *
  12974. * @param {Node || Edge} object
  12975. * @param {Boolean} append
  12976. * @param {Boolean} [doNotTrigger] | ignore trigger
  12977. * @private
  12978. */
  12979. _selectObject : function(object, append, doNotTrigger) {
  12980. if (doNotTrigger === undefined) {
  12981. doNotTrigger = false;
  12982. }
  12983. if (this._selectionIsEmpty() == false && append == false && this.forceAppendSelection == false) {
  12984. this._unselectAll(true);
  12985. }
  12986. if (object.selected == false) {
  12987. object.select();
  12988. this._addToSelection(object);
  12989. if (object instanceof Node && this.blockConnectingEdgeSelection == false) {
  12990. this._selectConnectedEdges(object);
  12991. }
  12992. }
  12993. else {
  12994. object.unselect();
  12995. this._removeFromSelection(object);
  12996. }
  12997. if (doNotTrigger == false) {
  12998. this.emit('select', this.getSelection());
  12999. }
  13000. },
  13001. /**
  13002. * handles the selection part of the touch, only for navigation controls elements;
  13003. * Touch is triggered before tap, also before hold. Hold triggers after a while.
  13004. * This is the most responsive solution
  13005. *
  13006. * @param {Object} pointer
  13007. * @private
  13008. */
  13009. _handleTouch : function(pointer) {
  13010. },
  13011. /**
  13012. * handles the selection part of the tap;
  13013. *
  13014. * @param {Object} pointer
  13015. * @private
  13016. */
  13017. _handleTap : function(pointer) {
  13018. var node = this._getNodeAt(pointer);
  13019. if (node != null) {
  13020. this._selectObject(node,false);
  13021. }
  13022. else {
  13023. var edge = this._getEdgeAt(pointer);
  13024. if (edge != null) {
  13025. this._selectObject(edge,false);
  13026. }
  13027. else {
  13028. this._unselectAll();
  13029. }
  13030. }
  13031. this._redraw();
  13032. },
  13033. /**
  13034. * handles the selection part of the double tap and opens a cluster if needed
  13035. *
  13036. * @param {Object} pointer
  13037. * @private
  13038. */
  13039. _handleDoubleTap : function(pointer) {
  13040. var node = this._getNodeAt(pointer);
  13041. if (node != null && node !== undefined) {
  13042. // we reset the areaCenter here so the opening of the node will occur
  13043. this.areaCenter = {"x" : this._canvasToX(pointer.x),
  13044. "y" : this._canvasToY(pointer.y)};
  13045. this.openCluster(node);
  13046. }
  13047. },
  13048. /**
  13049. * Handle the onHold selection part
  13050. *
  13051. * @param pointer
  13052. * @private
  13053. */
  13054. _handleOnHold : function(pointer) {
  13055. var node = this._getNodeAt(pointer);
  13056. if (node != null) {
  13057. this._selectObject(node,true);
  13058. }
  13059. else {
  13060. var edge = this._getEdgeAt(pointer);
  13061. if (edge != null) {
  13062. this._selectObject(edge,true);
  13063. }
  13064. }
  13065. this._redraw();
  13066. },
  13067. /**
  13068. * handle the onRelease event. These functions are here for the navigation controls module.
  13069. *
  13070. * @private
  13071. */
  13072. _handleOnRelease : function(pointer) {
  13073. },
  13074. /**
  13075. *
  13076. * retrieve the currently selected objects
  13077. * @return {Number[] | String[]} selection An array with the ids of the
  13078. * selected nodes.
  13079. */
  13080. getSelection : function() {
  13081. var nodeIds = this.getSelectedNodes();
  13082. var edgeIds = this.getSelectedEdges();
  13083. return {nodes:nodeIds, edges:edgeIds};
  13084. },
  13085. /**
  13086. *
  13087. * retrieve the currently selected nodes
  13088. * @return {String} selection An array with the ids of the
  13089. * selected nodes.
  13090. */
  13091. getSelectedNodes : function() {
  13092. var idArray = [];
  13093. for(var objectId in this.selectionObj) {
  13094. if(this.selectionObj.hasOwnProperty(objectId)) {
  13095. if (this.selectionObj[objectId] instanceof Node) {
  13096. idArray.push(objectId);
  13097. }
  13098. }
  13099. }
  13100. return idArray
  13101. },
  13102. /**
  13103. *
  13104. * retrieve the currently selected edges
  13105. * @return {Array} selection An array with the ids of the
  13106. * selected nodes.
  13107. */
  13108. getSelectedEdges : function() {
  13109. var idArray = [];
  13110. for(var objectId in this.selectionObj) {
  13111. if(this.selectionObj.hasOwnProperty(objectId)) {
  13112. if (this.selectionObj[objectId] instanceof Edge) {
  13113. idArray.push(objectId);
  13114. }
  13115. }
  13116. }
  13117. return idArray
  13118. },
  13119. /**
  13120. * select zero or more nodes
  13121. * @param {Number[] | String[]} selection An array with the ids of the
  13122. * selected nodes.
  13123. */
  13124. setSelection : function(selection) {
  13125. var i, iMax, id;
  13126. if (!selection || (selection.length == undefined))
  13127. throw 'Selection must be an array with ids';
  13128. // first unselect any selected node
  13129. this._unselectAll(true);
  13130. for (i = 0, iMax = selection.length; i < iMax; i++) {
  13131. id = selection[i];
  13132. var node = this.nodes[id];
  13133. if (!node) {
  13134. throw new RangeError('Node with id "' + id + '" not found');
  13135. }
  13136. this._selectObject(node,true,true);
  13137. }
  13138. this.redraw();
  13139. },
  13140. /**
  13141. * Validate the selection: remove ids of nodes which no longer exist
  13142. * @private
  13143. */
  13144. _updateSelection : function () {
  13145. for(var objectId in this.selectionObj) {
  13146. if(this.selectionObj.hasOwnProperty(objectId)) {
  13147. if (this.selectionObj[objectId] instanceof Node) {
  13148. if (!this.nodes.hasOwnProperty(objectId)) {
  13149. delete this.selectionObj[objectId];
  13150. }
  13151. }
  13152. else { // assuming only edges and nodes are selected
  13153. if (!this.edges.hasOwnProperty(objectId)) {
  13154. delete this.selectionObj[objectId];
  13155. }
  13156. }
  13157. }
  13158. }
  13159. }
  13160. };
  13161. /**
  13162. * Created by Alex on 1/22/14.
  13163. */
  13164. var NavigationMixin = {
  13165. _cleanNavigation : function() {
  13166. // clean up previosu navigation items
  13167. var wrapper = document.getElementById('graph-navigation_wrapper');
  13168. if (wrapper != null) {
  13169. this.containerElement.removeChild(wrapper);
  13170. }
  13171. document.onmouseup = null;
  13172. },
  13173. /**
  13174. * Creation of the navigation controls nodes. They are drawn over the rest of the nodes and are not affected by scale and translation
  13175. * they have a triggerFunction which is called on click. If the position of the navigation controls is dependent
  13176. * on this.frame.canvas.clientWidth or this.frame.canvas.clientHeight, we flag horizontalAlignLeft and verticalAlignTop false.
  13177. * This means that the location will be corrected by the _relocateNavigation function on a size change of the canvas.
  13178. *
  13179. * @private
  13180. */
  13181. _loadNavigationElements : function() {
  13182. this._cleanNavigation();
  13183. this.navigationDivs = {};
  13184. var navigationDivs = ['up','down','left','right','zoomIn','zoomOut','zoomExtends'];
  13185. var navigationDivActions = ['_moveUp','_moveDown','_moveLeft','_moveRight','_zoomIn','_zoomOut','zoomToFit'];
  13186. this.navigationDivs['wrapper'] = document.createElement('div');
  13187. this.navigationDivs['wrapper'].id = "graph-navigation_wrapper";
  13188. this.containerElement.insertBefore(this.navigationDivs['wrapper'],this.frame);
  13189. for (var i = 0; i < navigationDivs.length; i++) {
  13190. this.navigationDivs[navigationDivs[i]] = document.createElement('div');
  13191. this.navigationDivs[navigationDivs[i]].id = "graph-navigation_" + navigationDivs[i];
  13192. this.navigationDivs[navigationDivs[i]].className = "graph-navigation " + navigationDivs[i];
  13193. this.navigationDivs['wrapper'].appendChild(this.navigationDivs[navigationDivs[i]]);
  13194. this.navigationDivs[navigationDivs[i]].onmousedown = this[navigationDivActions[i]].bind(this);
  13195. }
  13196. document.onmouseup = this._stopMovement.bind(this);
  13197. },
  13198. /**
  13199. * this stops all movement induced by the navigation buttons
  13200. *
  13201. * @private
  13202. */
  13203. _stopMovement : function() {
  13204. this._xStopMoving();
  13205. this._yStopMoving();
  13206. this._stopZoom();
  13207. },
  13208. /**
  13209. * stops the actions performed by page up and down etc.
  13210. *
  13211. * @param event
  13212. * @private
  13213. */
  13214. _preventDefault : function(event) {
  13215. if (event !== undefined) {
  13216. if (event.preventDefault) {
  13217. event.preventDefault();
  13218. } else {
  13219. event.returnValue = false;
  13220. }
  13221. }
  13222. },
  13223. /**
  13224. * move the screen up
  13225. * By using the increments, instead of adding a fixed number to the translation, we keep fluent and
  13226. * instant movement. The onKeypress event triggers immediately, then pauses, then triggers frequently
  13227. * To avoid this behaviour, we do the translation in the start loop.
  13228. *
  13229. * @private
  13230. */
  13231. _moveUp : function(event) {
  13232. console.log("here")
  13233. this.yIncrement = this.constants.keyboard.speed.y;
  13234. this.start(); // if there is no node movement, the calculation wont be done
  13235. this._preventDefault(event);
  13236. },
  13237. /**
  13238. * move the screen down
  13239. * @private
  13240. */
  13241. _moveDown : function(event) {
  13242. this.yIncrement = -this.constants.keyboard.speed.y;
  13243. this.start(); // if there is no node movement, the calculation wont be done
  13244. this._preventDefault(event);
  13245. },
  13246. /**
  13247. * move the screen left
  13248. * @private
  13249. */
  13250. _moveLeft : function(event) {
  13251. this.xIncrement = this.constants.keyboard.speed.x;
  13252. this.start(); // if there is no node movement, the calculation wont be done
  13253. this._preventDefault(event);
  13254. },
  13255. /**
  13256. * move the screen right
  13257. * @private
  13258. */
  13259. _moveRight : function(event) {
  13260. this.xIncrement = -this.constants.keyboard.speed.y;
  13261. this.start(); // if there is no node movement, the calculation wont be done
  13262. this._preventDefault(event);
  13263. },
  13264. /**
  13265. * Zoom in, using the same method as the movement.
  13266. * @private
  13267. */
  13268. _zoomIn : function(event) {
  13269. this.zoomIncrement = this.constants.keyboard.speed.zoom;
  13270. this.start(); // if there is no node movement, the calculation wont be done
  13271. this._preventDefault(event);
  13272. },
  13273. /**
  13274. * Zoom out
  13275. * @private
  13276. */
  13277. _zoomOut : function() {
  13278. this.zoomIncrement = -this.constants.keyboard.speed.zoom;
  13279. this.start(); // if there is no node movement, the calculation wont be done
  13280. this._preventDefault(event);
  13281. },
  13282. /**
  13283. * Stop zooming and unhighlight the zoom controls
  13284. * @private
  13285. */
  13286. _stopZoom : function() {
  13287. this.zoomIncrement = 0;
  13288. },
  13289. /**
  13290. * Stop moving in the Y direction and unHighlight the up and down
  13291. * @private
  13292. */
  13293. _yStopMoving : function() {
  13294. this.yIncrement = 0;
  13295. },
  13296. /**
  13297. * Stop moving in the X direction and unHighlight left and right.
  13298. * @private
  13299. */
  13300. _xStopMoving : function() {
  13301. this.xIncrement = 0;
  13302. }
  13303. };
  13304. /**
  13305. * Created by Alex on 2/10/14.
  13306. */
  13307. var graphMixinLoaders = {
  13308. /**
  13309. * Load a mixin into the graph object
  13310. *
  13311. * @param {Object} sourceVariable | this object has to contain functions.
  13312. * @private
  13313. */
  13314. _loadMixin : function(sourceVariable) {
  13315. for (var mixinFunction in sourceVariable) {
  13316. if (sourceVariable.hasOwnProperty(mixinFunction)) {
  13317. Graph.prototype[mixinFunction] = sourceVariable[mixinFunction];
  13318. }
  13319. }
  13320. },
  13321. /**
  13322. * removes a mixin from the graph object.
  13323. *
  13324. * @param {Object} sourceVariable | this object has to contain functions.
  13325. * @private
  13326. */
  13327. _clearMixin : function(sourceVariable) {
  13328. for (var mixinFunction in sourceVariable) {
  13329. if (sourceVariable.hasOwnProperty(mixinFunction)) {
  13330. Graph.prototype[mixinFunction] = undefined;
  13331. }
  13332. }
  13333. },
  13334. /**
  13335. * Mixin the physics system and initialize the parameters required.
  13336. *
  13337. * @private
  13338. */
  13339. _loadPhysicsSystem : function() {
  13340. this._loadMixin(physicsMixin);
  13341. this._loadSelectedForceSolver();
  13342. },
  13343. /**
  13344. * This loads the node force solver based on the barnes hut or repulsion algorithm
  13345. *
  13346. * @private
  13347. */
  13348. _loadSelectedForceSolver : function() {
  13349. // this overloads the this._calculateNodeForces
  13350. if (this.constants.physics.barnesHut.enabled == true) {
  13351. this._clearMixin(repulsionMixin);
  13352. this._clearMixin(hierarchalRepulsionMixin);
  13353. this.constants.physics.centralGravity = this.constants.physics.barnesHut.centralGravity;
  13354. this.constants.physics.springLength = this.constants.physics.barnesHut.springLength;
  13355. this.constants.physics.springConstant = this.constants.physics.barnesHut.springConstant;
  13356. this.constants.physics.damping = this.constants.physics.barnesHut.damping;
  13357. this._loadMixin(barnesHutMixin);
  13358. }
  13359. else if (this.constants.physics.hierarchicalRepulsion.enabled == true) {
  13360. this._clearMixin(barnesHutMixin);
  13361. this._clearMixin(repulsionMixin);
  13362. this.constants.physics.centralGravity = this.constants.physics.hierarchicalRepulsion.centralGravity;
  13363. this.constants.physics.springLength = this.constants.physics.hierarchicalRepulsion.springLength;
  13364. this.constants.physics.springConstant = this.constants.physics.hierarchicalRepulsion.springConstant;
  13365. this.constants.physics.damping = this.constants.physics.hierarchicalRepulsion.damping;
  13366. this._loadMixin(hierarchalRepulsionMixin);
  13367. }
  13368. else {
  13369. this._clearMixin(barnesHutMixin);
  13370. this._clearMixin(hierarchalRepulsionMixin);
  13371. this.barnesHutTree = undefined;
  13372. this.constants.physics.centralGravity = this.constants.physics.repulsion.centralGravity;
  13373. this.constants.physics.springLength = this.constants.physics.repulsion.springLength;
  13374. this.constants.physics.springConstant = this.constants.physics.repulsion.springConstant;
  13375. this.constants.physics.damping = this.constants.physics.repulsion.damping;
  13376. this._loadMixin(repulsionMixin);
  13377. }
  13378. },
  13379. /**
  13380. * Mixin the cluster system and initialize the parameters required.
  13381. *
  13382. * @private
  13383. */
  13384. _loadClusterSystem : function() {
  13385. this.clusterSession = 0;
  13386. this.hubThreshold = 5;
  13387. this._loadMixin(ClusterMixin);
  13388. },
  13389. /**
  13390. * Mixin the sector system and initialize the parameters required
  13391. *
  13392. * @private
  13393. */
  13394. _loadSectorSystem : function() {
  13395. this.sectors = { },
  13396. this.activeSector = ["default"];
  13397. this.sectors["active"] = { },
  13398. this.sectors["active"]["default"] = {"nodes":{},
  13399. "edges":{},
  13400. "nodeIndices":[],
  13401. "formationScale": 1.0,
  13402. "drawingNode": undefined };
  13403. this.sectors["frozen"] = {},
  13404. this.sectors["support"] = {"nodes":{},
  13405. "edges":{},
  13406. "nodeIndices":[],
  13407. "formationScale": 1.0,
  13408. "drawingNode": undefined };
  13409. this.nodeIndices = this.sectors["active"]["default"]["nodeIndices"]; // the node indices list is used to speed up the computation of the repulsion fields
  13410. this._loadMixin(SectorMixin);
  13411. },
  13412. /**
  13413. * Mixin the selection system and initialize the parameters required
  13414. *
  13415. * @private
  13416. */
  13417. _loadSelectionSystem : function() {
  13418. this.selectionObj = { };
  13419. this._loadMixin(SelectionMixin);
  13420. },
  13421. /**
  13422. * Mixin the navigationUI (User Interface) system and initialize the parameters required
  13423. *
  13424. * @private
  13425. */
  13426. _loadManipulationSystem : function() {
  13427. // reset global variables -- these are used by the selection of nodes and edges.
  13428. this.blockConnectingEdgeSelection = false;
  13429. this.forceAppendSelection = false
  13430. if (this.constants.dataManipulation.enabled == true) {
  13431. // load the manipulator HTML elements. All styling done in css.
  13432. if (this.manipulationDiv === undefined) {
  13433. this.manipulationDiv = document.createElement('div');
  13434. this.manipulationDiv.className = 'graph-manipulationDiv';
  13435. this.manipulationDiv.id = 'graph-manipulationDiv';
  13436. if (this.editMode == true) {
  13437. this.manipulationDiv.style.display = "block";
  13438. }
  13439. else {
  13440. this.manipulationDiv.style.display = "none";
  13441. }
  13442. this.containerElement.insertBefore(this.manipulationDiv, this.frame);
  13443. }
  13444. if (this.editModeDiv === undefined) {
  13445. this.editModeDiv = document.createElement('div');
  13446. this.editModeDiv.className = 'graph-manipulation-editMode';
  13447. this.editModeDiv.id = 'graph-manipulation-editMode';
  13448. if (this.editMode == true) {
  13449. this.editModeDiv.style.display = "none";
  13450. }
  13451. else {
  13452. this.editModeDiv.style.display = "block";
  13453. }
  13454. this.containerElement.insertBefore(this.editModeDiv, this.frame);
  13455. }
  13456. if (this.closeDiv === undefined) {
  13457. this.closeDiv = document.createElement('div');
  13458. this.closeDiv.className = 'graph-manipulation-closeDiv';
  13459. this.closeDiv.id = 'graph-manipulation-closeDiv';
  13460. this.closeDiv.style.display = this.manipulationDiv.style.display;
  13461. this.containerElement.insertBefore(this.closeDiv, this.frame);
  13462. }
  13463. // load the manipulation functions
  13464. this._loadMixin(manipulationMixin);
  13465. // create the manipulator toolbar
  13466. this._createManipulatorBar();
  13467. }
  13468. else {
  13469. if (this.manipulationDiv !== undefined) {
  13470. // removes all the bindings and overloads
  13471. this._createManipulatorBar();
  13472. // remove the manipulation divs
  13473. this.containerElement.removeChild(this.manipulationDiv);
  13474. this.containerElement.removeChild(this.editModeDiv);
  13475. this.containerElement.removeChild(this.closeDiv);
  13476. this.manipulationDiv = undefined;
  13477. this.editModeDiv = undefined;
  13478. this.closeDiv = undefined;
  13479. // remove the mixin functions
  13480. this._clearMixin(manipulationMixin);
  13481. }
  13482. }
  13483. },
  13484. /**
  13485. * Mixin the navigation (User Interface) system and initialize the parameters required
  13486. *
  13487. * @private
  13488. */
  13489. _loadNavigationControls : function() {
  13490. this._loadMixin(NavigationMixin);
  13491. // the clean function removes the button divs, this is done to remove the bindings.
  13492. this._cleanNavigation();
  13493. if (this.constants.navigation.enabled == true) {
  13494. this._loadNavigationElements();
  13495. }
  13496. },
  13497. /**
  13498. * Mixin the hierarchical layout system.
  13499. *
  13500. * @private
  13501. */
  13502. _loadHierarchySystem : function() {
  13503. this._loadMixin(HierarchicalLayoutMixin);
  13504. }
  13505. }
  13506. /**
  13507. * @constructor Graph
  13508. * Create a graph visualization, displaying nodes and edges.
  13509. *
  13510. * @param {Element} container The DOM element in which the Graph will
  13511. * be created. Normally a div element.
  13512. * @param {Object} data An object containing parameters
  13513. * {Array} nodes
  13514. * {Array} edges
  13515. * @param {Object} options Options
  13516. */
  13517. function Graph (container, data, options) {
  13518. this._initializeMixinLoaders();
  13519. // create variables and set default values
  13520. this.containerElement = container;
  13521. this.width = '100%';
  13522. this.height = '100%';
  13523. // render and calculation settings
  13524. this.renderRefreshRate = 60; // hz (fps)
  13525. this.renderTimestep = 1000 / this.renderRefreshRate; // ms -- saves calculation later on
  13526. this.renderTime = 0.5 * this.renderTimestep; // measured time it takes to render a frame
  13527. this.maxRenderSteps = 3; // max amount of physics ticks per render step.
  13528. this.stabilize = true; // stabilize before displaying the graph
  13529. this.selectable = true;
  13530. // these functions are triggered when the dataset is edited
  13531. this.triggerFunctions = {add:null,edit:null,connect:null,delete:null};
  13532. // set constant values
  13533. this.constants = {
  13534. nodes: {
  13535. radiusMin: 5,
  13536. radiusMax: 20,
  13537. radius: 5,
  13538. shape: 'ellipse',
  13539. image: undefined,
  13540. widthMin: 16, // px
  13541. widthMax: 64, // px
  13542. fixed: false,
  13543. fontColor: 'black',
  13544. fontSize: 14, // px
  13545. fontFace: 'verdana',
  13546. level: -1,
  13547. color: {
  13548. border: '#2B7CE9',
  13549. background: '#97C2FC',
  13550. highlight: {
  13551. border: '#2B7CE9',
  13552. background: '#D2E5FF'
  13553. }
  13554. },
  13555. borderColor: '#2B7CE9',
  13556. backgroundColor: '#97C2FC',
  13557. highlightColor: '#D2E5FF',
  13558. group: undefined
  13559. },
  13560. edges: {
  13561. widthMin: 1,
  13562. widthMax: 15,
  13563. width: 1,
  13564. style: 'line',
  13565. color: '#848484',
  13566. fontColor: '#343434',
  13567. fontSize: 14, // px
  13568. fontFace: 'arial',
  13569. dash: {
  13570. length: 10,
  13571. gap: 5,
  13572. altLength: undefined
  13573. }
  13574. },
  13575. physics: {
  13576. barnesHut: {
  13577. enabled: true,
  13578. theta: 1 / 0.6, // inverted to save time during calculation
  13579. gravitationalConstant: -2000,
  13580. centralGravity: 0.3,
  13581. springLength: 100,
  13582. springConstant: 0.05,
  13583. damping: 0.09
  13584. },
  13585. repulsion: {
  13586. centralGravity: 0.1,
  13587. springLength: 200,
  13588. springConstant: 0.05,
  13589. nodeDistance: 100,
  13590. damping: 0.09
  13591. },
  13592. hierarchicalRepulsion: {
  13593. enabled: false,
  13594. centralGravity: 0.0,
  13595. springLength: 100,
  13596. springConstant: 0.01,
  13597. nodeDistance: 60,
  13598. damping: 0.09
  13599. },
  13600. damping: null,
  13601. centralGravity: null,
  13602. springLength: null,
  13603. springConstant: null
  13604. },
  13605. clustering: { // Per Node in Cluster = PNiC
  13606. enabled: false, // (Boolean) | global on/off switch for clustering.
  13607. initialMaxNodes: 100, // (# nodes) | if the initial amount of nodes is larger than this, we cluster until the total number is less than this threshold.
  13608. 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
  13609. 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
  13610. chainThreshold: 0.4, // (% of all drawn nodes)| maximum percentage of allowed chainnodes (long strings of connected nodes) within all nodes. (lower means less chains).
  13611. clusterEdgeThreshold: 20, // (px) | edge length threshold. if smaller, this node is clustered.
  13612. sectorThreshold: 100, // (# nodes in cluster) | cluster size threshold. If larger, expanding in own sector.
  13613. 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.
  13614. fontSizeMultiplier: 4.0, // (px PNiC) | how much the cluster font size grows per node in cluster (in px).
  13615. maxFontSize: 1000,
  13616. forceAmplification: 0.1, // (multiplier PNiC) | factor of increase fo the repulsion force of a cluster (per node in cluster).
  13617. distanceAmplification: 0.1, // (multiplier PNiC) | factor how much the repulsion distance of a cluster increases (per node in cluster).
  13618. edgeGrowth: 20, // (px PNiC) | amount of clusterSize connected to the edge is multiplied with this and added to edgeLength.
  13619. nodeScaling: {width: 1, // (px PNiC) | growth of the width per node in cluster.
  13620. height: 1, // (px PNiC) | growth of the height per node in cluster.
  13621. radius: 1}, // (px PNiC) | growth of the radius per node in cluster.
  13622. maxNodeSizeIncrements: 600, // (# increments) | max growth of the width per node in cluster.
  13623. activeAreaBoxSize: 80, // (px) | box area around the curser where clusters are popped open.
  13624. clusterLevelDifference: 2
  13625. },
  13626. navigation: {
  13627. enabled: false
  13628. },
  13629. keyboard: {
  13630. enabled: false,
  13631. speed: {x: 10, y: 10, zoom: 0.02}
  13632. },
  13633. dataManipulation: {
  13634. enabled: false,
  13635. initiallyVisible: false
  13636. },
  13637. hierarchicalLayout: {
  13638. enabled:false,
  13639. levelSeparation: 150,
  13640. nodeSpacing: 100
  13641. },
  13642. smoothCurves: true,
  13643. maxVelocity: 10,
  13644. minVelocity: 0.1, // px/s
  13645. maxIterations: 1000 // maximum number of iteration to stabilize
  13646. };
  13647. this.editMode = this.constants.dataManipulation.initiallyVisible;
  13648. // Node variables
  13649. var graph = this;
  13650. this.groups = new Groups(); // object with groups
  13651. this.images = new Images(); // object with images
  13652. this.images.setOnloadCallback(function () {
  13653. graph._redraw();
  13654. });
  13655. // keyboard navigation variables
  13656. this.xIncrement = 0;
  13657. this.yIncrement = 0;
  13658. this.zoomIncrement = 0;
  13659. // loading all the mixins:
  13660. // load the force calculation functions, grouped under the physics system.
  13661. this._loadPhysicsSystem();
  13662. // create a frame and canvas
  13663. this._create();
  13664. // load the sector system. (mandatory, fully integrated with Graph)
  13665. this._loadSectorSystem();
  13666. // load the cluster system. (mandatory, even when not using the cluster system, there are function calls to it)
  13667. this._loadClusterSystem();
  13668. // load the selection system. (mandatory, required by Graph)
  13669. this._loadSelectionSystem();
  13670. // load the selection system. (mandatory, required by Graph)
  13671. this._loadHierarchySystem();
  13672. // apply options
  13673. this.setOptions(options);
  13674. // other vars
  13675. this.freezeSimulation = false;// freeze the simulation
  13676. this.cachedFunctions = {};
  13677. // containers for nodes and edges
  13678. this.calculationNodes = {};
  13679. this.calculationNodeIndices = [];
  13680. this.nodeIndices = []; // array with all the indices of the nodes. Used to speed up forces calculation
  13681. this.nodes = {}; // object with Node objects
  13682. this.edges = {}; // object with Edge objects
  13683. // position and scale variables and objects
  13684. this.canvasTopLeft = {"x": 0,"y": 0}; // coordinates of the top left of the canvas. they will be set during _redraw.
  13685. this.canvasBottomRight = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  13686. this.pointerPosition = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  13687. this.areaCenter = {}; // object with x and y elements used for determining the center of the zoom action
  13688. this.scale = 1; // defining the global scale variable in the constructor
  13689. this.previousScale = this.scale; // this is used to check if the zoom operation is zooming in or out
  13690. // datasets or dataviews
  13691. this.nodesData = null; // A DataSet or DataView
  13692. this.edgesData = null; // A DataSet or DataView
  13693. // create event listeners used to subscribe on the DataSets of the nodes and edges
  13694. this.nodesListeners = {
  13695. 'add': function (event, params) {
  13696. graph._addNodes(params.items);
  13697. graph.start();
  13698. },
  13699. 'update': function (event, params) {
  13700. graph._updateNodes(params.items);
  13701. graph.start();
  13702. },
  13703. 'remove': function (event, params) {
  13704. graph._removeNodes(params.items);
  13705. graph.start();
  13706. }
  13707. };
  13708. this.edgesListeners = {
  13709. 'add': function (event, params) {
  13710. graph._addEdges(params.items);
  13711. graph.start();
  13712. },
  13713. 'update': function (event, params) {
  13714. graph._updateEdges(params.items);
  13715. graph.start();
  13716. },
  13717. 'remove': function (event, params) {
  13718. graph._removeEdges(params.items);
  13719. graph.start();
  13720. }
  13721. };
  13722. // properties for the animation
  13723. this.moving = true;
  13724. this.timer = undefined; // Scheduling function. Is definded in this.start();
  13725. // load data (the disable start variable will be the same as the enabled clustering)
  13726. this.setData(data,this.constants.clustering.enabled || this.constants.hierarchicalLayout.enabled);
  13727. // hierarchical layout
  13728. if (this.constants.hierarchicalLayout.enabled == true) {
  13729. this._setupHierarchicalLayout();
  13730. }
  13731. else {
  13732. // zoom so all data will fit on the screen, if clustering is enabled, we do not want start to be called here.
  13733. this.zoomToFit(true,this.constants.clustering.enabled);
  13734. }
  13735. // if clustering is disabled, the simulation will have started in the setData function
  13736. if (this.constants.clustering.enabled) {
  13737. this.startWithClustering();
  13738. }
  13739. }
  13740. // Extend Graph with an Emitter mixin
  13741. Emitter(Graph.prototype);
  13742. /**
  13743. * Get the script path where the vis.js library is located
  13744. *
  13745. * @returns {string | null} path Path or null when not found. Path does not
  13746. * end with a slash.
  13747. * @private
  13748. */
  13749. Graph.prototype._getScriptPath = function() {
  13750. var scripts = document.getElementsByTagName( 'script' );
  13751. // find script named vis.js or vis.min.js
  13752. for (var i = 0; i < scripts.length; i++) {
  13753. var src = scripts[i].src;
  13754. var match = src && /\/?vis(.min)?\.js$/.exec(src);
  13755. if (match) {
  13756. // return path without the script name
  13757. return src.substring(0, src.length - match[0].length);
  13758. }
  13759. }
  13760. return null;
  13761. };
  13762. /**
  13763. * Find the center position of the graph
  13764. * @private
  13765. */
  13766. Graph.prototype._getRange = function() {
  13767. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  13768. for (var nodeId in this.nodes) {
  13769. if (this.nodes.hasOwnProperty(nodeId)) {
  13770. node = this.nodes[nodeId];
  13771. if (minX > (node.x - node.width)) {minX = node.x - node.width;}
  13772. if (maxX < (node.x + node.width)) {maxX = node.x + node.width;}
  13773. if (minY > (node.y - node.height)) {minY = node.y - node.height;}
  13774. if (maxY < (node.y + node.height)) {maxY = node.y + node.height;}
  13775. }
  13776. }
  13777. return {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  13778. };
  13779. /**
  13780. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  13781. * @returns {{x: number, y: number}}
  13782. * @private
  13783. */
  13784. Graph.prototype._findCenter = function(range) {
  13785. return {x: (0.5 * (range.maxX + range.minX)),
  13786. y: (0.5 * (range.maxY + range.minY))};
  13787. };
  13788. /**
  13789. * center the graph
  13790. *
  13791. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  13792. */
  13793. Graph.prototype._centerGraph = function(range) {
  13794. var center = this._findCenter(range);
  13795. center.x *= this.scale;
  13796. center.y *= this.scale;
  13797. center.x -= 0.5 * this.frame.canvas.clientWidth;
  13798. center.y -= 0.5 * this.frame.canvas.clientHeight;
  13799. this._setTranslation(-center.x,-center.y); // set at 0,0
  13800. };
  13801. /**
  13802. * This function zooms out to fit all data on screen based on amount of nodes
  13803. *
  13804. * @param {Boolean} [initialZoom] | zoom based on fitted formula or range, true = fitted, default = false;
  13805. */
  13806. Graph.prototype.zoomToFit = function(initialZoom, disableStart) {
  13807. if (initialZoom === undefined) {
  13808. initialZoom = false;
  13809. }
  13810. var range = this._getRange();
  13811. var zoomLevel;
  13812. if (initialZoom == true) {
  13813. var numberOfNodes = this.nodeIndices.length;
  13814. if (this.constants.smoothCurves == true) {
  13815. if (this.constants.clustering.enabled == true &&
  13816. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  13817. 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.
  13818. }
  13819. else {
  13820. zoomLevel = 12.662 / (numberOfNodes + 7.4147) + 0.0964822; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  13821. }
  13822. }
  13823. else {
  13824. if (this.constants.clustering.enabled == true &&
  13825. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  13826. 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.
  13827. }
  13828. else {
  13829. zoomLevel = 30.5062972 / (numberOfNodes + 19.93597763) + 0.08413486; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  13830. }
  13831. }
  13832. }
  13833. else {
  13834. var xDistance = (Math.abs(range.minX) + Math.abs(range.maxX)) * 1.1;
  13835. var yDistance = (Math.abs(range.minY) + Math.abs(range.maxY)) * 1.1;
  13836. var xZoomLevel = this.frame.canvas.clientWidth / xDistance;
  13837. var yZoomLevel = this.frame.canvas.clientHeight / yDistance;
  13838. zoomLevel = (xZoomLevel <= yZoomLevel) ? xZoomLevel : yZoomLevel;
  13839. }
  13840. if (zoomLevel > 1.0) {
  13841. zoomLevel = 1.0;
  13842. }
  13843. this.pinch.mousewheelScale = zoomLevel;
  13844. this._setScale(zoomLevel);
  13845. this._centerGraph(range);
  13846. if (disableStart == false || disableStart === undefined) {
  13847. this.moving = true;
  13848. this.start();
  13849. }
  13850. };
  13851. /**
  13852. * Update the this.nodeIndices with the most recent node index list
  13853. * @private
  13854. */
  13855. Graph.prototype._updateNodeIndexList = function() {
  13856. this._clearNodeIndexList();
  13857. for (var idx in this.nodes) {
  13858. if (this.nodes.hasOwnProperty(idx)) {
  13859. this.nodeIndices.push(idx);
  13860. }
  13861. }
  13862. };
  13863. /**
  13864. * Set nodes and edges, and optionally options as well.
  13865. *
  13866. * @param {Object} data Object containing parameters:
  13867. * {Array | DataSet | DataView} [nodes] Array with nodes
  13868. * {Array | DataSet | DataView} [edges] Array with edges
  13869. * {String} [dot] String containing data in DOT format
  13870. * {Options} [options] Object with options
  13871. * @param {Boolean} [disableStart] | optional: disable the calling of the start function.
  13872. */
  13873. Graph.prototype.setData = function(data, disableStart) {
  13874. if (disableStart === undefined) {
  13875. disableStart = false;
  13876. }
  13877. if (data && data.dot && (data.nodes || data.edges)) {
  13878. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  13879. ' parameter pair "nodes" and "edges", but not both.');
  13880. }
  13881. // set options
  13882. this.setOptions(data && data.options);
  13883. // set all data
  13884. if (data && data.dot) {
  13885. // parse DOT file
  13886. if(data && data.dot) {
  13887. var dotData = vis.util.DOTToGraph(data.dot);
  13888. this.setData(dotData);
  13889. return;
  13890. }
  13891. }
  13892. else {
  13893. this._setNodes(data && data.nodes);
  13894. this._setEdges(data && data.edges);
  13895. }
  13896. this._putDataInSector();
  13897. if (!disableStart) {
  13898. // find a stable position or start animating to a stable position
  13899. if (this.stabilize) {
  13900. this._doStabilize();
  13901. }
  13902. this.start();
  13903. }
  13904. };
  13905. /**
  13906. * Set options
  13907. * @param {Object} options
  13908. */
  13909. Graph.prototype.setOptions = function (options) {
  13910. if (options) {
  13911. var prop;
  13912. // retrieve parameter values
  13913. if (options.width !== undefined) {this.width = options.width;}
  13914. if (options.height !== undefined) {this.height = options.height;}
  13915. if (options.stabilize !== undefined) {this.stabilize = options.stabilize;}
  13916. if (options.selectable !== undefined) {this.selectable = options.selectable;}
  13917. if (options.smoothCurves !== undefined) {this.constants.smoothCurves = options.smoothCurves;}
  13918. if (options.onAdd) {
  13919. this.triggerFunctions.add = options.onAdd;
  13920. }
  13921. if (options.onEdit) {
  13922. this.triggerFunctions.edit = options.onEdit;
  13923. }
  13924. if (options.onConnect) {
  13925. this.triggerFunctions.connect = options.onConnect;
  13926. }
  13927. if (options.onDelete) {
  13928. this.triggerFunctions.delete = options.onDelete;
  13929. }
  13930. if (options.physics) {
  13931. if (options.physics.barnesHut) {
  13932. this.constants.physics.barnesHut.enabled = true;
  13933. for (prop in options.physics.barnesHut) {
  13934. if (options.physics.barnesHut.hasOwnProperty(prop)) {
  13935. this.constants.physics.barnesHut[prop] = options.physics.barnesHut[prop];
  13936. }
  13937. }
  13938. }
  13939. if (options.physics.repulsion) {
  13940. this.constants.physics.barnesHut.enabled = false;
  13941. for (prop in options.physics.repulsion) {
  13942. if (options.physics.repulsion.hasOwnProperty(prop)) {
  13943. this.constants.physics.repulsion[prop] = options.physics.repulsion[prop];
  13944. }
  13945. }
  13946. }
  13947. }
  13948. if (options.hierarchicalLayout) {
  13949. this.constants.hierarchicalLayout.enabled = true;
  13950. for (prop in options.hierarchicalLayout) {
  13951. if (options.hierarchicalLayout.hasOwnProperty(prop)) {
  13952. this.constants.hierarchicalLayout[prop] = options.hierarchicalLayout[prop];
  13953. }
  13954. }
  13955. }
  13956. else if (options.hierarchicalLayout !== undefined) {
  13957. this.constants.hierarchicalLayout.enabled = false;
  13958. }
  13959. if (options.clustering) {
  13960. this.constants.clustering.enabled = true;
  13961. for (prop in options.clustering) {
  13962. if (options.clustering.hasOwnProperty(prop)) {
  13963. this.constants.clustering[prop] = options.clustering[prop];
  13964. }
  13965. }
  13966. }
  13967. else if (options.clustering !== undefined) {
  13968. this.constants.clustering.enabled = false;
  13969. }
  13970. if (options.navigation) {
  13971. this.constants.navigation.enabled = true;
  13972. for (prop in options.navigation) {
  13973. if (options.navigation.hasOwnProperty(prop)) {
  13974. this.constants.navigation[prop] = options.navigation[prop];
  13975. }
  13976. }
  13977. }
  13978. else if (options.navigation !== undefined) {
  13979. this.constants.navigation.enabled = false;
  13980. }
  13981. if (options.keyboard) {
  13982. this.constants.keyboard.enabled = true;
  13983. for (prop in options.keyboard) {
  13984. if (options.keyboard.hasOwnProperty(prop)) {
  13985. this.constants.keyboard[prop] = options.keyboard[prop];
  13986. }
  13987. }
  13988. }
  13989. else if (options.keyboard !== undefined) {
  13990. this.constants.keyboard.enabled = false;
  13991. }
  13992. if (options.dataManipulation) {
  13993. this.constants.dataManipulation.enabled = true;
  13994. for (prop in options.dataManipulation) {
  13995. if (options.dataManipulation.hasOwnProperty(prop)) {
  13996. this.constants.dataManipulation[prop] = options.dataManipulation[prop];
  13997. }
  13998. }
  13999. }
  14000. else if (options.dataManipulation !== undefined) {
  14001. this.constants.dataManipulation.enabled = false;
  14002. }
  14003. // TODO: work out these options and document them
  14004. if (options.edges) {
  14005. for (prop in options.edges) {
  14006. if (options.edges.hasOwnProperty(prop)) {
  14007. this.constants.edges[prop] = options.edges[prop];
  14008. }
  14009. }
  14010. if (!options.edges.fontColor) {
  14011. this.constants.edges.fontColor = options.edges.color;
  14012. }
  14013. // Added to support dashed lines
  14014. // David Jordan
  14015. // 2012-08-08
  14016. if (options.edges.dash) {
  14017. if (options.edges.dash.length !== undefined) {
  14018. this.constants.edges.dash.length = options.edges.dash.length;
  14019. }
  14020. if (options.edges.dash.gap !== undefined) {
  14021. this.constants.edges.dash.gap = options.edges.dash.gap;
  14022. }
  14023. if (options.edges.dash.altLength !== undefined) {
  14024. this.constants.edges.dash.altLength = options.edges.dash.altLength;
  14025. }
  14026. }
  14027. }
  14028. if (options.nodes) {
  14029. for (prop in options.nodes) {
  14030. if (options.nodes.hasOwnProperty(prop)) {
  14031. this.constants.nodes[prop] = options.nodes[prop];
  14032. }
  14033. }
  14034. if (options.nodes.color) {
  14035. this.constants.nodes.color = Node.parseColor(options.nodes.color);
  14036. }
  14037. /*
  14038. if (options.nodes.widthMin) this.constants.nodes.radiusMin = options.nodes.widthMin;
  14039. if (options.nodes.widthMax) this.constants.nodes.radiusMax = options.nodes.widthMax;
  14040. */
  14041. }
  14042. if (options.groups) {
  14043. for (var groupname in options.groups) {
  14044. if (options.groups.hasOwnProperty(groupname)) {
  14045. var group = options.groups[groupname];
  14046. this.groups.add(groupname, group);
  14047. }
  14048. }
  14049. }
  14050. }
  14051. // (Re)loading the mixins that can be enabled or disabled in the options.
  14052. // load the force calculation functions, grouped under the physics system.
  14053. this._loadPhysicsSystem();
  14054. // load the navigation system.
  14055. this._loadNavigationControls();
  14056. // load the data manipulation system
  14057. this._loadManipulationSystem();
  14058. // configure the smooth curves
  14059. this._configureSmoothCurves();
  14060. // bind keys. If disabled, this will not do anything;
  14061. this._createKeyBinds();
  14062. this.setSize(this.width, this.height);
  14063. this._setTranslation(this.frame.clientWidth / 2, this.frame.clientHeight / 2);
  14064. this._setScale(1);
  14065. this._redraw();
  14066. };
  14067. /**
  14068. * Create the main frame for the Graph.
  14069. * This function is executed once when a Graph object is created. The frame
  14070. * contains a canvas, and this canvas contains all objects like the axis and
  14071. * nodes.
  14072. * @private
  14073. */
  14074. Graph.prototype._create = function () {
  14075. // remove all elements from the container element.
  14076. while (this.containerElement.hasChildNodes()) {
  14077. this.containerElement.removeChild(this.containerElement.firstChild);
  14078. }
  14079. this.frame = document.createElement('div');
  14080. this.frame.className = 'graph-frame';
  14081. this.frame.style.position = 'relative';
  14082. this.frame.style.overflow = 'hidden';
  14083. this.frame.style.zIndex = "1";
  14084. // create the graph canvas (HTML canvas element)
  14085. this.frame.canvas = document.createElement( 'canvas' );
  14086. this.frame.canvas.style.position = 'relative';
  14087. this.frame.appendChild(this.frame.canvas);
  14088. if (!this.frame.canvas.getContext) {
  14089. var noCanvas = document.createElement( 'DIV' );
  14090. noCanvas.style.color = 'red';
  14091. noCanvas.style.fontWeight = 'bold' ;
  14092. noCanvas.style.padding = '10px';
  14093. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  14094. this.frame.canvas.appendChild(noCanvas);
  14095. }
  14096. var me = this;
  14097. this.drag = {};
  14098. this.pinch = {};
  14099. this.hammer = Hammer(this.frame.canvas, {
  14100. prevent_default: true
  14101. });
  14102. this.hammer.on('tap', me._onTap.bind(me) );
  14103. this.hammer.on('doubletap', me._onDoubleTap.bind(me) );
  14104. this.hammer.on('hold', me._onHold.bind(me) );
  14105. this.hammer.on('pinch', me._onPinch.bind(me) );
  14106. this.hammer.on('touch', me._onTouch.bind(me) );
  14107. this.hammer.on('dragstart', me._onDragStart.bind(me) );
  14108. this.hammer.on('drag', me._onDrag.bind(me) );
  14109. this.hammer.on('dragend', me._onDragEnd.bind(me) );
  14110. this.hammer.on('release', me._onRelease.bind(me) );
  14111. this.hammer.on('mousewheel',me._onMouseWheel.bind(me) );
  14112. this.hammer.on('DOMMouseScroll',me._onMouseWheel.bind(me) ); // for FF
  14113. this.hammer.on('mousemove', me._onMouseMoveTitle.bind(me) );
  14114. // add the frame to the container element
  14115. this.containerElement.appendChild(this.frame);
  14116. };
  14117. /**
  14118. * Binding the keys for keyboard navigation. These functions are defined in the NavigationMixin
  14119. * @private
  14120. */
  14121. Graph.prototype._createKeyBinds = function() {
  14122. var me = this;
  14123. this.mousetrap = mousetrap;
  14124. this.mousetrap.reset();
  14125. if (this.constants.keyboard.enabled == true) {
  14126. this.mousetrap.bind("up", this._moveUp.bind(me) , "keydown");
  14127. this.mousetrap.bind("up", this._yStopMoving.bind(me), "keyup");
  14128. this.mousetrap.bind("down", this._moveDown.bind(me) , "keydown");
  14129. this.mousetrap.bind("down", this._yStopMoving.bind(me), "keyup");
  14130. this.mousetrap.bind("left", this._moveLeft.bind(me) , "keydown");
  14131. this.mousetrap.bind("left", this._xStopMoving.bind(me), "keyup");
  14132. this.mousetrap.bind("right",this._moveRight.bind(me), "keydown");
  14133. this.mousetrap.bind("right",this._xStopMoving.bind(me), "keyup");
  14134. this.mousetrap.bind("=", this._zoomIn.bind(me), "keydown");
  14135. this.mousetrap.bind("=", this._stopZoom.bind(me), "keyup");
  14136. this.mousetrap.bind("-", this._zoomOut.bind(me), "keydown");
  14137. this.mousetrap.bind("-", this._stopZoom.bind(me), "keyup");
  14138. this.mousetrap.bind("[", this._zoomIn.bind(me), "keydown");
  14139. this.mousetrap.bind("[", this._stopZoom.bind(me), "keyup");
  14140. this.mousetrap.bind("]", this._zoomOut.bind(me), "keydown");
  14141. this.mousetrap.bind("]", this._stopZoom.bind(me), "keyup");
  14142. this.mousetrap.bind("pageup",this._zoomIn.bind(me), "keydown");
  14143. this.mousetrap.bind("pageup",this._stopZoom.bind(me), "keyup");
  14144. this.mousetrap.bind("pagedown",this._zoomOut.bind(me),"keydown");
  14145. this.mousetrap.bind("pagedown",this._stopZoom.bind(me), "keyup");
  14146. }
  14147. if (this.constants.dataManipulation.enabled == true) {
  14148. this.mousetrap.bind("escape",this._createManipulatorBar.bind(me));
  14149. this.mousetrap.bind("del",this._deleteSelected.bind(me));
  14150. }
  14151. };
  14152. /**
  14153. * Get the pointer location from a touch location
  14154. * @param {{pageX: Number, pageY: Number}} touch
  14155. * @return {{x: Number, y: Number}} pointer
  14156. * @private
  14157. */
  14158. Graph.prototype._getPointer = function (touch) {
  14159. return {
  14160. x: touch.pageX - vis.util.getAbsoluteLeft(this.frame.canvas),
  14161. y: touch.pageY - vis.util.getAbsoluteTop(this.frame.canvas)
  14162. };
  14163. };
  14164. /**
  14165. * On start of a touch gesture, store the pointer
  14166. * @param event
  14167. * @private
  14168. */
  14169. Graph.prototype._onTouch = function (event) {
  14170. this.drag.pointer = this._getPointer(event.gesture.center);
  14171. this.drag.pinched = false;
  14172. this.pinch.scale = this._getScale();
  14173. this._handleTouch(this.drag.pointer);
  14174. };
  14175. /**
  14176. * handle drag start event
  14177. * @private
  14178. */
  14179. Graph.prototype._onDragStart = function () {
  14180. this._handleDragStart();
  14181. };
  14182. /**
  14183. * This function is called by _onDragStart.
  14184. * It is separated out because we can then overload it for the datamanipulation system.
  14185. *
  14186. * @private
  14187. */
  14188. Graph.prototype._handleDragStart = function() {
  14189. var drag = this.drag;
  14190. var node = this._getNodeAt(drag.pointer);
  14191. // note: drag.pointer is set in _onTouch to get the initial touch location
  14192. drag.dragging = true;
  14193. drag.selection = [];
  14194. drag.translation = this._getTranslation();
  14195. drag.nodeId = null;
  14196. if (node != null) {
  14197. drag.nodeId = node.id;
  14198. // select the clicked node if not yet selected
  14199. if (!node.isSelected()) {
  14200. this._selectObject(node,false);
  14201. }
  14202. // create an array with the selected nodes and their original location and status
  14203. for (var objectId in this.selectionObj) {
  14204. if (this.selectionObj.hasOwnProperty(objectId)) {
  14205. var object = this.selectionObj[objectId];
  14206. if (object instanceof Node) {
  14207. var s = {
  14208. id: object.id,
  14209. node: object,
  14210. // store original x, y, xFixed and yFixed, make the node temporarily Fixed
  14211. x: object.x,
  14212. y: object.y,
  14213. xFixed: object.xFixed,
  14214. yFixed: object.yFixed
  14215. };
  14216. object.xFixed = true;
  14217. object.yFixed = true;
  14218. drag.selection.push(s);
  14219. }
  14220. }
  14221. }
  14222. }
  14223. };
  14224. /**
  14225. * handle drag event
  14226. * @private
  14227. */
  14228. Graph.prototype._onDrag = function (event) {
  14229. this._handleOnDrag(event)
  14230. };
  14231. /**
  14232. * This function is called by _onDrag.
  14233. * It is separated out because we can then overload it for the datamanipulation system.
  14234. *
  14235. * @private
  14236. */
  14237. Graph.prototype._handleOnDrag = function(event) {
  14238. if (this.drag.pinched) {
  14239. return;
  14240. }
  14241. var pointer = this._getPointer(event.gesture.center);
  14242. var me = this,
  14243. drag = this.drag,
  14244. selection = drag.selection;
  14245. if (selection && selection.length) {
  14246. // calculate delta's and new location
  14247. var deltaX = pointer.x - drag.pointer.x,
  14248. deltaY = pointer.y - drag.pointer.y;
  14249. // update position of all selected nodes
  14250. selection.forEach(function (s) {
  14251. var node = s.node;
  14252. if (!s.xFixed) {
  14253. node.x = me._canvasToX(me._xToCanvas(s.x) + deltaX);
  14254. }
  14255. if (!s.yFixed) {
  14256. node.y = me._canvasToY(me._yToCanvas(s.y) + deltaY);
  14257. }
  14258. });
  14259. // start _animationStep if not yet running
  14260. if (!this.moving) {
  14261. this.moving = true;
  14262. this.start();
  14263. }
  14264. }
  14265. else {
  14266. // move the graph
  14267. var diffX = pointer.x - this.drag.pointer.x;
  14268. var diffY = pointer.y - this.drag.pointer.y;
  14269. this._setTranslation(
  14270. this.drag.translation.x + diffX,
  14271. this.drag.translation.y + diffY);
  14272. this._redraw();
  14273. this.moved = true;
  14274. }
  14275. };
  14276. /**
  14277. * handle drag start event
  14278. * @private
  14279. */
  14280. Graph.prototype._onDragEnd = function () {
  14281. this.drag.dragging = false;
  14282. var selection = this.drag.selection;
  14283. if (selection) {
  14284. selection.forEach(function (s) {
  14285. // restore original xFixed and yFixed
  14286. s.node.xFixed = s.xFixed;
  14287. s.node.yFixed = s.yFixed;
  14288. });
  14289. }
  14290. };
  14291. /**
  14292. * handle tap/click event: select/unselect a node
  14293. * @private
  14294. */
  14295. Graph.prototype._onTap = function (event) {
  14296. var pointer = this._getPointer(event.gesture.center);
  14297. this.pointerPosition = pointer;
  14298. this._handleTap(pointer);
  14299. };
  14300. /**
  14301. * handle doubletap event
  14302. * @private
  14303. */
  14304. Graph.prototype._onDoubleTap = function (event) {
  14305. var pointer = this._getPointer(event.gesture.center);
  14306. this._handleDoubleTap(pointer);
  14307. };
  14308. /**
  14309. * handle long tap event: multi select nodes
  14310. * @private
  14311. */
  14312. Graph.prototype._onHold = function (event) {
  14313. var pointer = this._getPointer(event.gesture.center);
  14314. this.pointerPosition = pointer;
  14315. this._handleOnHold(pointer);
  14316. };
  14317. /**
  14318. * handle the release of the screen
  14319. *
  14320. * @private
  14321. */
  14322. Graph.prototype._onRelease = function (event) {
  14323. var pointer = this._getPointer(event.gesture.center);
  14324. this._handleOnRelease(pointer);
  14325. };
  14326. /**
  14327. * Handle pinch event
  14328. * @param event
  14329. * @private
  14330. */
  14331. Graph.prototype._onPinch = function (event) {
  14332. var pointer = this._getPointer(event.gesture.center);
  14333. this.drag.pinched = true;
  14334. if (!('scale' in this.pinch)) {
  14335. this.pinch.scale = 1;
  14336. }
  14337. // TODO: enabled moving while pinching?
  14338. var scale = this.pinch.scale * event.gesture.scale;
  14339. this._zoom(scale, pointer)
  14340. };
  14341. /**
  14342. * Zoom the graph in or out
  14343. * @param {Number} scale a number around 1, and between 0.01 and 10
  14344. * @param {{x: Number, y: Number}} pointer Position on screen
  14345. * @return {Number} appliedScale scale is limited within the boundaries
  14346. * @private
  14347. */
  14348. Graph.prototype._zoom = function(scale, pointer) {
  14349. var scaleOld = this._getScale();
  14350. if (scale < 0.00001) {
  14351. scale = 0.00001;
  14352. }
  14353. if (scale > 10) {
  14354. scale = 10;
  14355. }
  14356. // + this.frame.canvas.clientHeight / 2
  14357. var translation = this._getTranslation();
  14358. var scaleFrac = scale / scaleOld;
  14359. var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac;
  14360. var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac;
  14361. this.areaCenter = {"x" : this._canvasToX(pointer.x),
  14362. "y" : this._canvasToY(pointer.y)};
  14363. this.pinch.mousewheelScale = scale;
  14364. this._setScale(scale);
  14365. this._setTranslation(tx, ty);
  14366. this.updateClustersDefault();
  14367. this._redraw();
  14368. return scale;
  14369. };
  14370. /**
  14371. * Event handler for mouse wheel event, used to zoom the timeline
  14372. * See http://adomas.org/javascript-mouse-wheel/
  14373. * https://github.com/EightMedia/hammer.js/issues/256
  14374. * @param {MouseEvent} event
  14375. * @private
  14376. */
  14377. Graph.prototype._onMouseWheel = function(event) {
  14378. // retrieve delta
  14379. var delta = 0;
  14380. if (event.wheelDelta) { /* IE/Opera. */
  14381. delta = event.wheelDelta/120;
  14382. } else if (event.detail) { /* Mozilla case. */
  14383. // In Mozilla, sign of delta is different than in IE.
  14384. // Also, delta is multiple of 3.
  14385. delta = -event.detail/3;
  14386. }
  14387. // If delta is nonzero, handle it.
  14388. // Basically, delta is now positive if wheel was scrolled up,
  14389. // and negative, if wheel was scrolled down.
  14390. if (delta) {
  14391. if (!('mousewheelScale' in this.pinch)) {
  14392. this.pinch.mousewheelScale = 1;
  14393. }
  14394. // calculate the new scale
  14395. var scale = this.pinch.mousewheelScale;
  14396. var zoom = delta / 10;
  14397. if (delta < 0) {
  14398. zoom = zoom / (1 - zoom);
  14399. }
  14400. scale *= (1 + zoom);
  14401. // calculate the pointer location
  14402. var gesture = util.fakeGesture(this, event);
  14403. var pointer = this._getPointer(gesture.center);
  14404. // apply the new scale
  14405. this._zoom(scale, pointer);
  14406. // store the new, applied scale -- this is now done in _zoom
  14407. // this.pinch.mousewheelScale = scale;
  14408. }
  14409. // Prevent default actions caused by mouse wheel.
  14410. event.preventDefault();
  14411. };
  14412. /**
  14413. * Mouse move handler for checking whether the title moves over a node with a title.
  14414. * @param {Event} event
  14415. * @private
  14416. */
  14417. Graph.prototype._onMouseMoveTitle = function (event) {
  14418. var gesture = util.fakeGesture(this, event);
  14419. var pointer = this._getPointer(gesture.center);
  14420. // check if the previously selected node is still selected
  14421. if (this.popupNode) {
  14422. this._checkHidePopup(pointer);
  14423. }
  14424. // start a timeout that will check if the mouse is positioned above
  14425. // an element
  14426. var me = this;
  14427. var checkShow = function() {
  14428. me._checkShowPopup(pointer);
  14429. };
  14430. if (this.popupTimer) {
  14431. clearInterval(this.popupTimer); // stop any running calculationTimer
  14432. }
  14433. if (!this.drag.dragging) {
  14434. this.popupTimer = setTimeout(checkShow, 300);
  14435. }
  14436. };
  14437. /**
  14438. * Check if there is an element on the given position in the graph
  14439. * (a node or edge). If so, and if this element has a title,
  14440. * show a popup window with its title.
  14441. *
  14442. * @param {{x:Number, y:Number}} pointer
  14443. * @private
  14444. */
  14445. Graph.prototype._checkShowPopup = function (pointer) {
  14446. var obj = {
  14447. left: this._canvasToX(pointer.x),
  14448. top: this._canvasToY(pointer.y),
  14449. right: this._canvasToX(pointer.x),
  14450. bottom: this._canvasToY(pointer.y)
  14451. };
  14452. var id;
  14453. var lastPopupNode = this.popupNode;
  14454. if (this.popupNode == undefined) {
  14455. // search the nodes for overlap, select the top one in case of multiple nodes
  14456. var nodes = this.nodes;
  14457. for (id in nodes) {
  14458. if (nodes.hasOwnProperty(id)) {
  14459. var node = nodes[id];
  14460. if (node.getTitle() !== undefined && node.isOverlappingWith(obj)) {
  14461. this.popupNode = node;
  14462. break;
  14463. }
  14464. }
  14465. }
  14466. }
  14467. if (this.popupNode === undefined) {
  14468. // search the edges for overlap
  14469. var edges = this.edges;
  14470. for (id in edges) {
  14471. if (edges.hasOwnProperty(id)) {
  14472. var edge = edges[id];
  14473. if (edge.connected && (edge.getTitle() !== undefined) &&
  14474. edge.isOverlappingWith(obj)) {
  14475. this.popupNode = edge;
  14476. break;
  14477. }
  14478. }
  14479. }
  14480. }
  14481. if (this.popupNode) {
  14482. // show popup message window
  14483. if (this.popupNode != lastPopupNode) {
  14484. var me = this;
  14485. if (!me.popup) {
  14486. me.popup = new Popup(me.frame);
  14487. }
  14488. // adjust a small offset such that the mouse cursor is located in the
  14489. // bottom left location of the popup, and you can easily move over the
  14490. // popup area
  14491. me.popup.setPosition(pointer.x - 3, pointer.y - 3);
  14492. me.popup.setText(me.popupNode.getTitle());
  14493. me.popup.show();
  14494. }
  14495. }
  14496. else {
  14497. if (this.popup) {
  14498. this.popup.hide();
  14499. }
  14500. }
  14501. };
  14502. /**
  14503. * Check if the popup must be hided, which is the case when the mouse is no
  14504. * longer hovering on the object
  14505. * @param {{x:Number, y:Number}} pointer
  14506. * @private
  14507. */
  14508. Graph.prototype._checkHidePopup = function (pointer) {
  14509. if (!this.popupNode || !this._getNodeAt(pointer) ) {
  14510. this.popupNode = undefined;
  14511. if (this.popup) {
  14512. this.popup.hide();
  14513. }
  14514. }
  14515. };
  14516. /**
  14517. * Set a new size for the graph
  14518. * @param {string} width Width in pixels or percentage (for example '800px'
  14519. * or '50%')
  14520. * @param {string} height Height in pixels or percentage (for example '400px'
  14521. * or '30%')
  14522. */
  14523. Graph.prototype.setSize = function(width, height) {
  14524. this.frame.style.width = width;
  14525. this.frame.style.height = height;
  14526. this.frame.canvas.style.width = '100%';
  14527. this.frame.canvas.style.height = '100%';
  14528. this.frame.canvas.width = this.frame.canvas.clientWidth;
  14529. this.frame.canvas.height = this.frame.canvas.clientHeight;
  14530. if (this.manipulationDiv !== undefined) {
  14531. this.manipulationDiv.style.width = this.frame.canvas.clientWidth;
  14532. }
  14533. this.emit('frameResize', {width:this.frame.canvas.width,height:this.frame.canvas.height});
  14534. };
  14535. /**
  14536. * Set a data set with nodes for the graph
  14537. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  14538. * @private
  14539. */
  14540. Graph.prototype._setNodes = function(nodes) {
  14541. var oldNodesData = this.nodesData;
  14542. if (nodes instanceof DataSet || nodes instanceof DataView) {
  14543. this.nodesData = nodes;
  14544. }
  14545. else if (nodes instanceof Array) {
  14546. this.nodesData = new DataSet();
  14547. this.nodesData.add(nodes);
  14548. }
  14549. else if (!nodes) {
  14550. this.nodesData = new DataSet();
  14551. }
  14552. else {
  14553. throw new TypeError('Array or DataSet expected');
  14554. }
  14555. if (oldNodesData) {
  14556. // unsubscribe from old dataset
  14557. util.forEach(this.nodesListeners, function (callback, event) {
  14558. oldNodesData.off(event, callback);
  14559. });
  14560. }
  14561. // remove drawn nodes
  14562. this.nodes = {};
  14563. if (this.nodesData) {
  14564. // subscribe to new dataset
  14565. var me = this;
  14566. util.forEach(this.nodesListeners, function (callback, event) {
  14567. me.nodesData.on(event, callback);
  14568. });
  14569. // draw all new nodes
  14570. var ids = this.nodesData.getIds();
  14571. this._addNodes(ids);
  14572. }
  14573. this._updateSelection();
  14574. };
  14575. /**
  14576. * Add nodes
  14577. * @param {Number[] | String[]} ids
  14578. * @private
  14579. */
  14580. Graph.prototype._addNodes = function(ids) {
  14581. var id;
  14582. for (var i = 0, len = ids.length; i < len; i++) {
  14583. id = ids[i];
  14584. var data = this.nodesData.get(id);
  14585. var node = new Node(data, this.images, this.groups, this.constants);
  14586. this.nodes[id] = node; // note: this may replace an existing node
  14587. if ((node.xFixed == false || node.yFixed == false) && this.createNodeOnClick != true) {
  14588. var radius = 10 * 0.1*ids.length;
  14589. var angle = 2 * Math.PI * Math.random();
  14590. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  14591. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  14592. // note: no not use node.isMoving() here, as that gives the current
  14593. // velocity of the node, which is zero after creation of the node.
  14594. this.moving = true;
  14595. }
  14596. }
  14597. this._updateNodeIndexList();
  14598. this._updateCalculationNodes();
  14599. this._reconnectEdges();
  14600. this._updateValueRange(this.nodes);
  14601. this.updateLabels();
  14602. };
  14603. /**
  14604. * Update existing nodes, or create them when not yet existing
  14605. * @param {Number[] | String[]} ids
  14606. * @private
  14607. */
  14608. Graph.prototype._updateNodes = function(ids) {
  14609. var nodes = this.nodes,
  14610. nodesData = this.nodesData;
  14611. for (var i = 0, len = ids.length; i < len; i++) {
  14612. var id = ids[i];
  14613. var node = nodes[id];
  14614. var data = nodesData.get(id);
  14615. if (node) {
  14616. // update node
  14617. node.setProperties(data, this.constants);
  14618. }
  14619. else {
  14620. // create node
  14621. node = new Node(properties, this.images, this.groups, this.constants);
  14622. nodes[id] = node;
  14623. if (!node.isFixed()) {
  14624. this.moving = true;
  14625. }
  14626. }
  14627. }
  14628. this._updateNodeIndexList();
  14629. this._reconnectEdges();
  14630. this._updateValueRange(nodes);
  14631. };
  14632. /**
  14633. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  14634. * @param {Number[] | String[]} ids
  14635. * @private
  14636. */
  14637. Graph.prototype._removeNodes = function(ids) {
  14638. var nodes = this.nodes;
  14639. for (var i = 0, len = ids.length; i < len; i++) {
  14640. var id = ids[i];
  14641. delete nodes[id];
  14642. }
  14643. this._updateNodeIndexList();
  14644. this._reconnectEdges();
  14645. this._updateSelection();
  14646. this._updateValueRange(nodes);
  14647. };
  14648. /**
  14649. * Load edges by reading the data table
  14650. * @param {Array | DataSet | DataView} edges The data containing the edges.
  14651. * @private
  14652. * @private
  14653. */
  14654. Graph.prototype._setEdges = function(edges) {
  14655. var oldEdgesData = this.edgesData;
  14656. if (edges instanceof DataSet || edges instanceof DataView) {
  14657. this.edgesData = edges;
  14658. }
  14659. else if (edges instanceof Array) {
  14660. this.edgesData = new DataSet();
  14661. this.edgesData.add(edges);
  14662. }
  14663. else if (!edges) {
  14664. this.edgesData = new DataSet();
  14665. }
  14666. else {
  14667. throw new TypeError('Array or DataSet expected');
  14668. }
  14669. if (oldEdgesData) {
  14670. // unsubscribe from old dataset
  14671. util.forEach(this.edgesListeners, function (callback, event) {
  14672. oldEdgesData.off(event, callback);
  14673. });
  14674. }
  14675. // remove drawn edges
  14676. this.edges = {};
  14677. if (this.edgesData) {
  14678. // subscribe to new dataset
  14679. var me = this;
  14680. util.forEach(this.edgesListeners, function (callback, event) {
  14681. me.edgesData.on(event, callback);
  14682. });
  14683. // draw all new nodes
  14684. var ids = this.edgesData.getIds();
  14685. this._addEdges(ids);
  14686. }
  14687. this._reconnectEdges();
  14688. };
  14689. /**
  14690. * Add edges
  14691. * @param {Number[] | String[]} ids
  14692. * @private
  14693. */
  14694. Graph.prototype._addEdges = function (ids) {
  14695. var edges = this.edges,
  14696. edgesData = this.edgesData;
  14697. for (var i = 0, len = ids.length; i < len; i++) {
  14698. var id = ids[i];
  14699. var oldEdge = edges[id];
  14700. if (oldEdge) {
  14701. oldEdge.disconnect();
  14702. }
  14703. var data = edgesData.get(id, {"showInternalIds" : true});
  14704. edges[id] = new Edge(data, this, this.constants);
  14705. }
  14706. this.moving = true;
  14707. this._updateValueRange(edges);
  14708. this._createBezierNodes();
  14709. this._updateCalculationNodes();
  14710. };
  14711. /**
  14712. * Update existing edges, or create them when not yet existing
  14713. * @param {Number[] | String[]} ids
  14714. * @private
  14715. */
  14716. Graph.prototype._updateEdges = function (ids) {
  14717. var edges = this.edges,
  14718. edgesData = this.edgesData;
  14719. for (var i = 0, len = ids.length; i < len; i++) {
  14720. var id = ids[i];
  14721. var data = edgesData.get(id);
  14722. var edge = edges[id];
  14723. if (edge) {
  14724. // update edge
  14725. edge.disconnect();
  14726. edge.setProperties(data, this.constants);
  14727. edge.connect();
  14728. }
  14729. else {
  14730. // create edge
  14731. edge = new Edge(data, this, this.constants);
  14732. this.edges[id] = edge;
  14733. }
  14734. }
  14735. this._createBezierNodes();
  14736. this.moving = true;
  14737. this._updateValueRange(edges);
  14738. };
  14739. /**
  14740. * Remove existing edges. Non existing ids will be ignored
  14741. * @param {Number[] | String[]} ids
  14742. * @private
  14743. */
  14744. Graph.prototype._removeEdges = function (ids) {
  14745. var edges = this.edges;
  14746. for (var i = 0, len = ids.length; i < len; i++) {
  14747. var id = ids[i];
  14748. var edge = edges[id];
  14749. if (edge) {
  14750. if (edge.via != null) {
  14751. delete this.sectors['support']['nodes'][edge.via.id];
  14752. }
  14753. edge.disconnect();
  14754. delete edges[id];
  14755. }
  14756. }
  14757. this.moving = true;
  14758. this._updateValueRange(edges);
  14759. this._updateCalculationNodes();
  14760. };
  14761. /**
  14762. * Reconnect all edges
  14763. * @private
  14764. */
  14765. Graph.prototype._reconnectEdges = function() {
  14766. var id,
  14767. nodes = this.nodes,
  14768. edges = this.edges;
  14769. for (id in nodes) {
  14770. if (nodes.hasOwnProperty(id)) {
  14771. nodes[id].edges = [];
  14772. }
  14773. }
  14774. for (id in edges) {
  14775. if (edges.hasOwnProperty(id)) {
  14776. var edge = edges[id];
  14777. edge.from = null;
  14778. edge.to = null;
  14779. edge.connect();
  14780. }
  14781. }
  14782. };
  14783. /**
  14784. * Update the values of all object in the given array according to the current
  14785. * value range of the objects in the array.
  14786. * @param {Object} obj An object containing a set of Edges or Nodes
  14787. * The objects must have a method getValue() and
  14788. * setValueRange(min, max).
  14789. * @private
  14790. */
  14791. Graph.prototype._updateValueRange = function(obj) {
  14792. var id;
  14793. // determine the range of the objects
  14794. var valueMin = undefined;
  14795. var valueMax = undefined;
  14796. for (id in obj) {
  14797. if (obj.hasOwnProperty(id)) {
  14798. var value = obj[id].getValue();
  14799. if (value !== undefined) {
  14800. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  14801. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  14802. }
  14803. }
  14804. }
  14805. // adjust the range of all objects
  14806. if (valueMin !== undefined && valueMax !== undefined) {
  14807. for (id in obj) {
  14808. if (obj.hasOwnProperty(id)) {
  14809. obj[id].setValueRange(valueMin, valueMax);
  14810. }
  14811. }
  14812. }
  14813. };
  14814. /**
  14815. * Redraw the graph with the current data
  14816. * chart will be resized too.
  14817. */
  14818. Graph.prototype.redraw = function() {
  14819. this.setSize(this.width, this.height);
  14820. this._redraw();
  14821. };
  14822. /**
  14823. * Redraw the graph with the current data
  14824. * @private
  14825. */
  14826. Graph.prototype._redraw = function() {
  14827. var ctx = this.frame.canvas.getContext('2d');
  14828. // clear the canvas
  14829. var w = this.frame.canvas.width;
  14830. var h = this.frame.canvas.height;
  14831. ctx.clearRect(0, 0, w, h);
  14832. // set scaling and translation
  14833. ctx.save();
  14834. ctx.translate(this.translation.x, this.translation.y);
  14835. ctx.scale(this.scale, this.scale);
  14836. this.canvasTopLeft = {
  14837. "x": this._canvasToX(0),
  14838. "y": this._canvasToY(0)
  14839. };
  14840. this.canvasBottomRight = {
  14841. "x": this._canvasToX(this.frame.canvas.clientWidth),
  14842. "y": this._canvasToY(this.frame.canvas.clientHeight)
  14843. };
  14844. this._doInAllSectors("_drawAllSectorNodes",ctx);
  14845. this._doInAllSectors("_drawEdges",ctx);
  14846. this._doInAllSectors("_drawNodes",ctx,false);
  14847. // this._doInSupportSector("_drawNodes",ctx,true);
  14848. // this._drawTree(ctx,"#F00F0F");
  14849. // restore original scaling and translation
  14850. ctx.restore();
  14851. };
  14852. /**
  14853. * Set the translation of the graph
  14854. * @param {Number} offsetX Horizontal offset
  14855. * @param {Number} offsetY Vertical offset
  14856. * @private
  14857. */
  14858. Graph.prototype._setTranslation = function(offsetX, offsetY) {
  14859. if (this.translation === undefined) {
  14860. this.translation = {
  14861. x: 0,
  14862. y: 0
  14863. };
  14864. }
  14865. if (offsetX !== undefined) {
  14866. this.translation.x = offsetX;
  14867. }
  14868. if (offsetY !== undefined) {
  14869. this.translation.y = offsetY;
  14870. }
  14871. };
  14872. /**
  14873. * Get the translation of the graph
  14874. * @return {Object} translation An object with parameters x and y, both a number
  14875. * @private
  14876. */
  14877. Graph.prototype._getTranslation = function() {
  14878. return {
  14879. x: this.translation.x,
  14880. y: this.translation.y
  14881. };
  14882. };
  14883. /**
  14884. * Scale the graph
  14885. * @param {Number} scale Scaling factor 1.0 is unscaled
  14886. * @private
  14887. */
  14888. Graph.prototype._setScale = function(scale) {
  14889. this.scale = scale;
  14890. };
  14891. /**
  14892. * Get the current scale of the graph
  14893. * @return {Number} scale Scaling factor 1.0 is unscaled
  14894. * @private
  14895. */
  14896. Graph.prototype._getScale = function() {
  14897. return this.scale;
  14898. };
  14899. /**
  14900. * Convert a horizontal point on the HTML canvas to the x-value of the model
  14901. * @param {number} x
  14902. * @returns {number}
  14903. * @private
  14904. */
  14905. Graph.prototype._canvasToX = function(x) {
  14906. return (x - this.translation.x) / this.scale;
  14907. };
  14908. /**
  14909. * Convert an x-value in the model to a horizontal point on the HTML canvas
  14910. * @param {number} x
  14911. * @returns {number}
  14912. * @private
  14913. */
  14914. Graph.prototype._xToCanvas = function(x) {
  14915. return x * this.scale + this.translation.x;
  14916. };
  14917. /**
  14918. * Convert a vertical point on the HTML canvas to the y-value of the model
  14919. * @param {number} y
  14920. * @returns {number}
  14921. * @private
  14922. */
  14923. Graph.prototype._canvasToY = function(y) {
  14924. return (y - this.translation.y) / this.scale;
  14925. };
  14926. /**
  14927. * Convert an y-value in the model to a vertical point on the HTML canvas
  14928. * @param {number} y
  14929. * @returns {number}
  14930. * @private
  14931. */
  14932. Graph.prototype._yToCanvas = function(y) {
  14933. return y * this.scale + this.translation.y ;
  14934. };
  14935. /**
  14936. * Redraw all nodes
  14937. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  14938. * @param {CanvasRenderingContext2D} ctx
  14939. * @param {Boolean} [alwaysShow]
  14940. * @private
  14941. */
  14942. Graph.prototype._drawNodes = function(ctx,alwaysShow) {
  14943. if (alwaysShow === undefined) {
  14944. alwaysShow = false;
  14945. }
  14946. // first draw the unselected nodes
  14947. var nodes = this.nodes;
  14948. var selected = [];
  14949. for (var id in nodes) {
  14950. if (nodes.hasOwnProperty(id)) {
  14951. nodes[id].setScaleAndPos(this.scale,this.canvasTopLeft,this.canvasBottomRight);
  14952. if (nodes[id].isSelected()) {
  14953. selected.push(id);
  14954. }
  14955. else {
  14956. if (nodes[id].inArea() || alwaysShow) {
  14957. nodes[id].draw(ctx);
  14958. }
  14959. }
  14960. }
  14961. }
  14962. // draw the selected nodes on top
  14963. for (var s = 0, sMax = selected.length; s < sMax; s++) {
  14964. if (nodes[selected[s]].inArea() || alwaysShow) {
  14965. nodes[selected[s]].draw(ctx);
  14966. }
  14967. }
  14968. };
  14969. /**
  14970. * Redraw all edges
  14971. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  14972. * @param {CanvasRenderingContext2D} ctx
  14973. * @private
  14974. */
  14975. Graph.prototype._drawEdges = function(ctx) {
  14976. var edges = this.edges;
  14977. for (var id in edges) {
  14978. if (edges.hasOwnProperty(id)) {
  14979. var edge = edges[id];
  14980. edge.setScale(this.scale);
  14981. if (edge.connected) {
  14982. edges[id].draw(ctx);
  14983. }
  14984. }
  14985. }
  14986. };
  14987. /**
  14988. * Find a stable position for all nodes
  14989. * @private
  14990. */
  14991. Graph.prototype._doStabilize = function() {
  14992. // find stable position
  14993. var count = 0;
  14994. while (this.moving && count < this.constants.maxIterations) {
  14995. this._physicsTick();
  14996. count++;
  14997. }
  14998. this.zoomToFit(false,true);
  14999. };
  15000. /**
  15001. * Check if any of the nodes is still moving
  15002. * @param {number} vmin the minimum velocity considered as 'moving'
  15003. * @return {boolean} true if moving, false if non of the nodes is moving
  15004. * @private
  15005. */
  15006. Graph.prototype._isMoving = function(vmin) {
  15007. var nodes = this.nodes;
  15008. for (var id in nodes) {
  15009. if (nodes.hasOwnProperty(id) && nodes[id].isMoving(vmin)) {
  15010. return true;
  15011. }
  15012. }
  15013. return false;
  15014. };
  15015. /**
  15016. * /**
  15017. * Perform one discrete step for all nodes
  15018. *
  15019. * @private
  15020. */
  15021. Graph.prototype._discreteStepNodes = function() {
  15022. var interval = 0.65;
  15023. var nodes = this.nodes;
  15024. var nodeId;
  15025. if (this.constants.maxVelocity > 0) {
  15026. for (nodeId in nodes) {
  15027. if (nodes.hasOwnProperty(nodeId)) {
  15028. nodes[nodeId].discreteStepLimited(interval, this.constants.maxVelocity);
  15029. }
  15030. }
  15031. }
  15032. else {
  15033. for (nodeId in nodes) {
  15034. if (nodes.hasOwnProperty(nodeId)) {
  15035. nodes[nodeId].discreteStep(interval);
  15036. }
  15037. }
  15038. }
  15039. var vminCorrected = this.constants.minVelocity / Math.max(this.scale,0.05);
  15040. if (vminCorrected > 0.5*this.constants.maxVelocity) {
  15041. this.moving = true;
  15042. }
  15043. else {
  15044. this.moving = this._isMoving(vminCorrected);
  15045. }
  15046. };
  15047. Graph.prototype._physicsTick = function() {
  15048. if (!this.freezeSimulation) {
  15049. if (this.moving) {
  15050. this._doInAllActiveSectors("_initializeForceCalculation");
  15051. if (this.constants.smoothCurves) {
  15052. this._doInSupportSector("_discreteStepNodes");
  15053. }
  15054. this._doInAllActiveSectors("_discreteStepNodes");
  15055. this._findCenter(this._getRange())
  15056. }
  15057. }
  15058. };
  15059. /**
  15060. * This function runs one step of the animation. It calls an x amount of physics ticks and one render tick.
  15061. * It reschedules itself at the beginning of the function
  15062. *
  15063. * @private
  15064. */
  15065. Graph.prototype._animationStep = function() {
  15066. // reset the timer so a new scheduled animation step can be set
  15067. this.timer = undefined;
  15068. // handle the keyboad movement
  15069. this._handleNavigation();
  15070. // this schedules a new animation step
  15071. this.start();
  15072. // start the physics simulation
  15073. var calculationTime = Date.now();
  15074. var maxSteps = 1;
  15075. this._physicsTick();
  15076. var timeRequired = Date.now() - calculationTime;
  15077. while (timeRequired < (this.renderTimestep - this.renderTime) && maxSteps < this.maxRenderSteps) {
  15078. this._physicsTick();
  15079. timeRequired = Date.now() - calculationTime;
  15080. maxSteps++;
  15081. }
  15082. // start the rendering process
  15083. var renderTime = Date.now();
  15084. this._redraw();
  15085. this.renderTime = Date.now() - renderTime;
  15086. };
  15087. /**
  15088. * Schedule a animation step with the refreshrate interval.
  15089. *
  15090. * @poram {Boolean} runCalculationStep
  15091. */
  15092. Graph.prototype.start = function() {
  15093. if (this.moving || this.xIncrement != 0 || this.yIncrement != 0 || this.zoomIncrement != 0) {
  15094. if (!this.timer) {
  15095. this.timer = window.setTimeout(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  15096. }
  15097. }
  15098. else {
  15099. this._redraw();
  15100. }
  15101. };
  15102. /**
  15103. * Move the graph according to the keyboard presses.
  15104. *
  15105. * @private
  15106. */
  15107. Graph.prototype._handleNavigation = function() {
  15108. if (this.xIncrement != 0 || this.yIncrement != 0) {
  15109. var translation = this._getTranslation();
  15110. this._setTranslation(translation.x+this.xIncrement, translation.y+this.yIncrement);
  15111. }
  15112. if (this.zoomIncrement != 0) {
  15113. var center = {
  15114. x: this.frame.canvas.clientWidth / 2,
  15115. y: this.frame.canvas.clientHeight / 2
  15116. };
  15117. this._zoom(this.scale*(1 + this.zoomIncrement), center);
  15118. }
  15119. };
  15120. /**
  15121. * Freeze the _animationStep
  15122. */
  15123. Graph.prototype.toggleFreeze = function() {
  15124. if (this.freezeSimulation == false) {
  15125. this.freezeSimulation = true;
  15126. }
  15127. else {
  15128. this.freezeSimulation = false;
  15129. this.start();
  15130. }
  15131. };
  15132. Graph.prototype._configureSmoothCurves = function(disableStart) {
  15133. if (disableStart === undefined) {
  15134. disableStart = true;
  15135. }
  15136. if (this.constants.smoothCurves == true) {
  15137. this._createBezierNodes();
  15138. }
  15139. else {
  15140. // delete the support nodes
  15141. this.sectors['support']['nodes'] = {};
  15142. for (var edgeId in this.edges) {
  15143. if (this.edges.hasOwnProperty(edgeId)) {
  15144. this.edges[edgeId].smooth = false;
  15145. this.edges[edgeId].via = null;
  15146. }
  15147. }
  15148. }
  15149. this._updateCalculationNodes();
  15150. if (!disableStart) {
  15151. this.moving = true;
  15152. this.start();
  15153. }
  15154. };
  15155. Graph.prototype._createBezierNodes = function() {
  15156. if (this.constants.smoothCurves == true) {
  15157. for (var edgeId in this.edges) {
  15158. if (this.edges.hasOwnProperty(edgeId)) {
  15159. var edge = this.edges[edgeId];
  15160. if (edge.via == null) {
  15161. edge.smooth = true;
  15162. var nodeId = "edgeId:".concat(edge.id);
  15163. this.sectors['support']['nodes'][nodeId] = new Node(
  15164. {id:nodeId,
  15165. mass:1,
  15166. shape:'circle',
  15167. internalMultiplier:1
  15168. },{},{},this.constants);
  15169. edge.via = this.sectors['support']['nodes'][nodeId];
  15170. edge.via.parentEdgeId = edge.id;
  15171. edge.positionBezierNode();
  15172. }
  15173. }
  15174. }
  15175. }
  15176. };
  15177. Graph.prototype._initializeMixinLoaders = function () {
  15178. for (var mixinFunction in graphMixinLoaders) {
  15179. if (graphMixinLoaders.hasOwnProperty(mixinFunction)) {
  15180. Graph.prototype[mixinFunction] = graphMixinLoaders[mixinFunction];
  15181. }
  15182. }
  15183. };
  15184. /**
  15185. * vis.js module exports
  15186. */
  15187. var vis = {
  15188. util: util,
  15189. Controller: Controller,
  15190. DataSet: DataSet,
  15191. DataView: DataView,
  15192. Range: Range,
  15193. Stack: Stack,
  15194. TimeStep: TimeStep,
  15195. components: {
  15196. items: {
  15197. Item: Item,
  15198. ItemBox: ItemBox,
  15199. ItemPoint: ItemPoint,
  15200. ItemRange: ItemRange
  15201. },
  15202. Component: Component,
  15203. Panel: Panel,
  15204. RootPanel: RootPanel,
  15205. ItemSet: ItemSet,
  15206. TimeAxis: TimeAxis
  15207. },
  15208. graph: {
  15209. Node: Node,
  15210. Edge: Edge,
  15211. Popup: Popup,
  15212. Groups: Groups,
  15213. Images: Images
  15214. },
  15215. Timeline: Timeline,
  15216. Graph: Graph
  15217. };
  15218. /**
  15219. * CommonJS module exports
  15220. */
  15221. if (typeof exports !== 'undefined') {
  15222. exports = vis;
  15223. }
  15224. if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  15225. module.exports = vis;
  15226. }
  15227. /**
  15228. * AMD module exports
  15229. */
  15230. if (typeof(define) === 'function') {
  15231. define(function () {
  15232. return vis;
  15233. });
  15234. }
  15235. /**
  15236. * Window exports
  15237. */
  15238. if (typeof window !== 'undefined') {
  15239. // attach the module to the window, load as a regular javascript file
  15240. window['vis'] = vis;
  15241. }
  15242. },{"emitter-component":2,"hammerjs":3,"moment":4,"mousetrap":5}],2:[function(require,module,exports){
  15243. /**
  15244. * Expose `Emitter`.
  15245. */
  15246. module.exports = Emitter;
  15247. /**
  15248. * Initialize a new `Emitter`.
  15249. *
  15250. * @api public
  15251. */
  15252. function Emitter(obj) {
  15253. if (obj) return mixin(obj);
  15254. };
  15255. /**
  15256. * Mixin the emitter properties.
  15257. *
  15258. * @param {Object} obj
  15259. * @return {Object}
  15260. * @api private
  15261. */
  15262. function mixin(obj) {
  15263. for (var key in Emitter.prototype) {
  15264. obj[key] = Emitter.prototype[key];
  15265. }
  15266. return obj;
  15267. }
  15268. /**
  15269. * Listen on the given `event` with `fn`.
  15270. *
  15271. * @param {String} event
  15272. * @param {Function} fn
  15273. * @return {Emitter}
  15274. * @api public
  15275. */
  15276. Emitter.prototype.on =
  15277. Emitter.prototype.addEventListener = function(event, fn){
  15278. this._callbacks = this._callbacks || {};
  15279. (this._callbacks[event] = this._callbacks[event] || [])
  15280. .push(fn);
  15281. return this;
  15282. };
  15283. /**
  15284. * Adds an `event` listener that will be invoked a single
  15285. * time then automatically removed.
  15286. *
  15287. * @param {String} event
  15288. * @param {Function} fn
  15289. * @return {Emitter}
  15290. * @api public
  15291. */
  15292. Emitter.prototype.once = function(event, fn){
  15293. var self = this;
  15294. this._callbacks = this._callbacks || {};
  15295. function on() {
  15296. self.off(event, on);
  15297. fn.apply(this, arguments);
  15298. }
  15299. on.fn = fn;
  15300. this.on(event, on);
  15301. return this;
  15302. };
  15303. /**
  15304. * Remove the given callback for `event` or all
  15305. * registered callbacks.
  15306. *
  15307. * @param {String} event
  15308. * @param {Function} fn
  15309. * @return {Emitter}
  15310. * @api public
  15311. */
  15312. Emitter.prototype.off =
  15313. Emitter.prototype.removeListener =
  15314. Emitter.prototype.removeAllListeners =
  15315. Emitter.prototype.removeEventListener = function(event, fn){
  15316. this._callbacks = this._callbacks || {};
  15317. // all
  15318. if (0 == arguments.length) {
  15319. this._callbacks = {};
  15320. return this;
  15321. }
  15322. // specific event
  15323. var callbacks = this._callbacks[event];
  15324. if (!callbacks) return this;
  15325. // remove all handlers
  15326. if (1 == arguments.length) {
  15327. delete this._callbacks[event];
  15328. return this;
  15329. }
  15330. // remove specific handler
  15331. var cb;
  15332. for (var i = 0; i < callbacks.length; i++) {
  15333. cb = callbacks[i];
  15334. if (cb === fn || cb.fn === fn) {
  15335. callbacks.splice(i, 1);
  15336. break;
  15337. }
  15338. }
  15339. return this;
  15340. };
  15341. /**
  15342. * Emit `event` with the given args.
  15343. *
  15344. * @param {String} event
  15345. * @param {Mixed} ...
  15346. * @return {Emitter}
  15347. */
  15348. Emitter.prototype.emit = function(event){
  15349. this._callbacks = this._callbacks || {};
  15350. var args = [].slice.call(arguments, 1)
  15351. , callbacks = this._callbacks[event];
  15352. if (callbacks) {
  15353. callbacks = callbacks.slice(0);
  15354. for (var i = 0, len = callbacks.length; i < len; ++i) {
  15355. callbacks[i].apply(this, args);
  15356. }
  15357. }
  15358. return this;
  15359. };
  15360. /**
  15361. * Return array of callbacks for `event`.
  15362. *
  15363. * @param {String} event
  15364. * @return {Array}
  15365. * @api public
  15366. */
  15367. Emitter.prototype.listeners = function(event){
  15368. this._callbacks = this._callbacks || {};
  15369. return this._callbacks[event] || [];
  15370. };
  15371. /**
  15372. * Check if this emitter has `event` handlers.
  15373. *
  15374. * @param {String} event
  15375. * @return {Boolean}
  15376. * @api public
  15377. */
  15378. Emitter.prototype.hasListeners = function(event){
  15379. return !! this.listeners(event).length;
  15380. };
  15381. },{}],3:[function(require,module,exports){
  15382. /*! Hammer.JS - v1.0.5 - 2013-04-07
  15383. * http://eightmedia.github.com/hammer.js
  15384. *
  15385. * Copyright (c) 2013 Jorik Tangelder <j.tangelder@gmail.com>;
  15386. * Licensed under the MIT license */
  15387. (function(window, undefined) {
  15388. 'use strict';
  15389. /**
  15390. * Hammer
  15391. * use this to create instances
  15392. * @param {HTMLElement} element
  15393. * @param {Object} options
  15394. * @returns {Hammer.Instance}
  15395. * @constructor
  15396. */
  15397. var Hammer = function(element, options) {
  15398. return new Hammer.Instance(element, options || {});
  15399. };
  15400. // default settings
  15401. Hammer.defaults = {
  15402. // add styles and attributes to the element to prevent the browser from doing
  15403. // its native behavior. this doesnt prevent the scrolling, but cancels
  15404. // the contextmenu, tap highlighting etc
  15405. // set to false to disable this
  15406. stop_browser_behavior: {
  15407. // this also triggers onselectstart=false for IE
  15408. userSelect: 'none',
  15409. // this makes the element blocking in IE10 >, you could experiment with the value
  15410. // see for more options this issue; https://github.com/EightMedia/hammer.js/issues/241
  15411. touchAction: 'none',
  15412. touchCallout: 'none',
  15413. contentZooming: 'none',
  15414. userDrag: 'none',
  15415. tapHighlightColor: 'rgba(0,0,0,0)'
  15416. }
  15417. // more settings are defined per gesture at gestures.js
  15418. };
  15419. // detect touchevents
  15420. Hammer.HAS_POINTEREVENTS = navigator.pointerEnabled || navigator.msPointerEnabled;
  15421. Hammer.HAS_TOUCHEVENTS = ('ontouchstart' in window);
  15422. // dont use mouseevents on mobile devices
  15423. Hammer.MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;
  15424. Hammer.NO_MOUSEEVENTS = Hammer.HAS_TOUCHEVENTS && navigator.userAgent.match(Hammer.MOBILE_REGEX);
  15425. // eventtypes per touchevent (start, move, end)
  15426. // are filled by Hammer.event.determineEventTypes on setup
  15427. Hammer.EVENT_TYPES = {};
  15428. // direction defines
  15429. Hammer.DIRECTION_DOWN = 'down';
  15430. Hammer.DIRECTION_LEFT = 'left';
  15431. Hammer.DIRECTION_UP = 'up';
  15432. Hammer.DIRECTION_RIGHT = 'right';
  15433. // pointer type
  15434. Hammer.POINTER_MOUSE = 'mouse';
  15435. Hammer.POINTER_TOUCH = 'touch';
  15436. Hammer.POINTER_PEN = 'pen';
  15437. // touch event defines
  15438. Hammer.EVENT_START = 'start';
  15439. Hammer.EVENT_MOVE = 'move';
  15440. Hammer.EVENT_END = 'end';
  15441. // hammer document where the base events are added at
  15442. Hammer.DOCUMENT = document;
  15443. // plugins namespace
  15444. Hammer.plugins = {};
  15445. // if the window events are set...
  15446. Hammer.READY = false;
  15447. /**
  15448. * setup events to detect gestures on the document
  15449. */
  15450. function setup() {
  15451. if(Hammer.READY) {
  15452. return;
  15453. }
  15454. // find what eventtypes we add listeners to
  15455. Hammer.event.determineEventTypes();
  15456. // Register all gestures inside Hammer.gestures
  15457. for(var name in Hammer.gestures) {
  15458. if(Hammer.gestures.hasOwnProperty(name)) {
  15459. Hammer.detection.register(Hammer.gestures[name]);
  15460. }
  15461. }
  15462. // Add touch events on the document
  15463. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_MOVE, Hammer.detection.detect);
  15464. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_END, Hammer.detection.detect);
  15465. // Hammer is ready...!
  15466. Hammer.READY = true;
  15467. }
  15468. /**
  15469. * create new hammer instance
  15470. * all methods should return the instance itself, so it is chainable.
  15471. * @param {HTMLElement} element
  15472. * @param {Object} [options={}]
  15473. * @returns {Hammer.Instance}
  15474. * @constructor
  15475. */
  15476. Hammer.Instance = function(element, options) {
  15477. var self = this;
  15478. // setup HammerJS window events and register all gestures
  15479. // this also sets up the default options
  15480. setup();
  15481. this.element = element;
  15482. // start/stop detection option
  15483. this.enabled = true;
  15484. // merge options
  15485. this.options = Hammer.utils.extend(
  15486. Hammer.utils.extend({}, Hammer.defaults),
  15487. options || {});
  15488. // add some css to the element to prevent the browser from doing its native behavoir
  15489. if(this.options.stop_browser_behavior) {
  15490. Hammer.utils.stopDefaultBrowserBehavior(this.element, this.options.stop_browser_behavior);
  15491. }
  15492. // start detection on touchstart
  15493. Hammer.event.onTouch(element, Hammer.EVENT_START, function(ev) {
  15494. if(self.enabled) {
  15495. Hammer.detection.startDetect(self, ev);
  15496. }
  15497. });
  15498. // return instance
  15499. return this;
  15500. };
  15501. Hammer.Instance.prototype = {
  15502. /**
  15503. * bind events to the instance
  15504. * @param {String} gesture
  15505. * @param {Function} handler
  15506. * @returns {Hammer.Instance}
  15507. */
  15508. on: function onEvent(gesture, handler){
  15509. var gestures = gesture.split(' ');
  15510. for(var t=0; t<gestures.length; t++) {
  15511. this.element.addEventListener(gestures[t], handler, false);
  15512. }
  15513. return this;
  15514. },
  15515. /**
  15516. * unbind events to the instance
  15517. * @param {String} gesture
  15518. * @param {Function} handler
  15519. * @returns {Hammer.Instance}
  15520. */
  15521. off: function offEvent(gesture, handler){
  15522. var gestures = gesture.split(' ');
  15523. for(var t=0; t<gestures.length; t++) {
  15524. this.element.removeEventListener(gestures[t], handler, false);
  15525. }
  15526. return this;
  15527. },
  15528. /**
  15529. * trigger gesture event
  15530. * @param {String} gesture
  15531. * @param {Object} eventData
  15532. * @returns {Hammer.Instance}
  15533. */
  15534. trigger: function triggerEvent(gesture, eventData){
  15535. // create DOM event
  15536. var event = Hammer.DOCUMENT.createEvent('Event');
  15537. event.initEvent(gesture, true, true);
  15538. event.gesture = eventData;
  15539. // trigger on the target if it is in the instance element,
  15540. // this is for event delegation tricks
  15541. var element = this.element;
  15542. if(Hammer.utils.hasParent(eventData.target, element)) {
  15543. element = eventData.target;
  15544. }
  15545. element.dispatchEvent(event);
  15546. return this;
  15547. },
  15548. /**
  15549. * enable of disable hammer.js detection
  15550. * @param {Boolean} state
  15551. * @returns {Hammer.Instance}
  15552. */
  15553. enable: function enable(state) {
  15554. this.enabled = state;
  15555. return this;
  15556. }
  15557. };
  15558. /**
  15559. * this holds the last move event,
  15560. * used to fix empty touchend issue
  15561. * see the onTouch event for an explanation
  15562. * @type {Object}
  15563. */
  15564. var last_move_event = null;
  15565. /**
  15566. * when the mouse is hold down, this is true
  15567. * @type {Boolean}
  15568. */
  15569. var enable_detect = false;
  15570. /**
  15571. * when touch events have been fired, this is true
  15572. * @type {Boolean}
  15573. */
  15574. var touch_triggered = false;
  15575. Hammer.event = {
  15576. /**
  15577. * simple addEventListener
  15578. * @param {HTMLElement} element
  15579. * @param {String} type
  15580. * @param {Function} handler
  15581. */
  15582. bindDom: function(element, type, handler) {
  15583. var types = type.split(' ');
  15584. for(var t=0; t<types.length; t++) {
  15585. element.addEventListener(types[t], handler, false);
  15586. }
  15587. },
  15588. /**
  15589. * touch events with mouse fallback
  15590. * @param {HTMLElement} element
  15591. * @param {String} eventType like Hammer.EVENT_MOVE
  15592. * @param {Function} handler
  15593. */
  15594. onTouch: function onTouch(element, eventType, handler) {
  15595. var self = this;
  15596. this.bindDom(element, Hammer.EVENT_TYPES[eventType], function bindDomOnTouch(ev) {
  15597. var sourceEventType = ev.type.toLowerCase();
  15598. // onmouseup, but when touchend has been fired we do nothing.
  15599. // this is for touchdevices which also fire a mouseup on touchend
  15600. if(sourceEventType.match(/mouse/) && touch_triggered) {
  15601. return;
  15602. }
  15603. // mousebutton must be down or a touch event
  15604. else if( sourceEventType.match(/touch/) || // touch events are always on screen
  15605. sourceEventType.match(/pointerdown/) || // pointerevents touch
  15606. (sourceEventType.match(/mouse/) && ev.which === 1) // mouse is pressed
  15607. ){
  15608. enable_detect = true;
  15609. }
  15610. // we are in a touch event, set the touch triggered bool to true,
  15611. // this for the conflicts that may occur on ios and android
  15612. if(sourceEventType.match(/touch|pointer/)) {
  15613. touch_triggered = true;
  15614. }
  15615. // count the total touches on the screen
  15616. var count_touches = 0;
  15617. // when touch has been triggered in this detection session
  15618. // and we are now handling a mouse event, we stop that to prevent conflicts
  15619. if(enable_detect) {
  15620. // update pointerevent
  15621. if(Hammer.HAS_POINTEREVENTS && eventType != Hammer.EVENT_END) {
  15622. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  15623. }
  15624. // touch
  15625. else if(sourceEventType.match(/touch/)) {
  15626. count_touches = ev.touches.length;
  15627. }
  15628. // mouse
  15629. else if(!touch_triggered) {
  15630. count_touches = sourceEventType.match(/up/) ? 0 : 1;
  15631. }
  15632. // if we are in a end event, but when we remove one touch and
  15633. // we still have enough, set eventType to move
  15634. if(count_touches > 0 && eventType == Hammer.EVENT_END) {
  15635. eventType = Hammer.EVENT_MOVE;
  15636. }
  15637. // no touches, force the end event
  15638. else if(!count_touches) {
  15639. eventType = Hammer.EVENT_END;
  15640. }
  15641. // because touchend has no touches, and we often want to use these in our gestures,
  15642. // we send the last move event as our eventData in touchend
  15643. if(!count_touches && last_move_event !== null) {
  15644. ev = last_move_event;
  15645. }
  15646. // store the last move event
  15647. else {
  15648. last_move_event = ev;
  15649. }
  15650. // trigger the handler
  15651. handler.call(Hammer.detection, self.collectEventData(element, eventType, ev));
  15652. // remove pointerevent from list
  15653. if(Hammer.HAS_POINTEREVENTS && eventType == Hammer.EVENT_END) {
  15654. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  15655. }
  15656. }
  15657. //debug(sourceEventType +" "+ eventType);
  15658. // on the end we reset everything
  15659. if(!count_touches) {
  15660. last_move_event = null;
  15661. enable_detect = false;
  15662. touch_triggered = false;
  15663. Hammer.PointerEvent.reset();
  15664. }
  15665. });
  15666. },
  15667. /**
  15668. * we have different events for each device/browser
  15669. * determine what we need and set them in the Hammer.EVENT_TYPES constant
  15670. */
  15671. determineEventTypes: function determineEventTypes() {
  15672. // determine the eventtype we want to set
  15673. var types;
  15674. // pointerEvents magic
  15675. if(Hammer.HAS_POINTEREVENTS) {
  15676. types = Hammer.PointerEvent.getEvents();
  15677. }
  15678. // on Android, iOS, blackberry, windows mobile we dont want any mouseevents
  15679. else if(Hammer.NO_MOUSEEVENTS) {
  15680. types = [
  15681. 'touchstart',
  15682. 'touchmove',
  15683. 'touchend touchcancel'];
  15684. }
  15685. // for non pointer events browsers and mixed browsers,
  15686. // like chrome on windows8 touch laptop
  15687. else {
  15688. types = [
  15689. 'touchstart mousedown',
  15690. 'touchmove mousemove',
  15691. 'touchend touchcancel mouseup'];
  15692. }
  15693. Hammer.EVENT_TYPES[Hammer.EVENT_START] = types[0];
  15694. Hammer.EVENT_TYPES[Hammer.EVENT_MOVE] = types[1];
  15695. Hammer.EVENT_TYPES[Hammer.EVENT_END] = types[2];
  15696. },
  15697. /**
  15698. * create touchlist depending on the event
  15699. * @param {Object} ev
  15700. * @param {String} eventType used by the fakemultitouch plugin
  15701. */
  15702. getTouchList: function getTouchList(ev/*, eventType*/) {
  15703. // get the fake pointerEvent touchlist
  15704. if(Hammer.HAS_POINTEREVENTS) {
  15705. return Hammer.PointerEvent.getTouchList();
  15706. }
  15707. // get the touchlist
  15708. else if(ev.touches) {
  15709. return ev.touches;
  15710. }
  15711. // make fake touchlist from mouse position
  15712. else {
  15713. return [{
  15714. identifier: 1,
  15715. pageX: ev.pageX,
  15716. pageY: ev.pageY,
  15717. target: ev.target
  15718. }];
  15719. }
  15720. },
  15721. /**
  15722. * collect event data for Hammer js
  15723. * @param {HTMLElement} element
  15724. * @param {String} eventType like Hammer.EVENT_MOVE
  15725. * @param {Object} eventData
  15726. */
  15727. collectEventData: function collectEventData(element, eventType, ev) {
  15728. var touches = this.getTouchList(ev, eventType);
  15729. // find out pointerType
  15730. var pointerType = Hammer.POINTER_TOUCH;
  15731. if(ev.type.match(/mouse/) || Hammer.PointerEvent.matchType(Hammer.POINTER_MOUSE, ev)) {
  15732. pointerType = Hammer.POINTER_MOUSE;
  15733. }
  15734. return {
  15735. center : Hammer.utils.getCenter(touches),
  15736. timeStamp : new Date().getTime(),
  15737. target : ev.target,
  15738. touches : touches,
  15739. eventType : eventType,
  15740. pointerType : pointerType,
  15741. srcEvent : ev,
  15742. /**
  15743. * prevent the browser default actions
  15744. * mostly used to disable scrolling of the browser
  15745. */
  15746. preventDefault: function() {
  15747. if(this.srcEvent.preventManipulation) {
  15748. this.srcEvent.preventManipulation();
  15749. }
  15750. if(this.srcEvent.preventDefault) {
  15751. this.srcEvent.preventDefault();
  15752. }
  15753. },
  15754. /**
  15755. * stop bubbling the event up to its parents
  15756. */
  15757. stopPropagation: function() {
  15758. this.srcEvent.stopPropagation();
  15759. },
  15760. /**
  15761. * immediately stop gesture detection
  15762. * might be useful after a swipe was detected
  15763. * @return {*}
  15764. */
  15765. stopDetect: function() {
  15766. return Hammer.detection.stopDetect();
  15767. }
  15768. };
  15769. }
  15770. };
  15771. Hammer.PointerEvent = {
  15772. /**
  15773. * holds all pointers
  15774. * @type {Object}
  15775. */
  15776. pointers: {},
  15777. /**
  15778. * get a list of pointers
  15779. * @returns {Array} touchlist
  15780. */
  15781. getTouchList: function() {
  15782. var self = this;
  15783. var touchlist = [];
  15784. // we can use forEach since pointerEvents only is in IE10
  15785. Object.keys(self.pointers).sort().forEach(function(id) {
  15786. touchlist.push(self.pointers[id]);
  15787. });
  15788. return touchlist;
  15789. },
  15790. /**
  15791. * update the position of a pointer
  15792. * @param {String} type Hammer.EVENT_END
  15793. * @param {Object} pointerEvent
  15794. */
  15795. updatePointer: function(type, pointerEvent) {
  15796. if(type == Hammer.EVENT_END) {
  15797. this.pointers = {};
  15798. }
  15799. else {
  15800. pointerEvent.identifier = pointerEvent.pointerId;
  15801. this.pointers[pointerEvent.pointerId] = pointerEvent;
  15802. }
  15803. return Object.keys(this.pointers).length;
  15804. },
  15805. /**
  15806. * check if ev matches pointertype
  15807. * @param {String} pointerType Hammer.POINTER_MOUSE
  15808. * @param {PointerEvent} ev
  15809. */
  15810. matchType: function(pointerType, ev) {
  15811. if(!ev.pointerType) {
  15812. return false;
  15813. }
  15814. var types = {};
  15815. types[Hammer.POINTER_MOUSE] = (ev.pointerType == ev.MSPOINTER_TYPE_MOUSE || ev.pointerType == Hammer.POINTER_MOUSE);
  15816. types[Hammer.POINTER_TOUCH] = (ev.pointerType == ev.MSPOINTER_TYPE_TOUCH || ev.pointerType == Hammer.POINTER_TOUCH);
  15817. types[Hammer.POINTER_PEN] = (ev.pointerType == ev.MSPOINTER_TYPE_PEN || ev.pointerType == Hammer.POINTER_PEN);
  15818. return types[pointerType];
  15819. },
  15820. /**
  15821. * get events
  15822. */
  15823. getEvents: function() {
  15824. return [
  15825. 'pointerdown MSPointerDown',
  15826. 'pointermove MSPointerMove',
  15827. 'pointerup pointercancel MSPointerUp MSPointerCancel'
  15828. ];
  15829. },
  15830. /**
  15831. * reset the list
  15832. */
  15833. reset: function() {
  15834. this.pointers = {};
  15835. }
  15836. };
  15837. Hammer.utils = {
  15838. /**
  15839. * extend method,
  15840. * also used for cloning when dest is an empty object
  15841. * @param {Object} dest
  15842. * @param {Object} src
  15843. * @parm {Boolean} merge do a merge
  15844. * @returns {Object} dest
  15845. */
  15846. extend: function extend(dest, src, merge) {
  15847. for (var key in src) {
  15848. if(dest[key] !== undefined && merge) {
  15849. continue;
  15850. }
  15851. dest[key] = src[key];
  15852. }
  15853. return dest;
  15854. },
  15855. /**
  15856. * find if a node is in the given parent
  15857. * used for event delegation tricks
  15858. * @param {HTMLElement} node
  15859. * @param {HTMLElement} parent
  15860. * @returns {boolean} has_parent
  15861. */
  15862. hasParent: function(node, parent) {
  15863. while(node){
  15864. if(node == parent) {
  15865. return true;
  15866. }
  15867. node = node.parentNode;
  15868. }
  15869. return false;
  15870. },
  15871. /**
  15872. * get the center of all the touches
  15873. * @param {Array} touches
  15874. * @returns {Object} center
  15875. */
  15876. getCenter: function getCenter(touches) {
  15877. var valuesX = [], valuesY = [];
  15878. for(var t= 0,len=touches.length; t<len; t++) {
  15879. valuesX.push(touches[t].pageX);
  15880. valuesY.push(touches[t].pageY);
  15881. }
  15882. return {
  15883. pageX: ((Math.min.apply(Math, valuesX) + Math.max.apply(Math, valuesX)) / 2),
  15884. pageY: ((Math.min.apply(Math, valuesY) + Math.max.apply(Math, valuesY)) / 2)
  15885. };
  15886. },
  15887. /**
  15888. * calculate the velocity between two points
  15889. * @param {Number} delta_time
  15890. * @param {Number} delta_x
  15891. * @param {Number} delta_y
  15892. * @returns {Object} velocity
  15893. */
  15894. getVelocity: function getVelocity(delta_time, delta_x, delta_y) {
  15895. return {
  15896. x: Math.abs(delta_x / delta_time) || 0,
  15897. y: Math.abs(delta_y / delta_time) || 0
  15898. };
  15899. },
  15900. /**
  15901. * calculate the angle between two coordinates
  15902. * @param {Touch} touch1
  15903. * @param {Touch} touch2
  15904. * @returns {Number} angle
  15905. */
  15906. getAngle: function getAngle(touch1, touch2) {
  15907. var y = touch2.pageY - touch1.pageY,
  15908. x = touch2.pageX - touch1.pageX;
  15909. return Math.atan2(y, x) * 180 / Math.PI;
  15910. },
  15911. /**
  15912. * angle to direction define
  15913. * @param {Touch} touch1
  15914. * @param {Touch} touch2
  15915. * @returns {String} direction constant, like Hammer.DIRECTION_LEFT
  15916. */
  15917. getDirection: function getDirection(touch1, touch2) {
  15918. var x = Math.abs(touch1.pageX - touch2.pageX),
  15919. y = Math.abs(touch1.pageY - touch2.pageY);
  15920. if(x >= y) {
  15921. return touch1.pageX - touch2.pageX > 0 ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  15922. }
  15923. else {
  15924. return touch1.pageY - touch2.pageY > 0 ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  15925. }
  15926. },
  15927. /**
  15928. * calculate the distance between two touches
  15929. * @param {Touch} touch1
  15930. * @param {Touch} touch2
  15931. * @returns {Number} distance
  15932. */
  15933. getDistance: function getDistance(touch1, touch2) {
  15934. var x = touch2.pageX - touch1.pageX,
  15935. y = touch2.pageY - touch1.pageY;
  15936. return Math.sqrt((x*x) + (y*y));
  15937. },
  15938. /**
  15939. * calculate the scale factor between two touchLists (fingers)
  15940. * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
  15941. * @param {Array} start
  15942. * @param {Array} end
  15943. * @returns {Number} scale
  15944. */
  15945. getScale: function getScale(start, end) {
  15946. // need two fingers...
  15947. if(start.length >= 2 && end.length >= 2) {
  15948. return this.getDistance(end[0], end[1]) /
  15949. this.getDistance(start[0], start[1]);
  15950. }
  15951. return 1;
  15952. },
  15953. /**
  15954. * calculate the rotation degrees between two touchLists (fingers)
  15955. * @param {Array} start
  15956. * @param {Array} end
  15957. * @returns {Number} rotation
  15958. */
  15959. getRotation: function getRotation(start, end) {
  15960. // need two fingers
  15961. if(start.length >= 2 && end.length >= 2) {
  15962. return this.getAngle(end[1], end[0]) -
  15963. this.getAngle(start[1], start[0]);
  15964. }
  15965. return 0;
  15966. },
  15967. /**
  15968. * boolean if the direction is vertical
  15969. * @param {String} direction
  15970. * @returns {Boolean} is_vertical
  15971. */
  15972. isVertical: function isVertical(direction) {
  15973. return (direction == Hammer.DIRECTION_UP || direction == Hammer.DIRECTION_DOWN);
  15974. },
  15975. /**
  15976. * stop browser default behavior with css props
  15977. * @param {HtmlElement} element
  15978. * @param {Object} css_props
  15979. */
  15980. stopDefaultBrowserBehavior: function stopDefaultBrowserBehavior(element, css_props) {
  15981. var prop,
  15982. vendors = ['webkit','khtml','moz','ms','o',''];
  15983. if(!css_props || !element.style) {
  15984. return;
  15985. }
  15986. // with css properties for modern browsers
  15987. for(var i = 0; i < vendors.length; i++) {
  15988. for(var p in css_props) {
  15989. if(css_props.hasOwnProperty(p)) {
  15990. prop = p;
  15991. // vender prefix at the property
  15992. if(vendors[i]) {
  15993. prop = vendors[i] + prop.substring(0, 1).toUpperCase() + prop.substring(1);
  15994. }
  15995. // set the style
  15996. element.style[prop] = css_props[p];
  15997. }
  15998. }
  15999. }
  16000. // also the disable onselectstart
  16001. if(css_props.userSelect == 'none') {
  16002. element.onselectstart = function() {
  16003. return false;
  16004. };
  16005. }
  16006. }
  16007. };
  16008. Hammer.detection = {
  16009. // contains all registred Hammer.gestures in the correct order
  16010. gestures: [],
  16011. // data of the current Hammer.gesture detection session
  16012. current: null,
  16013. // the previous Hammer.gesture session data
  16014. // is a full clone of the previous gesture.current object
  16015. previous: null,
  16016. // when this becomes true, no gestures are fired
  16017. stopped: false,
  16018. /**
  16019. * start Hammer.gesture detection
  16020. * @param {Hammer.Instance} inst
  16021. * @param {Object} eventData
  16022. */
  16023. startDetect: function startDetect(inst, eventData) {
  16024. // already busy with a Hammer.gesture detection on an element
  16025. if(this.current) {
  16026. return;
  16027. }
  16028. this.stopped = false;
  16029. this.current = {
  16030. inst : inst, // reference to HammerInstance we're working for
  16031. startEvent : Hammer.utils.extend({}, eventData), // start eventData for distances, timing etc
  16032. lastEvent : false, // last eventData
  16033. name : '' // current gesture we're in/detected, can be 'tap', 'hold' etc
  16034. };
  16035. this.detect(eventData);
  16036. },
  16037. /**
  16038. * Hammer.gesture detection
  16039. * @param {Object} eventData
  16040. * @param {Object} eventData
  16041. */
  16042. detect: function detect(eventData) {
  16043. if(!this.current || this.stopped) {
  16044. return;
  16045. }
  16046. // extend event data with calculations about scale, distance etc
  16047. eventData = this.extendEventData(eventData);
  16048. // instance options
  16049. var inst_options = this.current.inst.options;
  16050. // call Hammer.gesture handlers
  16051. for(var g=0,len=this.gestures.length; g<len; g++) {
  16052. var gesture = this.gestures[g];
  16053. // only when the instance options have enabled this gesture
  16054. if(!this.stopped && inst_options[gesture.name] !== false) {
  16055. // if a handler returns false, we stop with the detection
  16056. if(gesture.handler.call(gesture, eventData, this.current.inst) === false) {
  16057. this.stopDetect();
  16058. break;
  16059. }
  16060. }
  16061. }
  16062. // store as previous event event
  16063. if(this.current) {
  16064. this.current.lastEvent = eventData;
  16065. }
  16066. // endevent, but not the last touch, so dont stop
  16067. if(eventData.eventType == Hammer.EVENT_END && !eventData.touches.length-1) {
  16068. this.stopDetect();
  16069. }
  16070. return eventData;
  16071. },
  16072. /**
  16073. * clear the Hammer.gesture vars
  16074. * this is called on endDetect, but can also be used when a final Hammer.gesture has been detected
  16075. * to stop other Hammer.gestures from being fired
  16076. */
  16077. stopDetect: function stopDetect() {
  16078. // clone current data to the store as the previous gesture
  16079. // used for the double tap gesture, since this is an other gesture detect session
  16080. this.previous = Hammer.utils.extend({}, this.current);
  16081. // reset the current
  16082. this.current = null;
  16083. // stopped!
  16084. this.stopped = true;
  16085. },
  16086. /**
  16087. * extend eventData for Hammer.gestures
  16088. * @param {Object} ev
  16089. * @returns {Object} ev
  16090. */
  16091. extendEventData: function extendEventData(ev) {
  16092. var startEv = this.current.startEvent;
  16093. // if the touches change, set the new touches over the startEvent touches
  16094. // this because touchevents don't have all the touches on touchstart, or the
  16095. // user must place his fingers at the EXACT same time on the screen, which is not realistic
  16096. // but, sometimes it happens that both fingers are touching at the EXACT same time
  16097. if(startEv && (ev.touches.length != startEv.touches.length || ev.touches === startEv.touches)) {
  16098. // extend 1 level deep to get the touchlist with the touch objects
  16099. startEv.touches = [];
  16100. for(var i=0,len=ev.touches.length; i<len; i++) {
  16101. startEv.touches.push(Hammer.utils.extend({}, ev.touches[i]));
  16102. }
  16103. }
  16104. var delta_time = ev.timeStamp - startEv.timeStamp,
  16105. delta_x = ev.center.pageX - startEv.center.pageX,
  16106. delta_y = ev.center.pageY - startEv.center.pageY,
  16107. velocity = Hammer.utils.getVelocity(delta_time, delta_x, delta_y);
  16108. Hammer.utils.extend(ev, {
  16109. deltaTime : delta_time,
  16110. deltaX : delta_x,
  16111. deltaY : delta_y,
  16112. velocityX : velocity.x,
  16113. velocityY : velocity.y,
  16114. distance : Hammer.utils.getDistance(startEv.center, ev.center),
  16115. angle : Hammer.utils.getAngle(startEv.center, ev.center),
  16116. direction : Hammer.utils.getDirection(startEv.center, ev.center),
  16117. scale : Hammer.utils.getScale(startEv.touches, ev.touches),
  16118. rotation : Hammer.utils.getRotation(startEv.touches, ev.touches),
  16119. startEvent : startEv
  16120. });
  16121. return ev;
  16122. },
  16123. /**
  16124. * register new gesture
  16125. * @param {Object} gesture object, see gestures.js for documentation
  16126. * @returns {Array} gestures
  16127. */
  16128. register: function register(gesture) {
  16129. // add an enable gesture options if there is no given
  16130. var options = gesture.defaults || {};
  16131. if(options[gesture.name] === undefined) {
  16132. options[gesture.name] = true;
  16133. }
  16134. // extend Hammer default options with the Hammer.gesture options
  16135. Hammer.utils.extend(Hammer.defaults, options, true);
  16136. // set its index
  16137. gesture.index = gesture.index || 1000;
  16138. // add Hammer.gesture to the list
  16139. this.gestures.push(gesture);
  16140. // sort the list by index
  16141. this.gestures.sort(function(a, b) {
  16142. if (a.index < b.index) {
  16143. return -1;
  16144. }
  16145. if (a.index > b.index) {
  16146. return 1;
  16147. }
  16148. return 0;
  16149. });
  16150. return this.gestures;
  16151. }
  16152. };
  16153. Hammer.gestures = Hammer.gestures || {};
  16154. /**
  16155. * Custom gestures
  16156. * ==============================
  16157. *
  16158. * Gesture object
  16159. * --------------------
  16160. * The object structure of a gesture:
  16161. *
  16162. * { name: 'mygesture',
  16163. * index: 1337,
  16164. * defaults: {
  16165. * mygesture_option: true
  16166. * }
  16167. * handler: function(type, ev, inst) {
  16168. * // trigger gesture event
  16169. * inst.trigger(this.name, ev);
  16170. * }
  16171. * }
  16172. * @param {String} name
  16173. * this should be the name of the gesture, lowercase
  16174. * it is also being used to disable/enable the gesture per instance config.
  16175. *
  16176. * @param {Number} [index=1000]
  16177. * the index of the gesture, where it is going to be in the stack of gestures detection
  16178. * like when you build an gesture that depends on the drag gesture, it is a good
  16179. * idea to place it after the index of the drag gesture.
  16180. *
  16181. * @param {Object} [defaults={}]
  16182. * the default settings of the gesture. these are added to the instance settings,
  16183. * and can be overruled per instance. you can also add the name of the gesture,
  16184. * but this is also added by default (and set to true).
  16185. *
  16186. * @param {Function} handler
  16187. * this handles the gesture detection of your custom gesture and receives the
  16188. * following arguments:
  16189. *
  16190. * @param {Object} eventData
  16191. * event data containing the following properties:
  16192. * timeStamp {Number} time the event occurred
  16193. * target {HTMLElement} target element
  16194. * touches {Array} touches (fingers, pointers, mouse) on the screen
  16195. * pointerType {String} kind of pointer that was used. matches Hammer.POINTER_MOUSE|TOUCH
  16196. * center {Object} center position of the touches. contains pageX and pageY
  16197. * deltaTime {Number} the total time of the touches in the screen
  16198. * deltaX {Number} the delta on x axis we haved moved
  16199. * deltaY {Number} the delta on y axis we haved moved
  16200. * velocityX {Number} the velocity on the x
  16201. * velocityY {Number} the velocity on y
  16202. * angle {Number} the angle we are moving
  16203. * direction {String} the direction we are moving. matches Hammer.DIRECTION_UP|DOWN|LEFT|RIGHT
  16204. * distance {Number} the distance we haved moved
  16205. * scale {Number} scaling of the touches, needs 2 touches
  16206. * rotation {Number} rotation of the touches, needs 2 touches *
  16207. * eventType {String} matches Hammer.EVENT_START|MOVE|END
  16208. * srcEvent {Object} the source event, like TouchStart or MouseDown *
  16209. * startEvent {Object} contains the same properties as above,
  16210. * but from the first touch. this is used to calculate
  16211. * distances, deltaTime, scaling etc
  16212. *
  16213. * @param {Hammer.Instance} inst
  16214. * the instance we are doing the detection for. you can get the options from
  16215. * the inst.options object and trigger the gesture event by calling inst.trigger
  16216. *
  16217. *
  16218. * Handle gestures
  16219. * --------------------
  16220. * inside the handler you can get/set Hammer.detection.current. This is the current
  16221. * detection session. It has the following properties
  16222. * @param {String} name
  16223. * contains the name of the gesture we have detected. it has not a real function,
  16224. * only to check in other gestures if something is detected.
  16225. * like in the drag gesture we set it to 'drag' and in the swipe gesture we can
  16226. * check if the current gesture is 'drag' by accessing Hammer.detection.current.name
  16227. *
  16228. * @readonly
  16229. * @param {Hammer.Instance} inst
  16230. * the instance we do the detection for
  16231. *
  16232. * @readonly
  16233. * @param {Object} startEvent
  16234. * contains the properties of the first gesture detection in this session.
  16235. * Used for calculations about timing, distance, etc.
  16236. *
  16237. * @readonly
  16238. * @param {Object} lastEvent
  16239. * contains all the properties of the last gesture detect in this session.
  16240. *
  16241. * after the gesture detection session has been completed (user has released the screen)
  16242. * the Hammer.detection.current object is copied into Hammer.detection.previous,
  16243. * this is usefull for gestures like doubletap, where you need to know if the
  16244. * previous gesture was a tap
  16245. *
  16246. * options that have been set by the instance can be received by calling inst.options
  16247. *
  16248. * You can trigger a gesture event by calling inst.trigger("mygesture", event).
  16249. * The first param is the name of your gesture, the second the event argument
  16250. *
  16251. *
  16252. * Register gestures
  16253. * --------------------
  16254. * When an gesture is added to the Hammer.gestures object, it is auto registered
  16255. * at the setup of the first Hammer instance. You can also call Hammer.detection.register
  16256. * manually and pass your gesture object as a param
  16257. *
  16258. */
  16259. /**
  16260. * Hold
  16261. * Touch stays at the same place for x time
  16262. * @events hold
  16263. */
  16264. Hammer.gestures.Hold = {
  16265. name: 'hold',
  16266. index: 10,
  16267. defaults: {
  16268. hold_timeout : 500,
  16269. hold_threshold : 1
  16270. },
  16271. timer: null,
  16272. handler: function holdGesture(ev, inst) {
  16273. switch(ev.eventType) {
  16274. case Hammer.EVENT_START:
  16275. // clear any running timers
  16276. clearTimeout(this.timer);
  16277. // set the gesture so we can check in the timeout if it still is
  16278. Hammer.detection.current.name = this.name;
  16279. // set timer and if after the timeout it still is hold,
  16280. // we trigger the hold event
  16281. this.timer = setTimeout(function() {
  16282. if(Hammer.detection.current.name == 'hold') {
  16283. inst.trigger('hold', ev);
  16284. }
  16285. }, inst.options.hold_timeout);
  16286. break;
  16287. // when you move or end we clear the timer
  16288. case Hammer.EVENT_MOVE:
  16289. if(ev.distance > inst.options.hold_threshold) {
  16290. clearTimeout(this.timer);
  16291. }
  16292. break;
  16293. case Hammer.EVENT_END:
  16294. clearTimeout(this.timer);
  16295. break;
  16296. }
  16297. }
  16298. };
  16299. /**
  16300. * Tap/DoubleTap
  16301. * Quick touch at a place or double at the same place
  16302. * @events tap, doubletap
  16303. */
  16304. Hammer.gestures.Tap = {
  16305. name: 'tap',
  16306. index: 100,
  16307. defaults: {
  16308. tap_max_touchtime : 250,
  16309. tap_max_distance : 10,
  16310. tap_always : true,
  16311. doubletap_distance : 20,
  16312. doubletap_interval : 300
  16313. },
  16314. handler: function tapGesture(ev, inst) {
  16315. if(ev.eventType == Hammer.EVENT_END) {
  16316. // previous gesture, for the double tap since these are two different gesture detections
  16317. var prev = Hammer.detection.previous,
  16318. did_doubletap = false;
  16319. // when the touchtime is higher then the max touch time
  16320. // or when the moving distance is too much
  16321. if(ev.deltaTime > inst.options.tap_max_touchtime ||
  16322. ev.distance > inst.options.tap_max_distance) {
  16323. return;
  16324. }
  16325. // check if double tap
  16326. if(prev && prev.name == 'tap' &&
  16327. (ev.timeStamp - prev.lastEvent.timeStamp) < inst.options.doubletap_interval &&
  16328. ev.distance < inst.options.doubletap_distance) {
  16329. inst.trigger('doubletap', ev);
  16330. did_doubletap = true;
  16331. }
  16332. // do a single tap
  16333. if(!did_doubletap || inst.options.tap_always) {
  16334. Hammer.detection.current.name = 'tap';
  16335. inst.trigger(Hammer.detection.current.name, ev);
  16336. }
  16337. }
  16338. }
  16339. };
  16340. /**
  16341. * Swipe
  16342. * triggers swipe events when the end velocity is above the threshold
  16343. * @events swipe, swipeleft, swiperight, swipeup, swipedown
  16344. */
  16345. Hammer.gestures.Swipe = {
  16346. name: 'swipe',
  16347. index: 40,
  16348. defaults: {
  16349. // set 0 for unlimited, but this can conflict with transform
  16350. swipe_max_touches : 1,
  16351. swipe_velocity : 0.7
  16352. },
  16353. handler: function swipeGesture(ev, inst) {
  16354. if(ev.eventType == Hammer.EVENT_END) {
  16355. // max touches
  16356. if(inst.options.swipe_max_touches > 0 &&
  16357. ev.touches.length > inst.options.swipe_max_touches) {
  16358. return;
  16359. }
  16360. // when the distance we moved is too small we skip this gesture
  16361. // or we can be already in dragging
  16362. if(ev.velocityX > inst.options.swipe_velocity ||
  16363. ev.velocityY > inst.options.swipe_velocity) {
  16364. // trigger swipe events
  16365. inst.trigger(this.name, ev);
  16366. inst.trigger(this.name + ev.direction, ev);
  16367. }
  16368. }
  16369. }
  16370. };
  16371. /**
  16372. * Drag
  16373. * Move with x fingers (default 1) around on the page. Blocking the scrolling when
  16374. * moving left and right is a good practice. When all the drag events are blocking
  16375. * you disable scrolling on that area.
  16376. * @events drag, drapleft, dragright, dragup, dragdown
  16377. */
  16378. Hammer.gestures.Drag = {
  16379. name: 'drag',
  16380. index: 50,
  16381. defaults: {
  16382. drag_min_distance : 10,
  16383. // set 0 for unlimited, but this can conflict with transform
  16384. drag_max_touches : 1,
  16385. // prevent default browser behavior when dragging occurs
  16386. // be careful with it, it makes the element a blocking element
  16387. // when you are using the drag gesture, it is a good practice to set this true
  16388. drag_block_horizontal : false,
  16389. drag_block_vertical : false,
  16390. // drag_lock_to_axis keeps the drag gesture on the axis that it started on,
  16391. // It disallows vertical directions if the initial direction was horizontal, and vice versa.
  16392. drag_lock_to_axis : false,
  16393. // drag lock only kicks in when distance > drag_lock_min_distance
  16394. // This way, locking occurs only when the distance has become large enough to reliably determine the direction
  16395. drag_lock_min_distance : 25
  16396. },
  16397. triggered: false,
  16398. handler: function dragGesture(ev, inst) {
  16399. // current gesture isnt drag, but dragged is true
  16400. // this means an other gesture is busy. now call dragend
  16401. if(Hammer.detection.current.name != this.name && this.triggered) {
  16402. inst.trigger(this.name +'end', ev);
  16403. this.triggered = false;
  16404. return;
  16405. }
  16406. // max touches
  16407. if(inst.options.drag_max_touches > 0 &&
  16408. ev.touches.length > inst.options.drag_max_touches) {
  16409. return;
  16410. }
  16411. switch(ev.eventType) {
  16412. case Hammer.EVENT_START:
  16413. this.triggered = false;
  16414. break;
  16415. case Hammer.EVENT_MOVE:
  16416. // when the distance we moved is too small we skip this gesture
  16417. // or we can be already in dragging
  16418. if(ev.distance < inst.options.drag_min_distance &&
  16419. Hammer.detection.current.name != this.name) {
  16420. return;
  16421. }
  16422. // we are dragging!
  16423. Hammer.detection.current.name = this.name;
  16424. // lock drag to axis?
  16425. if(Hammer.detection.current.lastEvent.drag_locked_to_axis || (inst.options.drag_lock_to_axis && inst.options.drag_lock_min_distance<=ev.distance)) {
  16426. ev.drag_locked_to_axis = true;
  16427. }
  16428. var last_direction = Hammer.detection.current.lastEvent.direction;
  16429. if(ev.drag_locked_to_axis && last_direction !== ev.direction) {
  16430. // keep direction on the axis that the drag gesture started on
  16431. if(Hammer.utils.isVertical(last_direction)) {
  16432. ev.direction = (ev.deltaY < 0) ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  16433. }
  16434. else {
  16435. ev.direction = (ev.deltaX < 0) ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  16436. }
  16437. }
  16438. // first time, trigger dragstart event
  16439. if(!this.triggered) {
  16440. inst.trigger(this.name +'start', ev);
  16441. this.triggered = true;
  16442. }
  16443. // trigger normal event
  16444. inst.trigger(this.name, ev);
  16445. // direction event, like dragdown
  16446. inst.trigger(this.name + ev.direction, ev);
  16447. // block the browser events
  16448. if( (inst.options.drag_block_vertical && Hammer.utils.isVertical(ev.direction)) ||
  16449. (inst.options.drag_block_horizontal && !Hammer.utils.isVertical(ev.direction))) {
  16450. ev.preventDefault();
  16451. }
  16452. break;
  16453. case Hammer.EVENT_END:
  16454. // trigger dragend
  16455. if(this.triggered) {
  16456. inst.trigger(this.name +'end', ev);
  16457. }
  16458. this.triggered = false;
  16459. break;
  16460. }
  16461. }
  16462. };
  16463. /**
  16464. * Transform
  16465. * User want to scale or rotate with 2 fingers
  16466. * @events transform, pinch, pinchin, pinchout, rotate
  16467. */
  16468. Hammer.gestures.Transform = {
  16469. name: 'transform',
  16470. index: 45,
  16471. defaults: {
  16472. // factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1
  16473. transform_min_scale : 0.01,
  16474. // rotation in degrees
  16475. transform_min_rotation : 1,
  16476. // prevent default browser behavior when two touches are on the screen
  16477. // but it makes the element a blocking element
  16478. // when you are using the transform gesture, it is a good practice to set this true
  16479. transform_always_block : false
  16480. },
  16481. triggered: false,
  16482. handler: function transformGesture(ev, inst) {
  16483. // current gesture isnt drag, but dragged is true
  16484. // this means an other gesture is busy. now call dragend
  16485. if(Hammer.detection.current.name != this.name && this.triggered) {
  16486. inst.trigger(this.name +'end', ev);
  16487. this.triggered = false;
  16488. return;
  16489. }
  16490. // atleast multitouch
  16491. if(ev.touches.length < 2) {
  16492. return;
  16493. }
  16494. // prevent default when two fingers are on the screen
  16495. if(inst.options.transform_always_block) {
  16496. ev.preventDefault();
  16497. }
  16498. switch(ev.eventType) {
  16499. case Hammer.EVENT_START:
  16500. this.triggered = false;
  16501. break;
  16502. case Hammer.EVENT_MOVE:
  16503. var scale_threshold = Math.abs(1-ev.scale);
  16504. var rotation_threshold = Math.abs(ev.rotation);
  16505. // when the distance we moved is too small we skip this gesture
  16506. // or we can be already in dragging
  16507. if(scale_threshold < inst.options.transform_min_scale &&
  16508. rotation_threshold < inst.options.transform_min_rotation) {
  16509. return;
  16510. }
  16511. // we are transforming!
  16512. Hammer.detection.current.name = this.name;
  16513. // first time, trigger dragstart event
  16514. if(!this.triggered) {
  16515. inst.trigger(this.name +'start', ev);
  16516. this.triggered = true;
  16517. }
  16518. inst.trigger(this.name, ev); // basic transform event
  16519. // trigger rotate event
  16520. if(rotation_threshold > inst.options.transform_min_rotation) {
  16521. inst.trigger('rotate', ev);
  16522. }
  16523. // trigger pinch event
  16524. if(scale_threshold > inst.options.transform_min_scale) {
  16525. inst.trigger('pinch', ev);
  16526. inst.trigger('pinch'+ ((ev.scale < 1) ? 'in' : 'out'), ev);
  16527. }
  16528. break;
  16529. case Hammer.EVENT_END:
  16530. // trigger dragend
  16531. if(this.triggered) {
  16532. inst.trigger(this.name +'end', ev);
  16533. }
  16534. this.triggered = false;
  16535. break;
  16536. }
  16537. }
  16538. };
  16539. /**
  16540. * Touch
  16541. * Called as first, tells the user has touched the screen
  16542. * @events touch
  16543. */
  16544. Hammer.gestures.Touch = {
  16545. name: 'touch',
  16546. index: -Infinity,
  16547. defaults: {
  16548. // call preventDefault at touchstart, and makes the element blocking by
  16549. // disabling the scrolling of the page, but it improves gestures like
  16550. // transforming and dragging.
  16551. // be careful with using this, it can be very annoying for users to be stuck
  16552. // on the page
  16553. prevent_default: false,
  16554. // disable mouse events, so only touch (or pen!) input triggers events
  16555. prevent_mouseevents: false
  16556. },
  16557. handler: function touchGesture(ev, inst) {
  16558. if(inst.options.prevent_mouseevents && ev.pointerType == Hammer.POINTER_MOUSE) {
  16559. ev.stopDetect();
  16560. return;
  16561. }
  16562. if(inst.options.prevent_default) {
  16563. ev.preventDefault();
  16564. }
  16565. if(ev.eventType == Hammer.EVENT_START) {
  16566. inst.trigger(this.name, ev);
  16567. }
  16568. }
  16569. };
  16570. /**
  16571. * Release
  16572. * Called as last, tells the user has released the screen
  16573. * @events release
  16574. */
  16575. Hammer.gestures.Release = {
  16576. name: 'release',
  16577. index: Infinity,
  16578. handler: function releaseGesture(ev, inst) {
  16579. if(ev.eventType == Hammer.EVENT_END) {
  16580. inst.trigger(this.name, ev);
  16581. }
  16582. }
  16583. };
  16584. // node export
  16585. if(typeof module === 'object' && typeof module.exports === 'object'){
  16586. module.exports = Hammer;
  16587. }
  16588. // just window export
  16589. else {
  16590. window.Hammer = Hammer;
  16591. // requireJS module definition
  16592. if(typeof window.define === 'function' && window.define.amd) {
  16593. window.define('hammer', [], function() {
  16594. return Hammer;
  16595. });
  16596. }
  16597. }
  16598. })(this);
  16599. },{}],4:[function(require,module,exports){
  16600. //! moment.js
  16601. //! version : 2.5.1
  16602. //! authors : Tim Wood, Iskren Chernev, Moment.js contributors
  16603. //! license : MIT
  16604. //! momentjs.com
  16605. (function (undefined) {
  16606. /************************************
  16607. Constants
  16608. ************************************/
  16609. var moment,
  16610. VERSION = "2.5.1",
  16611. global = this,
  16612. round = Math.round,
  16613. i,
  16614. YEAR = 0,
  16615. MONTH = 1,
  16616. DATE = 2,
  16617. HOUR = 3,
  16618. MINUTE = 4,
  16619. SECOND = 5,
  16620. MILLISECOND = 6,
  16621. // internal storage for language config files
  16622. languages = {},
  16623. // moment internal properties
  16624. momentProperties = {
  16625. _isAMomentObject: null,
  16626. _i : null,
  16627. _f : null,
  16628. _l : null,
  16629. _strict : null,
  16630. _isUTC : null,
  16631. _offset : null, // optional. Combine with _isUTC
  16632. _pf : null,
  16633. _lang : null // optional
  16634. },
  16635. // check for nodeJS
  16636. hasModule = (typeof module !== 'undefined' && module.exports && typeof require !== 'undefined'),
  16637. // ASP.NET json date format regex
  16638. aspNetJsonRegex = /^\/?Date\((\-?\d+)/i,
  16639. aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,
  16640. // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
  16641. // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
  16642. isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/,
  16643. // format tokens
  16644. 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,
  16645. localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g,
  16646. // parsing token regexes
  16647. parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99
  16648. parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999
  16649. parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999
  16650. parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999
  16651. parseTokenDigits = /\d+/, // nonzero number of digits
  16652. 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.
  16653. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z
  16654. parseTokenT = /T/i, // T (ISO separator)
  16655. parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
  16656. //strict parsing regexes
  16657. parseTokenOneDigit = /\d/, // 0 - 9
  16658. parseTokenTwoDigits = /\d\d/, // 00 - 99
  16659. parseTokenThreeDigits = /\d{3}/, // 000 - 999
  16660. parseTokenFourDigits = /\d{4}/, // 0000 - 9999
  16661. parseTokenSixDigits = /[+-]?\d{6}/, // -999,999 - 999,999
  16662. parseTokenSignedNumber = /[+-]?\d+/, // -inf - inf
  16663. // iso 8601 regex
  16664. // 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)
  16665. 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)?)?$/,
  16666. isoFormat = 'YYYY-MM-DDTHH:mm:ssZ',
  16667. isoDates = [
  16668. ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/],
  16669. ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/],
  16670. ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/],
  16671. ['GGGG-[W]WW', /\d{4}-W\d{2}/],
  16672. ['YYYY-DDD', /\d{4}-\d{3}/]
  16673. ],
  16674. // iso time formats and regexes
  16675. isoTimes = [
  16676. ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d{1,3}/],
  16677. ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/],
  16678. ['HH:mm', /(T| )\d\d:\d\d/],
  16679. ['HH', /(T| )\d\d/]
  16680. ],
  16681. // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"]
  16682. parseTimezoneChunker = /([\+\-]|\d\d)/gi,
  16683. // getter and setter names
  16684. proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'),
  16685. unitMillisecondFactors = {
  16686. 'Milliseconds' : 1,
  16687. 'Seconds' : 1e3,
  16688. 'Minutes' : 6e4,
  16689. 'Hours' : 36e5,
  16690. 'Days' : 864e5,
  16691. 'Months' : 2592e6,
  16692. 'Years' : 31536e6
  16693. },
  16694. unitAliases = {
  16695. ms : 'millisecond',
  16696. s : 'second',
  16697. m : 'minute',
  16698. h : 'hour',
  16699. d : 'day',
  16700. D : 'date',
  16701. w : 'week',
  16702. W : 'isoWeek',
  16703. M : 'month',
  16704. y : 'year',
  16705. DDD : 'dayOfYear',
  16706. e : 'weekday',
  16707. E : 'isoWeekday',
  16708. gg: 'weekYear',
  16709. GG: 'isoWeekYear'
  16710. },
  16711. camelFunctions = {
  16712. dayofyear : 'dayOfYear',
  16713. isoweekday : 'isoWeekday',
  16714. isoweek : 'isoWeek',
  16715. weekyear : 'weekYear',
  16716. isoweekyear : 'isoWeekYear'
  16717. },
  16718. // format function strings
  16719. formatFunctions = {},
  16720. // tokens to ordinalize and pad
  16721. ordinalizeTokens = 'DDD w W M D d'.split(' '),
  16722. paddedTokens = 'M D H h m s w W'.split(' '),
  16723. formatTokenFunctions = {
  16724. M : function () {
  16725. return this.month() + 1;
  16726. },
  16727. MMM : function (format) {
  16728. return this.lang().monthsShort(this, format);
  16729. },
  16730. MMMM : function (format) {
  16731. return this.lang().months(this, format);
  16732. },
  16733. D : function () {
  16734. return this.date();
  16735. },
  16736. DDD : function () {
  16737. return this.dayOfYear();
  16738. },
  16739. d : function () {
  16740. return this.day();
  16741. },
  16742. dd : function (format) {
  16743. return this.lang().weekdaysMin(this, format);
  16744. },
  16745. ddd : function (format) {
  16746. return this.lang().weekdaysShort(this, format);
  16747. },
  16748. dddd : function (format) {
  16749. return this.lang().weekdays(this, format);
  16750. },
  16751. w : function () {
  16752. return this.week();
  16753. },
  16754. W : function () {
  16755. return this.isoWeek();
  16756. },
  16757. YY : function () {
  16758. return leftZeroFill(this.year() % 100, 2);
  16759. },
  16760. YYYY : function () {
  16761. return leftZeroFill(this.year(), 4);
  16762. },
  16763. YYYYY : function () {
  16764. return leftZeroFill(this.year(), 5);
  16765. },
  16766. YYYYYY : function () {
  16767. var y = this.year(), sign = y >= 0 ? '+' : '-';
  16768. return sign + leftZeroFill(Math.abs(y), 6);
  16769. },
  16770. gg : function () {
  16771. return leftZeroFill(this.weekYear() % 100, 2);
  16772. },
  16773. gggg : function () {
  16774. return leftZeroFill(this.weekYear(), 4);
  16775. },
  16776. ggggg : function () {
  16777. return leftZeroFill(this.weekYear(), 5);
  16778. },
  16779. GG : function () {
  16780. return leftZeroFill(this.isoWeekYear() % 100, 2);
  16781. },
  16782. GGGG : function () {
  16783. return leftZeroFill(this.isoWeekYear(), 4);
  16784. },
  16785. GGGGG : function () {
  16786. return leftZeroFill(this.isoWeekYear(), 5);
  16787. },
  16788. e : function () {
  16789. return this.weekday();
  16790. },
  16791. E : function () {
  16792. return this.isoWeekday();
  16793. },
  16794. a : function () {
  16795. return this.lang().meridiem(this.hours(), this.minutes(), true);
  16796. },
  16797. A : function () {
  16798. return this.lang().meridiem(this.hours(), this.minutes(), false);
  16799. },
  16800. H : function () {
  16801. return this.hours();
  16802. },
  16803. h : function () {
  16804. return this.hours() % 12 || 12;
  16805. },
  16806. m : function () {
  16807. return this.minutes();
  16808. },
  16809. s : function () {
  16810. return this.seconds();
  16811. },
  16812. S : function () {
  16813. return toInt(this.milliseconds() / 100);
  16814. },
  16815. SS : function () {
  16816. return leftZeroFill(toInt(this.milliseconds() / 10), 2);
  16817. },
  16818. SSS : function () {
  16819. return leftZeroFill(this.milliseconds(), 3);
  16820. },
  16821. SSSS : function () {
  16822. return leftZeroFill(this.milliseconds(), 3);
  16823. },
  16824. Z : function () {
  16825. var a = -this.zone(),
  16826. b = "+";
  16827. if (a < 0) {
  16828. a = -a;
  16829. b = "-";
  16830. }
  16831. return b + leftZeroFill(toInt(a / 60), 2) + ":" + leftZeroFill(toInt(a) % 60, 2);
  16832. },
  16833. ZZ : function () {
  16834. var a = -this.zone(),
  16835. b = "+";
  16836. if (a < 0) {
  16837. a = -a;
  16838. b = "-";
  16839. }
  16840. return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2);
  16841. },
  16842. z : function () {
  16843. return this.zoneAbbr();
  16844. },
  16845. zz : function () {
  16846. return this.zoneName();
  16847. },
  16848. X : function () {
  16849. return this.unix();
  16850. },
  16851. Q : function () {
  16852. return this.quarter();
  16853. }
  16854. },
  16855. lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin'];
  16856. function defaultParsingFlags() {
  16857. // We need to deep clone this object, and es5 standard is not very
  16858. // helpful.
  16859. return {
  16860. empty : false,
  16861. unusedTokens : [],
  16862. unusedInput : [],
  16863. overflow : -2,
  16864. charsLeftOver : 0,
  16865. nullInput : false,
  16866. invalidMonth : null,
  16867. invalidFormat : false,
  16868. userInvalidated : false,
  16869. iso: false
  16870. };
  16871. }
  16872. function padToken(func, count) {
  16873. return function (a) {
  16874. return leftZeroFill(func.call(this, a), count);
  16875. };
  16876. }
  16877. function ordinalizeToken(func, period) {
  16878. return function (a) {
  16879. return this.lang().ordinal(func.call(this, a), period);
  16880. };
  16881. }
  16882. while (ordinalizeTokens.length) {
  16883. i = ordinalizeTokens.pop();
  16884. formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i);
  16885. }
  16886. while (paddedTokens.length) {
  16887. i = paddedTokens.pop();
  16888. formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2);
  16889. }
  16890. formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3);
  16891. /************************************
  16892. Constructors
  16893. ************************************/
  16894. function Language() {
  16895. }
  16896. // Moment prototype object
  16897. function Moment(config) {
  16898. checkOverflow(config);
  16899. extend(this, config);
  16900. }
  16901. // Duration Constructor
  16902. function Duration(duration) {
  16903. var normalizedInput = normalizeObjectUnits(duration),
  16904. years = normalizedInput.year || 0,
  16905. months = normalizedInput.month || 0,
  16906. weeks = normalizedInput.week || 0,
  16907. days = normalizedInput.day || 0,
  16908. hours = normalizedInput.hour || 0,
  16909. minutes = normalizedInput.minute || 0,
  16910. seconds = normalizedInput.second || 0,
  16911. milliseconds = normalizedInput.millisecond || 0;
  16912. // representation for dateAddRemove
  16913. this._milliseconds = +milliseconds +
  16914. seconds * 1e3 + // 1000
  16915. minutes * 6e4 + // 1000 * 60
  16916. hours * 36e5; // 1000 * 60 * 60
  16917. // Because of dateAddRemove treats 24 hours as different from a
  16918. // day when working around DST, we need to store them separately
  16919. this._days = +days +
  16920. weeks * 7;
  16921. // It is impossible translate months into days without knowing
  16922. // which months you are are talking about, so we have to store
  16923. // it separately.
  16924. this._months = +months +
  16925. years * 12;
  16926. this._data = {};
  16927. this._bubble();
  16928. }
  16929. /************************************
  16930. Helpers
  16931. ************************************/
  16932. function extend(a, b) {
  16933. for (var i in b) {
  16934. if (b.hasOwnProperty(i)) {
  16935. a[i] = b[i];
  16936. }
  16937. }
  16938. if (b.hasOwnProperty("toString")) {
  16939. a.toString = b.toString;
  16940. }
  16941. if (b.hasOwnProperty("valueOf")) {
  16942. a.valueOf = b.valueOf;
  16943. }
  16944. return a;
  16945. }
  16946. function cloneMoment(m) {
  16947. var result = {}, i;
  16948. for (i in m) {
  16949. if (m.hasOwnProperty(i) && momentProperties.hasOwnProperty(i)) {
  16950. result[i] = m[i];
  16951. }
  16952. }
  16953. return result;
  16954. }
  16955. function absRound(number) {
  16956. if (number < 0) {
  16957. return Math.ceil(number);
  16958. } else {
  16959. return Math.floor(number);
  16960. }
  16961. }
  16962. // left zero fill a number
  16963. // see http://jsperf.com/left-zero-filling for performance comparison
  16964. function leftZeroFill(number, targetLength, forceSign) {
  16965. var output = '' + Math.abs(number),
  16966. sign = number >= 0;
  16967. while (output.length < targetLength) {
  16968. output = '0' + output;
  16969. }
  16970. return (sign ? (forceSign ? '+' : '') : '-') + output;
  16971. }
  16972. // helper function for _.addTime and _.subtractTime
  16973. function addOrSubtractDurationFromMoment(mom, duration, isAdding, ignoreUpdateOffset) {
  16974. var milliseconds = duration._milliseconds,
  16975. days = duration._days,
  16976. months = duration._months,
  16977. minutes,
  16978. hours;
  16979. if (milliseconds) {
  16980. mom._d.setTime(+mom._d + milliseconds * isAdding);
  16981. }
  16982. // store the minutes and hours so we can restore them
  16983. if (days || months) {
  16984. minutes = mom.minute();
  16985. hours = mom.hour();
  16986. }
  16987. if (days) {
  16988. mom.date(mom.date() + days * isAdding);
  16989. }
  16990. if (months) {
  16991. mom.month(mom.month() + months * isAdding);
  16992. }
  16993. if (milliseconds && !ignoreUpdateOffset) {
  16994. moment.updateOffset(mom);
  16995. }
  16996. // restore the minutes and hours after possibly changing dst
  16997. if (days || months) {
  16998. mom.minute(minutes);
  16999. mom.hour(hours);
  17000. }
  17001. }
  17002. // check if is an array
  17003. function isArray(input) {
  17004. return Object.prototype.toString.call(input) === '[object Array]';
  17005. }
  17006. function isDate(input) {
  17007. return Object.prototype.toString.call(input) === '[object Date]' ||
  17008. input instanceof Date;
  17009. }
  17010. // compare two arrays, return the number of differences
  17011. function compareArrays(array1, array2, dontConvert) {
  17012. var len = Math.min(array1.length, array2.length),
  17013. lengthDiff = Math.abs(array1.length - array2.length),
  17014. diffs = 0,
  17015. i;
  17016. for (i = 0; i < len; i++) {
  17017. if ((dontConvert && array1[i] !== array2[i]) ||
  17018. (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
  17019. diffs++;
  17020. }
  17021. }
  17022. return diffs + lengthDiff;
  17023. }
  17024. function normalizeUnits(units) {
  17025. if (units) {
  17026. var lowered = units.toLowerCase().replace(/(.)s$/, '$1');
  17027. units = unitAliases[units] || camelFunctions[lowered] || lowered;
  17028. }
  17029. return units;
  17030. }
  17031. function normalizeObjectUnits(inputObject) {
  17032. var normalizedInput = {},
  17033. normalizedProp,
  17034. prop;
  17035. for (prop in inputObject) {
  17036. if (inputObject.hasOwnProperty(prop)) {
  17037. normalizedProp = normalizeUnits(prop);
  17038. if (normalizedProp) {
  17039. normalizedInput[normalizedProp] = inputObject[prop];
  17040. }
  17041. }
  17042. }
  17043. return normalizedInput;
  17044. }
  17045. function makeList(field) {
  17046. var count, setter;
  17047. if (field.indexOf('week') === 0) {
  17048. count = 7;
  17049. setter = 'day';
  17050. }
  17051. else if (field.indexOf('month') === 0) {
  17052. count = 12;
  17053. setter = 'month';
  17054. }
  17055. else {
  17056. return;
  17057. }
  17058. moment[field] = function (format, index) {
  17059. var i, getter,
  17060. method = moment.fn._lang[field],
  17061. results = [];
  17062. if (typeof format === 'number') {
  17063. index = format;
  17064. format = undefined;
  17065. }
  17066. getter = function (i) {
  17067. var m = moment().utc().set(setter, i);
  17068. return method.call(moment.fn._lang, m, format || '');
  17069. };
  17070. if (index != null) {
  17071. return getter(index);
  17072. }
  17073. else {
  17074. for (i = 0; i < count; i++) {
  17075. results.push(getter(i));
  17076. }
  17077. return results;
  17078. }
  17079. };
  17080. }
  17081. function toInt(argumentForCoercion) {
  17082. var coercedNumber = +argumentForCoercion,
  17083. value = 0;
  17084. if (coercedNumber !== 0 && isFinite(coercedNumber)) {
  17085. if (coercedNumber >= 0) {
  17086. value = Math.floor(coercedNumber);
  17087. } else {
  17088. value = Math.ceil(coercedNumber);
  17089. }
  17090. }
  17091. return value;
  17092. }
  17093. function daysInMonth(year, month) {
  17094. return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
  17095. }
  17096. function daysInYear(year) {
  17097. return isLeapYear(year) ? 366 : 365;
  17098. }
  17099. function isLeapYear(year) {
  17100. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  17101. }
  17102. function checkOverflow(m) {
  17103. var overflow;
  17104. if (m._a && m._pf.overflow === -2) {
  17105. overflow =
  17106. m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH :
  17107. m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE :
  17108. m._a[HOUR] < 0 || m._a[HOUR] > 23 ? HOUR :
  17109. m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE :
  17110. m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND :
  17111. m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND :
  17112. -1;
  17113. if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
  17114. overflow = DATE;
  17115. }
  17116. m._pf.overflow = overflow;
  17117. }
  17118. }
  17119. function isValid(m) {
  17120. if (m._isValid == null) {
  17121. m._isValid = !isNaN(m._d.getTime()) &&
  17122. m._pf.overflow < 0 &&
  17123. !m._pf.empty &&
  17124. !m._pf.invalidMonth &&
  17125. !m._pf.nullInput &&
  17126. !m._pf.invalidFormat &&
  17127. !m._pf.userInvalidated;
  17128. if (m._strict) {
  17129. m._isValid = m._isValid &&
  17130. m._pf.charsLeftOver === 0 &&
  17131. m._pf.unusedTokens.length === 0;
  17132. }
  17133. }
  17134. return m._isValid;
  17135. }
  17136. function normalizeLanguage(key) {
  17137. return key ? key.toLowerCase().replace('_', '-') : key;
  17138. }
  17139. // Return a moment from input, that is local/utc/zone equivalent to model.
  17140. function makeAs(input, model) {
  17141. return model._isUTC ? moment(input).zone(model._offset || 0) :
  17142. moment(input).local();
  17143. }
  17144. /************************************
  17145. Languages
  17146. ************************************/
  17147. extend(Language.prototype, {
  17148. set : function (config) {
  17149. var prop, i;
  17150. for (i in config) {
  17151. prop = config[i];
  17152. if (typeof prop === 'function') {
  17153. this[i] = prop;
  17154. } else {
  17155. this['_' + i] = prop;
  17156. }
  17157. }
  17158. },
  17159. _months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
  17160. months : function (m) {
  17161. return this._months[m.month()];
  17162. },
  17163. _monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),
  17164. monthsShort : function (m) {
  17165. return this._monthsShort[m.month()];
  17166. },
  17167. monthsParse : function (monthName) {
  17168. var i, mom, regex;
  17169. if (!this._monthsParse) {
  17170. this._monthsParse = [];
  17171. }
  17172. for (i = 0; i < 12; i++) {
  17173. // make the regex if we don't have it already
  17174. if (!this._monthsParse[i]) {
  17175. mom = moment.utc([2000, i]);
  17176. regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  17177. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  17178. }
  17179. // test the regex
  17180. if (this._monthsParse[i].test(monthName)) {
  17181. return i;
  17182. }
  17183. }
  17184. },
  17185. _weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
  17186. weekdays : function (m) {
  17187. return this._weekdays[m.day()];
  17188. },
  17189. _weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),
  17190. weekdaysShort : function (m) {
  17191. return this._weekdaysShort[m.day()];
  17192. },
  17193. _weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"),
  17194. weekdaysMin : function (m) {
  17195. return this._weekdaysMin[m.day()];
  17196. },
  17197. weekdaysParse : function (weekdayName) {
  17198. var i, mom, regex;
  17199. if (!this._weekdaysParse) {
  17200. this._weekdaysParse = [];
  17201. }
  17202. for (i = 0; i < 7; i++) {
  17203. // make the regex if we don't have it already
  17204. if (!this._weekdaysParse[i]) {
  17205. mom = moment([2000, 1]).day(i);
  17206. regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
  17207. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  17208. }
  17209. // test the regex
  17210. if (this._weekdaysParse[i].test(weekdayName)) {
  17211. return i;
  17212. }
  17213. }
  17214. },
  17215. _longDateFormat : {
  17216. LT : "h:mm A",
  17217. L : "MM/DD/YYYY",
  17218. LL : "MMMM D YYYY",
  17219. LLL : "MMMM D YYYY LT",
  17220. LLLL : "dddd, MMMM D YYYY LT"
  17221. },
  17222. longDateFormat : function (key) {
  17223. var output = this._longDateFormat[key];
  17224. if (!output && this._longDateFormat[key.toUpperCase()]) {
  17225. output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) {
  17226. return val.slice(1);
  17227. });
  17228. this._longDateFormat[key] = output;
  17229. }
  17230. return output;
  17231. },
  17232. isPM : function (input) {
  17233. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  17234. // Using charAt should be more compatible.
  17235. return ((input + '').toLowerCase().charAt(0) === 'p');
  17236. },
  17237. _meridiemParse : /[ap]\.?m?\.?/i,
  17238. meridiem : function (hours, minutes, isLower) {
  17239. if (hours > 11) {
  17240. return isLower ? 'pm' : 'PM';
  17241. } else {
  17242. return isLower ? 'am' : 'AM';
  17243. }
  17244. },
  17245. _calendar : {
  17246. sameDay : '[Today at] LT',
  17247. nextDay : '[Tomorrow at] LT',
  17248. nextWeek : 'dddd [at] LT',
  17249. lastDay : '[Yesterday at] LT',
  17250. lastWeek : '[Last] dddd [at] LT',
  17251. sameElse : 'L'
  17252. },
  17253. calendar : function (key, mom) {
  17254. var output = this._calendar[key];
  17255. return typeof output === 'function' ? output.apply(mom) : output;
  17256. },
  17257. _relativeTime : {
  17258. future : "in %s",
  17259. past : "%s ago",
  17260. s : "a few seconds",
  17261. m : "a minute",
  17262. mm : "%d minutes",
  17263. h : "an hour",
  17264. hh : "%d hours",
  17265. d : "a day",
  17266. dd : "%d days",
  17267. M : "a month",
  17268. MM : "%d months",
  17269. y : "a year",
  17270. yy : "%d years"
  17271. },
  17272. relativeTime : function (number, withoutSuffix, string, isFuture) {
  17273. var output = this._relativeTime[string];
  17274. return (typeof output === 'function') ?
  17275. output(number, withoutSuffix, string, isFuture) :
  17276. output.replace(/%d/i, number);
  17277. },
  17278. pastFuture : function (diff, output) {
  17279. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  17280. return typeof format === 'function' ? format(output) : format.replace(/%s/i, output);
  17281. },
  17282. ordinal : function (number) {
  17283. return this._ordinal.replace("%d", number);
  17284. },
  17285. _ordinal : "%d",
  17286. preparse : function (string) {
  17287. return string;
  17288. },
  17289. postformat : function (string) {
  17290. return string;
  17291. },
  17292. week : function (mom) {
  17293. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  17294. },
  17295. _week : {
  17296. dow : 0, // Sunday is the first day of the week.
  17297. doy : 6 // The week that contains Jan 1st is the first week of the year.
  17298. },
  17299. _invalidDate: 'Invalid date',
  17300. invalidDate: function () {
  17301. return this._invalidDate;
  17302. }
  17303. });
  17304. // Loads a language definition into the `languages` cache. The function
  17305. // takes a key and optionally values. If not in the browser and no values
  17306. // are provided, it will load the language file module. As a convenience,
  17307. // this function also returns the language values.
  17308. function loadLang(key, values) {
  17309. values.abbr = key;
  17310. if (!languages[key]) {
  17311. languages[key] = new Language();
  17312. }
  17313. languages[key].set(values);
  17314. return languages[key];
  17315. }
  17316. // Remove a language from the `languages` cache. Mostly useful in tests.
  17317. function unloadLang(key) {
  17318. delete languages[key];
  17319. }
  17320. // Determines which language definition to use and returns it.
  17321. //
  17322. // With no parameters, it will return the global language. If you
  17323. // pass in a language key, such as 'en', it will return the
  17324. // definition for 'en', so long as 'en' has already been loaded using
  17325. // moment.lang.
  17326. function getLangDefinition(key) {
  17327. var i = 0, j, lang, next, split,
  17328. get = function (k) {
  17329. if (!languages[k] && hasModule) {
  17330. try {
  17331. require('./lang/' + k);
  17332. } catch (e) { }
  17333. }
  17334. return languages[k];
  17335. };
  17336. if (!key) {
  17337. return moment.fn._lang;
  17338. }
  17339. if (!isArray(key)) {
  17340. //short-circuit everything else
  17341. lang = get(key);
  17342. if (lang) {
  17343. return lang;
  17344. }
  17345. key = [key];
  17346. }
  17347. //pick the language from the array
  17348. //try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
  17349. //substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
  17350. while (i < key.length) {
  17351. split = normalizeLanguage(key[i]).split('-');
  17352. j = split.length;
  17353. next = normalizeLanguage(key[i + 1]);
  17354. next = next ? next.split('-') : null;
  17355. while (j > 0) {
  17356. lang = get(split.slice(0, j).join('-'));
  17357. if (lang) {
  17358. return lang;
  17359. }
  17360. if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
  17361. //the next array item is better than a shallower substring of this one
  17362. break;
  17363. }
  17364. j--;
  17365. }
  17366. i++;
  17367. }
  17368. return moment.fn._lang;
  17369. }
  17370. /************************************
  17371. Formatting
  17372. ************************************/
  17373. function removeFormattingTokens(input) {
  17374. if (input.match(/\[[\s\S]/)) {
  17375. return input.replace(/^\[|\]$/g, "");
  17376. }
  17377. return input.replace(/\\/g, "");
  17378. }
  17379. function makeFormatFunction(format) {
  17380. var array = format.match(formattingTokens), i, length;
  17381. for (i = 0, length = array.length; i < length; i++) {
  17382. if (formatTokenFunctions[array[i]]) {
  17383. array[i] = formatTokenFunctions[array[i]];
  17384. } else {
  17385. array[i] = removeFormattingTokens(array[i]);
  17386. }
  17387. }
  17388. return function (mom) {
  17389. var output = "";
  17390. for (i = 0; i < length; i++) {
  17391. output += array[i] instanceof Function ? array[i].call(mom, format) : array[i];
  17392. }
  17393. return output;
  17394. };
  17395. }
  17396. // format date using native date object
  17397. function formatMoment(m, format) {
  17398. if (!m.isValid()) {
  17399. return m.lang().invalidDate();
  17400. }
  17401. format = expandFormat(format, m.lang());
  17402. if (!formatFunctions[format]) {
  17403. formatFunctions[format] = makeFormatFunction(format);
  17404. }
  17405. return formatFunctions[format](m);
  17406. }
  17407. function expandFormat(format, lang) {
  17408. var i = 5;
  17409. function replaceLongDateFormatTokens(input) {
  17410. return lang.longDateFormat(input) || input;
  17411. }
  17412. localFormattingTokens.lastIndex = 0;
  17413. while (i >= 0 && localFormattingTokens.test(format)) {
  17414. format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
  17415. localFormattingTokens.lastIndex = 0;
  17416. i -= 1;
  17417. }
  17418. return format;
  17419. }
  17420. /************************************
  17421. Parsing
  17422. ************************************/
  17423. // get the regex to find the next token
  17424. function getParseRegexForToken(token, config) {
  17425. var a, strict = config._strict;
  17426. switch (token) {
  17427. case 'DDDD':
  17428. return parseTokenThreeDigits;
  17429. case 'YYYY':
  17430. case 'GGGG':
  17431. case 'gggg':
  17432. return strict ? parseTokenFourDigits : parseTokenOneToFourDigits;
  17433. case 'Y':
  17434. case 'G':
  17435. case 'g':
  17436. return parseTokenSignedNumber;
  17437. case 'YYYYYY':
  17438. case 'YYYYY':
  17439. case 'GGGGG':
  17440. case 'ggggg':
  17441. return strict ? parseTokenSixDigits : parseTokenOneToSixDigits;
  17442. case 'S':
  17443. if (strict) { return parseTokenOneDigit; }
  17444. /* falls through */
  17445. case 'SS':
  17446. if (strict) { return parseTokenTwoDigits; }
  17447. /* falls through */
  17448. case 'SSS':
  17449. if (strict) { return parseTokenThreeDigits; }
  17450. /* falls through */
  17451. case 'DDD':
  17452. return parseTokenOneToThreeDigits;
  17453. case 'MMM':
  17454. case 'MMMM':
  17455. case 'dd':
  17456. case 'ddd':
  17457. case 'dddd':
  17458. return parseTokenWord;
  17459. case 'a':
  17460. case 'A':
  17461. return getLangDefinition(config._l)._meridiemParse;
  17462. case 'X':
  17463. return parseTokenTimestampMs;
  17464. case 'Z':
  17465. case 'ZZ':
  17466. return parseTokenTimezone;
  17467. case 'T':
  17468. return parseTokenT;
  17469. case 'SSSS':
  17470. return parseTokenDigits;
  17471. case 'MM':
  17472. case 'DD':
  17473. case 'YY':
  17474. case 'GG':
  17475. case 'gg':
  17476. case 'HH':
  17477. case 'hh':
  17478. case 'mm':
  17479. case 'ss':
  17480. case 'ww':
  17481. case 'WW':
  17482. return strict ? parseTokenTwoDigits : parseTokenOneOrTwoDigits;
  17483. case 'M':
  17484. case 'D':
  17485. case 'd':
  17486. case 'H':
  17487. case 'h':
  17488. case 'm':
  17489. case 's':
  17490. case 'w':
  17491. case 'W':
  17492. case 'e':
  17493. case 'E':
  17494. return parseTokenOneOrTwoDigits;
  17495. default :
  17496. a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), "i"));
  17497. return a;
  17498. }
  17499. }
  17500. function timezoneMinutesFromString(string) {
  17501. string = string || "";
  17502. var possibleTzMatches = (string.match(parseTokenTimezone) || []),
  17503. tzChunk = possibleTzMatches[possibleTzMatches.length - 1] || [],
  17504. parts = (tzChunk + '').match(parseTimezoneChunker) || ['-', 0, 0],
  17505. minutes = +(parts[1] * 60) + toInt(parts[2]);
  17506. return parts[0] === '+' ? -minutes : minutes;
  17507. }
  17508. // function to convert string input to date
  17509. function addTimeToArrayFromToken(token, input, config) {
  17510. var a, datePartArray = config._a;
  17511. switch (token) {
  17512. // MONTH
  17513. case 'M' : // fall through to MM
  17514. case 'MM' :
  17515. if (input != null) {
  17516. datePartArray[MONTH] = toInt(input) - 1;
  17517. }
  17518. break;
  17519. case 'MMM' : // fall through to MMMM
  17520. case 'MMMM' :
  17521. a = getLangDefinition(config._l).monthsParse(input);
  17522. // if we didn't find a month name, mark the date as invalid.
  17523. if (a != null) {
  17524. datePartArray[MONTH] = a;
  17525. } else {
  17526. config._pf.invalidMonth = input;
  17527. }
  17528. break;
  17529. // DAY OF MONTH
  17530. case 'D' : // fall through to DD
  17531. case 'DD' :
  17532. if (input != null) {
  17533. datePartArray[DATE] = toInt(input);
  17534. }
  17535. break;
  17536. // DAY OF YEAR
  17537. case 'DDD' : // fall through to DDDD
  17538. case 'DDDD' :
  17539. if (input != null) {
  17540. config._dayOfYear = toInt(input);
  17541. }
  17542. break;
  17543. // YEAR
  17544. case 'YY' :
  17545. datePartArray[YEAR] = toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
  17546. break;
  17547. case 'YYYY' :
  17548. case 'YYYYY' :
  17549. case 'YYYYYY' :
  17550. datePartArray[YEAR] = toInt(input);
  17551. break;
  17552. // AM / PM
  17553. case 'a' : // fall through to A
  17554. case 'A' :
  17555. config._isPm = getLangDefinition(config._l).isPM(input);
  17556. break;
  17557. // 24 HOUR
  17558. case 'H' : // fall through to hh
  17559. case 'HH' : // fall through to hh
  17560. case 'h' : // fall through to hh
  17561. case 'hh' :
  17562. datePartArray[HOUR] = toInt(input);
  17563. break;
  17564. // MINUTE
  17565. case 'm' : // fall through to mm
  17566. case 'mm' :
  17567. datePartArray[MINUTE] = toInt(input);
  17568. break;
  17569. // SECOND
  17570. case 's' : // fall through to ss
  17571. case 'ss' :
  17572. datePartArray[SECOND] = toInt(input);
  17573. break;
  17574. // MILLISECOND
  17575. case 'S' :
  17576. case 'SS' :
  17577. case 'SSS' :
  17578. case 'SSSS' :
  17579. datePartArray[MILLISECOND] = toInt(('0.' + input) * 1000);
  17580. break;
  17581. // UNIX TIMESTAMP WITH MS
  17582. case 'X':
  17583. config._d = new Date(parseFloat(input) * 1000);
  17584. break;
  17585. // TIMEZONE
  17586. case 'Z' : // fall through to ZZ
  17587. case 'ZZ' :
  17588. config._useUTC = true;
  17589. config._tzm = timezoneMinutesFromString(input);
  17590. break;
  17591. case 'w':
  17592. case 'ww':
  17593. case 'W':
  17594. case 'WW':
  17595. case 'd':
  17596. case 'dd':
  17597. case 'ddd':
  17598. case 'dddd':
  17599. case 'e':
  17600. case 'E':
  17601. token = token.substr(0, 1);
  17602. /* falls through */
  17603. case 'gg':
  17604. case 'gggg':
  17605. case 'GG':
  17606. case 'GGGG':
  17607. case 'GGGGG':
  17608. token = token.substr(0, 2);
  17609. if (input) {
  17610. config._w = config._w || {};
  17611. config._w[token] = input;
  17612. }
  17613. break;
  17614. }
  17615. }
  17616. // convert an array to a date.
  17617. // the array should mirror the parameters below
  17618. // note: all values past the year are optional and will default to the lowest possible value.
  17619. // [year, month, day , hour, minute, second, millisecond]
  17620. function dateFromConfig(config) {
  17621. var i, date, input = [], currentDate,
  17622. yearToUse, fixYear, w, temp, lang, weekday, week;
  17623. if (config._d) {
  17624. return;
  17625. }
  17626. currentDate = currentDateArray(config);
  17627. //compute day of the year from weeks and weekdays
  17628. if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
  17629. fixYear = function (val) {
  17630. var int_val = parseInt(val, 10);
  17631. return val ?
  17632. (val.length < 3 ? (int_val > 68 ? 1900 + int_val : 2000 + int_val) : int_val) :
  17633. (config._a[YEAR] == null ? moment().weekYear() : config._a[YEAR]);
  17634. };
  17635. w = config._w;
  17636. if (w.GG != null || w.W != null || w.E != null) {
  17637. temp = dayOfYearFromWeeks(fixYear(w.GG), w.W || 1, w.E, 4, 1);
  17638. }
  17639. else {
  17640. lang = getLangDefinition(config._l);
  17641. weekday = w.d != null ? parseWeekday(w.d, lang) :
  17642. (w.e != null ? parseInt(w.e, 10) + lang._week.dow : 0);
  17643. week = parseInt(w.w, 10) || 1;
  17644. //if we're parsing 'd', then the low day numbers may be next week
  17645. if (w.d != null && weekday < lang._week.dow) {
  17646. week++;
  17647. }
  17648. temp = dayOfYearFromWeeks(fixYear(w.gg), week, weekday, lang._week.doy, lang._week.dow);
  17649. }
  17650. config._a[YEAR] = temp.year;
  17651. config._dayOfYear = temp.dayOfYear;
  17652. }
  17653. //if the day of the year is set, figure out what it is
  17654. if (config._dayOfYear) {
  17655. yearToUse = config._a[YEAR] == null ? currentDate[YEAR] : config._a[YEAR];
  17656. if (config._dayOfYear > daysInYear(yearToUse)) {
  17657. config._pf._overflowDayOfYear = true;
  17658. }
  17659. date = makeUTCDate(yearToUse, 0, config._dayOfYear);
  17660. config._a[MONTH] = date.getUTCMonth();
  17661. config._a[DATE] = date.getUTCDate();
  17662. }
  17663. // Default to current date.
  17664. // * if no year, month, day of month are given, default to today
  17665. // * if day of month is given, default month and year
  17666. // * if month is given, default only year
  17667. // * if year is given, don't default anything
  17668. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  17669. config._a[i] = input[i] = currentDate[i];
  17670. }
  17671. // Zero out whatever was not defaulted, including time
  17672. for (; i < 7; i++) {
  17673. config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
  17674. }
  17675. // add the offsets to the time to be parsed so that we can have a clean array for checking isValid
  17676. input[HOUR] += toInt((config._tzm || 0) / 60);
  17677. input[MINUTE] += toInt((config._tzm || 0) % 60);
  17678. config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input);
  17679. }
  17680. function dateFromObject(config) {
  17681. var normalizedInput;
  17682. if (config._d) {
  17683. return;
  17684. }
  17685. normalizedInput = normalizeObjectUnits(config._i);
  17686. config._a = [
  17687. normalizedInput.year,
  17688. normalizedInput.month,
  17689. normalizedInput.day,
  17690. normalizedInput.hour,
  17691. normalizedInput.minute,
  17692. normalizedInput.second,
  17693. normalizedInput.millisecond
  17694. ];
  17695. dateFromConfig(config);
  17696. }
  17697. function currentDateArray(config) {
  17698. var now = new Date();
  17699. if (config._useUTC) {
  17700. return [
  17701. now.getUTCFullYear(),
  17702. now.getUTCMonth(),
  17703. now.getUTCDate()
  17704. ];
  17705. } else {
  17706. return [now.getFullYear(), now.getMonth(), now.getDate()];
  17707. }
  17708. }
  17709. // date from string and format string
  17710. function makeDateFromStringAndFormat(config) {
  17711. config._a = [];
  17712. config._pf.empty = true;
  17713. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  17714. var lang = getLangDefinition(config._l),
  17715. string = '' + config._i,
  17716. i, parsedInput, tokens, token, skipped,
  17717. stringLength = string.length,
  17718. totalParsedInputLength = 0;
  17719. tokens = expandFormat(config._f, lang).match(formattingTokens) || [];
  17720. for (i = 0; i < tokens.length; i++) {
  17721. token = tokens[i];
  17722. parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
  17723. if (parsedInput) {
  17724. skipped = string.substr(0, string.indexOf(parsedInput));
  17725. if (skipped.length > 0) {
  17726. config._pf.unusedInput.push(skipped);
  17727. }
  17728. string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
  17729. totalParsedInputLength += parsedInput.length;
  17730. }
  17731. // don't parse if it's not a known token
  17732. if (formatTokenFunctions[token]) {
  17733. if (parsedInput) {
  17734. config._pf.empty = false;
  17735. }
  17736. else {
  17737. config._pf.unusedTokens.push(token);
  17738. }
  17739. addTimeToArrayFromToken(token, parsedInput, config);
  17740. }
  17741. else if (config._strict && !parsedInput) {
  17742. config._pf.unusedTokens.push(token);
  17743. }
  17744. }
  17745. // add remaining unparsed input length to the string
  17746. config._pf.charsLeftOver = stringLength - totalParsedInputLength;
  17747. if (string.length > 0) {
  17748. config._pf.unusedInput.push(string);
  17749. }
  17750. // handle am pm
  17751. if (config._isPm && config._a[HOUR] < 12) {
  17752. config._a[HOUR] += 12;
  17753. }
  17754. // if is 12 am, change hours to 0
  17755. if (config._isPm === false && config._a[HOUR] === 12) {
  17756. config._a[HOUR] = 0;
  17757. }
  17758. dateFromConfig(config);
  17759. checkOverflow(config);
  17760. }
  17761. function unescapeFormat(s) {
  17762. return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
  17763. return p1 || p2 || p3 || p4;
  17764. });
  17765. }
  17766. // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  17767. function regexpEscape(s) {
  17768. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  17769. }
  17770. // date from string and array of format strings
  17771. function makeDateFromStringAndArray(config) {
  17772. var tempConfig,
  17773. bestMoment,
  17774. scoreToBeat,
  17775. i,
  17776. currentScore;
  17777. if (config._f.length === 0) {
  17778. config._pf.invalidFormat = true;
  17779. config._d = new Date(NaN);
  17780. return;
  17781. }
  17782. for (i = 0; i < config._f.length; i++) {
  17783. currentScore = 0;
  17784. tempConfig = extend({}, config);
  17785. tempConfig._pf = defaultParsingFlags();
  17786. tempConfig._f = config._f[i];
  17787. makeDateFromStringAndFormat(tempConfig);
  17788. if (!isValid(tempConfig)) {
  17789. continue;
  17790. }
  17791. // if there is any input that was not parsed add a penalty for that format
  17792. currentScore += tempConfig._pf.charsLeftOver;
  17793. //or tokens
  17794. currentScore += tempConfig._pf.unusedTokens.length * 10;
  17795. tempConfig._pf.score = currentScore;
  17796. if (scoreToBeat == null || currentScore < scoreToBeat) {
  17797. scoreToBeat = currentScore;
  17798. bestMoment = tempConfig;
  17799. }
  17800. }
  17801. extend(config, bestMoment || tempConfig);
  17802. }
  17803. // date from iso format
  17804. function makeDateFromString(config) {
  17805. var i, l,
  17806. string = config._i,
  17807. match = isoRegex.exec(string);
  17808. if (match) {
  17809. config._pf.iso = true;
  17810. for (i = 0, l = isoDates.length; i < l; i++) {
  17811. if (isoDates[i][1].exec(string)) {
  17812. // match[5] should be "T" or undefined
  17813. config._f = isoDates[i][0] + (match[6] || " ");
  17814. break;
  17815. }
  17816. }
  17817. for (i = 0, l = isoTimes.length; i < l; i++) {
  17818. if (isoTimes[i][1].exec(string)) {
  17819. config._f += isoTimes[i][0];
  17820. break;
  17821. }
  17822. }
  17823. if (string.match(parseTokenTimezone)) {
  17824. config._f += "Z";
  17825. }
  17826. makeDateFromStringAndFormat(config);
  17827. }
  17828. else {
  17829. config._d = new Date(string);
  17830. }
  17831. }
  17832. function makeDateFromInput(config) {
  17833. var input = config._i,
  17834. matched = aspNetJsonRegex.exec(input);
  17835. if (input === undefined) {
  17836. config._d = new Date();
  17837. } else if (matched) {
  17838. config._d = new Date(+matched[1]);
  17839. } else if (typeof input === 'string') {
  17840. makeDateFromString(config);
  17841. } else if (isArray(input)) {
  17842. config._a = input.slice(0);
  17843. dateFromConfig(config);
  17844. } else if (isDate(input)) {
  17845. config._d = new Date(+input);
  17846. } else if (typeof(input) === 'object') {
  17847. dateFromObject(config);
  17848. } else {
  17849. config._d = new Date(input);
  17850. }
  17851. }
  17852. function makeDate(y, m, d, h, M, s, ms) {
  17853. //can't just apply() to create a date:
  17854. //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply
  17855. var date = new Date(y, m, d, h, M, s, ms);
  17856. //the date constructor doesn't accept years < 1970
  17857. if (y < 1970) {
  17858. date.setFullYear(y);
  17859. }
  17860. return date;
  17861. }
  17862. function makeUTCDate(y) {
  17863. var date = new Date(Date.UTC.apply(null, arguments));
  17864. if (y < 1970) {
  17865. date.setUTCFullYear(y);
  17866. }
  17867. return date;
  17868. }
  17869. function parseWeekday(input, language) {
  17870. if (typeof input === 'string') {
  17871. if (!isNaN(input)) {
  17872. input = parseInt(input, 10);
  17873. }
  17874. else {
  17875. input = language.weekdaysParse(input);
  17876. if (typeof input !== 'number') {
  17877. return null;
  17878. }
  17879. }
  17880. }
  17881. return input;
  17882. }
  17883. /************************************
  17884. Relative Time
  17885. ************************************/
  17886. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  17887. function substituteTimeAgo(string, number, withoutSuffix, isFuture, lang) {
  17888. return lang.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  17889. }
  17890. function relativeTime(milliseconds, withoutSuffix, lang) {
  17891. var seconds = round(Math.abs(milliseconds) / 1000),
  17892. minutes = round(seconds / 60),
  17893. hours = round(minutes / 60),
  17894. days = round(hours / 24),
  17895. years = round(days / 365),
  17896. args = seconds < 45 && ['s', seconds] ||
  17897. minutes === 1 && ['m'] ||
  17898. minutes < 45 && ['mm', minutes] ||
  17899. hours === 1 && ['h'] ||
  17900. hours < 22 && ['hh', hours] ||
  17901. days === 1 && ['d'] ||
  17902. days <= 25 && ['dd', days] ||
  17903. days <= 45 && ['M'] ||
  17904. days < 345 && ['MM', round(days / 30)] ||
  17905. years === 1 && ['y'] || ['yy', years];
  17906. args[2] = withoutSuffix;
  17907. args[3] = milliseconds > 0;
  17908. args[4] = lang;
  17909. return substituteTimeAgo.apply({}, args);
  17910. }
  17911. /************************************
  17912. Week of Year
  17913. ************************************/
  17914. // firstDayOfWeek 0 = sun, 6 = sat
  17915. // the day of the week that starts the week
  17916. // (usually sunday or monday)
  17917. // firstDayOfWeekOfYear 0 = sun, 6 = sat
  17918. // the first week is the week that contains the first
  17919. // of this day of the week
  17920. // (eg. ISO weeks use thursday (4))
  17921. function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) {
  17922. var end = firstDayOfWeekOfYear - firstDayOfWeek,
  17923. daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(),
  17924. adjustedMoment;
  17925. if (daysToDayOfWeek > end) {
  17926. daysToDayOfWeek -= 7;
  17927. }
  17928. if (daysToDayOfWeek < end - 7) {
  17929. daysToDayOfWeek += 7;
  17930. }
  17931. adjustedMoment = moment(mom).add('d', daysToDayOfWeek);
  17932. return {
  17933. week: Math.ceil(adjustedMoment.dayOfYear() / 7),
  17934. year: adjustedMoment.year()
  17935. };
  17936. }
  17937. //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
  17938. function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) {
  17939. var d = makeUTCDate(year, 0, 1).getUTCDay(), daysToAdd, dayOfYear;
  17940. weekday = weekday != null ? weekday : firstDayOfWeek;
  17941. daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0);
  17942. dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1;
  17943. return {
  17944. year: dayOfYear > 0 ? year : year - 1,
  17945. dayOfYear: dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear
  17946. };
  17947. }
  17948. /************************************
  17949. Top Level Functions
  17950. ************************************/
  17951. function makeMoment(config) {
  17952. var input = config._i,
  17953. format = config._f;
  17954. if (input === null) {
  17955. return moment.invalid({nullInput: true});
  17956. }
  17957. if (typeof input === 'string') {
  17958. config._i = input = getLangDefinition().preparse(input);
  17959. }
  17960. if (moment.isMoment(input)) {
  17961. config = cloneMoment(input);
  17962. config._d = new Date(+input._d);
  17963. } else if (format) {
  17964. if (isArray(format)) {
  17965. makeDateFromStringAndArray(config);
  17966. } else {
  17967. makeDateFromStringAndFormat(config);
  17968. }
  17969. } else {
  17970. makeDateFromInput(config);
  17971. }
  17972. return new Moment(config);
  17973. }
  17974. moment = function (input, format, lang, strict) {
  17975. var c;
  17976. if (typeof(lang) === "boolean") {
  17977. strict = lang;
  17978. lang = undefined;
  17979. }
  17980. // object construction must be done this way.
  17981. // https://github.com/moment/moment/issues/1423
  17982. c = {};
  17983. c._isAMomentObject = true;
  17984. c._i = input;
  17985. c._f = format;
  17986. c._l = lang;
  17987. c._strict = strict;
  17988. c._isUTC = false;
  17989. c._pf = defaultParsingFlags();
  17990. return makeMoment(c);
  17991. };
  17992. // creating with utc
  17993. moment.utc = function (input, format, lang, strict) {
  17994. var c;
  17995. if (typeof(lang) === "boolean") {
  17996. strict = lang;
  17997. lang = undefined;
  17998. }
  17999. // object construction must be done this way.
  18000. // https://github.com/moment/moment/issues/1423
  18001. c = {};
  18002. c._isAMomentObject = true;
  18003. c._useUTC = true;
  18004. c._isUTC = true;
  18005. c._l = lang;
  18006. c._i = input;
  18007. c._f = format;
  18008. c._strict = strict;
  18009. c._pf = defaultParsingFlags();
  18010. return makeMoment(c).utc();
  18011. };
  18012. // creating with unix timestamp (in seconds)
  18013. moment.unix = function (input) {
  18014. return moment(input * 1000);
  18015. };
  18016. // duration
  18017. moment.duration = function (input, key) {
  18018. var duration = input,
  18019. // matching against regexp is expensive, do it on demand
  18020. match = null,
  18021. sign,
  18022. ret,
  18023. parseIso;
  18024. if (moment.isDuration(input)) {
  18025. duration = {
  18026. ms: input._milliseconds,
  18027. d: input._days,
  18028. M: input._months
  18029. };
  18030. } else if (typeof input === 'number') {
  18031. duration = {};
  18032. if (key) {
  18033. duration[key] = input;
  18034. } else {
  18035. duration.milliseconds = input;
  18036. }
  18037. } else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) {
  18038. sign = (match[1] === "-") ? -1 : 1;
  18039. duration = {
  18040. y: 0,
  18041. d: toInt(match[DATE]) * sign,
  18042. h: toInt(match[HOUR]) * sign,
  18043. m: toInt(match[MINUTE]) * sign,
  18044. s: toInt(match[SECOND]) * sign,
  18045. ms: toInt(match[MILLISECOND]) * sign
  18046. };
  18047. } else if (!!(match = isoDurationRegex.exec(input))) {
  18048. sign = (match[1] === "-") ? -1 : 1;
  18049. parseIso = function (inp) {
  18050. // We'd normally use ~~inp for this, but unfortunately it also
  18051. // converts floats to ints.
  18052. // inp may be undefined, so careful calling replace on it.
  18053. var res = inp && parseFloat(inp.replace(',', '.'));
  18054. // apply sign while we're at it
  18055. return (isNaN(res) ? 0 : res) * sign;
  18056. };
  18057. duration = {
  18058. y: parseIso(match[2]),
  18059. M: parseIso(match[3]),
  18060. d: parseIso(match[4]),
  18061. h: parseIso(match[5]),
  18062. m: parseIso(match[6]),
  18063. s: parseIso(match[7]),
  18064. w: parseIso(match[8])
  18065. };
  18066. }
  18067. ret = new Duration(duration);
  18068. if (moment.isDuration(input) && input.hasOwnProperty('_lang')) {
  18069. ret._lang = input._lang;
  18070. }
  18071. return ret;
  18072. };
  18073. // version number
  18074. moment.version = VERSION;
  18075. // default format
  18076. moment.defaultFormat = isoFormat;
  18077. // This function will be called whenever a moment is mutated.
  18078. // It is intended to keep the offset in sync with the timezone.
  18079. moment.updateOffset = function () {};
  18080. // This function will load languages and then set the global language. If
  18081. // no arguments are passed in, it will simply return the current global
  18082. // language key.
  18083. moment.lang = function (key, values) {
  18084. var r;
  18085. if (!key) {
  18086. return moment.fn._lang._abbr;
  18087. }
  18088. if (values) {
  18089. loadLang(normalizeLanguage(key), values);
  18090. } else if (values === null) {
  18091. unloadLang(key);
  18092. key = 'en';
  18093. } else if (!languages[key]) {
  18094. getLangDefinition(key);
  18095. }
  18096. r = moment.duration.fn._lang = moment.fn._lang = getLangDefinition(key);
  18097. return r._abbr;
  18098. };
  18099. // returns language data
  18100. moment.langData = function (key) {
  18101. if (key && key._lang && key._lang._abbr) {
  18102. key = key._lang._abbr;
  18103. }
  18104. return getLangDefinition(key);
  18105. };
  18106. // compare moment object
  18107. moment.isMoment = function (obj) {
  18108. return obj instanceof Moment ||
  18109. (obj != null && obj.hasOwnProperty('_isAMomentObject'));
  18110. };
  18111. // for typechecking Duration objects
  18112. moment.isDuration = function (obj) {
  18113. return obj instanceof Duration;
  18114. };
  18115. for (i = lists.length - 1; i >= 0; --i) {
  18116. makeList(lists[i]);
  18117. }
  18118. moment.normalizeUnits = function (units) {
  18119. return normalizeUnits(units);
  18120. };
  18121. moment.invalid = function (flags) {
  18122. var m = moment.utc(NaN);
  18123. if (flags != null) {
  18124. extend(m._pf, flags);
  18125. }
  18126. else {
  18127. m._pf.userInvalidated = true;
  18128. }
  18129. return m;
  18130. };
  18131. moment.parseZone = function (input) {
  18132. return moment(input).parseZone();
  18133. };
  18134. /************************************
  18135. Moment Prototype
  18136. ************************************/
  18137. extend(moment.fn = Moment.prototype, {
  18138. clone : function () {
  18139. return moment(this);
  18140. },
  18141. valueOf : function () {
  18142. return +this._d + ((this._offset || 0) * 60000);
  18143. },
  18144. unix : function () {
  18145. return Math.floor(+this / 1000);
  18146. },
  18147. toString : function () {
  18148. return this.clone().lang('en').format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ");
  18149. },
  18150. toDate : function () {
  18151. return this._offset ? new Date(+this) : this._d;
  18152. },
  18153. toISOString : function () {
  18154. var m = moment(this).utc();
  18155. if (0 < m.year() && m.year() <= 9999) {
  18156. return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  18157. } else {
  18158. return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  18159. }
  18160. },
  18161. toArray : function () {
  18162. var m = this;
  18163. return [
  18164. m.year(),
  18165. m.month(),
  18166. m.date(),
  18167. m.hours(),
  18168. m.minutes(),
  18169. m.seconds(),
  18170. m.milliseconds()
  18171. ];
  18172. },
  18173. isValid : function () {
  18174. return isValid(this);
  18175. },
  18176. isDSTShifted : function () {
  18177. if (this._a) {
  18178. return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0;
  18179. }
  18180. return false;
  18181. },
  18182. parsingFlags : function () {
  18183. return extend({}, this._pf);
  18184. },
  18185. invalidAt: function () {
  18186. return this._pf.overflow;
  18187. },
  18188. utc : function () {
  18189. return this.zone(0);
  18190. },
  18191. local : function () {
  18192. this.zone(0);
  18193. this._isUTC = false;
  18194. return this;
  18195. },
  18196. format : function (inputString) {
  18197. var output = formatMoment(this, inputString || moment.defaultFormat);
  18198. return this.lang().postformat(output);
  18199. },
  18200. add : function (input, val) {
  18201. var dur;
  18202. // switch args to support add('s', 1) and add(1, 's')
  18203. if (typeof input === 'string') {
  18204. dur = moment.duration(+val, input);
  18205. } else {
  18206. dur = moment.duration(input, val);
  18207. }
  18208. addOrSubtractDurationFromMoment(this, dur, 1);
  18209. return this;
  18210. },
  18211. subtract : function (input, val) {
  18212. var dur;
  18213. // switch args to support subtract('s', 1) and subtract(1, 's')
  18214. if (typeof input === 'string') {
  18215. dur = moment.duration(+val, input);
  18216. } else {
  18217. dur = moment.duration(input, val);
  18218. }
  18219. addOrSubtractDurationFromMoment(this, dur, -1);
  18220. return this;
  18221. },
  18222. diff : function (input, units, asFloat) {
  18223. var that = makeAs(input, this),
  18224. zoneDiff = (this.zone() - that.zone()) * 6e4,
  18225. diff, output;
  18226. units = normalizeUnits(units);
  18227. if (units === 'year' || units === 'month') {
  18228. // average number of days in the months in the given dates
  18229. diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2
  18230. // difference in months
  18231. output = ((this.year() - that.year()) * 12) + (this.month() - that.month());
  18232. // adjust by taking difference in days, average number of days
  18233. // and dst in the given months.
  18234. output += ((this - moment(this).startOf('month')) -
  18235. (that - moment(that).startOf('month'))) / diff;
  18236. // same as above but with zones, to negate all dst
  18237. output -= ((this.zone() - moment(this).startOf('month').zone()) -
  18238. (that.zone() - moment(that).startOf('month').zone())) * 6e4 / diff;
  18239. if (units === 'year') {
  18240. output = output / 12;
  18241. }
  18242. } else {
  18243. diff = (this - that);
  18244. output = units === 'second' ? diff / 1e3 : // 1000
  18245. units === 'minute' ? diff / 6e4 : // 1000 * 60
  18246. units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60
  18247. units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
  18248. units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
  18249. diff;
  18250. }
  18251. return asFloat ? output : absRound(output);
  18252. },
  18253. from : function (time, withoutSuffix) {
  18254. return moment.duration(this.diff(time)).lang(this.lang()._abbr).humanize(!withoutSuffix);
  18255. },
  18256. fromNow : function (withoutSuffix) {
  18257. return this.from(moment(), withoutSuffix);
  18258. },
  18259. calendar : function () {
  18260. // We want to compare the start of today, vs this.
  18261. // Getting start-of-today depends on whether we're zone'd or not.
  18262. var sod = makeAs(moment(), this).startOf('day'),
  18263. diff = this.diff(sod, 'days', true),
  18264. format = diff < -6 ? 'sameElse' :
  18265. diff < -1 ? 'lastWeek' :
  18266. diff < 0 ? 'lastDay' :
  18267. diff < 1 ? 'sameDay' :
  18268. diff < 2 ? 'nextDay' :
  18269. diff < 7 ? 'nextWeek' : 'sameElse';
  18270. return this.format(this.lang().calendar(format, this));
  18271. },
  18272. isLeapYear : function () {
  18273. return isLeapYear(this.year());
  18274. },
  18275. isDST : function () {
  18276. return (this.zone() < this.clone().month(0).zone() ||
  18277. this.zone() < this.clone().month(5).zone());
  18278. },
  18279. day : function (input) {
  18280. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  18281. if (input != null) {
  18282. input = parseWeekday(input, this.lang());
  18283. return this.add({ d : input - day });
  18284. } else {
  18285. return day;
  18286. }
  18287. },
  18288. month : function (input) {
  18289. var utc = this._isUTC ? 'UTC' : '',
  18290. dayOfMonth;
  18291. if (input != null) {
  18292. if (typeof input === 'string') {
  18293. input = this.lang().monthsParse(input);
  18294. if (typeof input !== 'number') {
  18295. return this;
  18296. }
  18297. }
  18298. dayOfMonth = this.date();
  18299. this.date(1);
  18300. this._d['set' + utc + 'Month'](input);
  18301. this.date(Math.min(dayOfMonth, this.daysInMonth()));
  18302. moment.updateOffset(this);
  18303. return this;
  18304. } else {
  18305. return this._d['get' + utc + 'Month']();
  18306. }
  18307. },
  18308. startOf: function (units) {
  18309. units = normalizeUnits(units);
  18310. // the following switch intentionally omits break keywords
  18311. // to utilize falling through the cases.
  18312. switch (units) {
  18313. case 'year':
  18314. this.month(0);
  18315. /* falls through */
  18316. case 'month':
  18317. this.date(1);
  18318. /* falls through */
  18319. case 'week':
  18320. case 'isoWeek':
  18321. case 'day':
  18322. this.hours(0);
  18323. /* falls through */
  18324. case 'hour':
  18325. this.minutes(0);
  18326. /* falls through */
  18327. case 'minute':
  18328. this.seconds(0);
  18329. /* falls through */
  18330. case 'second':
  18331. this.milliseconds(0);
  18332. /* falls through */
  18333. }
  18334. // weeks are a special case
  18335. if (units === 'week') {
  18336. this.weekday(0);
  18337. } else if (units === 'isoWeek') {
  18338. this.isoWeekday(1);
  18339. }
  18340. return this;
  18341. },
  18342. endOf: function (units) {
  18343. units = normalizeUnits(units);
  18344. return this.startOf(units).add((units === 'isoWeek' ? 'week' : units), 1).subtract('ms', 1);
  18345. },
  18346. isAfter: function (input, units) {
  18347. units = typeof units !== 'undefined' ? units : 'millisecond';
  18348. return +this.clone().startOf(units) > +moment(input).startOf(units);
  18349. },
  18350. isBefore: function (input, units) {
  18351. units = typeof units !== 'undefined' ? units : 'millisecond';
  18352. return +this.clone().startOf(units) < +moment(input).startOf(units);
  18353. },
  18354. isSame: function (input, units) {
  18355. units = units || 'ms';
  18356. return +this.clone().startOf(units) === +makeAs(input, this).startOf(units);
  18357. },
  18358. min: function (other) {
  18359. other = moment.apply(null, arguments);
  18360. return other < this ? this : other;
  18361. },
  18362. max: function (other) {
  18363. other = moment.apply(null, arguments);
  18364. return other > this ? this : other;
  18365. },
  18366. zone : function (input) {
  18367. var offset = this._offset || 0;
  18368. if (input != null) {
  18369. if (typeof input === "string") {
  18370. input = timezoneMinutesFromString(input);
  18371. }
  18372. if (Math.abs(input) < 16) {
  18373. input = input * 60;
  18374. }
  18375. this._offset = input;
  18376. this._isUTC = true;
  18377. if (offset !== input) {
  18378. addOrSubtractDurationFromMoment(this, moment.duration(offset - input, 'm'), 1, true);
  18379. }
  18380. } else {
  18381. return this._isUTC ? offset : this._d.getTimezoneOffset();
  18382. }
  18383. return this;
  18384. },
  18385. zoneAbbr : function () {
  18386. return this._isUTC ? "UTC" : "";
  18387. },
  18388. zoneName : function () {
  18389. return this._isUTC ? "Coordinated Universal Time" : "";
  18390. },
  18391. parseZone : function () {
  18392. if (this._tzm) {
  18393. this.zone(this._tzm);
  18394. } else if (typeof this._i === 'string') {
  18395. this.zone(this._i);
  18396. }
  18397. return this;
  18398. },
  18399. hasAlignedHourOffset : function (input) {
  18400. if (!input) {
  18401. input = 0;
  18402. }
  18403. else {
  18404. input = moment(input).zone();
  18405. }
  18406. return (this.zone() - input) % 60 === 0;
  18407. },
  18408. daysInMonth : function () {
  18409. return daysInMonth(this.year(), this.month());
  18410. },
  18411. dayOfYear : function (input) {
  18412. var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1;
  18413. return input == null ? dayOfYear : this.add("d", (input - dayOfYear));
  18414. },
  18415. quarter : function () {
  18416. return Math.ceil((this.month() + 1.0) / 3.0);
  18417. },
  18418. weekYear : function (input) {
  18419. var year = weekOfYear(this, this.lang()._week.dow, this.lang()._week.doy).year;
  18420. return input == null ? year : this.add("y", (input - year));
  18421. },
  18422. isoWeekYear : function (input) {
  18423. var year = weekOfYear(this, 1, 4).year;
  18424. return input == null ? year : this.add("y", (input - year));
  18425. },
  18426. week : function (input) {
  18427. var week = this.lang().week(this);
  18428. return input == null ? week : this.add("d", (input - week) * 7);
  18429. },
  18430. isoWeek : function (input) {
  18431. var week = weekOfYear(this, 1, 4).week;
  18432. return input == null ? week : this.add("d", (input - week) * 7);
  18433. },
  18434. weekday : function (input) {
  18435. var weekday = (this.day() + 7 - this.lang()._week.dow) % 7;
  18436. return input == null ? weekday : this.add("d", input - weekday);
  18437. },
  18438. isoWeekday : function (input) {
  18439. // behaves the same as moment#day except
  18440. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  18441. // as a setter, sunday should belong to the previous week.
  18442. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7);
  18443. },
  18444. get : function (units) {
  18445. units = normalizeUnits(units);
  18446. return this[units]();
  18447. },
  18448. set : function (units, value) {
  18449. units = normalizeUnits(units);
  18450. if (typeof this[units] === 'function') {
  18451. this[units](value);
  18452. }
  18453. return this;
  18454. },
  18455. // If passed a language key, it will set the language for this
  18456. // instance. Otherwise, it will return the language configuration
  18457. // variables for this instance.
  18458. lang : function (key) {
  18459. if (key === undefined) {
  18460. return this._lang;
  18461. } else {
  18462. this._lang = getLangDefinition(key);
  18463. return this;
  18464. }
  18465. }
  18466. });
  18467. // helper for adding shortcuts
  18468. function makeGetterAndSetter(name, key) {
  18469. moment.fn[name] = moment.fn[name + 's'] = function (input) {
  18470. var utc = this._isUTC ? 'UTC' : '';
  18471. if (input != null) {
  18472. this._d['set' + utc + key](input);
  18473. moment.updateOffset(this);
  18474. return this;
  18475. } else {
  18476. return this._d['get' + utc + key]();
  18477. }
  18478. };
  18479. }
  18480. // loop through and add shortcuts (Month, Date, Hours, Minutes, Seconds, Milliseconds)
  18481. for (i = 0; i < proxyGettersAndSetters.length; i ++) {
  18482. makeGetterAndSetter(proxyGettersAndSetters[i].toLowerCase().replace(/s$/, ''), proxyGettersAndSetters[i]);
  18483. }
  18484. // add shortcut for year (uses different syntax than the getter/setter 'year' == 'FullYear')
  18485. makeGetterAndSetter('year', 'FullYear');
  18486. // add plural methods
  18487. moment.fn.days = moment.fn.day;
  18488. moment.fn.months = moment.fn.month;
  18489. moment.fn.weeks = moment.fn.week;
  18490. moment.fn.isoWeeks = moment.fn.isoWeek;
  18491. // add aliased format methods
  18492. moment.fn.toJSON = moment.fn.toISOString;
  18493. /************************************
  18494. Duration Prototype
  18495. ************************************/
  18496. extend(moment.duration.fn = Duration.prototype, {
  18497. _bubble : function () {
  18498. var milliseconds = this._milliseconds,
  18499. days = this._days,
  18500. months = this._months,
  18501. data = this._data,
  18502. seconds, minutes, hours, years;
  18503. // The following code bubbles up values, see the tests for
  18504. // examples of what that means.
  18505. data.milliseconds = milliseconds % 1000;
  18506. seconds = absRound(milliseconds / 1000);
  18507. data.seconds = seconds % 60;
  18508. minutes = absRound(seconds / 60);
  18509. data.minutes = minutes % 60;
  18510. hours = absRound(minutes / 60);
  18511. data.hours = hours % 24;
  18512. days += absRound(hours / 24);
  18513. data.days = days % 30;
  18514. months += absRound(days / 30);
  18515. data.months = months % 12;
  18516. years = absRound(months / 12);
  18517. data.years = years;
  18518. },
  18519. weeks : function () {
  18520. return absRound(this.days() / 7);
  18521. },
  18522. valueOf : function () {
  18523. return this._milliseconds +
  18524. this._days * 864e5 +
  18525. (this._months % 12) * 2592e6 +
  18526. toInt(this._months / 12) * 31536e6;
  18527. },
  18528. humanize : function (withSuffix) {
  18529. var difference = +this,
  18530. output = relativeTime(difference, !withSuffix, this.lang());
  18531. if (withSuffix) {
  18532. output = this.lang().pastFuture(difference, output);
  18533. }
  18534. return this.lang().postformat(output);
  18535. },
  18536. add : function (input, val) {
  18537. // supports only 2.0-style add(1, 's') or add(moment)
  18538. var dur = moment.duration(input, val);
  18539. this._milliseconds += dur._milliseconds;
  18540. this._days += dur._days;
  18541. this._months += dur._months;
  18542. this._bubble();
  18543. return this;
  18544. },
  18545. subtract : function (input, val) {
  18546. var dur = moment.duration(input, val);
  18547. this._milliseconds -= dur._milliseconds;
  18548. this._days -= dur._days;
  18549. this._months -= dur._months;
  18550. this._bubble();
  18551. return this;
  18552. },
  18553. get : function (units) {
  18554. units = normalizeUnits(units);
  18555. return this[units.toLowerCase() + 's']();
  18556. },
  18557. as : function (units) {
  18558. units = normalizeUnits(units);
  18559. return this['as' + units.charAt(0).toUpperCase() + units.slice(1) + 's']();
  18560. },
  18561. lang : moment.fn.lang,
  18562. toIsoString : function () {
  18563. // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
  18564. var years = Math.abs(this.years()),
  18565. months = Math.abs(this.months()),
  18566. days = Math.abs(this.days()),
  18567. hours = Math.abs(this.hours()),
  18568. minutes = Math.abs(this.minutes()),
  18569. seconds = Math.abs(this.seconds() + this.milliseconds() / 1000);
  18570. if (!this.asSeconds()) {
  18571. // this is the same as C#'s (Noda) and python (isodate)...
  18572. // but not other JS (goog.date)
  18573. return 'P0D';
  18574. }
  18575. return (this.asSeconds() < 0 ? '-' : '') +
  18576. 'P' +
  18577. (years ? years + 'Y' : '') +
  18578. (months ? months + 'M' : '') +
  18579. (days ? days + 'D' : '') +
  18580. ((hours || minutes || seconds) ? 'T' : '') +
  18581. (hours ? hours + 'H' : '') +
  18582. (minutes ? minutes + 'M' : '') +
  18583. (seconds ? seconds + 'S' : '');
  18584. }
  18585. });
  18586. function makeDurationGetter(name) {
  18587. moment.duration.fn[name] = function () {
  18588. return this._data[name];
  18589. };
  18590. }
  18591. function makeDurationAsGetter(name, factor) {
  18592. moment.duration.fn['as' + name] = function () {
  18593. return +this / factor;
  18594. };
  18595. }
  18596. for (i in unitMillisecondFactors) {
  18597. if (unitMillisecondFactors.hasOwnProperty(i)) {
  18598. makeDurationAsGetter(i, unitMillisecondFactors[i]);
  18599. makeDurationGetter(i.toLowerCase());
  18600. }
  18601. }
  18602. makeDurationAsGetter('Weeks', 6048e5);
  18603. moment.duration.fn.asMonths = function () {
  18604. return (+this - this.years() * 31536e6) / 2592e6 + this.years() * 12;
  18605. };
  18606. /************************************
  18607. Default Lang
  18608. ************************************/
  18609. // Set default language, other languages will inherit from English.
  18610. moment.lang('en', {
  18611. ordinal : function (number) {
  18612. var b = number % 10,
  18613. output = (toInt(number % 100 / 10) === 1) ? 'th' :
  18614. (b === 1) ? 'st' :
  18615. (b === 2) ? 'nd' :
  18616. (b === 3) ? 'rd' : 'th';
  18617. return number + output;
  18618. }
  18619. });
  18620. /* EMBED_LANGUAGES */
  18621. /************************************
  18622. Exposing Moment
  18623. ************************************/
  18624. function makeGlobal(deprecate) {
  18625. var warned = false, local_moment = moment;
  18626. /*global ender:false */
  18627. if (typeof ender !== 'undefined') {
  18628. return;
  18629. }
  18630. // here, `this` means `window` in the browser, or `global` on the server
  18631. // add `moment` as a global object via a string identifier,
  18632. // for Closure Compiler "advanced" mode
  18633. if (deprecate) {
  18634. global.moment = function () {
  18635. if (!warned && console && console.warn) {
  18636. warned = true;
  18637. console.warn(
  18638. "Accessing Moment through the global scope is " +
  18639. "deprecated, and will be removed in an upcoming " +
  18640. "release.");
  18641. }
  18642. return local_moment.apply(null, arguments);
  18643. };
  18644. extend(global.moment, local_moment);
  18645. } else {
  18646. global['moment'] = moment;
  18647. }
  18648. }
  18649. // CommonJS module is defined
  18650. if (hasModule) {
  18651. module.exports = moment;
  18652. makeGlobal(true);
  18653. } else if (typeof define === "function" && define.amd) {
  18654. define("moment", function (require, exports, module) {
  18655. if (module.config && module.config() && module.config().noGlobal !== true) {
  18656. // If user provided noGlobal, he is aware of global
  18657. makeGlobal(module.config().noGlobal === undefined);
  18658. }
  18659. return moment;
  18660. });
  18661. } else {
  18662. makeGlobal();
  18663. }
  18664. }).call(this);
  18665. },{}],5:[function(require,module,exports){
  18666. /**
  18667. * Copyright 2012 Craig Campbell
  18668. *
  18669. * Licensed under the Apache License, Version 2.0 (the "License");
  18670. * you may not use this file except in compliance with the License.
  18671. * You may obtain a copy of the License at
  18672. *
  18673. * http://www.apache.org/licenses/LICENSE-2.0
  18674. *
  18675. * Unless required by applicable law or agreed to in writing, software
  18676. * distributed under the License is distributed on an "AS IS" BASIS,
  18677. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18678. * See the License for the specific language governing permissions and
  18679. * limitations under the License.
  18680. *
  18681. * Mousetrap is a simple keyboard shortcut library for Javascript with
  18682. * no external dependencies
  18683. *
  18684. * @version 1.1.2
  18685. * @url craig.is/killing/mice
  18686. */
  18687. /**
  18688. * mapping of special keycodes to their corresponding keys
  18689. *
  18690. * everything in this dictionary cannot use keypress events
  18691. * so it has to be here to map to the correct keycodes for
  18692. * keyup/keydown events
  18693. *
  18694. * @type {Object}
  18695. */
  18696. var _MAP = {
  18697. 8: 'backspace',
  18698. 9: 'tab',
  18699. 13: 'enter',
  18700. 16: 'shift',
  18701. 17: 'ctrl',
  18702. 18: 'alt',
  18703. 20: 'capslock',
  18704. 27: 'esc',
  18705. 32: 'space',
  18706. 33: 'pageup',
  18707. 34: 'pagedown',
  18708. 35: 'end',
  18709. 36: 'home',
  18710. 37: 'left',
  18711. 38: 'up',
  18712. 39: 'right',
  18713. 40: 'down',
  18714. 45: 'ins',
  18715. 46: 'del',
  18716. 91: 'meta',
  18717. 93: 'meta',
  18718. 224: 'meta'
  18719. },
  18720. /**
  18721. * mapping for special characters so they can support
  18722. *
  18723. * this dictionary is only used incase you want to bind a
  18724. * keyup or keydown event to one of these keys
  18725. *
  18726. * @type {Object}
  18727. */
  18728. _KEYCODE_MAP = {
  18729. 106: '*',
  18730. 107: '+',
  18731. 109: '-',
  18732. 110: '.',
  18733. 111 : '/',
  18734. 186: ';',
  18735. 187: '=',
  18736. 188: ',',
  18737. 189: '-',
  18738. 190: '.',
  18739. 191: '/',
  18740. 192: '`',
  18741. 219: '[',
  18742. 220: '\\',
  18743. 221: ']',
  18744. 222: '\''
  18745. },
  18746. /**
  18747. * this is a mapping of keys that require shift on a US keypad
  18748. * back to the non shift equivelents
  18749. *
  18750. * this is so you can use keyup events with these keys
  18751. *
  18752. * note that this will only work reliably on US keyboards
  18753. *
  18754. * @type {Object}
  18755. */
  18756. _SHIFT_MAP = {
  18757. '~': '`',
  18758. '!': '1',
  18759. '@': '2',
  18760. '#': '3',
  18761. '$': '4',
  18762. '%': '5',
  18763. '^': '6',
  18764. '&': '7',
  18765. '*': '8',
  18766. '(': '9',
  18767. ')': '0',
  18768. '_': '-',
  18769. '+': '=',
  18770. ':': ';',
  18771. '\"': '\'',
  18772. '<': ',',
  18773. '>': '.',
  18774. '?': '/',
  18775. '|': '\\'
  18776. },
  18777. /**
  18778. * this is a list of special strings you can use to map
  18779. * to modifier keys when you specify your keyboard shortcuts
  18780. *
  18781. * @type {Object}
  18782. */
  18783. _SPECIAL_ALIASES = {
  18784. 'option': 'alt',
  18785. 'command': 'meta',
  18786. 'return': 'enter',
  18787. 'escape': 'esc'
  18788. },
  18789. /**
  18790. * variable to store the flipped version of _MAP from above
  18791. * needed to check if we should use keypress or not when no action
  18792. * is specified
  18793. *
  18794. * @type {Object|undefined}
  18795. */
  18796. _REVERSE_MAP,
  18797. /**
  18798. * a list of all the callbacks setup via Mousetrap.bind()
  18799. *
  18800. * @type {Object}
  18801. */
  18802. _callbacks = {},
  18803. /**
  18804. * direct map of string combinations to callbacks used for trigger()
  18805. *
  18806. * @type {Object}
  18807. */
  18808. _direct_map = {},
  18809. /**
  18810. * keeps track of what level each sequence is at since multiple
  18811. * sequences can start out with the same sequence
  18812. *
  18813. * @type {Object}
  18814. */
  18815. _sequence_levels = {},
  18816. /**
  18817. * variable to store the setTimeout call
  18818. *
  18819. * @type {null|number}
  18820. */
  18821. _reset_timer,
  18822. /**
  18823. * temporary state where we will ignore the next keyup
  18824. *
  18825. * @type {boolean|string}
  18826. */
  18827. _ignore_next_keyup = false,
  18828. /**
  18829. * are we currently inside of a sequence?
  18830. * type of action ("keyup" or "keydown" or "keypress") or false
  18831. *
  18832. * @type {boolean|string}
  18833. */
  18834. _inside_sequence = false;
  18835. /**
  18836. * loop through the f keys, f1 to f19 and add them to the map
  18837. * programatically
  18838. */
  18839. for (var i = 1; i < 20; ++i) {
  18840. _MAP[111 + i] = 'f' + i;
  18841. }
  18842. /**
  18843. * loop through to map numbers on the numeric keypad
  18844. */
  18845. for (i = 0; i <= 9; ++i) {
  18846. _MAP[i + 96] = i;
  18847. }
  18848. /**
  18849. * cross browser add event method
  18850. *
  18851. * @param {Element|HTMLDocument} object
  18852. * @param {string} type
  18853. * @param {Function} callback
  18854. * @returns void
  18855. */
  18856. function _addEvent(object, type, callback) {
  18857. if (object.addEventListener) {
  18858. return object.addEventListener(type, callback, false);
  18859. }
  18860. object.attachEvent('on' + type, callback);
  18861. }
  18862. /**
  18863. * takes the event and returns the key character
  18864. *
  18865. * @param {Event} e
  18866. * @return {string}
  18867. */
  18868. function _characterFromEvent(e) {
  18869. // for keypress events we should return the character as is
  18870. if (e.type == 'keypress') {
  18871. return String.fromCharCode(e.which);
  18872. }
  18873. // for non keypress events the special maps are needed
  18874. if (_MAP[e.which]) {
  18875. return _MAP[e.which];
  18876. }
  18877. if (_KEYCODE_MAP[e.which]) {
  18878. return _KEYCODE_MAP[e.which];
  18879. }
  18880. // if it is not in the special map
  18881. return String.fromCharCode(e.which).toLowerCase();
  18882. }
  18883. /**
  18884. * should we stop this event before firing off callbacks
  18885. *
  18886. * @param {Event} e
  18887. * @return {boolean}
  18888. */
  18889. function _stop(e) {
  18890. var element = e.target || e.srcElement,
  18891. tag_name = element.tagName;
  18892. // if the element has the class "mousetrap" then no need to stop
  18893. if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {
  18894. return false;
  18895. }
  18896. // stop for input, select, and textarea
  18897. return tag_name == 'INPUT' || tag_name == 'SELECT' || tag_name == 'TEXTAREA' || (element.contentEditable && element.contentEditable == 'true');
  18898. }
  18899. /**
  18900. * checks if two arrays are equal
  18901. *
  18902. * @param {Array} modifiers1
  18903. * @param {Array} modifiers2
  18904. * @returns {boolean}
  18905. */
  18906. function _modifiersMatch(modifiers1, modifiers2) {
  18907. return modifiers1.sort().join(',') === modifiers2.sort().join(',');
  18908. }
  18909. /**
  18910. * resets all sequence counters except for the ones passed in
  18911. *
  18912. * @param {Object} do_not_reset
  18913. * @returns void
  18914. */
  18915. function _resetSequences(do_not_reset) {
  18916. do_not_reset = do_not_reset || {};
  18917. var active_sequences = false,
  18918. key;
  18919. for (key in _sequence_levels) {
  18920. if (do_not_reset[key]) {
  18921. active_sequences = true;
  18922. continue;
  18923. }
  18924. _sequence_levels[key] = 0;
  18925. }
  18926. if (!active_sequences) {
  18927. _inside_sequence = false;
  18928. }
  18929. }
  18930. /**
  18931. * finds all callbacks that match based on the keycode, modifiers,
  18932. * and action
  18933. *
  18934. * @param {string} character
  18935. * @param {Array} modifiers
  18936. * @param {string} action
  18937. * @param {boolean=} remove - should we remove any matches
  18938. * @param {string=} combination
  18939. * @returns {Array}
  18940. */
  18941. function _getMatches(character, modifiers, action, remove, combination) {
  18942. var i,
  18943. callback,
  18944. matches = [];
  18945. // if there are no events related to this keycode
  18946. if (!_callbacks[character]) {
  18947. return [];
  18948. }
  18949. // if a modifier key is coming up on its own we should allow it
  18950. if (action == 'keyup' && _isModifier(character)) {
  18951. modifiers = [character];
  18952. }
  18953. // loop through all callbacks for the key that was pressed
  18954. // and see if any of them match
  18955. for (i = 0; i < _callbacks[character].length; ++i) {
  18956. callback = _callbacks[character][i];
  18957. // if this is a sequence but it is not at the right level
  18958. // then move onto the next match
  18959. if (callback.seq && _sequence_levels[callback.seq] != callback.level) {
  18960. continue;
  18961. }
  18962. // if the action we are looking for doesn't match the action we got
  18963. // then we should keep going
  18964. if (action != callback.action) {
  18965. continue;
  18966. }
  18967. // if this is a keypress event that means that we need to only
  18968. // look at the character, otherwise check the modifiers as
  18969. // well
  18970. if (action == 'keypress' || _modifiersMatch(modifiers, callback.modifiers)) {
  18971. // remove is used so if you change your mind and call bind a
  18972. // second time with a new function the first one is overwritten
  18973. if (remove && callback.combo == combination) {
  18974. _callbacks[character].splice(i, 1);
  18975. }
  18976. matches.push(callback);
  18977. }
  18978. }
  18979. return matches;
  18980. }
  18981. /**
  18982. * takes a key event and figures out what the modifiers are
  18983. *
  18984. * @param {Event} e
  18985. * @returns {Array}
  18986. */
  18987. function _eventModifiers(e) {
  18988. var modifiers = [];
  18989. if (e.shiftKey) {
  18990. modifiers.push('shift');
  18991. }
  18992. if (e.altKey) {
  18993. modifiers.push('alt');
  18994. }
  18995. if (e.ctrlKey) {
  18996. modifiers.push('ctrl');
  18997. }
  18998. if (e.metaKey) {
  18999. modifiers.push('meta');
  19000. }
  19001. return modifiers;
  19002. }
  19003. /**
  19004. * actually calls the callback function
  19005. *
  19006. * if your callback function returns false this will use the jquery
  19007. * convention - prevent default and stop propogation on the event
  19008. *
  19009. * @param {Function} callback
  19010. * @param {Event} e
  19011. * @returns void
  19012. */
  19013. function _fireCallback(callback, e) {
  19014. if (callback(e) === false) {
  19015. if (e.preventDefault) {
  19016. e.preventDefault();
  19017. }
  19018. if (e.stopPropagation) {
  19019. e.stopPropagation();
  19020. }
  19021. e.returnValue = false;
  19022. e.cancelBubble = true;
  19023. }
  19024. }
  19025. /**
  19026. * handles a character key event
  19027. *
  19028. * @param {string} character
  19029. * @param {Event} e
  19030. * @returns void
  19031. */
  19032. function _handleCharacter(character, e) {
  19033. // if this event should not happen stop here
  19034. if (_stop(e)) {
  19035. return;
  19036. }
  19037. var callbacks = _getMatches(character, _eventModifiers(e), e.type),
  19038. i,
  19039. do_not_reset = {},
  19040. processed_sequence_callback = false;
  19041. // loop through matching callbacks for this key event
  19042. for (i = 0; i < callbacks.length; ++i) {
  19043. // fire for all sequence callbacks
  19044. // this is because if for example you have multiple sequences
  19045. // bound such as "g i" and "g t" they both need to fire the
  19046. // callback for matching g cause otherwise you can only ever
  19047. // match the first one
  19048. if (callbacks[i].seq) {
  19049. processed_sequence_callback = true;
  19050. // keep a list of which sequences were matches for later
  19051. do_not_reset[callbacks[i].seq] = 1;
  19052. _fireCallback(callbacks[i].callback, e);
  19053. continue;
  19054. }
  19055. // if there were no sequence matches but we are still here
  19056. // that means this is a regular match so we should fire that
  19057. if (!processed_sequence_callback && !_inside_sequence) {
  19058. _fireCallback(callbacks[i].callback, e);
  19059. }
  19060. }
  19061. // if you are inside of a sequence and the key you are pressing
  19062. // is not a modifier key then we should reset all sequences
  19063. // that were not matched by this key event
  19064. if (e.type == _inside_sequence && !_isModifier(character)) {
  19065. _resetSequences(do_not_reset);
  19066. }
  19067. }
  19068. /**
  19069. * handles a keydown event
  19070. *
  19071. * @param {Event} e
  19072. * @returns void
  19073. */
  19074. function _handleKey(e) {
  19075. // normalize e.which for key events
  19076. // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion
  19077. e.which = typeof e.which == "number" ? e.which : e.keyCode;
  19078. var character = _characterFromEvent(e);
  19079. // no character found then stop
  19080. if (!character) {
  19081. return;
  19082. }
  19083. if (e.type == 'keyup' && _ignore_next_keyup == character) {
  19084. _ignore_next_keyup = false;
  19085. return;
  19086. }
  19087. _handleCharacter(character, e);
  19088. }
  19089. /**
  19090. * determines if the keycode specified is a modifier key or not
  19091. *
  19092. * @param {string} key
  19093. * @returns {boolean}
  19094. */
  19095. function _isModifier(key) {
  19096. return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta';
  19097. }
  19098. /**
  19099. * called to set a 1 second timeout on the specified sequence
  19100. *
  19101. * this is so after each key press in the sequence you have 1 second
  19102. * to press the next key before you have to start over
  19103. *
  19104. * @returns void
  19105. */
  19106. function _resetSequenceTimer() {
  19107. clearTimeout(_reset_timer);
  19108. _reset_timer = setTimeout(_resetSequences, 1000);
  19109. }
  19110. /**
  19111. * reverses the map lookup so that we can look for specific keys
  19112. * to see what can and can't use keypress
  19113. *
  19114. * @return {Object}
  19115. */
  19116. function _getReverseMap() {
  19117. if (!_REVERSE_MAP) {
  19118. _REVERSE_MAP = {};
  19119. for (var key in _MAP) {
  19120. // pull out the numeric keypad from here cause keypress should
  19121. // be able to detect the keys from the character
  19122. if (key > 95 && key < 112) {
  19123. continue;
  19124. }
  19125. if (_MAP.hasOwnProperty(key)) {
  19126. _REVERSE_MAP[_MAP[key]] = key;
  19127. }
  19128. }
  19129. }
  19130. return _REVERSE_MAP;
  19131. }
  19132. /**
  19133. * picks the best action based on the key combination
  19134. *
  19135. * @param {string} key - character for key
  19136. * @param {Array} modifiers
  19137. * @param {string=} action passed in
  19138. */
  19139. function _pickBestAction(key, modifiers, action) {
  19140. // if no action was picked in we should try to pick the one
  19141. // that we think would work best for this key
  19142. if (!action) {
  19143. action = _getReverseMap()[key] ? 'keydown' : 'keypress';
  19144. }
  19145. // modifier keys don't work as expected with keypress,
  19146. // switch to keydown
  19147. if (action == 'keypress' && modifiers.length) {
  19148. action = 'keydown';
  19149. }
  19150. return action;
  19151. }
  19152. /**
  19153. * binds a key sequence to an event
  19154. *
  19155. * @param {string} combo - combo specified in bind call
  19156. * @param {Array} keys
  19157. * @param {Function} callback
  19158. * @param {string=} action
  19159. * @returns void
  19160. */
  19161. function _bindSequence(combo, keys, callback, action) {
  19162. // start off by adding a sequence level record for this combination
  19163. // and setting the level to 0
  19164. _sequence_levels[combo] = 0;
  19165. // if there is no action pick the best one for the first key
  19166. // in the sequence
  19167. if (!action) {
  19168. action = _pickBestAction(keys[0], []);
  19169. }
  19170. /**
  19171. * callback to increase the sequence level for this sequence and reset
  19172. * all other sequences that were active
  19173. *
  19174. * @param {Event} e
  19175. * @returns void
  19176. */
  19177. var _increaseSequence = function(e) {
  19178. _inside_sequence = action;
  19179. ++_sequence_levels[combo];
  19180. _resetSequenceTimer();
  19181. },
  19182. /**
  19183. * wraps the specified callback inside of another function in order
  19184. * to reset all sequence counters as soon as this sequence is done
  19185. *
  19186. * @param {Event} e
  19187. * @returns void
  19188. */
  19189. _callbackAndReset = function(e) {
  19190. _fireCallback(callback, e);
  19191. // we should ignore the next key up if the action is key down
  19192. // or keypress. this is so if you finish a sequence and
  19193. // release the key the final key will not trigger a keyup
  19194. if (action !== 'keyup') {
  19195. _ignore_next_keyup = _characterFromEvent(e);
  19196. }
  19197. // weird race condition if a sequence ends with the key
  19198. // another sequence begins with
  19199. setTimeout(_resetSequences, 10);
  19200. },
  19201. i;
  19202. // loop through keys one at a time and bind the appropriate callback
  19203. // function. for any key leading up to the final one it should
  19204. // increase the sequence. after the final, it should reset all sequences
  19205. for (i = 0; i < keys.length; ++i) {
  19206. _bindSingle(keys[i], i < keys.length - 1 ? _increaseSequence : _callbackAndReset, action, combo, i);
  19207. }
  19208. }
  19209. /**
  19210. * binds a single keyboard combination
  19211. *
  19212. * @param {string} combination
  19213. * @param {Function} callback
  19214. * @param {string=} action
  19215. * @param {string=} sequence_name - name of sequence if part of sequence
  19216. * @param {number=} level - what part of the sequence the command is
  19217. * @returns void
  19218. */
  19219. function _bindSingle(combination, callback, action, sequence_name, level) {
  19220. // make sure multiple spaces in a row become a single space
  19221. combination = combination.replace(/\s+/g, ' ');
  19222. var sequence = combination.split(' '),
  19223. i,
  19224. key,
  19225. keys,
  19226. modifiers = [];
  19227. // if this pattern is a sequence of keys then run through this method
  19228. // to reprocess each pattern one key at a time
  19229. if (sequence.length > 1) {
  19230. return _bindSequence(combination, sequence, callback, action);
  19231. }
  19232. // take the keys from this pattern and figure out what the actual
  19233. // pattern is all about
  19234. keys = combination === '+' ? ['+'] : combination.split('+');
  19235. for (i = 0; i < keys.length; ++i) {
  19236. key = keys[i];
  19237. // normalize key names
  19238. if (_SPECIAL_ALIASES[key]) {
  19239. key = _SPECIAL_ALIASES[key];
  19240. }
  19241. // if this is not a keypress event then we should
  19242. // be smart about using shift keys
  19243. // this will only work for US keyboards however
  19244. if (action && action != 'keypress' && _SHIFT_MAP[key]) {
  19245. key = _SHIFT_MAP[key];
  19246. modifiers.push('shift');
  19247. }
  19248. // if this key is a modifier then add it to the list of modifiers
  19249. if (_isModifier(key)) {
  19250. modifiers.push(key);
  19251. }
  19252. }
  19253. // depending on what the key combination is
  19254. // we will try to pick the best event for it
  19255. action = _pickBestAction(key, modifiers, action);
  19256. // make sure to initialize array if this is the first time
  19257. // a callback is added for this key
  19258. if (!_callbacks[key]) {
  19259. _callbacks[key] = [];
  19260. }
  19261. // remove an existing match if there is one
  19262. _getMatches(key, modifiers, action, !sequence_name, combination);
  19263. // add this call back to the array
  19264. // if it is a sequence put it at the beginning
  19265. // if not put it at the end
  19266. //
  19267. // this is important because the way these are processed expects
  19268. // the sequence ones to come first
  19269. _callbacks[key][sequence_name ? 'unshift' : 'push']({
  19270. callback: callback,
  19271. modifiers: modifiers,
  19272. action: action,
  19273. seq: sequence_name,
  19274. level: level,
  19275. combo: combination
  19276. });
  19277. }
  19278. /**
  19279. * binds multiple combinations to the same callback
  19280. *
  19281. * @param {Array} combinations
  19282. * @param {Function} callback
  19283. * @param {string|undefined} action
  19284. * @returns void
  19285. */
  19286. function _bindMultiple(combinations, callback, action) {
  19287. for (var i = 0; i < combinations.length; ++i) {
  19288. _bindSingle(combinations[i], callback, action);
  19289. }
  19290. }
  19291. // start!
  19292. _addEvent(document, 'keypress', _handleKey);
  19293. _addEvent(document, 'keydown', _handleKey);
  19294. _addEvent(document, 'keyup', _handleKey);
  19295. var mousetrap = {
  19296. /**
  19297. * binds an event to mousetrap
  19298. *
  19299. * can be a single key, a combination of keys separated with +,
  19300. * a comma separated list of keys, an array of keys, or
  19301. * a sequence of keys separated by spaces
  19302. *
  19303. * be sure to list the modifier keys first to make sure that the
  19304. * correct key ends up getting bound (the last key in the pattern)
  19305. *
  19306. * @param {string|Array} keys
  19307. * @param {Function} callback
  19308. * @param {string=} action - 'keypress', 'keydown', or 'keyup'
  19309. * @returns void
  19310. */
  19311. bind: function(keys, callback, action) {
  19312. _bindMultiple(keys instanceof Array ? keys : [keys], callback, action);
  19313. _direct_map[keys + ':' + action] = callback;
  19314. return this;
  19315. },
  19316. /**
  19317. * unbinds an event to mousetrap
  19318. *
  19319. * the unbinding sets the callback function of the specified key combo
  19320. * to an empty function and deletes the corresponding key in the
  19321. * _direct_map dict.
  19322. *
  19323. * the keycombo+action has to be exactly the same as
  19324. * it was defined in the bind method
  19325. *
  19326. * TODO: actually remove this from the _callbacks dictionary instead
  19327. * of binding an empty function
  19328. *
  19329. * @param {string|Array} keys
  19330. * @param {string} action
  19331. * @returns void
  19332. */
  19333. unbind: function(keys, action) {
  19334. if (_direct_map[keys + ':' + action]) {
  19335. delete _direct_map[keys + ':' + action];
  19336. this.bind(keys, function() {}, action);
  19337. }
  19338. return this;
  19339. },
  19340. /**
  19341. * triggers an event that has already been bound
  19342. *
  19343. * @param {string} keys
  19344. * @param {string=} action
  19345. * @returns void
  19346. */
  19347. trigger: function(keys, action) {
  19348. _direct_map[keys + ':' + action]();
  19349. return this;
  19350. },
  19351. /**
  19352. * resets the library back to its initial state. this is useful
  19353. * if you want to clear out the current keyboard shortcuts and bind
  19354. * new ones - for example if you switch to another page
  19355. *
  19356. * @returns void
  19357. */
  19358. reset: function() {
  19359. _callbacks = {};
  19360. _direct_map = {};
  19361. return this;
  19362. }
  19363. };
  19364. module.exports = mousetrap;
  19365. },{}]},{},[1])
  19366. (1)
  19367. });