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.

15193 lines
426 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
  1. /**
  2. * vis.js
  3. * https://github.com/almende/vis
  4. *
  5. * A dynamic, browser-based visualization library.
  6. *
  7. * @version 0.3.0-SNAPSHOT
  8. * @date 2014-01-03
  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;
  2773. if (typeof window !== 'undefined') {
  2774. // load hammer.js only when running in a browser (where window is available)
  2775. Hammer = window['Hammer'] || require('hammerjs');
  2776. }
  2777. else {
  2778. Hammer = function () {
  2779. throw Error('hammer.js is only available in a browser, not in node.js.');
  2780. }
  2781. }
  2782. // Internet Explorer 8 and older does not support Array.indexOf, so we define
  2783. // it here in that case.
  2784. // http://soledadpenades.com/2007/05/17/arrayindexof-in-internet-explorer/
  2785. if(!Array.prototype.indexOf) {
  2786. Array.prototype.indexOf = function(obj){
  2787. for(var i = 0; i < this.length; i++){
  2788. if(this[i] == obj){
  2789. return i;
  2790. }
  2791. }
  2792. return -1;
  2793. };
  2794. try {
  2795. console.log("Warning: Ancient browser detected. Please update your browser");
  2796. }
  2797. catch (err) {
  2798. }
  2799. }
  2800. // Internet Explorer 8 and older does not support Array.forEach, so we define
  2801. // it here in that case.
  2802. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach
  2803. if (!Array.prototype.forEach) {
  2804. Array.prototype.forEach = function(fn, scope) {
  2805. for(var i = 0, len = this.length; i < len; ++i) {
  2806. fn.call(scope || this, this[i], i, this);
  2807. }
  2808. }
  2809. }
  2810. // Internet Explorer 8 and older does not support Array.map, so we define it
  2811. // here in that case.
  2812. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map
  2813. // Production steps of ECMA-262, Edition 5, 15.4.4.19
  2814. // Reference: http://es5.github.com/#x15.4.4.19
  2815. if (!Array.prototype.map) {
  2816. Array.prototype.map = function(callback, thisArg) {
  2817. var T, A, k;
  2818. if (this == null) {
  2819. throw new TypeError(" this is null or not defined");
  2820. }
  2821. // 1. Let O be the result of calling ToObject passing the |this| value as the argument.
  2822. var O = Object(this);
  2823. // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
  2824. // 3. Let len be ToUint32(lenValue).
  2825. var len = O.length >>> 0;
  2826. // 4. If IsCallable(callback) is false, throw a TypeError exception.
  2827. // See: http://es5.github.com/#x9.11
  2828. if (typeof callback !== "function") {
  2829. throw new TypeError(callback + " is not a function");
  2830. }
  2831. // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
  2832. if (thisArg) {
  2833. T = thisArg;
  2834. }
  2835. // 6. Let A be a new array created as if by the expression new Array(len) where Array is
  2836. // the standard built-in constructor with that name and len is the value of len.
  2837. A = new Array(len);
  2838. // 7. Let k be 0
  2839. k = 0;
  2840. // 8. Repeat, while k < len
  2841. while(k < len) {
  2842. var kValue, mappedValue;
  2843. // a. Let Pk be ToString(k).
  2844. // This is implicit for LHS operands of the in operator
  2845. // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
  2846. // This step can be combined with c
  2847. // c. If kPresent is true, then
  2848. if (k in O) {
  2849. // i. Let kValue be the result of calling the Get internal method of O with argument Pk.
  2850. kValue = O[ k ];
  2851. // ii. Let mappedValue be the result of calling the Call internal method of callback
  2852. // with T as the this value and argument list containing kValue, k, and O.
  2853. mappedValue = callback.call(T, kValue, k, O);
  2854. // iii. Call the DefineOwnProperty internal method of A with arguments
  2855. // Pk, Property Descriptor {Value: mappedValue, : true, Enumerable: true, Configurable: true},
  2856. // and false.
  2857. // In browsers that support Object.defineProperty, use the following:
  2858. // Object.defineProperty(A, Pk, { value: mappedValue, writable: true, enumerable: true, configurable: true });
  2859. // For best browser support, use the following:
  2860. A[ k ] = mappedValue;
  2861. }
  2862. // d. Increase k by 1.
  2863. k++;
  2864. }
  2865. // 9. return A
  2866. return A;
  2867. };
  2868. }
  2869. // Internet Explorer 8 and older does not support Array.filter, so we define it
  2870. // here in that case.
  2871. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter
  2872. if (!Array.prototype.filter) {
  2873. Array.prototype.filter = function(fun /*, thisp */) {
  2874. "use strict";
  2875. if (this == null) {
  2876. throw new TypeError();
  2877. }
  2878. var t = Object(this);
  2879. var len = t.length >>> 0;
  2880. if (typeof fun != "function") {
  2881. throw new TypeError();
  2882. }
  2883. var res = [];
  2884. var thisp = arguments[1];
  2885. for (var i = 0; i < len; i++) {
  2886. if (i in t) {
  2887. var val = t[i]; // in case fun mutates this
  2888. if (fun.call(thisp, val, i, t))
  2889. res.push(val);
  2890. }
  2891. }
  2892. return res;
  2893. };
  2894. }
  2895. // Internet Explorer 8 and older does not support Object.keys, so we define it
  2896. // here in that case.
  2897. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/keys
  2898. if (!Object.keys) {
  2899. Object.keys = (function () {
  2900. var hasOwnProperty = Object.prototype.hasOwnProperty,
  2901. hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
  2902. dontEnums = [
  2903. 'toString',
  2904. 'toLocaleString',
  2905. 'valueOf',
  2906. 'hasOwnProperty',
  2907. 'isPrototypeOf',
  2908. 'propertyIsEnumerable',
  2909. 'constructor'
  2910. ],
  2911. dontEnumsLength = dontEnums.length;
  2912. return function (obj) {
  2913. if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) {
  2914. throw new TypeError('Object.keys called on non-object');
  2915. }
  2916. var result = [];
  2917. for (var prop in obj) {
  2918. if (hasOwnProperty.call(obj, prop)) result.push(prop);
  2919. }
  2920. if (hasDontEnumBug) {
  2921. for (var i=0; i < dontEnumsLength; i++) {
  2922. if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
  2923. }
  2924. }
  2925. return result;
  2926. }
  2927. })()
  2928. }
  2929. // Internet Explorer 8 and older does not support Array.isArray,
  2930. // so we define it here in that case.
  2931. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/isArray
  2932. if(!Array.isArray) {
  2933. Array.isArray = function (vArg) {
  2934. return Object.prototype.toString.call(vArg) === "[object Array]";
  2935. };
  2936. }
  2937. // Internet Explorer 8 and older does not support Function.bind,
  2938. // so we define it here in that case.
  2939. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind
  2940. if (!Function.prototype.bind) {
  2941. Function.prototype.bind = function (oThis) {
  2942. if (typeof this !== "function") {
  2943. // closest thing possible to the ECMAScript 5 internal IsCallable function
  2944. throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
  2945. }
  2946. var aArgs = Array.prototype.slice.call(arguments, 1),
  2947. fToBind = this,
  2948. fNOP = function () {},
  2949. fBound = function () {
  2950. return fToBind.apply(this instanceof fNOP && oThis
  2951. ? this
  2952. : oThis,
  2953. aArgs.concat(Array.prototype.slice.call(arguments)));
  2954. };
  2955. fNOP.prototype = this.prototype;
  2956. fBound.prototype = new fNOP();
  2957. return fBound;
  2958. };
  2959. }
  2960. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create
  2961. if (!Object.create) {
  2962. Object.create = function (o) {
  2963. if (arguments.length > 1) {
  2964. throw new Error('Object.create implementation only accepts the first parameter.');
  2965. }
  2966. function F() {}
  2967. F.prototype = o;
  2968. return new F();
  2969. };
  2970. }
  2971. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
  2972. if (!Function.prototype.bind) {
  2973. Function.prototype.bind = function (oThis) {
  2974. if (typeof this !== "function") {
  2975. // closest thing possible to the ECMAScript 5 internal IsCallable function
  2976. throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
  2977. }
  2978. var aArgs = Array.prototype.slice.call(arguments, 1),
  2979. fToBind = this,
  2980. fNOP = function () {},
  2981. fBound = function () {
  2982. return fToBind.apply(this instanceof fNOP && oThis
  2983. ? this
  2984. : oThis,
  2985. aArgs.concat(Array.prototype.slice.call(arguments)));
  2986. };
  2987. fNOP.prototype = this.prototype;
  2988. fBound.prototype = new fNOP();
  2989. return fBound;
  2990. };
  2991. }
  2992. /**
  2993. * utility functions
  2994. */
  2995. var util = {};
  2996. /**
  2997. * Test whether given object is a number
  2998. * @param {*} object
  2999. * @return {Boolean} isNumber
  3000. */
  3001. util.isNumber = function isNumber(object) {
  3002. return (object instanceof Number || typeof object == 'number');
  3003. };
  3004. /**
  3005. * Test whether given object is a string
  3006. * @param {*} object
  3007. * @return {Boolean} isString
  3008. */
  3009. util.isString = function isString(object) {
  3010. return (object instanceof String || typeof object == 'string');
  3011. };
  3012. /**
  3013. * Test whether given object is a Date, or a String containing a Date
  3014. * @param {Date | String} object
  3015. * @return {Boolean} isDate
  3016. */
  3017. util.isDate = function isDate(object) {
  3018. if (object instanceof Date) {
  3019. return true;
  3020. }
  3021. else if (util.isString(object)) {
  3022. // test whether this string contains a date
  3023. var match = ASPDateRegex.exec(object);
  3024. if (match) {
  3025. return true;
  3026. }
  3027. else if (!isNaN(Date.parse(object))) {
  3028. return true;
  3029. }
  3030. }
  3031. return false;
  3032. };
  3033. /**
  3034. * Test whether given object is an instance of google.visualization.DataTable
  3035. * @param {*} object
  3036. * @return {Boolean} isDataTable
  3037. */
  3038. util.isDataTable = function isDataTable(object) {
  3039. return (typeof (google) !== 'undefined') &&
  3040. (google.visualization) &&
  3041. (google.visualization.DataTable) &&
  3042. (object instanceof google.visualization.DataTable);
  3043. };
  3044. /**
  3045. * Create a semi UUID
  3046. * source: http://stackoverflow.com/a/105074/1262753
  3047. * @return {String} uuid
  3048. */
  3049. util.randomUUID = function randomUUID () {
  3050. var S4 = function () {
  3051. return Math.floor(
  3052. Math.random() * 0x10000 /* 65536 */
  3053. ).toString(16);
  3054. };
  3055. return (
  3056. S4() + S4() + '-' +
  3057. S4() + '-' +
  3058. S4() + '-' +
  3059. S4() + '-' +
  3060. S4() + S4() + S4()
  3061. );
  3062. };
  3063. /**
  3064. * Extend object a with the properties of object b or a series of objects
  3065. * Only properties with defined values are copied
  3066. * @param {Object} a
  3067. * @param {... Object} b
  3068. * @return {Object} a
  3069. */
  3070. util.extend = function (a, b) {
  3071. for (var i = 1, len = arguments.length; i < len; i++) {
  3072. var other = arguments[i];
  3073. for (var prop in other) {
  3074. if (other.hasOwnProperty(prop) && other[prop] !== undefined) {
  3075. a[prop] = other[prop];
  3076. }
  3077. }
  3078. }
  3079. return a;
  3080. };
  3081. /**
  3082. * Convert an object to another type
  3083. * @param {Boolean | Number | String | Date | Moment | Null | undefined} object
  3084. * @param {String | undefined} type Name of the type. Available types:
  3085. * 'Boolean', 'Number', 'String',
  3086. * 'Date', 'Moment', ISODate', 'ASPDate'.
  3087. * @return {*} object
  3088. * @throws Error
  3089. */
  3090. util.convert = function convert(object, type) {
  3091. var match;
  3092. if (object === undefined) {
  3093. return undefined;
  3094. }
  3095. if (object === null) {
  3096. return null;
  3097. }
  3098. if (!type) {
  3099. return object;
  3100. }
  3101. if (!(typeof type === 'string') && !(type instanceof String)) {
  3102. throw new Error('Type must be a string');
  3103. }
  3104. //noinspection FallthroughInSwitchStatementJS
  3105. switch (type) {
  3106. case 'boolean':
  3107. case 'Boolean':
  3108. return Boolean(object);
  3109. case 'number':
  3110. case 'Number':
  3111. return Number(object.valueOf());
  3112. case 'string':
  3113. case 'String':
  3114. return String(object);
  3115. case 'Date':
  3116. if (util.isNumber(object)) {
  3117. return new Date(object);
  3118. }
  3119. if (object instanceof Date) {
  3120. return new Date(object.valueOf());
  3121. }
  3122. else if (moment.isMoment(object)) {
  3123. return new Date(object.valueOf());
  3124. }
  3125. if (util.isString(object)) {
  3126. match = ASPDateRegex.exec(object);
  3127. if (match) {
  3128. // object is an ASP date
  3129. return new Date(Number(match[1])); // parse number
  3130. }
  3131. else {
  3132. return moment(object).toDate(); // parse string
  3133. }
  3134. }
  3135. else {
  3136. throw new Error(
  3137. 'Cannot convert object of type ' + util.getType(object) +
  3138. ' to type Date');
  3139. }
  3140. case 'Moment':
  3141. if (util.isNumber(object)) {
  3142. return moment(object);
  3143. }
  3144. if (object instanceof Date) {
  3145. return moment(object.valueOf());
  3146. }
  3147. else if (moment.isMoment(object)) {
  3148. return moment(object);
  3149. }
  3150. if (util.isString(object)) {
  3151. match = ASPDateRegex.exec(object);
  3152. if (match) {
  3153. // object is an ASP date
  3154. return moment(Number(match[1])); // parse number
  3155. }
  3156. else {
  3157. return moment(object); // parse string
  3158. }
  3159. }
  3160. else {
  3161. throw new Error(
  3162. 'Cannot convert object of type ' + util.getType(object) +
  3163. ' to type Date');
  3164. }
  3165. case 'ISODate':
  3166. if (util.isNumber(object)) {
  3167. return new Date(object);
  3168. }
  3169. else if (object instanceof Date) {
  3170. return object.toISOString();
  3171. }
  3172. else if (moment.isMoment(object)) {
  3173. return object.toDate().toISOString();
  3174. }
  3175. else if (util.isString(object)) {
  3176. match = ASPDateRegex.exec(object);
  3177. if (match) {
  3178. // object is an ASP date
  3179. return new Date(Number(match[1])).toISOString(); // parse number
  3180. }
  3181. else {
  3182. return new Date(object).toISOString(); // parse string
  3183. }
  3184. }
  3185. else {
  3186. throw new Error(
  3187. 'Cannot convert object of type ' + util.getType(object) +
  3188. ' to type ISODate');
  3189. }
  3190. case 'ASPDate':
  3191. if (util.isNumber(object)) {
  3192. return '/Date(' + object + ')/';
  3193. }
  3194. else if (object instanceof Date) {
  3195. return '/Date(' + object.valueOf() + ')/';
  3196. }
  3197. else if (util.isString(object)) {
  3198. match = ASPDateRegex.exec(object);
  3199. var value;
  3200. if (match) {
  3201. // object is an ASP date
  3202. value = new Date(Number(match[1])).valueOf(); // parse number
  3203. }
  3204. else {
  3205. value = new Date(object).valueOf(); // parse string
  3206. }
  3207. return '/Date(' + value + ')/';
  3208. }
  3209. else {
  3210. throw new Error(
  3211. 'Cannot convert object of type ' + util.getType(object) +
  3212. ' to type ASPDate');
  3213. }
  3214. default:
  3215. throw new Error('Cannot convert object of type ' + util.getType(object) +
  3216. ' to type "' + type + '"');
  3217. }
  3218. };
  3219. // parse ASP.Net Date pattern,
  3220. // for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/'
  3221. // code from http://momentjs.com/
  3222. var ASPDateRegex = /^\/?Date\((\-?\d+)/i;
  3223. /**
  3224. * Get the type of an object, for example util.getType([]) returns 'Array'
  3225. * @param {*} object
  3226. * @return {String} type
  3227. */
  3228. util.getType = function getType(object) {
  3229. var type = typeof object;
  3230. if (type == 'object') {
  3231. if (object == null) {
  3232. return 'null';
  3233. }
  3234. if (object instanceof Boolean) {
  3235. return 'Boolean';
  3236. }
  3237. if (object instanceof Number) {
  3238. return 'Number';
  3239. }
  3240. if (object instanceof String) {
  3241. return 'String';
  3242. }
  3243. if (object instanceof Array) {
  3244. return 'Array';
  3245. }
  3246. if (object instanceof Date) {
  3247. return 'Date';
  3248. }
  3249. return 'Object';
  3250. }
  3251. else if (type == 'number') {
  3252. return 'Number';
  3253. }
  3254. else if (type == 'boolean') {
  3255. return 'Boolean';
  3256. }
  3257. else if (type == 'string') {
  3258. return 'String';
  3259. }
  3260. return type;
  3261. };
  3262. /**
  3263. * Retrieve the absolute left value of a DOM element
  3264. * @param {Element} elem A dom element, for example a div
  3265. * @return {number} left The absolute left position of this element
  3266. * in the browser page.
  3267. */
  3268. util.getAbsoluteLeft = function getAbsoluteLeft (elem) {
  3269. var doc = document.documentElement;
  3270. var body = document.body;
  3271. var left = elem.offsetLeft;
  3272. var e = elem.offsetParent;
  3273. while (e != null && e != body && e != doc) {
  3274. left += e.offsetLeft;
  3275. left -= e.scrollLeft;
  3276. e = e.offsetParent;
  3277. }
  3278. return left;
  3279. };
  3280. /**
  3281. * Retrieve the absolute top value of a DOM element
  3282. * @param {Element} elem A dom element, for example a div
  3283. * @return {number} top The absolute top position of this element
  3284. * in the browser page.
  3285. */
  3286. util.getAbsoluteTop = function getAbsoluteTop (elem) {
  3287. var doc = document.documentElement;
  3288. var body = document.body;
  3289. var top = elem.offsetTop;
  3290. var e = elem.offsetParent;
  3291. while (e != null && e != body && e != doc) {
  3292. top += e.offsetTop;
  3293. top -= e.scrollTop;
  3294. e = e.offsetParent;
  3295. }
  3296. return top;
  3297. };
  3298. /**
  3299. * Get the absolute, vertical mouse position from an event.
  3300. * @param {Event} event
  3301. * @return {Number} pageY
  3302. */
  3303. util.getPageY = function getPageY (event) {
  3304. if ('pageY' in event) {
  3305. return event.pageY;
  3306. }
  3307. else {
  3308. var clientY;
  3309. if (('targetTouches' in event) && event.targetTouches.length) {
  3310. clientY = event.targetTouches[0].clientY;
  3311. }
  3312. else {
  3313. clientY = event.clientY;
  3314. }
  3315. var doc = document.documentElement;
  3316. var body = document.body;
  3317. return clientY +
  3318. ( doc && doc.scrollTop || body && body.scrollTop || 0 ) -
  3319. ( doc && doc.clientTop || body && body.clientTop || 0 );
  3320. }
  3321. };
  3322. /**
  3323. * Get the absolute, horizontal mouse position from an event.
  3324. * @param {Event} event
  3325. * @return {Number} pageX
  3326. */
  3327. util.getPageX = function getPageX (event) {
  3328. if ('pageY' in event) {
  3329. return event.pageX;
  3330. }
  3331. else {
  3332. var clientX;
  3333. if (('targetTouches' in event) && event.targetTouches.length) {
  3334. clientX = event.targetTouches[0].clientX;
  3335. }
  3336. else {
  3337. clientX = event.clientX;
  3338. }
  3339. var doc = document.documentElement;
  3340. var body = document.body;
  3341. return clientX +
  3342. ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) -
  3343. ( doc && doc.clientLeft || body && body.clientLeft || 0 );
  3344. }
  3345. };
  3346. /**
  3347. * add a className to the given elements style
  3348. * @param {Element} elem
  3349. * @param {String} className
  3350. */
  3351. util.addClassName = function addClassName(elem, className) {
  3352. var classes = elem.className.split(' ');
  3353. if (classes.indexOf(className) == -1) {
  3354. classes.push(className); // add the class to the array
  3355. elem.className = classes.join(' ');
  3356. }
  3357. };
  3358. /**
  3359. * add a className to the given elements style
  3360. * @param {Element} elem
  3361. * @param {String} className
  3362. */
  3363. util.removeClassName = function removeClassname(elem, className) {
  3364. var classes = elem.className.split(' ');
  3365. var index = classes.indexOf(className);
  3366. if (index != -1) {
  3367. classes.splice(index, 1); // remove the class from the array
  3368. elem.className = classes.join(' ');
  3369. }
  3370. };
  3371. /**
  3372. * For each method for both arrays and objects.
  3373. * In case of an array, the built-in Array.forEach() is applied.
  3374. * In case of an Object, the method loops over all properties of the object.
  3375. * @param {Object | Array} object An Object or Array
  3376. * @param {function} callback Callback method, called for each item in
  3377. * the object or array with three parameters:
  3378. * callback(value, index, object)
  3379. */
  3380. util.forEach = function forEach (object, callback) {
  3381. var i,
  3382. len;
  3383. if (object instanceof Array) {
  3384. // array
  3385. for (i = 0, len = object.length; i < len; i++) {
  3386. callback(object[i], i, object);
  3387. }
  3388. }
  3389. else {
  3390. // object
  3391. for (i in object) {
  3392. if (object.hasOwnProperty(i)) {
  3393. callback(object[i], i, object);
  3394. }
  3395. }
  3396. }
  3397. };
  3398. /**
  3399. * Update a property in an object
  3400. * @param {Object} object
  3401. * @param {String} key
  3402. * @param {*} value
  3403. * @return {Boolean} changed
  3404. */
  3405. util.updateProperty = function updateProp (object, key, value) {
  3406. if (object[key] !== value) {
  3407. object[key] = value;
  3408. return true;
  3409. }
  3410. else {
  3411. return false;
  3412. }
  3413. };
  3414. /**
  3415. * Add and event listener. Works for all browsers
  3416. * @param {Element} element An html element
  3417. * @param {string} action The action, for example "click",
  3418. * without the prefix "on"
  3419. * @param {function} listener The callback function to be executed
  3420. * @param {boolean} [useCapture]
  3421. */
  3422. util.addEventListener = function addEventListener(element, action, listener, useCapture) {
  3423. if (element.addEventListener) {
  3424. if (useCapture === undefined)
  3425. useCapture = false;
  3426. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  3427. action = "DOMMouseScroll"; // For Firefox
  3428. }
  3429. element.addEventListener(action, listener, useCapture);
  3430. } else {
  3431. element.attachEvent("on" + action, listener); // IE browsers
  3432. }
  3433. };
  3434. /**
  3435. * Remove an event listener from an element
  3436. * @param {Element} element An html dom element
  3437. * @param {string} action The name of the event, for example "mousedown"
  3438. * @param {function} listener The listener function
  3439. * @param {boolean} [useCapture]
  3440. */
  3441. util.removeEventListener = function removeEventListener(element, action, listener, useCapture) {
  3442. if (element.removeEventListener) {
  3443. // non-IE browsers
  3444. if (useCapture === undefined)
  3445. useCapture = false;
  3446. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  3447. action = "DOMMouseScroll"; // For Firefox
  3448. }
  3449. element.removeEventListener(action, listener, useCapture);
  3450. } else {
  3451. // IE browsers
  3452. element.detachEvent("on" + action, listener);
  3453. }
  3454. };
  3455. /**
  3456. * Get HTML element which is the target of the event
  3457. * @param {Event} event
  3458. * @return {Element} target element
  3459. */
  3460. util.getTarget = function getTarget(event) {
  3461. // code from http://www.quirksmode.org/js/events_properties.html
  3462. if (!event) {
  3463. event = window.event;
  3464. }
  3465. var target;
  3466. if (event.target) {
  3467. target = event.target;
  3468. }
  3469. else if (event.srcElement) {
  3470. target = event.srcElement;
  3471. }
  3472. if (target.nodeType != undefined && target.nodeType == 3) {
  3473. // defeat Safari bug
  3474. target = target.parentNode;
  3475. }
  3476. return target;
  3477. };
  3478. /**
  3479. * Stop event propagation
  3480. */
  3481. util.stopPropagation = function stopPropagation(event) {
  3482. if (!event)
  3483. event = window.event;
  3484. if (event.stopPropagation) {
  3485. event.stopPropagation(); // non-IE browsers
  3486. }
  3487. else {
  3488. event.cancelBubble = true; // IE browsers
  3489. }
  3490. };
  3491. /**
  3492. * Cancels the event if it is cancelable, without stopping further propagation of the event.
  3493. */
  3494. util.preventDefault = function preventDefault (event) {
  3495. if (!event)
  3496. event = window.event;
  3497. if (event.preventDefault) {
  3498. event.preventDefault(); // non-IE browsers
  3499. }
  3500. else {
  3501. event.returnValue = false; // IE browsers
  3502. }
  3503. };
  3504. util.option = {};
  3505. /**
  3506. * Convert a value into a boolean
  3507. * @param {Boolean | function | undefined} value
  3508. * @param {Boolean} [defaultValue]
  3509. * @returns {Boolean} bool
  3510. */
  3511. util.option.asBoolean = function (value, defaultValue) {
  3512. if (typeof value == 'function') {
  3513. value = value();
  3514. }
  3515. if (value != null) {
  3516. return (value != false);
  3517. }
  3518. return defaultValue || null;
  3519. };
  3520. /**
  3521. * Convert a value into a number
  3522. * @param {Boolean | function | undefined} value
  3523. * @param {Number} [defaultValue]
  3524. * @returns {Number} number
  3525. */
  3526. util.option.asNumber = function (value, defaultValue) {
  3527. if (typeof value == 'function') {
  3528. value = value();
  3529. }
  3530. if (value != null) {
  3531. return Number(value) || defaultValue || null;
  3532. }
  3533. return defaultValue || null;
  3534. };
  3535. /**
  3536. * Convert a value into a string
  3537. * @param {String | function | undefined} value
  3538. * @param {String} [defaultValue]
  3539. * @returns {String} str
  3540. */
  3541. util.option.asString = function (value, defaultValue) {
  3542. if (typeof value == 'function') {
  3543. value = value();
  3544. }
  3545. if (value != null) {
  3546. return String(value);
  3547. }
  3548. return defaultValue || null;
  3549. };
  3550. /**
  3551. * Convert a size or location into a string with pixels or a percentage
  3552. * @param {String | Number | function | undefined} value
  3553. * @param {String} [defaultValue]
  3554. * @returns {String} size
  3555. */
  3556. util.option.asSize = function (value, defaultValue) {
  3557. if (typeof value == 'function') {
  3558. value = value();
  3559. }
  3560. if (util.isString(value)) {
  3561. return value;
  3562. }
  3563. else if (util.isNumber(value)) {
  3564. return value + 'px';
  3565. }
  3566. else {
  3567. return defaultValue || null;
  3568. }
  3569. };
  3570. /**
  3571. * Convert a value into a DOM element
  3572. * @param {HTMLElement | function | undefined} value
  3573. * @param {HTMLElement} [defaultValue]
  3574. * @returns {HTMLElement | null} dom
  3575. */
  3576. util.option.asElement = function (value, defaultValue) {
  3577. if (typeof value == 'function') {
  3578. value = value();
  3579. }
  3580. return value || defaultValue || null;
  3581. };
  3582. /**
  3583. * load css from text
  3584. * @param {String} css Text containing css
  3585. */
  3586. util.loadCss = function (css) {
  3587. if (typeof document === 'undefined') {
  3588. return;
  3589. }
  3590. // get the script location, and built the css file name from the js file name
  3591. // http://stackoverflow.com/a/2161748/1262753
  3592. // var scripts = document.getElementsByTagName('script');
  3593. // var jsFile = scripts[scripts.length-1].src.split('?')[0];
  3594. // var cssFile = jsFile.substring(0, jsFile.length - 2) + 'css';
  3595. // inject css
  3596. // http://stackoverflow.com/questions/524696/how-to-create-a-style-tag-with-javascript
  3597. var style = document.createElement('style');
  3598. style.type = 'text/css';
  3599. if (style.styleSheet){
  3600. style.styleSheet.cssText = css;
  3601. } else {
  3602. style.appendChild(document.createTextNode(css));
  3603. }
  3604. document.getElementsByTagName('head')[0].appendChild(style);
  3605. };
  3606. /**
  3607. * Event listener (singleton)
  3608. */
  3609. // TODO: replace usage of the event listener for the EventBus
  3610. var events = {
  3611. 'listeners': [],
  3612. /**
  3613. * Find a single listener by its object
  3614. * @param {Object} object
  3615. * @return {Number} index -1 when not found
  3616. */
  3617. 'indexOf': function (object) {
  3618. var listeners = this.listeners;
  3619. for (var i = 0, iMax = this.listeners.length; i < iMax; i++) {
  3620. var listener = listeners[i];
  3621. if (listener && listener.object == object) {
  3622. return i;
  3623. }
  3624. }
  3625. return -1;
  3626. },
  3627. /**
  3628. * Add an event listener
  3629. * @param {Object} object
  3630. * @param {String} event The name of an event, for example 'select'
  3631. * @param {function} callback The callback method, called when the
  3632. * event takes place
  3633. */
  3634. 'addListener': function (object, event, callback) {
  3635. var index = this.indexOf(object);
  3636. var listener = this.listeners[index];
  3637. if (!listener) {
  3638. listener = {
  3639. 'object': object,
  3640. 'events': {}
  3641. };
  3642. this.listeners.push(listener);
  3643. }
  3644. var callbacks = listener.events[event];
  3645. if (!callbacks) {
  3646. callbacks = [];
  3647. listener.events[event] = callbacks;
  3648. }
  3649. // add the callback if it does not yet exist
  3650. if (callbacks.indexOf(callback) == -1) {
  3651. callbacks.push(callback);
  3652. }
  3653. },
  3654. /**
  3655. * Remove an event listener
  3656. * @param {Object} object
  3657. * @param {String} event The name of an event, for example 'select'
  3658. * @param {function} callback The registered callback method
  3659. */
  3660. 'removeListener': function (object, event, callback) {
  3661. var index = this.indexOf(object);
  3662. var listener = this.listeners[index];
  3663. if (listener) {
  3664. var callbacks = listener.events[event];
  3665. if (callbacks) {
  3666. index = callbacks.indexOf(callback);
  3667. if (index != -1) {
  3668. callbacks.splice(index, 1);
  3669. }
  3670. // remove the array when empty
  3671. if (callbacks.length == 0) {
  3672. delete listener.events[event];
  3673. }
  3674. }
  3675. // count the number of registered events. remove listener when empty
  3676. var count = 0;
  3677. var events = listener.events;
  3678. for (var e in events) {
  3679. if (events.hasOwnProperty(e)) {
  3680. count++;
  3681. }
  3682. }
  3683. if (count == 0) {
  3684. delete this.listeners[index];
  3685. }
  3686. }
  3687. },
  3688. /**
  3689. * Remove all registered event listeners
  3690. */
  3691. 'removeAllListeners': function () {
  3692. this.listeners = [];
  3693. },
  3694. /**
  3695. * Trigger an event. All registered event handlers will be called
  3696. * @param {Object} object
  3697. * @param {String} event
  3698. * @param {Object} properties (optional)
  3699. */
  3700. 'trigger': function (object, event, properties) {
  3701. var index = this.indexOf(object);
  3702. var listener = this.listeners[index];
  3703. if (listener) {
  3704. var callbacks = listener.events[event];
  3705. if (callbacks) {
  3706. for (var i = 0, iMax = callbacks.length; i < iMax; i++) {
  3707. callbacks[i](properties);
  3708. }
  3709. }
  3710. }
  3711. }
  3712. };
  3713. /**
  3714. * An event bus can be used to emit events, and to subscribe to events
  3715. * @constructor EventBus
  3716. */
  3717. function EventBus() {
  3718. this.subscriptions = [];
  3719. }
  3720. /**
  3721. * Subscribe to an event
  3722. * @param {String | RegExp} event The event can be a regular expression, or
  3723. * a string with wildcards, like 'server.*'.
  3724. * @param {function} callback. Callback are called with three parameters:
  3725. * {String} event, {*} [data], {*} [source]
  3726. * @param {*} [target]
  3727. * @returns {String} id A subscription id
  3728. */
  3729. EventBus.prototype.on = function (event, callback, target) {
  3730. var regexp = (event instanceof RegExp) ?
  3731. event :
  3732. new RegExp(event.replace('*', '\\w+'));
  3733. var subscription = {
  3734. id: util.randomUUID(),
  3735. event: event,
  3736. regexp: regexp,
  3737. callback: (typeof callback === 'function') ? callback : null,
  3738. target: target
  3739. };
  3740. this.subscriptions.push(subscription);
  3741. return subscription.id;
  3742. };
  3743. /**
  3744. * Unsubscribe from an event
  3745. * @param {String | Object} filter Filter for subscriptions to be removed
  3746. * Filter can be a string containing a
  3747. * subscription id, or an object containing
  3748. * one or more of the fields id, event,
  3749. * callback, and target.
  3750. */
  3751. EventBus.prototype.off = function (filter) {
  3752. var i = 0;
  3753. while (i < this.subscriptions.length) {
  3754. var subscription = this.subscriptions[i];
  3755. var match = true;
  3756. if (filter instanceof Object) {
  3757. // filter is an object. All fields must match
  3758. for (var prop in filter) {
  3759. if (filter.hasOwnProperty(prop)) {
  3760. if (filter[prop] !== subscription[prop]) {
  3761. match = false;
  3762. }
  3763. }
  3764. }
  3765. }
  3766. else {
  3767. // filter is a string, filter on id
  3768. match = (subscription.id == filter);
  3769. }
  3770. if (match) {
  3771. this.subscriptions.splice(i, 1);
  3772. }
  3773. else {
  3774. i++;
  3775. }
  3776. }
  3777. };
  3778. /**
  3779. * Emit an event
  3780. * @param {String} event
  3781. * @param {*} [data]
  3782. * @param {*} [source]
  3783. */
  3784. EventBus.prototype.emit = function (event, data, source) {
  3785. for (var i =0; i < this.subscriptions.length; i++) {
  3786. var subscription = this.subscriptions[i];
  3787. if (subscription.regexp.test(event)) {
  3788. if (subscription.callback) {
  3789. subscription.callback(event, data, source);
  3790. }
  3791. }
  3792. }
  3793. };
  3794. /**
  3795. * DataSet
  3796. *
  3797. * Usage:
  3798. * var dataSet = new DataSet({
  3799. * fieldId: '_id',
  3800. * convert: {
  3801. * // ...
  3802. * }
  3803. * });
  3804. *
  3805. * dataSet.add(item);
  3806. * dataSet.add(data);
  3807. * dataSet.update(item);
  3808. * dataSet.update(data);
  3809. * dataSet.remove(id);
  3810. * dataSet.remove(ids);
  3811. * var data = dataSet.get();
  3812. * var data = dataSet.get(id);
  3813. * var data = dataSet.get(ids);
  3814. * var data = dataSet.get(ids, options, data);
  3815. * dataSet.clear();
  3816. *
  3817. * A data set can:
  3818. * - add/remove/update data
  3819. * - gives triggers upon changes in the data
  3820. * - can import/export data in various data formats
  3821. *
  3822. * @param {Object} [options] Available options:
  3823. * {String} fieldId Field name of the id in the
  3824. * items, 'id' by default.
  3825. * {Object.<String, String} convert
  3826. * A map with field names as key,
  3827. * and the field type as value.
  3828. * @constructor DataSet
  3829. */
  3830. // TODO: add a DataSet constructor DataSet(data, options)
  3831. function DataSet (options) {
  3832. this.id = util.randomUUID();
  3833. this.options = options || {};
  3834. this.data = {}; // map with data indexed by id
  3835. this.fieldId = this.options.fieldId || 'id'; // name of the field containing id
  3836. this.convert = {}; // field types by field name
  3837. if (this.options.convert) {
  3838. for (var field in this.options.convert) {
  3839. if (this.options.convert.hasOwnProperty(field)) {
  3840. var value = this.options.convert[field];
  3841. if (value == 'Date' || value == 'ISODate' || value == 'ASPDate') {
  3842. this.convert[field] = 'Date';
  3843. }
  3844. else {
  3845. this.convert[field] = value;
  3846. }
  3847. }
  3848. }
  3849. }
  3850. // event subscribers
  3851. this.subscribers = {};
  3852. this.internalIds = {}; // internally generated id's
  3853. }
  3854. /**
  3855. * Subscribe to an event, add an event listener
  3856. * @param {String} event Event name. Available events: 'put', 'update',
  3857. * 'remove'
  3858. * @param {function} callback Callback method. Called with three parameters:
  3859. * {String} event
  3860. * {Object | null} params
  3861. * {String | Number} senderId
  3862. */
  3863. DataSet.prototype.subscribe = function (event, callback) {
  3864. var subscribers = this.subscribers[event];
  3865. if (!subscribers) {
  3866. subscribers = [];
  3867. this.subscribers[event] = subscribers;
  3868. }
  3869. subscribers.push({
  3870. callback: callback
  3871. });
  3872. };
  3873. /**
  3874. * Unsubscribe from an event, remove an event listener
  3875. * @param {String} event
  3876. * @param {function} callback
  3877. */
  3878. DataSet.prototype.unsubscribe = function (event, callback) {
  3879. var subscribers = this.subscribers[event];
  3880. if (subscribers) {
  3881. this.subscribers[event] = subscribers.filter(function (listener) {
  3882. return (listener.callback != callback);
  3883. });
  3884. }
  3885. };
  3886. /**
  3887. * Trigger an event
  3888. * @param {String} event
  3889. * @param {Object | null} params
  3890. * @param {String} [senderId] Optional id of the sender.
  3891. * @private
  3892. */
  3893. DataSet.prototype._trigger = function (event, params, senderId) {
  3894. if (event == '*') {
  3895. throw new Error('Cannot trigger event *');
  3896. }
  3897. var subscribers = [];
  3898. if (event in this.subscribers) {
  3899. subscribers = subscribers.concat(this.subscribers[event]);
  3900. }
  3901. if ('*' in this.subscribers) {
  3902. subscribers = subscribers.concat(this.subscribers['*']);
  3903. }
  3904. for (var i = 0; i < subscribers.length; i++) {
  3905. var subscriber = subscribers[i];
  3906. if (subscriber.callback) {
  3907. subscriber.callback(event, params, senderId || null);
  3908. }
  3909. }
  3910. };
  3911. /**
  3912. * Add data.
  3913. * Adding an item will fail when there already is an item with the same id.
  3914. * @param {Object | Array | DataTable} data
  3915. * @param {String} [senderId] Optional sender id
  3916. * @return {Array} addedIds Array with the ids of the added items
  3917. */
  3918. DataSet.prototype.add = function (data, senderId) {
  3919. var addedIds = [],
  3920. id,
  3921. me = this;
  3922. if (data instanceof Array) {
  3923. // Array
  3924. for (var i = 0, len = data.length; i < len; i++) {
  3925. id = me._addItem(data[i]);
  3926. addedIds.push(id);
  3927. }
  3928. }
  3929. else if (util.isDataTable(data)) {
  3930. // Google DataTable
  3931. var columns = this._getColumnNames(data);
  3932. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  3933. var item = {};
  3934. for (var col = 0, cols = columns.length; col < cols; col++) {
  3935. var field = columns[col];
  3936. item[field] = data.getValue(row, col);
  3937. }
  3938. id = me._addItem(item);
  3939. addedIds.push(id);
  3940. }
  3941. }
  3942. else if (data instanceof Object) {
  3943. // Single item
  3944. id = me._addItem(data);
  3945. addedIds.push(id);
  3946. }
  3947. else {
  3948. throw new Error('Unknown dataType');
  3949. }
  3950. if (addedIds.length) {
  3951. this._trigger('add', {items: addedIds}, senderId);
  3952. }
  3953. return addedIds;
  3954. };
  3955. /**
  3956. * Update existing items. When an item does not exist, it will be created
  3957. * @param {Object | Array | DataTable} data
  3958. * @param {String} [senderId] Optional sender id
  3959. * @return {Array} updatedIds The ids of the added or updated items
  3960. */
  3961. DataSet.prototype.update = function (data, senderId) {
  3962. var addedIds = [],
  3963. updatedIds = [],
  3964. me = this,
  3965. fieldId = me.fieldId;
  3966. var addOrUpdate = function (item) {
  3967. var id = item[fieldId];
  3968. if (me.data[id]) {
  3969. // update item
  3970. id = me._updateItem(item);
  3971. updatedIds.push(id);
  3972. }
  3973. else {
  3974. // add new item
  3975. id = me._addItem(item);
  3976. addedIds.push(id);
  3977. }
  3978. };
  3979. if (data instanceof Array) {
  3980. // Array
  3981. for (var i = 0, len = data.length; i < len; i++) {
  3982. addOrUpdate(data[i]);
  3983. }
  3984. }
  3985. else if (util.isDataTable(data)) {
  3986. // Google DataTable
  3987. var columns = this._getColumnNames(data);
  3988. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  3989. var item = {};
  3990. for (var col = 0, cols = columns.length; col < cols; col++) {
  3991. var field = columns[col];
  3992. item[field] = data.getValue(row, col);
  3993. }
  3994. addOrUpdate(item);
  3995. }
  3996. }
  3997. else if (data instanceof Object) {
  3998. // Single item
  3999. addOrUpdate(data);
  4000. }
  4001. else {
  4002. throw new Error('Unknown dataType');
  4003. }
  4004. if (addedIds.length) {
  4005. this._trigger('add', {items: addedIds}, senderId);
  4006. }
  4007. if (updatedIds.length) {
  4008. this._trigger('update', {items: updatedIds}, senderId);
  4009. }
  4010. return addedIds.concat(updatedIds);
  4011. };
  4012. /**
  4013. * Get a data item or multiple items.
  4014. *
  4015. * Usage:
  4016. *
  4017. * get()
  4018. * get(options: Object)
  4019. * get(options: Object, data: Array | DataTable)
  4020. *
  4021. * get(id: Number | String)
  4022. * get(id: Number | String, options: Object)
  4023. * get(id: Number | String, options: Object, data: Array | DataTable)
  4024. *
  4025. * get(ids: Number[] | String[])
  4026. * get(ids: Number[] | String[], options: Object)
  4027. * get(ids: Number[] | String[], options: Object, data: Array | DataTable)
  4028. *
  4029. * Where:
  4030. *
  4031. * {Number | String} id The id of an item
  4032. * {Number[] | String{}} ids An array with ids of items
  4033. * {Object} options An Object with options. Available options:
  4034. * {String} [type] Type of data to be returned. Can
  4035. * be 'DataTable' or 'Array' (default)
  4036. * {Object.<String, String>} [convert]
  4037. * {String[]} [fields] field names to be returned
  4038. * {function} [filter] filter items
  4039. * {String | function} [order] Order the items by
  4040. * a field name or custom sort function.
  4041. * {Array | DataTable} [data] If provided, items will be appended to this
  4042. * array or table. Required in case of Google
  4043. * DataTable.
  4044. *
  4045. * @throws Error
  4046. */
  4047. DataSet.prototype.get = function (args) {
  4048. var me = this;
  4049. // parse the arguments
  4050. var id, ids, options, data;
  4051. var firstType = util.getType(arguments[0]);
  4052. if (firstType == 'String' || firstType == 'Number') {
  4053. // get(id [, options] [, data])
  4054. id = arguments[0];
  4055. options = arguments[1];
  4056. data = arguments[2];
  4057. }
  4058. else if (firstType == 'Array') {
  4059. // get(ids [, options] [, data])
  4060. ids = arguments[0];
  4061. options = arguments[1];
  4062. data = arguments[2];
  4063. }
  4064. else {
  4065. // get([, options] [, data])
  4066. options = arguments[0];
  4067. data = arguments[1];
  4068. }
  4069. // determine the return type
  4070. var type;
  4071. if (options && options.type) {
  4072. type = (options.type == 'DataTable') ? 'DataTable' : 'Array';
  4073. if (data && (type != util.getType(data))) {
  4074. throw new Error('Type of parameter "data" (' + util.getType(data) + ') ' +
  4075. 'does not correspond with specified options.type (' + options.type + ')');
  4076. }
  4077. if (type == 'DataTable' && !util.isDataTable(data)) {
  4078. throw new Error('Parameter "data" must be a DataTable ' +
  4079. 'when options.type is "DataTable"');
  4080. }
  4081. }
  4082. else if (data) {
  4083. type = (util.getType(data) == 'DataTable') ? 'DataTable' : 'Array';
  4084. }
  4085. else {
  4086. type = 'Array';
  4087. }
  4088. // build options
  4089. var convert = options && options.convert || this.options.convert;
  4090. var filter = options && options.filter;
  4091. var items = [], item, itemId, i, len;
  4092. // convert items
  4093. if (id != undefined) {
  4094. // return a single item
  4095. item = me._getItem(id, convert);
  4096. if (filter && !filter(item)) {
  4097. item = null;
  4098. }
  4099. }
  4100. else if (ids != undefined) {
  4101. // return a subset of items
  4102. for (i = 0, len = ids.length; i < len; i++) {
  4103. item = me._getItem(ids[i], convert);
  4104. if (!filter || filter(item)) {
  4105. items.push(item);
  4106. }
  4107. }
  4108. }
  4109. else {
  4110. // return all items
  4111. for (itemId in this.data) {
  4112. if (this.data.hasOwnProperty(itemId)) {
  4113. item = me._getItem(itemId, convert);
  4114. if (!filter || filter(item)) {
  4115. items.push(item);
  4116. }
  4117. }
  4118. }
  4119. }
  4120. // order the results
  4121. if (options && options.order && id == undefined) {
  4122. this._sort(items, options.order);
  4123. }
  4124. // filter fields of the items
  4125. if (options && options.fields) {
  4126. var fields = options.fields;
  4127. if (id != undefined) {
  4128. item = this._filterFields(item, fields);
  4129. }
  4130. else {
  4131. for (i = 0, len = items.length; i < len; i++) {
  4132. items[i] = this._filterFields(items[i], fields);
  4133. }
  4134. }
  4135. }
  4136. // return the results
  4137. if (type == 'DataTable') {
  4138. var columns = this._getColumnNames(data);
  4139. if (id != undefined) {
  4140. // append a single item to the data table
  4141. me._appendRow(data, columns, item);
  4142. }
  4143. else {
  4144. // copy the items to the provided data table
  4145. for (i = 0, len = items.length; i < len; i++) {
  4146. me._appendRow(data, columns, items[i]);
  4147. }
  4148. }
  4149. return data;
  4150. }
  4151. else {
  4152. // return an array
  4153. if (id != undefined) {
  4154. // a single item
  4155. return item;
  4156. }
  4157. else {
  4158. // multiple items
  4159. if (data) {
  4160. // copy the items to the provided array
  4161. for (i = 0, len = items.length; i < len; i++) {
  4162. data.push(items[i]);
  4163. }
  4164. return data;
  4165. }
  4166. else {
  4167. // just return our array
  4168. return items;
  4169. }
  4170. }
  4171. }
  4172. };
  4173. /**
  4174. * Get ids of all items or from a filtered set of items.
  4175. * @param {Object} [options] An Object with options. Available options:
  4176. * {function} [filter] filter items
  4177. * {String | function} [order] Order the items by
  4178. * a field name or custom sort function.
  4179. * @return {Array} ids
  4180. */
  4181. DataSet.prototype.getIds = function (options) {
  4182. var data = this.data,
  4183. filter = options && options.filter,
  4184. order = options && options.order,
  4185. convert = options && options.convert || this.options.convert,
  4186. i,
  4187. len,
  4188. id,
  4189. item,
  4190. items,
  4191. ids = [];
  4192. if (filter) {
  4193. // get filtered items
  4194. if (order) {
  4195. // create ordered list
  4196. items = [];
  4197. for (id in data) {
  4198. if (data.hasOwnProperty(id)) {
  4199. item = this._getItem(id, convert);
  4200. if (filter(item)) {
  4201. items.push(item);
  4202. }
  4203. }
  4204. }
  4205. this._sort(items, order);
  4206. for (i = 0, len = items.length; i < len; i++) {
  4207. ids[i] = items[i][this.fieldId];
  4208. }
  4209. }
  4210. else {
  4211. // create unordered list
  4212. for (id in data) {
  4213. if (data.hasOwnProperty(id)) {
  4214. item = this._getItem(id, convert);
  4215. if (filter(item)) {
  4216. ids.push(item[this.fieldId]);
  4217. }
  4218. }
  4219. }
  4220. }
  4221. }
  4222. else {
  4223. // get all items
  4224. if (order) {
  4225. // create an ordered list
  4226. items = [];
  4227. for (id in data) {
  4228. if (data.hasOwnProperty(id)) {
  4229. items.push(data[id]);
  4230. }
  4231. }
  4232. this._sort(items, order);
  4233. for (i = 0, len = items.length; i < len; i++) {
  4234. ids[i] = items[i][this.fieldId];
  4235. }
  4236. }
  4237. else {
  4238. // create unordered list
  4239. for (id in data) {
  4240. if (data.hasOwnProperty(id)) {
  4241. item = data[id];
  4242. ids.push(item[this.fieldId]);
  4243. }
  4244. }
  4245. }
  4246. }
  4247. return ids;
  4248. };
  4249. /**
  4250. * Execute a callback function for every item in the dataset.
  4251. * The order of the items is not determined.
  4252. * @param {function} callback
  4253. * @param {Object} [options] Available options:
  4254. * {Object.<String, String>} [convert]
  4255. * {String[]} [fields] filter fields
  4256. * {function} [filter] filter items
  4257. * {String | function} [order] Order the items by
  4258. * a field name or custom sort function.
  4259. */
  4260. DataSet.prototype.forEach = function (callback, options) {
  4261. var filter = options && options.filter,
  4262. convert = options && options.convert || this.options.convert,
  4263. data = this.data,
  4264. item,
  4265. id;
  4266. if (options && options.order) {
  4267. // execute forEach on ordered list
  4268. var items = this.get(options);
  4269. for (var i = 0, len = items.length; i < len; i++) {
  4270. item = items[i];
  4271. id = item[this.fieldId];
  4272. callback(item, id);
  4273. }
  4274. }
  4275. else {
  4276. // unordered
  4277. for (id in data) {
  4278. if (data.hasOwnProperty(id)) {
  4279. item = this._getItem(id, convert);
  4280. if (!filter || filter(item)) {
  4281. callback(item, id);
  4282. }
  4283. }
  4284. }
  4285. }
  4286. };
  4287. /**
  4288. * Map every item in the dataset.
  4289. * @param {function} callback
  4290. * @param {Object} [options] Available options:
  4291. * {Object.<String, String>} [convert]
  4292. * {String[]} [fields] filter fields
  4293. * {function} [filter] filter items
  4294. * {String | function} [order] Order the items by
  4295. * a field name or custom sort function.
  4296. * @return {Object[]} mappedItems
  4297. */
  4298. DataSet.prototype.map = function (callback, options) {
  4299. var filter = options && options.filter,
  4300. convert = options && options.convert || this.options.convert,
  4301. mappedItems = [],
  4302. data = this.data,
  4303. item;
  4304. // convert and filter items
  4305. for (var id in data) {
  4306. if (data.hasOwnProperty(id)) {
  4307. item = this._getItem(id, convert);
  4308. if (!filter || filter(item)) {
  4309. mappedItems.push(callback(item, id));
  4310. }
  4311. }
  4312. }
  4313. // order items
  4314. if (options && options.order) {
  4315. this._sort(mappedItems, options.order);
  4316. }
  4317. return mappedItems;
  4318. };
  4319. /**
  4320. * Filter the fields of an item
  4321. * @param {Object} item
  4322. * @param {String[]} fields Field names
  4323. * @return {Object} filteredItem
  4324. * @private
  4325. */
  4326. DataSet.prototype._filterFields = function (item, fields) {
  4327. var filteredItem = {};
  4328. for (var field in item) {
  4329. if (item.hasOwnProperty(field) && (fields.indexOf(field) != -1)) {
  4330. filteredItem[field] = item[field];
  4331. }
  4332. }
  4333. return filteredItem;
  4334. };
  4335. /**
  4336. * Sort the provided array with items
  4337. * @param {Object[]} items
  4338. * @param {String | function} order A field name or custom sort function.
  4339. * @private
  4340. */
  4341. DataSet.prototype._sort = function (items, order) {
  4342. if (util.isString(order)) {
  4343. // order by provided field name
  4344. var name = order; // field name
  4345. items.sort(function (a, b) {
  4346. var av = a[name];
  4347. var bv = b[name];
  4348. return (av > bv) ? 1 : ((av < bv) ? -1 : 0);
  4349. });
  4350. }
  4351. else if (typeof order === 'function') {
  4352. // order by sort function
  4353. items.sort(order);
  4354. }
  4355. // TODO: extend order by an Object {field:String, direction:String}
  4356. // where direction can be 'asc' or 'desc'
  4357. else {
  4358. throw new TypeError('Order must be a function or a string');
  4359. }
  4360. };
  4361. /**
  4362. * Remove an object by pointer or by id
  4363. * @param {String | Number | Object | Array} id Object or id, or an array with
  4364. * objects or ids to be removed
  4365. * @param {String} [senderId] Optional sender id
  4366. * @return {Array} removedIds
  4367. */
  4368. DataSet.prototype.remove = function (id, senderId) {
  4369. var removedIds = [],
  4370. i, len, removedId;
  4371. if (id instanceof Array) {
  4372. for (i = 0, len = id.length; i < len; i++) {
  4373. removedId = this._remove(id[i]);
  4374. if (removedId != null) {
  4375. removedIds.push(removedId);
  4376. }
  4377. }
  4378. }
  4379. else {
  4380. removedId = this._remove(id);
  4381. if (removedId != null) {
  4382. removedIds.push(removedId);
  4383. }
  4384. }
  4385. if (removedIds.length) {
  4386. this._trigger('remove', {items: removedIds}, senderId);
  4387. }
  4388. return removedIds;
  4389. };
  4390. /**
  4391. * Remove an item by its id
  4392. * @param {Number | String | Object} id id or item
  4393. * @returns {Number | String | null} id
  4394. * @private
  4395. */
  4396. DataSet.prototype._remove = function (id) {
  4397. if (util.isNumber(id) || util.isString(id)) {
  4398. if (this.data[id]) {
  4399. delete this.data[id];
  4400. delete this.internalIds[id];
  4401. return id;
  4402. }
  4403. }
  4404. else if (id instanceof Object) {
  4405. var itemId = id[this.fieldId];
  4406. if (itemId && this.data[itemId]) {
  4407. delete this.data[itemId];
  4408. delete this.internalIds[itemId];
  4409. return itemId;
  4410. }
  4411. }
  4412. return null;
  4413. };
  4414. /**
  4415. * Clear the data
  4416. * @param {String} [senderId] Optional sender id
  4417. * @return {Array} removedIds The ids of all removed items
  4418. */
  4419. DataSet.prototype.clear = function (senderId) {
  4420. var ids = Object.keys(this.data);
  4421. this.data = {};
  4422. this.internalIds = {};
  4423. this._trigger('remove', {items: ids}, senderId);
  4424. return ids;
  4425. };
  4426. /**
  4427. * Find the item with maximum value of a specified field
  4428. * @param {String} field
  4429. * @return {Object | null} item Item containing max value, or null if no items
  4430. */
  4431. DataSet.prototype.max = function (field) {
  4432. var data = this.data,
  4433. max = null,
  4434. maxField = null;
  4435. for (var id in data) {
  4436. if (data.hasOwnProperty(id)) {
  4437. var item = data[id];
  4438. var itemField = item[field];
  4439. if (itemField != null && (!max || itemField > maxField)) {
  4440. max = item;
  4441. maxField = itemField;
  4442. }
  4443. }
  4444. }
  4445. return max;
  4446. };
  4447. /**
  4448. * Find the item with minimum value of a specified field
  4449. * @param {String} field
  4450. * @return {Object | null} item Item containing max value, or null if no items
  4451. */
  4452. DataSet.prototype.min = function (field) {
  4453. var data = this.data,
  4454. min = null,
  4455. minField = null;
  4456. for (var id in data) {
  4457. if (data.hasOwnProperty(id)) {
  4458. var item = data[id];
  4459. var itemField = item[field];
  4460. if (itemField != null && (!min || itemField < minField)) {
  4461. min = item;
  4462. minField = itemField;
  4463. }
  4464. }
  4465. }
  4466. return min;
  4467. };
  4468. /**
  4469. * Find all distinct values of a specified field
  4470. * @param {String} field
  4471. * @return {Array} values Array containing all distinct values. If the data
  4472. * items do not contain the specified field, an array
  4473. * containing a single value undefined is returned.
  4474. * The returned array is unordered.
  4475. */
  4476. DataSet.prototype.distinct = function (field) {
  4477. var data = this.data,
  4478. values = [],
  4479. fieldType = this.options.convert[field],
  4480. count = 0;
  4481. for (var prop in data) {
  4482. if (data.hasOwnProperty(prop)) {
  4483. var item = data[prop];
  4484. var value = util.convert(item[field], fieldType);
  4485. var exists = false;
  4486. for (var i = 0; i < count; i++) {
  4487. if (values[i] == value) {
  4488. exists = true;
  4489. break;
  4490. }
  4491. }
  4492. if (!exists) {
  4493. values[count] = value;
  4494. count++;
  4495. }
  4496. }
  4497. }
  4498. return values;
  4499. };
  4500. /**
  4501. * Add a single item. Will fail when an item with the same id already exists.
  4502. * @param {Object} item
  4503. * @return {String} id
  4504. * @private
  4505. */
  4506. DataSet.prototype._addItem = function (item) {
  4507. var id = item[this.fieldId];
  4508. if (id != undefined) {
  4509. // check whether this id is already taken
  4510. if (this.data[id]) {
  4511. // item already exists
  4512. throw new Error('Cannot add item: item with id ' + id + ' already exists');
  4513. }
  4514. }
  4515. else {
  4516. // generate an id
  4517. id = util.randomUUID();
  4518. item[this.fieldId] = id;
  4519. this.internalIds[id] = item;
  4520. }
  4521. var d = {};
  4522. for (var field in item) {
  4523. if (item.hasOwnProperty(field)) {
  4524. var fieldType = this.convert[field]; // type may be undefined
  4525. d[field] = util.convert(item[field], fieldType);
  4526. }
  4527. }
  4528. this.data[id] = d;
  4529. return id;
  4530. };
  4531. /**
  4532. * Get an item. Fields can be converted to a specific type
  4533. * @param {String} id
  4534. * @param {Object.<String, String>} [convert] field types to convert
  4535. * @return {Object | null} item
  4536. * @private
  4537. */
  4538. DataSet.prototype._getItem = function (id, convert) {
  4539. var field, value;
  4540. // get the item from the dataset
  4541. var raw = this.data[id];
  4542. if (!raw) {
  4543. return null;
  4544. }
  4545. // convert the items field types
  4546. var converted = {},
  4547. fieldId = this.fieldId,
  4548. internalIds = this.internalIds;
  4549. if (convert) {
  4550. for (field in raw) {
  4551. if (raw.hasOwnProperty(field)) {
  4552. value = raw[field];
  4553. // output all fields, except internal ids
  4554. if ((field != fieldId) || !(value in internalIds)) {
  4555. converted[field] = util.convert(value, convert[field]);
  4556. }
  4557. }
  4558. }
  4559. }
  4560. else {
  4561. // no field types specified, no converting needed
  4562. for (field in raw) {
  4563. if (raw.hasOwnProperty(field)) {
  4564. value = raw[field];
  4565. // output all fields, except internal ids
  4566. if ((field != fieldId) || !(value in internalIds)) {
  4567. converted[field] = value;
  4568. }
  4569. }
  4570. }
  4571. }
  4572. return converted;
  4573. };
  4574. /**
  4575. * Update a single item: merge with existing item.
  4576. * Will fail when the item has no id, or when there does not exist an item
  4577. * with the same id.
  4578. * @param {Object} item
  4579. * @return {String} id
  4580. * @private
  4581. */
  4582. DataSet.prototype._updateItem = function (item) {
  4583. var id = item[this.fieldId];
  4584. if (id == undefined) {
  4585. throw new Error('Cannot update item: item has no id (item: ' + JSON.stringify(item) + ')');
  4586. }
  4587. var d = this.data[id];
  4588. if (!d) {
  4589. // item doesn't exist
  4590. throw new Error('Cannot update item: no item with id ' + id + ' found');
  4591. }
  4592. // merge with current item
  4593. for (var field in item) {
  4594. if (item.hasOwnProperty(field)) {
  4595. var fieldType = this.convert[field]; // type may be undefined
  4596. d[field] = util.convert(item[field], fieldType);
  4597. }
  4598. }
  4599. return id;
  4600. };
  4601. /**
  4602. * Get an array with the column names of a Google DataTable
  4603. * @param {DataTable} dataTable
  4604. * @return {String[]} columnNames
  4605. * @private
  4606. */
  4607. DataSet.prototype._getColumnNames = function (dataTable) {
  4608. var columns = [];
  4609. for (var col = 0, cols = dataTable.getNumberOfColumns(); col < cols; col++) {
  4610. columns[col] = dataTable.getColumnId(col) || dataTable.getColumnLabel(col);
  4611. }
  4612. return columns;
  4613. };
  4614. /**
  4615. * Append an item as a row to the dataTable
  4616. * @param dataTable
  4617. * @param columns
  4618. * @param item
  4619. * @private
  4620. */
  4621. DataSet.prototype._appendRow = function (dataTable, columns, item) {
  4622. var row = dataTable.addRow();
  4623. for (var col = 0, cols = columns.length; col < cols; col++) {
  4624. var field = columns[col];
  4625. dataTable.setValue(row, col, item[field]);
  4626. }
  4627. };
  4628. /**
  4629. * DataView
  4630. *
  4631. * a dataview offers a filtered view on a dataset or an other dataview.
  4632. *
  4633. * @param {DataSet | DataView} data
  4634. * @param {Object} [options] Available options: see method get
  4635. *
  4636. * @constructor DataView
  4637. */
  4638. function DataView (data, options) {
  4639. this.id = util.randomUUID();
  4640. this.data = null;
  4641. this.ids = {}; // ids of the items currently in memory (just contains a boolean true)
  4642. this.options = options || {};
  4643. this.fieldId = 'id'; // name of the field containing id
  4644. this.subscribers = {}; // event subscribers
  4645. var me = this;
  4646. this.listener = function () {
  4647. me._onEvent.apply(me, arguments);
  4648. };
  4649. this.setData(data);
  4650. }
  4651. // TODO: implement a function .config() to dynamically update things like configured filter
  4652. // and trigger changes accordingly
  4653. /**
  4654. * Set a data source for the view
  4655. * @param {DataSet | DataView} data
  4656. */
  4657. DataView.prototype.setData = function (data) {
  4658. var ids, dataItems, i, len;
  4659. if (this.data) {
  4660. // unsubscribe from current dataset
  4661. if (this.data.unsubscribe) {
  4662. this.data.unsubscribe('*', this.listener);
  4663. }
  4664. // trigger a remove of all items in memory
  4665. ids = [];
  4666. for (var id in this.ids) {
  4667. if (this.ids.hasOwnProperty(id)) {
  4668. ids.push(id);
  4669. }
  4670. }
  4671. this.ids = {};
  4672. this._trigger('remove', {items: ids});
  4673. }
  4674. this.data = data;
  4675. if (this.data) {
  4676. // update fieldId
  4677. this.fieldId = this.options.fieldId ||
  4678. (this.data && this.data.options && this.data.options.fieldId) ||
  4679. 'id';
  4680. // trigger an add of all added items
  4681. ids = this.data.getIds({filter: this.options && this.options.filter});
  4682. for (i = 0, len = ids.length; i < len; i++) {
  4683. id = ids[i];
  4684. this.ids[id] = true;
  4685. }
  4686. this._trigger('add', {items: ids});
  4687. // subscribe to new dataset
  4688. if (this.data.subscribe) {
  4689. this.data.subscribe('*', this.listener);
  4690. }
  4691. }
  4692. };
  4693. /**
  4694. * Get data from the data view
  4695. *
  4696. * Usage:
  4697. *
  4698. * get()
  4699. * get(options: Object)
  4700. * get(options: Object, data: Array | DataTable)
  4701. *
  4702. * get(id: Number)
  4703. * get(id: Number, options: Object)
  4704. * get(id: Number, options: Object, data: Array | DataTable)
  4705. *
  4706. * get(ids: Number[])
  4707. * get(ids: Number[], options: Object)
  4708. * get(ids: Number[], options: Object, data: Array | DataTable)
  4709. *
  4710. * Where:
  4711. *
  4712. * {Number | String} id The id of an item
  4713. * {Number[] | String{}} ids An array with ids of items
  4714. * {Object} options An Object with options. Available options:
  4715. * {String} [type] Type of data to be returned. Can
  4716. * be 'DataTable' or 'Array' (default)
  4717. * {Object.<String, String>} [convert]
  4718. * {String[]} [fields] field names to be returned
  4719. * {function} [filter] filter items
  4720. * {String | function} [order] Order the items by
  4721. * a field name or custom sort function.
  4722. * {Array | DataTable} [data] If provided, items will be appended to this
  4723. * array or table. Required in case of Google
  4724. * DataTable.
  4725. * @param args
  4726. */
  4727. DataView.prototype.get = function (args) {
  4728. var me = this;
  4729. // parse the arguments
  4730. var ids, options, data;
  4731. var firstType = util.getType(arguments[0]);
  4732. if (firstType == 'String' || firstType == 'Number' || firstType == 'Array') {
  4733. // get(id(s) [, options] [, data])
  4734. ids = arguments[0]; // can be a single id or an array with ids
  4735. options = arguments[1];
  4736. data = arguments[2];
  4737. }
  4738. else {
  4739. // get([, options] [, data])
  4740. options = arguments[0];
  4741. data = arguments[1];
  4742. }
  4743. // extend the options with the default options and provided options
  4744. var viewOptions = util.extend({}, this.options, options);
  4745. // create a combined filter method when needed
  4746. if (this.options.filter && options && options.filter) {
  4747. viewOptions.filter = function (item) {
  4748. return me.options.filter(item) && options.filter(item);
  4749. }
  4750. }
  4751. // build up the call to the linked data set
  4752. var getArguments = [];
  4753. if (ids != undefined) {
  4754. getArguments.push(ids);
  4755. }
  4756. getArguments.push(viewOptions);
  4757. getArguments.push(data);
  4758. return this.data && this.data.get.apply(this.data, getArguments);
  4759. };
  4760. /**
  4761. * Get ids of all items or from a filtered set of items.
  4762. * @param {Object} [options] An Object with options. Available options:
  4763. * {function} [filter] filter items
  4764. * {String | function} [order] Order the items by
  4765. * a field name or custom sort function.
  4766. * @return {Array} ids
  4767. */
  4768. DataView.prototype.getIds = function (options) {
  4769. var ids;
  4770. if (this.data) {
  4771. var defaultFilter = this.options.filter;
  4772. var filter;
  4773. if (options && options.filter) {
  4774. if (defaultFilter) {
  4775. filter = function (item) {
  4776. return defaultFilter(item) && options.filter(item);
  4777. }
  4778. }
  4779. else {
  4780. filter = options.filter;
  4781. }
  4782. }
  4783. else {
  4784. filter = defaultFilter;
  4785. }
  4786. ids = this.data.getIds({
  4787. filter: filter,
  4788. order: options && options.order
  4789. });
  4790. }
  4791. else {
  4792. ids = [];
  4793. }
  4794. return ids;
  4795. };
  4796. /**
  4797. * Event listener. Will propagate all events from the connected data set to
  4798. * the subscribers of the DataView, but will filter the items and only trigger
  4799. * when there are changes in the filtered data set.
  4800. * @param {String} event
  4801. * @param {Object | null} params
  4802. * @param {String} senderId
  4803. * @private
  4804. */
  4805. DataView.prototype._onEvent = function (event, params, senderId) {
  4806. var i, len, id, item,
  4807. ids = params && params.items,
  4808. data = this.data,
  4809. added = [],
  4810. updated = [],
  4811. removed = [];
  4812. if (ids && data) {
  4813. switch (event) {
  4814. case 'add':
  4815. // filter the ids of the added items
  4816. for (i = 0, len = ids.length; i < len; i++) {
  4817. id = ids[i];
  4818. item = this.get(id);
  4819. if (item) {
  4820. this.ids[id] = true;
  4821. added.push(id);
  4822. }
  4823. }
  4824. break;
  4825. case 'update':
  4826. // determine the event from the views viewpoint: an updated
  4827. // item can be added, updated, or removed from this view.
  4828. for (i = 0, len = ids.length; i < len; i++) {
  4829. id = ids[i];
  4830. item = this.get(id);
  4831. if (item) {
  4832. if (this.ids[id]) {
  4833. updated.push(id);
  4834. }
  4835. else {
  4836. this.ids[id] = true;
  4837. added.push(id);
  4838. }
  4839. }
  4840. else {
  4841. if (this.ids[id]) {
  4842. delete this.ids[id];
  4843. removed.push(id);
  4844. }
  4845. else {
  4846. // nothing interesting for me :-(
  4847. }
  4848. }
  4849. }
  4850. break;
  4851. case 'remove':
  4852. // filter the ids of the removed items
  4853. for (i = 0, len = ids.length; i < len; i++) {
  4854. id = ids[i];
  4855. if (this.ids[id]) {
  4856. delete this.ids[id];
  4857. removed.push(id);
  4858. }
  4859. }
  4860. break;
  4861. }
  4862. if (added.length) {
  4863. this._trigger('add', {items: added}, senderId);
  4864. }
  4865. if (updated.length) {
  4866. this._trigger('update', {items: updated}, senderId);
  4867. }
  4868. if (removed.length) {
  4869. this._trigger('remove', {items: removed}, senderId);
  4870. }
  4871. }
  4872. };
  4873. // copy subscription functionality from DataSet
  4874. DataView.prototype.subscribe = DataSet.prototype.subscribe;
  4875. DataView.prototype.unsubscribe = DataSet.prototype.unsubscribe;
  4876. DataView.prototype._trigger = DataSet.prototype._trigger;
  4877. /**
  4878. * @constructor TimeStep
  4879. * The class TimeStep is an iterator for dates. You provide a start date and an
  4880. * end date. The class itself determines the best scale (step size) based on the
  4881. * provided start Date, end Date, and minimumStep.
  4882. *
  4883. * If minimumStep is provided, the step size is chosen as close as possible
  4884. * to the minimumStep but larger than minimumStep. If minimumStep is not
  4885. * provided, the scale is set to 1 DAY.
  4886. * The minimumStep should correspond with the onscreen size of about 6 characters
  4887. *
  4888. * Alternatively, you can set a scale by hand.
  4889. * After creation, you can initialize the class by executing first(). Then you
  4890. * can iterate from the start date to the end date via next(). You can check if
  4891. * the end date is reached with the function hasNext(). After each step, you can
  4892. * retrieve the current date via getCurrent().
  4893. * The TimeStep has scales ranging from milliseconds, seconds, minutes, hours,
  4894. * days, to years.
  4895. *
  4896. * Version: 1.2
  4897. *
  4898. * @param {Date} [start] The start date, for example new Date(2010, 9, 21)
  4899. * or new Date(2010, 9, 21, 23, 45, 00)
  4900. * @param {Date} [end] The end date
  4901. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  4902. */
  4903. TimeStep = function(start, end, minimumStep) {
  4904. // variables
  4905. this.current = new Date();
  4906. this._start = new Date();
  4907. this._end = new Date();
  4908. this.autoScale = true;
  4909. this.scale = TimeStep.SCALE.DAY;
  4910. this.step = 1;
  4911. // initialize the range
  4912. this.setRange(start, end, minimumStep);
  4913. };
  4914. /// enum scale
  4915. TimeStep.SCALE = {
  4916. MILLISECOND: 1,
  4917. SECOND: 2,
  4918. MINUTE: 3,
  4919. HOUR: 4,
  4920. DAY: 5,
  4921. WEEKDAY: 6,
  4922. MONTH: 7,
  4923. YEAR: 8
  4924. };
  4925. /**
  4926. * Set a new range
  4927. * If minimumStep is provided, the step size is chosen as close as possible
  4928. * to the minimumStep but larger than minimumStep. If minimumStep is not
  4929. * provided, the scale is set to 1 DAY.
  4930. * The minimumStep should correspond with the onscreen size of about 6 characters
  4931. * @param {Date} [start] The start date and time.
  4932. * @param {Date} [end] The end date and time.
  4933. * @param {int} [minimumStep] Optional. Minimum step size in milliseconds
  4934. */
  4935. TimeStep.prototype.setRange = function(start, end, minimumStep) {
  4936. if (!(start instanceof Date) || !(end instanceof Date)) {
  4937. throw "No legal start or end date in method setRange";
  4938. }
  4939. this._start = (start != undefined) ? new Date(start.valueOf()) : new Date();
  4940. this._end = (end != undefined) ? new Date(end.valueOf()) : new Date();
  4941. if (this.autoScale) {
  4942. this.setMinimumStep(minimumStep);
  4943. }
  4944. };
  4945. /**
  4946. * Set the range iterator to the start date.
  4947. */
  4948. TimeStep.prototype.first = function() {
  4949. this.current = new Date(this._start.valueOf());
  4950. this.roundToMinor();
  4951. };
  4952. /**
  4953. * Round the current date to the first minor date value
  4954. * This must be executed once when the current date is set to start Date
  4955. */
  4956. TimeStep.prototype.roundToMinor = function() {
  4957. // round to floor
  4958. // IMPORTANT: we have no breaks in this switch! (this is no bug)
  4959. //noinspection FallthroughInSwitchStatementJS
  4960. switch (this.scale) {
  4961. case TimeStep.SCALE.YEAR:
  4962. this.current.setFullYear(this.step * Math.floor(this.current.getFullYear() / this.step));
  4963. this.current.setMonth(0);
  4964. case TimeStep.SCALE.MONTH: this.current.setDate(1);
  4965. case TimeStep.SCALE.DAY: // intentional fall through
  4966. case TimeStep.SCALE.WEEKDAY: this.current.setHours(0);
  4967. case TimeStep.SCALE.HOUR: this.current.setMinutes(0);
  4968. case TimeStep.SCALE.MINUTE: this.current.setSeconds(0);
  4969. case TimeStep.SCALE.SECOND: this.current.setMilliseconds(0);
  4970. //case TimeStep.SCALE.MILLISECOND: // nothing to do for milliseconds
  4971. }
  4972. if (this.step != 1) {
  4973. // round down to the first minor value that is a multiple of the current step size
  4974. switch (this.scale) {
  4975. case TimeStep.SCALE.MILLISECOND: this.current.setMilliseconds(this.current.getMilliseconds() - this.current.getMilliseconds() % this.step); break;
  4976. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() - this.current.getSeconds() % this.step); break;
  4977. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() - this.current.getMinutes() % this.step); break;
  4978. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() - this.current.getHours() % this.step); break;
  4979. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  4980. case TimeStep.SCALE.DAY: this.current.setDate((this.current.getDate()-1) - (this.current.getDate()-1) % this.step + 1); break;
  4981. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() - this.current.getMonth() % this.step); break;
  4982. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() - this.current.getFullYear() % this.step); break;
  4983. default: break;
  4984. }
  4985. }
  4986. };
  4987. /**
  4988. * Check if the there is a next step
  4989. * @return {boolean} true if the current date has not passed the end date
  4990. */
  4991. TimeStep.prototype.hasNext = function () {
  4992. return (this.current.valueOf() <= this._end.valueOf());
  4993. };
  4994. /**
  4995. * Do the next step
  4996. */
  4997. TimeStep.prototype.next = function() {
  4998. var prev = this.current.valueOf();
  4999. // Two cases, needed to prevent issues with switching daylight savings
  5000. // (end of March and end of October)
  5001. if (this.current.getMonth() < 6) {
  5002. switch (this.scale) {
  5003. case TimeStep.SCALE.MILLISECOND:
  5004. this.current = new Date(this.current.valueOf() + this.step); break;
  5005. case TimeStep.SCALE.SECOND: this.current = new Date(this.current.valueOf() + this.step * 1000); break;
  5006. case TimeStep.SCALE.MINUTE: this.current = new Date(this.current.valueOf() + this.step * 1000 * 60); break;
  5007. case TimeStep.SCALE.HOUR:
  5008. this.current = new Date(this.current.valueOf() + this.step * 1000 * 60 * 60);
  5009. // in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...)
  5010. var h = this.current.getHours();
  5011. this.current.setHours(h - (h % this.step));
  5012. break;
  5013. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  5014. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  5015. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  5016. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  5017. default: break;
  5018. }
  5019. }
  5020. else {
  5021. switch (this.scale) {
  5022. case TimeStep.SCALE.MILLISECOND: this.current = new Date(this.current.valueOf() + this.step); break;
  5023. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() + this.step); break;
  5024. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() + this.step); break;
  5025. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() + this.step); break;
  5026. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  5027. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  5028. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  5029. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  5030. default: break;
  5031. }
  5032. }
  5033. if (this.step != 1) {
  5034. // round down to the correct major value
  5035. switch (this.scale) {
  5036. case TimeStep.SCALE.MILLISECOND: if(this.current.getMilliseconds() < this.step) this.current.setMilliseconds(0); break;
  5037. case TimeStep.SCALE.SECOND: if(this.current.getSeconds() < this.step) this.current.setSeconds(0); break;
  5038. case TimeStep.SCALE.MINUTE: if(this.current.getMinutes() < this.step) this.current.setMinutes(0); break;
  5039. case TimeStep.SCALE.HOUR: if(this.current.getHours() < this.step) this.current.setHours(0); break;
  5040. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  5041. case TimeStep.SCALE.DAY: if(this.current.getDate() < this.step+1) this.current.setDate(1); break;
  5042. case TimeStep.SCALE.MONTH: if(this.current.getMonth() < this.step) this.current.setMonth(0); break;
  5043. case TimeStep.SCALE.YEAR: break; // nothing to do for year
  5044. default: break;
  5045. }
  5046. }
  5047. // safety mechanism: if current time is still unchanged, move to the end
  5048. if (this.current.valueOf() == prev) {
  5049. this.current = new Date(this._end.valueOf());
  5050. }
  5051. };
  5052. /**
  5053. * Get the current datetime
  5054. * @return {Date} current The current date
  5055. */
  5056. TimeStep.prototype.getCurrent = function() {
  5057. return this.current;
  5058. };
  5059. /**
  5060. * Set a custom scale. Autoscaling will be disabled.
  5061. * For example setScale(SCALE.MINUTES, 5) will result
  5062. * in minor steps of 5 minutes, and major steps of an hour.
  5063. *
  5064. * @param {TimeStep.SCALE} newScale
  5065. * A scale. Choose from SCALE.MILLISECOND,
  5066. * SCALE.SECOND, SCALE.MINUTE, SCALE.HOUR,
  5067. * SCALE.WEEKDAY, SCALE.DAY, SCALE.MONTH,
  5068. * SCALE.YEAR.
  5069. * @param {Number} newStep A step size, by default 1. Choose for
  5070. * example 1, 2, 5, or 10.
  5071. */
  5072. TimeStep.prototype.setScale = function(newScale, newStep) {
  5073. this.scale = newScale;
  5074. if (newStep > 0) {
  5075. this.step = newStep;
  5076. }
  5077. this.autoScale = false;
  5078. };
  5079. /**
  5080. * Enable or disable autoscaling
  5081. * @param {boolean} enable If true, autoascaling is set true
  5082. */
  5083. TimeStep.prototype.setAutoScale = function (enable) {
  5084. this.autoScale = enable;
  5085. };
  5086. /**
  5087. * Automatically determine the scale that bests fits the provided minimum step
  5088. * @param {Number} [minimumStep] The minimum step size in milliseconds
  5089. */
  5090. TimeStep.prototype.setMinimumStep = function(minimumStep) {
  5091. if (minimumStep == undefined) {
  5092. return;
  5093. }
  5094. var stepYear = (1000 * 60 * 60 * 24 * 30 * 12);
  5095. var stepMonth = (1000 * 60 * 60 * 24 * 30);
  5096. var stepDay = (1000 * 60 * 60 * 24);
  5097. var stepHour = (1000 * 60 * 60);
  5098. var stepMinute = (1000 * 60);
  5099. var stepSecond = (1000);
  5100. var stepMillisecond= (1);
  5101. // find the smallest step that is larger than the provided minimumStep
  5102. if (stepYear*1000 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1000;}
  5103. if (stepYear*500 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 500;}
  5104. if (stepYear*100 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 100;}
  5105. if (stepYear*50 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 50;}
  5106. if (stepYear*10 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 10;}
  5107. if (stepYear*5 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 5;}
  5108. if (stepYear > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1;}
  5109. if (stepMonth*3 > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 3;}
  5110. if (stepMonth > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 1;}
  5111. if (stepDay*5 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 5;}
  5112. if (stepDay*2 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 2;}
  5113. if (stepDay > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 1;}
  5114. if (stepDay/2 > minimumStep) {this.scale = TimeStep.SCALE.WEEKDAY; this.step = 1;}
  5115. if (stepHour*4 > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 4;}
  5116. if (stepHour > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 1;}
  5117. if (stepMinute*15 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 15;}
  5118. if (stepMinute*10 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 10;}
  5119. if (stepMinute*5 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 5;}
  5120. if (stepMinute > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 1;}
  5121. if (stepSecond*15 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 15;}
  5122. if (stepSecond*10 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 10;}
  5123. if (stepSecond*5 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 5;}
  5124. if (stepSecond > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 1;}
  5125. if (stepMillisecond*200 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 200;}
  5126. if (stepMillisecond*100 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 100;}
  5127. if (stepMillisecond*50 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 50;}
  5128. if (stepMillisecond*10 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 10;}
  5129. if (stepMillisecond*5 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 5;}
  5130. if (stepMillisecond > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 1;}
  5131. };
  5132. /**
  5133. * Snap a date to a rounded value. The snap intervals are dependent on the
  5134. * current scale and step.
  5135. * @param {Date} date the date to be snapped
  5136. */
  5137. TimeStep.prototype.snap = function(date) {
  5138. if (this.scale == TimeStep.SCALE.YEAR) {
  5139. var year = date.getFullYear() + Math.round(date.getMonth() / 12);
  5140. date.setFullYear(Math.round(year / this.step) * this.step);
  5141. date.setMonth(0);
  5142. date.setDate(0);
  5143. date.setHours(0);
  5144. date.setMinutes(0);
  5145. date.setSeconds(0);
  5146. date.setMilliseconds(0);
  5147. }
  5148. else if (this.scale == TimeStep.SCALE.MONTH) {
  5149. if (date.getDate() > 15) {
  5150. date.setDate(1);
  5151. date.setMonth(date.getMonth() + 1);
  5152. // important: first set Date to 1, after that change the month.
  5153. }
  5154. else {
  5155. date.setDate(1);
  5156. }
  5157. date.setHours(0);
  5158. date.setMinutes(0);
  5159. date.setSeconds(0);
  5160. date.setMilliseconds(0);
  5161. }
  5162. else if (this.scale == TimeStep.SCALE.DAY ||
  5163. this.scale == TimeStep.SCALE.WEEKDAY) {
  5164. //noinspection FallthroughInSwitchStatementJS
  5165. switch (this.step) {
  5166. case 5:
  5167. case 2:
  5168. date.setHours(Math.round(date.getHours() / 24) * 24); break;
  5169. default:
  5170. date.setHours(Math.round(date.getHours() / 12) * 12); break;
  5171. }
  5172. date.setMinutes(0);
  5173. date.setSeconds(0);
  5174. date.setMilliseconds(0);
  5175. }
  5176. else if (this.scale == TimeStep.SCALE.HOUR) {
  5177. switch (this.step) {
  5178. case 4:
  5179. date.setMinutes(Math.round(date.getMinutes() / 60) * 60); break;
  5180. default:
  5181. date.setMinutes(Math.round(date.getMinutes() / 30) * 30); break;
  5182. }
  5183. date.setSeconds(0);
  5184. date.setMilliseconds(0);
  5185. } else if (this.scale == TimeStep.SCALE.MINUTE) {
  5186. //noinspection FallthroughInSwitchStatementJS
  5187. switch (this.step) {
  5188. case 15:
  5189. case 10:
  5190. date.setMinutes(Math.round(date.getMinutes() / 5) * 5);
  5191. date.setSeconds(0);
  5192. break;
  5193. case 5:
  5194. date.setSeconds(Math.round(date.getSeconds() / 60) * 60); break;
  5195. default:
  5196. date.setSeconds(Math.round(date.getSeconds() / 30) * 30); break;
  5197. }
  5198. date.setMilliseconds(0);
  5199. }
  5200. else if (this.scale == TimeStep.SCALE.SECOND) {
  5201. //noinspection FallthroughInSwitchStatementJS
  5202. switch (this.step) {
  5203. case 15:
  5204. case 10:
  5205. date.setSeconds(Math.round(date.getSeconds() / 5) * 5);
  5206. date.setMilliseconds(0);
  5207. break;
  5208. case 5:
  5209. date.setMilliseconds(Math.round(date.getMilliseconds() / 1000) * 1000); break;
  5210. default:
  5211. date.setMilliseconds(Math.round(date.getMilliseconds() / 500) * 500); break;
  5212. }
  5213. }
  5214. else if (this.scale == TimeStep.SCALE.MILLISECOND) {
  5215. var step = this.step > 5 ? this.step / 2 : 1;
  5216. date.setMilliseconds(Math.round(date.getMilliseconds() / step) * step);
  5217. }
  5218. };
  5219. /**
  5220. * Check if the current value is a major value (for example when the step
  5221. * is DAY, a major value is each first day of the MONTH)
  5222. * @return {boolean} true if current date is major, else false.
  5223. */
  5224. TimeStep.prototype.isMajor = function() {
  5225. switch (this.scale) {
  5226. case TimeStep.SCALE.MILLISECOND:
  5227. return (this.current.getMilliseconds() == 0);
  5228. case TimeStep.SCALE.SECOND:
  5229. return (this.current.getSeconds() == 0);
  5230. case TimeStep.SCALE.MINUTE:
  5231. return (this.current.getHours() == 0) && (this.current.getMinutes() == 0);
  5232. // Note: this is no bug. Major label is equal for both minute and hour scale
  5233. case TimeStep.SCALE.HOUR:
  5234. return (this.current.getHours() == 0);
  5235. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  5236. case TimeStep.SCALE.DAY:
  5237. return (this.current.getDate() == 1);
  5238. case TimeStep.SCALE.MONTH:
  5239. return (this.current.getMonth() == 0);
  5240. case TimeStep.SCALE.YEAR:
  5241. return false;
  5242. default:
  5243. return false;
  5244. }
  5245. };
  5246. /**
  5247. * Returns formatted text for the minor axislabel, depending on the current
  5248. * date and the scale. For example when scale is MINUTE, the current time is
  5249. * formatted as "hh:mm".
  5250. * @param {Date} [date] custom date. if not provided, current date is taken
  5251. */
  5252. TimeStep.prototype.getLabelMinor = function(date) {
  5253. if (date == undefined) {
  5254. date = this.current;
  5255. }
  5256. switch (this.scale) {
  5257. case TimeStep.SCALE.MILLISECOND: return moment(date).format('SSS');
  5258. case TimeStep.SCALE.SECOND: return moment(date).format('s');
  5259. case TimeStep.SCALE.MINUTE: return moment(date).format('HH:mm');
  5260. case TimeStep.SCALE.HOUR: return moment(date).format('HH:mm');
  5261. case TimeStep.SCALE.WEEKDAY: return moment(date).format('ddd D');
  5262. case TimeStep.SCALE.DAY: return moment(date).format('D');
  5263. case TimeStep.SCALE.MONTH: return moment(date).format('MMM');
  5264. case TimeStep.SCALE.YEAR: return moment(date).format('YYYY');
  5265. default: return '';
  5266. }
  5267. };
  5268. /**
  5269. * Returns formatted text for the major axis label, depending on the current
  5270. * date and the scale. For example when scale is MINUTE, the major scale is
  5271. * hours, and the hour will be formatted as "hh".
  5272. * @param {Date} [date] custom date. if not provided, current date is taken
  5273. */
  5274. TimeStep.prototype.getLabelMajor = function(date) {
  5275. if (date == undefined) {
  5276. date = this.current;
  5277. }
  5278. //noinspection FallthroughInSwitchStatementJS
  5279. switch (this.scale) {
  5280. case TimeStep.SCALE.MILLISECOND:return moment(date).format('HH:mm:ss');
  5281. case TimeStep.SCALE.SECOND: return moment(date).format('D MMMM HH:mm');
  5282. case TimeStep.SCALE.MINUTE:
  5283. case TimeStep.SCALE.HOUR: return moment(date).format('ddd D MMMM');
  5284. case TimeStep.SCALE.WEEKDAY:
  5285. case TimeStep.SCALE.DAY: return moment(date).format('MMMM YYYY');
  5286. case TimeStep.SCALE.MONTH: return moment(date).format('YYYY');
  5287. case TimeStep.SCALE.YEAR: return '';
  5288. default: return '';
  5289. }
  5290. };
  5291. /**
  5292. * @constructor Stack
  5293. * Stacks items on top of each other.
  5294. * @param {ItemSet} parent
  5295. * @param {Object} [options]
  5296. */
  5297. function Stack (parent, options) {
  5298. this.parent = parent;
  5299. this.options = options || {};
  5300. this.defaultOptions = {
  5301. order: function (a, b) {
  5302. //return (b.width - a.width) || (a.left - b.left); // TODO: cleanup
  5303. // Order: ranges over non-ranges, ranged ordered by width, and
  5304. // lastly ordered by start.
  5305. if (a instanceof ItemRange) {
  5306. if (b instanceof ItemRange) {
  5307. var aInt = (a.data.end - a.data.start);
  5308. var bInt = (b.data.end - b.data.start);
  5309. return (aInt - bInt) || (a.data.start - b.data.start);
  5310. }
  5311. else {
  5312. return -1;
  5313. }
  5314. }
  5315. else {
  5316. if (b instanceof ItemRange) {
  5317. return 1;
  5318. }
  5319. else {
  5320. return (a.data.start - b.data.start);
  5321. }
  5322. }
  5323. },
  5324. margin: {
  5325. item: 10
  5326. }
  5327. };
  5328. this.ordered = []; // ordered items
  5329. }
  5330. /**
  5331. * Set options for the stack
  5332. * @param {Object} options Available options:
  5333. * {ItemSet} parent
  5334. * {Number} margin
  5335. * {function} order Stacking order
  5336. */
  5337. Stack.prototype.setOptions = function setOptions (options) {
  5338. util.extend(this.options, options);
  5339. // TODO: register on data changes at the connected parent itemset, and update the changed part only and immediately
  5340. };
  5341. /**
  5342. * Stack the items such that they don't overlap. The items will have a minimal
  5343. * distance equal to options.margin.item.
  5344. */
  5345. Stack.prototype.update = function update() {
  5346. this._order();
  5347. this._stack();
  5348. };
  5349. /**
  5350. * Order the items. The items are ordered by width first, and by left position
  5351. * second.
  5352. * If a custom order function has been provided via the options, then this will
  5353. * be used.
  5354. * @private
  5355. */
  5356. Stack.prototype._order = function _order () {
  5357. var items = this.parent.items;
  5358. if (!items) {
  5359. throw new Error('Cannot stack items: parent does not contain items');
  5360. }
  5361. // TODO: store the sorted items, to have less work later on
  5362. var ordered = [];
  5363. var index = 0;
  5364. // items is a map (no array)
  5365. util.forEach(items, function (item) {
  5366. if (item.visible) {
  5367. ordered[index] = item;
  5368. index++;
  5369. }
  5370. });
  5371. //if a customer stack order function exists, use it.
  5372. var order = this.options.order || this.defaultOptions.order;
  5373. if (!(typeof order === 'function')) {
  5374. throw new Error('Option order must be a function');
  5375. }
  5376. ordered.sort(order);
  5377. this.ordered = ordered;
  5378. };
  5379. /**
  5380. * Adjust vertical positions of the events such that they don't overlap each
  5381. * other.
  5382. * @private
  5383. */
  5384. Stack.prototype._stack = function _stack () {
  5385. var i,
  5386. iMax,
  5387. ordered = this.ordered,
  5388. options = this.options,
  5389. orientation = options.orientation || this.defaultOptions.orientation,
  5390. axisOnTop = (orientation == 'top'),
  5391. margin;
  5392. if (options.margin && options.margin.item !== undefined) {
  5393. margin = options.margin.item;
  5394. }
  5395. else {
  5396. margin = this.defaultOptions.margin.item
  5397. }
  5398. // calculate new, non-overlapping positions
  5399. for (i = 0, iMax = ordered.length; i < iMax; i++) {
  5400. var item = ordered[i];
  5401. var collidingItem = null;
  5402. do {
  5403. // TODO: optimize checking for overlap. when there is a gap without items,
  5404. // you only need to check for items from the next item on, not from zero
  5405. collidingItem = this.checkOverlap(ordered, i, 0, i - 1, margin);
  5406. if (collidingItem != null) {
  5407. // There is a collision. Reposition the event above the colliding element
  5408. if (axisOnTop) {
  5409. item.top = collidingItem.top + collidingItem.height + margin;
  5410. }
  5411. else {
  5412. item.top = collidingItem.top - item.height - margin;
  5413. }
  5414. }
  5415. } while (collidingItem);
  5416. }
  5417. };
  5418. /**
  5419. * Check if the destiny position of given item overlaps with any
  5420. * of the other items from index itemStart to itemEnd.
  5421. * @param {Array} items Array with items
  5422. * @param {int} itemIndex Number of the item to be checked for overlap
  5423. * @param {int} itemStart First item to be checked.
  5424. * @param {int} itemEnd Last item to be checked.
  5425. * @return {Object | null} colliding item, or undefined when no collisions
  5426. * @param {Number} margin A minimum required margin.
  5427. * If margin is provided, the two items will be
  5428. * marked colliding when they overlap or
  5429. * when the margin between the two is smaller than
  5430. * the requested margin.
  5431. */
  5432. Stack.prototype.checkOverlap = function checkOverlap (items, itemIndex,
  5433. itemStart, itemEnd, margin) {
  5434. var collision = this.collision;
  5435. // we loop from end to start, as we suppose that the chance of a
  5436. // collision is larger for items at the end, so check these first.
  5437. var a = items[itemIndex];
  5438. for (var i = itemEnd; i >= itemStart; i--) {
  5439. var b = items[i];
  5440. if (collision(a, b, margin)) {
  5441. if (i != itemIndex) {
  5442. return b;
  5443. }
  5444. }
  5445. }
  5446. return null;
  5447. };
  5448. /**
  5449. * Test if the two provided items collide
  5450. * The items must have parameters left, width, top, and height.
  5451. * @param {Component} a The first item
  5452. * @param {Component} b The second item
  5453. * @param {Number} margin A minimum required margin.
  5454. * If margin is provided, the two items will be
  5455. * marked colliding when they overlap or
  5456. * when the margin between the two is smaller than
  5457. * the requested margin.
  5458. * @return {boolean} true if a and b collide, else false
  5459. */
  5460. Stack.prototype.collision = function collision (a, b, margin) {
  5461. return ((a.left - margin) < (b.left + b.getWidth()) &&
  5462. (a.left + a.getWidth() + margin) > b.left &&
  5463. (a.top - margin) < (b.top + b.height) &&
  5464. (a.top + a.height + margin) > b.top);
  5465. };
  5466. /**
  5467. * @constructor Range
  5468. * A Range controls a numeric range with a start and end value.
  5469. * The Range adjusts the range based on mouse events or programmatic changes,
  5470. * and triggers events when the range is changing or has been changed.
  5471. * @param {Object} [options] See description at Range.setOptions
  5472. * @extends Controller
  5473. */
  5474. function Range(options) {
  5475. this.id = util.randomUUID();
  5476. this.start = null; // Number
  5477. this.end = null; // Number
  5478. this.options = options || {};
  5479. this.setOptions(options);
  5480. }
  5481. /**
  5482. * Set options for the range controller
  5483. * @param {Object} options Available options:
  5484. * {Number} min Minimum value for start
  5485. * {Number} max Maximum value for end
  5486. * {Number} zoomMin Set a minimum value for
  5487. * (end - start).
  5488. * {Number} zoomMax Set a maximum value for
  5489. * (end - start).
  5490. */
  5491. Range.prototype.setOptions = function (options) {
  5492. util.extend(this.options, options);
  5493. // re-apply range with new limitations
  5494. if (this.start !== null && this.end !== null) {
  5495. this.setRange(this.start, this.end);
  5496. }
  5497. };
  5498. /**
  5499. * Test whether direction has a valid value
  5500. * @param {String} direction 'horizontal' or 'vertical'
  5501. */
  5502. function validateDirection (direction) {
  5503. if (direction != 'horizontal' && direction != 'vertical') {
  5504. throw new TypeError('Unknown direction "' + direction + '". ' +
  5505. 'Choose "horizontal" or "vertical".');
  5506. }
  5507. }
  5508. /**
  5509. * Add listeners for mouse and touch events to the component
  5510. * @param {Component} component
  5511. * @param {String} event Available events: 'move', 'zoom'
  5512. * @param {String} direction Available directions: 'horizontal', 'vertical'
  5513. */
  5514. Range.prototype.subscribe = function (component, event, direction) {
  5515. var me = this;
  5516. if (event == 'move') {
  5517. // drag start listener
  5518. component.on('dragstart', function (event) {
  5519. me._onDragStart(event, component);
  5520. });
  5521. // drag listener
  5522. component.on('drag', function (event) {
  5523. me._onDrag(event, component, direction);
  5524. });
  5525. // drag end listener
  5526. component.on('dragend', function (event) {
  5527. me._onDragEnd(event, component);
  5528. });
  5529. }
  5530. else if (event == 'zoom') {
  5531. // mouse wheel
  5532. function mousewheel (event) {
  5533. me._onMouseWheel(event, component, direction);
  5534. }
  5535. component.on('mousewheel', mousewheel);
  5536. component.on('DOMMouseScroll', mousewheel); // For FF
  5537. // pinch
  5538. component.on('touch', function (event) {
  5539. me._onTouch();
  5540. });
  5541. component.on('pinch', function (event) {
  5542. me._onPinch(event, component, direction);
  5543. });
  5544. }
  5545. else {
  5546. throw new TypeError('Unknown event "' + event + '". ' +
  5547. 'Choose "move" or "zoom".');
  5548. }
  5549. };
  5550. /**
  5551. * Event handler
  5552. * @param {String} event name of the event, for example 'click', 'mousemove'
  5553. * @param {function} callback callback handler, invoked with the raw HTML Event
  5554. * as parameter.
  5555. */
  5556. Range.prototype.on = function (event, callback) {
  5557. events.addListener(this, event, callback);
  5558. };
  5559. /**
  5560. * Trigger an event
  5561. * @param {String} event name of the event, available events: 'rangechange',
  5562. * 'rangechanged'
  5563. * @private
  5564. */
  5565. Range.prototype._trigger = function (event) {
  5566. events.trigger(this, event, {
  5567. start: this.start,
  5568. end: this.end
  5569. });
  5570. };
  5571. /**
  5572. * Set a new start and end range
  5573. * @param {Number} [start]
  5574. * @param {Number} [end]
  5575. */
  5576. Range.prototype.setRange = function(start, end) {
  5577. var changed = this._applyRange(start, end);
  5578. if (changed) {
  5579. this._trigger('rangechange');
  5580. this._trigger('rangechanged');
  5581. }
  5582. };
  5583. /**
  5584. * Set a new start and end range. This method is the same as setRange, but
  5585. * does not trigger a range change and range changed event, and it returns
  5586. * true when the range is changed
  5587. * @param {Number} [start]
  5588. * @param {Number} [end]
  5589. * @return {Boolean} changed
  5590. * @private
  5591. */
  5592. Range.prototype._applyRange = function(start, end) {
  5593. var newStart = (start != null) ? util.convert(start, 'Number') : this.start,
  5594. newEnd = (end != null) ? util.convert(end, 'Number') : this.end,
  5595. max = (this.options.max != null) ? util.convert(this.options.max, 'Date').valueOf() : null,
  5596. min = (this.options.min != null) ? util.convert(this.options.min, 'Date').valueOf() : null,
  5597. diff;
  5598. // check for valid number
  5599. if (isNaN(newStart) || newStart === null) {
  5600. throw new Error('Invalid start "' + start + '"');
  5601. }
  5602. if (isNaN(newEnd) || newEnd === null) {
  5603. throw new Error('Invalid end "' + end + '"');
  5604. }
  5605. // prevent start < end
  5606. if (newEnd < newStart) {
  5607. newEnd = newStart;
  5608. }
  5609. // prevent start < min
  5610. if (min !== null) {
  5611. if (newStart < min) {
  5612. diff = (min - newStart);
  5613. newStart += diff;
  5614. newEnd += diff;
  5615. // prevent end > max
  5616. if (max != null) {
  5617. if (newEnd > max) {
  5618. newEnd = max;
  5619. }
  5620. }
  5621. }
  5622. }
  5623. // prevent end > max
  5624. if (max !== null) {
  5625. if (newEnd > max) {
  5626. diff = (newEnd - max);
  5627. newStart -= diff;
  5628. newEnd -= diff;
  5629. // prevent start < min
  5630. if (min != null) {
  5631. if (newStart < min) {
  5632. newStart = min;
  5633. }
  5634. }
  5635. }
  5636. }
  5637. // prevent (end-start) < zoomMin
  5638. if (this.options.zoomMin !== null) {
  5639. var zoomMin = parseFloat(this.options.zoomMin);
  5640. if (zoomMin < 0) {
  5641. zoomMin = 0;
  5642. }
  5643. if ((newEnd - newStart) < zoomMin) {
  5644. if ((this.end - this.start) === zoomMin) {
  5645. // ignore this action, we are already zoomed to the minimum
  5646. newStart = this.start;
  5647. newEnd = this.end;
  5648. }
  5649. else {
  5650. // zoom to the minimum
  5651. diff = (zoomMin - (newEnd - newStart));
  5652. newStart -= diff / 2;
  5653. newEnd += diff / 2;
  5654. }
  5655. }
  5656. }
  5657. // prevent (end-start) > zoomMax
  5658. if (this.options.zoomMax !== null) {
  5659. var zoomMax = parseFloat(this.options.zoomMax);
  5660. if (zoomMax < 0) {
  5661. zoomMax = 0;
  5662. }
  5663. if ((newEnd - newStart) > zoomMax) {
  5664. if ((this.end - this.start) === zoomMax) {
  5665. // ignore this action, we are already zoomed to the maximum
  5666. newStart = this.start;
  5667. newEnd = this.end;
  5668. }
  5669. else {
  5670. // zoom to the maximum
  5671. diff = ((newEnd - newStart) - zoomMax);
  5672. newStart += diff / 2;
  5673. newEnd -= diff / 2;
  5674. }
  5675. }
  5676. }
  5677. var changed = (this.start != newStart || this.end != newEnd);
  5678. this.start = newStart;
  5679. this.end = newEnd;
  5680. return changed;
  5681. };
  5682. /**
  5683. * Retrieve the current range.
  5684. * @return {Object} An object with start and end properties
  5685. */
  5686. Range.prototype.getRange = function() {
  5687. return {
  5688. start: this.start,
  5689. end: this.end
  5690. };
  5691. };
  5692. /**
  5693. * Calculate the conversion offset and scale for current range, based on
  5694. * the provided width
  5695. * @param {Number} width
  5696. * @returns {{offset: number, scale: number}} conversion
  5697. */
  5698. Range.prototype.conversion = function (width) {
  5699. return Range.conversion(this.start, this.end, width);
  5700. };
  5701. /**
  5702. * Static method to calculate the conversion offset and scale for a range,
  5703. * based on the provided start, end, and width
  5704. * @param {Number} start
  5705. * @param {Number} end
  5706. * @param {Number} width
  5707. * @returns {{offset: number, scale: number}} conversion
  5708. */
  5709. Range.conversion = function (start, end, width) {
  5710. if (width != 0 && (end - start != 0)) {
  5711. return {
  5712. offset: start,
  5713. scale: width / (end - start)
  5714. }
  5715. }
  5716. else {
  5717. return {
  5718. offset: 0,
  5719. scale: 1
  5720. };
  5721. }
  5722. };
  5723. // global (private) object to store drag params
  5724. var touchParams = {};
  5725. /**
  5726. * Start dragging horizontally or vertically
  5727. * @param {Event} event
  5728. * @param {Object} component
  5729. * @private
  5730. */
  5731. Range.prototype._onDragStart = function(event, component) {
  5732. // refuse to drag when we where pinching to prevent the timeline make a jump
  5733. // when releasing the fingers in opposite order from the touch screen
  5734. if (touchParams.pinching) return;
  5735. touchParams.start = this.start;
  5736. touchParams.end = this.end;
  5737. var frame = component.frame;
  5738. if (frame) {
  5739. frame.style.cursor = 'move';
  5740. }
  5741. };
  5742. /**
  5743. * Perform dragging operating.
  5744. * @param {Event} event
  5745. * @param {Component} component
  5746. * @param {String} direction 'horizontal' or 'vertical'
  5747. * @private
  5748. */
  5749. Range.prototype._onDrag = function (event, component, direction) {
  5750. validateDirection(direction);
  5751. // refuse to drag when we where pinching to prevent the timeline make a jump
  5752. // when releasing the fingers in opposite order from the touch screen
  5753. if (touchParams.pinching) return;
  5754. var delta = (direction == 'horizontal') ? event.gesture.deltaX : event.gesture.deltaY,
  5755. interval = (touchParams.end - touchParams.start),
  5756. width = (direction == 'horizontal') ? component.width : component.height,
  5757. diffRange = -delta / width * interval;
  5758. this._applyRange(touchParams.start + diffRange, touchParams.end + diffRange);
  5759. // fire a rangechange event
  5760. this._trigger('rangechange');
  5761. };
  5762. /**
  5763. * Stop dragging operating.
  5764. * @param {event} event
  5765. * @param {Component} component
  5766. * @private
  5767. */
  5768. Range.prototype._onDragEnd = function (event, component) {
  5769. // refuse to drag when we where pinching to prevent the timeline make a jump
  5770. // when releasing the fingers in opposite order from the touch screen
  5771. if (touchParams.pinching) return;
  5772. if (component.frame) {
  5773. component.frame.style.cursor = 'auto';
  5774. }
  5775. // fire a rangechanged event
  5776. this._trigger('rangechanged');
  5777. };
  5778. /**
  5779. * Event handler for mouse wheel event, used to zoom
  5780. * Code from http://adomas.org/javascript-mouse-wheel/
  5781. * @param {Event} event
  5782. * @param {Component} component
  5783. * @param {String} direction 'horizontal' or 'vertical'
  5784. * @private
  5785. */
  5786. Range.prototype._onMouseWheel = function(event, component, direction) {
  5787. validateDirection(direction);
  5788. // retrieve delta
  5789. var delta = 0;
  5790. if (event.wheelDelta) { /* IE/Opera. */
  5791. delta = event.wheelDelta / 120;
  5792. } else if (event.detail) { /* Mozilla case. */
  5793. // In Mozilla, sign of delta is different than in IE.
  5794. // Also, delta is multiple of 3.
  5795. delta = -event.detail / 3;
  5796. }
  5797. // If delta is nonzero, handle it.
  5798. // Basically, delta is now positive if wheel was scrolled up,
  5799. // and negative, if wheel was scrolled down.
  5800. if (delta) {
  5801. // perform the zoom action. Delta is normally 1 or -1
  5802. // adjust a negative delta such that zooming in with delta 0.1
  5803. // equals zooming out with a delta -0.1
  5804. var scale;
  5805. if (delta < 0) {
  5806. scale = 1 - (delta / 5);
  5807. }
  5808. else {
  5809. scale = 1 / (1 + (delta / 5)) ;
  5810. }
  5811. // calculate center, the date to zoom around
  5812. var gesture = Hammer.event.collectEventData(this, 'scroll', event),
  5813. pointer = getPointer(gesture.touches[0], component.frame),
  5814. pointerDate = this._pointerToDate(component, direction, pointer);
  5815. this.zoom(scale, pointerDate);
  5816. }
  5817. // Prevent default actions caused by mouse wheel
  5818. // (else the page and timeline both zoom and scroll)
  5819. util.preventDefault(event);
  5820. };
  5821. /**
  5822. * On start of a touch gesture, initialize scale to 1
  5823. * @private
  5824. */
  5825. Range.prototype._onTouch = function () {
  5826. touchParams.start = this.start;
  5827. touchParams.end = this.end;
  5828. touchParams.pinching = false;
  5829. touchParams.center = null;
  5830. };
  5831. /**
  5832. * Handle pinch event
  5833. * @param {Event} event
  5834. * @param {Component} component
  5835. * @param {String} direction 'horizontal' or 'vertical'
  5836. * @private
  5837. */
  5838. Range.prototype._onPinch = function (event, component, direction) {
  5839. touchParams.pinching = true;
  5840. if (event.gesture.touches.length > 1) {
  5841. if (!touchParams.center) {
  5842. touchParams.center = getPointer(event.gesture.center, component.frame);
  5843. }
  5844. var scale = 1 / event.gesture.scale,
  5845. initDate = this._pointerToDate(component, direction, touchParams.center),
  5846. center = getPointer(event.gesture.center, component.frame),
  5847. date = this._pointerToDate(component, direction, center),
  5848. delta = date - initDate; // TODO: utilize delta
  5849. // calculate new start and end
  5850. var newStart = parseInt(initDate + (touchParams.start - initDate) * scale);
  5851. var newEnd = parseInt(initDate + (touchParams.end - initDate) * scale);
  5852. // apply new range
  5853. this.setRange(newStart, newEnd);
  5854. }
  5855. };
  5856. /**
  5857. * Helper function to calculate the center date for zooming
  5858. * @param {Component} component
  5859. * @param {{x: Number, y: Number}} pointer
  5860. * @param {String} direction 'horizontal' or 'vertical'
  5861. * @return {number} date
  5862. * @private
  5863. */
  5864. Range.prototype._pointerToDate = function (component, direction, pointer) {
  5865. var conversion;
  5866. if (direction == 'horizontal') {
  5867. var width = component.width;
  5868. conversion = this.conversion(width);
  5869. return pointer.x / conversion.scale + conversion.offset;
  5870. }
  5871. else {
  5872. var height = component.height;
  5873. conversion = this.conversion(height);
  5874. return pointer.y / conversion.scale + conversion.offset;
  5875. }
  5876. };
  5877. /**
  5878. * Get the pointer location relative to the location of the dom element
  5879. * @param {{pageX: Number, pageY: Number}} touch
  5880. * @param {Element} element HTML DOM element
  5881. * @return {{x: Number, y: Number}} pointer
  5882. * @private
  5883. */
  5884. function getPointer (touch, element) {
  5885. return {
  5886. x: touch.pageX - vis.util.getAbsoluteLeft(element),
  5887. y: touch.pageY - vis.util.getAbsoluteTop(element)
  5888. };
  5889. }
  5890. /**
  5891. * Zoom the range the given scale in or out. Start and end date will
  5892. * be adjusted, and the timeline will be redrawn. You can optionally give a
  5893. * date around which to zoom.
  5894. * For example, try scale = 0.9 or 1.1
  5895. * @param {Number} scale Scaling factor. Values above 1 will zoom out,
  5896. * values below 1 will zoom in.
  5897. * @param {Number} [center] Value representing a date around which will
  5898. * be zoomed.
  5899. */
  5900. Range.prototype.zoom = function(scale, center) {
  5901. // if centerDate is not provided, take it half between start Date and end Date
  5902. if (center == null) {
  5903. center = (this.start + this.end) / 2;
  5904. }
  5905. // calculate new start and end
  5906. var newStart = center + (this.start - center) * scale;
  5907. var newEnd = center + (this.end - center) * scale;
  5908. this.setRange(newStart, newEnd);
  5909. };
  5910. /**
  5911. * Move the range with a given delta to the left or right. Start and end
  5912. * value will be adjusted. For example, try delta = 0.1 or -0.1
  5913. * @param {Number} delta Moving amount. Positive value will move right,
  5914. * negative value will move left
  5915. */
  5916. Range.prototype.move = function(delta) {
  5917. // zoom start Date and end Date relative to the centerDate
  5918. var diff = (this.end - this.start);
  5919. // apply new values
  5920. var newStart = this.start + diff * delta;
  5921. var newEnd = this.end + diff * delta;
  5922. // TODO: reckon with min and max range
  5923. this.start = newStart;
  5924. this.end = newEnd;
  5925. };
  5926. /**
  5927. * Move the range to a new center point
  5928. * @param {Number} moveTo New center point of the range
  5929. */
  5930. Range.prototype.moveTo = function(moveTo) {
  5931. var center = (this.start + this.end) / 2;
  5932. var diff = center - moveTo;
  5933. // calculate new start and end
  5934. var newStart = this.start - diff;
  5935. var newEnd = this.end - diff;
  5936. this.setRange(newStart, newEnd);
  5937. };
  5938. /**
  5939. * @constructor Controller
  5940. *
  5941. * A Controller controls the reflows and repaints of all visual components
  5942. */
  5943. function Controller () {
  5944. this.id = util.randomUUID();
  5945. this.components = {};
  5946. this.repaintTimer = undefined;
  5947. this.reflowTimer = undefined;
  5948. }
  5949. /**
  5950. * Add a component to the controller
  5951. * @param {Component} component
  5952. */
  5953. Controller.prototype.add = function add(component) {
  5954. // validate the component
  5955. if (component.id == undefined) {
  5956. throw new Error('Component has no field id');
  5957. }
  5958. if (!(component instanceof Component) && !(component instanceof Controller)) {
  5959. throw new TypeError('Component must be an instance of ' +
  5960. 'prototype Component or Controller');
  5961. }
  5962. // add the component
  5963. component.controller = this;
  5964. this.components[component.id] = component;
  5965. };
  5966. /**
  5967. * Remove a component from the controller
  5968. * @param {Component | String} component
  5969. */
  5970. Controller.prototype.remove = function remove(component) {
  5971. var id;
  5972. for (id in this.components) {
  5973. if (this.components.hasOwnProperty(id)) {
  5974. if (id == component || this.components[id] == component) {
  5975. break;
  5976. }
  5977. }
  5978. }
  5979. if (id) {
  5980. delete this.components[id];
  5981. }
  5982. };
  5983. /**
  5984. * Request a reflow. The controller will schedule a reflow
  5985. * @param {Boolean} [force] If true, an immediate reflow is forced. Default
  5986. * is false.
  5987. */
  5988. Controller.prototype.requestReflow = function requestReflow(force) {
  5989. if (force) {
  5990. this.reflow();
  5991. }
  5992. else {
  5993. if (!this.reflowTimer) {
  5994. var me = this;
  5995. this.reflowTimer = setTimeout(function () {
  5996. me.reflowTimer = undefined;
  5997. me.reflow();
  5998. }, 0);
  5999. }
  6000. }
  6001. };
  6002. /**
  6003. * Request a repaint. The controller will schedule a repaint
  6004. * @param {Boolean} [force] If true, an immediate repaint is forced. Default
  6005. * is false.
  6006. */
  6007. Controller.prototype.requestRepaint = function requestRepaint(force) {
  6008. if (force) {
  6009. this.repaint();
  6010. }
  6011. else {
  6012. if (!this.repaintTimer) {
  6013. var me = this;
  6014. this.repaintTimer = setTimeout(function () {
  6015. me.repaintTimer = undefined;
  6016. me.repaint();
  6017. }, 0);
  6018. }
  6019. }
  6020. };
  6021. /**
  6022. * Repaint all components
  6023. */
  6024. Controller.prototype.repaint = function repaint() {
  6025. var changed = false;
  6026. // cancel any running repaint request
  6027. if (this.repaintTimer) {
  6028. clearTimeout(this.repaintTimer);
  6029. this.repaintTimer = undefined;
  6030. }
  6031. var done = {};
  6032. function repaint(component, id) {
  6033. if (!(id in done)) {
  6034. // first repaint the components on which this component is dependent
  6035. if (component.depends) {
  6036. component.depends.forEach(function (dep) {
  6037. repaint(dep, dep.id);
  6038. });
  6039. }
  6040. if (component.parent) {
  6041. repaint(component.parent, component.parent.id);
  6042. }
  6043. // repaint the component itself and mark as done
  6044. changed = component.repaint() || changed;
  6045. done[id] = true;
  6046. }
  6047. }
  6048. util.forEach(this.components, repaint);
  6049. // immediately reflow when needed
  6050. if (changed) {
  6051. this.reflow();
  6052. }
  6053. // TODO: limit the number of nested reflows/repaints, prevent loop
  6054. };
  6055. /**
  6056. * Reflow all components
  6057. */
  6058. Controller.prototype.reflow = function reflow() {
  6059. var resized = false;
  6060. // cancel any running repaint request
  6061. if (this.reflowTimer) {
  6062. clearTimeout(this.reflowTimer);
  6063. this.reflowTimer = undefined;
  6064. }
  6065. var done = {};
  6066. function reflow(component, id) {
  6067. if (!(id in done)) {
  6068. // first reflow the components on which this component is dependent
  6069. if (component.depends) {
  6070. component.depends.forEach(function (dep) {
  6071. reflow(dep, dep.id);
  6072. });
  6073. }
  6074. if (component.parent) {
  6075. reflow(component.parent, component.parent.id);
  6076. }
  6077. // reflow the component itself and mark as done
  6078. resized = component.reflow() || resized;
  6079. done[id] = true;
  6080. }
  6081. }
  6082. util.forEach(this.components, reflow);
  6083. // immediately repaint when needed
  6084. if (resized) {
  6085. this.repaint();
  6086. }
  6087. // TODO: limit the number of nested reflows/repaints, prevent loop
  6088. };
  6089. /**
  6090. * Prototype for visual components
  6091. */
  6092. function Component () {
  6093. this.id = null;
  6094. this.parent = null;
  6095. this.depends = null;
  6096. this.controller = null;
  6097. this.options = null;
  6098. this.frame = null; // main DOM element
  6099. this.top = 0;
  6100. this.left = 0;
  6101. this.width = 0;
  6102. this.height = 0;
  6103. }
  6104. /**
  6105. * Set parameters for the frame. Parameters will be merged in current parameter
  6106. * set.
  6107. * @param {Object} options Available parameters:
  6108. * {String | function} [className]
  6109. * {EventBus} [eventBus]
  6110. * {String | Number | function} [left]
  6111. * {String | Number | function} [top]
  6112. * {String | Number | function} [width]
  6113. * {String | Number | function} [height]
  6114. */
  6115. Component.prototype.setOptions = function setOptions(options) {
  6116. if (options) {
  6117. util.extend(this.options, options);
  6118. if (this.controller) {
  6119. this.requestRepaint();
  6120. this.requestReflow();
  6121. }
  6122. }
  6123. };
  6124. /**
  6125. * Get an option value by name
  6126. * The function will first check this.options object, and else will check
  6127. * this.defaultOptions.
  6128. * @param {String} name
  6129. * @return {*} value
  6130. */
  6131. Component.prototype.getOption = function getOption(name) {
  6132. var value;
  6133. if (this.options) {
  6134. value = this.options[name];
  6135. }
  6136. if (value === undefined && this.defaultOptions) {
  6137. value = this.defaultOptions[name];
  6138. }
  6139. return value;
  6140. };
  6141. /**
  6142. * Get the container element of the component, which can be used by a child to
  6143. * add its own widgets. Not all components do have a container for childs, in
  6144. * that case null is returned.
  6145. * @returns {HTMLElement | null} container
  6146. */
  6147. // TODO: get rid of the getContainer and getFrame methods, provide these via the options
  6148. Component.prototype.getContainer = function getContainer() {
  6149. // should be implemented by the component
  6150. return null;
  6151. };
  6152. /**
  6153. * Get the frame element of the component, the outer HTML DOM element.
  6154. * @returns {HTMLElement | null} frame
  6155. */
  6156. Component.prototype.getFrame = function getFrame() {
  6157. return this.frame;
  6158. };
  6159. /**
  6160. * Repaint the component
  6161. * @return {Boolean} changed
  6162. */
  6163. Component.prototype.repaint = function repaint() {
  6164. // should be implemented by the component
  6165. return false;
  6166. };
  6167. /**
  6168. * Reflow the component
  6169. * @return {Boolean} resized
  6170. */
  6171. Component.prototype.reflow = function reflow() {
  6172. // should be implemented by the component
  6173. return false;
  6174. };
  6175. /**
  6176. * Hide the component from the DOM
  6177. * @return {Boolean} changed
  6178. */
  6179. Component.prototype.hide = function hide() {
  6180. if (this.frame && this.frame.parentNode) {
  6181. this.frame.parentNode.removeChild(this.frame);
  6182. return true;
  6183. }
  6184. else {
  6185. return false;
  6186. }
  6187. };
  6188. /**
  6189. * Show the component in the DOM (when not already visible).
  6190. * A repaint will be executed when the component is not visible
  6191. * @return {Boolean} changed
  6192. */
  6193. Component.prototype.show = function show() {
  6194. if (!this.frame || !this.frame.parentNode) {
  6195. return this.repaint();
  6196. }
  6197. else {
  6198. return false;
  6199. }
  6200. };
  6201. /**
  6202. * Request a repaint. The controller will schedule a repaint
  6203. */
  6204. Component.prototype.requestRepaint = function requestRepaint() {
  6205. if (this.controller) {
  6206. this.controller.requestRepaint();
  6207. }
  6208. else {
  6209. throw new Error('Cannot request a repaint: no controller configured');
  6210. // TODO: just do a repaint when no parent is configured?
  6211. }
  6212. };
  6213. /**
  6214. * Request a reflow. The controller will schedule a reflow
  6215. */
  6216. Component.prototype.requestReflow = function requestReflow() {
  6217. if (this.controller) {
  6218. this.controller.requestReflow();
  6219. }
  6220. else {
  6221. throw new Error('Cannot request a reflow: no controller configured');
  6222. // TODO: just do a reflow when no parent is configured?
  6223. }
  6224. };
  6225. /**
  6226. * A panel can contain components
  6227. * @param {Component} [parent]
  6228. * @param {Component[]} [depends] Components on which this components depends
  6229. * (except for the parent)
  6230. * @param {Object} [options] Available parameters:
  6231. * {String | Number | function} [left]
  6232. * {String | Number | function} [top]
  6233. * {String | Number | function} [width]
  6234. * {String | Number | function} [height]
  6235. * {String | function} [className]
  6236. * @constructor Panel
  6237. * @extends Component
  6238. */
  6239. function Panel(parent, depends, options) {
  6240. this.id = util.randomUUID();
  6241. this.parent = parent;
  6242. this.depends = depends;
  6243. this.options = options || {};
  6244. }
  6245. Panel.prototype = new Component();
  6246. /**
  6247. * Set options. Will extend the current options.
  6248. * @param {Object} [options] Available parameters:
  6249. * {String | function} [className]
  6250. * {String | Number | function} [left]
  6251. * {String | Number | function} [top]
  6252. * {String | Number | function} [width]
  6253. * {String | Number | function} [height]
  6254. */
  6255. Panel.prototype.setOptions = Component.prototype.setOptions;
  6256. /**
  6257. * Get the container element of the panel, which can be used by a child to
  6258. * add its own widgets.
  6259. * @returns {HTMLElement} container
  6260. */
  6261. Panel.prototype.getContainer = function () {
  6262. return this.frame;
  6263. };
  6264. /**
  6265. * Repaint the component
  6266. * @return {Boolean} changed
  6267. */
  6268. Panel.prototype.repaint = function () {
  6269. var changed = 0,
  6270. update = util.updateProperty,
  6271. asSize = util.option.asSize,
  6272. options = this.options,
  6273. frame = this.frame;
  6274. if (!frame) {
  6275. frame = document.createElement('div');
  6276. frame.className = 'panel';
  6277. var className = options.className;
  6278. if (className) {
  6279. if (typeof className == 'function') {
  6280. util.addClassName(frame, String(className()));
  6281. }
  6282. else {
  6283. util.addClassName(frame, String(className));
  6284. }
  6285. }
  6286. this.frame = frame;
  6287. changed += 1;
  6288. }
  6289. if (!frame.parentNode) {
  6290. if (!this.parent) {
  6291. throw new Error('Cannot repaint panel: no parent attached');
  6292. }
  6293. var parentContainer = this.parent.getContainer();
  6294. if (!parentContainer) {
  6295. throw new Error('Cannot repaint panel: parent has no container element');
  6296. }
  6297. parentContainer.appendChild(frame);
  6298. changed += 1;
  6299. }
  6300. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  6301. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  6302. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  6303. changed += update(frame.style, 'height', asSize(options.height, '100%'));
  6304. return (changed > 0);
  6305. };
  6306. /**
  6307. * Reflow the component
  6308. * @return {Boolean} resized
  6309. */
  6310. Panel.prototype.reflow = function () {
  6311. var changed = 0,
  6312. update = util.updateProperty,
  6313. frame = this.frame;
  6314. if (frame) {
  6315. changed += update(this, 'top', frame.offsetTop);
  6316. changed += update(this, 'left', frame.offsetLeft);
  6317. changed += update(this, 'width', frame.offsetWidth);
  6318. changed += update(this, 'height', frame.offsetHeight);
  6319. }
  6320. else {
  6321. changed += 1;
  6322. }
  6323. return (changed > 0);
  6324. };
  6325. /**
  6326. * A root panel can hold components. The root panel must be initialized with
  6327. * a DOM element as container.
  6328. * @param {HTMLElement} container
  6329. * @param {Object} [options] Available parameters: see RootPanel.setOptions.
  6330. * @constructor RootPanel
  6331. * @extends Panel
  6332. */
  6333. function RootPanel(container, options) {
  6334. this.id = util.randomUUID();
  6335. this.container = container;
  6336. this.options = options || {};
  6337. this.defaultOptions = {
  6338. autoResize: true
  6339. };
  6340. this.listeners = {}; // event listeners
  6341. }
  6342. RootPanel.prototype = new Panel();
  6343. /**
  6344. * Set options. Will extend the current options.
  6345. * @param {Object} [options] Available parameters:
  6346. * {String | function} [className]
  6347. * {String | Number | function} [left]
  6348. * {String | Number | function} [top]
  6349. * {String | Number | function} [width]
  6350. * {String | Number | function} [height]
  6351. * {Boolean | function} [autoResize]
  6352. */
  6353. RootPanel.prototype.setOptions = Component.prototype.setOptions;
  6354. /**
  6355. * Repaint the component
  6356. * @return {Boolean} changed
  6357. */
  6358. RootPanel.prototype.repaint = function () {
  6359. var changed = 0,
  6360. update = util.updateProperty,
  6361. asSize = util.option.asSize,
  6362. options = this.options,
  6363. frame = this.frame;
  6364. if (!frame) {
  6365. frame = document.createElement('div');
  6366. this.frame = frame;
  6367. changed += 1;
  6368. }
  6369. if (!frame.parentNode) {
  6370. if (!this.container) {
  6371. throw new Error('Cannot repaint root panel: no container attached');
  6372. }
  6373. this.container.appendChild(frame);
  6374. changed += 1;
  6375. }
  6376. frame.className = 'vis timeline rootpanel ' + options.orientation;
  6377. var className = options.className;
  6378. if (className) {
  6379. util.addClassName(frame, util.option.asString(className));
  6380. }
  6381. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  6382. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  6383. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  6384. changed += update(frame.style, 'height', asSize(options.height, '100%'));
  6385. this._updateEventEmitters();
  6386. this._updateWatch();
  6387. return (changed > 0);
  6388. };
  6389. /**
  6390. * Reflow the component
  6391. * @return {Boolean} resized
  6392. */
  6393. RootPanel.prototype.reflow = function () {
  6394. var changed = 0,
  6395. update = util.updateProperty,
  6396. frame = this.frame;
  6397. if (frame) {
  6398. changed += update(this, 'top', frame.offsetTop);
  6399. changed += update(this, 'left', frame.offsetLeft);
  6400. changed += update(this, 'width', frame.offsetWidth);
  6401. changed += update(this, 'height', frame.offsetHeight);
  6402. }
  6403. else {
  6404. changed += 1;
  6405. }
  6406. return (changed > 0);
  6407. };
  6408. /**
  6409. * Update watching for resize, depending on the current option
  6410. * @private
  6411. */
  6412. RootPanel.prototype._updateWatch = function () {
  6413. var autoResize = this.getOption('autoResize');
  6414. if (autoResize) {
  6415. this._watch();
  6416. }
  6417. else {
  6418. this._unwatch();
  6419. }
  6420. };
  6421. /**
  6422. * Watch for changes in the size of the frame. On resize, the Panel will
  6423. * automatically redraw itself.
  6424. * @private
  6425. */
  6426. RootPanel.prototype._watch = function () {
  6427. var me = this;
  6428. this._unwatch();
  6429. var checkSize = function () {
  6430. var autoResize = me.getOption('autoResize');
  6431. if (!autoResize) {
  6432. // stop watching when the option autoResize is changed to false
  6433. me._unwatch();
  6434. return;
  6435. }
  6436. if (me.frame) {
  6437. // check whether the frame is resized
  6438. if ((me.frame.clientWidth != me.width) ||
  6439. (me.frame.clientHeight != me.height)) {
  6440. me.requestReflow();
  6441. }
  6442. }
  6443. };
  6444. // TODO: automatically cleanup the event listener when the frame is deleted
  6445. util.addEventListener(window, 'resize', checkSize);
  6446. this.watchTimer = setInterval(checkSize, 1000);
  6447. };
  6448. /**
  6449. * Stop watching for a resize of the frame.
  6450. * @private
  6451. */
  6452. RootPanel.prototype._unwatch = function () {
  6453. if (this.watchTimer) {
  6454. clearInterval(this.watchTimer);
  6455. this.watchTimer = undefined;
  6456. }
  6457. // TODO: remove event listener on window.resize
  6458. };
  6459. /**
  6460. * Event handler
  6461. * @param {String} event name of the event, for example 'click', 'mousemove'
  6462. * @param {function} callback callback handler, invoked with the raw HTML Event
  6463. * as parameter.
  6464. */
  6465. RootPanel.prototype.on = function (event, callback) {
  6466. // register the listener at this component
  6467. var arr = this.listeners[event];
  6468. if (!arr) {
  6469. arr = [];
  6470. this.listeners[event] = arr;
  6471. }
  6472. arr.push(callback);
  6473. this._updateEventEmitters();
  6474. };
  6475. /**
  6476. * Update the event listeners for all event emitters
  6477. * @private
  6478. */
  6479. RootPanel.prototype._updateEventEmitters = function () {
  6480. if (this.listeners) {
  6481. var me = this;
  6482. util.forEach(this.listeners, function (listeners, event) {
  6483. if (!me.emitters) {
  6484. me.emitters = {};
  6485. }
  6486. if (!(event in me.emitters)) {
  6487. // create event
  6488. var frame = me.frame;
  6489. if (frame) {
  6490. //console.log('Created a listener for event ' + event + ' on component ' + me.id); // TODO: cleanup logging
  6491. var callback = function(event) {
  6492. listeners.forEach(function (listener) {
  6493. // TODO: filter on event target!
  6494. listener(event);
  6495. });
  6496. };
  6497. me.emitters[event] = callback;
  6498. if (!me.hammer) {
  6499. me.hammer = Hammer(frame, {
  6500. prevent_default: true
  6501. });
  6502. }
  6503. me.hammer.on(event, callback);
  6504. }
  6505. }
  6506. });
  6507. // TODO: be able to delete event listeners
  6508. // TODO: be able to move event listeners to a parent when available
  6509. }
  6510. };
  6511. /**
  6512. * A horizontal time axis
  6513. * @param {Component} parent
  6514. * @param {Component[]} [depends] Components on which this components depends
  6515. * (except for the parent)
  6516. * @param {Object} [options] See TimeAxis.setOptions for the available
  6517. * options.
  6518. * @constructor TimeAxis
  6519. * @extends Component
  6520. */
  6521. function TimeAxis (parent, depends, options) {
  6522. this.id = util.randomUUID();
  6523. this.parent = parent;
  6524. this.depends = depends;
  6525. this.dom = {
  6526. majorLines: [],
  6527. majorTexts: [],
  6528. minorLines: [],
  6529. minorTexts: [],
  6530. redundant: {
  6531. majorLines: [],
  6532. majorTexts: [],
  6533. minorLines: [],
  6534. minorTexts: []
  6535. }
  6536. };
  6537. this.props = {
  6538. range: {
  6539. start: 0,
  6540. end: 0,
  6541. minimumStep: 0
  6542. },
  6543. lineTop: 0
  6544. };
  6545. this.options = options || {};
  6546. this.defaultOptions = {
  6547. orientation: 'bottom', // supported: 'top', 'bottom'
  6548. // TODO: implement timeaxis orientations 'left' and 'right'
  6549. showMinorLabels: true,
  6550. showMajorLabels: true
  6551. };
  6552. this.conversion = null;
  6553. this.range = null;
  6554. }
  6555. TimeAxis.prototype = new Component();
  6556. // TODO: comment options
  6557. TimeAxis.prototype.setOptions = Component.prototype.setOptions;
  6558. /**
  6559. * Set a range (start and end)
  6560. * @param {Range | Object} range A Range or an object containing start and end.
  6561. */
  6562. TimeAxis.prototype.setRange = function (range) {
  6563. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  6564. throw new TypeError('Range must be an instance of Range, ' +
  6565. 'or an object containing start and end.');
  6566. }
  6567. this.range = range;
  6568. };
  6569. /**
  6570. * Convert a position on screen (pixels) to a datetime
  6571. * @param {int} x Position on the screen in pixels
  6572. * @return {Date} time The datetime the corresponds with given position x
  6573. */
  6574. TimeAxis.prototype.toTime = function(x) {
  6575. var conversion = this.conversion;
  6576. return new Date(x / conversion.scale + conversion.offset);
  6577. };
  6578. /**
  6579. * Convert a datetime (Date object) into a position on the screen
  6580. * @param {Date} time A date
  6581. * @return {int} x The position on the screen in pixels which corresponds
  6582. * with the given date.
  6583. * @private
  6584. */
  6585. TimeAxis.prototype.toScreen = function(time) {
  6586. var conversion = this.conversion;
  6587. return (time.valueOf() - conversion.offset) * conversion.scale;
  6588. };
  6589. /**
  6590. * Repaint the component
  6591. * @return {Boolean} changed
  6592. */
  6593. TimeAxis.prototype.repaint = function () {
  6594. var changed = 0,
  6595. update = util.updateProperty,
  6596. asSize = util.option.asSize,
  6597. options = this.options,
  6598. orientation = this.getOption('orientation'),
  6599. props = this.props,
  6600. step = this.step;
  6601. var frame = this.frame;
  6602. if (!frame) {
  6603. frame = document.createElement('div');
  6604. this.frame = frame;
  6605. changed += 1;
  6606. }
  6607. frame.className = 'axis';
  6608. // TODO: custom className?
  6609. if (!frame.parentNode) {
  6610. if (!this.parent) {
  6611. throw new Error('Cannot repaint time axis: no parent attached');
  6612. }
  6613. var parentContainer = this.parent.getContainer();
  6614. if (!parentContainer) {
  6615. throw new Error('Cannot repaint time axis: parent has no container element');
  6616. }
  6617. parentContainer.appendChild(frame);
  6618. changed += 1;
  6619. }
  6620. var parent = frame.parentNode;
  6621. if (parent) {
  6622. var beforeChild = frame.nextSibling;
  6623. parent.removeChild(frame); // take frame offline while updating (is almost twice as fast)
  6624. var defaultTop = (orientation == 'bottom' && this.props.parentHeight && this.height) ?
  6625. (this.props.parentHeight - this.height) + 'px' :
  6626. '0px';
  6627. changed += update(frame.style, 'top', asSize(options.top, defaultTop));
  6628. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  6629. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  6630. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  6631. // get characters width and height
  6632. this._repaintMeasureChars();
  6633. if (this.step) {
  6634. this._repaintStart();
  6635. step.first();
  6636. var xFirstMajorLabel = undefined;
  6637. var max = 0;
  6638. while (step.hasNext() && max < 1000) {
  6639. max++;
  6640. var cur = step.getCurrent(),
  6641. x = this.toScreen(cur),
  6642. isMajor = step.isMajor();
  6643. // TODO: lines must have a width, such that we can create css backgrounds
  6644. if (this.getOption('showMinorLabels')) {
  6645. this._repaintMinorText(x, step.getLabelMinor());
  6646. }
  6647. if (isMajor && this.getOption('showMajorLabels')) {
  6648. if (x > 0) {
  6649. if (xFirstMajorLabel == undefined) {
  6650. xFirstMajorLabel = x;
  6651. }
  6652. this._repaintMajorText(x, step.getLabelMajor());
  6653. }
  6654. this._repaintMajorLine(x);
  6655. }
  6656. else {
  6657. this._repaintMinorLine(x);
  6658. }
  6659. step.next();
  6660. }
  6661. // create a major label on the left when needed
  6662. if (this.getOption('showMajorLabels')) {
  6663. var leftTime = this.toTime(0),
  6664. leftText = step.getLabelMajor(leftTime),
  6665. widthText = leftText.length * (props.majorCharWidth || 10) + 10; // upper bound estimation
  6666. if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) {
  6667. this._repaintMajorText(0, leftText);
  6668. }
  6669. }
  6670. this._repaintEnd();
  6671. }
  6672. this._repaintLine();
  6673. // put frame online again
  6674. if (beforeChild) {
  6675. parent.insertBefore(frame, beforeChild);
  6676. }
  6677. else {
  6678. parent.appendChild(frame)
  6679. }
  6680. }
  6681. return (changed > 0);
  6682. };
  6683. /**
  6684. * Start a repaint. Move all DOM elements to a redundant list, where they
  6685. * can be picked for re-use, or can be cleaned up in the end
  6686. * @private
  6687. */
  6688. TimeAxis.prototype._repaintStart = function () {
  6689. var dom = this.dom,
  6690. redundant = dom.redundant;
  6691. redundant.majorLines = dom.majorLines;
  6692. redundant.majorTexts = dom.majorTexts;
  6693. redundant.minorLines = dom.minorLines;
  6694. redundant.minorTexts = dom.minorTexts;
  6695. dom.majorLines = [];
  6696. dom.majorTexts = [];
  6697. dom.minorLines = [];
  6698. dom.minorTexts = [];
  6699. };
  6700. /**
  6701. * End a repaint. Cleanup leftover DOM elements in the redundant list
  6702. * @private
  6703. */
  6704. TimeAxis.prototype._repaintEnd = function () {
  6705. util.forEach(this.dom.redundant, function (arr) {
  6706. while (arr.length) {
  6707. var elem = arr.pop();
  6708. if (elem && elem.parentNode) {
  6709. elem.parentNode.removeChild(elem);
  6710. }
  6711. }
  6712. });
  6713. };
  6714. /**
  6715. * Create a minor label for the axis at position x
  6716. * @param {Number} x
  6717. * @param {String} text
  6718. * @private
  6719. */
  6720. TimeAxis.prototype._repaintMinorText = function (x, text) {
  6721. // reuse redundant label
  6722. var label = this.dom.redundant.minorTexts.shift();
  6723. if (!label) {
  6724. // create new label
  6725. var content = document.createTextNode('');
  6726. label = document.createElement('div');
  6727. label.appendChild(content);
  6728. label.className = 'text minor';
  6729. this.frame.appendChild(label);
  6730. }
  6731. this.dom.minorTexts.push(label);
  6732. label.childNodes[0].nodeValue = text;
  6733. label.style.left = x + 'px';
  6734. label.style.top = this.props.minorLabelTop + 'px';
  6735. //label.title = title; // TODO: this is a heavy operation
  6736. };
  6737. /**
  6738. * Create a Major label for the axis at position x
  6739. * @param {Number} x
  6740. * @param {String} text
  6741. * @private
  6742. */
  6743. TimeAxis.prototype._repaintMajorText = function (x, text) {
  6744. // reuse redundant label
  6745. var label = this.dom.redundant.majorTexts.shift();
  6746. if (!label) {
  6747. // create label
  6748. var content = document.createTextNode(text);
  6749. label = document.createElement('div');
  6750. label.className = 'text major';
  6751. label.appendChild(content);
  6752. this.frame.appendChild(label);
  6753. }
  6754. this.dom.majorTexts.push(label);
  6755. label.childNodes[0].nodeValue = text;
  6756. label.style.top = this.props.majorLabelTop + 'px';
  6757. label.style.left = x + 'px';
  6758. //label.title = title; // TODO: this is a heavy operation
  6759. };
  6760. /**
  6761. * Create a minor line for the axis at position x
  6762. * @param {Number} x
  6763. * @private
  6764. */
  6765. TimeAxis.prototype._repaintMinorLine = function (x) {
  6766. // reuse redundant line
  6767. var line = this.dom.redundant.minorLines.shift();
  6768. if (!line) {
  6769. // create vertical line
  6770. line = document.createElement('div');
  6771. line.className = 'grid vertical minor';
  6772. this.frame.appendChild(line);
  6773. }
  6774. this.dom.minorLines.push(line);
  6775. var props = this.props;
  6776. line.style.top = props.minorLineTop + 'px';
  6777. line.style.height = props.minorLineHeight + 'px';
  6778. line.style.left = (x - props.minorLineWidth / 2) + 'px';
  6779. };
  6780. /**
  6781. * Create a Major line for the axis at position x
  6782. * @param {Number} x
  6783. * @private
  6784. */
  6785. TimeAxis.prototype._repaintMajorLine = function (x) {
  6786. // reuse redundant line
  6787. var line = this.dom.redundant.majorLines.shift();
  6788. if (!line) {
  6789. // create vertical line
  6790. line = document.createElement('DIV');
  6791. line.className = 'grid vertical major';
  6792. this.frame.appendChild(line);
  6793. }
  6794. this.dom.majorLines.push(line);
  6795. var props = this.props;
  6796. line.style.top = props.majorLineTop + 'px';
  6797. line.style.left = (x - props.majorLineWidth / 2) + 'px';
  6798. line.style.height = props.majorLineHeight + 'px';
  6799. };
  6800. /**
  6801. * Repaint the horizontal line for the axis
  6802. * @private
  6803. */
  6804. TimeAxis.prototype._repaintLine = function() {
  6805. var line = this.dom.line,
  6806. frame = this.frame,
  6807. options = this.options;
  6808. // line before all axis elements
  6809. if (this.getOption('showMinorLabels') || this.getOption('showMajorLabels')) {
  6810. if (line) {
  6811. // put this line at the end of all childs
  6812. frame.removeChild(line);
  6813. frame.appendChild(line);
  6814. }
  6815. else {
  6816. // create the axis line
  6817. line = document.createElement('div');
  6818. line.className = 'grid horizontal major';
  6819. frame.appendChild(line);
  6820. this.dom.line = line;
  6821. }
  6822. line.style.top = this.props.lineTop + 'px';
  6823. }
  6824. else {
  6825. if (line && line.parentElement) {
  6826. frame.removeChild(line.line);
  6827. delete this.dom.line;
  6828. }
  6829. }
  6830. };
  6831. /**
  6832. * Create characters used to determine the size of text on the axis
  6833. * @private
  6834. */
  6835. TimeAxis.prototype._repaintMeasureChars = function () {
  6836. // calculate the width and height of a single character
  6837. // this is used to calculate the step size, and also the positioning of the
  6838. // axis
  6839. var dom = this.dom,
  6840. text;
  6841. if (!dom.measureCharMinor) {
  6842. text = document.createTextNode('0');
  6843. var measureCharMinor = document.createElement('DIV');
  6844. measureCharMinor.className = 'text minor measure';
  6845. measureCharMinor.appendChild(text);
  6846. this.frame.appendChild(measureCharMinor);
  6847. dom.measureCharMinor = measureCharMinor;
  6848. }
  6849. if (!dom.measureCharMajor) {
  6850. text = document.createTextNode('0');
  6851. var measureCharMajor = document.createElement('DIV');
  6852. measureCharMajor.className = 'text major measure';
  6853. measureCharMajor.appendChild(text);
  6854. this.frame.appendChild(measureCharMajor);
  6855. dom.measureCharMajor = measureCharMajor;
  6856. }
  6857. };
  6858. /**
  6859. * Reflow the component
  6860. * @return {Boolean} resized
  6861. */
  6862. TimeAxis.prototype.reflow = function () {
  6863. var changed = 0,
  6864. update = util.updateProperty,
  6865. frame = this.frame,
  6866. range = this.range;
  6867. if (!range) {
  6868. throw new Error('Cannot repaint time axis: no range configured');
  6869. }
  6870. if (frame) {
  6871. changed += update(this, 'top', frame.offsetTop);
  6872. changed += update(this, 'left', frame.offsetLeft);
  6873. // calculate size of a character
  6874. var props = this.props,
  6875. showMinorLabels = this.getOption('showMinorLabels'),
  6876. showMajorLabels = this.getOption('showMajorLabels'),
  6877. measureCharMinor = this.dom.measureCharMinor,
  6878. measureCharMajor = this.dom.measureCharMajor;
  6879. if (measureCharMinor) {
  6880. props.minorCharHeight = measureCharMinor.clientHeight;
  6881. props.minorCharWidth = measureCharMinor.clientWidth;
  6882. }
  6883. if (measureCharMajor) {
  6884. props.majorCharHeight = measureCharMajor.clientHeight;
  6885. props.majorCharWidth = measureCharMajor.clientWidth;
  6886. }
  6887. var parentHeight = frame.parentNode ? frame.parentNode.offsetHeight : 0;
  6888. if (parentHeight != props.parentHeight) {
  6889. props.parentHeight = parentHeight;
  6890. changed += 1;
  6891. }
  6892. switch (this.getOption('orientation')) {
  6893. case 'bottom':
  6894. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  6895. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  6896. props.minorLabelTop = 0;
  6897. props.majorLabelTop = props.minorLabelTop + props.minorLabelHeight;
  6898. props.minorLineTop = -this.top;
  6899. props.minorLineHeight = Math.max(this.top + props.majorLabelHeight, 0);
  6900. props.minorLineWidth = 1; // TODO: really calculate width
  6901. props.majorLineTop = -this.top;
  6902. props.majorLineHeight = Math.max(this.top + props.minorLabelHeight + props.majorLabelHeight, 0);
  6903. props.majorLineWidth = 1; // TODO: really calculate width
  6904. props.lineTop = 0;
  6905. break;
  6906. case 'top':
  6907. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  6908. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  6909. props.majorLabelTop = 0;
  6910. props.minorLabelTop = props.majorLabelTop + props.majorLabelHeight;
  6911. props.minorLineTop = props.minorLabelTop;
  6912. props.minorLineHeight = Math.max(parentHeight - props.majorLabelHeight - this.top);
  6913. props.minorLineWidth = 1; // TODO: really calculate width
  6914. props.majorLineTop = 0;
  6915. props.majorLineHeight = Math.max(parentHeight - this.top);
  6916. props.majorLineWidth = 1; // TODO: really calculate width
  6917. props.lineTop = props.majorLabelHeight + props.minorLabelHeight;
  6918. break;
  6919. default:
  6920. throw new Error('Unkown orientation "' + this.getOption('orientation') + '"');
  6921. }
  6922. var height = props.minorLabelHeight + props.majorLabelHeight;
  6923. changed += update(this, 'width', frame.offsetWidth);
  6924. changed += update(this, 'height', height);
  6925. // calculate range and step
  6926. this._updateConversion();
  6927. var start = util.convert(range.start, 'Number'),
  6928. end = util.convert(range.end, 'Number'),
  6929. minimumStep = this.toTime((props.minorCharWidth || 10) * 5).valueOf()
  6930. -this.toTime(0).valueOf();
  6931. this.step = new TimeStep(new Date(start), new Date(end), minimumStep);
  6932. changed += update(props.range, 'start', start);
  6933. changed += update(props.range, 'end', end);
  6934. changed += update(props.range, 'minimumStep', minimumStep.valueOf());
  6935. }
  6936. return (changed > 0);
  6937. };
  6938. /**
  6939. * Calculate the scale and offset to convert a position on screen to the
  6940. * corresponding date and vice versa.
  6941. * After the method _updateConversion is executed once, the methods toTime
  6942. * and toScreen can be used.
  6943. * @private
  6944. */
  6945. TimeAxis.prototype._updateConversion = function() {
  6946. var range = this.range;
  6947. if (!range) {
  6948. throw new Error('No range configured');
  6949. }
  6950. if (range.conversion) {
  6951. this.conversion = range.conversion(this.width);
  6952. }
  6953. else {
  6954. this.conversion = Range.conversion(range.start, range.end, this.width);
  6955. }
  6956. };
  6957. /**
  6958. * A current time bar
  6959. * @param {Component} parent
  6960. * @param {Component[]} [depends] Components on which this components depends
  6961. * (except for the parent)
  6962. * @param {Object} [options] Available parameters:
  6963. * {Boolean} [showCurrentTime]
  6964. * @constructor CurrentTime
  6965. * @extends Component
  6966. */
  6967. function CurrentTime (parent, depends, options) {
  6968. this.id = util.randomUUID();
  6969. this.parent = parent;
  6970. this.depends = depends;
  6971. this.options = options || {};
  6972. this.defaultOptions = {
  6973. showCurrentTime: false
  6974. };
  6975. }
  6976. CurrentTime.prototype = new Component();
  6977. CurrentTime.prototype.setOptions = Component.prototype.setOptions;
  6978. /**
  6979. * Get the container element of the bar, which can be used by a child to
  6980. * add its own widgets.
  6981. * @returns {HTMLElement} container
  6982. */
  6983. CurrentTime.prototype.getContainer = function () {
  6984. return this.frame;
  6985. };
  6986. /**
  6987. * Repaint the component
  6988. * @return {Boolean} changed
  6989. */
  6990. CurrentTime.prototype.repaint = function () {
  6991. var bar = this.frame,
  6992. parent = this.parent,
  6993. parentContainer = parent.parent.getContainer();
  6994. if (!parent) {
  6995. throw new Error('Cannot repaint bar: no parent attached');
  6996. }
  6997. if (!parentContainer) {
  6998. throw new Error('Cannot repaint bar: parent has no container element');
  6999. }
  7000. if (!this.getOption('showCurrentTime')) {
  7001. if (bar) {
  7002. parentContainer.removeChild(bar);
  7003. delete this.frame;
  7004. }
  7005. return;
  7006. }
  7007. if (!bar) {
  7008. bar = document.createElement('div');
  7009. bar.className = 'currenttime';
  7010. bar.style.position = 'absolute';
  7011. bar.style.top = '0px';
  7012. bar.style.height = '100%';
  7013. parentContainer.appendChild(bar);
  7014. this.frame = bar;
  7015. }
  7016. if (!parent.conversion) {
  7017. parent._updateConversion();
  7018. }
  7019. var now = new Date();
  7020. var x = parent.toScreen(now);
  7021. bar.style.left = x + 'px';
  7022. bar.title = 'Current time: ' + now;
  7023. // start a timer to adjust for the new time
  7024. if (this.currentTimeTimer !== undefined) {
  7025. clearTimeout(this.currentTimeTimer);
  7026. delete this.currentTimeTimer;
  7027. }
  7028. var timeline = this;
  7029. var interval = 1 / parent.conversion.scale / 2;
  7030. if (interval < 30) {
  7031. interval = 30;
  7032. }
  7033. this.currentTimeTimer = setTimeout(function() {
  7034. timeline.repaint();
  7035. }, interval);
  7036. return false;
  7037. };
  7038. /**
  7039. * A custom time bar
  7040. * @param {Component} parent
  7041. * @param {Component[]} [depends] Components on which this components depends
  7042. * (except for the parent)
  7043. * @param {Object} [options] Available parameters:
  7044. * {Boolean} [showCustomTime]
  7045. * @constructor CustomTime
  7046. * @extends Component
  7047. */
  7048. function CustomTime (parent, depends, options) {
  7049. this.id = util.randomUUID();
  7050. this.parent = parent;
  7051. this.depends = depends;
  7052. this.options = options || {};
  7053. this.defaultOptions = {
  7054. showCustomTime: false
  7055. };
  7056. this.listeners = [];
  7057. this.customTime = new Date();
  7058. }
  7059. CustomTime.prototype = new Component();
  7060. CustomTime.prototype.setOptions = Component.prototype.setOptions;
  7061. /**
  7062. * Get the container element of the bar, which can be used by a child to
  7063. * add its own widgets.
  7064. * @returns {HTMLElement} container
  7065. */
  7066. CustomTime.prototype.getContainer = function () {
  7067. return this.frame;
  7068. };
  7069. /**
  7070. * Repaint the component
  7071. * @return {Boolean} changed
  7072. */
  7073. CustomTime.prototype.repaint = function () {
  7074. var bar = this.frame,
  7075. parent = this.parent,
  7076. parentContainer = parent.parent.getContainer();
  7077. if (!parent) {
  7078. throw new Error('Cannot repaint bar: no parent attached');
  7079. }
  7080. if (!parentContainer) {
  7081. throw new Error('Cannot repaint bar: parent has no container element');
  7082. }
  7083. if (!this.getOption('showCustomTime')) {
  7084. if (bar) {
  7085. parentContainer.removeChild(bar);
  7086. delete this.frame;
  7087. }
  7088. return;
  7089. }
  7090. if (!bar) {
  7091. bar = document.createElement('div');
  7092. bar.className = 'customtime';
  7093. bar.style.position = 'absolute';
  7094. bar.style.top = '0px';
  7095. bar.style.height = '100%';
  7096. parentContainer.appendChild(bar);
  7097. var drag = document.createElement('div');
  7098. drag.style.position = 'relative';
  7099. drag.style.top = '0px';
  7100. drag.style.left = '-10px';
  7101. drag.style.height = '100%';
  7102. drag.style.width = '20px';
  7103. bar.appendChild(drag);
  7104. this.frame = bar;
  7105. this.subscribe(this, 'movetime');
  7106. }
  7107. if (!parent.conversion) {
  7108. parent._updateConversion();
  7109. }
  7110. var x = parent.toScreen(this.customTime);
  7111. bar.style.left = x + 'px';
  7112. bar.title = 'Time: ' + this.customTime;
  7113. return false;
  7114. };
  7115. /**
  7116. * Set custom time.
  7117. * @param {Date} time
  7118. */
  7119. CustomTime.prototype._setCustomTime = function(time) {
  7120. this.customTime = new Date(time.valueOf());
  7121. this.repaint();
  7122. };
  7123. /**
  7124. * Retrieve the current custom time.
  7125. * @return {Date} customTime
  7126. */
  7127. CustomTime.prototype._getCustomTime = function() {
  7128. return new Date(this.customTime.valueOf());
  7129. };
  7130. /**
  7131. * Add listeners for mouse and touch events to the component
  7132. * @param {Component} component
  7133. */
  7134. CustomTime.prototype.subscribe = function (component, event) {
  7135. var me = this;
  7136. var listener = {
  7137. component: component,
  7138. event: event,
  7139. callback: function (event) {
  7140. me._onMouseDown(event, listener);
  7141. },
  7142. params: {}
  7143. };
  7144. component.on('mousedown', listener.callback);
  7145. me.listeners.push(listener);
  7146. };
  7147. /**
  7148. * Event handler
  7149. * @param {String} event name of the event, for example 'click', 'mousemove'
  7150. * @param {function} callback callback handler, invoked with the raw HTML Event
  7151. * as parameter.
  7152. */
  7153. CustomTime.prototype.on = function (event, callback) {
  7154. var bar = this.frame;
  7155. if (!bar) {
  7156. throw new Error('Cannot add event listener: no parent attached');
  7157. }
  7158. events.addListener(this, event, callback);
  7159. util.addEventListener(bar, event, callback);
  7160. };
  7161. /**
  7162. * Start moving horizontally
  7163. * @param {Event} event
  7164. * @param {Object} listener Listener containing the component and params
  7165. * @private
  7166. */
  7167. CustomTime.prototype._onMouseDown = function(event, listener) {
  7168. event = event || window.event;
  7169. var params = listener.params;
  7170. // only react on left mouse button down
  7171. var leftButtonDown = event.which ? (event.which == 1) : (event.button == 1);
  7172. if (!leftButtonDown) {
  7173. return;
  7174. }
  7175. // get mouse position
  7176. params.mouseX = util.getPageX(event);
  7177. params.moved = false;
  7178. params.customTime = this.customTime;
  7179. // add event listeners to handle moving the custom time bar
  7180. var me = this;
  7181. if (!params.onMouseMove) {
  7182. params.onMouseMove = function (event) {
  7183. me._onMouseMove(event, listener);
  7184. };
  7185. util.addEventListener(document, 'mousemove', params.onMouseMove);
  7186. }
  7187. if (!params.onMouseUp) {
  7188. params.onMouseUp = function (event) {
  7189. me._onMouseUp(event, listener);
  7190. };
  7191. util.addEventListener(document, 'mouseup', params.onMouseUp);
  7192. }
  7193. util.stopPropagation(event);
  7194. util.preventDefault(event);
  7195. };
  7196. /**
  7197. * Perform moving operating.
  7198. * This function activated from within the funcion CustomTime._onMouseDown().
  7199. * @param {Event} event
  7200. * @param {Object} listener
  7201. * @private
  7202. */
  7203. CustomTime.prototype._onMouseMove = function (event, listener) {
  7204. event = event || window.event;
  7205. var params = listener.params;
  7206. var parent = this.parent;
  7207. // calculate change in mouse position
  7208. var mouseX = util.getPageX(event);
  7209. if (params.mouseX === undefined) {
  7210. params.mouseX = mouseX;
  7211. }
  7212. var diff = mouseX - params.mouseX;
  7213. // if mouse movement is big enough, register it as a "moved" event
  7214. if (Math.abs(diff) >= 1) {
  7215. params.moved = true;
  7216. }
  7217. var x = parent.toScreen(params.customTime);
  7218. var xnew = x + diff;
  7219. var time = parent.toTime(xnew);
  7220. this._setCustomTime(time);
  7221. // fire a timechange event
  7222. events.trigger(this, 'timechange', {customTime: this.customTime});
  7223. util.preventDefault(event);
  7224. };
  7225. /**
  7226. * Stop moving operating.
  7227. * This function activated from within the function CustomTime._onMouseDown().
  7228. * @param {event} event
  7229. * @param {Object} listener
  7230. * @private
  7231. */
  7232. CustomTime.prototype._onMouseUp = function (event, listener) {
  7233. event = event || window.event;
  7234. var params = listener.params;
  7235. // remove event listeners here, important for Safari
  7236. if (params.onMouseMove) {
  7237. util.removeEventListener(document, 'mousemove', params.onMouseMove);
  7238. params.onMouseMove = null;
  7239. }
  7240. if (params.onMouseUp) {
  7241. util.removeEventListener(document, 'mouseup', params.onMouseUp);
  7242. params.onMouseUp = null;
  7243. }
  7244. if (params.moved) {
  7245. // fire a timechanged event
  7246. events.trigger(this, 'timechanged', {customTime: this.customTime});
  7247. }
  7248. };
  7249. /**
  7250. * An ItemSet holds a set of items and ranges which can be displayed in a
  7251. * range. The width is determined by the parent of the ItemSet, and the height
  7252. * is determined by the size of the items.
  7253. * @param {Component} parent
  7254. * @param {Component[]} [depends] Components on which this components depends
  7255. * (except for the parent)
  7256. * @param {Object} [options] See ItemSet.setOptions for the available
  7257. * options.
  7258. * @constructor ItemSet
  7259. * @extends Panel
  7260. */
  7261. // TODO: improve performance by replacing all Array.forEach with a for loop
  7262. function ItemSet(parent, depends, options) {
  7263. this.id = util.randomUUID();
  7264. this.parent = parent;
  7265. this.depends = depends;
  7266. // one options object is shared by this itemset and all its items
  7267. this.options = options || {};
  7268. this.defaultOptions = {
  7269. type: 'box',
  7270. align: 'center',
  7271. orientation: 'bottom',
  7272. margin: {
  7273. axis: 20,
  7274. item: 10
  7275. },
  7276. padding: 5
  7277. };
  7278. this.dom = {};
  7279. var me = this;
  7280. this.itemsData = null; // DataSet
  7281. this.range = null; // Range or Object {start: number, end: number}
  7282. this.listeners = {
  7283. 'add': function (event, params, senderId) {
  7284. if (senderId != me.id) {
  7285. me._onAdd(params.items);
  7286. }
  7287. },
  7288. 'update': function (event, params, senderId) {
  7289. if (senderId != me.id) {
  7290. me._onUpdate(params.items);
  7291. }
  7292. },
  7293. 'remove': function (event, params, senderId) {
  7294. if (senderId != me.id) {
  7295. me._onRemove(params.items);
  7296. }
  7297. }
  7298. };
  7299. this.items = {}; // object with an Item for every data item
  7300. this.queue = {}; // queue with id/actions: 'add', 'update', 'delete'
  7301. this.stack = new Stack(this, Object.create(this.options));
  7302. this.conversion = null;
  7303. // TODO: ItemSet should also attach event listeners for rangechange and rangechanged, like timeaxis
  7304. }
  7305. ItemSet.prototype = new Panel();
  7306. // available item types will be registered here
  7307. ItemSet.types = {
  7308. box: ItemBox,
  7309. range: ItemRange,
  7310. rangeoverflow: ItemRangeOverflow,
  7311. point: ItemPoint
  7312. };
  7313. /**
  7314. * Set options for the ItemSet. Existing options will be extended/overwritten.
  7315. * @param {Object} [options] The following options are available:
  7316. * {String | function} [className]
  7317. * class name for the itemset
  7318. * {String} [type]
  7319. * Default type for the items. Choose from 'box'
  7320. * (default), 'point', or 'range'. The default
  7321. * Style can be overwritten by individual items.
  7322. * {String} align
  7323. * Alignment for the items, only applicable for
  7324. * ItemBox. Choose 'center' (default), 'left', or
  7325. * 'right'.
  7326. * {String} orientation
  7327. * Orientation of the item set. Choose 'top' or
  7328. * 'bottom' (default).
  7329. * {Number} margin.axis
  7330. * Margin between the axis and the items in pixels.
  7331. * Default is 20.
  7332. * {Number} margin.item
  7333. * Margin between items in pixels. Default is 10.
  7334. * {Number} padding
  7335. * Padding of the contents of an item in pixels.
  7336. * Must correspond with the items css. Default is 5.
  7337. */
  7338. ItemSet.prototype.setOptions = Component.prototype.setOptions;
  7339. /**
  7340. * Set range (start and end).
  7341. * @param {Range | Object} range A Range or an object containing start and end.
  7342. */
  7343. ItemSet.prototype.setRange = function setRange(range) {
  7344. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  7345. throw new TypeError('Range must be an instance of Range, ' +
  7346. 'or an object containing start and end.');
  7347. }
  7348. this.range = range;
  7349. };
  7350. /**
  7351. * Repaint the component
  7352. * @return {Boolean} changed
  7353. */
  7354. ItemSet.prototype.repaint = function repaint() {
  7355. var changed = 0,
  7356. update = util.updateProperty,
  7357. asSize = util.option.asSize,
  7358. options = this.options,
  7359. orientation = this.getOption('orientation'),
  7360. defaultOptions = this.defaultOptions,
  7361. frame = this.frame;
  7362. if (!frame) {
  7363. frame = document.createElement('div');
  7364. frame.className = 'itemset';
  7365. var className = options.className;
  7366. if (className) {
  7367. util.addClassName(frame, util.option.asString(className));
  7368. }
  7369. // create background panel
  7370. var background = document.createElement('div');
  7371. background.className = 'background';
  7372. frame.appendChild(background);
  7373. this.dom.background = background;
  7374. // create foreground panel
  7375. var foreground = document.createElement('div');
  7376. foreground.className = 'foreground';
  7377. frame.appendChild(foreground);
  7378. this.dom.foreground = foreground;
  7379. // create axis panel
  7380. var axis = document.createElement('div');
  7381. axis.className = 'itemset-axis';
  7382. //frame.appendChild(axis);
  7383. this.dom.axis = axis;
  7384. this.frame = frame;
  7385. changed += 1;
  7386. }
  7387. if (!this.parent) {
  7388. throw new Error('Cannot repaint itemset: no parent attached');
  7389. }
  7390. var parentContainer = this.parent.getContainer();
  7391. if (!parentContainer) {
  7392. throw new Error('Cannot repaint itemset: parent has no container element');
  7393. }
  7394. if (!frame.parentNode) {
  7395. parentContainer.appendChild(frame);
  7396. changed += 1;
  7397. }
  7398. if (!this.dom.axis.parentNode) {
  7399. parentContainer.appendChild(this.dom.axis);
  7400. changed += 1;
  7401. }
  7402. // reposition frame
  7403. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  7404. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  7405. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  7406. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  7407. // reposition axis
  7408. changed += update(this.dom.axis.style, 'left', asSize(options.left, '0px'));
  7409. changed += update(this.dom.axis.style, 'width', asSize(options.width, '100%'));
  7410. if (orientation == 'bottom') {
  7411. changed += update(this.dom.axis.style, 'top', (this.height + this.top) + 'px');
  7412. }
  7413. else { // orientation == 'top'
  7414. changed += update(this.dom.axis.style, 'top', this.top + 'px');
  7415. }
  7416. this._updateConversion();
  7417. var me = this,
  7418. queue = this.queue,
  7419. itemsData = this.itemsData,
  7420. items = this.items,
  7421. dataOptions = {
  7422. // TODO: cleanup
  7423. // fields: [(itemsData && itemsData.fieldId || 'id'), 'start', 'end', 'content', 'type', 'className']
  7424. };
  7425. // show/hide added/changed/removed items
  7426. Object.keys(queue).forEach(function (id) {
  7427. //var entry = queue[id];
  7428. var action = queue[id];
  7429. var item = items[id];
  7430. //var item = entry.item;
  7431. //noinspection FallthroughInSwitchStatementJS
  7432. switch (action) {
  7433. case 'add':
  7434. case 'update':
  7435. var itemData = itemsData && itemsData.get(id, dataOptions);
  7436. if (itemData) {
  7437. var type = itemData.type ||
  7438. (itemData.start && itemData.end && 'range') ||
  7439. options.type ||
  7440. 'box';
  7441. var constructor = ItemSet.types[type];
  7442. // TODO: how to handle items with invalid data? hide them and give a warning? or throw an error?
  7443. if (item) {
  7444. // update item
  7445. if (!constructor || !(item instanceof constructor)) {
  7446. // item type has changed, hide and delete the item
  7447. changed += item.hide();
  7448. item = null;
  7449. }
  7450. else {
  7451. item.data = itemData; // TODO: create a method item.setData ?
  7452. changed++;
  7453. }
  7454. }
  7455. if (!item) {
  7456. // create item
  7457. if (constructor) {
  7458. item = new constructor(me, itemData, options, defaultOptions);
  7459. changed++;
  7460. }
  7461. else {
  7462. throw new TypeError('Unknown item type "' + type + '"');
  7463. }
  7464. }
  7465. // force a repaint (not only a reposition)
  7466. item.repaint();
  7467. items[id] = item;
  7468. }
  7469. // update queue
  7470. delete queue[id];
  7471. break;
  7472. case 'remove':
  7473. if (item) {
  7474. // remove DOM of the item
  7475. changed += item.hide();
  7476. }
  7477. // update lists
  7478. delete items[id];
  7479. delete queue[id];
  7480. break;
  7481. default:
  7482. console.log('Error: unknown action "' + action + '"');
  7483. }
  7484. });
  7485. // reposition all items. Show items only when in the visible area
  7486. util.forEach(this.items, function (item) {
  7487. if (item.visible) {
  7488. changed += item.show();
  7489. item.reposition();
  7490. }
  7491. else {
  7492. changed += item.hide();
  7493. }
  7494. });
  7495. return (changed > 0);
  7496. };
  7497. /**
  7498. * Get the foreground container element
  7499. * @return {HTMLElement} foreground
  7500. */
  7501. ItemSet.prototype.getForeground = function getForeground() {
  7502. return this.dom.foreground;
  7503. };
  7504. /**
  7505. * Get the background container element
  7506. * @return {HTMLElement} background
  7507. */
  7508. ItemSet.prototype.getBackground = function getBackground() {
  7509. return this.dom.background;
  7510. };
  7511. /**
  7512. * Get the axis container element
  7513. * @return {HTMLElement} axis
  7514. */
  7515. ItemSet.prototype.getAxis = function getAxis() {
  7516. return this.dom.axis;
  7517. };
  7518. /**
  7519. * Reflow the component
  7520. * @return {Boolean} resized
  7521. */
  7522. ItemSet.prototype.reflow = function reflow () {
  7523. var changed = 0,
  7524. options = this.options,
  7525. marginAxis = options.margin && options.margin.axis || this.defaultOptions.margin.axis,
  7526. marginItem = options.margin && options.margin.item || this.defaultOptions.margin.item,
  7527. update = util.updateProperty,
  7528. asNumber = util.option.asNumber,
  7529. asSize = util.option.asSize,
  7530. frame = this.frame;
  7531. if (frame) {
  7532. this._updateConversion();
  7533. util.forEach(this.items, function (item) {
  7534. changed += item.reflow();
  7535. });
  7536. // TODO: stack.update should be triggered via an event, in stack itself
  7537. // TODO: only update the stack when there are changed items
  7538. this.stack.update();
  7539. var maxHeight = asNumber(options.maxHeight);
  7540. var fixedHeight = (asSize(options.height) != null);
  7541. var height;
  7542. if (fixedHeight) {
  7543. height = frame.offsetHeight;
  7544. }
  7545. else {
  7546. // height is not specified, determine the height from the height and positioned items
  7547. var visibleItems = this.stack.ordered; // TODO: not so nice way to get the filtered items
  7548. if (visibleItems.length) {
  7549. var min = visibleItems[0].top;
  7550. var max = visibleItems[0].top + visibleItems[0].height;
  7551. util.forEach(visibleItems, function (item) {
  7552. min = Math.min(min, item.top);
  7553. max = Math.max(max, (item.top + item.height));
  7554. });
  7555. height = (max - min) + marginAxis + marginItem;
  7556. }
  7557. else {
  7558. height = marginAxis + marginItem;
  7559. }
  7560. }
  7561. if (maxHeight != null) {
  7562. height = Math.min(height, maxHeight);
  7563. }
  7564. changed += update(this, 'height', height);
  7565. // calculate height from items
  7566. changed += update(this, 'top', frame.offsetTop);
  7567. changed += update(this, 'left', frame.offsetLeft);
  7568. changed += update(this, 'width', frame.offsetWidth);
  7569. }
  7570. else {
  7571. changed += 1;
  7572. }
  7573. return (changed > 0);
  7574. };
  7575. /**
  7576. * Hide this component from the DOM
  7577. * @return {Boolean} changed
  7578. */
  7579. ItemSet.prototype.hide = function hide() {
  7580. var changed = false;
  7581. // remove the DOM
  7582. if (this.frame && this.frame.parentNode) {
  7583. this.frame.parentNode.removeChild(this.frame);
  7584. changed = true;
  7585. }
  7586. if (this.dom.axis && this.dom.axis.parentNode) {
  7587. this.dom.axis.parentNode.removeChild(this.dom.axis);
  7588. changed = true;
  7589. }
  7590. return changed;
  7591. };
  7592. /**
  7593. * Set items
  7594. * @param {vis.DataSet | null} items
  7595. */
  7596. ItemSet.prototype.setItems = function setItems(items) {
  7597. var me = this,
  7598. ids,
  7599. oldItemsData = this.itemsData;
  7600. // replace the dataset
  7601. if (!items) {
  7602. this.itemsData = null;
  7603. }
  7604. else if (items instanceof DataSet || items instanceof DataView) {
  7605. this.itemsData = items;
  7606. }
  7607. else {
  7608. throw new TypeError('Data must be an instance of DataSet');
  7609. }
  7610. if (oldItemsData) {
  7611. // unsubscribe from old dataset
  7612. util.forEach(this.listeners, function (callback, event) {
  7613. oldItemsData.unsubscribe(event, callback);
  7614. });
  7615. // remove all drawn items
  7616. ids = oldItemsData.getIds();
  7617. this._onRemove(ids);
  7618. }
  7619. if (this.itemsData) {
  7620. // subscribe to new dataset
  7621. var id = this.id;
  7622. util.forEach(this.listeners, function (callback, event) {
  7623. me.itemsData.subscribe(event, callback, id);
  7624. });
  7625. // draw all new items
  7626. ids = this.itemsData.getIds();
  7627. this._onAdd(ids);
  7628. }
  7629. };
  7630. /**
  7631. * Get the current items items
  7632. * @returns {vis.DataSet | null}
  7633. */
  7634. ItemSet.prototype.getItems = function getItems() {
  7635. return this.itemsData;
  7636. };
  7637. /**
  7638. * Handle updated items
  7639. * @param {Number[]} ids
  7640. * @private
  7641. */
  7642. ItemSet.prototype._onUpdate = function _onUpdate(ids) {
  7643. this._toQueue('update', ids);
  7644. };
  7645. /**
  7646. * Handle changed items
  7647. * @param {Number[]} ids
  7648. * @private
  7649. */
  7650. ItemSet.prototype._onAdd = function _onAdd(ids) {
  7651. this._toQueue('add', ids);
  7652. };
  7653. /**
  7654. * Handle removed items
  7655. * @param {Number[]} ids
  7656. * @private
  7657. */
  7658. ItemSet.prototype._onRemove = function _onRemove(ids) {
  7659. this._toQueue('remove', ids);
  7660. };
  7661. /**
  7662. * Put items in the queue to be added/updated/remove
  7663. * @param {String} action can be 'add', 'update', 'remove'
  7664. * @param {Number[]} ids
  7665. */
  7666. ItemSet.prototype._toQueue = function _toQueue(action, ids) {
  7667. var queue = this.queue;
  7668. ids.forEach(function (id) {
  7669. queue[id] = action;
  7670. });
  7671. if (this.controller) {
  7672. //this.requestReflow();
  7673. this.requestRepaint();
  7674. }
  7675. };
  7676. /**
  7677. * Calculate the scale and offset to convert a position on screen to the
  7678. * corresponding date and vice versa.
  7679. * After the method _updateConversion is executed once, the methods toTime
  7680. * and toScreen can be used.
  7681. * @private
  7682. */
  7683. ItemSet.prototype._updateConversion = function _updateConversion() {
  7684. var range = this.range;
  7685. if (!range) {
  7686. throw new Error('No range configured');
  7687. }
  7688. if (range.conversion) {
  7689. this.conversion = range.conversion(this.width);
  7690. }
  7691. else {
  7692. this.conversion = Range.conversion(range.start, range.end, this.width);
  7693. }
  7694. };
  7695. /**
  7696. * Convert a position on screen (pixels) to a datetime
  7697. * Before this method can be used, the method _updateConversion must be
  7698. * executed once.
  7699. * @param {int} x Position on the screen in pixels
  7700. * @return {Date} time The datetime the corresponds with given position x
  7701. */
  7702. ItemSet.prototype.toTime = function toTime(x) {
  7703. var conversion = this.conversion;
  7704. return new Date(x / conversion.scale + conversion.offset);
  7705. };
  7706. /**
  7707. * Convert a datetime (Date object) into a position on the screen
  7708. * Before this method can be used, the method _updateConversion must be
  7709. * executed once.
  7710. * @param {Date} time A date
  7711. * @return {int} x The position on the screen in pixels which corresponds
  7712. * with the given date.
  7713. */
  7714. ItemSet.prototype.toScreen = function toScreen(time) {
  7715. var conversion = this.conversion;
  7716. return (time.valueOf() - conversion.offset) * conversion.scale;
  7717. };
  7718. /**
  7719. * @constructor Item
  7720. * @param {ItemSet} parent
  7721. * @param {Object} data Object containing (optional) parameters type,
  7722. * start, end, content, group, className.
  7723. * @param {Object} [options] Options to set initial property values
  7724. * @param {Object} [defaultOptions] default options
  7725. * // TODO: describe available options
  7726. */
  7727. function Item (parent, data, options, defaultOptions) {
  7728. this.parent = parent;
  7729. this.data = data;
  7730. this.dom = null;
  7731. this.options = options || {};
  7732. this.defaultOptions = defaultOptions || {};
  7733. this.selected = false;
  7734. this.visible = false;
  7735. this.top = 0;
  7736. this.left = 0;
  7737. this.width = 0;
  7738. this.height = 0;
  7739. }
  7740. /**
  7741. * Select current item
  7742. */
  7743. Item.prototype.select = function select() {
  7744. this.selected = true;
  7745. };
  7746. /**
  7747. * Unselect current item
  7748. */
  7749. Item.prototype.unselect = function unselect() {
  7750. this.selected = false;
  7751. };
  7752. /**
  7753. * Show the Item in the DOM (when not already visible)
  7754. * @return {Boolean} changed
  7755. */
  7756. Item.prototype.show = function show() {
  7757. return false;
  7758. };
  7759. /**
  7760. * Hide the Item from the DOM (when visible)
  7761. * @return {Boolean} changed
  7762. */
  7763. Item.prototype.hide = function hide() {
  7764. return false;
  7765. };
  7766. /**
  7767. * Repaint the item
  7768. * @return {Boolean} changed
  7769. */
  7770. Item.prototype.repaint = function repaint() {
  7771. // should be implemented by the item
  7772. return false;
  7773. };
  7774. /**
  7775. * Reflow the item
  7776. * @return {Boolean} resized
  7777. */
  7778. Item.prototype.reflow = function reflow() {
  7779. // should be implemented by the item
  7780. return false;
  7781. };
  7782. /**
  7783. * Return the items width
  7784. * @return {Integer} width
  7785. */
  7786. Item.prototype.getWidth = function getWidth() {
  7787. return this.width;
  7788. }
  7789. /**
  7790. * @constructor ItemBox
  7791. * @extends Item
  7792. * @param {ItemSet} parent
  7793. * @param {Object} data Object containing parameters start
  7794. * content, className.
  7795. * @param {Object} [options] Options to set initial property values
  7796. * @param {Object} [defaultOptions] default options
  7797. * // TODO: describe available options
  7798. */
  7799. function ItemBox (parent, data, options, defaultOptions) {
  7800. this.props = {
  7801. dot: {
  7802. left: 0,
  7803. top: 0,
  7804. width: 0,
  7805. height: 0
  7806. },
  7807. line: {
  7808. top: 0,
  7809. left: 0,
  7810. width: 0,
  7811. height: 0
  7812. }
  7813. };
  7814. Item.call(this, parent, data, options, defaultOptions);
  7815. }
  7816. ItemBox.prototype = new Item (null, null);
  7817. /**
  7818. * Select the item
  7819. * @override
  7820. */
  7821. ItemBox.prototype.select = function select() {
  7822. this.selected = true;
  7823. // TODO: select and unselect
  7824. };
  7825. /**
  7826. * Unselect the item
  7827. * @override
  7828. */
  7829. ItemBox.prototype.unselect = function unselect() {
  7830. this.selected = false;
  7831. // TODO: select and unselect
  7832. };
  7833. /**
  7834. * Repaint the item
  7835. * @return {Boolean} changed
  7836. */
  7837. ItemBox.prototype.repaint = function repaint() {
  7838. // TODO: make an efficient repaint
  7839. var changed = false;
  7840. var dom = this.dom;
  7841. if (!dom) {
  7842. this._create();
  7843. dom = this.dom;
  7844. changed = true;
  7845. }
  7846. if (dom) {
  7847. if (!this.parent) {
  7848. throw new Error('Cannot repaint item: no parent attached');
  7849. }
  7850. if (!dom.box.parentNode) {
  7851. var foreground = this.parent.getForeground();
  7852. if (!foreground) {
  7853. throw new Error('Cannot repaint time axis: ' +
  7854. 'parent has no foreground container element');
  7855. }
  7856. foreground.appendChild(dom.box);
  7857. changed = true;
  7858. }
  7859. if (!dom.line.parentNode) {
  7860. var background = this.parent.getBackground();
  7861. if (!background) {
  7862. throw new Error('Cannot repaint time axis: ' +
  7863. 'parent has no background container element');
  7864. }
  7865. background.appendChild(dom.line);
  7866. changed = true;
  7867. }
  7868. if (!dom.dot.parentNode) {
  7869. var axis = this.parent.getAxis();
  7870. if (!background) {
  7871. throw new Error('Cannot repaint time axis: ' +
  7872. 'parent has no axis container element');
  7873. }
  7874. axis.appendChild(dom.dot);
  7875. changed = true;
  7876. }
  7877. // update contents
  7878. if (this.data.content != this.content) {
  7879. this.content = this.data.content;
  7880. if (this.content instanceof Element) {
  7881. dom.content.innerHTML = '';
  7882. dom.content.appendChild(this.content);
  7883. }
  7884. else if (this.data.content != undefined) {
  7885. dom.content.innerHTML = this.content;
  7886. }
  7887. else {
  7888. throw new Error('Property "content" missing in item ' + this.data.id);
  7889. }
  7890. changed = true;
  7891. }
  7892. // update class
  7893. var className = (this.data.className? ' ' + this.data.className : '') +
  7894. (this.selected ? ' selected' : '');
  7895. if (this.className != className) {
  7896. this.className = className;
  7897. dom.box.className = 'item box' + className;
  7898. dom.line.className = 'item line' + className;
  7899. dom.dot.className = 'item dot' + className;
  7900. changed = true;
  7901. }
  7902. }
  7903. return changed;
  7904. };
  7905. /**
  7906. * Show the item in the DOM (when not already visible). The items DOM will
  7907. * be created when needed.
  7908. * @return {Boolean} changed
  7909. */
  7910. ItemBox.prototype.show = function show() {
  7911. if (!this.dom || !this.dom.box.parentNode) {
  7912. return this.repaint();
  7913. }
  7914. else {
  7915. return false;
  7916. }
  7917. };
  7918. /**
  7919. * Hide the item from the DOM (when visible)
  7920. * @return {Boolean} changed
  7921. */
  7922. ItemBox.prototype.hide = function hide() {
  7923. var changed = false,
  7924. dom = this.dom;
  7925. if (dom) {
  7926. if (dom.box.parentNode) {
  7927. dom.box.parentNode.removeChild(dom.box);
  7928. changed = true;
  7929. }
  7930. if (dom.line.parentNode) {
  7931. dom.line.parentNode.removeChild(dom.line);
  7932. }
  7933. if (dom.dot.parentNode) {
  7934. dom.dot.parentNode.removeChild(dom.dot);
  7935. }
  7936. }
  7937. return changed;
  7938. };
  7939. /**
  7940. * Reflow the item: calculate its actual size and position from the DOM
  7941. * @return {boolean} resized returns true if the axis is resized
  7942. * @override
  7943. */
  7944. ItemBox.prototype.reflow = function reflow() {
  7945. var changed = 0,
  7946. update,
  7947. dom,
  7948. props,
  7949. options,
  7950. margin,
  7951. start,
  7952. align,
  7953. orientation,
  7954. top,
  7955. left,
  7956. data,
  7957. range;
  7958. if (this.data.start == undefined) {
  7959. throw new Error('Property "start" missing in item ' + this.data.id);
  7960. }
  7961. data = this.data;
  7962. range = this.parent && this.parent.range;
  7963. if (data && range) {
  7964. // TODO: account for the width of the item
  7965. var interval = (range.end - range.start);
  7966. this.visible = (data.start > range.start - interval) && (data.start < range.end + interval);
  7967. }
  7968. else {
  7969. this.visible = false;
  7970. }
  7971. if (this.visible) {
  7972. dom = this.dom;
  7973. if (dom) {
  7974. update = util.updateProperty;
  7975. props = this.props;
  7976. options = this.options;
  7977. start = this.parent.toScreen(this.data.start);
  7978. align = options.align || this.defaultOptions.align;
  7979. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  7980. orientation = options.orientation || this.defaultOptions.orientation;
  7981. changed += update(props.dot, 'height', dom.dot.offsetHeight);
  7982. changed += update(props.dot, 'width', dom.dot.offsetWidth);
  7983. changed += update(props.line, 'width', dom.line.offsetWidth);
  7984. changed += update(props.line, 'height', dom.line.offsetHeight);
  7985. changed += update(props.line, 'top', dom.line.offsetTop);
  7986. changed += update(this, 'width', dom.box.offsetWidth);
  7987. changed += update(this, 'height', dom.box.offsetHeight);
  7988. if (align == 'right') {
  7989. left = start - this.width;
  7990. }
  7991. else if (align == 'left') {
  7992. left = start;
  7993. }
  7994. else {
  7995. // default or 'center'
  7996. left = start - this.width / 2;
  7997. }
  7998. changed += update(this, 'left', left);
  7999. changed += update(props.line, 'left', start - props.line.width / 2);
  8000. changed += update(props.dot, 'left', start - props.dot.width / 2);
  8001. changed += update(props.dot, 'top', -props.dot.height / 2);
  8002. if (orientation == 'top') {
  8003. top = margin;
  8004. changed += update(this, 'top', top);
  8005. }
  8006. else {
  8007. // default or 'bottom'
  8008. var parentHeight = this.parent.height;
  8009. top = parentHeight - this.height - margin;
  8010. changed += update(this, 'top', top);
  8011. }
  8012. }
  8013. else {
  8014. changed += 1;
  8015. }
  8016. }
  8017. return (changed > 0);
  8018. };
  8019. /**
  8020. * Create an items DOM
  8021. * @private
  8022. */
  8023. ItemBox.prototype._create = function _create() {
  8024. var dom = this.dom;
  8025. if (!dom) {
  8026. this.dom = dom = {};
  8027. // create the box
  8028. dom.box = document.createElement('DIV');
  8029. // className is updated in repaint()
  8030. // contents box (inside the background box). used for making margins
  8031. dom.content = document.createElement('DIV');
  8032. dom.content.className = 'content';
  8033. dom.box.appendChild(dom.content);
  8034. // line to axis
  8035. dom.line = document.createElement('DIV');
  8036. dom.line.className = 'line';
  8037. // dot on axis
  8038. dom.dot = document.createElement('DIV');
  8039. dom.dot.className = 'dot';
  8040. }
  8041. };
  8042. /**
  8043. * Reposition the item, recalculate its left, top, and width, using the current
  8044. * range and size of the items itemset
  8045. * @override
  8046. */
  8047. ItemBox.prototype.reposition = function reposition() {
  8048. var dom = this.dom,
  8049. props = this.props,
  8050. orientation = this.options.orientation || this.defaultOptions.orientation;
  8051. if (dom) {
  8052. var box = dom.box,
  8053. line = dom.line,
  8054. dot = dom.dot;
  8055. box.style.left = this.left + 'px';
  8056. box.style.top = this.top + 'px';
  8057. line.style.left = props.line.left + 'px';
  8058. if (orientation == 'top') {
  8059. line.style.top = 0 + 'px';
  8060. line.style.height = this.top + 'px';
  8061. }
  8062. else {
  8063. // orientation 'bottom'
  8064. line.style.top = (this.top + this.height) + 'px';
  8065. line.style.height = Math.max(this.parent.height - this.top - this.height +
  8066. this.props.dot.height / 2, 0) + 'px';
  8067. }
  8068. dot.style.left = props.dot.left + 'px';
  8069. dot.style.top = props.dot.top + 'px';
  8070. }
  8071. };
  8072. /**
  8073. * @constructor ItemPoint
  8074. * @extends Item
  8075. * @param {ItemSet} parent
  8076. * @param {Object} data Object containing parameters start
  8077. * content, className.
  8078. * @param {Object} [options] Options to set initial property values
  8079. * @param {Object} [defaultOptions] default options
  8080. * // TODO: describe available options
  8081. */
  8082. function ItemPoint (parent, data, options, defaultOptions) {
  8083. this.props = {
  8084. dot: {
  8085. top: 0,
  8086. width: 0,
  8087. height: 0
  8088. },
  8089. content: {
  8090. height: 0,
  8091. marginLeft: 0
  8092. }
  8093. };
  8094. Item.call(this, parent, data, options, defaultOptions);
  8095. }
  8096. ItemPoint.prototype = new Item (null, null);
  8097. /**
  8098. * Select the item
  8099. * @override
  8100. */
  8101. ItemPoint.prototype.select = function select() {
  8102. this.selected = true;
  8103. // TODO: select and unselect
  8104. };
  8105. /**
  8106. * Unselect the item
  8107. * @override
  8108. */
  8109. ItemPoint.prototype.unselect = function unselect() {
  8110. this.selected = false;
  8111. // TODO: select and unselect
  8112. };
  8113. /**
  8114. * Repaint the item
  8115. * @return {Boolean} changed
  8116. */
  8117. ItemPoint.prototype.repaint = function repaint() {
  8118. // TODO: make an efficient repaint
  8119. var changed = false;
  8120. var dom = this.dom;
  8121. if (!dom) {
  8122. this._create();
  8123. dom = this.dom;
  8124. changed = true;
  8125. }
  8126. if (dom) {
  8127. if (!this.parent) {
  8128. throw new Error('Cannot repaint item: no parent attached');
  8129. }
  8130. var foreground = this.parent.getForeground();
  8131. if (!foreground) {
  8132. throw new Error('Cannot repaint time axis: ' +
  8133. 'parent has no foreground container element');
  8134. }
  8135. if (!dom.point.parentNode) {
  8136. foreground.appendChild(dom.point);
  8137. foreground.appendChild(dom.point);
  8138. changed = true;
  8139. }
  8140. // update contents
  8141. if (this.data.content != this.content) {
  8142. this.content = this.data.content;
  8143. if (this.content instanceof Element) {
  8144. dom.content.innerHTML = '';
  8145. dom.content.appendChild(this.content);
  8146. }
  8147. else if (this.data.content != undefined) {
  8148. dom.content.innerHTML = this.content;
  8149. }
  8150. else {
  8151. throw new Error('Property "content" missing in item ' + this.data.id);
  8152. }
  8153. changed = true;
  8154. }
  8155. // update class
  8156. var className = (this.data.className? ' ' + this.data.className : '') +
  8157. (this.selected ? ' selected' : '');
  8158. if (this.className != className) {
  8159. this.className = className;
  8160. dom.point.className = 'item point' + className;
  8161. changed = true;
  8162. }
  8163. }
  8164. return changed;
  8165. };
  8166. /**
  8167. * Show the item in the DOM (when not already visible). The items DOM will
  8168. * be created when needed.
  8169. * @return {Boolean} changed
  8170. */
  8171. ItemPoint.prototype.show = function show() {
  8172. if (!this.dom || !this.dom.point.parentNode) {
  8173. return this.repaint();
  8174. }
  8175. else {
  8176. return false;
  8177. }
  8178. };
  8179. /**
  8180. * Hide the item from the DOM (when visible)
  8181. * @return {Boolean} changed
  8182. */
  8183. ItemPoint.prototype.hide = function hide() {
  8184. var changed = false,
  8185. dom = this.dom;
  8186. if (dom) {
  8187. if (dom.point.parentNode) {
  8188. dom.point.parentNode.removeChild(dom.point);
  8189. changed = true;
  8190. }
  8191. }
  8192. return changed;
  8193. };
  8194. /**
  8195. * Reflow the item: calculate its actual size from the DOM
  8196. * @return {boolean} resized returns true if the axis is resized
  8197. * @override
  8198. */
  8199. ItemPoint.prototype.reflow = function reflow() {
  8200. var changed = 0,
  8201. update,
  8202. dom,
  8203. props,
  8204. options,
  8205. margin,
  8206. orientation,
  8207. start,
  8208. top,
  8209. data,
  8210. range;
  8211. if (this.data.start == undefined) {
  8212. throw new Error('Property "start" missing in item ' + this.data.id);
  8213. }
  8214. data = this.data;
  8215. range = this.parent && this.parent.range;
  8216. if (data && range) {
  8217. // TODO: account for the width of the item
  8218. var interval = (range.end - range.start);
  8219. this.visible = (data.start > range.start - interval) && (data.start < range.end);
  8220. }
  8221. else {
  8222. this.visible = false;
  8223. }
  8224. if (this.visible) {
  8225. dom = this.dom;
  8226. if (dom) {
  8227. update = util.updateProperty;
  8228. props = this.props;
  8229. options = this.options;
  8230. orientation = options.orientation || this.defaultOptions.orientation;
  8231. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  8232. start = this.parent.toScreen(this.data.start);
  8233. changed += update(this, 'width', dom.point.offsetWidth);
  8234. changed += update(this, 'height', dom.point.offsetHeight);
  8235. changed += update(props.dot, 'width', dom.dot.offsetWidth);
  8236. changed += update(props.dot, 'height', dom.dot.offsetHeight);
  8237. changed += update(props.content, 'height', dom.content.offsetHeight);
  8238. if (orientation == 'top') {
  8239. top = margin;
  8240. }
  8241. else {
  8242. // default or 'bottom'
  8243. var parentHeight = this.parent.height;
  8244. top = Math.max(parentHeight - this.height - margin, 0);
  8245. }
  8246. changed += update(this, 'top', top);
  8247. changed += update(this, 'left', start - props.dot.width / 2);
  8248. changed += update(props.content, 'marginLeft', 1.5 * props.dot.width);
  8249. //changed += update(props.content, 'marginRight', 0.5 * props.dot.width); // TODO
  8250. changed += update(props.dot, 'top', (this.height - props.dot.height) / 2);
  8251. }
  8252. else {
  8253. changed += 1;
  8254. }
  8255. }
  8256. return (changed > 0);
  8257. };
  8258. /**
  8259. * Create an items DOM
  8260. * @private
  8261. */
  8262. ItemPoint.prototype._create = function _create() {
  8263. var dom = this.dom;
  8264. if (!dom) {
  8265. this.dom = dom = {};
  8266. // background box
  8267. dom.point = document.createElement('div');
  8268. // className is updated in repaint()
  8269. // contents box, right from the dot
  8270. dom.content = document.createElement('div');
  8271. dom.content.className = 'content';
  8272. dom.point.appendChild(dom.content);
  8273. // dot at start
  8274. dom.dot = document.createElement('div');
  8275. dom.dot.className = 'dot';
  8276. dom.point.appendChild(dom.dot);
  8277. }
  8278. };
  8279. /**
  8280. * Reposition the item, recalculate its left, top, and width, using the current
  8281. * range and size of the items itemset
  8282. * @override
  8283. */
  8284. ItemPoint.prototype.reposition = function reposition() {
  8285. var dom = this.dom,
  8286. props = this.props;
  8287. if (dom) {
  8288. dom.point.style.top = this.top + 'px';
  8289. dom.point.style.left = this.left + 'px';
  8290. dom.content.style.marginLeft = props.content.marginLeft + 'px';
  8291. //dom.content.style.marginRight = props.content.marginRight + 'px'; // TODO
  8292. dom.dot.style.top = props.dot.top + 'px';
  8293. }
  8294. };
  8295. /**
  8296. * @constructor ItemRange
  8297. * @extends Item
  8298. * @param {ItemSet} parent
  8299. * @param {Object} data Object containing parameters start, end
  8300. * content, className.
  8301. * @param {Object} [options] Options to set initial property values
  8302. * @param {Object} [defaultOptions] default options
  8303. * // TODO: describe available options
  8304. */
  8305. function ItemRange (parent, data, options, defaultOptions) {
  8306. this.props = {
  8307. content: {
  8308. left: 0,
  8309. width: 0
  8310. }
  8311. };
  8312. Item.call(this, parent, data, options, defaultOptions);
  8313. }
  8314. ItemRange.prototype = new Item (null, null);
  8315. /**
  8316. * Select the item
  8317. * @override
  8318. */
  8319. ItemRange.prototype.select = function select() {
  8320. this.selected = true;
  8321. // TODO: select and unselect
  8322. };
  8323. /**
  8324. * Unselect the item
  8325. * @override
  8326. */
  8327. ItemRange.prototype.unselect = function unselect() {
  8328. this.selected = false;
  8329. // TODO: select and unselect
  8330. };
  8331. /**
  8332. * Repaint the item
  8333. * @return {Boolean} changed
  8334. */
  8335. ItemRange.prototype.repaint = function repaint() {
  8336. // TODO: make an efficient repaint
  8337. var changed = false;
  8338. var dom = this.dom;
  8339. if (!dom) {
  8340. this._create();
  8341. dom = this.dom;
  8342. changed = true;
  8343. }
  8344. if (dom) {
  8345. if (!this.parent) {
  8346. throw new Error('Cannot repaint item: no parent attached');
  8347. }
  8348. var foreground = this.parent.getForeground();
  8349. if (!foreground) {
  8350. throw new Error('Cannot repaint time axis: ' +
  8351. 'parent has no foreground container element');
  8352. }
  8353. if (!dom.box.parentNode) {
  8354. foreground.appendChild(dom.box);
  8355. changed = true;
  8356. }
  8357. // update content
  8358. if (this.data.content != this.content) {
  8359. this.content = this.data.content;
  8360. if (this.content instanceof Element) {
  8361. dom.content.innerHTML = '';
  8362. dom.content.appendChild(this.content);
  8363. }
  8364. else if (this.data.content != undefined) {
  8365. dom.content.innerHTML = this.content;
  8366. }
  8367. else {
  8368. throw new Error('Property "content" missing in item ' + this.data.id);
  8369. }
  8370. changed = true;
  8371. }
  8372. // update class
  8373. var className = this.data.className ? (' ' + this.data.className) : '';
  8374. if (this.className != className) {
  8375. this.className = className;
  8376. dom.box.className = 'item range' + className;
  8377. changed = true;
  8378. }
  8379. }
  8380. return changed;
  8381. };
  8382. /**
  8383. * Show the item in the DOM (when not already visible). The items DOM will
  8384. * be created when needed.
  8385. * @return {Boolean} changed
  8386. */
  8387. ItemRange.prototype.show = function show() {
  8388. if (!this.dom || !this.dom.box.parentNode) {
  8389. return this.repaint();
  8390. }
  8391. else {
  8392. return false;
  8393. }
  8394. };
  8395. /**
  8396. * Hide the item from the DOM (when visible)
  8397. * @return {Boolean} changed
  8398. */
  8399. ItemRange.prototype.hide = function hide() {
  8400. var changed = false,
  8401. dom = this.dom;
  8402. if (dom) {
  8403. if (dom.box.parentNode) {
  8404. dom.box.parentNode.removeChild(dom.box);
  8405. changed = true;
  8406. }
  8407. }
  8408. return changed;
  8409. };
  8410. /**
  8411. * Reflow the item: calculate its actual size from the DOM
  8412. * @return {boolean} resized returns true if the axis is resized
  8413. * @override
  8414. */
  8415. ItemRange.prototype.reflow = function reflow() {
  8416. var changed = 0,
  8417. dom,
  8418. props,
  8419. options,
  8420. margin,
  8421. padding,
  8422. parent,
  8423. start,
  8424. end,
  8425. data,
  8426. range,
  8427. update,
  8428. box,
  8429. parentWidth,
  8430. contentLeft,
  8431. orientation,
  8432. top;
  8433. if (this.data.start == undefined) {
  8434. throw new Error('Property "start" missing in item ' + this.data.id);
  8435. }
  8436. if (this.data.end == undefined) {
  8437. throw new Error('Property "end" missing in item ' + this.data.id);
  8438. }
  8439. data = this.data;
  8440. range = this.parent && this.parent.range;
  8441. if (data && range) {
  8442. // TODO: account for the width of the item. Take some margin
  8443. this.visible = (data.start < range.end) && (data.end > range.start);
  8444. }
  8445. else {
  8446. this.visible = false;
  8447. }
  8448. if (this.visible) {
  8449. dom = this.dom;
  8450. if (dom) {
  8451. props = this.props;
  8452. options = this.options;
  8453. parent = this.parent;
  8454. start = parent.toScreen(this.data.start);
  8455. end = parent.toScreen(this.data.end);
  8456. update = util.updateProperty;
  8457. box = dom.box;
  8458. parentWidth = parent.width;
  8459. orientation = options.orientation || this.defaultOptions.orientation;
  8460. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  8461. padding = options.padding || this.defaultOptions.padding;
  8462. changed += update(props.content, 'width', dom.content.offsetWidth);
  8463. changed += update(this, 'height', box.offsetHeight);
  8464. // limit the width of the this, as browsers cannot draw very wide divs
  8465. if (start < -parentWidth) {
  8466. start = -parentWidth;
  8467. }
  8468. if (end > 2 * parentWidth) {
  8469. end = 2 * parentWidth;
  8470. }
  8471. // when range exceeds left of the window, position the contents at the left of the visible area
  8472. if (start < 0) {
  8473. contentLeft = Math.min(-start,
  8474. (end - start - props.content.width - 2 * padding));
  8475. // TODO: remove the need for options.padding. it's terrible.
  8476. }
  8477. else {
  8478. contentLeft = 0;
  8479. }
  8480. changed += update(props.content, 'left', contentLeft);
  8481. if (orientation == 'top') {
  8482. top = margin;
  8483. changed += update(this, 'top', top);
  8484. }
  8485. else {
  8486. // default or 'bottom'
  8487. top = parent.height - this.height - margin;
  8488. changed += update(this, 'top', top);
  8489. }
  8490. changed += update(this, 'left', start);
  8491. changed += update(this, 'width', Math.max(end - start, 1)); // TODO: reckon with border width;
  8492. }
  8493. else {
  8494. changed += 1;
  8495. }
  8496. }
  8497. return (changed > 0);
  8498. };
  8499. /**
  8500. * Create an items DOM
  8501. * @private
  8502. */
  8503. ItemRange.prototype._create = function _create() {
  8504. var dom = this.dom;
  8505. if (!dom) {
  8506. this.dom = dom = {};
  8507. // background box
  8508. dom.box = document.createElement('div');
  8509. // className is updated in repaint()
  8510. // contents box
  8511. dom.content = document.createElement('div');
  8512. dom.content.className = 'content';
  8513. dom.box.appendChild(dom.content);
  8514. }
  8515. };
  8516. /**
  8517. * Reposition the item, recalculate its left, top, and width, using the current
  8518. * range and size of the items itemset
  8519. * @override
  8520. */
  8521. ItemRange.prototype.reposition = function reposition() {
  8522. var dom = this.dom,
  8523. props = this.props;
  8524. if (dom) {
  8525. dom.box.style.top = this.top + 'px';
  8526. dom.box.style.left = this.left + 'px';
  8527. dom.box.style.width = this.width + 'px';
  8528. dom.content.style.left = props.content.left + 'px';
  8529. }
  8530. };
  8531. /**
  8532. * @constructor ItemRangeOverflow
  8533. * @extends ItemRange
  8534. * @param {ItemSet} parent
  8535. * @param {Object} data Object containing parameters start, end
  8536. * content, className.
  8537. * @param {Object} [options] Options to set initial property values
  8538. * @param {Object} [defaultOptions] default options
  8539. * // TODO: describe available options
  8540. */
  8541. function ItemRangeOverflow (parent, data, options, defaultOptions) {
  8542. this.props = {
  8543. content: {
  8544. left: 0,
  8545. width: 0
  8546. }
  8547. };
  8548. ItemRange.call(this, parent, data, options, defaultOptions);
  8549. }
  8550. ItemRangeOverflow.prototype = new ItemRange (null, null);
  8551. /**
  8552. * Repaint the item
  8553. * @return {Boolean} changed
  8554. */
  8555. ItemRangeOverflow.prototype.repaint = function repaint() {
  8556. // TODO: make an efficient repaint
  8557. var changed = false;
  8558. var dom = this.dom;
  8559. if (!dom) {
  8560. this._create();
  8561. dom = this.dom;
  8562. changed = true;
  8563. }
  8564. if (dom) {
  8565. if (!this.parent) {
  8566. throw new Error('Cannot repaint item: no parent attached');
  8567. }
  8568. var foreground = this.parent.getForeground();
  8569. if (!foreground) {
  8570. throw new Error('Cannot repaint time axis: ' +
  8571. 'parent has no foreground container element');
  8572. }
  8573. if (!dom.box.parentNode) {
  8574. foreground.appendChild(dom.box);
  8575. changed = true;
  8576. }
  8577. // update content
  8578. if (this.data.content != this.content) {
  8579. this.content = this.data.content;
  8580. if (this.content instanceof Element) {
  8581. dom.content.innerHTML = '';
  8582. dom.content.appendChild(this.content);
  8583. }
  8584. else if (this.data.content != undefined) {
  8585. dom.content.innerHTML = this.content;
  8586. }
  8587. else {
  8588. throw new Error('Property "content" missing in item ' + this.data.id);
  8589. }
  8590. changed = true;
  8591. }
  8592. // update class
  8593. var className = this.data.className ? (' ' + this.data.className) : '';
  8594. if (this.className != className) {
  8595. this.className = className;
  8596. dom.box.className = 'item rangeoverflow' + className;
  8597. changed = true;
  8598. }
  8599. }
  8600. return changed;
  8601. };
  8602. /**
  8603. * Return the items width
  8604. * @return {Number} width
  8605. */
  8606. ItemRangeOverflow.prototype.getWidth = function getWidth() {
  8607. if (this.props.content !== undefined && this.width < this.props.content.width)
  8608. return this.props.content.width;
  8609. else
  8610. return this.width;
  8611. };
  8612. /**
  8613. * @constructor Group
  8614. * @param {GroupSet} parent
  8615. * @param {Number | String} groupId
  8616. * @param {Object} [options] Options to set initial property values
  8617. * // TODO: describe available options
  8618. * @extends Component
  8619. */
  8620. function Group (parent, groupId, options) {
  8621. this.id = util.randomUUID();
  8622. this.parent = parent;
  8623. this.groupId = groupId;
  8624. this.itemset = null; // ItemSet
  8625. this.options = options || {};
  8626. this.options.top = 0;
  8627. this.props = {
  8628. label: {
  8629. width: 0,
  8630. height: 0
  8631. }
  8632. };
  8633. this.top = 0;
  8634. this.left = 0;
  8635. this.width = 0;
  8636. this.height = 0;
  8637. }
  8638. Group.prototype = new Component();
  8639. // TODO: comment
  8640. Group.prototype.setOptions = Component.prototype.setOptions;
  8641. /**
  8642. * Get the container element of the panel, which can be used by a child to
  8643. * add its own widgets.
  8644. * @returns {HTMLElement} container
  8645. */
  8646. Group.prototype.getContainer = function () {
  8647. return this.parent.getContainer();
  8648. };
  8649. /**
  8650. * Set item set for the group. The group will create a view on the itemset,
  8651. * filtered by the groups id.
  8652. * @param {DataSet | DataView} items
  8653. */
  8654. Group.prototype.setItems = function setItems(items) {
  8655. if (this.itemset) {
  8656. // remove current item set
  8657. this.itemset.hide();
  8658. this.itemset.setItems();
  8659. this.parent.controller.remove(this.itemset);
  8660. this.itemset = null;
  8661. }
  8662. if (items) {
  8663. var groupId = this.groupId;
  8664. var itemsetOptions = Object.create(this.options);
  8665. this.itemset = new ItemSet(this, null, itemsetOptions);
  8666. this.itemset.setRange(this.parent.range);
  8667. this.view = new DataView(items, {
  8668. filter: function (item) {
  8669. return item.group == groupId;
  8670. }
  8671. });
  8672. this.itemset.setItems(this.view);
  8673. this.parent.controller.add(this.itemset);
  8674. }
  8675. };
  8676. /**
  8677. * Repaint the item
  8678. * @return {Boolean} changed
  8679. */
  8680. Group.prototype.repaint = function repaint() {
  8681. return false;
  8682. };
  8683. /**
  8684. * Reflow the item
  8685. * @return {Boolean} resized
  8686. */
  8687. Group.prototype.reflow = function reflow() {
  8688. var changed = 0,
  8689. update = util.updateProperty;
  8690. changed += update(this, 'top', this.itemset ? this.itemset.top : 0);
  8691. changed += update(this, 'height', this.itemset ? this.itemset.height : 0);
  8692. // TODO: reckon with the height of the group label
  8693. if (this.label) {
  8694. var inner = this.label.firstChild;
  8695. changed += update(this.props.label, 'width', inner.clientWidth);
  8696. changed += update(this.props.label, 'height', inner.clientHeight);
  8697. }
  8698. else {
  8699. changed += update(this.props.label, 'width', 0);
  8700. changed += update(this.props.label, 'height', 0);
  8701. }
  8702. return (changed > 0);
  8703. };
  8704. /**
  8705. * An GroupSet holds a set of groups
  8706. * @param {Component} parent
  8707. * @param {Component[]} [depends] Components on which this components depends
  8708. * (except for the parent)
  8709. * @param {Object} [options] See GroupSet.setOptions for the available
  8710. * options.
  8711. * @constructor GroupSet
  8712. * @extends Panel
  8713. */
  8714. function GroupSet(parent, depends, options) {
  8715. this.id = util.randomUUID();
  8716. this.parent = parent;
  8717. this.depends = depends;
  8718. this.options = options || {};
  8719. this.range = null; // Range or Object {start: number, end: number}
  8720. this.itemsData = null; // DataSet with items
  8721. this.groupsData = null; // DataSet with groups
  8722. this.groups = {}; // map with groups
  8723. this.dom = {};
  8724. this.props = {
  8725. labels: {
  8726. width: 0
  8727. }
  8728. };
  8729. // TODO: implement right orientation of the labels
  8730. // changes in groups are queued key/value map containing id/action
  8731. this.queue = {};
  8732. var me = this;
  8733. this.listeners = {
  8734. 'add': function (event, params) {
  8735. me._onAdd(params.items);
  8736. },
  8737. 'update': function (event, params) {
  8738. me._onUpdate(params.items);
  8739. },
  8740. 'remove': function (event, params) {
  8741. me._onRemove(params.items);
  8742. }
  8743. };
  8744. }
  8745. GroupSet.prototype = new Panel();
  8746. /**
  8747. * Set options for the GroupSet. Existing options will be extended/overwritten.
  8748. * @param {Object} [options] The following options are available:
  8749. * {String | function} groupsOrder
  8750. * TODO: describe options
  8751. */
  8752. GroupSet.prototype.setOptions = Component.prototype.setOptions;
  8753. GroupSet.prototype.setRange = function (range) {
  8754. // TODO: implement setRange
  8755. };
  8756. /**
  8757. * Set items
  8758. * @param {vis.DataSet | null} items
  8759. */
  8760. GroupSet.prototype.setItems = function setItems(items) {
  8761. this.itemsData = items;
  8762. for (var id in this.groups) {
  8763. if (this.groups.hasOwnProperty(id)) {
  8764. var group = this.groups[id];
  8765. group.setItems(items);
  8766. }
  8767. }
  8768. };
  8769. /**
  8770. * Get items
  8771. * @return {vis.DataSet | null} items
  8772. */
  8773. GroupSet.prototype.getItems = function getItems() {
  8774. return this.itemsData;
  8775. };
  8776. /**
  8777. * Set range (start and end).
  8778. * @param {Range | Object} range A Range or an object containing start and end.
  8779. */
  8780. GroupSet.prototype.setRange = function setRange(range) {
  8781. this.range = range;
  8782. };
  8783. /**
  8784. * Set groups
  8785. * @param {vis.DataSet} groups
  8786. */
  8787. GroupSet.prototype.setGroups = function setGroups(groups) {
  8788. var me = this,
  8789. ids;
  8790. // unsubscribe from current dataset
  8791. if (this.groupsData) {
  8792. util.forEach(this.listeners, function (callback, event) {
  8793. me.groupsData.unsubscribe(event, callback);
  8794. });
  8795. // remove all drawn groups
  8796. ids = this.groupsData.getIds();
  8797. this._onRemove(ids);
  8798. }
  8799. // replace the dataset
  8800. if (!groups) {
  8801. this.groupsData = null;
  8802. }
  8803. else if (groups instanceof DataSet) {
  8804. this.groupsData = groups;
  8805. }
  8806. else {
  8807. this.groupsData = new DataSet({
  8808. convert: {
  8809. start: 'Date',
  8810. end: 'Date'
  8811. }
  8812. });
  8813. this.groupsData.add(groups);
  8814. }
  8815. if (this.groupsData) {
  8816. // subscribe to new dataset
  8817. var id = this.id;
  8818. util.forEach(this.listeners, function (callback, event) {
  8819. me.groupsData.subscribe(event, callback, id);
  8820. });
  8821. // draw all new groups
  8822. ids = this.groupsData.getIds();
  8823. this._onAdd(ids);
  8824. }
  8825. };
  8826. /**
  8827. * Get groups
  8828. * @return {vis.DataSet | null} groups
  8829. */
  8830. GroupSet.prototype.getGroups = function getGroups() {
  8831. return this.groupsData;
  8832. };
  8833. /**
  8834. * Repaint the component
  8835. * @return {Boolean} changed
  8836. */
  8837. GroupSet.prototype.repaint = function repaint() {
  8838. var changed = 0,
  8839. i, id, group, label,
  8840. update = util.updateProperty,
  8841. asSize = util.option.asSize,
  8842. asElement = util.option.asElement,
  8843. options = this.options,
  8844. frame = this.dom.frame,
  8845. labels = this.dom.labels,
  8846. labelSet = this.dom.labelSet;
  8847. // create frame
  8848. if (!this.parent) {
  8849. throw new Error('Cannot repaint groupset: no parent attached');
  8850. }
  8851. var parentContainer = this.parent.getContainer();
  8852. if (!parentContainer) {
  8853. throw new Error('Cannot repaint groupset: parent has no container element');
  8854. }
  8855. if (!frame) {
  8856. frame = document.createElement('div');
  8857. frame.className = 'groupset';
  8858. this.dom.frame = frame;
  8859. var className = options.className;
  8860. if (className) {
  8861. util.addClassName(frame, util.option.asString(className));
  8862. }
  8863. changed += 1;
  8864. }
  8865. if (!frame.parentNode) {
  8866. parentContainer.appendChild(frame);
  8867. changed += 1;
  8868. }
  8869. // create labels
  8870. var labelContainer = asElement(options.labelContainer);
  8871. if (!labelContainer) {
  8872. throw new Error('Cannot repaint groupset: option "labelContainer" not defined');
  8873. }
  8874. if (!labels) {
  8875. labels = document.createElement('div');
  8876. labels.className = 'labels';
  8877. this.dom.labels = labels;
  8878. }
  8879. if (!labelSet) {
  8880. labelSet = document.createElement('div');
  8881. labelSet.className = 'label-set';
  8882. labels.appendChild(labelSet);
  8883. this.dom.labelSet = labelSet;
  8884. }
  8885. if (!labels.parentNode || labels.parentNode != labelContainer) {
  8886. if (labels.parentNode) {
  8887. labels.parentNode.removeChild(labels.parentNode);
  8888. }
  8889. labelContainer.appendChild(labels);
  8890. }
  8891. // reposition frame
  8892. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  8893. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  8894. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  8895. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  8896. // reposition labels
  8897. changed += update(labelSet.style, 'top', asSize(options.top, '0px'));
  8898. changed += update(labelSet.style, 'height', asSize(options.height, this.height + 'px'));
  8899. var me = this,
  8900. queue = this.queue,
  8901. groups = this.groups,
  8902. groupsData = this.groupsData;
  8903. // show/hide added/changed/removed groups
  8904. var ids = Object.keys(queue);
  8905. if (ids.length) {
  8906. ids.forEach(function (id) {
  8907. var action = queue[id];
  8908. var group = groups[id];
  8909. //noinspection FallthroughInSwitchStatementJS
  8910. switch (action) {
  8911. case 'add':
  8912. case 'update':
  8913. if (!group) {
  8914. var groupOptions = Object.create(me.options);
  8915. util.extend(groupOptions, {
  8916. height: null,
  8917. maxHeight: null
  8918. });
  8919. group = new Group(me, id, groupOptions);
  8920. group.setItems(me.itemsData); // attach items data
  8921. groups[id] = group;
  8922. me.controller.add(group);
  8923. }
  8924. // TODO: update group data
  8925. group.data = groupsData.get(id);
  8926. delete queue[id];
  8927. break;
  8928. case 'remove':
  8929. if (group) {
  8930. group.setItems(); // detach items data
  8931. delete groups[id];
  8932. me.controller.remove(group);
  8933. }
  8934. // update lists
  8935. delete queue[id];
  8936. break;
  8937. default:
  8938. console.log('Error: unknown action "' + action + '"');
  8939. }
  8940. });
  8941. // the groupset depends on each of the groups
  8942. //this.depends = this.groups; // TODO: gives a circular reference through the parent
  8943. // TODO: apply dependencies of the groupset
  8944. // update the top positions of the groups in the correct order
  8945. var orderedGroups = this.groupsData.getIds({
  8946. order: this.options.groupOrder
  8947. });
  8948. for (i = 0; i < orderedGroups.length; i++) {
  8949. (function (group, prevGroup) {
  8950. var top = 0;
  8951. if (prevGroup) {
  8952. top = function () {
  8953. // TODO: top must reckon with options.maxHeight
  8954. return prevGroup.top + prevGroup.height;
  8955. }
  8956. }
  8957. group.setOptions({
  8958. top: top
  8959. });
  8960. })(groups[orderedGroups[i]], groups[orderedGroups[i - 1]]);
  8961. }
  8962. // (re)create the labels
  8963. while (labelSet.firstChild) {
  8964. labelSet.removeChild(labelSet.firstChild);
  8965. }
  8966. for (i = 0; i < orderedGroups.length; i++) {
  8967. id = orderedGroups[i];
  8968. label = this._createLabel(id);
  8969. labelSet.appendChild(label);
  8970. }
  8971. changed++;
  8972. }
  8973. // reposition the labels
  8974. // TODO: labels are not displayed correctly when orientation=='top'
  8975. // TODO: width of labelPanel is not immediately updated on a change in groups
  8976. for (id in groups) {
  8977. if (groups.hasOwnProperty(id)) {
  8978. group = groups[id];
  8979. label = group.label;
  8980. if (label) {
  8981. label.style.top = group.top + 'px';
  8982. label.style.height = group.height + 'px';
  8983. }
  8984. }
  8985. }
  8986. return (changed > 0);
  8987. };
  8988. /**
  8989. * Create a label for group with given id
  8990. * @param {Number} id
  8991. * @return {Element} label
  8992. * @private
  8993. */
  8994. GroupSet.prototype._createLabel = function(id) {
  8995. var group = this.groups[id];
  8996. var label = document.createElement('div');
  8997. label.className = 'label';
  8998. var inner = document.createElement('div');
  8999. inner.className = 'inner';
  9000. label.appendChild(inner);
  9001. var content = group.data && group.data.content;
  9002. if (content instanceof Element) {
  9003. inner.appendChild(content);
  9004. }
  9005. else if (content != undefined) {
  9006. inner.innerHTML = content;
  9007. }
  9008. var className = group.data && group.data.className;
  9009. if (className) {
  9010. util.addClassName(label, className);
  9011. }
  9012. group.label = label; // TODO: not so nice, parking labels in the group this way!!!
  9013. return label;
  9014. };
  9015. /**
  9016. * Get container element
  9017. * @return {HTMLElement} container
  9018. */
  9019. GroupSet.prototype.getContainer = function getContainer() {
  9020. return this.dom.frame;
  9021. };
  9022. /**
  9023. * Get the width of the group labels
  9024. * @return {Number} width
  9025. */
  9026. GroupSet.prototype.getLabelsWidth = function getContainer() {
  9027. return this.props.labels.width;
  9028. };
  9029. /**
  9030. * Reflow the component
  9031. * @return {Boolean} resized
  9032. */
  9033. GroupSet.prototype.reflow = function reflow() {
  9034. var changed = 0,
  9035. id, group,
  9036. options = this.options,
  9037. update = util.updateProperty,
  9038. asNumber = util.option.asNumber,
  9039. asSize = util.option.asSize,
  9040. frame = this.dom.frame;
  9041. if (frame) {
  9042. var maxHeight = asNumber(options.maxHeight);
  9043. var fixedHeight = (asSize(options.height) != null);
  9044. var height;
  9045. if (fixedHeight) {
  9046. height = frame.offsetHeight;
  9047. }
  9048. else {
  9049. // height is not specified, calculate the sum of the height of all groups
  9050. height = 0;
  9051. for (id in this.groups) {
  9052. if (this.groups.hasOwnProperty(id)) {
  9053. group = this.groups[id];
  9054. height += group.height;
  9055. }
  9056. }
  9057. }
  9058. if (maxHeight != null) {
  9059. height = Math.min(height, maxHeight);
  9060. }
  9061. changed += update(this, 'height', height);
  9062. changed += update(this, 'top', frame.offsetTop);
  9063. changed += update(this, 'left', frame.offsetLeft);
  9064. changed += update(this, 'width', frame.offsetWidth);
  9065. }
  9066. // calculate the maximum width of the labels
  9067. var width = 0;
  9068. for (id in this.groups) {
  9069. if (this.groups.hasOwnProperty(id)) {
  9070. group = this.groups[id];
  9071. var labelWidth = group.props && group.props.label && group.props.label.width || 0;
  9072. width = Math.max(width, labelWidth);
  9073. }
  9074. }
  9075. changed += update(this.props.labels, 'width', width);
  9076. return (changed > 0);
  9077. };
  9078. /**
  9079. * Hide the component from the DOM
  9080. * @return {Boolean} changed
  9081. */
  9082. GroupSet.prototype.hide = function hide() {
  9083. if (this.dom.frame && this.dom.frame.parentNode) {
  9084. this.dom.frame.parentNode.removeChild(this.dom.frame);
  9085. return true;
  9086. }
  9087. else {
  9088. return false;
  9089. }
  9090. };
  9091. /**
  9092. * Show the component in the DOM (when not already visible).
  9093. * A repaint will be executed when the component is not visible
  9094. * @return {Boolean} changed
  9095. */
  9096. GroupSet.prototype.show = function show() {
  9097. if (!this.dom.frame || !this.dom.frame.parentNode) {
  9098. return this.repaint();
  9099. }
  9100. else {
  9101. return false;
  9102. }
  9103. };
  9104. /**
  9105. * Handle updated groups
  9106. * @param {Number[]} ids
  9107. * @private
  9108. */
  9109. GroupSet.prototype._onUpdate = function _onUpdate(ids) {
  9110. this._toQueue(ids, 'update');
  9111. };
  9112. /**
  9113. * Handle changed groups
  9114. * @param {Number[]} ids
  9115. * @private
  9116. */
  9117. GroupSet.prototype._onAdd = function _onAdd(ids) {
  9118. this._toQueue(ids, 'add');
  9119. };
  9120. /**
  9121. * Handle removed groups
  9122. * @param {Number[]} ids
  9123. * @private
  9124. */
  9125. GroupSet.prototype._onRemove = function _onRemove(ids) {
  9126. this._toQueue(ids, 'remove');
  9127. };
  9128. /**
  9129. * Put groups in the queue to be added/updated/remove
  9130. * @param {Number[]} ids
  9131. * @param {String} action can be 'add', 'update', 'remove'
  9132. */
  9133. GroupSet.prototype._toQueue = function _toQueue(ids, action) {
  9134. var queue = this.queue;
  9135. ids.forEach(function (id) {
  9136. queue[id] = action;
  9137. });
  9138. if (this.controller) {
  9139. //this.requestReflow();
  9140. this.requestRepaint();
  9141. }
  9142. };
  9143. /**
  9144. * Create a timeline visualization
  9145. * @param {HTMLElement} container
  9146. * @param {vis.DataSet | Array | DataTable} [items]
  9147. * @param {Object} [options] See Timeline.setOptions for the available options.
  9148. * @constructor
  9149. */
  9150. function Timeline (container, items, options) {
  9151. var me = this;
  9152. var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0);
  9153. this.options = {
  9154. orientation: 'bottom',
  9155. min: null,
  9156. max: null,
  9157. zoomMin: 10, // milliseconds
  9158. zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000, // milliseconds
  9159. // moveable: true, // TODO: option moveable
  9160. // zoomable: true, // TODO: option zoomable
  9161. showMinorLabels: true,
  9162. showMajorLabels: true,
  9163. showCurrentTime: false,
  9164. showCustomTime: false,
  9165. autoResize: false
  9166. };
  9167. // controller
  9168. this.controller = new Controller();
  9169. // root panel
  9170. if (!container) {
  9171. throw new Error('No container element provided');
  9172. }
  9173. var rootOptions = Object.create(this.options);
  9174. rootOptions.height = function () {
  9175. // TODO: change to height
  9176. if (me.options.height) {
  9177. // fixed height
  9178. return me.options.height;
  9179. }
  9180. else {
  9181. // auto height
  9182. return (me.timeaxis.height + me.content.height) + 'px';
  9183. }
  9184. };
  9185. this.rootPanel = new RootPanel(container, rootOptions);
  9186. this.controller.add(this.rootPanel);
  9187. // item panel
  9188. var itemOptions = Object.create(this.options);
  9189. itemOptions.left = function () {
  9190. return me.labelPanel.width;
  9191. };
  9192. itemOptions.width = function () {
  9193. return me.rootPanel.width - me.labelPanel.width;
  9194. };
  9195. itemOptions.top = null;
  9196. itemOptions.height = null;
  9197. this.itemPanel = new Panel(this.rootPanel, [], itemOptions);
  9198. this.controller.add(this.itemPanel);
  9199. // label panel
  9200. var labelOptions = Object.create(this.options);
  9201. labelOptions.top = null;
  9202. labelOptions.left = null;
  9203. labelOptions.height = null;
  9204. labelOptions.width = function () {
  9205. if (me.content && typeof me.content.getLabelsWidth === 'function') {
  9206. return me.content.getLabelsWidth();
  9207. }
  9208. else {
  9209. return 0;
  9210. }
  9211. };
  9212. this.labelPanel = new Panel(this.rootPanel, [], labelOptions);
  9213. this.controller.add(this.labelPanel);
  9214. // range
  9215. var rangeOptions = Object.create(this.options);
  9216. this.range = new Range(rangeOptions);
  9217. this.range.setRange(
  9218. now.clone().add('days', -3).valueOf(),
  9219. now.clone().add('days', 4).valueOf()
  9220. );
  9221. // TODO: reckon with options moveable and zoomable
  9222. this.range.subscribe(this.rootPanel, 'move', 'horizontal');
  9223. this.range.subscribe(this.rootPanel, 'zoom', 'horizontal');
  9224. this.range.on('rangechange', function () {
  9225. var force = true;
  9226. me.controller.requestReflow(force);
  9227. });
  9228. this.range.on('rangechanged', function () {
  9229. var force = true;
  9230. me.controller.requestReflow(force);
  9231. });
  9232. // TODO: put the listeners in setOptions, be able to dynamically change with options moveable and zoomable
  9233. // time axis
  9234. var timeaxisOptions = Object.create(rootOptions);
  9235. timeaxisOptions.range = this.range;
  9236. timeaxisOptions.left = null;
  9237. timeaxisOptions.top = null;
  9238. timeaxisOptions.width = '100%';
  9239. timeaxisOptions.height = null;
  9240. this.timeaxis = new TimeAxis(this.itemPanel, [], timeaxisOptions);
  9241. this.timeaxis.setRange(this.range);
  9242. this.controller.add(this.timeaxis);
  9243. // current time bar
  9244. this.currenttime = new CurrentTime(this.timeaxis, [], rootOptions);
  9245. this.controller.add(this.currenttime);
  9246. // custom time bar
  9247. this.customtime = new CustomTime(this.timeaxis, [], rootOptions);
  9248. this.controller.add(this.customtime);
  9249. // create groupset
  9250. this.setGroups(null);
  9251. this.itemsData = null; // DataSet
  9252. this.groupsData = null; // DataSet
  9253. // apply options
  9254. if (options) {
  9255. this.setOptions(options);
  9256. }
  9257. // create itemset and groupset
  9258. if (items) {
  9259. this.setItems(items);
  9260. }
  9261. }
  9262. /**
  9263. * Set options
  9264. * @param {Object} options TODO: describe the available options
  9265. */
  9266. Timeline.prototype.setOptions = function (options) {
  9267. util.extend(this.options, options);
  9268. // force update of range
  9269. // options.start and options.end can be undefined
  9270. //this.range.setRange(options.start, options.end);
  9271. this.range.setRange();
  9272. this.controller.reflow();
  9273. this.controller.repaint();
  9274. };
  9275. /**
  9276. * Set a custom time bar
  9277. * @param {Date} time
  9278. */
  9279. Timeline.prototype.setCustomTime = function (time) {
  9280. this.customtime._setCustomTime(time);
  9281. };
  9282. /**
  9283. * Retrieve the current custom time.
  9284. * @return {Date} customTime
  9285. */
  9286. Timeline.prototype.getCustomTime = function() {
  9287. return new Date(this.customtime.customTime.valueOf());
  9288. };
  9289. /**
  9290. * Set items
  9291. * @param {vis.DataSet | Array | DataTable | null} items
  9292. */
  9293. Timeline.prototype.setItems = function(items) {
  9294. var initialLoad = (this.itemsData == null);
  9295. // convert to type DataSet when needed
  9296. var newItemSet;
  9297. if (!items) {
  9298. newItemSet = null;
  9299. }
  9300. else if (items instanceof DataSet) {
  9301. newItemSet = items;
  9302. }
  9303. if (!(items instanceof DataSet)) {
  9304. newItemSet = new DataSet({
  9305. convert: {
  9306. start: 'Date',
  9307. end: 'Date'
  9308. }
  9309. });
  9310. newItemSet.add(items);
  9311. }
  9312. // set items
  9313. this.itemsData = newItemSet;
  9314. this.content.setItems(newItemSet);
  9315. if (initialLoad && (this.options.start == undefined || this.options.end == undefined)) {
  9316. // apply the data range as range
  9317. var dataRange = this.getItemRange();
  9318. // add 5% space on both sides
  9319. var min = dataRange.min;
  9320. var max = dataRange.max;
  9321. if (min != null && max != null) {
  9322. var interval = (max.valueOf() - min.valueOf());
  9323. if (interval <= 0) {
  9324. // prevent an empty interval
  9325. interval = 24 * 60 * 60 * 1000; // 1 day
  9326. }
  9327. min = new Date(min.valueOf() - interval * 0.05);
  9328. max = new Date(max.valueOf() + interval * 0.05);
  9329. }
  9330. // override specified start and/or end date
  9331. if (this.options.start != undefined) {
  9332. min = util.convert(this.options.start, 'Date');
  9333. }
  9334. if (this.options.end != undefined) {
  9335. max = util.convert(this.options.end, 'Date');
  9336. }
  9337. // apply range if there is a min or max available
  9338. if (min != null || max != null) {
  9339. this.range.setRange(min, max);
  9340. }
  9341. }
  9342. };
  9343. /**
  9344. * Set groups
  9345. * @param {vis.DataSet | Array | DataTable} groups
  9346. */
  9347. Timeline.prototype.setGroups = function(groups) {
  9348. var me = this;
  9349. this.groupsData = groups;
  9350. // switch content type between ItemSet or GroupSet when needed
  9351. var Type = this.groupsData ? GroupSet : ItemSet;
  9352. if (!(this.content instanceof Type)) {
  9353. // remove old content set
  9354. if (this.content) {
  9355. this.content.hide();
  9356. if (this.content.setItems) {
  9357. this.content.setItems(); // disconnect from items
  9358. }
  9359. if (this.content.setGroups) {
  9360. this.content.setGroups(); // disconnect from groups
  9361. }
  9362. this.controller.remove(this.content);
  9363. }
  9364. // create new content set
  9365. var options = Object.create(this.options);
  9366. util.extend(options, {
  9367. top: function () {
  9368. if (me.options.orientation == 'top') {
  9369. return me.timeaxis.height;
  9370. }
  9371. else {
  9372. return me.itemPanel.height - me.timeaxis.height - me.content.height;
  9373. }
  9374. },
  9375. left: null,
  9376. width: '100%',
  9377. height: function () {
  9378. if (me.options.height) {
  9379. // fixed height
  9380. return me.itemPanel.height - me.timeaxis.height;
  9381. }
  9382. else {
  9383. // auto height
  9384. return null;
  9385. }
  9386. },
  9387. maxHeight: function () {
  9388. // TODO: change maxHeight to be a css string like '100%' or '300px'
  9389. if (me.options.maxHeight) {
  9390. if (!util.isNumber(me.options.maxHeight)) {
  9391. throw new TypeError('Number expected for property maxHeight');
  9392. }
  9393. return me.options.maxHeight - me.timeaxis.height;
  9394. }
  9395. else {
  9396. return null;
  9397. }
  9398. },
  9399. labelContainer: function () {
  9400. return me.labelPanel.getContainer();
  9401. }
  9402. });
  9403. this.content = new Type(this.itemPanel, [this.timeaxis], options);
  9404. if (this.content.setRange) {
  9405. this.content.setRange(this.range);
  9406. }
  9407. if (this.content.setItems) {
  9408. this.content.setItems(this.itemsData);
  9409. }
  9410. if (this.content.setGroups) {
  9411. this.content.setGroups(this.groupsData);
  9412. }
  9413. this.controller.add(this.content);
  9414. }
  9415. };
  9416. /**
  9417. * Get the data range of the item set.
  9418. * @returns {{min: Date, max: Date}} range A range with a start and end Date.
  9419. * When no minimum is found, min==null
  9420. * When no maximum is found, max==null
  9421. */
  9422. Timeline.prototype.getItemRange = function getItemRange() {
  9423. // calculate min from start filed
  9424. var itemsData = this.itemsData,
  9425. min = null,
  9426. max = null;
  9427. if (itemsData) {
  9428. // calculate the minimum value of the field 'start'
  9429. var minItem = itemsData.min('start');
  9430. min = minItem ? minItem.start.valueOf() : null;
  9431. // calculate maximum value of fields 'start' and 'end'
  9432. var maxStartItem = itemsData.max('start');
  9433. if (maxStartItem) {
  9434. max = maxStartItem.start.valueOf();
  9435. }
  9436. var maxEndItem = itemsData.max('end');
  9437. if (maxEndItem) {
  9438. if (max == null) {
  9439. max = maxEndItem.end.valueOf();
  9440. }
  9441. else {
  9442. max = Math.max(max, maxEndItem.end.valueOf());
  9443. }
  9444. }
  9445. }
  9446. return {
  9447. min: (min != null) ? new Date(min) : null,
  9448. max: (max != null) ? new Date(max) : null
  9449. };
  9450. };
  9451. (function(exports) {
  9452. /**
  9453. * Parse a text source containing data in DOT language into a JSON object.
  9454. * The object contains two lists: one with nodes and one with edges.
  9455. *
  9456. * DOT language reference: http://www.graphviz.org/doc/info/lang.html
  9457. *
  9458. * @param {String} data Text containing a graph in DOT-notation
  9459. * @return {Object} graph An object containing two parameters:
  9460. * {Object[]} nodes
  9461. * {Object[]} edges
  9462. */
  9463. function parseDOT (data) {
  9464. dot = data;
  9465. return parseGraph();
  9466. }
  9467. // token types enumeration
  9468. var TOKENTYPE = {
  9469. NULL : 0,
  9470. DELIMITER : 1,
  9471. IDENTIFIER: 2,
  9472. UNKNOWN : 3
  9473. };
  9474. // map with all delimiters
  9475. var DELIMITERS = {
  9476. '{': true,
  9477. '}': true,
  9478. '[': true,
  9479. ']': true,
  9480. ';': true,
  9481. '=': true,
  9482. ',': true,
  9483. '->': true,
  9484. '--': true
  9485. };
  9486. var dot = ''; // current dot file
  9487. var index = 0; // current index in dot file
  9488. var c = ''; // current token character in expr
  9489. var token = ''; // current token
  9490. var tokenType = TOKENTYPE.NULL; // type of the token
  9491. /**
  9492. * Get the first character from the dot file.
  9493. * The character is stored into the char c. If the end of the dot file is
  9494. * reached, the function puts an empty string in c.
  9495. */
  9496. function first() {
  9497. index = 0;
  9498. c = dot.charAt(0);
  9499. }
  9500. /**
  9501. * Get the next character from the dot file.
  9502. * The character is stored into the char c. If the end of the dot file is
  9503. * reached, the function puts an empty string in c.
  9504. */
  9505. function next() {
  9506. index++;
  9507. c = dot.charAt(index);
  9508. }
  9509. /**
  9510. * Preview the next character from the dot file.
  9511. * @return {String} cNext
  9512. */
  9513. function nextPreview() {
  9514. return dot.charAt(index + 1);
  9515. }
  9516. /**
  9517. * Test whether given character is alphabetic or numeric
  9518. * @param {String} c
  9519. * @return {Boolean} isAlphaNumeric
  9520. */
  9521. var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/;
  9522. function isAlphaNumeric(c) {
  9523. return regexAlphaNumeric.test(c);
  9524. }
  9525. /**
  9526. * Merge all properties of object b into object b
  9527. * @param {Object} a
  9528. * @param {Object} b
  9529. * @return {Object} a
  9530. */
  9531. function merge (a, b) {
  9532. if (!a) {
  9533. a = {};
  9534. }
  9535. if (b) {
  9536. for (var name in b) {
  9537. if (b.hasOwnProperty(name)) {
  9538. a[name] = b[name];
  9539. }
  9540. }
  9541. }
  9542. return a;
  9543. }
  9544. /**
  9545. * Set a value in an object, where the provided parameter name can be a
  9546. * path with nested parameters. For example:
  9547. *
  9548. * var obj = {a: 2};
  9549. * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}}
  9550. *
  9551. * @param {Object} obj
  9552. * @param {String} path A parameter name or dot-separated parameter path,
  9553. * like "color.highlight.border".
  9554. * @param {*} value
  9555. */
  9556. function setValue(obj, path, value) {
  9557. var keys = path.split('.');
  9558. var o = obj;
  9559. while (keys.length) {
  9560. var key = keys.shift();
  9561. if (keys.length) {
  9562. // this isn't the end point
  9563. if (!o[key]) {
  9564. o[key] = {};
  9565. }
  9566. o = o[key];
  9567. }
  9568. else {
  9569. // this is the end point
  9570. o[key] = value;
  9571. }
  9572. }
  9573. }
  9574. /**
  9575. * Add a node to a graph object. If there is already a node with
  9576. * the same id, their attributes will be merged.
  9577. * @param {Object} graph
  9578. * @param {Object} node
  9579. */
  9580. function addNode(graph, node) {
  9581. var i, len;
  9582. var current = null;
  9583. // find root graph (in case of subgraph)
  9584. var graphs = [graph]; // list with all graphs from current graph to root graph
  9585. var root = graph;
  9586. while (root.parent) {
  9587. graphs.push(root.parent);
  9588. root = root.parent;
  9589. }
  9590. // find existing node (at root level) by its id
  9591. if (root.nodes) {
  9592. for (i = 0, len = root.nodes.length; i < len; i++) {
  9593. if (node.id === root.nodes[i].id) {
  9594. current = root.nodes[i];
  9595. break;
  9596. }
  9597. }
  9598. }
  9599. if (!current) {
  9600. // this is a new node
  9601. current = {
  9602. id: node.id
  9603. };
  9604. if (graph.node) {
  9605. // clone default attributes
  9606. current.attr = merge(current.attr, graph.node);
  9607. }
  9608. }
  9609. // add node to this (sub)graph and all its parent graphs
  9610. for (i = graphs.length - 1; i >= 0; i--) {
  9611. var g = graphs[i];
  9612. if (!g.nodes) {
  9613. g.nodes = [];
  9614. }
  9615. if (g.nodes.indexOf(current) == -1) {
  9616. g.nodes.push(current);
  9617. }
  9618. }
  9619. // merge attributes
  9620. if (node.attr) {
  9621. current.attr = merge(current.attr, node.attr);
  9622. }
  9623. }
  9624. /**
  9625. * Add an edge to a graph object
  9626. * @param {Object} graph
  9627. * @param {Object} edge
  9628. */
  9629. function addEdge(graph, edge) {
  9630. if (!graph.edges) {
  9631. graph.edges = [];
  9632. }
  9633. graph.edges.push(edge);
  9634. if (graph.edge) {
  9635. var attr = merge({}, graph.edge); // clone default attributes
  9636. edge.attr = merge(attr, edge.attr); // merge attributes
  9637. }
  9638. }
  9639. /**
  9640. * Create an edge to a graph object
  9641. * @param {Object} graph
  9642. * @param {String | Number | Object} from
  9643. * @param {String | Number | Object} to
  9644. * @param {String} type
  9645. * @param {Object | null} attr
  9646. * @return {Object} edge
  9647. */
  9648. function createEdge(graph, from, to, type, attr) {
  9649. var edge = {
  9650. from: from,
  9651. to: to,
  9652. type: type
  9653. };
  9654. if (graph.edge) {
  9655. edge.attr = merge({}, graph.edge); // clone default attributes
  9656. }
  9657. edge.attr = merge(edge.attr || {}, attr); // merge attributes
  9658. return edge;
  9659. }
  9660. /**
  9661. * Get next token in the current dot file.
  9662. * The token and token type are available as token and tokenType
  9663. */
  9664. function getToken() {
  9665. tokenType = TOKENTYPE.NULL;
  9666. token = '';
  9667. // skip over whitespaces
  9668. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  9669. next();
  9670. }
  9671. do {
  9672. var isComment = false;
  9673. // skip comment
  9674. if (c == '#') {
  9675. // find the previous non-space character
  9676. var i = index - 1;
  9677. while (dot.charAt(i) == ' ' || dot.charAt(i) == '\t') {
  9678. i--;
  9679. }
  9680. if (dot.charAt(i) == '\n' || dot.charAt(i) == '') {
  9681. // the # is at the start of a line, this is indeed a line comment
  9682. while (c != '' && c != '\n') {
  9683. next();
  9684. }
  9685. isComment = true;
  9686. }
  9687. }
  9688. if (c == '/' && nextPreview() == '/') {
  9689. // skip line comment
  9690. while (c != '' && c != '\n') {
  9691. next();
  9692. }
  9693. isComment = true;
  9694. }
  9695. if (c == '/' && nextPreview() == '*') {
  9696. // skip block comment
  9697. while (c != '') {
  9698. if (c == '*' && nextPreview() == '/') {
  9699. // end of block comment found. skip these last two characters
  9700. next();
  9701. next();
  9702. break;
  9703. }
  9704. else {
  9705. next();
  9706. }
  9707. }
  9708. isComment = true;
  9709. }
  9710. // skip over whitespaces
  9711. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  9712. next();
  9713. }
  9714. }
  9715. while (isComment);
  9716. // check for end of dot file
  9717. if (c == '') {
  9718. // token is still empty
  9719. tokenType = TOKENTYPE.DELIMITER;
  9720. return;
  9721. }
  9722. // check for delimiters consisting of 2 characters
  9723. var c2 = c + nextPreview();
  9724. if (DELIMITERS[c2]) {
  9725. tokenType = TOKENTYPE.DELIMITER;
  9726. token = c2;
  9727. next();
  9728. next();
  9729. return;
  9730. }
  9731. // check for delimiters consisting of 1 character
  9732. if (DELIMITERS[c]) {
  9733. tokenType = TOKENTYPE.DELIMITER;
  9734. token = c;
  9735. next();
  9736. return;
  9737. }
  9738. // check for an identifier (number or string)
  9739. // TODO: more precise parsing of numbers/strings (and the port separator ':')
  9740. if (isAlphaNumeric(c) || c == '-') {
  9741. token += c;
  9742. next();
  9743. while (isAlphaNumeric(c)) {
  9744. token += c;
  9745. next();
  9746. }
  9747. if (token == 'false') {
  9748. token = false; // convert to boolean
  9749. }
  9750. else if (token == 'true') {
  9751. token = true; // convert to boolean
  9752. }
  9753. else if (!isNaN(Number(token))) {
  9754. token = Number(token); // convert to number
  9755. }
  9756. tokenType = TOKENTYPE.IDENTIFIER;
  9757. return;
  9758. }
  9759. // check for a string enclosed by double quotes
  9760. if (c == '"') {
  9761. next();
  9762. while (c != '' && (c != '"' || (c == '"' && nextPreview() == '"'))) {
  9763. token += c;
  9764. if (c == '"') { // skip the escape character
  9765. next();
  9766. }
  9767. next();
  9768. }
  9769. if (c != '"') {
  9770. throw newSyntaxError('End of string " expected');
  9771. }
  9772. next();
  9773. tokenType = TOKENTYPE.IDENTIFIER;
  9774. return;
  9775. }
  9776. // something unknown is found, wrong characters, a syntax error
  9777. tokenType = TOKENTYPE.UNKNOWN;
  9778. while (c != '') {
  9779. token += c;
  9780. next();
  9781. }
  9782. throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"');
  9783. }
  9784. /**
  9785. * Parse a graph.
  9786. * @returns {Object} graph
  9787. */
  9788. function parseGraph() {
  9789. var graph = {};
  9790. first();
  9791. getToken();
  9792. // optional strict keyword
  9793. if (token == 'strict') {
  9794. graph.strict = true;
  9795. getToken();
  9796. }
  9797. // graph or digraph keyword
  9798. if (token == 'graph' || token == 'digraph') {
  9799. graph.type = token;
  9800. getToken();
  9801. }
  9802. // optional graph id
  9803. if (tokenType == TOKENTYPE.IDENTIFIER) {
  9804. graph.id = token;
  9805. getToken();
  9806. }
  9807. // open angle bracket
  9808. if (token != '{') {
  9809. throw newSyntaxError('Angle bracket { expected');
  9810. }
  9811. getToken();
  9812. // statements
  9813. parseStatements(graph);
  9814. // close angle bracket
  9815. if (token != '}') {
  9816. throw newSyntaxError('Angle bracket } expected');
  9817. }
  9818. getToken();
  9819. // end of file
  9820. if (token !== '') {
  9821. throw newSyntaxError('End of file expected');
  9822. }
  9823. getToken();
  9824. // remove temporary default properties
  9825. delete graph.node;
  9826. delete graph.edge;
  9827. delete graph.graph;
  9828. return graph;
  9829. }
  9830. /**
  9831. * Parse a list with statements.
  9832. * @param {Object} graph
  9833. */
  9834. function parseStatements (graph) {
  9835. while (token !== '' && token != '}') {
  9836. parseStatement(graph);
  9837. if (token == ';') {
  9838. getToken();
  9839. }
  9840. }
  9841. }
  9842. /**
  9843. * Parse a single statement. Can be a an attribute statement, node
  9844. * statement, a series of node statements and edge statements, or a
  9845. * parameter.
  9846. * @param {Object} graph
  9847. */
  9848. function parseStatement(graph) {
  9849. // parse subgraph
  9850. var subgraph = parseSubgraph(graph);
  9851. if (subgraph) {
  9852. // edge statements
  9853. parseEdge(graph, subgraph);
  9854. return;
  9855. }
  9856. // parse an attribute statement
  9857. var attr = parseAttributeStatement(graph);
  9858. if (attr) {
  9859. return;
  9860. }
  9861. // parse node
  9862. if (tokenType != TOKENTYPE.IDENTIFIER) {
  9863. throw newSyntaxError('Identifier expected');
  9864. }
  9865. var id = token; // id can be a string or a number
  9866. getToken();
  9867. if (token == '=') {
  9868. // id statement
  9869. getToken();
  9870. if (tokenType != TOKENTYPE.IDENTIFIER) {
  9871. throw newSyntaxError('Identifier expected');
  9872. }
  9873. graph[id] = token;
  9874. getToken();
  9875. // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] "
  9876. }
  9877. else {
  9878. parseNodeStatement(graph, id);
  9879. }
  9880. }
  9881. /**
  9882. * Parse a subgraph
  9883. * @param {Object} graph parent graph object
  9884. * @return {Object | null} subgraph
  9885. */
  9886. function parseSubgraph (graph) {
  9887. var subgraph = null;
  9888. // optional subgraph keyword
  9889. if (token == 'subgraph') {
  9890. subgraph = {};
  9891. subgraph.type = 'subgraph';
  9892. getToken();
  9893. // optional graph id
  9894. if (tokenType == TOKENTYPE.IDENTIFIER) {
  9895. subgraph.id = token;
  9896. getToken();
  9897. }
  9898. }
  9899. // open angle bracket
  9900. if (token == '{') {
  9901. getToken();
  9902. if (!subgraph) {
  9903. subgraph = {};
  9904. }
  9905. subgraph.parent = graph;
  9906. subgraph.node = graph.node;
  9907. subgraph.edge = graph.edge;
  9908. subgraph.graph = graph.graph;
  9909. // statements
  9910. parseStatements(subgraph);
  9911. // close angle bracket
  9912. if (token != '}') {
  9913. throw newSyntaxError('Angle bracket } expected');
  9914. }
  9915. getToken();
  9916. // remove temporary default properties
  9917. delete subgraph.node;
  9918. delete subgraph.edge;
  9919. delete subgraph.graph;
  9920. delete subgraph.parent;
  9921. // register at the parent graph
  9922. if (!graph.subgraphs) {
  9923. graph.subgraphs = [];
  9924. }
  9925. graph.subgraphs.push(subgraph);
  9926. }
  9927. return subgraph;
  9928. }
  9929. /**
  9930. * parse an attribute statement like "node [shape=circle fontSize=16]".
  9931. * Available keywords are 'node', 'edge', 'graph'.
  9932. * The previous list with default attributes will be replaced
  9933. * @param {Object} graph
  9934. * @returns {String | null} keyword Returns the name of the parsed attribute
  9935. * (node, edge, graph), or null if nothing
  9936. * is parsed.
  9937. */
  9938. function parseAttributeStatement (graph) {
  9939. // attribute statements
  9940. if (token == 'node') {
  9941. getToken();
  9942. // node attributes
  9943. graph.node = parseAttributeList();
  9944. return 'node';
  9945. }
  9946. else if (token == 'edge') {
  9947. getToken();
  9948. // edge attributes
  9949. graph.edge = parseAttributeList();
  9950. return 'edge';
  9951. }
  9952. else if (token == 'graph') {
  9953. getToken();
  9954. // graph attributes
  9955. graph.graph = parseAttributeList();
  9956. return 'graph';
  9957. }
  9958. return null;
  9959. }
  9960. /**
  9961. * parse a node statement
  9962. * @param {Object} graph
  9963. * @param {String | Number} id
  9964. */
  9965. function parseNodeStatement(graph, id) {
  9966. // node statement
  9967. var node = {
  9968. id: id
  9969. };
  9970. var attr = parseAttributeList();
  9971. if (attr) {
  9972. node.attr = attr;
  9973. }
  9974. addNode(graph, node);
  9975. // edge statements
  9976. parseEdge(graph, id);
  9977. }
  9978. /**
  9979. * Parse an edge or a series of edges
  9980. * @param {Object} graph
  9981. * @param {String | Number} from Id of the from node
  9982. */
  9983. function parseEdge(graph, from) {
  9984. while (token == '->' || token == '--') {
  9985. var to;
  9986. var type = token;
  9987. getToken();
  9988. var subgraph = parseSubgraph(graph);
  9989. if (subgraph) {
  9990. to = subgraph;
  9991. }
  9992. else {
  9993. if (tokenType != TOKENTYPE.IDENTIFIER) {
  9994. throw newSyntaxError('Identifier or subgraph expected');
  9995. }
  9996. to = token;
  9997. addNode(graph, {
  9998. id: to
  9999. });
  10000. getToken();
  10001. }
  10002. // parse edge attributes
  10003. var attr = parseAttributeList();
  10004. // create edge
  10005. var edge = createEdge(graph, from, to, type, attr);
  10006. addEdge(graph, edge);
  10007. from = to;
  10008. }
  10009. }
  10010. /**
  10011. * Parse a set with attributes,
  10012. * for example [label="1.000", shape=solid]
  10013. * @return {Object | null} attr
  10014. */
  10015. function parseAttributeList() {
  10016. var attr = null;
  10017. while (token == '[') {
  10018. getToken();
  10019. attr = {};
  10020. while (token !== '' && token != ']') {
  10021. if (tokenType != TOKENTYPE.IDENTIFIER) {
  10022. throw newSyntaxError('Attribute name expected');
  10023. }
  10024. var name = token;
  10025. getToken();
  10026. if (token != '=') {
  10027. throw newSyntaxError('Equal sign = expected');
  10028. }
  10029. getToken();
  10030. if (tokenType != TOKENTYPE.IDENTIFIER) {
  10031. throw newSyntaxError('Attribute value expected');
  10032. }
  10033. var value = token;
  10034. setValue(attr, name, value); // name can be a path
  10035. getToken();
  10036. if (token ==',') {
  10037. getToken();
  10038. }
  10039. }
  10040. if (token != ']') {
  10041. throw newSyntaxError('Bracket ] expected');
  10042. }
  10043. getToken();
  10044. }
  10045. return attr;
  10046. }
  10047. /**
  10048. * Create a syntax error with extra information on current token and index.
  10049. * @param {String} message
  10050. * @returns {SyntaxError} err
  10051. */
  10052. function newSyntaxError(message) {
  10053. return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')');
  10054. }
  10055. /**
  10056. * Chop off text after a maximum length
  10057. * @param {String} text
  10058. * @param {Number} maxLength
  10059. * @returns {String}
  10060. */
  10061. function chop (text, maxLength) {
  10062. return (text.length <= maxLength) ? text : (text.substr(0, 27) + '...');
  10063. }
  10064. /**
  10065. * Execute a function fn for each pair of elements in two arrays
  10066. * @param {Array | *} array1
  10067. * @param {Array | *} array2
  10068. * @param {function} fn
  10069. */
  10070. function forEach2(array1, array2, fn) {
  10071. if (array1 instanceof Array) {
  10072. array1.forEach(function (elem1) {
  10073. if (array2 instanceof Array) {
  10074. array2.forEach(function (elem2) {
  10075. fn(elem1, elem2);
  10076. });
  10077. }
  10078. else {
  10079. fn(elem1, array2);
  10080. }
  10081. });
  10082. }
  10083. else {
  10084. if (array2 instanceof Array) {
  10085. array2.forEach(function (elem2) {
  10086. fn(array1, elem2);
  10087. });
  10088. }
  10089. else {
  10090. fn(array1, array2);
  10091. }
  10092. }
  10093. }
  10094. /**
  10095. * Convert a string containing a graph in DOT language into a map containing
  10096. * with nodes and edges in the format of graph.
  10097. * @param {String} data Text containing a graph in DOT-notation
  10098. * @return {Object} graphData
  10099. */
  10100. function DOTToGraph (data) {
  10101. // parse the DOT file
  10102. var dotData = parseDOT(data);
  10103. var graphData = {
  10104. nodes: [],
  10105. edges: [],
  10106. options: {}
  10107. };
  10108. // copy the nodes
  10109. if (dotData.nodes) {
  10110. dotData.nodes.forEach(function (dotNode) {
  10111. var graphNode = {
  10112. id: dotNode.id,
  10113. label: String(dotNode.label || dotNode.id)
  10114. };
  10115. merge(graphNode, dotNode.attr);
  10116. if (graphNode.image) {
  10117. graphNode.shape = 'image';
  10118. }
  10119. graphData.nodes.push(graphNode);
  10120. });
  10121. }
  10122. // copy the edges
  10123. if (dotData.edges) {
  10124. /**
  10125. * Convert an edge in DOT format to an edge with VisGraph format
  10126. * @param {Object} dotEdge
  10127. * @returns {Object} graphEdge
  10128. */
  10129. function convertEdge(dotEdge) {
  10130. var graphEdge = {
  10131. from: dotEdge.from,
  10132. to: dotEdge.to
  10133. };
  10134. merge(graphEdge, dotEdge.attr);
  10135. graphEdge.style = (dotEdge.type == '->') ? 'arrow' : 'line';
  10136. return graphEdge;
  10137. }
  10138. dotData.edges.forEach(function (dotEdge) {
  10139. var from, to;
  10140. if (dotEdge.from instanceof Object) {
  10141. from = dotEdge.from.nodes;
  10142. }
  10143. else {
  10144. from = {
  10145. id: dotEdge.from
  10146. }
  10147. }
  10148. if (dotEdge.to instanceof Object) {
  10149. to = dotEdge.to.nodes;
  10150. }
  10151. else {
  10152. to = {
  10153. id: dotEdge.to
  10154. }
  10155. }
  10156. if (dotEdge.from instanceof Object && dotEdge.from.edges) {
  10157. dotEdge.from.edges.forEach(function (subEdge) {
  10158. var graphEdge = convertEdge(subEdge);
  10159. graphData.edges.push(graphEdge);
  10160. });
  10161. }
  10162. forEach2(from, to, function (from, to) {
  10163. var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr);
  10164. var graphEdge = convertEdge(subEdge);
  10165. graphData.edges.push(graphEdge);
  10166. });
  10167. if (dotEdge.to instanceof Object && dotEdge.to.edges) {
  10168. dotEdge.to.edges.forEach(function (subEdge) {
  10169. var graphEdge = convertEdge(subEdge);
  10170. graphData.edges.push(graphEdge);
  10171. });
  10172. }
  10173. });
  10174. }
  10175. // copy the options
  10176. if (dotData.attr) {
  10177. graphData.options = dotData.attr;
  10178. }
  10179. return graphData;
  10180. }
  10181. // exports
  10182. exports.parseDOT = parseDOT;
  10183. exports.DOTToGraph = DOTToGraph;
  10184. })(typeof util !== 'undefined' ? util : exports);
  10185. /**
  10186. * Canvas shapes used by the Graph
  10187. */
  10188. if (typeof CanvasRenderingContext2D !== 'undefined') {
  10189. /**
  10190. * Draw a circle shape
  10191. */
  10192. CanvasRenderingContext2D.prototype.circle = function(x, y, r) {
  10193. this.beginPath();
  10194. this.arc(x, y, r, 0, 2*Math.PI, false);
  10195. };
  10196. /**
  10197. * Draw a square shape
  10198. * @param {Number} x horizontal center
  10199. * @param {Number} y vertical center
  10200. * @param {Number} r size, width and height of the square
  10201. */
  10202. CanvasRenderingContext2D.prototype.square = function(x, y, r) {
  10203. this.beginPath();
  10204. this.rect(x - r, y - r, r * 2, r * 2);
  10205. };
  10206. /**
  10207. * Draw a triangle shape
  10208. * @param {Number} x horizontal center
  10209. * @param {Number} y vertical center
  10210. * @param {Number} r radius, half the length of the sides of the triangle
  10211. */
  10212. CanvasRenderingContext2D.prototype.triangle = function(x, y, r) {
  10213. // http://en.wikipedia.org/wiki/Equilateral_triangle
  10214. this.beginPath();
  10215. var s = r * 2;
  10216. var s2 = s / 2;
  10217. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  10218. var h = Math.sqrt(s * s - s2 * s2); // height
  10219. this.moveTo(x, y - (h - ir));
  10220. this.lineTo(x + s2, y + ir);
  10221. this.lineTo(x - s2, y + ir);
  10222. this.lineTo(x, y - (h - ir));
  10223. this.closePath();
  10224. };
  10225. /**
  10226. * Draw a triangle shape in downward orientation
  10227. * @param {Number} x horizontal center
  10228. * @param {Number} y vertical center
  10229. * @param {Number} r radius
  10230. */
  10231. CanvasRenderingContext2D.prototype.triangleDown = function(x, y, r) {
  10232. // http://en.wikipedia.org/wiki/Equilateral_triangle
  10233. this.beginPath();
  10234. var s = r * 2;
  10235. var s2 = s / 2;
  10236. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  10237. var h = Math.sqrt(s * s - s2 * s2); // height
  10238. this.moveTo(x, y + (h - ir));
  10239. this.lineTo(x + s2, y - ir);
  10240. this.lineTo(x - s2, y - ir);
  10241. this.lineTo(x, y + (h - ir));
  10242. this.closePath();
  10243. };
  10244. /**
  10245. * Draw a star shape, a star with 5 points
  10246. * @param {Number} x horizontal center
  10247. * @param {Number} y vertical center
  10248. * @param {Number} r radius, half the length of the sides of the triangle
  10249. */
  10250. CanvasRenderingContext2D.prototype.star = function(x, y, r) {
  10251. // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/
  10252. this.beginPath();
  10253. for (var n = 0; n < 10; n++) {
  10254. var radius = (n % 2 === 0) ? r * 1.3 : r * 0.5;
  10255. this.lineTo(
  10256. x + radius * Math.sin(n * 2 * Math.PI / 10),
  10257. y - radius * Math.cos(n * 2 * Math.PI / 10)
  10258. );
  10259. }
  10260. this.closePath();
  10261. };
  10262. /**
  10263. * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas
  10264. */
  10265. CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) {
  10266. var r2d = Math.PI/180;
  10267. if( w - ( 2 * r ) < 0 ) { r = ( w / 2 ); } //ensure that the radius isn't too large for x
  10268. if( h - ( 2 * r ) < 0 ) { r = ( h / 2 ); } //ensure that the radius isn't too large for y
  10269. this.beginPath();
  10270. this.moveTo(x+r,y);
  10271. this.lineTo(x+w-r,y);
  10272. this.arc(x+w-r,y+r,r,r2d*270,r2d*360,false);
  10273. this.lineTo(x+w,y+h-r);
  10274. this.arc(x+w-r,y+h-r,r,0,r2d*90,false);
  10275. this.lineTo(x+r,y+h);
  10276. this.arc(x+r,y+h-r,r,r2d*90,r2d*180,false);
  10277. this.lineTo(x,y+r);
  10278. this.arc(x+r,y+r,r,r2d*180,r2d*270,false);
  10279. };
  10280. /**
  10281. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  10282. */
  10283. CanvasRenderingContext2D.prototype.ellipse = function(x, y, w, h) {
  10284. var kappa = .5522848,
  10285. ox = (w / 2) * kappa, // control point offset horizontal
  10286. oy = (h / 2) * kappa, // control point offset vertical
  10287. xe = x + w, // x-end
  10288. ye = y + h, // y-end
  10289. xm = x + w / 2, // x-middle
  10290. ym = y + h / 2; // y-middle
  10291. this.beginPath();
  10292. this.moveTo(x, ym);
  10293. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  10294. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  10295. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  10296. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  10297. };
  10298. /**
  10299. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  10300. */
  10301. CanvasRenderingContext2D.prototype.database = function(x, y, w, h) {
  10302. var f = 1/3;
  10303. var wEllipse = w;
  10304. var hEllipse = h * f;
  10305. var kappa = .5522848,
  10306. ox = (wEllipse / 2) * kappa, // control point offset horizontal
  10307. oy = (hEllipse / 2) * kappa, // control point offset vertical
  10308. xe = x + wEllipse, // x-end
  10309. ye = y + hEllipse, // y-end
  10310. xm = x + wEllipse / 2, // x-middle
  10311. ym = y + hEllipse / 2, // y-middle
  10312. ymb = y + (h - hEllipse/2), // y-midlle, bottom ellipse
  10313. yeb = y + h; // y-end, bottom ellipse
  10314. this.beginPath();
  10315. this.moveTo(xe, ym);
  10316. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  10317. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  10318. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  10319. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  10320. this.lineTo(xe, ymb);
  10321. this.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb);
  10322. this.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb);
  10323. this.lineTo(x, ym);
  10324. };
  10325. /**
  10326. * Draw an arrow point (no line)
  10327. */
  10328. CanvasRenderingContext2D.prototype.arrow = function(x, y, angle, length) {
  10329. // tail
  10330. var xt = x - length * Math.cos(angle);
  10331. var yt = y - length * Math.sin(angle);
  10332. // inner tail
  10333. // TODO: allow to customize different shapes
  10334. var xi = x - length * 0.9 * Math.cos(angle);
  10335. var yi = y - length * 0.9 * Math.sin(angle);
  10336. // left
  10337. var xl = xt + length / 3 * Math.cos(angle + 0.5 * Math.PI);
  10338. var yl = yt + length / 3 * Math.sin(angle + 0.5 * Math.PI);
  10339. // right
  10340. var xr = xt + length / 3 * Math.cos(angle - 0.5 * Math.PI);
  10341. var yr = yt + length / 3 * Math.sin(angle - 0.5 * Math.PI);
  10342. this.beginPath();
  10343. this.moveTo(x, y);
  10344. this.lineTo(xl, yl);
  10345. this.lineTo(xi, yi);
  10346. this.lineTo(xr, yr);
  10347. this.closePath();
  10348. };
  10349. /**
  10350. * Sets up the dashedLine functionality for drawing
  10351. * Original code came from http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
  10352. * @author David Jordan
  10353. * @date 2012-08-08
  10354. */
  10355. CanvasRenderingContext2D.prototype.dashedLine = function(x,y,x2,y2,dashArray){
  10356. if (!dashArray) dashArray=[10,5];
  10357. if (dashLength==0) dashLength = 0.001; // Hack for Safari
  10358. var dashCount = dashArray.length;
  10359. this.moveTo(x, y);
  10360. var dx = (x2-x), dy = (y2-y);
  10361. var slope = dy/dx;
  10362. var distRemaining = Math.sqrt( dx*dx + dy*dy );
  10363. var dashIndex=0, draw=true;
  10364. while (distRemaining>=0.1){
  10365. var dashLength = dashArray[dashIndex++%dashCount];
  10366. if (dashLength > distRemaining) dashLength = distRemaining;
  10367. var xStep = Math.sqrt( dashLength*dashLength / (1 + slope*slope) );
  10368. if (dx<0) xStep = -xStep;
  10369. x += xStep;
  10370. y += slope*xStep;
  10371. this[draw ? 'lineTo' : 'moveTo'](x,y);
  10372. distRemaining -= dashLength;
  10373. draw = !draw;
  10374. }
  10375. };
  10376. // TODO: add diamond shape
  10377. }
  10378. /**
  10379. * @class Node
  10380. * A node. A node can be connected to other nodes via one or multiple edges.
  10381. * @param {object} properties An object containing properties for the node. All
  10382. * properties are optional, except for the id.
  10383. * {number} id Id of the node. Required
  10384. * {string} label Text label for the node
  10385. * {number} x Horizontal position of the node
  10386. * {number} y Vertical position of the node
  10387. * {string} shape Node shape, available:
  10388. * "database", "circle", "ellipse",
  10389. * "box", "image", "text", "dot",
  10390. * "star", "triangle", "triangleDown",
  10391. * "square"
  10392. * {string} image An image url
  10393. * {string} title An title text, can be HTML
  10394. * {anytype} group A group name or number
  10395. * @param {Graph.Images} imagelist A list with images. Only needed
  10396. * when the node has an image
  10397. * @param {Graph.Groups} grouplist A list with groups. Needed for
  10398. * retrieving group properties
  10399. * @param {Object} constants An object with default values for
  10400. * example for the color
  10401. */
  10402. function Node(properties, imagelist, grouplist, constants) {
  10403. this.selected = false;
  10404. this.edges = []; // all edges connected to this node
  10405. this.group = constants.nodes.group;
  10406. this.fontSize = constants.nodes.fontSize;
  10407. this.fontFace = constants.nodes.fontFace;
  10408. this.fontColor = constants.nodes.fontColor;
  10409. this.color = constants.nodes.color;
  10410. // set defaults for the properties
  10411. this.id = undefined;
  10412. this.shape = constants.nodes.shape;
  10413. this.image = constants.nodes.image;
  10414. this.x = 0;
  10415. this.y = 0;
  10416. this.xFixed = false;
  10417. this.yFixed = false;
  10418. this.radius = constants.nodes.radius;
  10419. this.radiusFixed = false;
  10420. this.radiusMin = constants.nodes.radiusMin;
  10421. this.radiusMax = constants.nodes.radiusMax;
  10422. this.imagelist = imagelist;
  10423. this.grouplist = grouplist;
  10424. this.setProperties(properties, constants);
  10425. // mass, force, velocity
  10426. this.mass = 50; // kg (mass is adjusted for the number of connected edges)
  10427. this.fx = 0.0; // external force x
  10428. this.fy = 0.0; // external force y
  10429. this.vx = 0.0; // velocity x
  10430. this.vy = 0.0; // velocity y
  10431. this.minForce = constants.minForce;
  10432. this.damping = 0.9; // damping factor
  10433. };
  10434. /**
  10435. * Attach a edge to the node
  10436. * @param {Edge} edge
  10437. */
  10438. Node.prototype.attachEdge = function(edge) {
  10439. if (this.edges.indexOf(edge) == -1) {
  10440. this.edges.push(edge);
  10441. }
  10442. this._updateMass();
  10443. };
  10444. /**
  10445. * Detach a edge from the node
  10446. * @param {Edge} edge
  10447. */
  10448. Node.prototype.detachEdge = function(edge) {
  10449. var index = this.edges.indexOf(edge);
  10450. if (index != -1) {
  10451. this.edges.splice(index, 1);
  10452. }
  10453. this._updateMass();
  10454. };
  10455. /**
  10456. * Update the nodes mass, which is determined by the number of edges connecting
  10457. * to it (more edges -> heavier node).
  10458. * @private
  10459. */
  10460. Node.prototype._updateMass = function() {
  10461. this.mass = 50 + 20 * this.edges.length; // kg
  10462. };
  10463. /**
  10464. * Set or overwrite properties for the node
  10465. * @param {Object} properties an object with properties
  10466. * @param {Object} constants and object with default, global properties
  10467. */
  10468. Node.prototype.setProperties = function(properties, constants) {
  10469. if (!properties) {
  10470. return;
  10471. }
  10472. // basic properties
  10473. if (properties.id != undefined) {this.id = properties.id;}
  10474. if (properties.label != undefined) {this.label = properties.label;}
  10475. if (properties.title != undefined) {this.title = properties.title;}
  10476. if (properties.group != undefined) {this.group = properties.group;}
  10477. if (properties.x != undefined) {this.x = properties.x;}
  10478. if (properties.y != undefined) {this.y = properties.y;}
  10479. if (properties.value != undefined) {this.value = properties.value;}
  10480. if (this.id === undefined) {
  10481. throw "Node must have an id";
  10482. }
  10483. // copy group properties
  10484. if (this.group) {
  10485. var groupObj = this.grouplist.get(this.group);
  10486. for (var prop in groupObj) {
  10487. if (groupObj.hasOwnProperty(prop)) {
  10488. this[prop] = groupObj[prop];
  10489. }
  10490. }
  10491. }
  10492. // individual shape properties
  10493. if (properties.shape != undefined) {this.shape = properties.shape;}
  10494. if (properties.image != undefined) {this.image = properties.image;}
  10495. if (properties.radius != undefined) {this.radius = properties.radius;}
  10496. if (properties.color != undefined) {this.color = Node.parseColor(properties.color);}
  10497. if (properties.fontColor != undefined) {this.fontColor = properties.fontColor;}
  10498. if (properties.fontSize != undefined) {this.fontSize = properties.fontSize;}
  10499. if (properties.fontFace != undefined) {this.fontFace = properties.fontFace;}
  10500. if (this.image != undefined) {
  10501. if (this.imagelist) {
  10502. this.imageObj = this.imagelist.load(this.image);
  10503. }
  10504. else {
  10505. throw "No imagelist provided";
  10506. }
  10507. }
  10508. this.xFixed = this.xFixed || (properties.x != undefined);
  10509. this.yFixed = this.yFixed || (properties.y != undefined);
  10510. this.radiusFixed = this.radiusFixed || (properties.radius != undefined);
  10511. if (this.shape == 'image') {
  10512. this.radiusMin = constants.nodes.widthMin;
  10513. this.radiusMax = constants.nodes.widthMax;
  10514. }
  10515. // choose draw method depending on the shape
  10516. switch (this.shape) {
  10517. case 'database': this.draw = this._drawDatabase; this.resize = this._resizeDatabase; break;
  10518. case 'box': this.draw = this._drawBox; this.resize = this._resizeBox; break;
  10519. case 'circle': this.draw = this._drawCircle; this.resize = this._resizeCircle; break;
  10520. case 'ellipse': this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  10521. // TODO: add diamond shape
  10522. case 'image': this.draw = this._drawImage; this.resize = this._resizeImage; break;
  10523. case 'text': this.draw = this._drawText; this.resize = this._resizeText; break;
  10524. case 'dot': this.draw = this._drawDot; this.resize = this._resizeShape; break;
  10525. case 'square': this.draw = this._drawSquare; this.resize = this._resizeShape; break;
  10526. case 'triangle': this.draw = this._drawTriangle; this.resize = this._resizeShape; break;
  10527. case 'triangleDown': this.draw = this._drawTriangleDown; this.resize = this._resizeShape; break;
  10528. case 'star': this.draw = this._drawStar; this.resize = this._resizeShape; break;
  10529. default: this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  10530. }
  10531. // reset the size of the node, this can be changed
  10532. this._reset();
  10533. };
  10534. /**
  10535. * Parse a color property into an object with border, background, and
  10536. * hightlight colors
  10537. * @param {Object | String} color
  10538. * @return {Object} colorObject
  10539. */
  10540. Node.parseColor = function(color) {
  10541. var c;
  10542. if (util.isString(color)) {
  10543. c = {
  10544. border: color,
  10545. background: color,
  10546. highlight: {
  10547. border: color,
  10548. background: color
  10549. }
  10550. };
  10551. // TODO: automatically generate a nice highlight color
  10552. }
  10553. else {
  10554. c = {};
  10555. c.background = color.background || 'white';
  10556. c.border = color.border || c.background;
  10557. if (util.isString(color.highlight)) {
  10558. c.highlight = {
  10559. border: color.highlight,
  10560. background: color.highlight
  10561. }
  10562. }
  10563. else {
  10564. c.highlight = {};
  10565. c.highlight.background = color.highlight && color.highlight.background || c.background;
  10566. c.highlight.border = color.highlight && color.highlight.border || c.border;
  10567. }
  10568. }
  10569. return c;
  10570. };
  10571. /**
  10572. * select this node
  10573. */
  10574. Node.prototype.select = function() {
  10575. this.selected = true;
  10576. this._reset();
  10577. };
  10578. /**
  10579. * unselect this node
  10580. */
  10581. Node.prototype.unselect = function() {
  10582. this.selected = false;
  10583. this._reset();
  10584. };
  10585. /**
  10586. * Reset the calculated size of the node, forces it to recalculate its size
  10587. * @private
  10588. */
  10589. Node.prototype._reset = function() {
  10590. this.width = undefined;
  10591. this.height = undefined;
  10592. };
  10593. /**
  10594. * get the title of this node.
  10595. * @return {string} title The title of the node, or undefined when no title
  10596. * has been set.
  10597. */
  10598. Node.prototype.getTitle = function() {
  10599. return this.title;
  10600. };
  10601. /**
  10602. * Calculate the distance to the border of the Node
  10603. * @param {CanvasRenderingContext2D} ctx
  10604. * @param {Number} angle Angle in radians
  10605. * @returns {number} distance Distance to the border in pixels
  10606. */
  10607. Node.prototype.distanceToBorder = function (ctx, angle) {
  10608. var borderWidth = 1;
  10609. if (!this.width) {
  10610. this.resize(ctx);
  10611. }
  10612. //noinspection FallthroughInSwitchStatementJS
  10613. switch (this.shape) {
  10614. case 'circle':
  10615. case 'dot':
  10616. return this.radius + borderWidth;
  10617. case 'ellipse':
  10618. var a = this.width / 2;
  10619. var b = this.height / 2;
  10620. var w = (Math.sin(angle) * a);
  10621. var h = (Math.cos(angle) * b);
  10622. return a * b / Math.sqrt(w * w + h * h);
  10623. // TODO: implement distanceToBorder for database
  10624. // TODO: implement distanceToBorder for triangle
  10625. // TODO: implement distanceToBorder for triangleDown
  10626. case 'box':
  10627. case 'image':
  10628. case 'text':
  10629. default:
  10630. if (this.width) {
  10631. return Math.min(
  10632. Math.abs(this.width / 2 / Math.cos(angle)),
  10633. Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth;
  10634. // TODO: reckon with border radius too in case of box
  10635. }
  10636. else {
  10637. return 0;
  10638. }
  10639. }
  10640. // TODO: implement calculation of distance to border for all shapes
  10641. };
  10642. /**
  10643. * Set forces acting on the node
  10644. * @param {number} fx Force in horizontal direction
  10645. * @param {number} fy Force in vertical direction
  10646. */
  10647. Node.prototype._setForce = function(fx, fy) {
  10648. this.fx = fx;
  10649. this.fy = fy;
  10650. };
  10651. /**
  10652. * Add forces acting on the node
  10653. * @param {number} fx Force in horizontal direction
  10654. * @param {number} fy Force in vertical direction
  10655. * @private
  10656. */
  10657. Node.prototype._addForce = function(fx, fy) {
  10658. this.fx += fx;
  10659. this.fy += fy;
  10660. };
  10661. /**
  10662. * Perform one discrete step for the node
  10663. * @param {number} interval Time interval in seconds
  10664. */
  10665. Node.prototype.discreteStep = function(interval) {
  10666. if (!this.xFixed) {
  10667. var dx = -this.damping * this.vx; // damping force
  10668. var ax = (this.fx + dx) / this.mass; // acceleration
  10669. this.vx += ax / interval; // velocity
  10670. this.x += this.vx / interval; // position
  10671. }
  10672. if (!this.yFixed) {
  10673. var dy = -this.damping * this.vy; // damping force
  10674. var ay = (this.fy + dy) / this.mass; // acceleration
  10675. this.vy += ay / interval; // velocity
  10676. this.y += this.vy / interval; // position
  10677. }
  10678. };
  10679. /**
  10680. * Check if this node has a fixed x and y position
  10681. * @return {boolean} true if fixed, false if not
  10682. */
  10683. Node.prototype.isFixed = function() {
  10684. return (this.xFixed && this.yFixed);
  10685. };
  10686. /**
  10687. * Check if this node is moving
  10688. * @param {number} vmin the minimum velocity considered as "moving"
  10689. * @return {boolean} true if moving, false if it has no velocity
  10690. */
  10691. // TODO: replace this method with calculating the kinetic energy
  10692. Node.prototype.isMoving = function(vmin) {
  10693. return (Math.abs(this.vx) > vmin || Math.abs(this.vy) > vmin ||
  10694. (!this.xFixed && Math.abs(this.fx) > this.minForce) ||
  10695. (!this.yFixed && Math.abs(this.fy) > this.minForce));
  10696. };
  10697. /**
  10698. * check if this node is selecte
  10699. * @return {boolean} selected True if node is selected, else false
  10700. */
  10701. Node.prototype.isSelected = function() {
  10702. return this.selected;
  10703. };
  10704. /**
  10705. * Retrieve the value of the node. Can be undefined
  10706. * @return {Number} value
  10707. */
  10708. Node.prototype.getValue = function() {
  10709. return this.value;
  10710. };
  10711. /**
  10712. * Calculate the distance from the nodes location to the given location (x,y)
  10713. * @param {Number} x
  10714. * @param {Number} y
  10715. * @return {Number} value
  10716. */
  10717. Node.prototype.getDistance = function(x, y) {
  10718. var dx = this.x - x,
  10719. dy = this.y - y;
  10720. return Math.sqrt(dx * dx + dy * dy);
  10721. };
  10722. /**
  10723. * Adjust the value range of the node. The node will adjust it's radius
  10724. * based on its value.
  10725. * @param {Number} min
  10726. * @param {Number} max
  10727. */
  10728. Node.prototype.setValueRange = function(min, max) {
  10729. if (!this.radiusFixed && this.value !== undefined) {
  10730. if (max == min) {
  10731. this.radius = (this.radiusMin + this.radiusMax) / 2;
  10732. }
  10733. else {
  10734. var scale = (this.radiusMax - this.radiusMin) / (max - min);
  10735. this.radius = (this.value - min) * scale + this.radiusMin;
  10736. }
  10737. }
  10738. };
  10739. /**
  10740. * Draw this node in the given canvas
  10741. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  10742. * @param {CanvasRenderingContext2D} ctx
  10743. */
  10744. Node.prototype.draw = function(ctx) {
  10745. throw "Draw method not initialized for node";
  10746. };
  10747. /**
  10748. * Recalculate the size of this node in the given canvas
  10749. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  10750. * @param {CanvasRenderingContext2D} ctx
  10751. */
  10752. Node.prototype.resize = function(ctx) {
  10753. throw "Resize method not initialized for node";
  10754. };
  10755. /**
  10756. * Check if this object is overlapping with the provided object
  10757. * @param {Object} obj an object with parameters left, top, right, bottom
  10758. * @return {boolean} True if location is located on node
  10759. */
  10760. Node.prototype.isOverlappingWith = function(obj) {
  10761. return (this.left < obj.right &&
  10762. this.left + this.width > obj.left &&
  10763. this.top < obj.bottom &&
  10764. this.top + this.height > obj.top);
  10765. };
  10766. Node.prototype._resizeImage = function (ctx) {
  10767. // TODO: pre calculate the image size
  10768. if (!this.width) { // undefined or 0
  10769. var width, height;
  10770. if (this.value) {
  10771. var scale = this.imageObj.height / this.imageObj.width;
  10772. width = this.radius || this.imageObj.width;
  10773. height = this.radius * scale || this.imageObj.height;
  10774. }
  10775. else {
  10776. width = this.imageObj.width;
  10777. height = this.imageObj.height;
  10778. }
  10779. this.width = width;
  10780. this.height = height;
  10781. }
  10782. };
  10783. Node.prototype._drawImage = function (ctx) {
  10784. this._resizeImage(ctx);
  10785. this.left = this.x - this.width / 2;
  10786. this.top = this.y - this.height / 2;
  10787. var yLabel;
  10788. if (this.imageObj) {
  10789. ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height);
  10790. yLabel = this.y + this.height / 2;
  10791. }
  10792. else {
  10793. // image still loading... just draw the label for now
  10794. yLabel = this.y;
  10795. }
  10796. this._label(ctx, this.label, this.x, yLabel, undefined, "top");
  10797. };
  10798. Node.prototype._resizeBox = function (ctx) {
  10799. if (!this.width) {
  10800. var margin = 5;
  10801. var textSize = this.getTextSize(ctx);
  10802. this.width = textSize.width + 2 * margin;
  10803. this.height = textSize.height + 2 * margin;
  10804. }
  10805. };
  10806. Node.prototype._drawBox = function (ctx) {
  10807. this._resizeBox(ctx);
  10808. this.left = this.x - this.width / 2;
  10809. this.top = this.y - this.height / 2;
  10810. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  10811. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  10812. ctx.lineWidth = this.selected ? 2.0 : 1.0;
  10813. ctx.roundRect(this.left, this.top, this.width, this.height, this.radius);
  10814. ctx.fill();
  10815. ctx.stroke();
  10816. this._label(ctx, this.label, this.x, this.y);
  10817. };
  10818. Node.prototype._resizeDatabase = function (ctx) {
  10819. if (!this.width) {
  10820. var margin = 5;
  10821. var textSize = this.getTextSize(ctx);
  10822. var size = textSize.width + 2 * margin;
  10823. this.width = size;
  10824. this.height = size;
  10825. }
  10826. };
  10827. Node.prototype._drawDatabase = function (ctx) {
  10828. this._resizeDatabase(ctx);
  10829. this.left = this.x - this.width / 2;
  10830. this.top = this.y - this.height / 2;
  10831. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  10832. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  10833. ctx.lineWidth = this.selected ? 2.0 : 1.0;
  10834. ctx.database(this.x - this.width/2, this.y - this.height*0.5, this.width, this.height);
  10835. ctx.fill();
  10836. ctx.stroke();
  10837. this._label(ctx, this.label, this.x, this.y);
  10838. };
  10839. Node.prototype._resizeCircle = function (ctx) {
  10840. if (!this.width) {
  10841. var margin = 5;
  10842. var textSize = this.getTextSize(ctx);
  10843. var diameter = Math.max(textSize.width, textSize.height) + 2 * margin;
  10844. this.radius = diameter / 2;
  10845. this.width = diameter;
  10846. this.height = diameter;
  10847. }
  10848. };
  10849. Node.prototype._drawCircle = function (ctx) {
  10850. this._resizeCircle(ctx);
  10851. this.left = this.x - this.width / 2;
  10852. this.top = this.y - this.height / 2;
  10853. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  10854. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  10855. ctx.lineWidth = this.selected ? 2.0 : 1.0;
  10856. ctx.circle(this.x, this.y, this.radius);
  10857. ctx.fill();
  10858. ctx.stroke();
  10859. this._label(ctx, this.label, this.x, this.y);
  10860. };
  10861. Node.prototype._resizeEllipse = function (ctx) {
  10862. if (!this.width) {
  10863. var textSize = this.getTextSize(ctx);
  10864. this.width = textSize.width * 1.5;
  10865. this.height = textSize.height * 2;
  10866. if (this.width < this.height) {
  10867. this.width = this.height;
  10868. }
  10869. }
  10870. };
  10871. Node.prototype._drawEllipse = function (ctx) {
  10872. this._resizeEllipse(ctx);
  10873. this.left = this.x - this.width / 2;
  10874. this.top = this.y - this.height / 2;
  10875. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  10876. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  10877. ctx.lineWidth = this.selected ? 2.0 : 1.0;
  10878. ctx.ellipse(this.left, this.top, this.width, this.height);
  10879. ctx.fill();
  10880. ctx.stroke();
  10881. this._label(ctx, this.label, this.x, this.y);
  10882. };
  10883. Node.prototype._drawDot = function (ctx) {
  10884. this._drawShape(ctx, 'circle');
  10885. };
  10886. Node.prototype._drawTriangle = function (ctx) {
  10887. this._drawShape(ctx, 'triangle');
  10888. };
  10889. Node.prototype._drawTriangleDown = function (ctx) {
  10890. this._drawShape(ctx, 'triangleDown');
  10891. };
  10892. Node.prototype._drawSquare = function (ctx) {
  10893. this._drawShape(ctx, 'square');
  10894. };
  10895. Node.prototype._drawStar = function (ctx) {
  10896. this._drawShape(ctx, 'star');
  10897. };
  10898. Node.prototype._resizeShape = function (ctx) {
  10899. if (!this.width) {
  10900. var size = 2 * this.radius;
  10901. this.width = size;
  10902. this.height = size;
  10903. }
  10904. };
  10905. Node.prototype._drawShape = function (ctx, shape) {
  10906. this._resizeShape(ctx);
  10907. this.left = this.x - this.width / 2;
  10908. this.top = this.y - this.height / 2;
  10909. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  10910. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  10911. ctx.lineWidth = this.selected ? 2.0 : 1.0;
  10912. ctx[shape](this.x, this.y, this.radius);
  10913. ctx.fill();
  10914. ctx.stroke();
  10915. if (this.label) {
  10916. this._label(ctx, this.label, this.x, this.y + this.height / 2, undefined, 'top');
  10917. }
  10918. };
  10919. Node.prototype._resizeText = function (ctx) {
  10920. if (!this.width) {
  10921. var margin = 5;
  10922. var textSize = this.getTextSize(ctx);
  10923. this.width = textSize.width + 2 * margin;
  10924. this.height = textSize.height + 2 * margin;
  10925. }
  10926. };
  10927. Node.prototype._drawText = function (ctx) {
  10928. this._resizeText(ctx);
  10929. this.left = this.x - this.width / 2;
  10930. this.top = this.y - this.height / 2;
  10931. this._label(ctx, this.label, this.x, this.y);
  10932. };
  10933. Node.prototype._label = function (ctx, text, x, y, align, baseline) {
  10934. if (text) {
  10935. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  10936. ctx.fillStyle = this.fontColor || "black";
  10937. ctx.textAlign = align || "center";
  10938. ctx.textBaseline = baseline || "middle";
  10939. var lines = text.split('\n'),
  10940. lineCount = lines.length,
  10941. fontSize = (this.fontSize + 4),
  10942. yLine = y + (1 - lineCount) / 2 * fontSize;
  10943. for (var i = 0; i < lineCount; i++) {
  10944. ctx.fillText(lines[i], x, yLine);
  10945. yLine += fontSize;
  10946. }
  10947. }
  10948. };
  10949. Node.prototype.getTextSize = function(ctx) {
  10950. if (this.label != undefined) {
  10951. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  10952. var lines = this.label.split('\n'),
  10953. height = (this.fontSize + 4) * lines.length,
  10954. width = 0;
  10955. for (var i = 0, iMax = lines.length; i < iMax; i++) {
  10956. width = Math.max(width, ctx.measureText(lines[i]).width);
  10957. }
  10958. return {"width": width, "height": height};
  10959. }
  10960. else {
  10961. return {"width": 0, "height": 0};
  10962. }
  10963. };
  10964. /**
  10965. * @class Edge
  10966. *
  10967. * A edge connects two nodes
  10968. * @param {Object} properties Object with properties. Must contain
  10969. * At least properties from and to.
  10970. * Available properties: from (number),
  10971. * to (number), label (string, color (string),
  10972. * width (number), style (string),
  10973. * length (number), title (string)
  10974. * @param {Graph} graph A graph object, used to find and edge to
  10975. * nodes.
  10976. * @param {Object} constants An object with default values for
  10977. * example for the color
  10978. */
  10979. function Edge (properties, graph, constants) {
  10980. if (!graph) {
  10981. throw "No graph provided";
  10982. }
  10983. this.graph = graph;
  10984. // initialize constants
  10985. this.widthMin = constants.edges.widthMin;
  10986. this.widthMax = constants.edges.widthMax;
  10987. // initialize variables
  10988. this.id = undefined;
  10989. this.fromId = undefined;
  10990. this.toId = undefined;
  10991. this.style = constants.edges.style;
  10992. this.title = undefined;
  10993. this.width = constants.edges.width;
  10994. this.value = undefined;
  10995. this.length = constants.edges.length;
  10996. this.from = null; // a node
  10997. this.to = null; // a node
  10998. this.connected = false;
  10999. // Added to support dashed lines
  11000. // David Jordan
  11001. // 2012-08-08
  11002. this.dash = util.extend({}, constants.edges.dash); // contains properties length, gap, altLength
  11003. this.stiffness = undefined; // depends on the length of the edge
  11004. this.color = constants.edges.color;
  11005. this.widthFixed = false;
  11006. this.lengthFixed = false;
  11007. this.setProperties(properties, constants);
  11008. }
  11009. /**
  11010. * Set or overwrite properties for the edge
  11011. * @param {Object} properties an object with properties
  11012. * @param {Object} constants and object with default, global properties
  11013. */
  11014. Edge.prototype.setProperties = function(properties, constants) {
  11015. if (!properties) {
  11016. return;
  11017. }
  11018. if (properties.from != undefined) {this.fromId = properties.from;}
  11019. if (properties.to != undefined) {this.toId = properties.to;}
  11020. if (properties.id != undefined) {this.id = properties.id;}
  11021. if (properties.style != undefined) {this.style = properties.style;}
  11022. if (properties.label != undefined) {this.label = properties.label;}
  11023. if (this.label) {
  11024. this.fontSize = constants.edges.fontSize;
  11025. this.fontFace = constants.edges.fontFace;
  11026. this.fontColor = constants.edges.fontColor;
  11027. if (properties.fontColor != undefined) {this.fontColor = properties.fontColor;}
  11028. if (properties.fontSize != undefined) {this.fontSize = properties.fontSize;}
  11029. if (properties.fontFace != undefined) {this.fontFace = properties.fontFace;}
  11030. }
  11031. if (properties.title != undefined) {this.title = properties.title;}
  11032. if (properties.width != undefined) {this.width = properties.width;}
  11033. if (properties.value != undefined) {this.value = properties.value;}
  11034. if (properties.length != undefined) {this.length = properties.length;}
  11035. // Added to support dashed lines
  11036. // David Jordan
  11037. // 2012-08-08
  11038. if (properties.dash) {
  11039. if (properties.dash.length != undefined) {this.dash.length = properties.dash.length;}
  11040. if (properties.dash.gap != undefined) {this.dash.gap = properties.dash.gap;}
  11041. if (properties.dash.altLength != undefined) {this.dash.altLength = properties.dash.altLength;}
  11042. }
  11043. if (properties.color != undefined) {this.color = properties.color;}
  11044. // A node is connected when it has a from and to node.
  11045. this.connect();
  11046. this.widthFixed = this.widthFixed || (properties.width != undefined);
  11047. this.lengthFixed = this.lengthFixed || (properties.length != undefined);
  11048. this.stiffness = 1 / this.length;
  11049. // set draw method based on style
  11050. switch (this.style) {
  11051. case 'line': this.draw = this._drawLine; break;
  11052. case 'arrow': this.draw = this._drawArrow; break;
  11053. case 'arrow-center': this.draw = this._drawArrowCenter; break;
  11054. case 'dash-line': this.draw = this._drawDashLine; break;
  11055. default: this.draw = this._drawLine; break;
  11056. }
  11057. };
  11058. /**
  11059. * Connect an edge to its nodes
  11060. */
  11061. Edge.prototype.connect = function () {
  11062. this.disconnect();
  11063. this.from = this.graph.nodes[this.fromId] || null;
  11064. this.to = this.graph.nodes[this.toId] || null;
  11065. this.connected = (this.from && this.to);
  11066. if (this.connected) {
  11067. this.from.attachEdge(this);
  11068. this.to.attachEdge(this);
  11069. }
  11070. else {
  11071. if (this.from) {
  11072. this.from.detachEdge(this);
  11073. }
  11074. if (this.to) {
  11075. this.to.detachEdge(this);
  11076. }
  11077. }
  11078. };
  11079. /**
  11080. * Disconnect an edge from its nodes
  11081. */
  11082. Edge.prototype.disconnect = function () {
  11083. if (this.from) {
  11084. this.from.detachEdge(this);
  11085. this.from = null;
  11086. }
  11087. if (this.to) {
  11088. this.to.detachEdge(this);
  11089. this.to = null;
  11090. }
  11091. this.connected = false;
  11092. };
  11093. /**
  11094. * get the title of this edge.
  11095. * @return {string} title The title of the edge, or undefined when no title
  11096. * has been set.
  11097. */
  11098. Edge.prototype.getTitle = function() {
  11099. return this.title;
  11100. };
  11101. /**
  11102. * Retrieve the value of the edge. Can be undefined
  11103. * @return {Number} value
  11104. */
  11105. Edge.prototype.getValue = function() {
  11106. return this.value;
  11107. };
  11108. /**
  11109. * Adjust the value range of the edge. The edge will adjust it's width
  11110. * based on its value.
  11111. * @param {Number} min
  11112. * @param {Number} max
  11113. */
  11114. Edge.prototype.setValueRange = function(min, max) {
  11115. if (!this.widthFixed && this.value !== undefined) {
  11116. var scale = (this.widthMax - this.widthMin) / (max - min);
  11117. this.width = (this.value - min) * scale + this.widthMin;
  11118. }
  11119. };
  11120. /**
  11121. * Redraw a edge
  11122. * Draw this edge in the given canvas
  11123. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  11124. * @param {CanvasRenderingContext2D} ctx
  11125. */
  11126. Edge.prototype.draw = function(ctx) {
  11127. throw "Method draw not initialized in edge";
  11128. };
  11129. /**
  11130. * Check if this object is overlapping with the provided object
  11131. * @param {Object} obj an object with parameters left, top
  11132. * @return {boolean} True if location is located on the edge
  11133. */
  11134. Edge.prototype.isOverlappingWith = function(obj) {
  11135. var distMax = 10;
  11136. var xFrom = this.from.x;
  11137. var yFrom = this.from.y;
  11138. var xTo = this.to.x;
  11139. var yTo = this.to.y;
  11140. var xObj = obj.left;
  11141. var yObj = obj.top;
  11142. var dist = Edge._dist(xFrom, yFrom, xTo, yTo, xObj, yObj);
  11143. return (dist < distMax);
  11144. };
  11145. /**
  11146. * Redraw a edge as a line
  11147. * Draw this edge in the given canvas
  11148. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  11149. * @param {CanvasRenderingContext2D} ctx
  11150. * @private
  11151. */
  11152. Edge.prototype._drawLine = function(ctx) {
  11153. // set style
  11154. ctx.strokeStyle = this.color;
  11155. ctx.lineWidth = this._getLineWidth();
  11156. var point;
  11157. if (this.from != this.to) {
  11158. // draw line
  11159. this._line(ctx);
  11160. // draw label
  11161. if (this.label) {
  11162. point = this._pointOnLine(0.5);
  11163. this._label(ctx, this.label, point.x, point.y);
  11164. }
  11165. }
  11166. else {
  11167. var x, y;
  11168. var radius = this.length / 4;
  11169. var node = this.from;
  11170. if (!node.width) {
  11171. node.resize(ctx);
  11172. }
  11173. if (node.width > node.height) {
  11174. x = node.x + node.width / 2;
  11175. y = node.y - radius;
  11176. }
  11177. else {
  11178. x = node.x + radius;
  11179. y = node.y - node.height / 2;
  11180. }
  11181. this._circle(ctx, x, y, radius);
  11182. point = this._pointOnCircle(x, y, radius, 0.5);
  11183. this._label(ctx, this.label, point.x, point.y);
  11184. }
  11185. };
  11186. /**
  11187. * Get the line width of the edge. Depends on width and whether one of the
  11188. * connected nodes is selected.
  11189. * @return {Number} width
  11190. * @private
  11191. */
  11192. Edge.prototype._getLineWidth = function() {
  11193. if (this.from.selected || this.to.selected) {
  11194. return Math.min(this.width * 2, this.widthMax);
  11195. }
  11196. else {
  11197. return this.width;
  11198. }
  11199. };
  11200. /**
  11201. * Draw a line between two nodes
  11202. * @param {CanvasRenderingContext2D} ctx
  11203. * @private
  11204. */
  11205. Edge.prototype._line = function (ctx) {
  11206. // draw a straight line
  11207. ctx.beginPath();
  11208. ctx.moveTo(this.from.x, this.from.y);
  11209. ctx.lineTo(this.to.x, this.to.y);
  11210. ctx.stroke();
  11211. };
  11212. /**
  11213. * Draw a line from a node to itself, a circle
  11214. * @param {CanvasRenderingContext2D} ctx
  11215. * @param {Number} x
  11216. * @param {Number} y
  11217. * @param {Number} radius
  11218. * @private
  11219. */
  11220. Edge.prototype._circle = function (ctx, x, y, radius) {
  11221. // draw a circle
  11222. ctx.beginPath();
  11223. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  11224. ctx.stroke();
  11225. };
  11226. /**
  11227. * Draw label with white background and with the middle at (x, y)
  11228. * @param {CanvasRenderingContext2D} ctx
  11229. * @param {String} text
  11230. * @param {Number} x
  11231. * @param {Number} y
  11232. * @private
  11233. */
  11234. Edge.prototype._label = function (ctx, text, x, y) {
  11235. if (text) {
  11236. // TODO: cache the calculated size
  11237. ctx.font = ((this.from.selected || this.to.selected) ? "bold " : "") +
  11238. this.fontSize + "px " + this.fontFace;
  11239. ctx.fillStyle = 'white';
  11240. var width = ctx.measureText(text).width;
  11241. var height = this.fontSize;
  11242. var left = x - width / 2;
  11243. var top = y - height / 2;
  11244. ctx.fillRect(left, top, width, height);
  11245. // draw text
  11246. ctx.fillStyle = this.fontColor || "black";
  11247. ctx.textAlign = "left";
  11248. ctx.textBaseline = "top";
  11249. ctx.fillText(text, left, top);
  11250. }
  11251. };
  11252. /**
  11253. * Redraw a edge as a dashed line
  11254. * Draw this edge in the given canvas
  11255. * @author David Jordan
  11256. * @date 2012-08-08
  11257. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  11258. * @param {CanvasRenderingContext2D} ctx
  11259. * @private
  11260. */
  11261. Edge.prototype._drawDashLine = function(ctx) {
  11262. // set style
  11263. ctx.strokeStyle = this.color;
  11264. ctx.lineWidth = this._getLineWidth();
  11265. // draw dashed line
  11266. ctx.beginPath();
  11267. ctx.lineCap = 'round';
  11268. if (this.dash.altLength != undefined) //If an alt dash value has been set add to the array this value
  11269. {
  11270. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  11271. [this.dash.length,this.dash.gap,this.dash.altLength,this.dash.gap]);
  11272. }
  11273. 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
  11274. {
  11275. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  11276. [this.dash.length,this.dash.gap]);
  11277. }
  11278. else //If all else fails draw a line
  11279. {
  11280. ctx.moveTo(this.from.x, this.from.y);
  11281. ctx.lineTo(this.to.x, this.to.y);
  11282. }
  11283. ctx.stroke();
  11284. // draw label
  11285. if (this.label) {
  11286. var point = this._pointOnLine(0.5);
  11287. this._label(ctx, this.label, point.x, point.y);
  11288. }
  11289. };
  11290. /**
  11291. * Get a point on a line
  11292. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  11293. * @return {Object} point
  11294. * @private
  11295. */
  11296. Edge.prototype._pointOnLine = function (percentage) {
  11297. return {
  11298. x: (1 - percentage) * this.from.x + percentage * this.to.x,
  11299. y: (1 - percentage) * this.from.y + percentage * this.to.y
  11300. }
  11301. };
  11302. /**
  11303. * Get a point on a circle
  11304. * @param {Number} x
  11305. * @param {Number} y
  11306. * @param {Number} radius
  11307. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  11308. * @return {Object} point
  11309. * @private
  11310. */
  11311. Edge.prototype._pointOnCircle = function (x, y, radius, percentage) {
  11312. var angle = (percentage - 3/8) * 2 * Math.PI;
  11313. return {
  11314. x: x + radius * Math.cos(angle),
  11315. y: y - radius * Math.sin(angle)
  11316. }
  11317. };
  11318. /**
  11319. * Redraw a edge as a line with an arrow halfway the line
  11320. * Draw this edge in the given canvas
  11321. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  11322. * @param {CanvasRenderingContext2D} ctx
  11323. * @private
  11324. */
  11325. Edge.prototype._drawArrowCenter = function(ctx) {
  11326. var point;
  11327. // set style
  11328. ctx.strokeStyle = this.color;
  11329. ctx.fillStyle = this.color;
  11330. ctx.lineWidth = this._getLineWidth();
  11331. if (this.from != this.to) {
  11332. // draw line
  11333. this._line(ctx);
  11334. // draw an arrow halfway the line
  11335. var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  11336. var length = 10 + 5 * this.width; // TODO: make customizable?
  11337. point = this._pointOnLine(0.5);
  11338. ctx.arrow(point.x, point.y, angle, length);
  11339. ctx.fill();
  11340. ctx.stroke();
  11341. // draw label
  11342. if (this.label) {
  11343. point = this._pointOnLine(0.5);
  11344. this._label(ctx, this.label, point.x, point.y);
  11345. }
  11346. }
  11347. else {
  11348. // draw circle
  11349. var x, y;
  11350. var radius = this.length / 4;
  11351. var node = this.from;
  11352. if (!node.width) {
  11353. node.resize(ctx);
  11354. }
  11355. if (node.width > node.height) {
  11356. x = node.x + node.width / 2;
  11357. y = node.y - radius;
  11358. }
  11359. else {
  11360. x = node.x + radius;
  11361. y = node.y - node.height / 2;
  11362. }
  11363. this._circle(ctx, x, y, radius);
  11364. // draw all arrows
  11365. var angle = 0.2 * Math.PI;
  11366. var length = 10 + 5 * this.width; // TODO: make customizable?
  11367. point = this._pointOnCircle(x, y, radius, 0.5);
  11368. ctx.arrow(point.x, point.y, angle, length);
  11369. ctx.fill();
  11370. ctx.stroke();
  11371. // draw label
  11372. if (this.label) {
  11373. point = this._pointOnCircle(x, y, radius, 0.5);
  11374. this._label(ctx, this.label, point.x, point.y);
  11375. }
  11376. }
  11377. };
  11378. /**
  11379. * Redraw a edge as a line with an arrow
  11380. * Draw this edge in the given canvas
  11381. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  11382. * @param {CanvasRenderingContext2D} ctx
  11383. * @private
  11384. */
  11385. Edge.prototype._drawArrow = function(ctx) {
  11386. // set style
  11387. ctx.strokeStyle = this.color;
  11388. ctx.fillStyle = this.color;
  11389. ctx.lineWidth = this._getLineWidth();
  11390. // draw line
  11391. var angle, length;
  11392. if (this.from != this.to) {
  11393. // calculate length and angle of the line
  11394. angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  11395. var dx = (this.to.x - this.from.x);
  11396. var dy = (this.to.y - this.from.y);
  11397. var lEdge = Math.sqrt(dx * dx + dy * dy);
  11398. var lFrom = this.from.distanceToBorder(ctx, angle + Math.PI);
  11399. var pFrom = (lEdge - lFrom) / lEdge;
  11400. var xFrom = (pFrom) * this.from.x + (1 - pFrom) * this.to.x;
  11401. var yFrom = (pFrom) * this.from.y + (1 - pFrom) * this.to.y;
  11402. var lTo = this.to.distanceToBorder(ctx, angle);
  11403. var pTo = (lEdge - lTo) / lEdge;
  11404. var xTo = (1 - pTo) * this.from.x + pTo * this.to.x;
  11405. var yTo = (1 - pTo) * this.from.y + pTo * this.to.y;
  11406. ctx.beginPath();
  11407. ctx.moveTo(xFrom, yFrom);
  11408. ctx.lineTo(xTo, yTo);
  11409. ctx.stroke();
  11410. // draw arrow at the end of the line
  11411. length = 10 + 5 * this.width; // TODO: make customizable?
  11412. ctx.arrow(xTo, yTo, angle, length);
  11413. ctx.fill();
  11414. ctx.stroke();
  11415. // draw label
  11416. if (this.label) {
  11417. var point = this._pointOnLine(0.5);
  11418. this._label(ctx, this.label, point.x, point.y);
  11419. }
  11420. }
  11421. else {
  11422. // draw circle
  11423. var node = this.from;
  11424. var x, y, arrow;
  11425. var radius = this.length / 4;
  11426. if (!node.width) {
  11427. node.resize(ctx);
  11428. }
  11429. if (node.width > node.height) {
  11430. x = node.x + node.width / 2;
  11431. y = node.y - radius;
  11432. arrow = {
  11433. x: x,
  11434. y: node.y,
  11435. angle: 0.9 * Math.PI
  11436. };
  11437. }
  11438. else {
  11439. x = node.x + radius;
  11440. y = node.y - node.height / 2;
  11441. arrow = {
  11442. x: node.x,
  11443. y: y,
  11444. angle: 0.6 * Math.PI
  11445. };
  11446. }
  11447. ctx.beginPath();
  11448. // TODO: do not draw a circle, but an arc
  11449. // TODO: similarly, for a line without arrows, draw to the border of the nodes instead of the center
  11450. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  11451. ctx.stroke();
  11452. // draw all arrows
  11453. length = 10 + 5 * this.width; // TODO: make customizable?
  11454. ctx.arrow(arrow.x, arrow.y, arrow.angle, length);
  11455. ctx.fill();
  11456. ctx.stroke();
  11457. // draw label
  11458. if (this.label) {
  11459. point = this._pointOnCircle(x, y, radius, 0.5);
  11460. this._label(ctx, this.label, point.x, point.y);
  11461. }
  11462. }
  11463. };
  11464. /**
  11465. * Calculate the distance between a point (x3,y3) and a line segment from
  11466. * (x1,y1) to (x2,y2).
  11467. * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
  11468. * @param {number} x1
  11469. * @param {number} y1
  11470. * @param {number} x2
  11471. * @param {number} y2
  11472. * @param {number} x3
  11473. * @param {number} y3
  11474. * @private
  11475. */
  11476. Edge._dist = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is the point
  11477. var px = x2-x1,
  11478. py = y2-y1,
  11479. something = px*px + py*py,
  11480. u = ((x3 - x1) * px + (y3 - y1) * py) / something;
  11481. if (u > 1) {
  11482. u = 1;
  11483. }
  11484. else if (u < 0) {
  11485. u = 0;
  11486. }
  11487. var x = x1 + u * px,
  11488. y = y1 + u * py,
  11489. dx = x - x3,
  11490. dy = y - y3;
  11491. //# Note: If the actual distance does not matter,
  11492. //# if you only want to compare what this function
  11493. //# returns to other results of this function, you
  11494. //# can just return the squared distance instead
  11495. //# (i.e. remove the sqrt) to gain a little performance
  11496. return Math.sqrt(dx*dx + dy*dy);
  11497. };
  11498. /**
  11499. * Popup is a class to create a popup window with some text
  11500. * @param {Element} container The container object.
  11501. * @param {Number} [x]
  11502. * @param {Number} [y]
  11503. * @param {String} [text]
  11504. */
  11505. function Popup(container, x, y, text) {
  11506. if (container) {
  11507. this.container = container;
  11508. }
  11509. else {
  11510. this.container = document.body;
  11511. }
  11512. this.x = 0;
  11513. this.y = 0;
  11514. this.padding = 5;
  11515. if (x !== undefined && y !== undefined ) {
  11516. this.setPosition(x, y);
  11517. }
  11518. if (text !== undefined) {
  11519. this.setText(text);
  11520. }
  11521. // create the frame
  11522. this.frame = document.createElement("div");
  11523. var style = this.frame.style;
  11524. style.position = "absolute";
  11525. style.visibility = "hidden";
  11526. style.border = "1px solid #666";
  11527. style.color = "black";
  11528. style.padding = this.padding + "px";
  11529. style.backgroundColor = "#FFFFC6";
  11530. style.borderRadius = "3px";
  11531. style.MozBorderRadius = "3px";
  11532. style.WebkitBorderRadius = "3px";
  11533. style.boxShadow = "3px 3px 10px rgba(128, 128, 128, 0.5)";
  11534. style.whiteSpace = "nowrap";
  11535. this.container.appendChild(this.frame);
  11536. };
  11537. /**
  11538. * @param {number} x Horizontal position of the popup window
  11539. * @param {number} y Vertical position of the popup window
  11540. */
  11541. Popup.prototype.setPosition = function(x, y) {
  11542. this.x = parseInt(x);
  11543. this.y = parseInt(y);
  11544. };
  11545. /**
  11546. * Set the text for the popup window. This can be HTML code
  11547. * @param {string} text
  11548. */
  11549. Popup.prototype.setText = function(text) {
  11550. this.frame.innerHTML = text;
  11551. };
  11552. /**
  11553. * Show the popup window
  11554. * @param {boolean} show Optional. Show or hide the window
  11555. */
  11556. Popup.prototype.show = function (show) {
  11557. if (show === undefined) {
  11558. show = true;
  11559. }
  11560. if (show) {
  11561. var height = this.frame.clientHeight;
  11562. var width = this.frame.clientWidth;
  11563. var maxHeight = this.frame.parentNode.clientHeight;
  11564. var maxWidth = this.frame.parentNode.clientWidth;
  11565. var top = (this.y - height);
  11566. if (top + height + this.padding > maxHeight) {
  11567. top = maxHeight - height - this.padding;
  11568. }
  11569. if (top < this.padding) {
  11570. top = this.padding;
  11571. }
  11572. var left = this.x;
  11573. if (left + width + this.padding > maxWidth) {
  11574. left = maxWidth - width - this.padding;
  11575. }
  11576. if (left < this.padding) {
  11577. left = this.padding;
  11578. }
  11579. this.frame.style.left = left + "px";
  11580. this.frame.style.top = top + "px";
  11581. this.frame.style.visibility = "visible";
  11582. }
  11583. else {
  11584. this.hide();
  11585. }
  11586. };
  11587. /**
  11588. * Hide the popup window
  11589. */
  11590. Popup.prototype.hide = function () {
  11591. this.frame.style.visibility = "hidden";
  11592. };
  11593. /**
  11594. * @class Groups
  11595. * This class can store groups and properties specific for groups.
  11596. */
  11597. Groups = function () {
  11598. this.clear();
  11599. this.defaultIndex = 0;
  11600. };
  11601. /**
  11602. * default constants for group colors
  11603. */
  11604. Groups.DEFAULT = [
  11605. {border: "#2B7CE9", background: "#97C2FC", highlight: {border: "#2B7CE9", background: "#D2E5FF"}}, // blue
  11606. {border: "#FFA500", background: "#FFFF00", highlight: {border: "#FFA500", background: "#FFFFA3"}}, // yellow
  11607. {border: "#FA0A10", background: "#FB7E81", highlight: {border: "#FA0A10", background: "#FFAFB1"}}, // red
  11608. {border: "#41A906", background: "#7BE141", highlight: {border: "#41A906", background: "#A1EC76"}}, // green
  11609. {border: "#E129F0", background: "#EB7DF4", highlight: {border: "#E129F0", background: "#F0B3F5"}}, // magenta
  11610. {border: "#7C29F0", background: "#AD85E4", highlight: {border: "#7C29F0", background: "#D3BDF0"}}, // purple
  11611. {border: "#C37F00", background: "#FFA807", highlight: {border: "#C37F00", background: "#FFCA66"}}, // orange
  11612. {border: "#4220FB", background: "#6E6EFD", highlight: {border: "#4220FB", background: "#9B9BFD"}}, // darkblue
  11613. {border: "#FD5A77", background: "#FFC0CB", highlight: {border: "#FD5A77", background: "#FFD1D9"}}, // pink
  11614. {border: "#4AD63A", background: "#C2FABC", highlight: {border: "#4AD63A", background: "#E6FFE3"}} // mint
  11615. ];
  11616. /**
  11617. * Clear all groups
  11618. */
  11619. Groups.prototype.clear = function () {
  11620. this.groups = {};
  11621. this.groups.length = function()
  11622. {
  11623. var i = 0;
  11624. for ( var p in this ) {
  11625. if (this.hasOwnProperty(p)) {
  11626. i++;
  11627. }
  11628. }
  11629. return i;
  11630. }
  11631. };
  11632. /**
  11633. * get group properties of a groupname. If groupname is not found, a new group
  11634. * is added.
  11635. * @param {*} groupname Can be a number, string, Date, etc.
  11636. * @return {Object} group The created group, containing all group properties
  11637. */
  11638. Groups.prototype.get = function (groupname) {
  11639. var group = this.groups[groupname];
  11640. if (group == undefined) {
  11641. // create new group
  11642. var index = this.defaultIndex % Groups.DEFAULT.length;
  11643. this.defaultIndex++;
  11644. group = {};
  11645. group.color = Groups.DEFAULT[index];
  11646. this.groups[groupname] = group;
  11647. }
  11648. return group;
  11649. };
  11650. /**
  11651. * Add a custom group style
  11652. * @param {String} groupname
  11653. * @param {Object} style An object containing borderColor,
  11654. * backgroundColor, etc.
  11655. * @return {Object} group The created group object
  11656. */
  11657. Groups.prototype.add = function (groupname, style) {
  11658. this.groups[groupname] = style;
  11659. if (style.color) {
  11660. style.color = Node.parseColor(style.color);
  11661. }
  11662. return style;
  11663. };
  11664. /**
  11665. * @class Images
  11666. * This class loads images and keeps them stored.
  11667. */
  11668. Images = function () {
  11669. this.images = {};
  11670. this.callback = undefined;
  11671. };
  11672. /**
  11673. * Set an onload callback function. This will be called each time an image
  11674. * is loaded
  11675. * @param {function} callback
  11676. */
  11677. Images.prototype.setOnloadCallback = function(callback) {
  11678. this.callback = callback;
  11679. };
  11680. /**
  11681. *
  11682. * @param {string} url Url of the image
  11683. * @return {Image} img The image object
  11684. */
  11685. Images.prototype.load = function(url) {
  11686. var img = this.images[url];
  11687. if (img == undefined) {
  11688. // create the image
  11689. var images = this;
  11690. img = new Image();
  11691. this.images[url] = img;
  11692. img.onload = function() {
  11693. if (images.callback) {
  11694. images.callback(this);
  11695. }
  11696. };
  11697. img.src = url;
  11698. }
  11699. return img;
  11700. };
  11701. /**
  11702. * @constructor Graph
  11703. * Create a graph visualization, displaying nodes and edges.
  11704. *
  11705. * @param {Element} container The DOM element in which the Graph will
  11706. * be created. Normally a div element.
  11707. * @param {Object} data An object containing parameters
  11708. * {Array} nodes
  11709. * {Array} edges
  11710. * @param {Object} options Options
  11711. */
  11712. function Graph (container, data, options) {
  11713. // create variables and set default values
  11714. this.containerElement = container;
  11715. this.width = '100%';
  11716. this.height = '100%';
  11717. this.refreshRate = 50; // milliseconds
  11718. this.stabilize = true; // stabilize before displaying the graph
  11719. this.selectable = true;
  11720. // set constant values
  11721. this.constants = {
  11722. nodes: {
  11723. radiusMin: 5,
  11724. radiusMax: 20,
  11725. radius: 5,
  11726. distance: 100, // px
  11727. shape: 'ellipse',
  11728. image: undefined,
  11729. widthMin: 16, // px
  11730. widthMax: 64, // px
  11731. fontColor: 'black',
  11732. fontSize: 14, // px
  11733. //fontFace: verdana,
  11734. fontFace: 'arial',
  11735. color: {
  11736. border: '#2B7CE9',
  11737. background: '#97C2FC',
  11738. highlight: {
  11739. border: '#2B7CE9',
  11740. background: '#D2E5FF'
  11741. }
  11742. },
  11743. borderColor: '#2B7CE9',
  11744. backgroundColor: '#97C2FC',
  11745. highlightColor: '#D2E5FF',
  11746. group: undefined
  11747. },
  11748. edges: {
  11749. widthMin: 1,
  11750. widthMax: 15,
  11751. width: 1,
  11752. style: 'line',
  11753. color: '#343434',
  11754. fontColor: '#343434',
  11755. fontSize: 14, // px
  11756. fontFace: 'arial',
  11757. //distance: 100, //px
  11758. length: 100, // px
  11759. dash: {
  11760. length: 10,
  11761. gap: 5,
  11762. altLength: undefined
  11763. }
  11764. },
  11765. minForce: 0.05,
  11766. minVelocity: 0.02, // px/s
  11767. maxIterations: 1000 // maximum number of iteration to stabilize
  11768. };
  11769. var graph = this;
  11770. this.nodes = {}; // object with Node objects
  11771. this.edges = {}; // object with Edge objects
  11772. // TODO: create a counter to keep track on the number of nodes having values
  11773. // TODO: create a counter to keep track on the number of nodes currently moving
  11774. // TODO: create a counter to keep track on the number of edges having values
  11775. this.nodesData = null; // A DataSet or DataView
  11776. this.edgesData = null; // A DataSet or DataView
  11777. // create event listeners used to subscribe on the DataSets of the nodes and edges
  11778. var me = this;
  11779. this.nodesListeners = {
  11780. 'add': function (event, params) {
  11781. me._addNodes(params.items);
  11782. me.start();
  11783. },
  11784. 'update': function (event, params) {
  11785. me._updateNodes(params.items);
  11786. me.start();
  11787. },
  11788. 'remove': function (event, params) {
  11789. me._removeNodes(params.items);
  11790. me.start();
  11791. }
  11792. };
  11793. this.edgesListeners = {
  11794. 'add': function (event, params) {
  11795. me._addEdges(params.items);
  11796. me.start();
  11797. },
  11798. 'update': function (event, params) {
  11799. me._updateEdges(params.items);
  11800. me.start();
  11801. },
  11802. 'remove': function (event, params) {
  11803. me._removeEdges(params.items);
  11804. me.start();
  11805. }
  11806. };
  11807. this.groups = new Groups(); // object with groups
  11808. this.images = new Images(); // object with images
  11809. this.images.setOnloadCallback(function () {
  11810. graph._redraw();
  11811. });
  11812. // properties of the data
  11813. this.moving = false; // True if any of the nodes have an undefined position
  11814. this.selection = [];
  11815. this.timer = undefined;
  11816. // create a frame and canvas
  11817. this._create();
  11818. // apply options
  11819. this.setOptions(options);
  11820. // draw data
  11821. this.setData(data);
  11822. }
  11823. /**
  11824. * Set nodes and edges, and optionally options as well.
  11825. *
  11826. * @param {Object} data Object containing parameters:
  11827. * {Array | DataSet | DataView} [nodes] Array with nodes
  11828. * {Array | DataSet | DataView} [edges] Array with edges
  11829. * {String} [dot] String containing data in DOT format
  11830. * {Options} [options] Object with options
  11831. */
  11832. Graph.prototype.setData = function(data) {
  11833. if (data && data.dot && (data.nodes || data.edges)) {
  11834. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  11835. ' parameter pair "nodes" and "edges", but not both.');
  11836. }
  11837. // set options
  11838. this.setOptions(data && data.options);
  11839. // set all data
  11840. if (data && data.dot) {
  11841. // parse DOT file
  11842. if(data && data.dot) {
  11843. var dotData = vis.util.DOTToGraph(data.dot);
  11844. this.setData(dotData);
  11845. return;
  11846. }
  11847. }
  11848. else {
  11849. this._setNodes(data && data.nodes);
  11850. this._setEdges(data && data.edges);
  11851. }
  11852. // find a stable position or start animating to a stable position
  11853. if (this.stabilize) {
  11854. this._doStabilize();
  11855. }
  11856. this.start();
  11857. };
  11858. /**
  11859. * Set options
  11860. * @param {Object} options
  11861. */
  11862. Graph.prototype.setOptions = function (options) {
  11863. if (options) {
  11864. // retrieve parameter values
  11865. if (options.width != undefined) {this.width = options.width;}
  11866. if (options.height != undefined) {this.height = options.height;}
  11867. if (options.stabilize != undefined) {this.stabilize = options.stabilize;}
  11868. if (options.selectable != undefined) {this.selectable = options.selectable;}
  11869. // TODO: work out these options and document them
  11870. if (options.edges) {
  11871. for (var prop in options.edges) {
  11872. if (options.edges.hasOwnProperty(prop)) {
  11873. this.constants.edges[prop] = options.edges[prop];
  11874. }
  11875. }
  11876. if (options.edges.length != undefined &&
  11877. options.nodes && options.nodes.distance == undefined) {
  11878. this.constants.edges.length = options.edges.length;
  11879. this.constants.nodes.distance = options.edges.length * 1.25;
  11880. }
  11881. if (!options.edges.fontColor) {
  11882. this.constants.edges.fontColor = options.edges.color;
  11883. }
  11884. // Added to support dashed lines
  11885. // David Jordan
  11886. // 2012-08-08
  11887. if (options.edges.dash) {
  11888. if (options.edges.dash.length != undefined) {
  11889. this.constants.edges.dash.length = options.edges.dash.length;
  11890. }
  11891. if (options.edges.dash.gap != undefined) {
  11892. this.constants.edges.dash.gap = options.edges.dash.gap;
  11893. }
  11894. if (options.edges.dash.altLength != undefined) {
  11895. this.constants.edges.dash.altLength = options.edges.dash.altLength;
  11896. }
  11897. }
  11898. }
  11899. if (options.nodes) {
  11900. for (prop in options.nodes) {
  11901. if (options.nodes.hasOwnProperty(prop)) {
  11902. this.constants.nodes[prop] = options.nodes[prop];
  11903. }
  11904. }
  11905. if (options.nodes.color) {
  11906. this.constants.nodes.color = Node.parseColor(options.nodes.color);
  11907. }
  11908. /*
  11909. if (options.nodes.widthMin) this.constants.nodes.radiusMin = options.nodes.widthMin;
  11910. if (options.nodes.widthMax) this.constants.nodes.radiusMax = options.nodes.widthMax;
  11911. */
  11912. }
  11913. if (options.groups) {
  11914. for (var groupname in options.groups) {
  11915. if (options.groups.hasOwnProperty(groupname)) {
  11916. var group = options.groups[groupname];
  11917. this.groups.add(groupname, group);
  11918. }
  11919. }
  11920. }
  11921. }
  11922. this.setSize(this.width, this.height);
  11923. this._setTranslation(this.frame.clientWidth / 2, this.frame.clientHeight / 2);
  11924. this._setScale(1);
  11925. };
  11926. /**
  11927. * fire an event
  11928. * @param {String} event The name of an event, for example 'select'
  11929. * @param {Object} params Optional object with event parameters
  11930. * @private
  11931. */
  11932. Graph.prototype._trigger = function (event, params) {
  11933. events.trigger(this, event, params);
  11934. };
  11935. /**
  11936. * Create the main frame for the Graph.
  11937. * This function is executed once when a Graph object is created. The frame
  11938. * contains a canvas, and this canvas contains all objects like the axis and
  11939. * nodes.
  11940. * @private
  11941. */
  11942. Graph.prototype._create = function () {
  11943. // remove all elements from the container element.
  11944. while (this.containerElement.hasChildNodes()) {
  11945. this.containerElement.removeChild(this.containerElement.firstChild);
  11946. }
  11947. this.frame = document.createElement('div');
  11948. this.frame.className = 'graph-frame';
  11949. this.frame.style.position = 'relative';
  11950. this.frame.style.overflow = 'hidden';
  11951. // create the graph canvas (HTML canvas element)
  11952. this.frame.canvas = document.createElement( 'canvas' );
  11953. this.frame.canvas.style.position = 'relative';
  11954. this.frame.appendChild(this.frame.canvas);
  11955. if (!this.frame.canvas.getContext) {
  11956. var noCanvas = document.createElement( 'DIV' );
  11957. noCanvas.style.color = 'red';
  11958. noCanvas.style.fontWeight = 'bold' ;
  11959. noCanvas.style.padding = '10px';
  11960. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  11961. this.frame.canvas.appendChild(noCanvas);
  11962. }
  11963. var me = this;
  11964. this.drag = {};
  11965. this.pinch = {};
  11966. this.hammer = Hammer(this.frame.canvas, {
  11967. prevent_default: true
  11968. });
  11969. this.hammer.on('tap', me._onTap.bind(me) );
  11970. this.hammer.on('hold', me._onHold.bind(me) );
  11971. this.hammer.on('pinch', me._onPinch.bind(me) );
  11972. this.hammer.on('touch', me._onTouch.bind(me) );
  11973. this.hammer.on('dragstart', me._onDragStart.bind(me) );
  11974. this.hammer.on('drag', me._onDrag.bind(me) );
  11975. this.hammer.on('dragend', me._onDragEnd.bind(me) );
  11976. this.hammer.on('mousewheel',me._onMouseWheel.bind(me) );
  11977. this.hammer.on('DOMMouseScroll',me._onMouseWheel.bind(me) ); // for FF
  11978. this.hammer.on('mousemove', me._onMouseMoveTitle.bind(me) );
  11979. // add the frame to the container element
  11980. this.containerElement.appendChild(this.frame);
  11981. };
  11982. /**
  11983. *
  11984. * @param {{x: Number, y: Number}} pointer
  11985. * @return {Number | null} node
  11986. * @private
  11987. */
  11988. Graph.prototype._getNodeAt = function (pointer) {
  11989. var x = this._canvasToX(pointer.x);
  11990. var y = this._canvasToY(pointer.y);
  11991. var obj = {
  11992. left: x,
  11993. top: y,
  11994. right: x,
  11995. bottom: y
  11996. };
  11997. // if there are overlapping nodes, select the last one, this is the
  11998. // one which is drawn on top of the others
  11999. var overlappingNodes = this._getNodesOverlappingWith(obj);
  12000. return (overlappingNodes.length > 0) ?
  12001. overlappingNodes[overlappingNodes.length - 1] : null;
  12002. };
  12003. /**
  12004. * Get the pointer location from a touch location
  12005. * @param {{pageX: Number, pageY: Number}} touch
  12006. * @return {{x: Number, y: Number}} pointer
  12007. * @private
  12008. */
  12009. Graph.prototype._getPointer = function (touch) {
  12010. return {
  12011. x: touch.pageX - vis.util.getAbsoluteLeft(this.frame.canvas),
  12012. y: touch.pageY - vis.util.getAbsoluteTop(this.frame.canvas)
  12013. };
  12014. };
  12015. /**
  12016. * On start of a touch gesture, store the pointer
  12017. * @param event
  12018. * @private
  12019. */
  12020. Graph.prototype._onTouch = function (event) {
  12021. this.drag.pointer = this._getPointer(event.gesture.touches[0]);
  12022. this.drag.pinched = false;
  12023. this.pinch.scale = this._getScale();
  12024. };
  12025. /**
  12026. * handle drag start event
  12027. * @private
  12028. */
  12029. Graph.prototype._onDragStart = function () {
  12030. var drag = this.drag;
  12031. drag.selection = [];
  12032. drag.translation = this._getTranslation();
  12033. drag.nodeId = this._getNodeAt(drag.pointer);
  12034. // note: drag.pointer is set in _onTouch to get the initial touch location
  12035. var node = this.nodes[drag.nodeId];
  12036. if (node) {
  12037. // select the clicked node if not yet selected
  12038. if (!node.isSelected()) {
  12039. this._selectNodes([drag.nodeId]);
  12040. }
  12041. // create an array with the selected nodes and their original location and status
  12042. var me = this;
  12043. this.selection.forEach(function (id) {
  12044. var node = me.nodes[id];
  12045. if (node) {
  12046. var s = {
  12047. id: id,
  12048. node: node,
  12049. // store original x, y, xFixed and yFixed, make the node temporarily Fixed
  12050. x: node.x,
  12051. y: node.y,
  12052. xFixed: node.xFixed,
  12053. yFixed: node.yFixed
  12054. };
  12055. node.xFixed = true;
  12056. node.yFixed = true;
  12057. drag.selection.push(s);
  12058. }
  12059. });
  12060. }
  12061. };
  12062. /**
  12063. * handle drag event
  12064. * @private
  12065. */
  12066. Graph.prototype._onDrag = function (event) {
  12067. if (this.drag.pinched) {
  12068. return;
  12069. }
  12070. var pointer = this._getPointer(event.gesture.touches[0]);
  12071. var me = this,
  12072. drag = this.drag,
  12073. selection = drag.selection;
  12074. if (selection && selection.length) {
  12075. // calculate delta's and new location
  12076. var deltaX = pointer.x - drag.pointer.x,
  12077. deltaY = pointer.y - drag.pointer.y;
  12078. // update position of all selected nodes
  12079. selection.forEach(function (s) {
  12080. var node = s.node;
  12081. if (!s.xFixed) {
  12082. node.x = me._canvasToX(me._xToCanvas(s.x) + deltaX);
  12083. }
  12084. if (!s.yFixed) {
  12085. node.y = me._canvasToY(me._yToCanvas(s.y) + deltaY);
  12086. }
  12087. });
  12088. // start animation if not yet running
  12089. if (!this.moving) {
  12090. this.moving = true;
  12091. this.start();
  12092. }
  12093. }
  12094. else {
  12095. // move the graph
  12096. var diffX = pointer.x - this.drag.pointer.x;
  12097. var diffY = pointer.y - this.drag.pointer.y;
  12098. this._setTranslation(
  12099. this.drag.translation.x + diffX,
  12100. this.drag.translation.y + diffY);
  12101. this._redraw();
  12102. this.moved = true;
  12103. }
  12104. };
  12105. /**
  12106. * handle drag start event
  12107. * @private
  12108. */
  12109. Graph.prototype._onDragEnd = function () {
  12110. var selection = this.drag.selection;
  12111. if (selection) {
  12112. selection.forEach(function (s) {
  12113. // restore original xFixed and yFixed
  12114. s.node.xFixed = s.xFixed;
  12115. s.node.yFixed = s.yFixed;
  12116. });
  12117. }
  12118. };
  12119. /**
  12120. * handle tap/click event: select/unselect a node
  12121. * @private
  12122. */
  12123. Graph.prototype._onTap = function (event) {
  12124. var pointer = this._getPointer(event.gesture.touches[0]);
  12125. var nodeId = this._getNodeAt(pointer);
  12126. var node = this.nodes[nodeId];
  12127. if (node) {
  12128. // select this node
  12129. this._selectNodes([nodeId]);
  12130. if (!this.moving) {
  12131. this._redraw();
  12132. }
  12133. }
  12134. else {
  12135. // remove selection
  12136. this._unselectNodes();
  12137. this._redraw();
  12138. }
  12139. };
  12140. /**
  12141. * handle long tap event: multi select nodes
  12142. * @private
  12143. */
  12144. Graph.prototype._onHold = function (event) {
  12145. var pointer = this._getPointer(event.gesture.touches[0]);
  12146. var nodeId = this._getNodeAt(pointer);
  12147. var node = this.nodes[nodeId];
  12148. if (node) {
  12149. if (!node.isSelected()) {
  12150. // select this node, keep previous selection
  12151. var append = true;
  12152. this._selectNodes([nodeId], append);
  12153. }
  12154. else {
  12155. this._unselectNodes([nodeId]);
  12156. }
  12157. if (!this.moving) {
  12158. this._redraw();
  12159. }
  12160. }
  12161. else {
  12162. // Do nothing
  12163. }
  12164. };
  12165. /**
  12166. * Handle pinch event
  12167. * @param event
  12168. * @private
  12169. */
  12170. Graph.prototype._onPinch = function (event) {
  12171. var pointer = this._getPointer(event.gesture.center);
  12172. this.drag.pinched = true;
  12173. if (!('scale' in this.pinch)) {
  12174. this.pinch.scale = 1;
  12175. }
  12176. // TODO: enable moving while pinching?
  12177. var scale = this.pinch.scale * event.gesture.scale;
  12178. this._zoom(scale, pointer)
  12179. };
  12180. /**
  12181. * Zoom the graph in or out
  12182. * @param {Number} scale a number around 1, and between 0.01 and 10
  12183. * @param {{x: Number, y: Number}} pointer
  12184. * @return {Number} appliedScale scale is limited within the boundaries
  12185. * @private
  12186. */
  12187. Graph.prototype._zoom = function(scale, pointer) {
  12188. var scaleOld = this._getScale();
  12189. if (scale < 0.01) {
  12190. scale = 0.01;
  12191. }
  12192. if (scale > 10) {
  12193. scale = 10;
  12194. }
  12195. var translation = this._getTranslation();
  12196. var scaleFrac = scale / scaleOld;
  12197. var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac;
  12198. var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac;
  12199. this._setScale(scale);
  12200. this._setTranslation(tx, ty);
  12201. this._redraw();
  12202. return scale;
  12203. };
  12204. /**
  12205. * Event handler for mouse wheel event, used to zoom the timeline
  12206. * See http://adomas.org/javascript-mouse-wheel/
  12207. * https://github.com/EightMedia/hammer.js/issues/256
  12208. * @param {MouseEvent} event
  12209. * @private
  12210. */
  12211. Graph.prototype._onMouseWheel = function(event) {
  12212. // retrieve delta
  12213. var delta = 0;
  12214. if (event.wheelDelta) { /* IE/Opera. */
  12215. delta = event.wheelDelta/120;
  12216. } else if (event.detail) { /* Mozilla case. */
  12217. // In Mozilla, sign of delta is different than in IE.
  12218. // Also, delta is multiple of 3.
  12219. delta = -event.detail/3;
  12220. }
  12221. // If delta is nonzero, handle it.
  12222. // Basically, delta is now positive if wheel was scrolled up,
  12223. // and negative, if wheel was scrolled down.
  12224. if (delta) {
  12225. if (!('mouswheelScale' in this.pinch)) {
  12226. this.pinch.mouswheelScale = 1;
  12227. }
  12228. // calculate the new scale
  12229. var scale = this.pinch.mouswheelScale;
  12230. var zoom = delta / 10;
  12231. if (delta < 0) {
  12232. zoom = zoom / (1 - zoom);
  12233. }
  12234. scale *= (1 + zoom);
  12235. // calculate the pointer location
  12236. var gesture = Hammer.event.collectEventData(this, 'scroll', event);
  12237. var pointer = this._getPointer(gesture.center);
  12238. // apply the new scale
  12239. scale = this._zoom(scale, pointer);
  12240. // store the new, applied scale
  12241. this.pinch.mouswheelScale = scale;
  12242. }
  12243. // Prevent default actions caused by mouse wheel.
  12244. event.preventDefault();
  12245. };
  12246. /**
  12247. * Mouse move handler for checking whether the title moves over a node with a title.
  12248. * @param {Event} event
  12249. * @private
  12250. */
  12251. Graph.prototype._onMouseMoveTitle = function (event) {
  12252. var gesture = Hammer.event.collectEventData(this, 'mousemove', event);
  12253. var pointer = this._getPointer(gesture.center);
  12254. // check if the previously selected node is still selected
  12255. if (this.popupNode) {
  12256. this._checkHidePopup(pointer);
  12257. }
  12258. // start a timeout that will check if the mouse is positioned above
  12259. // an element
  12260. var me = this;
  12261. var checkShow = function() {
  12262. me._checkShowPopup(pointer);
  12263. };
  12264. if (this.popupTimer) {
  12265. clearInterval(this.popupTimer); // stop any running timer
  12266. }
  12267. if (!this.leftButtonDown) {
  12268. this.popupTimer = setTimeout(checkShow, 300);
  12269. }
  12270. };
  12271. /**
  12272. * Check if there is an element on the given position in the graph
  12273. * (a node or edge). If so, and if this element has a title,
  12274. * show a popup window with its title.
  12275. *
  12276. * @param {{x:Number, y:Number}} pointer
  12277. * @private
  12278. */
  12279. Graph.prototype._checkShowPopup = function (pointer) {
  12280. var obj = {
  12281. left: this._canvasToX(pointer.x),
  12282. top: this._canvasToY(pointer.y),
  12283. right: this._canvasToX(pointer.x),
  12284. bottom: this._canvasToY(pointer.y)
  12285. };
  12286. var id;
  12287. var lastPopupNode = this.popupNode;
  12288. if (this.popupNode == undefined) {
  12289. // search the nodes for overlap, select the top one in case of multiple nodes
  12290. var nodes = this.nodes;
  12291. for (id in nodes) {
  12292. if (nodes.hasOwnProperty(id)) {
  12293. var node = nodes[id];
  12294. if (node.getTitle() != undefined && node.isOverlappingWith(obj)) {
  12295. this.popupNode = node;
  12296. break;
  12297. }
  12298. }
  12299. }
  12300. }
  12301. if (this.popupNode == undefined) {
  12302. // search the edges for overlap
  12303. var edges = this.edges;
  12304. for (id in edges) {
  12305. if (edges.hasOwnProperty(id)) {
  12306. var edge = edges[id];
  12307. if (edge.connected && (edge.getTitle() != undefined) &&
  12308. edge.isOverlappingWith(obj)) {
  12309. this.popupNode = edge;
  12310. break;
  12311. }
  12312. }
  12313. }
  12314. }
  12315. if (this.popupNode) {
  12316. // show popup message window
  12317. if (this.popupNode != lastPopupNode) {
  12318. var me = this;
  12319. if (!me.popup) {
  12320. me.popup = new Popup(me.frame);
  12321. }
  12322. // adjust a small offset such that the mouse cursor is located in the
  12323. // bottom left location of the popup, and you can easily move over the
  12324. // popup area
  12325. me.popup.setPosition(pointer.x - 3, pointer.y - 3);
  12326. me.popup.setText(me.popupNode.getTitle());
  12327. me.popup.show();
  12328. }
  12329. }
  12330. else {
  12331. if (this.popup) {
  12332. this.popup.hide();
  12333. }
  12334. }
  12335. };
  12336. /**
  12337. * Check if the popup must be hided, which is the case when the mouse is no
  12338. * longer hovering on the object
  12339. * @param {{x:Number, y:Number}} pointer
  12340. * @private
  12341. */
  12342. Graph.prototype._checkHidePopup = function (pointer) {
  12343. if (!this.popupNode || !this._getNodeAt(pointer) ) {
  12344. this.popupNode = undefined;
  12345. if (this.popup) {
  12346. this.popup.hide();
  12347. }
  12348. }
  12349. };
  12350. /**
  12351. * Unselect selected nodes. If no selection array is provided, all nodes
  12352. * are unselected
  12353. * @param {Object[]} selection Array with selection objects, each selection
  12354. * object has a parameter row. Optional
  12355. * @param {Boolean} triggerSelect If true (default), the select event
  12356. * is triggered when nodes are unselected
  12357. * @return {Boolean} changed True if the selection is changed
  12358. * @private
  12359. */
  12360. Graph.prototype._unselectNodes = function(selection, triggerSelect) {
  12361. var changed = false;
  12362. var i, iMax, id;
  12363. if (selection) {
  12364. // remove provided selections
  12365. for (i = 0, iMax = selection.length; i < iMax; i++) {
  12366. id = selection[i];
  12367. this.nodes[id].unselect();
  12368. var j = 0;
  12369. while (j < this.selection.length) {
  12370. if (this.selection[j] == id) {
  12371. this.selection.splice(j, 1);
  12372. changed = true;
  12373. }
  12374. else {
  12375. j++;
  12376. }
  12377. }
  12378. }
  12379. }
  12380. else if (this.selection && this.selection.length) {
  12381. // remove all selections
  12382. for (i = 0, iMax = this.selection.length; i < iMax; i++) {
  12383. id = this.selection[i];
  12384. this.nodes[id].unselect();
  12385. changed = true;
  12386. }
  12387. this.selection = [];
  12388. }
  12389. if (changed && (triggerSelect == true || triggerSelect == undefined)) {
  12390. // fire the select event
  12391. this._trigger('select');
  12392. }
  12393. return changed;
  12394. };
  12395. /**
  12396. * select all nodes on given location x, y
  12397. * @param {Array} selection an array with node ids
  12398. * @param {boolean} append If true, the new selection will be appended to the
  12399. * current selection (except for duplicate entries)
  12400. * @return {Boolean} changed True if the selection is changed
  12401. * @private
  12402. */
  12403. Graph.prototype._selectNodes = function(selection, append) {
  12404. var changed = false;
  12405. var i, iMax;
  12406. // TODO: the selectNodes method is a little messy, rework this
  12407. // check if the current selection equals the desired selection
  12408. var selectionAlreadyThere = true;
  12409. if (selection.length != this.selection.length) {
  12410. selectionAlreadyThere = false;
  12411. }
  12412. else {
  12413. for (i = 0, iMax = Math.min(selection.length, this.selection.length); i < iMax; i++) {
  12414. if (selection[i] != this.selection[i]) {
  12415. selectionAlreadyThere = false;
  12416. break;
  12417. }
  12418. }
  12419. }
  12420. if (selectionAlreadyThere) {
  12421. return changed;
  12422. }
  12423. if (append == undefined || append == false) {
  12424. // first deselect any selected node
  12425. var triggerSelect = false;
  12426. changed = this._unselectNodes(undefined, triggerSelect);
  12427. }
  12428. for (i = 0, iMax = selection.length; i < iMax; i++) {
  12429. // add each of the new selections, but only when they are not duplicate
  12430. var id = selection[i];
  12431. var isDuplicate = (this.selection.indexOf(id) != -1);
  12432. if (!isDuplicate) {
  12433. this.nodes[id].select();
  12434. this.selection.push(id);
  12435. changed = true;
  12436. }
  12437. }
  12438. if (changed) {
  12439. // fire the select event
  12440. this._trigger('select');
  12441. }
  12442. return changed;
  12443. };
  12444. /**
  12445. * retrieve all nodes overlapping with given object
  12446. * @param {Object} obj An object with parameters left, top, right, bottom
  12447. * @return {Number[]} An array with id's of the overlapping nodes
  12448. * @private
  12449. */
  12450. Graph.prototype._getNodesOverlappingWith = function (obj) {
  12451. var nodes = this.nodes,
  12452. overlappingNodes = [];
  12453. for (var id in nodes) {
  12454. if (nodes.hasOwnProperty(id)) {
  12455. if (nodes[id].isOverlappingWith(obj)) {
  12456. overlappingNodes.push(id);
  12457. }
  12458. }
  12459. }
  12460. return overlappingNodes;
  12461. };
  12462. /**
  12463. * retrieve the currently selected nodes
  12464. * @return {Number[] | String[]} selection An array with the ids of the
  12465. * selected nodes.
  12466. */
  12467. Graph.prototype.getSelection = function() {
  12468. return this.selection.concat([]);
  12469. };
  12470. /**
  12471. * select zero or more nodes
  12472. * @param {Number[] | String[]} selection An array with the ids of the
  12473. * selected nodes.
  12474. */
  12475. Graph.prototype.setSelection = function(selection) {
  12476. var i, iMax, id;
  12477. if (!selection || (selection.length == undefined))
  12478. throw 'Selection must be an array with ids';
  12479. // first unselect any selected node
  12480. for (i = 0, iMax = this.selection.length; i < iMax; i++) {
  12481. id = this.selection[i];
  12482. this.nodes[id].unselect();
  12483. }
  12484. this.selection = [];
  12485. for (i = 0, iMax = selection.length; i < iMax; i++) {
  12486. id = selection[i];
  12487. var node = this.nodes[id];
  12488. if (!node) {
  12489. throw new RangeError('Node with id "' + id + '" not found');
  12490. }
  12491. node.select();
  12492. this.selection.push(id);
  12493. }
  12494. this.redraw();
  12495. };
  12496. /**
  12497. * Validate the selection: remove ids of nodes which no longer exist
  12498. * @private
  12499. */
  12500. Graph.prototype._updateSelection = function () {
  12501. var i = 0;
  12502. while (i < this.selection.length) {
  12503. var id = this.selection[i];
  12504. if (!this.nodes[id]) {
  12505. this.selection.splice(i, 1);
  12506. }
  12507. else {
  12508. i++;
  12509. }
  12510. }
  12511. };
  12512. /**
  12513. * Temporary method to test calculating a hub value for the nodes
  12514. * @param {number} level Maximum number edges between two nodes in order
  12515. * to call them connected. Optional, 1 by default
  12516. * @return {Number[]} connectioncount array with the connection count
  12517. * for each node
  12518. * @private
  12519. */
  12520. Graph.prototype._getConnectionCount = function(level) {
  12521. if (level == undefined) {
  12522. level = 1;
  12523. }
  12524. // get the nodes connected to given nodes
  12525. function getConnectedNodes(nodes) {
  12526. var connectedNodes = [];
  12527. for (var j = 0, jMax = nodes.length; j < jMax; j++) {
  12528. var node = nodes[j];
  12529. // find all nodes connected to this node
  12530. var edges = node.edges;
  12531. for (var i = 0, iMax = edges.length; i < iMax; i++) {
  12532. var edge = edges[i];
  12533. var other = null;
  12534. // check if connected
  12535. if (edge.from == node)
  12536. other = edge.to;
  12537. else if (edge.to == node)
  12538. other = edge.from;
  12539. // check if the other node is not already in the list with nodes
  12540. var k, kMax;
  12541. if (other) {
  12542. for (k = 0, kMax = nodes.length; k < kMax; k++) {
  12543. if (nodes[k] == other) {
  12544. other = null;
  12545. break;
  12546. }
  12547. }
  12548. }
  12549. if (other) {
  12550. for (k = 0, kMax = connectedNodes.length; k < kMax; k++) {
  12551. if (connectedNodes[k] == other) {
  12552. other = null;
  12553. break;
  12554. }
  12555. }
  12556. }
  12557. if (other)
  12558. connectedNodes.push(other);
  12559. }
  12560. }
  12561. return connectedNodes;
  12562. }
  12563. var connections = [];
  12564. var nodes = this.nodes;
  12565. for (var id in nodes) {
  12566. if (nodes.hasOwnProperty(id)) {
  12567. var c = [nodes[id]];
  12568. for (var l = 0; l < level; l++) {
  12569. c = c.concat(getConnectedNodes(c));
  12570. }
  12571. connections.push(c);
  12572. }
  12573. }
  12574. var hubs = [];
  12575. for (var i = 0, len = connections.length; i < len; i++) {
  12576. hubs.push(connections[i].length);
  12577. }
  12578. return hubs;
  12579. };
  12580. /**
  12581. * Set a new size for the graph
  12582. * @param {string} width Width in pixels or percentage (for example '800px'
  12583. * or '50%')
  12584. * @param {string} height Height in pixels or percentage (for example '400px'
  12585. * or '30%')
  12586. */
  12587. Graph.prototype.setSize = function(width, height) {
  12588. this.frame.style.width = width;
  12589. this.frame.style.height = height;
  12590. this.frame.canvas.style.width = '100%';
  12591. this.frame.canvas.style.height = '100%';
  12592. this.frame.canvas.width = this.frame.canvas.clientWidth;
  12593. this.frame.canvas.height = this.frame.canvas.clientHeight;
  12594. };
  12595. /**
  12596. * Set a data set with nodes for the graph
  12597. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  12598. * @private
  12599. */
  12600. Graph.prototype._setNodes = function(nodes) {
  12601. var oldNodesData = this.nodesData;
  12602. if (nodes instanceof DataSet || nodes instanceof DataView) {
  12603. this.nodesData = nodes;
  12604. }
  12605. else if (nodes instanceof Array) {
  12606. this.nodesData = new DataSet();
  12607. this.nodesData.add(nodes);
  12608. }
  12609. else if (!nodes) {
  12610. this.nodesData = new DataSet();
  12611. }
  12612. else {
  12613. throw new TypeError('Array or DataSet expected');
  12614. }
  12615. if (oldNodesData) {
  12616. // unsubscribe from old dataset
  12617. util.forEach(this.nodesListeners, function (callback, event) {
  12618. oldNodesData.unsubscribe(event, callback);
  12619. });
  12620. }
  12621. // remove drawn nodes
  12622. this.nodes = {};
  12623. if (this.nodesData) {
  12624. // subscribe to new dataset
  12625. var me = this;
  12626. util.forEach(this.nodesListeners, function (callback, event) {
  12627. me.nodesData.subscribe(event, callback);
  12628. });
  12629. // draw all new nodes
  12630. var ids = this.nodesData.getIds();
  12631. this._addNodes(ids);
  12632. }
  12633. this._updateSelection();
  12634. };
  12635. /**
  12636. * Add nodes
  12637. * @param {Number[] | String[]} ids
  12638. * @private
  12639. */
  12640. Graph.prototype._addNodes = function(ids) {
  12641. var id;
  12642. for (var i = 0, len = ids.length; i < len; i++) {
  12643. id = ids[i];
  12644. var data = this.nodesData.get(id);
  12645. var node = new Node(data, this.images, this.groups, this.constants);
  12646. this.nodes[id] = node; // note: this may replace an existing node
  12647. if (!node.isFixed()) {
  12648. // TODO: position new nodes in a smarter way!
  12649. var radius = this.constants.edges.length * 2;
  12650. var count = ids.length;
  12651. var angle = 2 * Math.PI * (i / count);
  12652. node.x = radius * Math.cos(angle);
  12653. node.y = radius * Math.sin(angle);
  12654. // note: no not use node.isMoving() here, as that gives the current
  12655. // velocity of the node, which is zero after creation of the node.
  12656. this.moving = true;
  12657. }
  12658. }
  12659. this._reconnectEdges();
  12660. this._updateValueRange(this.nodes);
  12661. };
  12662. /**
  12663. * Update existing nodes, or create them when not yet existing
  12664. * @param {Number[] | String[]} ids
  12665. * @private
  12666. */
  12667. Graph.prototype._updateNodes = function(ids) {
  12668. var nodes = this.nodes,
  12669. nodesData = this.nodesData;
  12670. for (var i = 0, len = ids.length; i < len; i++) {
  12671. var id = ids[i];
  12672. var node = nodes[id];
  12673. var data = nodesData.get(id);
  12674. if (node) {
  12675. // update node
  12676. node.setProperties(data, this.constants);
  12677. }
  12678. else {
  12679. // create node
  12680. node = new Node(properties, this.images, this.groups, this.constants);
  12681. nodes[id] = node;
  12682. if (!node.isFixed()) {
  12683. this.moving = true;
  12684. }
  12685. }
  12686. }
  12687. this._reconnectEdges();
  12688. this._updateValueRange(nodes);
  12689. };
  12690. /**
  12691. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  12692. * @param {Number[] | String[]} ids
  12693. * @private
  12694. */
  12695. Graph.prototype._removeNodes = function(ids) {
  12696. var nodes = this.nodes;
  12697. for (var i = 0, len = ids.length; i < len; i++) {
  12698. var id = ids[i];
  12699. delete nodes[id];
  12700. }
  12701. this._reconnectEdges();
  12702. this._updateSelection();
  12703. this._updateValueRange(nodes);
  12704. };
  12705. /**
  12706. * Load edges by reading the data table
  12707. * @param {Array | DataSet | DataView} edges The data containing the edges.
  12708. * @private
  12709. * @private
  12710. */
  12711. Graph.prototype._setEdges = function(edges) {
  12712. var oldEdgesData = this.edgesData;
  12713. if (edges instanceof DataSet || edges instanceof DataView) {
  12714. this.edgesData = edges;
  12715. }
  12716. else if (edges instanceof Array) {
  12717. this.edgesData = new DataSet();
  12718. this.edgesData.add(edges);
  12719. }
  12720. else if (!edges) {
  12721. this.edgesData = new DataSet();
  12722. }
  12723. else {
  12724. throw new TypeError('Array or DataSet expected');
  12725. }
  12726. if (oldEdgesData) {
  12727. // unsubscribe from old dataset
  12728. util.forEach(this.edgesListeners, function (callback, event) {
  12729. oldEdgesData.unsubscribe(event, callback);
  12730. });
  12731. }
  12732. // remove drawn edges
  12733. this.edges = {};
  12734. if (this.edgesData) {
  12735. // subscribe to new dataset
  12736. var me = this;
  12737. util.forEach(this.edgesListeners, function (callback, event) {
  12738. me.edgesData.subscribe(event, callback);
  12739. });
  12740. // draw all new nodes
  12741. var ids = this.edgesData.getIds();
  12742. this._addEdges(ids);
  12743. }
  12744. this._reconnectEdges();
  12745. };
  12746. /**
  12747. * Add edges
  12748. * @param {Number[] | String[]} ids
  12749. * @private
  12750. */
  12751. Graph.prototype._addEdges = function (ids) {
  12752. var edges = this.edges,
  12753. edgesData = this.edgesData;
  12754. for (var i = 0, len = ids.length; i < len; i++) {
  12755. var id = ids[i];
  12756. var oldEdge = edges[id];
  12757. if (oldEdge) {
  12758. oldEdge.disconnect();
  12759. }
  12760. var data = edgesData.get(id);
  12761. edges[id] = new Edge(data, this, this.constants);
  12762. }
  12763. this.moving = true;
  12764. this._updateValueRange(edges);
  12765. };
  12766. /**
  12767. * Update existing edges, or create them when not yet existing
  12768. * @param {Number[] | String[]} ids
  12769. * @private
  12770. */
  12771. Graph.prototype._updateEdges = function (ids) {
  12772. var edges = this.edges,
  12773. edgesData = this.edgesData;
  12774. for (var i = 0, len = ids.length; i < len; i++) {
  12775. var id = ids[i];
  12776. var data = edgesData.get(id);
  12777. var edge = edges[id];
  12778. if (edge) {
  12779. // update edge
  12780. edge.disconnect();
  12781. edge.setProperties(data, this.constants);
  12782. edge.connect();
  12783. }
  12784. else {
  12785. // create edge
  12786. edge = new Edge(data, this, this.constants);
  12787. this.edges[id] = edge;
  12788. }
  12789. }
  12790. this.moving = true;
  12791. this._updateValueRange(edges);
  12792. };
  12793. /**
  12794. * Remove existing edges. Non existing ids will be ignored
  12795. * @param {Number[] | String[]} ids
  12796. * @private
  12797. */
  12798. Graph.prototype._removeEdges = function (ids) {
  12799. var edges = this.edges;
  12800. for (var i = 0, len = ids.length; i < len; i++) {
  12801. var id = ids[i];
  12802. var edge = edges[id];
  12803. if (edge) {
  12804. edge.disconnect();
  12805. delete edges[id];
  12806. }
  12807. }
  12808. this.moving = true;
  12809. this._updateValueRange(edges);
  12810. };
  12811. /**
  12812. * Reconnect all edges
  12813. * @private
  12814. */
  12815. Graph.prototype._reconnectEdges = function() {
  12816. var id,
  12817. nodes = this.nodes,
  12818. edges = this.edges;
  12819. for (id in nodes) {
  12820. if (nodes.hasOwnProperty(id)) {
  12821. nodes[id].edges = [];
  12822. }
  12823. }
  12824. for (id in edges) {
  12825. if (edges.hasOwnProperty(id)) {
  12826. var edge = edges[id];
  12827. edge.from = null;
  12828. edge.to = null;
  12829. edge.connect();
  12830. }
  12831. }
  12832. };
  12833. /**
  12834. * Update the values of all object in the given array according to the current
  12835. * value range of the objects in the array.
  12836. * @param {Object} obj An object containing a set of Edges or Nodes
  12837. * The objects must have a method getValue() and
  12838. * setValueRange(min, max).
  12839. * @private
  12840. */
  12841. Graph.prototype._updateValueRange = function(obj) {
  12842. var id;
  12843. // determine the range of the objects
  12844. var valueMin = undefined;
  12845. var valueMax = undefined;
  12846. for (id in obj) {
  12847. if (obj.hasOwnProperty(id)) {
  12848. var value = obj[id].getValue();
  12849. if (value !== undefined) {
  12850. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  12851. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  12852. }
  12853. }
  12854. }
  12855. // adjust the range of all objects
  12856. if (valueMin !== undefined && valueMax !== undefined) {
  12857. for (id in obj) {
  12858. if (obj.hasOwnProperty(id)) {
  12859. obj[id].setValueRange(valueMin, valueMax);
  12860. }
  12861. }
  12862. }
  12863. };
  12864. /**
  12865. * Redraw the graph with the current data
  12866. * chart will be resized too.
  12867. */
  12868. Graph.prototype.redraw = function() {
  12869. this.setSize(this.width, this.height);
  12870. this._redraw();
  12871. };
  12872. /**
  12873. * Redraw the graph with the current data
  12874. * @private
  12875. */
  12876. Graph.prototype._redraw = function() {
  12877. var ctx = this.frame.canvas.getContext('2d');
  12878. // clear the canvas
  12879. var w = this.frame.canvas.width;
  12880. var h = this.frame.canvas.height;
  12881. ctx.clearRect(0, 0, w, h);
  12882. // set scaling and translation
  12883. ctx.save();
  12884. ctx.translate(this.translation.x, this.translation.y);
  12885. ctx.scale(this.scale, this.scale);
  12886. this._drawEdges(ctx);
  12887. this._drawNodes(ctx);
  12888. // restore original scaling and translation
  12889. ctx.restore();
  12890. };
  12891. /**
  12892. * Set the translation of the graph
  12893. * @param {Number} offsetX Horizontal offset
  12894. * @param {Number} offsetY Vertical offset
  12895. * @private
  12896. */
  12897. Graph.prototype._setTranslation = function(offsetX, offsetY) {
  12898. if (this.translation === undefined) {
  12899. this.translation = {
  12900. x: 0,
  12901. y: 0
  12902. };
  12903. }
  12904. if (offsetX !== undefined) {
  12905. this.translation.x = offsetX;
  12906. }
  12907. if (offsetY !== undefined) {
  12908. this.translation.y = offsetY;
  12909. }
  12910. };
  12911. /**
  12912. * Get the translation of the graph
  12913. * @return {Object} translation An object with parameters x and y, both a number
  12914. * @private
  12915. */
  12916. Graph.prototype._getTranslation = function() {
  12917. return {
  12918. x: this.translation.x,
  12919. y: this.translation.y
  12920. };
  12921. };
  12922. /**
  12923. * Scale the graph
  12924. * @param {Number} scale Scaling factor 1.0 is unscaled
  12925. * @private
  12926. */
  12927. Graph.prototype._setScale = function(scale) {
  12928. this.scale = scale;
  12929. };
  12930. /**
  12931. * Get the current scale of the graph
  12932. * @return {Number} scale Scaling factor 1.0 is unscaled
  12933. * @private
  12934. */
  12935. Graph.prototype._getScale = function() {
  12936. return this.scale;
  12937. };
  12938. /**
  12939. * Convert a horizontal point on the HTML canvas to the x-value of the model
  12940. * @param {number} x
  12941. * @returns {number}
  12942. * @private
  12943. */
  12944. Graph.prototype._canvasToX = function(x) {
  12945. return (x - this.translation.x) / this.scale;
  12946. };
  12947. /**
  12948. * Convert an x-value in the model to a horizontal point on the HTML canvas
  12949. * @param {number} x
  12950. * @returns {number}
  12951. * @private
  12952. */
  12953. Graph.prototype._xToCanvas = function(x) {
  12954. return x * this.scale + this.translation.x;
  12955. };
  12956. /**
  12957. * Convert a vertical point on the HTML canvas to the y-value of the model
  12958. * @param {number} y
  12959. * @returns {number}
  12960. * @private
  12961. */
  12962. Graph.prototype._canvasToY = function(y) {
  12963. return (y - this.translation.y) / this.scale;
  12964. };
  12965. /**
  12966. * Convert an y-value in the model to a vertical point on the HTML canvas
  12967. * @param {number} y
  12968. * @returns {number}
  12969. * @private
  12970. */
  12971. Graph.prototype._yToCanvas = function(y) {
  12972. return y * this.scale + this.translation.y ;
  12973. };
  12974. /**
  12975. * Redraw all nodes
  12976. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  12977. * @param {CanvasRenderingContext2D} ctx
  12978. * @private
  12979. */
  12980. Graph.prototype._drawNodes = function(ctx) {
  12981. // first draw the unselected nodes
  12982. var nodes = this.nodes;
  12983. var selected = [];
  12984. for (var id in nodes) {
  12985. if (nodes.hasOwnProperty(id)) {
  12986. if (nodes[id].isSelected()) {
  12987. selected.push(id);
  12988. }
  12989. else {
  12990. nodes[id].draw(ctx);
  12991. }
  12992. }
  12993. }
  12994. // draw the selected nodes on top
  12995. for (var s = 0, sMax = selected.length; s < sMax; s++) {
  12996. nodes[selected[s]].draw(ctx);
  12997. }
  12998. };
  12999. /**
  13000. * Redraw all edges
  13001. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  13002. * @param {CanvasRenderingContext2D} ctx
  13003. * @private
  13004. */
  13005. Graph.prototype._drawEdges = function(ctx) {
  13006. var edges = this.edges;
  13007. for (var id in edges) {
  13008. if (edges.hasOwnProperty(id)) {
  13009. var edge = edges[id];
  13010. if (edge.connected) {
  13011. edges[id].draw(ctx);
  13012. }
  13013. }
  13014. }
  13015. };
  13016. /**
  13017. * Find a stable position for all nodes
  13018. * @private
  13019. */
  13020. Graph.prototype._doStabilize = function() {
  13021. var start = new Date();
  13022. // find stable position
  13023. var count = 0;
  13024. var vmin = this.constants.minVelocity;
  13025. var stable = false;
  13026. while (!stable && count < this.constants.maxIterations) {
  13027. this._calculateForces();
  13028. this._discreteStepNodes();
  13029. stable = !this._isMoving(vmin);
  13030. count++;
  13031. }
  13032. var end = new Date();
  13033. // console.log('Stabilized in ' + (end-start) + ' ms, ' + count + ' iterations' ); // TODO: cleanup
  13034. };
  13035. /**
  13036. * Calculate the external forces acting on the nodes
  13037. * Forces are caused by: edges, repulsing forces between nodes, gravity
  13038. * @private
  13039. */
  13040. Graph.prototype._calculateForces = function() {
  13041. // create a local edge to the nodes and edges, that is faster
  13042. var id, dx, dy, angle, distance, fx, fy,
  13043. repulsingForce, springForce, length, edgeLength,
  13044. nodes = this.nodes,
  13045. edges = this.edges;
  13046. // gravity, add a small constant force to pull the nodes towards the center of
  13047. // the graph
  13048. // Also, the forces are reset to zero in this loop by using _setForce instead
  13049. // of _addForce
  13050. var gravity = 0.01,
  13051. gx = this.frame.canvas.clientWidth / 2,
  13052. gy = this.frame.canvas.clientHeight / 2;
  13053. for (id in nodes) {
  13054. if (nodes.hasOwnProperty(id)) {
  13055. var node = nodes[id];
  13056. dx = gx - node.x;
  13057. dy = gy - node.y;
  13058. angle = Math.atan2(dy, dx);
  13059. fx = Math.cos(angle) * gravity;
  13060. fy = Math.sin(angle) * gravity;
  13061. node._setForce(fx, fy);
  13062. }
  13063. }
  13064. // repulsing forces between nodes
  13065. var minimumDistance = this.constants.nodes.distance,
  13066. steepness = 10; // higher value gives steeper slope of the force around the given minimumDistance
  13067. for (var id1 in nodes) {
  13068. if (nodes.hasOwnProperty(id1)) {
  13069. var node1 = nodes[id1];
  13070. for (var id2 in nodes) {
  13071. if (nodes.hasOwnProperty(id2)) {
  13072. var node2 = nodes[id2];
  13073. // calculate normally distributed force
  13074. dx = node2.x - node1.x;
  13075. dy = node2.y - node1.y;
  13076. distance = Math.sqrt(dx * dx + dy * dy);
  13077. angle = Math.atan2(dy, dx);
  13078. // TODO: correct factor for repulsing force
  13079. //repulsingForce = 2 * Math.exp(-5 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  13080. //repulsingForce = Math.exp(-1 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  13081. repulsingForce = 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness)); // TODO: customize the repulsing force
  13082. fx = Math.cos(angle) * repulsingForce;
  13083. fy = Math.sin(angle) * repulsingForce;
  13084. node1._addForce(-fx, -fy);
  13085. node2._addForce(fx, fy);
  13086. }
  13087. }
  13088. }
  13089. }
  13090. /* TODO: re-implement repulsion of edges
  13091. for (var n = 0; n < nodes.length; n++) {
  13092. for (var l = 0; l < edges.length; l++) {
  13093. var lx = edges[l].from.x+(edges[l].to.x - edges[l].from.x)/2,
  13094. ly = edges[l].from.y+(edges[l].to.y - edges[l].from.y)/2,
  13095. // calculate normally distributed force
  13096. dx = nodes[n].x - lx,
  13097. dy = nodes[n].y - ly,
  13098. distance = Math.sqrt(dx * dx + dy * dy),
  13099. angle = Math.atan2(dy, dx),
  13100. // TODO: correct factor for repulsing force
  13101. //var repulsingforce = 2 * Math.exp(-5 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  13102. //repulsingforce = Math.exp(-1 * (distance * distance) / (dmin * dmin) ), // TODO: customize the repulsing force
  13103. repulsingforce = 1 / (1 + Math.exp((distance / (minimumDistance / 2) - 1) * steepness)), // TODO: customize the repulsing force
  13104. fx = Math.cos(angle) * repulsingforce,
  13105. fy = Math.sin(angle) * repulsingforce;
  13106. nodes[n]._addForce(fx, fy);
  13107. edges[l].from._addForce(-fx/2,-fy/2);
  13108. edges[l].to._addForce(-fx/2,-fy/2);
  13109. }
  13110. }
  13111. */
  13112. // forces caused by the edges, modelled as springs
  13113. for (id in edges) {
  13114. if (edges.hasOwnProperty(id)) {
  13115. var edge = edges[id];
  13116. if (edge.connected) {
  13117. dx = (edge.to.x - edge.from.x);
  13118. dy = (edge.to.y - edge.from.y);
  13119. //edgeLength = (edge.from.width + edge.from.height + edge.to.width + edge.to.height)/2 || edge.length; // TODO: dmin
  13120. //edgeLength = (edge.from.width + edge.to.width)/2 || edge.length; // TODO: dmin
  13121. //edgeLength = 20 + ((edge.from.width + edge.to.width) || 0) / 2;
  13122. edgeLength = edge.length;
  13123. length = Math.sqrt(dx * dx + dy * dy);
  13124. angle = Math.atan2(dy, dx);
  13125. springForce = edge.stiffness * (edgeLength - length);
  13126. fx = Math.cos(angle) * springForce;
  13127. fy = Math.sin(angle) * springForce;
  13128. edge.from._addForce(-fx, -fy);
  13129. edge.to._addForce(fx, fy);
  13130. }
  13131. }
  13132. }
  13133. /* TODO: re-implement repulsion of edges
  13134. // repulsing forces between edges
  13135. var minimumDistance = this.constants.edges.distance,
  13136. steepness = 10; // higher value gives steeper slope of the force around the given minimumDistance
  13137. for (var l = 0; l < edges.length; l++) {
  13138. //Keep distance from other edge centers
  13139. for (var l2 = l + 1; l2 < this.edges.length; l2++) {
  13140. //var dmin = (nodes[n].width + nodes[n].height + nodes[n2].width + nodes[n2].height) / 1 || minimumDistance, // TODO: dmin
  13141. //var dmin = (nodes[n].width + nodes[n2].width)/2 || minimumDistance, // TODO: dmin
  13142. //dmin = 40 + ((nodes[n].width/2 + nodes[n2].width/2) || 0),
  13143. var lx = edges[l].from.x+(edges[l].to.x - edges[l].from.x)/2,
  13144. ly = edges[l].from.y+(edges[l].to.y - edges[l].from.y)/2,
  13145. l2x = edges[l2].from.x+(edges[l2].to.x - edges[l2].from.x)/2,
  13146. l2y = edges[l2].from.y+(edges[l2].to.y - edges[l2].from.y)/2,
  13147. // calculate normally distributed force
  13148. dx = l2x - lx,
  13149. dy = l2y - ly,
  13150. distance = Math.sqrt(dx * dx + dy * dy),
  13151. angle = Math.atan2(dy, dx),
  13152. // TODO: correct factor for repulsing force
  13153. //var repulsingforce = 2 * Math.exp(-5 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  13154. //repulsingforce = Math.exp(-1 * (distance * distance) / (dmin * dmin) ), // TODO: customize the repulsing force
  13155. repulsingforce = 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness)), // TODO: customize the repulsing force
  13156. fx = Math.cos(angle) * repulsingforce,
  13157. fy = Math.sin(angle) * repulsingforce;
  13158. edges[l].from._addForce(-fx, -fy);
  13159. edges[l].to._addForce(-fx, -fy);
  13160. edges[l2].from._addForce(fx, fy);
  13161. edges[l2].to._addForce(fx, fy);
  13162. }
  13163. }
  13164. */
  13165. };
  13166. /**
  13167. * Check if any of the nodes is still moving
  13168. * @param {number} vmin the minimum velocity considered as 'moving'
  13169. * @return {boolean} true if moving, false if non of the nodes is moving
  13170. * @private
  13171. */
  13172. Graph.prototype._isMoving = function(vmin) {
  13173. // TODO: ismoving does not work well: should check the kinetic energy, not its velocity
  13174. var nodes = this.nodes;
  13175. for (var id in nodes) {
  13176. if (nodes.hasOwnProperty(id) && nodes[id].isMoving(vmin)) {
  13177. return true;
  13178. }
  13179. }
  13180. return false;
  13181. };
  13182. /**
  13183. * Perform one discrete step for all nodes
  13184. * @private
  13185. */
  13186. Graph.prototype._discreteStepNodes = function() {
  13187. var interval = this.refreshRate / 1000.0; // in seconds
  13188. var nodes = this.nodes;
  13189. for (var id in nodes) {
  13190. if (nodes.hasOwnProperty(id)) {
  13191. nodes[id].discreteStep(interval);
  13192. }
  13193. }
  13194. };
  13195. /**
  13196. * Start animating nodes and edges
  13197. */
  13198. Graph.prototype.start = function() {
  13199. if (this.moving) {
  13200. this._calculateForces();
  13201. this._discreteStepNodes();
  13202. var vmin = this.constants.minVelocity;
  13203. this.moving = this._isMoving(vmin);
  13204. }
  13205. if (this.moving) {
  13206. // start animation. only start timer if it is not already running
  13207. if (!this.timer) {
  13208. var graph = this;
  13209. this.timer = window.setTimeout(function () {
  13210. graph.timer = undefined;
  13211. graph.start();
  13212. graph._redraw();
  13213. }, this.refreshRate);
  13214. }
  13215. }
  13216. else {
  13217. this._redraw();
  13218. }
  13219. };
  13220. /**
  13221. * Stop animating nodes and edges.
  13222. */
  13223. Graph.prototype.stop = function () {
  13224. if (this.timer) {
  13225. window.clearInterval(this.timer);
  13226. this.timer = undefined;
  13227. }
  13228. };
  13229. /**
  13230. * vis.js module exports
  13231. */
  13232. var vis = {
  13233. util: util,
  13234. events: events,
  13235. Controller: Controller,
  13236. DataSet: DataSet,
  13237. DataView: DataView,
  13238. Range: Range,
  13239. Stack: Stack,
  13240. TimeStep: TimeStep,
  13241. EventBus: EventBus,
  13242. components: {
  13243. items: {
  13244. Item: Item,
  13245. ItemBox: ItemBox,
  13246. ItemPoint: ItemPoint,
  13247. ItemRange: ItemRange
  13248. },
  13249. Component: Component,
  13250. Panel: Panel,
  13251. RootPanel: RootPanel,
  13252. ItemSet: ItemSet,
  13253. TimeAxis: TimeAxis
  13254. },
  13255. graph: {
  13256. Node: Node,
  13257. Edge: Edge,
  13258. Popup: Popup,
  13259. Groups: Groups,
  13260. Images: Images
  13261. },
  13262. Timeline: Timeline,
  13263. Graph: Graph
  13264. };
  13265. /**
  13266. * CommonJS module exports
  13267. */
  13268. if (typeof exports !== 'undefined') {
  13269. exports = vis;
  13270. }
  13271. if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  13272. module.exports = vis;
  13273. }
  13274. /**
  13275. * AMD module exports
  13276. */
  13277. if (typeof(define) === 'function') {
  13278. define(function () {
  13279. return vis;
  13280. });
  13281. }
  13282. /**
  13283. * Window exports
  13284. */
  13285. if (typeof window !== 'undefined') {
  13286. // attach the module to the window, load as a regular javascript file
  13287. window['vis'] = vis;
  13288. }
  13289. // inject css
  13290. 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-set {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n\n overflow: hidden;\n\n border-top: none;\n border-bottom: 1px solid #bfbfbf;\n}\n\n.vis.timeline .labels .label-set .label {\n position: absolute;\n left: 0;\n top: 0;\n width: 100%;\n color: #4d4d4d;\n}\n\n.vis.timeline.top .labels .label-set .label,\n.vis.timeline.top .groupset .itemset-axis {\n border-top: 1px solid #bfbfbf;\n border-bottom: none;\n}\n\n.vis.timeline.bottom .labels .label-set .label,\n.vis.timeline.bottom .groupset .itemset-axis {\n border-top: none;\n border-bottom: 1px solid #bfbfbf;\n}\n\n.vis.timeline .labels .label-set .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\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.rangeoverflow {\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, .vis.timeline .item.rangeoverflow .drag-left {\n cursor: w-resize;\n z-index: 1000;\n}\n\n.vis.timeline .item.range .drag-right, .vis.timeline .item.rangeoverflow .drag-right {\n cursor: e-resize;\n z-index: 1000;\n}\n\n.vis.timeline .item.range .content, .vis.timeline .item.rangeoverflow .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:
  13291. },{"hammerjs":1,"moment":2}]},{},[3])
  13292. (3)
  13293. });
  13294. ;