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.

22634 lines
659 KiB

  1. /**
  2. * vis.js
  3. * https://github.com/almende/vis
  4. *
  5. * A dynamic, browser-based visualization library.
  6. *
  7. * @version @@version
  8. * @date @@date
  9. *
  10. * @license
  11. * Copyright (C) 2011-2014 Almende B.V, http://almende.com
  12. *
  13. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  14. * use this file except in compliance with the License. You may obtain a copy
  15. * of the License at
  16. *
  17. * http://www.apache.org/licenses/LICENSE-2.0
  18. *
  19. * Unless required by applicable law or agreed to in writing, software
  20. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  21. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  22. * License for the specific language governing permissions and limitations under
  23. * the License.
  24. */
  25. !function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.vis=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  26. /**
  27. * vis.js module imports
  28. */
  29. // Try to load dependencies from the global window object.
  30. // If not available there, load via require.
  31. var moment = (typeof window !== 'undefined') && window['moment'] || require('moment');
  32. var Emitter = require('emitter-component');
  33. var Hammer;
  34. if (typeof window !== 'undefined') {
  35. // load hammer.js only when running in a browser (where window is available)
  36. Hammer = window['Hammer'] || require('hammerjs');
  37. }
  38. else {
  39. Hammer = function () {
  40. throw Error('hammer.js is only available in a browser, not in node.js.');
  41. }
  42. }
  43. var mousetrap;
  44. if (typeof window !== 'undefined') {
  45. // load mousetrap.js only when running in a browser (where window is available)
  46. mousetrap = window['mousetrap'] || require('mousetrap');
  47. }
  48. else {
  49. mousetrap = function () {
  50. throw Error('mouseTrap is only available in a browser, not in node.js.');
  51. }
  52. }
  53. // Internet Explorer 8 and older does not support Array.indexOf, so we define
  54. // it here in that case.
  55. // http://soledadpenades.com/2007/05/17/arrayindexof-in-internet-explorer/
  56. if(!Array.prototype.indexOf) {
  57. Array.prototype.indexOf = function(obj){
  58. for(var i = 0; i < this.length; i++){
  59. if(this[i] == obj){
  60. return i;
  61. }
  62. }
  63. return -1;
  64. };
  65. try {
  66. console.log("Warning: Ancient browser detected. Please update your browser");
  67. }
  68. catch (err) {
  69. }
  70. }
  71. // Internet Explorer 8 and older does not support Array.forEach, so we define
  72. // it here in that case.
  73. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach
  74. if (!Array.prototype.forEach) {
  75. Array.prototype.forEach = function(fn, scope) {
  76. for(var i = 0, len = this.length; i < len; ++i) {
  77. fn.call(scope || this, this[i], i, this);
  78. }
  79. }
  80. }
  81. // Internet Explorer 8 and older does not support Array.map, so we define it
  82. // here in that case.
  83. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map
  84. // Production steps of ECMA-262, Edition 5, 15.4.4.19
  85. // Reference: http://es5.github.com/#x15.4.4.19
  86. if (!Array.prototype.map) {
  87. Array.prototype.map = function(callback, thisArg) {
  88. var T, A, k;
  89. if (this == null) {
  90. throw new TypeError(" this is null or not defined");
  91. }
  92. // 1. Let O be the result of calling ToObject passing the |this| value as the argument.
  93. var O = Object(this);
  94. // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
  95. // 3. Let len be ToUint32(lenValue).
  96. var len = O.length >>> 0;
  97. // 4. If IsCallable(callback) is false, throw a TypeError exception.
  98. // See: http://es5.github.com/#x9.11
  99. if (typeof callback !== "function") {
  100. throw new TypeError(callback + " is not a function");
  101. }
  102. // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
  103. if (thisArg) {
  104. T = thisArg;
  105. }
  106. // 6. Let A be a new array created as if by the expression new Array(len) where Array is
  107. // the standard built-in constructor with that name and len is the value of len.
  108. A = new Array(len);
  109. // 7. Let k be 0
  110. k = 0;
  111. // 8. Repeat, while k < len
  112. while(k < len) {
  113. var kValue, mappedValue;
  114. // a. Let Pk be ToString(k).
  115. // This is implicit for LHS operands of the in operator
  116. // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
  117. // This step can be combined with c
  118. // c. If kPresent is true, then
  119. if (k in O) {
  120. // i. Let kValue be the result of calling the Get internal method of O with argument Pk.
  121. kValue = O[ k ];
  122. // ii. Let mappedValue be the result of calling the Call internal method of callback
  123. // with T as the this value and argument list containing kValue, k, and O.
  124. mappedValue = callback.call(T, kValue, k, O);
  125. // iii. Call the DefineOwnProperty internal method of A with arguments
  126. // Pk, Property Descriptor {Value: mappedValue, : true, Enumerable: true, Configurable: true},
  127. // and false.
  128. // In browsers that support Object.defineProperty, use the following:
  129. // Object.defineProperty(A, Pk, { value: mappedValue, writable: true, enumerable: true, configurable: true });
  130. // For best browser support, use the following:
  131. A[ k ] = mappedValue;
  132. }
  133. // d. Increase k by 1.
  134. k++;
  135. }
  136. // 9. return A
  137. return A;
  138. };
  139. }
  140. // Internet Explorer 8 and older does not support Array.filter, so we define it
  141. // here in that case.
  142. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter
  143. if (!Array.prototype.filter) {
  144. Array.prototype.filter = function(fun /*, thisp */) {
  145. "use strict";
  146. if (this == null) {
  147. throw new TypeError();
  148. }
  149. var t = Object(this);
  150. var len = t.length >>> 0;
  151. if (typeof fun != "function") {
  152. throw new TypeError();
  153. }
  154. var res = [];
  155. var thisp = arguments[1];
  156. for (var i = 0; i < len; i++) {
  157. if (i in t) {
  158. var val = t[i]; // in case fun mutates this
  159. if (fun.call(thisp, val, i, t))
  160. res.push(val);
  161. }
  162. }
  163. return res;
  164. };
  165. }
  166. // Internet Explorer 8 and older does not support Object.keys, so we define it
  167. // here in that case.
  168. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/keys
  169. if (!Object.keys) {
  170. Object.keys = (function () {
  171. var hasOwnProperty = Object.prototype.hasOwnProperty,
  172. hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
  173. dontEnums = [
  174. 'toString',
  175. 'toLocaleString',
  176. 'valueOf',
  177. 'hasOwnProperty',
  178. 'isPrototypeOf',
  179. 'propertyIsEnumerable',
  180. 'constructor'
  181. ],
  182. dontEnumsLength = dontEnums.length;
  183. return function (obj) {
  184. if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) {
  185. throw new TypeError('Object.keys called on non-object');
  186. }
  187. var result = [];
  188. for (var prop in obj) {
  189. if (hasOwnProperty.call(obj, prop)) result.push(prop);
  190. }
  191. if (hasDontEnumBug) {
  192. for (var i=0; i < dontEnumsLength; i++) {
  193. if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
  194. }
  195. }
  196. return result;
  197. }
  198. })()
  199. }
  200. // Internet Explorer 8 and older does not support Array.isArray,
  201. // so we define it here in that case.
  202. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/isArray
  203. if(!Array.isArray) {
  204. Array.isArray = function (vArg) {
  205. return Object.prototype.toString.call(vArg) === "[object Array]";
  206. };
  207. }
  208. // Internet Explorer 8 and older does not support Function.bind,
  209. // so we define it here in that case.
  210. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind
  211. if (!Function.prototype.bind) {
  212. Function.prototype.bind = function (oThis) {
  213. if (typeof this !== "function") {
  214. // closest thing possible to the ECMAScript 5 internal IsCallable function
  215. throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
  216. }
  217. var aArgs = Array.prototype.slice.call(arguments, 1),
  218. fToBind = this,
  219. fNOP = function () {},
  220. fBound = function () {
  221. return fToBind.apply(this instanceof fNOP && oThis
  222. ? this
  223. : oThis,
  224. aArgs.concat(Array.prototype.slice.call(arguments)));
  225. };
  226. fNOP.prototype = this.prototype;
  227. fBound.prototype = new fNOP();
  228. return fBound;
  229. };
  230. }
  231. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create
  232. if (!Object.create) {
  233. Object.create = function (o) {
  234. if (arguments.length > 1) {
  235. throw new Error('Object.create implementation only accepts the first parameter.');
  236. }
  237. function F() {}
  238. F.prototype = o;
  239. return new F();
  240. };
  241. }
  242. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
  243. if (!Function.prototype.bind) {
  244. Function.prototype.bind = function (oThis) {
  245. if (typeof this !== "function") {
  246. // closest thing possible to the ECMAScript 5 internal IsCallable function
  247. throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
  248. }
  249. var aArgs = Array.prototype.slice.call(arguments, 1),
  250. fToBind = this,
  251. fNOP = function () {},
  252. fBound = function () {
  253. return fToBind.apply(this instanceof fNOP && oThis
  254. ? this
  255. : oThis,
  256. aArgs.concat(Array.prototype.slice.call(arguments)));
  257. };
  258. fNOP.prototype = this.prototype;
  259. fBound.prototype = new fNOP();
  260. return fBound;
  261. };
  262. }
  263. /**
  264. * utility functions
  265. */
  266. var util = {};
  267. /**
  268. * Test whether given object is a number
  269. * @param {*} object
  270. * @return {Boolean} isNumber
  271. */
  272. util.isNumber = function isNumber(object) {
  273. return (object instanceof Number || typeof object == 'number');
  274. };
  275. /**
  276. * Test whether given object is a string
  277. * @param {*} object
  278. * @return {Boolean} isString
  279. */
  280. util.isString = function isString(object) {
  281. return (object instanceof String || typeof object == 'string');
  282. };
  283. /**
  284. * Test whether given object is a Date, or a String containing a Date
  285. * @param {Date | String} object
  286. * @return {Boolean} isDate
  287. */
  288. util.isDate = function isDate(object) {
  289. if (object instanceof Date) {
  290. return true;
  291. }
  292. else if (util.isString(object)) {
  293. // test whether this string contains a date
  294. var match = ASPDateRegex.exec(object);
  295. if (match) {
  296. return true;
  297. }
  298. else if (!isNaN(Date.parse(object))) {
  299. return true;
  300. }
  301. }
  302. return false;
  303. };
  304. /**
  305. * Test whether given object is an instance of google.visualization.DataTable
  306. * @param {*} object
  307. * @return {Boolean} isDataTable
  308. */
  309. util.isDataTable = function isDataTable(object) {
  310. return (typeof (google) !== 'undefined') &&
  311. (google.visualization) &&
  312. (google.visualization.DataTable) &&
  313. (object instanceof google.visualization.DataTable);
  314. };
  315. /**
  316. * Create a semi UUID
  317. * source: http://stackoverflow.com/a/105074/1262753
  318. * @return {String} uuid
  319. */
  320. util.randomUUID = function randomUUID () {
  321. var S4 = function () {
  322. return Math.floor(
  323. Math.random() * 0x10000 /* 65536 */
  324. ).toString(16);
  325. };
  326. return (
  327. S4() + S4() + '-' +
  328. S4() + '-' +
  329. S4() + '-' +
  330. S4() + '-' +
  331. S4() + S4() + S4()
  332. );
  333. };
  334. /**
  335. * Extend object a with the properties of object b or a series of objects
  336. * Only properties with defined values are copied
  337. * @param {Object} a
  338. * @param {... Object} b
  339. * @return {Object} a
  340. */
  341. util.extend = function (a, b) {
  342. for (var i = 1, len = arguments.length; i < len; i++) {
  343. var other = arguments[i];
  344. for (var prop in other) {
  345. if (other.hasOwnProperty(prop) && other[prop] !== undefined) {
  346. a[prop] = other[prop];
  347. }
  348. }
  349. }
  350. return a;
  351. };
  352. /**
  353. * Convert an object to another type
  354. * @param {Boolean | Number | String | Date | Moment | Null | undefined} object
  355. * @param {String | undefined} type Name of the type. Available types:
  356. * 'Boolean', 'Number', 'String',
  357. * 'Date', 'Moment', ISODate', 'ASPDate'.
  358. * @return {*} object
  359. * @throws Error
  360. */
  361. util.convert = function convert(object, type) {
  362. var match;
  363. if (object === undefined) {
  364. return undefined;
  365. }
  366. if (object === null) {
  367. return null;
  368. }
  369. if (!type) {
  370. return object;
  371. }
  372. if (!(typeof type === 'string') && !(type instanceof String)) {
  373. throw new Error('Type must be a string');
  374. }
  375. //noinspection FallthroughInSwitchStatementJS
  376. switch (type) {
  377. case 'boolean':
  378. case 'Boolean':
  379. return Boolean(object);
  380. case 'number':
  381. case 'Number':
  382. return Number(object.valueOf());
  383. case 'string':
  384. case 'String':
  385. return String(object);
  386. case 'Date':
  387. if (util.isNumber(object)) {
  388. return new Date(object);
  389. }
  390. if (object instanceof Date) {
  391. return new Date(object.valueOf());
  392. }
  393. else if (moment.isMoment(object)) {
  394. return new Date(object.valueOf());
  395. }
  396. if (util.isString(object)) {
  397. match = ASPDateRegex.exec(object);
  398. if (match) {
  399. // object is an ASP date
  400. return new Date(Number(match[1])); // parse number
  401. }
  402. else {
  403. return moment(object).toDate(); // parse string
  404. }
  405. }
  406. else {
  407. throw new Error(
  408. 'Cannot convert object of type ' + util.getType(object) +
  409. ' to type Date');
  410. }
  411. case 'Moment':
  412. if (util.isNumber(object)) {
  413. return moment(object);
  414. }
  415. if (object instanceof Date) {
  416. return moment(object.valueOf());
  417. }
  418. else if (moment.isMoment(object)) {
  419. return moment(object);
  420. }
  421. if (util.isString(object)) {
  422. match = ASPDateRegex.exec(object);
  423. if (match) {
  424. // object is an ASP date
  425. return moment(Number(match[1])); // parse number
  426. }
  427. else {
  428. return moment(object); // parse string
  429. }
  430. }
  431. else {
  432. throw new Error(
  433. 'Cannot convert object of type ' + util.getType(object) +
  434. ' to type Date');
  435. }
  436. case 'ISODate':
  437. if (util.isNumber(object)) {
  438. return new Date(object);
  439. }
  440. else if (object instanceof Date) {
  441. return object.toISOString();
  442. }
  443. else if (moment.isMoment(object)) {
  444. return object.toDate().toISOString();
  445. }
  446. else if (util.isString(object)) {
  447. match = ASPDateRegex.exec(object);
  448. if (match) {
  449. // object is an ASP date
  450. return new Date(Number(match[1])).toISOString(); // parse number
  451. }
  452. else {
  453. return new Date(object).toISOString(); // parse string
  454. }
  455. }
  456. else {
  457. throw new Error(
  458. 'Cannot convert object of type ' + util.getType(object) +
  459. ' to type ISODate');
  460. }
  461. case 'ASPDate':
  462. if (util.isNumber(object)) {
  463. return '/Date(' + object + ')/';
  464. }
  465. else if (object instanceof Date) {
  466. return '/Date(' + object.valueOf() + ')/';
  467. }
  468. else if (util.isString(object)) {
  469. match = ASPDateRegex.exec(object);
  470. var value;
  471. if (match) {
  472. // object is an ASP date
  473. value = new Date(Number(match[1])).valueOf(); // parse number
  474. }
  475. else {
  476. value = new Date(object).valueOf(); // parse string
  477. }
  478. return '/Date(' + value + ')/';
  479. }
  480. else {
  481. throw new Error(
  482. 'Cannot convert object of type ' + util.getType(object) +
  483. ' to type ASPDate');
  484. }
  485. default:
  486. throw new Error('Cannot convert object of type ' + util.getType(object) +
  487. ' to type "' + type + '"');
  488. }
  489. };
  490. // parse ASP.Net Date pattern,
  491. // for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/'
  492. // code from http://momentjs.com/
  493. var ASPDateRegex = /^\/?Date\((\-?\d+)/i;
  494. /**
  495. * Get the type of an object, for example util.getType([]) returns 'Array'
  496. * @param {*} object
  497. * @return {String} type
  498. */
  499. util.getType = function getType(object) {
  500. var type = typeof object;
  501. if (type == 'object') {
  502. if (object == null) {
  503. return 'null';
  504. }
  505. if (object instanceof Boolean) {
  506. return 'Boolean';
  507. }
  508. if (object instanceof Number) {
  509. return 'Number';
  510. }
  511. if (object instanceof String) {
  512. return 'String';
  513. }
  514. if (object instanceof Array) {
  515. return 'Array';
  516. }
  517. if (object instanceof Date) {
  518. return 'Date';
  519. }
  520. return 'Object';
  521. }
  522. else if (type == 'number') {
  523. return 'Number';
  524. }
  525. else if (type == 'boolean') {
  526. return 'Boolean';
  527. }
  528. else if (type == 'string') {
  529. return 'String';
  530. }
  531. return type;
  532. };
  533. /**
  534. * Retrieve the absolute left value of a DOM element
  535. * @param {Element} elem A dom element, for example a div
  536. * @return {number} left The absolute left position of this element
  537. * in the browser page.
  538. */
  539. util.getAbsoluteLeft = function getAbsoluteLeft (elem) {
  540. var doc = document.documentElement;
  541. var body = document.body;
  542. var left = elem.offsetLeft;
  543. var e = elem.offsetParent;
  544. while (e != null && e != body && e != doc) {
  545. left += e.offsetLeft;
  546. left -= e.scrollLeft;
  547. e = e.offsetParent;
  548. }
  549. return left;
  550. };
  551. /**
  552. * Retrieve the absolute top value of a DOM element
  553. * @param {Element} elem A dom element, for example a div
  554. * @return {number} top The absolute top position of this element
  555. * in the browser page.
  556. */
  557. util.getAbsoluteTop = function getAbsoluteTop (elem) {
  558. var doc = document.documentElement;
  559. var body = document.body;
  560. var top = elem.offsetTop;
  561. var e = elem.offsetParent;
  562. while (e != null && e != body && e != doc) {
  563. top += e.offsetTop;
  564. top -= e.scrollTop;
  565. e = e.offsetParent;
  566. }
  567. return top;
  568. };
  569. /**
  570. * Get the absolute, vertical mouse position from an event.
  571. * @param {Event} event
  572. * @return {Number} pageY
  573. */
  574. util.getPageY = function getPageY (event) {
  575. if ('pageY' in event) {
  576. return event.pageY;
  577. }
  578. else {
  579. var clientY;
  580. if (('targetTouches' in event) && event.targetTouches.length) {
  581. clientY = event.targetTouches[0].clientY;
  582. }
  583. else {
  584. clientY = event.clientY;
  585. }
  586. var doc = document.documentElement;
  587. var body = document.body;
  588. return clientY +
  589. ( doc && doc.scrollTop || body && body.scrollTop || 0 ) -
  590. ( doc && doc.clientTop || body && body.clientTop || 0 );
  591. }
  592. };
  593. /**
  594. * Get the absolute, horizontal mouse position from an event.
  595. * @param {Event} event
  596. * @return {Number} pageX
  597. */
  598. util.getPageX = function getPageX (event) {
  599. if ('pageY' in event) {
  600. return event.pageX;
  601. }
  602. else {
  603. var clientX;
  604. if (('targetTouches' in event) && event.targetTouches.length) {
  605. clientX = event.targetTouches[0].clientX;
  606. }
  607. else {
  608. clientX = event.clientX;
  609. }
  610. var doc = document.documentElement;
  611. var body = document.body;
  612. return clientX +
  613. ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) -
  614. ( doc && doc.clientLeft || body && body.clientLeft || 0 );
  615. }
  616. };
  617. /**
  618. * add a className to the given elements style
  619. * @param {Element} elem
  620. * @param {String} className
  621. */
  622. util.addClassName = function addClassName(elem, className) {
  623. var classes = elem.className.split(' ');
  624. if (classes.indexOf(className) == -1) {
  625. classes.push(className); // add the class to the array
  626. elem.className = classes.join(' ');
  627. }
  628. };
  629. /**
  630. * add a className to the given elements style
  631. * @param {Element} elem
  632. * @param {String} className
  633. */
  634. util.removeClassName = function removeClassname(elem, className) {
  635. var classes = elem.className.split(' ');
  636. var index = classes.indexOf(className);
  637. if (index != -1) {
  638. classes.splice(index, 1); // remove the class from the array
  639. elem.className = classes.join(' ');
  640. }
  641. };
  642. /**
  643. * For each method for both arrays and objects.
  644. * In case of an array, the built-in Array.forEach() is applied.
  645. * In case of an Object, the method loops over all properties of the object.
  646. * @param {Object | Array} object An Object or Array
  647. * @param {function} callback Callback method, called for each item in
  648. * the object or array with three parameters:
  649. * callback(value, index, object)
  650. */
  651. util.forEach = function forEach (object, callback) {
  652. var i,
  653. len;
  654. if (object instanceof Array) {
  655. // array
  656. for (i = 0, len = object.length; i < len; i++) {
  657. callback(object[i], i, object);
  658. }
  659. }
  660. else {
  661. // object
  662. for (i in object) {
  663. if (object.hasOwnProperty(i)) {
  664. callback(object[i], i, object);
  665. }
  666. }
  667. }
  668. };
  669. /**
  670. * Update a property in an object
  671. * @param {Object} object
  672. * @param {String} key
  673. * @param {*} value
  674. * @return {Boolean} changed
  675. */
  676. util.updateProperty = function updateProp (object, key, value) {
  677. if (object[key] !== value) {
  678. object[key] = value;
  679. return true;
  680. }
  681. else {
  682. return false;
  683. }
  684. };
  685. /**
  686. * Add and event listener. Works for all browsers
  687. * @param {Element} element An html element
  688. * @param {string} action The action, for example "click",
  689. * without the prefix "on"
  690. * @param {function} listener The callback function to be executed
  691. * @param {boolean} [useCapture]
  692. */
  693. util.addEventListener = function addEventListener(element, action, listener, useCapture) {
  694. if (element.addEventListener) {
  695. if (useCapture === undefined)
  696. useCapture = false;
  697. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  698. action = "DOMMouseScroll"; // For Firefox
  699. }
  700. element.addEventListener(action, listener, useCapture);
  701. } else {
  702. element.attachEvent("on" + action, listener); // IE browsers
  703. }
  704. };
  705. /**
  706. * Remove an event listener from an element
  707. * @param {Element} element An html dom element
  708. * @param {string} action The name of the event, for example "mousedown"
  709. * @param {function} listener The listener function
  710. * @param {boolean} [useCapture]
  711. */
  712. util.removeEventListener = function removeEventListener(element, action, listener, useCapture) {
  713. if (element.removeEventListener) {
  714. // non-IE browsers
  715. if (useCapture === undefined)
  716. useCapture = false;
  717. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  718. action = "DOMMouseScroll"; // For Firefox
  719. }
  720. element.removeEventListener(action, listener, useCapture);
  721. } else {
  722. // IE browsers
  723. element.detachEvent("on" + action, listener);
  724. }
  725. };
  726. /**
  727. * Get HTML element which is the target of the event
  728. * @param {Event} event
  729. * @return {Element} target element
  730. */
  731. util.getTarget = function getTarget(event) {
  732. // code from http://www.quirksmode.org/js/events_properties.html
  733. if (!event) {
  734. event = window.event;
  735. }
  736. var target;
  737. if (event.target) {
  738. target = event.target;
  739. }
  740. else if (event.srcElement) {
  741. target = event.srcElement;
  742. }
  743. if (target.nodeType != undefined && target.nodeType == 3) {
  744. // defeat Safari bug
  745. target = target.parentNode;
  746. }
  747. return target;
  748. };
  749. /**
  750. * Fake a hammer.js gesture. Event can be a ScrollEvent or MouseMoveEvent
  751. * @param {Element} element
  752. * @param {Event} event
  753. */
  754. util.fakeGesture = function fakeGesture (element, event) {
  755. var eventType = null;
  756. // for hammer.js 1.0.5
  757. var gesture = Hammer.event.collectEventData(this, eventType, event);
  758. // for hammer.js 1.0.6
  759. //var touches = Hammer.event.getTouchList(event, eventType);
  760. // var gesture = Hammer.event.collectEventData(this, eventType, touches, event);
  761. // on IE in standards mode, no touches are recognized by hammer.js,
  762. // resulting in NaN values for center.pageX and center.pageY
  763. if (isNaN(gesture.center.pageX)) {
  764. gesture.center.pageX = event.pageX;
  765. }
  766. if (isNaN(gesture.center.pageY)) {
  767. gesture.center.pageY = event.pageY;
  768. }
  769. return gesture;
  770. };
  771. util.option = {};
  772. /**
  773. * Convert a value into a boolean
  774. * @param {Boolean | function | undefined} value
  775. * @param {Boolean} [defaultValue]
  776. * @returns {Boolean} bool
  777. */
  778. util.option.asBoolean = function (value, defaultValue) {
  779. if (typeof value == 'function') {
  780. value = value();
  781. }
  782. if (value != null) {
  783. return (value != false);
  784. }
  785. return defaultValue || null;
  786. };
  787. /**
  788. * Convert a value into a number
  789. * @param {Boolean | function | undefined} value
  790. * @param {Number} [defaultValue]
  791. * @returns {Number} number
  792. */
  793. util.option.asNumber = function (value, defaultValue) {
  794. if (typeof value == 'function') {
  795. value = value();
  796. }
  797. if (value != null) {
  798. return Number(value) || defaultValue || null;
  799. }
  800. return defaultValue || null;
  801. };
  802. /**
  803. * Convert a value into a string
  804. * @param {String | function | undefined} value
  805. * @param {String} [defaultValue]
  806. * @returns {String} str
  807. */
  808. util.option.asString = function (value, defaultValue) {
  809. if (typeof value == 'function') {
  810. value = value();
  811. }
  812. if (value != null) {
  813. return String(value);
  814. }
  815. return defaultValue || null;
  816. };
  817. /**
  818. * Convert a size or location into a string with pixels or a percentage
  819. * @param {String | Number | function | undefined} value
  820. * @param {String} [defaultValue]
  821. * @returns {String} size
  822. */
  823. util.option.asSize = function (value, defaultValue) {
  824. if (typeof value == 'function') {
  825. value = value();
  826. }
  827. if (util.isString(value)) {
  828. return value;
  829. }
  830. else if (util.isNumber(value)) {
  831. return value + 'px';
  832. }
  833. else {
  834. return defaultValue || null;
  835. }
  836. };
  837. /**
  838. * Convert a value into a DOM element
  839. * @param {HTMLElement | function | undefined} value
  840. * @param {HTMLElement} [defaultValue]
  841. * @returns {HTMLElement | null} dom
  842. */
  843. util.option.asElement = function (value, defaultValue) {
  844. if (typeof value == 'function') {
  845. value = value();
  846. }
  847. return value || defaultValue || null;
  848. };
  849. util.GiveDec = function GiveDec(Hex)
  850. {
  851. if(Hex == "A")
  852. Value = 10;
  853. else
  854. if(Hex == "B")
  855. Value = 11;
  856. else
  857. if(Hex == "C")
  858. Value = 12;
  859. else
  860. if(Hex == "D")
  861. Value = 13;
  862. else
  863. if(Hex == "E")
  864. Value = 14;
  865. else
  866. if(Hex == "F")
  867. Value = 15;
  868. else
  869. Value = eval(Hex)
  870. return Value;
  871. }
  872. util.GiveHex = function GiveHex(Dec)
  873. {
  874. if(Dec == 10)
  875. Value = "A";
  876. else
  877. if(Dec == 11)
  878. Value = "B";
  879. else
  880. if(Dec == 12)
  881. Value = "C";
  882. else
  883. if(Dec == 13)
  884. Value = "D";
  885. else
  886. if(Dec == 14)
  887. Value = "E";
  888. else
  889. if(Dec == 15)
  890. Value = "F";
  891. else
  892. Value = "" + Dec;
  893. return Value;
  894. }
  895. /**
  896. * http://www.yellowpipe.com/yis/tools/hex-to-rgb/color-converter.php
  897. *
  898. * @param {String} hex
  899. * @returns {{r: *, g: *, b: *}}
  900. */
  901. util.hexToRGB = function hexToRGB(hex) {
  902. hex = hex.replace("#","").toUpperCase();
  903. var a = util.GiveDec(hex.substring(0, 1));
  904. var b = util.GiveDec(hex.substring(1, 2));
  905. var c = util.GiveDec(hex.substring(2, 3));
  906. var d = util.GiveDec(hex.substring(3, 4));
  907. var e = util.GiveDec(hex.substring(4, 5));
  908. var f = util.GiveDec(hex.substring(5, 6));
  909. var r = (a * 16) + b;
  910. var g = (c * 16) + d;
  911. var b = (e * 16) + f;
  912. return {r:r,g:g,b:b};
  913. };
  914. util.RGBToHex = function RGBToHex(red,green,blue) {
  915. var a = util.GiveHex(Math.floor(red / 16));
  916. var b = util.GiveHex(red % 16);
  917. var c = util.GiveHex(Math.floor(green / 16));
  918. var d = util.GiveHex(green % 16);
  919. var e = util.GiveHex(Math.floor(blue / 16));
  920. var f = util.GiveHex(blue % 16);
  921. var hex = a + b + c + d + e + f;
  922. return "#" + hex;
  923. };
  924. /**
  925. * http://www.javascripter.net/faq/rgb2hsv.htm
  926. *
  927. * @param red
  928. * @param green
  929. * @param blue
  930. * @returns {*}
  931. * @constructor
  932. */
  933. util.RGBToHSV = function RGBToHSV (red,green,blue) {
  934. red=red/255; green=green/255; blue=blue/255;
  935. var minRGB = Math.min(red,Math.min(green,blue));
  936. var maxRGB = Math.max(red,Math.max(green,blue));
  937. // Black-gray-white
  938. if (minRGB == maxRGB) {
  939. return {h:0,s:0,v:minRGB};
  940. }
  941. // Colors other than black-gray-white:
  942. var d = (red==minRGB) ? green-blue : ((blue==minRGB) ? red-green : blue-red);
  943. var h = (red==minRGB) ? 3 : ((blue==minRGB) ? 1 : 5);
  944. var hue = 60*(h - d/(maxRGB - minRGB))/360;
  945. var saturation = (maxRGB - minRGB)/maxRGB;
  946. var value = maxRGB;
  947. return {h:hue,s:saturation,v:value};
  948. };
  949. /**
  950. * https://gist.github.com/mjijackson/5311256
  951. * @param hue
  952. * @param saturation
  953. * @param value
  954. * @returns {{r: number, g: number, b: number}}
  955. * @constructor
  956. */
  957. util.HSVToRGB = function HSVToRGB(h, s, v) {
  958. var r, g, b;
  959. var i = Math.floor(h * 6);
  960. var f = h * 6 - i;
  961. var p = v * (1 - s);
  962. var q = v * (1 - f * s);
  963. var t = v * (1 - (1 - f) * s);
  964. switch (i % 6) {
  965. case 0: r = v, g = t, b = p; break;
  966. case 1: r = q, g = v, b = p; break;
  967. case 2: r = p, g = v, b = t; break;
  968. case 3: r = p, g = q, b = v; break;
  969. case 4: r = t, g = p, b = v; break;
  970. case 5: r = v, g = p, b = q; break;
  971. }
  972. return {r:Math.floor(r * 255), g:Math.floor(g * 255), b:Math.floor(b * 255) };
  973. };
  974. util.HSVToHex = function HSVToHex(h,s,v) {
  975. var rgb = util.HSVToRGB(h,s,v);
  976. return util.RGBToHex(rgb.r,rgb.g,rgb.b);
  977. }
  978. util.hexToHSV = function hexToHSV(hex) {
  979. var rgb = util.hexToRGB(hex);
  980. return util.RGBToHSV(rgb.r,rgb.g,rgb.b);
  981. }
  982. util.isValidHex = function isValidHex(hex) {
  983. var isOk = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(hex);
  984. return isOk;
  985. }
  986. /**
  987. * DataSet
  988. *
  989. * Usage:
  990. * var dataSet = new DataSet({
  991. * fieldId: '_id',
  992. * convert: {
  993. * // ...
  994. * }
  995. * });
  996. *
  997. * dataSet.add(item);
  998. * dataSet.add(data);
  999. * dataSet.update(item);
  1000. * dataSet.update(data);
  1001. * dataSet.remove(id);
  1002. * dataSet.remove(ids);
  1003. * var data = dataSet.get();
  1004. * var data = dataSet.get(id);
  1005. * var data = dataSet.get(ids);
  1006. * var data = dataSet.get(ids, options, data);
  1007. * dataSet.clear();
  1008. *
  1009. * A data set can:
  1010. * - add/remove/update data
  1011. * - gives triggers upon changes in the data
  1012. * - can import/export data in various data formats
  1013. *
  1014. * @param {Object} [options] Available options:
  1015. * {String} fieldId Field name of the id in the
  1016. * items, 'id' by default.
  1017. * {Object.<String, String} convert
  1018. * A map with field names as key,
  1019. * and the field type as value.
  1020. * @constructor DataSet
  1021. */
  1022. // TODO: add a DataSet constructor DataSet(data, options)
  1023. function DataSet (options) {
  1024. this.id = util.randomUUID();
  1025. this.options = options || {};
  1026. this.data = {}; // map with data indexed by id
  1027. this.fieldId = this.options.fieldId || 'id'; // name of the field containing id
  1028. this.convert = {}; // field types by field name
  1029. this.showInternalIds = this.options.showInternalIds || false; // show internal ids with the get function
  1030. if (this.options.convert) {
  1031. for (var field in this.options.convert) {
  1032. if (this.options.convert.hasOwnProperty(field)) {
  1033. var value = this.options.convert[field];
  1034. if (value == 'Date' || value == 'ISODate' || value == 'ASPDate') {
  1035. this.convert[field] = 'Date';
  1036. }
  1037. else {
  1038. this.convert[field] = value;
  1039. }
  1040. }
  1041. }
  1042. }
  1043. // event subscribers
  1044. this.subscribers = {};
  1045. this.internalIds = {}; // internally generated id's
  1046. }
  1047. /**
  1048. * Subscribe to an event, add an event listener
  1049. * @param {String} event Event name. Available events: 'put', 'update',
  1050. * 'remove'
  1051. * @param {function} callback Callback method. Called with three parameters:
  1052. * {String} event
  1053. * {Object | null} params
  1054. * {String | Number} senderId
  1055. */
  1056. DataSet.prototype.on = function on (event, callback) {
  1057. var subscribers = this.subscribers[event];
  1058. if (!subscribers) {
  1059. subscribers = [];
  1060. this.subscribers[event] = subscribers;
  1061. }
  1062. subscribers.push({
  1063. callback: callback
  1064. });
  1065. };
  1066. // TODO: make this function deprecated (replaced with `on` since version 0.5)
  1067. DataSet.prototype.subscribe = DataSet.prototype.on;
  1068. /**
  1069. * Unsubscribe from an event, remove an event listener
  1070. * @param {String} event
  1071. * @param {function} callback
  1072. */
  1073. DataSet.prototype.off = function off(event, callback) {
  1074. var subscribers = this.subscribers[event];
  1075. if (subscribers) {
  1076. this.subscribers[event] = subscribers.filter(function (listener) {
  1077. return (listener.callback != callback);
  1078. });
  1079. }
  1080. };
  1081. // TODO: make this function deprecated (replaced with `on` since version 0.5)
  1082. DataSet.prototype.unsubscribe = DataSet.prototype.off;
  1083. /**
  1084. * Trigger an event
  1085. * @param {String} event
  1086. * @param {Object | null} params
  1087. * @param {String} [senderId] Optional id of the sender.
  1088. * @private
  1089. */
  1090. DataSet.prototype._trigger = function (event, params, senderId) {
  1091. if (event == '*') {
  1092. throw new Error('Cannot trigger event *');
  1093. }
  1094. var subscribers = [];
  1095. if (event in this.subscribers) {
  1096. subscribers = subscribers.concat(this.subscribers[event]);
  1097. }
  1098. if ('*' in this.subscribers) {
  1099. subscribers = subscribers.concat(this.subscribers['*']);
  1100. }
  1101. for (var i = 0; i < subscribers.length; i++) {
  1102. var subscriber = subscribers[i];
  1103. if (subscriber.callback) {
  1104. subscriber.callback(event, params, senderId || null);
  1105. }
  1106. }
  1107. };
  1108. /**
  1109. * Add data.
  1110. * Adding an item will fail when there already is an item with the same id.
  1111. * @param {Object | Array | DataTable} data
  1112. * @param {String} [senderId] Optional sender id
  1113. * @return {Array} addedIds Array with the ids of the added items
  1114. */
  1115. DataSet.prototype.add = function (data, senderId) {
  1116. var addedIds = [],
  1117. id,
  1118. me = this;
  1119. if (data instanceof Array) {
  1120. // Array
  1121. for (var i = 0, len = data.length; i < len; i++) {
  1122. id = me._addItem(data[i]);
  1123. addedIds.push(id);
  1124. }
  1125. }
  1126. else if (util.isDataTable(data)) {
  1127. // Google DataTable
  1128. var columns = this._getColumnNames(data);
  1129. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1130. var item = {};
  1131. for (var col = 0, cols = columns.length; col < cols; col++) {
  1132. var field = columns[col];
  1133. item[field] = data.getValue(row, col);
  1134. }
  1135. id = me._addItem(item);
  1136. addedIds.push(id);
  1137. }
  1138. }
  1139. else if (data instanceof Object) {
  1140. // Single item
  1141. id = me._addItem(data);
  1142. addedIds.push(id);
  1143. }
  1144. else {
  1145. throw new Error('Unknown dataType');
  1146. }
  1147. if (addedIds.length) {
  1148. this._trigger('add', {items: addedIds}, senderId);
  1149. }
  1150. return addedIds;
  1151. };
  1152. /**
  1153. * Update existing items. When an item does not exist, it will be created
  1154. * @param {Object | Array | DataTable} data
  1155. * @param {String} [senderId] Optional sender id
  1156. * @return {Array} updatedIds The ids of the added or updated items
  1157. */
  1158. DataSet.prototype.update = function (data, senderId) {
  1159. var addedIds = [],
  1160. updatedIds = [],
  1161. me = this,
  1162. fieldId = me.fieldId;
  1163. var addOrUpdate = function (item) {
  1164. var id = item[fieldId];
  1165. if (me.data[id]) {
  1166. // update item
  1167. id = me._updateItem(item);
  1168. updatedIds.push(id);
  1169. }
  1170. else {
  1171. // add new item
  1172. id = me._addItem(item);
  1173. addedIds.push(id);
  1174. }
  1175. };
  1176. if (data instanceof Array) {
  1177. // Array
  1178. for (var i = 0, len = data.length; i < len; i++) {
  1179. addOrUpdate(data[i]);
  1180. }
  1181. }
  1182. else if (util.isDataTable(data)) {
  1183. // Google DataTable
  1184. var columns = this._getColumnNames(data);
  1185. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1186. var item = {};
  1187. for (var col = 0, cols = columns.length; col < cols; col++) {
  1188. var field = columns[col];
  1189. item[field] = data.getValue(row, col);
  1190. }
  1191. addOrUpdate(item);
  1192. }
  1193. }
  1194. else if (data instanceof Object) {
  1195. // Single item
  1196. addOrUpdate(data);
  1197. }
  1198. else {
  1199. throw new Error('Unknown dataType');
  1200. }
  1201. if (addedIds.length) {
  1202. this._trigger('add', {items: addedIds}, senderId);
  1203. }
  1204. if (updatedIds.length) {
  1205. this._trigger('update', {items: updatedIds}, senderId);
  1206. }
  1207. return addedIds.concat(updatedIds);
  1208. };
  1209. /**
  1210. * Get a data item or multiple items.
  1211. *
  1212. * Usage:
  1213. *
  1214. * get()
  1215. * get(options: Object)
  1216. * get(options: Object, data: Array | DataTable)
  1217. *
  1218. * get(id: Number | String)
  1219. * get(id: Number | String, options: Object)
  1220. * get(id: Number | String, options: Object, data: Array | DataTable)
  1221. *
  1222. * get(ids: Number[] | String[])
  1223. * get(ids: Number[] | String[], options: Object)
  1224. * get(ids: Number[] | String[], options: Object, data: Array | DataTable)
  1225. *
  1226. * Where:
  1227. *
  1228. * {Number | String} id The id of an item
  1229. * {Number[] | String{}} ids An array with ids of items
  1230. * {Object} options An Object with options. Available options:
  1231. * {String} [type] Type of data to be returned. Can
  1232. * be 'DataTable' or 'Array' (default)
  1233. * {Object.<String, String>} [convert]
  1234. * {String[]} [fields] field names to be returned
  1235. * {function} [filter] filter items
  1236. * {String | function} [order] Order the items by
  1237. * a field name or custom sort function.
  1238. * {Array | DataTable} [data] If provided, items will be appended to this
  1239. * array or table. Required in case of Google
  1240. * DataTable.
  1241. *
  1242. * @throws Error
  1243. */
  1244. DataSet.prototype.get = function (args) {
  1245. var me = this;
  1246. var globalShowInternalIds = this.showInternalIds;
  1247. // parse the arguments
  1248. var id, ids, options, data;
  1249. var firstType = util.getType(arguments[0]);
  1250. if (firstType == 'String' || firstType == 'Number') {
  1251. // get(id [, options] [, data])
  1252. id = arguments[0];
  1253. options = arguments[1];
  1254. data = arguments[2];
  1255. }
  1256. else if (firstType == 'Array') {
  1257. // get(ids [, options] [, data])
  1258. ids = arguments[0];
  1259. options = arguments[1];
  1260. data = arguments[2];
  1261. }
  1262. else {
  1263. // get([, options] [, data])
  1264. options = arguments[0];
  1265. data = arguments[1];
  1266. }
  1267. // determine the return type
  1268. var type;
  1269. if (options && options.type) {
  1270. type = (options.type == 'DataTable') ? 'DataTable' : 'Array';
  1271. if (data && (type != util.getType(data))) {
  1272. throw new Error('Type of parameter "data" (' + util.getType(data) + ') ' +
  1273. 'does not correspond with specified options.type (' + options.type + ')');
  1274. }
  1275. if (type == 'DataTable' && !util.isDataTable(data)) {
  1276. throw new Error('Parameter "data" must be a DataTable ' +
  1277. 'when options.type is "DataTable"');
  1278. }
  1279. }
  1280. else if (data) {
  1281. type = (util.getType(data) == 'DataTable') ? 'DataTable' : 'Array';
  1282. }
  1283. else {
  1284. type = 'Array';
  1285. }
  1286. // we allow the setting of this value for a single get request.
  1287. if (options != undefined) {
  1288. if (options.showInternalIds != undefined) {
  1289. this.showInternalIds = options.showInternalIds;
  1290. }
  1291. }
  1292. // build options
  1293. var convert = options && options.convert || this.options.convert;
  1294. var filter = options && options.filter;
  1295. var items = [], item, itemId, i, len;
  1296. // convert items
  1297. if (id != undefined) {
  1298. // return a single item
  1299. item = me._getItem(id, convert);
  1300. if (filter && !filter(item)) {
  1301. item = null;
  1302. }
  1303. }
  1304. else if (ids != undefined) {
  1305. // return a subset of items
  1306. for (i = 0, len = ids.length; i < len; i++) {
  1307. item = me._getItem(ids[i], convert);
  1308. if (!filter || filter(item)) {
  1309. items.push(item);
  1310. }
  1311. }
  1312. }
  1313. else {
  1314. // return all items
  1315. for (itemId in this.data) {
  1316. if (this.data.hasOwnProperty(itemId)) {
  1317. item = me._getItem(itemId, convert);
  1318. if (!filter || filter(item)) {
  1319. items.push(item);
  1320. }
  1321. }
  1322. }
  1323. }
  1324. // restore the global value of showInternalIds
  1325. this.showInternalIds = globalShowInternalIds;
  1326. // order the results
  1327. if (options && options.order && id == undefined) {
  1328. this._sort(items, options.order);
  1329. }
  1330. // filter fields of the items
  1331. if (options && options.fields) {
  1332. var fields = options.fields;
  1333. if (id != undefined) {
  1334. item = this._filterFields(item, fields);
  1335. }
  1336. else {
  1337. for (i = 0, len = items.length; i < len; i++) {
  1338. items[i] = this._filterFields(items[i], fields);
  1339. }
  1340. }
  1341. }
  1342. // return the results
  1343. if (type == 'DataTable') {
  1344. var columns = this._getColumnNames(data);
  1345. if (id != undefined) {
  1346. // append a single item to the data table
  1347. me._appendRow(data, columns, item);
  1348. }
  1349. else {
  1350. // copy the items to the provided data table
  1351. for (i = 0, len = items.length; i < len; i++) {
  1352. me._appendRow(data, columns, items[i]);
  1353. }
  1354. }
  1355. return data;
  1356. }
  1357. else {
  1358. // return an array
  1359. if (id != undefined) {
  1360. // a single item
  1361. return item;
  1362. }
  1363. else {
  1364. // multiple items
  1365. if (data) {
  1366. // copy the items to the provided array
  1367. for (i = 0, len = items.length; i < len; i++) {
  1368. data.push(items[i]);
  1369. }
  1370. return data;
  1371. }
  1372. else {
  1373. // just return our array
  1374. return items;
  1375. }
  1376. }
  1377. }
  1378. };
  1379. /**
  1380. * Get ids of all items or from a filtered set of items.
  1381. * @param {Object} [options] An Object with options. Available options:
  1382. * {function} [filter] filter items
  1383. * {String | function} [order] Order the items by
  1384. * a field name or custom sort function.
  1385. * @return {Array} ids
  1386. */
  1387. DataSet.prototype.getIds = function (options) {
  1388. var data = this.data,
  1389. filter = options && options.filter,
  1390. order = options && options.order,
  1391. convert = options && options.convert || this.options.convert,
  1392. i,
  1393. len,
  1394. id,
  1395. item,
  1396. items,
  1397. ids = [];
  1398. if (filter) {
  1399. // get filtered items
  1400. if (order) {
  1401. // create ordered list
  1402. items = [];
  1403. for (id in data) {
  1404. if (data.hasOwnProperty(id)) {
  1405. item = this._getItem(id, convert);
  1406. if (filter(item)) {
  1407. items.push(item);
  1408. }
  1409. }
  1410. }
  1411. this._sort(items, order);
  1412. for (i = 0, len = items.length; i < len; i++) {
  1413. ids[i] = items[i][this.fieldId];
  1414. }
  1415. }
  1416. else {
  1417. // create unordered list
  1418. for (id in data) {
  1419. if (data.hasOwnProperty(id)) {
  1420. item = this._getItem(id, convert);
  1421. if (filter(item)) {
  1422. ids.push(item[this.fieldId]);
  1423. }
  1424. }
  1425. }
  1426. }
  1427. }
  1428. else {
  1429. // get all items
  1430. if (order) {
  1431. // create an ordered list
  1432. items = [];
  1433. for (id in data) {
  1434. if (data.hasOwnProperty(id)) {
  1435. items.push(data[id]);
  1436. }
  1437. }
  1438. this._sort(items, order);
  1439. for (i = 0, len = items.length; i < len; i++) {
  1440. ids[i] = items[i][this.fieldId];
  1441. }
  1442. }
  1443. else {
  1444. // create unordered list
  1445. for (id in data) {
  1446. if (data.hasOwnProperty(id)) {
  1447. item = data[id];
  1448. ids.push(item[this.fieldId]);
  1449. }
  1450. }
  1451. }
  1452. }
  1453. return ids;
  1454. };
  1455. /**
  1456. * Execute a callback function for every item in the dataset.
  1457. * The order of the items is not determined.
  1458. * @param {function} callback
  1459. * @param {Object} [options] Available options:
  1460. * {Object.<String, String>} [convert]
  1461. * {String[]} [fields] filter fields
  1462. * {function} [filter] filter items
  1463. * {String | function} [order] Order the items by
  1464. * a field name or custom sort function.
  1465. */
  1466. DataSet.prototype.forEach = function (callback, options) {
  1467. var filter = options && options.filter,
  1468. convert = options && options.convert || this.options.convert,
  1469. data = this.data,
  1470. item,
  1471. id;
  1472. if (options && options.order) {
  1473. // execute forEach on ordered list
  1474. var items = this.get(options);
  1475. for (var i = 0, len = items.length; i < len; i++) {
  1476. item = items[i];
  1477. id = item[this.fieldId];
  1478. callback(item, id);
  1479. }
  1480. }
  1481. else {
  1482. // unordered
  1483. for (id in data) {
  1484. if (data.hasOwnProperty(id)) {
  1485. item = this._getItem(id, convert);
  1486. if (!filter || filter(item)) {
  1487. callback(item, id);
  1488. }
  1489. }
  1490. }
  1491. }
  1492. };
  1493. /**
  1494. * Map every item in the dataset.
  1495. * @param {function} callback
  1496. * @param {Object} [options] Available options:
  1497. * {Object.<String, String>} [convert]
  1498. * {String[]} [fields] filter fields
  1499. * {function} [filter] filter items
  1500. * {String | function} [order] Order the items by
  1501. * a field name or custom sort function.
  1502. * @return {Object[]} mappedItems
  1503. */
  1504. DataSet.prototype.map = function (callback, options) {
  1505. var filter = options && options.filter,
  1506. convert = options && options.convert || this.options.convert,
  1507. mappedItems = [],
  1508. data = this.data,
  1509. item;
  1510. // convert and filter items
  1511. for (var id in data) {
  1512. if (data.hasOwnProperty(id)) {
  1513. item = this._getItem(id, convert);
  1514. if (!filter || filter(item)) {
  1515. mappedItems.push(callback(item, id));
  1516. }
  1517. }
  1518. }
  1519. // order items
  1520. if (options && options.order) {
  1521. this._sort(mappedItems, options.order);
  1522. }
  1523. return mappedItems;
  1524. };
  1525. /**
  1526. * Filter the fields of an item
  1527. * @param {Object} item
  1528. * @param {String[]} fields Field names
  1529. * @return {Object} filteredItem
  1530. * @private
  1531. */
  1532. DataSet.prototype._filterFields = function (item, fields) {
  1533. var filteredItem = {};
  1534. for (var field in item) {
  1535. if (item.hasOwnProperty(field) && (fields.indexOf(field) != -1)) {
  1536. filteredItem[field] = item[field];
  1537. }
  1538. }
  1539. return filteredItem;
  1540. };
  1541. /**
  1542. * Sort the provided array with items
  1543. * @param {Object[]} items
  1544. * @param {String | function} order A field name or custom sort function.
  1545. * @private
  1546. */
  1547. DataSet.prototype._sort = function (items, order) {
  1548. if (util.isString(order)) {
  1549. // order by provided field name
  1550. var name = order; // field name
  1551. items.sort(function (a, b) {
  1552. var av = a[name];
  1553. var bv = b[name];
  1554. return (av > bv) ? 1 : ((av < bv) ? -1 : 0);
  1555. });
  1556. }
  1557. else if (typeof order === 'function') {
  1558. // order by sort function
  1559. items.sort(order);
  1560. }
  1561. // TODO: extend order by an Object {field:String, direction:String}
  1562. // where direction can be 'asc' or 'desc'
  1563. else {
  1564. throw new TypeError('Order must be a function or a string');
  1565. }
  1566. };
  1567. /**
  1568. * Remove an object by pointer or by id
  1569. * @param {String | Number | Object | Array} id Object or id, or an array with
  1570. * objects or ids to be removed
  1571. * @param {String} [senderId] Optional sender id
  1572. * @return {Array} removedIds
  1573. */
  1574. DataSet.prototype.remove = function (id, senderId) {
  1575. var removedIds = [],
  1576. i, len, removedId;
  1577. if (id instanceof Array) {
  1578. for (i = 0, len = id.length; i < len; i++) {
  1579. removedId = this._remove(id[i]);
  1580. if (removedId != null) {
  1581. removedIds.push(removedId);
  1582. }
  1583. }
  1584. }
  1585. else {
  1586. removedId = this._remove(id);
  1587. if (removedId != null) {
  1588. removedIds.push(removedId);
  1589. }
  1590. }
  1591. if (removedIds.length) {
  1592. this._trigger('remove', {items: removedIds}, senderId);
  1593. }
  1594. return removedIds;
  1595. };
  1596. /**
  1597. * Remove an item by its id
  1598. * @param {Number | String | Object} id id or item
  1599. * @returns {Number | String | null} id
  1600. * @private
  1601. */
  1602. DataSet.prototype._remove = function (id) {
  1603. if (util.isNumber(id) || util.isString(id)) {
  1604. if (this.data[id]) {
  1605. delete this.data[id];
  1606. delete this.internalIds[id];
  1607. return id;
  1608. }
  1609. }
  1610. else if (id instanceof Object) {
  1611. var itemId = id[this.fieldId];
  1612. if (itemId && this.data[itemId]) {
  1613. delete this.data[itemId];
  1614. delete this.internalIds[itemId];
  1615. return itemId;
  1616. }
  1617. }
  1618. return null;
  1619. };
  1620. /**
  1621. * Clear the data
  1622. * @param {String} [senderId] Optional sender id
  1623. * @return {Array} removedIds The ids of all removed items
  1624. */
  1625. DataSet.prototype.clear = function (senderId) {
  1626. var ids = Object.keys(this.data);
  1627. this.data = {};
  1628. this.internalIds = {};
  1629. this._trigger('remove', {items: ids}, senderId);
  1630. return ids;
  1631. };
  1632. /**
  1633. * Find the item with maximum value of a specified field
  1634. * @param {String} field
  1635. * @return {Object | null} item Item containing max value, or null if no items
  1636. */
  1637. DataSet.prototype.max = function (field) {
  1638. var data = this.data,
  1639. max = null,
  1640. maxField = null;
  1641. for (var id in data) {
  1642. if (data.hasOwnProperty(id)) {
  1643. var item = data[id];
  1644. var itemField = item[field];
  1645. if (itemField != null && (!max || itemField > maxField)) {
  1646. max = item;
  1647. maxField = itemField;
  1648. }
  1649. }
  1650. }
  1651. return max;
  1652. };
  1653. /**
  1654. * Find the item with minimum value of a specified field
  1655. * @param {String} field
  1656. * @return {Object | null} item Item containing max value, or null if no items
  1657. */
  1658. DataSet.prototype.min = function (field) {
  1659. var data = this.data,
  1660. min = null,
  1661. minField = null;
  1662. for (var id in data) {
  1663. if (data.hasOwnProperty(id)) {
  1664. var item = data[id];
  1665. var itemField = item[field];
  1666. if (itemField != null && (!min || itemField < minField)) {
  1667. min = item;
  1668. minField = itemField;
  1669. }
  1670. }
  1671. }
  1672. return min;
  1673. };
  1674. /**
  1675. * Find all distinct values of a specified field
  1676. * @param {String} field
  1677. * @return {Array} values Array containing all distinct values. If the data
  1678. * items do not contain the specified field, an array
  1679. * containing a single value undefined is returned.
  1680. * The returned array is unordered.
  1681. */
  1682. DataSet.prototype.distinct = function (field) {
  1683. var data = this.data,
  1684. values = [],
  1685. fieldType = this.options.convert[field],
  1686. count = 0;
  1687. for (var prop in data) {
  1688. if (data.hasOwnProperty(prop)) {
  1689. var item = data[prop];
  1690. var value = util.convert(item[field], fieldType);
  1691. var exists = false;
  1692. for (var i = 0; i < count; i++) {
  1693. if (values[i] == value) {
  1694. exists = true;
  1695. break;
  1696. }
  1697. }
  1698. if (!exists) {
  1699. values[count] = value;
  1700. count++;
  1701. }
  1702. }
  1703. }
  1704. return values;
  1705. };
  1706. /**
  1707. * Add a single item. Will fail when an item with the same id already exists.
  1708. * @param {Object} item
  1709. * @return {String} id
  1710. * @private
  1711. */
  1712. DataSet.prototype._addItem = function (item) {
  1713. var id = item[this.fieldId];
  1714. if (id != undefined) {
  1715. // check whether this id is already taken
  1716. if (this.data[id]) {
  1717. // item already exists
  1718. throw new Error('Cannot add item: item with id ' + id + ' already exists');
  1719. }
  1720. }
  1721. else {
  1722. // generate an id
  1723. id = util.randomUUID();
  1724. item[this.fieldId] = id;
  1725. this.internalIds[id] = item;
  1726. }
  1727. var d = {};
  1728. for (var field in item) {
  1729. if (item.hasOwnProperty(field)) {
  1730. var fieldType = this.convert[field]; // type may be undefined
  1731. d[field] = util.convert(item[field], fieldType);
  1732. }
  1733. }
  1734. this.data[id] = d;
  1735. return id;
  1736. };
  1737. /**
  1738. * Get an item. Fields can be converted to a specific type
  1739. * @param {String} id
  1740. * @param {Object.<String, String>} [convert] field types to convert
  1741. * @return {Object | null} item
  1742. * @private
  1743. */
  1744. DataSet.prototype._getItem = function (id, convert) {
  1745. var field, value;
  1746. // get the item from the dataset
  1747. var raw = this.data[id];
  1748. if (!raw) {
  1749. return null;
  1750. }
  1751. // convert the items field types
  1752. var converted = {},
  1753. fieldId = this.fieldId,
  1754. internalIds = this.internalIds;
  1755. if (convert) {
  1756. for (field in raw) {
  1757. if (raw.hasOwnProperty(field)) {
  1758. value = raw[field];
  1759. // output all fields, except internal ids
  1760. if ((field != fieldId) || (!(value in internalIds) || this.showInternalIds)) {
  1761. converted[field] = util.convert(value, convert[field]);
  1762. }
  1763. }
  1764. }
  1765. }
  1766. else {
  1767. // no field types specified, no converting needed
  1768. for (field in raw) {
  1769. if (raw.hasOwnProperty(field)) {
  1770. value = raw[field];
  1771. // output all fields, except internal ids
  1772. if ((field != fieldId) || (!(value in internalIds) || this.showInternalIds)) {
  1773. converted[field] = value;
  1774. }
  1775. }
  1776. }
  1777. }
  1778. return converted;
  1779. };
  1780. /**
  1781. * Update a single item: merge with existing item.
  1782. * Will fail when the item has no id, or when there does not exist an item
  1783. * with the same id.
  1784. * @param {Object} item
  1785. * @return {String} id
  1786. * @private
  1787. */
  1788. DataSet.prototype._updateItem = function (item) {
  1789. var id = item[this.fieldId];
  1790. if (id == undefined) {
  1791. throw new Error('Cannot update item: item has no id (item: ' + JSON.stringify(item) + ')');
  1792. }
  1793. var d = this.data[id];
  1794. if (!d) {
  1795. // item doesn't exist
  1796. throw new Error('Cannot update item: no item with id ' + id + ' found');
  1797. }
  1798. // merge with current item
  1799. for (var field in item) {
  1800. if (item.hasOwnProperty(field)) {
  1801. var fieldType = this.convert[field]; // type may be undefined
  1802. d[field] = util.convert(item[field], fieldType);
  1803. }
  1804. }
  1805. return id;
  1806. };
  1807. /**
  1808. * check if an id is an internal or external id
  1809. * @param id
  1810. * @returns {boolean}
  1811. * @private
  1812. */
  1813. DataSet.prototype.isInternalId = function(id) {
  1814. return (id in this.internalIds);
  1815. };
  1816. /**
  1817. * Get an array with the column names of a Google DataTable
  1818. * @param {DataTable} dataTable
  1819. * @return {String[]} columnNames
  1820. * @private
  1821. */
  1822. DataSet.prototype._getColumnNames = function (dataTable) {
  1823. var columns = [];
  1824. for (var col = 0, cols = dataTable.getNumberOfColumns(); col < cols; col++) {
  1825. columns[col] = dataTable.getColumnId(col) || dataTable.getColumnLabel(col);
  1826. }
  1827. return columns;
  1828. };
  1829. /**
  1830. * Append an item as a row to the dataTable
  1831. * @param dataTable
  1832. * @param columns
  1833. * @param item
  1834. * @private
  1835. */
  1836. DataSet.prototype._appendRow = function (dataTable, columns, item) {
  1837. var row = dataTable.addRow();
  1838. for (var col = 0, cols = columns.length; col < cols; col++) {
  1839. var field = columns[col];
  1840. dataTable.setValue(row, col, item[field]);
  1841. }
  1842. };
  1843. /**
  1844. * DataView
  1845. *
  1846. * a dataview offers a filtered view on a dataset or an other dataview.
  1847. *
  1848. * @param {DataSet | DataView} data
  1849. * @param {Object} [options] Available options: see method get
  1850. *
  1851. * @constructor DataView
  1852. */
  1853. function DataView (data, options) {
  1854. this.id = util.randomUUID();
  1855. this.data = null;
  1856. this.ids = {}; // ids of the items currently in memory (just contains a boolean true)
  1857. this.options = options || {};
  1858. this.fieldId = 'id'; // name of the field containing id
  1859. this.subscribers = {}; // event subscribers
  1860. var me = this;
  1861. this.listener = function () {
  1862. me._onEvent.apply(me, arguments);
  1863. };
  1864. this.setData(data);
  1865. }
  1866. // TODO: implement a function .config() to dynamically update things like configured filter
  1867. // and trigger changes accordingly
  1868. /**
  1869. * Set a data source for the view
  1870. * @param {DataSet | DataView} data
  1871. */
  1872. DataView.prototype.setData = function (data) {
  1873. var ids, dataItems, i, len;
  1874. if (this.data) {
  1875. // unsubscribe from current dataset
  1876. if (this.data.unsubscribe) {
  1877. this.data.unsubscribe('*', this.listener);
  1878. }
  1879. // trigger a remove of all items in memory
  1880. ids = [];
  1881. for (var id in this.ids) {
  1882. if (this.ids.hasOwnProperty(id)) {
  1883. ids.push(id);
  1884. }
  1885. }
  1886. this.ids = {};
  1887. this._trigger('remove', {items: ids});
  1888. }
  1889. this.data = data;
  1890. if (this.data) {
  1891. // update fieldId
  1892. this.fieldId = this.options.fieldId ||
  1893. (this.data && this.data.options && this.data.options.fieldId) ||
  1894. 'id';
  1895. // trigger an add of all added items
  1896. ids = this.data.getIds({filter: this.options && this.options.filter});
  1897. for (i = 0, len = ids.length; i < len; i++) {
  1898. id = ids[i];
  1899. this.ids[id] = true;
  1900. }
  1901. this._trigger('add', {items: ids});
  1902. // subscribe to new dataset
  1903. if (this.data.on) {
  1904. this.data.on('*', this.listener);
  1905. }
  1906. }
  1907. };
  1908. /**
  1909. * Get data from the data view
  1910. *
  1911. * Usage:
  1912. *
  1913. * get()
  1914. * get(options: Object)
  1915. * get(options: Object, data: Array | DataTable)
  1916. *
  1917. * get(id: Number)
  1918. * get(id: Number, options: Object)
  1919. * get(id: Number, options: Object, data: Array | DataTable)
  1920. *
  1921. * get(ids: Number[])
  1922. * get(ids: Number[], options: Object)
  1923. * get(ids: Number[], options: Object, data: Array | DataTable)
  1924. *
  1925. * Where:
  1926. *
  1927. * {Number | String} id The id of an item
  1928. * {Number[] | String{}} ids An array with ids of items
  1929. * {Object} options An Object with options. Available options:
  1930. * {String} [type] Type of data to be returned. Can
  1931. * be 'DataTable' or 'Array' (default)
  1932. * {Object.<String, String>} [convert]
  1933. * {String[]} [fields] field names to be returned
  1934. * {function} [filter] filter items
  1935. * {String | function} [order] Order the items by
  1936. * a field name or custom sort function.
  1937. * {Array | DataTable} [data] If provided, items will be appended to this
  1938. * array or table. Required in case of Google
  1939. * DataTable.
  1940. * @param args
  1941. */
  1942. DataView.prototype.get = function (args) {
  1943. var me = this;
  1944. // parse the arguments
  1945. var ids, options, data;
  1946. var firstType = util.getType(arguments[0]);
  1947. if (firstType == 'String' || firstType == 'Number' || firstType == 'Array') {
  1948. // get(id(s) [, options] [, data])
  1949. ids = arguments[0]; // can be a single id or an array with ids
  1950. options = arguments[1];
  1951. data = arguments[2];
  1952. }
  1953. else {
  1954. // get([, options] [, data])
  1955. options = arguments[0];
  1956. data = arguments[1];
  1957. }
  1958. // extend the options with the default options and provided options
  1959. var viewOptions = util.extend({}, this.options, options);
  1960. // create a combined filter method when needed
  1961. if (this.options.filter && options && options.filter) {
  1962. viewOptions.filter = function (item) {
  1963. return me.options.filter(item) && options.filter(item);
  1964. }
  1965. }
  1966. // build up the call to the linked data set
  1967. var getArguments = [];
  1968. if (ids != undefined) {
  1969. getArguments.push(ids);
  1970. }
  1971. getArguments.push(viewOptions);
  1972. getArguments.push(data);
  1973. return this.data && this.data.get.apply(this.data, getArguments);
  1974. };
  1975. /**
  1976. * Get ids of all items or from a filtered set of items.
  1977. * @param {Object} [options] An Object with options. Available options:
  1978. * {function} [filter] filter items
  1979. * {String | function} [order] Order the items by
  1980. * a field name or custom sort function.
  1981. * @return {Array} ids
  1982. */
  1983. DataView.prototype.getIds = function (options) {
  1984. var ids;
  1985. if (this.data) {
  1986. var defaultFilter = this.options.filter;
  1987. var filter;
  1988. if (options && options.filter) {
  1989. if (defaultFilter) {
  1990. filter = function (item) {
  1991. return defaultFilter(item) && options.filter(item);
  1992. }
  1993. }
  1994. else {
  1995. filter = options.filter;
  1996. }
  1997. }
  1998. else {
  1999. filter = defaultFilter;
  2000. }
  2001. ids = this.data.getIds({
  2002. filter: filter,
  2003. order: options && options.order
  2004. });
  2005. }
  2006. else {
  2007. ids = [];
  2008. }
  2009. return ids;
  2010. };
  2011. /**
  2012. * Event listener. Will propagate all events from the connected data set to
  2013. * the subscribers of the DataView, but will filter the items and only trigger
  2014. * when there are changes in the filtered data set.
  2015. * @param {String} event
  2016. * @param {Object | null} params
  2017. * @param {String} senderId
  2018. * @private
  2019. */
  2020. DataView.prototype._onEvent = function (event, params, senderId) {
  2021. var i, len, id, item,
  2022. ids = params && params.items,
  2023. data = this.data,
  2024. added = [],
  2025. updated = [],
  2026. removed = [];
  2027. if (ids && data) {
  2028. switch (event) {
  2029. case 'add':
  2030. // filter the ids of the added items
  2031. for (i = 0, len = ids.length; i < len; i++) {
  2032. id = ids[i];
  2033. item = this.get(id);
  2034. if (item) {
  2035. this.ids[id] = true;
  2036. added.push(id);
  2037. }
  2038. }
  2039. break;
  2040. case 'update':
  2041. // determine the event from the views viewpoint: an updated
  2042. // item can be added, updated, or removed from this view.
  2043. for (i = 0, len = ids.length; i < len; i++) {
  2044. id = ids[i];
  2045. item = this.get(id);
  2046. if (item) {
  2047. if (this.ids[id]) {
  2048. updated.push(id);
  2049. }
  2050. else {
  2051. this.ids[id] = true;
  2052. added.push(id);
  2053. }
  2054. }
  2055. else {
  2056. if (this.ids[id]) {
  2057. delete this.ids[id];
  2058. removed.push(id);
  2059. }
  2060. else {
  2061. // nothing interesting for me :-(
  2062. }
  2063. }
  2064. }
  2065. break;
  2066. case 'remove':
  2067. // filter the ids of the removed items
  2068. for (i = 0, len = ids.length; i < len; i++) {
  2069. id = ids[i];
  2070. if (this.ids[id]) {
  2071. delete this.ids[id];
  2072. removed.push(id);
  2073. }
  2074. }
  2075. break;
  2076. }
  2077. if (added.length) {
  2078. this._trigger('add', {items: added}, senderId);
  2079. }
  2080. if (updated.length) {
  2081. this._trigger('update', {items: updated}, senderId);
  2082. }
  2083. if (removed.length) {
  2084. this._trigger('remove', {items: removed}, senderId);
  2085. }
  2086. }
  2087. };
  2088. // copy subscription functionality from DataSet
  2089. DataView.prototype.on = DataSet.prototype.on;
  2090. DataView.prototype.off = DataSet.prototype.off;
  2091. DataView.prototype._trigger = DataSet.prototype._trigger;
  2092. // TODO: make these functions deprecated (replaced with `on` and `off` since version 0.5)
  2093. DataView.prototype.subscribe = DataView.prototype.on;
  2094. DataView.prototype.unsubscribe = DataView.prototype.off;
  2095. /**
  2096. * @constructor TimeStep
  2097. * The class TimeStep is an iterator for dates. You provide a start date and an
  2098. * end date. The class itself determines the best scale (step size) based on the
  2099. * provided start Date, end Date, and minimumStep.
  2100. *
  2101. * If minimumStep is provided, the step size is chosen as close as possible
  2102. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2103. * provided, the scale is set to 1 DAY.
  2104. * The minimumStep should correspond with the onscreen size of about 6 characters
  2105. *
  2106. * Alternatively, you can set a scale by hand.
  2107. * After creation, you can initialize the class by executing first(). Then you
  2108. * can iterate from the start date to the end date via next(). You can check if
  2109. * the end date is reached with the function hasNext(). After each step, you can
  2110. * retrieve the current date via getCurrent().
  2111. * The TimeStep has scales ranging from milliseconds, seconds, minutes, hours,
  2112. * days, to years.
  2113. *
  2114. * Version: 1.2
  2115. *
  2116. * @param {Date} [start] The start date, for example new Date(2010, 9, 21)
  2117. * or new Date(2010, 9, 21, 23, 45, 00)
  2118. * @param {Date} [end] The end date
  2119. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  2120. */
  2121. TimeStep = function(start, end, minimumStep) {
  2122. // variables
  2123. this.current = new Date();
  2124. this._start = new Date();
  2125. this._end = new Date();
  2126. this.autoScale = true;
  2127. this.scale = TimeStep.SCALE.DAY;
  2128. this.step = 1;
  2129. // initialize the range
  2130. this.setRange(start, end, minimumStep);
  2131. };
  2132. /// enum scale
  2133. TimeStep.SCALE = {
  2134. MILLISECOND: 1,
  2135. SECOND: 2,
  2136. MINUTE: 3,
  2137. HOUR: 4,
  2138. DAY: 5,
  2139. WEEKDAY: 6,
  2140. MONTH: 7,
  2141. YEAR: 8
  2142. };
  2143. /**
  2144. * Set a new range
  2145. * If minimumStep is provided, the step size is chosen as close as possible
  2146. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2147. * provided, the scale is set to 1 DAY.
  2148. * The minimumStep should correspond with the onscreen size of about 6 characters
  2149. * @param {Date} [start] The start date and time.
  2150. * @param {Date} [end] The end date and time.
  2151. * @param {int} [minimumStep] Optional. Minimum step size in milliseconds
  2152. */
  2153. TimeStep.prototype.setRange = function(start, end, minimumStep) {
  2154. if (!(start instanceof Date) || !(end instanceof Date)) {
  2155. throw "No legal start or end date in method setRange";
  2156. }
  2157. this._start = (start != undefined) ? new Date(start.valueOf()) : new Date();
  2158. this._end = (end != undefined) ? new Date(end.valueOf()) : new Date();
  2159. if (this.autoScale) {
  2160. this.setMinimumStep(minimumStep);
  2161. }
  2162. };
  2163. /**
  2164. * Set the range iterator to the start date.
  2165. */
  2166. TimeStep.prototype.first = function() {
  2167. this.current = new Date(this._start.valueOf());
  2168. this.roundToMinor();
  2169. };
  2170. /**
  2171. * Round the current date to the first minor date value
  2172. * This must be executed once when the current date is set to start Date
  2173. */
  2174. TimeStep.prototype.roundToMinor = function() {
  2175. // round to floor
  2176. // IMPORTANT: we have no breaks in this switch! (this is no bug)
  2177. //noinspection FallthroughInSwitchStatementJS
  2178. switch (this.scale) {
  2179. case TimeStep.SCALE.YEAR:
  2180. this.current.setFullYear(this.step * Math.floor(this.current.getFullYear() / this.step));
  2181. this.current.setMonth(0);
  2182. case TimeStep.SCALE.MONTH: this.current.setDate(1);
  2183. case TimeStep.SCALE.DAY: // intentional fall through
  2184. case TimeStep.SCALE.WEEKDAY: this.current.setHours(0);
  2185. case TimeStep.SCALE.HOUR: this.current.setMinutes(0);
  2186. case TimeStep.SCALE.MINUTE: this.current.setSeconds(0);
  2187. case TimeStep.SCALE.SECOND: this.current.setMilliseconds(0);
  2188. //case TimeStep.SCALE.MILLISECOND: // nothing to do for milliseconds
  2189. }
  2190. if (this.step != 1) {
  2191. // round down to the first minor value that is a multiple of the current step size
  2192. switch (this.scale) {
  2193. case TimeStep.SCALE.MILLISECOND: this.current.setMilliseconds(this.current.getMilliseconds() - this.current.getMilliseconds() % this.step); break;
  2194. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() - this.current.getSeconds() % this.step); break;
  2195. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() - this.current.getMinutes() % this.step); break;
  2196. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() - this.current.getHours() % this.step); break;
  2197. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2198. case TimeStep.SCALE.DAY: this.current.setDate((this.current.getDate()-1) - (this.current.getDate()-1) % this.step + 1); break;
  2199. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() - this.current.getMonth() % this.step); break;
  2200. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() - this.current.getFullYear() % this.step); break;
  2201. default: break;
  2202. }
  2203. }
  2204. };
  2205. /**
  2206. * Check if the there is a next step
  2207. * @return {boolean} true if the current date has not passed the end date
  2208. */
  2209. TimeStep.prototype.hasNext = function () {
  2210. return (this.current.valueOf() <= this._end.valueOf());
  2211. };
  2212. /**
  2213. * Do the next step
  2214. */
  2215. TimeStep.prototype.next = function() {
  2216. var prev = this.current.valueOf();
  2217. // Two cases, needed to prevent issues with switching daylight savings
  2218. // (end of March and end of October)
  2219. if (this.current.getMonth() < 6) {
  2220. switch (this.scale) {
  2221. case TimeStep.SCALE.MILLISECOND:
  2222. this.current = new Date(this.current.valueOf() + this.step); break;
  2223. case TimeStep.SCALE.SECOND: this.current = new Date(this.current.valueOf() + this.step * 1000); break;
  2224. case TimeStep.SCALE.MINUTE: this.current = new Date(this.current.valueOf() + this.step * 1000 * 60); break;
  2225. case TimeStep.SCALE.HOUR:
  2226. this.current = new Date(this.current.valueOf() + this.step * 1000 * 60 * 60);
  2227. // in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...)
  2228. var h = this.current.getHours();
  2229. this.current.setHours(h - (h % this.step));
  2230. break;
  2231. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2232. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2233. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2234. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2235. default: break;
  2236. }
  2237. }
  2238. else {
  2239. switch (this.scale) {
  2240. case TimeStep.SCALE.MILLISECOND: this.current = new Date(this.current.valueOf() + this.step); break;
  2241. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() + this.step); break;
  2242. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() + this.step); break;
  2243. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() + this.step); break;
  2244. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2245. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2246. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2247. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2248. default: break;
  2249. }
  2250. }
  2251. if (this.step != 1) {
  2252. // round down to the correct major value
  2253. switch (this.scale) {
  2254. case TimeStep.SCALE.MILLISECOND: if(this.current.getMilliseconds() < this.step) this.current.setMilliseconds(0); break;
  2255. case TimeStep.SCALE.SECOND: if(this.current.getSeconds() < this.step) this.current.setSeconds(0); break;
  2256. case TimeStep.SCALE.MINUTE: if(this.current.getMinutes() < this.step) this.current.setMinutes(0); break;
  2257. case TimeStep.SCALE.HOUR: if(this.current.getHours() < this.step) this.current.setHours(0); break;
  2258. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2259. case TimeStep.SCALE.DAY: if(this.current.getDate() < this.step+1) this.current.setDate(1); break;
  2260. case TimeStep.SCALE.MONTH: if(this.current.getMonth() < this.step) this.current.setMonth(0); break;
  2261. case TimeStep.SCALE.YEAR: break; // nothing to do for year
  2262. default: break;
  2263. }
  2264. }
  2265. // safety mechanism: if current time is still unchanged, move to the end
  2266. if (this.current.valueOf() == prev) {
  2267. this.current = new Date(this._end.valueOf());
  2268. }
  2269. };
  2270. /**
  2271. * Get the current datetime
  2272. * @return {Date} current The current date
  2273. */
  2274. TimeStep.prototype.getCurrent = function() {
  2275. return this.current;
  2276. };
  2277. /**
  2278. * Set a custom scale. Autoscaling will be disabled.
  2279. * For example setScale(SCALE.MINUTES, 5) will result
  2280. * in minor steps of 5 minutes, and major steps of an hour.
  2281. *
  2282. * @param {TimeStep.SCALE} newScale
  2283. * A scale. Choose from SCALE.MILLISECOND,
  2284. * SCALE.SECOND, SCALE.MINUTE, SCALE.HOUR,
  2285. * SCALE.WEEKDAY, SCALE.DAY, SCALE.MONTH,
  2286. * SCALE.YEAR.
  2287. * @param {Number} newStep A step size, by default 1. Choose for
  2288. * example 1, 2, 5, or 10.
  2289. */
  2290. TimeStep.prototype.setScale = function(newScale, newStep) {
  2291. this.scale = newScale;
  2292. if (newStep > 0) {
  2293. this.step = newStep;
  2294. }
  2295. this.autoScale = false;
  2296. };
  2297. /**
  2298. * Enable or disable autoscaling
  2299. * @param {boolean} enable If true, autoascaling is set true
  2300. */
  2301. TimeStep.prototype.setAutoScale = function (enable) {
  2302. this.autoScale = enable;
  2303. };
  2304. /**
  2305. * Automatically determine the scale that bests fits the provided minimum step
  2306. * @param {Number} [minimumStep] The minimum step size in milliseconds
  2307. */
  2308. TimeStep.prototype.setMinimumStep = function(minimumStep) {
  2309. if (minimumStep == undefined) {
  2310. return;
  2311. }
  2312. var stepYear = (1000 * 60 * 60 * 24 * 30 * 12);
  2313. var stepMonth = (1000 * 60 * 60 * 24 * 30);
  2314. var stepDay = (1000 * 60 * 60 * 24);
  2315. var stepHour = (1000 * 60 * 60);
  2316. var stepMinute = (1000 * 60);
  2317. var stepSecond = (1000);
  2318. var stepMillisecond= (1);
  2319. // find the smallest step that is larger than the provided minimumStep
  2320. if (stepYear*1000 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1000;}
  2321. if (stepYear*500 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 500;}
  2322. if (stepYear*100 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 100;}
  2323. if (stepYear*50 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 50;}
  2324. if (stepYear*10 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 10;}
  2325. if (stepYear*5 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 5;}
  2326. if (stepYear > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1;}
  2327. if (stepMonth*3 > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 3;}
  2328. if (stepMonth > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 1;}
  2329. if (stepDay*5 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 5;}
  2330. if (stepDay*2 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 2;}
  2331. if (stepDay > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 1;}
  2332. if (stepDay/2 > minimumStep) {this.scale = TimeStep.SCALE.WEEKDAY; this.step = 1;}
  2333. if (stepHour*4 > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 4;}
  2334. if (stepHour > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 1;}
  2335. if (stepMinute*15 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 15;}
  2336. if (stepMinute*10 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 10;}
  2337. if (stepMinute*5 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 5;}
  2338. if (stepMinute > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 1;}
  2339. if (stepSecond*15 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 15;}
  2340. if (stepSecond*10 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 10;}
  2341. if (stepSecond*5 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 5;}
  2342. if (stepSecond > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 1;}
  2343. if (stepMillisecond*200 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 200;}
  2344. if (stepMillisecond*100 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 100;}
  2345. if (stepMillisecond*50 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 50;}
  2346. if (stepMillisecond*10 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 10;}
  2347. if (stepMillisecond*5 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 5;}
  2348. if (stepMillisecond > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 1;}
  2349. };
  2350. /**
  2351. * Snap a date to a rounded value.
  2352. * The snap intervals are dependent on the current scale and step.
  2353. * @param {Date} date the date to be snapped.
  2354. * @return {Date} snappedDate
  2355. */
  2356. TimeStep.prototype.snap = function(date) {
  2357. var clone = new Date(date.valueOf());
  2358. if (this.scale == TimeStep.SCALE.YEAR) {
  2359. var year = clone.getFullYear() + Math.round(clone.getMonth() / 12);
  2360. clone.setFullYear(Math.round(year / this.step) * this.step);
  2361. clone.setMonth(0);
  2362. clone.setDate(0);
  2363. clone.setHours(0);
  2364. clone.setMinutes(0);
  2365. clone.setSeconds(0);
  2366. clone.setMilliseconds(0);
  2367. }
  2368. else if (this.scale == TimeStep.SCALE.MONTH) {
  2369. if (clone.getDate() > 15) {
  2370. clone.setDate(1);
  2371. clone.setMonth(clone.getMonth() + 1);
  2372. // important: first set Date to 1, after that change the month.
  2373. }
  2374. else {
  2375. clone.setDate(1);
  2376. }
  2377. clone.setHours(0);
  2378. clone.setMinutes(0);
  2379. clone.setSeconds(0);
  2380. clone.setMilliseconds(0);
  2381. }
  2382. else if (this.scale == TimeStep.SCALE.DAY ||
  2383. this.scale == TimeStep.SCALE.WEEKDAY) {
  2384. //noinspection FallthroughInSwitchStatementJS
  2385. switch (this.step) {
  2386. case 5:
  2387. case 2:
  2388. clone.setHours(Math.round(clone.getHours() / 24) * 24); break;
  2389. default:
  2390. clone.setHours(Math.round(clone.getHours() / 12) * 12); break;
  2391. }
  2392. clone.setMinutes(0);
  2393. clone.setSeconds(0);
  2394. clone.setMilliseconds(0);
  2395. }
  2396. else if (this.scale == TimeStep.SCALE.HOUR) {
  2397. switch (this.step) {
  2398. case 4:
  2399. clone.setMinutes(Math.round(clone.getMinutes() / 60) * 60); break;
  2400. default:
  2401. clone.setMinutes(Math.round(clone.getMinutes() / 30) * 30); break;
  2402. }
  2403. clone.setSeconds(0);
  2404. clone.setMilliseconds(0);
  2405. } else if (this.scale == TimeStep.SCALE.MINUTE) {
  2406. //noinspection FallthroughInSwitchStatementJS
  2407. switch (this.step) {
  2408. case 15:
  2409. case 10:
  2410. clone.setMinutes(Math.round(clone.getMinutes() / 5) * 5);
  2411. clone.setSeconds(0);
  2412. break;
  2413. case 5:
  2414. clone.setSeconds(Math.round(clone.getSeconds() / 60) * 60); break;
  2415. default:
  2416. clone.setSeconds(Math.round(clone.getSeconds() / 30) * 30); break;
  2417. }
  2418. clone.setMilliseconds(0);
  2419. }
  2420. else if (this.scale == TimeStep.SCALE.SECOND) {
  2421. //noinspection FallthroughInSwitchStatementJS
  2422. switch (this.step) {
  2423. case 15:
  2424. case 10:
  2425. clone.setSeconds(Math.round(clone.getSeconds() / 5) * 5);
  2426. clone.setMilliseconds(0);
  2427. break;
  2428. case 5:
  2429. clone.setMilliseconds(Math.round(clone.getMilliseconds() / 1000) * 1000); break;
  2430. default:
  2431. clone.setMilliseconds(Math.round(clone.getMilliseconds() / 500) * 500); break;
  2432. }
  2433. }
  2434. else if (this.scale == TimeStep.SCALE.MILLISECOND) {
  2435. var step = this.step > 5 ? this.step / 2 : 1;
  2436. clone.setMilliseconds(Math.round(clone.getMilliseconds() / step) * step);
  2437. }
  2438. return clone;
  2439. };
  2440. /**
  2441. * Check if the current value is a major value (for example when the step
  2442. * is DAY, a major value is each first day of the MONTH)
  2443. * @return {boolean} true if current date is major, else false.
  2444. */
  2445. TimeStep.prototype.isMajor = function() {
  2446. switch (this.scale) {
  2447. case TimeStep.SCALE.MILLISECOND:
  2448. return (this.current.getMilliseconds() == 0);
  2449. case TimeStep.SCALE.SECOND:
  2450. return (this.current.getSeconds() == 0);
  2451. case TimeStep.SCALE.MINUTE:
  2452. return (this.current.getHours() == 0) && (this.current.getMinutes() == 0);
  2453. // Note: this is no bug. Major label is equal for both minute and hour scale
  2454. case TimeStep.SCALE.HOUR:
  2455. return (this.current.getHours() == 0);
  2456. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2457. case TimeStep.SCALE.DAY:
  2458. return (this.current.getDate() == 1);
  2459. case TimeStep.SCALE.MONTH:
  2460. return (this.current.getMonth() == 0);
  2461. case TimeStep.SCALE.YEAR:
  2462. return false;
  2463. default:
  2464. return false;
  2465. }
  2466. };
  2467. /**
  2468. * Returns formatted text for the minor axislabel, depending on the current
  2469. * date and the scale. For example when scale is MINUTE, the current time is
  2470. * formatted as "hh:mm".
  2471. * @param {Date} [date] custom date. if not provided, current date is taken
  2472. */
  2473. TimeStep.prototype.getLabelMinor = function(date) {
  2474. if (date == undefined) {
  2475. date = this.current;
  2476. }
  2477. switch (this.scale) {
  2478. case TimeStep.SCALE.MILLISECOND: return moment(date).format('SSS');
  2479. case TimeStep.SCALE.SECOND: return moment(date).format('s');
  2480. case TimeStep.SCALE.MINUTE: return moment(date).format('HH:mm');
  2481. case TimeStep.SCALE.HOUR: return moment(date).format('HH:mm');
  2482. case TimeStep.SCALE.WEEKDAY: return moment(date).format('ddd D');
  2483. case TimeStep.SCALE.DAY: return moment(date).format('D');
  2484. case TimeStep.SCALE.MONTH: return moment(date).format('MMM');
  2485. case TimeStep.SCALE.YEAR: return moment(date).format('YYYY');
  2486. default: return '';
  2487. }
  2488. };
  2489. /**
  2490. * Returns formatted text for the major axis label, depending on the current
  2491. * date and the scale. For example when scale is MINUTE, the major scale is
  2492. * hours, and the hour will be formatted as "hh".
  2493. * @param {Date} [date] custom date. if not provided, current date is taken
  2494. */
  2495. TimeStep.prototype.getLabelMajor = function(date) {
  2496. if (date == undefined) {
  2497. date = this.current;
  2498. }
  2499. //noinspection FallthroughInSwitchStatementJS
  2500. switch (this.scale) {
  2501. case TimeStep.SCALE.MILLISECOND:return moment(date).format('HH:mm:ss');
  2502. case TimeStep.SCALE.SECOND: return moment(date).format('D MMMM HH:mm');
  2503. case TimeStep.SCALE.MINUTE:
  2504. case TimeStep.SCALE.HOUR: return moment(date).format('ddd D MMMM');
  2505. case TimeStep.SCALE.WEEKDAY:
  2506. case TimeStep.SCALE.DAY: return moment(date).format('MMMM YYYY');
  2507. case TimeStep.SCALE.MONTH: return moment(date).format('YYYY');
  2508. case TimeStep.SCALE.YEAR: return '';
  2509. default: return '';
  2510. }
  2511. };
  2512. /**
  2513. * @constructor Stack
  2514. * Stacks items on top of each other.
  2515. * @param {ItemSet} itemset
  2516. * @param {Object} [options]
  2517. */
  2518. function Stack (itemset, options) {
  2519. this.itemset = itemset;
  2520. this.options = options || {};
  2521. this.defaultOptions = {
  2522. order: function (a, b) {
  2523. //return (b.width - a.width) || (a.left - b.left); // TODO: cleanup
  2524. // Order: ranges over non-ranges, ranged ordered by width, and
  2525. // lastly ordered by start.
  2526. if (a instanceof ItemRange) {
  2527. if (b instanceof ItemRange) {
  2528. var aInt = (a.data.end - a.data.start);
  2529. var bInt = (b.data.end - b.data.start);
  2530. return (aInt - bInt) || (a.data.start - b.data.start);
  2531. }
  2532. else {
  2533. return -1;
  2534. }
  2535. }
  2536. else {
  2537. if (b instanceof ItemRange) {
  2538. return 1;
  2539. }
  2540. else {
  2541. return (a.data.start - b.data.start);
  2542. }
  2543. }
  2544. },
  2545. margin: {
  2546. item: 10
  2547. }
  2548. };
  2549. this.ordered = []; // ordered items
  2550. }
  2551. /**
  2552. * Set options for the stack
  2553. * @param {Object} options Available options:
  2554. * {ItemSet} itemset
  2555. * {Number} margin
  2556. * {function} order Stacking order
  2557. */
  2558. Stack.prototype.setOptions = function setOptions (options) {
  2559. util.extend(this.options, options);
  2560. // TODO: register on data changes at the connected itemset, and update the changed part only and immediately
  2561. };
  2562. /**
  2563. * Stack the items such that they don't overlap. The items will have a minimal
  2564. * distance equal to options.margin.item.
  2565. */
  2566. Stack.prototype.update = function update() {
  2567. this._order();
  2568. this._stack();
  2569. };
  2570. /**
  2571. * Order the items. If a custom order function has been provided via the options,
  2572. * then this will be used.
  2573. * @private
  2574. */
  2575. Stack.prototype._order = function _order () {
  2576. var items = this.itemset.items;
  2577. if (!items) {
  2578. throw new Error('Cannot stack items: ItemSet does not contain items');
  2579. }
  2580. // TODO: store the sorted items, to have less work later on
  2581. var ordered = [];
  2582. var index = 0;
  2583. // items is a map (no array)
  2584. util.forEach(items, function (item) {
  2585. if (item.visible) {
  2586. ordered[index] = item;
  2587. index++;
  2588. }
  2589. });
  2590. //if a customer stack order function exists, use it.
  2591. var order = this.options.order || this.defaultOptions.order;
  2592. if (!(typeof order === 'function')) {
  2593. throw new Error('Option order must be a function');
  2594. }
  2595. ordered.sort(order);
  2596. this.ordered = ordered;
  2597. };
  2598. /**
  2599. * Adjust vertical positions of the events such that they don't overlap each
  2600. * other.
  2601. * @private
  2602. */
  2603. Stack.prototype._stack = function _stack () {
  2604. var i,
  2605. iMax,
  2606. ordered = this.ordered,
  2607. options = this.options,
  2608. orientation = options.orientation || this.defaultOptions.orientation,
  2609. axisOnTop = (orientation == 'top'),
  2610. margin;
  2611. if (options.margin && options.margin.item !== undefined) {
  2612. margin = options.margin.item;
  2613. }
  2614. else {
  2615. margin = this.defaultOptions.margin.item
  2616. }
  2617. // calculate new, non-overlapping positions
  2618. for (i = 0, iMax = ordered.length; i < iMax; i++) {
  2619. var item = ordered[i];
  2620. var collidingItem = null;
  2621. do {
  2622. // TODO: optimize checking for overlap. when there is a gap without items,
  2623. // you only need to check for items from the next item on, not from zero
  2624. collidingItem = this.checkOverlap(ordered, i, 0, i - 1, margin);
  2625. if (collidingItem != null) {
  2626. // There is a collision. Reposition the event above the colliding element
  2627. if (axisOnTop) {
  2628. item.top = collidingItem.top + collidingItem.height + margin;
  2629. }
  2630. else {
  2631. item.top = collidingItem.top - item.height - margin;
  2632. }
  2633. }
  2634. } while (collidingItem);
  2635. }
  2636. };
  2637. /**
  2638. * Check if the destiny position of given item overlaps with any
  2639. * of the other items from index itemStart to itemEnd.
  2640. * @param {Array} items Array with items
  2641. * @param {int} itemIndex Number of the item to be checked for overlap
  2642. * @param {int} itemStart First item to be checked.
  2643. * @param {int} itemEnd Last item to be checked.
  2644. * @return {Object | null} colliding item, or undefined when no collisions
  2645. * @param {Number} margin A minimum required margin.
  2646. * If margin is provided, the two items will be
  2647. * marked colliding when they overlap or
  2648. * when the margin between the two is smaller than
  2649. * the requested margin.
  2650. */
  2651. Stack.prototype.checkOverlap = function checkOverlap (items, itemIndex,
  2652. itemStart, itemEnd, margin) {
  2653. var collision = this.collision;
  2654. // we loop from end to start, as we suppose that the chance of a
  2655. // collision is larger for items at the end, so check these first.
  2656. var a = items[itemIndex];
  2657. for (var i = itemEnd; i >= itemStart; i--) {
  2658. var b = items[i];
  2659. if (collision(a, b, margin)) {
  2660. if (i != itemIndex) {
  2661. return b;
  2662. }
  2663. }
  2664. }
  2665. return null;
  2666. };
  2667. /**
  2668. * Test if the two provided items collide
  2669. * The items must have parameters left, width, top, and height.
  2670. * @param {Component} a The first item
  2671. * @param {Component} b The second item
  2672. * @param {Number} margin A minimum required margin.
  2673. * If margin is provided, the two items will be
  2674. * marked colliding when they overlap or
  2675. * when the margin between the two is smaller than
  2676. * the requested margin.
  2677. * @return {boolean} true if a and b collide, else false
  2678. */
  2679. Stack.prototype.collision = function collision (a, b, margin) {
  2680. return ((a.left - margin) < (b.left + b.width) &&
  2681. (a.left + a.width + margin) > b.left &&
  2682. (a.top - margin) < (b.top + b.height) &&
  2683. (a.top + a.height + margin) > b.top);
  2684. };
  2685. /**
  2686. * @constructor Range
  2687. * A Range controls a numeric range with a start and end value.
  2688. * The Range adjusts the range based on mouse events or programmatic changes,
  2689. * and triggers events when the range is changing or has been changed.
  2690. * @param {Object} [options] See description at Range.setOptions
  2691. * @extends Controller
  2692. */
  2693. function Range(options) {
  2694. this.id = util.randomUUID();
  2695. this.start = null; // Number
  2696. this.end = null; // Number
  2697. this.options = options || {};
  2698. this.setOptions(options);
  2699. }
  2700. // extend the Range prototype with an event emitter mixin
  2701. Emitter(Range.prototype);
  2702. /**
  2703. * Set options for the range controller
  2704. * @param {Object} options Available options:
  2705. * {Number} min Minimum value for start
  2706. * {Number} max Maximum value for end
  2707. * {Number} zoomMin Set a minimum value for
  2708. * (end - start).
  2709. * {Number} zoomMax Set a maximum value for
  2710. * (end - start).
  2711. */
  2712. Range.prototype.setOptions = function (options) {
  2713. util.extend(this.options, options);
  2714. // re-apply range with new limitations
  2715. if (this.start !== null && this.end !== null) {
  2716. this.setRange(this.start, this.end);
  2717. }
  2718. };
  2719. /**
  2720. * Test whether direction has a valid value
  2721. * @param {String} direction 'horizontal' or 'vertical'
  2722. */
  2723. function validateDirection (direction) {
  2724. if (direction != 'horizontal' && direction != 'vertical') {
  2725. throw new TypeError('Unknown direction "' + direction + '". ' +
  2726. 'Choose "horizontal" or "vertical".');
  2727. }
  2728. }
  2729. /**
  2730. * Add listeners for mouse and touch events to the component
  2731. * @param {Controller} controller
  2732. * @param {Component} component Should be a rootpanel
  2733. * @param {String} event Available events: 'move', 'zoom'
  2734. * @param {String} direction Available directions: 'horizontal', 'vertical'
  2735. */
  2736. Range.prototype.subscribe = function (controller, component, event, direction) {
  2737. var me = this;
  2738. if (event == 'move') {
  2739. // drag start listener
  2740. controller.on('dragstart', function (event) {
  2741. me._onDragStart(event, component);
  2742. });
  2743. // drag listener
  2744. controller.on('drag', function (event) {
  2745. me._onDrag(event, component, direction);
  2746. });
  2747. // drag end listener
  2748. controller.on('dragend', function (event) {
  2749. me._onDragEnd(event, component);
  2750. });
  2751. // ignore dragging when holding
  2752. controller.on('hold', function (event) {
  2753. me._onHold();
  2754. });
  2755. }
  2756. else if (event == 'zoom') {
  2757. // mouse wheel
  2758. function mousewheel (event) {
  2759. me._onMouseWheel(event, component, direction);
  2760. }
  2761. controller.on('mousewheel', mousewheel);
  2762. controller.on('DOMMouseScroll', mousewheel); // For FF
  2763. // pinch
  2764. controller.on('touch', function (event) {
  2765. me._onTouch(event);
  2766. });
  2767. controller.on('pinch', function (event) {
  2768. me._onPinch(event, component, direction);
  2769. });
  2770. }
  2771. else {
  2772. throw new TypeError('Unknown event "' + event + '". ' +
  2773. 'Choose "move" or "zoom".');
  2774. }
  2775. };
  2776. /**
  2777. * Set a new start and end range
  2778. * @param {Number} [start]
  2779. * @param {Number} [end]
  2780. */
  2781. Range.prototype.setRange = function(start, end) {
  2782. var changed = this._applyRange(start, end);
  2783. if (changed) {
  2784. var params = {
  2785. start: this.start,
  2786. end: this.end
  2787. };
  2788. this.emit('rangechange', params);
  2789. this.emit('rangechanged', params);
  2790. }
  2791. };
  2792. /**
  2793. * Set a new start and end range. This method is the same as setRange, but
  2794. * does not trigger a range change and range changed event, and it returns
  2795. * true when the range is changed
  2796. * @param {Number} [start]
  2797. * @param {Number} [end]
  2798. * @return {Boolean} changed
  2799. * @private
  2800. */
  2801. Range.prototype._applyRange = function(start, end) {
  2802. var newStart = (start != null) ? util.convert(start, 'Date').valueOf() : this.start,
  2803. newEnd = (end != null) ? util.convert(end, 'Date').valueOf() : this.end,
  2804. max = (this.options.max != null) ? util.convert(this.options.max, 'Date').valueOf() : null,
  2805. min = (this.options.min != null) ? util.convert(this.options.min, 'Date').valueOf() : null,
  2806. diff;
  2807. // check for valid number
  2808. if (isNaN(newStart) || newStart === null) {
  2809. throw new Error('Invalid start "' + start + '"');
  2810. }
  2811. if (isNaN(newEnd) || newEnd === null) {
  2812. throw new Error('Invalid end "' + end + '"');
  2813. }
  2814. // prevent start < end
  2815. if (newEnd < newStart) {
  2816. newEnd = newStart;
  2817. }
  2818. // prevent start < min
  2819. if (min !== null) {
  2820. if (newStart < min) {
  2821. diff = (min - newStart);
  2822. newStart += diff;
  2823. newEnd += diff;
  2824. // prevent end > max
  2825. if (max != null) {
  2826. if (newEnd > max) {
  2827. newEnd = max;
  2828. }
  2829. }
  2830. }
  2831. }
  2832. // prevent end > max
  2833. if (max !== null) {
  2834. if (newEnd > max) {
  2835. diff = (newEnd - max);
  2836. newStart -= diff;
  2837. newEnd -= diff;
  2838. // prevent start < min
  2839. if (min != null) {
  2840. if (newStart < min) {
  2841. newStart = min;
  2842. }
  2843. }
  2844. }
  2845. }
  2846. // prevent (end-start) < zoomMin
  2847. if (this.options.zoomMin !== null) {
  2848. var zoomMin = parseFloat(this.options.zoomMin);
  2849. if (zoomMin < 0) {
  2850. zoomMin = 0;
  2851. }
  2852. if ((newEnd - newStart) < zoomMin) {
  2853. if ((this.end - this.start) === zoomMin) {
  2854. // ignore this action, we are already zoomed to the minimum
  2855. newStart = this.start;
  2856. newEnd = this.end;
  2857. }
  2858. else {
  2859. // zoom to the minimum
  2860. diff = (zoomMin - (newEnd - newStart));
  2861. newStart -= diff / 2;
  2862. newEnd += diff / 2;
  2863. }
  2864. }
  2865. }
  2866. // prevent (end-start) > zoomMax
  2867. if (this.options.zoomMax !== null) {
  2868. var zoomMax = parseFloat(this.options.zoomMax);
  2869. if (zoomMax < 0) {
  2870. zoomMax = 0;
  2871. }
  2872. if ((newEnd - newStart) > zoomMax) {
  2873. if ((this.end - this.start) === zoomMax) {
  2874. // ignore this action, we are already zoomed to the maximum
  2875. newStart = this.start;
  2876. newEnd = this.end;
  2877. }
  2878. else {
  2879. // zoom to the maximum
  2880. diff = ((newEnd - newStart) - zoomMax);
  2881. newStart += diff / 2;
  2882. newEnd -= diff / 2;
  2883. }
  2884. }
  2885. }
  2886. var changed = (this.start != newStart || this.end != newEnd);
  2887. this.start = newStart;
  2888. this.end = newEnd;
  2889. return changed;
  2890. };
  2891. /**
  2892. * Retrieve the current range.
  2893. * @return {Object} An object with start and end properties
  2894. */
  2895. Range.prototype.getRange = function() {
  2896. return {
  2897. start: this.start,
  2898. end: this.end
  2899. };
  2900. };
  2901. /**
  2902. * Calculate the conversion offset and scale for current range, based on
  2903. * the provided width
  2904. * @param {Number} width
  2905. * @returns {{offset: number, scale: number}} conversion
  2906. */
  2907. Range.prototype.conversion = function (width) {
  2908. return Range.conversion(this.start, this.end, width);
  2909. };
  2910. /**
  2911. * Static method to calculate the conversion offset and scale for a range,
  2912. * based on the provided start, end, and width
  2913. * @param {Number} start
  2914. * @param {Number} end
  2915. * @param {Number} width
  2916. * @returns {{offset: number, scale: number}} conversion
  2917. */
  2918. Range.conversion = function (start, end, width) {
  2919. if (width != 0 && (end - start != 0)) {
  2920. return {
  2921. offset: start,
  2922. scale: width / (end - start)
  2923. }
  2924. }
  2925. else {
  2926. return {
  2927. offset: 0,
  2928. scale: 1
  2929. };
  2930. }
  2931. };
  2932. // global (private) object to store drag params
  2933. var touchParams = {};
  2934. /**
  2935. * Start dragging horizontally or vertically
  2936. * @param {Event} event
  2937. * @param {Object} component
  2938. * @private
  2939. */
  2940. Range.prototype._onDragStart = function(event, component) {
  2941. // refuse to drag when we where pinching to prevent the timeline make a jump
  2942. // when releasing the fingers in opposite order from the touch screen
  2943. if (touchParams.ignore) return;
  2944. // TODO: reckon with option movable
  2945. touchParams.start = this.start;
  2946. touchParams.end = this.end;
  2947. var frame = component.frame;
  2948. if (frame) {
  2949. frame.style.cursor = 'move';
  2950. }
  2951. };
  2952. /**
  2953. * Perform dragging operating.
  2954. * @param {Event} event
  2955. * @param {Component} component
  2956. * @param {String} direction 'horizontal' or 'vertical'
  2957. * @private
  2958. */
  2959. Range.prototype._onDrag = function (event, component, direction) {
  2960. validateDirection(direction);
  2961. // TODO: reckon with option movable
  2962. // refuse to drag when we where pinching to prevent the timeline make a jump
  2963. // when releasing the fingers in opposite order from the touch screen
  2964. if (touchParams.ignore) return;
  2965. var delta = (direction == 'horizontal') ? event.gesture.deltaX : event.gesture.deltaY,
  2966. interval = (touchParams.end - touchParams.start),
  2967. width = (direction == 'horizontal') ? component.width : component.height,
  2968. diffRange = -delta / width * interval;
  2969. this._applyRange(touchParams.start + diffRange, touchParams.end + diffRange);
  2970. this.emit('rangechange', {
  2971. start: this.start,
  2972. end: this.end
  2973. });
  2974. };
  2975. /**
  2976. * Stop dragging operating.
  2977. * @param {event} event
  2978. * @param {Component} component
  2979. * @private
  2980. */
  2981. Range.prototype._onDragEnd = function (event, component) {
  2982. // refuse to drag when we where pinching to prevent the timeline make a jump
  2983. // when releasing the fingers in opposite order from the touch screen
  2984. if (touchParams.ignore) return;
  2985. // TODO: reckon with option movable
  2986. if (component.frame) {
  2987. component.frame.style.cursor = 'auto';
  2988. }
  2989. // fire a rangechanged event
  2990. this.emit('rangechanged', {
  2991. start: this.start,
  2992. end: this.end
  2993. });
  2994. };
  2995. /**
  2996. * Event handler for mouse wheel event, used to zoom
  2997. * Code from http://adomas.org/javascript-mouse-wheel/
  2998. * @param {Event} event
  2999. * @param {Component} component
  3000. * @param {String} direction 'horizontal' or 'vertical'
  3001. * @private
  3002. */
  3003. Range.prototype._onMouseWheel = function(event, component, direction) {
  3004. validateDirection(direction);
  3005. // TODO: reckon with option zoomable
  3006. // retrieve delta
  3007. var delta = 0;
  3008. if (event.wheelDelta) { /* IE/Opera. */
  3009. delta = event.wheelDelta / 120;
  3010. } else if (event.detail) { /* Mozilla case. */
  3011. // In Mozilla, sign of delta is different than in IE.
  3012. // Also, delta is multiple of 3.
  3013. delta = -event.detail / 3;
  3014. }
  3015. // If delta is nonzero, handle it.
  3016. // Basically, delta is now positive if wheel was scrolled up,
  3017. // and negative, if wheel was scrolled down.
  3018. if (delta) {
  3019. // perform the zoom action. Delta is normally 1 or -1
  3020. // adjust a negative delta such that zooming in with delta 0.1
  3021. // equals zooming out with a delta -0.1
  3022. var scale;
  3023. if (delta < 0) {
  3024. scale = 1 - (delta / 5);
  3025. }
  3026. else {
  3027. scale = 1 / (1 + (delta / 5)) ;
  3028. }
  3029. // calculate center, the date to zoom around
  3030. var gesture = util.fakeGesture(this, event),
  3031. pointer = getPointer(gesture.center, component.frame),
  3032. pointerDate = this._pointerToDate(component, direction, pointer);
  3033. this.zoom(scale, pointerDate);
  3034. }
  3035. // Prevent default actions caused by mouse wheel
  3036. // (else the page and timeline both zoom and scroll)
  3037. event.preventDefault();
  3038. };
  3039. /**
  3040. * Start of a touch gesture
  3041. * @private
  3042. */
  3043. Range.prototype._onTouch = function (event) {
  3044. touchParams.start = this.start;
  3045. touchParams.end = this.end;
  3046. touchParams.ignore = false;
  3047. touchParams.center = null;
  3048. // don't move the range when dragging a selected event
  3049. // TODO: it's not so neat to have to know about the state of the ItemSet
  3050. var item = ItemSet.itemFromTarget(event);
  3051. if (item && item.selected && this.options.editable) {
  3052. touchParams.ignore = true;
  3053. }
  3054. };
  3055. /**
  3056. * On start of a hold gesture
  3057. * @private
  3058. */
  3059. Range.prototype._onHold = function () {
  3060. touchParams.ignore = true;
  3061. };
  3062. /**
  3063. * Handle pinch event
  3064. * @param {Event} event
  3065. * @param {Component} component
  3066. * @param {String} direction 'horizontal' or 'vertical'
  3067. * @private
  3068. */
  3069. Range.prototype._onPinch = function (event, component, direction) {
  3070. touchParams.ignore = true;
  3071. // TODO: reckon with option zoomable
  3072. if (event.gesture.touches.length > 1) {
  3073. if (!touchParams.center) {
  3074. touchParams.center = getPointer(event.gesture.center, component.frame);
  3075. }
  3076. var scale = 1 / event.gesture.scale,
  3077. initDate = this._pointerToDate(component, direction, touchParams.center),
  3078. center = getPointer(event.gesture.center, component.frame),
  3079. date = this._pointerToDate(component, direction, center),
  3080. delta = date - initDate; // TODO: utilize delta
  3081. // calculate new start and end
  3082. var newStart = parseInt(initDate + (touchParams.start - initDate) * scale);
  3083. var newEnd = parseInt(initDate + (touchParams.end - initDate) * scale);
  3084. // apply new range
  3085. this.setRange(newStart, newEnd);
  3086. }
  3087. };
  3088. /**
  3089. * Helper function to calculate the center date for zooming
  3090. * @param {Component} component
  3091. * @param {{x: Number, y: Number}} pointer
  3092. * @param {String} direction 'horizontal' or 'vertical'
  3093. * @return {number} date
  3094. * @private
  3095. */
  3096. Range.prototype._pointerToDate = function (component, direction, pointer) {
  3097. var conversion;
  3098. if (direction == 'horizontal') {
  3099. var width = component.width;
  3100. conversion = this.conversion(width);
  3101. return pointer.x / conversion.scale + conversion.offset;
  3102. }
  3103. else {
  3104. var height = component.height;
  3105. conversion = this.conversion(height);
  3106. return pointer.y / conversion.scale + conversion.offset;
  3107. }
  3108. };
  3109. /**
  3110. * Get the pointer location relative to the location of the dom element
  3111. * @param {{pageX: Number, pageY: Number}} touch
  3112. * @param {Element} element HTML DOM element
  3113. * @return {{x: Number, y: Number}} pointer
  3114. * @private
  3115. */
  3116. function getPointer (touch, element) {
  3117. return {
  3118. x: touch.pageX - vis.util.getAbsoluteLeft(element),
  3119. y: touch.pageY - vis.util.getAbsoluteTop(element)
  3120. };
  3121. }
  3122. /**
  3123. * Zoom the range the given scale in or out. Start and end date will
  3124. * be adjusted, and the timeline will be redrawn. You can optionally give a
  3125. * date around which to zoom.
  3126. * For example, try scale = 0.9 or 1.1
  3127. * @param {Number} scale Scaling factor. Values above 1 will zoom out,
  3128. * values below 1 will zoom in.
  3129. * @param {Number} [center] Value representing a date around which will
  3130. * be zoomed.
  3131. */
  3132. Range.prototype.zoom = function(scale, center) {
  3133. // if centerDate is not provided, take it half between start Date and end Date
  3134. if (center == null) {
  3135. center = (this.start + this.end) / 2;
  3136. }
  3137. // calculate new start and end
  3138. var newStart = center + (this.start - center) * scale;
  3139. var newEnd = center + (this.end - center) * scale;
  3140. this.setRange(newStart, newEnd);
  3141. };
  3142. /**
  3143. * Move the range with a given delta to the left or right. Start and end
  3144. * value will be adjusted. For example, try delta = 0.1 or -0.1
  3145. * @param {Number} delta Moving amount. Positive value will move right,
  3146. * negative value will move left
  3147. */
  3148. Range.prototype.move = function(delta) {
  3149. // zoom start Date and end Date relative to the centerDate
  3150. var diff = (this.end - this.start);
  3151. // apply new values
  3152. var newStart = this.start + diff * delta;
  3153. var newEnd = this.end + diff * delta;
  3154. // TODO: reckon with min and max range
  3155. this.start = newStart;
  3156. this.end = newEnd;
  3157. };
  3158. /**
  3159. * Move the range to a new center point
  3160. * @param {Number} moveTo New center point of the range
  3161. */
  3162. Range.prototype.moveTo = function(moveTo) {
  3163. var center = (this.start + this.end) / 2;
  3164. var diff = center - moveTo;
  3165. // calculate new start and end
  3166. var newStart = this.start - diff;
  3167. var newEnd = this.end - diff;
  3168. this.setRange(newStart, newEnd);
  3169. };
  3170. /**
  3171. * @constructor Controller
  3172. *
  3173. * A Controller controls the reflows and repaints of all components,
  3174. * and is used as an event bus for all components.
  3175. */
  3176. function Controller () {
  3177. var me = this;
  3178. this.id = util.randomUUID();
  3179. this.components = {};
  3180. /**
  3181. * Listen for a 'request-reflow' event. The controller will schedule a reflow
  3182. * @param {Boolean} [force] If true, an immediate reflow is forced. Default
  3183. * is false.
  3184. */
  3185. var reflowTimer = null;
  3186. this.on('request-reflow', function requestReflow(force) {
  3187. if (force) {
  3188. me.reflow();
  3189. }
  3190. else {
  3191. if (!reflowTimer) {
  3192. reflowTimer = setTimeout(function () {
  3193. reflowTimer = null;
  3194. me.reflow();
  3195. }, 0);
  3196. }
  3197. }
  3198. });
  3199. /**
  3200. * Request a repaint. The controller will schedule a repaint
  3201. * @param {Boolean} [force] If true, an immediate repaint is forced. Default
  3202. * is false.
  3203. */
  3204. var repaintTimer = null;
  3205. this.on('request-repaint', function requestRepaint(force) {
  3206. if (force) {
  3207. me.repaint();
  3208. }
  3209. else {
  3210. if (!repaintTimer) {
  3211. repaintTimer = setTimeout(function () {
  3212. repaintTimer = null;
  3213. me.repaint();
  3214. }, 0);
  3215. }
  3216. }
  3217. });
  3218. }
  3219. // Extend controller with Emitter mixin
  3220. Emitter(Controller.prototype);
  3221. /**
  3222. * Add a component to the controller
  3223. * @param {Component} component
  3224. */
  3225. Controller.prototype.add = function add(component) {
  3226. // validate the component
  3227. if (component.id == undefined) {
  3228. throw new Error('Component has no field id');
  3229. }
  3230. if (!(component instanceof Component) && !(component instanceof Controller)) {
  3231. throw new TypeError('Component must be an instance of ' +
  3232. 'prototype Component or Controller');
  3233. }
  3234. // add the component
  3235. component.setController(this);
  3236. this.components[component.id] = component;
  3237. };
  3238. /**
  3239. * Remove a component from the controller
  3240. * @param {Component | String} component
  3241. */
  3242. Controller.prototype.remove = function remove(component) {
  3243. var id;
  3244. for (id in this.components) {
  3245. if (this.components.hasOwnProperty(id)) {
  3246. if (id == component || this.components[id] === component) {
  3247. break;
  3248. }
  3249. }
  3250. }
  3251. if (id) {
  3252. // unregister the controller (gives the component the ability to unregister
  3253. // event listeners and clean up other stuff)
  3254. this.components[id].setController(null);
  3255. delete this.components[id];
  3256. }
  3257. };
  3258. /**
  3259. * Repaint all components
  3260. */
  3261. Controller.prototype.repaint = function repaint() {
  3262. var changed = false;
  3263. // cancel any running repaint request
  3264. if (this.repaintTimer) {
  3265. clearTimeout(this.repaintTimer);
  3266. this.repaintTimer = undefined;
  3267. }
  3268. var done = {};
  3269. function repaint(component, id) {
  3270. if (!(id in done)) {
  3271. // first repaint the components on which this component is dependent
  3272. if (component.depends) {
  3273. component.depends.forEach(function (dep) {
  3274. repaint(dep, dep.id);
  3275. });
  3276. }
  3277. if (component.parent) {
  3278. repaint(component.parent, component.parent.id);
  3279. }
  3280. // repaint the component itself and mark as done
  3281. changed = component.repaint() || changed;
  3282. done[id] = true;
  3283. }
  3284. }
  3285. util.forEach(this.components, repaint);
  3286. this.emit('repaint');
  3287. // immediately reflow when needed
  3288. if (changed) {
  3289. this.reflow();
  3290. }
  3291. // TODO: limit the number of nested reflows/repaints, prevent loop
  3292. };
  3293. /**
  3294. * Reflow all components
  3295. */
  3296. Controller.prototype.reflow = function reflow() {
  3297. var resized = false;
  3298. // cancel any running repaint request
  3299. if (this.reflowTimer) {
  3300. clearTimeout(this.reflowTimer);
  3301. this.reflowTimer = undefined;
  3302. }
  3303. var done = {};
  3304. function reflow(component, id) {
  3305. if (!(id in done)) {
  3306. // first reflow the components on which this component is dependent
  3307. if (component.depends) {
  3308. component.depends.forEach(function (dep) {
  3309. reflow(dep, dep.id);
  3310. });
  3311. }
  3312. if (component.parent) {
  3313. reflow(component.parent, component.parent.id);
  3314. }
  3315. // reflow the component itself and mark as done
  3316. resized = component.reflow() || resized;
  3317. done[id] = true;
  3318. }
  3319. }
  3320. util.forEach(this.components, reflow);
  3321. this.emit('reflow');
  3322. // immediately repaint when needed
  3323. if (resized) {
  3324. this.repaint();
  3325. }
  3326. // TODO: limit the number of nested reflows/repaints, prevent loop
  3327. };
  3328. /**
  3329. * Prototype for visual components
  3330. */
  3331. function Component () {
  3332. this.id = null;
  3333. this.parent = null;
  3334. this.depends = null;
  3335. this.controller = null;
  3336. this.options = null;
  3337. this.frame = null; // main DOM element
  3338. this.top = 0;
  3339. this.left = 0;
  3340. this.width = 0;
  3341. this.height = 0;
  3342. }
  3343. /**
  3344. * Set parameters for the frame. Parameters will be merged in current parameter
  3345. * set.
  3346. * @param {Object} options Available parameters:
  3347. * {String | function} [className]
  3348. * {String | Number | function} [left]
  3349. * {String | Number | function} [top]
  3350. * {String | Number | function} [width]
  3351. * {String | Number | function} [height]
  3352. */
  3353. Component.prototype.setOptions = function setOptions(options) {
  3354. if (options) {
  3355. util.extend(this.options, options);
  3356. if (this.controller) {
  3357. this.requestRepaint();
  3358. this.requestReflow();
  3359. }
  3360. }
  3361. };
  3362. /**
  3363. * Get an option value by name
  3364. * The function will first check this.options object, and else will check
  3365. * this.defaultOptions.
  3366. * @param {String} name
  3367. * @return {*} value
  3368. */
  3369. Component.prototype.getOption = function getOption(name) {
  3370. var value;
  3371. if (this.options) {
  3372. value = this.options[name];
  3373. }
  3374. if (value === undefined && this.defaultOptions) {
  3375. value = this.defaultOptions[name];
  3376. }
  3377. return value;
  3378. };
  3379. /**
  3380. * Set controller for this component, or remove current controller by passing
  3381. * null as parameter value.
  3382. * @param {Controller | null} controller
  3383. */
  3384. Component.prototype.setController = function setController (controller) {
  3385. this.controller = controller || null;
  3386. };
  3387. /**
  3388. * Get controller of this component
  3389. * @return {Controller} controller
  3390. */
  3391. Component.prototype.getController = function getController () {
  3392. return this.controller;
  3393. };
  3394. /**
  3395. * Get the container element of the component, which can be used by a child to
  3396. * add its own widgets. Not all components do have a container for childs, in
  3397. * that case null is returned.
  3398. * @returns {HTMLElement | null} container
  3399. */
  3400. // TODO: get rid of the getContainer and getFrame methods, provide these via the options
  3401. Component.prototype.getContainer = function getContainer() {
  3402. // should be implemented by the component
  3403. return null;
  3404. };
  3405. /**
  3406. * Get the frame element of the component, the outer HTML DOM element.
  3407. * @returns {HTMLElement | null} frame
  3408. */
  3409. Component.prototype.getFrame = function getFrame() {
  3410. return this.frame;
  3411. };
  3412. /**
  3413. * Repaint the component
  3414. * @return {Boolean} changed
  3415. */
  3416. Component.prototype.repaint = function repaint() {
  3417. // should be implemented by the component
  3418. return false;
  3419. };
  3420. /**
  3421. * Reflow the component
  3422. * @return {Boolean} resized
  3423. */
  3424. Component.prototype.reflow = function reflow() {
  3425. // should be implemented by the component
  3426. return false;
  3427. };
  3428. /**
  3429. * Hide the component from the DOM
  3430. * @return {Boolean} changed
  3431. */
  3432. Component.prototype.hide = function hide() {
  3433. if (this.frame && this.frame.parentNode) {
  3434. this.frame.parentNode.removeChild(this.frame);
  3435. return true;
  3436. }
  3437. else {
  3438. return false;
  3439. }
  3440. };
  3441. /**
  3442. * Show the component in the DOM (when not already visible).
  3443. * A repaint will be executed when the component is not visible
  3444. * @return {Boolean} changed
  3445. */
  3446. Component.prototype.show = function show() {
  3447. if (!this.frame || !this.frame.parentNode) {
  3448. return this.repaint();
  3449. }
  3450. else {
  3451. return false;
  3452. }
  3453. };
  3454. /**
  3455. * Request a repaint. The controller will schedule a repaint
  3456. */
  3457. Component.prototype.requestRepaint = function requestRepaint() {
  3458. if (this.controller) {
  3459. this.controller.emit('request-repaint');
  3460. }
  3461. else {
  3462. throw new Error('Cannot request a repaint: no controller configured');
  3463. // TODO: just do a repaint when no parent is configured?
  3464. }
  3465. };
  3466. /**
  3467. * Request a reflow. The controller will schedule a reflow
  3468. */
  3469. Component.prototype.requestReflow = function requestReflow() {
  3470. if (this.controller) {
  3471. this.controller.emit('request-reflow');
  3472. }
  3473. else {
  3474. throw new Error('Cannot request a reflow: no controller configured');
  3475. // TODO: just do a reflow when no parent is configured?
  3476. }
  3477. };
  3478. /**
  3479. * A panel can contain components
  3480. * @param {Component} [parent]
  3481. * @param {Component[]} [depends] Components on which this components depends
  3482. * (except for the parent)
  3483. * @param {Object} [options] Available parameters:
  3484. * {String | Number | function} [left]
  3485. * {String | Number | function} [top]
  3486. * {String | Number | function} [width]
  3487. * {String | Number | function} [height]
  3488. * {String | function} [className]
  3489. * @constructor Panel
  3490. * @extends Component
  3491. */
  3492. function Panel(parent, depends, options) {
  3493. this.id = util.randomUUID();
  3494. this.parent = parent;
  3495. this.depends = depends;
  3496. this.options = options || {};
  3497. }
  3498. Panel.prototype = new Component();
  3499. /**
  3500. * Set options. Will extend the current options.
  3501. * @param {Object} [options] Available parameters:
  3502. * {String | function} [className]
  3503. * {String | Number | function} [left]
  3504. * {String | Number | function} [top]
  3505. * {String | Number | function} [width]
  3506. * {String | Number | function} [height]
  3507. */
  3508. Panel.prototype.setOptions = Component.prototype.setOptions;
  3509. /**
  3510. * Get the container element of the panel, which can be used by a child to
  3511. * add its own widgets.
  3512. * @returns {HTMLElement} container
  3513. */
  3514. Panel.prototype.getContainer = function () {
  3515. return this.frame;
  3516. };
  3517. /**
  3518. * Repaint the component
  3519. * @return {Boolean} changed
  3520. */
  3521. Panel.prototype.repaint = function () {
  3522. var changed = 0,
  3523. update = util.updateProperty,
  3524. asSize = util.option.asSize,
  3525. options = this.options,
  3526. frame = this.frame;
  3527. if (!frame) {
  3528. frame = document.createElement('div');
  3529. frame.className = 'vpanel';
  3530. var className = options.className;
  3531. if (className) {
  3532. if (typeof className == 'function') {
  3533. util.addClassName(frame, String(className()));
  3534. }
  3535. else {
  3536. util.addClassName(frame, String(className));
  3537. }
  3538. }
  3539. this.frame = frame;
  3540. changed += 1;
  3541. }
  3542. if (!frame.parentNode) {
  3543. if (!this.parent) {
  3544. throw new Error('Cannot repaint panel: no parent attached');
  3545. }
  3546. var parentContainer = this.parent.getContainer();
  3547. if (!parentContainer) {
  3548. throw new Error('Cannot repaint panel: parent has no container element');
  3549. }
  3550. parentContainer.appendChild(frame);
  3551. changed += 1;
  3552. }
  3553. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  3554. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3555. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3556. changed += update(frame.style, 'height', asSize(options.height, '100%'));
  3557. return (changed > 0);
  3558. };
  3559. /**
  3560. * Reflow the component
  3561. * @return {Boolean} resized
  3562. */
  3563. Panel.prototype.reflow = function () {
  3564. var changed = 0,
  3565. update = util.updateProperty,
  3566. frame = this.frame;
  3567. if (frame) {
  3568. changed += update(this, 'top', frame.offsetTop);
  3569. changed += update(this, 'left', frame.offsetLeft);
  3570. changed += update(this, 'width', frame.offsetWidth);
  3571. changed += update(this, 'height', frame.offsetHeight);
  3572. }
  3573. else {
  3574. changed += 1;
  3575. }
  3576. return (changed > 0);
  3577. };
  3578. /**
  3579. * A root panel can hold components. The root panel must be initialized with
  3580. * a DOM element as container.
  3581. * @param {HTMLElement} container
  3582. * @param {Object} [options] Available parameters: see RootPanel.setOptions.
  3583. * @constructor RootPanel
  3584. * @extends Panel
  3585. */
  3586. function RootPanel(container, options) {
  3587. this.id = util.randomUUID();
  3588. this.container = container;
  3589. // create functions to be used as DOM event listeners
  3590. var me = this;
  3591. this.hammer = null;
  3592. // create listeners for all interesting events, these events will be emitted
  3593. // via the controller
  3594. var events = [
  3595. 'touch', 'pinch', 'tap', 'doubletap', 'hold',
  3596. 'dragstart', 'drag', 'dragend',
  3597. 'mousewheel', 'DOMMouseScroll' // DOMMouseScroll is for Firefox
  3598. ];
  3599. this.listeners = {};
  3600. events.forEach(function (event) {
  3601. me.listeners[event] = function () {
  3602. var args = [event].concat(Array.prototype.slice.call(arguments, 0));
  3603. me.controller.emit.apply(me.controller, args);
  3604. };
  3605. });
  3606. this.options = options || {};
  3607. this.defaultOptions = {
  3608. autoResize: true
  3609. };
  3610. }
  3611. RootPanel.prototype = new Panel();
  3612. /**
  3613. * Set options. Will extend the current options.
  3614. * @param {Object} [options] Available parameters:
  3615. * {String | function} [className]
  3616. * {String | Number | function} [left]
  3617. * {String | Number | function} [top]
  3618. * {String | Number | function} [width]
  3619. * {String | Number | function} [height]
  3620. * {Boolean | function} [autoResize]
  3621. */
  3622. RootPanel.prototype.setOptions = Component.prototype.setOptions;
  3623. /**
  3624. * Repaint the component
  3625. * @return {Boolean} changed
  3626. */
  3627. RootPanel.prototype.repaint = function () {
  3628. var changed = 0,
  3629. update = util.updateProperty,
  3630. asSize = util.option.asSize,
  3631. options = this.options,
  3632. frame = this.frame;
  3633. if (!frame) {
  3634. frame = document.createElement('div');
  3635. this.frame = frame;
  3636. this._registerListeners();
  3637. changed += 1;
  3638. }
  3639. if (!frame.parentNode) {
  3640. if (!this.container) {
  3641. throw new Error('Cannot repaint root panel: no container attached');
  3642. }
  3643. this.container.appendChild(frame);
  3644. changed += 1;
  3645. }
  3646. frame.className = 'vis timeline rootpanel ' + options.orientation +
  3647. (options.editable ? ' editable' : '');
  3648. var className = options.className;
  3649. if (className) {
  3650. util.addClassName(frame, util.option.asString(className));
  3651. }
  3652. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  3653. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3654. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3655. changed += update(frame.style, 'height', asSize(options.height, '100%'));
  3656. this._updateWatch();
  3657. return (changed > 0);
  3658. };
  3659. /**
  3660. * Reflow the component
  3661. * @return {Boolean} resized
  3662. */
  3663. RootPanel.prototype.reflow = function () {
  3664. var changed = 0,
  3665. update = util.updateProperty,
  3666. frame = this.frame;
  3667. if (frame) {
  3668. changed += update(this, 'top', frame.offsetTop);
  3669. changed += update(this, 'left', frame.offsetLeft);
  3670. changed += update(this, 'width', frame.offsetWidth);
  3671. changed += update(this, 'height', frame.offsetHeight);
  3672. }
  3673. else {
  3674. changed += 1;
  3675. }
  3676. return (changed > 0);
  3677. };
  3678. /**
  3679. * Update watching for resize, depending on the current option
  3680. * @private
  3681. */
  3682. RootPanel.prototype._updateWatch = function () {
  3683. var autoResize = this.getOption('autoResize');
  3684. if (autoResize) {
  3685. this._watch();
  3686. }
  3687. else {
  3688. this._unwatch();
  3689. }
  3690. };
  3691. /**
  3692. * Watch for changes in the size of the frame. On resize, the Panel will
  3693. * automatically redraw itself.
  3694. * @private
  3695. */
  3696. RootPanel.prototype._watch = function () {
  3697. var me = this;
  3698. this._unwatch();
  3699. var checkSize = function () {
  3700. var autoResize = me.getOption('autoResize');
  3701. if (!autoResize) {
  3702. // stop watching when the option autoResize is changed to false
  3703. me._unwatch();
  3704. return;
  3705. }
  3706. if (me.frame) {
  3707. // check whether the frame is resized
  3708. if ((me.frame.clientWidth != me.width) ||
  3709. (me.frame.clientHeight != me.height)) {
  3710. me.requestReflow();
  3711. }
  3712. }
  3713. };
  3714. // TODO: automatically cleanup the event listener when the frame is deleted
  3715. util.addEventListener(window, 'resize', checkSize);
  3716. this.watchTimer = setInterval(checkSize, 1000);
  3717. };
  3718. /**
  3719. * Stop watching for a resize of the frame.
  3720. * @private
  3721. */
  3722. RootPanel.prototype._unwatch = function () {
  3723. if (this.watchTimer) {
  3724. clearInterval(this.watchTimer);
  3725. this.watchTimer = undefined;
  3726. }
  3727. // TODO: remove event listener on window.resize
  3728. };
  3729. /**
  3730. * Set controller for this component, or remove current controller by passing
  3731. * null as parameter value.
  3732. * @param {Controller | null} controller
  3733. */
  3734. RootPanel.prototype.setController = function setController (controller) {
  3735. this.controller = controller || null;
  3736. if (this.controller) {
  3737. this._registerListeners();
  3738. }
  3739. else {
  3740. this._unregisterListeners();
  3741. }
  3742. };
  3743. /**
  3744. * Register event emitters emitted by the rootpanel
  3745. * @private
  3746. */
  3747. RootPanel.prototype._registerListeners = function () {
  3748. if (this.frame && this.controller && !this.hammer) {
  3749. this.hammer = Hammer(this.frame, {
  3750. prevent_default: true
  3751. });
  3752. for (var event in this.listeners) {
  3753. if (this.listeners.hasOwnProperty(event)) {
  3754. this.hammer.on(event, this.listeners[event]);
  3755. }
  3756. }
  3757. }
  3758. };
  3759. /**
  3760. * Unregister event emitters from the rootpanel
  3761. * @private
  3762. */
  3763. RootPanel.prototype._unregisterListeners = function () {
  3764. if (this.hammer) {
  3765. for (var event in this.listeners) {
  3766. if (this.listeners.hasOwnProperty(event)) {
  3767. this.hammer.off(event, this.listeners[event]);
  3768. }
  3769. }
  3770. this.hammer = null;
  3771. }
  3772. };
  3773. /**
  3774. * A horizontal time axis
  3775. * @param {Component} parent
  3776. * @param {Component[]} [depends] Components on which this components depends
  3777. * (except for the parent)
  3778. * @param {Object} [options] See TimeAxis.setOptions for the available
  3779. * options.
  3780. * @constructor TimeAxis
  3781. * @extends Component
  3782. */
  3783. function TimeAxis (parent, depends, options) {
  3784. this.id = util.randomUUID();
  3785. this.parent = parent;
  3786. this.depends = depends;
  3787. this.dom = {
  3788. majorLines: [],
  3789. majorTexts: [],
  3790. minorLines: [],
  3791. minorTexts: [],
  3792. redundant: {
  3793. majorLines: [],
  3794. majorTexts: [],
  3795. minorLines: [],
  3796. minorTexts: []
  3797. }
  3798. };
  3799. this.props = {
  3800. range: {
  3801. start: 0,
  3802. end: 0,
  3803. minimumStep: 0
  3804. },
  3805. lineTop: 0
  3806. };
  3807. this.options = options || {};
  3808. this.defaultOptions = {
  3809. orientation: 'bottom', // supported: 'top', 'bottom'
  3810. // TODO: implement timeaxis orientations 'left' and 'right'
  3811. showMinorLabels: true,
  3812. showMajorLabels: true
  3813. };
  3814. this.conversion = null;
  3815. this.range = null;
  3816. }
  3817. TimeAxis.prototype = new Component();
  3818. // TODO: comment options
  3819. TimeAxis.prototype.setOptions = Component.prototype.setOptions;
  3820. /**
  3821. * Set a range (start and end)
  3822. * @param {Range | Object} range A Range or an object containing start and end.
  3823. */
  3824. TimeAxis.prototype.setRange = function (range) {
  3825. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  3826. throw new TypeError('Range must be an instance of Range, ' +
  3827. 'or an object containing start and end.');
  3828. }
  3829. this.range = range;
  3830. };
  3831. /**
  3832. * Convert a position on screen (pixels) to a datetime
  3833. * @param {int} x Position on the screen in pixels
  3834. * @return {Date} time The datetime the corresponds with given position x
  3835. */
  3836. TimeAxis.prototype.toTime = function(x) {
  3837. var conversion = this.conversion;
  3838. return new Date(x / conversion.scale + conversion.offset);
  3839. };
  3840. /**
  3841. * Convert a datetime (Date object) into a position on the screen
  3842. * @param {Date} time A date
  3843. * @return {int} x The position on the screen in pixels which corresponds
  3844. * with the given date.
  3845. * @private
  3846. */
  3847. TimeAxis.prototype.toScreen = function(time) {
  3848. var conversion = this.conversion;
  3849. return (time.valueOf() - conversion.offset) * conversion.scale;
  3850. };
  3851. /**
  3852. * Repaint the component
  3853. * @return {Boolean} changed
  3854. */
  3855. TimeAxis.prototype.repaint = function () {
  3856. var changed = 0,
  3857. update = util.updateProperty,
  3858. asSize = util.option.asSize,
  3859. options = this.options,
  3860. orientation = this.getOption('orientation'),
  3861. props = this.props,
  3862. step = this.step;
  3863. var frame = this.frame;
  3864. if (!frame) {
  3865. frame = document.createElement('div');
  3866. this.frame = frame;
  3867. changed += 1;
  3868. }
  3869. frame.className = 'axis';
  3870. // TODO: custom className?
  3871. if (!frame.parentNode) {
  3872. if (!this.parent) {
  3873. throw new Error('Cannot repaint time axis: no parent attached');
  3874. }
  3875. var parentContainer = this.parent.getContainer();
  3876. if (!parentContainer) {
  3877. throw new Error('Cannot repaint time axis: parent has no container element');
  3878. }
  3879. parentContainer.appendChild(frame);
  3880. changed += 1;
  3881. }
  3882. var parent = frame.parentNode;
  3883. if (parent) {
  3884. var beforeChild = frame.nextSibling;
  3885. parent.removeChild(frame); // take frame offline while updating (is almost twice as fast)
  3886. var defaultTop = (orientation == 'bottom' && this.props.parentHeight && this.height) ?
  3887. (this.props.parentHeight - this.height) + 'px' :
  3888. '0px';
  3889. changed += update(frame.style, 'top', asSize(options.top, defaultTop));
  3890. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3891. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3892. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  3893. // get characters width and height
  3894. this._repaintMeasureChars();
  3895. if (this.step) {
  3896. this._repaintStart();
  3897. step.first();
  3898. var xFirstMajorLabel = undefined;
  3899. var max = 0;
  3900. while (step.hasNext() && max < 1000) {
  3901. max++;
  3902. var cur = step.getCurrent(),
  3903. x = this.toScreen(cur),
  3904. isMajor = step.isMajor();
  3905. // TODO: lines must have a width, such that we can create css backgrounds
  3906. if (this.getOption('showMinorLabels')) {
  3907. this._repaintMinorText(x, step.getLabelMinor());
  3908. }
  3909. if (isMajor && this.getOption('showMajorLabels')) {
  3910. if (x > 0) {
  3911. if (xFirstMajorLabel == undefined) {
  3912. xFirstMajorLabel = x;
  3913. }
  3914. this._repaintMajorText(x, step.getLabelMajor());
  3915. }
  3916. this._repaintMajorLine(x);
  3917. }
  3918. else {
  3919. this._repaintMinorLine(x);
  3920. }
  3921. step.next();
  3922. }
  3923. // create a major label on the left when needed
  3924. if (this.getOption('showMajorLabels')) {
  3925. var leftTime = this.toTime(0),
  3926. leftText = step.getLabelMajor(leftTime),
  3927. widthText = leftText.length * (props.majorCharWidth || 10) + 10; // upper bound estimation
  3928. if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) {
  3929. this._repaintMajorText(0, leftText);
  3930. }
  3931. }
  3932. this._repaintEnd();
  3933. }
  3934. this._repaintLine();
  3935. // put frame online again
  3936. if (beforeChild) {
  3937. parent.insertBefore(frame, beforeChild);
  3938. }
  3939. else {
  3940. parent.appendChild(frame)
  3941. }
  3942. }
  3943. return (changed > 0);
  3944. };
  3945. /**
  3946. * Start a repaint. Move all DOM elements to a redundant list, where they
  3947. * can be picked for re-use, or can be cleaned up in the end
  3948. * @private
  3949. */
  3950. TimeAxis.prototype._repaintStart = function () {
  3951. var dom = this.dom,
  3952. redundant = dom.redundant;
  3953. redundant.majorLines = dom.majorLines;
  3954. redundant.majorTexts = dom.majorTexts;
  3955. redundant.minorLines = dom.minorLines;
  3956. redundant.minorTexts = dom.minorTexts;
  3957. dom.majorLines = [];
  3958. dom.majorTexts = [];
  3959. dom.minorLines = [];
  3960. dom.minorTexts = [];
  3961. };
  3962. /**
  3963. * End a repaint. Cleanup leftover DOM elements in the redundant list
  3964. * @private
  3965. */
  3966. TimeAxis.prototype._repaintEnd = function () {
  3967. util.forEach(this.dom.redundant, function (arr) {
  3968. while (arr.length) {
  3969. var elem = arr.pop();
  3970. if (elem && elem.parentNode) {
  3971. elem.parentNode.removeChild(elem);
  3972. }
  3973. }
  3974. });
  3975. };
  3976. /**
  3977. * Create a minor label for the axis at position x
  3978. * @param {Number} x
  3979. * @param {String} text
  3980. * @private
  3981. */
  3982. TimeAxis.prototype._repaintMinorText = function (x, text) {
  3983. // reuse redundant label
  3984. var label = this.dom.redundant.minorTexts.shift();
  3985. if (!label) {
  3986. // create new label
  3987. var content = document.createTextNode('');
  3988. label = document.createElement('div');
  3989. label.appendChild(content);
  3990. label.className = 'text minor';
  3991. this.frame.appendChild(label);
  3992. }
  3993. this.dom.minorTexts.push(label);
  3994. label.childNodes[0].nodeValue = text;
  3995. label.style.left = x + 'px';
  3996. label.style.top = this.props.minorLabelTop + 'px';
  3997. //label.title = title; // TODO: this is a heavy operation
  3998. };
  3999. /**
  4000. * Create a Major label for the axis at position x
  4001. * @param {Number} x
  4002. * @param {String} text
  4003. * @private
  4004. */
  4005. TimeAxis.prototype._repaintMajorText = function (x, text) {
  4006. // reuse redundant label
  4007. var label = this.dom.redundant.majorTexts.shift();
  4008. if (!label) {
  4009. // create label
  4010. var content = document.createTextNode(text);
  4011. label = document.createElement('div');
  4012. label.className = 'text major';
  4013. label.appendChild(content);
  4014. this.frame.appendChild(label);
  4015. }
  4016. this.dom.majorTexts.push(label);
  4017. label.childNodes[0].nodeValue = text;
  4018. label.style.top = this.props.majorLabelTop + 'px';
  4019. label.style.left = x + 'px';
  4020. //label.title = title; // TODO: this is a heavy operation
  4021. };
  4022. /**
  4023. * Create a minor line for the axis at position x
  4024. * @param {Number} x
  4025. * @private
  4026. */
  4027. TimeAxis.prototype._repaintMinorLine = function (x) {
  4028. // reuse redundant line
  4029. var line = this.dom.redundant.minorLines.shift();
  4030. if (!line) {
  4031. // create vertical line
  4032. line = document.createElement('div');
  4033. line.className = 'grid vertical minor';
  4034. this.frame.appendChild(line);
  4035. }
  4036. this.dom.minorLines.push(line);
  4037. var props = this.props;
  4038. line.style.top = props.minorLineTop + 'px';
  4039. line.style.height = props.minorLineHeight + 'px';
  4040. line.style.left = (x - props.minorLineWidth / 2) + 'px';
  4041. };
  4042. /**
  4043. * Create a Major line for the axis at position x
  4044. * @param {Number} x
  4045. * @private
  4046. */
  4047. TimeAxis.prototype._repaintMajorLine = function (x) {
  4048. // reuse redundant line
  4049. var line = this.dom.redundant.majorLines.shift();
  4050. if (!line) {
  4051. // create vertical line
  4052. line = document.createElement('DIV');
  4053. line.className = 'grid vertical major';
  4054. this.frame.appendChild(line);
  4055. }
  4056. this.dom.majorLines.push(line);
  4057. var props = this.props;
  4058. line.style.top = props.majorLineTop + 'px';
  4059. line.style.left = (x - props.majorLineWidth / 2) + 'px';
  4060. line.style.height = props.majorLineHeight + 'px';
  4061. };
  4062. /**
  4063. * Repaint the horizontal line for the axis
  4064. * @private
  4065. */
  4066. TimeAxis.prototype._repaintLine = function() {
  4067. var line = this.dom.line,
  4068. frame = this.frame,
  4069. options = this.options;
  4070. // line before all axis elements
  4071. if (this.getOption('showMinorLabels') || this.getOption('showMajorLabels')) {
  4072. if (line) {
  4073. // put this line at the end of all childs
  4074. frame.removeChild(line);
  4075. frame.appendChild(line);
  4076. }
  4077. else {
  4078. // create the axis line
  4079. line = document.createElement('div');
  4080. line.className = 'grid horizontal major';
  4081. frame.appendChild(line);
  4082. this.dom.line = line;
  4083. }
  4084. line.style.top = this.props.lineTop + 'px';
  4085. }
  4086. else {
  4087. if (line && line.parentElement) {
  4088. frame.removeChild(line.line);
  4089. delete this.dom.line;
  4090. }
  4091. }
  4092. };
  4093. /**
  4094. * Create characters used to determine the size of text on the axis
  4095. * @private
  4096. */
  4097. TimeAxis.prototype._repaintMeasureChars = function () {
  4098. // calculate the width and height of a single character
  4099. // this is used to calculate the step size, and also the positioning of the
  4100. // axis
  4101. var dom = this.dom,
  4102. text;
  4103. if (!dom.measureCharMinor) {
  4104. text = document.createTextNode('0');
  4105. var measureCharMinor = document.createElement('DIV');
  4106. measureCharMinor.className = 'text minor measure';
  4107. measureCharMinor.appendChild(text);
  4108. this.frame.appendChild(measureCharMinor);
  4109. dom.measureCharMinor = measureCharMinor;
  4110. }
  4111. if (!dom.measureCharMajor) {
  4112. text = document.createTextNode('0');
  4113. var measureCharMajor = document.createElement('DIV');
  4114. measureCharMajor.className = 'text major measure';
  4115. measureCharMajor.appendChild(text);
  4116. this.frame.appendChild(measureCharMajor);
  4117. dom.measureCharMajor = measureCharMajor;
  4118. }
  4119. };
  4120. /**
  4121. * Reflow the component
  4122. * @return {Boolean} resized
  4123. */
  4124. TimeAxis.prototype.reflow = function () {
  4125. var changed = 0,
  4126. update = util.updateProperty,
  4127. frame = this.frame,
  4128. range = this.range;
  4129. if (!range) {
  4130. throw new Error('Cannot repaint time axis: no range configured');
  4131. }
  4132. if (frame) {
  4133. changed += update(this, 'top', frame.offsetTop);
  4134. changed += update(this, 'left', frame.offsetLeft);
  4135. // calculate size of a character
  4136. var props = this.props,
  4137. showMinorLabels = this.getOption('showMinorLabels'),
  4138. showMajorLabels = this.getOption('showMajorLabels'),
  4139. measureCharMinor = this.dom.measureCharMinor,
  4140. measureCharMajor = this.dom.measureCharMajor;
  4141. if (measureCharMinor) {
  4142. props.minorCharHeight = measureCharMinor.clientHeight;
  4143. props.minorCharWidth = measureCharMinor.clientWidth;
  4144. }
  4145. if (measureCharMajor) {
  4146. props.majorCharHeight = measureCharMajor.clientHeight;
  4147. props.majorCharWidth = measureCharMajor.clientWidth;
  4148. }
  4149. var parentHeight = frame.parentNode ? frame.parentNode.offsetHeight : 0;
  4150. if (parentHeight != props.parentHeight) {
  4151. props.parentHeight = parentHeight;
  4152. changed += 1;
  4153. }
  4154. switch (this.getOption('orientation')) {
  4155. case 'bottom':
  4156. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  4157. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  4158. props.minorLabelTop = 0;
  4159. props.majorLabelTop = props.minorLabelTop + props.minorLabelHeight;
  4160. props.minorLineTop = -this.top;
  4161. props.minorLineHeight = Math.max(this.top + props.majorLabelHeight, 0);
  4162. props.minorLineWidth = 1; // TODO: really calculate width
  4163. props.majorLineTop = -this.top;
  4164. props.majorLineHeight = Math.max(this.top + props.minorLabelHeight + props.majorLabelHeight, 0);
  4165. props.majorLineWidth = 1; // TODO: really calculate width
  4166. props.lineTop = 0;
  4167. break;
  4168. case 'top':
  4169. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  4170. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  4171. props.majorLabelTop = 0;
  4172. props.minorLabelTop = props.majorLabelTop + props.majorLabelHeight;
  4173. props.minorLineTop = props.minorLabelTop;
  4174. props.minorLineHeight = Math.max(parentHeight - props.majorLabelHeight - this.top);
  4175. props.minorLineWidth = 1; // TODO: really calculate width
  4176. props.majorLineTop = 0;
  4177. props.majorLineHeight = Math.max(parentHeight - this.top);
  4178. props.majorLineWidth = 1; // TODO: really calculate width
  4179. props.lineTop = props.majorLabelHeight + props.minorLabelHeight;
  4180. break;
  4181. default:
  4182. throw new Error('Unkown orientation "' + this.getOption('orientation') + '"');
  4183. }
  4184. var height = props.minorLabelHeight + props.majorLabelHeight;
  4185. changed += update(this, 'width', frame.offsetWidth);
  4186. changed += update(this, 'height', height);
  4187. // calculate range and step
  4188. this._updateConversion();
  4189. var start = util.convert(range.start, 'Number'),
  4190. end = util.convert(range.end, 'Number'),
  4191. minimumStep = this.toTime((props.minorCharWidth || 10) * 5).valueOf()
  4192. -this.toTime(0).valueOf();
  4193. this.step = new TimeStep(new Date(start), new Date(end), minimumStep);
  4194. changed += update(props.range, 'start', start);
  4195. changed += update(props.range, 'end', end);
  4196. changed += update(props.range, 'minimumStep', minimumStep.valueOf());
  4197. }
  4198. return (changed > 0);
  4199. };
  4200. /**
  4201. * Calculate the scale and offset to convert a position on screen to the
  4202. * corresponding date and vice versa.
  4203. * After the method _updateConversion is executed once, the methods toTime
  4204. * and toScreen can be used.
  4205. * @private
  4206. */
  4207. TimeAxis.prototype._updateConversion = function() {
  4208. var range = this.range;
  4209. if (!range) {
  4210. throw new Error('No range configured');
  4211. }
  4212. if (range.conversion) {
  4213. this.conversion = range.conversion(this.width);
  4214. }
  4215. else {
  4216. this.conversion = Range.conversion(range.start, range.end, this.width);
  4217. }
  4218. };
  4219. /**
  4220. * Snap a date to a rounded value.
  4221. * The snap intervals are dependent on the current scale and step.
  4222. * @param {Date} date the date to be snapped.
  4223. * @return {Date} snappedDate
  4224. */
  4225. TimeAxis.prototype.snap = function snap (date) {
  4226. return this.step.snap(date);
  4227. };
  4228. /**
  4229. * A current time bar
  4230. * @param {Component} parent
  4231. * @param {Component[]} [depends] Components on which this components depends
  4232. * (except for the parent)
  4233. * @param {Object} [options] Available parameters:
  4234. * {Boolean} [showCurrentTime]
  4235. * @constructor CurrentTime
  4236. * @extends Component
  4237. */
  4238. function CurrentTime (parent, depends, options) {
  4239. this.id = util.randomUUID();
  4240. this.parent = parent;
  4241. this.depends = depends;
  4242. this.options = options || {};
  4243. this.defaultOptions = {
  4244. showCurrentTime: false
  4245. };
  4246. }
  4247. CurrentTime.prototype = new Component();
  4248. CurrentTime.prototype.setOptions = Component.prototype.setOptions;
  4249. /**
  4250. * Get the container element of the bar, which can be used by a child to
  4251. * add its own widgets.
  4252. * @returns {HTMLElement} container
  4253. */
  4254. CurrentTime.prototype.getContainer = function () {
  4255. return this.frame;
  4256. };
  4257. /**
  4258. * Repaint the component
  4259. * @return {Boolean} changed
  4260. */
  4261. CurrentTime.prototype.repaint = function () {
  4262. var bar = this.frame,
  4263. parent = this.parent,
  4264. parentContainer = parent.parent.getContainer();
  4265. if (!parent) {
  4266. throw new Error('Cannot repaint bar: no parent attached');
  4267. }
  4268. if (!parentContainer) {
  4269. throw new Error('Cannot repaint bar: parent has no container element');
  4270. }
  4271. if (!this.getOption('showCurrentTime')) {
  4272. if (bar) {
  4273. parentContainer.removeChild(bar);
  4274. delete this.frame;
  4275. }
  4276. return false;
  4277. }
  4278. if (!bar) {
  4279. bar = document.createElement('div');
  4280. bar.className = 'currenttime';
  4281. bar.style.position = 'absolute';
  4282. bar.style.top = '0px';
  4283. bar.style.height = '100%';
  4284. parentContainer.appendChild(bar);
  4285. this.frame = bar;
  4286. }
  4287. if (!parent.conversion) {
  4288. parent._updateConversion();
  4289. }
  4290. var now = new Date();
  4291. var x = parent.toScreen(now);
  4292. bar.style.left = x + 'px';
  4293. bar.title = 'Current time: ' + now;
  4294. // start a timer to adjust for the new time
  4295. if (this.currentTimeTimer !== undefined) {
  4296. clearTimeout(this.currentTimeTimer);
  4297. delete this.currentTimeTimer;
  4298. }
  4299. var timeline = this;
  4300. var interval = 1 / parent.conversion.scale / 2;
  4301. if (interval < 30) {
  4302. interval = 30;
  4303. }
  4304. this.currentTimeTimer = setTimeout(function() {
  4305. timeline.repaint();
  4306. }, interval);
  4307. return false;
  4308. };
  4309. /**
  4310. * A custom time bar
  4311. * @param {Component} parent
  4312. * @param {Component[]} [depends] Components on which this components depends
  4313. * (except for the parent)
  4314. * @param {Object} [options] Available parameters:
  4315. * {Boolean} [showCustomTime]
  4316. * @constructor CustomTime
  4317. * @extends Component
  4318. */
  4319. function CustomTime (parent, depends, options) {
  4320. this.id = util.randomUUID();
  4321. this.parent = parent;
  4322. this.depends = depends;
  4323. this.options = options || {};
  4324. this.defaultOptions = {
  4325. showCustomTime: false
  4326. };
  4327. this.customTime = new Date();
  4328. this.eventParams = {}; // stores state parameters while dragging the bar
  4329. }
  4330. CustomTime.prototype = new Component();
  4331. Emitter(CustomTime.prototype);
  4332. CustomTime.prototype.setOptions = Component.prototype.setOptions;
  4333. /**
  4334. * Get the container element of the bar, which can be used by a child to
  4335. * add its own widgets.
  4336. * @returns {HTMLElement} container
  4337. */
  4338. CustomTime.prototype.getContainer = function () {
  4339. return this.frame;
  4340. };
  4341. /**
  4342. * Repaint the component
  4343. * @return {Boolean} changed
  4344. */
  4345. CustomTime.prototype.repaint = function () {
  4346. var bar = this.frame,
  4347. parent = this.parent;
  4348. if (!parent) {
  4349. throw new Error('Cannot repaint bar: no parent attached');
  4350. }
  4351. var parentContainer = parent.parent.getContainer();
  4352. if (!parentContainer) {
  4353. throw new Error('Cannot repaint bar: parent has no container element');
  4354. }
  4355. if (!this.getOption('showCustomTime')) {
  4356. if (bar) {
  4357. parentContainer.removeChild(bar);
  4358. delete this.frame;
  4359. }
  4360. return false;
  4361. }
  4362. if (!bar) {
  4363. bar = document.createElement('div');
  4364. bar.className = 'customtime';
  4365. bar.style.position = 'absolute';
  4366. bar.style.top = '0px';
  4367. bar.style.height = '100%';
  4368. parentContainer.appendChild(bar);
  4369. var drag = document.createElement('div');
  4370. drag.style.position = 'relative';
  4371. drag.style.top = '0px';
  4372. drag.style.left = '-10px';
  4373. drag.style.height = '100%';
  4374. drag.style.width = '20px';
  4375. bar.appendChild(drag);
  4376. this.frame = bar;
  4377. // attach event listeners
  4378. this.hammer = Hammer(bar, {
  4379. prevent_default: true
  4380. });
  4381. this.hammer.on('dragstart', this._onDragStart.bind(this));
  4382. this.hammer.on('drag', this._onDrag.bind(this));
  4383. this.hammer.on('dragend', this._onDragEnd.bind(this));
  4384. }
  4385. if (!parent.conversion) {
  4386. parent._updateConversion();
  4387. }
  4388. var x = parent.toScreen(this.customTime);
  4389. bar.style.left = x + 'px';
  4390. bar.title = 'Time: ' + this.customTime;
  4391. return false;
  4392. };
  4393. /**
  4394. * Set custom time.
  4395. * @param {Date} time
  4396. */
  4397. CustomTime.prototype.setCustomTime = function(time) {
  4398. this.customTime = new Date(time.valueOf());
  4399. this.repaint();
  4400. };
  4401. /**
  4402. * Retrieve the current custom time.
  4403. * @return {Date} customTime
  4404. */
  4405. CustomTime.prototype.getCustomTime = function() {
  4406. return new Date(this.customTime.valueOf());
  4407. };
  4408. /**
  4409. * Start moving horizontally
  4410. * @param {Event} event
  4411. * @private
  4412. */
  4413. CustomTime.prototype._onDragStart = function(event) {
  4414. this.eventParams.customTime = this.customTime;
  4415. event.stopPropagation();
  4416. event.preventDefault();
  4417. };
  4418. /**
  4419. * Perform moving operating.
  4420. * @param {Event} event
  4421. * @private
  4422. */
  4423. CustomTime.prototype._onDrag = function (event) {
  4424. var deltaX = event.gesture.deltaX,
  4425. x = this.parent.toScreen(this.eventParams.customTime) + deltaX,
  4426. time = this.parent.toTime(x);
  4427. this.setCustomTime(time);
  4428. // fire a timechange event
  4429. if (this.controller) {
  4430. this.controller.emit('timechange', {
  4431. time: this.customTime
  4432. })
  4433. }
  4434. event.stopPropagation();
  4435. event.preventDefault();
  4436. };
  4437. /**
  4438. * Stop moving operating.
  4439. * @param {event} event
  4440. * @private
  4441. */
  4442. CustomTime.prototype._onDragEnd = function (event) {
  4443. // fire a timechanged event
  4444. if (this.controller) {
  4445. this.controller.emit('timechanged', {
  4446. time: this.customTime
  4447. })
  4448. }
  4449. event.stopPropagation();
  4450. event.preventDefault();
  4451. };
  4452. /**
  4453. * An ItemSet holds a set of items and ranges which can be displayed in a
  4454. * range. The width is determined by the parent of the ItemSet, and the height
  4455. * is determined by the size of the items.
  4456. * @param {Component} parent
  4457. * @param {Component[]} [depends] Components on which this components depends
  4458. * (except for the parent)
  4459. * @param {Object} [options] See ItemSet.setOptions for the available
  4460. * options.
  4461. * @constructor ItemSet
  4462. * @extends Panel
  4463. */
  4464. // TODO: improve performance by replacing all Array.forEach with a for loop
  4465. function ItemSet(parent, depends, options) {
  4466. this.id = util.randomUUID();
  4467. this.parent = parent;
  4468. this.depends = depends;
  4469. // event listeners
  4470. this.eventListeners = {
  4471. dragstart: this._onDragStart.bind(this),
  4472. drag: this._onDrag.bind(this),
  4473. dragend: this._onDragEnd.bind(this)
  4474. };
  4475. // one options object is shared by this itemset and all its items
  4476. this.options = options || {};
  4477. this.defaultOptions = {
  4478. type: 'box',
  4479. align: 'center',
  4480. orientation: 'bottom',
  4481. margin: {
  4482. axis: 20,
  4483. item: 10
  4484. },
  4485. padding: 5
  4486. };
  4487. this.dom = {};
  4488. var me = this;
  4489. this.itemsData = null; // DataSet
  4490. this.range = null; // Range or Object {start: number, end: number}
  4491. // data change listeners
  4492. this.listeners = {
  4493. 'add': function (event, params, senderId) {
  4494. if (senderId != me.id) {
  4495. me._onAdd(params.items);
  4496. }
  4497. },
  4498. 'update': function (event, params, senderId) {
  4499. if (senderId != me.id) {
  4500. me._onUpdate(params.items);
  4501. }
  4502. },
  4503. 'remove': function (event, params, senderId) {
  4504. if (senderId != me.id) {
  4505. me._onRemove(params.items);
  4506. }
  4507. }
  4508. };
  4509. this.items = {}; // object with an Item for every data item
  4510. this.selection = []; // list with the ids of all selected nodes
  4511. this.queue = {}; // queue with id/actions: 'add', 'update', 'delete'
  4512. this.stack = new Stack(this, Object.create(this.options));
  4513. this.conversion = null;
  4514. this.touchParams = {}; // stores properties while dragging
  4515. // TODO: ItemSet should also attach event listeners for rangechange and rangechanged, like timeaxis
  4516. }
  4517. ItemSet.prototype = new Panel();
  4518. // available item types will be registered here
  4519. ItemSet.types = {
  4520. box: ItemBox,
  4521. range: ItemRange,
  4522. rangeoverflow: ItemRangeOverflow,
  4523. point: ItemPoint
  4524. };
  4525. /**
  4526. * Set options for the ItemSet. Existing options will be extended/overwritten.
  4527. * @param {Object} [options] The following options are available:
  4528. * {String | function} [className]
  4529. * class name for the itemset
  4530. * {String} [type]
  4531. * Default type for the items. Choose from 'box'
  4532. * (default), 'point', or 'range'. The default
  4533. * Style can be overwritten by individual items.
  4534. * {String} align
  4535. * Alignment for the items, only applicable for
  4536. * ItemBox. Choose 'center' (default), 'left', or
  4537. * 'right'.
  4538. * {String} orientation
  4539. * Orientation of the item set. Choose 'top' or
  4540. * 'bottom' (default).
  4541. * {Number} margin.axis
  4542. * Margin between the axis and the items in pixels.
  4543. * Default is 20.
  4544. * {Number} margin.item
  4545. * Margin between items in pixels. Default is 10.
  4546. * {Number} padding
  4547. * Padding of the contents of an item in pixels.
  4548. * Must correspond with the items css. Default is 5.
  4549. * {Function} snap
  4550. * Function to let items snap to nice dates when
  4551. * dragging items.
  4552. */
  4553. ItemSet.prototype.setOptions = Component.prototype.setOptions;
  4554. /**
  4555. * Set controller for this component
  4556. * @param {Controller | null} controller
  4557. */
  4558. ItemSet.prototype.setController = function setController (controller) {
  4559. var event;
  4560. // unregister old event listeners
  4561. if (this.controller) {
  4562. for (event in this.eventListeners) {
  4563. if (this.eventListeners.hasOwnProperty(event)) {
  4564. this.controller.off(event, this.eventListeners[event]);
  4565. }
  4566. }
  4567. }
  4568. this.controller = controller || null;
  4569. // register new event listeners
  4570. if (this.controller) {
  4571. for (event in this.eventListeners) {
  4572. if (this.eventListeners.hasOwnProperty(event)) {
  4573. this.controller.on(event, this.eventListeners[event]);
  4574. }
  4575. }
  4576. }
  4577. };
  4578. // attach event listeners for dragging items to the controller
  4579. (function (me) {
  4580. var _controller = null;
  4581. var _onDragStart = null;
  4582. var _onDrag = null;
  4583. var _onDragEnd = null;
  4584. Object.defineProperty(me, 'controller', {
  4585. get: function () {
  4586. return _controller;
  4587. },
  4588. set: function (controller) {
  4589. }
  4590. });
  4591. }) (this);
  4592. /**
  4593. * Set range (start and end).
  4594. * @param {Range | Object} range A Range or an object containing start and end.
  4595. */
  4596. ItemSet.prototype.setRange = function setRange(range) {
  4597. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  4598. throw new TypeError('Range must be an instance of Range, ' +
  4599. 'or an object containing start and end.');
  4600. }
  4601. this.range = range;
  4602. };
  4603. /**
  4604. * Set selected items by their id. Replaces the current selection
  4605. * Unknown id's are silently ignored.
  4606. * @param {Array} [ids] An array with zero or more id's of the items to be
  4607. * selected. If ids is an empty array, all items will be
  4608. * unselected.
  4609. */
  4610. ItemSet.prototype.setSelection = function setSelection(ids) {
  4611. var i, ii, id, item, selection;
  4612. if (ids) {
  4613. if (!Array.isArray(ids)) {
  4614. throw new TypeError('Array expected');
  4615. }
  4616. // unselect currently selected items
  4617. for (i = 0, ii = this.selection.length; i < ii; i++) {
  4618. id = this.selection[i];
  4619. item = this.items[id];
  4620. if (item) item.unselect();
  4621. }
  4622. // select items
  4623. this.selection = [];
  4624. for (i = 0, ii = ids.length; i < ii; i++) {
  4625. id = ids[i];
  4626. item = this.items[id];
  4627. if (item) {
  4628. this.selection.push(id);
  4629. item.select();
  4630. }
  4631. }
  4632. if (this.controller) {
  4633. this.requestRepaint();
  4634. }
  4635. }
  4636. };
  4637. /**
  4638. * Get the selected items by their id
  4639. * @return {Array} ids The ids of the selected items
  4640. */
  4641. ItemSet.prototype.getSelection = function getSelection() {
  4642. return this.selection.concat([]);
  4643. };
  4644. /**
  4645. * Deselect a selected item
  4646. * @param {String | Number} id
  4647. * @private
  4648. */
  4649. ItemSet.prototype._deselect = function _deselect(id) {
  4650. var selection = this.selection;
  4651. for (var i = 0, ii = selection.length; i < ii; i++) {
  4652. if (selection[i] == id) { // non-strict comparison!
  4653. selection.splice(i, 1);
  4654. break;
  4655. }
  4656. }
  4657. };
  4658. /**
  4659. * Repaint the component
  4660. * @return {Boolean} changed
  4661. */
  4662. ItemSet.prototype.repaint = function repaint() {
  4663. var changed = 0,
  4664. update = util.updateProperty,
  4665. asSize = util.option.asSize,
  4666. options = this.options,
  4667. orientation = this.getOption('orientation'),
  4668. defaultOptions = this.defaultOptions,
  4669. frame = this.frame;
  4670. if (!frame) {
  4671. frame = document.createElement('div');
  4672. frame.className = 'itemset';
  4673. frame['timeline-itemset'] = this;
  4674. var className = options.className;
  4675. if (className) {
  4676. util.addClassName(frame, util.option.asString(className));
  4677. }
  4678. // create background panel
  4679. var background = document.createElement('div');
  4680. background.className = 'background';
  4681. frame.appendChild(background);
  4682. this.dom.background = background;
  4683. // create foreground panel
  4684. var foreground = document.createElement('div');
  4685. foreground.className = 'foreground';
  4686. frame.appendChild(foreground);
  4687. this.dom.foreground = foreground;
  4688. // create axis panel
  4689. var axis = document.createElement('div');
  4690. axis.className = 'itemset-axis';
  4691. //frame.appendChild(axis);
  4692. this.dom.axis = axis;
  4693. this.frame = frame;
  4694. changed += 1;
  4695. }
  4696. if (!this.parent) {
  4697. throw new Error('Cannot repaint itemset: no parent attached');
  4698. }
  4699. var parentContainer = this.parent.getContainer();
  4700. if (!parentContainer) {
  4701. throw new Error('Cannot repaint itemset: parent has no container element');
  4702. }
  4703. if (!frame.parentNode) {
  4704. parentContainer.appendChild(frame);
  4705. changed += 1;
  4706. }
  4707. if (!this.dom.axis.parentNode) {
  4708. parentContainer.appendChild(this.dom.axis);
  4709. changed += 1;
  4710. }
  4711. // reposition frame
  4712. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  4713. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  4714. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  4715. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  4716. // reposition axis
  4717. changed += update(this.dom.axis.style, 'left', asSize(options.left, '0px'));
  4718. changed += update(this.dom.axis.style, 'width', asSize(options.width, '100%'));
  4719. if (orientation == 'bottom') {
  4720. changed += update(this.dom.axis.style, 'top', (this.height + this.top) + 'px');
  4721. }
  4722. else { // orientation == 'top'
  4723. changed += update(this.dom.axis.style, 'top', this.top + 'px');
  4724. }
  4725. this._updateConversion();
  4726. var me = this,
  4727. queue = this.queue,
  4728. itemsData = this.itemsData,
  4729. items = this.items,
  4730. dataOptions = {
  4731. // TODO: cleanup
  4732. // fields: [(itemsData && itemsData.fieldId || 'id'), 'start', 'end', 'content', 'type', 'className']
  4733. };
  4734. // show/hide added/changed/removed items
  4735. for (var id in queue) {
  4736. if (queue.hasOwnProperty(id)) {
  4737. var entry = queue[id],
  4738. item = items[id],
  4739. action = entry.action;
  4740. //noinspection FallthroughInSwitchStatementJS
  4741. switch (action) {
  4742. case 'add':
  4743. case 'update':
  4744. var itemData = itemsData && itemsData.get(id, dataOptions);
  4745. if (itemData) {
  4746. var type = itemData.type ||
  4747. (itemData.start && itemData.end && 'range') ||
  4748. options.type ||
  4749. 'box';
  4750. var constructor = ItemSet.types[type];
  4751. // TODO: how to handle items with invalid data? hide them and give a warning? or throw an error?
  4752. if (item) {
  4753. // update item
  4754. if (!constructor || !(item instanceof constructor)) {
  4755. // item type has changed, hide and delete the item
  4756. changed += item.hide();
  4757. item = null;
  4758. }
  4759. else {
  4760. item.data = itemData; // TODO: create a method item.setData ?
  4761. changed++;
  4762. }
  4763. }
  4764. if (!item) {
  4765. // create item
  4766. if (constructor) {
  4767. item = new constructor(me, itemData, options, defaultOptions);
  4768. item.id = entry.id; // we take entry.id, as id itself is stringified
  4769. changed++;
  4770. }
  4771. else {
  4772. throw new TypeError('Unknown item type "' + type + '"');
  4773. }
  4774. }
  4775. // force a repaint (not only a reposition)
  4776. item.repaint();
  4777. items[id] = item;
  4778. }
  4779. // update queue
  4780. delete queue[id];
  4781. break;
  4782. case 'remove':
  4783. if (item) {
  4784. // remove the item from the set selected items
  4785. if (item.selected) {
  4786. me._deselect(id);
  4787. }
  4788. // remove DOM of the item
  4789. changed += item.hide();
  4790. }
  4791. // update lists
  4792. delete items[id];
  4793. delete queue[id];
  4794. break;
  4795. default:
  4796. console.log('Error: unknown action "' + action + '"');
  4797. }
  4798. }
  4799. }
  4800. // reposition all items. Show items only when in the visible area
  4801. util.forEach(this.items, function (item) {
  4802. if (item.visible) {
  4803. changed += item.show();
  4804. item.reposition();
  4805. }
  4806. else {
  4807. changed += item.hide();
  4808. }
  4809. });
  4810. return (changed > 0);
  4811. };
  4812. /**
  4813. * Get the foreground container element
  4814. * @return {HTMLElement} foreground
  4815. */
  4816. ItemSet.prototype.getForeground = function getForeground() {
  4817. return this.dom.foreground;
  4818. };
  4819. /**
  4820. * Get the background container element
  4821. * @return {HTMLElement} background
  4822. */
  4823. ItemSet.prototype.getBackground = function getBackground() {
  4824. return this.dom.background;
  4825. };
  4826. /**
  4827. * Get the axis container element
  4828. * @return {HTMLElement} axis
  4829. */
  4830. ItemSet.prototype.getAxis = function getAxis() {
  4831. return this.dom.axis;
  4832. };
  4833. /**
  4834. * Reflow the component
  4835. * @return {Boolean} resized
  4836. */
  4837. ItemSet.prototype.reflow = function reflow () {
  4838. var changed = 0,
  4839. options = this.options,
  4840. marginAxis = (options.margin && 'axis' in options.margin) ? options.margin.axis : this.defaultOptions.margin.axis,
  4841. marginItem = (options.margin && 'item' in options.margin) ? options.margin.item : this.defaultOptions.margin.item,
  4842. update = util.updateProperty,
  4843. asNumber = util.option.asNumber,
  4844. asSize = util.option.asSize,
  4845. frame = this.frame;
  4846. if (frame) {
  4847. this._updateConversion();
  4848. util.forEach(this.items, function (item) {
  4849. changed += item.reflow();
  4850. });
  4851. // TODO: stack.update should be triggered via an event, in stack itself
  4852. // TODO: only update the stack when there are changed items
  4853. this.stack.update();
  4854. var maxHeight = asNumber(options.maxHeight);
  4855. var fixedHeight = (asSize(options.height) != null);
  4856. var height;
  4857. if (fixedHeight) {
  4858. height = frame.offsetHeight;
  4859. }
  4860. else {
  4861. // height is not specified, determine the height from the height and positioned items
  4862. var visibleItems = this.stack.ordered; // TODO: not so nice way to get the filtered items
  4863. if (visibleItems.length) {
  4864. var min = visibleItems[0].top;
  4865. var max = visibleItems[0].top + visibleItems[0].height;
  4866. util.forEach(visibleItems, function (item) {
  4867. min = Math.min(min, item.top);
  4868. max = Math.max(max, (item.top + item.height));
  4869. });
  4870. height = (max - min) + marginAxis + marginItem;
  4871. }
  4872. else {
  4873. height = marginAxis + marginItem;
  4874. }
  4875. }
  4876. if (maxHeight != null) {
  4877. height = Math.min(height, maxHeight);
  4878. }
  4879. changed += update(this, 'height', height);
  4880. // calculate height from items
  4881. changed += update(this, 'top', frame.offsetTop);
  4882. changed += update(this, 'left', frame.offsetLeft);
  4883. changed += update(this, 'width', frame.offsetWidth);
  4884. }
  4885. else {
  4886. changed += 1;
  4887. }
  4888. return (changed > 0);
  4889. };
  4890. /**
  4891. * Hide this component from the DOM
  4892. * @return {Boolean} changed
  4893. */
  4894. ItemSet.prototype.hide = function hide() {
  4895. var changed = false;
  4896. // remove the DOM
  4897. if (this.frame && this.frame.parentNode) {
  4898. this.frame.parentNode.removeChild(this.frame);
  4899. changed = true;
  4900. }
  4901. if (this.dom.axis && this.dom.axis.parentNode) {
  4902. this.dom.axis.parentNode.removeChild(this.dom.axis);
  4903. changed = true;
  4904. }
  4905. return changed;
  4906. };
  4907. /**
  4908. * Set items
  4909. * @param {vis.DataSet | null} items
  4910. */
  4911. ItemSet.prototype.setItems = function setItems(items) {
  4912. var me = this,
  4913. ids,
  4914. oldItemsData = this.itemsData;
  4915. // replace the dataset
  4916. if (!items) {
  4917. this.itemsData = null;
  4918. }
  4919. else if (items instanceof DataSet || items instanceof DataView) {
  4920. this.itemsData = items;
  4921. }
  4922. else {
  4923. throw new TypeError('Data must be an instance of DataSet');
  4924. }
  4925. if (oldItemsData) {
  4926. // unsubscribe from old dataset
  4927. util.forEach(this.listeners, function (callback, event) {
  4928. oldItemsData.unsubscribe(event, callback);
  4929. });
  4930. // remove all drawn items
  4931. ids = oldItemsData.getIds();
  4932. this._onRemove(ids);
  4933. }
  4934. if (this.itemsData) {
  4935. // subscribe to new dataset
  4936. var id = this.id;
  4937. util.forEach(this.listeners, function (callback, event) {
  4938. me.itemsData.on(event, callback, id);
  4939. });
  4940. // draw all new items
  4941. ids = this.itemsData.getIds();
  4942. this._onAdd(ids);
  4943. }
  4944. };
  4945. /**
  4946. * Get the current items items
  4947. * @returns {vis.DataSet | null}
  4948. */
  4949. ItemSet.prototype.getItems = function getItems() {
  4950. return this.itemsData;
  4951. };
  4952. /**
  4953. * Remove an item by its id
  4954. * @param {String | Number} id
  4955. */
  4956. ItemSet.prototype.removeItem = function removeItem (id) {
  4957. var item = this.itemsData.get(id),
  4958. dataset = this._myDataSet();
  4959. if (item) {
  4960. // confirm deletion
  4961. this.options.onRemove(item, function (item) {
  4962. if (item) {
  4963. dataset.remove(item);
  4964. }
  4965. });
  4966. }
  4967. };
  4968. /**
  4969. * Handle updated items
  4970. * @param {Number[]} ids
  4971. * @private
  4972. */
  4973. ItemSet.prototype._onUpdate = function _onUpdate(ids) {
  4974. this._toQueue('update', ids);
  4975. };
  4976. /**
  4977. * Handle changed items
  4978. * @param {Number[]} ids
  4979. * @private
  4980. */
  4981. ItemSet.prototype._onAdd = function _onAdd(ids) {
  4982. this._toQueue('add', ids);
  4983. };
  4984. /**
  4985. * Handle removed items
  4986. * @param {Number[]} ids
  4987. * @private
  4988. */
  4989. ItemSet.prototype._onRemove = function _onRemove(ids) {
  4990. this._toQueue('remove', ids);
  4991. };
  4992. /**
  4993. * Put items in the queue to be added/updated/remove
  4994. * @param {String} action can be 'add', 'update', 'remove'
  4995. * @param {Number[]} ids
  4996. */
  4997. ItemSet.prototype._toQueue = function _toQueue(action, ids) {
  4998. var queue = this.queue;
  4999. ids.forEach(function (id) {
  5000. queue[id] = {
  5001. id: id,
  5002. action: action
  5003. };
  5004. });
  5005. if (this.controller) {
  5006. //this.requestReflow();
  5007. this.requestRepaint();
  5008. }
  5009. };
  5010. /**
  5011. * Calculate the scale and offset to convert a position on screen to the
  5012. * corresponding date and vice versa.
  5013. * After the method _updateConversion is executed once, the methods toTime
  5014. * and toScreen can be used.
  5015. * @private
  5016. */
  5017. ItemSet.prototype._updateConversion = function _updateConversion() {
  5018. var range = this.range;
  5019. if (!range) {
  5020. throw new Error('No range configured');
  5021. }
  5022. if (range.conversion) {
  5023. this.conversion = range.conversion(this.width);
  5024. }
  5025. else {
  5026. this.conversion = Range.conversion(range.start, range.end, this.width);
  5027. }
  5028. };
  5029. /**
  5030. * Convert a position on screen (pixels) to a datetime
  5031. * Before this method can be used, the method _updateConversion must be
  5032. * executed once.
  5033. * @param {int} x Position on the screen in pixels
  5034. * @return {Date} time The datetime the corresponds with given position x
  5035. */
  5036. ItemSet.prototype.toTime = function toTime(x) {
  5037. var conversion = this.conversion;
  5038. return new Date(x / conversion.scale + conversion.offset);
  5039. };
  5040. /**
  5041. * Convert a datetime (Date object) into a position on the screen
  5042. * Before this method can be used, the method _updateConversion must be
  5043. * executed once.
  5044. * @param {Date} time A date
  5045. * @return {int} x The position on the screen in pixels which corresponds
  5046. * with the given date.
  5047. */
  5048. ItemSet.prototype.toScreen = function toScreen(time) {
  5049. var conversion = this.conversion;
  5050. return (time.valueOf() - conversion.offset) * conversion.scale;
  5051. };
  5052. /**
  5053. * Start dragging the selected events
  5054. * @param {Event} event
  5055. * @private
  5056. */
  5057. ItemSet.prototype._onDragStart = function (event) {
  5058. if (!this.options.editable) {
  5059. return;
  5060. }
  5061. var item = ItemSet.itemFromTarget(event),
  5062. me = this;
  5063. if (item && item.selected) {
  5064. var dragLeftItem = event.target.dragLeftItem;
  5065. var dragRightItem = event.target.dragRightItem;
  5066. if (dragLeftItem) {
  5067. this.touchParams.itemProps = [{
  5068. item: dragLeftItem,
  5069. start: item.data.start.valueOf()
  5070. }];
  5071. }
  5072. else if (dragRightItem) {
  5073. this.touchParams.itemProps = [{
  5074. item: dragRightItem,
  5075. end: item.data.end.valueOf()
  5076. }];
  5077. }
  5078. else {
  5079. this.touchParams.itemProps = this.getSelection().map(function (id) {
  5080. var item = me.items[id];
  5081. var props = {
  5082. item: item
  5083. };
  5084. if ('start' in item.data) {
  5085. props.start = item.data.start.valueOf()
  5086. }
  5087. if ('end' in item.data) {
  5088. props.end = item.data.end.valueOf()
  5089. }
  5090. return props;
  5091. });
  5092. }
  5093. event.stopPropagation();
  5094. }
  5095. };
  5096. /**
  5097. * Drag selected items
  5098. * @param {Event} event
  5099. * @private
  5100. */
  5101. ItemSet.prototype._onDrag = function (event) {
  5102. if (this.touchParams.itemProps) {
  5103. var snap = this.options.snap || null,
  5104. deltaX = event.gesture.deltaX,
  5105. offset = deltaX / this.conversion.scale;
  5106. // move
  5107. this.touchParams.itemProps.forEach(function (props) {
  5108. if ('start' in props) {
  5109. var start = new Date(props.start + offset);
  5110. props.item.data.start = snap ? snap(start) : start;
  5111. }
  5112. if ('end' in props) {
  5113. var end = new Date(props.end + offset);
  5114. props.item.data.end = snap ? snap(end) : end;
  5115. }
  5116. });
  5117. // TODO: implement onMoving handler
  5118. // TODO: implement dragging from one group to another
  5119. this.requestReflow();
  5120. event.stopPropagation();
  5121. }
  5122. };
  5123. /**
  5124. * End of dragging selected items
  5125. * @param {Event} event
  5126. * @private
  5127. */
  5128. ItemSet.prototype._onDragEnd = function (event) {
  5129. if (this.touchParams.itemProps) {
  5130. // prepare a change set for the changed items
  5131. var changes = [],
  5132. me = this,
  5133. dataset = this._myDataSet(),
  5134. type;
  5135. this.touchParams.itemProps.forEach(function (props) {
  5136. var id = props.item.id,
  5137. item = me.itemsData.get(id);
  5138. var changed = false;
  5139. if ('start' in props.item.data) {
  5140. changed = (props.start != props.item.data.start.valueOf());
  5141. item.start = util.convert(props.item.data.start, dataset.convert['start']);
  5142. }
  5143. if ('end' in props.item.data) {
  5144. changed = changed || (props.end != props.item.data.end.valueOf());
  5145. item.end = util.convert(props.item.data.end, dataset.convert['end']);
  5146. }
  5147. // only apply changes when start or end is actually changed
  5148. if (changed) {
  5149. me.options.onMove(item, function (item) {
  5150. if (item) {
  5151. // apply changes
  5152. changes.push(item);
  5153. }
  5154. else {
  5155. // restore original values
  5156. if ('start' in props) props.item.data.start = props.start;
  5157. if ('end' in props) props.item.data.end = props.end;
  5158. me.requestReflow();
  5159. }
  5160. });
  5161. }
  5162. });
  5163. this.touchParams.itemProps = null;
  5164. // apply the changes to the data (if there are changes)
  5165. if (changes.length) {
  5166. dataset.update(changes);
  5167. }
  5168. event.stopPropagation();
  5169. }
  5170. };
  5171. /**
  5172. * Find an item from an event target:
  5173. * searches for the attribute 'timeline-item' in the event target's element tree
  5174. * @param {Event} event
  5175. * @return {Item | null} item
  5176. */
  5177. ItemSet.itemFromTarget = function itemFromTarget (event) {
  5178. var target = event.target;
  5179. while (target) {
  5180. if (target.hasOwnProperty('timeline-item')) {
  5181. return target['timeline-item'];
  5182. }
  5183. target = target.parentNode;
  5184. }
  5185. return null;
  5186. };
  5187. /**
  5188. * Find the ItemSet from an event target:
  5189. * searches for the attribute 'timeline-itemset' in the event target's element tree
  5190. * @param {Event} event
  5191. * @return {ItemSet | null} item
  5192. */
  5193. ItemSet.itemSetFromTarget = function itemSetFromTarget (event) {
  5194. var target = event.target;
  5195. while (target) {
  5196. if (target.hasOwnProperty('timeline-itemset')) {
  5197. return target['timeline-itemset'];
  5198. }
  5199. target = target.parentNode;
  5200. }
  5201. return null;
  5202. };
  5203. /**
  5204. * Find the DataSet to which this ItemSet is connected
  5205. * @returns {null | DataSet} dataset
  5206. * @private
  5207. */
  5208. ItemSet.prototype._myDataSet = function _myDataSet() {
  5209. // find the root DataSet
  5210. var dataset = this.itemsData;
  5211. while (dataset instanceof DataView) {
  5212. dataset = dataset.data;
  5213. }
  5214. return dataset;
  5215. };
  5216. /**
  5217. * @constructor Item
  5218. * @param {ItemSet} parent
  5219. * @param {Object} data Object containing (optional) parameters type,
  5220. * start, end, content, group, className.
  5221. * @param {Object} [options] Options to set initial property values
  5222. * @param {Object} [defaultOptions] default options
  5223. * // TODO: describe available options
  5224. */
  5225. function Item (parent, data, options, defaultOptions) {
  5226. this.parent = parent;
  5227. this.data = data;
  5228. this.dom = null;
  5229. this.options = options || {};
  5230. this.defaultOptions = defaultOptions || {};
  5231. this.selected = false;
  5232. this.visible = false;
  5233. this.top = 0;
  5234. this.left = 0;
  5235. this.width = 0;
  5236. this.height = 0;
  5237. this.offset = 0;
  5238. }
  5239. /**
  5240. * Select current item
  5241. */
  5242. Item.prototype.select = function select() {
  5243. this.selected = true;
  5244. if (this.visible) this.repaint();
  5245. };
  5246. /**
  5247. * Unselect current item
  5248. */
  5249. Item.prototype.unselect = function unselect() {
  5250. this.selected = false;
  5251. if (this.visible) this.repaint();
  5252. };
  5253. /**
  5254. * Show the Item in the DOM (when not already visible)
  5255. * @return {Boolean} changed
  5256. */
  5257. Item.prototype.show = function show() {
  5258. return false;
  5259. };
  5260. /**
  5261. * Hide the Item from the DOM (when visible)
  5262. * @return {Boolean} changed
  5263. */
  5264. Item.prototype.hide = function hide() {
  5265. return false;
  5266. };
  5267. /**
  5268. * Repaint the item
  5269. * @return {Boolean} changed
  5270. */
  5271. Item.prototype.repaint = function repaint() {
  5272. // should be implemented by the item
  5273. return false;
  5274. };
  5275. /**
  5276. * Reflow the item
  5277. * @return {Boolean} resized
  5278. */
  5279. Item.prototype.reflow = function reflow() {
  5280. // should be implemented by the item
  5281. return false;
  5282. };
  5283. /**
  5284. * Give the item a display offset in pixels
  5285. * @param {Number} offset Offset on screen in pixels
  5286. */
  5287. Item.prototype.setOffset = function setOffset(offset) {
  5288. this.offset = offset;
  5289. };
  5290. /**
  5291. * Repaint a delete button on the top right of the item when the item is selected
  5292. * @param {HTMLElement} anchor
  5293. * @private
  5294. */
  5295. Item.prototype._repaintDeleteButton = function (anchor) {
  5296. if (this.selected && this.options.editable && !this.dom.deleteButton) {
  5297. // create and show button
  5298. var parent = this.parent;
  5299. var id = this.id;
  5300. var deleteButton = document.createElement('div');
  5301. deleteButton.className = 'delete';
  5302. deleteButton.title = 'Delete this item';
  5303. Hammer(deleteButton, {
  5304. preventDefault: true
  5305. }).on('tap', function (event) {
  5306. parent.removeItem(id);
  5307. event.stopPropagation();
  5308. });
  5309. anchor.appendChild(deleteButton);
  5310. this.dom.deleteButton = deleteButton;
  5311. }
  5312. else if (!this.selected && this.dom.deleteButton) {
  5313. // remove button
  5314. if (this.dom.deleteButton.parentNode) {
  5315. this.dom.deleteButton.parentNode.removeChild(this.dom.deleteButton);
  5316. }
  5317. this.dom.deleteButton = null;
  5318. }
  5319. };
  5320. /**
  5321. * @constructor ItemBox
  5322. * @extends Item
  5323. * @param {ItemSet} parent
  5324. * @param {Object} data Object containing parameters start
  5325. * content, className.
  5326. * @param {Object} [options] Options to set initial property values
  5327. * @param {Object} [defaultOptions] default options
  5328. * // TODO: describe available options
  5329. */
  5330. function ItemBox (parent, data, options, defaultOptions) {
  5331. this.props = {
  5332. dot: {
  5333. left: 0,
  5334. top: 0,
  5335. width: 0,
  5336. height: 0
  5337. },
  5338. line: {
  5339. top: 0,
  5340. left: 0,
  5341. width: 0,
  5342. height: 0
  5343. }
  5344. };
  5345. Item.call(this, parent, data, options, defaultOptions);
  5346. }
  5347. ItemBox.prototype = new Item (null, null);
  5348. /**
  5349. * Repaint the item
  5350. * @return {Boolean} changed
  5351. */
  5352. ItemBox.prototype.repaint = function repaint() {
  5353. // TODO: make an efficient repaint
  5354. var changed = false;
  5355. var dom = this.dom;
  5356. if (!dom) {
  5357. this._create();
  5358. dom = this.dom;
  5359. changed = true;
  5360. }
  5361. if (dom) {
  5362. if (!this.parent) {
  5363. throw new Error('Cannot repaint item: no parent attached');
  5364. }
  5365. if (!dom.box.parentNode) {
  5366. var foreground = this.parent.getForeground();
  5367. if (!foreground) {
  5368. throw new Error('Cannot repaint time axis: ' +
  5369. 'parent has no foreground container element');
  5370. }
  5371. foreground.appendChild(dom.box);
  5372. changed = true;
  5373. }
  5374. if (!dom.line.parentNode) {
  5375. var background = this.parent.getBackground();
  5376. if (!background) {
  5377. throw new Error('Cannot repaint time axis: ' +
  5378. 'parent has no background container element');
  5379. }
  5380. background.appendChild(dom.line);
  5381. changed = true;
  5382. }
  5383. if (!dom.dot.parentNode) {
  5384. var axis = this.parent.getAxis();
  5385. if (!background) {
  5386. throw new Error('Cannot repaint time axis: ' +
  5387. 'parent has no axis container element');
  5388. }
  5389. axis.appendChild(dom.dot);
  5390. changed = true;
  5391. }
  5392. this._repaintDeleteButton(dom.box);
  5393. // update contents
  5394. if (this.data.content != this.content) {
  5395. this.content = this.data.content;
  5396. if (this.content instanceof Element) {
  5397. dom.content.innerHTML = '';
  5398. dom.content.appendChild(this.content);
  5399. }
  5400. else if (this.data.content != undefined) {
  5401. dom.content.innerHTML = this.content;
  5402. }
  5403. else {
  5404. throw new Error('Property "content" missing in item ' + this.data.id);
  5405. }
  5406. changed = true;
  5407. }
  5408. // update class
  5409. var className = (this.data.className? ' ' + this.data.className : '') +
  5410. (this.selected ? ' selected' : '');
  5411. if (this.className != className) {
  5412. this.className = className;
  5413. dom.box.className = 'item box' + className;
  5414. dom.line.className = 'item line' + className;
  5415. dom.dot.className = 'item dot' + className;
  5416. changed = true;
  5417. }
  5418. }
  5419. return changed;
  5420. };
  5421. /**
  5422. * Show the item in the DOM (when not already visible). The items DOM will
  5423. * be created when needed.
  5424. * @return {Boolean} changed
  5425. */
  5426. ItemBox.prototype.show = function show() {
  5427. if (!this.dom || !this.dom.box.parentNode) {
  5428. return this.repaint();
  5429. }
  5430. else {
  5431. return false;
  5432. }
  5433. };
  5434. /**
  5435. * Hide the item from the DOM (when visible)
  5436. * @return {Boolean} changed
  5437. */
  5438. ItemBox.prototype.hide = function hide() {
  5439. var changed = false,
  5440. dom = this.dom;
  5441. if (dom) {
  5442. if (dom.box.parentNode) {
  5443. dom.box.parentNode.removeChild(dom.box);
  5444. changed = true;
  5445. }
  5446. if (dom.line.parentNode) {
  5447. dom.line.parentNode.removeChild(dom.line);
  5448. }
  5449. if (dom.dot.parentNode) {
  5450. dom.dot.parentNode.removeChild(dom.dot);
  5451. }
  5452. }
  5453. return changed;
  5454. };
  5455. /**
  5456. * Reflow the item: calculate its actual size and position from the DOM
  5457. * @return {boolean} resized returns true if the axis is resized
  5458. * @override
  5459. */
  5460. ItemBox.prototype.reflow = function reflow() {
  5461. var changed = 0,
  5462. update,
  5463. dom,
  5464. props,
  5465. options,
  5466. margin,
  5467. start,
  5468. align,
  5469. orientation,
  5470. top,
  5471. left,
  5472. data,
  5473. range;
  5474. if (this.data.start == undefined) {
  5475. throw new Error('Property "start" missing in item ' + this.data.id);
  5476. }
  5477. data = this.data;
  5478. range = this.parent && this.parent.range;
  5479. if (data && range) {
  5480. // TODO: account for the width of the item
  5481. var interval = (range.end - range.start);
  5482. this.visible = (data.start > range.start - interval) && (data.start < range.end + interval);
  5483. }
  5484. else {
  5485. this.visible = false;
  5486. }
  5487. if (this.visible) {
  5488. dom = this.dom;
  5489. if (dom) {
  5490. update = util.updateProperty;
  5491. props = this.props;
  5492. options = this.options;
  5493. start = this.parent.toScreen(this.data.start) + this.offset;
  5494. align = options.align || this.defaultOptions.align;
  5495. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  5496. orientation = options.orientation || this.defaultOptions.orientation;
  5497. changed += update(props.dot, 'height', dom.dot.offsetHeight);
  5498. changed += update(props.dot, 'width', dom.dot.offsetWidth);
  5499. changed += update(props.line, 'width', dom.line.offsetWidth);
  5500. changed += update(props.line, 'height', dom.line.offsetHeight);
  5501. changed += update(props.line, 'top', dom.line.offsetTop);
  5502. changed += update(this, 'width', dom.box.offsetWidth);
  5503. changed += update(this, 'height', dom.box.offsetHeight);
  5504. if (align == 'right') {
  5505. left = start - this.width;
  5506. }
  5507. else if (align == 'left') {
  5508. left = start;
  5509. }
  5510. else {
  5511. // default or 'center'
  5512. left = start - this.width / 2;
  5513. }
  5514. changed += update(this, 'left', left);
  5515. changed += update(props.line, 'left', start - props.line.width / 2);
  5516. changed += update(props.dot, 'left', start - props.dot.width / 2);
  5517. changed += update(props.dot, 'top', -props.dot.height / 2);
  5518. if (orientation == 'top') {
  5519. top = margin;
  5520. changed += update(this, 'top', top);
  5521. }
  5522. else {
  5523. // default or 'bottom'
  5524. var parentHeight = this.parent.height;
  5525. top = parentHeight - this.height - margin;
  5526. changed += update(this, 'top', top);
  5527. }
  5528. }
  5529. else {
  5530. changed += 1;
  5531. }
  5532. }
  5533. return (changed > 0);
  5534. };
  5535. /**
  5536. * Create an items DOM
  5537. * @private
  5538. */
  5539. ItemBox.prototype._create = function _create() {
  5540. var dom = this.dom;
  5541. if (!dom) {
  5542. this.dom = dom = {};
  5543. // create the box
  5544. dom.box = document.createElement('DIV');
  5545. // className is updated in repaint()
  5546. // contents box (inside the background box). used for making margins
  5547. dom.content = document.createElement('DIV');
  5548. dom.content.className = 'content';
  5549. dom.box.appendChild(dom.content);
  5550. // line to axis
  5551. dom.line = document.createElement('DIV');
  5552. dom.line.className = 'line';
  5553. // dot on axis
  5554. dom.dot = document.createElement('DIV');
  5555. dom.dot.className = 'dot';
  5556. // attach this item as attribute
  5557. dom.box['timeline-item'] = this;
  5558. }
  5559. };
  5560. /**
  5561. * Reposition the item, recalculate its left, top, and width, using the current
  5562. * range and size of the items itemset
  5563. * @override
  5564. */
  5565. ItemBox.prototype.reposition = function reposition() {
  5566. var dom = this.dom,
  5567. props = this.props,
  5568. orientation = this.options.orientation || this.defaultOptions.orientation;
  5569. if (dom) {
  5570. var box = dom.box,
  5571. line = dom.line,
  5572. dot = dom.dot;
  5573. box.style.left = this.left + 'px';
  5574. box.style.top = this.top + 'px';
  5575. line.style.left = props.line.left + 'px';
  5576. if (orientation == 'top') {
  5577. line.style.top = 0 + 'px';
  5578. line.style.height = this.top + 'px';
  5579. }
  5580. else {
  5581. // orientation 'bottom'
  5582. line.style.top = (this.top + this.height) + 'px';
  5583. line.style.height = Math.max(this.parent.height - this.top - this.height +
  5584. this.props.dot.height / 2, 0) + 'px';
  5585. }
  5586. dot.style.left = props.dot.left + 'px';
  5587. dot.style.top = props.dot.top + 'px';
  5588. }
  5589. };
  5590. /**
  5591. * @constructor ItemPoint
  5592. * @extends Item
  5593. * @param {ItemSet} parent
  5594. * @param {Object} data Object containing parameters start
  5595. * content, className.
  5596. * @param {Object} [options] Options to set initial property values
  5597. * @param {Object} [defaultOptions] default options
  5598. * // TODO: describe available options
  5599. */
  5600. function ItemPoint (parent, data, options, defaultOptions) {
  5601. this.props = {
  5602. dot: {
  5603. top: 0,
  5604. width: 0,
  5605. height: 0
  5606. },
  5607. content: {
  5608. height: 0,
  5609. marginLeft: 0
  5610. }
  5611. };
  5612. Item.call(this, parent, data, options, defaultOptions);
  5613. }
  5614. ItemPoint.prototype = new Item (null, null);
  5615. /**
  5616. * Repaint the item
  5617. * @return {Boolean} changed
  5618. */
  5619. ItemPoint.prototype.repaint = function repaint() {
  5620. // TODO: make an efficient repaint
  5621. var changed = false;
  5622. var dom = this.dom;
  5623. if (!dom) {
  5624. this._create();
  5625. dom = this.dom;
  5626. changed = true;
  5627. }
  5628. if (dom) {
  5629. if (!this.parent) {
  5630. throw new Error('Cannot repaint item: no parent attached');
  5631. }
  5632. var foreground = this.parent.getForeground();
  5633. if (!foreground) {
  5634. throw new Error('Cannot repaint time axis: ' +
  5635. 'parent has no foreground container element');
  5636. }
  5637. if (!dom.point.parentNode) {
  5638. foreground.appendChild(dom.point);
  5639. foreground.appendChild(dom.point);
  5640. changed = true;
  5641. }
  5642. // update contents
  5643. if (this.data.content != this.content) {
  5644. this.content = this.data.content;
  5645. if (this.content instanceof Element) {
  5646. dom.content.innerHTML = '';
  5647. dom.content.appendChild(this.content);
  5648. }
  5649. else if (this.data.content != undefined) {
  5650. dom.content.innerHTML = this.content;
  5651. }
  5652. else {
  5653. throw new Error('Property "content" missing in item ' + this.data.id);
  5654. }
  5655. changed = true;
  5656. }
  5657. this._repaintDeleteButton(dom.point);
  5658. // update class
  5659. var className = (this.data.className? ' ' + this.data.className : '') +
  5660. (this.selected ? ' selected' : '');
  5661. if (this.className != className) {
  5662. this.className = className;
  5663. dom.point.className = 'item point' + className;
  5664. changed = true;
  5665. }
  5666. }
  5667. return changed;
  5668. };
  5669. /**
  5670. * Show the item in the DOM (when not already visible). The items DOM will
  5671. * be created when needed.
  5672. * @return {Boolean} changed
  5673. */
  5674. ItemPoint.prototype.show = function show() {
  5675. if (!this.dom || !this.dom.point.parentNode) {
  5676. return this.repaint();
  5677. }
  5678. else {
  5679. return false;
  5680. }
  5681. };
  5682. /**
  5683. * Hide the item from the DOM (when visible)
  5684. * @return {Boolean} changed
  5685. */
  5686. ItemPoint.prototype.hide = function hide() {
  5687. var changed = false,
  5688. dom = this.dom;
  5689. if (dom) {
  5690. if (dom.point.parentNode) {
  5691. dom.point.parentNode.removeChild(dom.point);
  5692. changed = true;
  5693. }
  5694. }
  5695. return changed;
  5696. };
  5697. /**
  5698. * Reflow the item: calculate its actual size from the DOM
  5699. * @return {boolean} resized returns true if the axis is resized
  5700. * @override
  5701. */
  5702. ItemPoint.prototype.reflow = function reflow() {
  5703. var changed = 0,
  5704. update,
  5705. dom,
  5706. props,
  5707. options,
  5708. margin,
  5709. orientation,
  5710. start,
  5711. top,
  5712. data,
  5713. range;
  5714. if (this.data.start == undefined) {
  5715. throw new Error('Property "start" missing in item ' + this.data.id);
  5716. }
  5717. data = this.data;
  5718. range = this.parent && this.parent.range;
  5719. if (data && range) {
  5720. // TODO: account for the width of the item
  5721. var interval = (range.end - range.start);
  5722. this.visible = (data.start > range.start - interval) && (data.start < range.end);
  5723. }
  5724. else {
  5725. this.visible = false;
  5726. }
  5727. if (this.visible) {
  5728. dom = this.dom;
  5729. if (dom) {
  5730. update = util.updateProperty;
  5731. props = this.props;
  5732. options = this.options;
  5733. orientation = options.orientation || this.defaultOptions.orientation;
  5734. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  5735. start = this.parent.toScreen(this.data.start) + this.offset;
  5736. changed += update(this, 'width', dom.point.offsetWidth);
  5737. changed += update(this, 'height', dom.point.offsetHeight);
  5738. changed += update(props.dot, 'width', dom.dot.offsetWidth);
  5739. changed += update(props.dot, 'height', dom.dot.offsetHeight);
  5740. changed += update(props.content, 'height', dom.content.offsetHeight);
  5741. if (orientation == 'top') {
  5742. top = margin;
  5743. }
  5744. else {
  5745. // default or 'bottom'
  5746. var parentHeight = this.parent.height;
  5747. top = Math.max(parentHeight - this.height - margin, 0);
  5748. }
  5749. changed += update(this, 'top', top);
  5750. changed += update(this, 'left', start - props.dot.width / 2);
  5751. changed += update(props.content, 'marginLeft', 1.5 * props.dot.width);
  5752. //changed += update(props.content, 'marginRight', 0.5 * props.dot.width); // TODO
  5753. changed += update(props.dot, 'top', (this.height - props.dot.height) / 2);
  5754. }
  5755. else {
  5756. changed += 1;
  5757. }
  5758. }
  5759. return (changed > 0);
  5760. };
  5761. /**
  5762. * Create an items DOM
  5763. * @private
  5764. */
  5765. ItemPoint.prototype._create = function _create() {
  5766. var dom = this.dom;
  5767. if (!dom) {
  5768. this.dom = dom = {};
  5769. // background box
  5770. dom.point = document.createElement('div');
  5771. // className is updated in repaint()
  5772. // contents box, right from the dot
  5773. dom.content = document.createElement('div');
  5774. dom.content.className = 'content';
  5775. dom.point.appendChild(dom.content);
  5776. // dot at start
  5777. dom.dot = document.createElement('div');
  5778. dom.dot.className = 'dot';
  5779. dom.point.appendChild(dom.dot);
  5780. // attach this item as attribute
  5781. dom.point['timeline-item'] = this;
  5782. }
  5783. };
  5784. /**
  5785. * Reposition the item, recalculate its left, top, and width, using the current
  5786. * range and size of the items itemset
  5787. * @override
  5788. */
  5789. ItemPoint.prototype.reposition = function reposition() {
  5790. var dom = this.dom,
  5791. props = this.props;
  5792. if (dom) {
  5793. dom.point.style.top = this.top + 'px';
  5794. dom.point.style.left = this.left + 'px';
  5795. dom.content.style.marginLeft = props.content.marginLeft + 'px';
  5796. //dom.content.style.marginRight = props.content.marginRight + 'px'; // TODO
  5797. dom.dot.style.top = props.dot.top + 'px';
  5798. }
  5799. };
  5800. /**
  5801. * @constructor ItemRange
  5802. * @extends Item
  5803. * @param {ItemSet} parent
  5804. * @param {Object} data Object containing parameters start, end
  5805. * content, className.
  5806. * @param {Object} [options] Options to set initial property values
  5807. * @param {Object} [defaultOptions] default options
  5808. * // TODO: describe available options
  5809. */
  5810. function ItemRange (parent, data, options, defaultOptions) {
  5811. this.props = {
  5812. content: {
  5813. left: 0,
  5814. width: 0
  5815. }
  5816. };
  5817. Item.call(this, parent, data, options, defaultOptions);
  5818. }
  5819. ItemRange.prototype = new Item (null, null);
  5820. /**
  5821. * Repaint the item
  5822. * @return {Boolean} changed
  5823. */
  5824. ItemRange.prototype.repaint = function repaint() {
  5825. // TODO: make an efficient repaint
  5826. var changed = false;
  5827. var dom = this.dom;
  5828. if (!dom) {
  5829. this._create();
  5830. dom = this.dom;
  5831. changed = true;
  5832. }
  5833. if (dom) {
  5834. if (!this.parent) {
  5835. throw new Error('Cannot repaint item: no parent attached');
  5836. }
  5837. var foreground = this.parent.getForeground();
  5838. if (!foreground) {
  5839. throw new Error('Cannot repaint time axis: ' +
  5840. 'parent has no foreground container element');
  5841. }
  5842. if (!dom.box.parentNode) {
  5843. foreground.appendChild(dom.box);
  5844. changed = true;
  5845. }
  5846. // update content
  5847. if (this.data.content != this.content) {
  5848. this.content = this.data.content;
  5849. if (this.content instanceof Element) {
  5850. dom.content.innerHTML = '';
  5851. dom.content.appendChild(this.content);
  5852. }
  5853. else if (this.data.content != undefined) {
  5854. dom.content.innerHTML = this.content;
  5855. }
  5856. else {
  5857. throw new Error('Property "content" missing in item ' + this.data.id);
  5858. }
  5859. changed = true;
  5860. }
  5861. this._repaintDeleteButton(dom.box);
  5862. this._repaintDragLeft();
  5863. this._repaintDragRight();
  5864. // update class
  5865. var className = (this.data.className ? (' ' + this.data.className) : '') +
  5866. (this.selected ? ' selected' : '');
  5867. if (this.className != className) {
  5868. this.className = className;
  5869. dom.box.className = 'item range' + className;
  5870. changed = true;
  5871. }
  5872. }
  5873. return changed;
  5874. };
  5875. /**
  5876. * Show the item in the DOM (when not already visible). The items DOM will
  5877. * be created when needed.
  5878. * @return {Boolean} changed
  5879. */
  5880. ItemRange.prototype.show = function show() {
  5881. if (!this.dom || !this.dom.box.parentNode) {
  5882. return this.repaint();
  5883. }
  5884. else {
  5885. return false;
  5886. }
  5887. };
  5888. /**
  5889. * Hide the item from the DOM (when visible)
  5890. * @return {Boolean} changed
  5891. */
  5892. ItemRange.prototype.hide = function hide() {
  5893. var changed = false,
  5894. dom = this.dom;
  5895. if (dom) {
  5896. if (dom.box.parentNode) {
  5897. dom.box.parentNode.removeChild(dom.box);
  5898. changed = true;
  5899. }
  5900. }
  5901. return changed;
  5902. };
  5903. /**
  5904. * Reflow the item: calculate its actual size from the DOM
  5905. * @return {boolean} resized returns true if the axis is resized
  5906. * @override
  5907. */
  5908. ItemRange.prototype.reflow = function reflow() {
  5909. var changed = 0,
  5910. dom,
  5911. props,
  5912. options,
  5913. margin,
  5914. padding,
  5915. parent,
  5916. start,
  5917. end,
  5918. data,
  5919. range,
  5920. update,
  5921. box,
  5922. parentWidth,
  5923. contentLeft,
  5924. orientation,
  5925. top;
  5926. if (this.data.start == undefined) {
  5927. throw new Error('Property "start" missing in item ' + this.data.id);
  5928. }
  5929. if (this.data.end == undefined) {
  5930. throw new Error('Property "end" missing in item ' + this.data.id);
  5931. }
  5932. data = this.data;
  5933. range = this.parent && this.parent.range;
  5934. if (data && range) {
  5935. // TODO: account for the width of the item. Take some margin
  5936. this.visible = (data.start < range.end) && (data.end > range.start);
  5937. }
  5938. else {
  5939. this.visible = false;
  5940. }
  5941. if (this.visible) {
  5942. dom = this.dom;
  5943. if (dom) {
  5944. props = this.props;
  5945. options = this.options;
  5946. parent = this.parent;
  5947. start = parent.toScreen(this.data.start) + this.offset;
  5948. end = parent.toScreen(this.data.end) + this.offset;
  5949. update = util.updateProperty;
  5950. box = dom.box;
  5951. parentWidth = parent.width;
  5952. orientation = options.orientation || this.defaultOptions.orientation;
  5953. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  5954. padding = options.padding || this.defaultOptions.padding;
  5955. changed += update(props.content, 'width', dom.content.offsetWidth);
  5956. changed += update(this, 'height', box.offsetHeight);
  5957. // limit the width of the this, as browsers cannot draw very wide divs
  5958. if (start < -parentWidth) {
  5959. start = -parentWidth;
  5960. }
  5961. if (end > 2 * parentWidth) {
  5962. end = 2 * parentWidth;
  5963. }
  5964. // when range exceeds left of the window, position the contents at the left of the visible area
  5965. if (start < 0) {
  5966. contentLeft = Math.min(-start,
  5967. (end - start - props.content.width - 2 * padding));
  5968. // TODO: remove the need for options.padding. it's terrible.
  5969. }
  5970. else {
  5971. contentLeft = 0;
  5972. }
  5973. changed += update(props.content, 'left', contentLeft);
  5974. if (orientation == 'top') {
  5975. top = margin;
  5976. changed += update(this, 'top', top);
  5977. }
  5978. else {
  5979. // default or 'bottom'
  5980. top = parent.height - this.height - margin;
  5981. changed += update(this, 'top', top);
  5982. }
  5983. changed += update(this, 'left', start);
  5984. changed += update(this, 'width', Math.max(end - start, 1)); // TODO: reckon with border width;
  5985. }
  5986. else {
  5987. changed += 1;
  5988. }
  5989. }
  5990. return (changed > 0);
  5991. };
  5992. /**
  5993. * Create an items DOM
  5994. * @private
  5995. */
  5996. ItemRange.prototype._create = function _create() {
  5997. var dom = this.dom;
  5998. if (!dom) {
  5999. this.dom = dom = {};
  6000. // background box
  6001. dom.box = document.createElement('div');
  6002. // className is updated in repaint()
  6003. // contents box
  6004. dom.content = document.createElement('div');
  6005. dom.content.className = 'content';
  6006. dom.box.appendChild(dom.content);
  6007. // attach this item as attribute
  6008. dom.box['timeline-item'] = this;
  6009. }
  6010. };
  6011. /**
  6012. * Reposition the item, recalculate its left, top, and width, using the current
  6013. * range and size of the items itemset
  6014. * @override
  6015. */
  6016. ItemRange.prototype.reposition = function reposition() {
  6017. var dom = this.dom,
  6018. props = this.props;
  6019. if (dom) {
  6020. dom.box.style.top = this.top + 'px';
  6021. dom.box.style.left = this.left + 'px';
  6022. dom.box.style.width = this.width + 'px';
  6023. dom.content.style.left = props.content.left + 'px';
  6024. }
  6025. };
  6026. /**
  6027. * Repaint a drag area on the left side of the range when the range is selected
  6028. * @private
  6029. */
  6030. ItemRange.prototype._repaintDragLeft = function () {
  6031. if (this.selected && this.options.editable && !this.dom.dragLeft) {
  6032. // create and show drag area
  6033. var dragLeft = document.createElement('div');
  6034. dragLeft.className = 'drag-left';
  6035. dragLeft.dragLeftItem = this;
  6036. // TODO: this should be redundant?
  6037. Hammer(dragLeft, {
  6038. preventDefault: true
  6039. }).on('drag', function () {
  6040. //console.log('drag left')
  6041. });
  6042. this.dom.box.appendChild(dragLeft);
  6043. this.dom.dragLeft = dragLeft;
  6044. }
  6045. else if (!this.selected && this.dom.dragLeft) {
  6046. // delete drag area
  6047. if (this.dom.dragLeft.parentNode) {
  6048. this.dom.dragLeft.parentNode.removeChild(this.dom.dragLeft);
  6049. }
  6050. this.dom.dragLeft = null;
  6051. }
  6052. };
  6053. /**
  6054. * Repaint a drag area on the right side of the range when the range is selected
  6055. * @private
  6056. */
  6057. ItemRange.prototype._repaintDragRight = function () {
  6058. if (this.selected && this.options.editable && !this.dom.dragRight) {
  6059. // create and show drag area
  6060. var dragRight = document.createElement('div');
  6061. dragRight.className = 'drag-right';
  6062. dragRight.dragRightItem = this;
  6063. // TODO: this should be redundant?
  6064. Hammer(dragRight, {
  6065. preventDefault: true
  6066. }).on('drag', function () {
  6067. //console.log('drag right')
  6068. });
  6069. this.dom.box.appendChild(dragRight);
  6070. this.dom.dragRight = dragRight;
  6071. }
  6072. else if (!this.selected && this.dom.dragRight) {
  6073. // delete drag area
  6074. if (this.dom.dragRight.parentNode) {
  6075. this.dom.dragRight.parentNode.removeChild(this.dom.dragRight);
  6076. }
  6077. this.dom.dragRight = null;
  6078. }
  6079. };
  6080. /**
  6081. * @constructor ItemRangeOverflow
  6082. * @extends ItemRange
  6083. * @param {ItemSet} parent
  6084. * @param {Object} data Object containing parameters start, end
  6085. * content, className.
  6086. * @param {Object} [options] Options to set initial property values
  6087. * @param {Object} [defaultOptions] default options
  6088. * // TODO: describe available options
  6089. */
  6090. function ItemRangeOverflow (parent, data, options, defaultOptions) {
  6091. this.props = {
  6092. content: {
  6093. left: 0,
  6094. width: 0
  6095. }
  6096. };
  6097. // define a private property _width, which is the with of the range box
  6098. // adhering to the ranges start and end date. The property width has a
  6099. // getter which returns the max of border width and content width
  6100. this._width = 0;
  6101. Object.defineProperty(this, 'width', {
  6102. get: function () {
  6103. return (this.props.content && this._width < this.props.content.width) ?
  6104. this.props.content.width :
  6105. this._width;
  6106. },
  6107. set: function (width) {
  6108. this._width = width;
  6109. }
  6110. });
  6111. ItemRange.call(this, parent, data, options, defaultOptions);
  6112. }
  6113. ItemRangeOverflow.prototype = new ItemRange (null, null);
  6114. /**
  6115. * Repaint the item
  6116. * @return {Boolean} changed
  6117. */
  6118. ItemRangeOverflow.prototype.repaint = function repaint() {
  6119. // TODO: make an efficient repaint
  6120. var changed = false;
  6121. var dom = this.dom;
  6122. if (!dom) {
  6123. this._create();
  6124. dom = this.dom;
  6125. changed = true;
  6126. }
  6127. if (dom) {
  6128. if (!this.parent) {
  6129. throw new Error('Cannot repaint item: no parent attached');
  6130. }
  6131. var foreground = this.parent.getForeground();
  6132. if (!foreground) {
  6133. throw new Error('Cannot repaint time axis: ' +
  6134. 'parent has no foreground container element');
  6135. }
  6136. if (!dom.box.parentNode) {
  6137. foreground.appendChild(dom.box);
  6138. changed = true;
  6139. }
  6140. // update content
  6141. if (this.data.content != this.content) {
  6142. this.content = this.data.content;
  6143. if (this.content instanceof Element) {
  6144. dom.content.innerHTML = '';
  6145. dom.content.appendChild(this.content);
  6146. }
  6147. else if (this.data.content != undefined) {
  6148. dom.content.innerHTML = this.content;
  6149. }
  6150. else {
  6151. throw new Error('Property "content" missing in item ' + this.id);
  6152. }
  6153. changed = true;
  6154. }
  6155. this._repaintDeleteButton(dom.box);
  6156. this._repaintDragLeft();
  6157. this._repaintDragRight();
  6158. // update class
  6159. var className = (this.data.className? ' ' + this.data.className : '') +
  6160. (this.selected ? ' selected' : '');
  6161. if (this.className != className) {
  6162. this.className = className;
  6163. dom.box.className = 'item rangeoverflow' + className;
  6164. changed = true;
  6165. }
  6166. }
  6167. return changed;
  6168. };
  6169. /**
  6170. * Reposition the item, recalculate its left, top, and width, using the current
  6171. * range and size of the items itemset
  6172. * @override
  6173. */
  6174. ItemRangeOverflow.prototype.reposition = function reposition() {
  6175. var dom = this.dom,
  6176. props = this.props;
  6177. if (dom) {
  6178. dom.box.style.top = this.top + 'px';
  6179. dom.box.style.left = this.left + 'px';
  6180. dom.box.style.width = this._width + 'px';
  6181. dom.content.style.left = props.content.left + 'px';
  6182. }
  6183. };
  6184. /**
  6185. * @constructor Group
  6186. * @param {GroupSet} parent
  6187. * @param {Number | String} groupId
  6188. * @param {Object} [options] Options to set initial property values
  6189. * // TODO: describe available options
  6190. * @extends Component
  6191. */
  6192. function Group (parent, groupId, options) {
  6193. this.id = util.randomUUID();
  6194. this.parent = parent;
  6195. this.groupId = groupId;
  6196. this.itemset = null; // ItemSet
  6197. this.options = options || {};
  6198. this.options.top = 0;
  6199. this.props = {
  6200. label: {
  6201. width: 0,
  6202. height: 0
  6203. }
  6204. };
  6205. this.top = 0;
  6206. this.left = 0;
  6207. this.width = 0;
  6208. this.height = 0;
  6209. }
  6210. Group.prototype = new Component();
  6211. // TODO: comment
  6212. Group.prototype.setOptions = Component.prototype.setOptions;
  6213. /**
  6214. * Get the container element of the panel, which can be used by a child to
  6215. * add its own widgets.
  6216. * @returns {HTMLElement} container
  6217. */
  6218. Group.prototype.getContainer = function () {
  6219. return this.parent.getContainer();
  6220. };
  6221. /**
  6222. * Set item set for the group. The group will create a view on the itemset,
  6223. * filtered by the groups id.
  6224. * @param {DataSet | DataView} items
  6225. */
  6226. Group.prototype.setItems = function setItems(items) {
  6227. if (this.itemset) {
  6228. // remove current item set
  6229. this.itemset.hide();
  6230. this.itemset.setItems();
  6231. this.parent.controller.remove(this.itemset);
  6232. this.itemset = null;
  6233. }
  6234. if (items) {
  6235. var groupId = this.groupId;
  6236. var itemsetOptions = Object.create(this.options);
  6237. this.itemset = new ItemSet(this, null, itemsetOptions);
  6238. this.itemset.setRange(this.parent.range);
  6239. this.view = new DataView(items, {
  6240. filter: function (item) {
  6241. return item.group == groupId;
  6242. }
  6243. });
  6244. this.itemset.setItems(this.view);
  6245. this.parent.controller.add(this.itemset);
  6246. }
  6247. };
  6248. /**
  6249. * Set selected items by their id. Replaces the current selection.
  6250. * Unknown id's are silently ignored.
  6251. * @param {Array} [ids] An array with zero or more id's of the items to be
  6252. * selected. If ids is an empty array, all items will be
  6253. * unselected.
  6254. */
  6255. Group.prototype.setSelection = function setSelection(ids) {
  6256. if (this.itemset) this.itemset.setSelection(ids);
  6257. };
  6258. /**
  6259. * Get the selected items by their id
  6260. * @return {Array} ids The ids of the selected items
  6261. */
  6262. Group.prototype.getSelection = function getSelection() {
  6263. return this.itemset ? this.itemset.getSelection() : [];
  6264. };
  6265. /**
  6266. * Repaint the item
  6267. * @return {Boolean} changed
  6268. */
  6269. Group.prototype.repaint = function repaint() {
  6270. return false;
  6271. };
  6272. /**
  6273. * Reflow the item
  6274. * @return {Boolean} resized
  6275. */
  6276. Group.prototype.reflow = function reflow() {
  6277. var changed = 0,
  6278. update = util.updateProperty;
  6279. changed += update(this, 'top', this.itemset ? this.itemset.top : 0);
  6280. changed += update(this, 'height', this.itemset ? this.itemset.height : 0);
  6281. // TODO: reckon with the height of the group label
  6282. if (this.label) {
  6283. var inner = this.label.firstChild;
  6284. changed += update(this.props.label, 'width', inner.clientWidth);
  6285. changed += update(this.props.label, 'height', inner.clientHeight);
  6286. }
  6287. else {
  6288. changed += update(this.props.label, 'width', 0);
  6289. changed += update(this.props.label, 'height', 0);
  6290. }
  6291. return (changed > 0);
  6292. };
  6293. /**
  6294. * An GroupSet holds a set of groups
  6295. * @param {Component} parent
  6296. * @param {Component[]} [depends] Components on which this components depends
  6297. * (except for the parent)
  6298. * @param {Object} [options] See GroupSet.setOptions for the available
  6299. * options.
  6300. * @constructor GroupSet
  6301. * @extends Panel
  6302. */
  6303. function GroupSet(parent, depends, options) {
  6304. this.id = util.randomUUID();
  6305. this.parent = parent;
  6306. this.depends = depends;
  6307. this.options = options || {};
  6308. this.range = null; // Range or Object {start: number, end: number}
  6309. this.itemsData = null; // DataSet with items
  6310. this.groupsData = null; // DataSet with groups
  6311. this.groups = {}; // map with groups
  6312. this.dom = {};
  6313. this.props = {
  6314. labels: {
  6315. width: 0
  6316. }
  6317. };
  6318. // TODO: implement right orientation of the labels
  6319. // changes in groups are queued key/value map containing id/action
  6320. this.queue = {};
  6321. var me = this;
  6322. this.listeners = {
  6323. 'add': function (event, params) {
  6324. me._onAdd(params.items);
  6325. },
  6326. 'update': function (event, params) {
  6327. me._onUpdate(params.items);
  6328. },
  6329. 'remove': function (event, params) {
  6330. me._onRemove(params.items);
  6331. }
  6332. };
  6333. }
  6334. GroupSet.prototype = new Panel();
  6335. /**
  6336. * Set options for the GroupSet. Existing options will be extended/overwritten.
  6337. * @param {Object} [options] The following options are available:
  6338. * {String | function} groupsOrder
  6339. * TODO: describe options
  6340. */
  6341. GroupSet.prototype.setOptions = Component.prototype.setOptions;
  6342. GroupSet.prototype.setRange = function (range) {
  6343. // TODO: implement setRange
  6344. };
  6345. /**
  6346. * Set items
  6347. * @param {vis.DataSet | null} items
  6348. */
  6349. GroupSet.prototype.setItems = function setItems(items) {
  6350. this.itemsData = items;
  6351. for (var id in this.groups) {
  6352. if (this.groups.hasOwnProperty(id)) {
  6353. var group = this.groups[id];
  6354. group.setItems(items);
  6355. }
  6356. }
  6357. };
  6358. /**
  6359. * Get items
  6360. * @return {vis.DataSet | null} items
  6361. */
  6362. GroupSet.prototype.getItems = function getItems() {
  6363. return this.itemsData;
  6364. };
  6365. /**
  6366. * Set range (start and end).
  6367. * @param {Range | Object} range A Range or an object containing start and end.
  6368. */
  6369. GroupSet.prototype.setRange = function setRange(range) {
  6370. this.range = range;
  6371. };
  6372. /**
  6373. * Set groups
  6374. * @param {vis.DataSet} groups
  6375. */
  6376. GroupSet.prototype.setGroups = function setGroups(groups) {
  6377. var me = this,
  6378. ids;
  6379. // unsubscribe from current dataset
  6380. if (this.groupsData) {
  6381. util.forEach(this.listeners, function (callback, event) {
  6382. me.groupsData.unsubscribe(event, callback);
  6383. });
  6384. // remove all drawn groups
  6385. ids = this.groupsData.getIds();
  6386. this._onRemove(ids);
  6387. }
  6388. // replace the dataset
  6389. if (!groups) {
  6390. this.groupsData = null;
  6391. }
  6392. else if (groups instanceof DataSet) {
  6393. this.groupsData = groups;
  6394. }
  6395. else {
  6396. this.groupsData = new DataSet({
  6397. convert: {
  6398. start: 'Date',
  6399. end: 'Date'
  6400. }
  6401. });
  6402. this.groupsData.add(groups);
  6403. }
  6404. if (this.groupsData) {
  6405. // subscribe to new dataset
  6406. var id = this.id;
  6407. util.forEach(this.listeners, function (callback, event) {
  6408. me.groupsData.on(event, callback, id);
  6409. });
  6410. // draw all new groups
  6411. ids = this.groupsData.getIds();
  6412. this._onAdd(ids);
  6413. }
  6414. };
  6415. /**
  6416. * Get groups
  6417. * @return {vis.DataSet | null} groups
  6418. */
  6419. GroupSet.prototype.getGroups = function getGroups() {
  6420. return this.groupsData;
  6421. };
  6422. /**
  6423. * Set selected items by their id. Replaces the current selection.
  6424. * Unknown id's are silently ignored.
  6425. * @param {Array} [ids] An array with zero or more id's of the items to be
  6426. * selected. If ids is an empty array, all items will be
  6427. * unselected.
  6428. */
  6429. GroupSet.prototype.setSelection = function setSelection(ids) {
  6430. var selection = [],
  6431. groups = this.groups;
  6432. // iterate over each of the groups
  6433. for (var id in groups) {
  6434. if (groups.hasOwnProperty(id)) {
  6435. var group = groups[id];
  6436. group.setSelection(ids);
  6437. }
  6438. }
  6439. return selection;
  6440. };
  6441. /**
  6442. * Get the selected items by their id
  6443. * @return {Array} ids The ids of the selected items
  6444. */
  6445. GroupSet.prototype.getSelection = function getSelection() {
  6446. var selection = [],
  6447. groups = this.groups;
  6448. // iterate over each of the groups
  6449. for (var id in groups) {
  6450. if (groups.hasOwnProperty(id)) {
  6451. var group = groups[id];
  6452. selection = selection.concat(group.getSelection());
  6453. }
  6454. }
  6455. return selection;
  6456. };
  6457. /**
  6458. * Repaint the component
  6459. * @return {Boolean} changed
  6460. */
  6461. GroupSet.prototype.repaint = function repaint() {
  6462. var changed = 0,
  6463. i, id, group, label,
  6464. update = util.updateProperty,
  6465. asSize = util.option.asSize,
  6466. asElement = util.option.asElement,
  6467. options = this.options,
  6468. frame = this.dom.frame,
  6469. labels = this.dom.labels,
  6470. labelSet = this.dom.labelSet;
  6471. // create frame
  6472. if (!this.parent) {
  6473. throw new Error('Cannot repaint groupset: no parent attached');
  6474. }
  6475. var parentContainer = this.parent.getContainer();
  6476. if (!parentContainer) {
  6477. throw new Error('Cannot repaint groupset: parent has no container element');
  6478. }
  6479. if (!frame) {
  6480. frame = document.createElement('div');
  6481. frame.className = 'groupset';
  6482. frame['timeline-groupset'] = this;
  6483. this.dom.frame = frame;
  6484. var className = options.className;
  6485. if (className) {
  6486. util.addClassName(frame, util.option.asString(className));
  6487. }
  6488. changed += 1;
  6489. }
  6490. if (!frame.parentNode) {
  6491. parentContainer.appendChild(frame);
  6492. changed += 1;
  6493. }
  6494. // create labels
  6495. var labelContainer = asElement(options.labelContainer);
  6496. if (!labelContainer) {
  6497. throw new Error('Cannot repaint groupset: option "labelContainer" not defined');
  6498. }
  6499. if (!labels) {
  6500. labels = document.createElement('div');
  6501. labels.className = 'labels';
  6502. this.dom.labels = labels;
  6503. }
  6504. if (!labelSet) {
  6505. labelSet = document.createElement('div');
  6506. labelSet.className = 'label-set';
  6507. labels.appendChild(labelSet);
  6508. this.dom.labelSet = labelSet;
  6509. }
  6510. if (!labels.parentNode || labels.parentNode != labelContainer) {
  6511. if (labels.parentNode) {
  6512. labels.parentNode.removeChild(labels.parentNode);
  6513. }
  6514. labelContainer.appendChild(labels);
  6515. }
  6516. // reposition frame
  6517. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  6518. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  6519. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  6520. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  6521. // reposition labels
  6522. changed += update(labelSet.style, 'top', asSize(options.top, '0px'));
  6523. changed += update(labelSet.style, 'height', asSize(options.height, this.height + 'px'));
  6524. var me = this,
  6525. queue = this.queue,
  6526. groups = this.groups,
  6527. groupsData = this.groupsData;
  6528. // show/hide added/changed/removed groups
  6529. var ids = Object.keys(queue);
  6530. if (ids.length) {
  6531. ids.forEach(function (id) {
  6532. var action = queue[id];
  6533. var group = groups[id];
  6534. //noinspection FallthroughInSwitchStatementJS
  6535. switch (action) {
  6536. case 'add':
  6537. case 'update':
  6538. if (!group) {
  6539. var groupOptions = Object.create(me.options);
  6540. util.extend(groupOptions, {
  6541. height: null,
  6542. maxHeight: null
  6543. });
  6544. group = new Group(me, id, groupOptions);
  6545. group.setItems(me.itemsData); // attach items data
  6546. groups[id] = group;
  6547. me.controller.add(group);
  6548. }
  6549. // TODO: update group data
  6550. group.data = groupsData.get(id);
  6551. delete queue[id];
  6552. break;
  6553. case 'remove':
  6554. if (group) {
  6555. group.setItems(); // detach items data
  6556. delete groups[id];
  6557. me.controller.remove(group);
  6558. }
  6559. // update lists
  6560. delete queue[id];
  6561. break;
  6562. default:
  6563. console.log('Error: unknown action "' + action + '"');
  6564. }
  6565. });
  6566. // the groupset depends on each of the groups
  6567. //this.depends = this.groups; // TODO: gives a circular reference through the parent
  6568. // TODO: apply dependencies of the groupset
  6569. // update the top positions of the groups in the correct order
  6570. var orderedGroups = this.groupsData.getIds({
  6571. order: this.options.groupOrder
  6572. });
  6573. for (i = 0; i < orderedGroups.length; i++) {
  6574. (function (group, prevGroup) {
  6575. var top = 0;
  6576. if (prevGroup) {
  6577. top = function () {
  6578. // TODO: top must reckon with options.maxHeight
  6579. return prevGroup.top + prevGroup.height;
  6580. }
  6581. }
  6582. group.setOptions({
  6583. top: top
  6584. });
  6585. })(groups[orderedGroups[i]], groups[orderedGroups[i - 1]]);
  6586. }
  6587. // (re)create the labels
  6588. while (labelSet.firstChild) {
  6589. labelSet.removeChild(labelSet.firstChild);
  6590. }
  6591. for (i = 0; i < orderedGroups.length; i++) {
  6592. id = orderedGroups[i];
  6593. label = this._createLabel(id);
  6594. labelSet.appendChild(label);
  6595. }
  6596. changed++;
  6597. }
  6598. // reposition the labels
  6599. // TODO: labels are not displayed correctly when orientation=='top'
  6600. // TODO: width of labelPanel is not immediately updated on a change in groups
  6601. for (id in groups) {
  6602. if (groups.hasOwnProperty(id)) {
  6603. group = groups[id];
  6604. label = group.label;
  6605. if (label) {
  6606. label.style.top = group.top + 'px';
  6607. label.style.height = group.height + 'px';
  6608. }
  6609. }
  6610. }
  6611. return (changed > 0);
  6612. };
  6613. /**
  6614. * Create a label for group with given id
  6615. * @param {Number} id
  6616. * @return {Element} label
  6617. * @private
  6618. */
  6619. GroupSet.prototype._createLabel = function(id) {
  6620. var group = this.groups[id];
  6621. var label = document.createElement('div');
  6622. label.className = 'vlabel';
  6623. var inner = document.createElement('div');
  6624. inner.className = 'inner';
  6625. label.appendChild(inner);
  6626. var content = group.data && group.data.content;
  6627. if (content instanceof Element) {
  6628. inner.appendChild(content);
  6629. }
  6630. else if (content != undefined) {
  6631. inner.innerHTML = content;
  6632. }
  6633. var className = group.data && group.data.className;
  6634. if (className) {
  6635. util.addClassName(label, className);
  6636. }
  6637. group.label = label; // TODO: not so nice, parking labels in the group this way!!!
  6638. return label;
  6639. };
  6640. /**
  6641. * Get container element
  6642. * @return {HTMLElement} container
  6643. */
  6644. GroupSet.prototype.getContainer = function getContainer() {
  6645. return this.dom.frame;
  6646. };
  6647. /**
  6648. * Get the width of the group labels
  6649. * @return {Number} width
  6650. */
  6651. GroupSet.prototype.getLabelsWidth = function getContainer() {
  6652. return this.props.labels.width;
  6653. };
  6654. /**
  6655. * Reflow the component
  6656. * @return {Boolean} resized
  6657. */
  6658. GroupSet.prototype.reflow = function reflow() {
  6659. var changed = 0,
  6660. id, group,
  6661. options = this.options,
  6662. update = util.updateProperty,
  6663. asNumber = util.option.asNumber,
  6664. asSize = util.option.asSize,
  6665. frame = this.dom.frame;
  6666. if (frame) {
  6667. var maxHeight = asNumber(options.maxHeight);
  6668. var fixedHeight = (asSize(options.height) != null);
  6669. var height;
  6670. if (fixedHeight) {
  6671. height = frame.offsetHeight;
  6672. }
  6673. else {
  6674. // height is not specified, calculate the sum of the height of all groups
  6675. height = 0;
  6676. for (id in this.groups) {
  6677. if (this.groups.hasOwnProperty(id)) {
  6678. group = this.groups[id];
  6679. height += group.height;
  6680. }
  6681. }
  6682. }
  6683. if (maxHeight != null) {
  6684. height = Math.min(height, maxHeight);
  6685. }
  6686. changed += update(this, 'height', height);
  6687. changed += update(this, 'top', frame.offsetTop);
  6688. changed += update(this, 'left', frame.offsetLeft);
  6689. changed += update(this, 'width', frame.offsetWidth);
  6690. }
  6691. // calculate the maximum width of the labels
  6692. var width = 0;
  6693. for (id in this.groups) {
  6694. if (this.groups.hasOwnProperty(id)) {
  6695. group = this.groups[id];
  6696. var labelWidth = group.props && group.props.label && group.props.label.width || 0;
  6697. width = Math.max(width, labelWidth);
  6698. }
  6699. }
  6700. changed += update(this.props.labels, 'width', width);
  6701. return (changed > 0);
  6702. };
  6703. /**
  6704. * Hide the component from the DOM
  6705. * @return {Boolean} changed
  6706. */
  6707. GroupSet.prototype.hide = function hide() {
  6708. if (this.dom.frame && this.dom.frame.parentNode) {
  6709. this.dom.frame.parentNode.removeChild(this.dom.frame);
  6710. return true;
  6711. }
  6712. else {
  6713. return false;
  6714. }
  6715. };
  6716. /**
  6717. * Show the component in the DOM (when not already visible).
  6718. * A repaint will be executed when the component is not visible
  6719. * @return {Boolean} changed
  6720. */
  6721. GroupSet.prototype.show = function show() {
  6722. if (!this.dom.frame || !this.dom.frame.parentNode) {
  6723. return this.repaint();
  6724. }
  6725. else {
  6726. return false;
  6727. }
  6728. };
  6729. /**
  6730. * Handle updated groups
  6731. * @param {Number[]} ids
  6732. * @private
  6733. */
  6734. GroupSet.prototype._onUpdate = function _onUpdate(ids) {
  6735. this._toQueue(ids, 'update');
  6736. };
  6737. /**
  6738. * Handle changed groups
  6739. * @param {Number[]} ids
  6740. * @private
  6741. */
  6742. GroupSet.prototype._onAdd = function _onAdd(ids) {
  6743. this._toQueue(ids, 'add');
  6744. };
  6745. /**
  6746. * Handle removed groups
  6747. * @param {Number[]} ids
  6748. * @private
  6749. */
  6750. GroupSet.prototype._onRemove = function _onRemove(ids) {
  6751. this._toQueue(ids, 'remove');
  6752. };
  6753. /**
  6754. * Put groups in the queue to be added/updated/remove
  6755. * @param {Number[]} ids
  6756. * @param {String} action can be 'add', 'update', 'remove'
  6757. */
  6758. GroupSet.prototype._toQueue = function _toQueue(ids, action) {
  6759. var queue = this.queue;
  6760. ids.forEach(function (id) {
  6761. queue[id] = action;
  6762. });
  6763. if (this.controller) {
  6764. //this.requestReflow();
  6765. this.requestRepaint();
  6766. }
  6767. };
  6768. /**
  6769. * Find the Group from an event target:
  6770. * searches for the attribute 'timeline-groupset' in the event target's element
  6771. * tree, then finds the right group in this groupset
  6772. * @param {Event} event
  6773. * @return {Group | null} group
  6774. */
  6775. GroupSet.groupFromTarget = function groupFromTarget (event) {
  6776. var groupset,
  6777. target = event.target;
  6778. while (target) {
  6779. if (target.hasOwnProperty('timeline-groupset')) {
  6780. groupset = target['timeline-groupset'];
  6781. break;
  6782. }
  6783. target = target.parentNode;
  6784. }
  6785. if (groupset) {
  6786. for (var groupId in groupset.groups) {
  6787. if (groupset.groups.hasOwnProperty(groupId)) {
  6788. var group = groupset.groups[groupId];
  6789. if (group.itemset && ItemSet.itemSetFromTarget(event) == group.itemset) {
  6790. return group;
  6791. }
  6792. }
  6793. }
  6794. }
  6795. return null;
  6796. };
  6797. /**
  6798. * Create a timeline visualization
  6799. * @param {HTMLElement} container
  6800. * @param {vis.DataSet | Array | google.visualization.DataTable} [items]
  6801. * @param {Object} [options] See Timeline.setOptions for the available options.
  6802. * @constructor
  6803. */
  6804. function Timeline (container, items, options) {
  6805. var me = this;
  6806. var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0);
  6807. this.options = {
  6808. orientation: 'bottom',
  6809. autoResize: true,
  6810. editable: false,
  6811. selectable: true,
  6812. snap: null, // will be specified after timeaxis is created
  6813. min: null,
  6814. max: null,
  6815. zoomMin: 10, // milliseconds
  6816. zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000, // milliseconds
  6817. // moveable: true, // TODO: option moveable
  6818. // zoomable: true, // TODO: option zoomable
  6819. showMinorLabels: true,
  6820. showMajorLabels: true,
  6821. showCurrentTime: false,
  6822. showCustomTime: false,
  6823. onAdd: function (item, callback) {
  6824. callback(item);
  6825. },
  6826. onUpdate: function (item, callback) {
  6827. callback(item);
  6828. },
  6829. onMove: function (item, callback) {
  6830. callback(item);
  6831. },
  6832. onRemove: function (item, callback) {
  6833. callback(item);
  6834. }
  6835. };
  6836. // controller
  6837. this.controller = new Controller();
  6838. // root panel
  6839. if (!container) {
  6840. throw new Error('No container element provided');
  6841. }
  6842. var rootOptions = Object.create(this.options);
  6843. rootOptions.height = function () {
  6844. // TODO: change to height
  6845. if (me.options.height) {
  6846. // fixed height
  6847. return me.options.height;
  6848. }
  6849. else {
  6850. // auto height
  6851. return (me.timeaxis.height + me.content.height) + 'px';
  6852. }
  6853. };
  6854. this.rootPanel = new RootPanel(container, rootOptions);
  6855. this.controller.add(this.rootPanel);
  6856. // single select (or unselect) when tapping an item
  6857. this.controller.on('tap', this._onSelectItem.bind(this));
  6858. // multi select when holding mouse/touch, or on ctrl+click
  6859. this.controller.on('hold', this._onMultiSelectItem.bind(this));
  6860. // add item on doubletap
  6861. this.controller.on('doubletap', this._onAddItem.bind(this));
  6862. // item panel
  6863. var itemOptions = Object.create(this.options);
  6864. itemOptions.left = function () {
  6865. return me.labelPanel.width;
  6866. };
  6867. itemOptions.width = function () {
  6868. return me.rootPanel.width - me.labelPanel.width;
  6869. };
  6870. itemOptions.top = null;
  6871. itemOptions.height = null;
  6872. this.itemPanel = new Panel(this.rootPanel, [], itemOptions);
  6873. this.controller.add(this.itemPanel);
  6874. // label panel
  6875. var labelOptions = Object.create(this.options);
  6876. labelOptions.top = null;
  6877. labelOptions.left = null;
  6878. labelOptions.height = null;
  6879. labelOptions.width = function () {
  6880. if (me.content && typeof me.content.getLabelsWidth === 'function') {
  6881. return me.content.getLabelsWidth();
  6882. }
  6883. else {
  6884. return 0;
  6885. }
  6886. };
  6887. this.labelPanel = new Panel(this.rootPanel, [], labelOptions);
  6888. this.controller.add(this.labelPanel);
  6889. // range
  6890. var rangeOptions = Object.create(this.options);
  6891. this.range = new Range(rangeOptions);
  6892. this.range.setRange(
  6893. now.clone().add('days', -3).valueOf(),
  6894. now.clone().add('days', 4).valueOf()
  6895. );
  6896. this.range.subscribe(this.controller, this.rootPanel, 'move', 'horizontal');
  6897. this.range.subscribe(this.controller, this.rootPanel, 'zoom', 'horizontal');
  6898. this.range.on('rangechange', function (properties) {
  6899. var force = true;
  6900. me.controller.emit('rangechange', properties);
  6901. me.controller.emit('request-reflow', force);
  6902. });
  6903. this.range.on('rangechanged', function (properties) {
  6904. var force = true;
  6905. me.controller.emit('rangechanged', properties);
  6906. me.controller.emit('request-reflow', force);
  6907. });
  6908. // time axis
  6909. var timeaxisOptions = Object.create(rootOptions);
  6910. timeaxisOptions.range = this.range;
  6911. timeaxisOptions.left = null;
  6912. timeaxisOptions.top = null;
  6913. timeaxisOptions.width = '100%';
  6914. timeaxisOptions.height = null;
  6915. this.timeaxis = new TimeAxis(this.itemPanel, [], timeaxisOptions);
  6916. this.timeaxis.setRange(this.range);
  6917. this.controller.add(this.timeaxis);
  6918. this.options.snap = this.timeaxis.snap.bind(this.timeaxis);
  6919. // current time bar
  6920. this.currenttime = new CurrentTime(this.timeaxis, [], rootOptions);
  6921. this.controller.add(this.currenttime);
  6922. // custom time bar
  6923. this.customtime = new CustomTime(this.timeaxis, [], rootOptions);
  6924. this.controller.add(this.customtime);
  6925. // create groupset
  6926. this.setGroups(null);
  6927. this.itemsData = null; // DataSet
  6928. this.groupsData = null; // DataSet
  6929. // apply options
  6930. if (options) {
  6931. this.setOptions(options);
  6932. }
  6933. // create itemset and groupset
  6934. if (items) {
  6935. this.setItems(items);
  6936. }
  6937. }
  6938. /**
  6939. * Add an event listener to the timeline
  6940. * @param {String} event Available events: select, rangechange, rangechanged,
  6941. * timechange, timechanged
  6942. * @param {function} callback
  6943. */
  6944. Timeline.prototype.on = function on (event, callback) {
  6945. this.controller.on(event, callback);
  6946. };
  6947. /**
  6948. * Add an event listener from the timeline
  6949. * @param {String} event
  6950. * @param {function} callback
  6951. */
  6952. Timeline.prototype.off = function off (event, callback) {
  6953. this.controller.off(event, callback);
  6954. };
  6955. /**
  6956. * Set options
  6957. * @param {Object} options TODO: describe the available options
  6958. */
  6959. Timeline.prototype.setOptions = function (options) {
  6960. util.extend(this.options, options);
  6961. // force update of range (apply new min/max etc.)
  6962. // both start and end are optional
  6963. this.range.setRange(options.start, options.end);
  6964. if ('editable' in options || 'selectable' in options) {
  6965. if (this.options.selectable) {
  6966. // force update of selection
  6967. this.setSelection(this.getSelection());
  6968. }
  6969. else {
  6970. // remove selection
  6971. this.setSelection([]);
  6972. }
  6973. }
  6974. // validate the callback functions
  6975. var validateCallback = (function (fn) {
  6976. if (!(this.options[fn] instanceof Function) || this.options[fn].length != 2) {
  6977. throw new Error('option ' + fn + ' must be a function ' + fn + '(item, callback)');
  6978. }
  6979. }).bind(this);
  6980. ['onAdd', 'onUpdate', 'onRemove', 'onMove'].forEach(validateCallback);
  6981. this.controller.reflow();
  6982. this.controller.repaint();
  6983. };
  6984. /**
  6985. * Set a custom time bar
  6986. * @param {Date} time
  6987. */
  6988. Timeline.prototype.setCustomTime = function (time) {
  6989. if (!this.customtime) {
  6990. throw new Error('Cannot get custom time: Custom time bar is not enabled');
  6991. }
  6992. this.customtime.setCustomTime(time);
  6993. };
  6994. /**
  6995. * Retrieve the current custom time.
  6996. * @return {Date} customTime
  6997. */
  6998. Timeline.prototype.getCustomTime = function() {
  6999. if (!this.customtime) {
  7000. throw new Error('Cannot get custom time: Custom time bar is not enabled');
  7001. }
  7002. return this.customtime.getCustomTime();
  7003. };
  7004. /**
  7005. * Set items
  7006. * @param {vis.DataSet | Array | google.visualization.DataTable | null} items
  7007. */
  7008. Timeline.prototype.setItems = function(items) {
  7009. var initialLoad = (this.itemsData == null);
  7010. // convert to type DataSet when needed
  7011. var newDataSet;
  7012. if (!items) {
  7013. newDataSet = null;
  7014. }
  7015. else if (items instanceof DataSet) {
  7016. newDataSet = items;
  7017. }
  7018. if (!(items instanceof DataSet)) {
  7019. newDataSet = new DataSet({
  7020. convert: {
  7021. start: 'Date',
  7022. end: 'Date'
  7023. }
  7024. });
  7025. newDataSet.add(items);
  7026. }
  7027. // set items
  7028. this.itemsData = newDataSet;
  7029. this.content.setItems(newDataSet);
  7030. if (initialLoad && (this.options.start == undefined || this.options.end == undefined)) {
  7031. // apply the data range as range
  7032. var dataRange = this.getItemRange();
  7033. // add 5% space on both sides
  7034. var start = dataRange.min;
  7035. var end = dataRange.max;
  7036. if (start != null && end != null) {
  7037. var interval = (end.valueOf() - start.valueOf());
  7038. if (interval <= 0) {
  7039. // prevent an empty interval
  7040. interval = 24 * 60 * 60 * 1000; // 1 day
  7041. }
  7042. start = new Date(start.valueOf() - interval * 0.05);
  7043. end = new Date(end.valueOf() + interval * 0.05);
  7044. }
  7045. // override specified start and/or end date
  7046. if (this.options.start != undefined) {
  7047. start = util.convert(this.options.start, 'Date');
  7048. }
  7049. if (this.options.end != undefined) {
  7050. end = util.convert(this.options.end, 'Date');
  7051. }
  7052. // apply range if there is a min or max available
  7053. if (start != null || end != null) {
  7054. this.range.setRange(start, end);
  7055. }
  7056. }
  7057. };
  7058. /**
  7059. * Set groups
  7060. * @param {vis.DataSet | Array | google.visualization.DataTable} groups
  7061. */
  7062. Timeline.prototype.setGroups = function(groups) {
  7063. var me = this;
  7064. this.groupsData = groups;
  7065. // switch content type between ItemSet or GroupSet when needed
  7066. var Type = this.groupsData ? GroupSet : ItemSet;
  7067. if (!(this.content instanceof Type)) {
  7068. // remove old content set
  7069. if (this.content) {
  7070. this.content.hide();
  7071. if (this.content.setItems) {
  7072. this.content.setItems(); // disconnect from items
  7073. }
  7074. if (this.content.setGroups) {
  7075. this.content.setGroups(); // disconnect from groups
  7076. }
  7077. this.controller.remove(this.content);
  7078. }
  7079. // create new content set
  7080. var options = Object.create(this.options);
  7081. util.extend(options, {
  7082. top: function () {
  7083. if (me.options.orientation == 'top') {
  7084. return me.timeaxis.height;
  7085. }
  7086. else {
  7087. return me.itemPanel.height - me.timeaxis.height - me.content.height;
  7088. }
  7089. },
  7090. left: null,
  7091. width: '100%',
  7092. height: function () {
  7093. if (me.options.height) {
  7094. // fixed height
  7095. return me.itemPanel.height - me.timeaxis.height;
  7096. }
  7097. else {
  7098. // auto height
  7099. return null;
  7100. }
  7101. },
  7102. maxHeight: function () {
  7103. // TODO: change maxHeight to be a css string like '100%' or '300px'
  7104. if (me.options.maxHeight) {
  7105. if (!util.isNumber(me.options.maxHeight)) {
  7106. throw new TypeError('Number expected for property maxHeight');
  7107. }
  7108. return me.options.maxHeight - me.timeaxis.height;
  7109. }
  7110. else {
  7111. return null;
  7112. }
  7113. },
  7114. labelContainer: function () {
  7115. return me.labelPanel.getContainer();
  7116. }
  7117. });
  7118. this.content = new Type(this.itemPanel, [this.timeaxis], options);
  7119. if (this.content.setRange) {
  7120. this.content.setRange(this.range);
  7121. }
  7122. if (this.content.setItems) {
  7123. this.content.setItems(this.itemsData);
  7124. }
  7125. if (this.content.setGroups) {
  7126. this.content.setGroups(this.groupsData);
  7127. }
  7128. this.controller.add(this.content);
  7129. }
  7130. };
  7131. /**
  7132. * Get the data range of the item set.
  7133. * @returns {{min: Date, max: Date}} range A range with a start and end Date.
  7134. * When no minimum is found, min==null
  7135. * When no maximum is found, max==null
  7136. */
  7137. Timeline.prototype.getItemRange = function getItemRange() {
  7138. // calculate min from start filed
  7139. var itemsData = this.itemsData,
  7140. min = null,
  7141. max = null;
  7142. if (itemsData) {
  7143. // calculate the minimum value of the field 'start'
  7144. var minItem = itemsData.min('start');
  7145. min = minItem ? minItem.start.valueOf() : null;
  7146. // calculate maximum value of fields 'start' and 'end'
  7147. var maxStartItem = itemsData.max('start');
  7148. if (maxStartItem) {
  7149. max = maxStartItem.start.valueOf();
  7150. }
  7151. var maxEndItem = itemsData.max('end');
  7152. if (maxEndItem) {
  7153. if (max == null) {
  7154. max = maxEndItem.end.valueOf();
  7155. }
  7156. else {
  7157. max = Math.max(max, maxEndItem.end.valueOf());
  7158. }
  7159. }
  7160. }
  7161. return {
  7162. min: (min != null) ? new Date(min) : null,
  7163. max: (max != null) ? new Date(max) : null
  7164. };
  7165. };
  7166. /**
  7167. * Set selected items by their id. Replaces the current selection
  7168. * Unknown id's are silently ignored.
  7169. * @param {Array} [ids] An array with zero or more id's of the items to be
  7170. * selected. If ids is an empty array, all items will be
  7171. * unselected.
  7172. */
  7173. Timeline.prototype.setSelection = function setSelection (ids) {
  7174. if (this.content) this.content.setSelection(ids);
  7175. };
  7176. /**
  7177. * Get the selected items by their id
  7178. * @return {Array} ids The ids of the selected items
  7179. */
  7180. Timeline.prototype.getSelection = function getSelection() {
  7181. return this.content ? this.content.getSelection() : [];
  7182. };
  7183. /**
  7184. * Set the visible window. Both parameters are optional, you can change only
  7185. * start or only end.
  7186. * @param {Date | Number | String} [start] Start date of visible window
  7187. * @param {Date | Number | String} [end] End date of visible window
  7188. */
  7189. Timeline.prototype.setWindow = function setWindow(start, end) {
  7190. this.range.setRange(start, end);
  7191. };
  7192. /**
  7193. * Get the visible window
  7194. * @return {{start: Date, end: Date}} Visible range
  7195. */
  7196. Timeline.prototype.getWindow = function setWindow() {
  7197. var range = this.range.getRange();
  7198. return {
  7199. start: new Date(range.start),
  7200. end: new Date(range.end)
  7201. };
  7202. };
  7203. /**
  7204. * Handle selecting/deselecting an item when tapping it
  7205. * @param {Event} event
  7206. * @private
  7207. */
  7208. // TODO: move this function to ItemSet
  7209. Timeline.prototype._onSelectItem = function (event) {
  7210. if (!this.options.selectable) return;
  7211. var ctrlKey = event.gesture.srcEvent && event.gesture.srcEvent.ctrlKey;
  7212. var shiftKey = event.gesture.srcEvent && event.gesture.srcEvent.shiftKey;
  7213. if (ctrlKey || shiftKey) {
  7214. this._onMultiSelectItem(event);
  7215. return;
  7216. }
  7217. var item = ItemSet.itemFromTarget(event);
  7218. var selection = item ? [item.id] : [];
  7219. this.setSelection(selection);
  7220. this.controller.emit('select', {
  7221. items: this.getSelection()
  7222. });
  7223. event.stopPropagation();
  7224. };
  7225. /**
  7226. * Handle creation and updates of an item on double tap
  7227. * @param event
  7228. * @private
  7229. */
  7230. Timeline.prototype._onAddItem = function (event) {
  7231. if (!this.options.selectable) return;
  7232. if (!this.options.editable) return;
  7233. var me = this,
  7234. item = ItemSet.itemFromTarget(event);
  7235. if (item) {
  7236. // update item
  7237. // execute async handler to update the item (or cancel it)
  7238. var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset
  7239. this.options.onUpdate(itemData, function (itemData) {
  7240. if (itemData) {
  7241. me.itemsData.update(itemData);
  7242. }
  7243. });
  7244. }
  7245. else {
  7246. // add item
  7247. var xAbs = vis.util.getAbsoluteLeft(this.rootPanel.frame);
  7248. var x = event.gesture.center.pageX - xAbs;
  7249. var newItem = {
  7250. start: this.timeaxis.snap(this._toTime(x)),
  7251. content: 'new item'
  7252. };
  7253. var id = util.randomUUID();
  7254. newItem[this.itemsData.fieldId] = id;
  7255. var group = GroupSet.groupFromTarget(event);
  7256. if (group) {
  7257. newItem.group = group.groupId;
  7258. }
  7259. // execute async handler to customize (or cancel) adding an item
  7260. this.options.onAdd(newItem, function (item) {
  7261. if (item) {
  7262. me.itemsData.add(newItem);
  7263. // select the created item after it is repainted
  7264. me.controller.once('repaint', function () {
  7265. me.setSelection([id]);
  7266. me.controller.emit('select', {
  7267. items: me.getSelection()
  7268. });
  7269. }.bind(me));
  7270. }
  7271. });
  7272. }
  7273. };
  7274. /**
  7275. * Handle selecting/deselecting multiple items when holding an item
  7276. * @param {Event} event
  7277. * @private
  7278. */
  7279. // TODO: move this function to ItemSet
  7280. Timeline.prototype._onMultiSelectItem = function (event) {
  7281. if (!this.options.selectable) return;
  7282. var selection,
  7283. item = ItemSet.itemFromTarget(event);
  7284. if (item) {
  7285. // multi select items
  7286. selection = this.getSelection(); // current selection
  7287. var index = selection.indexOf(item.id);
  7288. if (index == -1) {
  7289. // item is not yet selected -> select it
  7290. selection.push(item.id);
  7291. }
  7292. else {
  7293. // item is already selected -> deselect it
  7294. selection.splice(index, 1);
  7295. }
  7296. this.setSelection(selection);
  7297. this.controller.emit('select', {
  7298. items: this.getSelection()
  7299. });
  7300. event.stopPropagation();
  7301. }
  7302. };
  7303. /**
  7304. * Convert a position on screen (pixels) to a datetime
  7305. * @param {int} x Position on the screen in pixels
  7306. * @return {Date} time The datetime the corresponds with given position x
  7307. * @private
  7308. */
  7309. Timeline.prototype._toTime = function _toTime(x) {
  7310. var conversion = this.range.conversion(this.content.width);
  7311. return new Date(x / conversion.scale + conversion.offset);
  7312. };
  7313. /**
  7314. * Convert a datetime (Date object) into a position on the screen
  7315. * @param {Date} time A date
  7316. * @return {int} x The position on the screen in pixels which corresponds
  7317. * with the given date.
  7318. * @private
  7319. */
  7320. Timeline.prototype._toScreen = function _toScreen(time) {
  7321. var conversion = this.range.conversion(this.content.width);
  7322. return (time.valueOf() - conversion.offset) * conversion.scale;
  7323. };
  7324. (function(exports) {
  7325. /**
  7326. * Parse a text source containing data in DOT language into a JSON object.
  7327. * The object contains two lists: one with nodes and one with edges.
  7328. *
  7329. * DOT language reference: http://www.graphviz.org/doc/info/lang.html
  7330. *
  7331. * @param {String} data Text containing a graph in DOT-notation
  7332. * @return {Object} graph An object containing two parameters:
  7333. * {Object[]} nodes
  7334. * {Object[]} edges
  7335. */
  7336. function parseDOT (data) {
  7337. dot = data;
  7338. return parseGraph();
  7339. }
  7340. // token types enumeration
  7341. var TOKENTYPE = {
  7342. NULL : 0,
  7343. DELIMITER : 1,
  7344. IDENTIFIER: 2,
  7345. UNKNOWN : 3
  7346. };
  7347. // map with all delimiters
  7348. var DELIMITERS = {
  7349. '{': true,
  7350. '}': true,
  7351. '[': true,
  7352. ']': true,
  7353. ';': true,
  7354. '=': true,
  7355. ',': true,
  7356. '->': true,
  7357. '--': true
  7358. };
  7359. var dot = ''; // current dot file
  7360. var index = 0; // current index in dot file
  7361. var c = ''; // current token character in expr
  7362. var token = ''; // current token
  7363. var tokenType = TOKENTYPE.NULL; // type of the token
  7364. /**
  7365. * Get the first character from the dot file.
  7366. * The character is stored into the char c. If the end of the dot file is
  7367. * reached, the function puts an empty string in c.
  7368. */
  7369. function first() {
  7370. index = 0;
  7371. c = dot.charAt(0);
  7372. }
  7373. /**
  7374. * Get the next character from the dot file.
  7375. * The character is stored into the char c. If the end of the dot file is
  7376. * reached, the function puts an empty string in c.
  7377. */
  7378. function next() {
  7379. index++;
  7380. c = dot.charAt(index);
  7381. }
  7382. /**
  7383. * Preview the next character from the dot file.
  7384. * @return {String} cNext
  7385. */
  7386. function nextPreview() {
  7387. return dot.charAt(index + 1);
  7388. }
  7389. /**
  7390. * Test whether given character is alphabetic or numeric
  7391. * @param {String} c
  7392. * @return {Boolean} isAlphaNumeric
  7393. */
  7394. var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/;
  7395. function isAlphaNumeric(c) {
  7396. return regexAlphaNumeric.test(c);
  7397. }
  7398. /**
  7399. * Merge all properties of object b into object b
  7400. * @param {Object} a
  7401. * @param {Object} b
  7402. * @return {Object} a
  7403. */
  7404. function merge (a, b) {
  7405. if (!a) {
  7406. a = {};
  7407. }
  7408. if (b) {
  7409. for (var name in b) {
  7410. if (b.hasOwnProperty(name)) {
  7411. a[name] = b[name];
  7412. }
  7413. }
  7414. }
  7415. return a;
  7416. }
  7417. /**
  7418. * Set a value in an object, where the provided parameter name can be a
  7419. * path with nested parameters. For example:
  7420. *
  7421. * var obj = {a: 2};
  7422. * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}}
  7423. *
  7424. * @param {Object} obj
  7425. * @param {String} path A parameter name or dot-separated parameter path,
  7426. * like "color.highlight.border".
  7427. * @param {*} value
  7428. */
  7429. function setValue(obj, path, value) {
  7430. var keys = path.split('.');
  7431. var o = obj;
  7432. while (keys.length) {
  7433. var key = keys.shift();
  7434. if (keys.length) {
  7435. // this isn't the end point
  7436. if (!o[key]) {
  7437. o[key] = {};
  7438. }
  7439. o = o[key];
  7440. }
  7441. else {
  7442. // this is the end point
  7443. o[key] = value;
  7444. }
  7445. }
  7446. }
  7447. /**
  7448. * Add a node to a graph object. If there is already a node with
  7449. * the same id, their attributes will be merged.
  7450. * @param {Object} graph
  7451. * @param {Object} node
  7452. */
  7453. function addNode(graph, node) {
  7454. var i, len;
  7455. var current = null;
  7456. // find root graph (in case of subgraph)
  7457. var graphs = [graph]; // list with all graphs from current graph to root graph
  7458. var root = graph;
  7459. while (root.parent) {
  7460. graphs.push(root.parent);
  7461. root = root.parent;
  7462. }
  7463. // find existing node (at root level) by its id
  7464. if (root.nodes) {
  7465. for (i = 0, len = root.nodes.length; i < len; i++) {
  7466. if (node.id === root.nodes[i].id) {
  7467. current = root.nodes[i];
  7468. break;
  7469. }
  7470. }
  7471. }
  7472. if (!current) {
  7473. // this is a new node
  7474. current = {
  7475. id: node.id
  7476. };
  7477. if (graph.node) {
  7478. // clone default attributes
  7479. current.attr = merge(current.attr, graph.node);
  7480. }
  7481. }
  7482. // add node to this (sub)graph and all its parent graphs
  7483. for (i = graphs.length - 1; i >= 0; i--) {
  7484. var g = graphs[i];
  7485. if (!g.nodes) {
  7486. g.nodes = [];
  7487. }
  7488. if (g.nodes.indexOf(current) == -1) {
  7489. g.nodes.push(current);
  7490. }
  7491. }
  7492. // merge attributes
  7493. if (node.attr) {
  7494. current.attr = merge(current.attr, node.attr);
  7495. }
  7496. }
  7497. /**
  7498. * Add an edge to a graph object
  7499. * @param {Object} graph
  7500. * @param {Object} edge
  7501. */
  7502. function addEdge(graph, edge) {
  7503. if (!graph.edges) {
  7504. graph.edges = [];
  7505. }
  7506. graph.edges.push(edge);
  7507. if (graph.edge) {
  7508. var attr = merge({}, graph.edge); // clone default attributes
  7509. edge.attr = merge(attr, edge.attr); // merge attributes
  7510. }
  7511. }
  7512. /**
  7513. * Create an edge to a graph object
  7514. * @param {Object} graph
  7515. * @param {String | Number | Object} from
  7516. * @param {String | Number | Object} to
  7517. * @param {String} type
  7518. * @param {Object | null} attr
  7519. * @return {Object} edge
  7520. */
  7521. function createEdge(graph, from, to, type, attr) {
  7522. var edge = {
  7523. from: from,
  7524. to: to,
  7525. type: type
  7526. };
  7527. if (graph.edge) {
  7528. edge.attr = merge({}, graph.edge); // clone default attributes
  7529. }
  7530. edge.attr = merge(edge.attr || {}, attr); // merge attributes
  7531. return edge;
  7532. }
  7533. /**
  7534. * Get next token in the current dot file.
  7535. * The token and token type are available as token and tokenType
  7536. */
  7537. function getToken() {
  7538. tokenType = TOKENTYPE.NULL;
  7539. token = '';
  7540. // skip over whitespaces
  7541. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  7542. next();
  7543. }
  7544. do {
  7545. var isComment = false;
  7546. // skip comment
  7547. if (c == '#') {
  7548. // find the previous non-space character
  7549. var i = index - 1;
  7550. while (dot.charAt(i) == ' ' || dot.charAt(i) == '\t') {
  7551. i--;
  7552. }
  7553. if (dot.charAt(i) == '\n' || dot.charAt(i) == '') {
  7554. // the # is at the start of a line, this is indeed a line comment
  7555. while (c != '' && c != '\n') {
  7556. next();
  7557. }
  7558. isComment = true;
  7559. }
  7560. }
  7561. if (c == '/' && nextPreview() == '/') {
  7562. // skip line comment
  7563. while (c != '' && c != '\n') {
  7564. next();
  7565. }
  7566. isComment = true;
  7567. }
  7568. if (c == '/' && nextPreview() == '*') {
  7569. // skip block comment
  7570. while (c != '') {
  7571. if (c == '*' && nextPreview() == '/') {
  7572. // end of block comment found. skip these last two characters
  7573. next();
  7574. next();
  7575. break;
  7576. }
  7577. else {
  7578. next();
  7579. }
  7580. }
  7581. isComment = true;
  7582. }
  7583. // skip over whitespaces
  7584. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  7585. next();
  7586. }
  7587. }
  7588. while (isComment);
  7589. // check for end of dot file
  7590. if (c == '') {
  7591. // token is still empty
  7592. tokenType = TOKENTYPE.DELIMITER;
  7593. return;
  7594. }
  7595. // check for delimiters consisting of 2 characters
  7596. var c2 = c + nextPreview();
  7597. if (DELIMITERS[c2]) {
  7598. tokenType = TOKENTYPE.DELIMITER;
  7599. token = c2;
  7600. next();
  7601. next();
  7602. return;
  7603. }
  7604. // check for delimiters consisting of 1 character
  7605. if (DELIMITERS[c]) {
  7606. tokenType = TOKENTYPE.DELIMITER;
  7607. token = c;
  7608. next();
  7609. return;
  7610. }
  7611. // check for an identifier (number or string)
  7612. // TODO: more precise parsing of numbers/strings (and the port separator ':')
  7613. if (isAlphaNumeric(c) || c == '-') {
  7614. token += c;
  7615. next();
  7616. while (isAlphaNumeric(c)) {
  7617. token += c;
  7618. next();
  7619. }
  7620. if (token == 'false') {
  7621. token = false; // convert to boolean
  7622. }
  7623. else if (token == 'true') {
  7624. token = true; // convert to boolean
  7625. }
  7626. else if (!isNaN(Number(token))) {
  7627. token = Number(token); // convert to number
  7628. }
  7629. tokenType = TOKENTYPE.IDENTIFIER;
  7630. return;
  7631. }
  7632. // check for a string enclosed by double quotes
  7633. if (c == '"') {
  7634. next();
  7635. while (c != '' && (c != '"' || (c == '"' && nextPreview() == '"'))) {
  7636. token += c;
  7637. if (c == '"') { // skip the escape character
  7638. next();
  7639. }
  7640. next();
  7641. }
  7642. if (c != '"') {
  7643. throw newSyntaxError('End of string " expected');
  7644. }
  7645. next();
  7646. tokenType = TOKENTYPE.IDENTIFIER;
  7647. return;
  7648. }
  7649. // something unknown is found, wrong characters, a syntax error
  7650. tokenType = TOKENTYPE.UNKNOWN;
  7651. while (c != '') {
  7652. token += c;
  7653. next();
  7654. }
  7655. throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"');
  7656. }
  7657. /**
  7658. * Parse a graph.
  7659. * @returns {Object} graph
  7660. */
  7661. function parseGraph() {
  7662. var graph = {};
  7663. first();
  7664. getToken();
  7665. // optional strict keyword
  7666. if (token == 'strict') {
  7667. graph.strict = true;
  7668. getToken();
  7669. }
  7670. // graph or digraph keyword
  7671. if (token == 'graph' || token == 'digraph') {
  7672. graph.type = token;
  7673. getToken();
  7674. }
  7675. // optional graph id
  7676. if (tokenType == TOKENTYPE.IDENTIFIER) {
  7677. graph.id = token;
  7678. getToken();
  7679. }
  7680. // open angle bracket
  7681. if (token != '{') {
  7682. throw newSyntaxError('Angle bracket { expected');
  7683. }
  7684. getToken();
  7685. // statements
  7686. parseStatements(graph);
  7687. // close angle bracket
  7688. if (token != '}') {
  7689. throw newSyntaxError('Angle bracket } expected');
  7690. }
  7691. getToken();
  7692. // end of file
  7693. if (token !== '') {
  7694. throw newSyntaxError('End of file expected');
  7695. }
  7696. getToken();
  7697. // remove temporary default properties
  7698. delete graph.node;
  7699. delete graph.edge;
  7700. delete graph.graph;
  7701. return graph;
  7702. }
  7703. /**
  7704. * Parse a list with statements.
  7705. * @param {Object} graph
  7706. */
  7707. function parseStatements (graph) {
  7708. while (token !== '' && token != '}') {
  7709. parseStatement(graph);
  7710. if (token == ';') {
  7711. getToken();
  7712. }
  7713. }
  7714. }
  7715. /**
  7716. * Parse a single statement. Can be a an attribute statement, node
  7717. * statement, a series of node statements and edge statements, or a
  7718. * parameter.
  7719. * @param {Object} graph
  7720. */
  7721. function parseStatement(graph) {
  7722. // parse subgraph
  7723. var subgraph = parseSubgraph(graph);
  7724. if (subgraph) {
  7725. // edge statements
  7726. parseEdge(graph, subgraph);
  7727. return;
  7728. }
  7729. // parse an attribute statement
  7730. var attr = parseAttributeStatement(graph);
  7731. if (attr) {
  7732. return;
  7733. }
  7734. // parse node
  7735. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7736. throw newSyntaxError('Identifier expected');
  7737. }
  7738. var id = token; // id can be a string or a number
  7739. getToken();
  7740. if (token == '=') {
  7741. // id statement
  7742. getToken();
  7743. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7744. throw newSyntaxError('Identifier expected');
  7745. }
  7746. graph[id] = token;
  7747. getToken();
  7748. // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] "
  7749. }
  7750. else {
  7751. parseNodeStatement(graph, id);
  7752. }
  7753. }
  7754. /**
  7755. * Parse a subgraph
  7756. * @param {Object} graph parent graph object
  7757. * @return {Object | null} subgraph
  7758. */
  7759. function parseSubgraph (graph) {
  7760. var subgraph = null;
  7761. // optional subgraph keyword
  7762. if (token == 'subgraph') {
  7763. subgraph = {};
  7764. subgraph.type = 'subgraph';
  7765. getToken();
  7766. // optional graph id
  7767. if (tokenType == TOKENTYPE.IDENTIFIER) {
  7768. subgraph.id = token;
  7769. getToken();
  7770. }
  7771. }
  7772. // open angle bracket
  7773. if (token == '{') {
  7774. getToken();
  7775. if (!subgraph) {
  7776. subgraph = {};
  7777. }
  7778. subgraph.parent = graph;
  7779. subgraph.node = graph.node;
  7780. subgraph.edge = graph.edge;
  7781. subgraph.graph = graph.graph;
  7782. // statements
  7783. parseStatements(subgraph);
  7784. // close angle bracket
  7785. if (token != '}') {
  7786. throw newSyntaxError('Angle bracket } expected');
  7787. }
  7788. getToken();
  7789. // remove temporary default properties
  7790. delete subgraph.node;
  7791. delete subgraph.edge;
  7792. delete subgraph.graph;
  7793. delete subgraph.parent;
  7794. // register at the parent graph
  7795. if (!graph.subgraphs) {
  7796. graph.subgraphs = [];
  7797. }
  7798. graph.subgraphs.push(subgraph);
  7799. }
  7800. return subgraph;
  7801. }
  7802. /**
  7803. * parse an attribute statement like "node [shape=circle fontSize=16]".
  7804. * Available keywords are 'node', 'edge', 'graph'.
  7805. * The previous list with default attributes will be replaced
  7806. * @param {Object} graph
  7807. * @returns {String | null} keyword Returns the name of the parsed attribute
  7808. * (node, edge, graph), or null if nothing
  7809. * is parsed.
  7810. */
  7811. function parseAttributeStatement (graph) {
  7812. // attribute statements
  7813. if (token == 'node') {
  7814. getToken();
  7815. // node attributes
  7816. graph.node = parseAttributeList();
  7817. return 'node';
  7818. }
  7819. else if (token == 'edge') {
  7820. getToken();
  7821. // edge attributes
  7822. graph.edge = parseAttributeList();
  7823. return 'edge';
  7824. }
  7825. else if (token == 'graph') {
  7826. getToken();
  7827. // graph attributes
  7828. graph.graph = parseAttributeList();
  7829. return 'graph';
  7830. }
  7831. return null;
  7832. }
  7833. /**
  7834. * parse a node statement
  7835. * @param {Object} graph
  7836. * @param {String | Number} id
  7837. */
  7838. function parseNodeStatement(graph, id) {
  7839. // node statement
  7840. var node = {
  7841. id: id
  7842. };
  7843. var attr = parseAttributeList();
  7844. if (attr) {
  7845. node.attr = attr;
  7846. }
  7847. addNode(graph, node);
  7848. // edge statements
  7849. parseEdge(graph, id);
  7850. }
  7851. /**
  7852. * Parse an edge or a series of edges
  7853. * @param {Object} graph
  7854. * @param {String | Number} from Id of the from node
  7855. */
  7856. function parseEdge(graph, from) {
  7857. while (token == '->' || token == '--') {
  7858. var to;
  7859. var type = token;
  7860. getToken();
  7861. var subgraph = parseSubgraph(graph);
  7862. if (subgraph) {
  7863. to = subgraph;
  7864. }
  7865. else {
  7866. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7867. throw newSyntaxError('Identifier or subgraph expected');
  7868. }
  7869. to = token;
  7870. addNode(graph, {
  7871. id: to
  7872. });
  7873. getToken();
  7874. }
  7875. // parse edge attributes
  7876. var attr = parseAttributeList();
  7877. // create edge
  7878. var edge = createEdge(graph, from, to, type, attr);
  7879. addEdge(graph, edge);
  7880. from = to;
  7881. }
  7882. }
  7883. /**
  7884. * Parse a set with attributes,
  7885. * for example [label="1.000", shape=solid]
  7886. * @return {Object | null} attr
  7887. */
  7888. function parseAttributeList() {
  7889. var attr = null;
  7890. while (token == '[') {
  7891. getToken();
  7892. attr = {};
  7893. while (token !== '' && token != ']') {
  7894. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7895. throw newSyntaxError('Attribute name expected');
  7896. }
  7897. var name = token;
  7898. getToken();
  7899. if (token != '=') {
  7900. throw newSyntaxError('Equal sign = expected');
  7901. }
  7902. getToken();
  7903. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7904. throw newSyntaxError('Attribute value expected');
  7905. }
  7906. var value = token;
  7907. setValue(attr, name, value); // name can be a path
  7908. getToken();
  7909. if (token ==',') {
  7910. getToken();
  7911. }
  7912. }
  7913. if (token != ']') {
  7914. throw newSyntaxError('Bracket ] expected');
  7915. }
  7916. getToken();
  7917. }
  7918. return attr;
  7919. }
  7920. /**
  7921. * Create a syntax error with extra information on current token and index.
  7922. * @param {String} message
  7923. * @returns {SyntaxError} err
  7924. */
  7925. function newSyntaxError(message) {
  7926. return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')');
  7927. }
  7928. /**
  7929. * Chop off text after a maximum length
  7930. * @param {String} text
  7931. * @param {Number} maxLength
  7932. * @returns {String}
  7933. */
  7934. function chop (text, maxLength) {
  7935. return (text.length <= maxLength) ? text : (text.substr(0, 27) + '...');
  7936. }
  7937. /**
  7938. * Execute a function fn for each pair of elements in two arrays
  7939. * @param {Array | *} array1
  7940. * @param {Array | *} array2
  7941. * @param {function} fn
  7942. */
  7943. function forEach2(array1, array2, fn) {
  7944. if (array1 instanceof Array) {
  7945. array1.forEach(function (elem1) {
  7946. if (array2 instanceof Array) {
  7947. array2.forEach(function (elem2) {
  7948. fn(elem1, elem2);
  7949. });
  7950. }
  7951. else {
  7952. fn(elem1, array2);
  7953. }
  7954. });
  7955. }
  7956. else {
  7957. if (array2 instanceof Array) {
  7958. array2.forEach(function (elem2) {
  7959. fn(array1, elem2);
  7960. });
  7961. }
  7962. else {
  7963. fn(array1, array2);
  7964. }
  7965. }
  7966. }
  7967. /**
  7968. * Convert a string containing a graph in DOT language into a map containing
  7969. * with nodes and edges in the format of graph.
  7970. * @param {String} data Text containing a graph in DOT-notation
  7971. * @return {Object} graphData
  7972. */
  7973. function DOTToGraph (data) {
  7974. // parse the DOT file
  7975. var dotData = parseDOT(data);
  7976. var graphData = {
  7977. nodes: [],
  7978. edges: [],
  7979. options: {}
  7980. };
  7981. // copy the nodes
  7982. if (dotData.nodes) {
  7983. dotData.nodes.forEach(function (dotNode) {
  7984. var graphNode = {
  7985. id: dotNode.id,
  7986. label: String(dotNode.label || dotNode.id)
  7987. };
  7988. merge(graphNode, dotNode.attr);
  7989. if (graphNode.image) {
  7990. graphNode.shape = 'image';
  7991. }
  7992. graphData.nodes.push(graphNode);
  7993. });
  7994. }
  7995. // copy the edges
  7996. if (dotData.edges) {
  7997. /**
  7998. * Convert an edge in DOT format to an edge with VisGraph format
  7999. * @param {Object} dotEdge
  8000. * @returns {Object} graphEdge
  8001. */
  8002. function convertEdge(dotEdge) {
  8003. var graphEdge = {
  8004. from: dotEdge.from,
  8005. to: dotEdge.to
  8006. };
  8007. merge(graphEdge, dotEdge.attr);
  8008. graphEdge.style = (dotEdge.type == '->') ? 'arrow' : 'line';
  8009. return graphEdge;
  8010. }
  8011. dotData.edges.forEach(function (dotEdge) {
  8012. var from, to;
  8013. if (dotEdge.from instanceof Object) {
  8014. from = dotEdge.from.nodes;
  8015. }
  8016. else {
  8017. from = {
  8018. id: dotEdge.from
  8019. }
  8020. }
  8021. if (dotEdge.to instanceof Object) {
  8022. to = dotEdge.to.nodes;
  8023. }
  8024. else {
  8025. to = {
  8026. id: dotEdge.to
  8027. }
  8028. }
  8029. if (dotEdge.from instanceof Object && dotEdge.from.edges) {
  8030. dotEdge.from.edges.forEach(function (subEdge) {
  8031. var graphEdge = convertEdge(subEdge);
  8032. graphData.edges.push(graphEdge);
  8033. });
  8034. }
  8035. forEach2(from, to, function (from, to) {
  8036. var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr);
  8037. var graphEdge = convertEdge(subEdge);
  8038. graphData.edges.push(graphEdge);
  8039. });
  8040. if (dotEdge.to instanceof Object && dotEdge.to.edges) {
  8041. dotEdge.to.edges.forEach(function (subEdge) {
  8042. var graphEdge = convertEdge(subEdge);
  8043. graphData.edges.push(graphEdge);
  8044. });
  8045. }
  8046. });
  8047. }
  8048. // copy the options
  8049. if (dotData.attr) {
  8050. graphData.options = dotData.attr;
  8051. }
  8052. return graphData;
  8053. }
  8054. // exports
  8055. exports.parseDOT = parseDOT;
  8056. exports.DOTToGraph = DOTToGraph;
  8057. })(typeof util !== 'undefined' ? util : exports);
  8058. /**
  8059. * Canvas shapes used by the Graph
  8060. */
  8061. if (typeof CanvasRenderingContext2D !== 'undefined') {
  8062. /**
  8063. * Draw a circle shape
  8064. */
  8065. CanvasRenderingContext2D.prototype.circle = function(x, y, r) {
  8066. this.beginPath();
  8067. this.arc(x, y, r, 0, 2*Math.PI, false);
  8068. };
  8069. /**
  8070. * Draw a square shape
  8071. * @param {Number} x horizontal center
  8072. * @param {Number} y vertical center
  8073. * @param {Number} r size, width and height of the square
  8074. */
  8075. CanvasRenderingContext2D.prototype.square = function(x, y, r) {
  8076. this.beginPath();
  8077. this.rect(x - r, y - r, r * 2, r * 2);
  8078. };
  8079. /**
  8080. * Draw a triangle shape
  8081. * @param {Number} x horizontal center
  8082. * @param {Number} y vertical center
  8083. * @param {Number} r radius, half the length of the sides of the triangle
  8084. */
  8085. CanvasRenderingContext2D.prototype.triangle = function(x, y, r) {
  8086. // http://en.wikipedia.org/wiki/Equilateral_triangle
  8087. this.beginPath();
  8088. var s = r * 2;
  8089. var s2 = s / 2;
  8090. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  8091. var h = Math.sqrt(s * s - s2 * s2); // height
  8092. this.moveTo(x, y - (h - ir));
  8093. this.lineTo(x + s2, y + ir);
  8094. this.lineTo(x - s2, y + ir);
  8095. this.lineTo(x, y - (h - ir));
  8096. this.closePath();
  8097. };
  8098. /**
  8099. * Draw a triangle shape in downward orientation
  8100. * @param {Number} x horizontal center
  8101. * @param {Number} y vertical center
  8102. * @param {Number} r radius
  8103. */
  8104. CanvasRenderingContext2D.prototype.triangleDown = function(x, y, r) {
  8105. // http://en.wikipedia.org/wiki/Equilateral_triangle
  8106. this.beginPath();
  8107. var s = r * 2;
  8108. var s2 = s / 2;
  8109. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  8110. var h = Math.sqrt(s * s - s2 * s2); // height
  8111. this.moveTo(x, y + (h - ir));
  8112. this.lineTo(x + s2, y - ir);
  8113. this.lineTo(x - s2, y - ir);
  8114. this.lineTo(x, y + (h - ir));
  8115. this.closePath();
  8116. };
  8117. /**
  8118. * Draw a star shape, a star with 5 points
  8119. * @param {Number} x horizontal center
  8120. * @param {Number} y vertical center
  8121. * @param {Number} r radius, half the length of the sides of the triangle
  8122. */
  8123. CanvasRenderingContext2D.prototype.star = function(x, y, r) {
  8124. // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/
  8125. this.beginPath();
  8126. for (var n = 0; n < 10; n++) {
  8127. var radius = (n % 2 === 0) ? r * 1.3 : r * 0.5;
  8128. this.lineTo(
  8129. x + radius * Math.sin(n * 2 * Math.PI / 10),
  8130. y - radius * Math.cos(n * 2 * Math.PI / 10)
  8131. );
  8132. }
  8133. this.closePath();
  8134. };
  8135. /**
  8136. * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas
  8137. */
  8138. CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) {
  8139. var r2d = Math.PI/180;
  8140. if( w - ( 2 * r ) < 0 ) { r = ( w / 2 ); } //ensure that the radius isn't too large for x
  8141. if( h - ( 2 * r ) < 0 ) { r = ( h / 2 ); } //ensure that the radius isn't too large for y
  8142. this.beginPath();
  8143. this.moveTo(x+r,y);
  8144. this.lineTo(x+w-r,y);
  8145. this.arc(x+w-r,y+r,r,r2d*270,r2d*360,false);
  8146. this.lineTo(x+w,y+h-r);
  8147. this.arc(x+w-r,y+h-r,r,0,r2d*90,false);
  8148. this.lineTo(x+r,y+h);
  8149. this.arc(x+r,y+h-r,r,r2d*90,r2d*180,false);
  8150. this.lineTo(x,y+r);
  8151. this.arc(x+r,y+r,r,r2d*180,r2d*270,false);
  8152. };
  8153. /**
  8154. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  8155. */
  8156. CanvasRenderingContext2D.prototype.ellipse = function(x, y, w, h) {
  8157. var kappa = .5522848,
  8158. ox = (w / 2) * kappa, // control point offset horizontal
  8159. oy = (h / 2) * kappa, // control point offset vertical
  8160. xe = x + w, // x-end
  8161. ye = y + h, // y-end
  8162. xm = x + w / 2, // x-middle
  8163. ym = y + h / 2; // y-middle
  8164. this.beginPath();
  8165. this.moveTo(x, ym);
  8166. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  8167. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  8168. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  8169. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  8170. };
  8171. /**
  8172. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  8173. */
  8174. CanvasRenderingContext2D.prototype.database = function(x, y, w, h) {
  8175. var f = 1/3;
  8176. var wEllipse = w;
  8177. var hEllipse = h * f;
  8178. var kappa = .5522848,
  8179. ox = (wEllipse / 2) * kappa, // control point offset horizontal
  8180. oy = (hEllipse / 2) * kappa, // control point offset vertical
  8181. xe = x + wEllipse, // x-end
  8182. ye = y + hEllipse, // y-end
  8183. xm = x + wEllipse / 2, // x-middle
  8184. ym = y + hEllipse / 2, // y-middle
  8185. ymb = y + (h - hEllipse/2), // y-midlle, bottom ellipse
  8186. yeb = y + h; // y-end, bottom ellipse
  8187. this.beginPath();
  8188. this.moveTo(xe, ym);
  8189. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  8190. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  8191. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  8192. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  8193. this.lineTo(xe, ymb);
  8194. this.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb);
  8195. this.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb);
  8196. this.lineTo(x, ym);
  8197. };
  8198. /**
  8199. * Draw an arrow point (no line)
  8200. */
  8201. CanvasRenderingContext2D.prototype.arrow = function(x, y, angle, length) {
  8202. // tail
  8203. var xt = x - length * Math.cos(angle);
  8204. var yt = y - length * Math.sin(angle);
  8205. // inner tail
  8206. // TODO: allow to customize different shapes
  8207. var xi = x - length * 0.9 * Math.cos(angle);
  8208. var yi = y - length * 0.9 * Math.sin(angle);
  8209. // left
  8210. var xl = xt + length / 3 * Math.cos(angle + 0.5 * Math.PI);
  8211. var yl = yt + length / 3 * Math.sin(angle + 0.5 * Math.PI);
  8212. // right
  8213. var xr = xt + length / 3 * Math.cos(angle - 0.5 * Math.PI);
  8214. var yr = yt + length / 3 * Math.sin(angle - 0.5 * Math.PI);
  8215. this.beginPath();
  8216. this.moveTo(x, y);
  8217. this.lineTo(xl, yl);
  8218. this.lineTo(xi, yi);
  8219. this.lineTo(xr, yr);
  8220. this.closePath();
  8221. };
  8222. /**
  8223. * Sets up the dashedLine functionality for drawing
  8224. * Original code came from http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
  8225. * @author David Jordan
  8226. * @date 2012-08-08
  8227. */
  8228. CanvasRenderingContext2D.prototype.dashedLine = function(x,y,x2,y2,dashArray){
  8229. if (!dashArray) dashArray=[10,5];
  8230. if (dashLength==0) dashLength = 0.001; // Hack for Safari
  8231. var dashCount = dashArray.length;
  8232. this.moveTo(x, y);
  8233. var dx = (x2-x), dy = (y2-y);
  8234. var slope = dy/dx;
  8235. var distRemaining = Math.sqrt( dx*dx + dy*dy );
  8236. var dashIndex=0, draw=true;
  8237. while (distRemaining>=0.1){
  8238. var dashLength = dashArray[dashIndex++%dashCount];
  8239. if (dashLength > distRemaining) dashLength = distRemaining;
  8240. var xStep = Math.sqrt( dashLength*dashLength / (1 + slope*slope) );
  8241. if (dx<0) xStep = -xStep;
  8242. x += xStep;
  8243. y += slope*xStep;
  8244. this[draw ? 'lineTo' : 'moveTo'](x,y);
  8245. distRemaining -= dashLength;
  8246. draw = !draw;
  8247. }
  8248. };
  8249. // TODO: add diamond shape
  8250. }
  8251. /**
  8252. * @class Node
  8253. * A node. A node can be connected to other nodes via one or multiple edges.
  8254. * @param {object} properties An object containing properties for the node. All
  8255. * properties are optional, except for the id.
  8256. * {number} id Id of the node. Required
  8257. * {string} label Text label for the node
  8258. * {number} x Horizontal position of the node
  8259. * {number} y Vertical position of the node
  8260. * {string} shape Node shape, available:
  8261. * "database", "circle", "ellipse",
  8262. * "box", "image", "text", "dot",
  8263. * "star", "triangle", "triangleDown",
  8264. * "square"
  8265. * {string} image An image url
  8266. * {string} title An title text, can be HTML
  8267. * {anytype} group A group name or number
  8268. * @param {Graph.Images} imagelist A list with images. Only needed
  8269. * when the node has an image
  8270. * @param {Graph.Groups} grouplist A list with groups. Needed for
  8271. * retrieving group properties
  8272. * @param {Object} constants An object with default values for
  8273. * example for the color
  8274. *
  8275. */
  8276. function Node(properties, imagelist, grouplist, constants) {
  8277. this.selected = false;
  8278. this.edges = []; // all edges connected to this node
  8279. this.dynamicEdges = [];
  8280. this.reroutedEdges = {};
  8281. this.group = constants.nodes.group;
  8282. this.fontSize = constants.nodes.fontSize;
  8283. this.fontFace = constants.nodes.fontFace;
  8284. this.fontColor = constants.nodes.fontColor;
  8285. this.fontDrawThreshold = 3;
  8286. this.color = constants.nodes.color;
  8287. // set defaults for the properties
  8288. this.id = undefined;
  8289. this.shape = constants.nodes.shape;
  8290. this.image = constants.nodes.image;
  8291. this.x = 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.allowedToMoveX);
  8422. this.yFixed = this.yFixed || (properties.y !== undefined && !properties.allowedToMoveY);
  8423. this.radiusFixed = this.radiusFixed || (properties.radius !== undefined);
  8424. if (this.shape == 'image') {
  8425. this.radiusMin = constants.nodes.widthMin;
  8426. this.radiusMax = constants.nodes.widthMax;
  8427. }
  8428. // choose draw method depending on the shape
  8429. switch (this.shape) {
  8430. case 'database': this.draw = this._drawDatabase; this.resize = this._resizeDatabase; break;
  8431. case 'box': this.draw = this._drawBox; this.resize = this._resizeBox; break;
  8432. case 'circle': this.draw = this._drawCircle; this.resize = this._resizeCircle; break;
  8433. case 'ellipse': this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  8434. // TODO: add diamond shape
  8435. case 'image': this.draw = this._drawImage; this.resize = this._resizeImage; break;
  8436. case 'text': this.draw = this._drawText; this.resize = this._resizeText; break;
  8437. case 'dot': this.draw = this._drawDot; this.resize = this._resizeShape; break;
  8438. case 'square': this.draw = this._drawSquare; this.resize = this._resizeShape; break;
  8439. case 'triangle': this.draw = this._drawTriangle; this.resize = this._resizeShape; break;
  8440. case 'triangleDown': this.draw = this._drawTriangleDown; this.resize = this._resizeShape; break;
  8441. case 'star': this.draw = this._drawStar; this.resize = this._resizeShape; break;
  8442. default: this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  8443. }
  8444. // reset the size of the node, this can be changed
  8445. this._reset();
  8446. };
  8447. /**
  8448. * Parse a color property into an object with border, background, and
  8449. * hightlight colors
  8450. * @param {Object | String} color
  8451. * @return {Object} colorObject
  8452. */
  8453. Node.parseColor = function(color) {
  8454. var c;
  8455. if (util.isString(color)) {
  8456. if (util.isValidHex(color)) {
  8457. var hsv = util.hexToHSV(color);
  8458. var lighterColorHSV = {h:hsv.h,s:hsv.s * 0.45,v:Math.min(1,hsv.v * 1.05)};
  8459. var darkerColorHSV = {h:hsv.h,s:Math.min(1,hsv.v * 1.25),v:hsv.v*0.6};
  8460. var darkerColorHex = util.HSVToHex(darkerColorHSV.h ,darkerColorHSV.h ,darkerColorHSV.v);
  8461. var lighterColorHex = util.HSVToHex(lighterColorHSV.h,lighterColorHSV.s,lighterColorHSV.v);
  8462. c = {
  8463. background: color,
  8464. border:darkerColorHex,
  8465. highlight: {
  8466. background:lighterColorHex,
  8467. border:darkerColorHex
  8468. }
  8469. };
  8470. }
  8471. else {
  8472. c = {
  8473. background:color,
  8474. border:color,
  8475. highlight: {
  8476. background:color,
  8477. border:color
  8478. }
  8479. };
  8480. }
  8481. }
  8482. else {
  8483. c = {};
  8484. c.background = color.background || 'white';
  8485. c.border = color.border || c.background;
  8486. if (util.isString(color.highlight)) {
  8487. c.highlight = {
  8488. border: color.highlight,
  8489. background: color.highlight
  8490. }
  8491. }
  8492. else {
  8493. c.highlight = {};
  8494. c.highlight.background = color.highlight && color.highlight.background || c.background;
  8495. c.highlight.border = color.highlight && color.highlight.border || c.border;
  8496. }
  8497. }
  8498. return c;
  8499. };
  8500. /**
  8501. * select this node
  8502. */
  8503. Node.prototype.select = function() {
  8504. this.selected = true;
  8505. this._reset();
  8506. };
  8507. /**
  8508. * unselect this node
  8509. */
  8510. Node.prototype.unselect = function() {
  8511. this.selected = false;
  8512. this._reset();
  8513. };
  8514. /**
  8515. * Reset the calculated size of the node, forces it to recalculate its size
  8516. */
  8517. Node.prototype.clearSizeCache = function() {
  8518. this._reset();
  8519. };
  8520. /**
  8521. * Reset the calculated size of the node, forces it to recalculate its size
  8522. * @private
  8523. */
  8524. Node.prototype._reset = function() {
  8525. this.width = undefined;
  8526. this.height = undefined;
  8527. };
  8528. /**
  8529. * get the title of this node.
  8530. * @return {string} title The title of the node, or undefined when no title
  8531. * has been set.
  8532. */
  8533. Node.prototype.getTitle = function() {
  8534. return this.title;
  8535. };
  8536. /**
  8537. * Calculate the distance to the border of the Node
  8538. * @param {CanvasRenderingContext2D} ctx
  8539. * @param {Number} angle Angle in radians
  8540. * @returns {number} distance Distance to the border in pixels
  8541. */
  8542. Node.prototype.distanceToBorder = function (ctx, angle) {
  8543. var borderWidth = 1;
  8544. if (!this.width) {
  8545. this.resize(ctx);
  8546. }
  8547. switch (this.shape) {
  8548. case 'circle':
  8549. case 'dot':
  8550. return this.radius + borderWidth;
  8551. case 'ellipse':
  8552. var a = this.width / 2;
  8553. var b = this.height / 2;
  8554. var w = (Math.sin(angle) * a);
  8555. var h = (Math.cos(angle) * b);
  8556. return a * b / Math.sqrt(w * w + h * h);
  8557. // TODO: implement distanceToBorder for database
  8558. // TODO: implement distanceToBorder for triangle
  8559. // TODO: implement distanceToBorder for triangleDown
  8560. case 'box':
  8561. case 'image':
  8562. case 'text':
  8563. default:
  8564. if (this.width) {
  8565. return Math.min(
  8566. Math.abs(this.width / 2 / Math.cos(angle)),
  8567. Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth;
  8568. // TODO: reckon with border radius too in case of box
  8569. }
  8570. else {
  8571. return 0;
  8572. }
  8573. }
  8574. // TODO: implement calculation of distance to border for all shapes
  8575. };
  8576. /**
  8577. * Set forces acting on the node
  8578. * @param {number} fx Force in horizontal direction
  8579. * @param {number} fy Force in vertical direction
  8580. */
  8581. Node.prototype._setForce = function(fx, fy) {
  8582. this.fx = fx;
  8583. this.fy = fy;
  8584. };
  8585. /**
  8586. * Add forces acting on the node
  8587. * @param {number} fx Force in horizontal direction
  8588. * @param {number} fy Force in vertical direction
  8589. * @private
  8590. */
  8591. Node.prototype._addForce = function(fx, fy) {
  8592. this.fx += fx;
  8593. this.fy += fy;
  8594. };
  8595. /**
  8596. * Perform one discrete step for the node
  8597. * @param {number} interval Time interval in seconds
  8598. */
  8599. Node.prototype.discreteStep = function(interval) {
  8600. if (!this.xFixed) {
  8601. var dx = this.damping * this.vx; // damping force
  8602. var ax = (this.fx - dx) / this.mass; // acceleration
  8603. this.vx += ax * interval; // velocity
  8604. this.x += this.vx * interval; // position
  8605. }
  8606. if (!this.yFixed) {
  8607. var dy = this.damping * this.vy; // damping force
  8608. var ay = (this.fy - dy) / this.mass; // acceleration
  8609. this.vy += ay * interval; // velocity
  8610. this.y += this.vy * interval; // position
  8611. }
  8612. };
  8613. /**
  8614. * Perform one discrete step for the node
  8615. * @param {number} interval Time interval in seconds
  8616. */
  8617. Node.prototype.discreteStepLimited = function(interval, maxVelocity) {
  8618. if (!this.xFixed) {
  8619. var dx = this.damping * this.vx; // damping force
  8620. var ax = (this.fx - dx) / this.mass; // acceleration
  8621. this.vx += ax * interval; // velocity
  8622. this.vx = (Math.abs(this.vx) > maxVelocity) ? ((this.vx > 0) ? maxVelocity : -maxVelocity) : this.vx;
  8623. this.x += this.vx * interval; // position
  8624. }
  8625. if (!this.yFixed) {
  8626. var dy = this.damping * this.vy; // damping force
  8627. var ay = (this.fy - dy) / this.mass; // acceleration
  8628. this.vy += ay * interval; // velocity
  8629. this.vy = (Math.abs(this.vy) > maxVelocity) ? ((this.vy > 0) ? maxVelocity : -maxVelocity) : this.vy;
  8630. this.y += this.vy * interval; // position
  8631. }
  8632. };
  8633. /**
  8634. * Check if this node has a fixed x and y position
  8635. * @return {boolean} true if fixed, false if not
  8636. */
  8637. Node.prototype.isFixed = function() {
  8638. return (this.xFixed && this.yFixed);
  8639. };
  8640. /**
  8641. * Check if this node is moving
  8642. * @param {number} vmin the minimum velocity considered as "moving"
  8643. * @return {boolean} true if moving, false if it has no velocity
  8644. */
  8645. // TODO: replace this method with calculating the kinetic energy
  8646. Node.prototype.isMoving = function(vmin) {
  8647. return (Math.abs(this.vx) > vmin || Math.abs(this.vy) > vmin);
  8648. };
  8649. /**
  8650. * check if this node is selecte
  8651. * @return {boolean} selected True if node is selected, else false
  8652. */
  8653. Node.prototype.isSelected = function() {
  8654. return this.selected;
  8655. };
  8656. /**
  8657. * Retrieve the value of the node. Can be undefined
  8658. * @return {Number} value
  8659. */
  8660. Node.prototype.getValue = function() {
  8661. return this.value;
  8662. };
  8663. /**
  8664. * Calculate the distance from the nodes location to the given location (x,y)
  8665. * @param {Number} x
  8666. * @param {Number} y
  8667. * @return {Number} value
  8668. */
  8669. Node.prototype.getDistance = function(x, y) {
  8670. var dx = this.x - x,
  8671. dy = this.y - y;
  8672. return Math.sqrt(dx * dx + dy * dy);
  8673. };
  8674. /**
  8675. * Adjust the value range of the node. The node will adjust it's radius
  8676. * based on its value.
  8677. * @param {Number} min
  8678. * @param {Number} max
  8679. */
  8680. Node.prototype.setValueRange = function(min, max) {
  8681. if (!this.radiusFixed && this.value !== undefined) {
  8682. if (max == min) {
  8683. this.radius = (this.radiusMin + this.radiusMax) / 2;
  8684. }
  8685. else {
  8686. var scale = (this.radiusMax - this.radiusMin) / (max - min);
  8687. this.radius = (this.value - min) * scale + this.radiusMin;
  8688. }
  8689. }
  8690. this.baseRadiusValue = this.radius;
  8691. };
  8692. /**
  8693. * Draw this node in the given canvas
  8694. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8695. * @param {CanvasRenderingContext2D} ctx
  8696. */
  8697. Node.prototype.draw = function(ctx) {
  8698. throw "Draw method not initialized for node";
  8699. };
  8700. /**
  8701. * Recalculate the size of this node in the given canvas
  8702. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8703. * @param {CanvasRenderingContext2D} ctx
  8704. */
  8705. Node.prototype.resize = function(ctx) {
  8706. throw "Resize method not initialized for node";
  8707. };
  8708. /**
  8709. * Check if this object is overlapping with the provided object
  8710. * @param {Object} obj an object with parameters left, top, right, bottom
  8711. * @return {boolean} True if location is located on node
  8712. */
  8713. Node.prototype.isOverlappingWith = function(obj) {
  8714. return (this.left < obj.right &&
  8715. this.left + this.width > obj.left &&
  8716. this.top < obj.bottom &&
  8717. this.top + this.height > obj.top);
  8718. };
  8719. Node.prototype._resizeImage = function (ctx) {
  8720. // TODO: pre calculate the image size
  8721. if (!this.width || !this.height) { // undefined or 0
  8722. var width, height;
  8723. if (this.value) {
  8724. this.radius = this.baseRadiusValue;
  8725. var scale = this.imageObj.height / this.imageObj.width;
  8726. if (scale !== undefined) {
  8727. width = this.radius || this.imageObj.width;
  8728. height = this.radius * scale || this.imageObj.height;
  8729. }
  8730. else {
  8731. width = 0;
  8732. height = 0;
  8733. }
  8734. }
  8735. else {
  8736. width = this.imageObj.width;
  8737. height = this.imageObj.height;
  8738. }
  8739. this.width = width;
  8740. this.height = height;
  8741. this.growthIndicator = 0;
  8742. if (this.width > 0 && this.height > 0) {
  8743. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8744. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8745. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8746. this.growthIndicator = this.width - width;
  8747. }
  8748. }
  8749. };
  8750. Node.prototype._drawImage = function (ctx) {
  8751. this._resizeImage(ctx);
  8752. this.left = this.x - this.width / 2;
  8753. this.top = this.y - this.height / 2;
  8754. var yLabel;
  8755. if (this.imageObj.width != 0 ) {
  8756. // draw the shade
  8757. if (this.clusterSize > 1) {
  8758. var lineWidth = ((this.clusterSize > 1) ? 10 : 0.0);
  8759. lineWidth *= this.graphScaleInv;
  8760. lineWidth = Math.min(0.2 * this.width,lineWidth);
  8761. ctx.globalAlpha = 0.5;
  8762. ctx.drawImage(this.imageObj, this.left - lineWidth, this.top - lineWidth, this.width + 2*lineWidth, this.height + 2*lineWidth);
  8763. }
  8764. // draw the image
  8765. ctx.globalAlpha = 1.0;
  8766. ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height);
  8767. yLabel = this.y + this.height / 2;
  8768. }
  8769. else {
  8770. // image still loading... just draw the label for now
  8771. yLabel = this.y;
  8772. }
  8773. this._label(ctx, this.label, this.x, yLabel, undefined, "top");
  8774. };
  8775. Node.prototype._resizeBox = function (ctx) {
  8776. if (!this.width) {
  8777. var margin = 5;
  8778. var textSize = this.getTextSize(ctx);
  8779. this.width = textSize.width + 2 * margin;
  8780. this.height = textSize.height + 2 * margin;
  8781. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  8782. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  8783. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  8784. // this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8785. }
  8786. };
  8787. Node.prototype._drawBox = function (ctx) {
  8788. this._resizeBox(ctx);
  8789. this.left = this.x - this.width / 2;
  8790. this.top = this.y - this.height / 2;
  8791. var clusterLineWidth = 2.5;
  8792. var selectionLineWidth = 2;
  8793. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8794. // draw the outer border
  8795. if (this.clusterSize > 1) {
  8796. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8797. ctx.lineWidth *= this.graphScaleInv;
  8798. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8799. ctx.roundRect(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth, this.radius);
  8800. ctx.stroke();
  8801. }
  8802. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8803. ctx.lineWidth *= this.graphScaleInv;
  8804. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8805. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8806. ctx.roundRect(this.left, this.top, this.width, this.height, this.radius);
  8807. ctx.fill();
  8808. ctx.stroke();
  8809. this._label(ctx, this.label, this.x, this.y);
  8810. };
  8811. Node.prototype._resizeDatabase = function (ctx) {
  8812. if (!this.width) {
  8813. var margin = 5;
  8814. var textSize = this.getTextSize(ctx);
  8815. var size = textSize.width + 2 * margin;
  8816. this.width = size;
  8817. this.height = size;
  8818. // scaling used for clustering
  8819. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8820. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8821. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8822. this.growthIndicator = this.width - size;
  8823. }
  8824. };
  8825. Node.prototype._drawDatabase = function (ctx) {
  8826. this._resizeDatabase(ctx);
  8827. this.left = this.x - this.width / 2;
  8828. this.top = this.y - this.height / 2;
  8829. var clusterLineWidth = 2.5;
  8830. var selectionLineWidth = 2;
  8831. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8832. // draw the outer border
  8833. if (this.clusterSize > 1) {
  8834. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8835. ctx.lineWidth *= this.graphScaleInv;
  8836. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8837. ctx.database(this.x - this.width/2 - 2*ctx.lineWidth, this.y - this.height*0.5 - 2*ctx.lineWidth, this.width + 4*ctx.lineWidth, this.height + 4*ctx.lineWidth);
  8838. ctx.stroke();
  8839. }
  8840. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8841. ctx.lineWidth *= this.graphScaleInv;
  8842. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8843. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8844. ctx.database(this.x - this.width/2, this.y - this.height*0.5, this.width, this.height);
  8845. ctx.fill();
  8846. ctx.stroke();
  8847. this._label(ctx, this.label, this.x, this.y);
  8848. };
  8849. Node.prototype._resizeCircle = function (ctx) {
  8850. if (!this.width) {
  8851. var margin = 5;
  8852. var textSize = this.getTextSize(ctx);
  8853. var diameter = Math.max(textSize.width, textSize.height) + 2 * margin;
  8854. this.radius = diameter / 2;
  8855. this.width = diameter;
  8856. this.height = diameter;
  8857. // scaling used for clustering
  8858. // this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  8859. // this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  8860. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8861. this.growthIndicator = this.radius - 0.5*diameter;
  8862. }
  8863. };
  8864. Node.prototype._drawCircle = function (ctx) {
  8865. this._resizeCircle(ctx);
  8866. this.left = this.x - this.width / 2;
  8867. this.top = this.y - this.height / 2;
  8868. var clusterLineWidth = 2.5;
  8869. var selectionLineWidth = 2;
  8870. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8871. // draw the outer border
  8872. if (this.clusterSize > 1) {
  8873. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8874. ctx.lineWidth *= this.graphScaleInv;
  8875. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8876. ctx.circle(this.x, this.y, this.radius+2*ctx.lineWidth);
  8877. ctx.stroke();
  8878. }
  8879. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8880. ctx.lineWidth *= this.graphScaleInv;
  8881. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8882. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8883. ctx.circle(this.x, this.y, this.radius);
  8884. ctx.fill();
  8885. ctx.stroke();
  8886. this._label(ctx, this.label, this.x, this.y);
  8887. };
  8888. Node.prototype._resizeEllipse = function (ctx) {
  8889. if (!this.width) {
  8890. var textSize = this.getTextSize(ctx);
  8891. this.width = textSize.width * 1.5;
  8892. this.height = textSize.height * 2;
  8893. if (this.width < this.height) {
  8894. this.width = this.height;
  8895. }
  8896. var defaultSize = this.width;
  8897. // scaling used for clustering
  8898. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8899. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8900. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8901. this.growthIndicator = this.width - defaultSize;
  8902. }
  8903. };
  8904. Node.prototype._drawEllipse = function (ctx) {
  8905. this._resizeEllipse(ctx);
  8906. this.left = this.x - this.width / 2;
  8907. this.top = this.y - this.height / 2;
  8908. var clusterLineWidth = 2.5;
  8909. var selectionLineWidth = 2;
  8910. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8911. // draw the outer border
  8912. if (this.clusterSize > 1) {
  8913. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8914. ctx.lineWidth *= this.graphScaleInv;
  8915. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8916. ctx.ellipse(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth);
  8917. ctx.stroke();
  8918. }
  8919. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8920. ctx.lineWidth *= this.graphScaleInv;
  8921. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8922. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8923. ctx.ellipse(this.left, this.top, this.width, this.height);
  8924. ctx.fill();
  8925. ctx.stroke();
  8926. this._label(ctx, this.label, this.x, this.y);
  8927. };
  8928. Node.prototype._drawDot = function (ctx) {
  8929. this._drawShape(ctx, 'circle');
  8930. };
  8931. Node.prototype._drawTriangle = function (ctx) {
  8932. this._drawShape(ctx, 'triangle');
  8933. };
  8934. Node.prototype._drawTriangleDown = function (ctx) {
  8935. this._drawShape(ctx, 'triangleDown');
  8936. };
  8937. Node.prototype._drawSquare = function (ctx) {
  8938. this._drawShape(ctx, 'square');
  8939. };
  8940. Node.prototype._drawStar = function (ctx) {
  8941. this._drawShape(ctx, 'star');
  8942. };
  8943. Node.prototype._resizeShape = function (ctx) {
  8944. if (!this.width) {
  8945. this.radius = this.baseRadiusValue;
  8946. var size = 2 * this.radius;
  8947. this.width = size;
  8948. this.height = size;
  8949. // scaling used for clustering
  8950. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8951. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8952. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8953. this.growthIndicator = this.width - size;
  8954. }
  8955. };
  8956. Node.prototype._drawShape = function (ctx, shape) {
  8957. this._resizeShape(ctx);
  8958. this.left = this.x - this.width / 2;
  8959. this.top = this.y - this.height / 2;
  8960. var clusterLineWidth = 2.5;
  8961. var selectionLineWidth = 2;
  8962. var radiusMultiplier = 2;
  8963. // choose draw method depending on the shape
  8964. switch (shape) {
  8965. case 'dot': radiusMultiplier = 2; break;
  8966. case 'square': radiusMultiplier = 2; break;
  8967. case 'triangle': radiusMultiplier = 3; break;
  8968. case 'triangleDown': radiusMultiplier = 3; break;
  8969. case 'star': radiusMultiplier = 4; break;
  8970. }
  8971. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8972. // draw the outer border
  8973. if (this.clusterSize > 1) {
  8974. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8975. ctx.lineWidth *= this.graphScaleInv;
  8976. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8977. ctx[shape](this.x, this.y, this.radius + radiusMultiplier * ctx.lineWidth);
  8978. ctx.stroke();
  8979. }
  8980. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8981. ctx.lineWidth *= this.graphScaleInv;
  8982. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8983. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8984. ctx[shape](this.x, this.y, this.radius);
  8985. ctx.fill();
  8986. ctx.stroke();
  8987. if (this.label) {
  8988. this._label(ctx, this.label, this.x, this.y + this.height / 2, undefined, 'top');
  8989. }
  8990. };
  8991. Node.prototype._resizeText = function (ctx) {
  8992. if (!this.width) {
  8993. var margin = 5;
  8994. var textSize = this.getTextSize(ctx);
  8995. this.width = textSize.width + 2 * margin;
  8996. this.height = textSize.height + 2 * margin;
  8997. // scaling used for clustering
  8998. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8999. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  9000. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  9001. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  9002. }
  9003. };
  9004. Node.prototype._drawText = function (ctx) {
  9005. this._resizeText(ctx);
  9006. this.left = this.x - this.width / 2;
  9007. this.top = this.y - this.height / 2;
  9008. this._label(ctx, this.label, this.x, this.y);
  9009. };
  9010. Node.prototype._label = function (ctx, text, x, y, align, baseline) {
  9011. if (text && this.fontSize * this.graphScale > this.fontDrawThreshold) {
  9012. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  9013. ctx.fillStyle = this.fontColor || "black";
  9014. ctx.textAlign = align || "center";
  9015. ctx.textBaseline = baseline || "middle";
  9016. var lines = text.split('\n'),
  9017. lineCount = lines.length,
  9018. fontSize = (this.fontSize + 4),
  9019. yLine = y + (1 - lineCount) / 2 * fontSize;
  9020. for (var i = 0; i < lineCount; i++) {
  9021. ctx.fillText(lines[i], x, yLine);
  9022. yLine += fontSize;
  9023. }
  9024. }
  9025. };
  9026. Node.prototype.getTextSize = function(ctx) {
  9027. if (this.label !== undefined) {
  9028. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  9029. var lines = this.label.split('\n'),
  9030. height = (this.fontSize + 4) * lines.length,
  9031. width = 0;
  9032. for (var i = 0, iMax = lines.length; i < iMax; i++) {
  9033. width = Math.max(width, ctx.measureText(lines[i]).width);
  9034. }
  9035. return {"width": width, "height": height};
  9036. }
  9037. else {
  9038. return {"width": 0, "height": 0};
  9039. }
  9040. };
  9041. /**
  9042. * this is used to determine if a node is visible at all. this is used to determine when it needs to be drawn.
  9043. * there is a safety margin of 0.3 * width;
  9044. *
  9045. * @returns {boolean}
  9046. */
  9047. Node.prototype.inArea = function() {
  9048. if (this.width !== undefined) {
  9049. return (this.x + this.width*this.graphScaleInv >= this.canvasTopLeft.x &&
  9050. this.x - this.width*this.graphScaleInv < this.canvasBottomRight.x &&
  9051. this.y + this.height*this.graphScaleInv >= this.canvasTopLeft.y &&
  9052. this.y - this.height*this.graphScaleInv < this.canvasBottomRight.y);
  9053. }
  9054. else {
  9055. return true;
  9056. }
  9057. };
  9058. /**
  9059. * checks if the core of the node is in the display area, this is used for opening clusters around zoom
  9060. * @returns {boolean}
  9061. */
  9062. Node.prototype.inView = function() {
  9063. return (this.x >= this.canvasTopLeft.x &&
  9064. this.x < this.canvasBottomRight.x &&
  9065. this.y >= this.canvasTopLeft.y &&
  9066. this.y < this.canvasBottomRight.y);
  9067. };
  9068. /**
  9069. * This allows the zoom level of the graph to influence the rendering
  9070. * We store the inverted scale and the coordinates of the top left, and bottom right points of the canvas
  9071. *
  9072. * @param scale
  9073. * @param canvasTopLeft
  9074. * @param canvasBottomRight
  9075. */
  9076. Node.prototype.setScaleAndPos = function(scale,canvasTopLeft,canvasBottomRight) {
  9077. this.graphScaleInv = 1.0/scale;
  9078. this.graphScale = scale;
  9079. this.canvasTopLeft = canvasTopLeft;
  9080. this.canvasBottomRight = canvasBottomRight;
  9081. };
  9082. /**
  9083. * This allows the zoom level of the graph to influence the rendering
  9084. *
  9085. * @param scale
  9086. */
  9087. Node.prototype.setScale = function(scale) {
  9088. this.graphScaleInv = 1.0/scale;
  9089. this.graphScale = scale;
  9090. };
  9091. /**
  9092. * set the velocity at 0. Is called when this node is contained in another during clustering
  9093. */
  9094. Node.prototype.clearVelocity = function() {
  9095. this.vx = 0;
  9096. this.vy = 0;
  9097. };
  9098. /**
  9099. * Basic preservation of (kinectic) energy
  9100. *
  9101. * @param massBeforeClustering
  9102. */
  9103. Node.prototype.updateVelocity = function(massBeforeClustering) {
  9104. var energyBefore = this.vx * this.vx * massBeforeClustering;
  9105. //this.vx = (this.vx < 0) ? -Math.sqrt(energyBefore/this.mass) : Math.sqrt(energyBefore/this.mass);
  9106. this.vx = Math.sqrt(energyBefore/this.mass);
  9107. energyBefore = this.vy * this.vy * massBeforeClustering;
  9108. //this.vy = (this.vy < 0) ? -Math.sqrt(energyBefore/this.mass) : Math.sqrt(energyBefore/this.mass);
  9109. this.vy = Math.sqrt(energyBefore/this.mass);
  9110. };
  9111. /**
  9112. * @class Edge
  9113. *
  9114. * A edge connects two nodes
  9115. * @param {Object} properties Object with properties. Must contain
  9116. * At least properties from and to.
  9117. * Available properties: from (number),
  9118. * to (number), label (string, color (string),
  9119. * width (number), style (string),
  9120. * length (number), title (string)
  9121. * @param {Graph} graph A graph object, used to find and edge to
  9122. * nodes.
  9123. * @param {Object} constants An object with default values for
  9124. * example for the color
  9125. */
  9126. function Edge (properties, graph, constants) {
  9127. if (!graph) {
  9128. throw "No graph provided";
  9129. }
  9130. this.graph = graph;
  9131. // initialize constants
  9132. this.widthMin = constants.edges.widthMin;
  9133. this.widthMax = constants.edges.widthMax;
  9134. // initialize variables
  9135. this.id = undefined;
  9136. this.fromId = undefined;
  9137. this.toId = undefined;
  9138. this.style = constants.edges.style;
  9139. this.title = undefined;
  9140. this.width = constants.edges.width;
  9141. this.value = undefined;
  9142. this.length = constants.physics.springLength;
  9143. this.customLength = false;
  9144. this.selected = false;
  9145. this.smooth = constants.smoothCurves;
  9146. this.from = null; // a node
  9147. this.to = null; // a node
  9148. this.via = null; // a temp node
  9149. // we use this to be able to reconnect the edge to a cluster if its node is put into a cluster
  9150. // by storing the original information we can revert to the original connection when the cluser is opened.
  9151. this.originalFromId = [];
  9152. this.originalToId = [];
  9153. this.connected = false;
  9154. // Added to support dashed lines
  9155. // David Jordan
  9156. // 2012-08-08
  9157. this.dash = util.extend({}, constants.edges.dash); // contains properties length, gap, altLength
  9158. this.color = {color:constants.edges.color.color,
  9159. highlight:constants.edges.color.highlight};
  9160. this.widthFixed = false;
  9161. this.lengthFixed = false;
  9162. this.setProperties(properties, constants);
  9163. }
  9164. /**
  9165. * Set or overwrite properties for the edge
  9166. * @param {Object} properties an object with properties
  9167. * @param {Object} constants and object with default, global properties
  9168. */
  9169. Edge.prototype.setProperties = function(properties, constants) {
  9170. if (!properties) {
  9171. return;
  9172. }
  9173. if (properties.from !== undefined) {this.fromId = properties.from;}
  9174. if (properties.to !== undefined) {this.toId = properties.to;}
  9175. if (properties.id !== undefined) {this.id = properties.id;}
  9176. if (properties.style !== undefined) {this.style = properties.style;}
  9177. if (properties.label !== undefined) {this.label = properties.label;}
  9178. if (this.label) {
  9179. this.fontSize = constants.edges.fontSize;
  9180. this.fontFace = constants.edges.fontFace;
  9181. this.fontColor = constants.edges.fontColor;
  9182. if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;}
  9183. if (properties.fontSize !== undefined) {this.fontSize = properties.fontSize;}
  9184. if (properties.fontFace !== undefined) {this.fontFace = properties.fontFace;}
  9185. }
  9186. if (properties.title !== undefined) {this.title = properties.title;}
  9187. if (properties.width !== undefined) {this.width = properties.width;}
  9188. if (properties.value !== undefined) {this.value = properties.value;}
  9189. if (properties.length !== undefined) {this.length = properties.length;
  9190. this.customLength = true;}
  9191. // Added to support dashed lines
  9192. // David Jordan
  9193. // 2012-08-08
  9194. if (properties.dash) {
  9195. if (properties.dash.length !== undefined) {this.dash.length = properties.dash.length;}
  9196. if (properties.dash.gap !== undefined) {this.dash.gap = properties.dash.gap;}
  9197. if (properties.dash.altLength !== undefined) {this.dash.altLength = properties.dash.altLength;}
  9198. }
  9199. if (properties.color !== undefined) {
  9200. if (util.isString(properties.color)) {
  9201. this.color.color = properties.color;
  9202. this.color.highlight = properties.color;
  9203. }
  9204. else {
  9205. if (properties.color.color !== undefined) {this.color.color = properties.color.color;}
  9206. if (properties.color.highlight !== undefined) {this.color.highlight = properties.color.highlight;}
  9207. }
  9208. }
  9209. // A node is connected when it has a from and to node.
  9210. this.connect();
  9211. this.widthFixed = this.widthFixed || (properties.width !== undefined);
  9212. this.lengthFixed = this.lengthFixed || (properties.length !== undefined);
  9213. // set draw method based on style
  9214. switch (this.style) {
  9215. case 'line': this.draw = this._drawLine; break;
  9216. case 'arrow': this.draw = this._drawArrow; break;
  9217. case 'arrow-center': this.draw = this._drawArrowCenter; break;
  9218. case 'dash-line': this.draw = this._drawDashLine; break;
  9219. default: this.draw = this._drawLine; break;
  9220. }
  9221. };
  9222. /**
  9223. * Connect an edge to its nodes
  9224. */
  9225. Edge.prototype.connect = function () {
  9226. this.disconnect();
  9227. this.from = this.graph.nodes[this.fromId] || null;
  9228. this.to = this.graph.nodes[this.toId] || null;
  9229. this.connected = (this.from && this.to);
  9230. if (this.connected) {
  9231. this.from.attachEdge(this);
  9232. this.to.attachEdge(this);
  9233. }
  9234. else {
  9235. if (this.from) {
  9236. this.from.detachEdge(this);
  9237. }
  9238. if (this.to) {
  9239. this.to.detachEdge(this);
  9240. }
  9241. }
  9242. };
  9243. /**
  9244. * Disconnect an edge from its nodes
  9245. */
  9246. Edge.prototype.disconnect = function () {
  9247. if (this.from) {
  9248. this.from.detachEdge(this);
  9249. this.from = null;
  9250. }
  9251. if (this.to) {
  9252. this.to.detachEdge(this);
  9253. this.to = null;
  9254. }
  9255. this.connected = false;
  9256. };
  9257. /**
  9258. * get the title of this edge.
  9259. * @return {string} title The title of the edge, or undefined when no title
  9260. * has been set.
  9261. */
  9262. Edge.prototype.getTitle = function() {
  9263. return this.title;
  9264. };
  9265. /**
  9266. * Retrieve the value of the edge. Can be undefined
  9267. * @return {Number} value
  9268. */
  9269. Edge.prototype.getValue = function() {
  9270. return this.value;
  9271. };
  9272. /**
  9273. * Adjust the value range of the edge. The edge will adjust it's width
  9274. * based on its value.
  9275. * @param {Number} min
  9276. * @param {Number} max
  9277. */
  9278. Edge.prototype.setValueRange = function(min, max) {
  9279. if (!this.widthFixed && this.value !== undefined) {
  9280. var scale = (this.widthMax - this.widthMin) / (max - min);
  9281. this.width = (this.value - min) * scale + this.widthMin;
  9282. }
  9283. };
  9284. /**
  9285. * Redraw a edge
  9286. * Draw this edge in the given canvas
  9287. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9288. * @param {CanvasRenderingContext2D} ctx
  9289. */
  9290. Edge.prototype.draw = function(ctx) {
  9291. throw "Method draw not initialized in edge";
  9292. };
  9293. /**
  9294. * Check if this object is overlapping with the provided object
  9295. * @param {Object} obj an object with parameters left, top
  9296. * @return {boolean} True if location is located on the edge
  9297. */
  9298. Edge.prototype.isOverlappingWith = function(obj) {
  9299. var distMax = 10;
  9300. var xFrom = this.from.x;
  9301. var yFrom = this.from.y;
  9302. var xTo = this.to.x;
  9303. var yTo = this.to.y;
  9304. var xObj = obj.left;
  9305. var yObj = obj.top;
  9306. var dist = this._getDistanceToEdge(xFrom, yFrom, xTo, yTo, xObj, yObj);
  9307. return (dist < distMax);
  9308. };
  9309. /**
  9310. * Redraw a edge as a line
  9311. * Draw this edge in the given canvas
  9312. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9313. * @param {CanvasRenderingContext2D} ctx
  9314. * @private
  9315. */
  9316. Edge.prototype._drawLine = function(ctx) {
  9317. // set style
  9318. if (this.selected == true) {ctx.strokeStyle = this.color.highlight;}
  9319. else {ctx.strokeStyle = this.color.color;}
  9320. ctx.lineWidth = this._getLineWidth();
  9321. if (this.from != this.to) {
  9322. // draw line
  9323. this._line(ctx);
  9324. // draw label
  9325. var point;
  9326. if (this.label) {
  9327. if (this.smooth == true) {
  9328. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9329. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9330. point = {x:midpointX, y:midpointY};
  9331. }
  9332. else {
  9333. point = this._pointOnLine(0.5);
  9334. }
  9335. this._label(ctx, this.label, point.x, point.y);
  9336. }
  9337. }
  9338. else {
  9339. var x, y;
  9340. var radius = this.length / 4;
  9341. var node = this.from;
  9342. if (!node.width) {
  9343. node.resize(ctx);
  9344. }
  9345. if (node.width > node.height) {
  9346. x = node.x + node.width / 2;
  9347. y = node.y - radius;
  9348. }
  9349. else {
  9350. x = node.x + radius;
  9351. y = node.y - node.height / 2;
  9352. }
  9353. this._circle(ctx, x, y, radius);
  9354. point = this._pointOnCircle(x, y, radius, 0.5);
  9355. this._label(ctx, this.label, point.x, point.y);
  9356. }
  9357. };
  9358. /**
  9359. * Get the line width of the edge. Depends on width and whether one of the
  9360. * connected nodes is selected.
  9361. * @return {Number} width
  9362. * @private
  9363. */
  9364. Edge.prototype._getLineWidth = function() {
  9365. if (this.selected == true) {
  9366. return Math.min(this.width * 2, this.widthMax)*this.graphScaleInv;
  9367. }
  9368. else {
  9369. return this.width*this.graphScaleInv;
  9370. }
  9371. };
  9372. /**
  9373. * Draw a line between two nodes
  9374. * @param {CanvasRenderingContext2D} ctx
  9375. * @private
  9376. */
  9377. Edge.prototype._line = function (ctx) {
  9378. // draw a straight line
  9379. ctx.beginPath();
  9380. ctx.moveTo(this.from.x, this.from.y);
  9381. if (this.smooth == true) {
  9382. ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y);
  9383. }
  9384. else {
  9385. ctx.lineTo(this.to.x, this.to.y);
  9386. }
  9387. ctx.stroke();
  9388. };
  9389. /**
  9390. * Draw a line from a node to itself, a circle
  9391. * @param {CanvasRenderingContext2D} ctx
  9392. * @param {Number} x
  9393. * @param {Number} y
  9394. * @param {Number} radius
  9395. * @private
  9396. */
  9397. Edge.prototype._circle = function (ctx, x, y, radius) {
  9398. // draw a circle
  9399. ctx.beginPath();
  9400. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  9401. ctx.stroke();
  9402. };
  9403. /**
  9404. * Draw label with white background and with the middle at (x, y)
  9405. * @param {CanvasRenderingContext2D} ctx
  9406. * @param {String} text
  9407. * @param {Number} x
  9408. * @param {Number} y
  9409. * @private
  9410. */
  9411. Edge.prototype._label = function (ctx, text, x, y) {
  9412. if (text) {
  9413. // TODO: cache the calculated size
  9414. ctx.font = ((this.from.selected || this.to.selected) ? "bold " : "") +
  9415. this.fontSize + "px " + this.fontFace;
  9416. ctx.fillStyle = 'white';
  9417. var width = ctx.measureText(text).width;
  9418. var height = this.fontSize;
  9419. var left = x - width / 2;
  9420. var top = y - height / 2;
  9421. ctx.fillRect(left, top, width, height);
  9422. // draw text
  9423. ctx.fillStyle = this.fontColor || "black";
  9424. ctx.textAlign = "left";
  9425. ctx.textBaseline = "top";
  9426. ctx.fillText(text, left, top);
  9427. }
  9428. };
  9429. /**
  9430. * Redraw a edge as a dashed line
  9431. * Draw this edge in the given canvas
  9432. * @author David Jordan
  9433. * @date 2012-08-08
  9434. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9435. * @param {CanvasRenderingContext2D} ctx
  9436. * @private
  9437. */
  9438. Edge.prototype._drawDashLine = function(ctx) {
  9439. // set style
  9440. if (this.selected == true) {ctx.strokeStyle = this.color.highlight;}
  9441. else {ctx.strokeStyle = this.color.color;}
  9442. ctx.lineWidth = this._getLineWidth();
  9443. // only firefox and chrome support this method, else we use the legacy one.
  9444. if (ctx.mozDash !== undefined || ctx.setLineDash !== undefined) {
  9445. ctx.beginPath();
  9446. ctx.moveTo(this.from.x, this.from.y);
  9447. // configure the dash pattern
  9448. var pattern = [0];
  9449. if (this.dash.length !== undefined && this.dash.gap !== undefined) {
  9450. pattern = [this.dash.length,this.dash.gap];
  9451. }
  9452. else {
  9453. pattern = [5,5];
  9454. }
  9455. // set dash settings for chrome or firefox
  9456. if (typeof ctx.setLineDash !== 'undefined') { //Chrome
  9457. ctx.setLineDash(pattern);
  9458. ctx.lineDashOffset = 0;
  9459. } else { //Firefox
  9460. ctx.mozDash = pattern;
  9461. ctx.mozDashOffset = 0;
  9462. }
  9463. // draw the line
  9464. if (this.smooth == true) {
  9465. ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y);
  9466. }
  9467. else {
  9468. ctx.lineTo(this.to.x, this.to.y);
  9469. }
  9470. ctx.stroke();
  9471. // restore the dash settings.
  9472. if (typeof ctx.setLineDash !== 'undefined') { //Chrome
  9473. ctx.setLineDash([0]);
  9474. ctx.lineDashOffset = 0;
  9475. } else { //Firefox
  9476. ctx.mozDash = [0];
  9477. ctx.mozDashOffset = 0;
  9478. }
  9479. }
  9480. else { // unsupporting smooth lines
  9481. // draw dashed line
  9482. ctx.beginPath();
  9483. ctx.lineCap = 'round';
  9484. if (this.dash.altLength !== undefined) //If an alt dash value has been set add to the array this value
  9485. {
  9486. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  9487. [this.dash.length,this.dash.gap,this.dash.altLength,this.dash.gap]);
  9488. }
  9489. else if (this.dash.length !== undefined && this.dash.gap !== undefined) //If a dash and gap value has been set add to the array this value
  9490. {
  9491. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  9492. [this.dash.length,this.dash.gap]);
  9493. }
  9494. else //If all else fails draw a line
  9495. {
  9496. ctx.moveTo(this.from.x, this.from.y);
  9497. ctx.lineTo(this.to.x, this.to.y);
  9498. }
  9499. ctx.stroke();
  9500. }
  9501. // draw label
  9502. if (this.label) {
  9503. var point;
  9504. if (this.smooth == true) {
  9505. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9506. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9507. point = {x:midpointX, y:midpointY};
  9508. }
  9509. else {
  9510. point = this._pointOnLine(0.5);
  9511. }
  9512. this._label(ctx, this.label, point.x, point.y);
  9513. }
  9514. };
  9515. /**
  9516. * Get a point on a line
  9517. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  9518. * @return {Object} point
  9519. * @private
  9520. */
  9521. Edge.prototype._pointOnLine = function (percentage) {
  9522. return {
  9523. x: (1 - percentage) * this.from.x + percentage * this.to.x,
  9524. y: (1 - percentage) * this.from.y + percentage * this.to.y
  9525. }
  9526. };
  9527. /**
  9528. * Get a point on a circle
  9529. * @param {Number} x
  9530. * @param {Number} y
  9531. * @param {Number} radius
  9532. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  9533. * @return {Object} point
  9534. * @private
  9535. */
  9536. Edge.prototype._pointOnCircle = function (x, y, radius, percentage) {
  9537. var angle = (percentage - 3/8) * 2 * Math.PI;
  9538. return {
  9539. x: x + radius * Math.cos(angle),
  9540. y: y - radius * Math.sin(angle)
  9541. }
  9542. };
  9543. /**
  9544. * Redraw a edge as a line with an arrow halfway the line
  9545. * Draw this edge in the given canvas
  9546. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9547. * @param {CanvasRenderingContext2D} ctx
  9548. * @private
  9549. */
  9550. Edge.prototype._drawArrowCenter = function(ctx) {
  9551. var point;
  9552. // set style
  9553. if (this.selected == true) {ctx.strokeStyle = this.color.highlight; ctx.fillStyle = this.color.highlight;}
  9554. else {ctx.strokeStyle = this.color.color; ctx.fillStyle = this.color.color;}
  9555. ctx.lineWidth = this._getLineWidth();
  9556. if (this.from != this.to) {
  9557. // draw line
  9558. this._line(ctx);
  9559. var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  9560. var length = 10 + 5 * this.width; // TODO: make customizable?
  9561. // draw an arrow halfway the line
  9562. if (this.smooth == true) {
  9563. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9564. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9565. point = {x:midpointX, y:midpointY};
  9566. }
  9567. else {
  9568. point = this._pointOnLine(0.5);
  9569. }
  9570. ctx.arrow(point.x, point.y, angle, length);
  9571. ctx.fill();
  9572. ctx.stroke();
  9573. // draw label
  9574. if (this.label) {
  9575. this._label(ctx, this.label, point.x, point.y);
  9576. }
  9577. }
  9578. else {
  9579. // draw circle
  9580. var x, y;
  9581. var radius = 0.25 * Math.max(100,this.length);
  9582. var node = this.from;
  9583. if (!node.width) {
  9584. node.resize(ctx);
  9585. }
  9586. if (node.width > node.height) {
  9587. x = node.x + node.width * 0.5;
  9588. y = node.y - radius;
  9589. }
  9590. else {
  9591. x = node.x + radius;
  9592. y = node.y - node.height * 0.5;
  9593. }
  9594. this._circle(ctx, x, y, radius);
  9595. // draw all arrows
  9596. var angle = 0.2 * Math.PI;
  9597. var length = 10 + 5 * this.width; // TODO: make customizable?
  9598. point = this._pointOnCircle(x, y, radius, 0.5);
  9599. ctx.arrow(point.x, point.y, angle, length);
  9600. ctx.fill();
  9601. ctx.stroke();
  9602. // draw label
  9603. if (this.label) {
  9604. point = this._pointOnCircle(x, y, radius, 0.5);
  9605. this._label(ctx, this.label, point.x, point.y);
  9606. }
  9607. }
  9608. };
  9609. /**
  9610. * Redraw a edge as a line with an arrow
  9611. * Draw this edge in the given canvas
  9612. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9613. * @param {CanvasRenderingContext2D} ctx
  9614. * @private
  9615. */
  9616. Edge.prototype._drawArrow = function(ctx) {
  9617. // set style
  9618. if (this.selected == true) {ctx.strokeStyle = this.color.highlight; ctx.fillStyle = this.color.highlight;}
  9619. else {ctx.strokeStyle = this.color.color; ctx.fillStyle = this.color.color;}
  9620. ctx.lineWidth = this._getLineWidth();
  9621. var angle, length;
  9622. //draw a line
  9623. if (this.from != this.to) {
  9624. angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  9625. var dx = (this.to.x - this.from.x);
  9626. var dy = (this.to.y - this.from.y);
  9627. var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  9628. // var fromBorderDist = this.from.distanceToBorder(ctx, angle + Math.PI);
  9629. // var fromBorderPoint = (edgeSegmentLength - fromBorderDist) / edgeSegmentLength;
  9630. // var xFrom = (fromBorderPoint) * this.from.x + (1 - fromBorderPoint) * this.to.x;
  9631. // var yFrom = (fromBorderPoint) * this.from.y + (1 - fromBorderPoint) * this.to.y;
  9632. if (this.smooth == true) {
  9633. angle = Math.atan2((this.to.y - this.via.y), (this.to.x - this.via.x));
  9634. dx = (this.to.x - this.via.x);
  9635. dy = (this.to.y - this.via.y);
  9636. edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  9637. }
  9638. var toBorderDist = this.to.distanceToBorder(ctx, angle);
  9639. var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength;
  9640. var xTo,yTo;
  9641. if (this.smooth == true) {
  9642. xTo = (1 - toBorderPoint) * this.via.x + toBorderPoint * this.to.x;
  9643. yTo = (1 - toBorderPoint) * this.via.y + toBorderPoint * this.to.y;
  9644. }
  9645. else {
  9646. xTo = (1 - toBorderPoint) * this.from.x + toBorderPoint * this.to.x;
  9647. yTo = (1 - toBorderPoint) * this.from.y + toBorderPoint * this.to.y;
  9648. }
  9649. ctx.beginPath();
  9650. ctx.moveTo(this.from.x,this.from.y);
  9651. if (this.smooth == true) {
  9652. ctx.quadraticCurveTo(this.via.x,this.via.y,xTo, yTo);
  9653. }
  9654. else {
  9655. ctx.lineTo(xTo, yTo);
  9656. }
  9657. ctx.stroke();
  9658. // draw arrow at the end of the line
  9659. length = 10 + 5 * this.width;
  9660. ctx.arrow(xTo, yTo, angle, length);
  9661. ctx.fill();
  9662. ctx.stroke();
  9663. // draw label
  9664. if (this.label) {
  9665. var point;
  9666. if (this.smooth == true) {
  9667. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9668. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9669. point = {x:midpointX, y:midpointY};
  9670. }
  9671. else {
  9672. point = this._pointOnLine(0.5);
  9673. }
  9674. this._label(ctx, this.label, point.x, point.y);
  9675. }
  9676. }
  9677. else {
  9678. // draw circle
  9679. var node = this.from;
  9680. var x, y, arrow;
  9681. var radius = 0.25 * Math.max(100,this.length);
  9682. if (!node.width) {
  9683. node.resize(ctx);
  9684. }
  9685. if (node.width > node.height) {
  9686. x = node.x + node.width * 0.5;
  9687. y = node.y - radius;
  9688. arrow = {
  9689. x: x,
  9690. y: node.y,
  9691. angle: 0.9 * Math.PI
  9692. };
  9693. }
  9694. else {
  9695. x = node.x + radius;
  9696. y = node.y - node.height * 0.5;
  9697. arrow = {
  9698. x: node.x,
  9699. y: y,
  9700. angle: 0.6 * Math.PI
  9701. };
  9702. }
  9703. ctx.beginPath();
  9704. // TODO: similarly, for a line without arrows, draw to the border of the nodes instead of the center
  9705. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  9706. ctx.stroke();
  9707. // draw all arrows
  9708. length = 10 + 5 * this.width; // TODO: make customizable?
  9709. ctx.arrow(arrow.x, arrow.y, arrow.angle, length);
  9710. ctx.fill();
  9711. ctx.stroke();
  9712. // draw label
  9713. if (this.label) {
  9714. point = this._pointOnCircle(x, y, radius, 0.5);
  9715. this._label(ctx, this.label, point.x, point.y);
  9716. }
  9717. }
  9718. };
  9719. /**
  9720. * Calculate the distance between a point (x3,y3) and a line segment from
  9721. * (x1,y1) to (x2,y2).
  9722. * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
  9723. * @param {number} x1
  9724. * @param {number} y1
  9725. * @param {number} x2
  9726. * @param {number} y2
  9727. * @param {number} x3
  9728. * @param {number} y3
  9729. * @private
  9730. */
  9731. Edge.prototype._getDistanceToEdge = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is the point
  9732. if (this.smooth == true) {
  9733. var minDistance = 1e9;
  9734. var i,t,x,y,dx,dy;
  9735. for (i = 0; i < 10; i++) {
  9736. t = 0.1*i;
  9737. x = Math.pow(1-t,2)*x1 + (2*t*(1 - t))*this.via.x + Math.pow(t,2)*x2;
  9738. y = Math.pow(1-t,2)*y1 + (2*t*(1 - t))*this.via.y + Math.pow(t,2)*y2;
  9739. dx = Math.abs(x3-x);
  9740. dy = Math.abs(y3-y);
  9741. minDistance = Math.min(minDistance,Math.sqrt(dx*dx + dy*dy));
  9742. }
  9743. return minDistance
  9744. }
  9745. else {
  9746. var px = x2-x1,
  9747. py = y2-y1,
  9748. something = px*px + py*py,
  9749. u = ((x3 - x1) * px + (y3 - y1) * py) / something;
  9750. if (u > 1) {
  9751. u = 1;
  9752. }
  9753. else if (u < 0) {
  9754. u = 0;
  9755. }
  9756. var x = x1 + u * px,
  9757. y = y1 + u * py,
  9758. dx = x - x3,
  9759. dy = y - y3;
  9760. //# Note: If the actual distance does not matter,
  9761. //# if you only want to compare what this function
  9762. //# returns to other results of this function, you
  9763. //# can just return the squared distance instead
  9764. //# (i.e. remove the sqrt) to gain a little performance
  9765. return Math.sqrt(dx*dx + dy*dy);
  9766. }
  9767. };
  9768. /**
  9769. * This allows the zoom level of the graph to influence the rendering
  9770. *
  9771. * @param scale
  9772. */
  9773. Edge.prototype.setScale = function(scale) {
  9774. this.graphScaleInv = 1.0/scale;
  9775. };
  9776. Edge.prototype.select = function() {
  9777. this.selected = true;
  9778. };
  9779. Edge.prototype.unselect = function() {
  9780. this.selected = false;
  9781. };
  9782. Edge.prototype.positionBezierNode = function() {
  9783. if (this.via !== null) {
  9784. this.via.x = 0.5 * (this.from.x + this.to.x);
  9785. this.via.y = 0.5 * (this.from.y + this.to.y);
  9786. }
  9787. };
  9788. /**
  9789. * Popup is a class to create a popup window with some text
  9790. * @param {Element} container The container object.
  9791. * @param {Number} [x]
  9792. * @param {Number} [y]
  9793. * @param {String} [text]
  9794. */
  9795. function Popup(container, x, y, text) {
  9796. if (container) {
  9797. this.container = container;
  9798. }
  9799. else {
  9800. this.container = document.body;
  9801. }
  9802. this.x = 0;
  9803. this.y = 0;
  9804. this.padding = 5;
  9805. if (x !== undefined && y !== undefined ) {
  9806. this.setPosition(x, y);
  9807. }
  9808. if (text !== undefined) {
  9809. this.setText(text);
  9810. }
  9811. // create the frame
  9812. this.frame = document.createElement("div");
  9813. var style = this.frame.style;
  9814. style.position = "absolute";
  9815. style.visibility = "hidden";
  9816. style.border = "1px solid #666";
  9817. style.color = "black";
  9818. style.padding = this.padding + "px";
  9819. style.backgroundColor = "#FFFFC6";
  9820. style.borderRadius = "3px";
  9821. style.MozBorderRadius = "3px";
  9822. style.WebkitBorderRadius = "3px";
  9823. style.boxShadow = "3px 3px 10px rgba(128, 128, 128, 0.5)";
  9824. style.whiteSpace = "nowrap";
  9825. this.container.appendChild(this.frame);
  9826. }
  9827. /**
  9828. * @param {number} x Horizontal position of the popup window
  9829. * @param {number} y Vertical position of the popup window
  9830. */
  9831. Popup.prototype.setPosition = function(x, y) {
  9832. this.x = parseInt(x);
  9833. this.y = parseInt(y);
  9834. };
  9835. /**
  9836. * Set the text for the popup window. This can be HTML code
  9837. * @param {string} text
  9838. */
  9839. Popup.prototype.setText = function(text) {
  9840. this.frame.innerHTML = text;
  9841. };
  9842. /**
  9843. * Show the popup window
  9844. * @param {boolean} show Optional. Show or hide the window
  9845. */
  9846. Popup.prototype.show = function (show) {
  9847. if (show === undefined) {
  9848. show = true;
  9849. }
  9850. if (show) {
  9851. var height = this.frame.clientHeight;
  9852. var width = this.frame.clientWidth;
  9853. var maxHeight = this.frame.parentNode.clientHeight;
  9854. var maxWidth = this.frame.parentNode.clientWidth;
  9855. var top = (this.y - height);
  9856. if (top + height + this.padding > maxHeight) {
  9857. top = maxHeight - height - this.padding;
  9858. }
  9859. if (top < this.padding) {
  9860. top = this.padding;
  9861. }
  9862. var left = this.x;
  9863. if (left + width + this.padding > maxWidth) {
  9864. left = maxWidth - width - this.padding;
  9865. }
  9866. if (left < this.padding) {
  9867. left = this.padding;
  9868. }
  9869. this.frame.style.left = left + "px";
  9870. this.frame.style.top = top + "px";
  9871. this.frame.style.visibility = "visible";
  9872. }
  9873. else {
  9874. this.hide();
  9875. }
  9876. };
  9877. /**
  9878. * Hide the popup window
  9879. */
  9880. Popup.prototype.hide = function () {
  9881. this.frame.style.visibility = "hidden";
  9882. };
  9883. /**
  9884. * @class Groups
  9885. * This class can store groups and properties specific for groups.
  9886. */
  9887. Groups = function () {
  9888. this.clear();
  9889. this.defaultIndex = 0;
  9890. };
  9891. /**
  9892. * default constants for group colors
  9893. */
  9894. Groups.DEFAULT = [
  9895. {border: "#2B7CE9", background: "#97C2FC", highlight: {border: "#2B7CE9", background: "#D2E5FF"}}, // blue
  9896. {border: "#FFA500", background: "#FFFF00", highlight: {border: "#FFA500", background: "#FFFFA3"}}, // yellow
  9897. {border: "#FA0A10", background: "#FB7E81", highlight: {border: "#FA0A10", background: "#FFAFB1"}}, // red
  9898. {border: "#41A906", background: "#7BE141", highlight: {border: "#41A906", background: "#A1EC76"}}, // green
  9899. {border: "#E129F0", background: "#EB7DF4", highlight: {border: "#E129F0", background: "#F0B3F5"}}, // magenta
  9900. {border: "#7C29F0", background: "#AD85E4", highlight: {border: "#7C29F0", background: "#D3BDF0"}}, // purple
  9901. {border: "#C37F00", background: "#FFA807", highlight: {border: "#C37F00", background: "#FFCA66"}}, // orange
  9902. {border: "#4220FB", background: "#6E6EFD", highlight: {border: "#4220FB", background: "#9B9BFD"}}, // darkblue
  9903. {border: "#FD5A77", background: "#FFC0CB", highlight: {border: "#FD5A77", background: "#FFD1D9"}}, // pink
  9904. {border: "#4AD63A", background: "#C2FABC", highlight: {border: "#4AD63A", background: "#E6FFE3"}} // mint
  9905. ];
  9906. /**
  9907. * Clear all groups
  9908. */
  9909. Groups.prototype.clear = function () {
  9910. this.groups = {};
  9911. this.groups.length = function()
  9912. {
  9913. var i = 0;
  9914. for ( var p in this ) {
  9915. if (this.hasOwnProperty(p)) {
  9916. i++;
  9917. }
  9918. }
  9919. return i;
  9920. }
  9921. };
  9922. /**
  9923. * get group properties of a groupname. If groupname is not found, a new group
  9924. * is added.
  9925. * @param {*} groupname Can be a number, string, Date, etc.
  9926. * @return {Object} group The created group, containing all group properties
  9927. */
  9928. Groups.prototype.get = function (groupname) {
  9929. var group = this.groups[groupname];
  9930. if (group == undefined) {
  9931. // create new group
  9932. var index = this.defaultIndex % Groups.DEFAULT.length;
  9933. this.defaultIndex++;
  9934. group = {};
  9935. group.color = Groups.DEFAULT[index];
  9936. this.groups[groupname] = group;
  9937. }
  9938. return group;
  9939. };
  9940. /**
  9941. * Add a custom group style
  9942. * @param {String} groupname
  9943. * @param {Object} style An object containing borderColor,
  9944. * backgroundColor, etc.
  9945. * @return {Object} group The created group object
  9946. */
  9947. Groups.prototype.add = function (groupname, style) {
  9948. this.groups[groupname] = style;
  9949. if (style.color) {
  9950. style.color = Node.parseColor(style.color);
  9951. }
  9952. return style;
  9953. };
  9954. /**
  9955. * @class Images
  9956. * This class loads images and keeps them stored.
  9957. */
  9958. Images = function () {
  9959. this.images = {};
  9960. this.callback = undefined;
  9961. };
  9962. /**
  9963. * Set an onload callback function. This will be called each time an image
  9964. * is loaded
  9965. * @param {function} callback
  9966. */
  9967. Images.prototype.setOnloadCallback = function(callback) {
  9968. this.callback = callback;
  9969. };
  9970. /**
  9971. *
  9972. * @param {string} url Url of the image
  9973. * @return {Image} img The image object
  9974. */
  9975. Images.prototype.load = function(url) {
  9976. var img = this.images[url];
  9977. if (img == undefined) {
  9978. // create the image
  9979. var images = this;
  9980. img = new Image();
  9981. this.images[url] = img;
  9982. img.onload = function() {
  9983. if (images.callback) {
  9984. images.callback(this);
  9985. }
  9986. };
  9987. img.src = url;
  9988. }
  9989. return img;
  9990. };
  9991. /**
  9992. * Created by Alex on 2/6/14.
  9993. */
  9994. var physicsMixin = {
  9995. /**
  9996. * Toggling barnes Hut calculation on and off.
  9997. *
  9998. * @private
  9999. */
  10000. _toggleBarnesHut : function() {
  10001. this.constants.physics.barnesHut.enabled = !this.constants.physics.barnesHut.enabled;
  10002. this._loadSelectedForceSolver();
  10003. this.moving = true;
  10004. this.start();
  10005. },
  10006. /**
  10007. * This loads the node force solver based on the barnes hut or repulsion algorithm
  10008. *
  10009. * @private
  10010. */
  10011. _loadSelectedForceSolver : function() {
  10012. // this overloads the this._calculateNodeForces
  10013. if (this.constants.physics.barnesHut.enabled == true) {
  10014. this._clearMixin(repulsionMixin);
  10015. this._clearMixin(hierarchalRepulsionMixin);
  10016. this.constants.physics.centralGravity = this.constants.physics.barnesHut.centralGravity;
  10017. this.constants.physics.springLength = this.constants.physics.barnesHut.springLength;
  10018. this.constants.physics.springConstant = this.constants.physics.barnesHut.springConstant;
  10019. this.constants.physics.damping = this.constants.physics.barnesHut.damping;
  10020. this._loadMixin(barnesHutMixin);
  10021. }
  10022. else if (this.constants.physics.hierarchicalRepulsion.enabled == true) {
  10023. this._clearMixin(barnesHutMixin);
  10024. this._clearMixin(repulsionMixin);
  10025. this.constants.physics.centralGravity = this.constants.physics.hierarchicalRepulsion.centralGravity;
  10026. this.constants.physics.springLength = this.constants.physics.hierarchicalRepulsion.springLength;
  10027. this.constants.physics.springConstant = this.constants.physics.hierarchicalRepulsion.springConstant;
  10028. this.constants.physics.damping = this.constants.physics.hierarchicalRepulsion.damping;
  10029. this._loadMixin(hierarchalRepulsionMixin);
  10030. }
  10031. else {
  10032. this._clearMixin(barnesHutMixin);
  10033. this._clearMixin(hierarchalRepulsionMixin);
  10034. this.barnesHutTree = undefined;
  10035. this.constants.physics.centralGravity = this.constants.physics.repulsion.centralGravity;
  10036. this.constants.physics.springLength = this.constants.physics.repulsion.springLength;
  10037. this.constants.physics.springConstant = this.constants.physics.repulsion.springConstant;
  10038. this.constants.physics.damping = this.constants.physics.repulsion.damping;
  10039. this._loadMixin(repulsionMixin);
  10040. }
  10041. },
  10042. /**
  10043. * Before calculating the forces, we check if we need to cluster to keep up performance and we check
  10044. * if there is more than one node. If it is just one node, we dont calculate anything.
  10045. *
  10046. * @private
  10047. */
  10048. _initializeForceCalculation : function() {
  10049. // stop calculation if there is only one node
  10050. if (this.nodeIndices.length == 1) {
  10051. this.nodes[this.nodeIndices[0]]._setForce(0,0);
  10052. }
  10053. else {
  10054. // if there are too many nodes on screen, we cluster without repositioning
  10055. if (this.nodeIndices.length > this.constants.clustering.clusterThreshold && this.constants.clustering.enabled == true) {
  10056. this.clusterToFit(this.constants.clustering.reduceToNodes, false);
  10057. }
  10058. // we now start the force calculation
  10059. this._calculateForces();
  10060. }
  10061. },
  10062. /**
  10063. * Calculate the external forces acting on the nodes
  10064. * Forces are caused by: edges, repulsing forces between nodes, gravity
  10065. * @private
  10066. */
  10067. _calculateForces : function() {
  10068. // Gravity is required to keep separated groups from floating off
  10069. // the forces are reset to zero in this loop by using _setForce instead
  10070. // of _addForce
  10071. this._calculateGravitationalForces();
  10072. this._calculateNodeForces();
  10073. if (this.constants.smoothCurves == true) {
  10074. this._calculateSpringForcesWithSupport();
  10075. }
  10076. else {
  10077. this._calculateSpringForces();
  10078. }
  10079. },
  10080. /**
  10081. * Smooth curves are created by adding invisible nodes in the center of the edges. These nodes are also
  10082. * handled in the calculateForces function. We then use a quadratic curve with the center node as control.
  10083. * This function joins the datanodes and invisible (called support) nodes into one object.
  10084. * We do this so we do not contaminate this.nodes with the support nodes.
  10085. *
  10086. * @private
  10087. */
  10088. _updateCalculationNodes : function() {
  10089. if (this.constants.smoothCurves == true) {
  10090. this.calculationNodes = {};
  10091. this.calculationNodeIndices = [];
  10092. for (var nodeId in this.nodes) {
  10093. if (this.nodes.hasOwnProperty(nodeId)) {
  10094. this.calculationNodes[nodeId] = this.nodes[nodeId];
  10095. }
  10096. }
  10097. var supportNodes = this.sectors['support']['nodes'];
  10098. for (var supportNodeId in supportNodes) {
  10099. if (supportNodes.hasOwnProperty(supportNodeId)) {
  10100. if (this.edges.hasOwnProperty(supportNodes[supportNodeId].parentEdgeId)) {
  10101. this.calculationNodes[supportNodeId] = supportNodes[supportNodeId];
  10102. }
  10103. else {
  10104. supportNodes[supportNodeId]._setForce(0,0);
  10105. }
  10106. }
  10107. }
  10108. for (var idx in this.calculationNodes) {
  10109. if (this.calculationNodes.hasOwnProperty(idx)) {
  10110. this.calculationNodeIndices.push(idx);
  10111. }
  10112. }
  10113. }
  10114. else {
  10115. this.calculationNodes = this.nodes;
  10116. this.calculationNodeIndices = this.nodeIndices;
  10117. }
  10118. },
  10119. /**
  10120. * this function applies the central gravity effect to keep groups from floating off
  10121. *
  10122. * @private
  10123. */
  10124. _calculateGravitationalForces : function() {
  10125. var dx, dy, distance, node, i;
  10126. var nodes = this.calculationNodes;
  10127. var gravity = this.constants.physics.centralGravity;
  10128. var gravityForce = 0;
  10129. for (i = 0; i < this.calculationNodeIndices.length; i++) {
  10130. node = nodes[this.calculationNodeIndices[i]];
  10131. node.damping = this.constants.physics.damping; // possibly add function to alter damping properties of clusters.
  10132. // gravity does not apply when we are in a pocket sector
  10133. if (this._sector() == "default" && gravity != 0) {
  10134. dx = -node.x;
  10135. dy = -node.y;
  10136. distance = Math.sqrt(dx*dx + dy*dy);
  10137. gravityForce = gravity / distance;
  10138. node.fx = dx * gravityForce;
  10139. node.fy = dy * gravityForce;
  10140. }
  10141. else {
  10142. node.fx = 0;
  10143. node.fy = 0;
  10144. }
  10145. }
  10146. },
  10147. /**
  10148. * this function calculates the effects of the springs in the case of unsmooth curves.
  10149. *
  10150. * @private
  10151. */
  10152. _calculateSpringForces : function() {
  10153. var edgeLength, edge, edgeId;
  10154. var dx, dy, fx, fy, springForce, length;
  10155. var edges = this.edges;
  10156. // forces caused by the edges, modelled as springs
  10157. for (edgeId in edges) {
  10158. if (edges.hasOwnProperty(edgeId)) {
  10159. edge = edges[edgeId];
  10160. if (edge.connected) {
  10161. // only calculate forces if nodes are in the same sector
  10162. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  10163. edgeLength = edge.customLength ? edge.length : this.constants.physics.springLength;
  10164. // this implies that the edges between big clusters are longer
  10165. edgeLength += (edge.to.clusterSize + edge.from.clusterSize - 2) * this.constants.clustering.edgeGrowth;
  10166. dx = (edge.from.x - edge.to.x);
  10167. dy = (edge.from.y - edge.to.y);
  10168. length = Math.sqrt(dx * dx + dy * dy);
  10169. if (length == 0) {
  10170. length = 0.01;
  10171. }
  10172. springForce = this.constants.physics.springConstant * (edgeLength - length) / length;
  10173. fx = dx * springForce;
  10174. fy = dy * springForce;
  10175. edge.from.fx += fx;
  10176. edge.from.fy += fy;
  10177. edge.to.fx -= fx;
  10178. edge.to.fy -= fy;
  10179. }
  10180. }
  10181. }
  10182. }
  10183. },
  10184. /**
  10185. * This function calculates the springforces on the nodes, accounting for the support nodes.
  10186. *
  10187. * @private
  10188. */
  10189. _calculateSpringForcesWithSupport : function() {
  10190. var edgeLength, edge, edgeId, combinedClusterSize;
  10191. var edges = this.edges;
  10192. // forces caused by the edges, modelled as springs
  10193. for (edgeId in edges) {
  10194. if (edges.hasOwnProperty(edgeId)) {
  10195. edge = edges[edgeId];
  10196. if (edge.connected) {
  10197. // only calculate forces if nodes are in the same sector
  10198. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  10199. if (edge.via != null) {
  10200. var node1 = edge.to;
  10201. var node2 = edge.via;
  10202. var node3 = edge.from;
  10203. edgeLength = edge.customLength ? edge.length : this.constants.physics.springLength;
  10204. combinedClusterSize = node1.clusterSize + node3.clusterSize - 2;
  10205. // this implies that the edges between big clusters are longer
  10206. edgeLength += combinedClusterSize * this.constants.clustering.edgeGrowth;
  10207. this._calculateSpringForce(node1,node2,0.5*edgeLength);
  10208. this._calculateSpringForce(node2,node3,0.5*edgeLength);
  10209. }
  10210. }
  10211. }
  10212. }
  10213. }
  10214. },
  10215. /**
  10216. * This is the code actually performing the calculation for the function above. It is split out to avoid repetition.
  10217. *
  10218. * @param node1
  10219. * @param node2
  10220. * @param edgeLength
  10221. * @private
  10222. */
  10223. _calculateSpringForce : function(node1,node2,edgeLength) {
  10224. var dx, dy, fx, fy, springForce, length;
  10225. dx = (node1.x - node2.x);
  10226. dy = (node1.y - node2.y);
  10227. length = Math.sqrt(dx * dx + dy * dy);
  10228. springForce = this.constants.physics.springConstant * (edgeLength - length) / length;
  10229. if (length == 0) {
  10230. length = 0.01;
  10231. }
  10232. fx = dx * springForce;
  10233. fy = dy * springForce;
  10234. node1.fx += fx;
  10235. node1.fy += fy;
  10236. node2.fx -= fx;
  10237. node2.fy -= fy;
  10238. },
  10239. /**
  10240. * Load the HTML for the physics config and bind it
  10241. * @private
  10242. */
  10243. _loadPhysicsConfiguration : function() {
  10244. if (this.physicsConfiguration === undefined) {
  10245. var hierarchicalLayoutDirections = ["LR","RL","UD","DU"];
  10246. this.physicsConfiguration = document.createElement('div');
  10247. this.physicsConfiguration.className = "PhysicsConfiguration";
  10248. this.physicsConfiguration.innerHTML = '' +
  10249. '<table><tr><td><b>Simulation Mode:</b></td></tr>' +
  10250. '<tr>' +
  10251. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod1" value="BH" checked="checked">Barnes Hut</td>' +
  10252. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod2" value="R">Repulsion</td>'+
  10253. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod3" value="H">Hierarchical</td>' +
  10254. '</tr>'+
  10255. '</table>' +
  10256. '<table id="graph_BH_table" style="display:none">'+
  10257. '<tr><td><b>Barnes Hut</b></td></tr>'+
  10258. '<tr>'+
  10259. '<td width="150px">gravitationalConstant</td><td>0</td><td><input type="range" min="500" max="20000" value="' + (-1* this.constants.physics.barnesHut.gravitationalConstant) + '" step="25" style="width:300px" id="graph_BH_gc"></td><td width="50px">-20000</td><td><input value="' + (-1* this.constants.physics.barnesHut.gravitationalConstant) + '" id="graph_BH_gc_value" style="width:60px"></td>'+
  10260. '</tr>'+
  10261. '<tr>'+
  10262. '<td width="150px">centralGravity</td><td>0</td><td><input type="range" min="0" max="3" value="' + this.constants.physics.barnesHut.centralGravity + '" step="0.05" style="width:300px" id="graph_BH_cg"></td><td>3</td><td><input value="' + this.constants.physics.barnesHut.centralGravity + '" id="graph_BH_cg_value" style="width:60px"></td>'+
  10263. '</tr>'+
  10264. '<tr>'+
  10265. '<td width="150px">springLength</td><td>0</td><td><input type="range" min="0" max="500" value="' + this.constants.physics.barnesHut.springLength + '" step="1" style="width:300px" id="graph_BH_sl"></td><td>500</td><td><input value="' + this.constants.physics.barnesHut.springLength + '" id="graph_BH_sl_value" style="width:60px"></td>'+
  10266. '</tr>'+
  10267. '<tr>'+
  10268. '<td width="150px">springConstant</td><td>0</td><td><input type="range" min="0" max="0.5" value="' + this.constants.physics.barnesHut.springConstant + '" step="0.001" style="width:300px" id="graph_BH_sc"></td><td>0.5</td><td><input value="' + this.constants.physics.barnesHut.springConstant + '" id="graph_BH_sc_value" style="width:60px"></td>'+
  10269. '</tr>'+
  10270. '<tr>'+
  10271. '<td width="150px">damping</td><td>0</td><td><input type="range" min="0" max="0.3" value="' + this.constants.physics.barnesHut.damping + '" step="0.005" style="width:300px" id="graph_BH_damp"></td><td>0.3</td><td><input value="' + this.constants.physics.barnesHut.damping + '" id="graph_BH_damp_value" style="width:60px"></td>'+
  10272. '</tr>'+
  10273. '</table>'+
  10274. '<table id="graph_R_table" style="display:none">'+
  10275. '<tr><td><b>Repulsion</b></td></tr>'+
  10276. '<tr>'+
  10277. '<td width="150px">nodeDistance</td><td>0</td><td><input type="range" min="0" max="300" value="' + this.constants.physics.repulsion.nodeDistance + '" step="1" style="width:300px" id="graph_R_nd"></td><td width="50px">300</td><td><input value="' + this.constants.physics.repulsion.nodeDistance + '" id="graph_R_nd_value" style="width:60px"></td>'+
  10278. '</tr>'+
  10279. '<tr>'+
  10280. '<td width="150px">centralGravity</td><td>0</td><td><input type="range" min="0" max="3" value="' + this.constants.physics.repulsion.centralGravity + '" step="0.05" style="width:300px" id="graph_R_cg"></td><td>3</td><td><input value="' + this.constants.physics.repulsion.centralGravity + '" id="graph_R_cg_value" style="width:60px"></td>'+
  10281. '</tr>'+
  10282. '<tr>'+
  10283. '<td width="150px">springLength</td><td>0</td><td><input type="range" min="0" max="500" value="' + this.constants.physics.repulsion.springLength + '" step="1" style="width:300px" id="graph_R_sl"></td><td>500</td><td><input value="' + this.constants.physics.repulsion.springLength + '" id="graph_R_sl_value" style="width:60px"></td>'+
  10284. '</tr>'+
  10285. '<tr>'+
  10286. '<td width="150px">springConstant</td><td>0</td><td><input type="range" min="0" max="0.5" value="' + this.constants.physics.repulsion.springConstant + '" step="0.001" style="width:300px" id="graph_R_sc"></td><td>0.5</td><td><input value="' + this.constants.physics.repulsion.springConstant + '" id="graph_R_sc_value" style="width:60px"></td>'+
  10287. '</tr>'+
  10288. '<tr>'+
  10289. '<td width="150px">damping</td><td>0</td><td><input type="range" min="0" max="0.3" value="' + this.constants.physics.repulsion.damping + '" step="0.005" style="width:300px" id="graph_R_damp"></td><td>0.3</td><td><input value="' + this.constants.physics.repulsion.damping + '" id="graph_R_damp_value" style="width:60px"></td>'+
  10290. '</tr>'+
  10291. '</table>'+
  10292. '<table id="graph_H_table" style="display:none">'+
  10293. '<tr><td width="150"><b>Hierarchical</b></td></tr>'+
  10294. '<tr>'+
  10295. '<td width="150px">nodeDistance</td><td>0</td><td><input type="range" min="0" max="300" value="' + this.constants.physics.hierarchicalRepulsion.nodeDistance + '" step="1" style="width:300px" id="graph_H_nd"></td><td width="50px">300</td><td><input value="' + this.constants.physics.hierarchicalRepulsion.nodeDistance + '" id="graph_H_nd_value" style="width:60px"></td>'+
  10296. '</tr>'+
  10297. '<tr>'+
  10298. '<td width="150px">centralGravity</td><td>0</td><td><input type="range" min="0" max="3" value="' + this.constants.physics.hierarchicalRepulsion.centralGravity + '" step="0.05" style="width:300px" id="graph_H_cg"></td><td>3</td><td><input value="' + this.constants.physics.hierarchicalRepulsion.centralGravity + '" id="graph_H_cg_value" style="width:60px"></td>'+
  10299. '</tr>'+
  10300. '<tr>'+
  10301. '<td width="150px">springLength</td><td>0</td><td><input type="range" min="0" max="500" value="' + this.constants.physics.hierarchicalRepulsion.springLength + '" step="1" style="width:300px" id="graph_H_sl"></td><td>500</td><td><input value="' + this.constants.physics.hierarchicalRepulsion.springLength + '" id="graph_H_sl_value" style="width:60px"></td>'+
  10302. '</tr>'+
  10303. '<tr>'+
  10304. '<td width="150px">springConstant</td><td>0</td><td><input type="range" min="0" max="0.5" value="' + this.constants.physics.hierarchicalRepulsion.springConstant + '" step="0.001" style="width:300px" id="graph_H_sc"></td><td>0.5</td><td><input value="' + this.constants.physics.hierarchicalRepulsion.springConstant + '" id="graph_H_sc_value" style="width:60px"></td>'+
  10305. '</tr>'+
  10306. '<tr>'+
  10307. '<td width="150px">damping</td><td>0</td><td><input type="range" min="0" max="0.3" value="' + this.constants.physics.hierarchicalRepulsion.damping + '" step="0.005" style="width:300px" id="graph_H_damp"></td><td>0.3</td><td><input value="' + this.constants.physics.hierarchicalRepulsion.damping + '" id="graph_H_damp_value" style="width:60px"></td>'+
  10308. '</tr>'+
  10309. '<tr>'+
  10310. '<td width="150px">direction</td><td>1</td><td><input type="range" min="0" max="3" value="' + hierarchicalLayoutDirections.indexOf(this.constants.hierarchicalLayout.direction) + '" step="1" style="width:300px" id="graph_H_direction"></td><td>4</td><td><input value="' + this.constants.hierarchicalLayout.direction + '" id="graph_H_direction_value" style="width:60px"></td>'+
  10311. '</tr>'+
  10312. '<tr>'+
  10313. '<td width="150px">levelSeparation</td><td>1</td><td><input type="range" min="0" max="500" value="' + this.constants.hierarchicalLayout.levelSeparation + '" step="1" style="width:300px" id="graph_H_levsep"></td><td>500</td><td><input value="' + this.constants.hierarchicalLayout.levelSeparation + '" id="graph_H_levsep_value" style="width:60px"></td>'+
  10314. '</tr>'+
  10315. '<tr>'+
  10316. '<td width="150px">nodeSpacing</td><td>1</td><td><input type="range" min="0" max="500" value="' + this.constants.hierarchicalLayout.nodeSpacing + '" step="1" style="width:300px" id="graph_H_nspac"></td><td>500</td><td><input value="' + this.constants.hierarchicalLayout.nodeSpacing + '" id="graph_H_nspac_value" style="width:60px"></td>'+
  10317. '</tr>'+
  10318. '</table>'
  10319. this.containerElement.parentElement.insertBefore(this.physicsConfiguration,this.containerElement);
  10320. var rangeElement;
  10321. rangeElement = document.getElementById('graph_BH_gc');
  10322. rangeElement.onchange = showValueOfRange.bind(this,'graph_BH_gc',-1,"physics_barnesHut_gravitationalConstant");
  10323. rangeElement = document.getElementById('graph_BH_cg');
  10324. rangeElement.onchange = showValueOfRange.bind(this,'graph_BH_cg',1,"physics_centralGravity");
  10325. rangeElement = document.getElementById('graph_BH_sc');
  10326. rangeElement.onchange = showValueOfRange.bind(this,'graph_BH_sc',1,"physics_springConstant");
  10327. rangeElement = document.getElementById('graph_BH_sl');
  10328. rangeElement.onchange = showValueOfRange.bind(this,'graph_BH_sl',1,"physics_springLength");
  10329. rangeElement = document.getElementById('graph_BH_damp');
  10330. rangeElement.onchange = showValueOfRange.bind(this,'graph_BH_damp',1,"physics_damping");
  10331. rangeElement = document.getElementById('graph_R_nd');
  10332. rangeElement.onchange = showValueOfRange.bind(this,'graph_R_nd',1,"physics_repulsion_nodeDistance");
  10333. rangeElement = document.getElementById('graph_R_cg');
  10334. rangeElement.onchange = showValueOfRange.bind(this,'graph_R_cg',1,"physics_centralGravity");
  10335. rangeElement = document.getElementById('graph_R_sc');
  10336. rangeElement.onchange = showValueOfRange.bind(this,'graph_R_sc',1,"physics_springConstant");
  10337. rangeElement = document.getElementById('graph_R_sl');
  10338. rangeElement.onchange = showValueOfRange.bind(this,'graph_R_sl',1,"physics_springLength");
  10339. rangeElement = document.getElementById('graph_R_damp');
  10340. rangeElement.onchange = showValueOfRange.bind(this,'graph_R_damp',1,"physics_damping");
  10341. rangeElement = document.getElementById('graph_H_nd');
  10342. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_nd',1,"physics_hierarchicalRepulsion_nodeDistance");
  10343. rangeElement = document.getElementById('graph_H_cg');
  10344. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_cg',1,"physics_centralGravity");
  10345. rangeElement = document.getElementById('graph_H_sc');
  10346. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_sc',1,"physics_springConstant");
  10347. rangeElement = document.getElementById('graph_H_sl');
  10348. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_sl',1,"physics_springLength");
  10349. rangeElement = document.getElementById('graph_H_damp');
  10350. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_damp',1,"physics_damping");
  10351. rangeElement = document.getElementById('graph_H_direction');
  10352. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_direction',hierarchicalLayoutDirections,"hierarchicalLayout_direction");
  10353. rangeElement = document.getElementById('graph_H_levsep');
  10354. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_levsep',1,"hierarchicalLayout_levelSeparation");
  10355. rangeElement = document.getElementById('graph_H_nspac');
  10356. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_nspac',1,"hierarchicalLayout_nodeSpacing");
  10357. var radioButton1 = document.getElementById("graph_physicsMethod1");
  10358. var radioButton2 = document.getElementById("graph_physicsMethod2");
  10359. var radioButton3 = document.getElementById("graph_physicsMethod3");
  10360. radioButton2.checked = true;
  10361. if (this.constants.physics.barnesHut.enabled) {
  10362. radioButton1.checked = true;
  10363. }
  10364. if (this.constants.hierarchicalLayout.enabled) {
  10365. radioButton3.checked = true;
  10366. }
  10367. switchConfigurations.apply(this);
  10368. radioButton1.onchange = switchConfigurations.bind(this);
  10369. radioButton2.onchange = switchConfigurations.bind(this);
  10370. radioButton3.onchange = switchConfigurations.bind(this);
  10371. }
  10372. },
  10373. _overWriteGraphConstants : function(constantsVariableName, value) {
  10374. var nameArray = constantsVariableName.split("_");
  10375. if (nameArray.length == 1) {
  10376. this.constants[nameArray[0]] = value;
  10377. }
  10378. else if (nameArray.length == 2) {
  10379. this.constants[nameArray[0]][nameArray[1]] = value;
  10380. }
  10381. else if (nameArray.length == 3) {
  10382. this.constants[nameArray[0]][nameArray[1]][nameArray[2]] = value;
  10383. }
  10384. }
  10385. }
  10386. function switchConfigurations () {
  10387. var ids = ["graph_BH_table","graph_R_table","graph_H_table"]
  10388. var radioButton = document.querySelector('input[name="graph_physicsMethod"]:checked').value;
  10389. var tableId = "graph_" + radioButton + "_table";
  10390. var table = document.getElementById(tableId);
  10391. table.style.display = "block";
  10392. for (var i = 0; i < ids.length; i++) {
  10393. if (ids[i] != tableId) {
  10394. table = document.getElementById(ids[i]);
  10395. table.style.display = "none";
  10396. }
  10397. }
  10398. this._restoreNodes();
  10399. if (radioButton == "R") {
  10400. this.constants.hierarchicalLayout.enabled = false;
  10401. this.constants.physics.hierarchicalRepulsion.enabeled = false;
  10402. this.constants.physics.barnesHut.enabled = false;
  10403. }
  10404. else if (radioButton == "H") {
  10405. this.constants.hierarchicalLayout.enabled = true;
  10406. this.constants.physics.hierarchicalRepulsion.enabeled = true;
  10407. this.constants.physics.barnesHut.enabled = false;
  10408. this._setupHierarchicalLayout();
  10409. }
  10410. else {
  10411. this.constants.hierarchicalLayout.enabled = false;
  10412. this.constants.physics.hierarchicalRepulsion.enabeled = false;
  10413. this.constants.physics.barnesHut.enabled = true;
  10414. }
  10415. this._loadSelectedForceSolver();
  10416. this.moving = true;
  10417. this.start();
  10418. }
  10419. function showValueOfRange (id,map,constantsVariableName) {
  10420. var valueId = id + "_value";
  10421. var rangeValue = document.getElementById(id).value;
  10422. if (map instanceof Array) {
  10423. document.getElementById(valueId).value = map[parseInt(rangeValue)];
  10424. this._overWriteGraphConstants(constantsVariableName,map[parseInt(rangeValue)]);
  10425. }
  10426. else {
  10427. document.getElementById(valueId).value = parseInt(map) * parseFloat(rangeValue);
  10428. this._overWriteGraphConstants(constantsVariableName, parseInt(map) * parseFloat(rangeValue));
  10429. }
  10430. if (constantsVariableName == "hierarchicalLayout_direction" ||
  10431. constantsVariableName == "hierarchicalLayout_levelSeparation" ||
  10432. constantsVariableName == "hierarchicalLayout_nodeSpacing") {
  10433. this._setupHierarchicalLayout();
  10434. }
  10435. this.moving = true;
  10436. this.start();
  10437. };
  10438. /**
  10439. * Created by Alex on 2/10/14.
  10440. */
  10441. var hierarchalRepulsionMixin = {
  10442. /**
  10443. * Calculate the forces the nodes apply on eachother based on a repulsion field.
  10444. * This field is linearly approximated.
  10445. *
  10446. * @private
  10447. */
  10448. _calculateNodeForces : function() {
  10449. var dx, dy, distance, fx, fy, combinedClusterSize,
  10450. repulsingForce, node1, node2, i, j;
  10451. var nodes = this.calculationNodes;
  10452. var nodeIndices = this.calculationNodeIndices;
  10453. // approximation constants
  10454. var b = 5;
  10455. var a_base = 0.5*-b;
  10456. // repulsing forces between nodes
  10457. var nodeDistance = this.constants.physics.hierarchicalRepulsion.nodeDistance;
  10458. var minimumDistance = nodeDistance;
  10459. // we loop from i over all but the last entree in the array
  10460. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  10461. for (i = 0; i < nodeIndices.length-1; i++) {
  10462. node1 = nodes[nodeIndices[i]];
  10463. for (j = i+1; j < nodeIndices.length; j++) {
  10464. node2 = nodes[nodeIndices[j]];
  10465. dx = node2.x - node1.x;
  10466. dy = node2.y - node1.y;
  10467. distance = Math.sqrt(dx * dx + dy * dy);
  10468. var a = a_base / minimumDistance;
  10469. if (distance < 2*minimumDistance) {
  10470. repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness))
  10471. // normalize force with
  10472. if (distance == 0) {
  10473. distance = 0.01;
  10474. }
  10475. else {
  10476. repulsingForce = repulsingForce/distance;
  10477. }
  10478. fx = dx * repulsingForce;
  10479. fy = dy * repulsingForce;
  10480. node1.fx -= fx;
  10481. node1.fy -= fy;
  10482. node2.fx += fx;
  10483. node2.fy += fy;
  10484. }
  10485. }
  10486. }
  10487. }
  10488. }
  10489. /**
  10490. * Created by Alex on 2/10/14.
  10491. */
  10492. var barnesHutMixin = {
  10493. /**
  10494. * This function calculates the forces the nodes apply on eachother based on a gravitational model.
  10495. * The Barnes Hut method is used to speed up this N-body simulation.
  10496. *
  10497. * @private
  10498. */
  10499. _calculateNodeForces : function() {
  10500. var node;
  10501. var nodes = this.calculationNodes;
  10502. var nodeIndices = this.calculationNodeIndices;
  10503. var nodeCount = nodeIndices.length;
  10504. this._formBarnesHutTree(nodes,nodeIndices);
  10505. var barnesHutTree = this.barnesHutTree;
  10506. // place the nodes one by one recursively
  10507. for (var i = 0; i < nodeCount; i++) {
  10508. node = nodes[nodeIndices[i]];
  10509. // starting with root is irrelevant, it never passes the BarnesHut condition
  10510. this._getForceContribution(barnesHutTree.root.children.NW,node);
  10511. this._getForceContribution(barnesHutTree.root.children.NE,node);
  10512. this._getForceContribution(barnesHutTree.root.children.SW,node);
  10513. this._getForceContribution(barnesHutTree.root.children.SE,node);
  10514. }
  10515. },
  10516. /**
  10517. * This function traverses the barnesHutTree. It checks when it can approximate distant nodes with their center of mass.
  10518. * If a region contains a single node, we check if it is not itself, then we apply the force.
  10519. *
  10520. * @param parentBranch
  10521. * @param node
  10522. * @private
  10523. */
  10524. _getForceContribution : function(parentBranch,node) {
  10525. // we get no force contribution from an empty region
  10526. if (parentBranch.childrenCount > 0) {
  10527. var dx,dy,distance;
  10528. // get the distance from the center of mass to the node.
  10529. dx = parentBranch.centerOfMass.x - node.x;
  10530. dy = parentBranch.centerOfMass.y - node.y;
  10531. distance = Math.sqrt(dx * dx + dy * dy);
  10532. // BarnesHut condition
  10533. // original condition : s/d < theta = passed === d/s > 1/theta = passed
  10534. // calcSize = 1/s --> d * 1/s > 1/theta = passed
  10535. if (distance * parentBranch.calcSize > this.constants.physics.barnesHut.theta) {
  10536. // duplicate code to reduce function calls to speed up program
  10537. if (distance == 0) {
  10538. distance = 0.1*Math.random();
  10539. dx = distance;
  10540. }
  10541. var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.mass / (distance * distance * distance);
  10542. var fx = dx * gravityForce;
  10543. var fy = dy * gravityForce;
  10544. node.fx += fx;
  10545. node.fy += fy;
  10546. }
  10547. else {
  10548. // Did not pass the condition, go into children if available
  10549. if (parentBranch.childrenCount == 4) {
  10550. this._getForceContribution(parentBranch.children.NW,node);
  10551. this._getForceContribution(parentBranch.children.NE,node);
  10552. this._getForceContribution(parentBranch.children.SW,node);
  10553. this._getForceContribution(parentBranch.children.SE,node);
  10554. }
  10555. else { // parentBranch must have only one node, if it was empty we wouldnt be here
  10556. if (parentBranch.children.data.id != node.id) { // if it is not self
  10557. // duplicate code to reduce function calls to speed up program
  10558. if (distance == 0) {
  10559. distance = 0.5*Math.random();
  10560. dx = distance;
  10561. }
  10562. var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.mass / (distance * distance * distance);
  10563. var fx = dx * gravityForce;
  10564. var fy = dy * gravityForce;
  10565. node.fx += fx;
  10566. node.fy += fy;
  10567. }
  10568. }
  10569. }
  10570. }
  10571. },
  10572. /**
  10573. * This function constructs the barnesHut tree recursively. It creates the root, splits it and starts placing the nodes.
  10574. *
  10575. * @param nodes
  10576. * @param nodeIndices
  10577. * @private
  10578. */
  10579. _formBarnesHutTree : function(nodes,nodeIndices) {
  10580. var node;
  10581. var nodeCount = nodeIndices.length;
  10582. var minX = Number.MAX_VALUE,
  10583. minY = Number.MAX_VALUE,
  10584. maxX =-Number.MAX_VALUE,
  10585. maxY =-Number.MAX_VALUE;
  10586. // get the range of the nodes
  10587. for (var i = 0; i < nodeCount; i++) {
  10588. var x = nodes[nodeIndices[i]].x;
  10589. var y = nodes[nodeIndices[i]].y;
  10590. if (x < minX) { minX = x; }
  10591. if (x > maxX) { maxX = x; }
  10592. if (y < minY) { minY = y; }
  10593. if (y > maxY) { maxY = y; }
  10594. }
  10595. // make the range a square
  10596. var sizeDiff = Math.abs(maxX - minX) - Math.abs(maxY - minY); // difference between X and Y
  10597. if (sizeDiff > 0) {minY -= 0.5 * sizeDiff; maxY += 0.5 * sizeDiff;} // xSize > ySize
  10598. else {minX += 0.5 * sizeDiff; maxX -= 0.5 * sizeDiff;} // xSize < ySize
  10599. var minimumTreeSize = 1e-5;
  10600. var rootSize = Math.max(minimumTreeSize,Math.abs(maxX - minX));
  10601. var halfRootSize = 0.5 * rootSize;
  10602. var centerX = 0.5 * (minX + maxX), centerY = 0.5 * (minY + maxY);
  10603. // construct the barnesHutTree
  10604. var barnesHutTree = {root:{
  10605. centerOfMass:{x:0,y:0}, // Center of Mass
  10606. mass:0,
  10607. range: {minX:centerX-halfRootSize,maxX:centerX+halfRootSize,
  10608. minY:centerY-halfRootSize,maxY:centerY+halfRootSize},
  10609. size: rootSize,
  10610. calcSize: 1 / rootSize,
  10611. children: {data:null},
  10612. maxWidth: 0,
  10613. level: 0,
  10614. childrenCount: 4
  10615. }};
  10616. this._splitBranch(barnesHutTree.root);
  10617. // place the nodes one by one recursively
  10618. for (i = 0; i < nodeCount; i++) {
  10619. node = nodes[nodeIndices[i]];
  10620. this._placeInTree(barnesHutTree.root,node);
  10621. }
  10622. // make global
  10623. this.barnesHutTree = barnesHutTree
  10624. },
  10625. _updateBranchMass : function(parentBranch, node) {
  10626. var totalMass = parentBranch.mass + node.mass;
  10627. var totalMassInv = 1/totalMass;
  10628. parentBranch.centerOfMass.x = parentBranch.centerOfMass.x * parentBranch.mass + node.x * node.mass;
  10629. parentBranch.centerOfMass.x *= totalMassInv;
  10630. parentBranch.centerOfMass.y = parentBranch.centerOfMass.y * parentBranch.mass + node.y * node.mass;
  10631. parentBranch.centerOfMass.y *= totalMassInv;
  10632. parentBranch.mass = totalMass;
  10633. var biggestSize = Math.max(Math.max(node.height,node.radius),node.width);
  10634. parentBranch.maxWidth = (parentBranch.maxWidth < biggestSize) ? biggestSize : parentBranch.maxWidth;
  10635. },
  10636. _placeInTree : function(parentBranch,node,skipMassUpdate) {
  10637. if (skipMassUpdate != true || skipMassUpdate === undefined) {
  10638. // update the mass of the branch.
  10639. this._updateBranchMass(parentBranch,node);
  10640. }
  10641. if (parentBranch.children.NW.range.maxX > node.x) { // in NW or SW
  10642. if (parentBranch.children.NW.range.maxY > node.y) { // in NW
  10643. this._placeInRegion(parentBranch,node,"NW");
  10644. }
  10645. else { // in SW
  10646. this._placeInRegion(parentBranch,node,"SW");
  10647. }
  10648. }
  10649. else { // in NE or SE
  10650. if (parentBranch.children.NW.range.maxY > node.y) { // in NE
  10651. this._placeInRegion(parentBranch,node,"NE");
  10652. }
  10653. else { // in SE
  10654. this._placeInRegion(parentBranch,node,"SE");
  10655. }
  10656. }
  10657. },
  10658. _placeInRegion : function(parentBranch,node,region) {
  10659. switch (parentBranch.children[region].childrenCount) {
  10660. case 0: // place node here
  10661. parentBranch.children[region].children.data = node;
  10662. parentBranch.children[region].childrenCount = 1;
  10663. this._updateBranchMass(parentBranch.children[region],node);
  10664. break;
  10665. case 1: // convert into children
  10666. // if there are two nodes exactly overlapping (on init, on opening of cluster etc.)
  10667. // we move one node a pixel and we do not put it in the tree.
  10668. if (parentBranch.children[region].children.data.x == node.x &&
  10669. parentBranch.children[region].children.data.y == node.y) {
  10670. node.x += Math.random();
  10671. node.y += Math.random();
  10672. this._placeInTree(parentBranch,node, true);
  10673. }
  10674. else {
  10675. this._splitBranch(parentBranch.children[region]);
  10676. this._placeInTree(parentBranch.children[region],node);
  10677. }
  10678. break;
  10679. case 4: // place in branch
  10680. this._placeInTree(parentBranch.children[region],node);
  10681. break;
  10682. }
  10683. },
  10684. /**
  10685. * this function splits a branch into 4 sub branches. If the branch contained a node, we place it in the subbranch
  10686. * after the split is complete.
  10687. *
  10688. * @param parentBranch
  10689. * @private
  10690. */
  10691. _splitBranch : function(parentBranch) {
  10692. // if the branch is filled with a node, replace the node in the new subset.
  10693. var containedNode = null;
  10694. if (parentBranch.childrenCount == 1) {
  10695. containedNode = parentBranch.children.data;
  10696. parentBranch.mass = 0; parentBranch.centerOfMass.x = 0; parentBranch.centerOfMass.y = 0;
  10697. }
  10698. parentBranch.childrenCount = 4;
  10699. parentBranch.children.data = null;
  10700. this._insertRegion(parentBranch,"NW");
  10701. this._insertRegion(parentBranch,"NE");
  10702. this._insertRegion(parentBranch,"SW");
  10703. this._insertRegion(parentBranch,"SE");
  10704. if (containedNode != null) {
  10705. this._placeInTree(parentBranch,containedNode);
  10706. }
  10707. },
  10708. /**
  10709. * This function subdivides the region into four new segments.
  10710. * Specifically, this inserts a single new segment.
  10711. * It fills the children section of the parentBranch
  10712. *
  10713. * @param parentBranch
  10714. * @param region
  10715. * @param parentRange
  10716. * @private
  10717. */
  10718. _insertRegion : function(parentBranch, region) {
  10719. var minX,maxX,minY,maxY;
  10720. var childSize = 0.5 * parentBranch.size;
  10721. switch (region) {
  10722. case "NW":
  10723. minX = parentBranch.range.minX;
  10724. maxX = parentBranch.range.minX + childSize;
  10725. minY = parentBranch.range.minY;
  10726. maxY = parentBranch.range.minY + childSize;
  10727. break;
  10728. case "NE":
  10729. minX = parentBranch.range.minX + childSize;
  10730. maxX = parentBranch.range.maxX;
  10731. minY = parentBranch.range.minY;
  10732. maxY = parentBranch.range.minY + childSize;
  10733. break;
  10734. case "SW":
  10735. minX = parentBranch.range.minX;
  10736. maxX = parentBranch.range.minX + childSize;
  10737. minY = parentBranch.range.minY + childSize;
  10738. maxY = parentBranch.range.maxY;
  10739. break;
  10740. case "SE":
  10741. minX = parentBranch.range.minX + childSize;
  10742. maxX = parentBranch.range.maxX;
  10743. minY = parentBranch.range.minY + childSize;
  10744. maxY = parentBranch.range.maxY;
  10745. break;
  10746. }
  10747. parentBranch.children[region] = {
  10748. centerOfMass:{x:0,y:0},
  10749. mass:0,
  10750. range:{minX:minX,maxX:maxX,minY:minY,maxY:maxY},
  10751. size: 0.5 * parentBranch.size,
  10752. calcSize: 2 * parentBranch.calcSize,
  10753. children: {data:null},
  10754. maxWidth: 0,
  10755. level: parentBranch.level+1,
  10756. childrenCount: 0
  10757. };
  10758. },
  10759. /**
  10760. * This function is for debugging purposed, it draws the tree.
  10761. *
  10762. * @param ctx
  10763. * @param color
  10764. * @private
  10765. */
  10766. _drawTree : function(ctx,color) {
  10767. if (this.barnesHutTree !== undefined) {
  10768. ctx.lineWidth = 1;
  10769. this._drawBranch(this.barnesHutTree.root,ctx,color);
  10770. }
  10771. },
  10772. /**
  10773. * This function is for debugging purposes. It draws the branches recursively.
  10774. *
  10775. * @param branch
  10776. * @param ctx
  10777. * @param color
  10778. * @private
  10779. */
  10780. _drawBranch : function(branch,ctx,color) {
  10781. if (color === undefined) {
  10782. color = "#FF0000";
  10783. }
  10784. if (branch.childrenCount == 4) {
  10785. this._drawBranch(branch.children.NW,ctx);
  10786. this._drawBranch(branch.children.NE,ctx);
  10787. this._drawBranch(branch.children.SE,ctx);
  10788. this._drawBranch(branch.children.SW,ctx);
  10789. }
  10790. ctx.strokeStyle = color;
  10791. ctx.beginPath();
  10792. ctx.moveTo(branch.range.minX,branch.range.minY);
  10793. ctx.lineTo(branch.range.maxX,branch.range.minY);
  10794. ctx.stroke();
  10795. ctx.beginPath();
  10796. ctx.moveTo(branch.range.maxX,branch.range.minY);
  10797. ctx.lineTo(branch.range.maxX,branch.range.maxY);
  10798. ctx.stroke();
  10799. ctx.beginPath();
  10800. ctx.moveTo(branch.range.maxX,branch.range.maxY);
  10801. ctx.lineTo(branch.range.minX,branch.range.maxY);
  10802. ctx.stroke();
  10803. ctx.beginPath();
  10804. ctx.moveTo(branch.range.minX,branch.range.maxY);
  10805. ctx.lineTo(branch.range.minX,branch.range.minY);
  10806. ctx.stroke();
  10807. /*
  10808. if (branch.mass > 0) {
  10809. ctx.circle(branch.centerOfMass.x, branch.centerOfMass.y, 3*branch.mass);
  10810. ctx.stroke();
  10811. }
  10812. */
  10813. }
  10814. };
  10815. /**
  10816. * Created by Alex on 2/10/14.
  10817. */
  10818. var repulsionMixin = {
  10819. /**
  10820. * Calculate the forces the nodes apply on eachother based on a repulsion field.
  10821. * This field is linearly approximated.
  10822. *
  10823. * @private
  10824. */
  10825. _calculateNodeForces : function() {
  10826. var dx, dy, angle, distance, fx, fy, combinedClusterSize,
  10827. repulsingForce, node1, node2, i, j;
  10828. var nodes = this.calculationNodes;
  10829. var nodeIndices = this.calculationNodeIndices;
  10830. // approximation constants
  10831. var a_base = -2/3;
  10832. var b = 4/3;
  10833. // repulsing forces between nodes
  10834. var nodeDistance = this.constants.physics.repulsion.nodeDistance;
  10835. var minimumDistance = nodeDistance;
  10836. // we loop from i over all but the last entree in the array
  10837. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  10838. for (i = 0; i < nodeIndices.length-1; i++) {
  10839. node1 = nodes[nodeIndices[i]];
  10840. for (j = i+1; j < nodeIndices.length; j++) {
  10841. node2 = nodes[nodeIndices[j]];
  10842. combinedClusterSize = node1.clusterSize + node2.clusterSize - 2;
  10843. dx = node2.x - node1.x;
  10844. dy = node2.y - node1.y;
  10845. distance = Math.sqrt(dx * dx + dy * dy);
  10846. minimumDistance = (combinedClusterSize == 0) ? nodeDistance : (nodeDistance * (1 + combinedClusterSize * this.constants.clustering.distanceAmplification));
  10847. var a = a_base / minimumDistance;
  10848. if (distance < 2*minimumDistance) {
  10849. if (distance < 0.5*minimumDistance) {
  10850. repulsingForce = 1.0;
  10851. }
  10852. else {
  10853. repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness))
  10854. }
  10855. // amplify the repulsion for clusters.
  10856. repulsingForce *= (combinedClusterSize == 0) ? 1 : 1 + combinedClusterSize * this.constants.clustering.forceAmplification;
  10857. repulsingForce = repulsingForce/distance;
  10858. fx = dx * repulsingForce;
  10859. fy = dy * repulsingForce;
  10860. node1.fx -= fx;
  10861. node1.fy -= fy;
  10862. node2.fx += fx;
  10863. node2.fy += fy;
  10864. }
  10865. }
  10866. }
  10867. }
  10868. }
  10869. var HierarchicalLayoutMixin = {
  10870. /**
  10871. * This is the main function to layout the nodes in a hierarchical way.
  10872. * It checks if the node details are supplied correctly
  10873. *
  10874. * @private
  10875. */
  10876. _setupHierarchicalLayout : function() {
  10877. if (this.constants.hierarchicalLayout.enabled == true) {
  10878. if (this.constants.hierarchicalLayout.direction == "RL" || this.constants.hierarchicalLayout.direction == "DU") {
  10879. this.constants.hierarchicalLayout.levelSeparation *= -1;
  10880. }
  10881. else {
  10882. this.constants.hierarchicalLayout.levelSeparation = Math.abs(this.constants.hierarchicalLayout.levelSeparation);
  10883. }
  10884. // get the size of the largest hubs and check if the user has defined a level for a node.
  10885. var hubsize = 0;
  10886. var node, nodeId;
  10887. var definedLevel = false;
  10888. var undefinedLevel = false;
  10889. for (nodeId in this.nodes) {
  10890. if (this.nodes.hasOwnProperty(nodeId)) {
  10891. node = this.nodes[nodeId];
  10892. if (node.level != -1) {
  10893. definedLevel = true;
  10894. }
  10895. else {
  10896. undefinedLevel = true;
  10897. }
  10898. if (hubsize < node.edges.length) {
  10899. hubsize = node.edges.length;
  10900. }
  10901. }
  10902. }
  10903. // if the user defined some levels but not all, alert and run without hierarchical layout
  10904. if (undefinedLevel == true && definedLevel == true) {
  10905. alert("To use the hierarchical layout, nodes require either no predefined levels or levels have to be defined for all nodes.")
  10906. this.zoomExtent(true,this.constants.clustering.enabled);
  10907. if (!this.constants.clustering.enabled) {
  10908. this.start();
  10909. }
  10910. }
  10911. else {
  10912. // setup the system to use hierarchical method.
  10913. this._changeConstants();
  10914. // define levels if undefined by the users. Based on hubsize
  10915. if (undefinedLevel == true) {
  10916. this._determineLevels(hubsize);
  10917. }
  10918. // check the distribution of the nodes per level.
  10919. var distribution = this._getDistribution();
  10920. // place the nodes on the canvas. This also stablilizes the system.
  10921. this._placeNodesByHierarchy(distribution);
  10922. // start the simulation.
  10923. this.start();
  10924. }
  10925. }
  10926. },
  10927. /**
  10928. * This function places the nodes on the canvas based on the hierarchial distribution.
  10929. *
  10930. * @param {Object} distribution | obtained by the function this._getDistribution()
  10931. * @private
  10932. */
  10933. _placeNodesByHierarchy : function(distribution) {
  10934. var nodeId, node;
  10935. // start placing all the level 0 nodes first. Then recursively position their branches.
  10936. for (nodeId in distribution[0].nodes) {
  10937. if (distribution[0].nodes.hasOwnProperty(nodeId)) {
  10938. node = distribution[0].nodes[nodeId];
  10939. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  10940. if (node.xFixed) {
  10941. node.x = distribution[0].minPos;
  10942. node.xFixed = false;
  10943. distribution[0].minPos += distribution[0].nodeSpacing;
  10944. }
  10945. }
  10946. else {
  10947. if (node.yFixed) {
  10948. node.y = distribution[0].minPos;
  10949. node.yFixed = false;
  10950. distribution[0].minPos += distribution[0].nodeSpacing;
  10951. }
  10952. }
  10953. this._placeBranchNodes(node.edges,node.id,distribution,node.level);
  10954. }
  10955. }
  10956. // stabilize the system after positioning. This function calls zoomExtent.
  10957. this._stabilize();
  10958. },
  10959. /**
  10960. * This function get the distribution of levels based on hubsize
  10961. *
  10962. * @returns {Object}
  10963. * @private
  10964. */
  10965. _getDistribution : function() {
  10966. var distribution = {};
  10967. var nodeId, node;
  10968. // we fix Y because the hierarchy is vertical, we fix X so we do not give a node an x position for a second time.
  10969. // the fix of X is removed after the x value has been set.
  10970. for (nodeId in this.nodes) {
  10971. if (this.nodes.hasOwnProperty(nodeId)) {
  10972. node = this.nodes[nodeId];
  10973. node.xFixed = true;
  10974. node.yFixed = true;
  10975. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  10976. node.y = this.constants.hierarchicalLayout.levelSeparation*node.level;
  10977. }
  10978. else {
  10979. node.x = this.constants.hierarchicalLayout.levelSeparation*node.level;
  10980. }
  10981. if (!distribution.hasOwnProperty(node.level)) {
  10982. distribution[node.level] = {amount: 0, nodes: {}, minPos:0, nodeSpacing:0};
  10983. }
  10984. distribution[node.level].amount += 1;
  10985. distribution[node.level].nodes[node.id] = node;
  10986. }
  10987. }
  10988. // determine the largest amount of nodes of all levels
  10989. var maxCount = 0;
  10990. for (var level in distribution) {
  10991. if (distribution.hasOwnProperty(level)) {
  10992. if (maxCount < distribution[level].amount) {
  10993. maxCount = distribution[level].amount;
  10994. }
  10995. }
  10996. }
  10997. // set the initial position and spacing of each nodes accordingly
  10998. for (var level in distribution) {
  10999. if (distribution.hasOwnProperty(level)) {
  11000. distribution[level].nodeSpacing = (maxCount + 1) * this.constants.hierarchicalLayout.nodeSpacing;
  11001. distribution[level].nodeSpacing /= (distribution[level].amount + 1);
  11002. distribution[level].minPos = distribution[level].nodeSpacing - (0.5 * (distribution[level].amount + 1) * distribution[level].nodeSpacing);
  11003. }
  11004. }
  11005. return distribution;
  11006. },
  11007. /**
  11008. * this function allocates nodes in levels based on the recursive branching from the largest hubs.
  11009. *
  11010. * @param hubsize
  11011. * @private
  11012. */
  11013. _determineLevels : function(hubsize) {
  11014. var nodeId, node;
  11015. // determine hubs
  11016. for (nodeId in this.nodes) {
  11017. if (this.nodes.hasOwnProperty(nodeId)) {
  11018. node = this.nodes[nodeId];
  11019. if (node.edges.length == hubsize) {
  11020. node.level = 0;
  11021. }
  11022. }
  11023. }
  11024. // branch from hubs
  11025. for (nodeId in this.nodes) {
  11026. if (this.nodes.hasOwnProperty(nodeId)) {
  11027. node = this.nodes[nodeId];
  11028. if (node.level == 0) {
  11029. this._setLevel(1,node.edges,node.id);
  11030. }
  11031. }
  11032. }
  11033. },
  11034. /**
  11035. * Since hierarchical layout does not support:
  11036. * - smooth curves (based on the physics),
  11037. * - clustering (based on dynamic node counts)
  11038. *
  11039. * We disable both features so there will be no problems.
  11040. *
  11041. * @private
  11042. */
  11043. _changeConstants : function() {
  11044. this.constants.clustering.enabled = false;
  11045. this.constants.physics.barnesHut.enabled = false;
  11046. this.constants.physics.hierarchicalRepulsion.enabled = true;
  11047. this._loadSelectedForceSolver();
  11048. this.constants.smoothCurves = false;
  11049. this._configureSmoothCurves();
  11050. },
  11051. /**
  11052. * This is a recursively called function to enumerate the branches from the largest hubs and place the nodes
  11053. * on a X position that ensures there will be no overlap.
  11054. *
  11055. * @param edges
  11056. * @param parentId
  11057. * @param distribution
  11058. * @param parentLevel
  11059. * @private
  11060. */
  11061. _placeBranchNodes : function(edges, parentId, distribution, parentLevel) {
  11062. for (var i = 0; i < edges.length; i++) {
  11063. var childNode = null;
  11064. if (edges[i].toId == parentId) {
  11065. childNode = edges[i].from;
  11066. }
  11067. else {
  11068. childNode = edges[i].to;
  11069. }
  11070. // if a node is conneceted to another node on the same level (or higher (means lower level))!, this is not handled here.
  11071. var nodeMoved = false;
  11072. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  11073. if (childNode.xFixed && childNode.level > parentLevel) {
  11074. childNode.xFixed = false;
  11075. childNode.x = distribution[childNode.level].minPos;
  11076. nodeMoved = true;
  11077. }
  11078. }
  11079. else {
  11080. if (childNode.yFixed && childNode.level > parentLevel) {
  11081. childNode.yFixed = false;
  11082. childNode.y = distribution[childNode.level].minPos;
  11083. nodeMoved = true;
  11084. }
  11085. }
  11086. if (nodeMoved == true) {
  11087. distribution[childNode.level].minPos += distribution[childNode.level].nodeSpacing;
  11088. if (childNode.edges.length > 1) {
  11089. this._placeBranchNodes(childNode.edges,childNode.id,distribution,childNode.level);
  11090. }
  11091. }
  11092. }
  11093. },
  11094. /**
  11095. * this function is called recursively to enumerate the barnches of the largest hubs and give each node a level.
  11096. *
  11097. * @param level
  11098. * @param edges
  11099. * @param parentId
  11100. * @private
  11101. */
  11102. _setLevel : function(level, edges, parentId) {
  11103. for (var i = 0; i < edges.length; i++) {
  11104. var childNode = null;
  11105. if (edges[i].toId == parentId) {
  11106. childNode = edges[i].from;
  11107. }
  11108. else {
  11109. childNode = edges[i].to;
  11110. }
  11111. if (childNode.level == -1 || childNode.level > level) {
  11112. childNode.level = level;
  11113. if (edges.length > 1) {
  11114. this._setLevel(level+1, childNode.edges, childNode.id);
  11115. }
  11116. }
  11117. }
  11118. },
  11119. /**
  11120. * Unfix nodes
  11121. *
  11122. * @private
  11123. */
  11124. _restoreNodes : function() {
  11125. for (nodeId in this.nodes) {
  11126. if (this.nodes.hasOwnProperty(nodeId)) {
  11127. this.nodes[nodeId].xFixed = false;
  11128. this.nodes[nodeId].yFixed = false;
  11129. }
  11130. }
  11131. }
  11132. };
  11133. /**
  11134. * Created by Alex on 2/4/14.
  11135. */
  11136. var manipulationMixin = {
  11137. /**
  11138. * clears the toolbar div element of children
  11139. *
  11140. * @private
  11141. */
  11142. _clearManipulatorBar : function() {
  11143. while (this.manipulationDiv.hasChildNodes()) {
  11144. this.manipulationDiv.removeChild(this.manipulationDiv.firstChild);
  11145. }
  11146. },
  11147. /**
  11148. * Manipulation UI temporarily overloads certain functions to extend or replace them. To be able to restore
  11149. * these functions to their original functionality, we saved them in this.cachedFunctions.
  11150. * This function restores these functions to their original function.
  11151. *
  11152. * @private
  11153. */
  11154. _restoreOverloadedFunctions : function() {
  11155. for (var functionName in this.cachedFunctions) {
  11156. if (this.cachedFunctions.hasOwnProperty(functionName)) {
  11157. this[functionName] = this.cachedFunctions[functionName];
  11158. }
  11159. }
  11160. },
  11161. /**
  11162. * Enable or disable edit-mode.
  11163. *
  11164. * @private
  11165. */
  11166. _toggleEditMode : function() {
  11167. this.editMode = !this.editMode;
  11168. var toolbar = document.getElementById("graph-manipulationDiv");
  11169. var closeDiv = document.getElementById("graph-manipulation-closeDiv");
  11170. var editModeDiv = document.getElementById("graph-manipulation-editMode");
  11171. if (this.editMode == true) {
  11172. toolbar.style.display="block";
  11173. closeDiv.style.display="block";
  11174. editModeDiv.style.display="none";
  11175. closeDiv.onclick = this._toggleEditMode.bind(this);
  11176. }
  11177. else {
  11178. toolbar.style.display="none";
  11179. closeDiv.style.display="none";
  11180. editModeDiv.style.display="block";
  11181. closeDiv.onclick = null;
  11182. }
  11183. this._createManipulatorBar()
  11184. },
  11185. /**
  11186. * main function, creates the main toolbar. Removes functions bound to the select event. Binds all the buttons of the toolbar.
  11187. *
  11188. * @private
  11189. */
  11190. _createManipulatorBar : function() {
  11191. // remove bound functions
  11192. if (this.boundFunction) {
  11193. this.off('select', this.boundFunction);
  11194. }
  11195. // restore overloaded functions
  11196. this._restoreOverloadedFunctions();
  11197. // resume calculation
  11198. this.freezeSimulation = false;
  11199. // reset global variables
  11200. this.blockConnectingEdgeSelection = false;
  11201. this.forceAppendSelection = false
  11202. if (this.editMode == true) {
  11203. while (this.manipulationDiv.hasChildNodes()) {
  11204. this.manipulationDiv.removeChild(this.manipulationDiv.firstChild);
  11205. }
  11206. // add the icons to the manipulator div
  11207. this.manipulationDiv.innerHTML = "" +
  11208. "<span class='graph-manipulationUI add' id='graph-manipulate-addNode'>" +
  11209. "<span class='graph-manipulationLabel'>Add Node</span></span>" +
  11210. "<div class='graph-seperatorLine'></div>" +
  11211. "<span class='graph-manipulationUI connect' id='graph-manipulate-connectNode'>" +
  11212. "<span class='graph-manipulationLabel'>Add Link</span></span>";
  11213. if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
  11214. this.manipulationDiv.innerHTML += "" +
  11215. "<div class='graph-seperatorLine'></div>" +
  11216. "<span class='graph-manipulationUI edit' id='graph-manipulate-editNode'>" +
  11217. "<span class='graph-manipulationLabel'>Edit Node</span></span>";
  11218. }
  11219. if (this._selectionIsEmpty() == false) {
  11220. this.manipulationDiv.innerHTML += "" +
  11221. "<div class='graph-seperatorLine'></div>" +
  11222. "<span class='graph-manipulationUI delete' id='graph-manipulate-delete'>" +
  11223. "<span class='graph-manipulationLabel'>Delete selected</span></span>";
  11224. }
  11225. // bind the icons
  11226. var addNodeButton = document.getElementById("graph-manipulate-addNode");
  11227. addNodeButton.onclick = this._createAddNodeToolbar.bind(this);
  11228. var addEdgeButton = document.getElementById("graph-manipulate-connectNode");
  11229. addEdgeButton.onclick = this._createAddEdgeToolbar.bind(this);
  11230. if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
  11231. var editButton = document.getElementById("graph-manipulate-editNode");
  11232. editButton.onclick = this._editNode.bind(this);
  11233. }
  11234. if (this._selectionIsEmpty() == false) {
  11235. var deleteButton = document.getElementById("graph-manipulate-delete");
  11236. deleteButton.onclick = this._deleteSelected.bind(this);
  11237. }
  11238. var closeDiv = document.getElementById("graph-manipulation-closeDiv");
  11239. closeDiv.onclick = this._toggleEditMode.bind(this);
  11240. this.boundFunction = this._createManipulatorBar.bind(this);
  11241. this.on('select', this.boundFunction);
  11242. }
  11243. else {
  11244. this.editModeDiv.innerHTML = "" +
  11245. "<span class='graph-manipulationUI edit editmode' id='graph-manipulate-editModeButton'>" +
  11246. "<span class='graph-manipulationLabel'>Edit</span></span>"
  11247. var editModeButton = document.getElementById("graph-manipulate-editModeButton");
  11248. editModeButton.onclick = this._toggleEditMode.bind(this);
  11249. }
  11250. },
  11251. /**
  11252. * Create the toolbar for adding Nodes
  11253. *
  11254. * @private
  11255. */
  11256. _createAddNodeToolbar : function() {
  11257. // clear the toolbar
  11258. this._clearManipulatorBar();
  11259. if (this.boundFunction) {
  11260. this.off('select', this.boundFunction);
  11261. }
  11262. // create the toolbar contents
  11263. this.manipulationDiv.innerHTML = "" +
  11264. "<span class='graph-manipulationUI back' id='graph-manipulate-back'>" +
  11265. "<span class='graph-manipulationLabel'>Back</span></span>" +
  11266. "<div class='graph-seperatorLine'></div>" +
  11267. "<span class='graph-manipulationUI none' id='graph-manipulate-back'>" +
  11268. "<span class='graph-manipulationLabel'>Click in an empty space to place a new node</span></span>";
  11269. // bind the icon
  11270. var backButton = document.getElementById("graph-manipulate-back");
  11271. backButton.onclick = this._createManipulatorBar.bind(this);
  11272. // we use the boundFunction so we can reference it when we unbind it from the "select" event.
  11273. this.boundFunction = this._addNode.bind(this);
  11274. this.on('select', this.boundFunction);
  11275. },
  11276. /**
  11277. * create the toolbar to connect nodes
  11278. *
  11279. * @private
  11280. */
  11281. _createAddEdgeToolbar : function() {
  11282. // clear the toolbar
  11283. this._clearManipulatorBar();
  11284. this._unselectAll(true);
  11285. this.freezeSimulation = true;
  11286. if (this.boundFunction) {
  11287. this.off('select', this.boundFunction);
  11288. }
  11289. this._unselectAll();
  11290. this.forceAppendSelection = false;
  11291. this.blockConnectingEdgeSelection = true;
  11292. this.manipulationDiv.innerHTML = "" +
  11293. "<span class='graph-manipulationUI back' id='graph-manipulate-back'>" +
  11294. "<span class='graph-manipulationLabel'>Back</span></span>" +
  11295. "<div class='graph-seperatorLine'></div>" +
  11296. "<span class='graph-manipulationUI none' id='graph-manipulate-back'>" +
  11297. "<span id='graph-manipulatorLabel' class='graph-manipulationLabel'>Click on a node and drag the edge to another node to connect them.</span></span>";
  11298. // bind the icon
  11299. var backButton = document.getElementById("graph-manipulate-back");
  11300. backButton.onclick = this._createManipulatorBar.bind(this);
  11301. // we use the boundFunction so we can reference it when we unbind it from the "select" event.
  11302. this.boundFunction = this._handleConnect.bind(this);
  11303. this.on('select', this.boundFunction);
  11304. // temporarily overload functions
  11305. this.cachedFunctions["_handleTouch"] = this._handleTouch;
  11306. this.cachedFunctions["_handleOnRelease"] = this._handleOnRelease;
  11307. this._handleTouch = this._handleConnect;
  11308. this._handleOnRelease = this._finishConnect;
  11309. // redraw to show the unselect
  11310. this._redraw();
  11311. },
  11312. /**
  11313. * the function bound to the selection event. It checks if you want to connect a cluster and changes the description
  11314. * to walk the user through the process.
  11315. *
  11316. * @private
  11317. */
  11318. _handleConnect : function(pointer) {
  11319. if (this._getSelectedNodeCount() == 0) {
  11320. var node = this._getNodeAt(pointer);
  11321. if (node != null) {
  11322. if (node.clusterSize > 1) {
  11323. alert("Cannot create edges to a cluster.")
  11324. }
  11325. else {
  11326. this._selectObject(node,false);
  11327. // create a node the temporary line can look at
  11328. this.sectors['support']['nodes']['targetNode'] = new Node({id:'targetNode'},{},{},this.constants);
  11329. this.sectors['support']['nodes']['targetNode'].x = node.x;
  11330. this.sectors['support']['nodes']['targetNode'].y = node.y;
  11331. this.sectors['support']['nodes']['targetViaNode'] = new Node({id:'targetViaNode'},{},{},this.constants);
  11332. this.sectors['support']['nodes']['targetViaNode'].x = node.x;
  11333. this.sectors['support']['nodes']['targetViaNode'].y = node.y;
  11334. this.sectors['support']['nodes']['targetViaNode'].parentEdgeId = "connectionEdge";
  11335. // create a temporary edge
  11336. this.edges['connectionEdge'] = new Edge({id:"connectionEdge",from:node.id,to:this.sectors['support']['nodes']['targetNode'].id}, this, this.constants);
  11337. this.edges['connectionEdge'].from = node;
  11338. this.edges['connectionEdge'].connected = true;
  11339. this.edges['connectionEdge'].smooth = true;
  11340. this.edges['connectionEdge'].selected = true;
  11341. this.edges['connectionEdge'].to = this.sectors['support']['nodes']['targetNode'];
  11342. this.edges['connectionEdge'].via = this.sectors['support']['nodes']['targetViaNode'];
  11343. this.cachedFunctions["_handleOnDrag"] = this._handleOnDrag;
  11344. this._handleOnDrag = function(event) {
  11345. var pointer = this._getPointer(event.gesture.center);
  11346. this.sectors['support']['nodes']['targetNode'].x = this._canvasToX(pointer.x);
  11347. this.sectors['support']['nodes']['targetNode'].y = this._canvasToY(pointer.y);
  11348. this.sectors['support']['nodes']['targetViaNode'].x = 0.5 * (this._canvasToX(pointer.x) + this.edges['connectionEdge'].from.x);
  11349. this.sectors['support']['nodes']['targetViaNode'].y = this._canvasToY(pointer.y);
  11350. };
  11351. this.moving = true;
  11352. this.start();
  11353. }
  11354. }
  11355. }
  11356. },
  11357. _finishConnect : function(pointer) {
  11358. if (this._getSelectedNodeCount() == 1) {
  11359. // restore the drag function
  11360. this._handleOnDrag = this.cachedFunctions["_handleOnDrag"];
  11361. delete this.cachedFunctions["_handleOnDrag"];
  11362. // remember the edge id
  11363. var connectFromId = this.edges['connectionEdge'].fromId;
  11364. // remove the temporary nodes and edge
  11365. delete this.edges['connectionEdge']
  11366. delete this.sectors['support']['nodes']['targetNode'];
  11367. delete this.sectors['support']['nodes']['targetViaNode'];
  11368. var node = this._getNodeAt(pointer);
  11369. if (node != null) {
  11370. if (node.clusterSize > 1) {
  11371. alert("Cannot create edges to a cluster.")
  11372. }
  11373. else {
  11374. this._createEdge(connectFromId,node.id);
  11375. this._createManipulatorBar();
  11376. }
  11377. }
  11378. this._unselectAll();
  11379. }
  11380. },
  11381. /**
  11382. * Adds a node on the specified location
  11383. *
  11384. * @param {Object} pointer
  11385. */
  11386. _addNode : function() {
  11387. if (this._selectionIsEmpty() && this.editMode == true) {
  11388. var positionObject = this._pointerToPositionObject(this.pointerPosition);
  11389. var defaultData = {id:util.randomUUID(),x:positionObject.left,y:positionObject.top,label:"new",allowedToMoveX:true,allowedToMoveY:true};
  11390. if (this.triggerFunctions.add) {
  11391. if (this.triggerFunctions.add.length == 2) {
  11392. var me = this;
  11393. this.triggerFunctions.add(defaultData, function(finalizedData) {
  11394. me.createNodeOnClick = true;
  11395. me.nodesData.add(finalizedData);
  11396. me.createNodeOnClick = false;
  11397. me._createManipulatorBar();
  11398. me.moving = true;
  11399. me.start();
  11400. });
  11401. }
  11402. else {
  11403. alert("The function for add does not support two arguments (data,callback).");
  11404. this._createManipulatorBar();
  11405. this.moving = true;
  11406. this.start();
  11407. }
  11408. }
  11409. else {
  11410. this.createNodeOnClick = true;
  11411. this.nodesData.add(defaultData);
  11412. this.createNodeOnClick = false;
  11413. this._createManipulatorBar();
  11414. this.moving = true;
  11415. this.start();
  11416. }
  11417. }
  11418. },
  11419. /**
  11420. * connect two nodes with a new edge.
  11421. *
  11422. * @private
  11423. */
  11424. _createEdge : function(sourceNodeId,targetNodeId) {
  11425. if (this.editMode == true) {
  11426. var defaultData = {from:sourceNodeId, to:targetNodeId};
  11427. if (this.triggerFunctions.connect) {
  11428. if (this.triggerFunctions.connect.length == 2) {
  11429. var me = this;
  11430. this.triggerFunctions.connect(defaultData, function(finalizedData) {
  11431. me.edgesData.add(finalizedData)
  11432. me.moving = true;
  11433. me.start();
  11434. });
  11435. }
  11436. else {
  11437. alert("The function for connect does not support two arguments (data,callback).");
  11438. this.moving = true;
  11439. this.start();
  11440. }
  11441. }
  11442. else {
  11443. this.edgesData.add(defaultData)
  11444. this.moving = true;
  11445. this.start();
  11446. }
  11447. }
  11448. },
  11449. /**
  11450. * Create the toolbar to edit the selected node. The label and the color can be changed. Other colors are derived from the chosen color.
  11451. *
  11452. * @private
  11453. */
  11454. _editNode : function() {
  11455. if (this.triggerFunctions.edit && this.editMode == true) {
  11456. var node = this._getSelectedNode();
  11457. var data = {id:node.id,
  11458. label: node.label,
  11459. group: node.group,
  11460. shape: node.shape,
  11461. color: {
  11462. background:node.color.background,
  11463. border:node.color.border,
  11464. highlight: {
  11465. background:node.color.highlight.background,
  11466. border:node.color.highlight.border
  11467. }
  11468. }};
  11469. if (this.triggerFunctions.edit.length == 2) {
  11470. var me = this;
  11471. this.triggerFunctions.edit(data, function (finalizedData) {
  11472. me.nodesData.update(finalizedData);
  11473. me._createManipulatorBar();
  11474. me.moving = true;
  11475. me.start();
  11476. });
  11477. }
  11478. else {
  11479. alert("The function for edit does not support two arguments (data, callback).")
  11480. }
  11481. }
  11482. else {
  11483. alert("No edit function has been bound to this button.")
  11484. }
  11485. },
  11486. /**
  11487. * delete everything in the selection
  11488. *
  11489. * @private
  11490. */
  11491. _deleteSelected : function() {
  11492. if (!this._selectionIsEmpty() && this.editMode == true) {
  11493. if (!this._clusterInSelection()) {
  11494. var selectedNodes = this.getSelectedNodes();
  11495. var selectedEdges = this.getSelectedEdges();
  11496. if (this.triggerFunctions.delete) {
  11497. var me = this;
  11498. var data = {nodes: selectedNodes, edges: selectedEdges};
  11499. if (this.triggerFunctions.delete.length = 2) {
  11500. this.triggerFunctions.delete(data, function (finalizedData) {
  11501. me.edgesData.remove(finalizedData.edges);
  11502. me.nodesData.remove(finalizedData.nodes);
  11503. this._unselectAll();
  11504. me.moving = true;
  11505. me.start();
  11506. });
  11507. }
  11508. else {
  11509. alert("The function for edit does not support two arguments (data, callback).")
  11510. }
  11511. }
  11512. else {
  11513. this.edgesData.remove(selectedEdges);
  11514. this.nodesData.remove(selectedNodes);
  11515. this._unselectAll();
  11516. this.moving = true;
  11517. this.start();
  11518. }
  11519. }
  11520. else {
  11521. alert("Clusters cannot be deleted.");
  11522. }
  11523. }
  11524. }
  11525. };
  11526. /**
  11527. * Creation of the SectorMixin var.
  11528. *
  11529. * This contains all the functions the Graph object can use to employ the sector system.
  11530. * The sector system is always used by Graph, though the benefits only apply to the use of clustering.
  11531. * If clustering is not used, there is no overhead except for a duplicate object with references to nodes and edges.
  11532. *
  11533. * Alex de Mulder
  11534. * 21-01-2013
  11535. */
  11536. var SectorMixin = {
  11537. /**
  11538. * This function is only called by the setData function of the Graph object.
  11539. * This loads the global references into the active sector. This initializes the sector.
  11540. *
  11541. * @private
  11542. */
  11543. _putDataInSector : function() {
  11544. this.sectors["active"][this._sector()].nodes = this.nodes;
  11545. this.sectors["active"][this._sector()].edges = this.edges;
  11546. this.sectors["active"][this._sector()].nodeIndices = this.nodeIndices;
  11547. },
  11548. /**
  11549. * /**
  11550. * This function sets the global references to nodes, edges and nodeIndices back to
  11551. * those of the supplied (active) sector. If a type is defined, do the specific type
  11552. *
  11553. * @param {String} sectorId
  11554. * @param {String} [sectorType] | "active" or "frozen"
  11555. * @private
  11556. */
  11557. _switchToSector : function(sectorId, sectorType) {
  11558. if (sectorType === undefined || sectorType == "active") {
  11559. this._switchToActiveSector(sectorId);
  11560. }
  11561. else {
  11562. this._switchToFrozenSector(sectorId);
  11563. }
  11564. },
  11565. /**
  11566. * This function sets the global references to nodes, edges and nodeIndices back to
  11567. * those of the supplied active sector.
  11568. *
  11569. * @param sectorId
  11570. * @private
  11571. */
  11572. _switchToActiveSector : function(sectorId) {
  11573. this.nodeIndices = this.sectors["active"][sectorId]["nodeIndices"];
  11574. this.nodes = this.sectors["active"][sectorId]["nodes"];
  11575. this.edges = this.sectors["active"][sectorId]["edges"];
  11576. },
  11577. /**
  11578. * This function sets the global references to nodes, edges and nodeIndices back to
  11579. * those of the supplied active sector.
  11580. *
  11581. * @param sectorId
  11582. * @private
  11583. */
  11584. _switchToSupportSector : function() {
  11585. this.nodeIndices = this.sectors["support"]["nodeIndices"];
  11586. this.nodes = this.sectors["support"]["nodes"];
  11587. this.edges = this.sectors["support"]["edges"];
  11588. },
  11589. /**
  11590. * This function sets the global references to nodes, edges and nodeIndices back to
  11591. * those of the supplied frozen sector.
  11592. *
  11593. * @param sectorId
  11594. * @private
  11595. */
  11596. _switchToFrozenSector : function(sectorId) {
  11597. this.nodeIndices = this.sectors["frozen"][sectorId]["nodeIndices"];
  11598. this.nodes = this.sectors["frozen"][sectorId]["nodes"];
  11599. this.edges = this.sectors["frozen"][sectorId]["edges"];
  11600. },
  11601. /**
  11602. * This function sets the global references to nodes, edges and nodeIndices back to
  11603. * those of the currently active sector.
  11604. *
  11605. * @private
  11606. */
  11607. _loadLatestSector : function() {
  11608. this._switchToSector(this._sector());
  11609. },
  11610. /**
  11611. * This function returns the currently active sector Id
  11612. *
  11613. * @returns {String}
  11614. * @private
  11615. */
  11616. _sector : function() {
  11617. return this.activeSector[this.activeSector.length-1];
  11618. },
  11619. /**
  11620. * This function returns the previously active sector Id
  11621. *
  11622. * @returns {String}
  11623. * @private
  11624. */
  11625. _previousSector : function() {
  11626. if (this.activeSector.length > 1) {
  11627. return this.activeSector[this.activeSector.length-2];
  11628. }
  11629. else {
  11630. throw new TypeError('there are not enough sectors in the this.activeSector array.');
  11631. }
  11632. },
  11633. /**
  11634. * We add the active sector at the end of the this.activeSector array
  11635. * This ensures it is the currently active sector returned by _sector() and it reaches the top
  11636. * of the activeSector stack. When we reverse our steps we move from the end to the beginning of this stack.
  11637. *
  11638. * @param newId
  11639. * @private
  11640. */
  11641. _setActiveSector : function(newId) {
  11642. this.activeSector.push(newId);
  11643. },
  11644. /**
  11645. * We remove the currently active sector id from the active sector stack. This happens when
  11646. * we reactivate the previously active sector
  11647. *
  11648. * @private
  11649. */
  11650. _forgetLastSector : function() {
  11651. this.activeSector.pop();
  11652. },
  11653. /**
  11654. * This function creates a new active sector with the supplied newId. This newId
  11655. * is the expanding node id.
  11656. *
  11657. * @param {String} newId | Id of the new active sector
  11658. * @private
  11659. */
  11660. _createNewSector : function(newId) {
  11661. // create the new sector
  11662. this.sectors["active"][newId] = {"nodes":{},
  11663. "edges":{},
  11664. "nodeIndices":[],
  11665. "formationScale": this.scale,
  11666. "drawingNode": undefined};
  11667. // create the new sector render node. This gives visual feedback that you are in a new sector.
  11668. this.sectors["active"][newId]['drawingNode'] = new Node(
  11669. {id:newId,
  11670. color: {
  11671. background: "#eaefef",
  11672. border: "495c5e"
  11673. }
  11674. },{},{},this.constants);
  11675. this.sectors["active"][newId]['drawingNode'].clusterSize = 2;
  11676. },
  11677. /**
  11678. * This function removes the currently active sector. This is called when we create a new
  11679. * active sector.
  11680. *
  11681. * @param {String} sectorId | Id of the active sector that will be removed
  11682. * @private
  11683. */
  11684. _deleteActiveSector : function(sectorId) {
  11685. delete this.sectors["active"][sectorId];
  11686. },
  11687. /**
  11688. * This function removes the currently active sector. This is called when we reactivate
  11689. * the previously active sector.
  11690. *
  11691. * @param {String} sectorId | Id of the active sector that will be removed
  11692. * @private
  11693. */
  11694. _deleteFrozenSector : function(sectorId) {
  11695. delete this.sectors["frozen"][sectorId];
  11696. },
  11697. /**
  11698. * Freezing an active sector means moving it from the "active" object to the "frozen" object.
  11699. * We copy the references, then delete the active entree.
  11700. *
  11701. * @param sectorId
  11702. * @private
  11703. */
  11704. _freezeSector : function(sectorId) {
  11705. // we move the set references from the active to the frozen stack.
  11706. this.sectors["frozen"][sectorId] = this.sectors["active"][sectorId];
  11707. // we have moved the sector data into the frozen set, we now remove it from the active set
  11708. this._deleteActiveSector(sectorId);
  11709. },
  11710. /**
  11711. * This is the reverse operation of _freezeSector. Activating means moving the sector from the "frozen"
  11712. * object to the "active" object.
  11713. *
  11714. * @param sectorId
  11715. * @private
  11716. */
  11717. _activateSector : function(sectorId) {
  11718. // we move the set references from the frozen to the active stack.
  11719. this.sectors["active"][sectorId] = this.sectors["frozen"][sectorId];
  11720. // we have moved the sector data into the active set, we now remove it from the frozen stack
  11721. this._deleteFrozenSector(sectorId);
  11722. },
  11723. /**
  11724. * This function merges the data from the currently active sector with a frozen sector. This is used
  11725. * in the process of reverting back to the previously active sector.
  11726. * The data that is placed in the frozen (the previously active) sector is the node that has been removed from it
  11727. * upon the creation of a new active sector.
  11728. *
  11729. * @param sectorId
  11730. * @private
  11731. */
  11732. _mergeThisWithFrozen : function(sectorId) {
  11733. // copy all nodes
  11734. for (var nodeId in this.nodes) {
  11735. if (this.nodes.hasOwnProperty(nodeId)) {
  11736. this.sectors["frozen"][sectorId]["nodes"][nodeId] = this.nodes[nodeId];
  11737. }
  11738. }
  11739. // copy all edges (if not fully clustered, else there are no edges)
  11740. for (var edgeId in this.edges) {
  11741. if (this.edges.hasOwnProperty(edgeId)) {
  11742. this.sectors["frozen"][sectorId]["edges"][edgeId] = this.edges[edgeId];
  11743. }
  11744. }
  11745. // merge the nodeIndices
  11746. for (var i = 0; i < this.nodeIndices.length; i++) {
  11747. this.sectors["frozen"][sectorId]["nodeIndices"].push(this.nodeIndices[i]);
  11748. }
  11749. },
  11750. /**
  11751. * This clusters the sector to one cluster. It was a single cluster before this process started so
  11752. * we revert to that state. The clusterToFit function with a maximum size of 1 node does this.
  11753. *
  11754. * @private
  11755. */
  11756. _collapseThisToSingleCluster : function() {
  11757. this.clusterToFit(1,false);
  11758. },
  11759. /**
  11760. * We create a new active sector from the node that we want to open.
  11761. *
  11762. * @param node
  11763. * @private
  11764. */
  11765. _addSector : function(node) {
  11766. // this is the currently active sector
  11767. var sector = this._sector();
  11768. // // this should allow me to select nodes from a frozen set.
  11769. // if (this.sectors['active'][sector]["nodes"].hasOwnProperty(node.id)) {
  11770. // console.log("the node is part of the active sector");
  11771. // }
  11772. // else {
  11773. // console.log("I dont know what the fuck happened!!");
  11774. // }
  11775. // when we switch to a new sector, we remove the node that will be expanded from the current nodes list.
  11776. delete this.nodes[node.id];
  11777. var unqiueIdentifier = util.randomUUID();
  11778. // we fully freeze the currently active sector
  11779. this._freezeSector(sector);
  11780. // we create a new active sector. This sector has the Id of the node to ensure uniqueness
  11781. this._createNewSector(unqiueIdentifier);
  11782. // we add the active sector to the sectors array to be able to revert these steps later on
  11783. this._setActiveSector(unqiueIdentifier);
  11784. // we redirect the global references to the new sector's references. this._sector() now returns unqiueIdentifier
  11785. this._switchToSector(this._sector());
  11786. // finally we add the node we removed from our previous active sector to the new active sector
  11787. this.nodes[node.id] = node;
  11788. },
  11789. /**
  11790. * We close the sector that is currently open and revert back to the one before.
  11791. * If the active sector is the "default" sector, nothing happens.
  11792. *
  11793. * @private
  11794. */
  11795. _collapseSector : function() {
  11796. // the currently active sector
  11797. var sector = this._sector();
  11798. // we cannot collapse the default sector
  11799. if (sector != "default") {
  11800. if ((this.nodeIndices.length == 1) ||
  11801. (this.sectors["active"][sector]["drawingNode"].width*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  11802. (this.sectors["active"][sector]["drawingNode"].height*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  11803. var previousSector = this._previousSector();
  11804. // we collapse the sector back to a single cluster
  11805. this._collapseThisToSingleCluster();
  11806. // we move the remaining nodes, edges and nodeIndices to the previous sector.
  11807. // This previous sector is the one we will reactivate
  11808. this._mergeThisWithFrozen(previousSector);
  11809. // the previously active (frozen) sector now has all the data from the currently active sector.
  11810. // we can now delete the active sector.
  11811. this._deleteActiveSector(sector);
  11812. // we activate the previously active (and currently frozen) sector.
  11813. this._activateSector(previousSector);
  11814. // we load the references from the newly active sector into the global references
  11815. this._switchToSector(previousSector);
  11816. // we forget the previously active sector because we reverted to the one before
  11817. this._forgetLastSector();
  11818. // finally, we update the node index list.
  11819. this._updateNodeIndexList();
  11820. // we refresh the list with calulation nodes and calculation node indices.
  11821. this._updateCalculationNodes();
  11822. }
  11823. }
  11824. },
  11825. /**
  11826. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  11827. *
  11828. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11829. * | we dont pass the function itself because then the "this" is the window object
  11830. * | instead of the Graph object
  11831. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11832. * @private
  11833. */
  11834. _doInAllActiveSectors : function(runFunction,argument) {
  11835. if (argument === undefined) {
  11836. for (var sector in this.sectors["active"]) {
  11837. if (this.sectors["active"].hasOwnProperty(sector)) {
  11838. // switch the global references to those of this sector
  11839. this._switchToActiveSector(sector);
  11840. this[runFunction]();
  11841. }
  11842. }
  11843. }
  11844. else {
  11845. for (var sector in this.sectors["active"]) {
  11846. if (this.sectors["active"].hasOwnProperty(sector)) {
  11847. // switch the global references to those of this sector
  11848. this._switchToActiveSector(sector);
  11849. var args = Array.prototype.splice.call(arguments, 1);
  11850. if (args.length > 1) {
  11851. this[runFunction](args[0],args[1]);
  11852. }
  11853. else {
  11854. this[runFunction](argument);
  11855. }
  11856. }
  11857. }
  11858. }
  11859. // we revert the global references back to our active sector
  11860. this._loadLatestSector();
  11861. },
  11862. /**
  11863. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  11864. *
  11865. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11866. * | we dont pass the function itself because then the "this" is the window object
  11867. * | instead of the Graph object
  11868. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11869. * @private
  11870. */
  11871. _doInSupportSector : function(runFunction,argument) {
  11872. if (argument === undefined) {
  11873. this._switchToSupportSector();
  11874. this[runFunction]();
  11875. }
  11876. else {
  11877. this._switchToSupportSector();
  11878. var args = Array.prototype.splice.call(arguments, 1);
  11879. if (args.length > 1) {
  11880. this[runFunction](args[0],args[1]);
  11881. }
  11882. else {
  11883. this[runFunction](argument);
  11884. }
  11885. }
  11886. // we revert the global references back to our active sector
  11887. this._loadLatestSector();
  11888. },
  11889. /**
  11890. * This runs a function in all frozen sectors. This is used in the _redraw().
  11891. *
  11892. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11893. * | we don't pass the function itself because then the "this" is the window object
  11894. * | instead of the Graph object
  11895. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11896. * @private
  11897. */
  11898. _doInAllFrozenSectors : function(runFunction,argument) {
  11899. if (argument === undefined) {
  11900. for (var sector in this.sectors["frozen"]) {
  11901. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  11902. // switch the global references to those of this sector
  11903. this._switchToFrozenSector(sector);
  11904. this[runFunction]();
  11905. }
  11906. }
  11907. }
  11908. else {
  11909. for (var sector in this.sectors["frozen"]) {
  11910. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  11911. // switch the global references to those of this sector
  11912. this._switchToFrozenSector(sector);
  11913. var args = Array.prototype.splice.call(arguments, 1);
  11914. if (args.length > 1) {
  11915. this[runFunction](args[0],args[1]);
  11916. }
  11917. else {
  11918. this[runFunction](argument);
  11919. }
  11920. }
  11921. }
  11922. }
  11923. this._loadLatestSector();
  11924. },
  11925. /**
  11926. * This runs a function in all sectors. This is used in the _redraw().
  11927. *
  11928. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11929. * | we don't pass the function itself because then the "this" is the window object
  11930. * | instead of the Graph object
  11931. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11932. * @private
  11933. */
  11934. _doInAllSectors : function(runFunction,argument) {
  11935. var args = Array.prototype.splice.call(arguments, 1);
  11936. if (argument === undefined) {
  11937. this._doInAllActiveSectors(runFunction);
  11938. this._doInAllFrozenSectors(runFunction);
  11939. }
  11940. else {
  11941. if (args.length > 1) {
  11942. this._doInAllActiveSectors(runFunction,args[0],args[1]);
  11943. this._doInAllFrozenSectors(runFunction,args[0],args[1]);
  11944. }
  11945. else {
  11946. this._doInAllActiveSectors(runFunction,argument);
  11947. this._doInAllFrozenSectors(runFunction,argument);
  11948. }
  11949. }
  11950. },
  11951. /**
  11952. * This clears the nodeIndices list. We cannot use this.nodeIndices = [] because we would break the link with the
  11953. * active sector. Thus we clear the nodeIndices in the active sector, then reconnect the this.nodeIndices to it.
  11954. *
  11955. * @private
  11956. */
  11957. _clearNodeIndexList : function() {
  11958. var sector = this._sector();
  11959. this.sectors["active"][sector]["nodeIndices"] = [];
  11960. this.nodeIndices = this.sectors["active"][sector]["nodeIndices"];
  11961. },
  11962. /**
  11963. * Draw the encompassing sector node
  11964. *
  11965. * @param ctx
  11966. * @param sectorType
  11967. * @private
  11968. */
  11969. _drawSectorNodes : function(ctx,sectorType) {
  11970. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  11971. for (var sector in this.sectors[sectorType]) {
  11972. if (this.sectors[sectorType].hasOwnProperty(sector)) {
  11973. if (this.sectors[sectorType][sector]["drawingNode"] !== undefined) {
  11974. this._switchToSector(sector,sectorType);
  11975. minY = 1e9; maxY = -1e9; minX = 1e9; maxX = -1e9;
  11976. for (var nodeId in this.nodes) {
  11977. if (this.nodes.hasOwnProperty(nodeId)) {
  11978. node = this.nodes[nodeId];
  11979. node.resize(ctx);
  11980. if (minX > node.x - 0.5 * node.width) {minX = node.x - 0.5 * node.width;}
  11981. if (maxX < node.x + 0.5 * node.width) {maxX = node.x + 0.5 * node.width;}
  11982. if (minY > node.y - 0.5 * node.height) {minY = node.y - 0.5 * node.height;}
  11983. if (maxY < node.y + 0.5 * node.height) {maxY = node.y + 0.5 * node.height;}
  11984. }
  11985. }
  11986. node = this.sectors[sectorType][sector]["drawingNode"];
  11987. node.x = 0.5 * (maxX + minX);
  11988. node.y = 0.5 * (maxY + minY);
  11989. node.width = 2 * (node.x - minX);
  11990. node.height = 2 * (node.y - minY);
  11991. node.radius = Math.sqrt(Math.pow(0.5*node.width,2) + Math.pow(0.5*node.height,2));
  11992. node.setScale(this.scale);
  11993. node._drawCircle(ctx);
  11994. }
  11995. }
  11996. }
  11997. },
  11998. _drawAllSectorNodes : function(ctx) {
  11999. this._drawSectorNodes(ctx,"frozen");
  12000. this._drawSectorNodes(ctx,"active");
  12001. this._loadLatestSector();
  12002. }
  12003. };
  12004. /**
  12005. * Creation of the ClusterMixin var.
  12006. *
  12007. * This contains all the functions the Graph object can use to employ clustering
  12008. *
  12009. * Alex de Mulder
  12010. * 21-01-2013
  12011. */
  12012. var ClusterMixin = {
  12013. /**
  12014. * This is only called in the constructor of the graph object
  12015. *
  12016. */
  12017. startWithClustering : function() {
  12018. // cluster if the data set is big
  12019. this.clusterToFit(this.constants.clustering.initialMaxNodes, true);
  12020. // updates the lables after clustering
  12021. this.updateLabels();
  12022. // this is called here because if clusterin is disabled, the start and stabilize are called in
  12023. // the setData function.
  12024. if (this.stabilize) {
  12025. this._stabilize();
  12026. }
  12027. this.start();
  12028. },
  12029. /**
  12030. * This function clusters until the initialMaxNodes has been reached
  12031. *
  12032. * @param {Number} maxNumberOfNodes
  12033. * @param {Boolean} reposition
  12034. */
  12035. clusterToFit : function(maxNumberOfNodes, reposition) {
  12036. var numberOfNodes = this.nodeIndices.length;
  12037. var maxLevels = 50;
  12038. var level = 0;
  12039. // we first cluster the hubs, then we pull in the outliers, repeat
  12040. while (numberOfNodes > maxNumberOfNodes && level < maxLevels) {
  12041. if (level % 3 == 0) {
  12042. this.forceAggregateHubs(true);
  12043. this.normalizeClusterLevels();
  12044. }
  12045. else {
  12046. this.increaseClusterLevel(); // this also includes a cluster normalization
  12047. }
  12048. numberOfNodes = this.nodeIndices.length;
  12049. level += 1;
  12050. }
  12051. // after the clustering we reposition the nodes to reduce the initial chaos
  12052. if (level > 0 && reposition == true) {
  12053. this.repositionNodes();
  12054. }
  12055. this._updateCalculationNodes();
  12056. },
  12057. /**
  12058. * This function can be called to open up a specific cluster. It is only called by
  12059. * It will unpack the cluster back one level.
  12060. *
  12061. * @param node | Node object: cluster to open.
  12062. */
  12063. openCluster : function(node) {
  12064. var isMovingBeforeClustering = this.moving;
  12065. if (node.clusterSize > this.constants.clustering.sectorThreshold && this._nodeInActiveArea(node) &&
  12066. !(this._sector() == "default" && this.nodeIndices.length == 1)) {
  12067. // this loads a new sector, loads the nodes and edges and nodeIndices of it.
  12068. this._addSector(node);
  12069. var level = 0;
  12070. // we decluster until we reach a decent number of nodes
  12071. while ((this.nodeIndices.length < this.constants.clustering.initialMaxNodes) && (level < 10)) {
  12072. this.decreaseClusterLevel();
  12073. level += 1;
  12074. }
  12075. }
  12076. else {
  12077. this._expandClusterNode(node,false,true);
  12078. // update the index list, dynamic edges and labels
  12079. this._updateNodeIndexList();
  12080. this._updateDynamicEdges();
  12081. this._updateCalculationNodes();
  12082. this.updateLabels();
  12083. }
  12084. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  12085. if (this.moving != isMovingBeforeClustering) {
  12086. this.start();
  12087. }
  12088. },
  12089. /**
  12090. * This calls the updateClustes with default arguments
  12091. */
  12092. updateClustersDefault : function() {
  12093. if (this.constants.clustering.enabled == true) {
  12094. this.updateClusters(0,false,false);
  12095. }
  12096. },
  12097. /**
  12098. * This function can be called to increase the cluster level. This means that the nodes with only one edge connection will
  12099. * be clustered with their connected node. This can be repeated as many times as needed.
  12100. * This can be called externally (by a keybind for instance) to reduce the complexity of big datasets.
  12101. */
  12102. increaseClusterLevel : function() {
  12103. this.updateClusters(-1,false,true);
  12104. },
  12105. /**
  12106. * This function can be called to decrease the cluster level. This means that the nodes with only one edge connection will
  12107. * be unpacked if they are a cluster. This can be repeated as many times as needed.
  12108. * This can be called externally (by a key-bind for instance) to look into clusters without zooming.
  12109. */
  12110. decreaseClusterLevel : function() {
  12111. this.updateClusters(1,false,true);
  12112. },
  12113. /**
  12114. * This is the main clustering function. It clusters and declusters on zoom or forced
  12115. * This function clusters on zoom, it can be called with a predefined zoom direction
  12116. * If out, check if we can form clusters, if in, check if we can open clusters.
  12117. * This function is only called from _zoom()
  12118. *
  12119. * @param {Number} zoomDirection | -1 / 0 / +1 for zoomOut / determineByZoom / zoomIn
  12120. * @param {Boolean} recursive | enabled or disable recursive calling of the opening of clusters
  12121. * @param {Boolean} force | enabled or disable forcing
  12122. *
  12123. */
  12124. updateClusters : function(zoomDirection,recursive,force,doNotStart) {
  12125. var isMovingBeforeClustering = this.moving;
  12126. var amountOfNodes = this.nodeIndices.length;
  12127. // on zoom out collapse the sector if the scale is at the level the sector was made
  12128. if (this.previousScale > this.scale && zoomDirection == 0) {
  12129. this._collapseSector();
  12130. }
  12131. // check if we zoom in or out
  12132. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  12133. // forming clusters when forced pulls outliers in. When not forced, the edge length of the
  12134. // outer nodes determines if it is being clustered
  12135. this._formClusters(force);
  12136. }
  12137. else if (this.previousScale < this.scale || zoomDirection == 1) { // zoom in
  12138. if (force == true) {
  12139. // _openClusters checks for each node if the formationScale of the cluster is smaller than
  12140. // the current scale and if so, declusters. When forced, all clusters are reduced by one step
  12141. this._openClusters(recursive,force);
  12142. }
  12143. else {
  12144. // if a cluster takes up a set percentage of the active window
  12145. this._openClustersBySize();
  12146. }
  12147. }
  12148. this._updateNodeIndexList();
  12149. // if a cluster was NOT formed and the user zoomed out, we try clustering by hubs
  12150. if (this.nodeIndices.length == amountOfNodes && (this.previousScale > this.scale || zoomDirection == -1)) {
  12151. this._aggregateHubs(force);
  12152. this._updateNodeIndexList();
  12153. }
  12154. // we now reduce chains.
  12155. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  12156. this.handleChains();
  12157. this._updateNodeIndexList();
  12158. }
  12159. this.previousScale = this.scale;
  12160. // rest of the update the index list, dynamic edges and labels
  12161. this._updateDynamicEdges();
  12162. this.updateLabels();
  12163. // if a cluster was formed, we increase the clusterSession
  12164. if (this.nodeIndices.length < amountOfNodes) { // this means a clustering operation has taken place
  12165. this.clusterSession += 1;
  12166. // if clusters have been made, we normalize the cluster level
  12167. this.normalizeClusterLevels();
  12168. }
  12169. if (doNotStart == false || doNotStart === undefined) {
  12170. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  12171. if (this.moving != isMovingBeforeClustering) {
  12172. this.start();
  12173. }
  12174. }
  12175. this._updateCalculationNodes();
  12176. },
  12177. /**
  12178. * This function handles the chains. It is called on every updateClusters().
  12179. */
  12180. handleChains : function() {
  12181. // after clustering we check how many chains there are
  12182. var chainPercentage = this._getChainFraction();
  12183. if (chainPercentage > this.constants.clustering.chainThreshold) {
  12184. this._reduceAmountOfChains(1 - this.constants.clustering.chainThreshold / chainPercentage)
  12185. }
  12186. },
  12187. /**
  12188. * this functions starts clustering by hubs
  12189. * The minimum hub threshold is set globally
  12190. *
  12191. * @private
  12192. */
  12193. _aggregateHubs : function(force) {
  12194. this._getHubSize();
  12195. this._formClustersByHub(force,false);
  12196. },
  12197. /**
  12198. * This function is fired by keypress. It forces hubs to form.
  12199. *
  12200. */
  12201. forceAggregateHubs : function(doNotStart) {
  12202. var isMovingBeforeClustering = this.moving;
  12203. var amountOfNodes = this.nodeIndices.length;
  12204. this._aggregateHubs(true);
  12205. // update the index list, dynamic edges and labels
  12206. this._updateNodeIndexList();
  12207. this._updateDynamicEdges();
  12208. this.updateLabels();
  12209. // if a cluster was formed, we increase the clusterSession
  12210. if (this.nodeIndices.length != amountOfNodes) {
  12211. this.clusterSession += 1;
  12212. }
  12213. if (doNotStart == false || doNotStart === undefined) {
  12214. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  12215. if (this.moving != isMovingBeforeClustering) {
  12216. this.start();
  12217. }
  12218. }
  12219. },
  12220. /**
  12221. * If a cluster takes up more than a set percentage of the screen, open the cluster
  12222. *
  12223. * @private
  12224. */
  12225. _openClustersBySize : function() {
  12226. for (var nodeId in this.nodes) {
  12227. if (this.nodes.hasOwnProperty(nodeId)) {
  12228. var node = this.nodes[nodeId];
  12229. if (node.inView() == true) {
  12230. if ((node.width*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  12231. (node.height*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  12232. this.openCluster(node);
  12233. }
  12234. }
  12235. }
  12236. }
  12237. },
  12238. /**
  12239. * This function loops over all nodes in the nodeIndices list. For each node it checks if it is a cluster and if it
  12240. * has to be opened based on the current zoom level.
  12241. *
  12242. * @private
  12243. */
  12244. _openClusters : function(recursive,force) {
  12245. for (var i = 0; i < this.nodeIndices.length; i++) {
  12246. var node = this.nodes[this.nodeIndices[i]];
  12247. this._expandClusterNode(node,recursive,force);
  12248. this._updateCalculationNodes();
  12249. }
  12250. },
  12251. /**
  12252. * This function checks if a node has to be opened. This is done by checking the zoom level.
  12253. * If the node contains child nodes, this function is recursively called on the child nodes as well.
  12254. * This recursive behaviour is optional and can be set by the recursive argument.
  12255. *
  12256. * @param {Node} parentNode | to check for cluster and expand
  12257. * @param {Boolean} recursive | enabled or disable recursive calling
  12258. * @param {Boolean} force | enabled or disable forcing
  12259. * @param {Boolean} [openAll] | This will recursively force all nodes in the parent to be released
  12260. * @private
  12261. */
  12262. _expandClusterNode : function(parentNode, recursive, force, openAll) {
  12263. // first check if node is a cluster
  12264. if (parentNode.clusterSize > 1) {
  12265. // this means that on a double tap event or a zoom event, the cluster fully unpacks if it is smaller than 20
  12266. if (parentNode.clusterSize < this.constants.clustering.sectorThreshold) {
  12267. openAll = true;
  12268. }
  12269. recursive = openAll ? true : recursive;
  12270. // if the last child has been added on a smaller scale than current scale decluster
  12271. if (parentNode.formationScale < this.scale || force == true) {
  12272. // we will check if any of the contained child nodes should be removed from the cluster
  12273. for (var containedNodeId in parentNode.containedNodes) {
  12274. if (parentNode.containedNodes.hasOwnProperty(containedNodeId)) {
  12275. var childNode = parentNode.containedNodes[containedNodeId];
  12276. // force expand will expand the largest cluster size clusters. Since we cluster from outside in, we assume that
  12277. // the largest cluster is the one that comes from outside
  12278. if (force == true) {
  12279. if (childNode.clusterSession == parentNode.clusterSessions[parentNode.clusterSessions.length-1]
  12280. || openAll) {
  12281. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  12282. }
  12283. }
  12284. else {
  12285. if (this._nodeInActiveArea(parentNode)) {
  12286. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  12287. }
  12288. }
  12289. }
  12290. }
  12291. }
  12292. }
  12293. },
  12294. /**
  12295. * ONLY CALLED FROM _expandClusterNode
  12296. *
  12297. * This function will expel a child_node from a parent_node. This is to de-cluster the node. This function will remove
  12298. * the child node from the parent contained_node object and put it back into the global nodes object.
  12299. * The same holds for the edge that was connected to the child node. It is moved back into the global edges object.
  12300. *
  12301. * @param {Node} parentNode | the parent node
  12302. * @param {String} containedNodeId | child_node id as it is contained in the containedNodes object of the parent node
  12303. * @param {Boolean} recursive | This will also check if the child needs to be expanded.
  12304. * With force and recursive both true, the entire cluster is unpacked
  12305. * @param {Boolean} force | This will disregard the zoom level and will expel this child from the parent
  12306. * @param {Boolean} openAll | This will recursively force all nodes in the parent to be released
  12307. * @private
  12308. */
  12309. _expelChildFromParent : function(parentNode, containedNodeId, recursive, force, openAll) {
  12310. var childNode = parentNode.containedNodes[containedNodeId];
  12311. // if child node has been added on smaller scale than current, kick out
  12312. if (childNode.formationScale < this.scale || force == true) {
  12313. // unselect all selected items
  12314. this._unselectAll();
  12315. // put the child node back in the global nodes object
  12316. this.nodes[containedNodeId] = childNode;
  12317. // release the contained edges from this childNode back into the global edges
  12318. this._releaseContainedEdges(parentNode,childNode);
  12319. // reconnect rerouted edges to the childNode
  12320. this._connectEdgeBackToChild(parentNode,childNode);
  12321. // validate all edges in dynamicEdges
  12322. this._validateEdges(parentNode);
  12323. // undo the changes from the clustering operation on the parent node
  12324. parentNode.mass -= childNode.mass;
  12325. parentNode.clusterSize -= childNode.clusterSize;
  12326. parentNode.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize);
  12327. parentNode.dynamicEdgesLength = parentNode.dynamicEdges.length;
  12328. // place the child node near the parent, not at the exact same location to avoid chaos in the system
  12329. childNode.x = parentNode.x + parentNode.growthIndicator * (0.5 - Math.random());
  12330. childNode.y = parentNode.y + parentNode.growthIndicator * (0.5 - Math.random());
  12331. // remove node from the list
  12332. delete parentNode.containedNodes[containedNodeId];
  12333. // check if there are other childs with this clusterSession in the parent.
  12334. var othersPresent = false;
  12335. for (var childNodeId in parentNode.containedNodes) {
  12336. if (parentNode.containedNodes.hasOwnProperty(childNodeId)) {
  12337. if (parentNode.containedNodes[childNodeId].clusterSession == childNode.clusterSession) {
  12338. othersPresent = true;
  12339. break;
  12340. }
  12341. }
  12342. }
  12343. // if there are no others, remove the cluster session from the list
  12344. if (othersPresent == false) {
  12345. parentNode.clusterSessions.pop();
  12346. }
  12347. this._repositionBezierNodes(childNode);
  12348. // this._repositionBezierNodes(parentNode);
  12349. // remove the clusterSession from the child node
  12350. childNode.clusterSession = 0;
  12351. // recalculate the size of the node on the next time the node is rendered
  12352. parentNode.clearSizeCache();
  12353. // restart the simulation to reorganise all nodes
  12354. this.moving = true;
  12355. }
  12356. // check if a further expansion step is possible if recursivity is enabled
  12357. if (recursive == true) {
  12358. this._expandClusterNode(childNode,recursive,force,openAll);
  12359. }
  12360. },
  12361. /**
  12362. * position the bezier nodes at the center of the edges
  12363. *
  12364. * @param node
  12365. * @private
  12366. */
  12367. _repositionBezierNodes : function(node) {
  12368. for (var i = 0; i < node.dynamicEdges.length; i++) {
  12369. node.dynamicEdges[i].positionBezierNode();
  12370. }
  12371. },
  12372. /**
  12373. * This function checks if any nodes at the end of their trees have edges below a threshold length
  12374. * This function is called only from updateClusters()
  12375. * forceLevelCollapse ignores the length of the edge and collapses one level
  12376. * This means that a node with only one edge will be clustered with its connected node
  12377. *
  12378. * @private
  12379. * @param {Boolean} force
  12380. */
  12381. _formClusters : function(force) {
  12382. if (force == false) {
  12383. this._formClustersByZoom();
  12384. }
  12385. else {
  12386. this._forceClustersByZoom();
  12387. }
  12388. },
  12389. /**
  12390. * This function handles the clustering by zooming out, this is based on a minimum edge distance
  12391. *
  12392. * @private
  12393. */
  12394. _formClustersByZoom : function() {
  12395. var dx,dy,length,
  12396. minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  12397. // check if any edges are shorter than minLength and start the clustering
  12398. // the clustering favours the node with the larger mass
  12399. for (var edgeId in this.edges) {
  12400. if (this.edges.hasOwnProperty(edgeId)) {
  12401. var edge = this.edges[edgeId];
  12402. if (edge.connected) {
  12403. if (edge.toId != edge.fromId) {
  12404. dx = (edge.to.x - edge.from.x);
  12405. dy = (edge.to.y - edge.from.y);
  12406. length = Math.sqrt(dx * dx + dy * dy);
  12407. if (length < minLength) {
  12408. // first check which node is larger
  12409. var parentNode = edge.from;
  12410. var childNode = edge.to;
  12411. if (edge.to.mass > edge.from.mass) {
  12412. parentNode = edge.to;
  12413. childNode = edge.from;
  12414. }
  12415. if (childNode.dynamicEdgesLength == 1) {
  12416. this._addToCluster(parentNode,childNode,false);
  12417. }
  12418. else if (parentNode.dynamicEdgesLength == 1) {
  12419. this._addToCluster(childNode,parentNode,false);
  12420. }
  12421. }
  12422. }
  12423. }
  12424. }
  12425. }
  12426. },
  12427. /**
  12428. * This function forces the graph to cluster all nodes with only one connecting edge to their
  12429. * connected node.
  12430. *
  12431. * @private
  12432. */
  12433. _forceClustersByZoom : function() {
  12434. for (var nodeId in this.nodes) {
  12435. // another node could have absorbed this child.
  12436. if (this.nodes.hasOwnProperty(nodeId)) {
  12437. var childNode = this.nodes[nodeId];
  12438. // the edges can be swallowed by another decrease
  12439. if (childNode.dynamicEdgesLength == 1 && childNode.dynamicEdges.length != 0) {
  12440. var edge = childNode.dynamicEdges[0];
  12441. var parentNode = (edge.toId == childNode.id) ? this.nodes[edge.fromId] : this.nodes[edge.toId];
  12442. // group to the largest node
  12443. if (childNode.id != parentNode.id) {
  12444. if (parentNode.mass > childNode.mass) {
  12445. this._addToCluster(parentNode,childNode,true);
  12446. }
  12447. else {
  12448. this._addToCluster(childNode,parentNode,true);
  12449. }
  12450. }
  12451. }
  12452. }
  12453. }
  12454. },
  12455. /**
  12456. * To keep the nodes of roughly equal size we normalize the cluster levels.
  12457. * This function clusters a node to its smallest connected neighbour.
  12458. *
  12459. * @param node
  12460. * @private
  12461. */
  12462. _clusterToSmallestNeighbour : function(node) {
  12463. var smallestNeighbour = -1;
  12464. var smallestNeighbourNode = null;
  12465. for (var i = 0; i < node.dynamicEdges.length; i++) {
  12466. if (node.dynamicEdges[i] !== undefined) {
  12467. var neighbour = null;
  12468. if (node.dynamicEdges[i].fromId != node.id) {
  12469. neighbour = node.dynamicEdges[i].from;
  12470. }
  12471. else if (node.dynamicEdges[i].toId != node.id) {
  12472. neighbour = node.dynamicEdges[i].to;
  12473. }
  12474. if (neighbour != null && smallestNeighbour > neighbour.clusterSessions.length) {
  12475. smallestNeighbour = neighbour.clusterSessions.length;
  12476. smallestNeighbourNode = neighbour;
  12477. }
  12478. }
  12479. }
  12480. if (neighbour != null && this.nodes[neighbour.id] !== undefined) {
  12481. this._addToCluster(neighbour, node, true);
  12482. }
  12483. },
  12484. /**
  12485. * This function forms clusters from hubs, it loops over all nodes
  12486. *
  12487. * @param {Boolean} force | Disregard zoom level
  12488. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  12489. * @private
  12490. */
  12491. _formClustersByHub : function(force, onlyEqual) {
  12492. // we loop over all nodes in the list
  12493. for (var nodeId in this.nodes) {
  12494. // we check if it is still available since it can be used by the clustering in this loop
  12495. if (this.nodes.hasOwnProperty(nodeId)) {
  12496. this._formClusterFromHub(this.nodes[nodeId],force,onlyEqual);
  12497. }
  12498. }
  12499. },
  12500. /**
  12501. * This function forms a cluster from a specific preselected hub node
  12502. *
  12503. * @param {Node} hubNode | the node we will cluster as a hub
  12504. * @param {Boolean} force | Disregard zoom level
  12505. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  12506. * @param {Number} [absorptionSizeOffset] |
  12507. * @private
  12508. */
  12509. _formClusterFromHub : function(hubNode, force, onlyEqual, absorptionSizeOffset) {
  12510. if (absorptionSizeOffset === undefined) {
  12511. absorptionSizeOffset = 0;
  12512. }
  12513. // we decide if the node is a hub
  12514. if ((hubNode.dynamicEdgesLength >= this.hubThreshold && onlyEqual == false) ||
  12515. (hubNode.dynamicEdgesLength == this.hubThreshold && onlyEqual == true)) {
  12516. // initialize variables
  12517. var dx,dy,length;
  12518. var minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  12519. var allowCluster = false;
  12520. // we create a list of edges because the dynamicEdges change over the course of this loop
  12521. var edgesIdarray = [];
  12522. var amountOfInitialEdges = hubNode.dynamicEdges.length;
  12523. for (var j = 0; j < amountOfInitialEdges; j++) {
  12524. edgesIdarray.push(hubNode.dynamicEdges[j].id);
  12525. }
  12526. // if the hub clustering is not forces, we check if one of the edges connected
  12527. // to a cluster is small enough based on the constants.clustering.clusterEdgeThreshold
  12528. if (force == false) {
  12529. allowCluster = false;
  12530. for (j = 0; j < amountOfInitialEdges; j++) {
  12531. var edge = this.edges[edgesIdarray[j]];
  12532. if (edge !== undefined) {
  12533. if (edge.connected) {
  12534. if (edge.toId != edge.fromId) {
  12535. dx = (edge.to.x - edge.from.x);
  12536. dy = (edge.to.y - edge.from.y);
  12537. length = Math.sqrt(dx * dx + dy * dy);
  12538. if (length < minLength) {
  12539. allowCluster = true;
  12540. break;
  12541. }
  12542. }
  12543. }
  12544. }
  12545. }
  12546. }
  12547. // start the clustering if allowed
  12548. if ((!force && allowCluster) || force) {
  12549. // we loop over all edges INITIALLY connected to this hub
  12550. for (j = 0; j < amountOfInitialEdges; j++) {
  12551. edge = this.edges[edgesIdarray[j]];
  12552. // the edge can be clustered by this function in a previous loop
  12553. if (edge !== undefined) {
  12554. var childNode = this.nodes[(edge.fromId == hubNode.id) ? edge.toId : edge.fromId];
  12555. // we do not want hubs to merge with other hubs nor do we want to cluster itself.
  12556. if ((childNode.dynamicEdges.length <= (this.hubThreshold + absorptionSizeOffset)) &&
  12557. (childNode.id != hubNode.id)) {
  12558. this._addToCluster(hubNode,childNode,force);
  12559. }
  12560. }
  12561. }
  12562. }
  12563. }
  12564. },
  12565. /**
  12566. * This function adds the child node to the parent node, creating a cluster if it is not already.
  12567. *
  12568. * @param {Node} parentNode | this is the node that will house the child node
  12569. * @param {Node} childNode | this node will be deleted from the global this.nodes and stored in the parent node
  12570. * @param {Boolean} force | true will only update the remainingEdges at the very end of the clustering, ensuring single level collapse
  12571. * @private
  12572. */
  12573. _addToCluster : function(parentNode, childNode, force) {
  12574. // join child node in the parent node
  12575. parentNode.containedNodes[childNode.id] = childNode;
  12576. // manage all the edges connected to the child and parent nodes
  12577. for (var i = 0; i < childNode.dynamicEdges.length; i++) {
  12578. var edge = childNode.dynamicEdges[i];
  12579. if (edge.toId == parentNode.id || edge.fromId == parentNode.id) { // edge connected to parentNode
  12580. this._addToContainedEdges(parentNode,childNode,edge);
  12581. }
  12582. else {
  12583. this._connectEdgeToCluster(parentNode,childNode,edge);
  12584. }
  12585. }
  12586. // a contained node has no dynamic edges.
  12587. childNode.dynamicEdges = [];
  12588. // remove circular edges from clusters
  12589. this._containCircularEdgesFromNode(parentNode,childNode);
  12590. // remove the childNode from the global nodes object
  12591. delete this.nodes[childNode.id];
  12592. // update the properties of the child and parent
  12593. var massBefore = parentNode.mass;
  12594. childNode.clusterSession = this.clusterSession;
  12595. parentNode.mass += childNode.mass;
  12596. parentNode.clusterSize += childNode.clusterSize;
  12597. parentNode.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize);
  12598. // keep track of the clustersessions so we can open the cluster up as it has been formed.
  12599. if (parentNode.clusterSessions[parentNode.clusterSessions.length - 1] != this.clusterSession) {
  12600. parentNode.clusterSessions.push(this.clusterSession);
  12601. }
  12602. // forced clusters only open from screen size and double tap
  12603. if (force == true) {
  12604. // parentNode.formationScale = Math.pow(1 - (1.0/11.0),this.clusterSession+3);
  12605. parentNode.formationScale = 0;
  12606. }
  12607. else {
  12608. parentNode.formationScale = this.scale; // The latest child has been added on this scale
  12609. }
  12610. // recalculate the size of the node on the next time the node is rendered
  12611. parentNode.clearSizeCache();
  12612. // set the pop-out scale for the childnode
  12613. parentNode.containedNodes[childNode.id].formationScale = parentNode.formationScale;
  12614. // nullify the movement velocity of the child, this is to avoid hectic behaviour
  12615. childNode.clearVelocity();
  12616. // the mass has altered, preservation of energy dictates the velocity to be updated
  12617. parentNode.updateVelocity(massBefore);
  12618. // restart the simulation to reorganise all nodes
  12619. this.moving = true;
  12620. },
  12621. /**
  12622. * This function will apply the changes made to the remainingEdges during the formation of the clusters.
  12623. * This is a seperate function to allow for level-wise collapsing of the node barnesHutTree.
  12624. * It has to be called if a level is collapsed. It is called by _formClusters().
  12625. * @private
  12626. */
  12627. _updateDynamicEdges : function() {
  12628. for (var i = 0; i < this.nodeIndices.length; i++) {
  12629. var node = this.nodes[this.nodeIndices[i]];
  12630. node.dynamicEdgesLength = node.dynamicEdges.length;
  12631. // this corrects for multiple edges pointing at the same other node
  12632. var correction = 0;
  12633. if (node.dynamicEdgesLength > 1) {
  12634. for (var j = 0; j < node.dynamicEdgesLength - 1; j++) {
  12635. var edgeToId = node.dynamicEdges[j].toId;
  12636. var edgeFromId = node.dynamicEdges[j].fromId;
  12637. for (var k = j+1; k < node.dynamicEdgesLength; k++) {
  12638. if ((node.dynamicEdges[k].toId == edgeToId && node.dynamicEdges[k].fromId == edgeFromId) ||
  12639. (node.dynamicEdges[k].fromId == edgeToId && node.dynamicEdges[k].toId == edgeFromId)) {
  12640. correction += 1;
  12641. }
  12642. }
  12643. }
  12644. }
  12645. node.dynamicEdgesLength -= correction;
  12646. }
  12647. },
  12648. /**
  12649. * This adds an edge from the childNode to the contained edges of the parent node
  12650. *
  12651. * @param parentNode | Node object
  12652. * @param childNode | Node object
  12653. * @param edge | Edge object
  12654. * @private
  12655. */
  12656. _addToContainedEdges : function(parentNode, childNode, edge) {
  12657. // create an array object if it does not yet exist for this childNode
  12658. if (!(parentNode.containedEdges.hasOwnProperty(childNode.id))) {
  12659. parentNode.containedEdges[childNode.id] = []
  12660. }
  12661. // add this edge to the list
  12662. parentNode.containedEdges[childNode.id].push(edge);
  12663. // remove the edge from the global edges object
  12664. delete this.edges[edge.id];
  12665. // remove the edge from the parent object
  12666. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12667. if (parentNode.dynamicEdges[i].id == edge.id) {
  12668. parentNode.dynamicEdges.splice(i,1);
  12669. break;
  12670. }
  12671. }
  12672. },
  12673. /**
  12674. * This function connects an edge that was connected to a child node to the parent node.
  12675. * It keeps track of which nodes it has been connected to with the originalId array.
  12676. *
  12677. * @param {Node} parentNode | Node object
  12678. * @param {Node} childNode | Node object
  12679. * @param {Edge} edge | Edge object
  12680. * @private
  12681. */
  12682. _connectEdgeToCluster : function(parentNode, childNode, edge) {
  12683. // handle circular edges
  12684. if (edge.toId == edge.fromId) {
  12685. this._addToContainedEdges(parentNode, childNode, edge);
  12686. }
  12687. else {
  12688. if (edge.toId == childNode.id) { // edge connected to other node on the "to" side
  12689. edge.originalToId.push(childNode.id);
  12690. edge.to = parentNode;
  12691. edge.toId = parentNode.id;
  12692. }
  12693. else { // edge connected to other node with the "from" side
  12694. edge.originalFromId.push(childNode.id);
  12695. edge.from = parentNode;
  12696. edge.fromId = parentNode.id;
  12697. }
  12698. this._addToReroutedEdges(parentNode,childNode,edge);
  12699. }
  12700. },
  12701. /**
  12702. * If a node is connected to itself, a circular edge is drawn. When clustering we want to contain
  12703. * these edges inside of the cluster.
  12704. *
  12705. * @param parentNode
  12706. * @param childNode
  12707. * @private
  12708. */
  12709. _containCircularEdgesFromNode : function(parentNode, childNode) {
  12710. // manage all the edges connected to the child and parent nodes
  12711. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12712. var edge = parentNode.dynamicEdges[i];
  12713. // handle circular edges
  12714. if (edge.toId == edge.fromId) {
  12715. this._addToContainedEdges(parentNode, childNode, edge);
  12716. }
  12717. }
  12718. },
  12719. /**
  12720. * This adds an edge from the childNode to the rerouted edges of the parent node
  12721. *
  12722. * @param parentNode | Node object
  12723. * @param childNode | Node object
  12724. * @param edge | Edge object
  12725. * @private
  12726. */
  12727. _addToReroutedEdges : function(parentNode, childNode, edge) {
  12728. // create an array object if it does not yet exist for this childNode
  12729. // we store the edge in the rerouted edges so we can restore it when the cluster pops open
  12730. if (!(parentNode.reroutedEdges.hasOwnProperty(childNode.id))) {
  12731. parentNode.reroutedEdges[childNode.id] = [];
  12732. }
  12733. parentNode.reroutedEdges[childNode.id].push(edge);
  12734. // this edge becomes part of the dynamicEdges of the cluster node
  12735. parentNode.dynamicEdges.push(edge);
  12736. },
  12737. /**
  12738. * This function connects an edge that was connected to a cluster node back to the child node.
  12739. *
  12740. * @param parentNode | Node object
  12741. * @param childNode | Node object
  12742. * @private
  12743. */
  12744. _connectEdgeBackToChild : function(parentNode, childNode) {
  12745. if (parentNode.reroutedEdges.hasOwnProperty(childNode.id)) {
  12746. for (var i = 0; i < parentNode.reroutedEdges[childNode.id].length; i++) {
  12747. var edge = parentNode.reroutedEdges[childNode.id][i];
  12748. if (edge.originalFromId[edge.originalFromId.length-1] == childNode.id) {
  12749. edge.originalFromId.pop();
  12750. edge.fromId = childNode.id;
  12751. edge.from = childNode;
  12752. }
  12753. else {
  12754. edge.originalToId.pop();
  12755. edge.toId = childNode.id;
  12756. edge.to = childNode;
  12757. }
  12758. // append this edge to the list of edges connecting to the childnode
  12759. childNode.dynamicEdges.push(edge);
  12760. // remove the edge from the parent object
  12761. for (var j = 0; j < parentNode.dynamicEdges.length; j++) {
  12762. if (parentNode.dynamicEdges[j].id == edge.id) {
  12763. parentNode.dynamicEdges.splice(j,1);
  12764. break;
  12765. }
  12766. }
  12767. }
  12768. // remove the entry from the rerouted edges
  12769. delete parentNode.reroutedEdges[childNode.id];
  12770. }
  12771. },
  12772. /**
  12773. * When loops are clustered, an edge can be both in the rerouted array and the contained array.
  12774. * This function is called last to verify that all edges in dynamicEdges are in fact connected to the
  12775. * parentNode
  12776. *
  12777. * @param parentNode | Node object
  12778. * @private
  12779. */
  12780. _validateEdges : function(parentNode) {
  12781. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12782. var edge = parentNode.dynamicEdges[i];
  12783. if (parentNode.id != edge.toId && parentNode.id != edge.fromId) {
  12784. parentNode.dynamicEdges.splice(i,1);
  12785. }
  12786. }
  12787. },
  12788. /**
  12789. * This function released the contained edges back into the global domain and puts them back into the
  12790. * dynamic edges of both parent and child.
  12791. *
  12792. * @param {Node} parentNode |
  12793. * @param {Node} childNode |
  12794. * @private
  12795. */
  12796. _releaseContainedEdges : function(parentNode, childNode) {
  12797. for (var i = 0; i < parentNode.containedEdges[childNode.id].length; i++) {
  12798. var edge = parentNode.containedEdges[childNode.id][i];
  12799. // put the edge back in the global edges object
  12800. this.edges[edge.id] = edge;
  12801. // put the edge back in the dynamic edges of the child and parent
  12802. childNode.dynamicEdges.push(edge);
  12803. parentNode.dynamicEdges.push(edge);
  12804. }
  12805. // remove the entry from the contained edges
  12806. delete parentNode.containedEdges[childNode.id];
  12807. },
  12808. // ------------------- UTILITY FUNCTIONS ---------------------------- //
  12809. /**
  12810. * This updates the node labels for all nodes (for debugging purposes)
  12811. */
  12812. updateLabels : function() {
  12813. var nodeId;
  12814. // update node labels
  12815. for (nodeId in this.nodes) {
  12816. if (this.nodes.hasOwnProperty(nodeId)) {
  12817. var node = this.nodes[nodeId];
  12818. if (node.clusterSize > 1) {
  12819. node.label = "[".concat(String(node.clusterSize),"]");
  12820. }
  12821. }
  12822. }
  12823. // update node labels
  12824. for (nodeId in this.nodes) {
  12825. if (this.nodes.hasOwnProperty(nodeId)) {
  12826. node = this.nodes[nodeId];
  12827. if (node.clusterSize == 1) {
  12828. if (node.originalLabel !== undefined) {
  12829. node.label = node.originalLabel;
  12830. }
  12831. else {
  12832. node.label = String(node.id);
  12833. }
  12834. }
  12835. }
  12836. }
  12837. // /* Debug Override */
  12838. // for (nodeId in this.nodes) {
  12839. // if (this.nodes.hasOwnProperty(nodeId)) {
  12840. // node = this.nodes[nodeId];
  12841. // node.label = String(node.level);
  12842. // }
  12843. // }
  12844. },
  12845. /**
  12846. * We want to keep the cluster level distribution rather small. This means we do not want unclustered nodes
  12847. * if the rest of the nodes are already a few cluster levels in.
  12848. * To fix this we use this function. It determines the min and max cluster level and sends nodes that have not
  12849. * clustered enough to the clusterToSmallestNeighbours function.
  12850. */
  12851. normalizeClusterLevels : function() {
  12852. var maxLevel = 0;
  12853. var minLevel = 1e9;
  12854. var clusterLevel = 0;
  12855. // we loop over all nodes in the list
  12856. for (var nodeId in this.nodes) {
  12857. if (this.nodes.hasOwnProperty(nodeId)) {
  12858. clusterLevel = this.nodes[nodeId].clusterSessions.length;
  12859. if (maxLevel < clusterLevel) {maxLevel = clusterLevel;}
  12860. if (minLevel > clusterLevel) {minLevel = clusterLevel;}
  12861. }
  12862. }
  12863. if (maxLevel - minLevel > this.constants.clustering.clusterLevelDifference) {
  12864. var amountOfNodes = this.nodeIndices.length;
  12865. var targetLevel = maxLevel - this.constants.clustering.clusterLevelDifference;
  12866. // we loop over all nodes in the list
  12867. for (var nodeId in this.nodes) {
  12868. if (this.nodes.hasOwnProperty(nodeId)) {
  12869. if (this.nodes[nodeId].clusterSessions.length < targetLevel) {
  12870. this._clusterToSmallestNeighbour(this.nodes[nodeId]);
  12871. }
  12872. }
  12873. }
  12874. this._updateNodeIndexList();
  12875. this._updateDynamicEdges();
  12876. // if a cluster was formed, we increase the clusterSession
  12877. if (this.nodeIndices.length != amountOfNodes) {
  12878. this.clusterSession += 1;
  12879. }
  12880. }
  12881. },
  12882. /**
  12883. * This function determines if the cluster we want to decluster is in the active area
  12884. * this means around the zoom center
  12885. *
  12886. * @param {Node} node
  12887. * @returns {boolean}
  12888. * @private
  12889. */
  12890. _nodeInActiveArea : function(node) {
  12891. return (
  12892. Math.abs(node.x - this.areaCenter.x) <= this.constants.clustering.activeAreaBoxSize/this.scale
  12893. &&
  12894. Math.abs(node.y - this.areaCenter.y) <= this.constants.clustering.activeAreaBoxSize/this.scale
  12895. )
  12896. },
  12897. /**
  12898. * This is an adaptation of the original repositioning function. This is called if the system is clustered initially
  12899. * It puts large clusters away from the center and randomizes the order.
  12900. *
  12901. */
  12902. repositionNodes : function() {
  12903. for (var i = 0; i < this.nodeIndices.length; i++) {
  12904. var node = this.nodes[this.nodeIndices[i]];
  12905. if ((node.xFixed == false || node.yFixed == false) && this.createNodeOnClick != true) {
  12906. var radius = this.constants.physics.springLength * Math.min(100,node.mass);
  12907. var angle = 2 * Math.PI * Math.random();
  12908. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  12909. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  12910. this._repositionBezierNodes(node);
  12911. }
  12912. }
  12913. },
  12914. /**
  12915. * We determine how many connections denote an important hub.
  12916. * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%)
  12917. *
  12918. * @private
  12919. */
  12920. _getHubSize : function() {
  12921. var average = 0;
  12922. var averageSquared = 0;
  12923. var hubCounter = 0;
  12924. var largestHub = 0;
  12925. for (var i = 0; i < this.nodeIndices.length; i++) {
  12926. var node = this.nodes[this.nodeIndices[i]];
  12927. if (node.dynamicEdgesLength > largestHub) {
  12928. largestHub = node.dynamicEdgesLength;
  12929. }
  12930. average += node.dynamicEdgesLength;
  12931. averageSquared += Math.pow(node.dynamicEdgesLength,2);
  12932. hubCounter += 1;
  12933. }
  12934. average = average / hubCounter;
  12935. averageSquared = averageSquared / hubCounter;
  12936. var variance = averageSquared - Math.pow(average,2);
  12937. var standardDeviation = Math.sqrt(variance);
  12938. this.hubThreshold = Math.floor(average + 2*standardDeviation);
  12939. // always have at least one to cluster
  12940. if (this.hubThreshold > largestHub) {
  12941. this.hubThreshold = largestHub;
  12942. }
  12943. // console.log("average",average,"averageSQ",averageSquared,"var",variance,"std",standardDeviation);
  12944. // console.log("hubThreshold:",this.hubThreshold);
  12945. },
  12946. /**
  12947. * We reduce the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  12948. * with this amount we can cluster specifically on these chains.
  12949. *
  12950. * @param {Number} fraction | between 0 and 1, the percentage of chains to reduce
  12951. * @private
  12952. */
  12953. _reduceAmountOfChains : function(fraction) {
  12954. this.hubThreshold = 2;
  12955. var reduceAmount = Math.floor(this.nodeIndices.length * fraction);
  12956. for (var nodeId in this.nodes) {
  12957. if (this.nodes.hasOwnProperty(nodeId)) {
  12958. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  12959. if (reduceAmount > 0) {
  12960. this._formClusterFromHub(this.nodes[nodeId],true,true,1);
  12961. reduceAmount -= 1;
  12962. }
  12963. }
  12964. }
  12965. }
  12966. },
  12967. /**
  12968. * We get the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  12969. * with this amount we can cluster specifically on these chains.
  12970. *
  12971. * @private
  12972. */
  12973. _getChainFraction : function() {
  12974. var chains = 0;
  12975. var total = 0;
  12976. for (var nodeId in this.nodes) {
  12977. if (this.nodes.hasOwnProperty(nodeId)) {
  12978. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  12979. chains += 1;
  12980. }
  12981. total += 1;
  12982. }
  12983. }
  12984. return chains/total;
  12985. }
  12986. };
  12987. var SelectionMixin = {
  12988. /**
  12989. * This function can be called from the _doInAllSectors function
  12990. *
  12991. * @param object
  12992. * @param overlappingNodes
  12993. * @private
  12994. */
  12995. _getNodesOverlappingWith : function(object, overlappingNodes) {
  12996. var nodes = this.nodes;
  12997. for (var nodeId in nodes) {
  12998. if (nodes.hasOwnProperty(nodeId)) {
  12999. if (nodes[nodeId].isOverlappingWith(object)) {
  13000. overlappingNodes.push(nodeId);
  13001. }
  13002. }
  13003. }
  13004. },
  13005. /**
  13006. * retrieve all nodes overlapping with given object
  13007. * @param {Object} object An object with parameters left, top, right, bottom
  13008. * @return {Number[]} An array with id's of the overlapping nodes
  13009. * @private
  13010. */
  13011. _getAllNodesOverlappingWith : function (object) {
  13012. var overlappingNodes = [];
  13013. this._doInAllActiveSectors("_getNodesOverlappingWith",object,overlappingNodes);
  13014. return overlappingNodes;
  13015. },
  13016. /**
  13017. * Return a position object in canvasspace from a single point in screenspace
  13018. *
  13019. * @param pointer
  13020. * @returns {{left: number, top: number, right: number, bottom: number}}
  13021. * @private
  13022. */
  13023. _pointerToPositionObject : function(pointer) {
  13024. var x = this._canvasToX(pointer.x);
  13025. var y = this._canvasToY(pointer.y);
  13026. return {left: x,
  13027. top: y,
  13028. right: x,
  13029. bottom: y};
  13030. },
  13031. /**
  13032. * Get the top node at the a specific point (like a click)
  13033. *
  13034. * @param {{x: Number, y: Number}} pointer
  13035. * @return {Node | null} node
  13036. * @private
  13037. */
  13038. _getNodeAt : function (pointer) {
  13039. // we first check if this is an navigation controls element
  13040. var positionObject = this._pointerToPositionObject(pointer);
  13041. var overlappingNodes = this._getAllNodesOverlappingWith(positionObject);
  13042. // if there are overlapping nodes, select the last one, this is the
  13043. // one which is drawn on top of the others
  13044. if (overlappingNodes.length > 0) {
  13045. return this.nodes[overlappingNodes[overlappingNodes.length - 1]];
  13046. }
  13047. else {
  13048. return null;
  13049. }
  13050. },
  13051. /**
  13052. * retrieve all edges overlapping with given object, selector is around center
  13053. * @param {Object} object An object with parameters left, top, right, bottom
  13054. * @return {Number[]} An array with id's of the overlapping nodes
  13055. * @private
  13056. */
  13057. _getEdgesOverlappingWith : function (object, overlappingEdges) {
  13058. var edges = this.edges;
  13059. for (var edgeId in edges) {
  13060. if (edges.hasOwnProperty(edgeId)) {
  13061. if (edges[edgeId].isOverlappingWith(object)) {
  13062. overlappingEdges.push(edgeId);
  13063. }
  13064. }
  13065. }
  13066. },
  13067. /**
  13068. * retrieve all nodes overlapping with given object
  13069. * @param {Object} object An object with parameters left, top, right, bottom
  13070. * @return {Number[]} An array with id's of the overlapping nodes
  13071. * @private
  13072. */
  13073. _getAllEdgesOverlappingWith : function (object) {
  13074. var overlappingEdges = [];
  13075. this._doInAllActiveSectors("_getEdgesOverlappingWith",object,overlappingEdges);
  13076. return overlappingEdges;
  13077. },
  13078. /**
  13079. * Place holder. To implement change the _getNodeAt to a _getObjectAt. Have the _getObjectAt call
  13080. * _getNodeAt and _getEdgesAt, then priortize the selection to user preferences.
  13081. *
  13082. * @param pointer
  13083. * @returns {null}
  13084. * @private
  13085. */
  13086. _getEdgeAt : function(pointer) {
  13087. var positionObject = this._pointerToPositionObject(pointer);
  13088. var overlappingEdges = this._getAllEdgesOverlappingWith(positionObject);
  13089. if (overlappingEdges.length > 0) {
  13090. return this.edges[overlappingEdges[overlappingEdges.length - 1]];
  13091. }
  13092. else {
  13093. return null;
  13094. }
  13095. },
  13096. /**
  13097. * Add object to the selection array.
  13098. *
  13099. * @param obj
  13100. * @private
  13101. */
  13102. _addToSelection : function(obj) {
  13103. this.selectionObj[obj.id] = obj;
  13104. },
  13105. /**
  13106. * Remove a single option from selection.
  13107. *
  13108. * @param {Object} obj
  13109. * @private
  13110. */
  13111. _removeFromSelection : function(obj) {
  13112. delete this.selectionObj[obj.id];
  13113. },
  13114. /**
  13115. * Unselect all. The selectionObj is useful for this.
  13116. *
  13117. * @param {Boolean} [doNotTrigger] | ignore trigger
  13118. * @private
  13119. */
  13120. _unselectAll : function(doNotTrigger) {
  13121. if (doNotTrigger === undefined) {
  13122. doNotTrigger = false;
  13123. }
  13124. for (var objectId in this.selectionObj) {
  13125. if (this.selectionObj.hasOwnProperty(objectId)) {
  13126. this.selectionObj[objectId].unselect();
  13127. }
  13128. }
  13129. this.selectionObj = {};
  13130. if (doNotTrigger == false) {
  13131. this.emit('select', this.getSelection());
  13132. }
  13133. },
  13134. /**
  13135. * Unselect all clusters. The selectionObj is useful for this.
  13136. *
  13137. * @param {Boolean} [doNotTrigger] | ignore trigger
  13138. * @private
  13139. */
  13140. _unselectClusters : function(doNotTrigger) {
  13141. if (doNotTrigger === undefined) {
  13142. doNotTrigger = false;
  13143. }
  13144. for (var objectId in this.selectionObj) {
  13145. if (this.selectionObj.hasOwnProperty(objectId)) {
  13146. if (this.selectionObj[objectId] instanceof Node) {
  13147. if (this.selectionObj[objectId].clusterSize > 1) {
  13148. this.selectionObj[objectId].unselect();
  13149. this._removeFromSelection(this.selectionObj[objectId]);
  13150. }
  13151. }
  13152. }
  13153. }
  13154. if (doNotTrigger == false) {
  13155. this.emit('select', this.getSelection());
  13156. }
  13157. },
  13158. /**
  13159. * return the number of selected nodes
  13160. *
  13161. * @returns {number}
  13162. * @private
  13163. */
  13164. _getSelectedNodeCount : function() {
  13165. var count = 0;
  13166. for (var objectId in this.selectionObj) {
  13167. if (this.selectionObj.hasOwnProperty(objectId)) {
  13168. if (this.selectionObj[objectId] instanceof Node) {
  13169. count += 1;
  13170. }
  13171. }
  13172. }
  13173. return count;
  13174. },
  13175. /**
  13176. * return the number of selected nodes
  13177. *
  13178. * @returns {number}
  13179. * @private
  13180. */
  13181. _getSelectedNode : function() {
  13182. for (var objectId in this.selectionObj) {
  13183. if (this.selectionObj.hasOwnProperty(objectId)) {
  13184. if (this.selectionObj[objectId] instanceof Node) {
  13185. return this.selectionObj[objectId];
  13186. }
  13187. }
  13188. }
  13189. return null;
  13190. },
  13191. /**
  13192. * return the number of selected edges
  13193. *
  13194. * @returns {number}
  13195. * @private
  13196. */
  13197. _getSelectedEdgeCount : function() {
  13198. var count = 0;
  13199. for (var objectId in this.selectionObj) {
  13200. if (this.selectionObj.hasOwnProperty(objectId)) {
  13201. if (this.selectionObj[objectId] instanceof Edge) {
  13202. count += 1;
  13203. }
  13204. }
  13205. }
  13206. return count;
  13207. },
  13208. /**
  13209. * return the number of selected objects.
  13210. *
  13211. * @returns {number}
  13212. * @private
  13213. */
  13214. _getSelectedObjectCount : function() {
  13215. var count = 0;
  13216. for (var objectId in this.selectionObj) {
  13217. if (this.selectionObj.hasOwnProperty(objectId)) {
  13218. count += 1;
  13219. }
  13220. }
  13221. return count;
  13222. },
  13223. /**
  13224. * Check if anything is selected
  13225. *
  13226. * @returns {boolean}
  13227. * @private
  13228. */
  13229. _selectionIsEmpty : function() {
  13230. for(var objectId in this.selectionObj) {
  13231. if(this.selectionObj.hasOwnProperty(objectId)) {
  13232. return false;
  13233. }
  13234. }
  13235. return true;
  13236. },
  13237. /**
  13238. * check if one of the selected nodes is a cluster.
  13239. *
  13240. * @returns {boolean}
  13241. * @private
  13242. */
  13243. _clusterInSelection : function() {
  13244. for(var objectId in this.selectionObj) {
  13245. if(this.selectionObj.hasOwnProperty(objectId)) {
  13246. if (this.selectionObj[objectId] instanceof Node) {
  13247. if (this.selectionObj[objectId].clusterSize > 1) {
  13248. return true;
  13249. }
  13250. }
  13251. }
  13252. }
  13253. return false;
  13254. },
  13255. /**
  13256. * select the edges connected to the node that is being selected
  13257. *
  13258. * @param {Node} node
  13259. * @private
  13260. */
  13261. _selectConnectedEdges : function(node) {
  13262. for (var i = 0; i < node.dynamicEdges.length; i++) {
  13263. var edge = node.dynamicEdges[i];
  13264. edge.select();
  13265. this._addToSelection(edge);
  13266. }
  13267. },
  13268. /**
  13269. * unselect the edges connected to the node that is being selected
  13270. *
  13271. * @param {Node} node
  13272. * @private
  13273. */
  13274. _unselectConnectedEdges : function(node) {
  13275. for (var i = 0; i < node.dynamicEdges.length; i++) {
  13276. var edge = node.dynamicEdges[i];
  13277. edge.unselect();
  13278. this._removeFromSelection(edge);
  13279. }
  13280. },
  13281. /**
  13282. * This is called when someone clicks on a node. either select or deselect it.
  13283. * If there is an existing selection and we don't want to append to it, clear the existing selection
  13284. *
  13285. * @param {Node || Edge} object
  13286. * @param {Boolean} append
  13287. * @param {Boolean} [doNotTrigger] | ignore trigger
  13288. * @private
  13289. */
  13290. _selectObject : function(object, append, doNotTrigger) {
  13291. if (doNotTrigger === undefined) {
  13292. doNotTrigger = false;
  13293. }
  13294. if (this._selectionIsEmpty() == false && append == false && this.forceAppendSelection == false) {
  13295. this._unselectAll(true);
  13296. }
  13297. if (object.selected == false) {
  13298. object.select();
  13299. this._addToSelection(object);
  13300. if (object instanceof Node && this.blockConnectingEdgeSelection == false) {
  13301. this._selectConnectedEdges(object);
  13302. }
  13303. }
  13304. else {
  13305. object.unselect();
  13306. this._removeFromSelection(object);
  13307. }
  13308. if (doNotTrigger == false) {
  13309. this.emit('select', this.getSelection());
  13310. }
  13311. },
  13312. /**
  13313. * handles the selection part of the touch, only for navigation controls elements;
  13314. * Touch is triggered before tap, also before hold. Hold triggers after a while.
  13315. * This is the most responsive solution
  13316. *
  13317. * @param {Object} pointer
  13318. * @private
  13319. */
  13320. _handleTouch : function(pointer) {
  13321. },
  13322. /**
  13323. * handles the selection part of the tap;
  13324. *
  13325. * @param {Object} pointer
  13326. * @private
  13327. */
  13328. _handleTap : function(pointer) {
  13329. var node = this._getNodeAt(pointer);
  13330. if (node != null) {
  13331. this._selectObject(node,false);
  13332. }
  13333. else {
  13334. var edge = this._getEdgeAt(pointer);
  13335. if (edge != null) {
  13336. this._selectObject(edge,false);
  13337. }
  13338. else {
  13339. this._unselectAll();
  13340. }
  13341. }
  13342. this.emit("click", this.getSelection());
  13343. this._redraw();
  13344. },
  13345. /**
  13346. * handles the selection part of the double tap and opens a cluster if needed
  13347. *
  13348. * @param {Object} pointer
  13349. * @private
  13350. */
  13351. _handleDoubleTap : function(pointer) {
  13352. var node = this._getNodeAt(pointer);
  13353. if (node != null && node !== undefined) {
  13354. // we reset the areaCenter here so the opening of the node will occur
  13355. this.areaCenter = {"x" : this._canvasToX(pointer.x),
  13356. "y" : this._canvasToY(pointer.y)};
  13357. this.openCluster(node);
  13358. }
  13359. this.emit("doubleClick", this.getSelection());
  13360. },
  13361. /**
  13362. * Handle the onHold selection part
  13363. *
  13364. * @param pointer
  13365. * @private
  13366. */
  13367. _handleOnHold : function(pointer) {
  13368. var node = this._getNodeAt(pointer);
  13369. if (node != null) {
  13370. this._selectObject(node,true);
  13371. }
  13372. else {
  13373. var edge = this._getEdgeAt(pointer);
  13374. if (edge != null) {
  13375. this._selectObject(edge,true);
  13376. }
  13377. }
  13378. this._redraw();
  13379. },
  13380. /**
  13381. * handle the onRelease event. These functions are here for the navigation controls module.
  13382. *
  13383. * @private
  13384. */
  13385. _handleOnRelease : function(pointer) {
  13386. },
  13387. /**
  13388. *
  13389. * retrieve the currently selected objects
  13390. * @return {Number[] | String[]} selection An array with the ids of the
  13391. * selected nodes.
  13392. */
  13393. getSelection : function() {
  13394. var nodeIds = this.getSelectedNodes();
  13395. var edgeIds = this.getSelectedEdges();
  13396. return {nodes:nodeIds, edges:edgeIds};
  13397. },
  13398. /**
  13399. *
  13400. * retrieve the currently selected nodes
  13401. * @return {String} selection An array with the ids of the
  13402. * selected nodes.
  13403. */
  13404. getSelectedNodes : function() {
  13405. var idArray = [];
  13406. for(var objectId in this.selectionObj) {
  13407. if(this.selectionObj.hasOwnProperty(objectId)) {
  13408. if (this.selectionObj[objectId] instanceof Node) {
  13409. idArray.push(objectId);
  13410. }
  13411. }
  13412. }
  13413. return idArray
  13414. },
  13415. /**
  13416. *
  13417. * retrieve the currently selected edges
  13418. * @return {Array} selection An array with the ids of the
  13419. * selected nodes.
  13420. */
  13421. getSelectedEdges : function() {
  13422. var idArray = [];
  13423. for(var objectId in this.selectionObj) {
  13424. if(this.selectionObj.hasOwnProperty(objectId)) {
  13425. if (this.selectionObj[objectId] instanceof Edge) {
  13426. idArray.push(objectId);
  13427. }
  13428. }
  13429. }
  13430. return idArray
  13431. },
  13432. /**
  13433. * select zero or more nodes
  13434. * @param {Number[] | String[]} selection An array with the ids of the
  13435. * selected nodes.
  13436. */
  13437. setSelection : function(selection) {
  13438. var i, iMax, id;
  13439. if (!selection || (selection.length == undefined))
  13440. throw 'Selection must be an array with ids';
  13441. // first unselect any selected node
  13442. this._unselectAll(true);
  13443. for (i = 0, iMax = selection.length; i < iMax; i++) {
  13444. id = selection[i];
  13445. var node = this.nodes[id];
  13446. if (!node) {
  13447. throw new RangeError('Node with id "' + id + '" not found');
  13448. }
  13449. this._selectObject(node,true,true);
  13450. }
  13451. this.redraw();
  13452. },
  13453. /**
  13454. * Validate the selection: remove ids of nodes which no longer exist
  13455. * @private
  13456. */
  13457. _updateSelection : function () {
  13458. for(var objectId in this.selectionObj) {
  13459. if(this.selectionObj.hasOwnProperty(objectId)) {
  13460. if (this.selectionObj[objectId] instanceof Node) {
  13461. if (!this.nodes.hasOwnProperty(objectId)) {
  13462. delete this.selectionObj[objectId];
  13463. }
  13464. }
  13465. else { // assuming only edges and nodes are selected
  13466. if (!this.edges.hasOwnProperty(objectId)) {
  13467. delete this.selectionObj[objectId];
  13468. }
  13469. }
  13470. }
  13471. }
  13472. }
  13473. };
  13474. /**
  13475. * Created by Alex on 1/22/14.
  13476. */
  13477. var NavigationMixin = {
  13478. _cleanNavigation : function() {
  13479. // clean up previosu navigation items
  13480. var wrapper = document.getElementById('graph-navigation_wrapper');
  13481. if (wrapper != null) {
  13482. this.containerElement.removeChild(wrapper);
  13483. }
  13484. document.onmouseup = null;
  13485. },
  13486. /**
  13487. * Creation of the navigation controls nodes. They are drawn over the rest of the nodes and are not affected by scale and translation
  13488. * they have a triggerFunction which is called on click. If the position of the navigation controls is dependent
  13489. * on this.frame.canvas.clientWidth or this.frame.canvas.clientHeight, we flag horizontalAlignLeft and verticalAlignTop false.
  13490. * This means that the location will be corrected by the _relocateNavigation function on a size change of the canvas.
  13491. *
  13492. * @private
  13493. */
  13494. _loadNavigationElements : function() {
  13495. this._cleanNavigation();
  13496. this.navigationDivs = {};
  13497. var navigationDivs = ['up','down','left','right','zoomIn','zoomOut','zoomExtends'];
  13498. var navigationDivActions = ['_moveUp','_moveDown','_moveLeft','_moveRight','_zoomIn','_zoomOut','zoomExtent'];
  13499. this.navigationDivs['wrapper'] = document.createElement('div');
  13500. this.navigationDivs['wrapper'].id = "graph-navigation_wrapper";
  13501. this.navigationDivs['wrapper'].style.position = "absolute";
  13502. this.navigationDivs['wrapper'].style.width = this.frame.canvas.clientWidth + "px";
  13503. this.navigationDivs['wrapper'].style.height = this.frame.canvas.clientHeight + "px";
  13504. this.containerElement.insertBefore(this.navigationDivs['wrapper'],this.frame);
  13505. for (var i = 0; i < navigationDivs.length; i++) {
  13506. this.navigationDivs[navigationDivs[i]] = document.createElement('div');
  13507. this.navigationDivs[navigationDivs[i]].id = "graph-navigation_" + navigationDivs[i];
  13508. this.navigationDivs[navigationDivs[i]].className = "graph-navigation " + navigationDivs[i];
  13509. this.navigationDivs['wrapper'].appendChild(this.navigationDivs[navigationDivs[i]]);
  13510. this.navigationDivs[navigationDivs[i]].onmousedown = this[navigationDivActions[i]].bind(this);
  13511. }
  13512. document.onmouseup = this._stopMovement.bind(this);
  13513. },
  13514. /**
  13515. * this stops all movement induced by the navigation buttons
  13516. *
  13517. * @private
  13518. */
  13519. _stopMovement : function() {
  13520. this._xStopMoving();
  13521. this._yStopMoving();
  13522. this._stopZoom();
  13523. },
  13524. /**
  13525. * stops the actions performed by page up and down etc.
  13526. *
  13527. * @param event
  13528. * @private
  13529. */
  13530. _preventDefault : function(event) {
  13531. if (event !== undefined) {
  13532. if (event.preventDefault) {
  13533. event.preventDefault();
  13534. } else {
  13535. event.returnValue = false;
  13536. }
  13537. }
  13538. },
  13539. /**
  13540. * move the screen up
  13541. * By using the increments, instead of adding a fixed number to the translation, we keep fluent and
  13542. * instant movement. The onKeypress event triggers immediately, then pauses, then triggers frequently
  13543. * To avoid this behaviour, we do the translation in the start loop.
  13544. *
  13545. * @private
  13546. */
  13547. _moveUp : function(event) {
  13548. this.yIncrement = this.constants.keyboard.speed.y;
  13549. this.start(); // if there is no node movement, the calculation wont be done
  13550. this._preventDefault(event);
  13551. },
  13552. /**
  13553. * move the screen down
  13554. * @private
  13555. */
  13556. _moveDown : function(event) {
  13557. this.yIncrement = -this.constants.keyboard.speed.y;
  13558. this.start(); // if there is no node movement, the calculation wont be done
  13559. this._preventDefault(event);
  13560. },
  13561. /**
  13562. * move the screen left
  13563. * @private
  13564. */
  13565. _moveLeft : function(event) {
  13566. this.xIncrement = this.constants.keyboard.speed.x;
  13567. this.start(); // if there is no node movement, the calculation wont be done
  13568. this._preventDefault(event);
  13569. },
  13570. /**
  13571. * move the screen right
  13572. * @private
  13573. */
  13574. _moveRight : function(event) {
  13575. this.xIncrement = -this.constants.keyboard.speed.y;
  13576. this.start(); // if there is no node movement, the calculation wont be done
  13577. this._preventDefault(event);
  13578. },
  13579. /**
  13580. * Zoom in, using the same method as the movement.
  13581. * @private
  13582. */
  13583. _zoomIn : function(event) {
  13584. this.zoomIncrement = this.constants.keyboard.speed.zoom;
  13585. this.start(); // if there is no node movement, the calculation wont be done
  13586. this._preventDefault(event);
  13587. },
  13588. /**
  13589. * Zoom out
  13590. * @private
  13591. */
  13592. _zoomOut : function() {
  13593. this.zoomIncrement = -this.constants.keyboard.speed.zoom;
  13594. this.start(); // if there is no node movement, the calculation wont be done
  13595. this._preventDefault(event);
  13596. },
  13597. /**
  13598. * Stop zooming and unhighlight the zoom controls
  13599. * @private
  13600. */
  13601. _stopZoom : function() {
  13602. this.zoomIncrement = 0;
  13603. },
  13604. /**
  13605. * Stop moving in the Y direction and unHighlight the up and down
  13606. * @private
  13607. */
  13608. _yStopMoving : function() {
  13609. this.yIncrement = 0;
  13610. },
  13611. /**
  13612. * Stop moving in the X direction and unHighlight left and right.
  13613. * @private
  13614. */
  13615. _xStopMoving : function() {
  13616. this.xIncrement = 0;
  13617. }
  13618. };
  13619. /**
  13620. * Created by Alex on 2/10/14.
  13621. */
  13622. var graphMixinLoaders = {
  13623. /**
  13624. * Load a mixin into the graph object
  13625. *
  13626. * @param {Object} sourceVariable | this object has to contain functions.
  13627. * @private
  13628. */
  13629. _loadMixin : function(sourceVariable) {
  13630. for (var mixinFunction in sourceVariable) {
  13631. if (sourceVariable.hasOwnProperty(mixinFunction)) {
  13632. Graph.prototype[mixinFunction] = sourceVariable[mixinFunction];
  13633. }
  13634. }
  13635. },
  13636. /**
  13637. * removes a mixin from the graph object.
  13638. *
  13639. * @param {Object} sourceVariable | this object has to contain functions.
  13640. * @private
  13641. */
  13642. _clearMixin : function(sourceVariable) {
  13643. for (var mixinFunction in sourceVariable) {
  13644. if (sourceVariable.hasOwnProperty(mixinFunction)) {
  13645. Graph.prototype[mixinFunction] = undefined;
  13646. }
  13647. }
  13648. },
  13649. /**
  13650. * Mixin the physics system and initialize the parameters required.
  13651. *
  13652. * @private
  13653. */
  13654. _loadPhysicsSystem : function() {
  13655. this._loadMixin(physicsMixin);
  13656. this._loadSelectedForceSolver();
  13657. if (this.constants.configurePhysics == true) {
  13658. this._loadPhysicsConfiguration();
  13659. }
  13660. },
  13661. /**
  13662. * Mixin the cluster system and initialize the parameters required.
  13663. *
  13664. * @private
  13665. */
  13666. _loadClusterSystem : function() {
  13667. this.clusterSession = 0;
  13668. this.hubThreshold = 5;
  13669. this._loadMixin(ClusterMixin);
  13670. },
  13671. /**
  13672. * Mixin the sector system and initialize the parameters required
  13673. *
  13674. * @private
  13675. */
  13676. _loadSectorSystem : function() {
  13677. this.sectors = { },
  13678. this.activeSector = ["default"];
  13679. this.sectors["active"] = { },
  13680. this.sectors["active"]["default"] = {"nodes":{},
  13681. "edges":{},
  13682. "nodeIndices":[],
  13683. "formationScale": 1.0,
  13684. "drawingNode": undefined };
  13685. this.sectors["frozen"] = {},
  13686. this.sectors["support"] = {"nodes":{},
  13687. "edges":{},
  13688. "nodeIndices":[],
  13689. "formationScale": 1.0,
  13690. "drawingNode": undefined };
  13691. this.nodeIndices = this.sectors["active"]["default"]["nodeIndices"]; // the node indices list is used to speed up the computation of the repulsion fields
  13692. this._loadMixin(SectorMixin);
  13693. },
  13694. /**
  13695. * Mixin the selection system and initialize the parameters required
  13696. *
  13697. * @private
  13698. */
  13699. _loadSelectionSystem : function() {
  13700. this.selectionObj = { };
  13701. this._loadMixin(SelectionMixin);
  13702. },
  13703. /**
  13704. * Mixin the navigationUI (User Interface) system and initialize the parameters required
  13705. *
  13706. * @private
  13707. */
  13708. _loadManipulationSystem : function() {
  13709. // reset global variables -- these are used by the selection of nodes and edges.
  13710. this.blockConnectingEdgeSelection = false;
  13711. this.forceAppendSelection = false
  13712. if (this.constants.dataManipulation.enabled == true) {
  13713. // load the manipulator HTML elements. All styling done in css.
  13714. if (this.manipulationDiv === undefined) {
  13715. this.manipulationDiv = document.createElement('div');
  13716. this.manipulationDiv.className = 'graph-manipulationDiv';
  13717. this.manipulationDiv.id = 'graph-manipulationDiv';
  13718. if (this.editMode == true) {
  13719. this.manipulationDiv.style.display = "block";
  13720. }
  13721. else {
  13722. this.manipulationDiv.style.display = "none";
  13723. }
  13724. this.containerElement.insertBefore(this.manipulationDiv, this.frame);
  13725. }
  13726. if (this.editModeDiv === undefined) {
  13727. this.editModeDiv = document.createElement('div');
  13728. this.editModeDiv.className = 'graph-manipulation-editMode';
  13729. this.editModeDiv.id = 'graph-manipulation-editMode';
  13730. if (this.editMode == true) {
  13731. this.editModeDiv.style.display = "none";
  13732. }
  13733. else {
  13734. this.editModeDiv.style.display = "block";
  13735. }
  13736. this.containerElement.insertBefore(this.editModeDiv, this.frame);
  13737. }
  13738. if (this.closeDiv === undefined) {
  13739. this.closeDiv = document.createElement('div');
  13740. this.closeDiv.className = 'graph-manipulation-closeDiv';
  13741. this.closeDiv.id = 'graph-manipulation-closeDiv';
  13742. this.closeDiv.style.display = this.manipulationDiv.style.display;
  13743. this.containerElement.insertBefore(this.closeDiv, this.frame);
  13744. }
  13745. // load the manipulation functions
  13746. this._loadMixin(manipulationMixin);
  13747. // create the manipulator toolbar
  13748. this._createManipulatorBar();
  13749. }
  13750. else {
  13751. if (this.manipulationDiv !== undefined) {
  13752. // removes all the bindings and overloads
  13753. this._createManipulatorBar();
  13754. // remove the manipulation divs
  13755. this.containerElement.removeChild(this.manipulationDiv);
  13756. this.containerElement.removeChild(this.editModeDiv);
  13757. this.containerElement.removeChild(this.closeDiv);
  13758. this.manipulationDiv = undefined;
  13759. this.editModeDiv = undefined;
  13760. this.closeDiv = undefined;
  13761. // remove the mixin functions
  13762. this._clearMixin(manipulationMixin);
  13763. }
  13764. }
  13765. },
  13766. /**
  13767. * Mixin the navigation (User Interface) system and initialize the parameters required
  13768. *
  13769. * @private
  13770. */
  13771. _loadNavigationControls : function() {
  13772. this._loadMixin(NavigationMixin);
  13773. // the clean function removes the button divs, this is done to remove the bindings.
  13774. this._cleanNavigation();
  13775. if (this.constants.navigation.enabled == true) {
  13776. this._loadNavigationElements();
  13777. }
  13778. },
  13779. /**
  13780. * Mixin the hierarchical layout system.
  13781. *
  13782. * @private
  13783. */
  13784. _loadHierarchySystem : function() {
  13785. this._loadMixin(HierarchicalLayoutMixin);
  13786. }
  13787. }
  13788. /**
  13789. * @constructor Graph
  13790. * Create a graph visualization, displaying nodes and edges.
  13791. *
  13792. * @param {Element} container The DOM element in which the Graph will
  13793. * be created. Normally a div element.
  13794. * @param {Object} data An object containing parameters
  13795. * {Array} nodes
  13796. * {Array} edges
  13797. * @param {Object} options Options
  13798. */
  13799. function Graph (container, data, options) {
  13800. this._initializeMixinLoaders();
  13801. // create variables and set default values
  13802. this.containerElement = container;
  13803. this.width = '100%';
  13804. this.height = '100%';
  13805. // render and calculation settings
  13806. this.renderRefreshRate = 60; // hz (fps)
  13807. this.renderTimestep = 1000 / this.renderRefreshRate; // ms -- saves calculation later on
  13808. this.renderTime = 0.5 * this.renderTimestep; // measured time it takes to render a frame
  13809. this.maxRenderSteps = 3; // max amount of physics ticks per render step.
  13810. this.stabilize = true; // stabilize before displaying the graph
  13811. this.selectable = true;
  13812. // these functions are triggered when the dataset is edited
  13813. this.triggerFunctions = {add:null,edit:null,connect:null,delete:null};
  13814. // set constant values
  13815. this.constants = {
  13816. nodes: {
  13817. radiusMin: 5,
  13818. radiusMax: 20,
  13819. radius: 5,
  13820. shape: 'ellipse',
  13821. image: undefined,
  13822. widthMin: 16, // px
  13823. widthMax: 64, // px
  13824. fixed: false,
  13825. fontColor: 'black',
  13826. fontSize: 14, // px
  13827. fontFace: 'verdana',
  13828. level: -1,
  13829. color: {
  13830. border: '#2B7CE9',
  13831. background: '#97C2FC',
  13832. highlight: {
  13833. border: '#2B7CE9',
  13834. background: '#D2E5FF'
  13835. }
  13836. },
  13837. borderColor: '#2B7CE9',
  13838. backgroundColor: '#97C2FC',
  13839. highlightColor: '#D2E5FF',
  13840. group: undefined
  13841. },
  13842. edges: {
  13843. widthMin: 1,
  13844. widthMax: 15,
  13845. width: 1,
  13846. style: 'line',
  13847. color: {
  13848. color:'#848484',
  13849. highlight:'#848484'
  13850. },
  13851. fontColor: '#343434',
  13852. fontSize: 14, // px
  13853. fontFace: 'arial',
  13854. dash: {
  13855. length: 10,
  13856. gap: 5,
  13857. altLength: undefined
  13858. }
  13859. },
  13860. configurePhysics:false,
  13861. physics: {
  13862. barnesHut: {
  13863. enabled: true,
  13864. theta: 1 / 0.6, // inverted to save time during calculation
  13865. gravitationalConstant: -2000,
  13866. centralGravity: 0.3,
  13867. springLength: 95,
  13868. springConstant: 0.04,
  13869. damping: 0.09
  13870. },
  13871. repulsion: {
  13872. centralGravity: 0.1,
  13873. springLength: 200,
  13874. springConstant: 0.05,
  13875. nodeDistance: 100,
  13876. damping: 0.09
  13877. },
  13878. hierarchicalRepulsion: {
  13879. enabled: false,
  13880. centralGravity: 0.0,
  13881. springLength: 100,
  13882. springConstant: 0.01,
  13883. nodeDistance: 60,
  13884. damping: 0.09
  13885. },
  13886. damping: null,
  13887. centralGravity: null,
  13888. springLength: null,
  13889. springConstant: null
  13890. },
  13891. clustering: { // Per Node in Cluster = PNiC
  13892. enabled: false, // (Boolean) | global on/off switch for clustering.
  13893. initialMaxNodes: 100, // (# nodes) | if the initial amount of nodes is larger than this, we cluster until the total number is less than this threshold.
  13894. 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
  13895. 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
  13896. chainThreshold: 0.4, // (% of all drawn nodes)| maximum percentage of allowed chainnodes (long strings of connected nodes) within all nodes. (lower means less chains).
  13897. clusterEdgeThreshold: 20, // (px) | edge length threshold. if smaller, this node is clustered.
  13898. sectorThreshold: 100, // (# nodes in cluster) | cluster size threshold. If larger, expanding in own sector.
  13899. 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.
  13900. fontSizeMultiplier: 4.0, // (px PNiC) | how much the cluster font size grows per node in cluster (in px).
  13901. maxFontSize: 1000,
  13902. forceAmplification: 0.1, // (multiplier PNiC) | factor of increase fo the repulsion force of a cluster (per node in cluster).
  13903. distanceAmplification: 0.1, // (multiplier PNiC) | factor how much the repulsion distance of a cluster increases (per node in cluster).
  13904. edgeGrowth: 20, // (px PNiC) | amount of clusterSize connected to the edge is multiplied with this and added to edgeLength.
  13905. nodeScaling: {width: 1, // (px PNiC) | growth of the width per node in cluster.
  13906. height: 1, // (px PNiC) | growth of the height per node in cluster.
  13907. radius: 1}, // (px PNiC) | growth of the radius per node in cluster.
  13908. maxNodeSizeIncrements: 600, // (# increments) | max growth of the width per node in cluster.
  13909. activeAreaBoxSize: 80, // (px) | box area around the curser where clusters are popped open.
  13910. clusterLevelDifference: 2
  13911. },
  13912. navigation: {
  13913. enabled: false
  13914. },
  13915. keyboard: {
  13916. enabled: false,
  13917. speed: {x: 10, y: 10, zoom: 0.02}
  13918. },
  13919. dataManipulation: {
  13920. enabled: false,
  13921. initiallyVisible: false
  13922. },
  13923. hierarchicalLayout: {
  13924. enabled:false,
  13925. levelSeparation: 150,
  13926. nodeSpacing: 100,
  13927. direction: "UD" // UD, DU, LR, RL
  13928. },
  13929. smoothCurves: true,
  13930. maxVelocity: 10,
  13931. minVelocity: 0.1, // px/s
  13932. stabilizationIterations: 1000 // maximum number of iteration to stabilize
  13933. };
  13934. this.editMode = this.constants.dataManipulation.initiallyVisible;
  13935. // Node variables
  13936. var graph = this;
  13937. this.groups = new Groups(); // object with groups
  13938. this.images = new Images(); // object with images
  13939. this.images.setOnloadCallback(function () {
  13940. graph._redraw();
  13941. });
  13942. // keyboard navigation variables
  13943. this.xIncrement = 0;
  13944. this.yIncrement = 0;
  13945. this.zoomIncrement = 0;
  13946. // loading all the mixins:
  13947. // load the force calculation functions, grouped under the physics system.
  13948. this._loadPhysicsSystem();
  13949. // create a frame and canvas
  13950. this._create();
  13951. // load the sector system. (mandatory, fully integrated with Graph)
  13952. this._loadSectorSystem();
  13953. // load the cluster system. (mandatory, even when not using the cluster system, there are function calls to it)
  13954. this._loadClusterSystem();
  13955. // load the selection system. (mandatory, required by Graph)
  13956. this._loadSelectionSystem();
  13957. // load the selection system. (mandatory, required by Graph)
  13958. this._loadHierarchySystem();
  13959. // apply options
  13960. this.setOptions(options);
  13961. // other vars
  13962. this.freezeSimulation = false;// freeze the simulation
  13963. this.cachedFunctions = {};
  13964. // containers for nodes and edges
  13965. this.calculationNodes = {};
  13966. this.calculationNodeIndices = [];
  13967. this.nodeIndices = []; // array with all the indices of the nodes. Used to speed up forces calculation
  13968. this.nodes = {}; // object with Node objects
  13969. this.edges = {}; // object with Edge objects
  13970. // position and scale variables and objects
  13971. this.canvasTopLeft = {"x": 0,"y": 0}; // coordinates of the top left of the canvas. they will be set during _redraw.
  13972. this.canvasBottomRight = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  13973. this.pointerPosition = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  13974. this.areaCenter = {}; // object with x and y elements used for determining the center of the zoom action
  13975. this.scale = 1; // defining the global scale variable in the constructor
  13976. this.previousScale = this.scale; // this is used to check if the zoom operation is zooming in or out
  13977. // datasets or dataviews
  13978. this.nodesData = null; // A DataSet or DataView
  13979. this.edgesData = null; // A DataSet or DataView
  13980. // create event listeners used to subscribe on the DataSets of the nodes and edges
  13981. this.nodesListeners = {
  13982. 'add': function (event, params) {
  13983. graph._addNodes(params.items);
  13984. graph.start();
  13985. },
  13986. 'update': function (event, params) {
  13987. graph._updateNodes(params.items);
  13988. graph.start();
  13989. },
  13990. 'remove': function (event, params) {
  13991. graph._removeNodes(params.items);
  13992. graph.start();
  13993. }
  13994. };
  13995. this.edgesListeners = {
  13996. 'add': function (event, params) {
  13997. graph._addEdges(params.items);
  13998. graph.start();
  13999. },
  14000. 'update': function (event, params) {
  14001. graph._updateEdges(params.items);
  14002. graph.start();
  14003. },
  14004. 'remove': function (event, params) {
  14005. graph._removeEdges(params.items);
  14006. graph.start();
  14007. }
  14008. };
  14009. // properties for the animation
  14010. this.moving = true;
  14011. this.timer = undefined; // Scheduling function. Is definded in this.start();
  14012. // load data (the disable start variable will be the same as the enabled clustering)
  14013. this.setData(data,this.constants.clustering.enabled || this.constants.hierarchicalLayout.enabled);
  14014. // hierarchical layout
  14015. if (this.constants.hierarchicalLayout.enabled == true) {
  14016. this._setupHierarchicalLayout();
  14017. }
  14018. else {
  14019. // zoom so all data will fit on the screen, if clustering is enabled, we do not want start to be called here.
  14020. if (this.stabilize == false) {
  14021. this.zoomExtent(true,this.constants.clustering.enabled);
  14022. }
  14023. }
  14024. // if clustering is disabled, the simulation will have started in the setData function
  14025. if (this.constants.clustering.enabled) {
  14026. this.startWithClustering();
  14027. }
  14028. }
  14029. // Extend Graph with an Emitter mixin
  14030. Emitter(Graph.prototype);
  14031. /**
  14032. * Get the script path where the vis.js library is located
  14033. *
  14034. * @returns {string | null} path Path or null when not found. Path does not
  14035. * end with a slash.
  14036. * @private
  14037. */
  14038. Graph.prototype._getScriptPath = function() {
  14039. var scripts = document.getElementsByTagName( 'script' );
  14040. // find script named vis.js or vis.min.js
  14041. for (var i = 0; i < scripts.length; i++) {
  14042. var src = scripts[i].src;
  14043. var match = src && /\/?vis(.min)?\.js$/.exec(src);
  14044. if (match) {
  14045. // return path without the script name
  14046. return src.substring(0, src.length - match[0].length);
  14047. }
  14048. }
  14049. return null;
  14050. };
  14051. /**
  14052. * Find the center position of the graph
  14053. * @private
  14054. */
  14055. Graph.prototype._getRange = function() {
  14056. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  14057. for (var nodeId in this.nodes) {
  14058. if (this.nodes.hasOwnProperty(nodeId)) {
  14059. node = this.nodes[nodeId];
  14060. if (minX > (node.x)) {minX = node.x;}
  14061. if (maxX < (node.x)) {maxX = node.x;}
  14062. if (minY > (node.y)) {minY = node.y;}
  14063. if (maxY < (node.y)) {maxY = node.y;}
  14064. }
  14065. }
  14066. return {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  14067. };
  14068. /**
  14069. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  14070. * @returns {{x: number, y: number}}
  14071. * @private
  14072. */
  14073. Graph.prototype._findCenter = function(range) {
  14074. return {x: (0.5 * (range.maxX + range.minX)),
  14075. y: (0.5 * (range.maxY + range.minY))};
  14076. };
  14077. /**
  14078. * center the graph
  14079. *
  14080. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  14081. */
  14082. Graph.prototype._centerGraph = function(range) {
  14083. var center = this._findCenter(range);
  14084. center.x *= this.scale;
  14085. center.y *= this.scale;
  14086. center.x -= 0.5 * this.frame.canvas.clientWidth;
  14087. center.y -= 0.5 * this.frame.canvas.clientHeight;
  14088. this._setTranslation(-center.x,-center.y); // set at 0,0
  14089. };
  14090. /**
  14091. * This function zooms out to fit all data on screen based on amount of nodes
  14092. *
  14093. * @param {Boolean} [initialZoom] | zoom based on fitted formula or range, true = fitted, default = false;
  14094. */
  14095. Graph.prototype.zoomExtent = function(initialZoom, disableStart) {
  14096. if (initialZoom === undefined) {
  14097. initialZoom = false;
  14098. }
  14099. if (disableStart === undefined) {
  14100. disableStart = false;
  14101. }
  14102. var range = this._getRange();
  14103. var zoomLevel;
  14104. if (initialZoom == true) {
  14105. var numberOfNodes = this.nodeIndices.length;
  14106. if (this.constants.smoothCurves == true) {
  14107. if (this.constants.clustering.enabled == true &&
  14108. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  14109. 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.
  14110. }
  14111. else {
  14112. zoomLevel = 12.662 / (numberOfNodes + 7.4147) + 0.0964822; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  14113. }
  14114. }
  14115. else {
  14116. if (this.constants.clustering.enabled == true &&
  14117. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  14118. 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.
  14119. }
  14120. else {
  14121. zoomLevel = 30.5062972 / (numberOfNodes + 19.93597763) + 0.08413486; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  14122. }
  14123. }
  14124. // correct for larger canvasses.
  14125. var factor = Math.min(this.frame.canvas.clientWidth / 600, this.frame.canvas.clientHeight / 600);
  14126. zoomLevel *= factor;
  14127. }
  14128. else {
  14129. var xDistance = (Math.abs(range.minX) + Math.abs(range.maxX)) * 1.1;
  14130. var yDistance = (Math.abs(range.minY) + Math.abs(range.maxY)) * 1.1;
  14131. var xZoomLevel = this.frame.canvas.clientWidth / xDistance;
  14132. var yZoomLevel = this.frame.canvas.clientHeight / yDistance;
  14133. zoomLevel = (xZoomLevel <= yZoomLevel) ? xZoomLevel : yZoomLevel;
  14134. }
  14135. if (zoomLevel > 1.0) {
  14136. zoomLevel = 1.0;
  14137. }
  14138. this._setScale(zoomLevel);
  14139. this._centerGraph(range);
  14140. if (disableStart == false) {
  14141. this.moving = true;
  14142. this.start();
  14143. }
  14144. };
  14145. /**
  14146. * Update the this.nodeIndices with the most recent node index list
  14147. * @private
  14148. */
  14149. Graph.prototype._updateNodeIndexList = function() {
  14150. this._clearNodeIndexList();
  14151. for (var idx in this.nodes) {
  14152. if (this.nodes.hasOwnProperty(idx)) {
  14153. this.nodeIndices.push(idx);
  14154. }
  14155. }
  14156. };
  14157. /**
  14158. * Set nodes and edges, and optionally options as well.
  14159. *
  14160. * @param {Object} data Object containing parameters:
  14161. * {Array | DataSet | DataView} [nodes] Array with nodes
  14162. * {Array | DataSet | DataView} [edges] Array with edges
  14163. * {String} [dot] String containing data in DOT format
  14164. * {Options} [options] Object with options
  14165. * @param {Boolean} [disableStart] | optional: disable the calling of the start function.
  14166. */
  14167. Graph.prototype.setData = function(data, disableStart) {
  14168. if (disableStart === undefined) {
  14169. disableStart = false;
  14170. }
  14171. if (data && data.dot && (data.nodes || data.edges)) {
  14172. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  14173. ' parameter pair "nodes" and "edges", but not both.');
  14174. }
  14175. // set options
  14176. this.setOptions(data && data.options);
  14177. // set all data
  14178. if (data && data.dot) {
  14179. // parse DOT file
  14180. if(data && data.dot) {
  14181. var dotData = vis.util.DOTToGraph(data.dot);
  14182. this.setData(dotData);
  14183. return;
  14184. }
  14185. }
  14186. else {
  14187. this._setNodes(data && data.nodes);
  14188. this._setEdges(data && data.edges);
  14189. }
  14190. this._putDataInSector();
  14191. if (!disableStart) {
  14192. // find a stable position or start animating to a stable position
  14193. if (this.stabilize) {
  14194. this._stabilize();
  14195. }
  14196. this.start();
  14197. }
  14198. };
  14199. /**
  14200. * Set options
  14201. * @param {Object} options
  14202. */
  14203. Graph.prototype.setOptions = function (options) {
  14204. if (options) {
  14205. var prop;
  14206. // retrieve parameter values
  14207. if (options.width !== undefined) {this.width = options.width;}
  14208. if (options.height !== undefined) {this.height = options.height;}
  14209. if (options.stabilize !== undefined) {this.stabilize = options.stabilize;}
  14210. if (options.selectable !== undefined) {this.selectable = options.selectable;}
  14211. if (options.smoothCurves !== undefined) {this.constants.smoothCurves = options.smoothCurves;}
  14212. if (options.configurePhysics !== undefined){this.constants.configurePhysics = options.configurePhysics;}
  14213. if (options.stabilizationIterations !== undefined) {this.constants.stabilizationIterations = options.stabilizationIterations;}
  14214. if (options.onAdd) {
  14215. this.triggerFunctions.add = options.onAdd;
  14216. }
  14217. if (options.onEdit) {
  14218. this.triggerFunctions.edit = options.onEdit;
  14219. }
  14220. if (options.onConnect) {
  14221. this.triggerFunctions.connect = options.onConnect;
  14222. }
  14223. if (options.onDelete) {
  14224. this.triggerFunctions.delete = options.onDelete;
  14225. }
  14226. if (options.physics) {
  14227. if (options.physics.barnesHut) {
  14228. this.constants.physics.barnesHut.enabled = true;
  14229. for (prop in options.physics.barnesHut) {
  14230. if (options.physics.barnesHut.hasOwnProperty(prop)) {
  14231. this.constants.physics.barnesHut[prop] = options.physics.barnesHut[prop];
  14232. }
  14233. }
  14234. }
  14235. if (options.physics.repulsion) {
  14236. this.constants.physics.barnesHut.enabled = false;
  14237. for (prop in options.physics.repulsion) {
  14238. if (options.physics.repulsion.hasOwnProperty(prop)) {
  14239. this.constants.physics.repulsion[prop] = options.physics.repulsion[prop];
  14240. }
  14241. }
  14242. }
  14243. }
  14244. if (options.hierarchicalLayout) {
  14245. this.constants.hierarchicalLayout.enabled = true;
  14246. for (prop in options.hierarchicalLayout) {
  14247. if (options.hierarchicalLayout.hasOwnProperty(prop)) {
  14248. this.constants.hierarchicalLayout[prop] = options.hierarchicalLayout[prop];
  14249. }
  14250. }
  14251. }
  14252. else if (options.hierarchicalLayout !== undefined) {
  14253. this.constants.hierarchicalLayout.enabled = false;
  14254. }
  14255. if (options.clustering) {
  14256. this.constants.clustering.enabled = true;
  14257. for (prop in options.clustering) {
  14258. if (options.clustering.hasOwnProperty(prop)) {
  14259. this.constants.clustering[prop] = options.clustering[prop];
  14260. }
  14261. }
  14262. }
  14263. else if (options.clustering !== undefined) {
  14264. this.constants.clustering.enabled = false;
  14265. }
  14266. if (options.navigation) {
  14267. this.constants.navigation.enabled = true;
  14268. for (prop in options.navigation) {
  14269. if (options.navigation.hasOwnProperty(prop)) {
  14270. this.constants.navigation[prop] = options.navigation[prop];
  14271. }
  14272. }
  14273. }
  14274. else if (options.navigation !== undefined) {
  14275. this.constants.navigation.enabled = false;
  14276. }
  14277. if (options.keyboard) {
  14278. this.constants.keyboard.enabled = true;
  14279. for (prop in options.keyboard) {
  14280. if (options.keyboard.hasOwnProperty(prop)) {
  14281. this.constants.keyboard[prop] = options.keyboard[prop];
  14282. }
  14283. }
  14284. }
  14285. else if (options.keyboard !== undefined) {
  14286. this.constants.keyboard.enabled = false;
  14287. }
  14288. if (options.dataManipulation) {
  14289. this.constants.dataManipulation.enabled = true;
  14290. for (prop in options.dataManipulation) {
  14291. if (options.dataManipulation.hasOwnProperty(prop)) {
  14292. this.constants.dataManipulation[prop] = options.dataManipulation[prop];
  14293. }
  14294. }
  14295. }
  14296. else if (options.dataManipulation !== undefined) {
  14297. this.constants.dataManipulation.enabled = false;
  14298. }
  14299. // TODO: work out these options and document them
  14300. if (options.edges) {
  14301. for (prop in options.edges) {
  14302. if (options.edges.hasOwnProperty(prop)) {
  14303. if (typeof options.edges[prop] != "object") {
  14304. this.constants.edges[prop] = options.edges[prop];
  14305. }
  14306. }
  14307. }
  14308. if (options.edges.color !== undefined) {
  14309. if (util.isString(options.edges.color)) {
  14310. this.constants.edges.color.color = options.edges.color;
  14311. this.constants.edges.color.highlight = options.edges.color;
  14312. }
  14313. else {
  14314. if (options.edges.color.color !== undefined) {this.constants.edges.color.color = options.edges.color.color;}
  14315. if (options.edges.color.highlight !== undefined) {this.constants.edges.color.highlight = options.edges.color.highlight;}
  14316. }
  14317. }
  14318. if (!options.edges.fontColor) {
  14319. if (options.edges.color !== undefined) {
  14320. if (util.isString(options.edges.color)) {this.constants.edges.fontColor = options.edges.color;}
  14321. else if (options.edges.color.color !== undefined) {this.constants.edges.fontColor = options.edges.color.color;}
  14322. }
  14323. }
  14324. // Added to support dashed lines
  14325. // David Jordan
  14326. // 2012-08-08
  14327. if (options.edges.dash) {
  14328. if (options.edges.dash.length !== undefined) {
  14329. this.constants.edges.dash.length = options.edges.dash.length;
  14330. }
  14331. if (options.edges.dash.gap !== undefined) {
  14332. this.constants.edges.dash.gap = options.edges.dash.gap;
  14333. }
  14334. if (options.edges.dash.altLength !== undefined) {
  14335. this.constants.edges.dash.altLength = options.edges.dash.altLength;
  14336. }
  14337. }
  14338. }
  14339. if (options.nodes) {
  14340. for (prop in options.nodes) {
  14341. if (options.nodes.hasOwnProperty(prop)) {
  14342. this.constants.nodes[prop] = options.nodes[prop];
  14343. }
  14344. }
  14345. if (options.nodes.color) {
  14346. this.constants.nodes.color = Node.parseColor(options.nodes.color);
  14347. }
  14348. /*
  14349. if (options.nodes.widthMin) this.constants.nodes.radiusMin = options.nodes.widthMin;
  14350. if (options.nodes.widthMax) this.constants.nodes.radiusMax = options.nodes.widthMax;
  14351. */
  14352. }
  14353. if (options.groups) {
  14354. for (var groupname in options.groups) {
  14355. if (options.groups.hasOwnProperty(groupname)) {
  14356. var group = options.groups[groupname];
  14357. this.groups.add(groupname, group);
  14358. }
  14359. }
  14360. }
  14361. }
  14362. // (Re)loading the mixins that can be enabled or disabled in the options.
  14363. // load the force calculation functions, grouped under the physics system.
  14364. this._loadPhysicsSystem();
  14365. // load the navigation system.
  14366. this._loadNavigationControls();
  14367. // load the data manipulation system
  14368. this._loadManipulationSystem();
  14369. // configure the smooth curves
  14370. this._configureSmoothCurves();
  14371. // bind keys. If disabled, this will not do anything;
  14372. this._createKeyBinds();
  14373. this.setSize(this.width, this.height);
  14374. this._setTranslation(this.frame.clientWidth / 2, this.frame.clientHeight / 2);
  14375. this._setScale(1);
  14376. this._redraw();
  14377. };
  14378. /**
  14379. * Create the main frame for the Graph.
  14380. * This function is executed once when a Graph object is created. The frame
  14381. * contains a canvas, and this canvas contains all objects like the axis and
  14382. * nodes.
  14383. * @private
  14384. */
  14385. Graph.prototype._create = function () {
  14386. // remove all elements from the container element.
  14387. while (this.containerElement.hasChildNodes()) {
  14388. this.containerElement.removeChild(this.containerElement.firstChild);
  14389. }
  14390. this.frame = document.createElement('div');
  14391. this.frame.className = 'graph-frame';
  14392. this.frame.style.position = 'relative';
  14393. this.frame.style.overflow = 'hidden';
  14394. this.frame.style.zIndex = "1";
  14395. // create the graph canvas (HTML canvas element)
  14396. this.frame.canvas = document.createElement( 'canvas' );
  14397. this.frame.canvas.style.position = 'relative';
  14398. this.frame.appendChild(this.frame.canvas);
  14399. if (!this.frame.canvas.getContext) {
  14400. var noCanvas = document.createElement( 'DIV' );
  14401. noCanvas.style.color = 'red';
  14402. noCanvas.style.fontWeight = 'bold' ;
  14403. noCanvas.style.padding = '10px';
  14404. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  14405. this.frame.canvas.appendChild(noCanvas);
  14406. }
  14407. var me = this;
  14408. this.drag = {};
  14409. this.pinch = {};
  14410. this.hammer = Hammer(this.frame.canvas, {
  14411. prevent_default: true
  14412. });
  14413. this.hammer.on('tap', me._onTap.bind(me) );
  14414. this.hammer.on('doubletap', me._onDoubleTap.bind(me) );
  14415. this.hammer.on('hold', me._onHold.bind(me) );
  14416. this.hammer.on('pinch', me._onPinch.bind(me) );
  14417. this.hammer.on('touch', me._onTouch.bind(me) );
  14418. this.hammer.on('dragstart', me._onDragStart.bind(me) );
  14419. this.hammer.on('drag', me._onDrag.bind(me) );
  14420. this.hammer.on('dragend', me._onDragEnd.bind(me) );
  14421. this.hammer.on('release', me._onRelease.bind(me) );
  14422. this.hammer.on('mousewheel',me._onMouseWheel.bind(me) );
  14423. this.hammer.on('DOMMouseScroll',me._onMouseWheel.bind(me) ); // for FF
  14424. this.hammer.on('mousemove', me._onMouseMoveTitle.bind(me) );
  14425. // add the frame to the container element
  14426. this.containerElement.appendChild(this.frame);
  14427. };
  14428. /**
  14429. * Binding the keys for keyboard navigation. These functions are defined in the NavigationMixin
  14430. * @private
  14431. */
  14432. Graph.prototype._createKeyBinds = function() {
  14433. var me = this;
  14434. this.mousetrap = mousetrap;
  14435. this.mousetrap.reset();
  14436. if (this.constants.keyboard.enabled == true) {
  14437. this.mousetrap.bind("up", this._moveUp.bind(me) , "keydown");
  14438. this.mousetrap.bind("up", this._yStopMoving.bind(me), "keyup");
  14439. this.mousetrap.bind("down", this._moveDown.bind(me) , "keydown");
  14440. this.mousetrap.bind("down", this._yStopMoving.bind(me), "keyup");
  14441. this.mousetrap.bind("left", this._moveLeft.bind(me) , "keydown");
  14442. this.mousetrap.bind("left", this._xStopMoving.bind(me), "keyup");
  14443. this.mousetrap.bind("right",this._moveRight.bind(me), "keydown");
  14444. this.mousetrap.bind("right",this._xStopMoving.bind(me), "keyup");
  14445. this.mousetrap.bind("=", this._zoomIn.bind(me), "keydown");
  14446. this.mousetrap.bind("=", this._stopZoom.bind(me), "keyup");
  14447. this.mousetrap.bind("-", this._zoomOut.bind(me), "keydown");
  14448. this.mousetrap.bind("-", this._stopZoom.bind(me), "keyup");
  14449. this.mousetrap.bind("[", this._zoomIn.bind(me), "keydown");
  14450. this.mousetrap.bind("[", this._stopZoom.bind(me), "keyup");
  14451. this.mousetrap.bind("]", this._zoomOut.bind(me), "keydown");
  14452. this.mousetrap.bind("]", this._stopZoom.bind(me), "keyup");
  14453. this.mousetrap.bind("pageup",this._zoomIn.bind(me), "keydown");
  14454. this.mousetrap.bind("pageup",this._stopZoom.bind(me), "keyup");
  14455. this.mousetrap.bind("pagedown",this._zoomOut.bind(me),"keydown");
  14456. this.mousetrap.bind("pagedown",this._stopZoom.bind(me), "keyup");
  14457. }
  14458. if (this.constants.dataManipulation.enabled == true) {
  14459. this.mousetrap.bind("escape",this._createManipulatorBar.bind(me));
  14460. this.mousetrap.bind("del",this._deleteSelected.bind(me));
  14461. }
  14462. };
  14463. /**
  14464. * Get the pointer location from a touch location
  14465. * @param {{pageX: Number, pageY: Number}} touch
  14466. * @return {{x: Number, y: Number}} pointer
  14467. * @private
  14468. */
  14469. Graph.prototype._getPointer = function (touch) {
  14470. return {
  14471. x: touch.pageX - vis.util.getAbsoluteLeft(this.frame.canvas),
  14472. y: touch.pageY - vis.util.getAbsoluteTop(this.frame.canvas)
  14473. };
  14474. };
  14475. /**
  14476. * On start of a touch gesture, store the pointer
  14477. * @param event
  14478. * @private
  14479. */
  14480. Graph.prototype._onTouch = function (event) {
  14481. this.drag.pointer = this._getPointer(event.gesture.center);
  14482. this.drag.pinched = false;
  14483. this.pinch.scale = this._getScale();
  14484. this._handleTouch(this.drag.pointer);
  14485. };
  14486. /**
  14487. * handle drag start event
  14488. * @private
  14489. */
  14490. Graph.prototype._onDragStart = function () {
  14491. this._handleDragStart();
  14492. };
  14493. /**
  14494. * This function is called by _onDragStart.
  14495. * It is separated out because we can then overload it for the datamanipulation system.
  14496. *
  14497. * @private
  14498. */
  14499. Graph.prototype._handleDragStart = function() {
  14500. var drag = this.drag;
  14501. var node = this._getNodeAt(drag.pointer);
  14502. // note: drag.pointer is set in _onTouch to get the initial touch location
  14503. drag.dragging = true;
  14504. drag.selection = [];
  14505. drag.translation = this._getTranslation();
  14506. drag.nodeId = null;
  14507. if (node != null) {
  14508. drag.nodeId = node.id;
  14509. // select the clicked node if not yet selected
  14510. if (!node.isSelected()) {
  14511. this._selectObject(node,false);
  14512. }
  14513. // create an array with the selected nodes and their original location and status
  14514. for (var objectId in this.selectionObj) {
  14515. if (this.selectionObj.hasOwnProperty(objectId)) {
  14516. var object = this.selectionObj[objectId];
  14517. if (object instanceof Node) {
  14518. var s = {
  14519. id: object.id,
  14520. node: object,
  14521. // store original x, y, xFixed and yFixed, make the node temporarily Fixed
  14522. x: object.x,
  14523. y: object.y,
  14524. xFixed: object.xFixed,
  14525. yFixed: object.yFixed
  14526. };
  14527. object.xFixed = true;
  14528. object.yFixed = true;
  14529. drag.selection.push(s);
  14530. }
  14531. }
  14532. }
  14533. }
  14534. };
  14535. /**
  14536. * handle drag event
  14537. * @private
  14538. */
  14539. Graph.prototype._onDrag = function (event) {
  14540. this._handleOnDrag(event)
  14541. };
  14542. /**
  14543. * This function is called by _onDrag.
  14544. * It is separated out because we can then overload it for the datamanipulation system.
  14545. *
  14546. * @private
  14547. */
  14548. Graph.prototype._handleOnDrag = function(event) {
  14549. if (this.drag.pinched) {
  14550. return;
  14551. }
  14552. var pointer = this._getPointer(event.gesture.center);
  14553. var me = this,
  14554. drag = this.drag,
  14555. selection = drag.selection;
  14556. if (selection && selection.length) {
  14557. // calculate delta's and new location
  14558. var deltaX = pointer.x - drag.pointer.x,
  14559. deltaY = pointer.y - drag.pointer.y;
  14560. // update position of all selected nodes
  14561. selection.forEach(function (s) {
  14562. var node = s.node;
  14563. if (!s.xFixed) {
  14564. node.x = me._canvasToX(me._xToCanvas(s.x) + deltaX);
  14565. }
  14566. if (!s.yFixed) {
  14567. node.y = me._canvasToY(me._yToCanvas(s.y) + deltaY);
  14568. }
  14569. });
  14570. // start _animationStep if not yet running
  14571. if (!this.moving) {
  14572. this.moving = true;
  14573. this.start();
  14574. }
  14575. }
  14576. else {
  14577. // move the graph
  14578. var diffX = pointer.x - this.drag.pointer.x;
  14579. var diffY = pointer.y - this.drag.pointer.y;
  14580. this._setTranslation(
  14581. this.drag.translation.x + diffX,
  14582. this.drag.translation.y + diffY);
  14583. this._redraw();
  14584. this.moved = true;
  14585. }
  14586. };
  14587. /**
  14588. * handle drag start event
  14589. * @private
  14590. */
  14591. Graph.prototype._onDragEnd = function () {
  14592. this.drag.dragging = false;
  14593. var selection = this.drag.selection;
  14594. if (selection) {
  14595. selection.forEach(function (s) {
  14596. // restore original xFixed and yFixed
  14597. s.node.xFixed = s.xFixed;
  14598. s.node.yFixed = s.yFixed;
  14599. });
  14600. }
  14601. };
  14602. /**
  14603. * handle tap/click event: select/unselect a node
  14604. * @private
  14605. */
  14606. Graph.prototype._onTap = function (event) {
  14607. var pointer = this._getPointer(event.gesture.center);
  14608. this.pointerPosition = pointer;
  14609. this._handleTap(pointer);
  14610. };
  14611. /**
  14612. * handle doubletap event
  14613. * @private
  14614. */
  14615. Graph.prototype._onDoubleTap = function (event) {
  14616. var pointer = this._getPointer(event.gesture.center);
  14617. this._handleDoubleTap(pointer);
  14618. };
  14619. /**
  14620. * handle long tap event: multi select nodes
  14621. * @private
  14622. */
  14623. Graph.prototype._onHold = function (event) {
  14624. var pointer = this._getPointer(event.gesture.center);
  14625. this.pointerPosition = pointer;
  14626. this._handleOnHold(pointer);
  14627. };
  14628. /**
  14629. * handle the release of the screen
  14630. *
  14631. * @private
  14632. */
  14633. Graph.prototype._onRelease = function (event) {
  14634. var pointer = this._getPointer(event.gesture.center);
  14635. this._handleOnRelease(pointer);
  14636. };
  14637. /**
  14638. * Handle pinch event
  14639. * @param event
  14640. * @private
  14641. */
  14642. Graph.prototype._onPinch = function (event) {
  14643. var pointer = this._getPointer(event.gesture.center);
  14644. this.drag.pinched = true;
  14645. if (!('scale' in this.pinch)) {
  14646. this.pinch.scale = 1;
  14647. }
  14648. // TODO: enabled moving while pinching?
  14649. var scale = this.pinch.scale * event.gesture.scale;
  14650. this._zoom(scale, pointer)
  14651. };
  14652. /**
  14653. * Zoom the graph in or out
  14654. * @param {Number} scale a number around 1, and between 0.01 and 10
  14655. * @param {{x: Number, y: Number}} pointer Position on screen
  14656. * @return {Number} appliedScale scale is limited within the boundaries
  14657. * @private
  14658. */
  14659. Graph.prototype._zoom = function(scale, pointer) {
  14660. var scaleOld = this._getScale();
  14661. if (scale < 0.00001) {
  14662. scale = 0.00001;
  14663. }
  14664. if (scale > 10) {
  14665. scale = 10;
  14666. }
  14667. // + this.frame.canvas.clientHeight / 2
  14668. var translation = this._getTranslation();
  14669. var scaleFrac = scale / scaleOld;
  14670. var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac;
  14671. var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac;
  14672. this.areaCenter = {"x" : this._canvasToX(pointer.x),
  14673. "y" : this._canvasToY(pointer.y)};
  14674. this._setScale(scale);
  14675. this._setTranslation(tx, ty);
  14676. this.updateClustersDefault();
  14677. this._redraw();
  14678. return scale;
  14679. };
  14680. /**
  14681. * Event handler for mouse wheel event, used to zoom the timeline
  14682. * See http://adomas.org/javascript-mouse-wheel/
  14683. * https://github.com/EightMedia/hammer.js/issues/256
  14684. * @param {MouseEvent} event
  14685. * @private
  14686. */
  14687. Graph.prototype._onMouseWheel = function(event) {
  14688. // retrieve delta
  14689. var delta = 0;
  14690. if (event.wheelDelta) { /* IE/Opera. */
  14691. delta = event.wheelDelta/120;
  14692. } else if (event.detail) { /* Mozilla case. */
  14693. // In Mozilla, sign of delta is different than in IE.
  14694. // Also, delta is multiple of 3.
  14695. delta = -event.detail/3;
  14696. }
  14697. // If delta is nonzero, handle it.
  14698. // Basically, delta is now positive if wheel was scrolled up,
  14699. // and negative, if wheel was scrolled down.
  14700. if (delta) {
  14701. // calculate the new scale
  14702. var scale = this._getScale();
  14703. var zoom = delta / 10;
  14704. if (delta < 0) {
  14705. zoom = zoom / (1 - zoom);
  14706. }
  14707. scale *= (1 + zoom);
  14708. // calculate the pointer location
  14709. var gesture = util.fakeGesture(this, event);
  14710. var pointer = this._getPointer(gesture.center);
  14711. // apply the new scale
  14712. this._zoom(scale, pointer);
  14713. }
  14714. // Prevent default actions caused by mouse wheel.
  14715. event.preventDefault();
  14716. };
  14717. /**
  14718. * Mouse move handler for checking whether the title moves over a node with a title.
  14719. * @param {Event} event
  14720. * @private
  14721. */
  14722. Graph.prototype._onMouseMoveTitle = function (event) {
  14723. var gesture = util.fakeGesture(this, event);
  14724. var pointer = this._getPointer(gesture.center);
  14725. // check if the previously selected node is still selected
  14726. if (this.popupNode) {
  14727. this._checkHidePopup(pointer);
  14728. }
  14729. // start a timeout that will check if the mouse is positioned above
  14730. // an element
  14731. var me = this;
  14732. var checkShow = function() {
  14733. me._checkShowPopup(pointer);
  14734. };
  14735. if (this.popupTimer) {
  14736. clearInterval(this.popupTimer); // stop any running calculationTimer
  14737. }
  14738. if (!this.drag.dragging) {
  14739. this.popupTimer = setTimeout(checkShow, 300);
  14740. }
  14741. };
  14742. /**
  14743. * Check if there is an element on the given position in the graph
  14744. * (a node or edge). If so, and if this element has a title,
  14745. * show a popup window with its title.
  14746. *
  14747. * @param {{x:Number, y:Number}} pointer
  14748. * @private
  14749. */
  14750. Graph.prototype._checkShowPopup = function (pointer) {
  14751. var obj = {
  14752. left: this._canvasToX(pointer.x),
  14753. top: this._canvasToY(pointer.y),
  14754. right: this._canvasToX(pointer.x),
  14755. bottom: this._canvasToY(pointer.y)
  14756. };
  14757. var id;
  14758. var lastPopupNode = this.popupNode;
  14759. if (this.popupNode == undefined) {
  14760. // search the nodes for overlap, select the top one in case of multiple nodes
  14761. var nodes = this.nodes;
  14762. for (id in nodes) {
  14763. if (nodes.hasOwnProperty(id)) {
  14764. var node = nodes[id];
  14765. if (node.getTitle() !== undefined && node.isOverlappingWith(obj)) {
  14766. this.popupNode = node;
  14767. break;
  14768. }
  14769. }
  14770. }
  14771. }
  14772. if (this.popupNode === undefined) {
  14773. // search the edges for overlap
  14774. var edges = this.edges;
  14775. for (id in edges) {
  14776. if (edges.hasOwnProperty(id)) {
  14777. var edge = edges[id];
  14778. if (edge.connected && (edge.getTitle() !== undefined) &&
  14779. edge.isOverlappingWith(obj)) {
  14780. this.popupNode = edge;
  14781. break;
  14782. }
  14783. }
  14784. }
  14785. }
  14786. if (this.popupNode) {
  14787. // show popup message window
  14788. if (this.popupNode != lastPopupNode) {
  14789. var me = this;
  14790. if (!me.popup) {
  14791. me.popup = new Popup(me.frame);
  14792. }
  14793. // adjust a small offset such that the mouse cursor is located in the
  14794. // bottom left location of the popup, and you can easily move over the
  14795. // popup area
  14796. me.popup.setPosition(pointer.x - 3, pointer.y - 3);
  14797. me.popup.setText(me.popupNode.getTitle());
  14798. me.popup.show();
  14799. }
  14800. }
  14801. else {
  14802. if (this.popup) {
  14803. this.popup.hide();
  14804. }
  14805. }
  14806. };
  14807. /**
  14808. * Check if the popup must be hided, which is the case when the mouse is no
  14809. * longer hovering on the object
  14810. * @param {{x:Number, y:Number}} pointer
  14811. * @private
  14812. */
  14813. Graph.prototype._checkHidePopup = function (pointer) {
  14814. if (!this.popupNode || !this._getNodeAt(pointer) ) {
  14815. this.popupNode = undefined;
  14816. if (this.popup) {
  14817. this.popup.hide();
  14818. }
  14819. }
  14820. };
  14821. /**
  14822. * Set a new size for the graph
  14823. * @param {string} width Width in pixels or percentage (for example '800px'
  14824. * or '50%')
  14825. * @param {string} height Height in pixels or percentage (for example '400px'
  14826. * or '30%')
  14827. */
  14828. Graph.prototype.setSize = function(width, height) {
  14829. this.frame.style.width = width;
  14830. this.frame.style.height = height;
  14831. this.frame.canvas.style.width = '100%';
  14832. this.frame.canvas.style.height = '100%';
  14833. this.frame.canvas.width = this.frame.canvas.clientWidth;
  14834. this.frame.canvas.height = this.frame.canvas.clientHeight;
  14835. if (this.manipulationDiv !== undefined) {
  14836. this.manipulationDiv.style.width = this.frame.canvas.clientWidth + "px";
  14837. }
  14838. if (this.navigationDivs !== undefined) {
  14839. if (this.navigationDivs['wrapper'] !== undefined) {
  14840. this.navigationDivs['wrapper'].style.width = this.frame.canvas.clientWidth + "px";
  14841. this.navigationDivs['wrapper'].style.height = this.frame.canvas.clientHeight + "px";
  14842. }
  14843. }
  14844. this.emit('resize', {width:this.frame.canvas.width,height:this.frame.canvas.height});
  14845. };
  14846. /**
  14847. * Set a data set with nodes for the graph
  14848. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  14849. * @private
  14850. */
  14851. Graph.prototype._setNodes = function(nodes) {
  14852. var oldNodesData = this.nodesData;
  14853. if (nodes instanceof DataSet || nodes instanceof DataView) {
  14854. this.nodesData = nodes;
  14855. }
  14856. else if (nodes instanceof Array) {
  14857. this.nodesData = new DataSet();
  14858. this.nodesData.add(nodes);
  14859. }
  14860. else if (!nodes) {
  14861. this.nodesData = new DataSet();
  14862. }
  14863. else {
  14864. throw new TypeError('Array or DataSet expected');
  14865. }
  14866. if (oldNodesData) {
  14867. // unsubscribe from old dataset
  14868. util.forEach(this.nodesListeners, function (callback, event) {
  14869. oldNodesData.off(event, callback);
  14870. });
  14871. }
  14872. // remove drawn nodes
  14873. this.nodes = {};
  14874. if (this.nodesData) {
  14875. // subscribe to new dataset
  14876. var me = this;
  14877. util.forEach(this.nodesListeners, function (callback, event) {
  14878. me.nodesData.on(event, callback);
  14879. });
  14880. // draw all new nodes
  14881. var ids = this.nodesData.getIds();
  14882. this._addNodes(ids);
  14883. }
  14884. this._updateSelection();
  14885. };
  14886. /**
  14887. * Add nodes
  14888. * @param {Number[] | String[]} ids
  14889. * @private
  14890. */
  14891. Graph.prototype._addNodes = function(ids) {
  14892. var id;
  14893. for (var i = 0, len = ids.length; i < len; i++) {
  14894. id = ids[i];
  14895. var data = this.nodesData.get(id);
  14896. var node = new Node(data, this.images, this.groups, this.constants);
  14897. this.nodes[id] = node; // note: this may replace an existing node
  14898. if ((node.xFixed == false || node.yFixed == false) && this.createNodeOnClick != true) {
  14899. var radius = 10 * 0.1*ids.length;
  14900. var angle = 2 * Math.PI * Math.random();
  14901. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  14902. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  14903. // note: no not use node.isMoving() here, as that gives the current
  14904. // velocity of the node, which is zero after creation of the node.
  14905. this.moving = true;
  14906. }
  14907. }
  14908. this._updateNodeIndexList();
  14909. this._updateCalculationNodes();
  14910. this._reconnectEdges();
  14911. this._updateValueRange(this.nodes);
  14912. this.updateLabels();
  14913. };
  14914. /**
  14915. * Update existing nodes, or create them when not yet existing
  14916. * @param {Number[] | String[]} ids
  14917. * @private
  14918. */
  14919. Graph.prototype._updateNodes = function(ids) {
  14920. var nodes = this.nodes,
  14921. nodesData = this.nodesData;
  14922. for (var i = 0, len = ids.length; i < len; i++) {
  14923. var id = ids[i];
  14924. var node = nodes[id];
  14925. var data = nodesData.get(id);
  14926. if (node) {
  14927. // update node
  14928. node.setProperties(data, this.constants);
  14929. }
  14930. else {
  14931. // create node
  14932. node = new Node(properties, this.images, this.groups, this.constants);
  14933. nodes[id] = node;
  14934. if (!node.isFixed()) {
  14935. this.moving = true;
  14936. }
  14937. }
  14938. }
  14939. this._updateNodeIndexList();
  14940. this._reconnectEdges();
  14941. this._updateValueRange(nodes);
  14942. };
  14943. /**
  14944. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  14945. * @param {Number[] | String[]} ids
  14946. * @private
  14947. */
  14948. Graph.prototype._removeNodes = function(ids) {
  14949. var nodes = this.nodes;
  14950. for (var i = 0, len = ids.length; i < len; i++) {
  14951. var id = ids[i];
  14952. delete nodes[id];
  14953. }
  14954. this._updateNodeIndexList();
  14955. this._reconnectEdges();
  14956. this._updateSelection();
  14957. this._updateValueRange(nodes);
  14958. };
  14959. /**
  14960. * Load edges by reading the data table
  14961. * @param {Array | DataSet | DataView} edges The data containing the edges.
  14962. * @private
  14963. * @private
  14964. */
  14965. Graph.prototype._setEdges = function(edges) {
  14966. var oldEdgesData = this.edgesData;
  14967. if (edges instanceof DataSet || edges instanceof DataView) {
  14968. this.edgesData = edges;
  14969. }
  14970. else if (edges instanceof Array) {
  14971. this.edgesData = new DataSet();
  14972. this.edgesData.add(edges);
  14973. }
  14974. else if (!edges) {
  14975. this.edgesData = new DataSet();
  14976. }
  14977. else {
  14978. throw new TypeError('Array or DataSet expected');
  14979. }
  14980. if (oldEdgesData) {
  14981. // unsubscribe from old dataset
  14982. util.forEach(this.edgesListeners, function (callback, event) {
  14983. oldEdgesData.off(event, callback);
  14984. });
  14985. }
  14986. // remove drawn edges
  14987. this.edges = {};
  14988. if (this.edgesData) {
  14989. // subscribe to new dataset
  14990. var me = this;
  14991. util.forEach(this.edgesListeners, function (callback, event) {
  14992. me.edgesData.on(event, callback);
  14993. });
  14994. // draw all new nodes
  14995. var ids = this.edgesData.getIds();
  14996. this._addEdges(ids);
  14997. }
  14998. this._reconnectEdges();
  14999. };
  15000. /**
  15001. * Add edges
  15002. * @param {Number[] | String[]} ids
  15003. * @private
  15004. */
  15005. Graph.prototype._addEdges = function (ids) {
  15006. var edges = this.edges,
  15007. edgesData = this.edgesData;
  15008. for (var i = 0, len = ids.length; i < len; i++) {
  15009. var id = ids[i];
  15010. var oldEdge = edges[id];
  15011. if (oldEdge) {
  15012. oldEdge.disconnect();
  15013. }
  15014. var data = edgesData.get(id, {"showInternalIds" : true});
  15015. edges[id] = new Edge(data, this, this.constants);
  15016. }
  15017. this.moving = true;
  15018. this._updateValueRange(edges);
  15019. this._createBezierNodes();
  15020. this._updateCalculationNodes();
  15021. };
  15022. /**
  15023. * Update existing edges, or create them when not yet existing
  15024. * @param {Number[] | String[]} ids
  15025. * @private
  15026. */
  15027. Graph.prototype._updateEdges = function (ids) {
  15028. var edges = this.edges,
  15029. edgesData = this.edgesData;
  15030. for (var i = 0, len = ids.length; i < len; i++) {
  15031. var id = ids[i];
  15032. var data = edgesData.get(id);
  15033. var edge = edges[id];
  15034. if (edge) {
  15035. // update edge
  15036. edge.disconnect();
  15037. edge.setProperties(data, this.constants);
  15038. edge.connect();
  15039. }
  15040. else {
  15041. // create edge
  15042. edge = new Edge(data, this, this.constants);
  15043. this.edges[id] = edge;
  15044. }
  15045. }
  15046. this._createBezierNodes();
  15047. this.moving = true;
  15048. this._updateValueRange(edges);
  15049. };
  15050. /**
  15051. * Remove existing edges. Non existing ids will be ignored
  15052. * @param {Number[] | String[]} ids
  15053. * @private
  15054. */
  15055. Graph.prototype._removeEdges = function (ids) {
  15056. var edges = this.edges;
  15057. for (var i = 0, len = ids.length; i < len; i++) {
  15058. var id = ids[i];
  15059. var edge = edges[id];
  15060. if (edge) {
  15061. if (edge.via != null) {
  15062. delete this.sectors['support']['nodes'][edge.via.id];
  15063. }
  15064. edge.disconnect();
  15065. delete edges[id];
  15066. }
  15067. }
  15068. this.moving = true;
  15069. this._updateValueRange(edges);
  15070. this._updateCalculationNodes();
  15071. };
  15072. /**
  15073. * Reconnect all edges
  15074. * @private
  15075. */
  15076. Graph.prototype._reconnectEdges = function() {
  15077. var id,
  15078. nodes = this.nodes,
  15079. edges = this.edges;
  15080. for (id in nodes) {
  15081. if (nodes.hasOwnProperty(id)) {
  15082. nodes[id].edges = [];
  15083. }
  15084. }
  15085. for (id in edges) {
  15086. if (edges.hasOwnProperty(id)) {
  15087. var edge = edges[id];
  15088. edge.from = null;
  15089. edge.to = null;
  15090. edge.connect();
  15091. }
  15092. }
  15093. };
  15094. /**
  15095. * Update the values of all object in the given array according to the current
  15096. * value range of the objects in the array.
  15097. * @param {Object} obj An object containing a set of Edges or Nodes
  15098. * The objects must have a method getValue() and
  15099. * setValueRange(min, max).
  15100. * @private
  15101. */
  15102. Graph.prototype._updateValueRange = function(obj) {
  15103. var id;
  15104. // determine the range of the objects
  15105. var valueMin = undefined;
  15106. var valueMax = undefined;
  15107. for (id in obj) {
  15108. if (obj.hasOwnProperty(id)) {
  15109. var value = obj[id].getValue();
  15110. if (value !== undefined) {
  15111. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  15112. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  15113. }
  15114. }
  15115. }
  15116. // adjust the range of all objects
  15117. if (valueMin !== undefined && valueMax !== undefined) {
  15118. for (id in obj) {
  15119. if (obj.hasOwnProperty(id)) {
  15120. obj[id].setValueRange(valueMin, valueMax);
  15121. }
  15122. }
  15123. }
  15124. };
  15125. /**
  15126. * Redraw the graph with the current data
  15127. * chart will be resized too.
  15128. */
  15129. Graph.prototype.redraw = function() {
  15130. this.setSize(this.width, this.height);
  15131. this._redraw();
  15132. };
  15133. /**
  15134. * Redraw the graph with the current data
  15135. * @private
  15136. */
  15137. Graph.prototype._redraw = function() {
  15138. var ctx = this.frame.canvas.getContext('2d');
  15139. // clear the canvas
  15140. var w = this.frame.canvas.width;
  15141. var h = this.frame.canvas.height;
  15142. ctx.clearRect(0, 0, w, h);
  15143. // set scaling and translation
  15144. ctx.save();
  15145. ctx.translate(this.translation.x, this.translation.y);
  15146. ctx.scale(this.scale, this.scale);
  15147. this.canvasTopLeft = {
  15148. "x": this._canvasToX(0),
  15149. "y": this._canvasToY(0)
  15150. };
  15151. this.canvasBottomRight = {
  15152. "x": this._canvasToX(this.frame.canvas.clientWidth),
  15153. "y": this._canvasToY(this.frame.canvas.clientHeight)
  15154. };
  15155. this._doInAllSectors("_drawAllSectorNodes",ctx);
  15156. this._doInAllSectors("_drawEdges",ctx);
  15157. this._doInAllSectors("_drawNodes",ctx,false);
  15158. // this._doInSupportSector("_drawNodes",ctx,true);
  15159. // this._drawTree(ctx,"#F00F0F");
  15160. // restore original scaling and translation
  15161. ctx.restore();
  15162. };
  15163. /**
  15164. * Set the translation of the graph
  15165. * @param {Number} offsetX Horizontal offset
  15166. * @param {Number} offsetY Vertical offset
  15167. * @private
  15168. */
  15169. Graph.prototype._setTranslation = function(offsetX, offsetY) {
  15170. if (this.translation === undefined) {
  15171. this.translation = {
  15172. x: 0,
  15173. y: 0
  15174. };
  15175. }
  15176. if (offsetX !== undefined) {
  15177. this.translation.x = offsetX;
  15178. }
  15179. if (offsetY !== undefined) {
  15180. this.translation.y = offsetY;
  15181. }
  15182. };
  15183. /**
  15184. * Get the translation of the graph
  15185. * @return {Object} translation An object with parameters x and y, both a number
  15186. * @private
  15187. */
  15188. Graph.prototype._getTranslation = function() {
  15189. return {
  15190. x: this.translation.x,
  15191. y: this.translation.y
  15192. };
  15193. };
  15194. /**
  15195. * Scale the graph
  15196. * @param {Number} scale Scaling factor 1.0 is unscaled
  15197. * @private
  15198. */
  15199. Graph.prototype._setScale = function(scale) {
  15200. this.scale = scale;
  15201. };
  15202. /**
  15203. * Get the current scale of the graph
  15204. * @return {Number} scale Scaling factor 1.0 is unscaled
  15205. * @private
  15206. */
  15207. Graph.prototype._getScale = function() {
  15208. return this.scale;
  15209. };
  15210. /**
  15211. * Convert a horizontal point on the HTML canvas to the x-value of the model
  15212. * @param {number} x
  15213. * @returns {number}
  15214. * @private
  15215. */
  15216. Graph.prototype._canvasToX = function(x) {
  15217. return (x - this.translation.x) / this.scale;
  15218. };
  15219. /**
  15220. * Convert an x-value in the model to a horizontal point on the HTML canvas
  15221. * @param {number} x
  15222. * @returns {number}
  15223. * @private
  15224. */
  15225. Graph.prototype._xToCanvas = function(x) {
  15226. return x * this.scale + this.translation.x;
  15227. };
  15228. /**
  15229. * Convert a vertical point on the HTML canvas to the y-value of the model
  15230. * @param {number} y
  15231. * @returns {number}
  15232. * @private
  15233. */
  15234. Graph.prototype._canvasToY = function(y) {
  15235. return (y - this.translation.y) / this.scale;
  15236. };
  15237. /**
  15238. * Convert an y-value in the model to a vertical point on the HTML canvas
  15239. * @param {number} y
  15240. * @returns {number}
  15241. * @private
  15242. */
  15243. Graph.prototype._yToCanvas = function(y) {
  15244. return y * this.scale + this.translation.y ;
  15245. };
  15246. /**
  15247. * Redraw all nodes
  15248. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  15249. * @param {CanvasRenderingContext2D} ctx
  15250. * @param {Boolean} [alwaysShow]
  15251. * @private
  15252. */
  15253. Graph.prototype._drawNodes = function(ctx,alwaysShow) {
  15254. if (alwaysShow === undefined) {
  15255. alwaysShow = false;
  15256. }
  15257. // first draw the unselected nodes
  15258. var nodes = this.nodes;
  15259. var selected = [];
  15260. for (var id in nodes) {
  15261. if (nodes.hasOwnProperty(id)) {
  15262. nodes[id].setScaleAndPos(this.scale,this.canvasTopLeft,this.canvasBottomRight);
  15263. if (nodes[id].isSelected()) {
  15264. selected.push(id);
  15265. }
  15266. else {
  15267. if (nodes[id].inArea() || alwaysShow) {
  15268. nodes[id].draw(ctx);
  15269. }
  15270. }
  15271. }
  15272. }
  15273. // draw the selected nodes on top
  15274. for (var s = 0, sMax = selected.length; s < sMax; s++) {
  15275. if (nodes[selected[s]].inArea() || alwaysShow) {
  15276. nodes[selected[s]].draw(ctx);
  15277. }
  15278. }
  15279. };
  15280. /**
  15281. * Redraw all edges
  15282. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  15283. * @param {CanvasRenderingContext2D} ctx
  15284. * @private
  15285. */
  15286. Graph.prototype._drawEdges = function(ctx) {
  15287. var edges = this.edges;
  15288. for (var id in edges) {
  15289. if (edges.hasOwnProperty(id)) {
  15290. var edge = edges[id];
  15291. edge.setScale(this.scale);
  15292. if (edge.connected) {
  15293. edges[id].draw(ctx);
  15294. }
  15295. }
  15296. }
  15297. };
  15298. /**
  15299. * Find a stable position for all nodes
  15300. * @private
  15301. */
  15302. Graph.prototype._stabilize = function() {
  15303. // find stable position
  15304. var count = 0;
  15305. while (this.moving && count < this.constants.stabilizationIterations) {
  15306. this._physicsTick();
  15307. count++;
  15308. }
  15309. this.zoomExtent(false,true);
  15310. };
  15311. /**
  15312. * Check if any of the nodes is still moving
  15313. * @param {number} vmin the minimum velocity considered as 'moving'
  15314. * @return {boolean} true if moving, false if non of the nodes is moving
  15315. * @private
  15316. */
  15317. Graph.prototype._isMoving = function(vmin) {
  15318. var nodes = this.nodes;
  15319. for (var id in nodes) {
  15320. if (nodes.hasOwnProperty(id) && nodes[id].isMoving(vmin)) {
  15321. return true;
  15322. }
  15323. }
  15324. return false;
  15325. };
  15326. /**
  15327. * /**
  15328. * Perform one discrete step for all nodes
  15329. *
  15330. * @private
  15331. */
  15332. Graph.prototype._discreteStepNodes = function() {
  15333. var interval = 0.65;
  15334. var nodes = this.nodes;
  15335. var nodeId;
  15336. if (this.constants.maxVelocity > 0) {
  15337. for (nodeId in nodes) {
  15338. if (nodes.hasOwnProperty(nodeId)) {
  15339. nodes[nodeId].discreteStepLimited(interval, this.constants.maxVelocity);
  15340. }
  15341. }
  15342. }
  15343. else {
  15344. for (nodeId in nodes) {
  15345. if (nodes.hasOwnProperty(nodeId)) {
  15346. nodes[nodeId].discreteStep(interval);
  15347. }
  15348. }
  15349. }
  15350. var vminCorrected = this.constants.minVelocity / Math.max(this.scale,0.05);
  15351. if (vminCorrected > 0.5*this.constants.maxVelocity) {
  15352. this.moving = true;
  15353. }
  15354. else {
  15355. this.moving = this._isMoving(vminCorrected);
  15356. }
  15357. };
  15358. Graph.prototype._physicsTick = function() {
  15359. if (!this.freezeSimulation) {
  15360. if (this.moving) {
  15361. this._doInAllActiveSectors("_initializeForceCalculation");
  15362. if (this.constants.smoothCurves) {
  15363. this._doInSupportSector("_discreteStepNodes");
  15364. }
  15365. this._doInAllActiveSectors("_discreteStepNodes");
  15366. this._findCenter(this._getRange())
  15367. }
  15368. }
  15369. };
  15370. /**
  15371. * This function runs one step of the animation. It calls an x amount of physics ticks and one render tick.
  15372. * It reschedules itself at the beginning of the function
  15373. *
  15374. * @private
  15375. */
  15376. Graph.prototype._animationStep = function() {
  15377. // reset the timer so a new scheduled animation step can be set
  15378. this.timer = undefined;
  15379. // handle the keyboad movement
  15380. this._handleNavigation();
  15381. // this schedules a new animation step
  15382. this.start();
  15383. // start the physics simulation
  15384. var calculationTime = Date.now();
  15385. var maxSteps = 1;
  15386. this._physicsTick();
  15387. var timeRequired = Date.now() - calculationTime;
  15388. while (timeRequired < (this.renderTimestep - this.renderTime) && maxSteps < this.maxRenderSteps) {
  15389. this._physicsTick();
  15390. timeRequired = Date.now() - calculationTime;
  15391. maxSteps++;
  15392. }
  15393. // start the rendering process
  15394. var renderTime = Date.now();
  15395. this._redraw();
  15396. this.renderTime = Date.now() - renderTime;
  15397. };
  15398. if (typeof window !== 'undefined') {
  15399. window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
  15400. window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
  15401. }
  15402. /**
  15403. * Schedule a animation step with the refreshrate interval.
  15404. *
  15405. * @poram {Boolean} runCalculationStep
  15406. */
  15407. Graph.prototype.start = function() {
  15408. if (this.moving || this.xIncrement != 0 || this.yIncrement != 0 || this.zoomIncrement != 0) {
  15409. if (!this.timer) {
  15410. this.timer = window.requestAnimationFrame(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  15411. }
  15412. }
  15413. else {
  15414. this._redraw();
  15415. }
  15416. };
  15417. /**
  15418. * Move the graph according to the keyboard presses.
  15419. *
  15420. * @private
  15421. */
  15422. Graph.prototype._handleNavigation = function() {
  15423. if (this.xIncrement != 0 || this.yIncrement != 0) {
  15424. var translation = this._getTranslation();
  15425. this._setTranslation(translation.x+this.xIncrement, translation.y+this.yIncrement);
  15426. }
  15427. if (this.zoomIncrement != 0) {
  15428. var center = {
  15429. x: this.frame.canvas.clientWidth / 2,
  15430. y: this.frame.canvas.clientHeight / 2
  15431. };
  15432. this._zoom(this.scale*(1 + this.zoomIncrement), center);
  15433. }
  15434. };
  15435. /**
  15436. * Freeze the _animationStep
  15437. */
  15438. Graph.prototype.toggleFreeze = function() {
  15439. if (this.freezeSimulation == false) {
  15440. this.freezeSimulation = true;
  15441. }
  15442. else {
  15443. this.freezeSimulation = false;
  15444. this.start();
  15445. }
  15446. };
  15447. Graph.prototype._configureSmoothCurves = function(disableStart) {
  15448. if (disableStart === undefined) {
  15449. disableStart = true;
  15450. }
  15451. if (this.constants.smoothCurves == true) {
  15452. this._createBezierNodes();
  15453. }
  15454. else {
  15455. // delete the support nodes
  15456. this.sectors['support']['nodes'] = {};
  15457. for (var edgeId in this.edges) {
  15458. if (this.edges.hasOwnProperty(edgeId)) {
  15459. this.edges[edgeId].smooth = false;
  15460. this.edges[edgeId].via = null;
  15461. }
  15462. }
  15463. }
  15464. this._updateCalculationNodes();
  15465. if (!disableStart) {
  15466. this.moving = true;
  15467. this.start();
  15468. }
  15469. };
  15470. Graph.prototype._createBezierNodes = function() {
  15471. if (this.constants.smoothCurves == true) {
  15472. for (var edgeId in this.edges) {
  15473. if (this.edges.hasOwnProperty(edgeId)) {
  15474. var edge = this.edges[edgeId];
  15475. if (edge.via == null) {
  15476. edge.smooth = true;
  15477. var nodeId = "edgeId:".concat(edge.id);
  15478. this.sectors['support']['nodes'][nodeId] = new Node(
  15479. {id:nodeId,
  15480. mass:1,
  15481. shape:'circle',
  15482. internalMultiplier:1
  15483. },{},{},this.constants);
  15484. edge.via = this.sectors['support']['nodes'][nodeId];
  15485. edge.via.parentEdgeId = edge.id;
  15486. edge.positionBezierNode();
  15487. }
  15488. }
  15489. }
  15490. }
  15491. };
  15492. Graph.prototype._initializeMixinLoaders = function () {
  15493. for (var mixinFunction in graphMixinLoaders) {
  15494. if (graphMixinLoaders.hasOwnProperty(mixinFunction)) {
  15495. Graph.prototype[mixinFunction] = graphMixinLoaders[mixinFunction];
  15496. }
  15497. }
  15498. };
  15499. /**
  15500. * Load the XY positions of the nodes into the dataset.
  15501. */
  15502. Graph.prototype.storePosition = function() {
  15503. var dataArray = [];
  15504. for (var nodeId in this.nodes) {
  15505. if (this.nodes.hasOwnProperty(nodeId)) {
  15506. var node = this.nodes[nodeId];
  15507. var allowedToMoveX = !this.nodes.xFixed;
  15508. var allowedToMoveY = !this.nodes.yFixed;
  15509. if (this.nodesData.data[nodeId].x != Math.round(node.x) || this.nodesData.data[nodeId].y != Math.round(node.y)) {
  15510. dataArray.push({id:nodeId,x:Math.round(node.x),y:Math.round(node.y),allowedToMoveX:allowedToMoveX,allowedToMoveY:allowedToMoveY});
  15511. }
  15512. }
  15513. }
  15514. this.nodesData.update(dataArray);
  15515. };
  15516. /**
  15517. * vis.js module exports
  15518. */
  15519. var vis = {
  15520. util: util,
  15521. Controller: Controller,
  15522. DataSet: DataSet,
  15523. DataView: DataView,
  15524. Range: Range,
  15525. Stack: Stack,
  15526. TimeStep: TimeStep,
  15527. components: {
  15528. items: {
  15529. Item: Item,
  15530. ItemBox: ItemBox,
  15531. ItemPoint: ItemPoint,
  15532. ItemRange: ItemRange
  15533. },
  15534. Component: Component,
  15535. Panel: Panel,
  15536. RootPanel: RootPanel,
  15537. ItemSet: ItemSet,
  15538. TimeAxis: TimeAxis
  15539. },
  15540. graph: {
  15541. Node: Node,
  15542. Edge: Edge,
  15543. Popup: Popup,
  15544. Groups: Groups,
  15545. Images: Images
  15546. },
  15547. Timeline: Timeline,
  15548. Graph: Graph
  15549. };
  15550. /**
  15551. * CommonJS module exports
  15552. */
  15553. if (typeof exports !== 'undefined') {
  15554. exports = vis;
  15555. }
  15556. if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  15557. module.exports = vis;
  15558. }
  15559. /**
  15560. * AMD module exports
  15561. */
  15562. if (typeof(define) === 'function') {
  15563. define(function () {
  15564. return vis;
  15565. });
  15566. }
  15567. /**
  15568. * Window exports
  15569. */
  15570. if (typeof window !== 'undefined') {
  15571. // attach the module to the window, load as a regular javascript file
  15572. window['vis'] = vis;
  15573. }
  15574. },{"emitter-component":2,"hammerjs":3,"moment":4,"mousetrap":5}],2:[function(require,module,exports){
  15575. /**
  15576. * Expose `Emitter`.
  15577. */
  15578. module.exports = Emitter;
  15579. /**
  15580. * Initialize a new `Emitter`.
  15581. *
  15582. * @api public
  15583. */
  15584. function Emitter(obj) {
  15585. if (obj) return mixin(obj);
  15586. };
  15587. /**
  15588. * Mixin the emitter properties.
  15589. *
  15590. * @param {Object} obj
  15591. * @return {Object}
  15592. * @api private
  15593. */
  15594. function mixin(obj) {
  15595. for (var key in Emitter.prototype) {
  15596. obj[key] = Emitter.prototype[key];
  15597. }
  15598. return obj;
  15599. }
  15600. /**
  15601. * Listen on the given `event` with `fn`.
  15602. *
  15603. * @param {String} event
  15604. * @param {Function} fn
  15605. * @return {Emitter}
  15606. * @api public
  15607. */
  15608. Emitter.prototype.on =
  15609. Emitter.prototype.addEventListener = function(event, fn){
  15610. this._callbacks = this._callbacks || {};
  15611. (this._callbacks[event] = this._callbacks[event] || [])
  15612. .push(fn);
  15613. return this;
  15614. };
  15615. /**
  15616. * Adds an `event` listener that will be invoked a single
  15617. * time then automatically removed.
  15618. *
  15619. * @param {String} event
  15620. * @param {Function} fn
  15621. * @return {Emitter}
  15622. * @api public
  15623. */
  15624. Emitter.prototype.once = function(event, fn){
  15625. var self = this;
  15626. this._callbacks = this._callbacks || {};
  15627. function on() {
  15628. self.off(event, on);
  15629. fn.apply(this, arguments);
  15630. }
  15631. on.fn = fn;
  15632. this.on(event, on);
  15633. return this;
  15634. };
  15635. /**
  15636. * Remove the given callback for `event` or all
  15637. * registered callbacks.
  15638. *
  15639. * @param {String} event
  15640. * @param {Function} fn
  15641. * @return {Emitter}
  15642. * @api public
  15643. */
  15644. Emitter.prototype.off =
  15645. Emitter.prototype.removeListener =
  15646. Emitter.prototype.removeAllListeners =
  15647. Emitter.prototype.removeEventListener = function(event, fn){
  15648. this._callbacks = this._callbacks || {};
  15649. // all
  15650. if (0 == arguments.length) {
  15651. this._callbacks = {};
  15652. return this;
  15653. }
  15654. // specific event
  15655. var callbacks = this._callbacks[event];
  15656. if (!callbacks) return this;
  15657. // remove all handlers
  15658. if (1 == arguments.length) {
  15659. delete this._callbacks[event];
  15660. return this;
  15661. }
  15662. // remove specific handler
  15663. var cb;
  15664. for (var i = 0; i < callbacks.length; i++) {
  15665. cb = callbacks[i];
  15666. if (cb === fn || cb.fn === fn) {
  15667. callbacks.splice(i, 1);
  15668. break;
  15669. }
  15670. }
  15671. return this;
  15672. };
  15673. /**
  15674. * Emit `event` with the given args.
  15675. *
  15676. * @param {String} event
  15677. * @param {Mixed} ...
  15678. * @return {Emitter}
  15679. */
  15680. Emitter.prototype.emit = function(event){
  15681. this._callbacks = this._callbacks || {};
  15682. var args = [].slice.call(arguments, 1)
  15683. , callbacks = this._callbacks[event];
  15684. if (callbacks) {
  15685. callbacks = callbacks.slice(0);
  15686. for (var i = 0, len = callbacks.length; i < len; ++i) {
  15687. callbacks[i].apply(this, args);
  15688. }
  15689. }
  15690. return this;
  15691. };
  15692. /**
  15693. * Return array of callbacks for `event`.
  15694. *
  15695. * @param {String} event
  15696. * @return {Array}
  15697. * @api public
  15698. */
  15699. Emitter.prototype.listeners = function(event){
  15700. this._callbacks = this._callbacks || {};
  15701. return this._callbacks[event] || [];
  15702. };
  15703. /**
  15704. * Check if this emitter has `event` handlers.
  15705. *
  15706. * @param {String} event
  15707. * @return {Boolean}
  15708. * @api public
  15709. */
  15710. Emitter.prototype.hasListeners = function(event){
  15711. return !! this.listeners(event).length;
  15712. };
  15713. },{}],3:[function(require,module,exports){
  15714. /*! Hammer.JS - v1.0.5 - 2013-04-07
  15715. * http://eightmedia.github.com/hammer.js
  15716. *
  15717. * Copyright (c) 2013 Jorik Tangelder <j.tangelder@gmail.com>;
  15718. * Licensed under the MIT license */
  15719. (function(window, undefined) {
  15720. 'use strict';
  15721. /**
  15722. * Hammer
  15723. * use this to create instances
  15724. * @param {HTMLElement} element
  15725. * @param {Object} options
  15726. * @returns {Hammer.Instance}
  15727. * @constructor
  15728. */
  15729. var Hammer = function(element, options) {
  15730. return new Hammer.Instance(element, options || {});
  15731. };
  15732. // default settings
  15733. Hammer.defaults = {
  15734. // add styles and attributes to the element to prevent the browser from doing
  15735. // its native behavior. this doesnt prevent the scrolling, but cancels
  15736. // the contextmenu, tap highlighting etc
  15737. // set to false to disable this
  15738. stop_browser_behavior: {
  15739. // this also triggers onselectstart=false for IE
  15740. userSelect: 'none',
  15741. // this makes the element blocking in IE10 >, you could experiment with the value
  15742. // see for more options this issue; https://github.com/EightMedia/hammer.js/issues/241
  15743. touchAction: 'none',
  15744. touchCallout: 'none',
  15745. contentZooming: 'none',
  15746. userDrag: 'none',
  15747. tapHighlightColor: 'rgba(0,0,0,0)'
  15748. }
  15749. // more settings are defined per gesture at gestures.js
  15750. };
  15751. // detect touchevents
  15752. Hammer.HAS_POINTEREVENTS = navigator.pointerEnabled || navigator.msPointerEnabled;
  15753. Hammer.HAS_TOUCHEVENTS = ('ontouchstart' in window);
  15754. // dont use mouseevents on mobile devices
  15755. Hammer.MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;
  15756. Hammer.NO_MOUSEEVENTS = Hammer.HAS_TOUCHEVENTS && navigator.userAgent.match(Hammer.MOBILE_REGEX);
  15757. // eventtypes per touchevent (start, move, end)
  15758. // are filled by Hammer.event.determineEventTypes on setup
  15759. Hammer.EVENT_TYPES = {};
  15760. // direction defines
  15761. Hammer.DIRECTION_DOWN = 'down';
  15762. Hammer.DIRECTION_LEFT = 'left';
  15763. Hammer.DIRECTION_UP = 'up';
  15764. Hammer.DIRECTION_RIGHT = 'right';
  15765. // pointer type
  15766. Hammer.POINTER_MOUSE = 'mouse';
  15767. Hammer.POINTER_TOUCH = 'touch';
  15768. Hammer.POINTER_PEN = 'pen';
  15769. // touch event defines
  15770. Hammer.EVENT_START = 'start';
  15771. Hammer.EVENT_MOVE = 'move';
  15772. Hammer.EVENT_END = 'end';
  15773. // hammer document where the base events are added at
  15774. Hammer.DOCUMENT = document;
  15775. // plugins namespace
  15776. Hammer.plugins = {};
  15777. // if the window events are set...
  15778. Hammer.READY = false;
  15779. /**
  15780. * setup events to detect gestures on the document
  15781. */
  15782. function setup() {
  15783. if(Hammer.READY) {
  15784. return;
  15785. }
  15786. // find what eventtypes we add listeners to
  15787. Hammer.event.determineEventTypes();
  15788. // Register all gestures inside Hammer.gestures
  15789. for(var name in Hammer.gestures) {
  15790. if(Hammer.gestures.hasOwnProperty(name)) {
  15791. Hammer.detection.register(Hammer.gestures[name]);
  15792. }
  15793. }
  15794. // Add touch events on the document
  15795. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_MOVE, Hammer.detection.detect);
  15796. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_END, Hammer.detection.detect);
  15797. // Hammer is ready...!
  15798. Hammer.READY = true;
  15799. }
  15800. /**
  15801. * create new hammer instance
  15802. * all methods should return the instance itself, so it is chainable.
  15803. * @param {HTMLElement} element
  15804. * @param {Object} [options={}]
  15805. * @returns {Hammer.Instance}
  15806. * @constructor
  15807. */
  15808. Hammer.Instance = function(element, options) {
  15809. var self = this;
  15810. // setup HammerJS window events and register all gestures
  15811. // this also sets up the default options
  15812. setup();
  15813. this.element = element;
  15814. // start/stop detection option
  15815. this.enabled = true;
  15816. // merge options
  15817. this.options = Hammer.utils.extend(
  15818. Hammer.utils.extend({}, Hammer.defaults),
  15819. options || {});
  15820. // add some css to the element to prevent the browser from doing its native behavoir
  15821. if(this.options.stop_browser_behavior) {
  15822. Hammer.utils.stopDefaultBrowserBehavior(this.element, this.options.stop_browser_behavior);
  15823. }
  15824. // start detection on touchstart
  15825. Hammer.event.onTouch(element, Hammer.EVENT_START, function(ev) {
  15826. if(self.enabled) {
  15827. Hammer.detection.startDetect(self, ev);
  15828. }
  15829. });
  15830. // return instance
  15831. return this;
  15832. };
  15833. Hammer.Instance.prototype = {
  15834. /**
  15835. * bind events to the instance
  15836. * @param {String} gesture
  15837. * @param {Function} handler
  15838. * @returns {Hammer.Instance}
  15839. */
  15840. on: function onEvent(gesture, handler){
  15841. var gestures = gesture.split(' ');
  15842. for(var t=0; t<gestures.length; t++) {
  15843. this.element.addEventListener(gestures[t], handler, false);
  15844. }
  15845. return this;
  15846. },
  15847. /**
  15848. * unbind events to the instance
  15849. * @param {String} gesture
  15850. * @param {Function} handler
  15851. * @returns {Hammer.Instance}
  15852. */
  15853. off: function offEvent(gesture, handler){
  15854. var gestures = gesture.split(' ');
  15855. for(var t=0; t<gestures.length; t++) {
  15856. this.element.removeEventListener(gestures[t], handler, false);
  15857. }
  15858. return this;
  15859. },
  15860. /**
  15861. * trigger gesture event
  15862. * @param {String} gesture
  15863. * @param {Object} eventData
  15864. * @returns {Hammer.Instance}
  15865. */
  15866. trigger: function triggerEvent(gesture, eventData){
  15867. // create DOM event
  15868. var event = Hammer.DOCUMENT.createEvent('Event');
  15869. event.initEvent(gesture, true, true);
  15870. event.gesture = eventData;
  15871. // trigger on the target if it is in the instance element,
  15872. // this is for event delegation tricks
  15873. var element = this.element;
  15874. if(Hammer.utils.hasParent(eventData.target, element)) {
  15875. element = eventData.target;
  15876. }
  15877. element.dispatchEvent(event);
  15878. return this;
  15879. },
  15880. /**
  15881. * enable of disable hammer.js detection
  15882. * @param {Boolean} state
  15883. * @returns {Hammer.Instance}
  15884. */
  15885. enable: function enable(state) {
  15886. this.enabled = state;
  15887. return this;
  15888. }
  15889. };
  15890. /**
  15891. * this holds the last move event,
  15892. * used to fix empty touchend issue
  15893. * see the onTouch event for an explanation
  15894. * @type {Object}
  15895. */
  15896. var last_move_event = null;
  15897. /**
  15898. * when the mouse is hold down, this is true
  15899. * @type {Boolean}
  15900. */
  15901. var enable_detect = false;
  15902. /**
  15903. * when touch events have been fired, this is true
  15904. * @type {Boolean}
  15905. */
  15906. var touch_triggered = false;
  15907. Hammer.event = {
  15908. /**
  15909. * simple addEventListener
  15910. * @param {HTMLElement} element
  15911. * @param {String} type
  15912. * @param {Function} handler
  15913. */
  15914. bindDom: function(element, type, handler) {
  15915. var types = type.split(' ');
  15916. for(var t=0; t<types.length; t++) {
  15917. element.addEventListener(types[t], handler, false);
  15918. }
  15919. },
  15920. /**
  15921. * touch events with mouse fallback
  15922. * @param {HTMLElement} element
  15923. * @param {String} eventType like Hammer.EVENT_MOVE
  15924. * @param {Function} handler
  15925. */
  15926. onTouch: function onTouch(element, eventType, handler) {
  15927. var self = this;
  15928. this.bindDom(element, Hammer.EVENT_TYPES[eventType], function bindDomOnTouch(ev) {
  15929. var sourceEventType = ev.type.toLowerCase();
  15930. // onmouseup, but when touchend has been fired we do nothing.
  15931. // this is for touchdevices which also fire a mouseup on touchend
  15932. if(sourceEventType.match(/mouse/) && touch_triggered) {
  15933. return;
  15934. }
  15935. // mousebutton must be down or a touch event
  15936. else if( sourceEventType.match(/touch/) || // touch events are always on screen
  15937. sourceEventType.match(/pointerdown/) || // pointerevents touch
  15938. (sourceEventType.match(/mouse/) && ev.which === 1) // mouse is pressed
  15939. ){
  15940. enable_detect = true;
  15941. }
  15942. // we are in a touch event, set the touch triggered bool to true,
  15943. // this for the conflicts that may occur on ios and android
  15944. if(sourceEventType.match(/touch|pointer/)) {
  15945. touch_triggered = true;
  15946. }
  15947. // count the total touches on the screen
  15948. var count_touches = 0;
  15949. // when touch has been triggered in this detection session
  15950. // and we are now handling a mouse event, we stop that to prevent conflicts
  15951. if(enable_detect) {
  15952. // update pointerevent
  15953. if(Hammer.HAS_POINTEREVENTS && eventType != Hammer.EVENT_END) {
  15954. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  15955. }
  15956. // touch
  15957. else if(sourceEventType.match(/touch/)) {
  15958. count_touches = ev.touches.length;
  15959. }
  15960. // mouse
  15961. else if(!touch_triggered) {
  15962. count_touches = sourceEventType.match(/up/) ? 0 : 1;
  15963. }
  15964. // if we are in a end event, but when we remove one touch and
  15965. // we still have enough, set eventType to move
  15966. if(count_touches > 0 && eventType == Hammer.EVENT_END) {
  15967. eventType = Hammer.EVENT_MOVE;
  15968. }
  15969. // no touches, force the end event
  15970. else if(!count_touches) {
  15971. eventType = Hammer.EVENT_END;
  15972. }
  15973. // because touchend has no touches, and we often want to use these in our gestures,
  15974. // we send the last move event as our eventData in touchend
  15975. if(!count_touches && last_move_event !== null) {
  15976. ev = last_move_event;
  15977. }
  15978. // store the last move event
  15979. else {
  15980. last_move_event = ev;
  15981. }
  15982. // trigger the handler
  15983. handler.call(Hammer.detection, self.collectEventData(element, eventType, ev));
  15984. // remove pointerevent from list
  15985. if(Hammer.HAS_POINTEREVENTS && eventType == Hammer.EVENT_END) {
  15986. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  15987. }
  15988. }
  15989. //debug(sourceEventType +" "+ eventType);
  15990. // on the end we reset everything
  15991. if(!count_touches) {
  15992. last_move_event = null;
  15993. enable_detect = false;
  15994. touch_triggered = false;
  15995. Hammer.PointerEvent.reset();
  15996. }
  15997. });
  15998. },
  15999. /**
  16000. * we have different events for each device/browser
  16001. * determine what we need and set them in the Hammer.EVENT_TYPES constant
  16002. */
  16003. determineEventTypes: function determineEventTypes() {
  16004. // determine the eventtype we want to set
  16005. var types;
  16006. // pointerEvents magic
  16007. if(Hammer.HAS_POINTEREVENTS) {
  16008. types = Hammer.PointerEvent.getEvents();
  16009. }
  16010. // on Android, iOS, blackberry, windows mobile we dont want any mouseevents
  16011. else if(Hammer.NO_MOUSEEVENTS) {
  16012. types = [
  16013. 'touchstart',
  16014. 'touchmove',
  16015. 'touchend touchcancel'];
  16016. }
  16017. // for non pointer events browsers and mixed browsers,
  16018. // like chrome on windows8 touch laptop
  16019. else {
  16020. types = [
  16021. 'touchstart mousedown',
  16022. 'touchmove mousemove',
  16023. 'touchend touchcancel mouseup'];
  16024. }
  16025. Hammer.EVENT_TYPES[Hammer.EVENT_START] = types[0];
  16026. Hammer.EVENT_TYPES[Hammer.EVENT_MOVE] = types[1];
  16027. Hammer.EVENT_TYPES[Hammer.EVENT_END] = types[2];
  16028. },
  16029. /**
  16030. * create touchlist depending on the event
  16031. * @param {Object} ev
  16032. * @param {String} eventType used by the fakemultitouch plugin
  16033. */
  16034. getTouchList: function getTouchList(ev/*, eventType*/) {
  16035. // get the fake pointerEvent touchlist
  16036. if(Hammer.HAS_POINTEREVENTS) {
  16037. return Hammer.PointerEvent.getTouchList();
  16038. }
  16039. // get the touchlist
  16040. else if(ev.touches) {
  16041. return ev.touches;
  16042. }
  16043. // make fake touchlist from mouse position
  16044. else {
  16045. return [{
  16046. identifier: 1,
  16047. pageX: ev.pageX,
  16048. pageY: ev.pageY,
  16049. target: ev.target
  16050. }];
  16051. }
  16052. },
  16053. /**
  16054. * collect event data for Hammer js
  16055. * @param {HTMLElement} element
  16056. * @param {String} eventType like Hammer.EVENT_MOVE
  16057. * @param {Object} eventData
  16058. */
  16059. collectEventData: function collectEventData(element, eventType, ev) {
  16060. var touches = this.getTouchList(ev, eventType);
  16061. // find out pointerType
  16062. var pointerType = Hammer.POINTER_TOUCH;
  16063. if(ev.type.match(/mouse/) || Hammer.PointerEvent.matchType(Hammer.POINTER_MOUSE, ev)) {
  16064. pointerType = Hammer.POINTER_MOUSE;
  16065. }
  16066. return {
  16067. center : Hammer.utils.getCenter(touches),
  16068. timeStamp : new Date().getTime(),
  16069. target : ev.target,
  16070. touches : touches,
  16071. eventType : eventType,
  16072. pointerType : pointerType,
  16073. srcEvent : ev,
  16074. /**
  16075. * prevent the browser default actions
  16076. * mostly used to disable scrolling of the browser
  16077. */
  16078. preventDefault: function() {
  16079. if(this.srcEvent.preventManipulation) {
  16080. this.srcEvent.preventManipulation();
  16081. }
  16082. if(this.srcEvent.preventDefault) {
  16083. this.srcEvent.preventDefault();
  16084. }
  16085. },
  16086. /**
  16087. * stop bubbling the event up to its parents
  16088. */
  16089. stopPropagation: function() {
  16090. this.srcEvent.stopPropagation();
  16091. },
  16092. /**
  16093. * immediately stop gesture detection
  16094. * might be useful after a swipe was detected
  16095. * @return {*}
  16096. */
  16097. stopDetect: function() {
  16098. return Hammer.detection.stopDetect();
  16099. }
  16100. };
  16101. }
  16102. };
  16103. Hammer.PointerEvent = {
  16104. /**
  16105. * holds all pointers
  16106. * @type {Object}
  16107. */
  16108. pointers: {},
  16109. /**
  16110. * get a list of pointers
  16111. * @returns {Array} touchlist
  16112. */
  16113. getTouchList: function() {
  16114. var self = this;
  16115. var touchlist = [];
  16116. // we can use forEach since pointerEvents only is in IE10
  16117. Object.keys(self.pointers).sort().forEach(function(id) {
  16118. touchlist.push(self.pointers[id]);
  16119. });
  16120. return touchlist;
  16121. },
  16122. /**
  16123. * update the position of a pointer
  16124. * @param {String} type Hammer.EVENT_END
  16125. * @param {Object} pointerEvent
  16126. */
  16127. updatePointer: function(type, pointerEvent) {
  16128. if(type == Hammer.EVENT_END) {
  16129. this.pointers = {};
  16130. }
  16131. else {
  16132. pointerEvent.identifier = pointerEvent.pointerId;
  16133. this.pointers[pointerEvent.pointerId] = pointerEvent;
  16134. }
  16135. return Object.keys(this.pointers).length;
  16136. },
  16137. /**
  16138. * check if ev matches pointertype
  16139. * @param {String} pointerType Hammer.POINTER_MOUSE
  16140. * @param {PointerEvent} ev
  16141. */
  16142. matchType: function(pointerType, ev) {
  16143. if(!ev.pointerType) {
  16144. return false;
  16145. }
  16146. var types = {};
  16147. types[Hammer.POINTER_MOUSE] = (ev.pointerType == ev.MSPOINTER_TYPE_MOUSE || ev.pointerType == Hammer.POINTER_MOUSE);
  16148. types[Hammer.POINTER_TOUCH] = (ev.pointerType == ev.MSPOINTER_TYPE_TOUCH || ev.pointerType == Hammer.POINTER_TOUCH);
  16149. types[Hammer.POINTER_PEN] = (ev.pointerType == ev.MSPOINTER_TYPE_PEN || ev.pointerType == Hammer.POINTER_PEN);
  16150. return types[pointerType];
  16151. },
  16152. /**
  16153. * get events
  16154. */
  16155. getEvents: function() {
  16156. return [
  16157. 'pointerdown MSPointerDown',
  16158. 'pointermove MSPointerMove',
  16159. 'pointerup pointercancel MSPointerUp MSPointerCancel'
  16160. ];
  16161. },
  16162. /**
  16163. * reset the list
  16164. */
  16165. reset: function() {
  16166. this.pointers = {};
  16167. }
  16168. };
  16169. Hammer.utils = {
  16170. /**
  16171. * extend method,
  16172. * also used for cloning when dest is an empty object
  16173. * @param {Object} dest
  16174. * @param {Object} src
  16175. * @parm {Boolean} merge do a merge
  16176. * @returns {Object} dest
  16177. */
  16178. extend: function extend(dest, src, merge) {
  16179. for (var key in src) {
  16180. if(dest[key] !== undefined && merge) {
  16181. continue;
  16182. }
  16183. dest[key] = src[key];
  16184. }
  16185. return dest;
  16186. },
  16187. /**
  16188. * find if a node is in the given parent
  16189. * used for event delegation tricks
  16190. * @param {HTMLElement} node
  16191. * @param {HTMLElement} parent
  16192. * @returns {boolean} has_parent
  16193. */
  16194. hasParent: function(node, parent) {
  16195. while(node){
  16196. if(node == parent) {
  16197. return true;
  16198. }
  16199. node = node.parentNode;
  16200. }
  16201. return false;
  16202. },
  16203. /**
  16204. * get the center of all the touches
  16205. * @param {Array} touches
  16206. * @returns {Object} center
  16207. */
  16208. getCenter: function getCenter(touches) {
  16209. var valuesX = [], valuesY = [];
  16210. for(var t= 0,len=touches.length; t<len; t++) {
  16211. valuesX.push(touches[t].pageX);
  16212. valuesY.push(touches[t].pageY);
  16213. }
  16214. return {
  16215. pageX: ((Math.min.apply(Math, valuesX) + Math.max.apply(Math, valuesX)) / 2),
  16216. pageY: ((Math.min.apply(Math, valuesY) + Math.max.apply(Math, valuesY)) / 2)
  16217. };
  16218. },
  16219. /**
  16220. * calculate the velocity between two points
  16221. * @param {Number} delta_time
  16222. * @param {Number} delta_x
  16223. * @param {Number} delta_y
  16224. * @returns {Object} velocity
  16225. */
  16226. getVelocity: function getVelocity(delta_time, delta_x, delta_y) {
  16227. return {
  16228. x: Math.abs(delta_x / delta_time) || 0,
  16229. y: Math.abs(delta_y / delta_time) || 0
  16230. };
  16231. },
  16232. /**
  16233. * calculate the angle between two coordinates
  16234. * @param {Touch} touch1
  16235. * @param {Touch} touch2
  16236. * @returns {Number} angle
  16237. */
  16238. getAngle: function getAngle(touch1, touch2) {
  16239. var y = touch2.pageY - touch1.pageY,
  16240. x = touch2.pageX - touch1.pageX;
  16241. return Math.atan2(y, x) * 180 / Math.PI;
  16242. },
  16243. /**
  16244. * angle to direction define
  16245. * @param {Touch} touch1
  16246. * @param {Touch} touch2
  16247. * @returns {String} direction constant, like Hammer.DIRECTION_LEFT
  16248. */
  16249. getDirection: function getDirection(touch1, touch2) {
  16250. var x = Math.abs(touch1.pageX - touch2.pageX),
  16251. y = Math.abs(touch1.pageY - touch2.pageY);
  16252. if(x >= y) {
  16253. return touch1.pageX - touch2.pageX > 0 ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  16254. }
  16255. else {
  16256. return touch1.pageY - touch2.pageY > 0 ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  16257. }
  16258. },
  16259. /**
  16260. * calculate the distance between two touches
  16261. * @param {Touch} touch1
  16262. * @param {Touch} touch2
  16263. * @returns {Number} distance
  16264. */
  16265. getDistance: function getDistance(touch1, touch2) {
  16266. var x = touch2.pageX - touch1.pageX,
  16267. y = touch2.pageY - touch1.pageY;
  16268. return Math.sqrt((x*x) + (y*y));
  16269. },
  16270. /**
  16271. * calculate the scale factor between two touchLists (fingers)
  16272. * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
  16273. * @param {Array} start
  16274. * @param {Array} end
  16275. * @returns {Number} scale
  16276. */
  16277. getScale: function getScale(start, end) {
  16278. // need two fingers...
  16279. if(start.length >= 2 && end.length >= 2) {
  16280. return this.getDistance(end[0], end[1]) /
  16281. this.getDistance(start[0], start[1]);
  16282. }
  16283. return 1;
  16284. },
  16285. /**
  16286. * calculate the rotation degrees between two touchLists (fingers)
  16287. * @param {Array} start
  16288. * @param {Array} end
  16289. * @returns {Number} rotation
  16290. */
  16291. getRotation: function getRotation(start, end) {
  16292. // need two fingers
  16293. if(start.length >= 2 && end.length >= 2) {
  16294. return this.getAngle(end[1], end[0]) -
  16295. this.getAngle(start[1], start[0]);
  16296. }
  16297. return 0;
  16298. },
  16299. /**
  16300. * boolean if the direction is vertical
  16301. * @param {String} direction
  16302. * @returns {Boolean} is_vertical
  16303. */
  16304. isVertical: function isVertical(direction) {
  16305. return (direction == Hammer.DIRECTION_UP || direction == Hammer.DIRECTION_DOWN);
  16306. },
  16307. /**
  16308. * stop browser default behavior with css props
  16309. * @param {HtmlElement} element
  16310. * @param {Object} css_props
  16311. */
  16312. stopDefaultBrowserBehavior: function stopDefaultBrowserBehavior(element, css_props) {
  16313. var prop,
  16314. vendors = ['webkit','khtml','moz','ms','o',''];
  16315. if(!css_props || !element.style) {
  16316. return;
  16317. }
  16318. // with css properties for modern browsers
  16319. for(var i = 0; i < vendors.length; i++) {
  16320. for(var p in css_props) {
  16321. if(css_props.hasOwnProperty(p)) {
  16322. prop = p;
  16323. // vender prefix at the property
  16324. if(vendors[i]) {
  16325. prop = vendors[i] + prop.substring(0, 1).toUpperCase() + prop.substring(1);
  16326. }
  16327. // set the style
  16328. element.style[prop] = css_props[p];
  16329. }
  16330. }
  16331. }
  16332. // also the disable onselectstart
  16333. if(css_props.userSelect == 'none') {
  16334. element.onselectstart = function() {
  16335. return false;
  16336. };
  16337. }
  16338. }
  16339. };
  16340. Hammer.detection = {
  16341. // contains all registred Hammer.gestures in the correct order
  16342. gestures: [],
  16343. // data of the current Hammer.gesture detection session
  16344. current: null,
  16345. // the previous Hammer.gesture session data
  16346. // is a full clone of the previous gesture.current object
  16347. previous: null,
  16348. // when this becomes true, no gestures are fired
  16349. stopped: false,
  16350. /**
  16351. * start Hammer.gesture detection
  16352. * @param {Hammer.Instance} inst
  16353. * @param {Object} eventData
  16354. */
  16355. startDetect: function startDetect(inst, eventData) {
  16356. // already busy with a Hammer.gesture detection on an element
  16357. if(this.current) {
  16358. return;
  16359. }
  16360. this.stopped = false;
  16361. this.current = {
  16362. inst : inst, // reference to HammerInstance we're working for
  16363. startEvent : Hammer.utils.extend({}, eventData), // start eventData for distances, timing etc
  16364. lastEvent : false, // last eventData
  16365. name : '' // current gesture we're in/detected, can be 'tap', 'hold' etc
  16366. };
  16367. this.detect(eventData);
  16368. },
  16369. /**
  16370. * Hammer.gesture detection
  16371. * @param {Object} eventData
  16372. * @param {Object} eventData
  16373. */
  16374. detect: function detect(eventData) {
  16375. if(!this.current || this.stopped) {
  16376. return;
  16377. }
  16378. // extend event data with calculations about scale, distance etc
  16379. eventData = this.extendEventData(eventData);
  16380. // instance options
  16381. var inst_options = this.current.inst.options;
  16382. // call Hammer.gesture handlers
  16383. for(var g=0,len=this.gestures.length; g<len; g++) {
  16384. var gesture = this.gestures[g];
  16385. // only when the instance options have enabled this gesture
  16386. if(!this.stopped && inst_options[gesture.name] !== false) {
  16387. // if a handler returns false, we stop with the detection
  16388. if(gesture.handler.call(gesture, eventData, this.current.inst) === false) {
  16389. this.stopDetect();
  16390. break;
  16391. }
  16392. }
  16393. }
  16394. // store as previous event event
  16395. if(this.current) {
  16396. this.current.lastEvent = eventData;
  16397. }
  16398. // endevent, but not the last touch, so dont stop
  16399. if(eventData.eventType == Hammer.EVENT_END && !eventData.touches.length-1) {
  16400. this.stopDetect();
  16401. }
  16402. return eventData;
  16403. },
  16404. /**
  16405. * clear the Hammer.gesture vars
  16406. * this is called on endDetect, but can also be used when a final Hammer.gesture has been detected
  16407. * to stop other Hammer.gestures from being fired
  16408. */
  16409. stopDetect: function stopDetect() {
  16410. // clone current data to the store as the previous gesture
  16411. // used for the double tap gesture, since this is an other gesture detect session
  16412. this.previous = Hammer.utils.extend({}, this.current);
  16413. // reset the current
  16414. this.current = null;
  16415. // stopped!
  16416. this.stopped = true;
  16417. },
  16418. /**
  16419. * extend eventData for Hammer.gestures
  16420. * @param {Object} ev
  16421. * @returns {Object} ev
  16422. */
  16423. extendEventData: function extendEventData(ev) {
  16424. var startEv = this.current.startEvent;
  16425. // if the touches change, set the new touches over the startEvent touches
  16426. // this because touchevents don't have all the touches on touchstart, or the
  16427. // user must place his fingers at the EXACT same time on the screen, which is not realistic
  16428. // but, sometimes it happens that both fingers are touching at the EXACT same time
  16429. if(startEv && (ev.touches.length != startEv.touches.length || ev.touches === startEv.touches)) {
  16430. // extend 1 level deep to get the touchlist with the touch objects
  16431. startEv.touches = [];
  16432. for(var i=0,len=ev.touches.length; i<len; i++) {
  16433. startEv.touches.push(Hammer.utils.extend({}, ev.touches[i]));
  16434. }
  16435. }
  16436. var delta_time = ev.timeStamp - startEv.timeStamp,
  16437. delta_x = ev.center.pageX - startEv.center.pageX,
  16438. delta_y = ev.center.pageY - startEv.center.pageY,
  16439. velocity = Hammer.utils.getVelocity(delta_time, delta_x, delta_y);
  16440. Hammer.utils.extend(ev, {
  16441. deltaTime : delta_time,
  16442. deltaX : delta_x,
  16443. deltaY : delta_y,
  16444. velocityX : velocity.x,
  16445. velocityY : velocity.y,
  16446. distance : Hammer.utils.getDistance(startEv.center, ev.center),
  16447. angle : Hammer.utils.getAngle(startEv.center, ev.center),
  16448. direction : Hammer.utils.getDirection(startEv.center, ev.center),
  16449. scale : Hammer.utils.getScale(startEv.touches, ev.touches),
  16450. rotation : Hammer.utils.getRotation(startEv.touches, ev.touches),
  16451. startEvent : startEv
  16452. });
  16453. return ev;
  16454. },
  16455. /**
  16456. * register new gesture
  16457. * @param {Object} gesture object, see gestures.js for documentation
  16458. * @returns {Array} gestures
  16459. */
  16460. register: function register(gesture) {
  16461. // add an enable gesture options if there is no given
  16462. var options = gesture.defaults || {};
  16463. if(options[gesture.name] === undefined) {
  16464. options[gesture.name] = true;
  16465. }
  16466. // extend Hammer default options with the Hammer.gesture options
  16467. Hammer.utils.extend(Hammer.defaults, options, true);
  16468. // set its index
  16469. gesture.index = gesture.index || 1000;
  16470. // add Hammer.gesture to the list
  16471. this.gestures.push(gesture);
  16472. // sort the list by index
  16473. this.gestures.sort(function(a, b) {
  16474. if (a.index < b.index) {
  16475. return -1;
  16476. }
  16477. if (a.index > b.index) {
  16478. return 1;
  16479. }
  16480. return 0;
  16481. });
  16482. return this.gestures;
  16483. }
  16484. };
  16485. Hammer.gestures = Hammer.gestures || {};
  16486. /**
  16487. * Custom gestures
  16488. * ==============================
  16489. *
  16490. * Gesture object
  16491. * --------------------
  16492. * The object structure of a gesture:
  16493. *
  16494. * { name: 'mygesture',
  16495. * index: 1337,
  16496. * defaults: {
  16497. * mygesture_option: true
  16498. * }
  16499. * handler: function(type, ev, inst) {
  16500. * // trigger gesture event
  16501. * inst.trigger(this.name, ev);
  16502. * }
  16503. * }
  16504. * @param {String} name
  16505. * this should be the name of the gesture, lowercase
  16506. * it is also being used to disable/enable the gesture per instance config.
  16507. *
  16508. * @param {Number} [index=1000]
  16509. * the index of the gesture, where it is going to be in the stack of gestures detection
  16510. * like when you build an gesture that depends on the drag gesture, it is a good
  16511. * idea to place it after the index of the drag gesture.
  16512. *
  16513. * @param {Object} [defaults={}]
  16514. * the default settings of the gesture. these are added to the instance settings,
  16515. * and can be overruled per instance. you can also add the name of the gesture,
  16516. * but this is also added by default (and set to true).
  16517. *
  16518. * @param {Function} handler
  16519. * this handles the gesture detection of your custom gesture and receives the
  16520. * following arguments:
  16521. *
  16522. * @param {Object} eventData
  16523. * event data containing the following properties:
  16524. * timeStamp {Number} time the event occurred
  16525. * target {HTMLElement} target element
  16526. * touches {Array} touches (fingers, pointers, mouse) on the screen
  16527. * pointerType {String} kind of pointer that was used. matches Hammer.POINTER_MOUSE|TOUCH
  16528. * center {Object} center position of the touches. contains pageX and pageY
  16529. * deltaTime {Number} the total time of the touches in the screen
  16530. * deltaX {Number} the delta on x axis we haved moved
  16531. * deltaY {Number} the delta on y axis we haved moved
  16532. * velocityX {Number} the velocity on the x
  16533. * velocityY {Number} the velocity on y
  16534. * angle {Number} the angle we are moving
  16535. * direction {String} the direction we are moving. matches Hammer.DIRECTION_UP|DOWN|LEFT|RIGHT
  16536. * distance {Number} the distance we haved moved
  16537. * scale {Number} scaling of the touches, needs 2 touches
  16538. * rotation {Number} rotation of the touches, needs 2 touches *
  16539. * eventType {String} matches Hammer.EVENT_START|MOVE|END
  16540. * srcEvent {Object} the source event, like TouchStart or MouseDown *
  16541. * startEvent {Object} contains the same properties as above,
  16542. * but from the first touch. this is used to calculate
  16543. * distances, deltaTime, scaling etc
  16544. *
  16545. * @param {Hammer.Instance} inst
  16546. * the instance we are doing the detection for. you can get the options from
  16547. * the inst.options object and trigger the gesture event by calling inst.trigger
  16548. *
  16549. *
  16550. * Handle gestures
  16551. * --------------------
  16552. * inside the handler you can get/set Hammer.detection.current. This is the current
  16553. * detection session. It has the following properties
  16554. * @param {String} name
  16555. * contains the name of the gesture we have detected. it has not a real function,
  16556. * only to check in other gestures if something is detected.
  16557. * like in the drag gesture we set it to 'drag' and in the swipe gesture we can
  16558. * check if the current gesture is 'drag' by accessing Hammer.detection.current.name
  16559. *
  16560. * @readonly
  16561. * @param {Hammer.Instance} inst
  16562. * the instance we do the detection for
  16563. *
  16564. * @readonly
  16565. * @param {Object} startEvent
  16566. * contains the properties of the first gesture detection in this session.
  16567. * Used for calculations about timing, distance, etc.
  16568. *
  16569. * @readonly
  16570. * @param {Object} lastEvent
  16571. * contains all the properties of the last gesture detect in this session.
  16572. *
  16573. * after the gesture detection session has been completed (user has released the screen)
  16574. * the Hammer.detection.current object is copied into Hammer.detection.previous,
  16575. * this is usefull for gestures like doubletap, where you need to know if the
  16576. * previous gesture was a tap
  16577. *
  16578. * options that have been set by the instance can be received by calling inst.options
  16579. *
  16580. * You can trigger a gesture event by calling inst.trigger("mygesture", event).
  16581. * The first param is the name of your gesture, the second the event argument
  16582. *
  16583. *
  16584. * Register gestures
  16585. * --------------------
  16586. * When an gesture is added to the Hammer.gestures object, it is auto registered
  16587. * at the setup of the first Hammer instance. You can also call Hammer.detection.register
  16588. * manually and pass your gesture object as a param
  16589. *
  16590. */
  16591. /**
  16592. * Hold
  16593. * Touch stays at the same place for x time
  16594. * @events hold
  16595. */
  16596. Hammer.gestures.Hold = {
  16597. name: 'hold',
  16598. index: 10,
  16599. defaults: {
  16600. hold_timeout : 500,
  16601. hold_threshold : 1
  16602. },
  16603. timer: null,
  16604. handler: function holdGesture(ev, inst) {
  16605. switch(ev.eventType) {
  16606. case Hammer.EVENT_START:
  16607. // clear any running timers
  16608. clearTimeout(this.timer);
  16609. // set the gesture so we can check in the timeout if it still is
  16610. Hammer.detection.current.name = this.name;
  16611. // set timer and if after the timeout it still is hold,
  16612. // we trigger the hold event
  16613. this.timer = setTimeout(function() {
  16614. if(Hammer.detection.current.name == 'hold') {
  16615. inst.trigger('hold', ev);
  16616. }
  16617. }, inst.options.hold_timeout);
  16618. break;
  16619. // when you move or end we clear the timer
  16620. case Hammer.EVENT_MOVE:
  16621. if(ev.distance > inst.options.hold_threshold) {
  16622. clearTimeout(this.timer);
  16623. }
  16624. break;
  16625. case Hammer.EVENT_END:
  16626. clearTimeout(this.timer);
  16627. break;
  16628. }
  16629. }
  16630. };
  16631. /**
  16632. * Tap/DoubleTap
  16633. * Quick touch at a place or double at the same place
  16634. * @events tap, doubletap
  16635. */
  16636. Hammer.gestures.Tap = {
  16637. name: 'tap',
  16638. index: 100,
  16639. defaults: {
  16640. tap_max_touchtime : 250,
  16641. tap_max_distance : 10,
  16642. tap_always : true,
  16643. doubletap_distance : 20,
  16644. doubletap_interval : 300
  16645. },
  16646. handler: function tapGesture(ev, inst) {
  16647. if(ev.eventType == Hammer.EVENT_END) {
  16648. // previous gesture, for the double tap since these are two different gesture detections
  16649. var prev = Hammer.detection.previous,
  16650. did_doubletap = false;
  16651. // when the touchtime is higher then the max touch time
  16652. // or when the moving distance is too much
  16653. if(ev.deltaTime > inst.options.tap_max_touchtime ||
  16654. ev.distance > inst.options.tap_max_distance) {
  16655. return;
  16656. }
  16657. // check if double tap
  16658. if(prev && prev.name == 'tap' &&
  16659. (ev.timeStamp - prev.lastEvent.timeStamp) < inst.options.doubletap_interval &&
  16660. ev.distance < inst.options.doubletap_distance) {
  16661. inst.trigger('doubletap', ev);
  16662. did_doubletap = true;
  16663. }
  16664. // do a single tap
  16665. if(!did_doubletap || inst.options.tap_always) {
  16666. Hammer.detection.current.name = 'tap';
  16667. inst.trigger(Hammer.detection.current.name, ev);
  16668. }
  16669. }
  16670. }
  16671. };
  16672. /**
  16673. * Swipe
  16674. * triggers swipe events when the end velocity is above the threshold
  16675. * @events swipe, swipeleft, swiperight, swipeup, swipedown
  16676. */
  16677. Hammer.gestures.Swipe = {
  16678. name: 'swipe',
  16679. index: 40,
  16680. defaults: {
  16681. // set 0 for unlimited, but this can conflict with transform
  16682. swipe_max_touches : 1,
  16683. swipe_velocity : 0.7
  16684. },
  16685. handler: function swipeGesture(ev, inst) {
  16686. if(ev.eventType == Hammer.EVENT_END) {
  16687. // max touches
  16688. if(inst.options.swipe_max_touches > 0 &&
  16689. ev.touches.length > inst.options.swipe_max_touches) {
  16690. return;
  16691. }
  16692. // when the distance we moved is too small we skip this gesture
  16693. // or we can be already in dragging
  16694. if(ev.velocityX > inst.options.swipe_velocity ||
  16695. ev.velocityY > inst.options.swipe_velocity) {
  16696. // trigger swipe events
  16697. inst.trigger(this.name, ev);
  16698. inst.trigger(this.name + ev.direction, ev);
  16699. }
  16700. }
  16701. }
  16702. };
  16703. /**
  16704. * Drag
  16705. * Move with x fingers (default 1) around on the page. Blocking the scrolling when
  16706. * moving left and right is a good practice. When all the drag events are blocking
  16707. * you disable scrolling on that area.
  16708. * @events drag, drapleft, dragright, dragup, dragdown
  16709. */
  16710. Hammer.gestures.Drag = {
  16711. name: 'drag',
  16712. index: 50,
  16713. defaults: {
  16714. drag_min_distance : 10,
  16715. // set 0 for unlimited, but this can conflict with transform
  16716. drag_max_touches : 1,
  16717. // prevent default browser behavior when dragging occurs
  16718. // be careful with it, it makes the element a blocking element
  16719. // when you are using the drag gesture, it is a good practice to set this true
  16720. drag_block_horizontal : false,
  16721. drag_block_vertical : false,
  16722. // drag_lock_to_axis keeps the drag gesture on the axis that it started on,
  16723. // It disallows vertical directions if the initial direction was horizontal, and vice versa.
  16724. drag_lock_to_axis : false,
  16725. // drag lock only kicks in when distance > drag_lock_min_distance
  16726. // This way, locking occurs only when the distance has become large enough to reliably determine the direction
  16727. drag_lock_min_distance : 25
  16728. },
  16729. triggered: false,
  16730. handler: function dragGesture(ev, inst) {
  16731. // current gesture isnt drag, but dragged is true
  16732. // this means an other gesture is busy. now call dragend
  16733. if(Hammer.detection.current.name != this.name && this.triggered) {
  16734. inst.trigger(this.name +'end', ev);
  16735. this.triggered = false;
  16736. return;
  16737. }
  16738. // max touches
  16739. if(inst.options.drag_max_touches > 0 &&
  16740. ev.touches.length > inst.options.drag_max_touches) {
  16741. return;
  16742. }
  16743. switch(ev.eventType) {
  16744. case Hammer.EVENT_START:
  16745. this.triggered = false;
  16746. break;
  16747. case Hammer.EVENT_MOVE:
  16748. // when the distance we moved is too small we skip this gesture
  16749. // or we can be already in dragging
  16750. if(ev.distance < inst.options.drag_min_distance &&
  16751. Hammer.detection.current.name != this.name) {
  16752. return;
  16753. }
  16754. // we are dragging!
  16755. Hammer.detection.current.name = this.name;
  16756. // lock drag to axis?
  16757. if(Hammer.detection.current.lastEvent.drag_locked_to_axis || (inst.options.drag_lock_to_axis && inst.options.drag_lock_min_distance<=ev.distance)) {
  16758. ev.drag_locked_to_axis = true;
  16759. }
  16760. var last_direction = Hammer.detection.current.lastEvent.direction;
  16761. if(ev.drag_locked_to_axis && last_direction !== ev.direction) {
  16762. // keep direction on the axis that the drag gesture started on
  16763. if(Hammer.utils.isVertical(last_direction)) {
  16764. ev.direction = (ev.deltaY < 0) ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  16765. }
  16766. else {
  16767. ev.direction = (ev.deltaX < 0) ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  16768. }
  16769. }
  16770. // first time, trigger dragstart event
  16771. if(!this.triggered) {
  16772. inst.trigger(this.name +'start', ev);
  16773. this.triggered = true;
  16774. }
  16775. // trigger normal event
  16776. inst.trigger(this.name, ev);
  16777. // direction event, like dragdown
  16778. inst.trigger(this.name + ev.direction, ev);
  16779. // block the browser events
  16780. if( (inst.options.drag_block_vertical && Hammer.utils.isVertical(ev.direction)) ||
  16781. (inst.options.drag_block_horizontal && !Hammer.utils.isVertical(ev.direction))) {
  16782. ev.preventDefault();
  16783. }
  16784. break;
  16785. case Hammer.EVENT_END:
  16786. // trigger dragend
  16787. if(this.triggered) {
  16788. inst.trigger(this.name +'end', ev);
  16789. }
  16790. this.triggered = false;
  16791. break;
  16792. }
  16793. }
  16794. };
  16795. /**
  16796. * Transform
  16797. * User want to scale or rotate with 2 fingers
  16798. * @events transform, pinch, pinchin, pinchout, rotate
  16799. */
  16800. Hammer.gestures.Transform = {
  16801. name: 'transform',
  16802. index: 45,
  16803. defaults: {
  16804. // factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1
  16805. transform_min_scale : 0.01,
  16806. // rotation in degrees
  16807. transform_min_rotation : 1,
  16808. // prevent default browser behavior when two touches are on the screen
  16809. // but it makes the element a blocking element
  16810. // when you are using the transform gesture, it is a good practice to set this true
  16811. transform_always_block : false
  16812. },
  16813. triggered: false,
  16814. handler: function transformGesture(ev, inst) {
  16815. // current gesture isnt drag, but dragged is true
  16816. // this means an other gesture is busy. now call dragend
  16817. if(Hammer.detection.current.name != this.name && this.triggered) {
  16818. inst.trigger(this.name +'end', ev);
  16819. this.triggered = false;
  16820. return;
  16821. }
  16822. // atleast multitouch
  16823. if(ev.touches.length < 2) {
  16824. return;
  16825. }
  16826. // prevent default when two fingers are on the screen
  16827. if(inst.options.transform_always_block) {
  16828. ev.preventDefault();
  16829. }
  16830. switch(ev.eventType) {
  16831. case Hammer.EVENT_START:
  16832. this.triggered = false;
  16833. break;
  16834. case Hammer.EVENT_MOVE:
  16835. var scale_threshold = Math.abs(1-ev.scale);
  16836. var rotation_threshold = Math.abs(ev.rotation);
  16837. // when the distance we moved is too small we skip this gesture
  16838. // or we can be already in dragging
  16839. if(scale_threshold < inst.options.transform_min_scale &&
  16840. rotation_threshold < inst.options.transform_min_rotation) {
  16841. return;
  16842. }
  16843. // we are transforming!
  16844. Hammer.detection.current.name = this.name;
  16845. // first time, trigger dragstart event
  16846. if(!this.triggered) {
  16847. inst.trigger(this.name +'start', ev);
  16848. this.triggered = true;
  16849. }
  16850. inst.trigger(this.name, ev); // basic transform event
  16851. // trigger rotate event
  16852. if(rotation_threshold > inst.options.transform_min_rotation) {
  16853. inst.trigger('rotate', ev);
  16854. }
  16855. // trigger pinch event
  16856. if(scale_threshold > inst.options.transform_min_scale) {
  16857. inst.trigger('pinch', ev);
  16858. inst.trigger('pinch'+ ((ev.scale < 1) ? 'in' : 'out'), ev);
  16859. }
  16860. break;
  16861. case Hammer.EVENT_END:
  16862. // trigger dragend
  16863. if(this.triggered) {
  16864. inst.trigger(this.name +'end', ev);
  16865. }
  16866. this.triggered = false;
  16867. break;
  16868. }
  16869. }
  16870. };
  16871. /**
  16872. * Touch
  16873. * Called as first, tells the user has touched the screen
  16874. * @events touch
  16875. */
  16876. Hammer.gestures.Touch = {
  16877. name: 'touch',
  16878. index: -Infinity,
  16879. defaults: {
  16880. // call preventDefault at touchstart, and makes the element blocking by
  16881. // disabling the scrolling of the page, but it improves gestures like
  16882. // transforming and dragging.
  16883. // be careful with using this, it can be very annoying for users to be stuck
  16884. // on the page
  16885. prevent_default: false,
  16886. // disable mouse events, so only touch (or pen!) input triggers events
  16887. prevent_mouseevents: false
  16888. },
  16889. handler: function touchGesture(ev, inst) {
  16890. if(inst.options.prevent_mouseevents && ev.pointerType == Hammer.POINTER_MOUSE) {
  16891. ev.stopDetect();
  16892. return;
  16893. }
  16894. if(inst.options.prevent_default) {
  16895. ev.preventDefault();
  16896. }
  16897. if(ev.eventType == Hammer.EVENT_START) {
  16898. inst.trigger(this.name, ev);
  16899. }
  16900. }
  16901. };
  16902. /**
  16903. * Release
  16904. * Called as last, tells the user has released the screen
  16905. * @events release
  16906. */
  16907. Hammer.gestures.Release = {
  16908. name: 'release',
  16909. index: Infinity,
  16910. handler: function releaseGesture(ev, inst) {
  16911. if(ev.eventType == Hammer.EVENT_END) {
  16912. inst.trigger(this.name, ev);
  16913. }
  16914. }
  16915. };
  16916. // node export
  16917. if(typeof module === 'object' && typeof module.exports === 'object'){
  16918. module.exports = Hammer;
  16919. }
  16920. // just window export
  16921. else {
  16922. window.Hammer = Hammer;
  16923. // requireJS module definition
  16924. if(typeof window.define === 'function' && window.define.amd) {
  16925. window.define('hammer', [], function() {
  16926. return Hammer;
  16927. });
  16928. }
  16929. }
  16930. })(this);
  16931. },{}],4:[function(require,module,exports){
  16932. //! moment.js
  16933. //! version : 2.5.1
  16934. //! authors : Tim Wood, Iskren Chernev, Moment.js contributors
  16935. //! license : MIT
  16936. //! momentjs.com
  16937. (function (undefined) {
  16938. /************************************
  16939. Constants
  16940. ************************************/
  16941. var moment,
  16942. VERSION = "2.5.1",
  16943. global = this,
  16944. round = Math.round,
  16945. i,
  16946. YEAR = 0,
  16947. MONTH = 1,
  16948. DATE = 2,
  16949. HOUR = 3,
  16950. MINUTE = 4,
  16951. SECOND = 5,
  16952. MILLISECOND = 6,
  16953. // internal storage for language config files
  16954. languages = {},
  16955. // moment internal properties
  16956. momentProperties = {
  16957. _isAMomentObject: null,
  16958. _i : null,
  16959. _f : null,
  16960. _l : null,
  16961. _strict : null,
  16962. _isUTC : null,
  16963. _offset : null, // optional. Combine with _isUTC
  16964. _pf : null,
  16965. _lang : null // optional
  16966. },
  16967. // check for nodeJS
  16968. hasModule = (typeof module !== 'undefined' && module.exports && typeof require !== 'undefined'),
  16969. // ASP.NET json date format regex
  16970. aspNetJsonRegex = /^\/?Date\((\-?\d+)/i,
  16971. aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,
  16972. // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
  16973. // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
  16974. isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/,
  16975. // format tokens
  16976. 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,
  16977. localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g,
  16978. // parsing token regexes
  16979. parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99
  16980. parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999
  16981. parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999
  16982. parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999
  16983. parseTokenDigits = /\d+/, // nonzero number of digits
  16984. 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.
  16985. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z
  16986. parseTokenT = /T/i, // T (ISO separator)
  16987. parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
  16988. //strict parsing regexes
  16989. parseTokenOneDigit = /\d/, // 0 - 9
  16990. parseTokenTwoDigits = /\d\d/, // 00 - 99
  16991. parseTokenThreeDigits = /\d{3}/, // 000 - 999
  16992. parseTokenFourDigits = /\d{4}/, // 0000 - 9999
  16993. parseTokenSixDigits = /[+-]?\d{6}/, // -999,999 - 999,999
  16994. parseTokenSignedNumber = /[+-]?\d+/, // -inf - inf
  16995. // iso 8601 regex
  16996. // 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)
  16997. 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)?)?$/,
  16998. isoFormat = 'YYYY-MM-DDTHH:mm:ssZ',
  16999. isoDates = [
  17000. ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/],
  17001. ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/],
  17002. ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/],
  17003. ['GGGG-[W]WW', /\d{4}-W\d{2}/],
  17004. ['YYYY-DDD', /\d{4}-\d{3}/]
  17005. ],
  17006. // iso time formats and regexes
  17007. isoTimes = [
  17008. ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d{1,3}/],
  17009. ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/],
  17010. ['HH:mm', /(T| )\d\d:\d\d/],
  17011. ['HH', /(T| )\d\d/]
  17012. ],
  17013. // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"]
  17014. parseTimezoneChunker = /([\+\-]|\d\d)/gi,
  17015. // getter and setter names
  17016. proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'),
  17017. unitMillisecondFactors = {
  17018. 'Milliseconds' : 1,
  17019. 'Seconds' : 1e3,
  17020. 'Minutes' : 6e4,
  17021. 'Hours' : 36e5,
  17022. 'Days' : 864e5,
  17023. 'Months' : 2592e6,
  17024. 'Years' : 31536e6
  17025. },
  17026. unitAliases = {
  17027. ms : 'millisecond',
  17028. s : 'second',
  17029. m : 'minute',
  17030. h : 'hour',
  17031. d : 'day',
  17032. D : 'date',
  17033. w : 'week',
  17034. W : 'isoWeek',
  17035. M : 'month',
  17036. y : 'year',
  17037. DDD : 'dayOfYear',
  17038. e : 'weekday',
  17039. E : 'isoWeekday',
  17040. gg: 'weekYear',
  17041. GG: 'isoWeekYear'
  17042. },
  17043. camelFunctions = {
  17044. dayofyear : 'dayOfYear',
  17045. isoweekday : 'isoWeekday',
  17046. isoweek : 'isoWeek',
  17047. weekyear : 'weekYear',
  17048. isoweekyear : 'isoWeekYear'
  17049. },
  17050. // format function strings
  17051. formatFunctions = {},
  17052. // tokens to ordinalize and pad
  17053. ordinalizeTokens = 'DDD w W M D d'.split(' '),
  17054. paddedTokens = 'M D H h m s w W'.split(' '),
  17055. formatTokenFunctions = {
  17056. M : function () {
  17057. return this.month() + 1;
  17058. },
  17059. MMM : function (format) {
  17060. return this.lang().monthsShort(this, format);
  17061. },
  17062. MMMM : function (format) {
  17063. return this.lang().months(this, format);
  17064. },
  17065. D : function () {
  17066. return this.date();
  17067. },
  17068. DDD : function () {
  17069. return this.dayOfYear();
  17070. },
  17071. d : function () {
  17072. return this.day();
  17073. },
  17074. dd : function (format) {
  17075. return this.lang().weekdaysMin(this, format);
  17076. },
  17077. ddd : function (format) {
  17078. return this.lang().weekdaysShort(this, format);
  17079. },
  17080. dddd : function (format) {
  17081. return this.lang().weekdays(this, format);
  17082. },
  17083. w : function () {
  17084. return this.week();
  17085. },
  17086. W : function () {
  17087. return this.isoWeek();
  17088. },
  17089. YY : function () {
  17090. return leftZeroFill(this.year() % 100, 2);
  17091. },
  17092. YYYY : function () {
  17093. return leftZeroFill(this.year(), 4);
  17094. },
  17095. YYYYY : function () {
  17096. return leftZeroFill(this.year(), 5);
  17097. },
  17098. YYYYYY : function () {
  17099. var y = this.year(), sign = y >= 0 ? '+' : '-';
  17100. return sign + leftZeroFill(Math.abs(y), 6);
  17101. },
  17102. gg : function () {
  17103. return leftZeroFill(this.weekYear() % 100, 2);
  17104. },
  17105. gggg : function () {
  17106. return leftZeroFill(this.weekYear(), 4);
  17107. },
  17108. ggggg : function () {
  17109. return leftZeroFill(this.weekYear(), 5);
  17110. },
  17111. GG : function () {
  17112. return leftZeroFill(this.isoWeekYear() % 100, 2);
  17113. },
  17114. GGGG : function () {
  17115. return leftZeroFill(this.isoWeekYear(), 4);
  17116. },
  17117. GGGGG : function () {
  17118. return leftZeroFill(this.isoWeekYear(), 5);
  17119. },
  17120. e : function () {
  17121. return this.weekday();
  17122. },
  17123. E : function () {
  17124. return this.isoWeekday();
  17125. },
  17126. a : function () {
  17127. return this.lang().meridiem(this.hours(), this.minutes(), true);
  17128. },
  17129. A : function () {
  17130. return this.lang().meridiem(this.hours(), this.minutes(), false);
  17131. },
  17132. H : function () {
  17133. return this.hours();
  17134. },
  17135. h : function () {
  17136. return this.hours() % 12 || 12;
  17137. },
  17138. m : function () {
  17139. return this.minutes();
  17140. },
  17141. s : function () {
  17142. return this.seconds();
  17143. },
  17144. S : function () {
  17145. return toInt(this.milliseconds() / 100);
  17146. },
  17147. SS : function () {
  17148. return leftZeroFill(toInt(this.milliseconds() / 10), 2);
  17149. },
  17150. SSS : function () {
  17151. return leftZeroFill(this.milliseconds(), 3);
  17152. },
  17153. SSSS : function () {
  17154. return leftZeroFill(this.milliseconds(), 3);
  17155. },
  17156. Z : function () {
  17157. var a = -this.zone(),
  17158. b = "+";
  17159. if (a < 0) {
  17160. a = -a;
  17161. b = "-";
  17162. }
  17163. return b + leftZeroFill(toInt(a / 60), 2) + ":" + leftZeroFill(toInt(a) % 60, 2);
  17164. },
  17165. ZZ : function () {
  17166. var a = -this.zone(),
  17167. b = "+";
  17168. if (a < 0) {
  17169. a = -a;
  17170. b = "-";
  17171. }
  17172. return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2);
  17173. },
  17174. z : function () {
  17175. return this.zoneAbbr();
  17176. },
  17177. zz : function () {
  17178. return this.zoneName();
  17179. },
  17180. X : function () {
  17181. return this.unix();
  17182. },
  17183. Q : function () {
  17184. return this.quarter();
  17185. }
  17186. },
  17187. lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin'];
  17188. function defaultParsingFlags() {
  17189. // We need to deep clone this object, and es5 standard is not very
  17190. // helpful.
  17191. return {
  17192. empty : false,
  17193. unusedTokens : [],
  17194. unusedInput : [],
  17195. overflow : -2,
  17196. charsLeftOver : 0,
  17197. nullInput : false,
  17198. invalidMonth : null,
  17199. invalidFormat : false,
  17200. userInvalidated : false,
  17201. iso: false
  17202. };
  17203. }
  17204. function padToken(func, count) {
  17205. return function (a) {
  17206. return leftZeroFill(func.call(this, a), count);
  17207. };
  17208. }
  17209. function ordinalizeToken(func, period) {
  17210. return function (a) {
  17211. return this.lang().ordinal(func.call(this, a), period);
  17212. };
  17213. }
  17214. while (ordinalizeTokens.length) {
  17215. i = ordinalizeTokens.pop();
  17216. formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i);
  17217. }
  17218. while (paddedTokens.length) {
  17219. i = paddedTokens.pop();
  17220. formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2);
  17221. }
  17222. formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3);
  17223. /************************************
  17224. Constructors
  17225. ************************************/
  17226. function Language() {
  17227. }
  17228. // Moment prototype object
  17229. function Moment(config) {
  17230. checkOverflow(config);
  17231. extend(this, config);
  17232. }
  17233. // Duration Constructor
  17234. function Duration(duration) {
  17235. var normalizedInput = normalizeObjectUnits(duration),
  17236. years = normalizedInput.year || 0,
  17237. months = normalizedInput.month || 0,
  17238. weeks = normalizedInput.week || 0,
  17239. days = normalizedInput.day || 0,
  17240. hours = normalizedInput.hour || 0,
  17241. minutes = normalizedInput.minute || 0,
  17242. seconds = normalizedInput.second || 0,
  17243. milliseconds = normalizedInput.millisecond || 0;
  17244. // representation for dateAddRemove
  17245. this._milliseconds = +milliseconds +
  17246. seconds * 1e3 + // 1000
  17247. minutes * 6e4 + // 1000 * 60
  17248. hours * 36e5; // 1000 * 60 * 60
  17249. // Because of dateAddRemove treats 24 hours as different from a
  17250. // day when working around DST, we need to store them separately
  17251. this._days = +days +
  17252. weeks * 7;
  17253. // It is impossible translate months into days without knowing
  17254. // which months you are are talking about, so we have to store
  17255. // it separately.
  17256. this._months = +months +
  17257. years * 12;
  17258. this._data = {};
  17259. this._bubble();
  17260. }
  17261. /************************************
  17262. Helpers
  17263. ************************************/
  17264. function extend(a, b) {
  17265. for (var i in b) {
  17266. if (b.hasOwnProperty(i)) {
  17267. a[i] = b[i];
  17268. }
  17269. }
  17270. if (b.hasOwnProperty("toString")) {
  17271. a.toString = b.toString;
  17272. }
  17273. if (b.hasOwnProperty("valueOf")) {
  17274. a.valueOf = b.valueOf;
  17275. }
  17276. return a;
  17277. }
  17278. function cloneMoment(m) {
  17279. var result = {}, i;
  17280. for (i in m) {
  17281. if (m.hasOwnProperty(i) && momentProperties.hasOwnProperty(i)) {
  17282. result[i] = m[i];
  17283. }
  17284. }
  17285. return result;
  17286. }
  17287. function absRound(number) {
  17288. if (number < 0) {
  17289. return Math.ceil(number);
  17290. } else {
  17291. return Math.floor(number);
  17292. }
  17293. }
  17294. // left zero fill a number
  17295. // see http://jsperf.com/left-zero-filling for performance comparison
  17296. function leftZeroFill(number, targetLength, forceSign) {
  17297. var output = '' + Math.abs(number),
  17298. sign = number >= 0;
  17299. while (output.length < targetLength) {
  17300. output = '0' + output;
  17301. }
  17302. return (sign ? (forceSign ? '+' : '') : '-') + output;
  17303. }
  17304. // helper function for _.addTime and _.subtractTime
  17305. function addOrSubtractDurationFromMoment(mom, duration, isAdding, ignoreUpdateOffset) {
  17306. var milliseconds = duration._milliseconds,
  17307. days = duration._days,
  17308. months = duration._months,
  17309. minutes,
  17310. hours;
  17311. if (milliseconds) {
  17312. mom._d.setTime(+mom._d + milliseconds * isAdding);
  17313. }
  17314. // store the minutes and hours so we can restore them
  17315. if (days || months) {
  17316. minutes = mom.minute();
  17317. hours = mom.hour();
  17318. }
  17319. if (days) {
  17320. mom.date(mom.date() + days * isAdding);
  17321. }
  17322. if (months) {
  17323. mom.month(mom.month() + months * isAdding);
  17324. }
  17325. if (milliseconds && !ignoreUpdateOffset) {
  17326. moment.updateOffset(mom);
  17327. }
  17328. // restore the minutes and hours after possibly changing dst
  17329. if (days || months) {
  17330. mom.minute(minutes);
  17331. mom.hour(hours);
  17332. }
  17333. }
  17334. // check if is an array
  17335. function isArray(input) {
  17336. return Object.prototype.toString.call(input) === '[object Array]';
  17337. }
  17338. function isDate(input) {
  17339. return Object.prototype.toString.call(input) === '[object Date]' ||
  17340. input instanceof Date;
  17341. }
  17342. // compare two arrays, return the number of differences
  17343. function compareArrays(array1, array2, dontConvert) {
  17344. var len = Math.min(array1.length, array2.length),
  17345. lengthDiff = Math.abs(array1.length - array2.length),
  17346. diffs = 0,
  17347. i;
  17348. for (i = 0; i < len; i++) {
  17349. if ((dontConvert && array1[i] !== array2[i]) ||
  17350. (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
  17351. diffs++;
  17352. }
  17353. }
  17354. return diffs + lengthDiff;
  17355. }
  17356. function normalizeUnits(units) {
  17357. if (units) {
  17358. var lowered = units.toLowerCase().replace(/(.)s$/, '$1');
  17359. units = unitAliases[units] || camelFunctions[lowered] || lowered;
  17360. }
  17361. return units;
  17362. }
  17363. function normalizeObjectUnits(inputObject) {
  17364. var normalizedInput = {},
  17365. normalizedProp,
  17366. prop;
  17367. for (prop in inputObject) {
  17368. if (inputObject.hasOwnProperty(prop)) {
  17369. normalizedProp = normalizeUnits(prop);
  17370. if (normalizedProp) {
  17371. normalizedInput[normalizedProp] = inputObject[prop];
  17372. }
  17373. }
  17374. }
  17375. return normalizedInput;
  17376. }
  17377. function makeList(field) {
  17378. var count, setter;
  17379. if (field.indexOf('week') === 0) {
  17380. count = 7;
  17381. setter = 'day';
  17382. }
  17383. else if (field.indexOf('month') === 0) {
  17384. count = 12;
  17385. setter = 'month';
  17386. }
  17387. else {
  17388. return;
  17389. }
  17390. moment[field] = function (format, index) {
  17391. var i, getter,
  17392. method = moment.fn._lang[field],
  17393. results = [];
  17394. if (typeof format === 'number') {
  17395. index = format;
  17396. format = undefined;
  17397. }
  17398. getter = function (i) {
  17399. var m = moment().utc().set(setter, i);
  17400. return method.call(moment.fn._lang, m, format || '');
  17401. };
  17402. if (index != null) {
  17403. return getter(index);
  17404. }
  17405. else {
  17406. for (i = 0; i < count; i++) {
  17407. results.push(getter(i));
  17408. }
  17409. return results;
  17410. }
  17411. };
  17412. }
  17413. function toInt(argumentForCoercion) {
  17414. var coercedNumber = +argumentForCoercion,
  17415. value = 0;
  17416. if (coercedNumber !== 0 && isFinite(coercedNumber)) {
  17417. if (coercedNumber >= 0) {
  17418. value = Math.floor(coercedNumber);
  17419. } else {
  17420. value = Math.ceil(coercedNumber);
  17421. }
  17422. }
  17423. return value;
  17424. }
  17425. function daysInMonth(year, month) {
  17426. return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
  17427. }
  17428. function daysInYear(year) {
  17429. return isLeapYear(year) ? 366 : 365;
  17430. }
  17431. function isLeapYear(year) {
  17432. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  17433. }
  17434. function checkOverflow(m) {
  17435. var overflow;
  17436. if (m._a && m._pf.overflow === -2) {
  17437. overflow =
  17438. m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH :
  17439. m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE :
  17440. m._a[HOUR] < 0 || m._a[HOUR] > 23 ? HOUR :
  17441. m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE :
  17442. m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND :
  17443. m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND :
  17444. -1;
  17445. if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
  17446. overflow = DATE;
  17447. }
  17448. m._pf.overflow = overflow;
  17449. }
  17450. }
  17451. function isValid(m) {
  17452. if (m._isValid == null) {
  17453. m._isValid = !isNaN(m._d.getTime()) &&
  17454. m._pf.overflow < 0 &&
  17455. !m._pf.empty &&
  17456. !m._pf.invalidMonth &&
  17457. !m._pf.nullInput &&
  17458. !m._pf.invalidFormat &&
  17459. !m._pf.userInvalidated;
  17460. if (m._strict) {
  17461. m._isValid = m._isValid &&
  17462. m._pf.charsLeftOver === 0 &&
  17463. m._pf.unusedTokens.length === 0;
  17464. }
  17465. }
  17466. return m._isValid;
  17467. }
  17468. function normalizeLanguage(key) {
  17469. return key ? key.toLowerCase().replace('_', '-') : key;
  17470. }
  17471. // Return a moment from input, that is local/utc/zone equivalent to model.
  17472. function makeAs(input, model) {
  17473. return model._isUTC ? moment(input).zone(model._offset || 0) :
  17474. moment(input).local();
  17475. }
  17476. /************************************
  17477. Languages
  17478. ************************************/
  17479. extend(Language.prototype, {
  17480. set : function (config) {
  17481. var prop, i;
  17482. for (i in config) {
  17483. prop = config[i];
  17484. if (typeof prop === 'function') {
  17485. this[i] = prop;
  17486. } else {
  17487. this['_' + i] = prop;
  17488. }
  17489. }
  17490. },
  17491. _months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
  17492. months : function (m) {
  17493. return this._months[m.month()];
  17494. },
  17495. _monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),
  17496. monthsShort : function (m) {
  17497. return this._monthsShort[m.month()];
  17498. },
  17499. monthsParse : function (monthName) {
  17500. var i, mom, regex;
  17501. if (!this._monthsParse) {
  17502. this._monthsParse = [];
  17503. }
  17504. for (i = 0; i < 12; i++) {
  17505. // make the regex if we don't have it already
  17506. if (!this._monthsParse[i]) {
  17507. mom = moment.utc([2000, i]);
  17508. regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  17509. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  17510. }
  17511. // test the regex
  17512. if (this._monthsParse[i].test(monthName)) {
  17513. return i;
  17514. }
  17515. }
  17516. },
  17517. _weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
  17518. weekdays : function (m) {
  17519. return this._weekdays[m.day()];
  17520. },
  17521. _weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),
  17522. weekdaysShort : function (m) {
  17523. return this._weekdaysShort[m.day()];
  17524. },
  17525. _weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"),
  17526. weekdaysMin : function (m) {
  17527. return this._weekdaysMin[m.day()];
  17528. },
  17529. weekdaysParse : function (weekdayName) {
  17530. var i, mom, regex;
  17531. if (!this._weekdaysParse) {
  17532. this._weekdaysParse = [];
  17533. }
  17534. for (i = 0; i < 7; i++) {
  17535. // make the regex if we don't have it already
  17536. if (!this._weekdaysParse[i]) {
  17537. mom = moment([2000, 1]).day(i);
  17538. regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
  17539. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  17540. }
  17541. // test the regex
  17542. if (this._weekdaysParse[i].test(weekdayName)) {
  17543. return i;
  17544. }
  17545. }
  17546. },
  17547. _longDateFormat : {
  17548. LT : "h:mm A",
  17549. L : "MM/DD/YYYY",
  17550. LL : "MMMM D YYYY",
  17551. LLL : "MMMM D YYYY LT",
  17552. LLLL : "dddd, MMMM D YYYY LT"
  17553. },
  17554. longDateFormat : function (key) {
  17555. var output = this._longDateFormat[key];
  17556. if (!output && this._longDateFormat[key.toUpperCase()]) {
  17557. output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) {
  17558. return val.slice(1);
  17559. });
  17560. this._longDateFormat[key] = output;
  17561. }
  17562. return output;
  17563. },
  17564. isPM : function (input) {
  17565. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  17566. // Using charAt should be more compatible.
  17567. return ((input + '').toLowerCase().charAt(0) === 'p');
  17568. },
  17569. _meridiemParse : /[ap]\.?m?\.?/i,
  17570. meridiem : function (hours, minutes, isLower) {
  17571. if (hours > 11) {
  17572. return isLower ? 'pm' : 'PM';
  17573. } else {
  17574. return isLower ? 'am' : 'AM';
  17575. }
  17576. },
  17577. _calendar : {
  17578. sameDay : '[Today at] LT',
  17579. nextDay : '[Tomorrow at] LT',
  17580. nextWeek : 'dddd [at] LT',
  17581. lastDay : '[Yesterday at] LT',
  17582. lastWeek : '[Last] dddd [at] LT',
  17583. sameElse : 'L'
  17584. },
  17585. calendar : function (key, mom) {
  17586. var output = this._calendar[key];
  17587. return typeof output === 'function' ? output.apply(mom) : output;
  17588. },
  17589. _relativeTime : {
  17590. future : "in %s",
  17591. past : "%s ago",
  17592. s : "a few seconds",
  17593. m : "a minute",
  17594. mm : "%d minutes",
  17595. h : "an hour",
  17596. hh : "%d hours",
  17597. d : "a day",
  17598. dd : "%d days",
  17599. M : "a month",
  17600. MM : "%d months",
  17601. y : "a year",
  17602. yy : "%d years"
  17603. },
  17604. relativeTime : function (number, withoutSuffix, string, isFuture) {
  17605. var output = this._relativeTime[string];
  17606. return (typeof output === 'function') ?
  17607. output(number, withoutSuffix, string, isFuture) :
  17608. output.replace(/%d/i, number);
  17609. },
  17610. pastFuture : function (diff, output) {
  17611. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  17612. return typeof format === 'function' ? format(output) : format.replace(/%s/i, output);
  17613. },
  17614. ordinal : function (number) {
  17615. return this._ordinal.replace("%d", number);
  17616. },
  17617. _ordinal : "%d",
  17618. preparse : function (string) {
  17619. return string;
  17620. },
  17621. postformat : function (string) {
  17622. return string;
  17623. },
  17624. week : function (mom) {
  17625. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  17626. },
  17627. _week : {
  17628. dow : 0, // Sunday is the first day of the week.
  17629. doy : 6 // The week that contains Jan 1st is the first week of the year.
  17630. },
  17631. _invalidDate: 'Invalid date',
  17632. invalidDate: function () {
  17633. return this._invalidDate;
  17634. }
  17635. });
  17636. // Loads a language definition into the `languages` cache. The function
  17637. // takes a key and optionally values. If not in the browser and no values
  17638. // are provided, it will load the language file module. As a convenience,
  17639. // this function also returns the language values.
  17640. function loadLang(key, values) {
  17641. values.abbr = key;
  17642. if (!languages[key]) {
  17643. languages[key] = new Language();
  17644. }
  17645. languages[key].set(values);
  17646. return languages[key];
  17647. }
  17648. // Remove a language from the `languages` cache. Mostly useful in tests.
  17649. function unloadLang(key) {
  17650. delete languages[key];
  17651. }
  17652. // Determines which language definition to use and returns it.
  17653. //
  17654. // With no parameters, it will return the global language. If you
  17655. // pass in a language key, such as 'en', it will return the
  17656. // definition for 'en', so long as 'en' has already been loaded using
  17657. // moment.lang.
  17658. function getLangDefinition(key) {
  17659. var i = 0, j, lang, next, split,
  17660. get = function (k) {
  17661. if (!languages[k] && hasModule) {
  17662. try {
  17663. require('./lang/' + k);
  17664. } catch (e) { }
  17665. }
  17666. return languages[k];
  17667. };
  17668. if (!key) {
  17669. return moment.fn._lang;
  17670. }
  17671. if (!isArray(key)) {
  17672. //short-circuit everything else
  17673. lang = get(key);
  17674. if (lang) {
  17675. return lang;
  17676. }
  17677. key = [key];
  17678. }
  17679. //pick the language from the array
  17680. //try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
  17681. //substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
  17682. while (i < key.length) {
  17683. split = normalizeLanguage(key[i]).split('-');
  17684. j = split.length;
  17685. next = normalizeLanguage(key[i + 1]);
  17686. next = next ? next.split('-') : null;
  17687. while (j > 0) {
  17688. lang = get(split.slice(0, j).join('-'));
  17689. if (lang) {
  17690. return lang;
  17691. }
  17692. if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
  17693. //the next array item is better than a shallower substring of this one
  17694. break;
  17695. }
  17696. j--;
  17697. }
  17698. i++;
  17699. }
  17700. return moment.fn._lang;
  17701. }
  17702. /************************************
  17703. Formatting
  17704. ************************************/
  17705. function removeFormattingTokens(input) {
  17706. if (input.match(/\[[\s\S]/)) {
  17707. return input.replace(/^\[|\]$/g, "");
  17708. }
  17709. return input.replace(/\\/g, "");
  17710. }
  17711. function makeFormatFunction(format) {
  17712. var array = format.match(formattingTokens), i, length;
  17713. for (i = 0, length = array.length; i < length; i++) {
  17714. if (formatTokenFunctions[array[i]]) {
  17715. array[i] = formatTokenFunctions[array[i]];
  17716. } else {
  17717. array[i] = removeFormattingTokens(array[i]);
  17718. }
  17719. }
  17720. return function (mom) {
  17721. var output = "";
  17722. for (i = 0; i < length; i++) {
  17723. output += array[i] instanceof Function ? array[i].call(mom, format) : array[i];
  17724. }
  17725. return output;
  17726. };
  17727. }
  17728. // format date using native date object
  17729. function formatMoment(m, format) {
  17730. if (!m.isValid()) {
  17731. return m.lang().invalidDate();
  17732. }
  17733. format = expandFormat(format, m.lang());
  17734. if (!formatFunctions[format]) {
  17735. formatFunctions[format] = makeFormatFunction(format);
  17736. }
  17737. return formatFunctions[format](m);
  17738. }
  17739. function expandFormat(format, lang) {
  17740. var i = 5;
  17741. function replaceLongDateFormatTokens(input) {
  17742. return lang.longDateFormat(input) || input;
  17743. }
  17744. localFormattingTokens.lastIndex = 0;
  17745. while (i >= 0 && localFormattingTokens.test(format)) {
  17746. format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
  17747. localFormattingTokens.lastIndex = 0;
  17748. i -= 1;
  17749. }
  17750. return format;
  17751. }
  17752. /************************************
  17753. Parsing
  17754. ************************************/
  17755. // get the regex to find the next token
  17756. function getParseRegexForToken(token, config) {
  17757. var a, strict = config._strict;
  17758. switch (token) {
  17759. case 'DDDD':
  17760. return parseTokenThreeDigits;
  17761. case 'YYYY':
  17762. case 'GGGG':
  17763. case 'gggg':
  17764. return strict ? parseTokenFourDigits : parseTokenOneToFourDigits;
  17765. case 'Y':
  17766. case 'G':
  17767. case 'g':
  17768. return parseTokenSignedNumber;
  17769. case 'YYYYYY':
  17770. case 'YYYYY':
  17771. case 'GGGGG':
  17772. case 'ggggg':
  17773. return strict ? parseTokenSixDigits : parseTokenOneToSixDigits;
  17774. case 'S':
  17775. if (strict) { return parseTokenOneDigit; }
  17776. /* falls through */
  17777. case 'SS':
  17778. if (strict) { return parseTokenTwoDigits; }
  17779. /* falls through */
  17780. case 'SSS':
  17781. if (strict) { return parseTokenThreeDigits; }
  17782. /* falls through */
  17783. case 'DDD':
  17784. return parseTokenOneToThreeDigits;
  17785. case 'MMM':
  17786. case 'MMMM':
  17787. case 'dd':
  17788. case 'ddd':
  17789. case 'dddd':
  17790. return parseTokenWord;
  17791. case 'a':
  17792. case 'A':
  17793. return getLangDefinition(config._l)._meridiemParse;
  17794. case 'X':
  17795. return parseTokenTimestampMs;
  17796. case 'Z':
  17797. case 'ZZ':
  17798. return parseTokenTimezone;
  17799. case 'T':
  17800. return parseTokenT;
  17801. case 'SSSS':
  17802. return parseTokenDigits;
  17803. case 'MM':
  17804. case 'DD':
  17805. case 'YY':
  17806. case 'GG':
  17807. case 'gg':
  17808. case 'HH':
  17809. case 'hh':
  17810. case 'mm':
  17811. case 'ss':
  17812. case 'ww':
  17813. case 'WW':
  17814. return strict ? parseTokenTwoDigits : parseTokenOneOrTwoDigits;
  17815. case 'M':
  17816. case 'D':
  17817. case 'd':
  17818. case 'H':
  17819. case 'h':
  17820. case 'm':
  17821. case 's':
  17822. case 'w':
  17823. case 'W':
  17824. case 'e':
  17825. case 'E':
  17826. return parseTokenOneOrTwoDigits;
  17827. default :
  17828. a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), "i"));
  17829. return a;
  17830. }
  17831. }
  17832. function timezoneMinutesFromString(string) {
  17833. string = string || "";
  17834. var possibleTzMatches = (string.match(parseTokenTimezone) || []),
  17835. tzChunk = possibleTzMatches[possibleTzMatches.length - 1] || [],
  17836. parts = (tzChunk + '').match(parseTimezoneChunker) || ['-', 0, 0],
  17837. minutes = +(parts[1] * 60) + toInt(parts[2]);
  17838. return parts[0] === '+' ? -minutes : minutes;
  17839. }
  17840. // function to convert string input to date
  17841. function addTimeToArrayFromToken(token, input, config) {
  17842. var a, datePartArray = config._a;
  17843. switch (token) {
  17844. // MONTH
  17845. case 'M' : // fall through to MM
  17846. case 'MM' :
  17847. if (input != null) {
  17848. datePartArray[MONTH] = toInt(input) - 1;
  17849. }
  17850. break;
  17851. case 'MMM' : // fall through to MMMM
  17852. case 'MMMM' :
  17853. a = getLangDefinition(config._l).monthsParse(input);
  17854. // if we didn't find a month name, mark the date as invalid.
  17855. if (a != null) {
  17856. datePartArray[MONTH] = a;
  17857. } else {
  17858. config._pf.invalidMonth = input;
  17859. }
  17860. break;
  17861. // DAY OF MONTH
  17862. case 'D' : // fall through to DD
  17863. case 'DD' :
  17864. if (input != null) {
  17865. datePartArray[DATE] = toInt(input);
  17866. }
  17867. break;
  17868. // DAY OF YEAR
  17869. case 'DDD' : // fall through to DDDD
  17870. case 'DDDD' :
  17871. if (input != null) {
  17872. config._dayOfYear = toInt(input);
  17873. }
  17874. break;
  17875. // YEAR
  17876. case 'YY' :
  17877. datePartArray[YEAR] = toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
  17878. break;
  17879. case 'YYYY' :
  17880. case 'YYYYY' :
  17881. case 'YYYYYY' :
  17882. datePartArray[YEAR] = toInt(input);
  17883. break;
  17884. // AM / PM
  17885. case 'a' : // fall through to A
  17886. case 'A' :
  17887. config._isPm = getLangDefinition(config._l).isPM(input);
  17888. break;
  17889. // 24 HOUR
  17890. case 'H' : // fall through to hh
  17891. case 'HH' : // fall through to hh
  17892. case 'h' : // fall through to hh
  17893. case 'hh' :
  17894. datePartArray[HOUR] = toInt(input);
  17895. break;
  17896. // MINUTE
  17897. case 'm' : // fall through to mm
  17898. case 'mm' :
  17899. datePartArray[MINUTE] = toInt(input);
  17900. break;
  17901. // SECOND
  17902. case 's' : // fall through to ss
  17903. case 'ss' :
  17904. datePartArray[SECOND] = toInt(input);
  17905. break;
  17906. // MILLISECOND
  17907. case 'S' :
  17908. case 'SS' :
  17909. case 'SSS' :
  17910. case 'SSSS' :
  17911. datePartArray[MILLISECOND] = toInt(('0.' + input) * 1000);
  17912. break;
  17913. // UNIX TIMESTAMP WITH MS
  17914. case 'X':
  17915. config._d = new Date(parseFloat(input) * 1000);
  17916. break;
  17917. // TIMEZONE
  17918. case 'Z' : // fall through to ZZ
  17919. case 'ZZ' :
  17920. config._useUTC = true;
  17921. config._tzm = timezoneMinutesFromString(input);
  17922. break;
  17923. case 'w':
  17924. case 'ww':
  17925. case 'W':
  17926. case 'WW':
  17927. case 'd':
  17928. case 'dd':
  17929. case 'ddd':
  17930. case 'dddd':
  17931. case 'e':
  17932. case 'E':
  17933. token = token.substr(0, 1);
  17934. /* falls through */
  17935. case 'gg':
  17936. case 'gggg':
  17937. case 'GG':
  17938. case 'GGGG':
  17939. case 'GGGGG':
  17940. token = token.substr(0, 2);
  17941. if (input) {
  17942. config._w = config._w || {};
  17943. config._w[token] = input;
  17944. }
  17945. break;
  17946. }
  17947. }
  17948. // convert an array to a date.
  17949. // the array should mirror the parameters below
  17950. // note: all values past the year are optional and will default to the lowest possible value.
  17951. // [year, month, day , hour, minute, second, millisecond]
  17952. function dateFromConfig(config) {
  17953. var i, date, input = [], currentDate,
  17954. yearToUse, fixYear, w, temp, lang, weekday, week;
  17955. if (config._d) {
  17956. return;
  17957. }
  17958. currentDate = currentDateArray(config);
  17959. //compute day of the year from weeks and weekdays
  17960. if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
  17961. fixYear = function (val) {
  17962. var int_val = parseInt(val, 10);
  17963. return val ?
  17964. (val.length < 3 ? (int_val > 68 ? 1900 + int_val : 2000 + int_val) : int_val) :
  17965. (config._a[YEAR] == null ? moment().weekYear() : config._a[YEAR]);
  17966. };
  17967. w = config._w;
  17968. if (w.GG != null || w.W != null || w.E != null) {
  17969. temp = dayOfYearFromWeeks(fixYear(w.GG), w.W || 1, w.E, 4, 1);
  17970. }
  17971. else {
  17972. lang = getLangDefinition(config._l);
  17973. weekday = w.d != null ? parseWeekday(w.d, lang) :
  17974. (w.e != null ? parseInt(w.e, 10) + lang._week.dow : 0);
  17975. week = parseInt(w.w, 10) || 1;
  17976. //if we're parsing 'd', then the low day numbers may be next week
  17977. if (w.d != null && weekday < lang._week.dow) {
  17978. week++;
  17979. }
  17980. temp = dayOfYearFromWeeks(fixYear(w.gg), week, weekday, lang._week.doy, lang._week.dow);
  17981. }
  17982. config._a[YEAR] = temp.year;
  17983. config._dayOfYear = temp.dayOfYear;
  17984. }
  17985. //if the day of the year is set, figure out what it is
  17986. if (config._dayOfYear) {
  17987. yearToUse = config._a[YEAR] == null ? currentDate[YEAR] : config._a[YEAR];
  17988. if (config._dayOfYear > daysInYear(yearToUse)) {
  17989. config._pf._overflowDayOfYear = true;
  17990. }
  17991. date = makeUTCDate(yearToUse, 0, config._dayOfYear);
  17992. config._a[MONTH] = date.getUTCMonth();
  17993. config._a[DATE] = date.getUTCDate();
  17994. }
  17995. // Default to current date.
  17996. // * if no year, month, day of month are given, default to today
  17997. // * if day of month is given, default month and year
  17998. // * if month is given, default only year
  17999. // * if year is given, don't default anything
  18000. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  18001. config._a[i] = input[i] = currentDate[i];
  18002. }
  18003. // Zero out whatever was not defaulted, including time
  18004. for (; i < 7; i++) {
  18005. config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
  18006. }
  18007. // add the offsets to the time to be parsed so that we can have a clean array for checking isValid
  18008. input[HOUR] += toInt((config._tzm || 0) / 60);
  18009. input[MINUTE] += toInt((config._tzm || 0) % 60);
  18010. config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input);
  18011. }
  18012. function dateFromObject(config) {
  18013. var normalizedInput;
  18014. if (config._d) {
  18015. return;
  18016. }
  18017. normalizedInput = normalizeObjectUnits(config._i);
  18018. config._a = [
  18019. normalizedInput.year,
  18020. normalizedInput.month,
  18021. normalizedInput.day,
  18022. normalizedInput.hour,
  18023. normalizedInput.minute,
  18024. normalizedInput.second,
  18025. normalizedInput.millisecond
  18026. ];
  18027. dateFromConfig(config);
  18028. }
  18029. function currentDateArray(config) {
  18030. var now = new Date();
  18031. if (config._useUTC) {
  18032. return [
  18033. now.getUTCFullYear(),
  18034. now.getUTCMonth(),
  18035. now.getUTCDate()
  18036. ];
  18037. } else {
  18038. return [now.getFullYear(), now.getMonth(), now.getDate()];
  18039. }
  18040. }
  18041. // date from string and format string
  18042. function makeDateFromStringAndFormat(config) {
  18043. config._a = [];
  18044. config._pf.empty = true;
  18045. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  18046. var lang = getLangDefinition(config._l),
  18047. string = '' + config._i,
  18048. i, parsedInput, tokens, token, skipped,
  18049. stringLength = string.length,
  18050. totalParsedInputLength = 0;
  18051. tokens = expandFormat(config._f, lang).match(formattingTokens) || [];
  18052. for (i = 0; i < tokens.length; i++) {
  18053. token = tokens[i];
  18054. parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
  18055. if (parsedInput) {
  18056. skipped = string.substr(0, string.indexOf(parsedInput));
  18057. if (skipped.length > 0) {
  18058. config._pf.unusedInput.push(skipped);
  18059. }
  18060. string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
  18061. totalParsedInputLength += parsedInput.length;
  18062. }
  18063. // don't parse if it's not a known token
  18064. if (formatTokenFunctions[token]) {
  18065. if (parsedInput) {
  18066. config._pf.empty = false;
  18067. }
  18068. else {
  18069. config._pf.unusedTokens.push(token);
  18070. }
  18071. addTimeToArrayFromToken(token, parsedInput, config);
  18072. }
  18073. else if (config._strict && !parsedInput) {
  18074. config._pf.unusedTokens.push(token);
  18075. }
  18076. }
  18077. // add remaining unparsed input length to the string
  18078. config._pf.charsLeftOver = stringLength - totalParsedInputLength;
  18079. if (string.length > 0) {
  18080. config._pf.unusedInput.push(string);
  18081. }
  18082. // handle am pm
  18083. if (config._isPm && config._a[HOUR] < 12) {
  18084. config._a[HOUR] += 12;
  18085. }
  18086. // if is 12 am, change hours to 0
  18087. if (config._isPm === false && config._a[HOUR] === 12) {
  18088. config._a[HOUR] = 0;
  18089. }
  18090. dateFromConfig(config);
  18091. checkOverflow(config);
  18092. }
  18093. function unescapeFormat(s) {
  18094. return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
  18095. return p1 || p2 || p3 || p4;
  18096. });
  18097. }
  18098. // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  18099. function regexpEscape(s) {
  18100. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  18101. }
  18102. // date from string and array of format strings
  18103. function makeDateFromStringAndArray(config) {
  18104. var tempConfig,
  18105. bestMoment,
  18106. scoreToBeat,
  18107. i,
  18108. currentScore;
  18109. if (config._f.length === 0) {
  18110. config._pf.invalidFormat = true;
  18111. config._d = new Date(NaN);
  18112. return;
  18113. }
  18114. for (i = 0; i < config._f.length; i++) {
  18115. currentScore = 0;
  18116. tempConfig = extend({}, config);
  18117. tempConfig._pf = defaultParsingFlags();
  18118. tempConfig._f = config._f[i];
  18119. makeDateFromStringAndFormat(tempConfig);
  18120. if (!isValid(tempConfig)) {
  18121. continue;
  18122. }
  18123. // if there is any input that was not parsed add a penalty for that format
  18124. currentScore += tempConfig._pf.charsLeftOver;
  18125. //or tokens
  18126. currentScore += tempConfig._pf.unusedTokens.length * 10;
  18127. tempConfig._pf.score = currentScore;
  18128. if (scoreToBeat == null || currentScore < scoreToBeat) {
  18129. scoreToBeat = currentScore;
  18130. bestMoment = tempConfig;
  18131. }
  18132. }
  18133. extend(config, bestMoment || tempConfig);
  18134. }
  18135. // date from iso format
  18136. function makeDateFromString(config) {
  18137. var i, l,
  18138. string = config._i,
  18139. match = isoRegex.exec(string);
  18140. if (match) {
  18141. config._pf.iso = true;
  18142. for (i = 0, l = isoDates.length; i < l; i++) {
  18143. if (isoDates[i][1].exec(string)) {
  18144. // match[5] should be "T" or undefined
  18145. config._f = isoDates[i][0] + (match[6] || " ");
  18146. break;
  18147. }
  18148. }
  18149. for (i = 0, l = isoTimes.length; i < l; i++) {
  18150. if (isoTimes[i][1].exec(string)) {
  18151. config._f += isoTimes[i][0];
  18152. break;
  18153. }
  18154. }
  18155. if (string.match(parseTokenTimezone)) {
  18156. config._f += "Z";
  18157. }
  18158. makeDateFromStringAndFormat(config);
  18159. }
  18160. else {
  18161. config._d = new Date(string);
  18162. }
  18163. }
  18164. function makeDateFromInput(config) {
  18165. var input = config._i,
  18166. matched = aspNetJsonRegex.exec(input);
  18167. if (input === undefined) {
  18168. config._d = new Date();
  18169. } else if (matched) {
  18170. config._d = new Date(+matched[1]);
  18171. } else if (typeof input === 'string') {
  18172. makeDateFromString(config);
  18173. } else if (isArray(input)) {
  18174. config._a = input.slice(0);
  18175. dateFromConfig(config);
  18176. } else if (isDate(input)) {
  18177. config._d = new Date(+input);
  18178. } else if (typeof(input) === 'object') {
  18179. dateFromObject(config);
  18180. } else {
  18181. config._d = new Date(input);
  18182. }
  18183. }
  18184. function makeDate(y, m, d, h, M, s, ms) {
  18185. //can't just apply() to create a date:
  18186. //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply
  18187. var date = new Date(y, m, d, h, M, s, ms);
  18188. //the date constructor doesn't accept years < 1970
  18189. if (y < 1970) {
  18190. date.setFullYear(y);
  18191. }
  18192. return date;
  18193. }
  18194. function makeUTCDate(y) {
  18195. var date = new Date(Date.UTC.apply(null, arguments));
  18196. if (y < 1970) {
  18197. date.setUTCFullYear(y);
  18198. }
  18199. return date;
  18200. }
  18201. function parseWeekday(input, language) {
  18202. if (typeof input === 'string') {
  18203. if (!isNaN(input)) {
  18204. input = parseInt(input, 10);
  18205. }
  18206. else {
  18207. input = language.weekdaysParse(input);
  18208. if (typeof input !== 'number') {
  18209. return null;
  18210. }
  18211. }
  18212. }
  18213. return input;
  18214. }
  18215. /************************************
  18216. Relative Time
  18217. ************************************/
  18218. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  18219. function substituteTimeAgo(string, number, withoutSuffix, isFuture, lang) {
  18220. return lang.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  18221. }
  18222. function relativeTime(milliseconds, withoutSuffix, lang) {
  18223. var seconds = round(Math.abs(milliseconds) / 1000),
  18224. minutes = round(seconds / 60),
  18225. hours = round(minutes / 60),
  18226. days = round(hours / 24),
  18227. years = round(days / 365),
  18228. args = seconds < 45 && ['s', seconds] ||
  18229. minutes === 1 && ['m'] ||
  18230. minutes < 45 && ['mm', minutes] ||
  18231. hours === 1 && ['h'] ||
  18232. hours < 22 && ['hh', hours] ||
  18233. days === 1 && ['d'] ||
  18234. days <= 25 && ['dd', days] ||
  18235. days <= 45 && ['M'] ||
  18236. days < 345 && ['MM', round(days / 30)] ||
  18237. years === 1 && ['y'] || ['yy', years];
  18238. args[2] = withoutSuffix;
  18239. args[3] = milliseconds > 0;
  18240. args[4] = lang;
  18241. return substituteTimeAgo.apply({}, args);
  18242. }
  18243. /************************************
  18244. Week of Year
  18245. ************************************/
  18246. // firstDayOfWeek 0 = sun, 6 = sat
  18247. // the day of the week that starts the week
  18248. // (usually sunday or monday)
  18249. // firstDayOfWeekOfYear 0 = sun, 6 = sat
  18250. // the first week is the week that contains the first
  18251. // of this day of the week
  18252. // (eg. ISO weeks use thursday (4))
  18253. function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) {
  18254. var end = firstDayOfWeekOfYear - firstDayOfWeek,
  18255. daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(),
  18256. adjustedMoment;
  18257. if (daysToDayOfWeek > end) {
  18258. daysToDayOfWeek -= 7;
  18259. }
  18260. if (daysToDayOfWeek < end - 7) {
  18261. daysToDayOfWeek += 7;
  18262. }
  18263. adjustedMoment = moment(mom).add('d', daysToDayOfWeek);
  18264. return {
  18265. week: Math.ceil(adjustedMoment.dayOfYear() / 7),
  18266. year: adjustedMoment.year()
  18267. };
  18268. }
  18269. //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
  18270. function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) {
  18271. var d = makeUTCDate(year, 0, 1).getUTCDay(), daysToAdd, dayOfYear;
  18272. weekday = weekday != null ? weekday : firstDayOfWeek;
  18273. daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0);
  18274. dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1;
  18275. return {
  18276. year: dayOfYear > 0 ? year : year - 1,
  18277. dayOfYear: dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear
  18278. };
  18279. }
  18280. /************************************
  18281. Top Level Functions
  18282. ************************************/
  18283. function makeMoment(config) {
  18284. var input = config._i,
  18285. format = config._f;
  18286. if (input === null) {
  18287. return moment.invalid({nullInput: true});
  18288. }
  18289. if (typeof input === 'string') {
  18290. config._i = input = getLangDefinition().preparse(input);
  18291. }
  18292. if (moment.isMoment(input)) {
  18293. config = cloneMoment(input);
  18294. config._d = new Date(+input._d);
  18295. } else if (format) {
  18296. if (isArray(format)) {
  18297. makeDateFromStringAndArray(config);
  18298. } else {
  18299. makeDateFromStringAndFormat(config);
  18300. }
  18301. } else {
  18302. makeDateFromInput(config);
  18303. }
  18304. return new Moment(config);
  18305. }
  18306. moment = function (input, format, lang, strict) {
  18307. var c;
  18308. if (typeof(lang) === "boolean") {
  18309. strict = lang;
  18310. lang = undefined;
  18311. }
  18312. // object construction must be done this way.
  18313. // https://github.com/moment/moment/issues/1423
  18314. c = {};
  18315. c._isAMomentObject = true;
  18316. c._i = input;
  18317. c._f = format;
  18318. c._l = lang;
  18319. c._strict = strict;
  18320. c._isUTC = false;
  18321. c._pf = defaultParsingFlags();
  18322. return makeMoment(c);
  18323. };
  18324. // creating with utc
  18325. moment.utc = function (input, format, lang, strict) {
  18326. var c;
  18327. if (typeof(lang) === "boolean") {
  18328. strict = lang;
  18329. lang = undefined;
  18330. }
  18331. // object construction must be done this way.
  18332. // https://github.com/moment/moment/issues/1423
  18333. c = {};
  18334. c._isAMomentObject = true;
  18335. c._useUTC = true;
  18336. c._isUTC = true;
  18337. c._l = lang;
  18338. c._i = input;
  18339. c._f = format;
  18340. c._strict = strict;
  18341. c._pf = defaultParsingFlags();
  18342. return makeMoment(c).utc();
  18343. };
  18344. // creating with unix timestamp (in seconds)
  18345. moment.unix = function (input) {
  18346. return moment(input * 1000);
  18347. };
  18348. // duration
  18349. moment.duration = function (input, key) {
  18350. var duration = input,
  18351. // matching against regexp is expensive, do it on demand
  18352. match = null,
  18353. sign,
  18354. ret,
  18355. parseIso;
  18356. if (moment.isDuration(input)) {
  18357. duration = {
  18358. ms: input._milliseconds,
  18359. d: input._days,
  18360. M: input._months
  18361. };
  18362. } else if (typeof input === 'number') {
  18363. duration = {};
  18364. if (key) {
  18365. duration[key] = input;
  18366. } else {
  18367. duration.milliseconds = input;
  18368. }
  18369. } else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) {
  18370. sign = (match[1] === "-") ? -1 : 1;
  18371. duration = {
  18372. y: 0,
  18373. d: toInt(match[DATE]) * sign,
  18374. h: toInt(match[HOUR]) * sign,
  18375. m: toInt(match[MINUTE]) * sign,
  18376. s: toInt(match[SECOND]) * sign,
  18377. ms: toInt(match[MILLISECOND]) * sign
  18378. };
  18379. } else if (!!(match = isoDurationRegex.exec(input))) {
  18380. sign = (match[1] === "-") ? -1 : 1;
  18381. parseIso = function (inp) {
  18382. // We'd normally use ~~inp for this, but unfortunately it also
  18383. // converts floats to ints.
  18384. // inp may be undefined, so careful calling replace on it.
  18385. var res = inp && parseFloat(inp.replace(',', '.'));
  18386. // apply sign while we're at it
  18387. return (isNaN(res) ? 0 : res) * sign;
  18388. };
  18389. duration = {
  18390. y: parseIso(match[2]),
  18391. M: parseIso(match[3]),
  18392. d: parseIso(match[4]),
  18393. h: parseIso(match[5]),
  18394. m: parseIso(match[6]),
  18395. s: parseIso(match[7]),
  18396. w: parseIso(match[8])
  18397. };
  18398. }
  18399. ret = new Duration(duration);
  18400. if (moment.isDuration(input) && input.hasOwnProperty('_lang')) {
  18401. ret._lang = input._lang;
  18402. }
  18403. return ret;
  18404. };
  18405. // version number
  18406. moment.version = VERSION;
  18407. // default format
  18408. moment.defaultFormat = isoFormat;
  18409. // This function will be called whenever a moment is mutated.
  18410. // It is intended to keep the offset in sync with the timezone.
  18411. moment.updateOffset = function () {};
  18412. // This function will load languages and then set the global language. If
  18413. // no arguments are passed in, it will simply return the current global
  18414. // language key.
  18415. moment.lang = function (key, values) {
  18416. var r;
  18417. if (!key) {
  18418. return moment.fn._lang._abbr;
  18419. }
  18420. if (values) {
  18421. loadLang(normalizeLanguage(key), values);
  18422. } else if (values === null) {
  18423. unloadLang(key);
  18424. key = 'en';
  18425. } else if (!languages[key]) {
  18426. getLangDefinition(key);
  18427. }
  18428. r = moment.duration.fn._lang = moment.fn._lang = getLangDefinition(key);
  18429. return r._abbr;
  18430. };
  18431. // returns language data
  18432. moment.langData = function (key) {
  18433. if (key && key._lang && key._lang._abbr) {
  18434. key = key._lang._abbr;
  18435. }
  18436. return getLangDefinition(key);
  18437. };
  18438. // compare moment object
  18439. moment.isMoment = function (obj) {
  18440. return obj instanceof Moment ||
  18441. (obj != null && obj.hasOwnProperty('_isAMomentObject'));
  18442. };
  18443. // for typechecking Duration objects
  18444. moment.isDuration = function (obj) {
  18445. return obj instanceof Duration;
  18446. };
  18447. for (i = lists.length - 1; i >= 0; --i) {
  18448. makeList(lists[i]);
  18449. }
  18450. moment.normalizeUnits = function (units) {
  18451. return normalizeUnits(units);
  18452. };
  18453. moment.invalid = function (flags) {
  18454. var m = moment.utc(NaN);
  18455. if (flags != null) {
  18456. extend(m._pf, flags);
  18457. }
  18458. else {
  18459. m._pf.userInvalidated = true;
  18460. }
  18461. return m;
  18462. };
  18463. moment.parseZone = function (input) {
  18464. return moment(input).parseZone();
  18465. };
  18466. /************************************
  18467. Moment Prototype
  18468. ************************************/
  18469. extend(moment.fn = Moment.prototype, {
  18470. clone : function () {
  18471. return moment(this);
  18472. },
  18473. valueOf : function () {
  18474. return +this._d + ((this._offset || 0) * 60000);
  18475. },
  18476. unix : function () {
  18477. return Math.floor(+this / 1000);
  18478. },
  18479. toString : function () {
  18480. return this.clone().lang('en').format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ");
  18481. },
  18482. toDate : function () {
  18483. return this._offset ? new Date(+this) : this._d;
  18484. },
  18485. toISOString : function () {
  18486. var m = moment(this).utc();
  18487. if (0 < m.year() && m.year() <= 9999) {
  18488. return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  18489. } else {
  18490. return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  18491. }
  18492. },
  18493. toArray : function () {
  18494. var m = this;
  18495. return [
  18496. m.year(),
  18497. m.month(),
  18498. m.date(),
  18499. m.hours(),
  18500. m.minutes(),
  18501. m.seconds(),
  18502. m.milliseconds()
  18503. ];
  18504. },
  18505. isValid : function () {
  18506. return isValid(this);
  18507. },
  18508. isDSTShifted : function () {
  18509. if (this._a) {
  18510. return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0;
  18511. }
  18512. return false;
  18513. },
  18514. parsingFlags : function () {
  18515. return extend({}, this._pf);
  18516. },
  18517. invalidAt: function () {
  18518. return this._pf.overflow;
  18519. },
  18520. utc : function () {
  18521. return this.zone(0);
  18522. },
  18523. local : function () {
  18524. this.zone(0);
  18525. this._isUTC = false;
  18526. return this;
  18527. },
  18528. format : function (inputString) {
  18529. var output = formatMoment(this, inputString || moment.defaultFormat);
  18530. return this.lang().postformat(output);
  18531. },
  18532. add : function (input, val) {
  18533. var dur;
  18534. // switch args to support add('s', 1) and add(1, 's')
  18535. if (typeof input === 'string') {
  18536. dur = moment.duration(+val, input);
  18537. } else {
  18538. dur = moment.duration(input, val);
  18539. }
  18540. addOrSubtractDurationFromMoment(this, dur, 1);
  18541. return this;
  18542. },
  18543. subtract : function (input, val) {
  18544. var dur;
  18545. // switch args to support subtract('s', 1) and subtract(1, 's')
  18546. if (typeof input === 'string') {
  18547. dur = moment.duration(+val, input);
  18548. } else {
  18549. dur = moment.duration(input, val);
  18550. }
  18551. addOrSubtractDurationFromMoment(this, dur, -1);
  18552. return this;
  18553. },
  18554. diff : function (input, units, asFloat) {
  18555. var that = makeAs(input, this),
  18556. zoneDiff = (this.zone() - that.zone()) * 6e4,
  18557. diff, output;
  18558. units = normalizeUnits(units);
  18559. if (units === 'year' || units === 'month') {
  18560. // average number of days in the months in the given dates
  18561. diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2
  18562. // difference in months
  18563. output = ((this.year() - that.year()) * 12) + (this.month() - that.month());
  18564. // adjust by taking difference in days, average number of days
  18565. // and dst in the given months.
  18566. output += ((this - moment(this).startOf('month')) -
  18567. (that - moment(that).startOf('month'))) / diff;
  18568. // same as above but with zones, to negate all dst
  18569. output -= ((this.zone() - moment(this).startOf('month').zone()) -
  18570. (that.zone() - moment(that).startOf('month').zone())) * 6e4 / diff;
  18571. if (units === 'year') {
  18572. output = output / 12;
  18573. }
  18574. } else {
  18575. diff = (this - that);
  18576. output = units === 'second' ? diff / 1e3 : // 1000
  18577. units === 'minute' ? diff / 6e4 : // 1000 * 60
  18578. units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60
  18579. units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
  18580. units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
  18581. diff;
  18582. }
  18583. return asFloat ? output : absRound(output);
  18584. },
  18585. from : function (time, withoutSuffix) {
  18586. return moment.duration(this.diff(time)).lang(this.lang()._abbr).humanize(!withoutSuffix);
  18587. },
  18588. fromNow : function (withoutSuffix) {
  18589. return this.from(moment(), withoutSuffix);
  18590. },
  18591. calendar : function () {
  18592. // We want to compare the start of today, vs this.
  18593. // Getting start-of-today depends on whether we're zone'd or not.
  18594. var sod = makeAs(moment(), this).startOf('day'),
  18595. diff = this.diff(sod, 'days', true),
  18596. format = diff < -6 ? 'sameElse' :
  18597. diff < -1 ? 'lastWeek' :
  18598. diff < 0 ? 'lastDay' :
  18599. diff < 1 ? 'sameDay' :
  18600. diff < 2 ? 'nextDay' :
  18601. diff < 7 ? 'nextWeek' : 'sameElse';
  18602. return this.format(this.lang().calendar(format, this));
  18603. },
  18604. isLeapYear : function () {
  18605. return isLeapYear(this.year());
  18606. },
  18607. isDST : function () {
  18608. return (this.zone() < this.clone().month(0).zone() ||
  18609. this.zone() < this.clone().month(5).zone());
  18610. },
  18611. day : function (input) {
  18612. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  18613. if (input != null) {
  18614. input = parseWeekday(input, this.lang());
  18615. return this.add({ d : input - day });
  18616. } else {
  18617. return day;
  18618. }
  18619. },
  18620. month : function (input) {
  18621. var utc = this._isUTC ? 'UTC' : '',
  18622. dayOfMonth;
  18623. if (input != null) {
  18624. if (typeof input === 'string') {
  18625. input = this.lang().monthsParse(input);
  18626. if (typeof input !== 'number') {
  18627. return this;
  18628. }
  18629. }
  18630. dayOfMonth = this.date();
  18631. this.date(1);
  18632. this._d['set' + utc + 'Month'](input);
  18633. this.date(Math.min(dayOfMonth, this.daysInMonth()));
  18634. moment.updateOffset(this);
  18635. return this;
  18636. } else {
  18637. return this._d['get' + utc + 'Month']();
  18638. }
  18639. },
  18640. startOf: function (units) {
  18641. units = normalizeUnits(units);
  18642. // the following switch intentionally omits break keywords
  18643. // to utilize falling through the cases.
  18644. switch (units) {
  18645. case 'year':
  18646. this.month(0);
  18647. /* falls through */
  18648. case 'month':
  18649. this.date(1);
  18650. /* falls through */
  18651. case 'week':
  18652. case 'isoWeek':
  18653. case 'day':
  18654. this.hours(0);
  18655. /* falls through */
  18656. case 'hour':
  18657. this.minutes(0);
  18658. /* falls through */
  18659. case 'minute':
  18660. this.seconds(0);
  18661. /* falls through */
  18662. case 'second':
  18663. this.milliseconds(0);
  18664. /* falls through */
  18665. }
  18666. // weeks are a special case
  18667. if (units === 'week') {
  18668. this.weekday(0);
  18669. } else if (units === 'isoWeek') {
  18670. this.isoWeekday(1);
  18671. }
  18672. return this;
  18673. },
  18674. endOf: function (units) {
  18675. units = normalizeUnits(units);
  18676. return this.startOf(units).add((units === 'isoWeek' ? 'week' : units), 1).subtract('ms', 1);
  18677. },
  18678. isAfter: function (input, units) {
  18679. units = typeof units !== 'undefined' ? units : 'millisecond';
  18680. return +this.clone().startOf(units) > +moment(input).startOf(units);
  18681. },
  18682. isBefore: function (input, units) {
  18683. units = typeof units !== 'undefined' ? units : 'millisecond';
  18684. return +this.clone().startOf(units) < +moment(input).startOf(units);
  18685. },
  18686. isSame: function (input, units) {
  18687. units = units || 'ms';
  18688. return +this.clone().startOf(units) === +makeAs(input, this).startOf(units);
  18689. },
  18690. min: function (other) {
  18691. other = moment.apply(null, arguments);
  18692. return other < this ? this : other;
  18693. },
  18694. max: function (other) {
  18695. other = moment.apply(null, arguments);
  18696. return other > this ? this : other;
  18697. },
  18698. zone : function (input) {
  18699. var offset = this._offset || 0;
  18700. if (input != null) {
  18701. if (typeof input === "string") {
  18702. input = timezoneMinutesFromString(input);
  18703. }
  18704. if (Math.abs(input) < 16) {
  18705. input = input * 60;
  18706. }
  18707. this._offset = input;
  18708. this._isUTC = true;
  18709. if (offset !== input) {
  18710. addOrSubtractDurationFromMoment(this, moment.duration(offset - input, 'm'), 1, true);
  18711. }
  18712. } else {
  18713. return this._isUTC ? offset : this._d.getTimezoneOffset();
  18714. }
  18715. return this;
  18716. },
  18717. zoneAbbr : function () {
  18718. return this._isUTC ? "UTC" : "";
  18719. },
  18720. zoneName : function () {
  18721. return this._isUTC ? "Coordinated Universal Time" : "";
  18722. },
  18723. parseZone : function () {
  18724. if (this._tzm) {
  18725. this.zone(this._tzm);
  18726. } else if (typeof this._i === 'string') {
  18727. this.zone(this._i);
  18728. }
  18729. return this;
  18730. },
  18731. hasAlignedHourOffset : function (input) {
  18732. if (!input) {
  18733. input = 0;
  18734. }
  18735. else {
  18736. input = moment(input).zone();
  18737. }
  18738. return (this.zone() - input) % 60 === 0;
  18739. },
  18740. daysInMonth : function () {
  18741. return daysInMonth(this.year(), this.month());
  18742. },
  18743. dayOfYear : function (input) {
  18744. var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1;
  18745. return input == null ? dayOfYear : this.add("d", (input - dayOfYear));
  18746. },
  18747. quarter : function () {
  18748. return Math.ceil((this.month() + 1.0) / 3.0);
  18749. },
  18750. weekYear : function (input) {
  18751. var year = weekOfYear(this, this.lang()._week.dow, this.lang()._week.doy).year;
  18752. return input == null ? year : this.add("y", (input - year));
  18753. },
  18754. isoWeekYear : function (input) {
  18755. var year = weekOfYear(this, 1, 4).year;
  18756. return input == null ? year : this.add("y", (input - year));
  18757. },
  18758. week : function (input) {
  18759. var week = this.lang().week(this);
  18760. return input == null ? week : this.add("d", (input - week) * 7);
  18761. },
  18762. isoWeek : function (input) {
  18763. var week = weekOfYear(this, 1, 4).week;
  18764. return input == null ? week : this.add("d", (input - week) * 7);
  18765. },
  18766. weekday : function (input) {
  18767. var weekday = (this.day() + 7 - this.lang()._week.dow) % 7;
  18768. return input == null ? weekday : this.add("d", input - weekday);
  18769. },
  18770. isoWeekday : function (input) {
  18771. // behaves the same as moment#day except
  18772. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  18773. // as a setter, sunday should belong to the previous week.
  18774. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7);
  18775. },
  18776. get : function (units) {
  18777. units = normalizeUnits(units);
  18778. return this[units]();
  18779. },
  18780. set : function (units, value) {
  18781. units = normalizeUnits(units);
  18782. if (typeof this[units] === 'function') {
  18783. this[units](value);
  18784. }
  18785. return this;
  18786. },
  18787. // If passed a language key, it will set the language for this
  18788. // instance. Otherwise, it will return the language configuration
  18789. // variables for this instance.
  18790. lang : function (key) {
  18791. if (key === undefined) {
  18792. return this._lang;
  18793. } else {
  18794. this._lang = getLangDefinition(key);
  18795. return this;
  18796. }
  18797. }
  18798. });
  18799. // helper for adding shortcuts
  18800. function makeGetterAndSetter(name, key) {
  18801. moment.fn[name] = moment.fn[name + 's'] = function (input) {
  18802. var utc = this._isUTC ? 'UTC' : '';
  18803. if (input != null) {
  18804. this._d['set' + utc + key](input);
  18805. moment.updateOffset(this);
  18806. return this;
  18807. } else {
  18808. return this._d['get' + utc + key]();
  18809. }
  18810. };
  18811. }
  18812. // loop through and add shortcuts (Month, Date, Hours, Minutes, Seconds, Milliseconds)
  18813. for (i = 0; i < proxyGettersAndSetters.length; i ++) {
  18814. makeGetterAndSetter(proxyGettersAndSetters[i].toLowerCase().replace(/s$/, ''), proxyGettersAndSetters[i]);
  18815. }
  18816. // add shortcut for year (uses different syntax than the getter/setter 'year' == 'FullYear')
  18817. makeGetterAndSetter('year', 'FullYear');
  18818. // add plural methods
  18819. moment.fn.days = moment.fn.day;
  18820. moment.fn.months = moment.fn.month;
  18821. moment.fn.weeks = moment.fn.week;
  18822. moment.fn.isoWeeks = moment.fn.isoWeek;
  18823. // add aliased format methods
  18824. moment.fn.toJSON = moment.fn.toISOString;
  18825. /************************************
  18826. Duration Prototype
  18827. ************************************/
  18828. extend(moment.duration.fn = Duration.prototype, {
  18829. _bubble : function () {
  18830. var milliseconds = this._milliseconds,
  18831. days = this._days,
  18832. months = this._months,
  18833. data = this._data,
  18834. seconds, minutes, hours, years;
  18835. // The following code bubbles up values, see the tests for
  18836. // examples of what that means.
  18837. data.milliseconds = milliseconds % 1000;
  18838. seconds = absRound(milliseconds / 1000);
  18839. data.seconds = seconds % 60;
  18840. minutes = absRound(seconds / 60);
  18841. data.minutes = minutes % 60;
  18842. hours = absRound(minutes / 60);
  18843. data.hours = hours % 24;
  18844. days += absRound(hours / 24);
  18845. data.days = days % 30;
  18846. months += absRound(days / 30);
  18847. data.months = months % 12;
  18848. years = absRound(months / 12);
  18849. data.years = years;
  18850. },
  18851. weeks : function () {
  18852. return absRound(this.days() / 7);
  18853. },
  18854. valueOf : function () {
  18855. return this._milliseconds +
  18856. this._days * 864e5 +
  18857. (this._months % 12) * 2592e6 +
  18858. toInt(this._months / 12) * 31536e6;
  18859. },
  18860. humanize : function (withSuffix) {
  18861. var difference = +this,
  18862. output = relativeTime(difference, !withSuffix, this.lang());
  18863. if (withSuffix) {
  18864. output = this.lang().pastFuture(difference, output);
  18865. }
  18866. return this.lang().postformat(output);
  18867. },
  18868. add : function (input, val) {
  18869. // supports only 2.0-style add(1, 's') or add(moment)
  18870. var dur = moment.duration(input, val);
  18871. this._milliseconds += dur._milliseconds;
  18872. this._days += dur._days;
  18873. this._months += dur._months;
  18874. this._bubble();
  18875. return this;
  18876. },
  18877. subtract : function (input, val) {
  18878. var dur = moment.duration(input, val);
  18879. this._milliseconds -= dur._milliseconds;
  18880. this._days -= dur._days;
  18881. this._months -= dur._months;
  18882. this._bubble();
  18883. return this;
  18884. },
  18885. get : function (units) {
  18886. units = normalizeUnits(units);
  18887. return this[units.toLowerCase() + 's']();
  18888. },
  18889. as : function (units) {
  18890. units = normalizeUnits(units);
  18891. return this['as' + units.charAt(0).toUpperCase() + units.slice(1) + 's']();
  18892. },
  18893. lang : moment.fn.lang,
  18894. toIsoString : function () {
  18895. // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
  18896. var years = Math.abs(this.years()),
  18897. months = Math.abs(this.months()),
  18898. days = Math.abs(this.days()),
  18899. hours = Math.abs(this.hours()),
  18900. minutes = Math.abs(this.minutes()),
  18901. seconds = Math.abs(this.seconds() + this.milliseconds() / 1000);
  18902. if (!this.asSeconds()) {
  18903. // this is the same as C#'s (Noda) and python (isodate)...
  18904. // but not other JS (goog.date)
  18905. return 'P0D';
  18906. }
  18907. return (this.asSeconds() < 0 ? '-' : '') +
  18908. 'P' +
  18909. (years ? years + 'Y' : '') +
  18910. (months ? months + 'M' : '') +
  18911. (days ? days + 'D' : '') +
  18912. ((hours || minutes || seconds) ? 'T' : '') +
  18913. (hours ? hours + 'H' : '') +
  18914. (minutes ? minutes + 'M' : '') +
  18915. (seconds ? seconds + 'S' : '');
  18916. }
  18917. });
  18918. function makeDurationGetter(name) {
  18919. moment.duration.fn[name] = function () {
  18920. return this._data[name];
  18921. };
  18922. }
  18923. function makeDurationAsGetter(name, factor) {
  18924. moment.duration.fn['as' + name] = function () {
  18925. return +this / factor;
  18926. };
  18927. }
  18928. for (i in unitMillisecondFactors) {
  18929. if (unitMillisecondFactors.hasOwnProperty(i)) {
  18930. makeDurationAsGetter(i, unitMillisecondFactors[i]);
  18931. makeDurationGetter(i.toLowerCase());
  18932. }
  18933. }
  18934. makeDurationAsGetter('Weeks', 6048e5);
  18935. moment.duration.fn.asMonths = function () {
  18936. return (+this - this.years() * 31536e6) / 2592e6 + this.years() * 12;
  18937. };
  18938. /************************************
  18939. Default Lang
  18940. ************************************/
  18941. // Set default language, other languages will inherit from English.
  18942. moment.lang('en', {
  18943. ordinal : function (number) {
  18944. var b = number % 10,
  18945. output = (toInt(number % 100 / 10) === 1) ? 'th' :
  18946. (b === 1) ? 'st' :
  18947. (b === 2) ? 'nd' :
  18948. (b === 3) ? 'rd' : 'th';
  18949. return number + output;
  18950. }
  18951. });
  18952. /* EMBED_LANGUAGES */
  18953. /************************************
  18954. Exposing Moment
  18955. ************************************/
  18956. function makeGlobal(deprecate) {
  18957. var warned = false, local_moment = moment;
  18958. /*global ender:false */
  18959. if (typeof ender !== 'undefined') {
  18960. return;
  18961. }
  18962. // here, `this` means `window` in the browser, or `global` on the server
  18963. // add `moment` as a global object via a string identifier,
  18964. // for Closure Compiler "advanced" mode
  18965. if (deprecate) {
  18966. global.moment = function () {
  18967. if (!warned && console && console.warn) {
  18968. warned = true;
  18969. console.warn(
  18970. "Accessing Moment through the global scope is " +
  18971. "deprecated, and will be removed in an upcoming " +
  18972. "release.");
  18973. }
  18974. return local_moment.apply(null, arguments);
  18975. };
  18976. extend(global.moment, local_moment);
  18977. } else {
  18978. global['moment'] = moment;
  18979. }
  18980. }
  18981. // CommonJS module is defined
  18982. if (hasModule) {
  18983. module.exports = moment;
  18984. makeGlobal(true);
  18985. } else if (typeof define === "function" && define.amd) {
  18986. define("moment", function (require, exports, module) {
  18987. if (module.config && module.config() && module.config().noGlobal !== true) {
  18988. // If user provided noGlobal, he is aware of global
  18989. makeGlobal(module.config().noGlobal === undefined);
  18990. }
  18991. return moment;
  18992. });
  18993. } else {
  18994. makeGlobal();
  18995. }
  18996. }).call(this);
  18997. },{}],5:[function(require,module,exports){
  18998. /**
  18999. * Copyright 2012 Craig Campbell
  19000. *
  19001. * Licensed under the Apache License, Version 2.0 (the "License");
  19002. * you may not use this file except in compliance with the License.
  19003. * You may obtain a copy of the License at
  19004. *
  19005. * http://www.apache.org/licenses/LICENSE-2.0
  19006. *
  19007. * Unless required by applicable law or agreed to in writing, software
  19008. * distributed under the License is distributed on an "AS IS" BASIS,
  19009. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19010. * See the License for the specific language governing permissions and
  19011. * limitations under the License.
  19012. *
  19013. * Mousetrap is a simple keyboard shortcut library for Javascript with
  19014. * no external dependencies
  19015. *
  19016. * @version 1.1.2
  19017. * @url craig.is/killing/mice
  19018. */
  19019. /**
  19020. * mapping of special keycodes to their corresponding keys
  19021. *
  19022. * everything in this dictionary cannot use keypress events
  19023. * so it has to be here to map to the correct keycodes for
  19024. * keyup/keydown events
  19025. *
  19026. * @type {Object}
  19027. */
  19028. var _MAP = {
  19029. 8: 'backspace',
  19030. 9: 'tab',
  19031. 13: 'enter',
  19032. 16: 'shift',
  19033. 17: 'ctrl',
  19034. 18: 'alt',
  19035. 20: 'capslock',
  19036. 27: 'esc',
  19037. 32: 'space',
  19038. 33: 'pageup',
  19039. 34: 'pagedown',
  19040. 35: 'end',
  19041. 36: 'home',
  19042. 37: 'left',
  19043. 38: 'up',
  19044. 39: 'right',
  19045. 40: 'down',
  19046. 45: 'ins',
  19047. 46: 'del',
  19048. 91: 'meta',
  19049. 93: 'meta',
  19050. 224: 'meta'
  19051. },
  19052. /**
  19053. * mapping for special characters so they can support
  19054. *
  19055. * this dictionary is only used incase you want to bind a
  19056. * keyup or keydown event to one of these keys
  19057. *
  19058. * @type {Object}
  19059. */
  19060. _KEYCODE_MAP = {
  19061. 106: '*',
  19062. 107: '+',
  19063. 109: '-',
  19064. 110: '.',
  19065. 111 : '/',
  19066. 186: ';',
  19067. 187: '=',
  19068. 188: ',',
  19069. 189: '-',
  19070. 190: '.',
  19071. 191: '/',
  19072. 192: '`',
  19073. 219: '[',
  19074. 220: '\\',
  19075. 221: ']',
  19076. 222: '\''
  19077. },
  19078. /**
  19079. * this is a mapping of keys that require shift on a US keypad
  19080. * back to the non shift equivelents
  19081. *
  19082. * this is so you can use keyup events with these keys
  19083. *
  19084. * note that this will only work reliably on US keyboards
  19085. *
  19086. * @type {Object}
  19087. */
  19088. _SHIFT_MAP = {
  19089. '~': '`',
  19090. '!': '1',
  19091. '@': '2',
  19092. '#': '3',
  19093. '$': '4',
  19094. '%': '5',
  19095. '^': '6',
  19096. '&': '7',
  19097. '*': '8',
  19098. '(': '9',
  19099. ')': '0',
  19100. '_': '-',
  19101. '+': '=',
  19102. ':': ';',
  19103. '\"': '\'',
  19104. '<': ',',
  19105. '>': '.',
  19106. '?': '/',
  19107. '|': '\\'
  19108. },
  19109. /**
  19110. * this is a list of special strings you can use to map
  19111. * to modifier keys when you specify your keyboard shortcuts
  19112. *
  19113. * @type {Object}
  19114. */
  19115. _SPECIAL_ALIASES = {
  19116. 'option': 'alt',
  19117. 'command': 'meta',
  19118. 'return': 'enter',
  19119. 'escape': 'esc'
  19120. },
  19121. /**
  19122. * variable to store the flipped version of _MAP from above
  19123. * needed to check if we should use keypress or not when no action
  19124. * is specified
  19125. *
  19126. * @type {Object|undefined}
  19127. */
  19128. _REVERSE_MAP,
  19129. /**
  19130. * a list of all the callbacks setup via Mousetrap.bind()
  19131. *
  19132. * @type {Object}
  19133. */
  19134. _callbacks = {},
  19135. /**
  19136. * direct map of string combinations to callbacks used for trigger()
  19137. *
  19138. * @type {Object}
  19139. */
  19140. _direct_map = {},
  19141. /**
  19142. * keeps track of what level each sequence is at since multiple
  19143. * sequences can start out with the same sequence
  19144. *
  19145. * @type {Object}
  19146. */
  19147. _sequence_levels = {},
  19148. /**
  19149. * variable to store the setTimeout call
  19150. *
  19151. * @type {null|number}
  19152. */
  19153. _reset_timer,
  19154. /**
  19155. * temporary state where we will ignore the next keyup
  19156. *
  19157. * @type {boolean|string}
  19158. */
  19159. _ignore_next_keyup = false,
  19160. /**
  19161. * are we currently inside of a sequence?
  19162. * type of action ("keyup" or "keydown" or "keypress") or false
  19163. *
  19164. * @type {boolean|string}
  19165. */
  19166. _inside_sequence = false;
  19167. /**
  19168. * loop through the f keys, f1 to f19 and add them to the map
  19169. * programatically
  19170. */
  19171. for (var i = 1; i < 20; ++i) {
  19172. _MAP[111 + i] = 'f' + i;
  19173. }
  19174. /**
  19175. * loop through to map numbers on the numeric keypad
  19176. */
  19177. for (i = 0; i <= 9; ++i) {
  19178. _MAP[i + 96] = i;
  19179. }
  19180. /**
  19181. * cross browser add event method
  19182. *
  19183. * @param {Element|HTMLDocument} object
  19184. * @param {string} type
  19185. * @param {Function} callback
  19186. * @returns void
  19187. */
  19188. function _addEvent(object, type, callback) {
  19189. if (object.addEventListener) {
  19190. return object.addEventListener(type, callback, false);
  19191. }
  19192. object.attachEvent('on' + type, callback);
  19193. }
  19194. /**
  19195. * takes the event and returns the key character
  19196. *
  19197. * @param {Event} e
  19198. * @return {string}
  19199. */
  19200. function _characterFromEvent(e) {
  19201. // for keypress events we should return the character as is
  19202. if (e.type == 'keypress') {
  19203. return String.fromCharCode(e.which);
  19204. }
  19205. // for non keypress events the special maps are needed
  19206. if (_MAP[e.which]) {
  19207. return _MAP[e.which];
  19208. }
  19209. if (_KEYCODE_MAP[e.which]) {
  19210. return _KEYCODE_MAP[e.which];
  19211. }
  19212. // if it is not in the special map
  19213. return String.fromCharCode(e.which).toLowerCase();
  19214. }
  19215. /**
  19216. * should we stop this event before firing off callbacks
  19217. *
  19218. * @param {Event} e
  19219. * @return {boolean}
  19220. */
  19221. function _stop(e) {
  19222. var element = e.target || e.srcElement,
  19223. tag_name = element.tagName;
  19224. // if the element has the class "mousetrap" then no need to stop
  19225. if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {
  19226. return false;
  19227. }
  19228. // stop for input, select, and textarea
  19229. return tag_name == 'INPUT' || tag_name == 'SELECT' || tag_name == 'TEXTAREA' || (element.contentEditable && element.contentEditable == 'true');
  19230. }
  19231. /**
  19232. * checks if two arrays are equal
  19233. *
  19234. * @param {Array} modifiers1
  19235. * @param {Array} modifiers2
  19236. * @returns {boolean}
  19237. */
  19238. function _modifiersMatch(modifiers1, modifiers2) {
  19239. return modifiers1.sort().join(',') === modifiers2.sort().join(',');
  19240. }
  19241. /**
  19242. * resets all sequence counters except for the ones passed in
  19243. *
  19244. * @param {Object} do_not_reset
  19245. * @returns void
  19246. */
  19247. function _resetSequences(do_not_reset) {
  19248. do_not_reset = do_not_reset || {};
  19249. var active_sequences = false,
  19250. key;
  19251. for (key in _sequence_levels) {
  19252. if (do_not_reset[key]) {
  19253. active_sequences = true;
  19254. continue;
  19255. }
  19256. _sequence_levels[key] = 0;
  19257. }
  19258. if (!active_sequences) {
  19259. _inside_sequence = false;
  19260. }
  19261. }
  19262. /**
  19263. * finds all callbacks that match based on the keycode, modifiers,
  19264. * and action
  19265. *
  19266. * @param {string} character
  19267. * @param {Array} modifiers
  19268. * @param {string} action
  19269. * @param {boolean=} remove - should we remove any matches
  19270. * @param {string=} combination
  19271. * @returns {Array}
  19272. */
  19273. function _getMatches(character, modifiers, action, remove, combination) {
  19274. var i,
  19275. callback,
  19276. matches = [];
  19277. // if there are no events related to this keycode
  19278. if (!_callbacks[character]) {
  19279. return [];
  19280. }
  19281. // if a modifier key is coming up on its own we should allow it
  19282. if (action == 'keyup' && _isModifier(character)) {
  19283. modifiers = [character];
  19284. }
  19285. // loop through all callbacks for the key that was pressed
  19286. // and see if any of them match
  19287. for (i = 0; i < _callbacks[character].length; ++i) {
  19288. callback = _callbacks[character][i];
  19289. // if this is a sequence but it is not at the right level
  19290. // then move onto the next match
  19291. if (callback.seq && _sequence_levels[callback.seq] != callback.level) {
  19292. continue;
  19293. }
  19294. // if the action we are looking for doesn't match the action we got
  19295. // then we should keep going
  19296. if (action != callback.action) {
  19297. continue;
  19298. }
  19299. // if this is a keypress event that means that we need to only
  19300. // look at the character, otherwise check the modifiers as
  19301. // well
  19302. if (action == 'keypress' || _modifiersMatch(modifiers, callback.modifiers)) {
  19303. // remove is used so if you change your mind and call bind a
  19304. // second time with a new function the first one is overwritten
  19305. if (remove && callback.combo == combination) {
  19306. _callbacks[character].splice(i, 1);
  19307. }
  19308. matches.push(callback);
  19309. }
  19310. }
  19311. return matches;
  19312. }
  19313. /**
  19314. * takes a key event and figures out what the modifiers are
  19315. *
  19316. * @param {Event} e
  19317. * @returns {Array}
  19318. */
  19319. function _eventModifiers(e) {
  19320. var modifiers = [];
  19321. if (e.shiftKey) {
  19322. modifiers.push('shift');
  19323. }
  19324. if (e.altKey) {
  19325. modifiers.push('alt');
  19326. }
  19327. if (e.ctrlKey) {
  19328. modifiers.push('ctrl');
  19329. }
  19330. if (e.metaKey) {
  19331. modifiers.push('meta');
  19332. }
  19333. return modifiers;
  19334. }
  19335. /**
  19336. * actually calls the callback function
  19337. *
  19338. * if your callback function returns false this will use the jquery
  19339. * convention - prevent default and stop propogation on the event
  19340. *
  19341. * @param {Function} callback
  19342. * @param {Event} e
  19343. * @returns void
  19344. */
  19345. function _fireCallback(callback, e) {
  19346. if (callback(e) === false) {
  19347. if (e.preventDefault) {
  19348. e.preventDefault();
  19349. }
  19350. if (e.stopPropagation) {
  19351. e.stopPropagation();
  19352. }
  19353. e.returnValue = false;
  19354. e.cancelBubble = true;
  19355. }
  19356. }
  19357. /**
  19358. * handles a character key event
  19359. *
  19360. * @param {string} character
  19361. * @param {Event} e
  19362. * @returns void
  19363. */
  19364. function _handleCharacter(character, e) {
  19365. // if this event should not happen stop here
  19366. if (_stop(e)) {
  19367. return;
  19368. }
  19369. var callbacks = _getMatches(character, _eventModifiers(e), e.type),
  19370. i,
  19371. do_not_reset = {},
  19372. processed_sequence_callback = false;
  19373. // loop through matching callbacks for this key event
  19374. for (i = 0; i < callbacks.length; ++i) {
  19375. // fire for all sequence callbacks
  19376. // this is because if for example you have multiple sequences
  19377. // bound such as "g i" and "g t" they both need to fire the
  19378. // callback for matching g cause otherwise you can only ever
  19379. // match the first one
  19380. if (callbacks[i].seq) {
  19381. processed_sequence_callback = true;
  19382. // keep a list of which sequences were matches for later
  19383. do_not_reset[callbacks[i].seq] = 1;
  19384. _fireCallback(callbacks[i].callback, e);
  19385. continue;
  19386. }
  19387. // if there were no sequence matches but we are still here
  19388. // that means this is a regular match so we should fire that
  19389. if (!processed_sequence_callback && !_inside_sequence) {
  19390. _fireCallback(callbacks[i].callback, e);
  19391. }
  19392. }
  19393. // if you are inside of a sequence and the key you are pressing
  19394. // is not a modifier key then we should reset all sequences
  19395. // that were not matched by this key event
  19396. if (e.type == _inside_sequence && !_isModifier(character)) {
  19397. _resetSequences(do_not_reset);
  19398. }
  19399. }
  19400. /**
  19401. * handles a keydown event
  19402. *
  19403. * @param {Event} e
  19404. * @returns void
  19405. */
  19406. function _handleKey(e) {
  19407. // normalize e.which for key events
  19408. // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion
  19409. e.which = typeof e.which == "number" ? e.which : e.keyCode;
  19410. var character = _characterFromEvent(e);
  19411. // no character found then stop
  19412. if (!character) {
  19413. return;
  19414. }
  19415. if (e.type == 'keyup' && _ignore_next_keyup == character) {
  19416. _ignore_next_keyup = false;
  19417. return;
  19418. }
  19419. _handleCharacter(character, e);
  19420. }
  19421. /**
  19422. * determines if the keycode specified is a modifier key or not
  19423. *
  19424. * @param {string} key
  19425. * @returns {boolean}
  19426. */
  19427. function _isModifier(key) {
  19428. return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta';
  19429. }
  19430. /**
  19431. * called to set a 1 second timeout on the specified sequence
  19432. *
  19433. * this is so after each key press in the sequence you have 1 second
  19434. * to press the next key before you have to start over
  19435. *
  19436. * @returns void
  19437. */
  19438. function _resetSequenceTimer() {
  19439. clearTimeout(_reset_timer);
  19440. _reset_timer = setTimeout(_resetSequences, 1000);
  19441. }
  19442. /**
  19443. * reverses the map lookup so that we can look for specific keys
  19444. * to see what can and can't use keypress
  19445. *
  19446. * @return {Object}
  19447. */
  19448. function _getReverseMap() {
  19449. if (!_REVERSE_MAP) {
  19450. _REVERSE_MAP = {};
  19451. for (var key in _MAP) {
  19452. // pull out the numeric keypad from here cause keypress should
  19453. // be able to detect the keys from the character
  19454. if (key > 95 && key < 112) {
  19455. continue;
  19456. }
  19457. if (_MAP.hasOwnProperty(key)) {
  19458. _REVERSE_MAP[_MAP[key]] = key;
  19459. }
  19460. }
  19461. }
  19462. return _REVERSE_MAP;
  19463. }
  19464. /**
  19465. * picks the best action based on the key combination
  19466. *
  19467. * @param {string} key - character for key
  19468. * @param {Array} modifiers
  19469. * @param {string=} action passed in
  19470. */
  19471. function _pickBestAction(key, modifiers, action) {
  19472. // if no action was picked in we should try to pick the one
  19473. // that we think would work best for this key
  19474. if (!action) {
  19475. action = _getReverseMap()[key] ? 'keydown' : 'keypress';
  19476. }
  19477. // modifier keys don't work as expected with keypress,
  19478. // switch to keydown
  19479. if (action == 'keypress' && modifiers.length) {
  19480. action = 'keydown';
  19481. }
  19482. return action;
  19483. }
  19484. /**
  19485. * binds a key sequence to an event
  19486. *
  19487. * @param {string} combo - combo specified in bind call
  19488. * @param {Array} keys
  19489. * @param {Function} callback
  19490. * @param {string=} action
  19491. * @returns void
  19492. */
  19493. function _bindSequence(combo, keys, callback, action) {
  19494. // start off by adding a sequence level record for this combination
  19495. // and setting the level to 0
  19496. _sequence_levels[combo] = 0;
  19497. // if there is no action pick the best one for the first key
  19498. // in the sequence
  19499. if (!action) {
  19500. action = _pickBestAction(keys[0], []);
  19501. }
  19502. /**
  19503. * callback to increase the sequence level for this sequence and reset
  19504. * all other sequences that were active
  19505. *
  19506. * @param {Event} e
  19507. * @returns void
  19508. */
  19509. var _increaseSequence = function(e) {
  19510. _inside_sequence = action;
  19511. ++_sequence_levels[combo];
  19512. _resetSequenceTimer();
  19513. },
  19514. /**
  19515. * wraps the specified callback inside of another function in order
  19516. * to reset all sequence counters as soon as this sequence is done
  19517. *
  19518. * @param {Event} e
  19519. * @returns void
  19520. */
  19521. _callbackAndReset = function(e) {
  19522. _fireCallback(callback, e);
  19523. // we should ignore the next key up if the action is key down
  19524. // or keypress. this is so if you finish a sequence and
  19525. // release the key the final key will not trigger a keyup
  19526. if (action !== 'keyup') {
  19527. _ignore_next_keyup = _characterFromEvent(e);
  19528. }
  19529. // weird race condition if a sequence ends with the key
  19530. // another sequence begins with
  19531. setTimeout(_resetSequences, 10);
  19532. },
  19533. i;
  19534. // loop through keys one at a time and bind the appropriate callback
  19535. // function. for any key leading up to the final one it should
  19536. // increase the sequence. after the final, it should reset all sequences
  19537. for (i = 0; i < keys.length; ++i) {
  19538. _bindSingle(keys[i], i < keys.length - 1 ? _increaseSequence : _callbackAndReset, action, combo, i);
  19539. }
  19540. }
  19541. /**
  19542. * binds a single keyboard combination
  19543. *
  19544. * @param {string} combination
  19545. * @param {Function} callback
  19546. * @param {string=} action
  19547. * @param {string=} sequence_name - name of sequence if part of sequence
  19548. * @param {number=} level - what part of the sequence the command is
  19549. * @returns void
  19550. */
  19551. function _bindSingle(combination, callback, action, sequence_name, level) {
  19552. // make sure multiple spaces in a row become a single space
  19553. combination = combination.replace(/\s+/g, ' ');
  19554. var sequence = combination.split(' '),
  19555. i,
  19556. key,
  19557. keys,
  19558. modifiers = [];
  19559. // if this pattern is a sequence of keys then run through this method
  19560. // to reprocess each pattern one key at a time
  19561. if (sequence.length > 1) {
  19562. return _bindSequence(combination, sequence, callback, action);
  19563. }
  19564. // take the keys from this pattern and figure out what the actual
  19565. // pattern is all about
  19566. keys = combination === '+' ? ['+'] : combination.split('+');
  19567. for (i = 0; i < keys.length; ++i) {
  19568. key = keys[i];
  19569. // normalize key names
  19570. if (_SPECIAL_ALIASES[key]) {
  19571. key = _SPECIAL_ALIASES[key];
  19572. }
  19573. // if this is not a keypress event then we should
  19574. // be smart about using shift keys
  19575. // this will only work for US keyboards however
  19576. if (action && action != 'keypress' && _SHIFT_MAP[key]) {
  19577. key = _SHIFT_MAP[key];
  19578. modifiers.push('shift');
  19579. }
  19580. // if this key is a modifier then add it to the list of modifiers
  19581. if (_isModifier(key)) {
  19582. modifiers.push(key);
  19583. }
  19584. }
  19585. // depending on what the key combination is
  19586. // we will try to pick the best event for it
  19587. action = _pickBestAction(key, modifiers, action);
  19588. // make sure to initialize array if this is the first time
  19589. // a callback is added for this key
  19590. if (!_callbacks[key]) {
  19591. _callbacks[key] = [];
  19592. }
  19593. // remove an existing match if there is one
  19594. _getMatches(key, modifiers, action, !sequence_name, combination);
  19595. // add this call back to the array
  19596. // if it is a sequence put it at the beginning
  19597. // if not put it at the end
  19598. //
  19599. // this is important because the way these are processed expects
  19600. // the sequence ones to come first
  19601. _callbacks[key][sequence_name ? 'unshift' : 'push']({
  19602. callback: callback,
  19603. modifiers: modifiers,
  19604. action: action,
  19605. seq: sequence_name,
  19606. level: level,
  19607. combo: combination
  19608. });
  19609. }
  19610. /**
  19611. * binds multiple combinations to the same callback
  19612. *
  19613. * @param {Array} combinations
  19614. * @param {Function} callback
  19615. * @param {string|undefined} action
  19616. * @returns void
  19617. */
  19618. function _bindMultiple(combinations, callback, action) {
  19619. for (var i = 0; i < combinations.length; ++i) {
  19620. _bindSingle(combinations[i], callback, action);
  19621. }
  19622. }
  19623. // start!
  19624. _addEvent(document, 'keypress', _handleKey);
  19625. _addEvent(document, 'keydown', _handleKey);
  19626. _addEvent(document, 'keyup', _handleKey);
  19627. var mousetrap = {
  19628. /**
  19629. * binds an event to mousetrap
  19630. *
  19631. * can be a single key, a combination of keys separated with +,
  19632. * a comma separated list of keys, an array of keys, or
  19633. * a sequence of keys separated by spaces
  19634. *
  19635. * be sure to list the modifier keys first to make sure that the
  19636. * correct key ends up getting bound (the last key in the pattern)
  19637. *
  19638. * @param {string|Array} keys
  19639. * @param {Function} callback
  19640. * @param {string=} action - 'keypress', 'keydown', or 'keyup'
  19641. * @returns void
  19642. */
  19643. bind: function(keys, callback, action) {
  19644. _bindMultiple(keys instanceof Array ? keys : [keys], callback, action);
  19645. _direct_map[keys + ':' + action] = callback;
  19646. return this;
  19647. },
  19648. /**
  19649. * unbinds an event to mousetrap
  19650. *
  19651. * the unbinding sets the callback function of the specified key combo
  19652. * to an empty function and deletes the corresponding key in the
  19653. * _direct_map dict.
  19654. *
  19655. * the keycombo+action has to be exactly the same as
  19656. * it was defined in the bind method
  19657. *
  19658. * TODO: actually remove this from the _callbacks dictionary instead
  19659. * of binding an empty function
  19660. *
  19661. * @param {string|Array} keys
  19662. * @param {string} action
  19663. * @returns void
  19664. */
  19665. unbind: function(keys, action) {
  19666. if (_direct_map[keys + ':' + action]) {
  19667. delete _direct_map[keys + ':' + action];
  19668. this.bind(keys, function() {}, action);
  19669. }
  19670. return this;
  19671. },
  19672. /**
  19673. * triggers an event that has already been bound
  19674. *
  19675. * @param {string} keys
  19676. * @param {string=} action
  19677. * @returns void
  19678. */
  19679. trigger: function(keys, action) {
  19680. _direct_map[keys + ':' + action]();
  19681. return this;
  19682. },
  19683. /**
  19684. * resets the library back to its initial state. this is useful
  19685. * if you want to clear out the current keyboard shortcuts and bind
  19686. * new ones - for example if you switch to another page
  19687. *
  19688. * @returns void
  19689. */
  19690. reset: function() {
  19691. _callbacks = {};
  19692. _direct_map = {};
  19693. return this;
  19694. }
  19695. };
  19696. module.exports = mousetrap;
  19697. },{}]},{},[1])
  19698. (1)
  19699. });