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.

14666 lines
441 KiB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
  1. /**
  2. * vis.js
  3. * https://github.com/almende/vis
  4. *
  5. * A dynamic, browser-based visualization library.
  6. *
  7. * @version 0.2.0
  8. * @date 2013-09-20
  9. *
  10. * @license
  11. * Copyright (C) 2011-2013 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("function"==typeof bootstrap)bootstrap("vis",e);else if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else if("undefined"!=typeof ses){if(!ses.ok())return;ses.makeVis=e}else"undefined"!=typeof window?window.vis=e():global.vis=e()})(function(){var define,ses,bootstrap,module,exports;
  26. 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){
  27. /*! Hammer.JS - v1.0.5 - 2013-04-07
  28. * http://eightmedia.github.com/hammer.js
  29. *
  30. * Copyright (c) 2013 Jorik Tangelder <j.tangelder@gmail.com>;
  31. * Licensed under the MIT license */
  32. (function(window, undefined) {
  33. 'use strict';
  34. /**
  35. * Hammer
  36. * use this to create instances
  37. * @param {HTMLElement} element
  38. * @param {Object} options
  39. * @returns {Hammer.Instance}
  40. * @constructor
  41. */
  42. var Hammer = function(element, options) {
  43. return new Hammer.Instance(element, options || {});
  44. };
  45. // default settings
  46. Hammer.defaults = {
  47. // add styles and attributes to the element to prevent the browser from doing
  48. // its native behavior. this doesnt prevent the scrolling, but cancels
  49. // the contextmenu, tap highlighting etc
  50. // set to false to disable this
  51. stop_browser_behavior: {
  52. // this also triggers onselectstart=false for IE
  53. userSelect: 'none',
  54. // this makes the element blocking in IE10 >, you could experiment with the value
  55. // see for more options this issue; https://github.com/EightMedia/hammer.js/issues/241
  56. touchAction: 'none',
  57. touchCallout: 'none',
  58. contentZooming: 'none',
  59. userDrag: 'none',
  60. tapHighlightColor: 'rgba(0,0,0,0)'
  61. }
  62. // more settings are defined per gesture at gestures.js
  63. };
  64. // detect touchevents
  65. Hammer.HAS_POINTEREVENTS = navigator.pointerEnabled || navigator.msPointerEnabled;
  66. Hammer.HAS_TOUCHEVENTS = ('ontouchstart' in window);
  67. // dont use mouseevents on mobile devices
  68. Hammer.MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;
  69. Hammer.NO_MOUSEEVENTS = Hammer.HAS_TOUCHEVENTS && navigator.userAgent.match(Hammer.MOBILE_REGEX);
  70. // eventtypes per touchevent (start, move, end)
  71. // are filled by Hammer.event.determineEventTypes on setup
  72. Hammer.EVENT_TYPES = {};
  73. // direction defines
  74. Hammer.DIRECTION_DOWN = 'down';
  75. Hammer.DIRECTION_LEFT = 'left';
  76. Hammer.DIRECTION_UP = 'up';
  77. Hammer.DIRECTION_RIGHT = 'right';
  78. // pointer type
  79. Hammer.POINTER_MOUSE = 'mouse';
  80. Hammer.POINTER_TOUCH = 'touch';
  81. Hammer.POINTER_PEN = 'pen';
  82. // touch event defines
  83. Hammer.EVENT_START = 'start';
  84. Hammer.EVENT_MOVE = 'move';
  85. Hammer.EVENT_END = 'end';
  86. // hammer document where the base events are added at
  87. Hammer.DOCUMENT = document;
  88. // plugins namespace
  89. Hammer.plugins = {};
  90. // if the window events are set...
  91. Hammer.READY = false;
  92. /**
  93. * setup events to detect gestures on the document
  94. */
  95. function setup() {
  96. if(Hammer.READY) {
  97. return;
  98. }
  99. // find what eventtypes we add listeners to
  100. Hammer.event.determineEventTypes();
  101. // Register all gestures inside Hammer.gestures
  102. for(var name in Hammer.gestures) {
  103. if(Hammer.gestures.hasOwnProperty(name)) {
  104. Hammer.detection.register(Hammer.gestures[name]);
  105. }
  106. }
  107. // Add touch events on the document
  108. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_MOVE, Hammer.detection.detect);
  109. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_END, Hammer.detection.detect);
  110. // Hammer is ready...!
  111. Hammer.READY = true;
  112. }
  113. /**
  114. * create new hammer instance
  115. * all methods should return the instance itself, so it is chainable.
  116. * @param {HTMLElement} element
  117. * @param {Object} [options={}]
  118. * @returns {Hammer.Instance}
  119. * @constructor
  120. */
  121. Hammer.Instance = function(element, options) {
  122. var self = this;
  123. // setup HammerJS window events and register all gestures
  124. // this also sets up the default options
  125. setup();
  126. this.element = element;
  127. // start/stop detection option
  128. this.enabled = true;
  129. // merge options
  130. this.options = Hammer.utils.extend(
  131. Hammer.utils.extend({}, Hammer.defaults),
  132. options || {});
  133. // add some css to the element to prevent the browser from doing its native behavoir
  134. if(this.options.stop_browser_behavior) {
  135. Hammer.utils.stopDefaultBrowserBehavior(this.element, this.options.stop_browser_behavior);
  136. }
  137. // start detection on touchstart
  138. Hammer.event.onTouch(element, Hammer.EVENT_START, function(ev) {
  139. if(self.enabled) {
  140. Hammer.detection.startDetect(self, ev);
  141. }
  142. });
  143. // return instance
  144. return this;
  145. };
  146. Hammer.Instance.prototype = {
  147. /**
  148. * bind events to the instance
  149. * @param {String} gesture
  150. * @param {Function} handler
  151. * @returns {Hammer.Instance}
  152. */
  153. on: function onEvent(gesture, handler){
  154. var gestures = gesture.split(' ');
  155. for(var t=0; t<gestures.length; t++) {
  156. this.element.addEventListener(gestures[t], handler, false);
  157. }
  158. return this;
  159. },
  160. /**
  161. * unbind events to the instance
  162. * @param {String} gesture
  163. * @param {Function} handler
  164. * @returns {Hammer.Instance}
  165. */
  166. off: function offEvent(gesture, handler){
  167. var gestures = gesture.split(' ');
  168. for(var t=0; t<gestures.length; t++) {
  169. this.element.removeEventListener(gestures[t], handler, false);
  170. }
  171. return this;
  172. },
  173. /**
  174. * trigger gesture event
  175. * @param {String} gesture
  176. * @param {Object} eventData
  177. * @returns {Hammer.Instance}
  178. */
  179. trigger: function triggerEvent(gesture, eventData){
  180. // create DOM event
  181. var event = Hammer.DOCUMENT.createEvent('Event');
  182. event.initEvent(gesture, true, true);
  183. event.gesture = eventData;
  184. // trigger on the target if it is in the instance element,
  185. // this is for event delegation tricks
  186. var element = this.element;
  187. if(Hammer.utils.hasParent(eventData.target, element)) {
  188. element = eventData.target;
  189. }
  190. element.dispatchEvent(event);
  191. return this;
  192. },
  193. /**
  194. * enable of disable hammer.js detection
  195. * @param {Boolean} state
  196. * @returns {Hammer.Instance}
  197. */
  198. enable: function enable(state) {
  199. this.enabled = state;
  200. return this;
  201. }
  202. };
  203. /**
  204. * this holds the last move event,
  205. * used to fix empty touchend issue
  206. * see the onTouch event for an explanation
  207. * @type {Object}
  208. */
  209. var last_move_event = null;
  210. /**
  211. * when the mouse is hold down, this is true
  212. * @type {Boolean}
  213. */
  214. var enable_detect = false;
  215. /**
  216. * when touch events have been fired, this is true
  217. * @type {Boolean}
  218. */
  219. var touch_triggered = false;
  220. Hammer.event = {
  221. /**
  222. * simple addEventListener
  223. * @param {HTMLElement} element
  224. * @param {String} type
  225. * @param {Function} handler
  226. */
  227. bindDom: function(element, type, handler) {
  228. var types = type.split(' ');
  229. for(var t=0; t<types.length; t++) {
  230. element.addEventListener(types[t], handler, false);
  231. }
  232. },
  233. /**
  234. * touch events with mouse fallback
  235. * @param {HTMLElement} element
  236. * @param {String} eventType like Hammer.EVENT_MOVE
  237. * @param {Function} handler
  238. */
  239. onTouch: function onTouch(element, eventType, handler) {
  240. var self = this;
  241. this.bindDom(element, Hammer.EVENT_TYPES[eventType], function bindDomOnTouch(ev) {
  242. var sourceEventType = ev.type.toLowerCase();
  243. // onmouseup, but when touchend has been fired we do nothing.
  244. // this is for touchdevices which also fire a mouseup on touchend
  245. if(sourceEventType.match(/mouse/) && touch_triggered) {
  246. return;
  247. }
  248. // mousebutton must be down or a touch event
  249. else if( sourceEventType.match(/touch/) || // touch events are always on screen
  250. sourceEventType.match(/pointerdown/) || // pointerevents touch
  251. (sourceEventType.match(/mouse/) && ev.which === 1) // mouse is pressed
  252. ){
  253. enable_detect = true;
  254. }
  255. // we are in a touch event, set the touch triggered bool to true,
  256. // this for the conflicts that may occur on ios and android
  257. if(sourceEventType.match(/touch|pointer/)) {
  258. touch_triggered = true;
  259. }
  260. // count the total touches on the screen
  261. var count_touches = 0;
  262. // when touch has been triggered in this detection session
  263. // and we are now handling a mouse event, we stop that to prevent conflicts
  264. if(enable_detect) {
  265. // update pointerevent
  266. if(Hammer.HAS_POINTEREVENTS && eventType != Hammer.EVENT_END) {
  267. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  268. }
  269. // touch
  270. else if(sourceEventType.match(/touch/)) {
  271. count_touches = ev.touches.length;
  272. }
  273. // mouse
  274. else if(!touch_triggered) {
  275. count_touches = sourceEventType.match(/up/) ? 0 : 1;
  276. }
  277. // if we are in a end event, but when we remove one touch and
  278. // we still have enough, set eventType to move
  279. if(count_touches > 0 && eventType == Hammer.EVENT_END) {
  280. eventType = Hammer.EVENT_MOVE;
  281. }
  282. // no touches, force the end event
  283. else if(!count_touches) {
  284. eventType = Hammer.EVENT_END;
  285. }
  286. // because touchend has no touches, and we often want to use these in our gestures,
  287. // we send the last move event as our eventData in touchend
  288. if(!count_touches && last_move_event !== null) {
  289. ev = last_move_event;
  290. }
  291. // store the last move event
  292. else {
  293. last_move_event = ev;
  294. }
  295. // trigger the handler
  296. handler.call(Hammer.detection, self.collectEventData(element, eventType, ev));
  297. // remove pointerevent from list
  298. if(Hammer.HAS_POINTEREVENTS && eventType == Hammer.EVENT_END) {
  299. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  300. }
  301. }
  302. //debug(sourceEventType +" "+ eventType);
  303. // on the end we reset everything
  304. if(!count_touches) {
  305. last_move_event = null;
  306. enable_detect = false;
  307. touch_triggered = false;
  308. Hammer.PointerEvent.reset();
  309. }
  310. });
  311. },
  312. /**
  313. * we have different events for each device/browser
  314. * determine what we need and set them in the Hammer.EVENT_TYPES constant
  315. */
  316. determineEventTypes: function determineEventTypes() {
  317. // determine the eventtype we want to set
  318. var types;
  319. // pointerEvents magic
  320. if(Hammer.HAS_POINTEREVENTS) {
  321. types = Hammer.PointerEvent.getEvents();
  322. }
  323. // on Android, iOS, blackberry, windows mobile we dont want any mouseevents
  324. else if(Hammer.NO_MOUSEEVENTS) {
  325. types = [
  326. 'touchstart',
  327. 'touchmove',
  328. 'touchend touchcancel'];
  329. }
  330. // for non pointer events browsers and mixed browsers,
  331. // like chrome on windows8 touch laptop
  332. else {
  333. types = [
  334. 'touchstart mousedown',
  335. 'touchmove mousemove',
  336. 'touchend touchcancel mouseup'];
  337. }
  338. Hammer.EVENT_TYPES[Hammer.EVENT_START] = types[0];
  339. Hammer.EVENT_TYPES[Hammer.EVENT_MOVE] = types[1];
  340. Hammer.EVENT_TYPES[Hammer.EVENT_END] = types[2];
  341. },
  342. /**
  343. * create touchlist depending on the event
  344. * @param {Object} ev
  345. * @param {String} eventType used by the fakemultitouch plugin
  346. */
  347. getTouchList: function getTouchList(ev/*, eventType*/) {
  348. // get the fake pointerEvent touchlist
  349. if(Hammer.HAS_POINTEREVENTS) {
  350. return Hammer.PointerEvent.getTouchList();
  351. }
  352. // get the touchlist
  353. else if(ev.touches) {
  354. return ev.touches;
  355. }
  356. // make fake touchlist from mouse position
  357. else {
  358. return [{
  359. identifier: 1,
  360. pageX: ev.pageX,
  361. pageY: ev.pageY,
  362. target: ev.target
  363. }];
  364. }
  365. },
  366. /**
  367. * collect event data for Hammer js
  368. * @param {HTMLElement} element
  369. * @param {String} eventType like Hammer.EVENT_MOVE
  370. * @param {Object} eventData
  371. */
  372. collectEventData: function collectEventData(element, eventType, ev) {
  373. var touches = this.getTouchList(ev, eventType);
  374. // find out pointerType
  375. var pointerType = Hammer.POINTER_TOUCH;
  376. if(ev.type.match(/mouse/) || Hammer.PointerEvent.matchType(Hammer.POINTER_MOUSE, ev)) {
  377. pointerType = Hammer.POINTER_MOUSE;
  378. }
  379. return {
  380. center : Hammer.utils.getCenter(touches),
  381. timeStamp : new Date().getTime(),
  382. target : ev.target,
  383. touches : touches,
  384. eventType : eventType,
  385. pointerType : pointerType,
  386. srcEvent : ev,
  387. /**
  388. * prevent the browser default actions
  389. * mostly used to disable scrolling of the browser
  390. */
  391. preventDefault: function() {
  392. if(this.srcEvent.preventManipulation) {
  393. this.srcEvent.preventManipulation();
  394. }
  395. if(this.srcEvent.preventDefault) {
  396. this.srcEvent.preventDefault();
  397. }
  398. },
  399. /**
  400. * stop bubbling the event up to its parents
  401. */
  402. stopPropagation: function() {
  403. this.srcEvent.stopPropagation();
  404. },
  405. /**
  406. * immediately stop gesture detection
  407. * might be useful after a swipe was detected
  408. * @return {*}
  409. */
  410. stopDetect: function() {
  411. return Hammer.detection.stopDetect();
  412. }
  413. };
  414. }
  415. };
  416. Hammer.PointerEvent = {
  417. /**
  418. * holds all pointers
  419. * @type {Object}
  420. */
  421. pointers: {},
  422. /**
  423. * get a list of pointers
  424. * @returns {Array} touchlist
  425. */
  426. getTouchList: function() {
  427. var self = this;
  428. var touchlist = [];
  429. // we can use forEach since pointerEvents only is in IE10
  430. Object.keys(self.pointers).sort().forEach(function(id) {
  431. touchlist.push(self.pointers[id]);
  432. });
  433. return touchlist;
  434. },
  435. /**
  436. * update the position of a pointer
  437. * @param {String} type Hammer.EVENT_END
  438. * @param {Object} pointerEvent
  439. */
  440. updatePointer: function(type, pointerEvent) {
  441. if(type == Hammer.EVENT_END) {
  442. this.pointers = {};
  443. }
  444. else {
  445. pointerEvent.identifier = pointerEvent.pointerId;
  446. this.pointers[pointerEvent.pointerId] = pointerEvent;
  447. }
  448. return Object.keys(this.pointers).length;
  449. },
  450. /**
  451. * check if ev matches pointertype
  452. * @param {String} pointerType Hammer.POINTER_MOUSE
  453. * @param {PointerEvent} ev
  454. */
  455. matchType: function(pointerType, ev) {
  456. if(!ev.pointerType) {
  457. return false;
  458. }
  459. var types = {};
  460. types[Hammer.POINTER_MOUSE] = (ev.pointerType == ev.MSPOINTER_TYPE_MOUSE || ev.pointerType == Hammer.POINTER_MOUSE);
  461. types[Hammer.POINTER_TOUCH] = (ev.pointerType == ev.MSPOINTER_TYPE_TOUCH || ev.pointerType == Hammer.POINTER_TOUCH);
  462. types[Hammer.POINTER_PEN] = (ev.pointerType == ev.MSPOINTER_TYPE_PEN || ev.pointerType == Hammer.POINTER_PEN);
  463. return types[pointerType];
  464. },
  465. /**
  466. * get events
  467. */
  468. getEvents: function() {
  469. return [
  470. 'pointerdown MSPointerDown',
  471. 'pointermove MSPointerMove',
  472. 'pointerup pointercancel MSPointerUp MSPointerCancel'
  473. ];
  474. },
  475. /**
  476. * reset the list
  477. */
  478. reset: function() {
  479. this.pointers = {};
  480. }
  481. };
  482. Hammer.utils = {
  483. /**
  484. * extend method,
  485. * also used for cloning when dest is an empty object
  486. * @param {Object} dest
  487. * @param {Object} src
  488. * @parm {Boolean} merge do a merge
  489. * @returns {Object} dest
  490. */
  491. extend: function extend(dest, src, merge) {
  492. for (var key in src) {
  493. if(dest[key] !== undefined && merge) {
  494. continue;
  495. }
  496. dest[key] = src[key];
  497. }
  498. return dest;
  499. },
  500. /**
  501. * find if a node is in the given parent
  502. * used for event delegation tricks
  503. * @param {HTMLElement} node
  504. * @param {HTMLElement} parent
  505. * @returns {boolean} has_parent
  506. */
  507. hasParent: function(node, parent) {
  508. while(node){
  509. if(node == parent) {
  510. return true;
  511. }
  512. node = node.parentNode;
  513. }
  514. return false;
  515. },
  516. /**
  517. * get the center of all the touches
  518. * @param {Array} touches
  519. * @returns {Object} center
  520. */
  521. getCenter: function getCenter(touches) {
  522. var valuesX = [], valuesY = [];
  523. for(var t= 0,len=touches.length; t<len; t++) {
  524. valuesX.push(touches[t].pageX);
  525. valuesY.push(touches[t].pageY);
  526. }
  527. return {
  528. pageX: ((Math.min.apply(Math, valuesX) + Math.max.apply(Math, valuesX)) / 2),
  529. pageY: ((Math.min.apply(Math, valuesY) + Math.max.apply(Math, valuesY)) / 2)
  530. };
  531. },
  532. /**
  533. * calculate the velocity between two points
  534. * @param {Number} delta_time
  535. * @param {Number} delta_x
  536. * @param {Number} delta_y
  537. * @returns {Object} velocity
  538. */
  539. getVelocity: function getVelocity(delta_time, delta_x, delta_y) {
  540. return {
  541. x: Math.abs(delta_x / delta_time) || 0,
  542. y: Math.abs(delta_y / delta_time) || 0
  543. };
  544. },
  545. /**
  546. * calculate the angle between two coordinates
  547. * @param {Touch} touch1
  548. * @param {Touch} touch2
  549. * @returns {Number} angle
  550. */
  551. getAngle: function getAngle(touch1, touch2) {
  552. var y = touch2.pageY - touch1.pageY,
  553. x = touch2.pageX - touch1.pageX;
  554. return Math.atan2(y, x) * 180 / Math.PI;
  555. },
  556. /**
  557. * angle to direction define
  558. * @param {Touch} touch1
  559. * @param {Touch} touch2
  560. * @returns {String} direction constant, like Hammer.DIRECTION_LEFT
  561. */
  562. getDirection: function getDirection(touch1, touch2) {
  563. var x = Math.abs(touch1.pageX - touch2.pageX),
  564. y = Math.abs(touch1.pageY - touch2.pageY);
  565. if(x >= y) {
  566. return touch1.pageX - touch2.pageX > 0 ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  567. }
  568. else {
  569. return touch1.pageY - touch2.pageY > 0 ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  570. }
  571. },
  572. /**
  573. * calculate the distance between two touches
  574. * @param {Touch} touch1
  575. * @param {Touch} touch2
  576. * @returns {Number} distance
  577. */
  578. getDistance: function getDistance(touch1, touch2) {
  579. var x = touch2.pageX - touch1.pageX,
  580. y = touch2.pageY - touch1.pageY;
  581. return Math.sqrt((x*x) + (y*y));
  582. },
  583. /**
  584. * calculate the scale factor between two touchLists (fingers)
  585. * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
  586. * @param {Array} start
  587. * @param {Array} end
  588. * @returns {Number} scale
  589. */
  590. getScale: function getScale(start, end) {
  591. // need two fingers...
  592. if(start.length >= 2 && end.length >= 2) {
  593. return this.getDistance(end[0], end[1]) /
  594. this.getDistance(start[0], start[1]);
  595. }
  596. return 1;
  597. },
  598. /**
  599. * calculate the rotation degrees between two touchLists (fingers)
  600. * @param {Array} start
  601. * @param {Array} end
  602. * @returns {Number} rotation
  603. */
  604. getRotation: function getRotation(start, end) {
  605. // need two fingers
  606. if(start.length >= 2 && end.length >= 2) {
  607. return this.getAngle(end[1], end[0]) -
  608. this.getAngle(start[1], start[0]);
  609. }
  610. return 0;
  611. },
  612. /**
  613. * boolean if the direction is vertical
  614. * @param {String} direction
  615. * @returns {Boolean} is_vertical
  616. */
  617. isVertical: function isVertical(direction) {
  618. return (direction == Hammer.DIRECTION_UP || direction == Hammer.DIRECTION_DOWN);
  619. },
  620. /**
  621. * stop browser default behavior with css props
  622. * @param {HtmlElement} element
  623. * @param {Object} css_props
  624. */
  625. stopDefaultBrowserBehavior: function stopDefaultBrowserBehavior(element, css_props) {
  626. var prop,
  627. vendors = ['webkit','khtml','moz','ms','o',''];
  628. if(!css_props || !element.style) {
  629. return;
  630. }
  631. // with css properties for modern browsers
  632. for(var i = 0; i < vendors.length; i++) {
  633. for(var p in css_props) {
  634. if(css_props.hasOwnProperty(p)) {
  635. prop = p;
  636. // vender prefix at the property
  637. if(vendors[i]) {
  638. prop = vendors[i] + prop.substring(0, 1).toUpperCase() + prop.substring(1);
  639. }
  640. // set the style
  641. element.style[prop] = css_props[p];
  642. }
  643. }
  644. }
  645. // also the disable onselectstart
  646. if(css_props.userSelect == 'none') {
  647. element.onselectstart = function() {
  648. return false;
  649. };
  650. }
  651. }
  652. };
  653. Hammer.detection = {
  654. // contains all registred Hammer.gestures in the correct order
  655. gestures: [],
  656. // data of the current Hammer.gesture detection session
  657. current: null,
  658. // the previous Hammer.gesture session data
  659. // is a full clone of the previous gesture.current object
  660. previous: null,
  661. // when this becomes true, no gestures are fired
  662. stopped: false,
  663. /**
  664. * start Hammer.gesture detection
  665. * @param {Hammer.Instance} inst
  666. * @param {Object} eventData
  667. */
  668. startDetect: function startDetect(inst, eventData) {
  669. // already busy with a Hammer.gesture detection on an element
  670. if(this.current) {
  671. return;
  672. }
  673. this.stopped = false;
  674. this.current = {
  675. inst : inst, // reference to HammerInstance we're working for
  676. startEvent : Hammer.utils.extend({}, eventData), // start eventData for distances, timing etc
  677. lastEvent : false, // last eventData
  678. name : '' // current gesture we're in/detected, can be 'tap', 'hold' etc
  679. };
  680. this.detect(eventData);
  681. },
  682. /**
  683. * Hammer.gesture detection
  684. * @param {Object} eventData
  685. * @param {Object} eventData
  686. */
  687. detect: function detect(eventData) {
  688. if(!this.current || this.stopped) {
  689. return;
  690. }
  691. // extend event data with calculations about scale, distance etc
  692. eventData = this.extendEventData(eventData);
  693. // instance options
  694. var inst_options = this.current.inst.options;
  695. // call Hammer.gesture handlers
  696. for(var g=0,len=this.gestures.length; g<len; g++) {
  697. var gesture = this.gestures[g];
  698. // only when the instance options have enabled this gesture
  699. if(!this.stopped && inst_options[gesture.name] !== false) {
  700. // if a handler returns false, we stop with the detection
  701. if(gesture.handler.call(gesture, eventData, this.current.inst) === false) {
  702. this.stopDetect();
  703. break;
  704. }
  705. }
  706. }
  707. // store as previous event event
  708. if(this.current) {
  709. this.current.lastEvent = eventData;
  710. }
  711. // endevent, but not the last touch, so dont stop
  712. if(eventData.eventType == Hammer.EVENT_END && !eventData.touches.length-1) {
  713. this.stopDetect();
  714. }
  715. return eventData;
  716. },
  717. /**
  718. * clear the Hammer.gesture vars
  719. * this is called on endDetect, but can also be used when a final Hammer.gesture has been detected
  720. * to stop other Hammer.gestures from being fired
  721. */
  722. stopDetect: function stopDetect() {
  723. // clone current data to the store as the previous gesture
  724. // used for the double tap gesture, since this is an other gesture detect session
  725. this.previous = Hammer.utils.extend({}, this.current);
  726. // reset the current
  727. this.current = null;
  728. // stopped!
  729. this.stopped = true;
  730. },
  731. /**
  732. * extend eventData for Hammer.gestures
  733. * @param {Object} ev
  734. * @returns {Object} ev
  735. */
  736. extendEventData: function extendEventData(ev) {
  737. var startEv = this.current.startEvent;
  738. // if the touches change, set the new touches over the startEvent touches
  739. // this because touchevents don't have all the touches on touchstart, or the
  740. // user must place his fingers at the EXACT same time on the screen, which is not realistic
  741. // but, sometimes it happens that both fingers are touching at the EXACT same time
  742. if(startEv && (ev.touches.length != startEv.touches.length || ev.touches === startEv.touches)) {
  743. // extend 1 level deep to get the touchlist with the touch objects
  744. startEv.touches = [];
  745. for(var i=0,len=ev.touches.length; i<len; i++) {
  746. startEv.touches.push(Hammer.utils.extend({}, ev.touches[i]));
  747. }
  748. }
  749. var delta_time = ev.timeStamp - startEv.timeStamp,
  750. delta_x = ev.center.pageX - startEv.center.pageX,
  751. delta_y = ev.center.pageY - startEv.center.pageY,
  752. velocity = Hammer.utils.getVelocity(delta_time, delta_x, delta_y);
  753. Hammer.utils.extend(ev, {
  754. deltaTime : delta_time,
  755. deltaX : delta_x,
  756. deltaY : delta_y,
  757. velocityX : velocity.x,
  758. velocityY : velocity.y,
  759. distance : Hammer.utils.getDistance(startEv.center, ev.center),
  760. angle : Hammer.utils.getAngle(startEv.center, ev.center),
  761. direction : Hammer.utils.getDirection(startEv.center, ev.center),
  762. scale : Hammer.utils.getScale(startEv.touches, ev.touches),
  763. rotation : Hammer.utils.getRotation(startEv.touches, ev.touches),
  764. startEvent : startEv
  765. });
  766. return ev;
  767. },
  768. /**
  769. * register new gesture
  770. * @param {Object} gesture object, see gestures.js for documentation
  771. * @returns {Array} gestures
  772. */
  773. register: function register(gesture) {
  774. // add an enable gesture options if there is no given
  775. var options = gesture.defaults || {};
  776. if(options[gesture.name] === undefined) {
  777. options[gesture.name] = true;
  778. }
  779. // extend Hammer default options with the Hammer.gesture options
  780. Hammer.utils.extend(Hammer.defaults, options, true);
  781. // set its index
  782. gesture.index = gesture.index || 1000;
  783. // add Hammer.gesture to the list
  784. this.gestures.push(gesture);
  785. // sort the list by index
  786. this.gestures.sort(function(a, b) {
  787. if (a.index < b.index) {
  788. return -1;
  789. }
  790. if (a.index > b.index) {
  791. return 1;
  792. }
  793. return 0;
  794. });
  795. return this.gestures;
  796. }
  797. };
  798. Hammer.gestures = Hammer.gestures || {};
  799. /**
  800. * Custom gestures
  801. * ==============================
  802. *
  803. * Gesture object
  804. * --------------------
  805. * The object structure of a gesture:
  806. *
  807. * { name: 'mygesture',
  808. * index: 1337,
  809. * defaults: {
  810. * mygesture_option: true
  811. * }
  812. * handler: function(type, ev, inst) {
  813. * // trigger gesture event
  814. * inst.trigger(this.name, ev);
  815. * }
  816. * }
  817. * @param {String} name
  818. * this should be the name of the gesture, lowercase
  819. * it is also being used to disable/enable the gesture per instance config.
  820. *
  821. * @param {Number} [index=1000]
  822. * the index of the gesture, where it is going to be in the stack of gestures detection
  823. * like when you build an gesture that depends on the drag gesture, it is a good
  824. * idea to place it after the index of the drag gesture.
  825. *
  826. * @param {Object} [defaults={}]
  827. * the default settings of the gesture. these are added to the instance settings,
  828. * and can be overruled per instance. you can also add the name of the gesture,
  829. * but this is also added by default (and set to true).
  830. *
  831. * @param {Function} handler
  832. * this handles the gesture detection of your custom gesture and receives the
  833. * following arguments:
  834. *
  835. * @param {Object} eventData
  836. * event data containing the following properties:
  837. * timeStamp {Number} time the event occurred
  838. * target {HTMLElement} target element
  839. * touches {Array} touches (fingers, pointers, mouse) on the screen
  840. * pointerType {String} kind of pointer that was used. matches Hammer.POINTER_MOUSE|TOUCH
  841. * center {Object} center position of the touches. contains pageX and pageY
  842. * deltaTime {Number} the total time of the touches in the screen
  843. * deltaX {Number} the delta on x axis we haved moved
  844. * deltaY {Number} the delta on y axis we haved moved
  845. * velocityX {Number} the velocity on the x
  846. * velocityY {Number} the velocity on y
  847. * angle {Number} the angle we are moving
  848. * direction {String} the direction we are moving. matches Hammer.DIRECTION_UP|DOWN|LEFT|RIGHT
  849. * distance {Number} the distance we haved moved
  850. * scale {Number} scaling of the touches, needs 2 touches
  851. * rotation {Number} rotation of the touches, needs 2 touches *
  852. * eventType {String} matches Hammer.EVENT_START|MOVE|END
  853. * srcEvent {Object} the source event, like TouchStart or MouseDown *
  854. * startEvent {Object} contains the same properties as above,
  855. * but from the first touch. this is used to calculate
  856. * distances, deltaTime, scaling etc
  857. *
  858. * @param {Hammer.Instance} inst
  859. * the instance we are doing the detection for. you can get the options from
  860. * the inst.options object and trigger the gesture event by calling inst.trigger
  861. *
  862. *
  863. * Handle gestures
  864. * --------------------
  865. * inside the handler you can get/set Hammer.detection.current. This is the current
  866. * detection session. It has the following properties
  867. * @param {String} name
  868. * contains the name of the gesture we have detected. it has not a real function,
  869. * only to check in other gestures if something is detected.
  870. * like in the drag gesture we set it to 'drag' and in the swipe gesture we can
  871. * check if the current gesture is 'drag' by accessing Hammer.detection.current.name
  872. *
  873. * @readonly
  874. * @param {Hammer.Instance} inst
  875. * the instance we do the detection for
  876. *
  877. * @readonly
  878. * @param {Object} startEvent
  879. * contains the properties of the first gesture detection in this session.
  880. * Used for calculations about timing, distance, etc.
  881. *
  882. * @readonly
  883. * @param {Object} lastEvent
  884. * contains all the properties of the last gesture detect in this session.
  885. *
  886. * after the gesture detection session has been completed (user has released the screen)
  887. * the Hammer.detection.current object is copied into Hammer.detection.previous,
  888. * this is usefull for gestures like doubletap, where you need to know if the
  889. * previous gesture was a tap
  890. *
  891. * options that have been set by the instance can be received by calling inst.options
  892. *
  893. * You can trigger a gesture event by calling inst.trigger("mygesture", event).
  894. * The first param is the name of your gesture, the second the event argument
  895. *
  896. *
  897. * Register gestures
  898. * --------------------
  899. * When an gesture is added to the Hammer.gestures object, it is auto registered
  900. * at the setup of the first Hammer instance. You can also call Hammer.detection.register
  901. * manually and pass your gesture object as a param
  902. *
  903. */
  904. /**
  905. * Hold
  906. * Touch stays at the same place for x time
  907. * @events hold
  908. */
  909. Hammer.gestures.Hold = {
  910. name: 'hold',
  911. index: 10,
  912. defaults: {
  913. hold_timeout : 500,
  914. hold_threshold : 1
  915. },
  916. timer: null,
  917. handler: function holdGesture(ev, inst) {
  918. switch(ev.eventType) {
  919. case Hammer.EVENT_START:
  920. // clear any running timers
  921. clearTimeout(this.timer);
  922. // set the gesture so we can check in the timeout if it still is
  923. Hammer.detection.current.name = this.name;
  924. // set timer and if after the timeout it still is hold,
  925. // we trigger the hold event
  926. this.timer = setTimeout(function() {
  927. if(Hammer.detection.current.name == 'hold') {
  928. inst.trigger('hold', ev);
  929. }
  930. }, inst.options.hold_timeout);
  931. break;
  932. // when you move or end we clear the timer
  933. case Hammer.EVENT_MOVE:
  934. if(ev.distance > inst.options.hold_threshold) {
  935. clearTimeout(this.timer);
  936. }
  937. break;
  938. case Hammer.EVENT_END:
  939. clearTimeout(this.timer);
  940. break;
  941. }
  942. }
  943. };
  944. /**
  945. * Tap/DoubleTap
  946. * Quick touch at a place or double at the same place
  947. * @events tap, doubletap
  948. */
  949. Hammer.gestures.Tap = {
  950. name: 'tap',
  951. index: 100,
  952. defaults: {
  953. tap_max_touchtime : 250,
  954. tap_max_distance : 10,
  955. tap_always : true,
  956. doubletap_distance : 20,
  957. doubletap_interval : 300
  958. },
  959. handler: function tapGesture(ev, inst) {
  960. if(ev.eventType == Hammer.EVENT_END) {
  961. // previous gesture, for the double tap since these are two different gesture detections
  962. var prev = Hammer.detection.previous,
  963. did_doubletap = false;
  964. // when the touchtime is higher then the max touch time
  965. // or when the moving distance is too much
  966. if(ev.deltaTime > inst.options.tap_max_touchtime ||
  967. ev.distance > inst.options.tap_max_distance) {
  968. return;
  969. }
  970. // check if double tap
  971. if(prev && prev.name == 'tap' &&
  972. (ev.timeStamp - prev.lastEvent.timeStamp) < inst.options.doubletap_interval &&
  973. ev.distance < inst.options.doubletap_distance) {
  974. inst.trigger('doubletap', ev);
  975. did_doubletap = true;
  976. }
  977. // do a single tap
  978. if(!did_doubletap || inst.options.tap_always) {
  979. Hammer.detection.current.name = 'tap';
  980. inst.trigger(Hammer.detection.current.name, ev);
  981. }
  982. }
  983. }
  984. };
  985. /**
  986. * Swipe
  987. * triggers swipe events when the end velocity is above the threshold
  988. * @events swipe, swipeleft, swiperight, swipeup, swipedown
  989. */
  990. Hammer.gestures.Swipe = {
  991. name: 'swipe',
  992. index: 40,
  993. defaults: {
  994. // set 0 for unlimited, but this can conflict with transform
  995. swipe_max_touches : 1,
  996. swipe_velocity : 0.7
  997. },
  998. handler: function swipeGesture(ev, inst) {
  999. if(ev.eventType == Hammer.EVENT_END) {
  1000. // max touches
  1001. if(inst.options.swipe_max_touches > 0 &&
  1002. ev.touches.length > inst.options.swipe_max_touches) {
  1003. return;
  1004. }
  1005. // when the distance we moved is too small we skip this gesture
  1006. // or we can be already in dragging
  1007. if(ev.velocityX > inst.options.swipe_velocity ||
  1008. ev.velocityY > inst.options.swipe_velocity) {
  1009. // trigger swipe events
  1010. inst.trigger(this.name, ev);
  1011. inst.trigger(this.name + ev.direction, ev);
  1012. }
  1013. }
  1014. }
  1015. };
  1016. /**
  1017. * Drag
  1018. * Move with x fingers (default 1) around on the page. Blocking the scrolling when
  1019. * moving left and right is a good practice. When all the drag events are blocking
  1020. * you disable scrolling on that area.
  1021. * @events drag, drapleft, dragright, dragup, dragdown
  1022. */
  1023. Hammer.gestures.Drag = {
  1024. name: 'drag',
  1025. index: 50,
  1026. defaults: {
  1027. drag_min_distance : 10,
  1028. // set 0 for unlimited, but this can conflict with transform
  1029. drag_max_touches : 1,
  1030. // prevent default browser behavior when dragging occurs
  1031. // be careful with it, it makes the element a blocking element
  1032. // when you are using the drag gesture, it is a good practice to set this true
  1033. drag_block_horizontal : false,
  1034. drag_block_vertical : false,
  1035. // drag_lock_to_axis keeps the drag gesture on the axis that it started on,
  1036. // It disallows vertical directions if the initial direction was horizontal, and vice versa.
  1037. drag_lock_to_axis : false,
  1038. // drag lock only kicks in when distance > drag_lock_min_distance
  1039. // This way, locking occurs only when the distance has become large enough to reliably determine the direction
  1040. drag_lock_min_distance : 25
  1041. },
  1042. triggered: false,
  1043. handler: function dragGesture(ev, inst) {
  1044. // current gesture isnt drag, but dragged is true
  1045. // this means an other gesture is busy. now call dragend
  1046. if(Hammer.detection.current.name != this.name && this.triggered) {
  1047. inst.trigger(this.name +'end', ev);
  1048. this.triggered = false;
  1049. return;
  1050. }
  1051. // max touches
  1052. if(inst.options.drag_max_touches > 0 &&
  1053. ev.touches.length > inst.options.drag_max_touches) {
  1054. return;
  1055. }
  1056. switch(ev.eventType) {
  1057. case Hammer.EVENT_START:
  1058. this.triggered = false;
  1059. break;
  1060. case Hammer.EVENT_MOVE:
  1061. // when the distance we moved is too small we skip this gesture
  1062. // or we can be already in dragging
  1063. if(ev.distance < inst.options.drag_min_distance &&
  1064. Hammer.detection.current.name != this.name) {
  1065. return;
  1066. }
  1067. // we are dragging!
  1068. Hammer.detection.current.name = this.name;
  1069. // lock drag to axis?
  1070. if(Hammer.detection.current.lastEvent.drag_locked_to_axis || (inst.options.drag_lock_to_axis && inst.options.drag_lock_min_distance<=ev.distance)) {
  1071. ev.drag_locked_to_axis = true;
  1072. }
  1073. var last_direction = Hammer.detection.current.lastEvent.direction;
  1074. if(ev.drag_locked_to_axis && last_direction !== ev.direction) {
  1075. // keep direction on the axis that the drag gesture started on
  1076. if(Hammer.utils.isVertical(last_direction)) {
  1077. ev.direction = (ev.deltaY < 0) ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  1078. }
  1079. else {
  1080. ev.direction = (ev.deltaX < 0) ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  1081. }
  1082. }
  1083. // first time, trigger dragstart event
  1084. if(!this.triggered) {
  1085. inst.trigger(this.name +'start', ev);
  1086. this.triggered = true;
  1087. }
  1088. // trigger normal event
  1089. inst.trigger(this.name, ev);
  1090. // direction event, like dragdown
  1091. inst.trigger(this.name + ev.direction, ev);
  1092. // block the browser events
  1093. if( (inst.options.drag_block_vertical && Hammer.utils.isVertical(ev.direction)) ||
  1094. (inst.options.drag_block_horizontal && !Hammer.utils.isVertical(ev.direction))) {
  1095. ev.preventDefault();
  1096. }
  1097. break;
  1098. case Hammer.EVENT_END:
  1099. // trigger dragend
  1100. if(this.triggered) {
  1101. inst.trigger(this.name +'end', ev);
  1102. }
  1103. this.triggered = false;
  1104. break;
  1105. }
  1106. }
  1107. };
  1108. /**
  1109. * Transform
  1110. * User want to scale or rotate with 2 fingers
  1111. * @events transform, pinch, pinchin, pinchout, rotate
  1112. */
  1113. Hammer.gestures.Transform = {
  1114. name: 'transform',
  1115. index: 45,
  1116. defaults: {
  1117. // factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1
  1118. transform_min_scale : 0.01,
  1119. // rotation in degrees
  1120. transform_min_rotation : 1,
  1121. // prevent default browser behavior when two touches are on the screen
  1122. // but it makes the element a blocking element
  1123. // when you are using the transform gesture, it is a good practice to set this true
  1124. transform_always_block : false
  1125. },
  1126. triggered: false,
  1127. handler: function transformGesture(ev, inst) {
  1128. // current gesture isnt drag, but dragged is true
  1129. // this means an other gesture is busy. now call dragend
  1130. if(Hammer.detection.current.name != this.name && this.triggered) {
  1131. inst.trigger(this.name +'end', ev);
  1132. this.triggered = false;
  1133. return;
  1134. }
  1135. // atleast multitouch
  1136. if(ev.touches.length < 2) {
  1137. return;
  1138. }
  1139. // prevent default when two fingers are on the screen
  1140. if(inst.options.transform_always_block) {
  1141. ev.preventDefault();
  1142. }
  1143. switch(ev.eventType) {
  1144. case Hammer.EVENT_START:
  1145. this.triggered = false;
  1146. break;
  1147. case Hammer.EVENT_MOVE:
  1148. var scale_threshold = Math.abs(1-ev.scale);
  1149. var rotation_threshold = Math.abs(ev.rotation);
  1150. // when the distance we moved is too small we skip this gesture
  1151. // or we can be already in dragging
  1152. if(scale_threshold < inst.options.transform_min_scale &&
  1153. rotation_threshold < inst.options.transform_min_rotation) {
  1154. return;
  1155. }
  1156. // we are transforming!
  1157. Hammer.detection.current.name = this.name;
  1158. // first time, trigger dragstart event
  1159. if(!this.triggered) {
  1160. inst.trigger(this.name +'start', ev);
  1161. this.triggered = true;
  1162. }
  1163. inst.trigger(this.name, ev); // basic transform event
  1164. // trigger rotate event
  1165. if(rotation_threshold > inst.options.transform_min_rotation) {
  1166. inst.trigger('rotate', ev);
  1167. }
  1168. // trigger pinch event
  1169. if(scale_threshold > inst.options.transform_min_scale) {
  1170. inst.trigger('pinch', ev);
  1171. inst.trigger('pinch'+ ((ev.scale < 1) ? 'in' : 'out'), ev);
  1172. }
  1173. break;
  1174. case Hammer.EVENT_END:
  1175. // trigger dragend
  1176. if(this.triggered) {
  1177. inst.trigger(this.name +'end', ev);
  1178. }
  1179. this.triggered = false;
  1180. break;
  1181. }
  1182. }
  1183. };
  1184. /**
  1185. * Touch
  1186. * Called as first, tells the user has touched the screen
  1187. * @events touch
  1188. */
  1189. Hammer.gestures.Touch = {
  1190. name: 'touch',
  1191. index: -Infinity,
  1192. defaults: {
  1193. // call preventDefault at touchstart, and makes the element blocking by
  1194. // disabling the scrolling of the page, but it improves gestures like
  1195. // transforming and dragging.
  1196. // be careful with using this, it can be very annoying for users to be stuck
  1197. // on the page
  1198. prevent_default: false,
  1199. // disable mouse events, so only touch (or pen!) input triggers events
  1200. prevent_mouseevents: false
  1201. },
  1202. handler: function touchGesture(ev, inst) {
  1203. if(inst.options.prevent_mouseevents && ev.pointerType == Hammer.POINTER_MOUSE) {
  1204. ev.stopDetect();
  1205. return;
  1206. }
  1207. if(inst.options.prevent_default) {
  1208. ev.preventDefault();
  1209. }
  1210. if(ev.eventType == Hammer.EVENT_START) {
  1211. inst.trigger(this.name, ev);
  1212. }
  1213. }
  1214. };
  1215. /**
  1216. * Release
  1217. * Called as last, tells the user has released the screen
  1218. * @events release
  1219. */
  1220. Hammer.gestures.Release = {
  1221. name: 'release',
  1222. index: Infinity,
  1223. handler: function releaseGesture(ev, inst) {
  1224. if(ev.eventType == Hammer.EVENT_END) {
  1225. inst.trigger(this.name, ev);
  1226. }
  1227. }
  1228. };
  1229. // node export
  1230. if(typeof module === 'object' && typeof module.exports === 'object'){
  1231. module.exports = Hammer;
  1232. }
  1233. // just window export
  1234. else {
  1235. window.Hammer = Hammer;
  1236. // requireJS module definition
  1237. if(typeof window.define === 'function' && window.define.amd) {
  1238. window.define('hammer', [], function() {
  1239. return Hammer;
  1240. });
  1241. }
  1242. }
  1243. })(this);
  1244. },{}],2:[function(require,module,exports){
  1245. //! moment.js
  1246. //! version : 2.2.1
  1247. //! authors : Tim Wood, Iskren Chernev, Moment.js contributors
  1248. //! license : MIT
  1249. //! momentjs.com
  1250. (function (undefined) {
  1251. /************************************
  1252. Constants
  1253. ************************************/
  1254. var moment,
  1255. VERSION = "2.2.1",
  1256. round = Math.round, i,
  1257. // internal storage for language config files
  1258. languages = {},
  1259. // check for nodeJS
  1260. hasModule = (typeof module !== 'undefined' && module.exports),
  1261. // ASP.NET json date format regex
  1262. aspNetJsonRegex = /^\/?Date\((\-?\d+)/i,
  1263. aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)\:(\d+)\.?(\d{3})?/,
  1264. // format tokens
  1265. formattingTokens = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|SS?S?|X|zz?|ZZ?|.)/g,
  1266. localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g,
  1267. // parsing token regexes
  1268. parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99
  1269. parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999
  1270. parseTokenThreeDigits = /\d{3}/, // 000 - 999
  1271. parseTokenFourDigits = /\d{1,4}/, // 0 - 9999
  1272. parseTokenSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999
  1273. 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.
  1274. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/i, // +00:00 -00:00 +0000 -0000 or Z
  1275. parseTokenT = /T/i, // T (ISO seperator)
  1276. parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
  1277. // preliminary iso regex
  1278. // 0000-00-00 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000
  1279. isoRegex = /^\s*\d{4}-\d\d-\d\d((T| )(\d\d(:\d\d(:\d\d(\.\d\d?\d?)?)?)?)?([\+\-]\d\d:?\d\d)?)?/,
  1280. isoFormat = 'YYYY-MM-DDTHH:mm:ssZ',
  1281. // iso time formats and regexes
  1282. isoTimes = [
  1283. ['HH:mm:ss.S', /(T| )\d\d:\d\d:\d\d\.\d{1,3}/],
  1284. ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/],
  1285. ['HH:mm', /(T| )\d\d:\d\d/],
  1286. ['HH', /(T| )\d\d/]
  1287. ],
  1288. // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"]
  1289. parseTimezoneChunker = /([\+\-]|\d\d)/gi,
  1290. // getter and setter names
  1291. proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'),
  1292. unitMillisecondFactors = {
  1293. 'Milliseconds' : 1,
  1294. 'Seconds' : 1e3,
  1295. 'Minutes' : 6e4,
  1296. 'Hours' : 36e5,
  1297. 'Days' : 864e5,
  1298. 'Months' : 2592e6,
  1299. 'Years' : 31536e6
  1300. },
  1301. unitAliases = {
  1302. ms : 'millisecond',
  1303. s : 'second',
  1304. m : 'minute',
  1305. h : 'hour',
  1306. d : 'day',
  1307. w : 'week',
  1308. W : 'isoweek',
  1309. M : 'month',
  1310. y : 'year'
  1311. },
  1312. // format function strings
  1313. formatFunctions = {},
  1314. // tokens to ordinalize and pad
  1315. ordinalizeTokens = 'DDD w W M D d'.split(' '),
  1316. paddedTokens = 'M D H h m s w W'.split(' '),
  1317. formatTokenFunctions = {
  1318. M : function () {
  1319. return this.month() + 1;
  1320. },
  1321. MMM : function (format) {
  1322. return this.lang().monthsShort(this, format);
  1323. },
  1324. MMMM : function (format) {
  1325. return this.lang().months(this, format);
  1326. },
  1327. D : function () {
  1328. return this.date();
  1329. },
  1330. DDD : function () {
  1331. return this.dayOfYear();
  1332. },
  1333. d : function () {
  1334. return this.day();
  1335. },
  1336. dd : function (format) {
  1337. return this.lang().weekdaysMin(this, format);
  1338. },
  1339. ddd : function (format) {
  1340. return this.lang().weekdaysShort(this, format);
  1341. },
  1342. dddd : function (format) {
  1343. return this.lang().weekdays(this, format);
  1344. },
  1345. w : function () {
  1346. return this.week();
  1347. },
  1348. W : function () {
  1349. return this.isoWeek();
  1350. },
  1351. YY : function () {
  1352. return leftZeroFill(this.year() % 100, 2);
  1353. },
  1354. YYYY : function () {
  1355. return leftZeroFill(this.year(), 4);
  1356. },
  1357. YYYYY : function () {
  1358. return leftZeroFill(this.year(), 5);
  1359. },
  1360. gg : function () {
  1361. return leftZeroFill(this.weekYear() % 100, 2);
  1362. },
  1363. gggg : function () {
  1364. return this.weekYear();
  1365. },
  1366. ggggg : function () {
  1367. return leftZeroFill(this.weekYear(), 5);
  1368. },
  1369. GG : function () {
  1370. return leftZeroFill(this.isoWeekYear() % 100, 2);
  1371. },
  1372. GGGG : function () {
  1373. return this.isoWeekYear();
  1374. },
  1375. GGGGG : function () {
  1376. return leftZeroFill(this.isoWeekYear(), 5);
  1377. },
  1378. e : function () {
  1379. return this.weekday();
  1380. },
  1381. E : function () {
  1382. return this.isoWeekday();
  1383. },
  1384. a : function () {
  1385. return this.lang().meridiem(this.hours(), this.minutes(), true);
  1386. },
  1387. A : function () {
  1388. return this.lang().meridiem(this.hours(), this.minutes(), false);
  1389. },
  1390. H : function () {
  1391. return this.hours();
  1392. },
  1393. h : function () {
  1394. return this.hours() % 12 || 12;
  1395. },
  1396. m : function () {
  1397. return this.minutes();
  1398. },
  1399. s : function () {
  1400. return this.seconds();
  1401. },
  1402. S : function () {
  1403. return ~~(this.milliseconds() / 100);
  1404. },
  1405. SS : function () {
  1406. return leftZeroFill(~~(this.milliseconds() / 10), 2);
  1407. },
  1408. SSS : function () {
  1409. return leftZeroFill(this.milliseconds(), 3);
  1410. },
  1411. Z : function () {
  1412. var a = -this.zone(),
  1413. b = "+";
  1414. if (a < 0) {
  1415. a = -a;
  1416. b = "-";
  1417. }
  1418. return b + leftZeroFill(~~(a / 60), 2) + ":" + leftZeroFill(~~a % 60, 2);
  1419. },
  1420. ZZ : function () {
  1421. var a = -this.zone(),
  1422. b = "+";
  1423. if (a < 0) {
  1424. a = -a;
  1425. b = "-";
  1426. }
  1427. return b + leftZeroFill(~~(10 * a / 6), 4);
  1428. },
  1429. z : function () {
  1430. return this.zoneAbbr();
  1431. },
  1432. zz : function () {
  1433. return this.zoneName();
  1434. },
  1435. X : function () {
  1436. return this.unix();
  1437. }
  1438. };
  1439. function padToken(func, count) {
  1440. return function (a) {
  1441. return leftZeroFill(func.call(this, a), count);
  1442. };
  1443. }
  1444. function ordinalizeToken(func, period) {
  1445. return function (a) {
  1446. return this.lang().ordinal(func.call(this, a), period);
  1447. };
  1448. }
  1449. while (ordinalizeTokens.length) {
  1450. i = ordinalizeTokens.pop();
  1451. formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i);
  1452. }
  1453. while (paddedTokens.length) {
  1454. i = paddedTokens.pop();
  1455. formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2);
  1456. }
  1457. formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3);
  1458. /************************************
  1459. Constructors
  1460. ************************************/
  1461. function Language() {
  1462. }
  1463. // Moment prototype object
  1464. function Moment(config) {
  1465. extend(this, config);
  1466. }
  1467. // Duration Constructor
  1468. function Duration(duration) {
  1469. var years = duration.years || duration.year || duration.y || 0,
  1470. months = duration.months || duration.month || duration.M || 0,
  1471. weeks = duration.weeks || duration.week || duration.w || 0,
  1472. days = duration.days || duration.day || duration.d || 0,
  1473. hours = duration.hours || duration.hour || duration.h || 0,
  1474. minutes = duration.minutes || duration.minute || duration.m || 0,
  1475. seconds = duration.seconds || duration.second || duration.s || 0,
  1476. milliseconds = duration.milliseconds || duration.millisecond || duration.ms || 0;
  1477. // store reference to input for deterministic cloning
  1478. this._input = duration;
  1479. // representation for dateAddRemove
  1480. this._milliseconds = +milliseconds +
  1481. seconds * 1e3 + // 1000
  1482. minutes * 6e4 + // 1000 * 60
  1483. hours * 36e5; // 1000 * 60 * 60
  1484. // Because of dateAddRemove treats 24 hours as different from a
  1485. // day when working around DST, we need to store them separately
  1486. this._days = +days +
  1487. weeks * 7;
  1488. // It is impossible translate months into days without knowing
  1489. // which months you are are talking about, so we have to store
  1490. // it separately.
  1491. this._months = +months +
  1492. years * 12;
  1493. this._data = {};
  1494. this._bubble();
  1495. }
  1496. /************************************
  1497. Helpers
  1498. ************************************/
  1499. function extend(a, b) {
  1500. for (var i in b) {
  1501. if (b.hasOwnProperty(i)) {
  1502. a[i] = b[i];
  1503. }
  1504. }
  1505. return a;
  1506. }
  1507. function absRound(number) {
  1508. if (number < 0) {
  1509. return Math.ceil(number);
  1510. } else {
  1511. return Math.floor(number);
  1512. }
  1513. }
  1514. // left zero fill a number
  1515. // see http://jsperf.com/left-zero-filling for performance comparison
  1516. function leftZeroFill(number, targetLength) {
  1517. var output = number + '';
  1518. while (output.length < targetLength) {
  1519. output = '0' + output;
  1520. }
  1521. return output;
  1522. }
  1523. // helper function for _.addTime and _.subtractTime
  1524. function addOrSubtractDurationFromMoment(mom, duration, isAdding, ignoreUpdateOffset) {
  1525. var milliseconds = duration._milliseconds,
  1526. days = duration._days,
  1527. months = duration._months,
  1528. minutes,
  1529. hours;
  1530. if (milliseconds) {
  1531. mom._d.setTime(+mom._d + milliseconds * isAdding);
  1532. }
  1533. // store the minutes and hours so we can restore them
  1534. if (days || months) {
  1535. minutes = mom.minute();
  1536. hours = mom.hour();
  1537. }
  1538. if (days) {
  1539. mom.date(mom.date() + days * isAdding);
  1540. }
  1541. if (months) {
  1542. mom.month(mom.month() + months * isAdding);
  1543. }
  1544. if (milliseconds && !ignoreUpdateOffset) {
  1545. moment.updateOffset(mom);
  1546. }
  1547. // restore the minutes and hours after possibly changing dst
  1548. if (days || months) {
  1549. mom.minute(minutes);
  1550. mom.hour(hours);
  1551. }
  1552. }
  1553. // check if is an array
  1554. function isArray(input) {
  1555. return Object.prototype.toString.call(input) === '[object Array]';
  1556. }
  1557. // compare two arrays, return the number of differences
  1558. function compareArrays(array1, array2) {
  1559. var len = Math.min(array1.length, array2.length),
  1560. lengthDiff = Math.abs(array1.length - array2.length),
  1561. diffs = 0,
  1562. i;
  1563. for (i = 0; i < len; i++) {
  1564. if (~~array1[i] !== ~~array2[i]) {
  1565. diffs++;
  1566. }
  1567. }
  1568. return diffs + lengthDiff;
  1569. }
  1570. function normalizeUnits(units) {
  1571. return units ? unitAliases[units] || units.toLowerCase().replace(/(.)s$/, '$1') : units;
  1572. }
  1573. /************************************
  1574. Languages
  1575. ************************************/
  1576. extend(Language.prototype, {
  1577. set : function (config) {
  1578. var prop, i;
  1579. for (i in config) {
  1580. prop = config[i];
  1581. if (typeof prop === 'function') {
  1582. this[i] = prop;
  1583. } else {
  1584. this['_' + i] = prop;
  1585. }
  1586. }
  1587. },
  1588. _months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
  1589. months : function (m) {
  1590. return this._months[m.month()];
  1591. },
  1592. _monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),
  1593. monthsShort : function (m) {
  1594. return this._monthsShort[m.month()];
  1595. },
  1596. monthsParse : function (monthName) {
  1597. var i, mom, regex;
  1598. if (!this._monthsParse) {
  1599. this._monthsParse = [];
  1600. }
  1601. for (i = 0; i < 12; i++) {
  1602. // make the regex if we don't have it already
  1603. if (!this._monthsParse[i]) {
  1604. mom = moment.utc([2000, i]);
  1605. regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  1606. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  1607. }
  1608. // test the regex
  1609. if (this._monthsParse[i].test(monthName)) {
  1610. return i;
  1611. }
  1612. }
  1613. },
  1614. _weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
  1615. weekdays : function (m) {
  1616. return this._weekdays[m.day()];
  1617. },
  1618. _weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),
  1619. weekdaysShort : function (m) {
  1620. return this._weekdaysShort[m.day()];
  1621. },
  1622. _weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"),
  1623. weekdaysMin : function (m) {
  1624. return this._weekdaysMin[m.day()];
  1625. },
  1626. weekdaysParse : function (weekdayName) {
  1627. var i, mom, regex;
  1628. if (!this._weekdaysParse) {
  1629. this._weekdaysParse = [];
  1630. }
  1631. for (i = 0; i < 7; i++) {
  1632. // make the regex if we don't have it already
  1633. if (!this._weekdaysParse[i]) {
  1634. mom = moment([2000, 1]).day(i);
  1635. regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
  1636. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  1637. }
  1638. // test the regex
  1639. if (this._weekdaysParse[i].test(weekdayName)) {
  1640. return i;
  1641. }
  1642. }
  1643. },
  1644. _longDateFormat : {
  1645. LT : "h:mm A",
  1646. L : "MM/DD/YYYY",
  1647. LL : "MMMM D YYYY",
  1648. LLL : "MMMM D YYYY LT",
  1649. LLLL : "dddd, MMMM D YYYY LT"
  1650. },
  1651. longDateFormat : function (key) {
  1652. var output = this._longDateFormat[key];
  1653. if (!output && this._longDateFormat[key.toUpperCase()]) {
  1654. output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) {
  1655. return val.slice(1);
  1656. });
  1657. this._longDateFormat[key] = output;
  1658. }
  1659. return output;
  1660. },
  1661. isPM : function (input) {
  1662. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  1663. // Using charAt should be more compatible.
  1664. return ((input + '').toLowerCase().charAt(0) === 'p');
  1665. },
  1666. _meridiemParse : /[ap]\.?m?\.?/i,
  1667. meridiem : function (hours, minutes, isLower) {
  1668. if (hours > 11) {
  1669. return isLower ? 'pm' : 'PM';
  1670. } else {
  1671. return isLower ? 'am' : 'AM';
  1672. }
  1673. },
  1674. _calendar : {
  1675. sameDay : '[Today at] LT',
  1676. nextDay : '[Tomorrow at] LT',
  1677. nextWeek : 'dddd [at] LT',
  1678. lastDay : '[Yesterday at] LT',
  1679. lastWeek : '[Last] dddd [at] LT',
  1680. sameElse : 'L'
  1681. },
  1682. calendar : function (key, mom) {
  1683. var output = this._calendar[key];
  1684. return typeof output === 'function' ? output.apply(mom) : output;
  1685. },
  1686. _relativeTime : {
  1687. future : "in %s",
  1688. past : "%s ago",
  1689. s : "a few seconds",
  1690. m : "a minute",
  1691. mm : "%d minutes",
  1692. h : "an hour",
  1693. hh : "%d hours",
  1694. d : "a day",
  1695. dd : "%d days",
  1696. M : "a month",
  1697. MM : "%d months",
  1698. y : "a year",
  1699. yy : "%d years"
  1700. },
  1701. relativeTime : function (number, withoutSuffix, string, isFuture) {
  1702. var output = this._relativeTime[string];
  1703. return (typeof output === 'function') ?
  1704. output(number, withoutSuffix, string, isFuture) :
  1705. output.replace(/%d/i, number);
  1706. },
  1707. pastFuture : function (diff, output) {
  1708. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  1709. return typeof format === 'function' ? format(output) : format.replace(/%s/i, output);
  1710. },
  1711. ordinal : function (number) {
  1712. return this._ordinal.replace("%d", number);
  1713. },
  1714. _ordinal : "%d",
  1715. preparse : function (string) {
  1716. return string;
  1717. },
  1718. postformat : function (string) {
  1719. return string;
  1720. },
  1721. week : function (mom) {
  1722. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  1723. },
  1724. _week : {
  1725. dow : 0, // Sunday is the first day of the week.
  1726. doy : 6 // The week that contains Jan 1st is the first week of the year.
  1727. }
  1728. });
  1729. // Loads a language definition into the `languages` cache. The function
  1730. // takes a key and optionally values. If not in the browser and no values
  1731. // are provided, it will load the language file module. As a convenience,
  1732. // this function also returns the language values.
  1733. function loadLang(key, values) {
  1734. values.abbr = key;
  1735. if (!languages[key]) {
  1736. languages[key] = new Language();
  1737. }
  1738. languages[key].set(values);
  1739. return languages[key];
  1740. }
  1741. // Remove a language from the `languages` cache. Mostly useful in tests.
  1742. function unloadLang(key) {
  1743. delete languages[key];
  1744. }
  1745. // Determines which language definition to use and returns it.
  1746. //
  1747. // With no parameters, it will return the global language. If you
  1748. // pass in a language key, such as 'en', it will return the
  1749. // definition for 'en', so long as 'en' has already been loaded using
  1750. // moment.lang.
  1751. function getLangDefinition(key) {
  1752. if (!key) {
  1753. return moment.fn._lang;
  1754. }
  1755. if (!languages[key] && hasModule) {
  1756. try {
  1757. require('./lang/' + key);
  1758. } catch (e) {
  1759. // call with no params to set to default
  1760. return moment.fn._lang;
  1761. }
  1762. }
  1763. return languages[key] || moment.fn._lang;
  1764. }
  1765. /************************************
  1766. Formatting
  1767. ************************************/
  1768. function removeFormattingTokens(input) {
  1769. if (input.match(/\[.*\]/)) {
  1770. return input.replace(/^\[|\]$/g, "");
  1771. }
  1772. return input.replace(/\\/g, "");
  1773. }
  1774. function makeFormatFunction(format) {
  1775. var array = format.match(formattingTokens), i, length;
  1776. for (i = 0, length = array.length; i < length; i++) {
  1777. if (formatTokenFunctions[array[i]]) {
  1778. array[i] = formatTokenFunctions[array[i]];
  1779. } else {
  1780. array[i] = removeFormattingTokens(array[i]);
  1781. }
  1782. }
  1783. return function (mom) {
  1784. var output = "";
  1785. for (i = 0; i < length; i++) {
  1786. output += array[i] instanceof Function ? array[i].call(mom, format) : array[i];
  1787. }
  1788. return output;
  1789. };
  1790. }
  1791. // format date using native date object
  1792. function formatMoment(m, format) {
  1793. format = expandFormat(format, m.lang());
  1794. if (!formatFunctions[format]) {
  1795. formatFunctions[format] = makeFormatFunction(format);
  1796. }
  1797. return formatFunctions[format](m);
  1798. }
  1799. function expandFormat(format, lang) {
  1800. var i = 5;
  1801. function replaceLongDateFormatTokens(input) {
  1802. return lang.longDateFormat(input) || input;
  1803. }
  1804. while (i-- && (localFormattingTokens.lastIndex = 0,
  1805. localFormattingTokens.test(format))) {
  1806. format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
  1807. }
  1808. return format;
  1809. }
  1810. /************************************
  1811. Parsing
  1812. ************************************/
  1813. // get the regex to find the next token
  1814. function getParseRegexForToken(token, config) {
  1815. switch (token) {
  1816. case 'DDDD':
  1817. return parseTokenThreeDigits;
  1818. case 'YYYY':
  1819. return parseTokenFourDigits;
  1820. case 'YYYYY':
  1821. return parseTokenSixDigits;
  1822. case 'S':
  1823. case 'SS':
  1824. case 'SSS':
  1825. case 'DDD':
  1826. return parseTokenOneToThreeDigits;
  1827. case 'MMM':
  1828. case 'MMMM':
  1829. case 'dd':
  1830. case 'ddd':
  1831. case 'dddd':
  1832. return parseTokenWord;
  1833. case 'a':
  1834. case 'A':
  1835. return getLangDefinition(config._l)._meridiemParse;
  1836. case 'X':
  1837. return parseTokenTimestampMs;
  1838. case 'Z':
  1839. case 'ZZ':
  1840. return parseTokenTimezone;
  1841. case 'T':
  1842. return parseTokenT;
  1843. case 'MM':
  1844. case 'DD':
  1845. case 'YY':
  1846. case 'HH':
  1847. case 'hh':
  1848. case 'mm':
  1849. case 'ss':
  1850. case 'M':
  1851. case 'D':
  1852. case 'd':
  1853. case 'H':
  1854. case 'h':
  1855. case 'm':
  1856. case 's':
  1857. return parseTokenOneOrTwoDigits;
  1858. default :
  1859. return new RegExp(token.replace('\\', ''));
  1860. }
  1861. }
  1862. function timezoneMinutesFromString(string) {
  1863. var tzchunk = (parseTokenTimezone.exec(string) || [])[0],
  1864. parts = (tzchunk + '').match(parseTimezoneChunker) || ['-', 0, 0],
  1865. minutes = +(parts[1] * 60) + ~~parts[2];
  1866. return parts[0] === '+' ? -minutes : minutes;
  1867. }
  1868. // function to convert string input to date
  1869. function addTimeToArrayFromToken(token, input, config) {
  1870. var a, datePartArray = config._a;
  1871. switch (token) {
  1872. // MONTH
  1873. case 'M' : // fall through to MM
  1874. case 'MM' :
  1875. if (input != null) {
  1876. datePartArray[1] = ~~input - 1;
  1877. }
  1878. break;
  1879. case 'MMM' : // fall through to MMMM
  1880. case 'MMMM' :
  1881. a = getLangDefinition(config._l).monthsParse(input);
  1882. // if we didn't find a month name, mark the date as invalid.
  1883. if (a != null) {
  1884. datePartArray[1] = a;
  1885. } else {
  1886. config._isValid = false;
  1887. }
  1888. break;
  1889. // DAY OF MONTH
  1890. case 'D' : // fall through to DD
  1891. case 'DD' :
  1892. if (input != null) {
  1893. datePartArray[2] = ~~input;
  1894. }
  1895. break;
  1896. // DAY OF YEAR
  1897. case 'DDD' : // fall through to DDDD
  1898. case 'DDDD' :
  1899. if (input != null) {
  1900. datePartArray[1] = 0;
  1901. datePartArray[2] = ~~input;
  1902. }
  1903. break;
  1904. // YEAR
  1905. case 'YY' :
  1906. datePartArray[0] = ~~input + (~~input > 68 ? 1900 : 2000);
  1907. break;
  1908. case 'YYYY' :
  1909. case 'YYYYY' :
  1910. datePartArray[0] = ~~input;
  1911. break;
  1912. // AM / PM
  1913. case 'a' : // fall through to A
  1914. case 'A' :
  1915. config._isPm = getLangDefinition(config._l).isPM(input);
  1916. break;
  1917. // 24 HOUR
  1918. case 'H' : // fall through to hh
  1919. case 'HH' : // fall through to hh
  1920. case 'h' : // fall through to hh
  1921. case 'hh' :
  1922. datePartArray[3] = ~~input;
  1923. break;
  1924. // MINUTE
  1925. case 'm' : // fall through to mm
  1926. case 'mm' :
  1927. datePartArray[4] = ~~input;
  1928. break;
  1929. // SECOND
  1930. case 's' : // fall through to ss
  1931. case 'ss' :
  1932. datePartArray[5] = ~~input;
  1933. break;
  1934. // MILLISECOND
  1935. case 'S' :
  1936. case 'SS' :
  1937. case 'SSS' :
  1938. datePartArray[6] = ~~ (('0.' + input) * 1000);
  1939. break;
  1940. // UNIX TIMESTAMP WITH MS
  1941. case 'X':
  1942. config._d = new Date(parseFloat(input) * 1000);
  1943. break;
  1944. // TIMEZONE
  1945. case 'Z' : // fall through to ZZ
  1946. case 'ZZ' :
  1947. config._useUTC = true;
  1948. config._tzm = timezoneMinutesFromString(input);
  1949. break;
  1950. }
  1951. // if the input is null, the date is not valid
  1952. if (input == null) {
  1953. config._isValid = false;
  1954. }
  1955. }
  1956. // convert an array to a date.
  1957. // the array should mirror the parameters below
  1958. // note: all values past the year are optional and will default to the lowest possible value.
  1959. // [year, month, day , hour, minute, second, millisecond]
  1960. function dateFromArray(config) {
  1961. var i, date, input = [], currentDate;
  1962. if (config._d) {
  1963. return;
  1964. }
  1965. // Default to current date.
  1966. // * if no year, month, day of month are given, default to today
  1967. // * if day of month is given, default month and year
  1968. // * if month is given, default only year
  1969. // * if year is given, don't default anything
  1970. currentDate = currentDateArray(config);
  1971. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  1972. config._a[i] = input[i] = currentDate[i];
  1973. }
  1974. // Zero out whatever was not defaulted, including time
  1975. for (; i < 7; i++) {
  1976. config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
  1977. }
  1978. // add the offsets to the time to be parsed so that we can have a clean array for checking isValid
  1979. input[3] += ~~((config._tzm || 0) / 60);
  1980. input[4] += ~~((config._tzm || 0) % 60);
  1981. date = new Date(0);
  1982. if (config._useUTC) {
  1983. date.setUTCFullYear(input[0], input[1], input[2]);
  1984. date.setUTCHours(input[3], input[4], input[5], input[6]);
  1985. } else {
  1986. date.setFullYear(input[0], input[1], input[2]);
  1987. date.setHours(input[3], input[4], input[5], input[6]);
  1988. }
  1989. config._d = date;
  1990. }
  1991. function dateFromObject(config) {
  1992. var o = config._i;
  1993. if (config._d) {
  1994. return;
  1995. }
  1996. config._a = [
  1997. o.years || o.year || o.y,
  1998. o.months || o.month || o.M,
  1999. o.days || o.day || o.d,
  2000. o.hours || o.hour || o.h,
  2001. o.minutes || o.minute || o.m,
  2002. o.seconds || o.second || o.s,
  2003. o.milliseconds || o.millisecond || o.ms
  2004. ];
  2005. dateFromArray(config);
  2006. }
  2007. function currentDateArray(config) {
  2008. var now = new Date();
  2009. if (config._useUTC) {
  2010. return [
  2011. now.getUTCFullYear(),
  2012. now.getUTCMonth(),
  2013. now.getUTCDate()
  2014. ];
  2015. } else {
  2016. return [now.getFullYear(), now.getMonth(), now.getDate()];
  2017. }
  2018. }
  2019. // date from string and format string
  2020. function makeDateFromStringAndFormat(config) {
  2021. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  2022. var lang = getLangDefinition(config._l),
  2023. string = '' + config._i,
  2024. i, parsedInput, tokens;
  2025. tokens = expandFormat(config._f, lang).match(formattingTokens);
  2026. config._a = [];
  2027. for (i = 0; i < tokens.length; i++) {
  2028. parsedInput = (getParseRegexForToken(tokens[i], config).exec(string) || [])[0];
  2029. if (parsedInput) {
  2030. string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
  2031. }
  2032. // don't parse if its not a known token
  2033. if (formatTokenFunctions[tokens[i]]) {
  2034. addTimeToArrayFromToken(tokens[i], parsedInput, config);
  2035. }
  2036. }
  2037. // add remaining unparsed input to the string
  2038. if (string) {
  2039. config._il = string;
  2040. }
  2041. // handle am pm
  2042. if (config._isPm && config._a[3] < 12) {
  2043. config._a[3] += 12;
  2044. }
  2045. // if is 12 am, change hours to 0
  2046. if (config._isPm === false && config._a[3] === 12) {
  2047. config._a[3] = 0;
  2048. }
  2049. // return
  2050. dateFromArray(config);
  2051. }
  2052. // date from string and array of format strings
  2053. function makeDateFromStringAndArray(config) {
  2054. var tempConfig,
  2055. tempMoment,
  2056. bestMoment,
  2057. scoreToBeat = 99,
  2058. i,
  2059. currentScore;
  2060. for (i = 0; i < config._f.length; i++) {
  2061. tempConfig = extend({}, config);
  2062. tempConfig._f = config._f[i];
  2063. makeDateFromStringAndFormat(tempConfig);
  2064. tempMoment = new Moment(tempConfig);
  2065. currentScore = compareArrays(tempConfig._a, tempMoment.toArray());
  2066. // if there is any input that was not parsed
  2067. // add a penalty for that format
  2068. if (tempMoment._il) {
  2069. currentScore += tempMoment._il.length;
  2070. }
  2071. if (currentScore < scoreToBeat) {
  2072. scoreToBeat = currentScore;
  2073. bestMoment = tempMoment;
  2074. }
  2075. }
  2076. extend(config, bestMoment);
  2077. }
  2078. // date from iso format
  2079. function makeDateFromString(config) {
  2080. var i,
  2081. string = config._i,
  2082. match = isoRegex.exec(string);
  2083. if (match) {
  2084. // match[2] should be "T" or undefined
  2085. config._f = 'YYYY-MM-DD' + (match[2] || " ");
  2086. for (i = 0; i < 4; i++) {
  2087. if (isoTimes[i][1].exec(string)) {
  2088. config._f += isoTimes[i][0];
  2089. break;
  2090. }
  2091. }
  2092. if (parseTokenTimezone.exec(string)) {
  2093. config._f += " Z";
  2094. }
  2095. makeDateFromStringAndFormat(config);
  2096. } else {
  2097. config._d = new Date(string);
  2098. }
  2099. }
  2100. function makeDateFromInput(config) {
  2101. var input = config._i,
  2102. matched = aspNetJsonRegex.exec(input);
  2103. if (input === undefined) {
  2104. config._d = new Date();
  2105. } else if (matched) {
  2106. config._d = new Date(+matched[1]);
  2107. } else if (typeof input === 'string') {
  2108. makeDateFromString(config);
  2109. } else if (isArray(input)) {
  2110. config._a = input.slice(0);
  2111. dateFromArray(config);
  2112. } else if (input instanceof Date) {
  2113. config._d = new Date(+input);
  2114. } else if (typeof(input) === 'object') {
  2115. dateFromObject(config);
  2116. } else {
  2117. config._d = new Date(input);
  2118. }
  2119. }
  2120. /************************************
  2121. Relative Time
  2122. ************************************/
  2123. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  2124. function substituteTimeAgo(string, number, withoutSuffix, isFuture, lang) {
  2125. return lang.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  2126. }
  2127. function relativeTime(milliseconds, withoutSuffix, lang) {
  2128. var seconds = round(Math.abs(milliseconds) / 1000),
  2129. minutes = round(seconds / 60),
  2130. hours = round(minutes / 60),
  2131. days = round(hours / 24),
  2132. years = round(days / 365),
  2133. args = seconds < 45 && ['s', seconds] ||
  2134. minutes === 1 && ['m'] ||
  2135. minutes < 45 && ['mm', minutes] ||
  2136. hours === 1 && ['h'] ||
  2137. hours < 22 && ['hh', hours] ||
  2138. days === 1 && ['d'] ||
  2139. days <= 25 && ['dd', days] ||
  2140. days <= 45 && ['M'] ||
  2141. days < 345 && ['MM', round(days / 30)] ||
  2142. years === 1 && ['y'] || ['yy', years];
  2143. args[2] = withoutSuffix;
  2144. args[3] = milliseconds > 0;
  2145. args[4] = lang;
  2146. return substituteTimeAgo.apply({}, args);
  2147. }
  2148. /************************************
  2149. Week of Year
  2150. ************************************/
  2151. // firstDayOfWeek 0 = sun, 6 = sat
  2152. // the day of the week that starts the week
  2153. // (usually sunday or monday)
  2154. // firstDayOfWeekOfYear 0 = sun, 6 = sat
  2155. // the first week is the week that contains the first
  2156. // of this day of the week
  2157. // (eg. ISO weeks use thursday (4))
  2158. function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) {
  2159. var end = firstDayOfWeekOfYear - firstDayOfWeek,
  2160. daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(),
  2161. adjustedMoment;
  2162. if (daysToDayOfWeek > end) {
  2163. daysToDayOfWeek -= 7;
  2164. }
  2165. if (daysToDayOfWeek < end - 7) {
  2166. daysToDayOfWeek += 7;
  2167. }
  2168. adjustedMoment = moment(mom).add('d', daysToDayOfWeek);
  2169. return {
  2170. week: Math.ceil(adjustedMoment.dayOfYear() / 7),
  2171. year: adjustedMoment.year()
  2172. };
  2173. }
  2174. /************************************
  2175. Top Level Functions
  2176. ************************************/
  2177. function makeMoment(config) {
  2178. var input = config._i,
  2179. format = config._f;
  2180. if (input === null || input === '') {
  2181. return null;
  2182. }
  2183. if (typeof input === 'string') {
  2184. config._i = input = getLangDefinition().preparse(input);
  2185. }
  2186. if (moment.isMoment(input)) {
  2187. config = extend({}, input);
  2188. config._d = new Date(+input._d);
  2189. } else if (format) {
  2190. if (isArray(format)) {
  2191. makeDateFromStringAndArray(config);
  2192. } else {
  2193. makeDateFromStringAndFormat(config);
  2194. }
  2195. } else {
  2196. makeDateFromInput(config);
  2197. }
  2198. return new Moment(config);
  2199. }
  2200. moment = function (input, format, lang) {
  2201. return makeMoment({
  2202. _i : input,
  2203. _f : format,
  2204. _l : lang,
  2205. _isUTC : false
  2206. });
  2207. };
  2208. // creating with utc
  2209. moment.utc = function (input, format, lang) {
  2210. return makeMoment({
  2211. _useUTC : true,
  2212. _isUTC : true,
  2213. _l : lang,
  2214. _i : input,
  2215. _f : format
  2216. }).utc();
  2217. };
  2218. // creating with unix timestamp (in seconds)
  2219. moment.unix = function (input) {
  2220. return moment(input * 1000);
  2221. };
  2222. // duration
  2223. moment.duration = function (input, key) {
  2224. var isDuration = moment.isDuration(input),
  2225. isNumber = (typeof input === 'number'),
  2226. duration = (isDuration ? input._input : (isNumber ? {} : input)),
  2227. matched = aspNetTimeSpanJsonRegex.exec(input),
  2228. sign,
  2229. ret;
  2230. if (isNumber) {
  2231. if (key) {
  2232. duration[key] = input;
  2233. } else {
  2234. duration.milliseconds = input;
  2235. }
  2236. } else if (matched) {
  2237. sign = (matched[1] === "-") ? -1 : 1;
  2238. duration = {
  2239. y: 0,
  2240. d: ~~matched[2] * sign,
  2241. h: ~~matched[3] * sign,
  2242. m: ~~matched[4] * sign,
  2243. s: ~~matched[5] * sign,
  2244. ms: ~~matched[6] * sign
  2245. };
  2246. }
  2247. ret = new Duration(duration);
  2248. if (isDuration && input.hasOwnProperty('_lang')) {
  2249. ret._lang = input._lang;
  2250. }
  2251. return ret;
  2252. };
  2253. // version number
  2254. moment.version = VERSION;
  2255. // default format
  2256. moment.defaultFormat = isoFormat;
  2257. // This function will be called whenever a moment is mutated.
  2258. // It is intended to keep the offset in sync with the timezone.
  2259. moment.updateOffset = function () {};
  2260. // This function will load languages and then set the global language. If
  2261. // no arguments are passed in, it will simply return the current global
  2262. // language key.
  2263. moment.lang = function (key, values) {
  2264. if (!key) {
  2265. return moment.fn._lang._abbr;
  2266. }
  2267. key = key.toLowerCase();
  2268. key = key.replace('_', '-');
  2269. if (values) {
  2270. loadLang(key, values);
  2271. } else if (values === null) {
  2272. unloadLang(key);
  2273. key = 'en';
  2274. } else if (!languages[key]) {
  2275. getLangDefinition(key);
  2276. }
  2277. moment.duration.fn._lang = moment.fn._lang = getLangDefinition(key);
  2278. };
  2279. // returns language data
  2280. moment.langData = function (key) {
  2281. if (key && key._lang && key._lang._abbr) {
  2282. key = key._lang._abbr;
  2283. }
  2284. return getLangDefinition(key);
  2285. };
  2286. // compare moment object
  2287. moment.isMoment = function (obj) {
  2288. return obj instanceof Moment;
  2289. };
  2290. // for typechecking Duration objects
  2291. moment.isDuration = function (obj) {
  2292. return obj instanceof Duration;
  2293. };
  2294. /************************************
  2295. Moment Prototype
  2296. ************************************/
  2297. extend(moment.fn = Moment.prototype, {
  2298. clone : function () {
  2299. return moment(this);
  2300. },
  2301. valueOf : function () {
  2302. return +this._d + ((this._offset || 0) * 60000);
  2303. },
  2304. unix : function () {
  2305. return Math.floor(+this / 1000);
  2306. },
  2307. toString : function () {
  2308. return this.format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ");
  2309. },
  2310. toDate : function () {
  2311. return this._offset ? new Date(+this) : this._d;
  2312. },
  2313. toISOString : function () {
  2314. return formatMoment(moment(this).utc(), 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  2315. },
  2316. toArray : function () {
  2317. var m = this;
  2318. return [
  2319. m.year(),
  2320. m.month(),
  2321. m.date(),
  2322. m.hours(),
  2323. m.minutes(),
  2324. m.seconds(),
  2325. m.milliseconds()
  2326. ];
  2327. },
  2328. isValid : function () {
  2329. if (this._isValid == null) {
  2330. if (this._a) {
  2331. this._isValid = !compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray());
  2332. } else {
  2333. this._isValid = !isNaN(this._d.getTime());
  2334. }
  2335. }
  2336. return !!this._isValid;
  2337. },
  2338. invalidAt: function () {
  2339. var i, arr1 = this._a, arr2 = (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray();
  2340. for (i = 6; i >= 0 && arr1[i] === arr2[i]; --i) {
  2341. // empty loop body
  2342. }
  2343. return i;
  2344. },
  2345. utc : function () {
  2346. return this.zone(0);
  2347. },
  2348. local : function () {
  2349. this.zone(0);
  2350. this._isUTC = false;
  2351. return this;
  2352. },
  2353. format : function (inputString) {
  2354. var output = formatMoment(this, inputString || moment.defaultFormat);
  2355. return this.lang().postformat(output);
  2356. },
  2357. add : function (input, val) {
  2358. var dur;
  2359. // switch args to support add('s', 1) and add(1, 's')
  2360. if (typeof input === 'string') {
  2361. dur = moment.duration(+val, input);
  2362. } else {
  2363. dur = moment.duration(input, val);
  2364. }
  2365. addOrSubtractDurationFromMoment(this, dur, 1);
  2366. return this;
  2367. },
  2368. subtract : function (input, val) {
  2369. var dur;
  2370. // switch args to support subtract('s', 1) and subtract(1, 's')
  2371. if (typeof input === 'string') {
  2372. dur = moment.duration(+val, input);
  2373. } else {
  2374. dur = moment.duration(input, val);
  2375. }
  2376. addOrSubtractDurationFromMoment(this, dur, -1);
  2377. return this;
  2378. },
  2379. diff : function (input, units, asFloat) {
  2380. var that = this._isUTC ? moment(input).zone(this._offset || 0) : moment(input).local(),
  2381. zoneDiff = (this.zone() - that.zone()) * 6e4,
  2382. diff, output;
  2383. units = normalizeUnits(units);
  2384. if (units === 'year' || units === 'month') {
  2385. // average number of days in the months in the given dates
  2386. diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2
  2387. // difference in months
  2388. output = ((this.year() - that.year()) * 12) + (this.month() - that.month());
  2389. // adjust by taking difference in days, average number of days
  2390. // and dst in the given months.
  2391. output += ((this - moment(this).startOf('month')) -
  2392. (that - moment(that).startOf('month'))) / diff;
  2393. // same as above but with zones, to negate all dst
  2394. output -= ((this.zone() - moment(this).startOf('month').zone()) -
  2395. (that.zone() - moment(that).startOf('month').zone())) * 6e4 / diff;
  2396. if (units === 'year') {
  2397. output = output / 12;
  2398. }
  2399. } else {
  2400. diff = (this - that);
  2401. output = units === 'second' ? diff / 1e3 : // 1000
  2402. units === 'minute' ? diff / 6e4 : // 1000 * 60
  2403. units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60
  2404. units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
  2405. units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
  2406. diff;
  2407. }
  2408. return asFloat ? output : absRound(output);
  2409. },
  2410. from : function (time, withoutSuffix) {
  2411. return moment.duration(this.diff(time)).lang(this.lang()._abbr).humanize(!withoutSuffix);
  2412. },
  2413. fromNow : function (withoutSuffix) {
  2414. return this.from(moment(), withoutSuffix);
  2415. },
  2416. calendar : function () {
  2417. var diff = this.diff(moment().zone(this.zone()).startOf('day'), 'days', true),
  2418. format = diff < -6 ? 'sameElse' :
  2419. diff < -1 ? 'lastWeek' :
  2420. diff < 0 ? 'lastDay' :
  2421. diff < 1 ? 'sameDay' :
  2422. diff < 2 ? 'nextDay' :
  2423. diff < 7 ? 'nextWeek' : 'sameElse';
  2424. return this.format(this.lang().calendar(format, this));
  2425. },
  2426. isLeapYear : function () {
  2427. var year = this.year();
  2428. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  2429. },
  2430. isDST : function () {
  2431. return (this.zone() < this.clone().month(0).zone() ||
  2432. this.zone() < this.clone().month(5).zone());
  2433. },
  2434. day : function (input) {
  2435. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  2436. if (input != null) {
  2437. if (typeof input === 'string') {
  2438. input = this.lang().weekdaysParse(input);
  2439. if (typeof input !== 'number') {
  2440. return this;
  2441. }
  2442. }
  2443. return this.add({ d : input - day });
  2444. } else {
  2445. return day;
  2446. }
  2447. },
  2448. month : function (input) {
  2449. var utc = this._isUTC ? 'UTC' : '',
  2450. dayOfMonth;
  2451. if (input != null) {
  2452. if (typeof input === 'string') {
  2453. input = this.lang().monthsParse(input);
  2454. if (typeof input !== 'number') {
  2455. return this;
  2456. }
  2457. }
  2458. dayOfMonth = this.date();
  2459. this.date(1);
  2460. this._d['set' + utc + 'Month'](input);
  2461. this.date(Math.min(dayOfMonth, this.daysInMonth()));
  2462. moment.updateOffset(this);
  2463. return this;
  2464. } else {
  2465. return this._d['get' + utc + 'Month']();
  2466. }
  2467. },
  2468. startOf: function (units) {
  2469. units = normalizeUnits(units);
  2470. // the following switch intentionally omits break keywords
  2471. // to utilize falling through the cases.
  2472. switch (units) {
  2473. case 'year':
  2474. this.month(0);
  2475. /* falls through */
  2476. case 'month':
  2477. this.date(1);
  2478. /* falls through */
  2479. case 'week':
  2480. case 'isoweek':
  2481. case 'day':
  2482. this.hours(0);
  2483. /* falls through */
  2484. case 'hour':
  2485. this.minutes(0);
  2486. /* falls through */
  2487. case 'minute':
  2488. this.seconds(0);
  2489. /* falls through */
  2490. case 'second':
  2491. this.milliseconds(0);
  2492. /* falls through */
  2493. }
  2494. // weeks are a special case
  2495. if (units === 'week') {
  2496. this.weekday(0);
  2497. } else if (units === 'isoweek') {
  2498. this.isoWeekday(1);
  2499. }
  2500. return this;
  2501. },
  2502. endOf: function (units) {
  2503. units = normalizeUnits(units);
  2504. return this.startOf(units).add((units === 'isoweek' ? 'week' : units), 1).subtract('ms', 1);
  2505. },
  2506. isAfter: function (input, units) {
  2507. units = typeof units !== 'undefined' ? units : 'millisecond';
  2508. return +this.clone().startOf(units) > +moment(input).startOf(units);
  2509. },
  2510. isBefore: function (input, units) {
  2511. units = typeof units !== 'undefined' ? units : 'millisecond';
  2512. return +this.clone().startOf(units) < +moment(input).startOf(units);
  2513. },
  2514. isSame: function (input, units) {
  2515. units = typeof units !== 'undefined' ? units : 'millisecond';
  2516. return +this.clone().startOf(units) === +moment(input).startOf(units);
  2517. },
  2518. min: function (other) {
  2519. other = moment.apply(null, arguments);
  2520. return other < this ? this : other;
  2521. },
  2522. max: function (other) {
  2523. other = moment.apply(null, arguments);
  2524. return other > this ? this : other;
  2525. },
  2526. zone : function (input) {
  2527. var offset = this._offset || 0;
  2528. if (input != null) {
  2529. if (typeof input === "string") {
  2530. input = timezoneMinutesFromString(input);
  2531. }
  2532. if (Math.abs(input) < 16) {
  2533. input = input * 60;
  2534. }
  2535. this._offset = input;
  2536. this._isUTC = true;
  2537. if (offset !== input) {
  2538. addOrSubtractDurationFromMoment(this, moment.duration(offset - input, 'm'), 1, true);
  2539. }
  2540. } else {
  2541. return this._isUTC ? offset : this._d.getTimezoneOffset();
  2542. }
  2543. return this;
  2544. },
  2545. zoneAbbr : function () {
  2546. return this._isUTC ? "UTC" : "";
  2547. },
  2548. zoneName : function () {
  2549. return this._isUTC ? "Coordinated Universal Time" : "";
  2550. },
  2551. hasAlignedHourOffset : function (input) {
  2552. if (!input) {
  2553. input = 0;
  2554. }
  2555. else {
  2556. input = moment(input).zone();
  2557. }
  2558. return (this.zone() - input) % 60 === 0;
  2559. },
  2560. daysInMonth : function () {
  2561. return moment.utc([this.year(), this.month() + 1, 0]).date();
  2562. },
  2563. dayOfYear : function (input) {
  2564. var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1;
  2565. return input == null ? dayOfYear : this.add("d", (input - dayOfYear));
  2566. },
  2567. weekYear : function (input) {
  2568. var year = weekOfYear(this, this.lang()._week.dow, this.lang()._week.doy).year;
  2569. return input == null ? year : this.add("y", (input - year));
  2570. },
  2571. isoWeekYear : function (input) {
  2572. var year = weekOfYear(this, 1, 4).year;
  2573. return input == null ? year : this.add("y", (input - year));
  2574. },
  2575. week : function (input) {
  2576. var week = this.lang().week(this);
  2577. return input == null ? week : this.add("d", (input - week) * 7);
  2578. },
  2579. isoWeek : function (input) {
  2580. var week = weekOfYear(this, 1, 4).week;
  2581. return input == null ? week : this.add("d", (input - week) * 7);
  2582. },
  2583. weekday : function (input) {
  2584. var weekday = (this._d.getDay() + 7 - this.lang()._week.dow) % 7;
  2585. return input == null ? weekday : this.add("d", input - weekday);
  2586. },
  2587. isoWeekday : function (input) {
  2588. // behaves the same as moment#day except
  2589. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  2590. // as a setter, sunday should belong to the previous week.
  2591. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7);
  2592. },
  2593. get : function (units) {
  2594. units = normalizeUnits(units);
  2595. return this[units.toLowerCase()]();
  2596. },
  2597. set : function (units, value) {
  2598. units = normalizeUnits(units);
  2599. this[units.toLowerCase()](value);
  2600. },
  2601. // If passed a language key, it will set the language for this
  2602. // instance. Otherwise, it will return the language configuration
  2603. // variables for this instance.
  2604. lang : function (key) {
  2605. if (key === undefined) {
  2606. return this._lang;
  2607. } else {
  2608. this._lang = getLangDefinition(key);
  2609. return this;
  2610. }
  2611. }
  2612. });
  2613. // helper for adding shortcuts
  2614. function makeGetterAndSetter(name, key) {
  2615. moment.fn[name] = moment.fn[name + 's'] = function (input) {
  2616. var utc = this._isUTC ? 'UTC' : '';
  2617. if (input != null) {
  2618. this._d['set' + utc + key](input);
  2619. moment.updateOffset(this);
  2620. return this;
  2621. } else {
  2622. return this._d['get' + utc + key]();
  2623. }
  2624. };
  2625. }
  2626. // loop through and add shortcuts (Month, Date, Hours, Minutes, Seconds, Milliseconds)
  2627. for (i = 0; i < proxyGettersAndSetters.length; i ++) {
  2628. makeGetterAndSetter(proxyGettersAndSetters[i].toLowerCase().replace(/s$/, ''), proxyGettersAndSetters[i]);
  2629. }
  2630. // add shortcut for year (uses different syntax than the getter/setter 'year' == 'FullYear')
  2631. makeGetterAndSetter('year', 'FullYear');
  2632. // add plural methods
  2633. moment.fn.days = moment.fn.day;
  2634. moment.fn.months = moment.fn.month;
  2635. moment.fn.weeks = moment.fn.week;
  2636. moment.fn.isoWeeks = moment.fn.isoWeek;
  2637. // add aliased format methods
  2638. moment.fn.toJSON = moment.fn.toISOString;
  2639. /************************************
  2640. Duration Prototype
  2641. ************************************/
  2642. extend(moment.duration.fn = Duration.prototype, {
  2643. _bubble : function () {
  2644. var milliseconds = this._milliseconds,
  2645. days = this._days,
  2646. months = this._months,
  2647. data = this._data,
  2648. seconds, minutes, hours, years;
  2649. // The following code bubbles up values, see the tests for
  2650. // examples of what that means.
  2651. data.milliseconds = milliseconds % 1000;
  2652. seconds = absRound(milliseconds / 1000);
  2653. data.seconds = seconds % 60;
  2654. minutes = absRound(seconds / 60);
  2655. data.minutes = minutes % 60;
  2656. hours = absRound(minutes / 60);
  2657. data.hours = hours % 24;
  2658. days += absRound(hours / 24);
  2659. data.days = days % 30;
  2660. months += absRound(days / 30);
  2661. data.months = months % 12;
  2662. years = absRound(months / 12);
  2663. data.years = years;
  2664. },
  2665. weeks : function () {
  2666. return absRound(this.days() / 7);
  2667. },
  2668. valueOf : function () {
  2669. return this._milliseconds +
  2670. this._days * 864e5 +
  2671. (this._months % 12) * 2592e6 +
  2672. ~~(this._months / 12) * 31536e6;
  2673. },
  2674. humanize : function (withSuffix) {
  2675. var difference = +this,
  2676. output = relativeTime(difference, !withSuffix, this.lang());
  2677. if (withSuffix) {
  2678. output = this.lang().pastFuture(difference, output);
  2679. }
  2680. return this.lang().postformat(output);
  2681. },
  2682. add : function (input, val) {
  2683. // supports only 2.0-style add(1, 's') or add(moment)
  2684. var dur = moment.duration(input, val);
  2685. this._milliseconds += dur._milliseconds;
  2686. this._days += dur._days;
  2687. this._months += dur._months;
  2688. this._bubble();
  2689. return this;
  2690. },
  2691. subtract : function (input, val) {
  2692. var dur = moment.duration(input, val);
  2693. this._milliseconds -= dur._milliseconds;
  2694. this._days -= dur._days;
  2695. this._months -= dur._months;
  2696. this._bubble();
  2697. return this;
  2698. },
  2699. get : function (units) {
  2700. units = normalizeUnits(units);
  2701. return this[units.toLowerCase() + 's']();
  2702. },
  2703. as : function (units) {
  2704. units = normalizeUnits(units);
  2705. return this['as' + units.charAt(0).toUpperCase() + units.slice(1) + 's']();
  2706. },
  2707. lang : moment.fn.lang
  2708. });
  2709. function makeDurationGetter(name) {
  2710. moment.duration.fn[name] = function () {
  2711. return this._data[name];
  2712. };
  2713. }
  2714. function makeDurationAsGetter(name, factor) {
  2715. moment.duration.fn['as' + name] = function () {
  2716. return +this / factor;
  2717. };
  2718. }
  2719. for (i in unitMillisecondFactors) {
  2720. if (unitMillisecondFactors.hasOwnProperty(i)) {
  2721. makeDurationAsGetter(i, unitMillisecondFactors[i]);
  2722. makeDurationGetter(i.toLowerCase());
  2723. }
  2724. }
  2725. makeDurationAsGetter('Weeks', 6048e5);
  2726. moment.duration.fn.asMonths = function () {
  2727. return (+this - this.years() * 31536e6) / 2592e6 + this.years() * 12;
  2728. };
  2729. /************************************
  2730. Default Lang
  2731. ************************************/
  2732. // Set default language, other languages will inherit from English.
  2733. moment.lang('en', {
  2734. ordinal : function (number) {
  2735. var b = number % 10,
  2736. output = (~~ (number % 100 / 10) === 1) ? 'th' :
  2737. (b === 1) ? 'st' :
  2738. (b === 2) ? 'nd' :
  2739. (b === 3) ? 'rd' : 'th';
  2740. return number + output;
  2741. }
  2742. });
  2743. /* EMBED_LANGUAGES */
  2744. /************************************
  2745. Exposing Moment
  2746. ************************************/
  2747. // CommonJS module is defined
  2748. if (hasModule) {
  2749. module.exports = moment;
  2750. }
  2751. /*global ender:false */
  2752. if (typeof ender === 'undefined') {
  2753. // here, `this` means `window` in the browser, or `global` on the server
  2754. // add `moment` as a global object via a string identifier,
  2755. // for Closure Compiler "advanced" mode
  2756. this['moment'] = moment;
  2757. }
  2758. /*global define:false */
  2759. if (typeof define === "function" && define.amd) {
  2760. define("moment", [], function () {
  2761. return moment;
  2762. });
  2763. }
  2764. }).call(this);
  2765. },{}],3:[function(require,module,exports){
  2766. /**
  2767. * vis.js module imports
  2768. */
  2769. // Try to load dependencies from the global window object.
  2770. // If not available there, load via require.
  2771. var moment = (typeof window !== 'undefined') && window['moment'] || require('moment');
  2772. var Hammer = (typeof window !== 'undefined') && window['Hammer'] || require('hammerjs');
  2773. // Internet Explorer 8 and older does not support Array.indexOf, so we define
  2774. // it here in that case.
  2775. // http://soledadpenades.com/2007/05/17/arrayindexof-in-internet-explorer/
  2776. if(!Array.prototype.indexOf) {
  2777. Array.prototype.indexOf = function(obj){
  2778. for(var i = 0; i < this.length; i++){
  2779. if(this[i] == obj){
  2780. return i;
  2781. }
  2782. }
  2783. return -1;
  2784. };
  2785. try {
  2786. console.log("Warning: Ancient browser detected. Please update your browser");
  2787. }
  2788. catch (err) {
  2789. }
  2790. }
  2791. // Internet Explorer 8 and older does not support Array.forEach, so we define
  2792. // it here in that case.
  2793. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach
  2794. if (!Array.prototype.forEach) {
  2795. Array.prototype.forEach = function(fn, scope) {
  2796. for(var i = 0, len = this.length; i < len; ++i) {
  2797. fn.call(scope || this, this[i], i, this);
  2798. }
  2799. }
  2800. }
  2801. // Internet Explorer 8 and older does not support Array.map, so we define it
  2802. // here in that case.
  2803. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map
  2804. // Production steps of ECMA-262, Edition 5, 15.4.4.19
  2805. // Reference: http://es5.github.com/#x15.4.4.19
  2806. if (!Array.prototype.map) {
  2807. Array.prototype.map = function(callback, thisArg) {
  2808. var T, A, k;
  2809. if (this == null) {
  2810. throw new TypeError(" this is null or not defined");
  2811. }
  2812. // 1. Let O be the result of calling ToObject passing the |this| value as the argument.
  2813. var O = Object(this);
  2814. // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
  2815. // 3. Let len be ToUint32(lenValue).
  2816. var len = O.length >>> 0;
  2817. // 4. If IsCallable(callback) is false, throw a TypeError exception.
  2818. // See: http://es5.github.com/#x9.11
  2819. if (typeof callback !== "function") {
  2820. throw new TypeError(callback + " is not a function");
  2821. }
  2822. // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
  2823. if (thisArg) {
  2824. T = thisArg;
  2825. }
  2826. // 6. Let A be a new array created as if by the expression new Array(len) where Array is
  2827. // the standard built-in constructor with that name and len is the value of len.
  2828. A = new Array(len);
  2829. // 7. Let k be 0
  2830. k = 0;
  2831. // 8. Repeat, while k < len
  2832. while(k < len) {
  2833. var kValue, mappedValue;
  2834. // a. Let Pk be ToString(k).
  2835. // This is implicit for LHS operands of the in operator
  2836. // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
  2837. // This step can be combined with c
  2838. // c. If kPresent is true, then
  2839. if (k in O) {
  2840. // i. Let kValue be the result of calling the Get internal method of O with argument Pk.
  2841. kValue = O[ k ];
  2842. // ii. Let mappedValue be the result of calling the Call internal method of callback
  2843. // with T as the this value and argument list containing kValue, k, and O.
  2844. mappedValue = callback.call(T, kValue, k, O);
  2845. // iii. Call the DefineOwnProperty internal method of A with arguments
  2846. // Pk, Property Descriptor {Value: mappedValue, : true, Enumerable: true, Configurable: true},
  2847. // and false.
  2848. // In browsers that support Object.defineProperty, use the following:
  2849. // Object.defineProperty(A, Pk, { value: mappedValue, writable: true, enumerable: true, configurable: true });
  2850. // For best browser support, use the following:
  2851. A[ k ] = mappedValue;
  2852. }
  2853. // d. Increase k by 1.
  2854. k++;
  2855. }
  2856. // 9. return A
  2857. return A;
  2858. };
  2859. }
  2860. // Internet Explorer 8 and older does not support Array.filter, so we define it
  2861. // here in that case.
  2862. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter
  2863. if (!Array.prototype.filter) {
  2864. Array.prototype.filter = function(fun /*, thisp */) {
  2865. "use strict";
  2866. if (this == null) {
  2867. throw new TypeError();
  2868. }
  2869. var t = Object(this);
  2870. var len = t.length >>> 0;
  2871. if (typeof fun != "function") {
  2872. throw new TypeError();
  2873. }
  2874. var res = [];
  2875. var thisp = arguments[1];
  2876. for (var i = 0; i < len; i++) {
  2877. if (i in t) {
  2878. var val = t[i]; // in case fun mutates this
  2879. if (fun.call(thisp, val, i, t))
  2880. res.push(val);
  2881. }
  2882. }
  2883. return res;
  2884. };
  2885. }
  2886. // Internet Explorer 8 and older does not support Object.keys, so we define it
  2887. // here in that case.
  2888. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/keys
  2889. if (!Object.keys) {
  2890. Object.keys = (function () {
  2891. var hasOwnProperty = Object.prototype.hasOwnProperty,
  2892. hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
  2893. dontEnums = [
  2894. 'toString',
  2895. 'toLocaleString',
  2896. 'valueOf',
  2897. 'hasOwnProperty',
  2898. 'isPrototypeOf',
  2899. 'propertyIsEnumerable',
  2900. 'constructor'
  2901. ],
  2902. dontEnumsLength = dontEnums.length;
  2903. return function (obj) {
  2904. if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) {
  2905. throw new TypeError('Object.keys called on non-object');
  2906. }
  2907. var result = [];
  2908. for (var prop in obj) {
  2909. if (hasOwnProperty.call(obj, prop)) result.push(prop);
  2910. }
  2911. if (hasDontEnumBug) {
  2912. for (var i=0; i < dontEnumsLength; i++) {
  2913. if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
  2914. }
  2915. }
  2916. return result;
  2917. }
  2918. })()
  2919. }
  2920. // Internet Explorer 8 and older does not support Array.isArray,
  2921. // so we define it here in that case.
  2922. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/isArray
  2923. if(!Array.isArray) {
  2924. Array.isArray = function (vArg) {
  2925. return Object.prototype.toString.call(vArg) === "[object Array]";
  2926. };
  2927. }
  2928. // Internet Explorer 8 and older does not support Function.bind,
  2929. // so we define it here in that case.
  2930. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind
  2931. if (!Function.prototype.bind) {
  2932. Function.prototype.bind = function (oThis) {
  2933. if (typeof this !== "function") {
  2934. // closest thing possible to the ECMAScript 5 internal IsCallable function
  2935. throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
  2936. }
  2937. var aArgs = Array.prototype.slice.call(arguments, 1),
  2938. fToBind = this,
  2939. fNOP = function () {},
  2940. fBound = function () {
  2941. return fToBind.apply(this instanceof fNOP && oThis
  2942. ? this
  2943. : oThis,
  2944. aArgs.concat(Array.prototype.slice.call(arguments)));
  2945. };
  2946. fNOP.prototype = this.prototype;
  2947. fBound.prototype = new fNOP();
  2948. return fBound;
  2949. };
  2950. }
  2951. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create
  2952. if (!Object.create) {
  2953. Object.create = function (o) {
  2954. if (arguments.length > 1) {
  2955. throw new Error('Object.create implementation only accepts the first parameter.');
  2956. }
  2957. function F() {}
  2958. F.prototype = o;
  2959. return new F();
  2960. };
  2961. }
  2962. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
  2963. if (!Function.prototype.bind) {
  2964. Function.prototype.bind = function (oThis) {
  2965. if (typeof this !== "function") {
  2966. // closest thing possible to the ECMAScript 5 internal IsCallable function
  2967. throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
  2968. }
  2969. var aArgs = Array.prototype.slice.call(arguments, 1),
  2970. fToBind = this,
  2971. fNOP = function () {},
  2972. fBound = function () {
  2973. return fToBind.apply(this instanceof fNOP && oThis
  2974. ? this
  2975. : oThis,
  2976. aArgs.concat(Array.prototype.slice.call(arguments)));
  2977. };
  2978. fNOP.prototype = this.prototype;
  2979. fBound.prototype = new fNOP();
  2980. return fBound;
  2981. };
  2982. }
  2983. /**
  2984. * utility functions
  2985. */
  2986. var util = {};
  2987. /**
  2988. * Test whether given object is a number
  2989. * @param {*} object
  2990. * @return {Boolean} isNumber
  2991. */
  2992. util.isNumber = function isNumber(object) {
  2993. return (object instanceof Number || typeof object == 'number');
  2994. };
  2995. /**
  2996. * Test whether given object is a string
  2997. * @param {*} object
  2998. * @return {Boolean} isString
  2999. */
  3000. util.isString = function isString(object) {
  3001. return (object instanceof String || typeof object == 'string');
  3002. };
  3003. /**
  3004. * Test whether given object is a Date, or a String containing a Date
  3005. * @param {Date | String} object
  3006. * @return {Boolean} isDate
  3007. */
  3008. util.isDate = function isDate(object) {
  3009. if (object instanceof Date) {
  3010. return true;
  3011. }
  3012. else if (util.isString(object)) {
  3013. // test whether this string contains a date
  3014. var match = ASPDateRegex.exec(object);
  3015. if (match) {
  3016. return true;
  3017. }
  3018. else if (!isNaN(Date.parse(object))) {
  3019. return true;
  3020. }
  3021. }
  3022. return false;
  3023. };
  3024. /**
  3025. * Test whether given object is an instance of google.visualization.DataTable
  3026. * @param {*} object
  3027. * @return {Boolean} isDataTable
  3028. */
  3029. util.isDataTable = function isDataTable(object) {
  3030. return (typeof (google) !== 'undefined') &&
  3031. (google.visualization) &&
  3032. (google.visualization.DataTable) &&
  3033. (object instanceof google.visualization.DataTable);
  3034. };
  3035. /**
  3036. * Create a semi UUID
  3037. * source: http://stackoverflow.com/a/105074/1262753
  3038. * @return {String} uuid
  3039. */
  3040. util.randomUUID = function randomUUID () {
  3041. var S4 = function () {
  3042. return Math.floor(
  3043. Math.random() * 0x10000 /* 65536 */
  3044. ).toString(16);
  3045. };
  3046. return (
  3047. S4() + S4() + '-' +
  3048. S4() + '-' +
  3049. S4() + '-' +
  3050. S4() + '-' +
  3051. S4() + S4() + S4()
  3052. );
  3053. };
  3054. /**
  3055. * Extend object a with the properties of object b or a series of objects
  3056. * Only properties with defined values are copied
  3057. * @param {Object} a
  3058. * @param {... Object} b
  3059. * @return {Object} a
  3060. */
  3061. util.extend = function (a, b) {
  3062. for (var i = 1, len = arguments.length; i < len; i++) {
  3063. var other = arguments[i];
  3064. for (var prop in other) {
  3065. if (other.hasOwnProperty(prop) && other[prop] !== undefined) {
  3066. a[prop] = other[prop];
  3067. }
  3068. }
  3069. }
  3070. return a;
  3071. };
  3072. /**
  3073. * Convert an object to another type
  3074. * @param {Boolean | Number | String | Date | Moment | Null | undefined} object
  3075. * @param {String | undefined} type Name of the type. Available types:
  3076. * 'Boolean', 'Number', 'String',
  3077. * 'Date', 'Moment', ISODate', 'ASPDate'.
  3078. * @return {*} object
  3079. * @throws Error
  3080. */
  3081. util.convert = function convert(object, type) {
  3082. var match;
  3083. if (object === undefined) {
  3084. return undefined;
  3085. }
  3086. if (object === null) {
  3087. return null;
  3088. }
  3089. if (!type) {
  3090. return object;
  3091. }
  3092. if (!(typeof type === 'string') && !(type instanceof String)) {
  3093. throw new Error('Type must be a string');
  3094. }
  3095. //noinspection FallthroughInSwitchStatementJS
  3096. switch (type) {
  3097. case 'boolean':
  3098. case 'Boolean':
  3099. return Boolean(object);
  3100. case 'number':
  3101. case 'Number':
  3102. return Number(object.valueOf());
  3103. case 'string':
  3104. case 'String':
  3105. return String(object);
  3106. case 'Date':
  3107. if (util.isNumber(object)) {
  3108. return new Date(object);
  3109. }
  3110. if (object instanceof Date) {
  3111. return new Date(object.valueOf());
  3112. }
  3113. else if (moment.isMoment(object)) {
  3114. return new Date(object.valueOf());
  3115. }
  3116. if (util.isString(object)) {
  3117. match = ASPDateRegex.exec(object);
  3118. if (match) {
  3119. // object is an ASP date
  3120. return new Date(Number(match[1])); // parse number
  3121. }
  3122. else {
  3123. return moment(object).toDate(); // parse string
  3124. }
  3125. }
  3126. else {
  3127. throw new Error(
  3128. 'Cannot convert object of type ' + util.getType(object) +
  3129. ' to type Date');
  3130. }
  3131. case 'Moment':
  3132. if (util.isNumber(object)) {
  3133. return moment(object);
  3134. }
  3135. if (object instanceof Date) {
  3136. return moment(object.valueOf());
  3137. }
  3138. else if (moment.isMoment(object)) {
  3139. return moment.clone();
  3140. }
  3141. if (util.isString(object)) {
  3142. match = ASPDateRegex.exec(object);
  3143. if (match) {
  3144. // object is an ASP date
  3145. return moment(Number(match[1])); // parse number
  3146. }
  3147. else {
  3148. return moment(object); // parse string
  3149. }
  3150. }
  3151. else {
  3152. throw new Error(
  3153. 'Cannot convert object of type ' + util.getType(object) +
  3154. ' to type Date');
  3155. }
  3156. case 'ISODate':
  3157. if (util.isNumber(object)) {
  3158. return new Date(object);
  3159. }
  3160. else if (object instanceof Date) {
  3161. return object.toISOString();
  3162. }
  3163. else if (moment.isMoment(object)) {
  3164. return object.toDate().toISOString();
  3165. }
  3166. else if (util.isString(object)) {
  3167. match = ASPDateRegex.exec(object);
  3168. if (match) {
  3169. // object is an ASP date
  3170. return new Date(Number(match[1])).toISOString(); // parse number
  3171. }
  3172. else {
  3173. return new Date(object).toISOString(); // parse string
  3174. }
  3175. }
  3176. else {
  3177. throw new Error(
  3178. 'Cannot convert object of type ' + util.getType(object) +
  3179. ' to type ISODate');
  3180. }
  3181. case 'ASPDate':
  3182. if (util.isNumber(object)) {
  3183. return '/Date(' + object + ')/';
  3184. }
  3185. else if (object instanceof Date) {
  3186. return '/Date(' + object.valueOf() + ')/';
  3187. }
  3188. else if (util.isString(object)) {
  3189. match = ASPDateRegex.exec(object);
  3190. var value;
  3191. if (match) {
  3192. // object is an ASP date
  3193. value = new Date(Number(match[1])).valueOf(); // parse number
  3194. }
  3195. else {
  3196. value = new Date(object).valueOf(); // parse string
  3197. }
  3198. return '/Date(' + value + ')/';
  3199. }
  3200. else {
  3201. throw new Error(
  3202. 'Cannot convert object of type ' + util.getType(object) +
  3203. ' to type ASPDate');
  3204. }
  3205. default:
  3206. throw new Error('Cannot convert object of type ' + util.getType(object) +
  3207. ' to type "' + type + '"');
  3208. }
  3209. };
  3210. // parse ASP.Net Date pattern,
  3211. // for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/'
  3212. // code from http://momentjs.com/
  3213. var ASPDateRegex = /^\/?Date\((\-?\d+)/i;
  3214. /**
  3215. * Get the type of an object, for example util.getType([]) returns 'Array'
  3216. * @param {*} object
  3217. * @return {String} type
  3218. */
  3219. util.getType = function getType(object) {
  3220. var type = typeof object;
  3221. if (type == 'object') {
  3222. if (object == null) {
  3223. return 'null';
  3224. }
  3225. if (object instanceof Boolean) {
  3226. return 'Boolean';
  3227. }
  3228. if (object instanceof Number) {
  3229. return 'Number';
  3230. }
  3231. if (object instanceof String) {
  3232. return 'String';
  3233. }
  3234. if (object instanceof Array) {
  3235. return 'Array';
  3236. }
  3237. if (object instanceof Date) {
  3238. return 'Date';
  3239. }
  3240. return 'Object';
  3241. }
  3242. else if (type == 'number') {
  3243. return 'Number';
  3244. }
  3245. else if (type == 'boolean') {
  3246. return 'Boolean';
  3247. }
  3248. else if (type == 'string') {
  3249. return 'String';
  3250. }
  3251. return type;
  3252. };
  3253. /**
  3254. * Retrieve the absolute left value of a DOM element
  3255. * @param {Element} elem A dom element, for example a div
  3256. * @return {number} left The absolute left position of this element
  3257. * in the browser page.
  3258. */
  3259. util.getAbsoluteLeft = function getAbsoluteLeft (elem) {
  3260. var doc = document.documentElement;
  3261. var body = document.body;
  3262. var left = elem.offsetLeft;
  3263. var e = elem.offsetParent;
  3264. while (e != null && e != body && e != doc) {
  3265. left += e.offsetLeft;
  3266. left -= e.scrollLeft;
  3267. e = e.offsetParent;
  3268. }
  3269. return left;
  3270. };
  3271. /**
  3272. * Retrieve the absolute top value of a DOM element
  3273. * @param {Element} elem A dom element, for example a div
  3274. * @return {number} top The absolute top position of this element
  3275. * in the browser page.
  3276. */
  3277. util.getAbsoluteTop = function getAbsoluteTop (elem) {
  3278. var doc = document.documentElement;
  3279. var body = document.body;
  3280. var top = elem.offsetTop;
  3281. var e = elem.offsetParent;
  3282. while (e != null && e != body && e != doc) {
  3283. top += e.offsetTop;
  3284. top -= e.scrollTop;
  3285. e = e.offsetParent;
  3286. }
  3287. return top;
  3288. };
  3289. /**
  3290. * Get the absolute, vertical mouse position from an event.
  3291. * @param {Event} event
  3292. * @return {Number} pageY
  3293. */
  3294. util.getPageY = function getPageY (event) {
  3295. if ('pageY' in event) {
  3296. return event.pageY;
  3297. }
  3298. else {
  3299. var clientY;
  3300. if (('targetTouches' in event) && event.targetTouches.length) {
  3301. clientY = event.targetTouches[0].clientY;
  3302. }
  3303. else {
  3304. clientY = event.clientY;
  3305. }
  3306. var doc = document.documentElement;
  3307. var body = document.body;
  3308. return clientY +
  3309. ( doc && doc.scrollTop || body && body.scrollTop || 0 ) -
  3310. ( doc && doc.clientTop || body && body.clientTop || 0 );
  3311. }
  3312. };
  3313. /**
  3314. * Get the absolute, horizontal mouse position from an event.
  3315. * @param {Event} event
  3316. * @return {Number} pageX
  3317. */
  3318. util.getPageX = function getPageX (event) {
  3319. if ('pageY' in event) {
  3320. return event.pageX;
  3321. }
  3322. else {
  3323. var clientX;
  3324. if (('targetTouches' in event) && event.targetTouches.length) {
  3325. clientX = event.targetTouches[0].clientX;
  3326. }
  3327. else {
  3328. clientX = event.clientX;
  3329. }
  3330. var doc = document.documentElement;
  3331. var body = document.body;
  3332. return clientX +
  3333. ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) -
  3334. ( doc && doc.clientLeft || body && body.clientLeft || 0 );
  3335. }
  3336. };
  3337. /**
  3338. * add a className to the given elements style
  3339. * @param {Element} elem
  3340. * @param {String} className
  3341. */
  3342. util.addClassName = function addClassName(elem, className) {
  3343. var classes = elem.className.split(' ');
  3344. if (classes.indexOf(className) == -1) {
  3345. classes.push(className); // add the class to the array
  3346. elem.className = classes.join(' ');
  3347. }
  3348. };
  3349. /**
  3350. * add a className to the given elements style
  3351. * @param {Element} elem
  3352. * @param {String} className
  3353. */
  3354. util.removeClassName = function removeClassname(elem, className) {
  3355. var classes = elem.className.split(' ');
  3356. var index = classes.indexOf(className);
  3357. if (index != -1) {
  3358. classes.splice(index, 1); // remove the class from the array
  3359. elem.className = classes.join(' ');
  3360. }
  3361. };
  3362. /**
  3363. * For each method for both arrays and objects.
  3364. * In case of an array, the built-in Array.forEach() is applied.
  3365. * In case of an Object, the method loops over all properties of the object.
  3366. * @param {Object | Array} object An Object or Array
  3367. * @param {function} callback Callback method, called for each item in
  3368. * the object or array with three parameters:
  3369. * callback(value, index, object)
  3370. */
  3371. util.forEach = function forEach (object, callback) {
  3372. var i,
  3373. len;
  3374. if (object instanceof Array) {
  3375. // array
  3376. for (i = 0, len = object.length; i < len; i++) {
  3377. callback(object[i], i, object);
  3378. }
  3379. }
  3380. else {
  3381. // object
  3382. for (i in object) {
  3383. if (object.hasOwnProperty(i)) {
  3384. callback(object[i], i, object);
  3385. }
  3386. }
  3387. }
  3388. };
  3389. /**
  3390. * Update a property in an object
  3391. * @param {Object} object
  3392. * @param {String} key
  3393. * @param {*} value
  3394. * @return {Boolean} changed
  3395. */
  3396. util.updateProperty = function updateProp (object, key, value) {
  3397. if (object[key] !== value) {
  3398. object[key] = value;
  3399. return true;
  3400. }
  3401. else {
  3402. return false;
  3403. }
  3404. };
  3405. /**
  3406. * Add and event listener. Works for all browsers
  3407. * @param {Element} element An html element
  3408. * @param {string} action The action, for example "click",
  3409. * without the prefix "on"
  3410. * @param {function} listener The callback function to be executed
  3411. * @param {boolean} [useCapture]
  3412. */
  3413. util.addEventListener = function addEventListener(element, action, listener, useCapture) {
  3414. if (element.addEventListener) {
  3415. if (useCapture === undefined)
  3416. useCapture = false;
  3417. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  3418. action = "DOMMouseScroll"; // For Firefox
  3419. }
  3420. element.addEventListener(action, listener, useCapture);
  3421. } else {
  3422. element.attachEvent("on" + action, listener); // IE browsers
  3423. }
  3424. };
  3425. /**
  3426. * Remove an event listener from an element
  3427. * @param {Element} element An html dom element
  3428. * @param {string} action The name of the event, for example "mousedown"
  3429. * @param {function} listener The listener function
  3430. * @param {boolean} [useCapture]
  3431. */
  3432. util.removeEventListener = function removeEventListener(element, action, listener, useCapture) {
  3433. if (element.removeEventListener) {
  3434. // non-IE browsers
  3435. if (useCapture === undefined)
  3436. useCapture = false;
  3437. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  3438. action = "DOMMouseScroll"; // For Firefox
  3439. }
  3440. element.removeEventListener(action, listener, useCapture);
  3441. } else {
  3442. // IE browsers
  3443. element.detachEvent("on" + action, listener);
  3444. }
  3445. };
  3446. /**
  3447. * Get HTML element which is the target of the event
  3448. * @param {Event} event
  3449. * @return {Element} target element
  3450. */
  3451. util.getTarget = function getTarget(event) {
  3452. // code from http://www.quirksmode.org/js/events_properties.html
  3453. if (!event) {
  3454. event = window.event;
  3455. }
  3456. var target;
  3457. if (event.target) {
  3458. target = event.target;
  3459. }
  3460. else if (event.srcElement) {
  3461. target = event.srcElement;
  3462. }
  3463. if (target.nodeType != undefined && target.nodeType == 3) {
  3464. // defeat Safari bug
  3465. target = target.parentNode;
  3466. }
  3467. return target;
  3468. };
  3469. /**
  3470. * Stop event propagation
  3471. */
  3472. util.stopPropagation = function stopPropagation(event) {
  3473. if (!event)
  3474. event = window.event;
  3475. if (event.stopPropagation) {
  3476. event.stopPropagation(); // non-IE browsers
  3477. }
  3478. else {
  3479. event.cancelBubble = true; // IE browsers
  3480. }
  3481. };
  3482. /**
  3483. * Cancels the event if it is cancelable, without stopping further propagation of the event.
  3484. */
  3485. util.preventDefault = function preventDefault (event) {
  3486. if (!event)
  3487. event = window.event;
  3488. if (event.preventDefault) {
  3489. event.preventDefault(); // non-IE browsers
  3490. }
  3491. else {
  3492. event.returnValue = false; // IE browsers
  3493. }
  3494. };
  3495. util.option = {};
  3496. /**
  3497. * Convert a value into a boolean
  3498. * @param {Boolean | function | undefined} value
  3499. * @param {Boolean} [defaultValue]
  3500. * @returns {Boolean} bool
  3501. */
  3502. util.option.asBoolean = function (value, defaultValue) {
  3503. if (typeof value == 'function') {
  3504. value = value();
  3505. }
  3506. if (value != null) {
  3507. return (value != false);
  3508. }
  3509. return defaultValue || null;
  3510. };
  3511. /**
  3512. * Convert a value into a number
  3513. * @param {Boolean | function | undefined} value
  3514. * @param {Number} [defaultValue]
  3515. * @returns {Number} number
  3516. */
  3517. util.option.asNumber = function (value, defaultValue) {
  3518. if (typeof value == 'function') {
  3519. value = value();
  3520. }
  3521. if (value != null) {
  3522. return Number(value) || defaultValue || null;
  3523. }
  3524. return defaultValue || null;
  3525. };
  3526. /**
  3527. * Convert a value into a string
  3528. * @param {String | function | undefined} value
  3529. * @param {String} [defaultValue]
  3530. * @returns {String} str
  3531. */
  3532. util.option.asString = function (value, defaultValue) {
  3533. if (typeof value == 'function') {
  3534. value = value();
  3535. }
  3536. if (value != null) {
  3537. return String(value);
  3538. }
  3539. return defaultValue || null;
  3540. };
  3541. /**
  3542. * Convert a size or location into a string with pixels or a percentage
  3543. * @param {String | Number | function | undefined} value
  3544. * @param {String} [defaultValue]
  3545. * @returns {String} size
  3546. */
  3547. util.option.asSize = function (value, defaultValue) {
  3548. if (typeof value == 'function') {
  3549. value = value();
  3550. }
  3551. if (util.isString(value)) {
  3552. return value;
  3553. }
  3554. else if (util.isNumber(value)) {
  3555. return value + 'px';
  3556. }
  3557. else {
  3558. return defaultValue || null;
  3559. }
  3560. };
  3561. /**
  3562. * Convert a value into a DOM element
  3563. * @param {HTMLElement | function | undefined} value
  3564. * @param {HTMLElement} [defaultValue]
  3565. * @returns {HTMLElement | null} dom
  3566. */
  3567. util.option.asElement = function (value, defaultValue) {
  3568. if (typeof value == 'function') {
  3569. value = value();
  3570. }
  3571. return value || defaultValue || null;
  3572. };
  3573. /**
  3574. * load css from text
  3575. * @param {String} css Text containing css
  3576. */
  3577. util.loadCss = function (css) {
  3578. if (typeof document === 'undefined') {
  3579. return;
  3580. }
  3581. // get the script location, and built the css file name from the js file name
  3582. // http://stackoverflow.com/a/2161748/1262753
  3583. // var scripts = document.getElementsByTagName('script');
  3584. // var jsFile = scripts[scripts.length-1].src.split('?')[0];
  3585. // var cssFile = jsFile.substring(0, jsFile.length - 2) + 'css';
  3586. // inject css
  3587. // http://stackoverflow.com/questions/524696/how-to-create-a-style-tag-with-javascript
  3588. var style = document.createElement('style');
  3589. style.type = 'text/css';
  3590. if (style.styleSheet){
  3591. style.styleSheet.cssText = css;
  3592. } else {
  3593. style.appendChild(document.createTextNode(css));
  3594. }
  3595. document.getElementsByTagName('head')[0].appendChild(style);
  3596. };
  3597. /**
  3598. * Event listener (singleton)
  3599. */
  3600. // TODO: replace usage of the event listener for the EventBus
  3601. var events = {
  3602. 'listeners': [],
  3603. /**
  3604. * Find a single listener by its object
  3605. * @param {Object} object
  3606. * @return {Number} index -1 when not found
  3607. */
  3608. 'indexOf': function (object) {
  3609. var listeners = this.listeners;
  3610. for (var i = 0, iMax = this.listeners.length; i < iMax; i++) {
  3611. var listener = listeners[i];
  3612. if (listener && listener.object == object) {
  3613. return i;
  3614. }
  3615. }
  3616. return -1;
  3617. },
  3618. /**
  3619. * Add an event listener
  3620. * @param {Object} object
  3621. * @param {String} event The name of an event, for example 'select'
  3622. * @param {function} callback The callback method, called when the
  3623. * event takes place
  3624. */
  3625. 'addListener': function (object, event, callback) {
  3626. var index = this.indexOf(object);
  3627. var listener = this.listeners[index];
  3628. if (!listener) {
  3629. listener = {
  3630. 'object': object,
  3631. 'events': {}
  3632. };
  3633. this.listeners.push(listener);
  3634. }
  3635. var callbacks = listener.events[event];
  3636. if (!callbacks) {
  3637. callbacks = [];
  3638. listener.events[event] = callbacks;
  3639. }
  3640. // add the callback if it does not yet exist
  3641. if (callbacks.indexOf(callback) == -1) {
  3642. callbacks.push(callback);
  3643. }
  3644. },
  3645. /**
  3646. * Remove an event listener
  3647. * @param {Object} object
  3648. * @param {String} event The name of an event, for example 'select'
  3649. * @param {function} callback The registered callback method
  3650. */
  3651. 'removeListener': function (object, event, callback) {
  3652. var index = this.indexOf(object);
  3653. var listener = this.listeners[index];
  3654. if (listener) {
  3655. var callbacks = listener.events[event];
  3656. if (callbacks) {
  3657. index = callbacks.indexOf(callback);
  3658. if (index != -1) {
  3659. callbacks.splice(index, 1);
  3660. }
  3661. // remove the array when empty
  3662. if (callbacks.length == 0) {
  3663. delete listener.events[event];
  3664. }
  3665. }
  3666. // count the number of registered events. remove listener when empty
  3667. var count = 0;
  3668. var events = listener.events;
  3669. for (var e in events) {
  3670. if (events.hasOwnProperty(e)) {
  3671. count++;
  3672. }
  3673. }
  3674. if (count == 0) {
  3675. delete this.listeners[index];
  3676. }
  3677. }
  3678. },
  3679. /**
  3680. * Remove all registered event listeners
  3681. */
  3682. 'removeAllListeners': function () {
  3683. this.listeners = [];
  3684. },
  3685. /**
  3686. * Trigger an event. All registered event handlers will be called
  3687. * @param {Object} object
  3688. * @param {String} event
  3689. * @param {Object} properties (optional)
  3690. */
  3691. 'trigger': function (object, event, properties) {
  3692. var index = this.indexOf(object);
  3693. var listener = this.listeners[index];
  3694. if (listener) {
  3695. var callbacks = listener.events[event];
  3696. if (callbacks) {
  3697. for (var i = 0, iMax = callbacks.length; i < iMax; i++) {
  3698. callbacks[i](properties);
  3699. }
  3700. }
  3701. }
  3702. }
  3703. };
  3704. /**
  3705. * An event bus can be used to emit events, and to subscribe to events
  3706. * @constructor EventBus
  3707. */
  3708. function EventBus() {
  3709. this.subscriptions = [];
  3710. }
  3711. /**
  3712. * Subscribe to an event
  3713. * @param {String | RegExp} event The event can be a regular expression, or
  3714. * a string with wildcards, like 'server.*'.
  3715. * @param {function} callback. Callback are called with three parameters:
  3716. * {String} event, {*} [data], {*} [source]
  3717. * @param {*} [target]
  3718. * @returns {String} id A subscription id
  3719. */
  3720. EventBus.prototype.on = function (event, callback, target) {
  3721. var regexp = (event instanceof RegExp) ?
  3722. event :
  3723. new RegExp(event.replace('*', '\\w+'));
  3724. var subscription = {
  3725. id: util.randomUUID(),
  3726. event: event,
  3727. regexp: regexp,
  3728. callback: (typeof callback === 'function') ? callback : null,
  3729. target: target
  3730. };
  3731. this.subscriptions.push(subscription);
  3732. return subscription.id;
  3733. };
  3734. /**
  3735. * Unsubscribe from an event
  3736. * @param {String | Object} filter Filter for subscriptions to be removed
  3737. * Filter can be a string containing a
  3738. * subscription id, or an object containing
  3739. * one or more of the fields id, event,
  3740. * callback, and target.
  3741. */
  3742. EventBus.prototype.off = function (filter) {
  3743. var i = 0;
  3744. while (i < this.subscriptions.length) {
  3745. var subscription = this.subscriptions[i];
  3746. var match = true;
  3747. if (filter instanceof Object) {
  3748. // filter is an object. All fields must match
  3749. for (var prop in filter) {
  3750. if (filter.hasOwnProperty(prop)) {
  3751. if (filter[prop] !== subscription[prop]) {
  3752. match = false;
  3753. }
  3754. }
  3755. }
  3756. }
  3757. else {
  3758. // filter is a string, filter on id
  3759. match = (subscription.id == filter);
  3760. }
  3761. if (match) {
  3762. this.subscriptions.splice(i, 1);
  3763. }
  3764. else {
  3765. i++;
  3766. }
  3767. }
  3768. };
  3769. /**
  3770. * Emit an event
  3771. * @param {String} event
  3772. * @param {*} [data]
  3773. * @param {*} [source]
  3774. */
  3775. EventBus.prototype.emit = function (event, data, source) {
  3776. for (var i =0; i < this.subscriptions.length; i++) {
  3777. var subscription = this.subscriptions[i];
  3778. if (subscription.regexp.test(event)) {
  3779. if (subscription.callback) {
  3780. subscription.callback(event, data, source);
  3781. }
  3782. }
  3783. }
  3784. };
  3785. /**
  3786. * DataSet
  3787. *
  3788. * Usage:
  3789. * var dataSet = new DataSet({
  3790. * fieldId: '_id',
  3791. * convert: {
  3792. * // ...
  3793. * }
  3794. * });
  3795. *
  3796. * dataSet.add(item);
  3797. * dataSet.add(data);
  3798. * dataSet.update(item);
  3799. * dataSet.update(data);
  3800. * dataSet.remove(id);
  3801. * dataSet.remove(ids);
  3802. * var data = dataSet.get();
  3803. * var data = dataSet.get(id);
  3804. * var data = dataSet.get(ids);
  3805. * var data = dataSet.get(ids, options, data);
  3806. * dataSet.clear();
  3807. *
  3808. * A data set can:
  3809. * - add/remove/update data
  3810. * - gives triggers upon changes in the data
  3811. * - can import/export data in various data formats
  3812. *
  3813. * @param {Object} [options] Available options:
  3814. * {String} fieldId Field name of the id in the
  3815. * items, 'id' by default.
  3816. * {Object.<String, String} convert
  3817. * A map with field names as key,
  3818. * and the field type as value.
  3819. * @constructor DataSet
  3820. */
  3821. // TODO: add a DataSet constructor DataSet(data, options)
  3822. function DataSet (options) {
  3823. this.id = util.randomUUID();
  3824. this.options = options || {};
  3825. this.data = {}; // map with data indexed by id
  3826. this.fieldId = this.options.fieldId || 'id'; // name of the field containing id
  3827. this.convert = {}; // field types by field name
  3828. if (this.options.convert) {
  3829. for (var field in this.options.convert) {
  3830. if (this.options.convert.hasOwnProperty(field)) {
  3831. var value = this.options.convert[field];
  3832. if (value == 'Date' || value == 'ISODate' || value == 'ASPDate') {
  3833. this.convert[field] = 'Date';
  3834. }
  3835. else {
  3836. this.convert[field] = value;
  3837. }
  3838. }
  3839. }
  3840. }
  3841. // event subscribers
  3842. this.subscribers = {};
  3843. this.internalIds = {}; // internally generated id's
  3844. }
  3845. /**
  3846. * Subscribe to an event, add an event listener
  3847. * @param {String} event Event name. Available events: 'put', 'update',
  3848. * 'remove'
  3849. * @param {function} callback Callback method. Called with three parameters:
  3850. * {String} event
  3851. * {Object | null} params
  3852. * {String | Number} senderId
  3853. */
  3854. DataSet.prototype.subscribe = function (event, callback) {
  3855. var subscribers = this.subscribers[event];
  3856. if (!subscribers) {
  3857. subscribers = [];
  3858. this.subscribers[event] = subscribers;
  3859. }
  3860. subscribers.push({
  3861. callback: callback
  3862. });
  3863. };
  3864. /**
  3865. * Unsubscribe from an event, remove an event listener
  3866. * @param {String} event
  3867. * @param {function} callback
  3868. */
  3869. DataSet.prototype.unsubscribe = function (event, callback) {
  3870. var subscribers = this.subscribers[event];
  3871. if (subscribers) {
  3872. this.subscribers[event] = subscribers.filter(function (listener) {
  3873. return (listener.callback != callback);
  3874. });
  3875. }
  3876. };
  3877. /**
  3878. * Trigger an event
  3879. * @param {String} event
  3880. * @param {Object | null} params
  3881. * @param {String} [senderId] Optional id of the sender.
  3882. * @private
  3883. */
  3884. DataSet.prototype._trigger = function (event, params, senderId) {
  3885. if (event == '*') {
  3886. throw new Error('Cannot trigger event *');
  3887. }
  3888. var subscribers = [];
  3889. if (event in this.subscribers) {
  3890. subscribers = subscribers.concat(this.subscribers[event]);
  3891. }
  3892. if ('*' in this.subscribers) {
  3893. subscribers = subscribers.concat(this.subscribers['*']);
  3894. }
  3895. for (var i = 0; i < subscribers.length; i++) {
  3896. var subscriber = subscribers[i];
  3897. if (subscriber.callback) {
  3898. subscriber.callback(event, params, senderId || null);
  3899. }
  3900. }
  3901. };
  3902. /**
  3903. * Add data.
  3904. * Adding an item will fail when there already is an item with the same id.
  3905. * @param {Object | Array | DataTable} data
  3906. * @param {String} [senderId] Optional sender id
  3907. * @return {Array} addedIds Array with the ids of the added items
  3908. */
  3909. DataSet.prototype.add = function (data, senderId) {
  3910. var addedIds = [],
  3911. id,
  3912. me = this;
  3913. if (data instanceof Array) {
  3914. // Array
  3915. for (var i = 0, len = data.length; i < len; i++) {
  3916. id = me._addItem(data[i]);
  3917. addedIds.push(id);
  3918. }
  3919. }
  3920. else if (util.isDataTable(data)) {
  3921. // Google DataTable
  3922. var columns = this._getColumnNames(data);
  3923. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  3924. var item = {};
  3925. for (var col = 0, cols = columns.length; col < cols; col++) {
  3926. var field = columns[col];
  3927. item[field] = data.getValue(row, col);
  3928. }
  3929. id = me._addItem(item);
  3930. addedIds.push(id);
  3931. }
  3932. }
  3933. else if (data instanceof Object) {
  3934. // Single item
  3935. id = me._addItem(data);
  3936. addedIds.push(id);
  3937. }
  3938. else {
  3939. throw new Error('Unknown dataType');
  3940. }
  3941. if (addedIds.length) {
  3942. this._trigger('add', {items: addedIds}, senderId);
  3943. }
  3944. return addedIds;
  3945. };
  3946. /**
  3947. * Update existing items. When an item does not exist, it will be created
  3948. * @param {Object | Array | DataTable} data
  3949. * @param {String} [senderId] Optional sender id
  3950. * @return {Array} updatedIds The ids of the added or updated items
  3951. */
  3952. DataSet.prototype.update = function (data, senderId) {
  3953. var addedIds = [],
  3954. updatedIds = [],
  3955. me = this,
  3956. fieldId = me.fieldId;
  3957. var addOrUpdate = function (item) {
  3958. var id = item[fieldId];
  3959. if (me.data[id]) {
  3960. // update item
  3961. id = me._updateItem(item);
  3962. updatedIds.push(id);
  3963. }
  3964. else {
  3965. // add new item
  3966. id = me._addItem(item);
  3967. addedIds.push(id);
  3968. }
  3969. };
  3970. if (data instanceof Array) {
  3971. // Array
  3972. for (var i = 0, len = data.length; i < len; i++) {
  3973. addOrUpdate(data[i]);
  3974. }
  3975. }
  3976. else if (util.isDataTable(data)) {
  3977. // Google DataTable
  3978. var columns = this._getColumnNames(data);
  3979. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  3980. var item = {};
  3981. for (var col = 0, cols = columns.length; col < cols; col++) {
  3982. var field = columns[col];
  3983. item[field] = data.getValue(row, col);
  3984. }
  3985. addOrUpdate(item);
  3986. }
  3987. }
  3988. else if (data instanceof Object) {
  3989. // Single item
  3990. addOrUpdate(data);
  3991. }
  3992. else {
  3993. throw new Error('Unknown dataType');
  3994. }
  3995. if (addedIds.length) {
  3996. this._trigger('add', {items: addedIds}, senderId);
  3997. }
  3998. if (updatedIds.length) {
  3999. this._trigger('update', {items: updatedIds}, senderId);
  4000. }
  4001. return addedIds.concat(updatedIds);
  4002. };
  4003. /**
  4004. * Get a data item or multiple items.
  4005. *
  4006. * Usage:
  4007. *
  4008. * get()
  4009. * get(options: Object)
  4010. * get(options: Object, data: Array | DataTable)
  4011. *
  4012. * get(id: Number | String)
  4013. * get(id: Number | String, options: Object)
  4014. * get(id: Number | String, options: Object, data: Array | DataTable)
  4015. *
  4016. * get(ids: Number[] | String[])
  4017. * get(ids: Number[] | String[], options: Object)
  4018. * get(ids: Number[] | String[], options: Object, data: Array | DataTable)
  4019. *
  4020. * Where:
  4021. *
  4022. * {Number | String} id The id of an item
  4023. * {Number[] | String{}} ids An array with ids of items
  4024. * {Object} options An Object with options. Available options:
  4025. * {String} [type] Type of data to be returned. Can
  4026. * be 'DataTable' or 'Array' (default)
  4027. * {Object.<String, String>} [convert]
  4028. * {String[]} [fields] field names to be returned
  4029. * {function} [filter] filter items
  4030. * {String | function} [order] Order the items by
  4031. * a field name or custom sort function.
  4032. * {Array | DataTable} [data] If provided, items will be appended to this
  4033. * array or table. Required in case of Google
  4034. * DataTable.
  4035. *
  4036. * @throws Error
  4037. */
  4038. DataSet.prototype.get = function (args) {
  4039. var me = this;
  4040. // parse the arguments
  4041. var id, ids, options, data;
  4042. var firstType = util.getType(arguments[0]);
  4043. if (firstType == 'String' || firstType == 'Number') {
  4044. // get(id [, options] [, data])
  4045. id = arguments[0];
  4046. options = arguments[1];
  4047. data = arguments[2];
  4048. }
  4049. else if (firstType == 'Array') {
  4050. // get(ids [, options] [, data])
  4051. ids = arguments[0];
  4052. options = arguments[1];
  4053. data = arguments[2];
  4054. }
  4055. else {
  4056. // get([, options] [, data])
  4057. options = arguments[0];
  4058. data = arguments[1];
  4059. }
  4060. // determine the return type
  4061. var type;
  4062. if (options && options.type) {
  4063. type = (options.type == 'DataTable') ? 'DataTable' : 'Array';
  4064. if (data && (type != util.getType(data))) {
  4065. throw new Error('Type of parameter "data" (' + util.getType(data) + ') ' +
  4066. 'does not correspond with specified options.type (' + options.type + ')');
  4067. }
  4068. if (type == 'DataTable' && !util.isDataTable(data)) {
  4069. throw new Error('Parameter "data" must be a DataTable ' +
  4070. 'when options.type is "DataTable"');
  4071. }
  4072. }
  4073. else if (data) {
  4074. type = (util.getType(data) == 'DataTable') ? 'DataTable' : 'Array';
  4075. }
  4076. else {
  4077. type = 'Array';
  4078. }
  4079. // build options
  4080. var convert = options && options.convert || this.options.convert;
  4081. var filter = options && options.filter;
  4082. var items = [], item, itemId, i, len;
  4083. // convert items
  4084. if (id != undefined) {
  4085. // return a single item
  4086. item = me._getItem(id, convert);
  4087. if (filter && !filter(item)) {
  4088. item = null;
  4089. }
  4090. }
  4091. else if (ids != undefined) {
  4092. // return a subset of items
  4093. for (i = 0, len = ids.length; i < len; i++) {
  4094. item = me._getItem(ids[i], convert);
  4095. if (!filter || filter(item)) {
  4096. items.push(item);
  4097. }
  4098. }
  4099. }
  4100. else {
  4101. // return all items
  4102. for (itemId in this.data) {
  4103. if (this.data.hasOwnProperty(itemId)) {
  4104. item = me._getItem(itemId, convert);
  4105. if (!filter || filter(item)) {
  4106. items.push(item);
  4107. }
  4108. }
  4109. }
  4110. }
  4111. // order the results
  4112. if (options && options.order && id == undefined) {
  4113. this._sort(items, options.order);
  4114. }
  4115. // filter fields of the items
  4116. if (options && options.fields) {
  4117. var fields = options.fields;
  4118. if (id != undefined) {
  4119. item = this._filterFields(item, fields);
  4120. }
  4121. else {
  4122. for (i = 0, len = items.length; i < len; i++) {
  4123. items[i] = this._filterFields(items[i], fields);
  4124. }
  4125. }
  4126. }
  4127. // return the results
  4128. if (type == 'DataTable') {
  4129. var columns = this._getColumnNames(data);
  4130. if (id != undefined) {
  4131. // append a single item to the data table
  4132. me._appendRow(data, columns, item);
  4133. }
  4134. else {
  4135. // copy the items to the provided data table
  4136. for (i = 0, len = items.length; i < len; i++) {
  4137. me._appendRow(data, columns, items[i]);
  4138. }
  4139. }
  4140. return data;
  4141. }
  4142. else {
  4143. // return an array
  4144. if (id != undefined) {
  4145. // a single item
  4146. return item;
  4147. }
  4148. else {
  4149. // multiple items
  4150. if (data) {
  4151. // copy the items to the provided array
  4152. for (i = 0, len = items.length; i < len; i++) {
  4153. data.push(items[i]);
  4154. }
  4155. return data;
  4156. }
  4157. else {
  4158. // just return our array
  4159. return items;
  4160. }
  4161. }
  4162. }
  4163. };
  4164. /**
  4165. * Get ids of all items or from a filtered set of items.
  4166. * @param {Object} [options] An Object with options. Available options:
  4167. * {function} [filter] filter items
  4168. * {String | function} [order] Order the items by
  4169. * a field name or custom sort function.
  4170. * @return {Array} ids
  4171. */
  4172. DataSet.prototype.getIds = function (options) {
  4173. var data = this.data,
  4174. filter = options && options.filter,
  4175. order = options && options.order,
  4176. convert = options && options.convert || this.options.convert,
  4177. i,
  4178. len,
  4179. id,
  4180. item,
  4181. items,
  4182. ids = [];
  4183. if (filter) {
  4184. // get filtered items
  4185. if (order) {
  4186. // create ordered list
  4187. items = [];
  4188. for (id in data) {
  4189. if (data.hasOwnProperty(id)) {
  4190. item = this._getItem(id, convert);
  4191. if (filter(item)) {
  4192. items.push(item);
  4193. }
  4194. }
  4195. }
  4196. this._sort(items, order);
  4197. for (i = 0, len = items.length; i < len; i++) {
  4198. ids[i] = items[i][this.fieldId];
  4199. }
  4200. }
  4201. else {
  4202. // create unordered list
  4203. for (id in data) {
  4204. if (data.hasOwnProperty(id)) {
  4205. item = this._getItem(id, convert);
  4206. if (filter(item)) {
  4207. ids.push(item[this.fieldId]);
  4208. }
  4209. }
  4210. }
  4211. }
  4212. }
  4213. else {
  4214. // get all items
  4215. if (order) {
  4216. // create an ordered list
  4217. items = [];
  4218. for (id in data) {
  4219. if (data.hasOwnProperty(id)) {
  4220. items.push(data[id]);
  4221. }
  4222. }
  4223. this._sort(items, order);
  4224. for (i = 0, len = items.length; i < len; i++) {
  4225. ids[i] = items[i][this.fieldId];
  4226. }
  4227. }
  4228. else {
  4229. // create unordered list
  4230. for (id in data) {
  4231. if (data.hasOwnProperty(id)) {
  4232. item = data[id];
  4233. ids.push(item[this.fieldId]);
  4234. }
  4235. }
  4236. }
  4237. }
  4238. return ids;
  4239. };
  4240. /**
  4241. * Execute a callback function for every item in the dataset.
  4242. * The order of the items is not determined.
  4243. * @param {function} callback
  4244. * @param {Object} [options] Available options:
  4245. * {Object.<String, String>} [convert]
  4246. * {String[]} [fields] filter fields
  4247. * {function} [filter] filter items
  4248. * {String | function} [order] Order the items by
  4249. * a field name or custom sort function.
  4250. */
  4251. DataSet.prototype.forEach = function (callback, options) {
  4252. var filter = options && options.filter,
  4253. convert = options && options.convert || this.options.convert,
  4254. data = this.data,
  4255. item,
  4256. id;
  4257. if (options && options.order) {
  4258. // execute forEach on ordered list
  4259. var items = this.get(options);
  4260. for (var i = 0, len = items.length; i < len; i++) {
  4261. item = items[i];
  4262. id = item[this.fieldId];
  4263. callback(item, id);
  4264. }
  4265. }
  4266. else {
  4267. // unordered
  4268. for (id in data) {
  4269. if (data.hasOwnProperty(id)) {
  4270. item = this._getItem(id, convert);
  4271. if (!filter || filter(item)) {
  4272. callback(item, id);
  4273. }
  4274. }
  4275. }
  4276. }
  4277. };
  4278. /**
  4279. * Map every item in the dataset.
  4280. * @param {function} callback
  4281. * @param {Object} [options] Available options:
  4282. * {Object.<String, String>} [convert]
  4283. * {String[]} [fields] filter fields
  4284. * {function} [filter] filter items
  4285. * {String | function} [order] Order the items by
  4286. * a field name or custom sort function.
  4287. * @return {Object[]} mappedItems
  4288. */
  4289. DataSet.prototype.map = function (callback, options) {
  4290. var filter = options && options.filter,
  4291. convert = options && options.convert || this.options.convert,
  4292. mappedItems = [],
  4293. data = this.data,
  4294. item;
  4295. // convert and filter items
  4296. for (var id in data) {
  4297. if (data.hasOwnProperty(id)) {
  4298. item = this._getItem(id, convert);
  4299. if (!filter || filter(item)) {
  4300. mappedItems.push(callback(item, id));
  4301. }
  4302. }
  4303. }
  4304. // order items
  4305. if (options && options.order) {
  4306. this._sort(mappedItems, options.order);
  4307. }
  4308. return mappedItems;
  4309. };
  4310. /**
  4311. * Filter the fields of an item
  4312. * @param {Object} item
  4313. * @param {String[]} fields Field names
  4314. * @return {Object} filteredItem
  4315. * @private
  4316. */
  4317. DataSet.prototype._filterFields = function (item, fields) {
  4318. var filteredItem = {};
  4319. for (var field in item) {
  4320. if (item.hasOwnProperty(field) && (fields.indexOf(field) != -1)) {
  4321. filteredItem[field] = item[field];
  4322. }
  4323. }
  4324. return filteredItem;
  4325. };
  4326. /**
  4327. * Sort the provided array with items
  4328. * @param {Object[]} items
  4329. * @param {String | function} order A field name or custom sort function.
  4330. * @private
  4331. */
  4332. DataSet.prototype._sort = function (items, order) {
  4333. if (util.isString(order)) {
  4334. // order by provided field name
  4335. var name = order; // field name
  4336. items.sort(function (a, b) {
  4337. var av = a[name];
  4338. var bv = b[name];
  4339. return (av > bv) ? 1 : ((av < bv) ? -1 : 0);
  4340. });
  4341. }
  4342. else if (typeof order === 'function') {
  4343. // order by sort function
  4344. items.sort(order);
  4345. }
  4346. // TODO: extend order by an Object {field:String, direction:String}
  4347. // where direction can be 'asc' or 'desc'
  4348. else {
  4349. throw new TypeError('Order must be a function or a string');
  4350. }
  4351. };
  4352. /**
  4353. * Remove an object by pointer or by id
  4354. * @param {String | Number | Object | Array} id Object or id, or an array with
  4355. * objects or ids to be removed
  4356. * @param {String} [senderId] Optional sender id
  4357. * @return {Array} removedIds
  4358. */
  4359. DataSet.prototype.remove = function (id, senderId) {
  4360. var removedIds = [],
  4361. i, len, removedId;
  4362. if (id instanceof Array) {
  4363. for (i = 0, len = id.length; i < len; i++) {
  4364. removedId = this._remove(id[i]);
  4365. if (removedId != null) {
  4366. removedIds.push(removedId);
  4367. }
  4368. }
  4369. }
  4370. else {
  4371. removedId = this._remove(id);
  4372. if (removedId != null) {
  4373. removedIds.push(removedId);
  4374. }
  4375. }
  4376. if (removedIds.length) {
  4377. this._trigger('remove', {items: removedIds}, senderId);
  4378. }
  4379. return removedIds;
  4380. };
  4381. /**
  4382. * Remove an item by its id
  4383. * @param {Number | String | Object} id id or item
  4384. * @returns {Number | String | null} id
  4385. * @private
  4386. */
  4387. DataSet.prototype._remove = function (id) {
  4388. if (util.isNumber(id) || util.isString(id)) {
  4389. if (this.data[id]) {
  4390. delete this.data[id];
  4391. delete this.internalIds[id];
  4392. return id;
  4393. }
  4394. }
  4395. else if (id instanceof Object) {
  4396. var itemId = id[this.fieldId];
  4397. if (itemId && this.data[itemId]) {
  4398. delete this.data[itemId];
  4399. delete this.internalIds[itemId];
  4400. return itemId;
  4401. }
  4402. }
  4403. return null;
  4404. };
  4405. /**
  4406. * Clear the data
  4407. * @param {String} [senderId] Optional sender id
  4408. * @return {Array} removedIds The ids of all removed items
  4409. */
  4410. DataSet.prototype.clear = function (senderId) {
  4411. var ids = Object.keys(this.data);
  4412. this.data = {};
  4413. this.internalIds = {};
  4414. this._trigger('remove', {items: ids}, senderId);
  4415. return ids;
  4416. };
  4417. /**
  4418. * Find the item with maximum value of a specified field
  4419. * @param {String} field
  4420. * @return {Object | null} item Item containing max value, or null if no items
  4421. */
  4422. DataSet.prototype.max = function (field) {
  4423. var data = this.data,
  4424. max = null,
  4425. maxField = null;
  4426. for (var id in data) {
  4427. if (data.hasOwnProperty(id)) {
  4428. var item = data[id];
  4429. var itemField = item[field];
  4430. if (itemField != null && (!max || itemField > maxField)) {
  4431. max = item;
  4432. maxField = itemField;
  4433. }
  4434. }
  4435. }
  4436. return max;
  4437. };
  4438. /**
  4439. * Find the item with minimum value of a specified field
  4440. * @param {String} field
  4441. * @return {Object | null} item Item containing max value, or null if no items
  4442. */
  4443. DataSet.prototype.min = function (field) {
  4444. var data = this.data,
  4445. min = null,
  4446. minField = null;
  4447. for (var id in data) {
  4448. if (data.hasOwnProperty(id)) {
  4449. var item = data[id];
  4450. var itemField = item[field];
  4451. if (itemField != null && (!min || itemField < minField)) {
  4452. min = item;
  4453. minField = itemField;
  4454. }
  4455. }
  4456. }
  4457. return min;
  4458. };
  4459. /**
  4460. * Find all distinct values of a specified field
  4461. * @param {String} field
  4462. * @return {Array} values Array containing all distinct values. If the data
  4463. * items do not contain the specified field, an array
  4464. * containing a single value undefined is returned.
  4465. * The returned array is unordered.
  4466. */
  4467. DataSet.prototype.distinct = function (field) {
  4468. var data = this.data,
  4469. values = [],
  4470. fieldType = this.options.convert[field],
  4471. count = 0;
  4472. for (var prop in data) {
  4473. if (data.hasOwnProperty(prop)) {
  4474. var item = data[prop];
  4475. var value = util.convert(item[field], fieldType);
  4476. var exists = false;
  4477. for (var i = 0; i < count; i++) {
  4478. if (values[i] == value) {
  4479. exists = true;
  4480. break;
  4481. }
  4482. }
  4483. if (!exists) {
  4484. values[count] = value;
  4485. count++;
  4486. }
  4487. }
  4488. }
  4489. return values;
  4490. };
  4491. /**
  4492. * Add a single item. Will fail when an item with the same id already exists.
  4493. * @param {Object} item
  4494. * @return {String} id
  4495. * @private
  4496. */
  4497. DataSet.prototype._addItem = function (item) {
  4498. var id = item[this.fieldId];
  4499. if (id != undefined) {
  4500. // check whether this id is already taken
  4501. if (this.data[id]) {
  4502. // item already exists
  4503. throw new Error('Cannot add item: item with id ' + id + ' already exists');
  4504. }
  4505. }
  4506. else {
  4507. // generate an id
  4508. id = util.randomUUID();
  4509. item[this.fieldId] = id;
  4510. this.internalIds[id] = item;
  4511. }
  4512. var d = {};
  4513. for (var field in item) {
  4514. if (item.hasOwnProperty(field)) {
  4515. var fieldType = this.convert[field]; // type may be undefined
  4516. d[field] = util.convert(item[field], fieldType);
  4517. }
  4518. }
  4519. this.data[id] = d;
  4520. return id;
  4521. };
  4522. /**
  4523. * Get an item. Fields can be converted to a specific type
  4524. * @param {String} id
  4525. * @param {Object.<String, String>} [convert] field types to convert
  4526. * @return {Object | null} item
  4527. * @private
  4528. */
  4529. DataSet.prototype._getItem = function (id, convert) {
  4530. var field, value;
  4531. // get the item from the dataset
  4532. var raw = this.data[id];
  4533. if (!raw) {
  4534. return null;
  4535. }
  4536. // convert the items field types
  4537. var converted = {},
  4538. fieldId = this.fieldId,
  4539. internalIds = this.internalIds;
  4540. if (convert) {
  4541. for (field in raw) {
  4542. if (raw.hasOwnProperty(field)) {
  4543. value = raw[field];
  4544. // output all fields, except internal ids
  4545. if ((field != fieldId) || !(value in internalIds)) {
  4546. converted[field] = util.convert(value, convert[field]);
  4547. }
  4548. }
  4549. }
  4550. }
  4551. else {
  4552. // no field types specified, no converting needed
  4553. for (field in raw) {
  4554. if (raw.hasOwnProperty(field)) {
  4555. value = raw[field];
  4556. // output all fields, except internal ids
  4557. if ((field != fieldId) || !(value in internalIds)) {
  4558. converted[field] = value;
  4559. }
  4560. }
  4561. }
  4562. }
  4563. return converted;
  4564. };
  4565. /**
  4566. * Update a single item: merge with existing item.
  4567. * Will fail when the item has no id, or when there does not exist an item
  4568. * with the same id.
  4569. * @param {Object} item
  4570. * @return {String} id
  4571. * @private
  4572. */
  4573. DataSet.prototype._updateItem = function (item) {
  4574. var id = item[this.fieldId];
  4575. if (id == undefined) {
  4576. throw new Error('Cannot update item: item has no id (item: ' + JSON.stringify(item) + ')');
  4577. }
  4578. var d = this.data[id];
  4579. if (!d) {
  4580. // item doesn't exist
  4581. throw new Error('Cannot update item: no item with id ' + id + ' found');
  4582. }
  4583. // merge with current item
  4584. for (var field in item) {
  4585. if (item.hasOwnProperty(field)) {
  4586. var fieldType = this.convert[field]; // type may be undefined
  4587. d[field] = util.convert(item[field], fieldType);
  4588. }
  4589. }
  4590. return id;
  4591. };
  4592. /**
  4593. * Get an array with the column names of a Google DataTable
  4594. * @param {DataTable} dataTable
  4595. * @return {String[]} columnNames
  4596. * @private
  4597. */
  4598. DataSet.prototype._getColumnNames = function (dataTable) {
  4599. var columns = [];
  4600. for (var col = 0, cols = dataTable.getNumberOfColumns(); col < cols; col++) {
  4601. columns[col] = dataTable.getColumnId(col) || dataTable.getColumnLabel(col);
  4602. }
  4603. return columns;
  4604. };
  4605. /**
  4606. * Append an item as a row to the dataTable
  4607. * @param dataTable
  4608. * @param columns
  4609. * @param item
  4610. * @private
  4611. */
  4612. DataSet.prototype._appendRow = function (dataTable, columns, item) {
  4613. var row = dataTable.addRow();
  4614. for (var col = 0, cols = columns.length; col < cols; col++) {
  4615. var field = columns[col];
  4616. dataTable.setValue(row, col, item[field]);
  4617. }
  4618. };
  4619. /**
  4620. * DataView
  4621. *
  4622. * a dataview offers a filtered view on a dataset or an other dataview.
  4623. *
  4624. * @param {DataSet | DataView} data
  4625. * @param {Object} [options] Available options: see method get
  4626. *
  4627. * @constructor DataView
  4628. */
  4629. function DataView (data, options) {
  4630. this.id = util.randomUUID();
  4631. this.data = null;
  4632. this.ids = {}; // ids of the items currently in memory (just contains a boolean true)
  4633. this.options = options || {};
  4634. this.fieldId = 'id'; // name of the field containing id
  4635. this.subscribers = {}; // event subscribers
  4636. var me = this;
  4637. this.listener = function () {
  4638. me._onEvent.apply(me, arguments);
  4639. };
  4640. this.setData(data);
  4641. }
  4642. /**
  4643. * Set a data source for the view
  4644. * @param {DataSet | DataView} data
  4645. */
  4646. DataView.prototype.setData = function (data) {
  4647. var ids, dataItems, i, len;
  4648. if (this.data) {
  4649. // unsubscribe from current dataset
  4650. if (this.data.unsubscribe) {
  4651. this.data.unsubscribe('*', this.listener);
  4652. }
  4653. // trigger a remove of all items in memory
  4654. ids = [];
  4655. for (var id in this.ids) {
  4656. if (this.ids.hasOwnProperty(id)) {
  4657. ids.push(id);
  4658. }
  4659. }
  4660. this.ids = {};
  4661. this._trigger('remove', {items: ids});
  4662. }
  4663. this.data = data;
  4664. if (this.data) {
  4665. // update fieldId
  4666. this.fieldId = this.options.fieldId ||
  4667. (this.data && this.data.options && this.data.options.fieldId) ||
  4668. 'id';
  4669. // trigger an add of all added items
  4670. ids = this.data.getIds({filter: this.options && this.options.filter});
  4671. for (i = 0, len = ids.length; i < len; i++) {
  4672. id = ids[i];
  4673. this.ids[id] = true;
  4674. }
  4675. this._trigger('add', {items: ids});
  4676. // subscribe to new dataset
  4677. if (this.data.subscribe) {
  4678. this.data.subscribe('*', this.listener);
  4679. }
  4680. }
  4681. };
  4682. /**
  4683. * Get data from the data view
  4684. *
  4685. * Usage:
  4686. *
  4687. * get()
  4688. * get(options: Object)
  4689. * get(options: Object, data: Array | DataTable)
  4690. *
  4691. * get(id: Number)
  4692. * get(id: Number, options: Object)
  4693. * get(id: Number, options: Object, data: Array | DataTable)
  4694. *
  4695. * get(ids: Number[])
  4696. * get(ids: Number[], options: Object)
  4697. * get(ids: Number[], options: Object, data: Array | DataTable)
  4698. *
  4699. * Where:
  4700. *
  4701. * {Number | String} id The id of an item
  4702. * {Number[] | String{}} ids An array with ids of items
  4703. * {Object} options An Object with options. Available options:
  4704. * {String} [type] Type of data to be returned. Can
  4705. * be 'DataTable' or 'Array' (default)
  4706. * {Object.<String, String>} [convert]
  4707. * {String[]} [fields] field names to be returned
  4708. * {function} [filter] filter items
  4709. * {String | function} [order] Order the items by
  4710. * a field name or custom sort function.
  4711. * {Array | DataTable} [data] If provided, items will be appended to this
  4712. * array or table. Required in case of Google
  4713. * DataTable.
  4714. * @param args
  4715. */
  4716. DataView.prototype.get = function (args) {
  4717. var me = this;
  4718. // parse the arguments
  4719. var ids, options, data;
  4720. var firstType = util.getType(arguments[0]);
  4721. if (firstType == 'String' || firstType == 'Number' || firstType == 'Array') {
  4722. // get(id(s) [, options] [, data])
  4723. ids = arguments[0]; // can be a single id or an array with ids
  4724. options = arguments[1];
  4725. data = arguments[2];
  4726. }
  4727. else {
  4728. // get([, options] [, data])
  4729. options = arguments[0];
  4730. data = arguments[1];
  4731. }
  4732. // extend the options with the default options and provided options
  4733. var viewOptions = util.extend({}, this.options, options);
  4734. // create a combined filter method when needed
  4735. if (this.options.filter && options && options.filter) {
  4736. viewOptions.filter = function (item) {
  4737. return me.options.filter(item) && options.filter(item);
  4738. }
  4739. }
  4740. // build up the call to the linked data set
  4741. var getArguments = [];
  4742. if (ids != undefined) {
  4743. getArguments.push(ids);
  4744. }
  4745. getArguments.push(viewOptions);
  4746. getArguments.push(data);
  4747. return this.data && this.data.get.apply(this.data, getArguments);
  4748. };
  4749. /**
  4750. * Get ids of all items or from a filtered set of items.
  4751. * @param {Object} [options] An Object with options. Available options:
  4752. * {function} [filter] filter items
  4753. * {String | function} [order] Order the items by
  4754. * a field name or custom sort function.
  4755. * @return {Array} ids
  4756. */
  4757. DataView.prototype.getIds = function (options) {
  4758. var ids;
  4759. if (this.data) {
  4760. var defaultFilter = this.options.filter;
  4761. var filter;
  4762. if (options && options.filter) {
  4763. if (defaultFilter) {
  4764. filter = function (item) {
  4765. return defaultFilter(item) && options.filter(item);
  4766. }
  4767. }
  4768. else {
  4769. filter = options.filter;
  4770. }
  4771. }
  4772. else {
  4773. filter = defaultFilter;
  4774. }
  4775. ids = this.data.getIds({
  4776. filter: filter,
  4777. order: options && options.order
  4778. });
  4779. }
  4780. else {
  4781. ids = [];
  4782. }
  4783. return ids;
  4784. };
  4785. /**
  4786. * Event listener. Will propagate all events from the connected data set to
  4787. * the subscribers of the DataView, but will filter the items and only trigger
  4788. * when there are changes in the filtered data set.
  4789. * @param {String} event
  4790. * @param {Object | null} params
  4791. * @param {String} senderId
  4792. * @private
  4793. */
  4794. DataView.prototype._onEvent = function (event, params, senderId) {
  4795. var i, len, id, item,
  4796. ids = params && params.items,
  4797. data = this.data,
  4798. added = [],
  4799. updated = [],
  4800. removed = [];
  4801. if (ids && data) {
  4802. switch (event) {
  4803. case 'add':
  4804. // filter the ids of the added items
  4805. for (i = 0, len = ids.length; i < len; i++) {
  4806. id = ids[i];
  4807. item = this.get(id);
  4808. if (item) {
  4809. this.ids[id] = true;
  4810. added.push(id);
  4811. }
  4812. }
  4813. break;
  4814. case 'update':
  4815. // determine the event from the views viewpoint: an updated
  4816. // item can be added, updated, or removed from this view.
  4817. for (i = 0, len = ids.length; i < len; i++) {
  4818. id = ids[i];
  4819. item = this.get(id);
  4820. if (item) {
  4821. if (this.ids[id]) {
  4822. updated.push(id);
  4823. }
  4824. else {
  4825. this.ids[id] = true;
  4826. added.push(id);
  4827. }
  4828. }
  4829. else {
  4830. if (this.ids[id]) {
  4831. delete this.ids[id];
  4832. removed.push(id);
  4833. }
  4834. else {
  4835. // nothing interesting for me :-(
  4836. }
  4837. }
  4838. }
  4839. break;
  4840. case 'remove':
  4841. // filter the ids of the removed items
  4842. for (i = 0, len = ids.length; i < len; i++) {
  4843. id = ids[i];
  4844. if (this.ids[id]) {
  4845. delete this.ids[id];
  4846. removed.push(id);
  4847. }
  4848. }
  4849. break;
  4850. }
  4851. if (added.length) {
  4852. this._trigger('add', {items: added}, senderId);
  4853. }
  4854. if (updated.length) {
  4855. this._trigger('update', {items: updated}, senderId);
  4856. }
  4857. if (removed.length) {
  4858. this._trigger('remove', {items: removed}, senderId);
  4859. }
  4860. }
  4861. };
  4862. // copy subscription functionality from DataSet
  4863. DataView.prototype.subscribe = DataSet.prototype.subscribe;
  4864. DataView.prototype.unsubscribe = DataSet.prototype.unsubscribe;
  4865. DataView.prototype._trigger = DataSet.prototype._trigger;
  4866. /**
  4867. * @constructor TimeStep
  4868. * The class TimeStep is an iterator for dates. You provide a start date and an
  4869. * end date. The class itself determines the best scale (step size) based on the
  4870. * provided start Date, end Date, and minimumStep.
  4871. *
  4872. * If minimumStep is provided, the step size is chosen as close as possible
  4873. * to the minimumStep but larger than minimumStep. If minimumStep is not
  4874. * provided, the scale is set to 1 DAY.
  4875. * The minimumStep should correspond with the onscreen size of about 6 characters
  4876. *
  4877. * Alternatively, you can set a scale by hand.
  4878. * After creation, you can initialize the class by executing first(). Then you
  4879. * can iterate from the start date to the end date via next(). You can check if
  4880. * the end date is reached with the function hasNext(). After each step, you can
  4881. * retrieve the current date via getCurrent().
  4882. * The TimeStep has scales ranging from milliseconds, seconds, minutes, hours,
  4883. * days, to years.
  4884. *
  4885. * Version: 1.2
  4886. *
  4887. * @param {Date} [start] The start date, for example new Date(2010, 9, 21)
  4888. * or new Date(2010, 9, 21, 23, 45, 00)
  4889. * @param {Date} [end] The end date
  4890. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  4891. */
  4892. TimeStep = function(start, end, minimumStep) {
  4893. // variables
  4894. this.current = new Date();
  4895. this._start = new Date();
  4896. this._end = new Date();
  4897. this.autoScale = true;
  4898. this.scale = TimeStep.SCALE.DAY;
  4899. this.step = 1;
  4900. // initialize the range
  4901. this.setRange(start, end, minimumStep);
  4902. };
  4903. /// enum scale
  4904. TimeStep.SCALE = {
  4905. MILLISECOND: 1,
  4906. SECOND: 2,
  4907. MINUTE: 3,
  4908. HOUR: 4,
  4909. DAY: 5,
  4910. WEEKDAY: 6,
  4911. MONTH: 7,
  4912. YEAR: 8
  4913. };
  4914. /**
  4915. * Set a new range
  4916. * If minimumStep is provided, the step size is chosen as close as possible
  4917. * to the minimumStep but larger than minimumStep. If minimumStep is not
  4918. * provided, the scale is set to 1 DAY.
  4919. * The minimumStep should correspond with the onscreen size of about 6 characters
  4920. * @param {Date} [start] The start date and time.
  4921. * @param {Date} [end] The end date and time.
  4922. * @param {int} [minimumStep] Optional. Minimum step size in milliseconds
  4923. */
  4924. TimeStep.prototype.setRange = function(start, end, minimumStep) {
  4925. if (!(start instanceof Date) || !(end instanceof Date)) {
  4926. //throw "No legal start or end date in method setRange";
  4927. return;
  4928. }
  4929. this._start = (start != undefined) ? new Date(start.valueOf()) : new Date();
  4930. this._end = (end != undefined) ? new Date(end.valueOf()) : new Date();
  4931. if (this.autoScale) {
  4932. this.setMinimumStep(minimumStep);
  4933. }
  4934. };
  4935. /**
  4936. * Set the range iterator to the start date.
  4937. */
  4938. TimeStep.prototype.first = function() {
  4939. this.current = new Date(this._start.valueOf());
  4940. this.roundToMinor();
  4941. };
  4942. /**
  4943. * Round the current date to the first minor date value
  4944. * This must be executed once when the current date is set to start Date
  4945. */
  4946. TimeStep.prototype.roundToMinor = function() {
  4947. // round to floor
  4948. // IMPORTANT: we have no breaks in this switch! (this is no bug)
  4949. //noinspection FallthroughInSwitchStatementJS
  4950. switch (this.scale) {
  4951. case TimeStep.SCALE.YEAR:
  4952. this.current.setFullYear(this.step * Math.floor(this.current.getFullYear() / this.step));
  4953. this.current.setMonth(0);
  4954. case TimeStep.SCALE.MONTH: this.current.setDate(1);
  4955. case TimeStep.SCALE.DAY: // intentional fall through
  4956. case TimeStep.SCALE.WEEKDAY: this.current.setHours(0);
  4957. case TimeStep.SCALE.HOUR: this.current.setMinutes(0);
  4958. case TimeStep.SCALE.MINUTE: this.current.setSeconds(0);
  4959. case TimeStep.SCALE.SECOND: this.current.setMilliseconds(0);
  4960. //case TimeStep.SCALE.MILLISECOND: // nothing to do for milliseconds
  4961. }
  4962. if (this.step != 1) {
  4963. // round down to the first minor value that is a multiple of the current step size
  4964. switch (this.scale) {
  4965. case TimeStep.SCALE.MILLISECOND: this.current.setMilliseconds(this.current.getMilliseconds() - this.current.getMilliseconds() % this.step); break;
  4966. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() - this.current.getSeconds() % this.step); break;
  4967. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() - this.current.getMinutes() % this.step); break;
  4968. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() - this.current.getHours() % this.step); break;
  4969. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  4970. case TimeStep.SCALE.DAY: this.current.setDate((this.current.getDate()-1) - (this.current.getDate()-1) % this.step + 1); break;
  4971. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() - this.current.getMonth() % this.step); break;
  4972. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() - this.current.getFullYear() % this.step); break;
  4973. default: break;
  4974. }
  4975. }
  4976. };
  4977. /**
  4978. * Check if the there is a next step
  4979. * @return {boolean} true if the current date has not passed the end date
  4980. */
  4981. TimeStep.prototype.hasNext = function () {
  4982. return (this.current.valueOf() <= this._end.valueOf());
  4983. };
  4984. /**
  4985. * Do the next step
  4986. */
  4987. TimeStep.prototype.next = function() {
  4988. var prev = this.current.valueOf();
  4989. // Two cases, needed to prevent issues with switching daylight savings
  4990. // (end of March and end of October)
  4991. if (this.current.getMonth() < 6) {
  4992. switch (this.scale) {
  4993. case TimeStep.SCALE.MILLISECOND:
  4994. this.current = new Date(this.current.valueOf() + this.step); break;
  4995. case TimeStep.SCALE.SECOND: this.current = new Date(this.current.valueOf() + this.step * 1000); break;
  4996. case TimeStep.SCALE.MINUTE: this.current = new Date(this.current.valueOf() + this.step * 1000 * 60); break;
  4997. case TimeStep.SCALE.HOUR:
  4998. this.current = new Date(this.current.valueOf() + this.step * 1000 * 60 * 60);
  4999. // in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...)
  5000. var h = this.current.getHours();
  5001. this.current.setHours(h - (h % this.step));
  5002. break;
  5003. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  5004. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  5005. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  5006. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  5007. default: break;
  5008. }
  5009. }
  5010. else {
  5011. switch (this.scale) {
  5012. case TimeStep.SCALE.MILLISECOND: this.current = new Date(this.current.valueOf() + this.step); break;
  5013. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() + this.step); break;
  5014. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() + this.step); break;
  5015. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() + this.step); break;
  5016. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  5017. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  5018. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  5019. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  5020. default: break;
  5021. }
  5022. }
  5023. if (this.step != 1) {
  5024. // round down to the correct major value
  5025. switch (this.scale) {
  5026. case TimeStep.SCALE.MILLISECOND: if(this.current.getMilliseconds() < this.step) this.current.setMilliseconds(0); break;
  5027. case TimeStep.SCALE.SECOND: if(this.current.getSeconds() < this.step) this.current.setSeconds(0); break;
  5028. case TimeStep.SCALE.MINUTE: if(this.current.getMinutes() < this.step) this.current.setMinutes(0); break;
  5029. case TimeStep.SCALE.HOUR: if(this.current.getHours() < this.step) this.current.setHours(0); break;
  5030. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  5031. case TimeStep.SCALE.DAY: if(this.current.getDate() < this.step+1) this.current.setDate(1); break;
  5032. case TimeStep.SCALE.MONTH: if(this.current.getMonth() < this.step) this.current.setMonth(0); break;
  5033. case TimeStep.SCALE.YEAR: break; // nothing to do for year
  5034. default: break;
  5035. }
  5036. }
  5037. // safety mechanism: if current time is still unchanged, move to the end
  5038. if (this.current.valueOf() == prev) {
  5039. this.current = new Date(this._end.valueOf());
  5040. }
  5041. };
  5042. /**
  5043. * Get the current datetime
  5044. * @return {Date} current The current date
  5045. */
  5046. TimeStep.prototype.getCurrent = function() {
  5047. return this.current;
  5048. };
  5049. /**
  5050. * Set a custom scale. Autoscaling will be disabled.
  5051. * For example setScale(SCALE.MINUTES, 5) will result
  5052. * in minor steps of 5 minutes, and major steps of an hour.
  5053. *
  5054. * @param {TimeStep.SCALE} newScale
  5055. * A scale. Choose from SCALE.MILLISECOND,
  5056. * SCALE.SECOND, SCALE.MINUTE, SCALE.HOUR,
  5057. * SCALE.WEEKDAY, SCALE.DAY, SCALE.MONTH,
  5058. * SCALE.YEAR.
  5059. * @param {Number} newStep A step size, by default 1. Choose for
  5060. * example 1, 2, 5, or 10.
  5061. */
  5062. TimeStep.prototype.setScale = function(newScale, newStep) {
  5063. this.scale = newScale;
  5064. if (newStep > 0) {
  5065. this.step = newStep;
  5066. }
  5067. this.autoScale = false;
  5068. };
  5069. /**
  5070. * Enable or disable autoscaling
  5071. * @param {boolean} enable If true, autoascaling is set true
  5072. */
  5073. TimeStep.prototype.setAutoScale = function (enable) {
  5074. this.autoScale = enable;
  5075. };
  5076. /**
  5077. * Automatically determine the scale that bests fits the provided minimum step
  5078. * @param {Number} [minimumStep] The minimum step size in milliseconds
  5079. */
  5080. TimeStep.prototype.setMinimumStep = function(minimumStep) {
  5081. if (minimumStep == undefined) {
  5082. return;
  5083. }
  5084. var stepYear = (1000 * 60 * 60 * 24 * 30 * 12);
  5085. var stepMonth = (1000 * 60 * 60 * 24 * 30);
  5086. var stepDay = (1000 * 60 * 60 * 24);
  5087. var stepHour = (1000 * 60 * 60);
  5088. var stepMinute = (1000 * 60);
  5089. var stepSecond = (1000);
  5090. var stepMillisecond= (1);
  5091. // find the smallest step that is larger than the provided minimumStep
  5092. if (stepYear*1000 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1000;}
  5093. if (stepYear*500 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 500;}
  5094. if (stepYear*100 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 100;}
  5095. if (stepYear*50 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 50;}
  5096. if (stepYear*10 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 10;}
  5097. if (stepYear*5 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 5;}
  5098. if (stepYear > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1;}
  5099. if (stepMonth*3 > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 3;}
  5100. if (stepMonth > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 1;}
  5101. if (stepDay*5 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 5;}
  5102. if (stepDay*2 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 2;}
  5103. if (stepDay > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 1;}
  5104. if (stepDay/2 > minimumStep) {this.scale = TimeStep.SCALE.WEEKDAY; this.step = 1;}
  5105. if (stepHour*4 > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 4;}
  5106. if (stepHour > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 1;}
  5107. if (stepMinute*15 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 15;}
  5108. if (stepMinute*10 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 10;}
  5109. if (stepMinute*5 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 5;}
  5110. if (stepMinute > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 1;}
  5111. if (stepSecond*15 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 15;}
  5112. if (stepSecond*10 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 10;}
  5113. if (stepSecond*5 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 5;}
  5114. if (stepSecond > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 1;}
  5115. if (stepMillisecond*200 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 200;}
  5116. if (stepMillisecond*100 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 100;}
  5117. if (stepMillisecond*50 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 50;}
  5118. if (stepMillisecond*10 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 10;}
  5119. if (stepMillisecond*5 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 5;}
  5120. if (stepMillisecond > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 1;}
  5121. };
  5122. /**
  5123. * Snap a date to a rounded value. The snap intervals are dependent on the
  5124. * current scale and step.
  5125. * @param {Date} date the date to be snapped
  5126. */
  5127. TimeStep.prototype.snap = function(date) {
  5128. if (this.scale == TimeStep.SCALE.YEAR) {
  5129. var year = date.getFullYear() + Math.round(date.getMonth() / 12);
  5130. date.setFullYear(Math.round(year / this.step) * this.step);
  5131. date.setMonth(0);
  5132. date.setDate(0);
  5133. date.setHours(0);
  5134. date.setMinutes(0);
  5135. date.setSeconds(0);
  5136. date.setMilliseconds(0);
  5137. }
  5138. else if (this.scale == TimeStep.SCALE.MONTH) {
  5139. if (date.getDate() > 15) {
  5140. date.setDate(1);
  5141. date.setMonth(date.getMonth() + 1);
  5142. // important: first set Date to 1, after that change the month.
  5143. }
  5144. else {
  5145. date.setDate(1);
  5146. }
  5147. date.setHours(0);
  5148. date.setMinutes(0);
  5149. date.setSeconds(0);
  5150. date.setMilliseconds(0);
  5151. }
  5152. else if (this.scale == TimeStep.SCALE.DAY ||
  5153. this.scale == TimeStep.SCALE.WEEKDAY) {
  5154. //noinspection FallthroughInSwitchStatementJS
  5155. switch (this.step) {
  5156. case 5:
  5157. case 2:
  5158. date.setHours(Math.round(date.getHours() / 24) * 24); break;
  5159. default:
  5160. date.setHours(Math.round(date.getHours() / 12) * 12); break;
  5161. }
  5162. date.setMinutes(0);
  5163. date.setSeconds(0);
  5164. date.setMilliseconds(0);
  5165. }
  5166. else if (this.scale == TimeStep.SCALE.HOUR) {
  5167. switch (this.step) {
  5168. case 4:
  5169. date.setMinutes(Math.round(date.getMinutes() / 60) * 60); break;
  5170. default:
  5171. date.setMinutes(Math.round(date.getMinutes() / 30) * 30); break;
  5172. }
  5173. date.setSeconds(0);
  5174. date.setMilliseconds(0);
  5175. } else if (this.scale == TimeStep.SCALE.MINUTE) {
  5176. //noinspection FallthroughInSwitchStatementJS
  5177. switch (this.step) {
  5178. case 15:
  5179. case 10:
  5180. date.setMinutes(Math.round(date.getMinutes() / 5) * 5);
  5181. date.setSeconds(0);
  5182. break;
  5183. case 5:
  5184. date.setSeconds(Math.round(date.getSeconds() / 60) * 60); break;
  5185. default:
  5186. date.setSeconds(Math.round(date.getSeconds() / 30) * 30); break;
  5187. }
  5188. date.setMilliseconds(0);
  5189. }
  5190. else if (this.scale == TimeStep.SCALE.SECOND) {
  5191. //noinspection FallthroughInSwitchStatementJS
  5192. switch (this.step) {
  5193. case 15:
  5194. case 10:
  5195. date.setSeconds(Math.round(date.getSeconds() / 5) * 5);
  5196. date.setMilliseconds(0);
  5197. break;
  5198. case 5:
  5199. date.setMilliseconds(Math.round(date.getMilliseconds() / 1000) * 1000); break;
  5200. default:
  5201. date.setMilliseconds(Math.round(date.getMilliseconds() / 500) * 500); break;
  5202. }
  5203. }
  5204. else if (this.scale == TimeStep.SCALE.MILLISECOND) {
  5205. var step = this.step > 5 ? this.step / 2 : 1;
  5206. date.setMilliseconds(Math.round(date.getMilliseconds() / step) * step);
  5207. }
  5208. };
  5209. /**
  5210. * Check if the current value is a major value (for example when the step
  5211. * is DAY, a major value is each first day of the MONTH)
  5212. * @return {boolean} true if current date is major, else false.
  5213. */
  5214. TimeStep.prototype.isMajor = function() {
  5215. switch (this.scale) {
  5216. case TimeStep.SCALE.MILLISECOND:
  5217. return (this.current.getMilliseconds() == 0);
  5218. case TimeStep.SCALE.SECOND:
  5219. return (this.current.getSeconds() == 0);
  5220. case TimeStep.SCALE.MINUTE:
  5221. return (this.current.getHours() == 0) && (this.current.getMinutes() == 0);
  5222. // Note: this is no bug. Major label is equal for both minute and hour scale
  5223. case TimeStep.SCALE.HOUR:
  5224. return (this.current.getHours() == 0);
  5225. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  5226. case TimeStep.SCALE.DAY:
  5227. return (this.current.getDate() == 1);
  5228. case TimeStep.SCALE.MONTH:
  5229. return (this.current.getMonth() == 0);
  5230. case TimeStep.SCALE.YEAR:
  5231. return false;
  5232. default:
  5233. return false;
  5234. }
  5235. };
  5236. /**
  5237. * Returns formatted text for the minor axislabel, depending on the current
  5238. * date and the scale. For example when scale is MINUTE, the current time is
  5239. * formatted as "hh:mm".
  5240. * @param {Date} [date] custom date. if not provided, current date is taken
  5241. */
  5242. TimeStep.prototype.getLabelMinor = function(date) {
  5243. if (date == undefined) {
  5244. date = this.current;
  5245. }
  5246. switch (this.scale) {
  5247. case TimeStep.SCALE.MILLISECOND: return moment(date).format('SSS');
  5248. case TimeStep.SCALE.SECOND: return moment(date).format('s');
  5249. case TimeStep.SCALE.MINUTE: return moment(date).format('HH:mm');
  5250. case TimeStep.SCALE.HOUR: return moment(date).format('HH:mm');
  5251. case TimeStep.SCALE.WEEKDAY: return moment(date).format('ddd D');
  5252. case TimeStep.SCALE.DAY: return moment(date).format('D');
  5253. case TimeStep.SCALE.MONTH: return moment(date).format('MMM');
  5254. case TimeStep.SCALE.YEAR: return moment(date).format('YYYY');
  5255. default: return '';
  5256. }
  5257. };
  5258. /**
  5259. * Returns formatted text for the major axis label, depending on the current
  5260. * date and the scale. For example when scale is MINUTE, the major scale is
  5261. * hours, and the hour will be formatted as "hh".
  5262. * @param {Date} [date] custom date. if not provided, current date is taken
  5263. */
  5264. TimeStep.prototype.getLabelMajor = function(date) {
  5265. if (date == undefined) {
  5266. date = this.current;
  5267. }
  5268. //noinspection FallthroughInSwitchStatementJS
  5269. switch (this.scale) {
  5270. case TimeStep.SCALE.MILLISECOND:return moment(date).format('HH:mm:ss');
  5271. case TimeStep.SCALE.SECOND: return moment(date).format('D MMMM HH:mm');
  5272. case TimeStep.SCALE.MINUTE:
  5273. case TimeStep.SCALE.HOUR: return moment(date).format('ddd D MMMM');
  5274. case TimeStep.SCALE.WEEKDAY:
  5275. case TimeStep.SCALE.DAY: return moment(date).format('MMMM YYYY');
  5276. case TimeStep.SCALE.MONTH: return moment(date).format('YYYY');
  5277. case TimeStep.SCALE.YEAR: return '';
  5278. default: return '';
  5279. }
  5280. };
  5281. /**
  5282. * @constructor Stack
  5283. * Stacks items on top of each other.
  5284. * @param {ItemSet} parent
  5285. * @param {Object} [options]
  5286. */
  5287. function Stack (parent, options) {
  5288. this.parent = parent;
  5289. this.options = options || {};
  5290. this.defaultOptions = {
  5291. order: function (a, b) {
  5292. //return (b.width - a.width) || (a.left - b.left); // TODO: cleanup
  5293. // Order: ranges over non-ranges, ranged ordered by width, and
  5294. // lastly ordered by start.
  5295. if (a instanceof ItemRange) {
  5296. if (b instanceof ItemRange) {
  5297. var aInt = (a.data.end - a.data.start);
  5298. var bInt = (b.data.end - b.data.start);
  5299. return (aInt - bInt) || (a.data.start - b.data.start);
  5300. }
  5301. else {
  5302. return -1;
  5303. }
  5304. }
  5305. else {
  5306. if (b instanceof ItemRange) {
  5307. return 1;
  5308. }
  5309. else {
  5310. return (a.data.start - b.data.start);
  5311. }
  5312. }
  5313. },
  5314. margin: {
  5315. item: 10
  5316. }
  5317. };
  5318. this.ordered = []; // ordered items
  5319. }
  5320. /**
  5321. * Set options for the stack
  5322. * @param {Object} options Available options:
  5323. * {ItemSet} parent
  5324. * {Number} margin
  5325. * {function} order Stacking order
  5326. */
  5327. Stack.prototype.setOptions = function setOptions (options) {
  5328. util.extend(this.options, options);
  5329. // TODO: register on data changes at the connected parent itemset, and update the changed part only and immediately
  5330. };
  5331. /**
  5332. * Stack the items such that they don't overlap. The items will have a minimal
  5333. * distance equal to options.margin.item.
  5334. */
  5335. Stack.prototype.update = function update() {
  5336. this._order();
  5337. this._stack();
  5338. };
  5339. /**
  5340. * Order the items. The items are ordered by width first, and by left position
  5341. * second.
  5342. * If a custom order function has been provided via the options, then this will
  5343. * be used.
  5344. * @private
  5345. */
  5346. Stack.prototype._order = function _order () {
  5347. var items = this.parent.items;
  5348. if (!items) {
  5349. throw new Error('Cannot stack items: parent does not contain items');
  5350. }
  5351. // TODO: store the sorted items, to have less work later on
  5352. var ordered = [];
  5353. var index = 0;
  5354. // items is a map (no array)
  5355. util.forEach(items, function (item) {
  5356. if (item.visible) {
  5357. ordered[index] = item;
  5358. index++;
  5359. }
  5360. });
  5361. //if a customer stack order function exists, use it.
  5362. var order = this.options.order || this.defaultOptions.order;
  5363. if (!(typeof order === 'function')) {
  5364. throw new Error('Option order must be a function');
  5365. }
  5366. ordered.sort(order);
  5367. this.ordered = ordered;
  5368. };
  5369. /**
  5370. * Adjust vertical positions of the events such that they don't overlap each
  5371. * other.
  5372. * @private
  5373. */
  5374. Stack.prototype._stack = function _stack () {
  5375. var i,
  5376. iMax,
  5377. ordered = this.ordered,
  5378. options = this.options,
  5379. orientation = options.orientation || this.defaultOptions.orientation,
  5380. axisOnTop = (orientation == 'top'),
  5381. margin;
  5382. if (options.margin && options.margin.item !== undefined) {
  5383. margin = options.margin.item;
  5384. }
  5385. else {
  5386. margin = this.defaultOptions.margin.item
  5387. }
  5388. // calculate new, non-overlapping positions
  5389. for (i = 0, iMax = ordered.length; i < iMax; i++) {
  5390. var item = ordered[i];
  5391. var collidingItem = null;
  5392. do {
  5393. // TODO: optimize checking for overlap. when there is a gap without items,
  5394. // you only need to check for items from the next item on, not from zero
  5395. collidingItem = this.checkOverlap(ordered, i, 0, i - 1, margin);
  5396. if (collidingItem != null) {
  5397. // There is a collision. Reposition the event above the colliding element
  5398. if (axisOnTop) {
  5399. item.top = collidingItem.top + collidingItem.height + margin;
  5400. }
  5401. else {
  5402. item.top = collidingItem.top - item.height - margin;
  5403. }
  5404. }
  5405. } while (collidingItem);
  5406. }
  5407. };
  5408. /**
  5409. * Check if the destiny position of given item overlaps with any
  5410. * of the other items from index itemStart to itemEnd.
  5411. * @param {Array} items Array with items
  5412. * @param {int} itemIndex Number of the item to be checked for overlap
  5413. * @param {int} itemStart First item to be checked.
  5414. * @param {int} itemEnd Last item to be checked.
  5415. * @return {Object | null} colliding item, or undefined when no collisions
  5416. * @param {Number} margin A minimum required margin.
  5417. * If margin is provided, the two items will be
  5418. * marked colliding when they overlap or
  5419. * when the margin between the two is smaller than
  5420. * the requested margin.
  5421. */
  5422. Stack.prototype.checkOverlap = function checkOverlap (items, itemIndex,
  5423. itemStart, itemEnd, margin) {
  5424. var collision = this.collision;
  5425. // we loop from end to start, as we suppose that the chance of a
  5426. // collision is larger for items at the end, so check these first.
  5427. var a = items[itemIndex];
  5428. for (var i = itemEnd; i >= itemStart; i--) {
  5429. var b = items[i];
  5430. if (collision(a, b, margin)) {
  5431. if (i != itemIndex) {
  5432. return b;
  5433. }
  5434. }
  5435. }
  5436. return null;
  5437. };
  5438. /**
  5439. * Test if the two provided items collide
  5440. * The items must have parameters left, width, top, and height.
  5441. * @param {Component} a The first item
  5442. * @param {Component} b The second item
  5443. * @param {Number} margin A minimum required margin.
  5444. * If margin is provided, the two items will be
  5445. * marked colliding when they overlap or
  5446. * when the margin between the two is smaller than
  5447. * the requested margin.
  5448. * @return {boolean} true if a and b collide, else false
  5449. */
  5450. Stack.prototype.collision = function collision (a, b, margin) {
  5451. return ((a.left - margin) < (b.left + b.width) &&
  5452. (a.left + a.width + margin) > b.left &&
  5453. (a.top - margin) < (b.top + b.height) &&
  5454. (a.top + a.height + margin) > b.top);
  5455. };
  5456. /**
  5457. * @constructor Range
  5458. * A Range controls a numeric range with a start and end value.
  5459. * The Range adjusts the range based on mouse events or programmatic changes,
  5460. * and triggers events when the range is changing or has been changed.
  5461. * @param {Object} [options] See description at Range.setOptions
  5462. * @extends Controller
  5463. */
  5464. function Range(options) {
  5465. this.id = util.randomUUID();
  5466. this.start = 0; // Number
  5467. this.end = 0; // Number
  5468. // this.options = options || {}; // TODO: fix range options
  5469. this.options = {
  5470. min: null,
  5471. max: null,
  5472. zoomMin: null,
  5473. zoomMax: null
  5474. };
  5475. this.listeners = [];
  5476. this.setOptions(options);
  5477. }
  5478. /**
  5479. * Set options for the range controller
  5480. * @param {Object} options Available options:
  5481. * {Number} start Set start value of the range
  5482. * {Number} end Set end value of the range
  5483. * {Number} min Minimum value for start
  5484. * {Number} max Maximum value for end
  5485. * {Number} zoomMin Set a minimum value for
  5486. * (end - start).
  5487. * {Number} zoomMax Set a maximum value for
  5488. * (end - start).
  5489. */
  5490. Range.prototype.setOptions = function (options) {
  5491. util.extend(this.options, options);
  5492. if (options.start != null || options.end != null) {
  5493. this.setRange(options.start, options.end);
  5494. }
  5495. };
  5496. /**
  5497. * Add listeners for mouse and touch events to the component
  5498. * @param {Component} component
  5499. * @param {String} event Available events: 'move', 'zoom'
  5500. * @param {String} direction Available directions: 'horizontal', 'vertical'
  5501. */
  5502. Range.prototype.subscribe = function (component, event, direction) {
  5503. var me = this;
  5504. var listener;
  5505. if (direction != 'horizontal' && direction != 'vertical') {
  5506. throw new TypeError('Unknown direction "' + direction + '". ' +
  5507. 'Choose "horizontal" or "vertical".');
  5508. }
  5509. //noinspection FallthroughInSwitchStatementJS
  5510. if (event == 'move') {
  5511. listener = {
  5512. component: component,
  5513. event: event,
  5514. direction: direction,
  5515. callback: function (event) {
  5516. me._onMouseDown(event, listener);
  5517. },
  5518. params: {}
  5519. };
  5520. component.on('mousedown', listener.callback);
  5521. me.listeners.push(listener);
  5522. }
  5523. else if (event == 'zoom') {
  5524. listener = {
  5525. component: component,
  5526. event: event,
  5527. direction: direction,
  5528. callback: function (event) {
  5529. me._onMouseWheel(event, listener);
  5530. },
  5531. params: {}
  5532. };
  5533. component.on('mousewheel', listener.callback);
  5534. me.listeners.push(listener);
  5535. }
  5536. else {
  5537. throw new TypeError('Unknown event "' + event + '". ' +
  5538. 'Choose "move" or "zoom".');
  5539. }
  5540. };
  5541. /**
  5542. * Event handler
  5543. * @param {String} event name of the event, for example 'click', 'mousemove'
  5544. * @param {function} callback callback handler, invoked with the raw HTML Event
  5545. * as parameter.
  5546. */
  5547. Range.prototype.on = function (event, callback) {
  5548. events.addListener(this, event, callback);
  5549. };
  5550. /**
  5551. * Trigger an event
  5552. * @param {String} event name of the event, available events: 'rangechange',
  5553. * 'rangechanged'
  5554. * @private
  5555. */
  5556. Range.prototype._trigger = function (event) {
  5557. events.trigger(this, event, {
  5558. start: this.start,
  5559. end: this.end
  5560. });
  5561. };
  5562. /**
  5563. * Set a new start and end range
  5564. * @param {Number} start
  5565. * @param {Number} end
  5566. */
  5567. Range.prototype.setRange = function(start, end) {
  5568. var changed = this._applyRange(start, end);
  5569. if (changed) {
  5570. this._trigger('rangechange');
  5571. this._trigger('rangechanged');
  5572. }
  5573. };
  5574. /**
  5575. * Set a new start and end range. This method is the same as setRange, but
  5576. * does not trigger a range change and range changed event, and it returns
  5577. * true when the range is changed
  5578. * @param {Number} start
  5579. * @param {Number} end
  5580. * @return {Boolean} changed
  5581. * @private
  5582. */
  5583. Range.prototype._applyRange = function(start, end) {
  5584. var newStart = (start != null) ? util.convert(start, 'Number') : this.start;
  5585. var newEnd = (end != null) ? util.convert(end, 'Number') : this.end;
  5586. var diff;
  5587. // check for valid number
  5588. if (isNaN(newStart)) {
  5589. throw new Error('Invalid start "' + start + '"');
  5590. }
  5591. if (isNaN(newEnd)) {
  5592. throw new Error('Invalid end "' + end + '"');
  5593. }
  5594. // prevent start < end
  5595. if (newEnd < newStart) {
  5596. newEnd = newStart;
  5597. }
  5598. // prevent start < min
  5599. if (this.options.min != null) {
  5600. var min = this.options.min.valueOf();
  5601. if (newStart < min) {
  5602. diff = (min - newStart);
  5603. newStart += diff;
  5604. newEnd += diff;
  5605. }
  5606. }
  5607. // prevent end > max
  5608. if (this.options.max != null) {
  5609. var max = this.options.max.valueOf();
  5610. if (newEnd > max) {
  5611. diff = (newEnd - max);
  5612. newStart -= diff;
  5613. newEnd -= diff;
  5614. }
  5615. }
  5616. // prevent (end-start) > zoomMin
  5617. if (this.options.zoomMin != null) {
  5618. var zoomMin = this.options.zoomMin.valueOf();
  5619. if (zoomMin < 0) {
  5620. zoomMin = 0;
  5621. }
  5622. if ((newEnd - newStart) < zoomMin) {
  5623. if ((this.end - this.start) > zoomMin) {
  5624. // zoom to the minimum
  5625. diff = (zoomMin - (newEnd - newStart));
  5626. newStart -= diff / 2;
  5627. newEnd += diff / 2;
  5628. }
  5629. else {
  5630. // ingore this action, we are already zoomed to the minimum
  5631. newStart = this.start;
  5632. newEnd = this.end;
  5633. }
  5634. }
  5635. }
  5636. // prevent (end-start) > zoomMin
  5637. if (this.options.zoomMax != null) {
  5638. var zoomMax = this.options.zoomMax.valueOf();
  5639. if (zoomMax < 0) {
  5640. zoomMax = 0;
  5641. }
  5642. if ((newEnd - newStart) > zoomMax) {
  5643. if ((this.end - this.start) < zoomMax) {
  5644. // zoom to the maximum
  5645. diff = ((newEnd - newStart) - zoomMax);
  5646. newStart += diff / 2;
  5647. newEnd -= diff / 2;
  5648. }
  5649. else {
  5650. // ingore this action, we are already zoomed to the maximum
  5651. newStart = this.start;
  5652. newEnd = this.end;
  5653. }
  5654. }
  5655. }
  5656. var changed = (this.start != newStart || this.end != newEnd);
  5657. this.start = newStart;
  5658. this.end = newEnd;
  5659. return changed;
  5660. };
  5661. /**
  5662. * Retrieve the current range.
  5663. * @return {Object} An object with start and end properties
  5664. */
  5665. Range.prototype.getRange = function() {
  5666. return {
  5667. start: this.start,
  5668. end: this.end
  5669. };
  5670. };
  5671. /**
  5672. * Calculate the conversion offset and factor for current range, based on
  5673. * the provided width
  5674. * @param {Number} width
  5675. * @returns {{offset: number, factor: number}} conversion
  5676. */
  5677. Range.prototype.conversion = function (width) {
  5678. var start = this.start;
  5679. var end = this.end;
  5680. return Range.conversion(this.start, this.end, width);
  5681. };
  5682. /**
  5683. * Static method to calculate the conversion offset and factor for a range,
  5684. * based on the provided start, end, and width
  5685. * @param {Number} start
  5686. * @param {Number} end
  5687. * @param {Number} width
  5688. * @returns {{offset: number, factor: number}} conversion
  5689. */
  5690. Range.conversion = function (start, end, width) {
  5691. if (width != 0 && (end - start != 0)) {
  5692. return {
  5693. offset: start,
  5694. factor: width / (end - start)
  5695. }
  5696. }
  5697. else {
  5698. return {
  5699. offset: 0,
  5700. factor: 1
  5701. };
  5702. }
  5703. };
  5704. /**
  5705. * Start moving horizontally or vertically
  5706. * @param {Event} event
  5707. * @param {Object} listener Listener containing the component and params
  5708. * @private
  5709. */
  5710. Range.prototype._onMouseDown = function(event, listener) {
  5711. event = event || window.event;
  5712. var params = listener.params;
  5713. // only react on left mouse button down
  5714. var leftButtonDown = event.which ? (event.which == 1) : (event.button == 1);
  5715. if (!leftButtonDown) {
  5716. return;
  5717. }
  5718. // get mouse position
  5719. params.mouseX = util.getPageX(event);
  5720. params.mouseY = util.getPageY(event);
  5721. params.previousLeft = 0;
  5722. params.previousOffset = 0;
  5723. params.moved = false;
  5724. params.start = this.start;
  5725. params.end = this.end;
  5726. var frame = listener.component.frame;
  5727. if (frame) {
  5728. frame.style.cursor = 'move';
  5729. }
  5730. // add event listeners to handle moving the contents
  5731. // we store the function onmousemove and onmouseup in the timeaxis,
  5732. // so we can remove the eventlisteners lateron in the function onmouseup
  5733. var me = this;
  5734. if (!params.onMouseMove) {
  5735. params.onMouseMove = function (event) {
  5736. me._onMouseMove(event, listener);
  5737. };
  5738. util.addEventListener(document, "mousemove", params.onMouseMove);
  5739. }
  5740. if (!params.onMouseUp) {
  5741. params.onMouseUp = function (event) {
  5742. me._onMouseUp(event, listener);
  5743. };
  5744. util.addEventListener(document, "mouseup", params.onMouseUp);
  5745. }
  5746. util.preventDefault(event);
  5747. };
  5748. /**
  5749. * Perform moving operating.
  5750. * This function activated from within the funcion TimeAxis._onMouseDown().
  5751. * @param {Event} event
  5752. * @param {Object} listener
  5753. * @private
  5754. */
  5755. Range.prototype._onMouseMove = function (event, listener) {
  5756. event = event || window.event;
  5757. var params = listener.params;
  5758. // calculate change in mouse position
  5759. var mouseX = util.getPageX(event);
  5760. var mouseY = util.getPageY(event);
  5761. if (params.mouseX == undefined) {
  5762. params.mouseX = mouseX;
  5763. }
  5764. if (params.mouseY == undefined) {
  5765. params.mouseY = mouseY;
  5766. }
  5767. var diffX = mouseX - params.mouseX;
  5768. var diffY = mouseY - params.mouseY;
  5769. var diff = (listener.direction == 'horizontal') ? diffX : diffY;
  5770. // if mouse movement is big enough, register it as a "moved" event
  5771. if (Math.abs(diff) >= 1) {
  5772. params.moved = true;
  5773. }
  5774. var interval = (params.end - params.start);
  5775. var width = (listener.direction == 'horizontal') ?
  5776. listener.component.width : listener.component.height;
  5777. var diffRange = -diff / width * interval;
  5778. this._applyRange(params.start + diffRange, params.end + diffRange);
  5779. // fire a rangechange event
  5780. this._trigger('rangechange');
  5781. util.preventDefault(event);
  5782. };
  5783. /**
  5784. * Stop moving operating.
  5785. * This function activated from within the function Range._onMouseDown().
  5786. * @param {event} event
  5787. * @param {Object} listener
  5788. * @private
  5789. */
  5790. Range.prototype._onMouseUp = function (event, listener) {
  5791. event = event || window.event;
  5792. var params = listener.params;
  5793. if (listener.component.frame) {
  5794. listener.component.frame.style.cursor = 'auto';
  5795. }
  5796. // remove event listeners here, important for Safari
  5797. if (params.onMouseMove) {
  5798. util.removeEventListener(document, "mousemove", params.onMouseMove);
  5799. params.onMouseMove = null;
  5800. }
  5801. if (params.onMouseUp) {
  5802. util.removeEventListener(document, "mouseup", params.onMouseUp);
  5803. params.onMouseUp = null;
  5804. }
  5805. //util.preventDefault(event);
  5806. if (params.moved) {
  5807. // fire a rangechanged event
  5808. this._trigger('rangechanged');
  5809. }
  5810. };
  5811. /**
  5812. * Event handler for mouse wheel event, used to zoom
  5813. * Code from http://adomas.org/javascript-mouse-wheel/
  5814. * @param {Event} event
  5815. * @param {Object} listener
  5816. * @private
  5817. */
  5818. Range.prototype._onMouseWheel = function(event, listener) {
  5819. event = event || window.event;
  5820. // retrieve delta
  5821. var delta = 0;
  5822. if (event.wheelDelta) { /* IE/Opera. */
  5823. delta = event.wheelDelta / 120;
  5824. } else if (event.detail) { /* Mozilla case. */
  5825. // In Mozilla, sign of delta is different than in IE.
  5826. // Also, delta is multiple of 3.
  5827. delta = -event.detail / 3;
  5828. }
  5829. // If delta is nonzero, handle it.
  5830. // Basically, delta is now positive if wheel was scrolled up,
  5831. // and negative, if wheel was scrolled down.
  5832. if (delta) {
  5833. var me = this;
  5834. var zoom = function () {
  5835. // perform the zoom action. Delta is normally 1 or -1
  5836. var zoomFactor = delta / 5.0;
  5837. var zoomAround = null;
  5838. var frame = listener.component.frame;
  5839. if (frame) {
  5840. var size, conversion;
  5841. if (listener.direction == 'horizontal') {
  5842. size = listener.component.width;
  5843. conversion = me.conversion(size);
  5844. var frameLeft = util.getAbsoluteLeft(frame);
  5845. var mouseX = util.getPageX(event);
  5846. zoomAround = (mouseX - frameLeft) / conversion.factor + conversion.offset;
  5847. }
  5848. else {
  5849. size = listener.component.height;
  5850. conversion = me.conversion(size);
  5851. var frameTop = util.getAbsoluteTop(frame);
  5852. var mouseY = util.getPageY(event);
  5853. zoomAround = ((frameTop + size - mouseY) - frameTop) / conversion.factor + conversion.offset;
  5854. }
  5855. }
  5856. me.zoom(zoomFactor, zoomAround);
  5857. };
  5858. zoom();
  5859. }
  5860. // Prevent default actions caused by mouse wheel.
  5861. // That might be ugly, but we handle scrolls somehow
  5862. // anyway, so don't bother here...
  5863. util.preventDefault(event);
  5864. };
  5865. /**
  5866. * Zoom the range the given zoomfactor in or out. Start and end date will
  5867. * be adjusted, and the timeline will be redrawn. You can optionally give a
  5868. * date around which to zoom.
  5869. * For example, try zoomfactor = 0.1 or -0.1
  5870. * @param {Number} zoomFactor Zooming amount. Positive value will zoom in,
  5871. * negative value will zoom out
  5872. * @param {Number} zoomAround Value around which will be zoomed. Optional
  5873. */
  5874. Range.prototype.zoom = function(zoomFactor, zoomAround) {
  5875. // if zoomAroundDate is not provided, take it half between start Date and end Date
  5876. if (zoomAround == null) {
  5877. zoomAround = (this.start + this.end) / 2;
  5878. }
  5879. // prevent zoom factor larger than 1 or smaller than -1 (larger than 1 will
  5880. // result in a start>=end )
  5881. if (zoomFactor >= 1) {
  5882. zoomFactor = 0.9;
  5883. }
  5884. if (zoomFactor <= -1) {
  5885. zoomFactor = -0.9;
  5886. }
  5887. // adjust a negative factor such that zooming in with 0.1 equals zooming
  5888. // out with a factor -0.1
  5889. if (zoomFactor < 0) {
  5890. zoomFactor = zoomFactor / (1 + zoomFactor);
  5891. }
  5892. // zoom start and end relative to the zoomAround value
  5893. var startDiff = (this.start - zoomAround);
  5894. var endDiff = (this.end - zoomAround);
  5895. // calculate new start and end
  5896. var newStart = this.start - startDiff * zoomFactor;
  5897. var newEnd = this.end - endDiff * zoomFactor;
  5898. this.setRange(newStart, newEnd);
  5899. };
  5900. /**
  5901. * Move the range with a given factor to the left or right. Start and end
  5902. * value will be adjusted. For example, try moveFactor = 0.1 or -0.1
  5903. * @param {Number} moveFactor Moving amount. Positive value will move right,
  5904. * negative value will move left
  5905. */
  5906. Range.prototype.move = function(moveFactor) {
  5907. // zoom start Date and end Date relative to the zoomAroundDate
  5908. var diff = (this.end - this.start);
  5909. // apply new values
  5910. var newStart = this.start + diff * moveFactor;
  5911. var newEnd = this.end + diff * moveFactor;
  5912. // TODO: reckon with min and max range
  5913. this.start = newStart;
  5914. this.end = newEnd;
  5915. };
  5916. /**
  5917. * Move the range to a new center point
  5918. * @param {Number} moveTo New center point of the range
  5919. */
  5920. Range.prototype.moveTo = function(moveTo) {
  5921. var center = (this.start + this.end) / 2;
  5922. var diff = center - moveTo;
  5923. // calculate new start and end
  5924. var newStart = this.start - diff;
  5925. var newEnd = this.end - diff;
  5926. this.setRange(newStart, newEnd);
  5927. }
  5928. /**
  5929. * @constructor Controller
  5930. *
  5931. * A Controller controls the reflows and repaints of all visual components
  5932. */
  5933. function Controller () {
  5934. this.id = util.randomUUID();
  5935. this.components = {};
  5936. this.repaintTimer = undefined;
  5937. this.reflowTimer = undefined;
  5938. }
  5939. /**
  5940. * Add a component to the controller
  5941. * @param {Component} component
  5942. */
  5943. Controller.prototype.add = function add(component) {
  5944. // validate the component
  5945. if (component.id == undefined) {
  5946. throw new Error('Component has no field id');
  5947. }
  5948. if (!(component instanceof Component) && !(component instanceof Controller)) {
  5949. throw new TypeError('Component must be an instance of ' +
  5950. 'prototype Component or Controller');
  5951. }
  5952. // add the component
  5953. component.controller = this;
  5954. this.components[component.id] = component;
  5955. };
  5956. /**
  5957. * Remove a component from the controller
  5958. * @param {Component | String} component
  5959. */
  5960. Controller.prototype.remove = function remove(component) {
  5961. var id;
  5962. for (id in this.components) {
  5963. if (this.components.hasOwnProperty(id)) {
  5964. if (id == component || this.components[id] == component) {
  5965. break;
  5966. }
  5967. }
  5968. }
  5969. if (id) {
  5970. delete this.components[id];
  5971. }
  5972. };
  5973. /**
  5974. * Request a reflow. The controller will schedule a reflow
  5975. * @param {Boolean} [force] If true, an immediate reflow is forced. Default
  5976. * is false.
  5977. */
  5978. Controller.prototype.requestReflow = function requestReflow(force) {
  5979. if (force) {
  5980. this.reflow();
  5981. }
  5982. else {
  5983. if (!this.reflowTimer) {
  5984. var me = this;
  5985. this.reflowTimer = setTimeout(function () {
  5986. me.reflowTimer = undefined;
  5987. me.reflow();
  5988. }, 0);
  5989. }
  5990. }
  5991. };
  5992. /**
  5993. * Request a repaint. The controller will schedule a repaint
  5994. * @param {Boolean} [force] If true, an immediate repaint is forced. Default
  5995. * is false.
  5996. */
  5997. Controller.prototype.requestRepaint = function requestRepaint(force) {
  5998. if (force) {
  5999. this.repaint();
  6000. }
  6001. else {
  6002. if (!this.repaintTimer) {
  6003. var me = this;
  6004. this.repaintTimer = setTimeout(function () {
  6005. me.repaintTimer = undefined;
  6006. me.repaint();
  6007. }, 0);
  6008. }
  6009. }
  6010. };
  6011. /**
  6012. * Repaint all components
  6013. */
  6014. Controller.prototype.repaint = function repaint() {
  6015. var changed = false;
  6016. // cancel any running repaint request
  6017. if (this.repaintTimer) {
  6018. clearTimeout(this.repaintTimer);
  6019. this.repaintTimer = undefined;
  6020. }
  6021. var done = {};
  6022. function repaint(component, id) {
  6023. if (!(id in done)) {
  6024. // first repaint the components on which this component is dependent
  6025. if (component.depends) {
  6026. component.depends.forEach(function (dep) {
  6027. repaint(dep, dep.id);
  6028. });
  6029. }
  6030. if (component.parent) {
  6031. repaint(component.parent, component.parent.id);
  6032. }
  6033. // repaint the component itself and mark as done
  6034. changed = component.repaint() || changed;
  6035. done[id] = true;
  6036. }
  6037. }
  6038. util.forEach(this.components, repaint);
  6039. // immediately reflow when needed
  6040. if (changed) {
  6041. this.reflow();
  6042. }
  6043. // TODO: limit the number of nested reflows/repaints, prevent loop
  6044. };
  6045. /**
  6046. * Reflow all components
  6047. */
  6048. Controller.prototype.reflow = function reflow() {
  6049. var resized = false;
  6050. // cancel any running repaint request
  6051. if (this.reflowTimer) {
  6052. clearTimeout(this.reflowTimer);
  6053. this.reflowTimer = undefined;
  6054. }
  6055. var done = {};
  6056. function reflow(component, id) {
  6057. if (!(id in done)) {
  6058. // first reflow the components on which this component is dependent
  6059. if (component.depends) {
  6060. component.depends.forEach(function (dep) {
  6061. reflow(dep, dep.id);
  6062. });
  6063. }
  6064. if (component.parent) {
  6065. reflow(component.parent, component.parent.id);
  6066. }
  6067. // reflow the component itself and mark as done
  6068. resized = component.reflow() || resized;
  6069. done[id] = true;
  6070. }
  6071. }
  6072. util.forEach(this.components, reflow);
  6073. // immediately repaint when needed
  6074. if (resized) {
  6075. this.repaint();
  6076. }
  6077. // TODO: limit the number of nested reflows/repaints, prevent loop
  6078. };
  6079. /**
  6080. * Prototype for visual components
  6081. */
  6082. function Component () {
  6083. this.id = null;
  6084. this.parent = null;
  6085. this.depends = null;
  6086. this.controller = null;
  6087. this.options = null;
  6088. this.frame = null; // main DOM element
  6089. this.top = 0;
  6090. this.left = 0;
  6091. this.width = 0;
  6092. this.height = 0;
  6093. }
  6094. /**
  6095. * Set parameters for the frame. Parameters will be merged in current parameter
  6096. * set.
  6097. * @param {Object} options Available parameters:
  6098. * {String | function} [className]
  6099. * {EventBus} [eventBus]
  6100. * {String | Number | function} [left]
  6101. * {String | Number | function} [top]
  6102. * {String | Number | function} [width]
  6103. * {String | Number | function} [height]
  6104. */
  6105. Component.prototype.setOptions = function setOptions(options) {
  6106. if (options) {
  6107. util.extend(this.options, options);
  6108. if (this.controller) {
  6109. this.requestRepaint();
  6110. this.requestReflow();
  6111. }
  6112. }
  6113. };
  6114. /**
  6115. * Get an option value by name
  6116. * The function will first check this.options object, and else will check
  6117. * this.defaultOptions.
  6118. * @param {String} name
  6119. * @return {*} value
  6120. */
  6121. Component.prototype.getOption = function getOption(name) {
  6122. var value;
  6123. if (this.options) {
  6124. value = this.options[name];
  6125. }
  6126. if (value === undefined && this.defaultOptions) {
  6127. value = this.defaultOptions[name];
  6128. }
  6129. return value;
  6130. };
  6131. /**
  6132. * Get the container element of the component, which can be used by a child to
  6133. * add its own widgets. Not all components do have a container for childs, in
  6134. * that case null is returned.
  6135. * @returns {HTMLElement | null} container
  6136. */
  6137. // TODO: get rid of the getContainer and getFrame methods, provide these via the options
  6138. Component.prototype.getContainer = function getContainer() {
  6139. // should be implemented by the component
  6140. return null;
  6141. };
  6142. /**
  6143. * Get the frame element of the component, the outer HTML DOM element.
  6144. * @returns {HTMLElement | null} frame
  6145. */
  6146. Component.prototype.getFrame = function getFrame() {
  6147. return this.frame;
  6148. };
  6149. /**
  6150. * Repaint the component
  6151. * @return {Boolean} changed
  6152. */
  6153. Component.prototype.repaint = function repaint() {
  6154. // should be implemented by the component
  6155. return false;
  6156. };
  6157. /**
  6158. * Reflow the component
  6159. * @return {Boolean} resized
  6160. */
  6161. Component.prototype.reflow = function reflow() {
  6162. // should be implemented by the component
  6163. return false;
  6164. };
  6165. /**
  6166. * Hide the component from the DOM
  6167. * @return {Boolean} changed
  6168. */
  6169. Component.prototype.hide = function hide() {
  6170. if (this.frame && this.frame.parentNode) {
  6171. this.frame.parentNode.removeChild(this.frame);
  6172. return true;
  6173. }
  6174. else {
  6175. return false;
  6176. }
  6177. };
  6178. /**
  6179. * Show the component in the DOM (when not already visible).
  6180. * A repaint will be executed when the component is not visible
  6181. * @return {Boolean} changed
  6182. */
  6183. Component.prototype.show = function show() {
  6184. if (!this.frame || !this.frame.parentNode) {
  6185. return this.repaint();
  6186. }
  6187. else {
  6188. return false;
  6189. }
  6190. };
  6191. /**
  6192. * Request a repaint. The controller will schedule a repaint
  6193. */
  6194. Component.prototype.requestRepaint = function requestRepaint() {
  6195. if (this.controller) {
  6196. this.controller.requestRepaint();
  6197. }
  6198. else {
  6199. throw new Error('Cannot request a repaint: no controller configured');
  6200. // TODO: just do a repaint when no parent is configured?
  6201. }
  6202. };
  6203. /**
  6204. * Request a reflow. The controller will schedule a reflow
  6205. */
  6206. Component.prototype.requestReflow = function requestReflow() {
  6207. if (this.controller) {
  6208. this.controller.requestReflow();
  6209. }
  6210. else {
  6211. throw new Error('Cannot request a reflow: no controller configured');
  6212. // TODO: just do a reflow when no parent is configured?
  6213. }
  6214. };
  6215. /**
  6216. * A panel can contain components
  6217. * @param {Component} [parent]
  6218. * @param {Component[]} [depends] Components on which this components depends
  6219. * (except for the parent)
  6220. * @param {Object} [options] Available parameters:
  6221. * {String | Number | function} [left]
  6222. * {String | Number | function} [top]
  6223. * {String | Number | function} [width]
  6224. * {String | Number | function} [height]
  6225. * {String | function} [className]
  6226. * @constructor Panel
  6227. * @extends Component
  6228. */
  6229. function Panel(parent, depends, options) {
  6230. this.id = util.randomUUID();
  6231. this.parent = parent;
  6232. this.depends = depends;
  6233. this.options = options || {};
  6234. }
  6235. Panel.prototype = new Component();
  6236. /**
  6237. * Set options. Will extend the current options.
  6238. * @param {Object} [options] Available parameters:
  6239. * {String | function} [className]
  6240. * {String | Number | function} [left]
  6241. * {String | Number | function} [top]
  6242. * {String | Number | function} [width]
  6243. * {String | Number | function} [height]
  6244. */
  6245. Panel.prototype.setOptions = Component.prototype.setOptions;
  6246. /**
  6247. * Get the container element of the panel, which can be used by a child to
  6248. * add its own widgets.
  6249. * @returns {HTMLElement} container
  6250. */
  6251. Panel.prototype.getContainer = function () {
  6252. return this.frame;
  6253. };
  6254. /**
  6255. * Repaint the component
  6256. * @return {Boolean} changed
  6257. */
  6258. Panel.prototype.repaint = function () {
  6259. var changed = 0,
  6260. update = util.updateProperty,
  6261. asSize = util.option.asSize,
  6262. options = this.options,
  6263. frame = this.frame;
  6264. if (!frame) {
  6265. frame = document.createElement('div');
  6266. frame.className = 'panel';
  6267. var className = options.className;
  6268. if (className) {
  6269. if (typeof className == 'function') {
  6270. util.addClassName(frame, String(className()));
  6271. }
  6272. else {
  6273. util.addClassName(frame, String(className));
  6274. }
  6275. }
  6276. this.frame = frame;
  6277. changed += 1;
  6278. }
  6279. if (!frame.parentNode) {
  6280. if (!this.parent) {
  6281. throw new Error('Cannot repaint panel: no parent attached');
  6282. }
  6283. var parentContainer = this.parent.getContainer();
  6284. if (!parentContainer) {
  6285. throw new Error('Cannot repaint panel: parent has no container element');
  6286. }
  6287. parentContainer.appendChild(frame);
  6288. changed += 1;
  6289. }
  6290. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  6291. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  6292. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  6293. changed += update(frame.style, 'height', asSize(options.height, '100%'));
  6294. return (changed > 0);
  6295. };
  6296. /**
  6297. * Reflow the component
  6298. * @return {Boolean} resized
  6299. */
  6300. Panel.prototype.reflow = function () {
  6301. var changed = 0,
  6302. update = util.updateProperty,
  6303. frame = this.frame;
  6304. if (frame) {
  6305. changed += update(this, 'top', frame.offsetTop);
  6306. changed += update(this, 'left', frame.offsetLeft);
  6307. changed += update(this, 'width', frame.offsetWidth);
  6308. changed += update(this, 'height', frame.offsetHeight);
  6309. }
  6310. else {
  6311. changed += 1;
  6312. }
  6313. return (changed > 0);
  6314. };
  6315. /**
  6316. * A root panel can hold components. The root panel must be initialized with
  6317. * a DOM element as container.
  6318. * @param {HTMLElement} container
  6319. * @param {Object} [options] Available parameters: see RootPanel.setOptions.
  6320. * @constructor RootPanel
  6321. * @extends Panel
  6322. */
  6323. function RootPanel(container, options) {
  6324. this.id = util.randomUUID();
  6325. this.container = container;
  6326. this.options = options || {};
  6327. this.defaultOptions = {
  6328. autoResize: true
  6329. };
  6330. this.listeners = {}; // event listeners
  6331. }
  6332. RootPanel.prototype = new Panel();
  6333. /**
  6334. * Set options. Will extend the current options.
  6335. * @param {Object} [options] Available parameters:
  6336. * {String | function} [className]
  6337. * {String | Number | function} [left]
  6338. * {String | Number | function} [top]
  6339. * {String | Number | function} [width]
  6340. * {String | Number | function} [height]
  6341. * {Boolean | function} [autoResize]
  6342. */
  6343. RootPanel.prototype.setOptions = Component.prototype.setOptions;
  6344. /**
  6345. * Repaint the component
  6346. * @return {Boolean} changed
  6347. */
  6348. RootPanel.prototype.repaint = function () {
  6349. var changed = 0,
  6350. update = util.updateProperty,
  6351. asSize = util.option.asSize,
  6352. options = this.options,
  6353. frame = this.frame;
  6354. if (!frame) {
  6355. frame = document.createElement('div');
  6356. frame.className = 'vis timeline rootpanel';
  6357. var className = options.className;
  6358. if (className) {
  6359. util.addClassName(frame, util.option.asString(className));
  6360. }
  6361. this.frame = frame;
  6362. changed += 1;
  6363. }
  6364. if (!frame.parentNode) {
  6365. if (!this.container) {
  6366. throw new Error('Cannot repaint root panel: no container attached');
  6367. }
  6368. this.container.appendChild(frame);
  6369. changed += 1;
  6370. }
  6371. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  6372. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  6373. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  6374. changed += update(frame.style, 'height', asSize(options.height, '100%'));
  6375. this._updateEventEmitters();
  6376. this._updateWatch();
  6377. return (changed > 0);
  6378. };
  6379. /**
  6380. * Reflow the component
  6381. * @return {Boolean} resized
  6382. */
  6383. RootPanel.prototype.reflow = function () {
  6384. var changed = 0,
  6385. update = util.updateProperty,
  6386. frame = this.frame;
  6387. if (frame) {
  6388. changed += update(this, 'top', frame.offsetTop);
  6389. changed += update(this, 'left', frame.offsetLeft);
  6390. changed += update(this, 'width', frame.offsetWidth);
  6391. changed += update(this, 'height', frame.offsetHeight);
  6392. }
  6393. else {
  6394. changed += 1;
  6395. }
  6396. return (changed > 0);
  6397. };
  6398. /**
  6399. * Update watching for resize, depending on the current option
  6400. * @private
  6401. */
  6402. RootPanel.prototype._updateWatch = function () {
  6403. var autoResize = this.getOption('autoResize');
  6404. if (autoResize) {
  6405. this._watch();
  6406. }
  6407. else {
  6408. this._unwatch();
  6409. }
  6410. };
  6411. /**
  6412. * Watch for changes in the size of the frame. On resize, the Panel will
  6413. * automatically redraw itself.
  6414. * @private
  6415. */
  6416. RootPanel.prototype._watch = function () {
  6417. var me = this;
  6418. this._unwatch();
  6419. var checkSize = function () {
  6420. var autoResize = me.getOption('autoResize');
  6421. if (!autoResize) {
  6422. // stop watching when the option autoResize is changed to false
  6423. me._unwatch();
  6424. return;
  6425. }
  6426. if (me.frame) {
  6427. // check whether the frame is resized
  6428. if ((me.frame.clientWidth != me.width) ||
  6429. (me.frame.clientHeight != me.height)) {
  6430. me.requestReflow();
  6431. }
  6432. }
  6433. };
  6434. // TODO: automatically cleanup the event listener when the frame is deleted
  6435. util.addEventListener(window, 'resize', checkSize);
  6436. this.watchTimer = setInterval(checkSize, 1000);
  6437. };
  6438. /**
  6439. * Stop watching for a resize of the frame.
  6440. * @private
  6441. */
  6442. RootPanel.prototype._unwatch = function () {
  6443. if (this.watchTimer) {
  6444. clearInterval(this.watchTimer);
  6445. this.watchTimer = undefined;
  6446. }
  6447. // TODO: remove event listener on window.resize
  6448. };
  6449. /**
  6450. * Event handler
  6451. * @param {String} event name of the event, for example 'click', 'mousemove'
  6452. * @param {function} callback callback handler, invoked with the raw HTML Event
  6453. * as parameter.
  6454. */
  6455. RootPanel.prototype.on = function (event, callback) {
  6456. // register the listener at this component
  6457. var arr = this.listeners[event];
  6458. if (!arr) {
  6459. arr = [];
  6460. this.listeners[event] = arr;
  6461. }
  6462. arr.push(callback);
  6463. this._updateEventEmitters();
  6464. };
  6465. /**
  6466. * Update the event listeners for all event emitters
  6467. * @private
  6468. */
  6469. RootPanel.prototype._updateEventEmitters = function () {
  6470. if (this.listeners) {
  6471. var me = this;
  6472. util.forEach(this.listeners, function (listeners, event) {
  6473. if (!me.emitters) {
  6474. me.emitters = {};
  6475. }
  6476. if (!(event in me.emitters)) {
  6477. // create event
  6478. var frame = me.frame;
  6479. if (frame) {
  6480. //console.log('Created a listener for event ' + event + ' on component ' + me.id); // TODO: cleanup logging
  6481. var callback = function(event) {
  6482. listeners.forEach(function (listener) {
  6483. // TODO: filter on event target!
  6484. listener(event);
  6485. });
  6486. };
  6487. me.emitters[event] = callback;
  6488. util.addEventListener(frame, event, callback);
  6489. }
  6490. }
  6491. });
  6492. // TODO: be able to delete event listeners
  6493. // TODO: be able to move event listeners to a parent when available
  6494. }
  6495. };
  6496. /**
  6497. * A horizontal time axis
  6498. * @param {Component} parent
  6499. * @param {Component[]} [depends] Components on which this components depends
  6500. * (except for the parent)
  6501. * @param {Object} [options] See TimeAxis.setOptions for the available
  6502. * options.
  6503. * @constructor TimeAxis
  6504. * @extends Component
  6505. */
  6506. function TimeAxis (parent, depends, options) {
  6507. this.id = util.randomUUID();
  6508. this.parent = parent;
  6509. this.depends = depends;
  6510. this.dom = {
  6511. majorLines: [],
  6512. majorTexts: [],
  6513. minorLines: [],
  6514. minorTexts: [],
  6515. redundant: {
  6516. majorLines: [],
  6517. majorTexts: [],
  6518. minorLines: [],
  6519. minorTexts: []
  6520. }
  6521. };
  6522. this.props = {
  6523. range: {
  6524. start: 0,
  6525. end: 0,
  6526. minimumStep: 0
  6527. },
  6528. lineTop: 0
  6529. };
  6530. this.options = options || {};
  6531. this.defaultOptions = {
  6532. orientation: 'bottom', // supported: 'top', 'bottom'
  6533. // TODO: implement timeaxis orientations 'left' and 'right'
  6534. showMinorLabels: true,
  6535. showMajorLabels: true
  6536. };
  6537. this.conversion = null;
  6538. this.range = null;
  6539. }
  6540. TimeAxis.prototype = new Component();
  6541. // TODO: comment options
  6542. TimeAxis.prototype.setOptions = Component.prototype.setOptions;
  6543. /**
  6544. * Set a range (start and end)
  6545. * @param {Range | Object} range A Range or an object containing start and end.
  6546. */
  6547. TimeAxis.prototype.setRange = function (range) {
  6548. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  6549. throw new TypeError('Range must be an instance of Range, ' +
  6550. 'or an object containing start and end.');
  6551. }
  6552. this.range = range;
  6553. };
  6554. /**
  6555. * Convert a position on screen (pixels) to a datetime
  6556. * @param {int} x Position on the screen in pixels
  6557. * @return {Date} time The datetime the corresponds with given position x
  6558. */
  6559. TimeAxis.prototype.toTime = function(x) {
  6560. var conversion = this.conversion;
  6561. return new Date(x / conversion.factor + conversion.offset);
  6562. };
  6563. /**
  6564. * Convert a datetime (Date object) into a position on the screen
  6565. * @param {Date} time A date
  6566. * @return {int} x The position on the screen in pixels which corresponds
  6567. * with the given date.
  6568. * @private
  6569. */
  6570. TimeAxis.prototype.toScreen = function(time) {
  6571. var conversion = this.conversion;
  6572. return (time.valueOf() - conversion.offset) * conversion.factor;
  6573. };
  6574. /**
  6575. * Repaint the component
  6576. * @return {Boolean} changed
  6577. */
  6578. TimeAxis.prototype.repaint = function () {
  6579. var changed = 0,
  6580. update = util.updateProperty,
  6581. asSize = util.option.asSize,
  6582. options = this.options,
  6583. orientation = this.getOption('orientation'),
  6584. props = this.props,
  6585. step = this.step;
  6586. var frame = this.frame;
  6587. if (!frame) {
  6588. frame = document.createElement('div');
  6589. this.frame = frame;
  6590. changed += 1;
  6591. }
  6592. frame.className = 'axis ' + orientation;
  6593. // TODO: custom className?
  6594. if (!frame.parentNode) {
  6595. if (!this.parent) {
  6596. throw new Error('Cannot repaint time axis: no parent attached');
  6597. }
  6598. var parentContainer = this.parent.getContainer();
  6599. if (!parentContainer) {
  6600. throw new Error('Cannot repaint time axis: parent has no container element');
  6601. }
  6602. parentContainer.appendChild(frame);
  6603. changed += 1;
  6604. }
  6605. var parent = frame.parentNode;
  6606. if (parent) {
  6607. var beforeChild = frame.nextSibling;
  6608. parent.removeChild(frame); // take frame offline while updating (is almost twice as fast)
  6609. var defaultTop = (orientation == 'bottom' && this.props.parentHeight && this.height) ?
  6610. (this.props.parentHeight - this.height) + 'px' :
  6611. '0px';
  6612. changed += update(frame.style, 'top', asSize(options.top, defaultTop));
  6613. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  6614. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  6615. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  6616. // get characters width and height
  6617. this._repaintMeasureChars();
  6618. if (this.step) {
  6619. this._repaintStart();
  6620. step.first();
  6621. var xFirstMajorLabel = undefined;
  6622. var max = 0;
  6623. while (step.hasNext() && max < 1000) {
  6624. max++;
  6625. var cur = step.getCurrent(),
  6626. x = this.toScreen(cur),
  6627. isMajor = step.isMajor();
  6628. // TODO: lines must have a width, such that we can create css backgrounds
  6629. if (this.getOption('showMinorLabels')) {
  6630. this._repaintMinorText(x, step.getLabelMinor());
  6631. }
  6632. if (isMajor && this.getOption('showMajorLabels')) {
  6633. if (x > 0) {
  6634. if (xFirstMajorLabel == undefined) {
  6635. xFirstMajorLabel = x;
  6636. }
  6637. this._repaintMajorText(x, step.getLabelMajor());
  6638. }
  6639. this._repaintMajorLine(x);
  6640. }
  6641. else {
  6642. this._repaintMinorLine(x);
  6643. }
  6644. step.next();
  6645. }
  6646. // create a major label on the left when needed
  6647. if (this.getOption('showMajorLabels')) {
  6648. var leftTime = this.toTime(0),
  6649. leftText = step.getLabelMajor(leftTime),
  6650. widthText = leftText.length * (props.majorCharWidth || 10) + 10; // upper bound estimation
  6651. if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) {
  6652. this._repaintMajorText(0, leftText);
  6653. }
  6654. }
  6655. this._repaintEnd();
  6656. }
  6657. this._repaintLine();
  6658. // put frame online again
  6659. if (beforeChild) {
  6660. parent.insertBefore(frame, beforeChild);
  6661. }
  6662. else {
  6663. parent.appendChild(frame)
  6664. }
  6665. }
  6666. return (changed > 0);
  6667. };
  6668. /**
  6669. * Start a repaint. Move all DOM elements to a redundant list, where they
  6670. * can be picked for re-use, or can be cleaned up in the end
  6671. * @private
  6672. */
  6673. TimeAxis.prototype._repaintStart = function () {
  6674. var dom = this.dom,
  6675. redundant = dom.redundant;
  6676. redundant.majorLines = dom.majorLines;
  6677. redundant.majorTexts = dom.majorTexts;
  6678. redundant.minorLines = dom.minorLines;
  6679. redundant.minorTexts = dom.minorTexts;
  6680. dom.majorLines = [];
  6681. dom.majorTexts = [];
  6682. dom.minorLines = [];
  6683. dom.minorTexts = [];
  6684. };
  6685. /**
  6686. * End a repaint. Cleanup leftover DOM elements in the redundant list
  6687. * @private
  6688. */
  6689. TimeAxis.prototype._repaintEnd = function () {
  6690. util.forEach(this.dom.redundant, function (arr) {
  6691. while (arr.length) {
  6692. var elem = arr.pop();
  6693. if (elem && elem.parentNode) {
  6694. elem.parentNode.removeChild(elem);
  6695. }
  6696. }
  6697. });
  6698. };
  6699. /**
  6700. * Create a minor label for the axis at position x
  6701. * @param {Number} x
  6702. * @param {String} text
  6703. * @private
  6704. */
  6705. TimeAxis.prototype._repaintMinorText = function (x, text) {
  6706. // reuse redundant label
  6707. var label = this.dom.redundant.minorTexts.shift();
  6708. if (!label) {
  6709. // create new label
  6710. var content = document.createTextNode('');
  6711. label = document.createElement('div');
  6712. label.appendChild(content);
  6713. label.className = 'text minor';
  6714. this.frame.appendChild(label);
  6715. }
  6716. this.dom.minorTexts.push(label);
  6717. label.childNodes[0].nodeValue = text;
  6718. label.style.left = x + 'px';
  6719. label.style.top = this.props.minorLabelTop + 'px';
  6720. //label.title = title; // TODO: this is a heavy operation
  6721. };
  6722. /**
  6723. * Create a Major label for the axis at position x
  6724. * @param {Number} x
  6725. * @param {String} text
  6726. * @private
  6727. */
  6728. TimeAxis.prototype._repaintMajorText = function (x, text) {
  6729. // reuse redundant label
  6730. var label = this.dom.redundant.majorTexts.shift();
  6731. if (!label) {
  6732. // create label
  6733. var content = document.createTextNode(text);
  6734. label = document.createElement('div');
  6735. label.className = 'text major';
  6736. label.appendChild(content);
  6737. this.frame.appendChild(label);
  6738. }
  6739. this.dom.majorTexts.push(label);
  6740. label.childNodes[0].nodeValue = text;
  6741. label.style.top = this.props.majorLabelTop + 'px';
  6742. label.style.left = x + 'px';
  6743. //label.title = title; // TODO: this is a heavy operation
  6744. };
  6745. /**
  6746. * Create a minor line for the axis at position x
  6747. * @param {Number} x
  6748. * @private
  6749. */
  6750. TimeAxis.prototype._repaintMinorLine = function (x) {
  6751. // reuse redundant line
  6752. var line = this.dom.redundant.minorLines.shift();
  6753. if (!line) {
  6754. // create vertical line
  6755. line = document.createElement('div');
  6756. line.className = 'grid vertical minor';
  6757. this.frame.appendChild(line);
  6758. }
  6759. this.dom.minorLines.push(line);
  6760. var props = this.props;
  6761. line.style.top = props.minorLineTop + 'px';
  6762. line.style.height = props.minorLineHeight + 'px';
  6763. line.style.left = (x - props.minorLineWidth / 2) + 'px';
  6764. };
  6765. /**
  6766. * Create a Major line for the axis at position x
  6767. * @param {Number} x
  6768. * @private
  6769. */
  6770. TimeAxis.prototype._repaintMajorLine = function (x) {
  6771. // reuse redundant line
  6772. var line = this.dom.redundant.majorLines.shift();
  6773. if (!line) {
  6774. // create vertical line
  6775. line = document.createElement('DIV');
  6776. line.className = 'grid vertical major';
  6777. this.frame.appendChild(line);
  6778. }
  6779. this.dom.majorLines.push(line);
  6780. var props = this.props;
  6781. line.style.top = props.majorLineTop + 'px';
  6782. line.style.left = (x - props.majorLineWidth / 2) + 'px';
  6783. line.style.height = props.majorLineHeight + 'px';
  6784. };
  6785. /**
  6786. * Repaint the horizontal line for the axis
  6787. * @private
  6788. */
  6789. TimeAxis.prototype._repaintLine = function() {
  6790. var line = this.dom.line,
  6791. frame = this.frame,
  6792. options = this.options;
  6793. // line before all axis elements
  6794. if (this.getOption('showMinorLabels') || this.getOption('showMajorLabels')) {
  6795. if (line) {
  6796. // put this line at the end of all childs
  6797. frame.removeChild(line);
  6798. frame.appendChild(line);
  6799. }
  6800. else {
  6801. // create the axis line
  6802. line = document.createElement('div');
  6803. line.className = 'grid horizontal major';
  6804. frame.appendChild(line);
  6805. this.dom.line = line;
  6806. }
  6807. line.style.top = this.props.lineTop + 'px';
  6808. }
  6809. else {
  6810. if (line && axis.parentElement) {
  6811. frame.removeChild(axis.line);
  6812. delete this.dom.line;
  6813. }
  6814. }
  6815. };
  6816. /**
  6817. * Create characters used to determine the size of text on the axis
  6818. * @private
  6819. */
  6820. TimeAxis.prototype._repaintMeasureChars = function () {
  6821. // calculate the width and height of a single character
  6822. // this is used to calculate the step size, and also the positioning of the
  6823. // axis
  6824. var dom = this.dom,
  6825. text;
  6826. if (!dom.measureCharMinor) {
  6827. text = document.createTextNode('0');
  6828. var measureCharMinor = document.createElement('DIV');
  6829. measureCharMinor.className = 'text minor measure';
  6830. measureCharMinor.appendChild(text);
  6831. this.frame.appendChild(measureCharMinor);
  6832. dom.measureCharMinor = measureCharMinor;
  6833. }
  6834. if (!dom.measureCharMajor) {
  6835. text = document.createTextNode('0');
  6836. var measureCharMajor = document.createElement('DIV');
  6837. measureCharMajor.className = 'text major measure';
  6838. measureCharMajor.appendChild(text);
  6839. this.frame.appendChild(measureCharMajor);
  6840. dom.measureCharMajor = measureCharMajor;
  6841. }
  6842. };
  6843. /**
  6844. * Reflow the component
  6845. * @return {Boolean} resized
  6846. */
  6847. TimeAxis.prototype.reflow = function () {
  6848. var changed = 0,
  6849. update = util.updateProperty,
  6850. frame = this.frame,
  6851. range = this.range;
  6852. if (!range) {
  6853. throw new Error('Cannot repaint time axis: no range configured');
  6854. }
  6855. if (frame) {
  6856. changed += update(this, 'top', frame.offsetTop);
  6857. changed += update(this, 'left', frame.offsetLeft);
  6858. // calculate size of a character
  6859. var props = this.props,
  6860. showMinorLabels = this.getOption('showMinorLabels'),
  6861. showMajorLabels = this.getOption('showMajorLabels'),
  6862. measureCharMinor = this.dom.measureCharMinor,
  6863. measureCharMajor = this.dom.measureCharMajor;
  6864. if (measureCharMinor) {
  6865. props.minorCharHeight = measureCharMinor.clientHeight;
  6866. props.minorCharWidth = measureCharMinor.clientWidth;
  6867. }
  6868. if (measureCharMajor) {
  6869. props.majorCharHeight = measureCharMajor.clientHeight;
  6870. props.majorCharWidth = measureCharMajor.clientWidth;
  6871. }
  6872. var parentHeight = frame.parentNode ? frame.parentNode.offsetHeight : 0;
  6873. if (parentHeight != props.parentHeight) {
  6874. props.parentHeight = parentHeight;
  6875. changed += 1;
  6876. }
  6877. switch (this.getOption('orientation')) {
  6878. case 'bottom':
  6879. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  6880. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  6881. props.minorLabelTop = 0;
  6882. props.majorLabelTop = props.minorLabelTop + props.minorLabelHeight;
  6883. props.minorLineTop = -this.top;
  6884. props.minorLineHeight = Math.max(this.top + props.majorLabelHeight, 0);
  6885. props.minorLineWidth = 1; // TODO: really calculate width
  6886. props.majorLineTop = -this.top;
  6887. props.majorLineHeight = Math.max(this.top + props.minorLabelHeight + props.majorLabelHeight, 0);
  6888. props.majorLineWidth = 1; // TODO: really calculate width
  6889. props.lineTop = 0;
  6890. break;
  6891. case 'top':
  6892. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  6893. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  6894. props.majorLabelTop = 0;
  6895. props.minorLabelTop = props.majorLabelTop + props.majorLabelHeight;
  6896. props.minorLineTop = props.minorLabelTop;
  6897. props.minorLineHeight = Math.max(parentHeight - props.majorLabelHeight - this.top);
  6898. props.minorLineWidth = 1; // TODO: really calculate width
  6899. props.majorLineTop = 0;
  6900. props.majorLineHeight = Math.max(parentHeight - this.top);
  6901. props.majorLineWidth = 1; // TODO: really calculate width
  6902. props.lineTop = props.majorLabelHeight + props.minorLabelHeight;
  6903. break;
  6904. default:
  6905. throw new Error('Unkown orientation "' + this.getOption('orientation') + '"');
  6906. }
  6907. var height = props.minorLabelHeight + props.majorLabelHeight;
  6908. changed += update(this, 'width', frame.offsetWidth);
  6909. changed += update(this, 'height', height);
  6910. // calculate range and step
  6911. this._updateConversion();
  6912. var start = util.convert(range.start, 'Date'),
  6913. end = util.convert(range.end, 'Date'),
  6914. minimumStep = this.toTime((props.minorCharWidth || 10) * 5) - this.toTime(0);
  6915. this.step = new TimeStep(start, end, minimumStep);
  6916. changed += update(props.range, 'start', start.valueOf());
  6917. changed += update(props.range, 'end', end.valueOf());
  6918. changed += update(props.range, 'minimumStep', minimumStep.valueOf());
  6919. }
  6920. return (changed > 0);
  6921. };
  6922. /**
  6923. * Calculate the factor and offset to convert a position on screen to the
  6924. * corresponding date and vice versa.
  6925. * After the method _updateConversion is executed once, the methods toTime
  6926. * and toScreen can be used.
  6927. * @private
  6928. */
  6929. TimeAxis.prototype._updateConversion = function() {
  6930. var range = this.range;
  6931. if (!range) {
  6932. throw new Error('No range configured');
  6933. }
  6934. if (range.conversion) {
  6935. this.conversion = range.conversion(this.width);
  6936. }
  6937. else {
  6938. this.conversion = Range.conversion(range.start, range.end, this.width);
  6939. }
  6940. };
  6941. /**
  6942. * An ItemSet holds a set of items and ranges which can be displayed in a
  6943. * range. The width is determined by the parent of the ItemSet, and the height
  6944. * is determined by the size of the items.
  6945. * @param {Component} parent
  6946. * @param {Component[]} [depends] Components on which this components depends
  6947. * (except for the parent)
  6948. * @param {Object} [options] See ItemSet.setOptions for the available
  6949. * options.
  6950. * @constructor ItemSet
  6951. * @extends Panel
  6952. */
  6953. // TODO: improve performance by replacing all Array.forEach with a for loop
  6954. function ItemSet(parent, depends, options) {
  6955. this.id = util.randomUUID();
  6956. this.parent = parent;
  6957. this.depends = depends;
  6958. // one options object is shared by this itemset and all its items
  6959. this.options = options || {};
  6960. this.defaultOptions = {
  6961. type: 'box',
  6962. align: 'center',
  6963. orientation: 'bottom',
  6964. margin: {
  6965. axis: 20,
  6966. item: 10
  6967. },
  6968. padding: 5
  6969. };
  6970. this.dom = {};
  6971. var me = this;
  6972. this.itemsData = null; // DataSet
  6973. this.range = null; // Range or Object {start: number, end: number}
  6974. this.listeners = {
  6975. 'add': function (event, params, senderId) {
  6976. if (senderId != me.id) {
  6977. me._onAdd(params.items);
  6978. }
  6979. },
  6980. 'update': function (event, params, senderId) {
  6981. if (senderId != me.id) {
  6982. me._onUpdate(params.items);
  6983. }
  6984. },
  6985. 'remove': function (event, params, senderId) {
  6986. if (senderId != me.id) {
  6987. me._onRemove(params.items);
  6988. }
  6989. }
  6990. };
  6991. this.items = {}; // object with an Item for every data item
  6992. this.queue = {}; // queue with id/actions: 'add', 'update', 'delete'
  6993. this.stack = new Stack(this, Object.create(this.options));
  6994. this.conversion = null;
  6995. // TODO: ItemSet should also attach event listeners for rangechange and rangechanged, like timeaxis
  6996. }
  6997. ItemSet.prototype = new Panel();
  6998. // available item types will be registered here
  6999. ItemSet.types = {
  7000. box: ItemBox,
  7001. range: ItemRange,
  7002. point: ItemPoint
  7003. };
  7004. /**
  7005. * Set options for the ItemSet. Existing options will be extended/overwritten.
  7006. * @param {Object} [options] The following options are available:
  7007. * {String | function} [className]
  7008. * class name for the itemset
  7009. * {String} [type]
  7010. * Default type for the items. Choose from 'box'
  7011. * (default), 'point', or 'range'. The default
  7012. * Style can be overwritten by individual items.
  7013. * {String} align
  7014. * Alignment for the items, only applicable for
  7015. * ItemBox. Choose 'center' (default), 'left', or
  7016. * 'right'.
  7017. * {String} orientation
  7018. * Orientation of the item set. Choose 'top' or
  7019. * 'bottom' (default).
  7020. * {Number} margin.axis
  7021. * Margin between the axis and the items in pixels.
  7022. * Default is 20.
  7023. * {Number} margin.item
  7024. * Margin between items in pixels. Default is 10.
  7025. * {Number} padding
  7026. * Padding of the contents of an item in pixels.
  7027. * Must correspond with the items css. Default is 5.
  7028. */
  7029. ItemSet.prototype.setOptions = Component.prototype.setOptions;
  7030. /**
  7031. * Set range (start and end).
  7032. * @param {Range | Object} range A Range or an object containing start and end.
  7033. */
  7034. ItemSet.prototype.setRange = function setRange(range) {
  7035. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  7036. throw new TypeError('Range must be an instance of Range, ' +
  7037. 'or an object containing start and end.');
  7038. }
  7039. this.range = range;
  7040. };
  7041. /**
  7042. * Repaint the component
  7043. * @return {Boolean} changed
  7044. */
  7045. ItemSet.prototype.repaint = function repaint() {
  7046. var changed = 0,
  7047. update = util.updateProperty,
  7048. asSize = util.option.asSize,
  7049. options = this.options,
  7050. orientation = this.getOption('orientation'),
  7051. defaultOptions = this.defaultOptions,
  7052. frame = this.frame;
  7053. if (!frame) {
  7054. frame = document.createElement('div');
  7055. frame.className = 'itemset';
  7056. var className = options.className;
  7057. if (className) {
  7058. util.addClassName(frame, util.option.asString(className));
  7059. }
  7060. // create background panel
  7061. var background = document.createElement('div');
  7062. background.className = 'background';
  7063. frame.appendChild(background);
  7064. this.dom.background = background;
  7065. // create foreground panel
  7066. var foreground = document.createElement('div');
  7067. foreground.className = 'foreground';
  7068. frame.appendChild(foreground);
  7069. this.dom.foreground = foreground;
  7070. // create axis panel
  7071. var axis = document.createElement('div');
  7072. axis.className = 'itemset-axis';
  7073. //frame.appendChild(axis);
  7074. this.dom.axis = axis;
  7075. this.frame = frame;
  7076. changed += 1;
  7077. }
  7078. if (!this.parent) {
  7079. throw new Error('Cannot repaint itemset: no parent attached');
  7080. }
  7081. var parentContainer = this.parent.getContainer();
  7082. if (!parentContainer) {
  7083. throw new Error('Cannot repaint itemset: parent has no container element');
  7084. }
  7085. if (!frame.parentNode) {
  7086. parentContainer.appendChild(frame);
  7087. changed += 1;
  7088. }
  7089. if (!this.dom.axis.parentNode) {
  7090. parentContainer.appendChild(this.dom.axis);
  7091. changed += 1;
  7092. }
  7093. // reposition frame
  7094. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  7095. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  7096. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  7097. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  7098. // reposition axis
  7099. changed += update(this.dom.axis.style, 'left', asSize(options.left, '0px'));
  7100. changed += update(this.dom.axis.style, 'width', asSize(options.width, '100%'));
  7101. if (orientation == 'bottom') {
  7102. changed += update(this.dom.axis.style, 'top', (this.height + this.top) + 'px');
  7103. }
  7104. else { // orientation == 'top'
  7105. changed += update(this.dom.axis.style, 'top', this.top + 'px');
  7106. }
  7107. this._updateConversion();
  7108. var me = this,
  7109. queue = this.queue,
  7110. itemsData = this.itemsData,
  7111. items = this.items,
  7112. dataOptions = {
  7113. // TODO: cleanup
  7114. // fields: [(itemsData && itemsData.fieldId || 'id'), 'start', 'end', 'content', 'type', 'className']
  7115. };
  7116. // show/hide added/changed/removed items
  7117. Object.keys(queue).forEach(function (id) {
  7118. //var entry = queue[id];
  7119. var action = queue[id];
  7120. var item = items[id];
  7121. //var item = entry.item;
  7122. //noinspection FallthroughInSwitchStatementJS
  7123. switch (action) {
  7124. case 'add':
  7125. case 'update':
  7126. var itemData = itemsData && itemsData.get(id, dataOptions);
  7127. if (itemData) {
  7128. var type = itemData.type ||
  7129. (itemData.start && itemData.end && 'range') ||
  7130. options.type ||
  7131. 'box';
  7132. var constructor = ItemSet.types[type];
  7133. // TODO: how to handle items with invalid data? hide them and give a warning? or throw an error?
  7134. if (item) {
  7135. // update item
  7136. if (!constructor || !(item instanceof constructor)) {
  7137. // item type has changed, hide and delete the item
  7138. changed += item.hide();
  7139. item = null;
  7140. }
  7141. else {
  7142. item.data = itemData; // TODO: create a method item.setData ?
  7143. changed++;
  7144. }
  7145. }
  7146. if (!item) {
  7147. // create item
  7148. if (constructor) {
  7149. item = new constructor(me, itemData, options, defaultOptions);
  7150. changed++;
  7151. }
  7152. else {
  7153. throw new TypeError('Unknown item type "' + type + '"');
  7154. }
  7155. }
  7156. // force a repaint (not only a reposition)
  7157. item.repaint();
  7158. items[id] = item;
  7159. }
  7160. // update queue
  7161. delete queue[id];
  7162. break;
  7163. case 'remove':
  7164. if (item) {
  7165. // remove DOM of the item
  7166. changed += item.hide();
  7167. }
  7168. // update lists
  7169. delete items[id];
  7170. delete queue[id];
  7171. break;
  7172. default:
  7173. console.log('Error: unknown action "' + action + '"');
  7174. }
  7175. });
  7176. // reposition all items. Show items only when in the visible area
  7177. util.forEach(this.items, function (item) {
  7178. if (item.visible) {
  7179. changed += item.show();
  7180. item.reposition();
  7181. }
  7182. else {
  7183. changed += item.hide();
  7184. }
  7185. });
  7186. return (changed > 0);
  7187. };
  7188. /**
  7189. * Get the foreground container element
  7190. * @return {HTMLElement} foreground
  7191. */
  7192. ItemSet.prototype.getForeground = function getForeground() {
  7193. return this.dom.foreground;
  7194. };
  7195. /**
  7196. * Get the background container element
  7197. * @return {HTMLElement} background
  7198. */
  7199. ItemSet.prototype.getBackground = function getBackground() {
  7200. return this.dom.background;
  7201. };
  7202. /**
  7203. * Get the axis container element
  7204. * @return {HTMLElement} axis
  7205. */
  7206. ItemSet.prototype.getAxis = function getAxis() {
  7207. return this.dom.axis;
  7208. };
  7209. /**
  7210. * Reflow the component
  7211. * @return {Boolean} resized
  7212. */
  7213. ItemSet.prototype.reflow = function reflow () {
  7214. var changed = 0,
  7215. options = this.options,
  7216. marginAxis = options.margin && options.margin.axis || this.defaultOptions.margin.axis,
  7217. marginItem = options.margin && options.margin.item || this.defaultOptions.margin.item,
  7218. update = util.updateProperty,
  7219. asNumber = util.option.asNumber,
  7220. asSize = util.option.asSize,
  7221. frame = this.frame;
  7222. if (frame) {
  7223. this._updateConversion();
  7224. util.forEach(this.items, function (item) {
  7225. changed += item.reflow();
  7226. });
  7227. // TODO: stack.update should be triggered via an event, in stack itself
  7228. // TODO: only update the stack when there are changed items
  7229. this.stack.update();
  7230. var maxHeight = asNumber(options.maxHeight);
  7231. var fixedHeight = (asSize(options.height) != null);
  7232. var height;
  7233. if (fixedHeight) {
  7234. height = frame.offsetHeight;
  7235. }
  7236. else {
  7237. // height is not specified, determine the height from the height and positioned items
  7238. var visibleItems = this.stack.ordered; // TODO: not so nice way to get the filtered items
  7239. if (visibleItems.length) {
  7240. var min = visibleItems[0].top;
  7241. var max = visibleItems[0].top + visibleItems[0].height;
  7242. util.forEach(visibleItems, function (item) {
  7243. min = Math.min(min, item.top);
  7244. max = Math.max(max, (item.top + item.height));
  7245. });
  7246. height = (max - min) + marginAxis + marginItem;
  7247. }
  7248. else {
  7249. height = marginAxis + marginItem;
  7250. }
  7251. }
  7252. if (maxHeight != null) {
  7253. height = Math.min(height, maxHeight);
  7254. }
  7255. changed += update(this, 'height', height);
  7256. // calculate height from items
  7257. changed += update(this, 'top', frame.offsetTop);
  7258. changed += update(this, 'left', frame.offsetLeft);
  7259. changed += update(this, 'width', frame.offsetWidth);
  7260. }
  7261. else {
  7262. changed += 1;
  7263. }
  7264. return (changed > 0);
  7265. };
  7266. /**
  7267. * Hide this component from the DOM
  7268. * @return {Boolean} changed
  7269. */
  7270. ItemSet.prototype.hide = function hide() {
  7271. var changed = false;
  7272. // remove the DOM
  7273. if (this.frame && this.frame.parentNode) {
  7274. this.frame.parentNode.removeChild(this.frame);
  7275. changed = true;
  7276. }
  7277. if (this.dom.axis && this.dom.axis.parentNode) {
  7278. this.dom.axis.parentNode.removeChild(this.dom.axis);
  7279. changed = true;
  7280. }
  7281. return changed;
  7282. };
  7283. /**
  7284. * Set items
  7285. * @param {vis.DataSet | null} items
  7286. */
  7287. ItemSet.prototype.setItems = function setItems(items) {
  7288. var me = this,
  7289. ids,
  7290. oldItemsData = this.itemsData;
  7291. // replace the dataset
  7292. if (!items) {
  7293. this.itemsData = null;
  7294. }
  7295. else if (items instanceof DataSet || items instanceof DataView) {
  7296. this.itemsData = items;
  7297. }
  7298. else {
  7299. throw new TypeError('Data must be an instance of DataSet');
  7300. }
  7301. if (oldItemsData) {
  7302. // unsubscribe from old dataset
  7303. util.forEach(this.listeners, function (callback, event) {
  7304. oldItemsData.unsubscribe(event, callback);
  7305. });
  7306. // remove all drawn items
  7307. ids = oldItemsData.getIds();
  7308. this._onRemove(ids);
  7309. }
  7310. if (this.itemsData) {
  7311. // subscribe to new dataset
  7312. var id = this.id;
  7313. util.forEach(this.listeners, function (callback, event) {
  7314. me.itemsData.subscribe(event, callback, id);
  7315. });
  7316. // draw all new items
  7317. ids = this.itemsData.getIds();
  7318. this._onAdd(ids);
  7319. }
  7320. };
  7321. /**
  7322. * Get the current items items
  7323. * @returns {vis.DataSet | null}
  7324. */
  7325. ItemSet.prototype.getItems = function getItems() {
  7326. return this.itemsData;
  7327. };
  7328. /**
  7329. * Handle updated items
  7330. * @param {Number[]} ids
  7331. * @private
  7332. */
  7333. ItemSet.prototype._onUpdate = function _onUpdate(ids) {
  7334. this._toQueue('update', ids);
  7335. };
  7336. /**
  7337. * Handle changed items
  7338. * @param {Number[]} ids
  7339. * @private
  7340. */
  7341. ItemSet.prototype._onAdd = function _onAdd(ids) {
  7342. this._toQueue('add', ids);
  7343. };
  7344. /**
  7345. * Handle removed items
  7346. * @param {Number[]} ids
  7347. * @private
  7348. */
  7349. ItemSet.prototype._onRemove = function _onRemove(ids) {
  7350. this._toQueue('remove', ids);
  7351. };
  7352. /**
  7353. * Put items in the queue to be added/updated/remove
  7354. * @param {String} action can be 'add', 'update', 'remove'
  7355. * @param {Number[]} ids
  7356. */
  7357. ItemSet.prototype._toQueue = function _toQueue(action, ids) {
  7358. var queue = this.queue;
  7359. ids.forEach(function (id) {
  7360. queue[id] = action;
  7361. });
  7362. if (this.controller) {
  7363. //this.requestReflow();
  7364. this.requestRepaint();
  7365. }
  7366. };
  7367. /**
  7368. * Calculate the factor and offset to convert a position on screen to the
  7369. * corresponding date and vice versa.
  7370. * After the method _updateConversion is executed once, the methods toTime
  7371. * and toScreen can be used.
  7372. * @private
  7373. */
  7374. ItemSet.prototype._updateConversion = function _updateConversion() {
  7375. var range = this.range;
  7376. if (!range) {
  7377. throw new Error('No range configured');
  7378. }
  7379. if (range.conversion) {
  7380. this.conversion = range.conversion(this.width);
  7381. }
  7382. else {
  7383. this.conversion = Range.conversion(range.start, range.end, this.width);
  7384. }
  7385. };
  7386. /**
  7387. * Convert a position on screen (pixels) to a datetime
  7388. * Before this method can be used, the method _updateConversion must be
  7389. * executed once.
  7390. * @param {int} x Position on the screen in pixels
  7391. * @return {Date} time The datetime the corresponds with given position x
  7392. */
  7393. ItemSet.prototype.toTime = function toTime(x) {
  7394. var conversion = this.conversion;
  7395. return new Date(x / conversion.factor + conversion.offset);
  7396. };
  7397. /**
  7398. * Convert a datetime (Date object) into a position on the screen
  7399. * Before this method can be used, the method _updateConversion must be
  7400. * executed once.
  7401. * @param {Date} time A date
  7402. * @return {int} x The position on the screen in pixels which corresponds
  7403. * with the given date.
  7404. */
  7405. ItemSet.prototype.toScreen = function toScreen(time) {
  7406. var conversion = this.conversion;
  7407. return (time.valueOf() - conversion.offset) * conversion.factor;
  7408. };
  7409. /**
  7410. * @constructor Item
  7411. * @param {ItemSet} parent
  7412. * @param {Object} data Object containing (optional) parameters type,
  7413. * start, end, content, group, className.
  7414. * @param {Object} [options] Options to set initial property values
  7415. * @param {Object} [defaultOptions] default options
  7416. * // TODO: describe available options
  7417. */
  7418. function Item (parent, data, options, defaultOptions) {
  7419. this.parent = parent;
  7420. this.data = data;
  7421. this.dom = null;
  7422. this.options = options || {};
  7423. this.defaultOptions = defaultOptions || {};
  7424. this.selected = false;
  7425. this.visible = false;
  7426. this.top = 0;
  7427. this.left = 0;
  7428. this.width = 0;
  7429. this.height = 0;
  7430. }
  7431. /**
  7432. * Select current item
  7433. */
  7434. Item.prototype.select = function select() {
  7435. this.selected = true;
  7436. };
  7437. /**
  7438. * Unselect current item
  7439. */
  7440. Item.prototype.unselect = function unselect() {
  7441. this.selected = false;
  7442. };
  7443. /**
  7444. * Show the Item in the DOM (when not already visible)
  7445. * @return {Boolean} changed
  7446. */
  7447. Item.prototype.show = function show() {
  7448. return false;
  7449. };
  7450. /**
  7451. * Hide the Item from the DOM (when visible)
  7452. * @return {Boolean} changed
  7453. */
  7454. Item.prototype.hide = function hide() {
  7455. return false;
  7456. };
  7457. /**
  7458. * Repaint the item
  7459. * @return {Boolean} changed
  7460. */
  7461. Item.prototype.repaint = function repaint() {
  7462. // should be implemented by the item
  7463. return false;
  7464. };
  7465. /**
  7466. * Reflow the item
  7467. * @return {Boolean} resized
  7468. */
  7469. Item.prototype.reflow = function reflow() {
  7470. // should be implemented by the item
  7471. return false;
  7472. };
  7473. /**
  7474. * @constructor ItemBox
  7475. * @extends Item
  7476. * @param {ItemSet} parent
  7477. * @param {Object} data Object containing parameters start
  7478. * content, className.
  7479. * @param {Object} [options] Options to set initial property values
  7480. * @param {Object} [defaultOptions] default options
  7481. * // TODO: describe available options
  7482. */
  7483. function ItemBox (parent, data, options, defaultOptions) {
  7484. this.props = {
  7485. dot: {
  7486. left: 0,
  7487. top: 0,
  7488. width: 0,
  7489. height: 0
  7490. },
  7491. line: {
  7492. top: 0,
  7493. left: 0,
  7494. width: 0,
  7495. height: 0
  7496. }
  7497. };
  7498. Item.call(this, parent, data, options, defaultOptions);
  7499. }
  7500. ItemBox.prototype = new Item (null, null);
  7501. /**
  7502. * Select the item
  7503. * @override
  7504. */
  7505. ItemBox.prototype.select = function select() {
  7506. this.selected = true;
  7507. // TODO: select and unselect
  7508. };
  7509. /**
  7510. * Unselect the item
  7511. * @override
  7512. */
  7513. ItemBox.prototype.unselect = function unselect() {
  7514. this.selected = false;
  7515. // TODO: select and unselect
  7516. };
  7517. /**
  7518. * Repaint the item
  7519. * @return {Boolean} changed
  7520. */
  7521. ItemBox.prototype.repaint = function repaint() {
  7522. // TODO: make an efficient repaint
  7523. var changed = false;
  7524. var dom = this.dom;
  7525. if (!dom) {
  7526. this._create();
  7527. dom = this.dom;
  7528. changed = true;
  7529. }
  7530. if (dom) {
  7531. if (!this.parent) {
  7532. throw new Error('Cannot repaint item: no parent attached');
  7533. }
  7534. var foreground = this.parent.getForeground();
  7535. if (!foreground) {
  7536. throw new Error('Cannot repaint time axis: ' +
  7537. 'parent has no foreground container element');
  7538. }
  7539. var background = this.parent.getBackground();
  7540. if (!background) {
  7541. throw new Error('Cannot repaint time axis: ' +
  7542. 'parent has no background container element');
  7543. }
  7544. var axis = this.parent.getAxis();
  7545. if (!background) {
  7546. throw new Error('Cannot repaint time axis: ' +
  7547. 'parent has no axis container element');
  7548. }
  7549. if (!dom.box.parentNode) {
  7550. foreground.appendChild(dom.box);
  7551. changed = true;
  7552. }
  7553. if (!dom.line.parentNode) {
  7554. background.appendChild(dom.line);
  7555. changed = true;
  7556. }
  7557. if (!dom.dot.parentNode) {
  7558. axis.appendChild(dom.dot);
  7559. changed = true;
  7560. }
  7561. // update contents
  7562. if (this.data.content != this.content) {
  7563. this.content = this.data.content;
  7564. if (this.content instanceof Element) {
  7565. dom.content.innerHTML = '';
  7566. dom.content.appendChild(this.content);
  7567. }
  7568. else if (this.data.content != undefined) {
  7569. dom.content.innerHTML = this.content;
  7570. }
  7571. else {
  7572. throw new Error('Property "content" missing in item ' + this.data.id);
  7573. }
  7574. changed = true;
  7575. }
  7576. // update class
  7577. var className = (this.data.className? ' ' + this.data.className : '') +
  7578. (this.selected ? ' selected' : '');
  7579. if (this.className != className) {
  7580. this.className = className;
  7581. dom.box.className = 'item box' + className;
  7582. dom.line.className = 'item line' + className;
  7583. dom.dot.className = 'item dot' + className;
  7584. changed = true;
  7585. }
  7586. }
  7587. return changed;
  7588. };
  7589. /**
  7590. * Show the item in the DOM (when not already visible). The items DOM will
  7591. * be created when needed.
  7592. * @return {Boolean} changed
  7593. */
  7594. ItemBox.prototype.show = function show() {
  7595. if (!this.dom || !this.dom.box.parentNode) {
  7596. return this.repaint();
  7597. }
  7598. else {
  7599. return false;
  7600. }
  7601. };
  7602. /**
  7603. * Hide the item from the DOM (when visible)
  7604. * @return {Boolean} changed
  7605. */
  7606. ItemBox.prototype.hide = function hide() {
  7607. var changed = false,
  7608. dom = this.dom;
  7609. if (dom) {
  7610. if (dom.box.parentNode) {
  7611. dom.box.parentNode.removeChild(dom.box);
  7612. changed = true;
  7613. }
  7614. if (dom.line.parentNode) {
  7615. dom.line.parentNode.removeChild(dom.line);
  7616. }
  7617. if (dom.dot.parentNode) {
  7618. dom.dot.parentNode.removeChild(dom.dot);
  7619. }
  7620. }
  7621. return changed;
  7622. };
  7623. /**
  7624. * Reflow the item: calculate its actual size and position from the DOM
  7625. * @return {boolean} resized returns true if the axis is resized
  7626. * @override
  7627. */
  7628. ItemBox.prototype.reflow = function reflow() {
  7629. var changed = 0,
  7630. update,
  7631. dom,
  7632. props,
  7633. options,
  7634. margin,
  7635. start,
  7636. align,
  7637. orientation,
  7638. top,
  7639. left,
  7640. data,
  7641. range;
  7642. if (this.data.start == undefined) {
  7643. throw new Error('Property "start" missing in item ' + this.data.id);
  7644. }
  7645. data = this.data;
  7646. range = this.parent && this.parent.range;
  7647. if (data && range) {
  7648. // TODO: account for the width of the item
  7649. var interval = (range.end - range.start);
  7650. this.visible = (data.start > range.start - interval) && (data.start < range.end + interval);
  7651. }
  7652. else {
  7653. this.visible = false;
  7654. }
  7655. if (this.visible) {
  7656. dom = this.dom;
  7657. if (dom) {
  7658. update = util.updateProperty;
  7659. props = this.props;
  7660. options = this.options;
  7661. start = this.parent.toScreen(this.data.start);
  7662. align = options.align || this.defaultOptions.align;
  7663. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  7664. orientation = options.orientation || this.defaultOptions.orientation;
  7665. changed += update(props.dot, 'height', dom.dot.offsetHeight);
  7666. changed += update(props.dot, 'width', dom.dot.offsetWidth);
  7667. changed += update(props.line, 'width', dom.line.offsetWidth);
  7668. changed += update(props.line, 'height', dom.line.offsetHeight);
  7669. changed += update(props.line, 'top', dom.line.offsetTop);
  7670. changed += update(this, 'width', dom.box.offsetWidth);
  7671. changed += update(this, 'height', dom.box.offsetHeight);
  7672. if (align == 'right') {
  7673. left = start - this.width;
  7674. }
  7675. else if (align == 'left') {
  7676. left = start;
  7677. }
  7678. else {
  7679. // default or 'center'
  7680. left = start - this.width / 2;
  7681. }
  7682. changed += update(this, 'left', left);
  7683. changed += update(props.line, 'left', start - props.line.width / 2);
  7684. changed += update(props.dot, 'left', start - props.dot.width / 2);
  7685. changed += update(props.dot, 'top', -props.dot.height / 2);
  7686. if (orientation == 'top') {
  7687. top = margin;
  7688. changed += update(this, 'top', top);
  7689. }
  7690. else {
  7691. // default or 'bottom'
  7692. var parentHeight = this.parent.height;
  7693. top = parentHeight - this.height - margin;
  7694. changed += update(this, 'top', top);
  7695. }
  7696. }
  7697. else {
  7698. changed += 1;
  7699. }
  7700. }
  7701. return (changed > 0);
  7702. };
  7703. /**
  7704. * Create an items DOM
  7705. * @private
  7706. */
  7707. ItemBox.prototype._create = function _create() {
  7708. var dom = this.dom;
  7709. if (!dom) {
  7710. this.dom = dom = {};
  7711. // create the box
  7712. dom.box = document.createElement('DIV');
  7713. // className is updated in repaint()
  7714. // contents box (inside the background box). used for making margins
  7715. dom.content = document.createElement('DIV');
  7716. dom.content.className = 'content';
  7717. dom.box.appendChild(dom.content);
  7718. // line to axis
  7719. dom.line = document.createElement('DIV');
  7720. dom.line.className = 'line';
  7721. // dot on axis
  7722. dom.dot = document.createElement('DIV');
  7723. dom.dot.className = 'dot';
  7724. }
  7725. };
  7726. /**
  7727. * Reposition the item, recalculate its left, top, and width, using the current
  7728. * range and size of the items itemset
  7729. * @override
  7730. */
  7731. ItemBox.prototype.reposition = function reposition() {
  7732. var dom = this.dom,
  7733. props = this.props,
  7734. orientation = this.options.orientation || this.defaultOptions.orientation;
  7735. if (dom) {
  7736. var box = dom.box,
  7737. line = dom.line,
  7738. dot = dom.dot;
  7739. box.style.left = this.left + 'px';
  7740. box.style.top = this.top + 'px';
  7741. line.style.left = props.line.left + 'px';
  7742. if (orientation == 'top') {
  7743. line.style.top = 0 + 'px';
  7744. line.style.height = this.top + 'px';
  7745. }
  7746. else {
  7747. // orientation 'bottom'
  7748. line.style.top = (this.top + this.height) + 'px';
  7749. line.style.height = Math.max(this.parent.height - this.top - this.height +
  7750. this.props.dot.height / 2, 0) + 'px';
  7751. }
  7752. dot.style.left = props.dot.left + 'px';
  7753. dot.style.top = props.dot.top + 'px';
  7754. }
  7755. };
  7756. /**
  7757. * @constructor ItemPoint
  7758. * @extends Item
  7759. * @param {ItemSet} parent
  7760. * @param {Object} data Object containing parameters start
  7761. * content, className.
  7762. * @param {Object} [options] Options to set initial property values
  7763. * @param {Object} [defaultOptions] default options
  7764. * // TODO: describe available options
  7765. */
  7766. function ItemPoint (parent, data, options, defaultOptions) {
  7767. this.props = {
  7768. dot: {
  7769. top: 0,
  7770. width: 0,
  7771. height: 0
  7772. },
  7773. content: {
  7774. height: 0,
  7775. marginLeft: 0
  7776. }
  7777. };
  7778. Item.call(this, parent, data, options, defaultOptions);
  7779. }
  7780. ItemPoint.prototype = new Item (null, null);
  7781. /**
  7782. * Select the item
  7783. * @override
  7784. */
  7785. ItemPoint.prototype.select = function select() {
  7786. this.selected = true;
  7787. // TODO: select and unselect
  7788. };
  7789. /**
  7790. * Unselect the item
  7791. * @override
  7792. */
  7793. ItemPoint.prototype.unselect = function unselect() {
  7794. this.selected = false;
  7795. // TODO: select and unselect
  7796. };
  7797. /**
  7798. * Repaint the item
  7799. * @return {Boolean} changed
  7800. */
  7801. ItemPoint.prototype.repaint = function repaint() {
  7802. // TODO: make an efficient repaint
  7803. var changed = false;
  7804. var dom = this.dom;
  7805. if (!dom) {
  7806. this._create();
  7807. dom = this.dom;
  7808. changed = true;
  7809. }
  7810. if (dom) {
  7811. if (!this.parent) {
  7812. throw new Error('Cannot repaint item: no parent attached');
  7813. }
  7814. var foreground = this.parent.getForeground();
  7815. if (!foreground) {
  7816. throw new Error('Cannot repaint time axis: ' +
  7817. 'parent has no foreground container element');
  7818. }
  7819. if (!dom.point.parentNode) {
  7820. foreground.appendChild(dom.point);
  7821. foreground.appendChild(dom.point);
  7822. changed = true;
  7823. }
  7824. // update contents
  7825. if (this.data.content != this.content) {
  7826. this.content = this.data.content;
  7827. if (this.content instanceof Element) {
  7828. dom.content.innerHTML = '';
  7829. dom.content.appendChild(this.content);
  7830. }
  7831. else if (this.data.content != undefined) {
  7832. dom.content.innerHTML = this.content;
  7833. }
  7834. else {
  7835. throw new Error('Property "content" missing in item ' + this.data.id);
  7836. }
  7837. changed = true;
  7838. }
  7839. // update class
  7840. var className = (this.data.className? ' ' + this.data.className : '') +
  7841. (this.selected ? ' selected' : '');
  7842. if (this.className != className) {
  7843. this.className = className;
  7844. dom.point.className = 'item point' + className;
  7845. changed = true;
  7846. }
  7847. }
  7848. return changed;
  7849. };
  7850. /**
  7851. * Show the item in the DOM (when not already visible). The items DOM will
  7852. * be created when needed.
  7853. * @return {Boolean} changed
  7854. */
  7855. ItemPoint.prototype.show = function show() {
  7856. if (!this.dom || !this.dom.point.parentNode) {
  7857. return this.repaint();
  7858. }
  7859. else {
  7860. return false;
  7861. }
  7862. };
  7863. /**
  7864. * Hide the item from the DOM (when visible)
  7865. * @return {Boolean} changed
  7866. */
  7867. ItemPoint.prototype.hide = function hide() {
  7868. var changed = false,
  7869. dom = this.dom;
  7870. if (dom) {
  7871. if (dom.point.parentNode) {
  7872. dom.point.parentNode.removeChild(dom.point);
  7873. changed = true;
  7874. }
  7875. }
  7876. return changed;
  7877. };
  7878. /**
  7879. * Reflow the item: calculate its actual size from the DOM
  7880. * @return {boolean} resized returns true if the axis is resized
  7881. * @override
  7882. */
  7883. ItemPoint.prototype.reflow = function reflow() {
  7884. var changed = 0,
  7885. update,
  7886. dom,
  7887. props,
  7888. options,
  7889. margin,
  7890. orientation,
  7891. start,
  7892. top,
  7893. data,
  7894. range;
  7895. if (this.data.start == undefined) {
  7896. throw new Error('Property "start" missing in item ' + this.data.id);
  7897. }
  7898. data = this.data;
  7899. range = this.parent && this.parent.range;
  7900. if (data && range) {
  7901. // TODO: account for the width of the item
  7902. var interval = (range.end - range.start);
  7903. this.visible = (data.start > range.start - interval) && (data.start < range.end);
  7904. }
  7905. else {
  7906. this.visible = false;
  7907. }
  7908. if (this.visible) {
  7909. dom = this.dom;
  7910. if (dom) {
  7911. update = util.updateProperty;
  7912. props = this.props;
  7913. options = this.options;
  7914. orientation = options.orientation || this.defaultOptions.orientation;
  7915. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  7916. start = this.parent.toScreen(this.data.start);
  7917. changed += update(this, 'width', dom.point.offsetWidth);
  7918. changed += update(this, 'height', dom.point.offsetHeight);
  7919. changed += update(props.dot, 'width', dom.dot.offsetWidth);
  7920. changed += update(props.dot, 'height', dom.dot.offsetHeight);
  7921. changed += update(props.content, 'height', dom.content.offsetHeight);
  7922. if (orientation == 'top') {
  7923. top = margin;
  7924. }
  7925. else {
  7926. // default or 'bottom'
  7927. var parentHeight = this.parent.height;
  7928. top = Math.max(parentHeight - this.height - margin, 0);
  7929. }
  7930. changed += update(this, 'top', top);
  7931. changed += update(this, 'left', start - props.dot.width / 2);
  7932. changed += update(props.content, 'marginLeft', 1.5 * props.dot.width);
  7933. //changed += update(props.content, 'marginRight', 0.5 * props.dot.width); // TODO
  7934. changed += update(props.dot, 'top', (this.height - props.dot.height) / 2);
  7935. }
  7936. else {
  7937. changed += 1;
  7938. }
  7939. }
  7940. return (changed > 0);
  7941. };
  7942. /**
  7943. * Create an items DOM
  7944. * @private
  7945. */
  7946. ItemPoint.prototype._create = function _create() {
  7947. var dom = this.dom;
  7948. if (!dom) {
  7949. this.dom = dom = {};
  7950. // background box
  7951. dom.point = document.createElement('div');
  7952. // className is updated in repaint()
  7953. // contents box, right from the dot
  7954. dom.content = document.createElement('div');
  7955. dom.content.className = 'content';
  7956. dom.point.appendChild(dom.content);
  7957. // dot at start
  7958. dom.dot = document.createElement('div');
  7959. dom.dot.className = 'dot';
  7960. dom.point.appendChild(dom.dot);
  7961. }
  7962. };
  7963. /**
  7964. * Reposition the item, recalculate its left, top, and width, using the current
  7965. * range and size of the items itemset
  7966. * @override
  7967. */
  7968. ItemPoint.prototype.reposition = function reposition() {
  7969. var dom = this.dom,
  7970. props = this.props;
  7971. if (dom) {
  7972. dom.point.style.top = this.top + 'px';
  7973. dom.point.style.left = this.left + 'px';
  7974. dom.content.style.marginLeft = props.content.marginLeft + 'px';
  7975. //dom.content.style.marginRight = props.content.marginRight + 'px'; // TODO
  7976. dom.dot.style.top = props.dot.top + 'px';
  7977. }
  7978. };
  7979. /**
  7980. * @constructor ItemRange
  7981. * @extends Item
  7982. * @param {ItemSet} parent
  7983. * @param {Object} data Object containing parameters start, end
  7984. * content, className.
  7985. * @param {Object} [options] Options to set initial property values
  7986. * @param {Object} [defaultOptions] default options
  7987. * // TODO: describe available options
  7988. */
  7989. function ItemRange (parent, data, options, defaultOptions) {
  7990. this.props = {
  7991. content: {
  7992. left: 0,
  7993. width: 0
  7994. }
  7995. };
  7996. Item.call(this, parent, data, options, defaultOptions);
  7997. }
  7998. ItemRange.prototype = new Item (null, null);
  7999. /**
  8000. * Select the item
  8001. * @override
  8002. */
  8003. ItemRange.prototype.select = function select() {
  8004. this.selected = true;
  8005. // TODO: select and unselect
  8006. };
  8007. /**
  8008. * Unselect the item
  8009. * @override
  8010. */
  8011. ItemRange.prototype.unselect = function unselect() {
  8012. this.selected = false;
  8013. // TODO: select and unselect
  8014. };
  8015. /**
  8016. * Repaint the item
  8017. * @return {Boolean} changed
  8018. */
  8019. ItemRange.prototype.repaint = function repaint() {
  8020. // TODO: make an efficient repaint
  8021. var changed = false;
  8022. var dom = this.dom;
  8023. if (!dom) {
  8024. this._create();
  8025. dom = this.dom;
  8026. changed = true;
  8027. }
  8028. if (dom) {
  8029. if (!this.parent) {
  8030. throw new Error('Cannot repaint item: no parent attached');
  8031. }
  8032. var foreground = this.parent.getForeground();
  8033. if (!foreground) {
  8034. throw new Error('Cannot repaint time axis: ' +
  8035. 'parent has no foreground container element');
  8036. }
  8037. if (!dom.box.parentNode) {
  8038. foreground.appendChild(dom.box);
  8039. changed = true;
  8040. }
  8041. // update content
  8042. if (this.data.content != this.content) {
  8043. this.content = this.data.content;
  8044. if (this.content instanceof Element) {
  8045. dom.content.innerHTML = '';
  8046. dom.content.appendChild(this.content);
  8047. }
  8048. else if (this.data.content != undefined) {
  8049. dom.content.innerHTML = this.content;
  8050. }
  8051. else {
  8052. throw new Error('Property "content" missing in item ' + this.data.id);
  8053. }
  8054. changed = true;
  8055. }
  8056. // update class
  8057. var className = this.data.className ? (' ' + this.data.className) : '';
  8058. if (this.className != className) {
  8059. this.className = className;
  8060. dom.box.className = 'item range' + className;
  8061. changed = true;
  8062. }
  8063. }
  8064. return changed;
  8065. };
  8066. /**
  8067. * Show the item in the DOM (when not already visible). The items DOM will
  8068. * be created when needed.
  8069. * @return {Boolean} changed
  8070. */
  8071. ItemRange.prototype.show = function show() {
  8072. if (!this.dom || !this.dom.box.parentNode) {
  8073. return this.repaint();
  8074. }
  8075. else {
  8076. return false;
  8077. }
  8078. };
  8079. /**
  8080. * Hide the item from the DOM (when visible)
  8081. * @return {Boolean} changed
  8082. */
  8083. ItemRange.prototype.hide = function hide() {
  8084. var changed = false,
  8085. dom = this.dom;
  8086. if (dom) {
  8087. if (dom.box.parentNode) {
  8088. dom.box.parentNode.removeChild(dom.box);
  8089. changed = true;
  8090. }
  8091. }
  8092. return changed;
  8093. };
  8094. /**
  8095. * Reflow the item: calculate its actual size from the DOM
  8096. * @return {boolean} resized returns true if the axis is resized
  8097. * @override
  8098. */
  8099. ItemRange.prototype.reflow = function reflow() {
  8100. var changed = 0,
  8101. dom,
  8102. props,
  8103. options,
  8104. margin,
  8105. padding,
  8106. parent,
  8107. start,
  8108. end,
  8109. data,
  8110. range,
  8111. update,
  8112. box,
  8113. parentWidth,
  8114. contentLeft,
  8115. orientation,
  8116. top;
  8117. if (this.data.start == undefined) {
  8118. throw new Error('Property "start" missing in item ' + this.data.id);
  8119. }
  8120. if (this.data.end == undefined) {
  8121. throw new Error('Property "end" missing in item ' + this.data.id);
  8122. }
  8123. data = this.data;
  8124. range = this.parent && this.parent.range;
  8125. if (data && range) {
  8126. // TODO: account for the width of the item. Take some margin
  8127. this.visible = (data.start < range.end) && (data.end > range.start);
  8128. }
  8129. else {
  8130. this.visible = false;
  8131. }
  8132. if (this.visible) {
  8133. dom = this.dom;
  8134. if (dom) {
  8135. props = this.props;
  8136. options = this.options;
  8137. parent = this.parent;
  8138. start = parent.toScreen(this.data.start);
  8139. end = parent.toScreen(this.data.end);
  8140. update = util.updateProperty;
  8141. box = dom.box;
  8142. parentWidth = parent.width;
  8143. orientation = options.orientation || this.defaultOptions.orientation;
  8144. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  8145. padding = options.padding || this.defaultOptions.padding;
  8146. changed += update(props.content, 'width', dom.content.offsetWidth);
  8147. changed += update(this, 'height', box.offsetHeight);
  8148. // limit the width of the this, as browsers cannot draw very wide divs
  8149. if (start < -parentWidth) {
  8150. start = -parentWidth;
  8151. }
  8152. if (end > 2 * parentWidth) {
  8153. end = 2 * parentWidth;
  8154. }
  8155. // when range exceeds left of the window, position the contents at the left of the visible area
  8156. if (start < 0) {
  8157. contentLeft = Math.min(-start,
  8158. (end - start - props.content.width - 2 * padding));
  8159. // TODO: remove the need for options.padding. it's terrible.
  8160. }
  8161. else {
  8162. contentLeft = 0;
  8163. }
  8164. changed += update(props.content, 'left', contentLeft);
  8165. if (orientation == 'top') {
  8166. top = margin;
  8167. changed += update(this, 'top', top);
  8168. }
  8169. else {
  8170. // default or 'bottom'
  8171. top = parent.height - this.height - margin;
  8172. changed += update(this, 'top', top);
  8173. }
  8174. changed += update(this, 'left', start);
  8175. changed += update(this, 'width', Math.max(end - start, 1)); // TODO: reckon with border width;
  8176. }
  8177. else {
  8178. changed += 1;
  8179. }
  8180. }
  8181. return (changed > 0);
  8182. };
  8183. /**
  8184. * Create an items DOM
  8185. * @private
  8186. */
  8187. ItemRange.prototype._create = function _create() {
  8188. var dom = this.dom;
  8189. if (!dom) {
  8190. this.dom = dom = {};
  8191. // background box
  8192. dom.box = document.createElement('div');
  8193. // className is updated in repaint()
  8194. // contents box
  8195. dom.content = document.createElement('div');
  8196. dom.content.className = 'content';
  8197. dom.box.appendChild(dom.content);
  8198. }
  8199. };
  8200. /**
  8201. * Reposition the item, recalculate its left, top, and width, using the current
  8202. * range and size of the items itemset
  8203. * @override
  8204. */
  8205. ItemRange.prototype.reposition = function reposition() {
  8206. var dom = this.dom,
  8207. props = this.props;
  8208. if (dom) {
  8209. dom.box.style.top = this.top + 'px';
  8210. dom.box.style.left = this.left + 'px';
  8211. dom.box.style.width = this.width + 'px';
  8212. dom.content.style.left = props.content.left + 'px';
  8213. }
  8214. };
  8215. /**
  8216. * @constructor Group
  8217. * @param {GroupSet} parent
  8218. * @param {Number | String} groupId
  8219. * @param {Object} [options] Options to set initial property values
  8220. * // TODO: describe available options
  8221. * @extends Component
  8222. */
  8223. function Group (parent, groupId, options) {
  8224. this.id = util.randomUUID();
  8225. this.parent = parent;
  8226. this.groupId = groupId;
  8227. this.itemset = null; // ItemSet
  8228. this.options = options || {};
  8229. this.options.top = 0;
  8230. this.props = {
  8231. label: {
  8232. width: 0,
  8233. height: 0
  8234. }
  8235. };
  8236. this.top = 0;
  8237. this.left = 0;
  8238. this.width = 0;
  8239. this.height = 0;
  8240. }
  8241. Group.prototype = new Component();
  8242. // TODO: comment
  8243. Group.prototype.setOptions = Component.prototype.setOptions;
  8244. /**
  8245. * Get the container element of the panel, which can be used by a child to
  8246. * add its own widgets.
  8247. * @returns {HTMLElement} container
  8248. */
  8249. Group.prototype.getContainer = function () {
  8250. return this.parent.getContainer();
  8251. };
  8252. /**
  8253. * Set item set for the group. The group will create a view on the itemset,
  8254. * filtered by the groups id.
  8255. * @param {DataSet | DataView} items
  8256. */
  8257. Group.prototype.setItems = function setItems(items) {
  8258. if (this.itemset) {
  8259. // remove current item set
  8260. this.itemset.hide();
  8261. this.itemset.setItems();
  8262. this.parent.controller.remove(this.itemset);
  8263. this.itemset = null;
  8264. }
  8265. if (items) {
  8266. var groupId = this.groupId;
  8267. var itemsetOptions = Object.create(this.options);
  8268. this.itemset = new ItemSet(this, null, itemsetOptions);
  8269. this.itemset.setRange(this.parent.range);
  8270. this.view = new DataView(items, {
  8271. filter: function (item) {
  8272. return item.group == groupId;
  8273. }
  8274. });
  8275. this.itemset.setItems(this.view);
  8276. this.parent.controller.add(this.itemset);
  8277. }
  8278. };
  8279. /**
  8280. * Repaint the item
  8281. * @return {Boolean} changed
  8282. */
  8283. Group.prototype.repaint = function repaint() {
  8284. return false;
  8285. };
  8286. /**
  8287. * Reflow the item
  8288. * @return {Boolean} resized
  8289. */
  8290. Group.prototype.reflow = function reflow() {
  8291. var changed = 0,
  8292. update = util.updateProperty;
  8293. changed += update(this, 'top', this.itemset ? this.itemset.top : 0);
  8294. changed += update(this, 'height', this.itemset ? this.itemset.height : 0);
  8295. // TODO: reckon with the height of the group label
  8296. if (this.label) {
  8297. var inner = this.label.firstChild;
  8298. changed += update(this.props.label, 'width', inner.clientWidth);
  8299. changed += update(this.props.label, 'height', inner.clientHeight);
  8300. }
  8301. else {
  8302. changed += update(this.props.label, 'width', 0);
  8303. changed += update(this.props.label, 'height', 0);
  8304. }
  8305. return (changed > 0);
  8306. };
  8307. /**
  8308. * An GroupSet holds a set of groups
  8309. * @param {Component} parent
  8310. * @param {Component[]} [depends] Components on which this components depends
  8311. * (except for the parent)
  8312. * @param {Object} [options] See GroupSet.setOptions for the available
  8313. * options.
  8314. * @constructor GroupSet
  8315. * @extends Panel
  8316. */
  8317. function GroupSet(parent, depends, options) {
  8318. this.id = util.randomUUID();
  8319. this.parent = parent;
  8320. this.depends = depends;
  8321. this.options = options || {};
  8322. this.range = null; // Range or Object {start: number, end: number}
  8323. this.itemsData = null; // DataSet with items
  8324. this.groupsData = null; // DataSet with groups
  8325. this.groups = {}; // map with groups
  8326. this.dom = {};
  8327. this.props = {
  8328. labels: {
  8329. width: 0
  8330. }
  8331. };
  8332. // TODO: implement right orientation of the labels
  8333. // changes in groups are queued key/value map containing id/action
  8334. this.queue = {};
  8335. var me = this;
  8336. this.listeners = {
  8337. 'add': function (event, params) {
  8338. me._onAdd(params.items);
  8339. },
  8340. 'update': function (event, params) {
  8341. me._onUpdate(params.items);
  8342. },
  8343. 'remove': function (event, params) {
  8344. me._onRemove(params.items);
  8345. }
  8346. };
  8347. }
  8348. GroupSet.prototype = new Panel();
  8349. /**
  8350. * Set options for the GroupSet. Existing options will be extended/overwritten.
  8351. * @param {Object} [options] The following options are available:
  8352. * {String | function} groupsOrder
  8353. * TODO: describe options
  8354. */
  8355. GroupSet.prototype.setOptions = Component.prototype.setOptions;
  8356. GroupSet.prototype.setRange = function (range) {
  8357. // TODO: implement setRange
  8358. };
  8359. /**
  8360. * Set items
  8361. * @param {vis.DataSet | null} items
  8362. */
  8363. GroupSet.prototype.setItems = function setItems(items) {
  8364. this.itemsData = items;
  8365. for (var id in this.groups) {
  8366. if (this.groups.hasOwnProperty(id)) {
  8367. var group = this.groups[id];
  8368. group.setItems(items);
  8369. }
  8370. }
  8371. };
  8372. /**
  8373. * Get items
  8374. * @return {vis.DataSet | null} items
  8375. */
  8376. GroupSet.prototype.getItems = function getItems() {
  8377. return this.itemsData;
  8378. };
  8379. /**
  8380. * Set range (start and end).
  8381. * @param {Range | Object} range A Range or an object containing start and end.
  8382. */
  8383. GroupSet.prototype.setRange = function setRange(range) {
  8384. this.range = range;
  8385. };
  8386. /**
  8387. * Set groups
  8388. * @param {vis.DataSet} groups
  8389. */
  8390. GroupSet.prototype.setGroups = function setGroups(groups) {
  8391. var me = this,
  8392. ids;
  8393. // unsubscribe from current dataset
  8394. if (this.groupsData) {
  8395. util.forEach(this.listeners, function (callback, event) {
  8396. me.groupsData.unsubscribe(event, callback);
  8397. });
  8398. // remove all drawn groups
  8399. ids = this.groupsData.getIds();
  8400. this._onRemove(ids);
  8401. }
  8402. // replace the dataset
  8403. if (!groups) {
  8404. this.groupsData = null;
  8405. }
  8406. else if (groups instanceof DataSet) {
  8407. this.groupsData = groups;
  8408. }
  8409. else {
  8410. this.groupsData = new DataSet({
  8411. convert: {
  8412. start: 'Date',
  8413. end: 'Date'
  8414. }
  8415. });
  8416. this.groupsData.add(groups);
  8417. }
  8418. if (this.groupsData) {
  8419. // subscribe to new dataset
  8420. var id = this.id;
  8421. util.forEach(this.listeners, function (callback, event) {
  8422. me.groupsData.subscribe(event, callback, id);
  8423. });
  8424. // draw all new groups
  8425. ids = this.groupsData.getIds();
  8426. this._onAdd(ids);
  8427. }
  8428. };
  8429. /**
  8430. * Get groups
  8431. * @return {vis.DataSet | null} groups
  8432. */
  8433. GroupSet.prototype.getGroups = function getGroups() {
  8434. return this.groupsData;
  8435. };
  8436. /**
  8437. * Repaint the component
  8438. * @return {Boolean} changed
  8439. */
  8440. GroupSet.prototype.repaint = function repaint() {
  8441. var changed = 0,
  8442. i, id, group, label,
  8443. update = util.updateProperty,
  8444. asSize = util.option.asSize,
  8445. asElement = util.option.asElement,
  8446. options = this.options,
  8447. frame = this.dom.frame,
  8448. labels = this.dom.labels;
  8449. // create frame
  8450. if (!this.parent) {
  8451. throw new Error('Cannot repaint groupset: no parent attached');
  8452. }
  8453. var parentContainer = this.parent.getContainer();
  8454. if (!parentContainer) {
  8455. throw new Error('Cannot repaint groupset: parent has no container element');
  8456. }
  8457. if (!frame) {
  8458. frame = document.createElement('div');
  8459. frame.className = 'groupset';
  8460. this.dom.frame = frame;
  8461. var className = options.className;
  8462. if (className) {
  8463. util.addClassName(frame, util.option.asString(className));
  8464. }
  8465. changed += 1;
  8466. }
  8467. if (!frame.parentNode) {
  8468. parentContainer.appendChild(frame);
  8469. changed += 1;
  8470. }
  8471. // create labels
  8472. var labelContainer = asElement(options.labelContainer);
  8473. if (!labelContainer) {
  8474. throw new Error('Cannot repaint groupset: option "labelContainer" not defined');
  8475. }
  8476. if (!labels) {
  8477. labels = document.createElement('div');
  8478. labels.className = 'labels';
  8479. //frame.appendChild(labels);
  8480. this.dom.labels = labels;
  8481. }
  8482. if (!labels.parentNode || labels.parentNode != labelContainer) {
  8483. if (labels.parentNode) {
  8484. labels.parentNode.removeChild(labels.parentNode);
  8485. }
  8486. labelContainer.appendChild(labels);
  8487. }
  8488. // reposition frame
  8489. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  8490. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  8491. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  8492. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  8493. // reposition labels
  8494. changed += update(labels.style, 'top', asSize(options.top, '0px'));
  8495. var me = this,
  8496. queue = this.queue,
  8497. groups = this.groups,
  8498. groupsData = this.groupsData;
  8499. // show/hide added/changed/removed groups
  8500. var ids = Object.keys(queue);
  8501. if (ids.length) {
  8502. ids.forEach(function (id) {
  8503. var action = queue[id];
  8504. var group = groups[id];
  8505. //noinspection FallthroughInSwitchStatementJS
  8506. switch (action) {
  8507. case 'add':
  8508. case 'update':
  8509. if (!group) {
  8510. var groupOptions = Object.create(me.options);
  8511. group = new Group(me, id, groupOptions);
  8512. group.setItems(me.itemsData); // attach items data
  8513. groups[id] = group;
  8514. me.controller.add(group);
  8515. }
  8516. // TODO: update group data
  8517. group.data = groupsData.get(id);
  8518. delete queue[id];
  8519. break;
  8520. case 'remove':
  8521. if (group) {
  8522. group.setItems(); // detach items data
  8523. delete groups[id];
  8524. me.controller.remove(group);
  8525. }
  8526. // update lists
  8527. delete queue[id];
  8528. break;
  8529. default:
  8530. console.log('Error: unknown action "' + action + '"');
  8531. }
  8532. });
  8533. // the groupset depends on each of the groups
  8534. //this.depends = this.groups; // TODO: gives a circular reference through the parent
  8535. // TODO: apply dependencies of the groupset
  8536. // update the top positions of the groups in the correct order
  8537. var orderedGroups = this.groupsData.getIds({
  8538. order: this.options.groupsOrder
  8539. });
  8540. for (i = 0; i < orderedGroups.length; i++) {
  8541. (function (group, prevGroup) {
  8542. var top = 0;
  8543. if (prevGroup) {
  8544. top = function () {
  8545. // TODO: top must reckon with options.maxHeight
  8546. return prevGroup.top + prevGroup.height;
  8547. }
  8548. }
  8549. group.setOptions({
  8550. top: top
  8551. });
  8552. })(groups[orderedGroups[i]], groups[orderedGroups[i - 1]]);
  8553. }
  8554. // (re)create the labels
  8555. while (labels.firstChild) {
  8556. labels.removeChild(labels.firstChild);
  8557. }
  8558. for (i = 0; i < orderedGroups.length; i++) {
  8559. id = orderedGroups[i];
  8560. label = this._createLabel(id);
  8561. labels.appendChild(label);
  8562. }
  8563. changed++;
  8564. }
  8565. // reposition the labels
  8566. // TODO: labels are not displayed correctly when orientation=='top'
  8567. // TODO: width of labelPanel is not immediately updated on a change in groups
  8568. for (id in groups) {
  8569. if (groups.hasOwnProperty(id)) {
  8570. group = groups[id];
  8571. label = group.label;
  8572. if (label) {
  8573. label.style.top = group.top + 'px';
  8574. label.style.height = group.height + 'px';
  8575. }
  8576. }
  8577. }
  8578. return (changed > 0);
  8579. };
  8580. /**
  8581. * Create a label for group with given id
  8582. * @param {Number} id
  8583. * @return {Element} label
  8584. * @private
  8585. */
  8586. GroupSet.prototype._createLabel = function(id) {
  8587. var group = this.groups[id];
  8588. var label = document.createElement('div');
  8589. label.className = 'label';
  8590. var inner = document.createElement('div');
  8591. inner.className = 'inner';
  8592. label.appendChild(inner);
  8593. var content = group.data && group.data.content;
  8594. if (content instanceof Element) {
  8595. inner.appendChild(content);
  8596. }
  8597. else if (content != undefined) {
  8598. inner.innerHTML = content;
  8599. }
  8600. var className = group.data && group.data.className;
  8601. if (className) {
  8602. util.addClassName(label, className);
  8603. }
  8604. group.label = label; // TODO: not so nice, parking labels in the group this way!!!
  8605. return label;
  8606. };
  8607. /**
  8608. * Get container element
  8609. * @return {HTMLElement} container
  8610. */
  8611. GroupSet.prototype.getContainer = function getContainer() {
  8612. return this.dom.frame;
  8613. };
  8614. /**
  8615. * Get the width of the group labels
  8616. * @return {Number} width
  8617. */
  8618. GroupSet.prototype.getLabelsWidth = function getContainer() {
  8619. return this.props.labels.width;
  8620. };
  8621. /**
  8622. * Reflow the component
  8623. * @return {Boolean} resized
  8624. */
  8625. GroupSet.prototype.reflow = function reflow() {
  8626. var changed = 0,
  8627. id, group,
  8628. options = this.options,
  8629. update = util.updateProperty,
  8630. asNumber = util.option.asNumber,
  8631. asSize = util.option.asSize,
  8632. frame = this.dom.frame;
  8633. if (frame) {
  8634. var maxHeight = asNumber(options.maxHeight);
  8635. var fixedHeight = (asSize(options.height) != null);
  8636. var height;
  8637. if (fixedHeight) {
  8638. height = frame.offsetHeight;
  8639. }
  8640. else {
  8641. // height is not specified, calculate the sum of the height of all groups
  8642. height = 0;
  8643. for (id in this.groups) {
  8644. if (this.groups.hasOwnProperty(id)) {
  8645. group = this.groups[id];
  8646. height += group.height;
  8647. }
  8648. }
  8649. }
  8650. if (maxHeight != null) {
  8651. height = Math.min(height, maxHeight);
  8652. }
  8653. changed += update(this, 'height', height);
  8654. changed += update(this, 'top', frame.offsetTop);
  8655. changed += update(this, 'left', frame.offsetLeft);
  8656. changed += update(this, 'width', frame.offsetWidth);
  8657. }
  8658. // calculate the maximum width of the labels
  8659. var width = 0;
  8660. for (id in this.groups) {
  8661. if (this.groups.hasOwnProperty(id)) {
  8662. group = this.groups[id];
  8663. var labelWidth = group.props && group.props.label && group.props.label.width || 0;
  8664. width = Math.max(width, labelWidth);
  8665. }
  8666. }
  8667. changed += update(this.props.labels, 'width', width);
  8668. return (changed > 0);
  8669. };
  8670. /**
  8671. * Hide the component from the DOM
  8672. * @return {Boolean} changed
  8673. */
  8674. GroupSet.prototype.hide = function hide() {
  8675. if (this.dom.frame && this.dom.frame.parentNode) {
  8676. this.dom.frame.parentNode.removeChild(this.dom.frame);
  8677. return true;
  8678. }
  8679. else {
  8680. return false;
  8681. }
  8682. };
  8683. /**
  8684. * Show the component in the DOM (when not already visible).
  8685. * A repaint will be executed when the component is not visible
  8686. * @return {Boolean} changed
  8687. */
  8688. GroupSet.prototype.show = function show() {
  8689. if (!this.dom.frame || !this.dom.frame.parentNode) {
  8690. return this.repaint();
  8691. }
  8692. else {
  8693. return false;
  8694. }
  8695. };
  8696. /**
  8697. * Handle updated groups
  8698. * @param {Number[]} ids
  8699. * @private
  8700. */
  8701. GroupSet.prototype._onUpdate = function _onUpdate(ids) {
  8702. this._toQueue(ids, 'update');
  8703. };
  8704. /**
  8705. * Handle changed groups
  8706. * @param {Number[]} ids
  8707. * @private
  8708. */
  8709. GroupSet.prototype._onAdd = function _onAdd(ids) {
  8710. this._toQueue(ids, 'add');
  8711. };
  8712. /**
  8713. * Handle removed groups
  8714. * @param {Number[]} ids
  8715. * @private
  8716. */
  8717. GroupSet.prototype._onRemove = function _onRemove(ids) {
  8718. this._toQueue(ids, 'remove');
  8719. };
  8720. /**
  8721. * Put groups in the queue to be added/updated/remove
  8722. * @param {Number[]} ids
  8723. * @param {String} action can be 'add', 'update', 'remove'
  8724. */
  8725. GroupSet.prototype._toQueue = function _toQueue(ids, action) {
  8726. var queue = this.queue;
  8727. ids.forEach(function (id) {
  8728. queue[id] = action;
  8729. });
  8730. if (this.controller) {
  8731. //this.requestReflow();
  8732. this.requestRepaint();
  8733. }
  8734. };
  8735. /**
  8736. * Create a timeline visualization
  8737. * @param {HTMLElement} container
  8738. * @param {vis.DataSet | Array | DataTable} [items]
  8739. * @param {Object} [options] See Timeline.setOptions for the available options.
  8740. * @constructor
  8741. */
  8742. function Timeline (container, items, options) {
  8743. var me = this;
  8744. this.options = util.extend({
  8745. orientation: 'bottom',
  8746. min: null,
  8747. max: null,
  8748. zoomMin: 10, // milliseconds
  8749. zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000, // milliseconds
  8750. // moveable: true, // TODO: option moveable
  8751. // zoomable: true, // TODO: option zoomable
  8752. showMinorLabels: true,
  8753. showMajorLabels: true,
  8754. autoResize: false
  8755. }, options);
  8756. // controller
  8757. this.controller = new Controller();
  8758. // root panel
  8759. if (!container) {
  8760. throw new Error('No container element provided');
  8761. }
  8762. var rootOptions = Object.create(this.options);
  8763. rootOptions.height = function () {
  8764. if (me.options.height) {
  8765. // fixed height
  8766. return me.options.height;
  8767. }
  8768. else {
  8769. // auto height
  8770. return me.timeaxis.height + me.content.height;
  8771. }
  8772. };
  8773. this.rootPanel = new RootPanel(container, rootOptions);
  8774. this.controller.add(this.rootPanel);
  8775. // item panel
  8776. var itemOptions = Object.create(this.options);
  8777. itemOptions.left = function () {
  8778. return me.labelPanel.width;
  8779. };
  8780. itemOptions.width = function () {
  8781. return me.rootPanel.width - me.labelPanel.width;
  8782. };
  8783. itemOptions.top = null;
  8784. itemOptions.height = null;
  8785. this.itemPanel = new Panel(this.rootPanel, [], itemOptions);
  8786. this.controller.add(this.itemPanel);
  8787. // label panel
  8788. var labelOptions = Object.create(this.options);
  8789. labelOptions.top = null;
  8790. labelOptions.left = null;
  8791. labelOptions.height = null;
  8792. labelOptions.width = function () {
  8793. if (me.content && typeof me.content.getLabelsWidth === 'function') {
  8794. return me.content.getLabelsWidth();
  8795. }
  8796. else {
  8797. return 0;
  8798. }
  8799. };
  8800. this.labelPanel = new Panel(this.rootPanel, [], labelOptions);
  8801. this.controller.add(this.labelPanel);
  8802. // range
  8803. var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0);
  8804. this.range = new Range({
  8805. start: now.clone().add('days', -3).valueOf(),
  8806. end: now.clone().add('days', 4).valueOf()
  8807. });
  8808. /* TODO: fix range options
  8809. var rangeOptions = Object.create(this.options);
  8810. this.range = new Range(rangeOptions);
  8811. this.range.setRange(
  8812. now.clone().add('days', -3).valueOf(),
  8813. now.clone().add('days', 4).valueOf()
  8814. );
  8815. */
  8816. // TODO: reckon with options moveable and zoomable
  8817. this.range.subscribe(this.rootPanel, 'move', 'horizontal');
  8818. this.range.subscribe(this.rootPanel, 'zoom', 'horizontal');
  8819. this.range.on('rangechange', function () {
  8820. var force = true;
  8821. me.controller.requestReflow(force);
  8822. });
  8823. this.range.on('rangechanged', function () {
  8824. var force = true;
  8825. me.controller.requestReflow(force);
  8826. });
  8827. // TODO: put the listeners in setOptions, be able to dynamically change with options moveable and zoomable
  8828. // time axis
  8829. var timeaxisOptions = Object.create(rootOptions);
  8830. timeaxisOptions.range = this.range;
  8831. timeaxisOptions.left = null;
  8832. timeaxisOptions.top = null;
  8833. timeaxisOptions.width = '100%';
  8834. timeaxisOptions.height = null;
  8835. this.timeaxis = new TimeAxis(this.itemPanel, [], timeaxisOptions);
  8836. this.timeaxis.setRange(this.range);
  8837. this.controller.add(this.timeaxis);
  8838. // create itemset or groupset
  8839. this.setGroups(null);
  8840. this.itemsData = null; // DataSet
  8841. this.groupsData = null; // DataSet
  8842. // set data
  8843. if (items) {
  8844. this.setItems(items);
  8845. }
  8846. }
  8847. /**
  8848. * Set options
  8849. * @param {Object} options TODO: describe the available options
  8850. */
  8851. Timeline.prototype.setOptions = function (options) {
  8852. if (options) {
  8853. util.extend(this.options, options);
  8854. }
  8855. // TODO: apply range min,max
  8856. this.controller.reflow();
  8857. this.controller.repaint();
  8858. };
  8859. /**
  8860. * Set items
  8861. * @param {vis.DataSet | Array | DataTable | null} items
  8862. */
  8863. Timeline.prototype.setItems = function(items) {
  8864. var initialLoad = (this.itemsData == null);
  8865. // convert to type DataSet when needed
  8866. var newItemSet;
  8867. if (!items) {
  8868. newItemSet = null;
  8869. }
  8870. else if (items instanceof DataSet) {
  8871. newItemSet = items;
  8872. }
  8873. if (!(items instanceof DataSet)) {
  8874. newItemSet = new DataSet({
  8875. convert: {
  8876. start: 'Date',
  8877. end: 'Date'
  8878. }
  8879. });
  8880. newItemSet.add(items);
  8881. }
  8882. // set items
  8883. this.itemsData = newItemSet;
  8884. this.content.setItems(newItemSet);
  8885. if (initialLoad && (this.options.start == undefined || this.options.end == undefined)) {
  8886. // apply the data range as range
  8887. var dataRange = this.getItemRange();
  8888. // add 5% on both sides
  8889. var min = dataRange.min;
  8890. var max = dataRange.max;
  8891. if (min != null && max != null) {
  8892. var interval = (max.valueOf() - min.valueOf());
  8893. if (interval <= 0) {
  8894. // prevent an empty interval
  8895. interval = 24 * 60 * 60 * 1000; // 1 day
  8896. }
  8897. min = new Date(min.valueOf() - interval * 0.05);
  8898. max = new Date(max.valueOf() + interval * 0.05);
  8899. }
  8900. // override specified start and/or end date
  8901. if (this.options.start != undefined) {
  8902. min = new Date(this.options.start.valueOf());
  8903. }
  8904. if (this.options.end != undefined) {
  8905. max = new Date(this.options.end.valueOf());
  8906. }
  8907. // apply range if there is a min or max available
  8908. if (min != null || max != null) {
  8909. this.range.setRange(min, max);
  8910. }
  8911. }
  8912. };
  8913. /**
  8914. * Set groups
  8915. * @param {vis.DataSet | Array | DataTable} groups
  8916. */
  8917. Timeline.prototype.setGroups = function(groups) {
  8918. var me = this;
  8919. this.groupsData = groups;
  8920. // switch content type between ItemSet or GroupSet when needed
  8921. var type = this.groupsData ? GroupSet : ItemSet;
  8922. if (!(this.content instanceof type)) {
  8923. // remove old content set
  8924. if (this.content) {
  8925. this.content.hide();
  8926. if (this.content.setItems) {
  8927. this.content.setItems(); // disconnect from items
  8928. }
  8929. if (this.content.setGroups) {
  8930. this.content.setGroups(); // disconnect from groups
  8931. }
  8932. this.controller.remove(this.content);
  8933. }
  8934. // create new content set
  8935. var options = Object.create(this.options);
  8936. util.extend(options, {
  8937. top: function () {
  8938. if (me.options.orientation == 'top') {
  8939. return me.timeaxis.height;
  8940. }
  8941. else {
  8942. return me.itemPanel.height - me.timeaxis.height - me.content.height;
  8943. }
  8944. },
  8945. left: null,
  8946. width: '100%',
  8947. height: function () {
  8948. if (me.options.height) {
  8949. return me.itemPanel.height - me.timeaxis.height;
  8950. }
  8951. else {
  8952. return null;
  8953. }
  8954. },
  8955. maxHeight: function () {
  8956. if (me.options.maxHeight) {
  8957. if (!util.isNumber(me.options.maxHeight)) {
  8958. throw new TypeError('Number expected for property maxHeight');
  8959. }
  8960. return me.options.maxHeight - me.timeaxis.height;
  8961. }
  8962. else {
  8963. return null;
  8964. }
  8965. },
  8966. labelContainer: function () {
  8967. return me.labelPanel.getContainer();
  8968. }
  8969. });
  8970. this.content = new type(this.itemPanel, [this.timeaxis], options);
  8971. if (this.content.setRange) {
  8972. this.content.setRange(this.range);
  8973. }
  8974. if (this.content.setItems) {
  8975. this.content.setItems(this.itemsData);
  8976. }
  8977. if (this.content.setGroups) {
  8978. this.content.setGroups(this.groupsData);
  8979. }
  8980. this.controller.add(this.content);
  8981. }
  8982. };
  8983. /**
  8984. * Get the data range of the item set.
  8985. * @returns {{min: Date, max: Date}} range A range with a start and end Date.
  8986. * When no minimum is found, min==null
  8987. * When no maximum is found, max==null
  8988. */
  8989. Timeline.prototype.getItemRange = function getItemRange() {
  8990. // calculate min from start filed
  8991. var itemsData = this.itemsData,
  8992. min = null,
  8993. max = null;
  8994. if (itemsData) {
  8995. // calculate the minimum value of the field 'start'
  8996. var minItem = itemsData.min('start');
  8997. min = minItem ? minItem.start.valueOf() : null;
  8998. // calculate maximum value of fields 'start' and 'end'
  8999. var maxStartItem = itemsData.max('start');
  9000. if (maxStartItem) {
  9001. max = maxStartItem.start.valueOf();
  9002. }
  9003. var maxEndItem = itemsData.max('end');
  9004. if (maxEndItem) {
  9005. if (max == null) {
  9006. max = maxEndItem.end.valueOf();
  9007. }
  9008. else {
  9009. max = Math.max(max, maxEndItem.end.valueOf());
  9010. }
  9011. }
  9012. }
  9013. return {
  9014. min: (min != null) ? new Date(min) : null,
  9015. max: (max != null) ? new Date(max) : null
  9016. };
  9017. };
  9018. (function(exports) {
  9019. /**
  9020. * Parse a text source containing data in DOT language into a JSON object.
  9021. * The object contains two lists: one with nodes and one with edges.
  9022. *
  9023. * DOT language reference: http://www.graphviz.org/doc/info/lang.html
  9024. *
  9025. * @param {String} data Text containing a graph in DOT-notation
  9026. * @return {Object} graph An object containing two parameters:
  9027. * {Object[]} nodes
  9028. * {Object[]} edges
  9029. */
  9030. function parseDOT (data) {
  9031. dot = data;
  9032. return parseGraph();
  9033. }
  9034. // token types enumeration
  9035. var TOKENTYPE = {
  9036. NULL : 0,
  9037. DELIMITER : 1,
  9038. IDENTIFIER: 2,
  9039. UNKNOWN : 3
  9040. };
  9041. // map with all delimiters
  9042. var DELIMITERS = {
  9043. '{': true,
  9044. '}': true,
  9045. '[': true,
  9046. ']': true,
  9047. ';': true,
  9048. '=': true,
  9049. ',': true,
  9050. '->': true,
  9051. '--': true
  9052. };
  9053. var dot = ''; // current dot file
  9054. var index = 0; // current index in dot file
  9055. var c = ''; // current token character in expr
  9056. var token = ''; // current token
  9057. var tokenType = TOKENTYPE.NULL; // type of the token
  9058. /**
  9059. * Get the first character from the dot file.
  9060. * The character is stored into the char c. If the end of the dot file is
  9061. * reached, the function puts an empty string in c.
  9062. */
  9063. function first() {
  9064. index = 0;
  9065. c = dot.charAt(0);
  9066. }
  9067. /**
  9068. * Get the next character from the dot file.
  9069. * The character is stored into the char c. If the end of the dot file is
  9070. * reached, the function puts an empty string in c.
  9071. */
  9072. function next() {
  9073. index++;
  9074. c = dot.charAt(index);
  9075. }
  9076. /**
  9077. * Preview the next character from the dot file.
  9078. * @return {String} cNext
  9079. */
  9080. function nextPreview() {
  9081. return dot.charAt(index + 1);
  9082. }
  9083. /**
  9084. * Test whether given character is alphabetic or numeric
  9085. * @param {String} c
  9086. * @return {Boolean} isAlphaNumeric
  9087. */
  9088. var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/;
  9089. function isAlphaNumeric(c) {
  9090. return regexAlphaNumeric.test(c);
  9091. }
  9092. /**
  9093. * Merge all properties of object b into object b
  9094. * @param {Object} a
  9095. * @param {Object} b
  9096. * @return {Object} a
  9097. */
  9098. function merge (a, b) {
  9099. if (!a) {
  9100. a = {};
  9101. }
  9102. if (b) {
  9103. for (var name in b) {
  9104. if (b.hasOwnProperty(name)) {
  9105. a[name] = b[name];
  9106. }
  9107. }
  9108. }
  9109. return a;
  9110. }
  9111. /**
  9112. * Set a value in an object, where the provided parameter name can be a
  9113. * path with nested parameters. For example:
  9114. *
  9115. * var obj = {a: 2};
  9116. * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}}
  9117. *
  9118. * @param {Object} obj
  9119. * @param {String} path A parameter name or dot-separated parameter path,
  9120. * like "color.highlight.border".
  9121. * @param {*} value
  9122. */
  9123. function setValue(obj, path, value) {
  9124. var keys = path.split('.');
  9125. var o = obj;
  9126. while (keys.length) {
  9127. var key = keys.shift();
  9128. if (keys.length) {
  9129. // this isn't the end point
  9130. if (!o[key]) {
  9131. o[key] = {};
  9132. }
  9133. o = o[key];
  9134. }
  9135. else {
  9136. // this is the end point
  9137. o[key] = value;
  9138. }
  9139. }
  9140. }
  9141. /**
  9142. * Add a node to a graph object. If there is already a node with
  9143. * the same id, their attributes will be merged.
  9144. * @param {Object} graph
  9145. * @param {Object} node
  9146. */
  9147. function addNode(graph, node) {
  9148. var i, len;
  9149. var current = null;
  9150. // find root graph (in case of subgraph)
  9151. var graphs = [graph]; // list with all graphs from current graph to root graph
  9152. var root = graph;
  9153. while (root.parent) {
  9154. graphs.push(root.parent);
  9155. root = root.parent;
  9156. }
  9157. // find existing node (at root level) by its id
  9158. if (root.nodes) {
  9159. for (i = 0, len = root.nodes.length; i < len; i++) {
  9160. if (node.id === root.nodes[i].id) {
  9161. current = root.nodes[i];
  9162. break;
  9163. }
  9164. }
  9165. }
  9166. if (!current) {
  9167. // this is a new node
  9168. current = {
  9169. id: node.id
  9170. };
  9171. if (graph.node) {
  9172. // clone default attributes
  9173. current.attr = merge(current.attr, graph.node);
  9174. }
  9175. }
  9176. // add node to this (sub)graph and all its parent graphs
  9177. for (i = graphs.length - 1; i >= 0; i--) {
  9178. var g = graphs[i];
  9179. if (!g.nodes) {
  9180. g.nodes = [];
  9181. }
  9182. if (g.nodes.indexOf(current) == -1) {
  9183. g.nodes.push(current);
  9184. }
  9185. }
  9186. // merge attributes
  9187. if (node.attr) {
  9188. current.attr = merge(current.attr, node.attr);
  9189. }
  9190. }
  9191. /**
  9192. * Add an edge to a graph object
  9193. * @param {Object} graph
  9194. * @param {Object} edge
  9195. */
  9196. function addEdge(graph, edge) {
  9197. if (!graph.edges) {
  9198. graph.edges = [];
  9199. }
  9200. graph.edges.push(edge);
  9201. if (graph.edge) {
  9202. var attr = merge({}, graph.edge); // clone default attributes
  9203. edge.attr = merge(attr, edge.attr); // merge attributes
  9204. }
  9205. }
  9206. /**
  9207. * Create an edge to a graph object
  9208. * @param {Object} graph
  9209. * @param {String | Number | Object} from
  9210. * @param {String | Number | Object} to
  9211. * @param {String} type
  9212. * @param {Object | null} attr
  9213. * @return {Object} edge
  9214. */
  9215. function createEdge(graph, from, to, type, attr) {
  9216. var edge = {
  9217. from: from,
  9218. to: to,
  9219. type: type
  9220. };
  9221. if (graph.edge) {
  9222. edge.attr = merge({}, graph.edge); // clone default attributes
  9223. }
  9224. edge.attr = merge(edge.attr || {}, attr); // merge attributes
  9225. return edge;
  9226. }
  9227. /**
  9228. * Get next token in the current dot file.
  9229. * The token and token type are available as token and tokenType
  9230. */
  9231. function getToken() {
  9232. tokenType = TOKENTYPE.NULL;
  9233. token = '';
  9234. // skip over whitespaces
  9235. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  9236. next();
  9237. }
  9238. do {
  9239. var isComment = false;
  9240. // skip comment
  9241. if (c == '#') {
  9242. // find the previous non-space character
  9243. var i = index - 1;
  9244. while (dot.charAt(i) == ' ' || dot.charAt(i) == '\t') {
  9245. i--;
  9246. }
  9247. if (dot.charAt(i) == '\n' || dot.charAt(i) == '') {
  9248. // the # is at the start of a line, this is indeed a line comment
  9249. while (c != '' && c != '\n') {
  9250. next();
  9251. }
  9252. isComment = true;
  9253. }
  9254. }
  9255. if (c == '/' && nextPreview() == '/') {
  9256. // skip line comment
  9257. while (c != '' && c != '\n') {
  9258. next();
  9259. }
  9260. isComment = true;
  9261. }
  9262. if (c == '/' && nextPreview() == '*') {
  9263. // skip block comment
  9264. while (c != '') {
  9265. if (c == '*' && nextPreview() == '/') {
  9266. // end of block comment found. skip these last two characters
  9267. next();
  9268. next();
  9269. break;
  9270. }
  9271. else {
  9272. next();
  9273. }
  9274. }
  9275. isComment = true;
  9276. }
  9277. // skip over whitespaces
  9278. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  9279. next();
  9280. }
  9281. }
  9282. while (isComment);
  9283. // check for end of dot file
  9284. if (c == '') {
  9285. // token is still empty
  9286. tokenType = TOKENTYPE.DELIMITER;
  9287. return;
  9288. }
  9289. // check for delimiters consisting of 2 characters
  9290. var c2 = c + nextPreview();
  9291. if (DELIMITERS[c2]) {
  9292. tokenType = TOKENTYPE.DELIMITER;
  9293. token = c2;
  9294. next();
  9295. next();
  9296. return;
  9297. }
  9298. // check for delimiters consisting of 1 character
  9299. if (DELIMITERS[c]) {
  9300. tokenType = TOKENTYPE.DELIMITER;
  9301. token = c;
  9302. next();
  9303. return;
  9304. }
  9305. // check for an identifier (number or string)
  9306. // TODO: more precise parsing of numbers/strings (and the port separator ':')
  9307. if (isAlphaNumeric(c) || c == '-') {
  9308. token += c;
  9309. next();
  9310. while (isAlphaNumeric(c)) {
  9311. token += c;
  9312. next();
  9313. }
  9314. if (token == 'false') {
  9315. token = false; // convert to boolean
  9316. }
  9317. else if (token == 'true') {
  9318. token = true; // convert to boolean
  9319. }
  9320. else if (!isNaN(Number(token))) {
  9321. token = Number(token); // convert to number
  9322. }
  9323. tokenType = TOKENTYPE.IDENTIFIER;
  9324. return;
  9325. }
  9326. // check for a string enclosed by double quotes
  9327. if (c == '"') {
  9328. next();
  9329. while (c != '' && (c != '"' || (c == '"' && nextPreview() == '"'))) {
  9330. token += c;
  9331. if (c == '"') { // skip the escape character
  9332. next();
  9333. }
  9334. next();
  9335. }
  9336. if (c != '"') {
  9337. throw newSyntaxError('End of string " expected');
  9338. }
  9339. next();
  9340. tokenType = TOKENTYPE.IDENTIFIER;
  9341. return;
  9342. }
  9343. // something unknown is found, wrong characters, a syntax error
  9344. tokenType = TOKENTYPE.UNKNOWN;
  9345. while (c != '') {
  9346. token += c;
  9347. next();
  9348. }
  9349. throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"');
  9350. }
  9351. /**
  9352. * Parse a graph.
  9353. * @returns {Object} graph
  9354. */
  9355. function parseGraph() {
  9356. var graph = {};
  9357. first();
  9358. getToken();
  9359. // optional strict keyword
  9360. if (token == 'strict') {
  9361. graph.strict = true;
  9362. getToken();
  9363. }
  9364. // graph or digraph keyword
  9365. if (token == 'graph' || token == 'digraph') {
  9366. graph.type = token;
  9367. getToken();
  9368. }
  9369. // optional graph id
  9370. if (tokenType == TOKENTYPE.IDENTIFIER) {
  9371. graph.id = token;
  9372. getToken();
  9373. }
  9374. // open angle bracket
  9375. if (token != '{') {
  9376. throw newSyntaxError('Angle bracket { expected');
  9377. }
  9378. getToken();
  9379. // statements
  9380. parseStatements(graph);
  9381. // close angle bracket
  9382. if (token != '}') {
  9383. throw newSyntaxError('Angle bracket } expected');
  9384. }
  9385. getToken();
  9386. // end of file
  9387. if (token !== '') {
  9388. throw newSyntaxError('End of file expected');
  9389. }
  9390. getToken();
  9391. // remove temporary default properties
  9392. delete graph.node;
  9393. delete graph.edge;
  9394. delete graph.graph;
  9395. return graph;
  9396. }
  9397. /**
  9398. * Parse a list with statements.
  9399. * @param {Object} graph
  9400. */
  9401. function parseStatements (graph) {
  9402. while (token !== '' && token != '}') {
  9403. parseStatement(graph);
  9404. if (token == ';') {
  9405. getToken();
  9406. }
  9407. }
  9408. }
  9409. /**
  9410. * Parse a single statement. Can be a an attribute statement, node
  9411. * statement, a series of node statements and edge statements, or a
  9412. * parameter.
  9413. * @param {Object} graph
  9414. */
  9415. function parseStatement(graph) {
  9416. // parse subgraph
  9417. var subgraph = parseSubgraph(graph);
  9418. if (subgraph) {
  9419. // edge statements
  9420. parseEdge(graph, subgraph);
  9421. return;
  9422. }
  9423. // parse an attribute statement
  9424. var attr = parseAttributeStatement(graph);
  9425. if (attr) {
  9426. return;
  9427. }
  9428. // parse node
  9429. if (tokenType != TOKENTYPE.IDENTIFIER) {
  9430. throw newSyntaxError('Identifier expected');
  9431. }
  9432. var id = token; // id can be a string or a number
  9433. getToken();
  9434. if (token == '=') {
  9435. // id statement
  9436. getToken();
  9437. if (tokenType != TOKENTYPE.IDENTIFIER) {
  9438. throw newSyntaxError('Identifier expected');
  9439. }
  9440. graph[id] = token;
  9441. getToken();
  9442. // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] "
  9443. }
  9444. else {
  9445. parseNodeStatement(graph, id);
  9446. }
  9447. }
  9448. /**
  9449. * Parse a subgraph
  9450. * @param {Object} graph parent graph object
  9451. * @return {Object | null} subgraph
  9452. */
  9453. function parseSubgraph (graph) {
  9454. var subgraph = null;
  9455. // optional subgraph keyword
  9456. if (token == 'subgraph') {
  9457. subgraph = {};
  9458. subgraph.type = 'subgraph';
  9459. getToken();
  9460. // optional graph id
  9461. if (tokenType == TOKENTYPE.IDENTIFIER) {
  9462. subgraph.id = token;
  9463. getToken();
  9464. }
  9465. }
  9466. // open angle bracket
  9467. if (token == '{') {
  9468. getToken();
  9469. if (!subgraph) {
  9470. subgraph = {};
  9471. }
  9472. subgraph.parent = graph;
  9473. subgraph.node = graph.node;
  9474. subgraph.edge = graph.edge;
  9475. subgraph.graph = graph.graph;
  9476. // statements
  9477. parseStatements(subgraph);
  9478. // close angle bracket
  9479. if (token != '}') {
  9480. throw newSyntaxError('Angle bracket } expected');
  9481. }
  9482. getToken();
  9483. // remove temporary default properties
  9484. delete subgraph.node;
  9485. delete subgraph.edge;
  9486. delete subgraph.graph;
  9487. delete subgraph.parent;
  9488. // register at the parent graph
  9489. if (!graph.subgraphs) {
  9490. graph.subgraphs = [];
  9491. }
  9492. graph.subgraphs.push(subgraph);
  9493. }
  9494. return subgraph;
  9495. }
  9496. /**
  9497. * parse an attribute statement like "node [shape=circle fontSize=16]".
  9498. * Available keywords are 'node', 'edge', 'graph'.
  9499. * The previous list with default attributes will be replaced
  9500. * @param {Object} graph
  9501. * @returns {String | null} keyword Returns the name of the parsed attribute
  9502. * (node, edge, graph), or null if nothing
  9503. * is parsed.
  9504. */
  9505. function parseAttributeStatement (graph) {
  9506. // attribute statements
  9507. if (token == 'node') {
  9508. getToken();
  9509. // node attributes
  9510. graph.node = parseAttributeList();
  9511. return 'node';
  9512. }
  9513. else if (token == 'edge') {
  9514. getToken();
  9515. // edge attributes
  9516. graph.edge = parseAttributeList();
  9517. return 'edge';
  9518. }
  9519. else if (token == 'graph') {
  9520. getToken();
  9521. // graph attributes
  9522. graph.graph = parseAttributeList();
  9523. return 'graph';
  9524. }
  9525. return null;
  9526. }
  9527. /**
  9528. * parse a node statement
  9529. * @param {Object} graph
  9530. * @param {String | Number} id
  9531. */
  9532. function parseNodeStatement(graph, id) {
  9533. // node statement
  9534. var node = {
  9535. id: id
  9536. };
  9537. var attr = parseAttributeList();
  9538. if (attr) {
  9539. node.attr = attr;
  9540. }
  9541. addNode(graph, node);
  9542. // edge statements
  9543. parseEdge(graph, id);
  9544. }
  9545. /**
  9546. * Parse an edge or a series of edges
  9547. * @param {Object} graph
  9548. * @param {String | Number} from Id of the from node
  9549. */
  9550. function parseEdge(graph, from) {
  9551. while (token == '->' || token == '--') {
  9552. var to;
  9553. var type = token;
  9554. getToken();
  9555. var subgraph = parseSubgraph(graph);
  9556. if (subgraph) {
  9557. to = subgraph;
  9558. }
  9559. else {
  9560. if (tokenType != TOKENTYPE.IDENTIFIER) {
  9561. throw newSyntaxError('Identifier or subgraph expected');
  9562. }
  9563. to = token;
  9564. addNode(graph, {
  9565. id: to
  9566. });
  9567. getToken();
  9568. }
  9569. // parse edge attributes
  9570. var attr = parseAttributeList();
  9571. // create edge
  9572. var edge = createEdge(graph, from, to, type, attr);
  9573. addEdge(graph, edge);
  9574. from = to;
  9575. }
  9576. }
  9577. /**
  9578. * Parse a set with attributes,
  9579. * for example [label="1.000", shape=solid]
  9580. * @return {Object | null} attr
  9581. */
  9582. function parseAttributeList() {
  9583. var attr = null;
  9584. while (token == '[') {
  9585. getToken();
  9586. attr = {};
  9587. while (token !== '' && token != ']') {
  9588. if (tokenType != TOKENTYPE.IDENTIFIER) {
  9589. throw newSyntaxError('Attribute name expected');
  9590. }
  9591. var name = token;
  9592. getToken();
  9593. if (token != '=') {
  9594. throw newSyntaxError('Equal sign = expected');
  9595. }
  9596. getToken();
  9597. if (tokenType != TOKENTYPE.IDENTIFIER) {
  9598. throw newSyntaxError('Attribute value expected');
  9599. }
  9600. var value = token;
  9601. setValue(attr, name, value); // name can be a path
  9602. getToken();
  9603. if (token ==',') {
  9604. getToken();
  9605. }
  9606. }
  9607. if (token != ']') {
  9608. throw newSyntaxError('Bracket ] expected');
  9609. }
  9610. getToken();
  9611. }
  9612. return attr;
  9613. }
  9614. /**
  9615. * Create a syntax error with extra information on current token and index.
  9616. * @param {String} message
  9617. * @returns {SyntaxError} err
  9618. */
  9619. function newSyntaxError(message) {
  9620. return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')');
  9621. }
  9622. /**
  9623. * Chop off text after a maximum length
  9624. * @param {String} text
  9625. * @param {Number} maxLength
  9626. * @returns {String}
  9627. */
  9628. function chop (text, maxLength) {
  9629. return (text.length <= maxLength) ? text : (text.substr(0, 27) + '...');
  9630. }
  9631. /**
  9632. * Execute a function fn for each pair of elements in two arrays
  9633. * @param {Array | *} array1
  9634. * @param {Array | *} array2
  9635. * @param {function} fn
  9636. */
  9637. function forEach2(array1, array2, fn) {
  9638. if (array1 instanceof Array) {
  9639. array1.forEach(function (elem1) {
  9640. if (array2 instanceof Array) {
  9641. array2.forEach(function (elem2) {
  9642. fn(elem1, elem2);
  9643. });
  9644. }
  9645. else {
  9646. fn(elem1, array2);
  9647. }
  9648. });
  9649. }
  9650. else {
  9651. if (array2 instanceof Array) {
  9652. array2.forEach(function (elem2) {
  9653. fn(array1, elem2);
  9654. });
  9655. }
  9656. else {
  9657. fn(array1, array2);
  9658. }
  9659. }
  9660. }
  9661. /**
  9662. * Convert a string containing a graph in DOT language into a map containing
  9663. * with nodes and edges in the format of graph.
  9664. * @param {String} data Text containing a graph in DOT-notation
  9665. * @return {Object} graphData
  9666. */
  9667. function DOTToGraph (data) {
  9668. // parse the DOT file
  9669. var dotData = parseDOT(data);
  9670. var graphData = {
  9671. nodes: [],
  9672. edges: [],
  9673. options: {}
  9674. };
  9675. // copy the nodes
  9676. if (dotData.nodes) {
  9677. dotData.nodes.forEach(function (dotNode) {
  9678. var graphNode = {
  9679. id: dotNode.id,
  9680. label: String(dotNode.label || dotNode.id)
  9681. };
  9682. merge(graphNode, dotNode.attr);
  9683. if (graphNode.image) {
  9684. graphNode.shape = 'image';
  9685. }
  9686. graphData.nodes.push(graphNode);
  9687. });
  9688. }
  9689. // copy the edges
  9690. if (dotData.edges) {
  9691. /**
  9692. * Convert an edge in DOT format to an edge with VisGraph format
  9693. * @param {Object} dotEdge
  9694. * @returns {Object} graphEdge
  9695. */
  9696. function convertEdge(dotEdge) {
  9697. var graphEdge = {
  9698. from: dotEdge.from,
  9699. to: dotEdge.to
  9700. };
  9701. merge(graphEdge, dotEdge.attr);
  9702. graphEdge.style = (dotEdge.type == '->') ? 'arrow' : 'line';
  9703. return graphEdge;
  9704. }
  9705. dotData.edges.forEach(function (dotEdge) {
  9706. var from, to;
  9707. if (dotEdge.from instanceof Object) {
  9708. from = dotEdge.from.nodes;
  9709. }
  9710. else {
  9711. from = {
  9712. id: dotEdge.from
  9713. }
  9714. }
  9715. if (dotEdge.to instanceof Object) {
  9716. to = dotEdge.to.nodes;
  9717. }
  9718. else {
  9719. to = {
  9720. id: dotEdge.to
  9721. }
  9722. }
  9723. if (dotEdge.from instanceof Object && dotEdge.from.edges) {
  9724. dotEdge.from.edges.forEach(function (subEdge) {
  9725. var graphEdge = convertEdge(subEdge);
  9726. graphData.edges.push(graphEdge);
  9727. });
  9728. }
  9729. forEach2(from, to, function (from, to) {
  9730. var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr);
  9731. var graphEdge = convertEdge(subEdge);
  9732. graphData.edges.push(graphEdge);
  9733. });
  9734. if (dotEdge.to instanceof Object && dotEdge.to.edges) {
  9735. dotEdge.to.edges.forEach(function (subEdge) {
  9736. var graphEdge = convertEdge(subEdge);
  9737. graphData.edges.push(graphEdge);
  9738. });
  9739. }
  9740. });
  9741. }
  9742. // copy the options
  9743. if (dotData.attr) {
  9744. graphData.options = dotData.attr;
  9745. }
  9746. return graphData;
  9747. }
  9748. // exports
  9749. exports.parseDOT = parseDOT;
  9750. exports.DOTToGraph = DOTToGraph;
  9751. })(typeof util !== 'undefined' ? util : exports);
  9752. /**
  9753. * Canvas shapes used by the Graph
  9754. */
  9755. if (typeof CanvasRenderingContext2D !== 'undefined') {
  9756. /**
  9757. * Draw a circle shape
  9758. */
  9759. CanvasRenderingContext2D.prototype.circle = function(x, y, r) {
  9760. this.beginPath();
  9761. this.arc(x, y, r, 0, 2*Math.PI, false);
  9762. };
  9763. /**
  9764. * Draw a square shape
  9765. * @param {Number} x horizontal center
  9766. * @param {Number} y vertical center
  9767. * @param {Number} r size, width and height of the square
  9768. */
  9769. CanvasRenderingContext2D.prototype.square = function(x, y, r) {
  9770. this.beginPath();
  9771. this.rect(x - r, y - r, r * 2, r * 2);
  9772. };
  9773. /**
  9774. * Draw a triangle shape
  9775. * @param {Number} x horizontal center
  9776. * @param {Number} y vertical center
  9777. * @param {Number} r radius, half the length of the sides of the triangle
  9778. */
  9779. CanvasRenderingContext2D.prototype.triangle = function(x, y, r) {
  9780. // http://en.wikipedia.org/wiki/Equilateral_triangle
  9781. this.beginPath();
  9782. var s = r * 2;
  9783. var s2 = s / 2;
  9784. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  9785. var h = Math.sqrt(s * s - s2 * s2); // height
  9786. this.moveTo(x, y - (h - ir));
  9787. this.lineTo(x + s2, y + ir);
  9788. this.lineTo(x - s2, y + ir);
  9789. this.lineTo(x, y - (h - ir));
  9790. this.closePath();
  9791. };
  9792. /**
  9793. * Draw a triangle shape in downward orientation
  9794. * @param {Number} x horizontal center
  9795. * @param {Number} y vertical center
  9796. * @param {Number} r radius
  9797. */
  9798. CanvasRenderingContext2D.prototype.triangleDown = function(x, y, r) {
  9799. // http://en.wikipedia.org/wiki/Equilateral_triangle
  9800. this.beginPath();
  9801. var s = r * 2;
  9802. var s2 = s / 2;
  9803. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  9804. var h = Math.sqrt(s * s - s2 * s2); // height
  9805. this.moveTo(x, y + (h - ir));
  9806. this.lineTo(x + s2, y - ir);
  9807. this.lineTo(x - s2, y - ir);
  9808. this.lineTo(x, y + (h - ir));
  9809. this.closePath();
  9810. };
  9811. /**
  9812. * Draw a star shape, a star with 5 points
  9813. * @param {Number} x horizontal center
  9814. * @param {Number} y vertical center
  9815. * @param {Number} r radius, half the length of the sides of the triangle
  9816. */
  9817. CanvasRenderingContext2D.prototype.star = function(x, y, r) {
  9818. // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/
  9819. this.beginPath();
  9820. for (var n = 0; n < 10; n++) {
  9821. var radius = (n % 2 === 0) ? r * 1.3 : r * 0.5;
  9822. this.lineTo(
  9823. x + radius * Math.sin(n * 2 * Math.PI / 10),
  9824. y - radius * Math.cos(n * 2 * Math.PI / 10)
  9825. );
  9826. }
  9827. this.closePath();
  9828. };
  9829. /**
  9830. * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas
  9831. */
  9832. CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) {
  9833. var r2d = Math.PI/180;
  9834. if( w - ( 2 * r ) < 0 ) { r = ( w / 2 ); } //ensure that the radius isn't too large for x
  9835. if( h - ( 2 * r ) < 0 ) { r = ( h / 2 ); } //ensure that the radius isn't too large for y
  9836. this.beginPath();
  9837. this.moveTo(x+r,y);
  9838. this.lineTo(x+w-r,y);
  9839. this.arc(x+w-r,y+r,r,r2d*270,r2d*360,false);
  9840. this.lineTo(x+w,y+h-r);
  9841. this.arc(x+w-r,y+h-r,r,0,r2d*90,false);
  9842. this.lineTo(x+r,y+h);
  9843. this.arc(x+r,y+h-r,r,r2d*90,r2d*180,false);
  9844. this.lineTo(x,y+r);
  9845. this.arc(x+r,y+r,r,r2d*180,r2d*270,false);
  9846. };
  9847. /**
  9848. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  9849. */
  9850. CanvasRenderingContext2D.prototype.ellipse = function(x, y, w, h) {
  9851. var kappa = .5522848,
  9852. ox = (w / 2) * kappa, // control point offset horizontal
  9853. oy = (h / 2) * kappa, // control point offset vertical
  9854. xe = x + w, // x-end
  9855. ye = y + h, // y-end
  9856. xm = x + w / 2, // x-middle
  9857. ym = y + h / 2; // y-middle
  9858. this.beginPath();
  9859. this.moveTo(x, ym);
  9860. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  9861. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  9862. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  9863. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  9864. };
  9865. /**
  9866. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  9867. */
  9868. CanvasRenderingContext2D.prototype.database = function(x, y, w, h) {
  9869. var f = 1/3;
  9870. var wEllipse = w;
  9871. var hEllipse = h * f;
  9872. var kappa = .5522848,
  9873. ox = (wEllipse / 2) * kappa, // control point offset horizontal
  9874. oy = (hEllipse / 2) * kappa, // control point offset vertical
  9875. xe = x + wEllipse, // x-end
  9876. ye = y + hEllipse, // y-end
  9877. xm = x + wEllipse / 2, // x-middle
  9878. ym = y + hEllipse / 2, // y-middle
  9879. ymb = y + (h - hEllipse/2), // y-midlle, bottom ellipse
  9880. yeb = y + h; // y-end, bottom ellipse
  9881. this.beginPath();
  9882. this.moveTo(xe, ym);
  9883. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  9884. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  9885. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  9886. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  9887. this.lineTo(xe, ymb);
  9888. this.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb);
  9889. this.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb);
  9890. this.lineTo(x, ym);
  9891. };
  9892. /**
  9893. * Draw an arrow point (no line)
  9894. */
  9895. CanvasRenderingContext2D.prototype.arrow = function(x, y, angle, length) {
  9896. // tail
  9897. var xt = x - length * Math.cos(angle);
  9898. var yt = y - length * Math.sin(angle);
  9899. // inner tail
  9900. // TODO: allow to customize different shapes
  9901. var xi = x - length * 0.9 * Math.cos(angle);
  9902. var yi = y - length * 0.9 * Math.sin(angle);
  9903. // left
  9904. var xl = xt + length / 3 * Math.cos(angle + 0.5 * Math.PI);
  9905. var yl = yt + length / 3 * Math.sin(angle + 0.5 * Math.PI);
  9906. // right
  9907. var xr = xt + length / 3 * Math.cos(angle - 0.5 * Math.PI);
  9908. var yr = yt + length / 3 * Math.sin(angle - 0.5 * Math.PI);
  9909. this.beginPath();
  9910. this.moveTo(x, y);
  9911. this.lineTo(xl, yl);
  9912. this.lineTo(xi, yi);
  9913. this.lineTo(xr, yr);
  9914. this.closePath();
  9915. };
  9916. /**
  9917. * Sets up the dashedLine functionality for drawing
  9918. * Original code came from http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
  9919. * @author David Jordan
  9920. * @date 2012-08-08
  9921. */
  9922. CanvasRenderingContext2D.prototype.dashedLine = function(x,y,x2,y2,dashArray){
  9923. if (!dashArray) dashArray=[10,5];
  9924. if (dashLength==0) dashLength = 0.001; // Hack for Safari
  9925. var dashCount = dashArray.length;
  9926. this.moveTo(x, y);
  9927. var dx = (x2-x), dy = (y2-y);
  9928. var slope = dy/dx;
  9929. var distRemaining = Math.sqrt( dx*dx + dy*dy );
  9930. var dashIndex=0, draw=true;
  9931. while (distRemaining>=0.1){
  9932. var dashLength = dashArray[dashIndex++%dashCount];
  9933. if (dashLength > distRemaining) dashLength = distRemaining;
  9934. var xStep = Math.sqrt( dashLength*dashLength / (1 + slope*slope) );
  9935. if (dx<0) xStep = -xStep;
  9936. x += xStep;
  9937. y += slope*xStep;
  9938. this[draw ? 'lineTo' : 'moveTo'](x,y);
  9939. distRemaining -= dashLength;
  9940. draw = !draw;
  9941. }
  9942. };
  9943. // TODO: add diamond shape
  9944. }
  9945. /**
  9946. * @class Node
  9947. * A node. A node can be connected to other nodes via one or multiple edges.
  9948. * @param {object} properties An object containing properties for the node. All
  9949. * properties are optional, except for the id.
  9950. * {number} id Id of the node. Required
  9951. * {string} label Text label for the node
  9952. * {number} x Horizontal position of the node
  9953. * {number} y Vertical position of the node
  9954. * {string} shape Node shape, available:
  9955. * "database", "circle", "ellipse",
  9956. * "box", "image", "text", "dot",
  9957. * "star", "triangle", "triangleDown",
  9958. * "square"
  9959. * {string} image An image url
  9960. * {string} title An title text, can be HTML
  9961. * {anytype} group A group name or number
  9962. * @param {Graph.Images} imagelist A list with images. Only needed
  9963. * when the node has an image
  9964. * @param {Graph.Groups} grouplist A list with groups. Needed for
  9965. * retrieving group properties
  9966. * @param {Object} constants An object with default values for
  9967. * example for the color
  9968. */
  9969. function Node(properties, imagelist, grouplist, constants) {
  9970. this.selected = false;
  9971. this.edges = []; // all edges connected to this node
  9972. this.group = constants.nodes.group;
  9973. this.fontSize = constants.nodes.fontSize;
  9974. this.fontFace = constants.nodes.fontFace;
  9975. this.fontColor = constants.nodes.fontColor;
  9976. this.color = constants.nodes.color;
  9977. // set defaults for the properties
  9978. this.id = undefined;
  9979. this.shape = constants.nodes.shape;
  9980. this.image = constants.nodes.image;
  9981. this.x = 0;
  9982. this.y = 0;
  9983. this.xFixed = false;
  9984. this.yFixed = false;
  9985. this.radius = constants.nodes.radius;
  9986. this.radiusFixed = false;
  9987. this.radiusMin = constants.nodes.radiusMin;
  9988. this.radiusMax = constants.nodes.radiusMax;
  9989. this.imagelist = imagelist;
  9990. this.grouplist = grouplist;
  9991. this.setProperties(properties, constants);
  9992. // mass, force, velocity
  9993. this.mass = 50; // kg (mass is adjusted for the number of connected edges)
  9994. this.fx = 0.0; // external force x
  9995. this.fy = 0.0; // external force y
  9996. this.vx = 0.0; // velocity x
  9997. this.vy = 0.0; // velocity y
  9998. this.minForce = constants.minForce;
  9999. this.damping = 0.9; // damping factor
  10000. };
  10001. /**
  10002. * Attach a edge to the node
  10003. * @param {Edge} edge
  10004. */
  10005. Node.prototype.attachEdge = function(edge) {
  10006. if (this.edges.indexOf(edge) == -1) {
  10007. this.edges.push(edge);
  10008. }
  10009. this._updateMass();
  10010. };
  10011. /**
  10012. * Detach a edge from the node
  10013. * @param {Edge} edge
  10014. */
  10015. Node.prototype.detachEdge = function(edge) {
  10016. var index = this.edges.indexOf(edge);
  10017. if (index != -1) {
  10018. this.edges.splice(index, 1);
  10019. }
  10020. this._updateMass();
  10021. };
  10022. /**
  10023. * Update the nodes mass, which is determined by the number of edges connecting
  10024. * to it (more edges -> heavier node).
  10025. * @private
  10026. */
  10027. Node.prototype._updateMass = function() {
  10028. this.mass = 50 + 20 * this.edges.length; // kg
  10029. };
  10030. /**
  10031. * Set or overwrite properties for the node
  10032. * @param {Object} properties an object with properties
  10033. * @param {Object} constants and object with default, global properties
  10034. */
  10035. Node.prototype.setProperties = function(properties, constants) {
  10036. if (!properties) {
  10037. return;
  10038. }
  10039. // basic properties
  10040. if (properties.id != undefined) {this.id = properties.id;}
  10041. if (properties.label != undefined) {this.label = properties.label;}
  10042. if (properties.title != undefined) {this.title = properties.title;}
  10043. if (properties.group != undefined) {this.group = properties.group;}
  10044. if (properties.x != undefined) {this.x = properties.x;}
  10045. if (properties.y != undefined) {this.y = properties.y;}
  10046. if (properties.value != undefined) {this.value = properties.value;}
  10047. if (this.id === undefined) {
  10048. throw "Node must have an id";
  10049. }
  10050. // copy group properties
  10051. if (this.group) {
  10052. var groupObj = this.grouplist.get(this.group);
  10053. for (var prop in groupObj) {
  10054. if (groupObj.hasOwnProperty(prop)) {
  10055. this[prop] = groupObj[prop];
  10056. }
  10057. }
  10058. }
  10059. // individual shape properties
  10060. if (properties.shape != undefined) {this.shape = properties.shape;}
  10061. if (properties.image != undefined) {this.image = properties.image;}
  10062. if (properties.radius != undefined) {this.radius = properties.radius;}
  10063. if (properties.color != undefined) {this.color = Node.parseColor(properties.color);}
  10064. if (properties.fontColor != undefined) {this.fontColor = properties.fontColor;}
  10065. if (properties.fontSize != undefined) {this.fontSize = properties.fontSize;}
  10066. if (properties.fontFace != undefined) {this.fontFace = properties.fontFace;}
  10067. if (this.image != undefined) {
  10068. if (this.imagelist) {
  10069. this.imageObj = this.imagelist.load(this.image);
  10070. }
  10071. else {
  10072. throw "No imagelist provided";
  10073. }
  10074. }
  10075. this.xFixed = this.xFixed || (properties.x != undefined);
  10076. this.yFixed = this.yFixed || (properties.y != undefined);
  10077. this.radiusFixed = this.radiusFixed || (properties.radius != undefined);
  10078. if (this.shape == 'image') {
  10079. this.radiusMin = constants.nodes.widthMin;
  10080. this.radiusMax = constants.nodes.widthMax;
  10081. }
  10082. // choose draw method depending on the shape
  10083. switch (this.shape) {
  10084. case 'database': this.draw = this._drawDatabase; this.resize = this._resizeDatabase; break;
  10085. case 'box': this.draw = this._drawBox; this.resize = this._resizeBox; break;
  10086. case 'circle': this.draw = this._drawCircle; this.resize = this._resizeCircle; break;
  10087. case 'ellipse': this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  10088. // TODO: add diamond shape
  10089. case 'image': this.draw = this._drawImage; this.resize = this._resizeImage; break;
  10090. case 'text': this.draw = this._drawText; this.resize = this._resizeText; break;
  10091. case 'dot': this.draw = this._drawDot; this.resize = this._resizeShape; break;
  10092. case 'square': this.draw = this._drawSquare; this.resize = this._resizeShape; break;
  10093. case 'triangle': this.draw = this._drawTriangle; this.resize = this._resizeShape; break;
  10094. case 'triangleDown': this.draw = this._drawTriangleDown; this.resize = this._resizeShape; break;
  10095. case 'star': this.draw = this._drawStar; this.resize = this._resizeShape; break;
  10096. default: this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  10097. }
  10098. // reset the size of the node, this can be changed
  10099. this._reset();
  10100. };
  10101. /**
  10102. * Parse a color property into an object with border, background, and
  10103. * hightlight colors
  10104. * @param {Object | String} color
  10105. * @return {Object} colorObject
  10106. */
  10107. Node.parseColor = function(color) {
  10108. var c;
  10109. if (util.isString(color)) {
  10110. c = {
  10111. border: color,
  10112. background: color,
  10113. highlight: {
  10114. border: color,
  10115. background: color
  10116. }
  10117. };
  10118. // TODO: automatically generate a nice highlight color
  10119. }
  10120. else {
  10121. c = {};
  10122. c.background = color.background || 'white';
  10123. c.border = color.border || c.background;
  10124. if (util.isString(color.highlight)) {
  10125. c.highlight = {
  10126. border: color.highlight,
  10127. background: color.highlight
  10128. }
  10129. }
  10130. else {
  10131. c.highlight = {};
  10132. c.highlight.background = color.highlight && color.highlight.background || c.background;
  10133. c.highlight.border = color.highlight && color.highlight.border || c.border;
  10134. }
  10135. }
  10136. return c;
  10137. };
  10138. /**
  10139. * select this node
  10140. */
  10141. Node.prototype.select = function() {
  10142. this.selected = true;
  10143. this._reset();
  10144. };
  10145. /**
  10146. * unselect this node
  10147. */
  10148. Node.prototype.unselect = function() {
  10149. this.selected = false;
  10150. this._reset();
  10151. };
  10152. /**
  10153. * Reset the calculated size of the node, forces it to recalculate its size
  10154. * @private
  10155. */
  10156. Node.prototype._reset = function() {
  10157. this.width = undefined;
  10158. this.height = undefined;
  10159. };
  10160. /**
  10161. * get the title of this node.
  10162. * @return {string} title The title of the node, or undefined when no title
  10163. * has been set.
  10164. */
  10165. Node.prototype.getTitle = function() {
  10166. return this.title;
  10167. };
  10168. /**
  10169. * Calculate the distance to the border of the Node
  10170. * @param {CanvasRenderingContext2D} ctx
  10171. * @param {Number} angle Angle in radians
  10172. * @returns {number} distance Distance to the border in pixels
  10173. */
  10174. Node.prototype.distanceToBorder = function (ctx, angle) {
  10175. var borderWidth = 1;
  10176. if (!this.width) {
  10177. this.resize(ctx);
  10178. }
  10179. //noinspection FallthroughInSwitchStatementJS
  10180. switch (this.shape) {
  10181. case 'circle':
  10182. case 'dot':
  10183. return this.radius + borderWidth;
  10184. case 'ellipse':
  10185. var a = this.width / 2;
  10186. var b = this.height / 2;
  10187. var w = (Math.sin(angle) * a);
  10188. var h = (Math.cos(angle) * b);
  10189. return a * b / Math.sqrt(w * w + h * h);
  10190. // TODO: implement distanceToBorder for database
  10191. // TODO: implement distanceToBorder for triangle
  10192. // TODO: implement distanceToBorder for triangleDown
  10193. case 'box':
  10194. case 'image':
  10195. case 'text':
  10196. default:
  10197. if (this.width) {
  10198. return Math.min(
  10199. Math.abs(this.width / 2 / Math.cos(angle)),
  10200. Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth;
  10201. // TODO: reckon with border radius too in case of box
  10202. }
  10203. else {
  10204. return 0;
  10205. }
  10206. }
  10207. // TODO: implement calculation of distance to border for all shapes
  10208. };
  10209. /**
  10210. * Set forces acting on the node
  10211. * @param {number} fx Force in horizontal direction
  10212. * @param {number} fy Force in vertical direction
  10213. */
  10214. Node.prototype._setForce = function(fx, fy) {
  10215. this.fx = fx;
  10216. this.fy = fy;
  10217. };
  10218. /**
  10219. * Add forces acting on the node
  10220. * @param {number} fx Force in horizontal direction
  10221. * @param {number} fy Force in vertical direction
  10222. * @private
  10223. */
  10224. Node.prototype._addForce = function(fx, fy) {
  10225. this.fx += fx;
  10226. this.fy += fy;
  10227. };
  10228. /**
  10229. * Perform one discrete step for the node
  10230. * @param {number} interval Time interval in seconds
  10231. */
  10232. Node.prototype.discreteStep = function(interval) {
  10233. if (!this.xFixed) {
  10234. var dx = -this.damping * this.vx; // damping force
  10235. var ax = (this.fx + dx) / this.mass; // acceleration
  10236. this.vx += ax / interval; // velocity
  10237. this.x += this.vx / interval; // position
  10238. }
  10239. if (!this.yFixed) {
  10240. var dy = -this.damping * this.vy; // damping force
  10241. var ay = (this.fy + dy) / this.mass; // acceleration
  10242. this.vy += ay / interval; // velocity
  10243. this.y += this.vy / interval; // position
  10244. }
  10245. };
  10246. /**
  10247. * Check if this node has a fixed x and y position
  10248. * @return {boolean} true if fixed, false if not
  10249. */
  10250. Node.prototype.isFixed = function() {
  10251. return (this.xFixed && this.yFixed);
  10252. };
  10253. /**
  10254. * Check if this node is moving
  10255. * @param {number} vmin the minimum velocity considered as "moving"
  10256. * @return {boolean} true if moving, false if it has no velocity
  10257. */
  10258. // TODO: replace this method with calculating the kinetic energy
  10259. Node.prototype.isMoving = function(vmin) {
  10260. return (Math.abs(this.vx) > vmin || Math.abs(this.vy) > vmin ||
  10261. (!this.xFixed && Math.abs(this.fx) > this.minForce) ||
  10262. (!this.yFixed && Math.abs(this.fy) > this.minForce));
  10263. };
  10264. /**
  10265. * check if this node is selecte
  10266. * @return {boolean} selected True if node is selected, else false
  10267. */
  10268. Node.prototype.isSelected = function() {
  10269. return this.selected;
  10270. };
  10271. /**
  10272. * Retrieve the value of the node. Can be undefined
  10273. * @return {Number} value
  10274. */
  10275. Node.prototype.getValue = function() {
  10276. return this.value;
  10277. };
  10278. /**
  10279. * Calculate the distance from the nodes location to the given location (x,y)
  10280. * @param {Number} x
  10281. * @param {Number} y
  10282. * @return {Number} value
  10283. */
  10284. Node.prototype.getDistance = function(x, y) {
  10285. var dx = this.x - x,
  10286. dy = this.y - y;
  10287. return Math.sqrt(dx * dx + dy * dy);
  10288. };
  10289. /**
  10290. * Adjust the value range of the node. The node will adjust it's radius
  10291. * based on its value.
  10292. * @param {Number} min
  10293. * @param {Number} max
  10294. */
  10295. Node.prototype.setValueRange = function(min, max) {
  10296. if (!this.radiusFixed && this.value !== undefined) {
  10297. var scale = (this.radiusMax - this.radiusMin) / (max - min);
  10298. this.radius = (this.value - min) * scale + this.radiusMin;
  10299. }
  10300. };
  10301. /**
  10302. * Draw this node in the given canvas
  10303. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  10304. * @param {CanvasRenderingContext2D} ctx
  10305. */
  10306. Node.prototype.draw = function(ctx) {
  10307. throw "Draw method not initialized for node";
  10308. };
  10309. /**
  10310. * Recalculate the size of this node in the given canvas
  10311. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  10312. * @param {CanvasRenderingContext2D} ctx
  10313. */
  10314. Node.prototype.resize = function(ctx) {
  10315. throw "Resize method not initialized for node";
  10316. };
  10317. /**
  10318. * Check if this object is overlapping with the provided object
  10319. * @param {Object} obj an object with parameters left, top, right, bottom
  10320. * @return {boolean} True if location is located on node
  10321. */
  10322. Node.prototype.isOverlappingWith = function(obj) {
  10323. return (this.left < obj.right &&
  10324. this.left + this.width > obj.left &&
  10325. this.top < obj.bottom &&
  10326. this.top + this.height > obj.top);
  10327. };
  10328. Node.prototype._resizeImage = function (ctx) {
  10329. // TODO: pre calculate the image size
  10330. if (!this.width) { // undefined or 0
  10331. var width, height;
  10332. if (this.value) {
  10333. var scale = this.imageObj.height / this.imageObj.width;
  10334. width = this.radius || this.imageObj.width;
  10335. height = this.radius * scale || this.imageObj.height;
  10336. }
  10337. else {
  10338. width = this.imageObj.width;
  10339. height = this.imageObj.height;
  10340. }
  10341. this.width = width;
  10342. this.height = height;
  10343. }
  10344. };
  10345. Node.prototype._drawImage = function (ctx) {
  10346. this._resizeImage(ctx);
  10347. this.left = this.x - this.width / 2;
  10348. this.top = this.y - this.height / 2;
  10349. var yLabel;
  10350. if (this.imageObj) {
  10351. ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height);
  10352. yLabel = this.y + this.height / 2;
  10353. }
  10354. else {
  10355. // image still loading... just draw the label for now
  10356. yLabel = this.y;
  10357. }
  10358. this._label(ctx, this.label, this.x, yLabel, undefined, "top");
  10359. };
  10360. Node.prototype._resizeBox = function (ctx) {
  10361. if (!this.width) {
  10362. var margin = 5;
  10363. var textSize = this.getTextSize(ctx);
  10364. this.width = textSize.width + 2 * margin;
  10365. this.height = textSize.height + 2 * margin;
  10366. }
  10367. };
  10368. Node.prototype._drawBox = function (ctx) {
  10369. this._resizeBox(ctx);
  10370. this.left = this.x - this.width / 2;
  10371. this.top = this.y - this.height / 2;
  10372. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  10373. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  10374. ctx.lineWidth = this.selected ? 2.0 : 1.0;
  10375. ctx.roundRect(this.left, this.top, this.width, this.height, this.radius);
  10376. ctx.fill();
  10377. ctx.stroke();
  10378. this._label(ctx, this.label, this.x, this.y);
  10379. };
  10380. Node.prototype._resizeDatabase = function (ctx) {
  10381. if (!this.width) {
  10382. var margin = 5;
  10383. var textSize = this.getTextSize(ctx);
  10384. var size = textSize.width + 2 * margin;
  10385. this.width = size;
  10386. this.height = size;
  10387. }
  10388. };
  10389. Node.prototype._drawDatabase = function (ctx) {
  10390. this._resizeDatabase(ctx);
  10391. this.left = this.x - this.width / 2;
  10392. this.top = this.y - this.height / 2;
  10393. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  10394. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  10395. ctx.lineWidth = this.selected ? 2.0 : 1.0;
  10396. ctx.database(this.x - this.width/2, this.y - this.height*0.5, this.width, this.height);
  10397. ctx.fill();
  10398. ctx.stroke();
  10399. this._label(ctx, this.label, this.x, this.y);
  10400. };
  10401. Node.prototype._resizeCircle = function (ctx) {
  10402. if (!this.width) {
  10403. var margin = 5;
  10404. var textSize = this.getTextSize(ctx);
  10405. var diameter = Math.max(textSize.width, textSize.height) + 2 * margin;
  10406. this.radius = diameter / 2;
  10407. this.width = diameter;
  10408. this.height = diameter;
  10409. }
  10410. };
  10411. Node.prototype._drawCircle = function (ctx) {
  10412. this._resizeCircle(ctx);
  10413. this.left = this.x - this.width / 2;
  10414. this.top = this.y - this.height / 2;
  10415. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  10416. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  10417. ctx.lineWidth = this.selected ? 2.0 : 1.0;
  10418. ctx.circle(this.x, this.y, this.radius);
  10419. ctx.fill();
  10420. ctx.stroke();
  10421. this._label(ctx, this.label, this.x, this.y);
  10422. };
  10423. Node.prototype._resizeEllipse = function (ctx) {
  10424. if (!this.width) {
  10425. var textSize = this.getTextSize(ctx);
  10426. this.width = textSize.width * 1.5;
  10427. this.height = textSize.height * 2;
  10428. if (this.width < this.height) {
  10429. this.width = this.height;
  10430. }
  10431. }
  10432. };
  10433. Node.prototype._drawEllipse = function (ctx) {
  10434. this._resizeEllipse(ctx);
  10435. this.left = this.x - this.width / 2;
  10436. this.top = this.y - this.height / 2;
  10437. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  10438. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  10439. ctx.lineWidth = this.selected ? 2.0 : 1.0;
  10440. ctx.ellipse(this.left, this.top, this.width, this.height);
  10441. ctx.fill();
  10442. ctx.stroke();
  10443. this._label(ctx, this.label, this.x, this.y);
  10444. };
  10445. Node.prototype._drawDot = function (ctx) {
  10446. this._drawShape(ctx, 'circle');
  10447. };
  10448. Node.prototype._drawTriangle = function (ctx) {
  10449. this._drawShape(ctx, 'triangle');
  10450. };
  10451. Node.prototype._drawTriangleDown = function (ctx) {
  10452. this._drawShape(ctx, 'triangleDown');
  10453. };
  10454. Node.prototype._drawSquare = function (ctx) {
  10455. this._drawShape(ctx, 'square');
  10456. };
  10457. Node.prototype._drawStar = function (ctx) {
  10458. this._drawShape(ctx, 'star');
  10459. };
  10460. Node.prototype._resizeShape = function (ctx) {
  10461. if (!this.width) {
  10462. var size = 2 * this.radius;
  10463. this.width = size;
  10464. this.height = size;
  10465. }
  10466. };
  10467. Node.prototype._drawShape = function (ctx, shape) {
  10468. this._resizeShape(ctx);
  10469. this.left = this.x - this.width / 2;
  10470. this.top = this.y - this.height / 2;
  10471. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  10472. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  10473. ctx.lineWidth = this.selected ? 2.0 : 1.0;
  10474. ctx[shape](this.x, this.y, this.radius);
  10475. ctx.fill();
  10476. ctx.stroke();
  10477. if (this.label) {
  10478. this._label(ctx, this.label, this.x, this.y + this.height / 2, undefined, 'top');
  10479. }
  10480. };
  10481. Node.prototype._resizeText = function (ctx) {
  10482. if (!this.width) {
  10483. var margin = 5;
  10484. var textSize = this.getTextSize(ctx);
  10485. this.width = textSize.width + 2 * margin;
  10486. this.height = textSize.height + 2 * margin;
  10487. }
  10488. };
  10489. Node.prototype._drawText = function (ctx) {
  10490. this._resizeText(ctx);
  10491. this.left = this.x - this.width / 2;
  10492. this.top = this.y - this.height / 2;
  10493. this._label(ctx, this.label, this.x, this.y);
  10494. };
  10495. Node.prototype._label = function (ctx, text, x, y, align, baseline) {
  10496. if (text) {
  10497. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  10498. ctx.fillStyle = this.fontColor || "black";
  10499. ctx.textAlign = align || "center";
  10500. ctx.textBaseline = baseline || "middle";
  10501. var lines = text.split('\n'),
  10502. lineCount = lines.length,
  10503. fontSize = (this.fontSize + 4),
  10504. yLine = y + (1 - lineCount) / 2 * fontSize;
  10505. for (var i = 0; i < lineCount; i++) {
  10506. ctx.fillText(lines[i], x, yLine);
  10507. yLine += fontSize;
  10508. }
  10509. }
  10510. };
  10511. Node.prototype.getTextSize = function(ctx) {
  10512. if (this.label != undefined) {
  10513. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  10514. var lines = this.label.split('\n'),
  10515. height = (this.fontSize + 4) * lines.length,
  10516. width = 0;
  10517. for (var i = 0, iMax = lines.length; i < iMax; i++) {
  10518. width = Math.max(width, ctx.measureText(lines[i]).width);
  10519. }
  10520. return {"width": width, "height": height};
  10521. }
  10522. else {
  10523. return {"width": 0, "height": 0};
  10524. }
  10525. };
  10526. /**
  10527. * @class Edge
  10528. *
  10529. * A edge connects two nodes
  10530. * @param {Object} properties Object with properties. Must contain
  10531. * At least properties from and to.
  10532. * Available properties: from (number),
  10533. * to (number), label (string, color (string),
  10534. * width (number), style (string),
  10535. * length (number), title (string)
  10536. * @param {Graph} graph A graph object, used to find and edge to
  10537. * nodes.
  10538. * @param {Object} constants An object with default values for
  10539. * example for the color
  10540. */
  10541. function Edge (properties, graph, constants) {
  10542. if (!graph) {
  10543. throw "No graph provided";
  10544. }
  10545. this.graph = graph;
  10546. // initialize constants
  10547. this.widthMin = constants.edges.widthMin;
  10548. this.widthMax = constants.edges.widthMax;
  10549. // initialize variables
  10550. this.id = undefined;
  10551. this.fromId = undefined;
  10552. this.toId = undefined;
  10553. this.style = constants.edges.style;
  10554. this.title = undefined;
  10555. this.width = constants.edges.width;
  10556. this.value = undefined;
  10557. this.length = constants.edges.length;
  10558. this.from = null; // a node
  10559. this.to = null; // a node
  10560. this.connected = false;
  10561. // Added to support dashed lines
  10562. // David Jordan
  10563. // 2012-08-08
  10564. this.dash = util.extend({}, constants.edges.dash); // contains properties length, gap, altLength
  10565. this.stiffness = undefined; // depends on the length of the edge
  10566. this.color = constants.edges.color;
  10567. this.widthFixed = false;
  10568. this.lengthFixed = false;
  10569. this.setProperties(properties, constants);
  10570. }
  10571. /**
  10572. * Set or overwrite properties for the edge
  10573. * @param {Object} properties an object with properties
  10574. * @param {Object} constants and object with default, global properties
  10575. */
  10576. Edge.prototype.setProperties = function(properties, constants) {
  10577. if (!properties) {
  10578. return;
  10579. }
  10580. if (properties.from != undefined) {this.fromId = properties.from;}
  10581. if (properties.to != undefined) {this.toId = properties.to;}
  10582. if (properties.id != undefined) {this.id = properties.id;}
  10583. if (properties.style != undefined) {this.style = properties.style;}
  10584. if (properties.label != undefined) {this.label = properties.label;}
  10585. if (this.label) {
  10586. this.fontSize = constants.edges.fontSize;
  10587. this.fontFace = constants.edges.fontFace;
  10588. this.fontColor = constants.edges.fontColor;
  10589. if (properties.fontColor != undefined) {this.fontColor = properties.fontColor;}
  10590. if (properties.fontSize != undefined) {this.fontSize = properties.fontSize;}
  10591. if (properties.fontFace != undefined) {this.fontFace = properties.fontFace;}
  10592. }
  10593. if (properties.title != undefined) {this.title = properties.title;}
  10594. if (properties.width != undefined) {this.width = properties.width;}
  10595. if (properties.value != undefined) {this.value = properties.value;}
  10596. if (properties.length != undefined) {this.length = properties.length;}
  10597. // Added to support dashed lines
  10598. // David Jordan
  10599. // 2012-08-08
  10600. if (properties.dash) {
  10601. if (properties.dash.length != undefined) {this.dash.length = properties.dash.length;}
  10602. if (properties.dash.gap != undefined) {this.dash.gap = properties.dash.gap;}
  10603. if (properties.dash.altLength != undefined) {this.dash.altLength = properties.dash.altLength;}
  10604. }
  10605. if (properties.color != undefined) {this.color = properties.color;}
  10606. // A node is connected when it has a from and to node.
  10607. this.connect();
  10608. this.widthFixed = this.widthFixed || (properties.width != undefined);
  10609. this.lengthFixed = this.lengthFixed || (properties.length != undefined);
  10610. this.stiffness = 1 / this.length;
  10611. // set draw method based on style
  10612. switch (this.style) {
  10613. case 'line': this.draw = this._drawLine; break;
  10614. case 'arrow': this.draw = this._drawArrow; break;
  10615. case 'arrow-center': this.draw = this._drawArrowCenter; break;
  10616. case 'dash-line': this.draw = this._drawDashLine; break;
  10617. default: this.draw = this._drawLine; break;
  10618. }
  10619. };
  10620. /**
  10621. * Connect an edge to its nodes
  10622. */
  10623. Edge.prototype.connect = function () {
  10624. this.disconnect();
  10625. this.from = this.graph.nodes[this.fromId] || null;
  10626. this.to = this.graph.nodes[this.toId] || null;
  10627. this.connected = (this.from && this.to);
  10628. if (this.connected) {
  10629. this.from.attachEdge(this);
  10630. this.to.attachEdge(this);
  10631. }
  10632. else {
  10633. if (this.from) {
  10634. this.from.detachEdge(this);
  10635. }
  10636. if (this.to) {
  10637. this.to.detachEdge(this);
  10638. }
  10639. }
  10640. };
  10641. /**
  10642. * Disconnect an edge from its nodes
  10643. */
  10644. Edge.prototype.disconnect = function () {
  10645. if (this.from) {
  10646. this.from.detachEdge(this);
  10647. this.from = null;
  10648. }
  10649. if (this.to) {
  10650. this.to.detachEdge(this);
  10651. this.to = null;
  10652. }
  10653. this.connected = false;
  10654. };
  10655. /**
  10656. * get the title of this edge.
  10657. * @return {string} title The title of the edge, or undefined when no title
  10658. * has been set.
  10659. */
  10660. Edge.prototype.getTitle = function() {
  10661. return this.title;
  10662. };
  10663. /**
  10664. * Retrieve the value of the edge. Can be undefined
  10665. * @return {Number} value
  10666. */
  10667. Edge.prototype.getValue = function() {
  10668. return this.value;
  10669. };
  10670. /**
  10671. * Adjust the value range of the edge. The edge will adjust it's width
  10672. * based on its value.
  10673. * @param {Number} min
  10674. * @param {Number} max
  10675. */
  10676. Edge.prototype.setValueRange = function(min, max) {
  10677. if (!this.widthFixed && this.value !== undefined) {
  10678. var factor = (this.widthMax - this.widthMin) / (max - min);
  10679. this.width = (this.value - min) * factor + this.widthMin;
  10680. }
  10681. };
  10682. /**
  10683. * Redraw a edge
  10684. * Draw this edge in the given canvas
  10685. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  10686. * @param {CanvasRenderingContext2D} ctx
  10687. */
  10688. Edge.prototype.draw = function(ctx) {
  10689. throw "Method draw not initialized in edge";
  10690. };
  10691. /**
  10692. * Check if this object is overlapping with the provided object
  10693. * @param {Object} obj an object with parameters left, top
  10694. * @return {boolean} True if location is located on the edge
  10695. */
  10696. Edge.prototype.isOverlappingWith = function(obj) {
  10697. var distMax = 10;
  10698. var xFrom = this.from.x;
  10699. var yFrom = this.from.y;
  10700. var xTo = this.to.x;
  10701. var yTo = this.to.y;
  10702. var xObj = obj.left;
  10703. var yObj = obj.top;
  10704. var dist = Edge._dist(xFrom, yFrom, xTo, yTo, xObj, yObj);
  10705. return (dist < distMax);
  10706. };
  10707. /**
  10708. * Redraw a edge as a line
  10709. * Draw this edge in the given canvas
  10710. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  10711. * @param {CanvasRenderingContext2D} ctx
  10712. * @private
  10713. */
  10714. Edge.prototype._drawLine = function(ctx) {
  10715. // set style
  10716. ctx.strokeStyle = this.color;
  10717. ctx.lineWidth = this._getLineWidth();
  10718. var point;
  10719. if (this.from != this.to) {
  10720. // draw line
  10721. this._line(ctx);
  10722. // draw label
  10723. if (this.label) {
  10724. point = this._pointOnLine(0.5);
  10725. this._label(ctx, this.label, point.x, point.y);
  10726. }
  10727. }
  10728. else {
  10729. var x, y;
  10730. var radius = this.length / 4;
  10731. var node = this.from;
  10732. if (!node.width) {
  10733. node.resize(ctx);
  10734. }
  10735. if (node.width > node.height) {
  10736. x = node.x + node.width / 2;
  10737. y = node.y - radius;
  10738. }
  10739. else {
  10740. x = node.x + radius;
  10741. y = node.y - node.height / 2;
  10742. }
  10743. this._circle(ctx, x, y, radius);
  10744. point = this._pointOnCircle(x, y, radius, 0.5);
  10745. this._label(ctx, this.label, point.x, point.y);
  10746. }
  10747. };
  10748. /**
  10749. * Get the line width of the edge. Depends on width and whether one of the
  10750. * connected nodes is selected.
  10751. * @return {Number} width
  10752. * @private
  10753. */
  10754. Edge.prototype._getLineWidth = function() {
  10755. if (this.from.selected || this.to.selected) {
  10756. return Math.min(this.width * 2, this.widthMax);
  10757. }
  10758. else {
  10759. return this.width;
  10760. }
  10761. };
  10762. /**
  10763. * Draw a line between two nodes
  10764. * @param {CanvasRenderingContext2D} ctx
  10765. * @private
  10766. */
  10767. Edge.prototype._line = function (ctx) {
  10768. // draw a straight line
  10769. ctx.beginPath();
  10770. ctx.moveTo(this.from.x, this.from.y);
  10771. ctx.lineTo(this.to.x, this.to.y);
  10772. ctx.stroke();
  10773. };
  10774. /**
  10775. * Draw a line from a node to itself, a circle
  10776. * @param {CanvasRenderingContext2D} ctx
  10777. * @param {Number} x
  10778. * @param {Number} y
  10779. * @param {Number} radius
  10780. * @private
  10781. */
  10782. Edge.prototype._circle = function (ctx, x, y, radius) {
  10783. // draw a circle
  10784. ctx.beginPath();
  10785. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  10786. ctx.stroke();
  10787. };
  10788. /**
  10789. * Draw label with white background and with the middle at (x, y)
  10790. * @param {CanvasRenderingContext2D} ctx
  10791. * @param {String} text
  10792. * @param {Number} x
  10793. * @param {Number} y
  10794. * @private
  10795. */
  10796. Edge.prototype._label = function (ctx, text, x, y) {
  10797. if (text) {
  10798. // TODO: cache the calculated size
  10799. ctx.font = ((this.from.selected || this.to.selected) ? "bold " : "") +
  10800. this.fontSize + "px " + this.fontFace;
  10801. ctx.fillStyle = 'white';
  10802. var width = ctx.measureText(text).width;
  10803. var height = this.fontSize;
  10804. var left = x - width / 2;
  10805. var top = y - height / 2;
  10806. ctx.fillRect(left, top, width, height);
  10807. // draw text
  10808. ctx.fillStyle = this.fontColor || "black";
  10809. ctx.textAlign = "left";
  10810. ctx.textBaseline = "top";
  10811. ctx.fillText(text, left, top);
  10812. }
  10813. };
  10814. /**
  10815. * Redraw a edge as a dashed line
  10816. * Draw this edge in the given canvas
  10817. * @author David Jordan
  10818. * @date 2012-08-08
  10819. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  10820. * @param {CanvasRenderingContext2D} ctx
  10821. * @private
  10822. */
  10823. Edge.prototype._drawDashLine = function(ctx) {
  10824. // set style
  10825. ctx.strokeStyle = this.color;
  10826. ctx.lineWidth = this._getLineWidth();
  10827. // draw dashed line
  10828. ctx.beginPath();
  10829. ctx.lineCap = 'round';
  10830. if (this.dash.altLength != undefined) //If an alt dash value has been set add to the array this value
  10831. {
  10832. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  10833. [this.dash.length,this.dash.gap,this.dash.altLength,this.dash.gap]);
  10834. }
  10835. 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
  10836. {
  10837. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  10838. [this.dash.length,this.dash.gap]);
  10839. }
  10840. else //If all else fails draw a line
  10841. {
  10842. ctx.moveTo(this.from.x, this.from.y);
  10843. ctx.lineTo(this.to.x, this.to.y);
  10844. }
  10845. ctx.stroke();
  10846. // draw label
  10847. if (this.label) {
  10848. var point = this._pointOnLine(0.5);
  10849. this._label(ctx, this.label, point.x, point.y);
  10850. }
  10851. };
  10852. /**
  10853. * Get a point on a line
  10854. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  10855. * @return {Object} point
  10856. * @private
  10857. */
  10858. Edge.prototype._pointOnLine = function (percentage) {
  10859. return {
  10860. x: (1 - percentage) * this.from.x + percentage * this.to.x,
  10861. y: (1 - percentage) * this.from.y + percentage * this.to.y
  10862. }
  10863. };
  10864. /**
  10865. * Get a point on a circle
  10866. * @param {Number} x
  10867. * @param {Number} y
  10868. * @param {Number} radius
  10869. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  10870. * @return {Object} point
  10871. * @private
  10872. */
  10873. Edge.prototype._pointOnCircle = function (x, y, radius, percentage) {
  10874. var angle = (percentage - 3/8) * 2 * Math.PI;
  10875. return {
  10876. x: x + radius * Math.cos(angle),
  10877. y: y - radius * Math.sin(angle)
  10878. }
  10879. };
  10880. /**
  10881. * Redraw a edge as a line with an arrow halfway the line
  10882. * Draw this edge in the given canvas
  10883. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  10884. * @param {CanvasRenderingContext2D} ctx
  10885. * @private
  10886. */
  10887. Edge.prototype._drawArrowCenter = function(ctx) {
  10888. var point;
  10889. // set style
  10890. ctx.strokeStyle = this.color;
  10891. ctx.fillStyle = this.color;
  10892. ctx.lineWidth = this._getLineWidth();
  10893. if (this.from != this.to) {
  10894. // draw line
  10895. this._line(ctx);
  10896. // draw an arrow halfway the line
  10897. var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  10898. var length = 10 + 5 * this.width; // TODO: make customizable?
  10899. point = this._pointOnLine(0.5);
  10900. ctx.arrow(point.x, point.y, angle, length);
  10901. ctx.fill();
  10902. ctx.stroke();
  10903. // draw label
  10904. if (this.label) {
  10905. point = this._pointOnLine(0.5);
  10906. this._label(ctx, this.label, point.x, point.y);
  10907. }
  10908. }
  10909. else {
  10910. // draw circle
  10911. var x, y;
  10912. var radius = this.length / 4;
  10913. var node = this.from;
  10914. if (!node.width) {
  10915. node.resize(ctx);
  10916. }
  10917. if (node.width > node.height) {
  10918. x = node.x + node.width / 2;
  10919. y = node.y - radius;
  10920. }
  10921. else {
  10922. x = node.x + radius;
  10923. y = node.y - node.height / 2;
  10924. }
  10925. this._circle(ctx, x, y, radius);
  10926. // draw all arrows
  10927. var angle = 0.2 * Math.PI;
  10928. var length = 10 + 5 * this.width; // TODO: make customizable?
  10929. point = this._pointOnCircle(x, y, radius, 0.5);
  10930. ctx.arrow(point.x, point.y, angle, length);
  10931. ctx.fill();
  10932. ctx.stroke();
  10933. // draw label
  10934. if (this.label) {
  10935. point = this._pointOnCircle(x, y, radius, 0.5);
  10936. this._label(ctx, this.label, point.x, point.y);
  10937. }
  10938. }
  10939. };
  10940. /**
  10941. * Redraw a edge as a line with an arrow
  10942. * Draw this edge in the given canvas
  10943. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  10944. * @param {CanvasRenderingContext2D} ctx
  10945. * @private
  10946. */
  10947. Edge.prototype._drawArrow = function(ctx) {
  10948. // set style
  10949. ctx.strokeStyle = this.color;
  10950. ctx.fillStyle = this.color;
  10951. ctx.lineWidth = this._getLineWidth();
  10952. // draw line
  10953. var angle, length;
  10954. if (this.from != this.to) {
  10955. // calculate length and angle of the line
  10956. angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  10957. var dx = (this.to.x - this.from.x);
  10958. var dy = (this.to.y - this.from.y);
  10959. var lEdge = Math.sqrt(dx * dx + dy * dy);
  10960. var lFrom = this.from.distanceToBorder(ctx, angle + Math.PI);
  10961. var pFrom = (lEdge - lFrom) / lEdge;
  10962. var xFrom = (pFrom) * this.from.x + (1 - pFrom) * this.to.x;
  10963. var yFrom = (pFrom) * this.from.y + (1 - pFrom) * this.to.y;
  10964. var lTo = this.to.distanceToBorder(ctx, angle);
  10965. var pTo = (lEdge - lTo) / lEdge;
  10966. var xTo = (1 - pTo) * this.from.x + pTo * this.to.x;
  10967. var yTo = (1 - pTo) * this.from.y + pTo * this.to.y;
  10968. ctx.beginPath();
  10969. ctx.moveTo(xFrom, yFrom);
  10970. ctx.lineTo(xTo, yTo);
  10971. ctx.stroke();
  10972. // draw arrow at the end of the line
  10973. length = 10 + 5 * this.width; // TODO: make customizable?
  10974. ctx.arrow(xTo, yTo, angle, length);
  10975. ctx.fill();
  10976. ctx.stroke();
  10977. // draw label
  10978. if (this.label) {
  10979. var point = this._pointOnLine(0.5);
  10980. this._label(ctx, this.label, point.x, point.y);
  10981. }
  10982. }
  10983. else {
  10984. // draw circle
  10985. var node = this.from;
  10986. var x, y, arrow;
  10987. var radius = this.length / 4;
  10988. if (!node.width) {
  10989. node.resize(ctx);
  10990. }
  10991. if (node.width > node.height) {
  10992. x = node.x + node.width / 2;
  10993. y = node.y - radius;
  10994. arrow = {
  10995. x: x,
  10996. y: node.y,
  10997. angle: 0.9 * Math.PI
  10998. };
  10999. }
  11000. else {
  11001. x = node.x + radius;
  11002. y = node.y - node.height / 2;
  11003. arrow = {
  11004. x: node.x,
  11005. y: y,
  11006. angle: 0.6 * Math.PI
  11007. };
  11008. }
  11009. ctx.beginPath();
  11010. // TODO: do not draw a circle, but an arc
  11011. // TODO: similarly, for a line without arrows, draw to the border of the nodes instead of the center
  11012. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  11013. ctx.stroke();
  11014. // draw all arrows
  11015. length = 10 + 5 * this.width; // TODO: make customizable?
  11016. ctx.arrow(arrow.x, arrow.y, arrow.angle, length);
  11017. ctx.fill();
  11018. ctx.stroke();
  11019. // draw label
  11020. if (this.label) {
  11021. point = this._pointOnCircle(x, y, radius, 0.5);
  11022. this._label(ctx, this.label, point.x, point.y);
  11023. }
  11024. }
  11025. };
  11026. /**
  11027. * Calculate the distance between a point (x3,y3) and a line segment from
  11028. * (x1,y1) to (x2,y2).
  11029. * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
  11030. * @param {number} x1
  11031. * @param {number} y1
  11032. * @param {number} x2
  11033. * @param {number} y2
  11034. * @param {number} x3
  11035. * @param {number} y3
  11036. * @private
  11037. */
  11038. Edge._dist = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is the point
  11039. var px = x2-x1,
  11040. py = y2-y1,
  11041. something = px*px + py*py,
  11042. u = ((x3 - x1) * px + (y3 - y1) * py) / something;
  11043. if (u > 1) {
  11044. u = 1;
  11045. }
  11046. else if (u < 0) {
  11047. u = 0;
  11048. }
  11049. var x = x1 + u * px,
  11050. y = y1 + u * py,
  11051. dx = x - x3,
  11052. dy = y - y3;
  11053. //# Note: If the actual distance does not matter,
  11054. //# if you only want to compare what this function
  11055. //# returns to other results of this function, you
  11056. //# can just return the squared distance instead
  11057. //# (i.e. remove the sqrt) to gain a little performance
  11058. return Math.sqrt(dx*dx + dy*dy);
  11059. };
  11060. /**
  11061. * Popup is a class to create a popup window with some text
  11062. * @param {Element} container The container object.
  11063. * @param {Number} [x]
  11064. * @param {Number} [y]
  11065. * @param {String} [text]
  11066. */
  11067. function Popup(container, x, y, text) {
  11068. if (container) {
  11069. this.container = container;
  11070. }
  11071. else {
  11072. this.container = document.body;
  11073. }
  11074. this.x = 0;
  11075. this.y = 0;
  11076. this.padding = 5;
  11077. if (x !== undefined && y !== undefined ) {
  11078. this.setPosition(x, y);
  11079. }
  11080. if (text !== undefined) {
  11081. this.setText(text);
  11082. }
  11083. // create the frame
  11084. this.frame = document.createElement("div");
  11085. var style = this.frame.style;
  11086. style.position = "absolute";
  11087. style.visibility = "hidden";
  11088. style.border = "1px solid #666";
  11089. style.color = "black";
  11090. style.padding = this.padding + "px";
  11091. style.backgroundColor = "#FFFFC6";
  11092. style.borderRadius = "3px";
  11093. style.MozBorderRadius = "3px";
  11094. style.WebkitBorderRadius = "3px";
  11095. style.boxShadow = "3px 3px 10px rgba(128, 128, 128, 0.5)";
  11096. style.whiteSpace = "nowrap";
  11097. this.container.appendChild(this.frame);
  11098. };
  11099. /**
  11100. * @param {number} x Horizontal position of the popup window
  11101. * @param {number} y Vertical position of the popup window
  11102. */
  11103. Popup.prototype.setPosition = function(x, y) {
  11104. this.x = parseInt(x);
  11105. this.y = parseInt(y);
  11106. };
  11107. /**
  11108. * Set the text for the popup window. This can be HTML code
  11109. * @param {string} text
  11110. */
  11111. Popup.prototype.setText = function(text) {
  11112. this.frame.innerHTML = text;
  11113. };
  11114. /**
  11115. * Show the popup window
  11116. * @param {boolean} show Optional. Show or hide the window
  11117. */
  11118. Popup.prototype.show = function (show) {
  11119. if (show === undefined) {
  11120. show = true;
  11121. }
  11122. if (show) {
  11123. var height = this.frame.clientHeight;
  11124. var width = this.frame.clientWidth;
  11125. var maxHeight = this.frame.parentNode.clientHeight;
  11126. var maxWidth = this.frame.parentNode.clientWidth;
  11127. var top = (this.y - height);
  11128. if (top + height + this.padding > maxHeight) {
  11129. top = maxHeight - height - this.padding;
  11130. }
  11131. if (top < this.padding) {
  11132. top = this.padding;
  11133. }
  11134. var left = this.x;
  11135. if (left + width + this.padding > maxWidth) {
  11136. left = maxWidth - width - this.padding;
  11137. }
  11138. if (left < this.padding) {
  11139. left = this.padding;
  11140. }
  11141. this.frame.style.left = left + "px";
  11142. this.frame.style.top = top + "px";
  11143. this.frame.style.visibility = "visible";
  11144. }
  11145. else {
  11146. this.hide();
  11147. }
  11148. };
  11149. /**
  11150. * Hide the popup window
  11151. */
  11152. Popup.prototype.hide = function () {
  11153. this.frame.style.visibility = "hidden";
  11154. };
  11155. /**
  11156. * @class Groups
  11157. * This class can store groups and properties specific for groups.
  11158. */
  11159. Groups = function () {
  11160. this.clear();
  11161. this.defaultIndex = 0;
  11162. };
  11163. /**
  11164. * default constants for group colors
  11165. */
  11166. Groups.DEFAULT = [
  11167. {border: "#2B7CE9", background: "#97C2FC", highlight: {border: "#2B7CE9", background: "#D2E5FF"}}, // blue
  11168. {border: "#FFA500", background: "#FFFF00", highlight: {border: "#FFA500", background: "#FFFFA3"}}, // yellow
  11169. {border: "#FA0A10", background: "#FB7E81", highlight: {border: "#FA0A10", background: "#FFAFB1"}}, // red
  11170. {border: "#41A906", background: "#7BE141", highlight: {border: "#41A906", background: "#A1EC76"}}, // green
  11171. {border: "#E129F0", background: "#EB7DF4", highlight: {border: "#E129F0", background: "#F0B3F5"}}, // magenta
  11172. {border: "#7C29F0", background: "#AD85E4", highlight: {border: "#7C29F0", background: "#D3BDF0"}}, // purple
  11173. {border: "#C37F00", background: "#FFA807", highlight: {border: "#C37F00", background: "#FFCA66"}}, // orange
  11174. {border: "#4220FB", background: "#6E6EFD", highlight: {border: "#4220FB", background: "#9B9BFD"}}, // darkblue
  11175. {border: "#FD5A77", background: "#FFC0CB", highlight: {border: "#FD5A77", background: "#FFD1D9"}}, // pink
  11176. {border: "#4AD63A", background: "#C2FABC", highlight: {border: "#4AD63A", background: "#E6FFE3"}} // mint
  11177. ];
  11178. /**
  11179. * Clear all groups
  11180. */
  11181. Groups.prototype.clear = function () {
  11182. this.groups = {};
  11183. this.groups.length = function()
  11184. {
  11185. var i = 0;
  11186. for ( var p in this ) {
  11187. if (this.hasOwnProperty(p)) {
  11188. i++;
  11189. }
  11190. }
  11191. return i;
  11192. }
  11193. };
  11194. /**
  11195. * get group properties of a groupname. If groupname is not found, a new group
  11196. * is added.
  11197. * @param {*} groupname Can be a number, string, Date, etc.
  11198. * @return {Object} group The created group, containing all group properties
  11199. */
  11200. Groups.prototype.get = function (groupname) {
  11201. var group = this.groups[groupname];
  11202. if (group == undefined) {
  11203. // create new group
  11204. var index = this.defaultIndex % Groups.DEFAULT.length;
  11205. this.defaultIndex++;
  11206. group = {};
  11207. group.color = Groups.DEFAULT[index];
  11208. this.groups[groupname] = group;
  11209. }
  11210. return group;
  11211. };
  11212. /**
  11213. * Add a custom group style
  11214. * @param {String} groupname
  11215. * @param {Object} style An object containing borderColor,
  11216. * backgroundColor, etc.
  11217. * @return {Object} group The created group object
  11218. */
  11219. Groups.prototype.add = function (groupname, style) {
  11220. this.groups[groupname] = style;
  11221. if (style.color) {
  11222. style.color = Node.parseColor(style.color);
  11223. }
  11224. return style;
  11225. };
  11226. /**
  11227. * @class Images
  11228. * This class loads images and keeps them stored.
  11229. */
  11230. Images = function () {
  11231. this.images = {};
  11232. this.callback = undefined;
  11233. };
  11234. /**
  11235. * Set an onload callback function. This will be called each time an image
  11236. * is loaded
  11237. * @param {function} callback
  11238. */
  11239. Images.prototype.setOnloadCallback = function(callback) {
  11240. this.callback = callback;
  11241. };
  11242. /**
  11243. *
  11244. * @param {string} url Url of the image
  11245. * @return {Image} img The image object
  11246. */
  11247. Images.prototype.load = function(url) {
  11248. var img = this.images[url];
  11249. if (img == undefined) {
  11250. // create the image
  11251. var images = this;
  11252. img = new Image();
  11253. this.images[url] = img;
  11254. img.onload = function() {
  11255. if (images.callback) {
  11256. images.callback(this);
  11257. }
  11258. };
  11259. img.src = url;
  11260. }
  11261. return img;
  11262. };
  11263. /**
  11264. * @constructor Graph
  11265. * Create a graph visualization, displaying nodes and edges.
  11266. *
  11267. * @param {Element} container The DOM element in which the Graph will
  11268. * be created. Normally a div element.
  11269. * @param {Object} data An object containing parameters
  11270. * {Array} nodes
  11271. * {Array} edges
  11272. * @param {Object} options Options
  11273. */
  11274. function Graph (container, data, options) {
  11275. // create variables and set default values
  11276. this.containerElement = container;
  11277. this.width = '100%';
  11278. this.height = '100%';
  11279. this.refreshRate = 50; // milliseconds
  11280. this.stabilize = true; // stabilize before displaying the graph
  11281. this.selectable = true;
  11282. // set constant values
  11283. this.constants = {
  11284. nodes: {
  11285. radiusMin: 5,
  11286. radiusMax: 20,
  11287. radius: 5,
  11288. distance: 100, // px
  11289. shape: 'ellipse',
  11290. image: undefined,
  11291. widthMin: 16, // px
  11292. widthMax: 64, // px
  11293. fontColor: 'black',
  11294. fontSize: 14, // px
  11295. //fontFace: verdana,
  11296. fontFace: 'arial',
  11297. color: {
  11298. border: '#2B7CE9',
  11299. background: '#97C2FC',
  11300. highlight: {
  11301. border: '#2B7CE9',
  11302. background: '#D2E5FF'
  11303. }
  11304. },
  11305. borderColor: '#2B7CE9',
  11306. backgroundColor: '#97C2FC',
  11307. highlightColor: '#D2E5FF',
  11308. group: undefined
  11309. },
  11310. edges: {
  11311. widthMin: 1,
  11312. widthMax: 15,
  11313. width: 1,
  11314. style: 'line',
  11315. color: '#343434',
  11316. fontColor: '#343434',
  11317. fontSize: 14, // px
  11318. fontFace: 'arial',
  11319. //distance: 100, //px
  11320. length: 100, // px
  11321. dash: {
  11322. length: 10,
  11323. gap: 5,
  11324. altLength: undefined
  11325. }
  11326. },
  11327. minForce: 0.05,
  11328. minVelocity: 0.02, // px/s
  11329. maxIterations: 1000 // maximum number of iteration to stabilize
  11330. };
  11331. var graph = this;
  11332. this.nodes = {}; // object with Node objects
  11333. this.edges = {}; // object with Edge objects
  11334. // TODO: create a counter to keep track on the number of nodes having values
  11335. // TODO: create a counter to keep track on the number of nodes currently moving
  11336. // TODO: create a counter to keep track on the number of edges having values
  11337. this.nodesData = null; // A DataSet or DataView
  11338. this.edgesData = null; // A DataSet or DataView
  11339. // create event listeners used to subscribe on the DataSets of the nodes and edges
  11340. var me = this;
  11341. this.nodesListeners = {
  11342. 'add': function (event, params) {
  11343. me._addNodes(params.items);
  11344. me.start();
  11345. },
  11346. 'update': function (event, params) {
  11347. me._updateNodes(params.items);
  11348. me.start();
  11349. },
  11350. 'remove': function (event, params) {
  11351. me._removeNodes(params.items);
  11352. me.start();
  11353. }
  11354. };
  11355. this.edgesListeners = {
  11356. 'add': function (event, params) {
  11357. me._addEdges(params.items);
  11358. me.start();
  11359. },
  11360. 'update': function (event, params) {
  11361. me._updateEdges(params.items);
  11362. me.start();
  11363. },
  11364. 'remove': function (event, params) {
  11365. me._removeEdges(params.items);
  11366. me.start();
  11367. }
  11368. };
  11369. this.groups = new Groups(); // object with groups
  11370. this.images = new Images(); // object with images
  11371. this.images.setOnloadCallback(function () {
  11372. graph._redraw();
  11373. });
  11374. // properties of the data
  11375. this.moving = false; // True if any of the nodes have an undefined position
  11376. this.selection = [];
  11377. this.timer = undefined;
  11378. // create a frame and canvas
  11379. this._create();
  11380. // apply options
  11381. this.setOptions(options);
  11382. // draw data
  11383. this.setData(data);
  11384. }
  11385. /**
  11386. * Set nodes and edges, and optionally options as well.
  11387. *
  11388. * @param {Object} data Object containing parameters:
  11389. * {Array | DataSet | DataView} [nodes] Array with nodes
  11390. * {Array | DataSet | DataView} [edges] Array with edges
  11391. * {String} [dot] String containing data in DOT format
  11392. * {Options} [options] Object with options
  11393. */
  11394. Graph.prototype.setData = function(data) {
  11395. if (data && data.dot && (data.nodes || data.edges)) {
  11396. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  11397. ' parameter pair "nodes" and "edges", but not both.');
  11398. }
  11399. // set options
  11400. this.setOptions(data && data.options);
  11401. // set all data
  11402. if (data && data.dot) {
  11403. // parse DOT file
  11404. if(data && data.dot) {
  11405. var dotData = vis.util.DOTToGraph(data.dot);
  11406. this.setData(dotData);
  11407. return;
  11408. }
  11409. }
  11410. else {
  11411. this._setNodes(data && data.nodes);
  11412. this._setEdges(data && data.edges);
  11413. }
  11414. // find a stable position or start animating to a stable position
  11415. if (this.stabilize) {
  11416. this._doStabilize();
  11417. }
  11418. this.start();
  11419. };
  11420. /**
  11421. * Set options
  11422. * @param {Object} options
  11423. */
  11424. Graph.prototype.setOptions = function (options) {
  11425. if (options) {
  11426. // retrieve parameter values
  11427. if (options.width != undefined) {this.width = options.width;}
  11428. if (options.height != undefined) {this.height = options.height;}
  11429. if (options.stabilize != undefined) {this.stabilize = options.stabilize;}
  11430. if (options.selectable != undefined) {this.selectable = options.selectable;}
  11431. // TODO: work out these options and document them
  11432. if (options.edges) {
  11433. for (var prop in options.edges) {
  11434. if (options.edges.hasOwnProperty(prop)) {
  11435. this.constants.edges[prop] = options.edges[prop];
  11436. }
  11437. }
  11438. if (options.edges.length != undefined &&
  11439. options.nodes && options.nodes.distance == undefined) {
  11440. this.constants.edges.length = options.edges.length;
  11441. this.constants.nodes.distance = options.edges.length * 1.25;
  11442. }
  11443. if (!options.edges.fontColor) {
  11444. this.constants.edges.fontColor = options.edges.color;
  11445. }
  11446. // Added to support dashed lines
  11447. // David Jordan
  11448. // 2012-08-08
  11449. if (options.edges.dash) {
  11450. if (options.edges.dash.length != undefined) {
  11451. this.constants.edges.dash.length = options.edges.dash.length;
  11452. }
  11453. if (options.edges.dash.gap != undefined) {
  11454. this.constants.edges.dash.gap = options.edges.dash.gap;
  11455. }
  11456. if (options.edges.dash.altLength != undefined) {
  11457. this.constants.edges.dash.altLength = options.edges.dash.altLength;
  11458. }
  11459. }
  11460. }
  11461. if (options.nodes) {
  11462. for (prop in options.nodes) {
  11463. if (options.nodes.hasOwnProperty(prop)) {
  11464. this.constants.nodes[prop] = options.nodes[prop];
  11465. }
  11466. }
  11467. if (options.nodes.color) {
  11468. this.constants.nodes.color = Node.parseColor(options.nodes.color);
  11469. }
  11470. /*
  11471. if (options.nodes.widthMin) this.constants.nodes.radiusMin = options.nodes.widthMin;
  11472. if (options.nodes.widthMax) this.constants.nodes.radiusMax = options.nodes.widthMax;
  11473. */
  11474. }
  11475. if (options.groups) {
  11476. for (var groupname in options.groups) {
  11477. if (options.groups.hasOwnProperty(groupname)) {
  11478. var group = options.groups[groupname];
  11479. this.groups.add(groupname, group);
  11480. }
  11481. }
  11482. }
  11483. }
  11484. this.setSize(this.width, this.height);
  11485. this._setTranslation(this.frame.clientWidth / 2, this.frame.clientHeight / 2);
  11486. this._setScale(1);
  11487. };
  11488. /**
  11489. * fire an event
  11490. * @param {String} event The name of an event, for example 'select'
  11491. * @param {Object} params Optional object with event parameters
  11492. * @private
  11493. */
  11494. Graph.prototype._trigger = function (event, params) {
  11495. events.trigger(this, event, params);
  11496. };
  11497. /**
  11498. * Create the main frame for the Graph.
  11499. * This function is executed once when a Graph object is created. The frame
  11500. * contains a canvas, and this canvas contains all objects like the axis and
  11501. * nodes.
  11502. * @private
  11503. */
  11504. Graph.prototype._create = function () {
  11505. // remove all elements from the container element.
  11506. while (this.containerElement.hasChildNodes()) {
  11507. this.containerElement.removeChild(this.containerElement.firstChild);
  11508. }
  11509. this.frame = document.createElement('div');
  11510. this.frame.className = 'graph-frame';
  11511. this.frame.style.position = 'relative';
  11512. this.frame.style.overflow = 'hidden';
  11513. // create the graph canvas (HTML canvas element)
  11514. this.frame.canvas = document.createElement( 'canvas' );
  11515. this.frame.canvas.style.position = 'relative';
  11516. this.frame.appendChild(this.frame.canvas);
  11517. if (!this.frame.canvas.getContext) {
  11518. var noCanvas = document.createElement( 'DIV' );
  11519. noCanvas.style.color = 'red';
  11520. noCanvas.style.fontWeight = 'bold' ;
  11521. noCanvas.style.padding = '10px';
  11522. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  11523. this.frame.canvas.appendChild(noCanvas);
  11524. }
  11525. var me = this;
  11526. this.drag = {};
  11527. this.pinch = {};
  11528. this.hammer = Hammer(this.frame.canvas, {
  11529. prevent_default: true
  11530. });
  11531. this.hammer.on('tap', me._onTap.bind(me) );
  11532. this.hammer.on('hold', me._onHold.bind(me) );
  11533. this.hammer.on('pinch', me._onPinch.bind(me) );
  11534. this.hammer.on('touch', me._onTouch.bind(me) );
  11535. this.hammer.on('dragstart', me._onDragStart.bind(me) );
  11536. this.hammer.on('drag', me._onDrag.bind(me) );
  11537. this.hammer.on('dragend', me._onDragEnd.bind(me) );
  11538. this.hammer.on('mousewheel',me._onMouseWheel.bind(me) );
  11539. this.hammer.on('mousemove', me._onMouseMoveTitle.bind(me) );
  11540. // add the frame to the container element
  11541. this.containerElement.appendChild(this.frame);
  11542. };
  11543. /**
  11544. *
  11545. * @param {{x: Number, y: Number}} pointer
  11546. * @return {Number | null} node
  11547. * @private
  11548. */
  11549. Graph.prototype._getNodeAt = function (pointer) {
  11550. var x = this._canvasToX(pointer.x);
  11551. var y = this._canvasToY(pointer.y);
  11552. var obj = {
  11553. left: x,
  11554. top: y,
  11555. right: x,
  11556. bottom: y
  11557. };
  11558. // if there are overlapping nodes, select the last one, this is the
  11559. // one which is drawn on top of the others
  11560. var overlappingNodes = this._getNodesOverlappingWith(obj);
  11561. return (overlappingNodes.length > 0) ?
  11562. overlappingNodes[overlappingNodes.length - 1] : null;
  11563. };
  11564. /**
  11565. * Get the pointer location from a touch location
  11566. * @param {{pageX: Number, pageY: Number}} touch
  11567. * @return {{x: Number, y: Number}} pointer
  11568. * @private
  11569. */
  11570. Graph.prototype._getPointer = function (touch) {
  11571. return {
  11572. x: touch.pageX - vis.util.getAbsoluteLeft(this.frame.canvas),
  11573. y: touch.pageY - vis.util.getAbsoluteTop(this.frame.canvas)
  11574. };
  11575. };
  11576. /**
  11577. * On start of a touch gesture, store the pointer
  11578. * @param event
  11579. * @private
  11580. */
  11581. Graph.prototype._onTouch = function (event) {
  11582. this.drag.pointer = this._getPointer(event.gesture.touches[0]);
  11583. this.drag.pinched = false;
  11584. this.pinch.scale = this._getScale();
  11585. };
  11586. /**
  11587. * handle drag start event
  11588. * @private
  11589. */
  11590. Graph.prototype._onDragStart = function () {
  11591. var drag = this.drag;
  11592. drag.selection = [];
  11593. drag.translation = this._getTranslation();
  11594. drag.nodeId = this._getNodeAt(drag.pointer);
  11595. // note: drag.pointer is set in _onTouch to get the initial touch location
  11596. var node = this.nodes[drag.nodeId];
  11597. if (node) {
  11598. // select the clicked node if not yet selected
  11599. if (!node.isSelected()) {
  11600. this._selectNodes([drag.nodeId]);
  11601. }
  11602. // create an array with the selected nodes and their original location and status
  11603. var me = this;
  11604. this.selection.forEach(function (id) {
  11605. var node = me.nodes[id];
  11606. if (node) {
  11607. var s = {
  11608. id: id,
  11609. node: node,
  11610. // store original x, y, xFixed and yFixed, make the node temporarily Fixed
  11611. x: node.x,
  11612. y: node.y,
  11613. xFixed: node.xFixed,
  11614. yFixed: node.yFixed
  11615. };
  11616. node.xFixed = true;
  11617. node.yFixed = true;
  11618. drag.selection.push(s);
  11619. }
  11620. });
  11621. }
  11622. };
  11623. /**
  11624. * handle drag event
  11625. * @private
  11626. */
  11627. Graph.prototype._onDrag = function (event) {
  11628. if (this.drag.pinched) {
  11629. return;
  11630. }
  11631. var pointer = this._getPointer(event.gesture.touches[0]);
  11632. var me = this,
  11633. drag = this.drag,
  11634. selection = drag.selection;
  11635. if (selection && selection.length) {
  11636. // calculate delta's and new location
  11637. var deltaX = pointer.x - drag.pointer.x,
  11638. deltaY = pointer.y - drag.pointer.y;
  11639. // update position of all selected nodes
  11640. selection.forEach(function (s) {
  11641. var node = s.node;
  11642. if (!s.xFixed) {
  11643. node.x = me._canvasToX(me._xToCanvas(s.x) + deltaX);
  11644. }
  11645. if (!s.yFixed) {
  11646. node.y = me._canvasToY(me._yToCanvas(s.y) + deltaY);
  11647. }
  11648. });
  11649. // start animation if not yet running
  11650. if (!this.moving) {
  11651. this.moving = true;
  11652. this.start();
  11653. }
  11654. }
  11655. else {
  11656. // move the graph
  11657. var diffX = pointer.x - this.drag.pointer.x;
  11658. var diffY = pointer.y - this.drag.pointer.y;
  11659. this._setTranslation(
  11660. this.drag.translation.x + diffX,
  11661. this.drag.translation.y + diffY);
  11662. this._redraw();
  11663. this.moved = true;
  11664. }
  11665. };
  11666. /**
  11667. * handle drag start event
  11668. * @private
  11669. */
  11670. Graph.prototype._onDragEnd = function () {
  11671. var selection = this.drag.selection;
  11672. if (selection) {
  11673. selection.forEach(function (s) {
  11674. // restore original xFixed and yFixed
  11675. s.node.xFixed = s.xFixed;
  11676. s.node.yFixed = s.yFixed;
  11677. });
  11678. }
  11679. };
  11680. /**
  11681. * handle tap/click event: select/unselect a node
  11682. * @private
  11683. */
  11684. Graph.prototype._onTap = function (event) {
  11685. var pointer = this._getPointer(event.gesture.touches[0]);
  11686. var nodeId = this._getNodeAt(pointer);
  11687. var node = this.nodes[nodeId];
  11688. if (node) {
  11689. // select this node
  11690. this._selectNodes([nodeId]);
  11691. if (!this.moving) {
  11692. this._redraw();
  11693. }
  11694. }
  11695. else {
  11696. // remove selection
  11697. this._unselectNodes();
  11698. this._redraw();
  11699. }
  11700. };
  11701. /**
  11702. * handle long tap event: multi select nodes
  11703. * @private
  11704. */
  11705. Graph.prototype._onHold = function (event) {
  11706. var pointer = this._getPointer(event.gesture.touches[0]);
  11707. var nodeId = this._getNodeAt(pointer);
  11708. var node = this.nodes[nodeId];
  11709. if (node) {
  11710. if (!node.isSelected()) {
  11711. // select this node, keep previous selection
  11712. var append = true;
  11713. this._selectNodes([nodeId], append);
  11714. }
  11715. else {
  11716. this._unselectNodes([nodeId]);
  11717. }
  11718. if (!this.moving) {
  11719. this._redraw();
  11720. }
  11721. }
  11722. else {
  11723. // Do nothing
  11724. }
  11725. };
  11726. /**
  11727. * Handle pinch event
  11728. * @param event
  11729. * @private
  11730. */
  11731. Graph.prototype._onPinch = function (event) {
  11732. var pointer = this._getPointer(event.gesture.center);
  11733. this.drag.pinched = true;
  11734. if (!('scale' in this.pinch)) {
  11735. this.pinch.scale = 1;
  11736. }
  11737. // TODO: enable moving while pinching?
  11738. var scale = this.pinch.scale * event.gesture.scale;
  11739. this._zoom(scale, pointer)
  11740. };
  11741. /**
  11742. * Zoom the graph in or out
  11743. * @param {Number} scale a number around 1, and between 0.01 and 10
  11744. * @param {{x: Number, y: Number}} pointer
  11745. * @return {Number} appliedScale scale is limited within the boundaries
  11746. * @private
  11747. */
  11748. Graph.prototype._zoom = function(scale, pointer) {
  11749. var scaleOld = this._getScale();
  11750. if (scale < 0.01) {
  11751. scale = 0.01;
  11752. }
  11753. if (scale > 10) {
  11754. scale = 10;
  11755. }
  11756. var translation = this._getTranslation();
  11757. var scaleFrac = scale / scaleOld;
  11758. var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac;
  11759. var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac;
  11760. this._setScale(scale);
  11761. this._setTranslation(tx, ty);
  11762. this._redraw();
  11763. return scale;
  11764. };
  11765. /**
  11766. * Event handler for mouse wheel event, used to zoom the timeline
  11767. * See http://adomas.org/javascript-mouse-wheel/
  11768. * https://github.com/EightMedia/hammer.js/issues/256
  11769. * @param {MouseEvent} event
  11770. * @private
  11771. */
  11772. Graph.prototype._onMouseWheel = function(event) {
  11773. // retrieve delta
  11774. var delta = 0;
  11775. if (event.wheelDelta) { /* IE/Opera. */
  11776. delta = event.wheelDelta/120;
  11777. } else if (event.detail) { /* Mozilla case. */
  11778. // In Mozilla, sign of delta is different than in IE.
  11779. // Also, delta is multiple of 3.
  11780. delta = -event.detail/3;
  11781. }
  11782. // If delta is nonzero, handle it.
  11783. // Basically, delta is now positive if wheel was scrolled up,
  11784. // and negative, if wheel was scrolled down.
  11785. if (delta) {
  11786. if (!('mouswheelScale' in this.pinch)) {
  11787. this.pinch.mouswheelScale = 1;
  11788. }
  11789. // calculate the new scale
  11790. var scale = this.pinch.mouswheelScale;
  11791. var zoom = delta / 10;
  11792. if (delta < 0) {
  11793. zoom = zoom / (1 - zoom);
  11794. }
  11795. scale *= (1 + zoom);
  11796. // calculate the pointer location
  11797. var gesture = Hammer.event.collectEventData(this, 'scroll', event);
  11798. var pointer = this._getPointer(gesture.center);
  11799. // apply the new scale
  11800. scale = this._zoom(scale, pointer);
  11801. // store the new, applied scale
  11802. this.pinch.mouswheelScale = scale;
  11803. }
  11804. // Prevent default actions caused by mouse wheel.
  11805. event.preventDefault();
  11806. };
  11807. /**
  11808. * Mouse move handler for checking whether the title moves over a node with a title.
  11809. * @param {Event} event
  11810. * @private
  11811. */
  11812. Graph.prototype._onMouseMoveTitle = function (event) {
  11813. var gesture = Hammer.event.collectEventData(this, 'mousemove', event);
  11814. var pointer = this._getPointer(gesture.center);
  11815. // check if the previously selected node is still selected
  11816. if (this.popupNode) {
  11817. this._checkHidePopup(pointer);
  11818. }
  11819. // start a timeout that will check if the mouse is positioned above
  11820. // an element
  11821. var me = this;
  11822. var checkShow = function() {
  11823. me._checkShowPopup(pointer);
  11824. };
  11825. if (this.popupTimer) {
  11826. clearInterval(this.popupTimer); // stop any running timer
  11827. }
  11828. if (!this.leftButtonDown) {
  11829. this.popupTimer = setTimeout(checkShow, 300);
  11830. }
  11831. };
  11832. /**
  11833. * Check if there is an element on the given position in the graph
  11834. * (a node or edge). If so, and if this element has a title,
  11835. * show a popup window with its title.
  11836. *
  11837. * @param {{x:Number, y:Number}} pointer
  11838. * @private
  11839. */
  11840. Graph.prototype._checkShowPopup = function (pointer) {
  11841. var obj = {
  11842. left: this._canvasToX(pointer.x),
  11843. top: this._canvasToY(pointer.y),
  11844. right: this._canvasToX(pointer.x),
  11845. bottom: this._canvasToY(pointer.y)
  11846. };
  11847. var id;
  11848. var lastPopupNode = this.popupNode;
  11849. if (this.popupNode == undefined) {
  11850. // search the nodes for overlap, select the top one in case of multiple nodes
  11851. var nodes = this.nodes;
  11852. for (id in nodes) {
  11853. if (nodes.hasOwnProperty(id)) {
  11854. var node = nodes[id];
  11855. if (node.getTitle() != undefined && node.isOverlappingWith(obj)) {
  11856. this.popupNode = node;
  11857. break;
  11858. }
  11859. }
  11860. }
  11861. }
  11862. if (this.popupNode == undefined) {
  11863. // search the edges for overlap
  11864. var edges = this.edges;
  11865. for (id in edges) {
  11866. if (edges.hasOwnProperty(id)) {
  11867. var edge = edges[id];
  11868. if (edge.connected && (edge.getTitle() != undefined) &&
  11869. edge.isOverlappingWith(obj)) {
  11870. this.popupNode = edge;
  11871. break;
  11872. }
  11873. }
  11874. }
  11875. }
  11876. if (this.popupNode) {
  11877. // show popup message window
  11878. if (this.popupNode != lastPopupNode) {
  11879. var me = this;
  11880. if (!me.popup) {
  11881. me.popup = new Popup(me.frame);
  11882. }
  11883. // adjust a small offset such that the mouse cursor is located in the
  11884. // bottom left location of the popup, and you can easily move over the
  11885. // popup area
  11886. me.popup.setPosition(pointer.x - 3, pointer.y - 3);
  11887. me.popup.setText(me.popupNode.getTitle());
  11888. me.popup.show();
  11889. }
  11890. }
  11891. else {
  11892. if (this.popup) {
  11893. this.popup.hide();
  11894. }
  11895. }
  11896. };
  11897. /**
  11898. * Check if the popup must be hided, which is the case when the mouse is no
  11899. * longer hovering on the object
  11900. * @param {{x:Number, y:Number}} pointer
  11901. * @private
  11902. */
  11903. Graph.prototype._checkHidePopup = function (pointer) {
  11904. if (!this.popupNode || !this._getNodeAt(pointer) ) {
  11905. this.popupNode = undefined;
  11906. if (this.popup) {
  11907. this.popup.hide();
  11908. }
  11909. }
  11910. };
  11911. /**
  11912. * Unselect selected nodes. If no selection array is provided, all nodes
  11913. * are unselected
  11914. * @param {Object[]} selection Array with selection objects, each selection
  11915. * object has a parameter row. Optional
  11916. * @param {Boolean} triggerSelect If true (default), the select event
  11917. * is triggered when nodes are unselected
  11918. * @return {Boolean} changed True if the selection is changed
  11919. * @private
  11920. */
  11921. Graph.prototype._unselectNodes = function(selection, triggerSelect) {
  11922. var changed = false;
  11923. var i, iMax, id;
  11924. if (selection) {
  11925. // remove provided selections
  11926. for (i = 0, iMax = selection.length; i < iMax; i++) {
  11927. id = selection[i];
  11928. this.nodes[id].unselect();
  11929. var j = 0;
  11930. while (j < this.selection.length) {
  11931. if (this.selection[j] == id) {
  11932. this.selection.splice(j, 1);
  11933. changed = true;
  11934. }
  11935. else {
  11936. j++;
  11937. }
  11938. }
  11939. }
  11940. }
  11941. else if (this.selection && this.selection.length) {
  11942. // remove all selections
  11943. for (i = 0, iMax = this.selection.length; i < iMax; i++) {
  11944. id = this.selection[i];
  11945. this.nodes[id].unselect();
  11946. changed = true;
  11947. }
  11948. this.selection = [];
  11949. }
  11950. if (changed && (triggerSelect == true || triggerSelect == undefined)) {
  11951. // fire the select event
  11952. this._trigger('select');
  11953. }
  11954. return changed;
  11955. };
  11956. /**
  11957. * select all nodes on given location x, y
  11958. * @param {Array} selection an array with node ids
  11959. * @param {boolean} append If true, the new selection will be appended to the
  11960. * current selection (except for duplicate entries)
  11961. * @return {Boolean} changed True if the selection is changed
  11962. * @private
  11963. */
  11964. Graph.prototype._selectNodes = function(selection, append) {
  11965. var changed = false;
  11966. var i, iMax;
  11967. // TODO: the selectNodes method is a little messy, rework this
  11968. // check if the current selection equals the desired selection
  11969. var selectionAlreadyThere = true;
  11970. if (selection.length != this.selection.length) {
  11971. selectionAlreadyThere = false;
  11972. }
  11973. else {
  11974. for (i = 0, iMax = Math.min(selection.length, this.selection.length); i < iMax; i++) {
  11975. if (selection[i] != this.selection[i]) {
  11976. selectionAlreadyThere = false;
  11977. break;
  11978. }
  11979. }
  11980. }
  11981. if (selectionAlreadyThere) {
  11982. return changed;
  11983. }
  11984. if (append == undefined || append == false) {
  11985. // first deselect any selected node
  11986. var triggerSelect = false;
  11987. changed = this._unselectNodes(undefined, triggerSelect);
  11988. }
  11989. for (i = 0, iMax = selection.length; i < iMax; i++) {
  11990. // add each of the new selections, but only when they are not duplicate
  11991. var id = selection[i];
  11992. var isDuplicate = (this.selection.indexOf(id) != -1);
  11993. if (!isDuplicate) {
  11994. this.nodes[id].select();
  11995. this.selection.push(id);
  11996. changed = true;
  11997. }
  11998. }
  11999. if (changed) {
  12000. // fire the select event
  12001. this._trigger('select');
  12002. }
  12003. return changed;
  12004. };
  12005. /**
  12006. * retrieve all nodes overlapping with given object
  12007. * @param {Object} obj An object with parameters left, top, right, bottom
  12008. * @return {Number[]} An array with id's of the overlapping nodes
  12009. * @private
  12010. */
  12011. Graph.prototype._getNodesOverlappingWith = function (obj) {
  12012. var nodes = this.nodes,
  12013. overlappingNodes = [];
  12014. for (var id in nodes) {
  12015. if (nodes.hasOwnProperty(id)) {
  12016. if (nodes[id].isOverlappingWith(obj)) {
  12017. overlappingNodes.push(id);
  12018. }
  12019. }
  12020. }
  12021. return overlappingNodes;
  12022. };
  12023. /**
  12024. * retrieve the currently selected nodes
  12025. * @return {Number[] | String[]} selection An array with the ids of the
  12026. * selected nodes.
  12027. */
  12028. Graph.prototype.getSelection = function() {
  12029. return this.selection.concat([]);
  12030. };
  12031. /**
  12032. * select zero or more nodes
  12033. * @param {Number[] | String[]} selection An array with the ids of the
  12034. * selected nodes.
  12035. */
  12036. Graph.prototype.setSelection = function(selection) {
  12037. var i, iMax, id;
  12038. if (!selection || (selection.length == undefined))
  12039. throw 'Selection must be an array with ids';
  12040. // first unselect any selected node
  12041. for (i = 0, iMax = this.selection.length; i < iMax; i++) {
  12042. id = this.selection[i];
  12043. this.nodes[id].unselect();
  12044. }
  12045. this.selection = [];
  12046. for (i = 0, iMax = selection.length; i < iMax; i++) {
  12047. id = selection[i];
  12048. var node = this.nodes[id];
  12049. if (!node) {
  12050. throw new RangeError('Node with id "' + id + '" not found');
  12051. }
  12052. node.select();
  12053. this.selection.push(id);
  12054. }
  12055. this.redraw();
  12056. };
  12057. /**
  12058. * Validate the selection: remove ids of nodes which no longer exist
  12059. * @private
  12060. */
  12061. Graph.prototype._updateSelection = function () {
  12062. var i = 0;
  12063. while (i < this.selection.length) {
  12064. var id = this.selection[i];
  12065. if (!this.nodes[id]) {
  12066. this.selection.splice(i, 1);
  12067. }
  12068. else {
  12069. i++;
  12070. }
  12071. }
  12072. };
  12073. /**
  12074. * Temporary method to test calculating a hub value for the nodes
  12075. * @param {number} level Maximum number edges between two nodes in order
  12076. * to call them connected. Optional, 1 by default
  12077. * @return {Number[]} connectioncount array with the connection count
  12078. * for each node
  12079. * @private
  12080. */
  12081. Graph.prototype._getConnectionCount = function(level) {
  12082. if (level == undefined) {
  12083. level = 1;
  12084. }
  12085. // get the nodes connected to given nodes
  12086. function getConnectedNodes(nodes) {
  12087. var connectedNodes = [];
  12088. for (var j = 0, jMax = nodes.length; j < jMax; j++) {
  12089. var node = nodes[j];
  12090. // find all nodes connected to this node
  12091. var edges = node.edges;
  12092. for (var i = 0, iMax = edges.length; i < iMax; i++) {
  12093. var edge = edges[i];
  12094. var other = null;
  12095. // check if connected
  12096. if (edge.from == node)
  12097. other = edge.to;
  12098. else if (edge.to == node)
  12099. other = edge.from;
  12100. // check if the other node is not already in the list with nodes
  12101. var k, kMax;
  12102. if (other) {
  12103. for (k = 0, kMax = nodes.length; k < kMax; k++) {
  12104. if (nodes[k] == other) {
  12105. other = null;
  12106. break;
  12107. }
  12108. }
  12109. }
  12110. if (other) {
  12111. for (k = 0, kMax = connectedNodes.length; k < kMax; k++) {
  12112. if (connectedNodes[k] == other) {
  12113. other = null;
  12114. break;
  12115. }
  12116. }
  12117. }
  12118. if (other)
  12119. connectedNodes.push(other);
  12120. }
  12121. }
  12122. return connectedNodes;
  12123. }
  12124. var connections = [];
  12125. var nodes = this.nodes;
  12126. for (var id in nodes) {
  12127. if (nodes.hasOwnProperty(id)) {
  12128. var c = [nodes[id]];
  12129. for (var l = 0; l < level; l++) {
  12130. c = c.concat(getConnectedNodes(c));
  12131. }
  12132. connections.push(c);
  12133. }
  12134. }
  12135. var hubs = [];
  12136. for (var i = 0, len = connections.length; i < len; i++) {
  12137. hubs.push(connections[i].length);
  12138. }
  12139. return hubs;
  12140. };
  12141. /**
  12142. * Set a new size for the graph
  12143. * @param {string} width Width in pixels or percentage (for example '800px'
  12144. * or '50%')
  12145. * @param {string} height Height in pixels or percentage (for example '400px'
  12146. * or '30%')
  12147. */
  12148. Graph.prototype.setSize = function(width, height) {
  12149. this.frame.style.width = width;
  12150. this.frame.style.height = height;
  12151. this.frame.canvas.style.width = '100%';
  12152. this.frame.canvas.style.height = '100%';
  12153. this.frame.canvas.width = this.frame.canvas.clientWidth;
  12154. this.frame.canvas.height = this.frame.canvas.clientHeight;
  12155. };
  12156. /**
  12157. * Set a data set with nodes for the graph
  12158. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  12159. * @private
  12160. */
  12161. Graph.prototype._setNodes = function(nodes) {
  12162. var oldNodesData = this.nodesData;
  12163. if (nodes instanceof DataSet || nodes instanceof DataView) {
  12164. this.nodesData = nodes;
  12165. }
  12166. else if (nodes instanceof Array) {
  12167. this.nodesData = new DataSet();
  12168. this.nodesData.add(nodes);
  12169. }
  12170. else if (!nodes) {
  12171. this.nodesData = new DataSet();
  12172. }
  12173. else {
  12174. throw new TypeError('Array or DataSet expected');
  12175. }
  12176. if (oldNodesData) {
  12177. // unsubscribe from old dataset
  12178. util.forEach(this.nodesListeners, function (callback, event) {
  12179. oldNodesData.unsubscribe(event, callback);
  12180. });
  12181. }
  12182. // remove drawn nodes
  12183. this.nodes = {};
  12184. if (this.nodesData) {
  12185. // subscribe to new dataset
  12186. var me = this;
  12187. util.forEach(this.nodesListeners, function (callback, event) {
  12188. me.nodesData.subscribe(event, callback);
  12189. });
  12190. // draw all new nodes
  12191. var ids = this.nodesData.getIds();
  12192. this._addNodes(ids);
  12193. }
  12194. this._updateSelection();
  12195. };
  12196. /**
  12197. * Add nodes
  12198. * @param {Number[] | String[]} ids
  12199. * @private
  12200. */
  12201. Graph.prototype._addNodes = function(ids) {
  12202. var id;
  12203. for (var i = 0, len = ids.length; i < len; i++) {
  12204. id = ids[i];
  12205. var data = this.nodesData.get(id);
  12206. var node = new Node(data, this.images, this.groups, this.constants);
  12207. this.nodes[id] = node; // note: this may replace an existing node
  12208. if (!node.isFixed()) {
  12209. // TODO: position new nodes in a smarter way!
  12210. var radius = this.constants.edges.length * 2;
  12211. var count = ids.length;
  12212. var angle = 2 * Math.PI * (i / count);
  12213. node.x = radius * Math.cos(angle);
  12214. node.y = radius * Math.sin(angle);
  12215. // note: no not use node.isMoving() here, as that gives the current
  12216. // velocity of the node, which is zero after creation of the node.
  12217. this.moving = true;
  12218. }
  12219. }
  12220. this._reconnectEdges();
  12221. this._updateValueRange(this.nodes);
  12222. };
  12223. /**
  12224. * Update existing nodes, or create them when not yet existing
  12225. * @param {Number[] | String[]} ids
  12226. * @private
  12227. */
  12228. Graph.prototype._updateNodes = function(ids) {
  12229. var nodes = this.nodes,
  12230. nodesData = this.nodesData;
  12231. for (var i = 0, len = ids.length; i < len; i++) {
  12232. var id = ids[i];
  12233. var node = nodes[id];
  12234. var data = nodesData.get(id);
  12235. if (node) {
  12236. // update node
  12237. node.setProperties(data, this.constants);
  12238. }
  12239. else {
  12240. // create node
  12241. node = new Node(properties, this.images, this.groups, this.constants);
  12242. nodes[id] = node;
  12243. if (!node.isFixed()) {
  12244. this.moving = true;
  12245. }
  12246. }
  12247. }
  12248. this._reconnectEdges();
  12249. this._updateValueRange(nodes);
  12250. };
  12251. /**
  12252. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  12253. * @param {Number[] | String[]} ids
  12254. * @private
  12255. */
  12256. Graph.prototype._removeNodes = function(ids) {
  12257. var nodes = this.nodes;
  12258. for (var i = 0, len = ids.length; i < len; i++) {
  12259. var id = ids[i];
  12260. delete nodes[id];
  12261. }
  12262. this._reconnectEdges();
  12263. this._updateSelection();
  12264. this._updateValueRange(nodes);
  12265. };
  12266. /**
  12267. * Load edges by reading the data table
  12268. * @param {Array | DataSet | DataView} edges The data containing the edges.
  12269. * @private
  12270. * @private
  12271. */
  12272. Graph.prototype._setEdges = function(edges) {
  12273. var oldEdgesData = this.edgesData;
  12274. if (edges instanceof DataSet || edges instanceof DataView) {
  12275. this.edgesData = edges;
  12276. }
  12277. else if (edges instanceof Array) {
  12278. this.edgesData = new DataSet();
  12279. this.edgesData.add(edges);
  12280. }
  12281. else if (!edges) {
  12282. this.edgesData = new DataSet();
  12283. }
  12284. else {
  12285. throw new TypeError('Array or DataSet expected');
  12286. }
  12287. if (oldEdgesData) {
  12288. // unsubscribe from old dataset
  12289. util.forEach(this.edgesListeners, function (callback, event) {
  12290. oldEdgesData.unsubscribe(event, callback);
  12291. });
  12292. }
  12293. // remove drawn edges
  12294. this.edges = {};
  12295. if (this.edgesData) {
  12296. // subscribe to new dataset
  12297. var me = this;
  12298. util.forEach(this.edgesListeners, function (callback, event) {
  12299. me.edgesData.subscribe(event, callback);
  12300. });
  12301. // draw all new nodes
  12302. var ids = this.edgesData.getIds();
  12303. this._addEdges(ids);
  12304. }
  12305. this._reconnectEdges();
  12306. };
  12307. /**
  12308. * Add edges
  12309. * @param {Number[] | String[]} ids
  12310. * @private
  12311. */
  12312. Graph.prototype._addEdges = function (ids) {
  12313. var edges = this.edges,
  12314. edgesData = this.edgesData;
  12315. for (var i = 0, len = ids.length; i < len; i++) {
  12316. var id = ids[i];
  12317. var oldEdge = edges[id];
  12318. if (oldEdge) {
  12319. oldEdge.disconnect();
  12320. }
  12321. var data = edgesData.get(id);
  12322. edges[id] = new Edge(data, this, this.constants);
  12323. }
  12324. this.moving = true;
  12325. this._updateValueRange(edges);
  12326. };
  12327. /**
  12328. * Update existing edges, or create them when not yet existing
  12329. * @param {Number[] | String[]} ids
  12330. * @private
  12331. */
  12332. Graph.prototype._updateEdges = function (ids) {
  12333. var edges = this.edges,
  12334. edgesData = this.edgesData;
  12335. for (var i = 0, len = ids.length; i < len; i++) {
  12336. var id = ids[i];
  12337. var data = edgesData.get(id);
  12338. var edge = edges[id];
  12339. if (edge) {
  12340. // update edge
  12341. edge.disconnect();
  12342. edge.setProperties(data, this.constants);
  12343. edge.connect();
  12344. }
  12345. else {
  12346. // create edge
  12347. edge = new Edge(data, this, this.constants);
  12348. this.edges[id] = edge;
  12349. }
  12350. }
  12351. this.moving = true;
  12352. this._updateValueRange(edges);
  12353. };
  12354. /**
  12355. * Remove existing edges. Non existing ids will be ignored
  12356. * @param {Number[] | String[]} ids
  12357. * @private
  12358. */
  12359. Graph.prototype._removeEdges = function (ids) {
  12360. var edges = this.edges;
  12361. for (var i = 0, len = ids.length; i < len; i++) {
  12362. var id = ids[i];
  12363. var edge = edges[id];
  12364. if (edge) {
  12365. edge.disconnect();
  12366. delete edges[id];
  12367. }
  12368. }
  12369. this.moving = true;
  12370. this._updateValueRange(edges);
  12371. };
  12372. /**
  12373. * Reconnect all edges
  12374. * @private
  12375. */
  12376. Graph.prototype._reconnectEdges = function() {
  12377. var id,
  12378. nodes = this.nodes,
  12379. edges = this.edges;
  12380. for (id in nodes) {
  12381. if (nodes.hasOwnProperty(id)) {
  12382. nodes[id].edges = [];
  12383. }
  12384. }
  12385. for (id in edges) {
  12386. if (edges.hasOwnProperty(id)) {
  12387. var edge = edges[id];
  12388. edge.from = null;
  12389. edge.to = null;
  12390. edge.connect();
  12391. }
  12392. }
  12393. };
  12394. /**
  12395. * Update the values of all object in the given array according to the current
  12396. * value range of the objects in the array.
  12397. * @param {Object} obj An object containing a set of Edges or Nodes
  12398. * The objects must have a method getValue() and
  12399. * setValueRange(min, max).
  12400. * @private
  12401. */
  12402. Graph.prototype._updateValueRange = function(obj) {
  12403. var id;
  12404. // determine the range of the objects
  12405. var valueMin = undefined;
  12406. var valueMax = undefined;
  12407. for (id in obj) {
  12408. if (obj.hasOwnProperty(id)) {
  12409. var value = obj[id].getValue();
  12410. if (value !== undefined) {
  12411. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  12412. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  12413. }
  12414. }
  12415. }
  12416. // adjust the range of all objects
  12417. if (valueMin !== undefined && valueMax !== undefined) {
  12418. for (id in obj) {
  12419. if (obj.hasOwnProperty(id)) {
  12420. obj[id].setValueRange(valueMin, valueMax);
  12421. }
  12422. }
  12423. }
  12424. };
  12425. /**
  12426. * Redraw the graph with the current data
  12427. * chart will be resized too.
  12428. */
  12429. Graph.prototype.redraw = function() {
  12430. this.setSize(this.width, this.height);
  12431. this._redraw();
  12432. };
  12433. /**
  12434. * Redraw the graph with the current data
  12435. * @private
  12436. */
  12437. Graph.prototype._redraw = function() {
  12438. var ctx = this.frame.canvas.getContext('2d');
  12439. // clear the canvas
  12440. var w = this.frame.canvas.width;
  12441. var h = this.frame.canvas.height;
  12442. ctx.clearRect(0, 0, w, h);
  12443. // set scaling and translation
  12444. ctx.save();
  12445. ctx.translate(this.translation.x, this.translation.y);
  12446. ctx.scale(this.scale, this.scale);
  12447. this._drawEdges(ctx);
  12448. this._drawNodes(ctx);
  12449. // restore original scaling and translation
  12450. ctx.restore();
  12451. };
  12452. /**
  12453. * Set the translation of the graph
  12454. * @param {Number} offsetX Horizontal offset
  12455. * @param {Number} offsetY Vertical offset
  12456. * @private
  12457. */
  12458. Graph.prototype._setTranslation = function(offsetX, offsetY) {
  12459. if (this.translation === undefined) {
  12460. this.translation = {
  12461. x: 0,
  12462. y: 0
  12463. };
  12464. }
  12465. if (offsetX !== undefined) {
  12466. this.translation.x = offsetX;
  12467. }
  12468. if (offsetY !== undefined) {
  12469. this.translation.y = offsetY;
  12470. }
  12471. };
  12472. /**
  12473. * Get the translation of the graph
  12474. * @return {Object} translation An object with parameters x and y, both a number
  12475. * @private
  12476. */
  12477. Graph.prototype._getTranslation = function() {
  12478. return {
  12479. x: this.translation.x,
  12480. y: this.translation.y
  12481. };
  12482. };
  12483. /**
  12484. * Scale the graph
  12485. * @param {Number} scale Scaling factor 1.0 is unscaled
  12486. * @private
  12487. */
  12488. Graph.prototype._setScale = function(scale) {
  12489. this.scale = scale;
  12490. };
  12491. /**
  12492. * Get the current scale of the graph
  12493. * @return {Number} scale Scaling factor 1.0 is unscaled
  12494. * @private
  12495. */
  12496. Graph.prototype._getScale = function() {
  12497. return this.scale;
  12498. };
  12499. /**
  12500. * Convert a horizontal point on the HTML canvas to the x-value of the model
  12501. * @param {number} x
  12502. * @returns {number}
  12503. * @private
  12504. */
  12505. Graph.prototype._canvasToX = function(x) {
  12506. return (x - this.translation.x) / this.scale;
  12507. };
  12508. /**
  12509. * Convert an x-value in the model to a horizontal point on the HTML canvas
  12510. * @param {number} x
  12511. * @returns {number}
  12512. * @private
  12513. */
  12514. Graph.prototype._xToCanvas = function(x) {
  12515. return x * this.scale + this.translation.x;
  12516. };
  12517. /**
  12518. * Convert a vertical point on the HTML canvas to the y-value of the model
  12519. * @param {number} y
  12520. * @returns {number}
  12521. * @private
  12522. */
  12523. Graph.prototype._canvasToY = function(y) {
  12524. return (y - this.translation.y) / this.scale;
  12525. };
  12526. /**
  12527. * Convert an y-value in the model to a vertical point on the HTML canvas
  12528. * @param {number} y
  12529. * @returns {number}
  12530. * @private
  12531. */
  12532. Graph.prototype._yToCanvas = function(y) {
  12533. return y * this.scale + this.translation.y ;
  12534. };
  12535. /**
  12536. * Redraw all nodes
  12537. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  12538. * @param {CanvasRenderingContext2D} ctx
  12539. * @private
  12540. */
  12541. Graph.prototype._drawNodes = function(ctx) {
  12542. // first draw the unselected nodes
  12543. var nodes = this.nodes;
  12544. var selected = [];
  12545. for (var id in nodes) {
  12546. if (nodes.hasOwnProperty(id)) {
  12547. if (nodes[id].isSelected()) {
  12548. selected.push(id);
  12549. }
  12550. else {
  12551. nodes[id].draw(ctx);
  12552. }
  12553. }
  12554. }
  12555. // draw the selected nodes on top
  12556. for (var s = 0, sMax = selected.length; s < sMax; s++) {
  12557. nodes[selected[s]].draw(ctx);
  12558. }
  12559. };
  12560. /**
  12561. * Redraw all edges
  12562. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  12563. * @param {CanvasRenderingContext2D} ctx
  12564. * @private
  12565. */
  12566. Graph.prototype._drawEdges = function(ctx) {
  12567. var edges = this.edges;
  12568. for (var id in edges) {
  12569. if (edges.hasOwnProperty(id)) {
  12570. var edge = edges[id];
  12571. if (edge.connected) {
  12572. edges[id].draw(ctx);
  12573. }
  12574. }
  12575. }
  12576. };
  12577. /**
  12578. * Find a stable position for all nodes
  12579. * @private
  12580. */
  12581. Graph.prototype._doStabilize = function() {
  12582. var start = new Date();
  12583. // find stable position
  12584. var count = 0;
  12585. var vmin = this.constants.minVelocity;
  12586. var stable = false;
  12587. while (!stable && count < this.constants.maxIterations) {
  12588. this._calculateForces();
  12589. this._discreteStepNodes();
  12590. stable = !this._isMoving(vmin);
  12591. count++;
  12592. }
  12593. var end = new Date();
  12594. // console.log('Stabilized in ' + (end-start) + ' ms, ' + count + ' iterations' ); // TODO: cleanup
  12595. };
  12596. /**
  12597. * Calculate the external forces acting on the nodes
  12598. * Forces are caused by: edges, repulsing forces between nodes, gravity
  12599. * @private
  12600. */
  12601. Graph.prototype._calculateForces = function() {
  12602. // create a local edge to the nodes and edges, that is faster
  12603. var id, dx, dy, angle, distance, fx, fy,
  12604. repulsingForce, springForce, length, edgeLength,
  12605. nodes = this.nodes,
  12606. edges = this.edges;
  12607. // gravity, add a small constant force to pull the nodes towards the center of
  12608. // the graph
  12609. // Also, the forces are reset to zero in this loop by using _setForce instead
  12610. // of _addForce
  12611. var gravity = 0.01,
  12612. gx = this.frame.canvas.clientWidth / 2,
  12613. gy = this.frame.canvas.clientHeight / 2;
  12614. for (id in nodes) {
  12615. if (nodes.hasOwnProperty(id)) {
  12616. var node = nodes[id];
  12617. dx = gx - node.x;
  12618. dy = gy - node.y;
  12619. angle = Math.atan2(dy, dx);
  12620. fx = Math.cos(angle) * gravity;
  12621. fy = Math.sin(angle) * gravity;
  12622. node._setForce(fx, fy);
  12623. }
  12624. }
  12625. // repulsing forces between nodes
  12626. var minimumDistance = this.constants.nodes.distance,
  12627. steepness = 10; // higher value gives steeper slope of the force around the given minimumDistance
  12628. for (var id1 in nodes) {
  12629. if (nodes.hasOwnProperty(id1)) {
  12630. var node1 = nodes[id1];
  12631. for (var id2 in nodes) {
  12632. if (nodes.hasOwnProperty(id2)) {
  12633. var node2 = nodes[id2];
  12634. // calculate normally distributed force
  12635. dx = node2.x - node1.x;
  12636. dy = node2.y - node1.y;
  12637. distance = Math.sqrt(dx * dx + dy * dy);
  12638. angle = Math.atan2(dy, dx);
  12639. // TODO: correct factor for repulsing force
  12640. //repulsingForce = 2 * Math.exp(-5 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  12641. //repulsingForce = Math.exp(-1 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  12642. repulsingForce = 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness)); // TODO: customize the repulsing force
  12643. fx = Math.cos(angle) * repulsingForce;
  12644. fy = Math.sin(angle) * repulsingForce;
  12645. node1._addForce(-fx, -fy);
  12646. node2._addForce(fx, fy);
  12647. }
  12648. }
  12649. }
  12650. }
  12651. /* TODO: re-implement repulsion of edges
  12652. for (var n = 0; n < nodes.length; n++) {
  12653. for (var l = 0; l < edges.length; l++) {
  12654. var lx = edges[l].from.x+(edges[l].to.x - edges[l].from.x)/2,
  12655. ly = edges[l].from.y+(edges[l].to.y - edges[l].from.y)/2,
  12656. // calculate normally distributed force
  12657. dx = nodes[n].x - lx,
  12658. dy = nodes[n].y - ly,
  12659. distance = Math.sqrt(dx * dx + dy * dy),
  12660. angle = Math.atan2(dy, dx),
  12661. // TODO: correct factor for repulsing force
  12662. //var repulsingforce = 2 * Math.exp(-5 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  12663. //repulsingforce = Math.exp(-1 * (distance * distance) / (dmin * dmin) ), // TODO: customize the repulsing force
  12664. repulsingforce = 1 / (1 + Math.exp((distance / (minimumDistance / 2) - 1) * steepness)), // TODO: customize the repulsing force
  12665. fx = Math.cos(angle) * repulsingforce,
  12666. fy = Math.sin(angle) * repulsingforce;
  12667. nodes[n]._addForce(fx, fy);
  12668. edges[l].from._addForce(-fx/2,-fy/2);
  12669. edges[l].to._addForce(-fx/2,-fy/2);
  12670. }
  12671. }
  12672. */
  12673. // forces caused by the edges, modelled as springs
  12674. for (id in edges) {
  12675. if (edges.hasOwnProperty(id)) {
  12676. var edge = edges[id];
  12677. if (edge.connected) {
  12678. dx = (edge.to.x - edge.from.x);
  12679. dy = (edge.to.y - edge.from.y);
  12680. //edgeLength = (edge.from.width + edge.from.height + edge.to.width + edge.to.height)/2 || edge.length; // TODO: dmin
  12681. //edgeLength = (edge.from.width + edge.to.width)/2 || edge.length; // TODO: dmin
  12682. //edgeLength = 20 + ((edge.from.width + edge.to.width) || 0) / 2;
  12683. edgeLength = edge.length;
  12684. length = Math.sqrt(dx * dx + dy * dy);
  12685. angle = Math.atan2(dy, dx);
  12686. springForce = edge.stiffness * (edgeLength - length);
  12687. fx = Math.cos(angle) * springForce;
  12688. fy = Math.sin(angle) * springForce;
  12689. edge.from._addForce(-fx, -fy);
  12690. edge.to._addForce(fx, fy);
  12691. }
  12692. }
  12693. }
  12694. /* TODO: re-implement repulsion of edges
  12695. // repulsing forces between edges
  12696. var minimumDistance = this.constants.edges.distance,
  12697. steepness = 10; // higher value gives steeper slope of the force around the given minimumDistance
  12698. for (var l = 0; l < edges.length; l++) {
  12699. //Keep distance from other edge centers
  12700. for (var l2 = l + 1; l2 < this.edges.length; l2++) {
  12701. //var dmin = (nodes[n].width + nodes[n].height + nodes[n2].width + nodes[n2].height) / 1 || minimumDistance, // TODO: dmin
  12702. //var dmin = (nodes[n].width + nodes[n2].width)/2 || minimumDistance, // TODO: dmin
  12703. //dmin = 40 + ((nodes[n].width/2 + nodes[n2].width/2) || 0),
  12704. var lx = edges[l].from.x+(edges[l].to.x - edges[l].from.x)/2,
  12705. ly = edges[l].from.y+(edges[l].to.y - edges[l].from.y)/2,
  12706. l2x = edges[l2].from.x+(edges[l2].to.x - edges[l2].from.x)/2,
  12707. l2y = edges[l2].from.y+(edges[l2].to.y - edges[l2].from.y)/2,
  12708. // calculate normally distributed force
  12709. dx = l2x - lx,
  12710. dy = l2y - ly,
  12711. distance = Math.sqrt(dx * dx + dy * dy),
  12712. angle = Math.atan2(dy, dx),
  12713. // TODO: correct factor for repulsing force
  12714. //var repulsingforce = 2 * Math.exp(-5 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  12715. //repulsingforce = Math.exp(-1 * (distance * distance) / (dmin * dmin) ), // TODO: customize the repulsing force
  12716. repulsingforce = 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness)), // TODO: customize the repulsing force
  12717. fx = Math.cos(angle) * repulsingforce,
  12718. fy = Math.sin(angle) * repulsingforce;
  12719. edges[l].from._addForce(-fx, -fy);
  12720. edges[l].to._addForce(-fx, -fy);
  12721. edges[l2].from._addForce(fx, fy);
  12722. edges[l2].to._addForce(fx, fy);
  12723. }
  12724. }
  12725. */
  12726. };
  12727. /**
  12728. * Check if any of the nodes is still moving
  12729. * @param {number} vmin the minimum velocity considered as 'moving'
  12730. * @return {boolean} true if moving, false if non of the nodes is moving
  12731. * @private
  12732. */
  12733. Graph.prototype._isMoving = function(vmin) {
  12734. // TODO: ismoving does not work well: should check the kinetic energy, not its velocity
  12735. var nodes = this.nodes;
  12736. for (var id in nodes) {
  12737. if (nodes.hasOwnProperty(id) && nodes[id].isMoving(vmin)) {
  12738. return true;
  12739. }
  12740. }
  12741. return false;
  12742. };
  12743. /**
  12744. * Perform one discrete step for all nodes
  12745. * @private
  12746. */
  12747. Graph.prototype._discreteStepNodes = function() {
  12748. var interval = this.refreshRate / 1000.0; // in seconds
  12749. var nodes = this.nodes;
  12750. for (var id in nodes) {
  12751. if (nodes.hasOwnProperty(id)) {
  12752. nodes[id].discreteStep(interval);
  12753. }
  12754. }
  12755. };
  12756. /**
  12757. * Start animating nodes and edges
  12758. */
  12759. Graph.prototype.start = function() {
  12760. if (this.moving) {
  12761. this._calculateForces();
  12762. this._discreteStepNodes();
  12763. var vmin = this.constants.minVelocity;
  12764. this.moving = this._isMoving(vmin);
  12765. }
  12766. if (this.moving) {
  12767. // start animation. only start timer if it is not already running
  12768. if (!this.timer) {
  12769. var graph = this;
  12770. this.timer = window.setTimeout(function () {
  12771. graph.timer = undefined;
  12772. graph.start();
  12773. graph._redraw();
  12774. }, this.refreshRate);
  12775. }
  12776. }
  12777. else {
  12778. this._redraw();
  12779. }
  12780. };
  12781. /**
  12782. * Stop animating nodes and edges.
  12783. */
  12784. Graph.prototype.stop = function () {
  12785. if (this.timer) {
  12786. window.clearInterval(this.timer);
  12787. this.timer = undefined;
  12788. }
  12789. };
  12790. /**
  12791. * vis.js module exports
  12792. */
  12793. var vis = {
  12794. util: util,
  12795. events: events,
  12796. Controller: Controller,
  12797. DataSet: DataSet,
  12798. DataView: DataView,
  12799. Range: Range,
  12800. Stack: Stack,
  12801. TimeStep: TimeStep,
  12802. EventBus: EventBus,
  12803. components: {
  12804. items: {
  12805. Item: Item,
  12806. ItemBox: ItemBox,
  12807. ItemPoint: ItemPoint,
  12808. ItemRange: ItemRange
  12809. },
  12810. Component: Component,
  12811. Panel: Panel,
  12812. RootPanel: RootPanel,
  12813. ItemSet: ItemSet,
  12814. TimeAxis: TimeAxis
  12815. },
  12816. graph: {
  12817. Node: Node,
  12818. Edge: Edge,
  12819. Popup: Popup,
  12820. Groups: Groups,
  12821. Images: Images
  12822. },
  12823. Timeline: Timeline,
  12824. Graph: Graph
  12825. };
  12826. /**
  12827. * CommonJS module exports
  12828. */
  12829. if (typeof exports !== 'undefined') {
  12830. exports = vis;
  12831. }
  12832. if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  12833. module.exports = vis;
  12834. }
  12835. /**
  12836. * AMD module exports
  12837. */
  12838. if (typeof(define) === 'function') {
  12839. define(function () {
  12840. return vis;
  12841. });
  12842. }
  12843. /**
  12844. * Window exports
  12845. */
  12846. if (typeof window !== 'undefined') {
  12847. // attach the module to the window, load as a regular javascript file
  12848. window['vis'] = vis;
  12849. }
  12850. // inject css
  12851. util.loadCss("/* vis.js stylesheet */\n.vis.timeline {\n}\n\n\n.vis.timeline.rootpanel {\n position: relative;\n overflow: hidden;\n\n border: 1px solid #bfbfbf;\n -moz-box-sizing: border-box;\n box-sizing: border-box;\n}\n\n.vis.timeline .panel {\n position: absolute;\n overflow: hidden;\n}\n\n\n.vis.timeline .groupset {\n position: absolute;\n padding: 0;\n margin: 0;\n}\n\n.vis.timeline .labels {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n\n padding: 0;\n margin: 0;\n\n border-right: 1px solid #bfbfbf;\n box-sizing: border-box;\n -moz-box-sizing: border-box;\n}\n\n.vis.timeline .labels .label {\n position: absolute;\n left: 0;\n top: 0;\n width: 100%;\n border-bottom: 1px solid #bfbfbf;\n color: #4d4d4d;\n}\n\n.vis.timeline .labels .label .inner {\n display: inline-block;\n padding: 5px;\n}\n\n\n.vis.timeline .itemset {\n position: absolute;\n padding: 0;\n margin: 0;\n overflow: hidden;\n}\n\n.vis.timeline .background {\n}\n\n.vis.timeline .foreground {\n}\n\n.vis.timeline .itemset-axis {\n position: absolute;\n}\n\n.vis.timeline .groupset .itemset-axis {\n border-top: 1px solid #bfbfbf;\n}\n\n/* TODO: with orientation=='bottom', this will more or less overlap with timeline axis\n.vis.timeline .groupset .itemset-axis:last-child {\n border-top: none;\n}\n*/\n\n\n.vis.timeline .item {\n position: absolute;\n color: #1A1A1A;\n border-color: #97B0F8;\n background-color: #D5DDF6;\n display: inline-block;\n}\n\n.vis.timeline .item.selected {\n border-color: #FFC200;\n background-color: #FFF785;\n z-index: 999;\n}\n\n.vis.timeline .item.cluster {\n /* TODO: use another color or pattern? */\n background: #97B0F8 url('img/cluster_bg.png');\n color: white;\n}\n.vis.timeline .item.cluster.point {\n border-color: #D5DDF6;\n}\n\n.vis.timeline .item.box {\n text-align: center;\n border-style: solid;\n border-width: 1px;\n border-radius: 5px;\n -moz-border-radius: 5px; /* For Firefox 3.6 and older */\n}\n\n.vis.timeline .item.point {\n background: none;\n}\n\n.vis.timeline .dot {\n border: 5px solid #97B0F8;\n position: absolute;\n border-radius: 5px;\n -moz-border-radius: 5px; /* For Firefox 3.6 and older */\n}\n\n.vis.timeline .item.range {\n overflow: hidden;\n border-style: solid;\n border-width: 1px;\n border-radius: 2px;\n -moz-border-radius: 2px; /* For Firefox 3.6 and older */\n}\n\n.vis.timeline .item.range .drag-left {\n cursor: w-resize;\n z-index: 1000;\n}\n\n.vis.timeline .item.range .drag-right {\n cursor: e-resize;\n z-index: 1000;\n}\n\n.vis.timeline .item.range .content {\n position: relative;\n display: inline-block;\n}\n\n.vis.timeline .item.line {\n position: absolute;\n width: 0;\n border-left-width: 1px;\n border-left-style: solid;\n}\n\n.vis.timeline .item .content {\n margin: 5px;\n white-space: nowrap;\n overflow: hidden;\n}\n\n.vis.timeline .axis {\n position: relative;\n}\n\n.vis.timeline .axis .text {\n position: absolute;\n color: #4d4d4d;\n padding: 3px;\n white-space: nowrap;\n}\n\n.vis.timeline .axis .text.measure {\n position: absolute;\n padding-left: 0;\n padding-right: 0;\n margin-left: 0;\n margin-right: 0;\n visibility: hidden;\n}\n\n.vis.timeline .axis .grid.vertical {\n position: absolute;\n width: 0;\n border-right: 1px solid;\n}\n\n.vis.timeline .axis .grid.horizontal {\n position: absolute;\n left: 0;\n width: 100%;\n height: 0;\n border-bottom: 1px solid;\n}\n\n.vis.timeline .axis .grid.minor {\n border-color: #e5e5e5;\n}\n\n.vis.timeline .axis .grid.major {\n border-color: #bfbfbf;\n}\n\n");
  12852. },{"hammerjs":1,"moment":2}]},{},[3])
  12853. (3)
  12854. });
  12855. ;