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.

17571 lines
500 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
  1. /**
  2. * vis.js
  3. * https://github.com/almende/vis
  4. *
  5. * A dynamic, browser-based visualization library.
  6. *
  7. * @version @@version
  8. * @date @@date
  9. *
  10. * @license
  11. * Copyright (C) 2011-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("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.vis=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  26. /*! Hammer.JS - v1.0.5 - 2013-04-07
  27. * http://eightmedia.github.com/hammer.js
  28. *
  29. * Copyright (c) 2013 Jorik Tangelder <j.tangelder@gmail.com>;
  30. * Licensed under the MIT license */
  31. (function(window, undefined) {
  32. 'use strict';
  33. /**
  34. * Hammer
  35. * use this to create instances
  36. * @param {HTMLElement} element
  37. * @param {Object} options
  38. * @returns {Hammer.Instance}
  39. * @constructor
  40. */
  41. var Hammer = function(element, options) {
  42. return new Hammer.Instance(element, options || {});
  43. };
  44. // default settings
  45. Hammer.defaults = {
  46. // add styles and attributes to the element to prevent the browser from doing
  47. // its native behavior. this doesnt prevent the scrolling, but cancels
  48. // the contextmenu, tap highlighting etc
  49. // set to false to disable this
  50. stop_browser_behavior: {
  51. // this also triggers onselectstart=false for IE
  52. userSelect: 'none',
  53. // this makes the element blocking in IE10 >, you could experiment with the value
  54. // see for more options this issue; https://github.com/EightMedia/hammer.js/issues/241
  55. touchAction: 'none',
  56. touchCallout: 'none',
  57. contentZooming: 'none',
  58. userDrag: 'none',
  59. tapHighlightColor: 'rgba(0,0,0,0)'
  60. }
  61. // more settings are defined per gesture at gestures.js
  62. };
  63. // detect touchevents
  64. Hammer.HAS_POINTEREVENTS = navigator.pointerEnabled || navigator.msPointerEnabled;
  65. Hammer.HAS_TOUCHEVENTS = ('ontouchstart' in window);
  66. // dont use mouseevents on mobile devices
  67. Hammer.MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;
  68. Hammer.NO_MOUSEEVENTS = Hammer.HAS_TOUCHEVENTS && navigator.userAgent.match(Hammer.MOBILE_REGEX);
  69. // eventtypes per touchevent (start, move, end)
  70. // are filled by Hammer.event.determineEventTypes on setup
  71. Hammer.EVENT_TYPES = {};
  72. // direction defines
  73. Hammer.DIRECTION_DOWN = 'down';
  74. Hammer.DIRECTION_LEFT = 'left';
  75. Hammer.DIRECTION_UP = 'up';
  76. Hammer.DIRECTION_RIGHT = 'right';
  77. // pointer type
  78. Hammer.POINTER_MOUSE = 'mouse';
  79. Hammer.POINTER_TOUCH = 'touch';
  80. Hammer.POINTER_PEN = 'pen';
  81. // touch event defines
  82. Hammer.EVENT_START = 'start';
  83. Hammer.EVENT_MOVE = 'move';
  84. Hammer.EVENT_END = 'end';
  85. // hammer document where the base events are added at
  86. Hammer.DOCUMENT = document;
  87. // plugins namespace
  88. Hammer.plugins = {};
  89. // if the window events are set...
  90. Hammer.READY = false;
  91. /**
  92. * setup events to detect gestures on the document
  93. */
  94. function setup() {
  95. if(Hammer.READY) {
  96. return;
  97. }
  98. // find what eventtypes we add listeners to
  99. Hammer.event.determineEventTypes();
  100. // Register all gestures inside Hammer.gestures
  101. for(var name in Hammer.gestures) {
  102. if(Hammer.gestures.hasOwnProperty(name)) {
  103. Hammer.detection.register(Hammer.gestures[name]);
  104. }
  105. }
  106. // Add touch events on the document
  107. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_MOVE, Hammer.detection.detect);
  108. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_END, Hammer.detection.detect);
  109. // Hammer is ready...!
  110. Hammer.READY = true;
  111. }
  112. /**
  113. * create new hammer instance
  114. * all methods should return the instance itself, so it is chainable.
  115. * @param {HTMLElement} element
  116. * @param {Object} [options={}]
  117. * @returns {Hammer.Instance}
  118. * @constructor
  119. */
  120. Hammer.Instance = function(element, options) {
  121. var self = this;
  122. // setup HammerJS window events and register all gestures
  123. // this also sets up the default options
  124. setup();
  125. this.element = element;
  126. // start/stop detection option
  127. this.enabled = true;
  128. // merge options
  129. this.options = Hammer.utils.extend(
  130. Hammer.utils.extend({}, Hammer.defaults),
  131. options || {});
  132. // add some css to the element to prevent the browser from doing its native behavoir
  133. if(this.options.stop_browser_behavior) {
  134. Hammer.utils.stopDefaultBrowserBehavior(this.element, this.options.stop_browser_behavior);
  135. }
  136. // start detection on touchstart
  137. Hammer.event.onTouch(element, Hammer.EVENT_START, function(ev) {
  138. if(self.enabled) {
  139. Hammer.detection.startDetect(self, ev);
  140. }
  141. });
  142. // return instance
  143. return this;
  144. };
  145. Hammer.Instance.prototype = {
  146. /**
  147. * bind events to the instance
  148. * @param {String} gesture
  149. * @param {Function} handler
  150. * @returns {Hammer.Instance}
  151. */
  152. on: function onEvent(gesture, handler){
  153. var gestures = gesture.split(' ');
  154. for(var t=0; t<gestures.length; t++) {
  155. this.element.addEventListener(gestures[t], handler, false);
  156. }
  157. return this;
  158. },
  159. /**
  160. * unbind events to the instance
  161. * @param {String} gesture
  162. * @param {Function} handler
  163. * @returns {Hammer.Instance}
  164. */
  165. off: function offEvent(gesture, handler){
  166. var gestures = gesture.split(' ');
  167. for(var t=0; t<gestures.length; t++) {
  168. this.element.removeEventListener(gestures[t], handler, false);
  169. }
  170. return this;
  171. },
  172. /**
  173. * trigger gesture event
  174. * @param {String} gesture
  175. * @param {Object} eventData
  176. * @returns {Hammer.Instance}
  177. */
  178. trigger: function triggerEvent(gesture, eventData){
  179. // create DOM event
  180. var event = Hammer.DOCUMENT.createEvent('Event');
  181. event.initEvent(gesture, true, true);
  182. event.gesture = eventData;
  183. // trigger on the target if it is in the instance element,
  184. // this is for event delegation tricks
  185. var element = this.element;
  186. if(Hammer.utils.hasParent(eventData.target, element)) {
  187. element = eventData.target;
  188. }
  189. element.dispatchEvent(event);
  190. return this;
  191. },
  192. /**
  193. * enable of disable hammer.js detection
  194. * @param {Boolean} state
  195. * @returns {Hammer.Instance}
  196. */
  197. enable: function enable(state) {
  198. this.enabled = state;
  199. return this;
  200. }
  201. };
  202. /**
  203. * this holds the last move event,
  204. * used to fix empty touchend issue
  205. * see the onTouch event for an explanation
  206. * @type {Object}
  207. */
  208. var last_move_event = null;
  209. /**
  210. * when the mouse is hold down, this is true
  211. * @type {Boolean}
  212. */
  213. var enable_detect = false;
  214. /**
  215. * when touch events have been fired, this is true
  216. * @type {Boolean}
  217. */
  218. var touch_triggered = false;
  219. Hammer.event = {
  220. /**
  221. * simple addEventListener
  222. * @param {HTMLElement} element
  223. * @param {String} type
  224. * @param {Function} handler
  225. */
  226. bindDom: function(element, type, handler) {
  227. var types = type.split(' ');
  228. for(var t=0; t<types.length; t++) {
  229. element.addEventListener(types[t], handler, false);
  230. }
  231. },
  232. /**
  233. * touch events with mouse fallback
  234. * @param {HTMLElement} element
  235. * @param {String} eventType like Hammer.EVENT_MOVE
  236. * @param {Function} handler
  237. */
  238. onTouch: function onTouch(element, eventType, handler) {
  239. var self = this;
  240. this.bindDom(element, Hammer.EVENT_TYPES[eventType], function bindDomOnTouch(ev) {
  241. var sourceEventType = ev.type.toLowerCase();
  242. // onmouseup, but when touchend has been fired we do nothing.
  243. // this is for touchdevices which also fire a mouseup on touchend
  244. if(sourceEventType.match(/mouse/) && touch_triggered) {
  245. return;
  246. }
  247. // mousebutton must be down or a touch event
  248. else if( sourceEventType.match(/touch/) || // touch events are always on screen
  249. sourceEventType.match(/pointerdown/) || // pointerevents touch
  250. (sourceEventType.match(/mouse/) && ev.which === 1) // mouse is pressed
  251. ){
  252. enable_detect = true;
  253. }
  254. // we are in a touch event, set the touch triggered bool to true,
  255. // this for the conflicts that may occur on ios and android
  256. if(sourceEventType.match(/touch|pointer/)) {
  257. touch_triggered = true;
  258. }
  259. // count the total touches on the screen
  260. var count_touches = 0;
  261. // when touch has been triggered in this detection session
  262. // and we are now handling a mouse event, we stop that to prevent conflicts
  263. if(enable_detect) {
  264. // update pointerevent
  265. if(Hammer.HAS_POINTEREVENTS && eventType != Hammer.EVENT_END) {
  266. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  267. }
  268. // touch
  269. else if(sourceEventType.match(/touch/)) {
  270. count_touches = ev.touches.length;
  271. }
  272. // mouse
  273. else if(!touch_triggered) {
  274. count_touches = sourceEventType.match(/up/) ? 0 : 1;
  275. }
  276. // if we are in a end event, but when we remove one touch and
  277. // we still have enough, set eventType to move
  278. if(count_touches > 0 && eventType == Hammer.EVENT_END) {
  279. eventType = Hammer.EVENT_MOVE;
  280. }
  281. // no touches, force the end event
  282. else if(!count_touches) {
  283. eventType = Hammer.EVENT_END;
  284. }
  285. // because touchend has no touches, and we often want to use these in our gestures,
  286. // we send the last move event as our eventData in touchend
  287. if(!count_touches && last_move_event !== null) {
  288. ev = last_move_event;
  289. }
  290. // store the last move event
  291. else {
  292. last_move_event = ev;
  293. }
  294. // trigger the handler
  295. handler.call(Hammer.detection, self.collectEventData(element, eventType, ev));
  296. // remove pointerevent from list
  297. if(Hammer.HAS_POINTEREVENTS && eventType == Hammer.EVENT_END) {
  298. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  299. }
  300. }
  301. //debug(sourceEventType +" "+ eventType);
  302. // on the end we reset everything
  303. if(!count_touches) {
  304. last_move_event = null;
  305. enable_detect = false;
  306. touch_triggered = false;
  307. Hammer.PointerEvent.reset();
  308. }
  309. });
  310. },
  311. /**
  312. * we have different events for each device/browser
  313. * determine what we need and set them in the Hammer.EVENT_TYPES constant
  314. */
  315. determineEventTypes: function determineEventTypes() {
  316. // determine the eventtype we want to set
  317. var types;
  318. // pointerEvents magic
  319. if(Hammer.HAS_POINTEREVENTS) {
  320. types = Hammer.PointerEvent.getEvents();
  321. }
  322. // on Android, iOS, blackberry, windows mobile we dont want any mouseevents
  323. else if(Hammer.NO_MOUSEEVENTS) {
  324. types = [
  325. 'touchstart',
  326. 'touchmove',
  327. 'touchend touchcancel'];
  328. }
  329. // for non pointer events browsers and mixed browsers,
  330. // like chrome on windows8 touch laptop
  331. else {
  332. types = [
  333. 'touchstart mousedown',
  334. 'touchmove mousemove',
  335. 'touchend touchcancel mouseup'];
  336. }
  337. Hammer.EVENT_TYPES[Hammer.EVENT_START] = types[0];
  338. Hammer.EVENT_TYPES[Hammer.EVENT_MOVE] = types[1];
  339. Hammer.EVENT_TYPES[Hammer.EVENT_END] = types[2];
  340. },
  341. /**
  342. * create touchlist depending on the event
  343. * @param {Object} ev
  344. * @param {String} eventType used by the fakemultitouch plugin
  345. */
  346. getTouchList: function getTouchList(ev/*, eventType*/) {
  347. // get the fake pointerEvent touchlist
  348. if(Hammer.HAS_POINTEREVENTS) {
  349. return Hammer.PointerEvent.getTouchList();
  350. }
  351. // get the touchlist
  352. else if(ev.touches) {
  353. return ev.touches;
  354. }
  355. // make fake touchlist from mouse position
  356. else {
  357. return [{
  358. identifier: 1,
  359. pageX: ev.pageX,
  360. pageY: ev.pageY,
  361. target: ev.target
  362. }];
  363. }
  364. },
  365. /**
  366. * collect event data for Hammer js
  367. * @param {HTMLElement} element
  368. * @param {String} eventType like Hammer.EVENT_MOVE
  369. * @param {Object} eventData
  370. */
  371. collectEventData: function collectEventData(element, eventType, ev) {
  372. var touches = this.getTouchList(ev, eventType);
  373. // find out pointerType
  374. var pointerType = Hammer.POINTER_TOUCH;
  375. if(ev.type.match(/mouse/) || Hammer.PointerEvent.matchType(Hammer.POINTER_MOUSE, ev)) {
  376. pointerType = Hammer.POINTER_MOUSE;
  377. }
  378. return {
  379. center : Hammer.utils.getCenter(touches),
  380. timeStamp : new Date().getTime(),
  381. target : ev.target,
  382. touches : touches,
  383. eventType : eventType,
  384. pointerType : pointerType,
  385. srcEvent : ev,
  386. /**
  387. * prevent the browser default actions
  388. * mostly used to disable scrolling of the browser
  389. */
  390. preventDefault: function() {
  391. if(this.srcEvent.preventManipulation) {
  392. this.srcEvent.preventManipulation();
  393. }
  394. if(this.srcEvent.preventDefault) {
  395. this.srcEvent.preventDefault();
  396. }
  397. },
  398. /**
  399. * stop bubbling the event up to its parents
  400. */
  401. stopPropagation: function() {
  402. this.srcEvent.stopPropagation();
  403. },
  404. /**
  405. * immediately stop gesture detection
  406. * might be useful after a swipe was detected
  407. * @return {*}
  408. */
  409. stopDetect: function() {
  410. return Hammer.detection.stopDetect();
  411. }
  412. };
  413. }
  414. };
  415. Hammer.PointerEvent = {
  416. /**
  417. * holds all pointers
  418. * @type {Object}
  419. */
  420. pointers: {},
  421. /**
  422. * get a list of pointers
  423. * @returns {Array} touchlist
  424. */
  425. getTouchList: function() {
  426. var self = this;
  427. var touchlist = [];
  428. // we can use forEach since pointerEvents only is in IE10
  429. Object.keys(self.pointers).sort().forEach(function(id) {
  430. touchlist.push(self.pointers[id]);
  431. });
  432. return touchlist;
  433. },
  434. /**
  435. * update the position of a pointer
  436. * @param {String} type Hammer.EVENT_END
  437. * @param {Object} pointerEvent
  438. */
  439. updatePointer: function(type, pointerEvent) {
  440. if(type == Hammer.EVENT_END) {
  441. this.pointers = {};
  442. }
  443. else {
  444. pointerEvent.identifier = pointerEvent.pointerId;
  445. this.pointers[pointerEvent.pointerId] = pointerEvent;
  446. }
  447. return Object.keys(this.pointers).length;
  448. },
  449. /**
  450. * check if ev matches pointertype
  451. * @param {String} pointerType Hammer.POINTER_MOUSE
  452. * @param {PointerEvent} ev
  453. */
  454. matchType: function(pointerType, ev) {
  455. if(!ev.pointerType) {
  456. return false;
  457. }
  458. var types = {};
  459. types[Hammer.POINTER_MOUSE] = (ev.pointerType == ev.MSPOINTER_TYPE_MOUSE || ev.pointerType == Hammer.POINTER_MOUSE);
  460. types[Hammer.POINTER_TOUCH] = (ev.pointerType == ev.MSPOINTER_TYPE_TOUCH || ev.pointerType == Hammer.POINTER_TOUCH);
  461. types[Hammer.POINTER_PEN] = (ev.pointerType == ev.MSPOINTER_TYPE_PEN || ev.pointerType == Hammer.POINTER_PEN);
  462. return types[pointerType];
  463. },
  464. /**
  465. * get events
  466. */
  467. getEvents: function() {
  468. return [
  469. 'pointerdown MSPointerDown',
  470. 'pointermove MSPointerMove',
  471. 'pointerup pointercancel MSPointerUp MSPointerCancel'
  472. ];
  473. },
  474. /**
  475. * reset the list
  476. */
  477. reset: function() {
  478. this.pointers = {};
  479. }
  480. };
  481. Hammer.utils = {
  482. /**
  483. * extend method,
  484. * also used for cloning when dest is an empty object
  485. * @param {Object} dest
  486. * @param {Object} src
  487. * @parm {Boolean} merge do a merge
  488. * @returns {Object} dest
  489. */
  490. extend: function extend(dest, src, merge) {
  491. for (var key in src) {
  492. if(dest[key] !== undefined && merge) {
  493. continue;
  494. }
  495. dest[key] = src[key];
  496. }
  497. return dest;
  498. },
  499. /**
  500. * find if a node is in the given parent
  501. * used for event delegation tricks
  502. * @param {HTMLElement} node
  503. * @param {HTMLElement} parent
  504. * @returns {boolean} has_parent
  505. */
  506. hasParent: function(node, parent) {
  507. while(node){
  508. if(node == parent) {
  509. return true;
  510. }
  511. node = node.parentNode;
  512. }
  513. return false;
  514. },
  515. /**
  516. * get the center of all the touches
  517. * @param {Array} touches
  518. * @returns {Object} center
  519. */
  520. getCenter: function getCenter(touches) {
  521. var valuesX = [], valuesY = [];
  522. for(var t= 0,len=touches.length; t<len; t++) {
  523. valuesX.push(touches[t].pageX);
  524. valuesY.push(touches[t].pageY);
  525. }
  526. return {
  527. pageX: ((Math.min.apply(Math, valuesX) + Math.max.apply(Math, valuesX)) / 2),
  528. pageY: ((Math.min.apply(Math, valuesY) + Math.max.apply(Math, valuesY)) / 2)
  529. };
  530. },
  531. /**
  532. * calculate the velocity between two points
  533. * @param {Number} delta_time
  534. * @param {Number} delta_x
  535. * @param {Number} delta_y
  536. * @returns {Object} velocity
  537. */
  538. getVelocity: function getVelocity(delta_time, delta_x, delta_y) {
  539. return {
  540. x: Math.abs(delta_x / delta_time) || 0,
  541. y: Math.abs(delta_y / delta_time) || 0
  542. };
  543. },
  544. /**
  545. * calculate the angle between two coordinates
  546. * @param {Touch} touch1
  547. * @param {Touch} touch2
  548. * @returns {Number} angle
  549. */
  550. getAngle: function getAngle(touch1, touch2) {
  551. var y = touch2.pageY - touch1.pageY,
  552. x = touch2.pageX - touch1.pageX;
  553. return Math.atan2(y, x) * 180 / Math.PI;
  554. },
  555. /**
  556. * angle to direction define
  557. * @param {Touch} touch1
  558. * @param {Touch} touch2
  559. * @returns {String} direction constant, like Hammer.DIRECTION_LEFT
  560. */
  561. getDirection: function getDirection(touch1, touch2) {
  562. var x = Math.abs(touch1.pageX - touch2.pageX),
  563. y = Math.abs(touch1.pageY - touch2.pageY);
  564. if(x >= y) {
  565. return touch1.pageX - touch2.pageX > 0 ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  566. }
  567. else {
  568. return touch1.pageY - touch2.pageY > 0 ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  569. }
  570. },
  571. /**
  572. * calculate the distance between two touches
  573. * @param {Touch} touch1
  574. * @param {Touch} touch2
  575. * @returns {Number} distance
  576. */
  577. getDistance: function getDistance(touch1, touch2) {
  578. var x = touch2.pageX - touch1.pageX,
  579. y = touch2.pageY - touch1.pageY;
  580. return Math.sqrt((x*x) + (y*y));
  581. },
  582. /**
  583. * calculate the scale factor between two touchLists (fingers)
  584. * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
  585. * @param {Array} start
  586. * @param {Array} end
  587. * @returns {Number} scale
  588. */
  589. getScale: function getScale(start, end) {
  590. // need two fingers...
  591. if(start.length >= 2 && end.length >= 2) {
  592. return this.getDistance(end[0], end[1]) /
  593. this.getDistance(start[0], start[1]);
  594. }
  595. return 1;
  596. },
  597. /**
  598. * calculate the rotation degrees between two touchLists (fingers)
  599. * @param {Array} start
  600. * @param {Array} end
  601. * @returns {Number} rotation
  602. */
  603. getRotation: function getRotation(start, end) {
  604. // need two fingers
  605. if(start.length >= 2 && end.length >= 2) {
  606. return this.getAngle(end[1], end[0]) -
  607. this.getAngle(start[1], start[0]);
  608. }
  609. return 0;
  610. },
  611. /**
  612. * boolean if the direction is vertical
  613. * @param {String} direction
  614. * @returns {Boolean} is_vertical
  615. */
  616. isVertical: function isVertical(direction) {
  617. return (direction == Hammer.DIRECTION_UP || direction == Hammer.DIRECTION_DOWN);
  618. },
  619. /**
  620. * stop browser default behavior with css props
  621. * @param {HtmlElement} element
  622. * @param {Object} css_props
  623. */
  624. stopDefaultBrowserBehavior: function stopDefaultBrowserBehavior(element, css_props) {
  625. var prop,
  626. vendors = ['webkit','khtml','moz','ms','o',''];
  627. if(!css_props || !element.style) {
  628. return;
  629. }
  630. // with css properties for modern browsers
  631. for(var i = 0; i < vendors.length; i++) {
  632. for(var p in css_props) {
  633. if(css_props.hasOwnProperty(p)) {
  634. prop = p;
  635. // vender prefix at the property
  636. if(vendors[i]) {
  637. prop = vendors[i] + prop.substring(0, 1).toUpperCase() + prop.substring(1);
  638. }
  639. // set the style
  640. element.style[prop] = css_props[p];
  641. }
  642. }
  643. }
  644. // also the disable onselectstart
  645. if(css_props.userSelect == 'none') {
  646. element.onselectstart = function() {
  647. return false;
  648. };
  649. }
  650. }
  651. };
  652. Hammer.detection = {
  653. // contains all registred Hammer.gestures in the correct order
  654. gestures: [],
  655. // data of the current Hammer.gesture detection session
  656. current: null,
  657. // the previous Hammer.gesture session data
  658. // is a full clone of the previous gesture.current object
  659. previous: null,
  660. // when this becomes true, no gestures are fired
  661. stopped: false,
  662. /**
  663. * start Hammer.gesture detection
  664. * @param {Hammer.Instance} inst
  665. * @param {Object} eventData
  666. */
  667. startDetect: function startDetect(inst, eventData) {
  668. // already busy with a Hammer.gesture detection on an element
  669. if(this.current) {
  670. return;
  671. }
  672. this.stopped = false;
  673. this.current = {
  674. inst : inst, // reference to HammerInstance we're working for
  675. startEvent : Hammer.utils.extend({}, eventData), // start eventData for distances, timing etc
  676. lastEvent : false, // last eventData
  677. name : '' // current gesture we're in/detected, can be 'tap', 'hold' etc
  678. };
  679. this.detect(eventData);
  680. },
  681. /**
  682. * Hammer.gesture detection
  683. * @param {Object} eventData
  684. * @param {Object} eventData
  685. */
  686. detect: function detect(eventData) {
  687. if(!this.current || this.stopped) {
  688. return;
  689. }
  690. // extend event data with calculations about scale, distance etc
  691. eventData = this.extendEventData(eventData);
  692. // instance options
  693. var inst_options = this.current.inst.options;
  694. // call Hammer.gesture handlers
  695. for(var g=0,len=this.gestures.length; g<len; g++) {
  696. var gesture = this.gestures[g];
  697. // only when the instance options have enabled this gesture
  698. if(!this.stopped && inst_options[gesture.name] !== false) {
  699. // if a handler returns false, we stop with the detection
  700. if(gesture.handler.call(gesture, eventData, this.current.inst) === false) {
  701. this.stopDetect();
  702. break;
  703. }
  704. }
  705. }
  706. // store as previous event event
  707. if(this.current) {
  708. this.current.lastEvent = eventData;
  709. }
  710. // endevent, but not the last touch, so dont stop
  711. if(eventData.eventType == Hammer.EVENT_END && !eventData.touches.length-1) {
  712. this.stopDetect();
  713. }
  714. return eventData;
  715. },
  716. /**
  717. * clear the Hammer.gesture vars
  718. * this is called on endDetect, but can also be used when a final Hammer.gesture has been detected
  719. * to stop other Hammer.gestures from being fired
  720. */
  721. stopDetect: function stopDetect() {
  722. // clone current data to the store as the previous gesture
  723. // used for the double tap gesture, since this is an other gesture detect session
  724. this.previous = Hammer.utils.extend({}, this.current);
  725. // reset the current
  726. this.current = null;
  727. // stopped!
  728. this.stopped = true;
  729. },
  730. /**
  731. * extend eventData for Hammer.gestures
  732. * @param {Object} ev
  733. * @returns {Object} ev
  734. */
  735. extendEventData: function extendEventData(ev) {
  736. var startEv = this.current.startEvent;
  737. // if the touches change, set the new touches over the startEvent touches
  738. // this because touchevents don't have all the touches on touchstart, or the
  739. // user must place his fingers at the EXACT same time on the screen, which is not realistic
  740. // but, sometimes it happens that both fingers are touching at the EXACT same time
  741. if(startEv && (ev.touches.length != startEv.touches.length || ev.touches === startEv.touches)) {
  742. // extend 1 level deep to get the touchlist with the touch objects
  743. startEv.touches = [];
  744. for(var i=0,len=ev.touches.length; i<len; i++) {
  745. startEv.touches.push(Hammer.utils.extend({}, ev.touches[i]));
  746. }
  747. }
  748. var delta_time = ev.timeStamp - startEv.timeStamp,
  749. delta_x = ev.center.pageX - startEv.center.pageX,
  750. delta_y = ev.center.pageY - startEv.center.pageY,
  751. velocity = Hammer.utils.getVelocity(delta_time, delta_x, delta_y);
  752. Hammer.utils.extend(ev, {
  753. deltaTime : delta_time,
  754. deltaX : delta_x,
  755. deltaY : delta_y,
  756. velocityX : velocity.x,
  757. velocityY : velocity.y,
  758. distance : Hammer.utils.getDistance(startEv.center, ev.center),
  759. angle : Hammer.utils.getAngle(startEv.center, ev.center),
  760. direction : Hammer.utils.getDirection(startEv.center, ev.center),
  761. scale : Hammer.utils.getScale(startEv.touches, ev.touches),
  762. rotation : Hammer.utils.getRotation(startEv.touches, ev.touches),
  763. startEvent : startEv
  764. });
  765. return ev;
  766. },
  767. /**
  768. * register new gesture
  769. * @param {Object} gesture object, see gestures.js for documentation
  770. * @returns {Array} gestures
  771. */
  772. register: function register(gesture) {
  773. // add an enable gesture options if there is no given
  774. var options = gesture.defaults || {};
  775. if(options[gesture.name] === undefined) {
  776. options[gesture.name] = true;
  777. }
  778. // extend Hammer default options with the Hammer.gesture options
  779. Hammer.utils.extend(Hammer.defaults, options, true);
  780. // set its index
  781. gesture.index = gesture.index || 1000;
  782. // add Hammer.gesture to the list
  783. this.gestures.push(gesture);
  784. // sort the list by index
  785. this.gestures.sort(function(a, b) {
  786. if (a.index < b.index) {
  787. return -1;
  788. }
  789. if (a.index > b.index) {
  790. return 1;
  791. }
  792. return 0;
  793. });
  794. return this.gestures;
  795. }
  796. };
  797. Hammer.gestures = Hammer.gestures || {};
  798. /**
  799. * Custom gestures
  800. * ==============================
  801. *
  802. * Gesture object
  803. * --------------------
  804. * The object structure of a gesture:
  805. *
  806. * { name: 'mygesture',
  807. * index: 1337,
  808. * defaults: {
  809. * mygesture_option: true
  810. * }
  811. * handler: function(type, ev, inst) {
  812. * // trigger gesture event
  813. * inst.trigger(this.name, ev);
  814. * }
  815. * }
  816. * @param {String} name
  817. * this should be the name of the gesture, lowercase
  818. * it is also being used to disable/enable the gesture per instance config.
  819. *
  820. * @param {Number} [index=1000]
  821. * the index of the gesture, where it is going to be in the stack of gestures detection
  822. * like when you build an gesture that depends on the drag gesture, it is a good
  823. * idea to place it after the index of the drag gesture.
  824. *
  825. * @param {Object} [defaults={}]
  826. * the default settings of the gesture. these are added to the instance settings,
  827. * and can be overruled per instance. you can also add the name of the gesture,
  828. * but this is also added by default (and set to true).
  829. *
  830. * @param {Function} handler
  831. * this handles the gesture detection of your custom gesture and receives the
  832. * following arguments:
  833. *
  834. * @param {Object} eventData
  835. * event data containing the following properties:
  836. * timeStamp {Number} time the event occurred
  837. * target {HTMLElement} target element
  838. * touches {Array} touches (fingers, pointers, mouse) on the screen
  839. * pointerType {String} kind of pointer that was used. matches Hammer.POINTER_MOUSE|TOUCH
  840. * center {Object} center position of the touches. contains pageX and pageY
  841. * deltaTime {Number} the total time of the touches in the screen
  842. * deltaX {Number} the delta on x axis we haved moved
  843. * deltaY {Number} the delta on y axis we haved moved
  844. * velocityX {Number} the velocity on the x
  845. * velocityY {Number} the velocity on y
  846. * angle {Number} the angle we are moving
  847. * direction {String} the direction we are moving. matches Hammer.DIRECTION_UP|DOWN|LEFT|RIGHT
  848. * distance {Number} the distance we haved moved
  849. * scale {Number} scaling of the touches, needs 2 touches
  850. * rotation {Number} rotation of the touches, needs 2 touches *
  851. * eventType {String} matches Hammer.EVENT_START|MOVE|END
  852. * srcEvent {Object} the source event, like TouchStart or MouseDown *
  853. * startEvent {Object} contains the same properties as above,
  854. * but from the first touch. this is used to calculate
  855. * distances, deltaTime, scaling etc
  856. *
  857. * @param {Hammer.Instance} inst
  858. * the instance we are doing the detection for. you can get the options from
  859. * the inst.options object and trigger the gesture event by calling inst.trigger
  860. *
  861. *
  862. * Handle gestures
  863. * --------------------
  864. * inside the handler you can get/set Hammer.detection.current. This is the current
  865. * detection session. It has the following properties
  866. * @param {String} name
  867. * contains the name of the gesture we have detected. it has not a real function,
  868. * only to check in other gestures if something is detected.
  869. * like in the drag gesture we set it to 'drag' and in the swipe gesture we can
  870. * check if the current gesture is 'drag' by accessing Hammer.detection.current.name
  871. *
  872. * @readonly
  873. * @param {Hammer.Instance} inst
  874. * the instance we do the detection for
  875. *
  876. * @readonly
  877. * @param {Object} startEvent
  878. * contains the properties of the first gesture detection in this session.
  879. * Used for calculations about timing, distance, etc.
  880. *
  881. * @readonly
  882. * @param {Object} lastEvent
  883. * contains all the properties of the last gesture detect in this session.
  884. *
  885. * after the gesture detection session has been completed (user has released the screen)
  886. * the Hammer.detection.current object is copied into Hammer.detection.previous,
  887. * this is usefull for gestures like doubletap, where you need to know if the
  888. * previous gesture was a tap
  889. *
  890. * options that have been set by the instance can be received by calling inst.options
  891. *
  892. * You can trigger a gesture event by calling inst.trigger("mygesture", event).
  893. * The first param is the name of your gesture, the second the event argument
  894. *
  895. *
  896. * Register gestures
  897. * --------------------
  898. * When an gesture is added to the Hammer.gestures object, it is auto registered
  899. * at the setup of the first Hammer instance. You can also call Hammer.detection.register
  900. * manually and pass your gesture object as a param
  901. *
  902. */
  903. /**
  904. * Hold
  905. * Touch stays at the same place for x time
  906. * @events hold
  907. */
  908. Hammer.gestures.Hold = {
  909. name: 'hold',
  910. index: 10,
  911. defaults: {
  912. hold_timeout : 500,
  913. hold_threshold : 1
  914. },
  915. timer: null,
  916. handler: function holdGesture(ev, inst) {
  917. switch(ev.eventType) {
  918. case Hammer.EVENT_START:
  919. // clear any running timers
  920. clearTimeout(this.timer);
  921. // set the gesture so we can check in the timeout if it still is
  922. Hammer.detection.current.name = this.name;
  923. // set timer and if after the timeout it still is hold,
  924. // we trigger the hold event
  925. this.timer = setTimeout(function() {
  926. if(Hammer.detection.current.name == 'hold') {
  927. inst.trigger('hold', ev);
  928. }
  929. }, inst.options.hold_timeout);
  930. break;
  931. // when you move or end we clear the timer
  932. case Hammer.EVENT_MOVE:
  933. if(ev.distance > inst.options.hold_threshold) {
  934. clearTimeout(this.timer);
  935. }
  936. break;
  937. case Hammer.EVENT_END:
  938. clearTimeout(this.timer);
  939. break;
  940. }
  941. }
  942. };
  943. /**
  944. * Tap/DoubleTap
  945. * Quick touch at a place or double at the same place
  946. * @events tap, doubletap
  947. */
  948. Hammer.gestures.Tap = {
  949. name: 'tap',
  950. index: 100,
  951. defaults: {
  952. tap_max_touchtime : 250,
  953. tap_max_distance : 10,
  954. tap_always : true,
  955. doubletap_distance : 20,
  956. doubletap_interval : 300
  957. },
  958. handler: function tapGesture(ev, inst) {
  959. if(ev.eventType == Hammer.EVENT_END) {
  960. // previous gesture, for the double tap since these are two different gesture detections
  961. var prev = Hammer.detection.previous,
  962. did_doubletap = false;
  963. // when the touchtime is higher then the max touch time
  964. // or when the moving distance is too much
  965. if(ev.deltaTime > inst.options.tap_max_touchtime ||
  966. ev.distance > inst.options.tap_max_distance) {
  967. return;
  968. }
  969. // check if double tap
  970. if(prev && prev.name == 'tap' &&
  971. (ev.timeStamp - prev.lastEvent.timeStamp) < inst.options.doubletap_interval &&
  972. ev.distance < inst.options.doubletap_distance) {
  973. inst.trigger('doubletap', ev);
  974. did_doubletap = true;
  975. }
  976. // do a single tap
  977. if(!did_doubletap || inst.options.tap_always) {
  978. Hammer.detection.current.name = 'tap';
  979. inst.trigger(Hammer.detection.current.name, ev);
  980. }
  981. }
  982. }
  983. };
  984. /**
  985. * Swipe
  986. * triggers swipe events when the end velocity is above the threshold
  987. * @events swipe, swipeleft, swiperight, swipeup, swipedown
  988. */
  989. Hammer.gestures.Swipe = {
  990. name: 'swipe',
  991. index: 40,
  992. defaults: {
  993. // set 0 for unlimited, but this can conflict with transform
  994. swipe_max_touches : 1,
  995. swipe_velocity : 0.7
  996. },
  997. handler: function swipeGesture(ev, inst) {
  998. if(ev.eventType == Hammer.EVENT_END) {
  999. // max touches
  1000. if(inst.options.swipe_max_touches > 0 &&
  1001. ev.touches.length > inst.options.swipe_max_touches) {
  1002. return;
  1003. }
  1004. // when the distance we moved is too small we skip this gesture
  1005. // or we can be already in dragging
  1006. if(ev.velocityX > inst.options.swipe_velocity ||
  1007. ev.velocityY > inst.options.swipe_velocity) {
  1008. // trigger swipe events
  1009. inst.trigger(this.name, ev);
  1010. inst.trigger(this.name + ev.direction, ev);
  1011. }
  1012. }
  1013. }
  1014. };
  1015. /**
  1016. * Drag
  1017. * Move with x fingers (default 1) around on the page. Blocking the scrolling when
  1018. * moving left and right is a good practice. When all the drag events are blocking
  1019. * you disable scrolling on that area.
  1020. * @events drag, drapleft, dragright, dragup, dragdown
  1021. */
  1022. Hammer.gestures.Drag = {
  1023. name: 'drag',
  1024. index: 50,
  1025. defaults: {
  1026. drag_min_distance : 10,
  1027. // set 0 for unlimited, but this can conflict with transform
  1028. drag_max_touches : 1,
  1029. // prevent default browser behavior when dragging occurs
  1030. // be careful with it, it makes the element a blocking element
  1031. // when you are using the drag gesture, it is a good practice to set this true
  1032. drag_block_horizontal : false,
  1033. drag_block_vertical : false,
  1034. // drag_lock_to_axis keeps the drag gesture on the axis that it started on,
  1035. // It disallows vertical directions if the initial direction was horizontal, and vice versa.
  1036. drag_lock_to_axis : false,
  1037. // drag lock only kicks in when distance > drag_lock_min_distance
  1038. // This way, locking occurs only when the distance has become large enough to reliably determine the direction
  1039. drag_lock_min_distance : 25
  1040. },
  1041. triggered: false,
  1042. handler: function dragGesture(ev, inst) {
  1043. // current gesture isnt drag, but dragged is true
  1044. // this means an other gesture is busy. now call dragend
  1045. if(Hammer.detection.current.name != this.name && this.triggered) {
  1046. inst.trigger(this.name +'end', ev);
  1047. this.triggered = false;
  1048. return;
  1049. }
  1050. // max touches
  1051. if(inst.options.drag_max_touches > 0 &&
  1052. ev.touches.length > inst.options.drag_max_touches) {
  1053. return;
  1054. }
  1055. switch(ev.eventType) {
  1056. case Hammer.EVENT_START:
  1057. this.triggered = false;
  1058. break;
  1059. case Hammer.EVENT_MOVE:
  1060. // when the distance we moved is too small we skip this gesture
  1061. // or we can be already in dragging
  1062. if(ev.distance < inst.options.drag_min_distance &&
  1063. Hammer.detection.current.name != this.name) {
  1064. return;
  1065. }
  1066. // we are dragging!
  1067. Hammer.detection.current.name = this.name;
  1068. // lock drag to axis?
  1069. if(Hammer.detection.current.lastEvent.drag_locked_to_axis || (inst.options.drag_lock_to_axis && inst.options.drag_lock_min_distance<=ev.distance)) {
  1070. ev.drag_locked_to_axis = true;
  1071. }
  1072. var last_direction = Hammer.detection.current.lastEvent.direction;
  1073. if(ev.drag_locked_to_axis && last_direction !== ev.direction) {
  1074. // keep direction on the axis that the drag gesture started on
  1075. if(Hammer.utils.isVertical(last_direction)) {
  1076. ev.direction = (ev.deltaY < 0) ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  1077. }
  1078. else {
  1079. ev.direction = (ev.deltaX < 0) ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  1080. }
  1081. }
  1082. // first time, trigger dragstart event
  1083. if(!this.triggered) {
  1084. inst.trigger(this.name +'start', ev);
  1085. this.triggered = true;
  1086. }
  1087. // trigger normal event
  1088. inst.trigger(this.name, ev);
  1089. // direction event, like dragdown
  1090. inst.trigger(this.name + ev.direction, ev);
  1091. // block the browser events
  1092. if( (inst.options.drag_block_vertical && Hammer.utils.isVertical(ev.direction)) ||
  1093. (inst.options.drag_block_horizontal && !Hammer.utils.isVertical(ev.direction))) {
  1094. ev.preventDefault();
  1095. }
  1096. break;
  1097. case Hammer.EVENT_END:
  1098. // trigger dragend
  1099. if(this.triggered) {
  1100. inst.trigger(this.name +'end', ev);
  1101. }
  1102. this.triggered = false;
  1103. break;
  1104. }
  1105. }
  1106. };
  1107. /**
  1108. * Transform
  1109. * User want to scale or rotate with 2 fingers
  1110. * @events transform, pinch, pinchin, pinchout, rotate
  1111. */
  1112. Hammer.gestures.Transform = {
  1113. name: 'transform',
  1114. index: 45,
  1115. defaults: {
  1116. // factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1
  1117. transform_min_scale : 0.01,
  1118. // rotation in degrees
  1119. transform_min_rotation : 1,
  1120. // prevent default browser behavior when two touches are on the screen
  1121. // but it makes the element a blocking element
  1122. // when you are using the transform gesture, it is a good practice to set this true
  1123. transform_always_block : false
  1124. },
  1125. triggered: false,
  1126. handler: function transformGesture(ev, inst) {
  1127. // current gesture isnt drag, but dragged is true
  1128. // this means an other gesture is busy. now call dragend
  1129. if(Hammer.detection.current.name != this.name && this.triggered) {
  1130. inst.trigger(this.name +'end', ev);
  1131. this.triggered = false;
  1132. return;
  1133. }
  1134. // atleast multitouch
  1135. if(ev.touches.length < 2) {
  1136. return;
  1137. }
  1138. // prevent default when two fingers are on the screen
  1139. if(inst.options.transform_always_block) {
  1140. ev.preventDefault();
  1141. }
  1142. switch(ev.eventType) {
  1143. case Hammer.EVENT_START:
  1144. this.triggered = false;
  1145. break;
  1146. case Hammer.EVENT_MOVE:
  1147. var scale_threshold = Math.abs(1-ev.scale);
  1148. var rotation_threshold = Math.abs(ev.rotation);
  1149. // when the distance we moved is too small we skip this gesture
  1150. // or we can be already in dragging
  1151. if(scale_threshold < inst.options.transform_min_scale &&
  1152. rotation_threshold < inst.options.transform_min_rotation) {
  1153. return;
  1154. }
  1155. // we are transforming!
  1156. Hammer.detection.current.name = this.name;
  1157. // first time, trigger dragstart event
  1158. if(!this.triggered) {
  1159. inst.trigger(this.name +'start', ev);
  1160. this.triggered = true;
  1161. }
  1162. inst.trigger(this.name, ev); // basic transform event
  1163. // trigger rotate event
  1164. if(rotation_threshold > inst.options.transform_min_rotation) {
  1165. inst.trigger('rotate', ev);
  1166. }
  1167. // trigger pinch event
  1168. if(scale_threshold > inst.options.transform_min_scale) {
  1169. inst.trigger('pinch', ev);
  1170. inst.trigger('pinch'+ ((ev.scale < 1) ? 'in' : 'out'), ev);
  1171. }
  1172. break;
  1173. case Hammer.EVENT_END:
  1174. // trigger dragend
  1175. if(this.triggered) {
  1176. inst.trigger(this.name +'end', ev);
  1177. }
  1178. this.triggered = false;
  1179. break;
  1180. }
  1181. }
  1182. };
  1183. /**
  1184. * Touch
  1185. * Called as first, tells the user has touched the screen
  1186. * @events touch
  1187. */
  1188. Hammer.gestures.Touch = {
  1189. name: 'touch',
  1190. index: -Infinity,
  1191. defaults: {
  1192. // call preventDefault at touchstart, and makes the element blocking by
  1193. // disabling the scrolling of the page, but it improves gestures like
  1194. // transforming and dragging.
  1195. // be careful with using this, it can be very annoying for users to be stuck
  1196. // on the page
  1197. prevent_default: false,
  1198. // disable mouse events, so only touch (or pen!) input triggers events
  1199. prevent_mouseevents: false
  1200. },
  1201. handler: function touchGesture(ev, inst) {
  1202. if(inst.options.prevent_mouseevents && ev.pointerType == Hammer.POINTER_MOUSE) {
  1203. ev.stopDetect();
  1204. return;
  1205. }
  1206. if(inst.options.prevent_default) {
  1207. ev.preventDefault();
  1208. }
  1209. if(ev.eventType == Hammer.EVENT_START) {
  1210. inst.trigger(this.name, ev);
  1211. }
  1212. }
  1213. };
  1214. /**
  1215. * Release
  1216. * Called as last, tells the user has released the screen
  1217. * @events release
  1218. */
  1219. Hammer.gestures.Release = {
  1220. name: 'release',
  1221. index: Infinity,
  1222. handler: function releaseGesture(ev, inst) {
  1223. if(ev.eventType == Hammer.EVENT_END) {
  1224. inst.trigger(this.name, ev);
  1225. }
  1226. }
  1227. };
  1228. // node export
  1229. if(typeof module === 'object' && typeof module.exports === 'object'){
  1230. module.exports = Hammer;
  1231. }
  1232. // just window export
  1233. else {
  1234. window.Hammer = Hammer;
  1235. // requireJS module definition
  1236. if(typeof window.define === 'function' && window.define.amd) {
  1237. window.define('hammer', [], function() {
  1238. return Hammer;
  1239. });
  1240. }
  1241. }
  1242. })(this);
  1243. },{}],2:[function(require,module,exports){
  1244. //! moment.js
  1245. //! version : 2.5.0
  1246. //! authors : Tim Wood, Iskren Chernev, Moment.js contributors
  1247. //! license : MIT
  1248. //! momentjs.com
  1249. (function (undefined) {
  1250. /************************************
  1251. Constants
  1252. ************************************/
  1253. var moment,
  1254. VERSION = "2.5.0",
  1255. global = this,
  1256. round = Math.round,
  1257. i,
  1258. YEAR = 0,
  1259. MONTH = 1,
  1260. DATE = 2,
  1261. HOUR = 3,
  1262. MINUTE = 4,
  1263. SECOND = 5,
  1264. MILLISECOND = 6,
  1265. // internal storage for language config files
  1266. languages = {},
  1267. // check for nodeJS
  1268. hasModule = (typeof module !== 'undefined' && module.exports && typeof require !== 'undefined'),
  1269. // ASP.NET json date format regex
  1270. aspNetJsonRegex = /^\/?Date\((\-?\d+)/i,
  1271. aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,
  1272. // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
  1273. // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
  1274. isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/,
  1275. // format tokens
  1276. formattingTokens = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|X|zz?|ZZ?|.)/g,
  1277. localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g,
  1278. // parsing token regexes
  1279. parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99
  1280. parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999
  1281. parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999
  1282. parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999
  1283. parseTokenDigits = /\d+/, // nonzero number of digits
  1284. 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.
  1285. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z
  1286. parseTokenT = /T/i, // T (ISO separator)
  1287. parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
  1288. //strict parsing regexes
  1289. parseTokenOneDigit = /\d/, // 0 - 9
  1290. parseTokenTwoDigits = /\d\d/, // 00 - 99
  1291. parseTokenThreeDigits = /\d{3}/, // 000 - 999
  1292. parseTokenFourDigits = /\d{4}/, // 0000 - 9999
  1293. parseTokenSixDigits = /[+\-]?\d{6}/, // -999,999 - 999,999
  1294. // iso 8601 regex
  1295. // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00)
  1296. isoRegex = /^\s*\d{4}-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,
  1297. isoFormat = 'YYYY-MM-DDTHH:mm:ssZ',
  1298. isoDates = [
  1299. 'YYYY-MM-DD',
  1300. 'GGGG-[W]WW',
  1301. 'GGGG-[W]WW-E',
  1302. 'YYYY-DDD'
  1303. ],
  1304. // iso time formats and regexes
  1305. isoTimes = [
  1306. ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d{1,3}/],
  1307. ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/],
  1308. ['HH:mm', /(T| )\d\d:\d\d/],
  1309. ['HH', /(T| )\d\d/]
  1310. ],
  1311. // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"]
  1312. parseTimezoneChunker = /([\+\-]|\d\d)/gi,
  1313. // getter and setter names
  1314. proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'),
  1315. unitMillisecondFactors = {
  1316. 'Milliseconds' : 1,
  1317. 'Seconds' : 1e3,
  1318. 'Minutes' : 6e4,
  1319. 'Hours' : 36e5,
  1320. 'Days' : 864e5,
  1321. 'Months' : 2592e6,
  1322. 'Years' : 31536e6
  1323. },
  1324. unitAliases = {
  1325. ms : 'millisecond',
  1326. s : 'second',
  1327. m : 'minute',
  1328. h : 'hour',
  1329. d : 'day',
  1330. D : 'date',
  1331. w : 'week',
  1332. W : 'isoWeek',
  1333. M : 'month',
  1334. y : 'year',
  1335. DDD : 'dayOfYear',
  1336. e : 'weekday',
  1337. E : 'isoWeekday',
  1338. gg: 'weekYear',
  1339. GG: 'isoWeekYear'
  1340. },
  1341. camelFunctions = {
  1342. dayofyear : 'dayOfYear',
  1343. isoweekday : 'isoWeekday',
  1344. isoweek : 'isoWeek',
  1345. weekyear : 'weekYear',
  1346. isoweekyear : 'isoWeekYear'
  1347. },
  1348. // format function strings
  1349. formatFunctions = {},
  1350. // tokens to ordinalize and pad
  1351. ordinalizeTokens = 'DDD w W M D d'.split(' '),
  1352. paddedTokens = 'M D H h m s w W'.split(' '),
  1353. formatTokenFunctions = {
  1354. M : function () {
  1355. return this.month() + 1;
  1356. },
  1357. MMM : function (format) {
  1358. return this.lang().monthsShort(this, format);
  1359. },
  1360. MMMM : function (format) {
  1361. return this.lang().months(this, format);
  1362. },
  1363. D : function () {
  1364. return this.date();
  1365. },
  1366. DDD : function () {
  1367. return this.dayOfYear();
  1368. },
  1369. d : function () {
  1370. return this.day();
  1371. },
  1372. dd : function (format) {
  1373. return this.lang().weekdaysMin(this, format);
  1374. },
  1375. ddd : function (format) {
  1376. return this.lang().weekdaysShort(this, format);
  1377. },
  1378. dddd : function (format) {
  1379. return this.lang().weekdays(this, format);
  1380. },
  1381. w : function () {
  1382. return this.week();
  1383. },
  1384. W : function () {
  1385. return this.isoWeek();
  1386. },
  1387. YY : function () {
  1388. return leftZeroFill(this.year() % 100, 2);
  1389. },
  1390. YYYY : function () {
  1391. return leftZeroFill(this.year(), 4);
  1392. },
  1393. YYYYY : function () {
  1394. return leftZeroFill(this.year(), 5);
  1395. },
  1396. YYYYYY : function () {
  1397. var y = this.year(), sign = y >= 0 ? '+' : '-';
  1398. return sign + leftZeroFill(Math.abs(y), 6);
  1399. },
  1400. gg : function () {
  1401. return leftZeroFill(this.weekYear() % 100, 2);
  1402. },
  1403. gggg : function () {
  1404. return this.weekYear();
  1405. },
  1406. ggggg : function () {
  1407. return leftZeroFill(this.weekYear(), 5);
  1408. },
  1409. GG : function () {
  1410. return leftZeroFill(this.isoWeekYear() % 100, 2);
  1411. },
  1412. GGGG : function () {
  1413. return this.isoWeekYear();
  1414. },
  1415. GGGGG : function () {
  1416. return leftZeroFill(this.isoWeekYear(), 5);
  1417. },
  1418. e : function () {
  1419. return this.weekday();
  1420. },
  1421. E : function () {
  1422. return this.isoWeekday();
  1423. },
  1424. a : function () {
  1425. return this.lang().meridiem(this.hours(), this.minutes(), true);
  1426. },
  1427. A : function () {
  1428. return this.lang().meridiem(this.hours(), this.minutes(), false);
  1429. },
  1430. H : function () {
  1431. return this.hours();
  1432. },
  1433. h : function () {
  1434. return this.hours() % 12 || 12;
  1435. },
  1436. m : function () {
  1437. return this.minutes();
  1438. },
  1439. s : function () {
  1440. return this.seconds();
  1441. },
  1442. S : function () {
  1443. return toInt(this.milliseconds() / 100);
  1444. },
  1445. SS : function () {
  1446. return leftZeroFill(toInt(this.milliseconds() / 10), 2);
  1447. },
  1448. SSS : function () {
  1449. return leftZeroFill(this.milliseconds(), 3);
  1450. },
  1451. SSSS : function () {
  1452. return leftZeroFill(this.milliseconds(), 3);
  1453. },
  1454. Z : function () {
  1455. var a = -this.zone(),
  1456. b = "+";
  1457. if (a < 0) {
  1458. a = -a;
  1459. b = "-";
  1460. }
  1461. return b + leftZeroFill(toInt(a / 60), 2) + ":" + leftZeroFill(toInt(a) % 60, 2);
  1462. },
  1463. ZZ : function () {
  1464. var a = -this.zone(),
  1465. b = "+";
  1466. if (a < 0) {
  1467. a = -a;
  1468. b = "-";
  1469. }
  1470. return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2);
  1471. },
  1472. z : function () {
  1473. return this.zoneAbbr();
  1474. },
  1475. zz : function () {
  1476. return this.zoneName();
  1477. },
  1478. X : function () {
  1479. return this.unix();
  1480. },
  1481. Q : function () {
  1482. return this.quarter();
  1483. }
  1484. },
  1485. lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin'];
  1486. function padToken(func, count) {
  1487. return function (a) {
  1488. return leftZeroFill(func.call(this, a), count);
  1489. };
  1490. }
  1491. function ordinalizeToken(func, period) {
  1492. return function (a) {
  1493. return this.lang().ordinal(func.call(this, a), period);
  1494. };
  1495. }
  1496. while (ordinalizeTokens.length) {
  1497. i = ordinalizeTokens.pop();
  1498. formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i);
  1499. }
  1500. while (paddedTokens.length) {
  1501. i = paddedTokens.pop();
  1502. formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2);
  1503. }
  1504. formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3);
  1505. /************************************
  1506. Constructors
  1507. ************************************/
  1508. function Language() {
  1509. }
  1510. // Moment prototype object
  1511. function Moment(config) {
  1512. checkOverflow(config);
  1513. extend(this, config);
  1514. }
  1515. // Duration Constructor
  1516. function Duration(duration) {
  1517. var normalizedInput = normalizeObjectUnits(duration),
  1518. years = normalizedInput.year || 0,
  1519. months = normalizedInput.month || 0,
  1520. weeks = normalizedInput.week || 0,
  1521. days = normalizedInput.day || 0,
  1522. hours = normalizedInput.hour || 0,
  1523. minutes = normalizedInput.minute || 0,
  1524. seconds = normalizedInput.second || 0,
  1525. milliseconds = normalizedInput.millisecond || 0;
  1526. // representation for dateAddRemove
  1527. this._milliseconds = +milliseconds +
  1528. seconds * 1e3 + // 1000
  1529. minutes * 6e4 + // 1000 * 60
  1530. hours * 36e5; // 1000 * 60 * 60
  1531. // Because of dateAddRemove treats 24 hours as different from a
  1532. // day when working around DST, we need to store them separately
  1533. this._days = +days +
  1534. weeks * 7;
  1535. // It is impossible translate months into days without knowing
  1536. // which months you are are talking about, so we have to store
  1537. // it separately.
  1538. this._months = +months +
  1539. years * 12;
  1540. this._data = {};
  1541. this._bubble();
  1542. }
  1543. /************************************
  1544. Helpers
  1545. ************************************/
  1546. function extend(a, b) {
  1547. for (var i in b) {
  1548. if (b.hasOwnProperty(i)) {
  1549. a[i] = b[i];
  1550. }
  1551. }
  1552. if (b.hasOwnProperty("toString")) {
  1553. a.toString = b.toString;
  1554. }
  1555. if (b.hasOwnProperty("valueOf")) {
  1556. a.valueOf = b.valueOf;
  1557. }
  1558. return a;
  1559. }
  1560. function absRound(number) {
  1561. if (number < 0) {
  1562. return Math.ceil(number);
  1563. } else {
  1564. return Math.floor(number);
  1565. }
  1566. }
  1567. // left zero fill a number
  1568. // see http://jsperf.com/left-zero-filling for performance comparison
  1569. function leftZeroFill(number, targetLength, forceSign) {
  1570. var output = Math.abs(number) + '',
  1571. sign = number >= 0;
  1572. while (output.length < targetLength) {
  1573. output = '0' + output;
  1574. }
  1575. return (sign ? (forceSign ? '+' : '') : '-') + output;
  1576. }
  1577. // helper function for _.addTime and _.subtractTime
  1578. function addOrSubtractDurationFromMoment(mom, duration, isAdding, ignoreUpdateOffset) {
  1579. var milliseconds = duration._milliseconds,
  1580. days = duration._days,
  1581. months = duration._months,
  1582. minutes,
  1583. hours;
  1584. if (milliseconds) {
  1585. mom._d.setTime(+mom._d + milliseconds * isAdding);
  1586. }
  1587. // store the minutes and hours so we can restore them
  1588. if (days || months) {
  1589. minutes = mom.minute();
  1590. hours = mom.hour();
  1591. }
  1592. if (days) {
  1593. mom.date(mom.date() + days * isAdding);
  1594. }
  1595. if (months) {
  1596. mom.month(mom.month() + months * isAdding);
  1597. }
  1598. if (milliseconds && !ignoreUpdateOffset) {
  1599. moment.updateOffset(mom);
  1600. }
  1601. // restore the minutes and hours after possibly changing dst
  1602. if (days || months) {
  1603. mom.minute(minutes);
  1604. mom.hour(hours);
  1605. }
  1606. }
  1607. // check if is an array
  1608. function isArray(input) {
  1609. return Object.prototype.toString.call(input) === '[object Array]';
  1610. }
  1611. function isDate(input) {
  1612. return Object.prototype.toString.call(input) === '[object Date]' ||
  1613. input instanceof Date;
  1614. }
  1615. // compare two arrays, return the number of differences
  1616. function compareArrays(array1, array2, dontConvert) {
  1617. var len = Math.min(array1.length, array2.length),
  1618. lengthDiff = Math.abs(array1.length - array2.length),
  1619. diffs = 0,
  1620. i;
  1621. for (i = 0; i < len; i++) {
  1622. if ((dontConvert && array1[i] !== array2[i]) ||
  1623. (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
  1624. diffs++;
  1625. }
  1626. }
  1627. return diffs + lengthDiff;
  1628. }
  1629. function normalizeUnits(units) {
  1630. if (units) {
  1631. var lowered = units.toLowerCase().replace(/(.)s$/, '$1');
  1632. units = unitAliases[units] || camelFunctions[lowered] || lowered;
  1633. }
  1634. return units;
  1635. }
  1636. function normalizeObjectUnits(inputObject) {
  1637. var normalizedInput = {},
  1638. normalizedProp,
  1639. prop;
  1640. for (prop in inputObject) {
  1641. if (inputObject.hasOwnProperty(prop)) {
  1642. normalizedProp = normalizeUnits(prop);
  1643. if (normalizedProp) {
  1644. normalizedInput[normalizedProp] = inputObject[prop];
  1645. }
  1646. }
  1647. }
  1648. return normalizedInput;
  1649. }
  1650. function makeList(field) {
  1651. var count, setter;
  1652. if (field.indexOf('week') === 0) {
  1653. count = 7;
  1654. setter = 'day';
  1655. }
  1656. else if (field.indexOf('month') === 0) {
  1657. count = 12;
  1658. setter = 'month';
  1659. }
  1660. else {
  1661. return;
  1662. }
  1663. moment[field] = function (format, index) {
  1664. var i, getter,
  1665. method = moment.fn._lang[field],
  1666. results = [];
  1667. if (typeof format === 'number') {
  1668. index = format;
  1669. format = undefined;
  1670. }
  1671. getter = function (i) {
  1672. var m = moment().utc().set(setter, i);
  1673. return method.call(moment.fn._lang, m, format || '');
  1674. };
  1675. if (index != null) {
  1676. return getter(index);
  1677. }
  1678. else {
  1679. for (i = 0; i < count; i++) {
  1680. results.push(getter(i));
  1681. }
  1682. return results;
  1683. }
  1684. };
  1685. }
  1686. function toInt(argumentForCoercion) {
  1687. var coercedNumber = +argumentForCoercion,
  1688. value = 0;
  1689. if (coercedNumber !== 0 && isFinite(coercedNumber)) {
  1690. if (coercedNumber >= 0) {
  1691. value = Math.floor(coercedNumber);
  1692. } else {
  1693. value = Math.ceil(coercedNumber);
  1694. }
  1695. }
  1696. return value;
  1697. }
  1698. function daysInMonth(year, month) {
  1699. return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
  1700. }
  1701. function daysInYear(year) {
  1702. return isLeapYear(year) ? 366 : 365;
  1703. }
  1704. function isLeapYear(year) {
  1705. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  1706. }
  1707. function checkOverflow(m) {
  1708. var overflow;
  1709. if (m._a && m._pf.overflow === -2) {
  1710. overflow =
  1711. m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH :
  1712. m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE :
  1713. m._a[HOUR] < 0 || m._a[HOUR] > 23 ? HOUR :
  1714. m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE :
  1715. m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND :
  1716. m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND :
  1717. -1;
  1718. if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
  1719. overflow = DATE;
  1720. }
  1721. m._pf.overflow = overflow;
  1722. }
  1723. }
  1724. function initializeParsingFlags(config) {
  1725. config._pf = {
  1726. empty : false,
  1727. unusedTokens : [],
  1728. unusedInput : [],
  1729. overflow : -2,
  1730. charsLeftOver : 0,
  1731. nullInput : false,
  1732. invalidMonth : null,
  1733. invalidFormat : false,
  1734. userInvalidated : false,
  1735. iso: false
  1736. };
  1737. }
  1738. function isValid(m) {
  1739. if (m._isValid == null) {
  1740. m._isValid = !isNaN(m._d.getTime()) &&
  1741. m._pf.overflow < 0 &&
  1742. !m._pf.empty &&
  1743. !m._pf.invalidMonth &&
  1744. !m._pf.nullInput &&
  1745. !m._pf.invalidFormat &&
  1746. !m._pf.userInvalidated;
  1747. if (m._strict) {
  1748. m._isValid = m._isValid &&
  1749. m._pf.charsLeftOver === 0 &&
  1750. m._pf.unusedTokens.length === 0;
  1751. }
  1752. }
  1753. return m._isValid;
  1754. }
  1755. function normalizeLanguage(key) {
  1756. return key ? key.toLowerCase().replace('_', '-') : key;
  1757. }
  1758. // Return a moment from input, that is local/utc/zone equivalent to model.
  1759. function makeAs(input, model) {
  1760. return model._isUTC ? moment(input).zone(model._offset || 0) :
  1761. moment(input).local();
  1762. }
  1763. /************************************
  1764. Languages
  1765. ************************************/
  1766. extend(Language.prototype, {
  1767. set : function (config) {
  1768. var prop, i;
  1769. for (i in config) {
  1770. prop = config[i];
  1771. if (typeof prop === 'function') {
  1772. this[i] = prop;
  1773. } else {
  1774. this['_' + i] = prop;
  1775. }
  1776. }
  1777. },
  1778. _months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
  1779. months : function (m) {
  1780. return this._months[m.month()];
  1781. },
  1782. _monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),
  1783. monthsShort : function (m) {
  1784. return this._monthsShort[m.month()];
  1785. },
  1786. monthsParse : function (monthName) {
  1787. var i, mom, regex;
  1788. if (!this._monthsParse) {
  1789. this._monthsParse = [];
  1790. }
  1791. for (i = 0; i < 12; i++) {
  1792. // make the regex if we don't have it already
  1793. if (!this._monthsParse[i]) {
  1794. mom = moment.utc([2000, i]);
  1795. regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  1796. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  1797. }
  1798. // test the regex
  1799. if (this._monthsParse[i].test(monthName)) {
  1800. return i;
  1801. }
  1802. }
  1803. },
  1804. _weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
  1805. weekdays : function (m) {
  1806. return this._weekdays[m.day()];
  1807. },
  1808. _weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),
  1809. weekdaysShort : function (m) {
  1810. return this._weekdaysShort[m.day()];
  1811. },
  1812. _weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"),
  1813. weekdaysMin : function (m) {
  1814. return this._weekdaysMin[m.day()];
  1815. },
  1816. weekdaysParse : function (weekdayName) {
  1817. var i, mom, regex;
  1818. if (!this._weekdaysParse) {
  1819. this._weekdaysParse = [];
  1820. }
  1821. for (i = 0; i < 7; i++) {
  1822. // make the regex if we don't have it already
  1823. if (!this._weekdaysParse[i]) {
  1824. mom = moment([2000, 1]).day(i);
  1825. regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
  1826. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  1827. }
  1828. // test the regex
  1829. if (this._weekdaysParse[i].test(weekdayName)) {
  1830. return i;
  1831. }
  1832. }
  1833. },
  1834. _longDateFormat : {
  1835. LT : "h:mm A",
  1836. L : "MM/DD/YYYY",
  1837. LL : "MMMM D YYYY",
  1838. LLL : "MMMM D YYYY LT",
  1839. LLLL : "dddd, MMMM D YYYY LT"
  1840. },
  1841. longDateFormat : function (key) {
  1842. var output = this._longDateFormat[key];
  1843. if (!output && this._longDateFormat[key.toUpperCase()]) {
  1844. output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) {
  1845. return val.slice(1);
  1846. });
  1847. this._longDateFormat[key] = output;
  1848. }
  1849. return output;
  1850. },
  1851. isPM : function (input) {
  1852. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  1853. // Using charAt should be more compatible.
  1854. return ((input + '').toLowerCase().charAt(0) === 'p');
  1855. },
  1856. _meridiemParse : /[ap]\.?m?\.?/i,
  1857. meridiem : function (hours, minutes, isLower) {
  1858. if (hours > 11) {
  1859. return isLower ? 'pm' : 'PM';
  1860. } else {
  1861. return isLower ? 'am' : 'AM';
  1862. }
  1863. },
  1864. _calendar : {
  1865. sameDay : '[Today at] LT',
  1866. nextDay : '[Tomorrow at] LT',
  1867. nextWeek : 'dddd [at] LT',
  1868. lastDay : '[Yesterday at] LT',
  1869. lastWeek : '[Last] dddd [at] LT',
  1870. sameElse : 'L'
  1871. },
  1872. calendar : function (key, mom) {
  1873. var output = this._calendar[key];
  1874. return typeof output === 'function' ? output.apply(mom) : output;
  1875. },
  1876. _relativeTime : {
  1877. future : "in %s",
  1878. past : "%s ago",
  1879. s : "a few seconds",
  1880. m : "a minute",
  1881. mm : "%d minutes",
  1882. h : "an hour",
  1883. hh : "%d hours",
  1884. d : "a day",
  1885. dd : "%d days",
  1886. M : "a month",
  1887. MM : "%d months",
  1888. y : "a year",
  1889. yy : "%d years"
  1890. },
  1891. relativeTime : function (number, withoutSuffix, string, isFuture) {
  1892. var output = this._relativeTime[string];
  1893. return (typeof output === 'function') ?
  1894. output(number, withoutSuffix, string, isFuture) :
  1895. output.replace(/%d/i, number);
  1896. },
  1897. pastFuture : function (diff, output) {
  1898. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  1899. return typeof format === 'function' ? format(output) : format.replace(/%s/i, output);
  1900. },
  1901. ordinal : function (number) {
  1902. return this._ordinal.replace("%d", number);
  1903. },
  1904. _ordinal : "%d",
  1905. preparse : function (string) {
  1906. return string;
  1907. },
  1908. postformat : function (string) {
  1909. return string;
  1910. },
  1911. week : function (mom) {
  1912. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  1913. },
  1914. _week : {
  1915. dow : 0, // Sunday is the first day of the week.
  1916. doy : 6 // The week that contains Jan 1st is the first week of the year.
  1917. },
  1918. _invalidDate: 'Invalid date',
  1919. invalidDate: function () {
  1920. return this._invalidDate;
  1921. }
  1922. });
  1923. // Loads a language definition into the `languages` cache. The function
  1924. // takes a key and optionally values. If not in the browser and no values
  1925. // are provided, it will load the language file module. As a convenience,
  1926. // this function also returns the language values.
  1927. function loadLang(key, values) {
  1928. values.abbr = key;
  1929. if (!languages[key]) {
  1930. languages[key] = new Language();
  1931. }
  1932. languages[key].set(values);
  1933. return languages[key];
  1934. }
  1935. // Remove a language from the `languages` cache. Mostly useful in tests.
  1936. function unloadLang(key) {
  1937. delete languages[key];
  1938. }
  1939. // Determines which language definition to use and returns it.
  1940. //
  1941. // With no parameters, it will return the global language. If you
  1942. // pass in a language key, such as 'en', it will return the
  1943. // definition for 'en', so long as 'en' has already been loaded using
  1944. // moment.lang.
  1945. function getLangDefinition(key) {
  1946. var i = 0, j, lang, next, split,
  1947. get = function (k) {
  1948. if (!languages[k] && hasModule) {
  1949. try {
  1950. require('./lang/' + k);
  1951. } catch (e) { }
  1952. }
  1953. return languages[k];
  1954. };
  1955. if (!key) {
  1956. return moment.fn._lang;
  1957. }
  1958. if (!isArray(key)) {
  1959. //short-circuit everything else
  1960. lang = get(key);
  1961. if (lang) {
  1962. return lang;
  1963. }
  1964. key = [key];
  1965. }
  1966. //pick the language from the array
  1967. //try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
  1968. //substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
  1969. while (i < key.length) {
  1970. split = normalizeLanguage(key[i]).split('-');
  1971. j = split.length;
  1972. next = normalizeLanguage(key[i + 1]);
  1973. next = next ? next.split('-') : null;
  1974. while (j > 0) {
  1975. lang = get(split.slice(0, j).join('-'));
  1976. if (lang) {
  1977. return lang;
  1978. }
  1979. if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
  1980. //the next array item is better than a shallower substring of this one
  1981. break;
  1982. }
  1983. j--;
  1984. }
  1985. i++;
  1986. }
  1987. return moment.fn._lang;
  1988. }
  1989. /************************************
  1990. Formatting
  1991. ************************************/
  1992. function removeFormattingTokens(input) {
  1993. if (input.match(/\[[\s\S]/)) {
  1994. return input.replace(/^\[|\]$/g, "");
  1995. }
  1996. return input.replace(/\\/g, "");
  1997. }
  1998. function makeFormatFunction(format) {
  1999. var array = format.match(formattingTokens), i, length;
  2000. for (i = 0, length = array.length; i < length; i++) {
  2001. if (formatTokenFunctions[array[i]]) {
  2002. array[i] = formatTokenFunctions[array[i]];
  2003. } else {
  2004. array[i] = removeFormattingTokens(array[i]);
  2005. }
  2006. }
  2007. return function (mom) {
  2008. var output = "";
  2009. for (i = 0; i < length; i++) {
  2010. output += array[i] instanceof Function ? array[i].call(mom, format) : array[i];
  2011. }
  2012. return output;
  2013. };
  2014. }
  2015. // format date using native date object
  2016. function formatMoment(m, format) {
  2017. if (!m.isValid()) {
  2018. return m.lang().invalidDate();
  2019. }
  2020. format = expandFormat(format, m.lang());
  2021. if (!formatFunctions[format]) {
  2022. formatFunctions[format] = makeFormatFunction(format);
  2023. }
  2024. return formatFunctions[format](m);
  2025. }
  2026. function expandFormat(format, lang) {
  2027. var i = 5;
  2028. function replaceLongDateFormatTokens(input) {
  2029. return lang.longDateFormat(input) || input;
  2030. }
  2031. localFormattingTokens.lastIndex = 0;
  2032. while (i >= 0 && localFormattingTokens.test(format)) {
  2033. format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
  2034. localFormattingTokens.lastIndex = 0;
  2035. i -= 1;
  2036. }
  2037. return format;
  2038. }
  2039. /************************************
  2040. Parsing
  2041. ************************************/
  2042. // get the regex to find the next token
  2043. function getParseRegexForToken(token, config) {
  2044. var a, strict = config._strict;
  2045. switch (token) {
  2046. case 'DDDD':
  2047. return parseTokenThreeDigits;
  2048. case 'YYYY':
  2049. case 'GGGG':
  2050. case 'gggg':
  2051. return strict ? parseTokenFourDigits : parseTokenOneToFourDigits;
  2052. case 'YYYYYY':
  2053. case 'YYYYY':
  2054. case 'GGGGG':
  2055. case 'ggggg':
  2056. return strict ? parseTokenSixDigits : parseTokenOneToSixDigits;
  2057. case 'S':
  2058. if (strict) { return parseTokenOneDigit; }
  2059. /* falls through */
  2060. case 'SS':
  2061. if (strict) { return parseTokenTwoDigits; }
  2062. /* falls through */
  2063. case 'SSS':
  2064. case 'DDD':
  2065. return strict ? parseTokenThreeDigits : parseTokenOneToThreeDigits;
  2066. case 'MMM':
  2067. case 'MMMM':
  2068. case 'dd':
  2069. case 'ddd':
  2070. case 'dddd':
  2071. return parseTokenWord;
  2072. case 'a':
  2073. case 'A':
  2074. return getLangDefinition(config._l)._meridiemParse;
  2075. case 'X':
  2076. return parseTokenTimestampMs;
  2077. case 'Z':
  2078. case 'ZZ':
  2079. return parseTokenTimezone;
  2080. case 'T':
  2081. return parseTokenT;
  2082. case 'SSSS':
  2083. return parseTokenDigits;
  2084. case 'MM':
  2085. case 'DD':
  2086. case 'YY':
  2087. case 'GG':
  2088. case 'gg':
  2089. case 'HH':
  2090. case 'hh':
  2091. case 'mm':
  2092. case 'ss':
  2093. case 'ww':
  2094. case 'WW':
  2095. return strict ? parseTokenTwoDigits : parseTokenOneOrTwoDigits;
  2096. case 'M':
  2097. case 'D':
  2098. case 'd':
  2099. case 'H':
  2100. case 'h':
  2101. case 'm':
  2102. case 's':
  2103. case 'w':
  2104. case 'W':
  2105. case 'e':
  2106. case 'E':
  2107. return strict ? parseTokenOneDigit : parseTokenOneOrTwoDigits;
  2108. default :
  2109. a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), "i"));
  2110. return a;
  2111. }
  2112. }
  2113. function timezoneMinutesFromString(string) {
  2114. string = string || "";
  2115. var possibleTzMatches = (string.match(parseTokenTimezone) || []),
  2116. tzChunk = possibleTzMatches[possibleTzMatches.length - 1] || [],
  2117. parts = (tzChunk + '').match(parseTimezoneChunker) || ['-', 0, 0],
  2118. minutes = +(parts[1] * 60) + toInt(parts[2]);
  2119. return parts[0] === '+' ? -minutes : minutes;
  2120. }
  2121. // function to convert string input to date
  2122. function addTimeToArrayFromToken(token, input, config) {
  2123. var a, datePartArray = config._a;
  2124. switch (token) {
  2125. // MONTH
  2126. case 'M' : // fall through to MM
  2127. case 'MM' :
  2128. if (input != null) {
  2129. datePartArray[MONTH] = toInt(input) - 1;
  2130. }
  2131. break;
  2132. case 'MMM' : // fall through to MMMM
  2133. case 'MMMM' :
  2134. a = getLangDefinition(config._l).monthsParse(input);
  2135. // if we didn't find a month name, mark the date as invalid.
  2136. if (a != null) {
  2137. datePartArray[MONTH] = a;
  2138. } else {
  2139. config._pf.invalidMonth = input;
  2140. }
  2141. break;
  2142. // DAY OF MONTH
  2143. case 'D' : // fall through to DD
  2144. case 'DD' :
  2145. if (input != null) {
  2146. datePartArray[DATE] = toInt(input);
  2147. }
  2148. break;
  2149. // DAY OF YEAR
  2150. case 'DDD' : // fall through to DDDD
  2151. case 'DDDD' :
  2152. if (input != null) {
  2153. config._dayOfYear = toInt(input);
  2154. }
  2155. break;
  2156. // YEAR
  2157. case 'YY' :
  2158. datePartArray[YEAR] = toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
  2159. break;
  2160. case 'YYYY' :
  2161. case 'YYYYY' :
  2162. case 'YYYYYY' :
  2163. datePartArray[YEAR] = toInt(input);
  2164. break;
  2165. // AM / PM
  2166. case 'a' : // fall through to A
  2167. case 'A' :
  2168. config._isPm = getLangDefinition(config._l).isPM(input);
  2169. break;
  2170. // 24 HOUR
  2171. case 'H' : // fall through to hh
  2172. case 'HH' : // fall through to hh
  2173. case 'h' : // fall through to hh
  2174. case 'hh' :
  2175. datePartArray[HOUR] = toInt(input);
  2176. break;
  2177. // MINUTE
  2178. case 'm' : // fall through to mm
  2179. case 'mm' :
  2180. datePartArray[MINUTE] = toInt(input);
  2181. break;
  2182. // SECOND
  2183. case 's' : // fall through to ss
  2184. case 'ss' :
  2185. datePartArray[SECOND] = toInt(input);
  2186. break;
  2187. // MILLISECOND
  2188. case 'S' :
  2189. case 'SS' :
  2190. case 'SSS' :
  2191. case 'SSSS' :
  2192. datePartArray[MILLISECOND] = toInt(('0.' + input) * 1000);
  2193. break;
  2194. // UNIX TIMESTAMP WITH MS
  2195. case 'X':
  2196. config._d = new Date(parseFloat(input) * 1000);
  2197. break;
  2198. // TIMEZONE
  2199. case 'Z' : // fall through to ZZ
  2200. case 'ZZ' :
  2201. config._useUTC = true;
  2202. config._tzm = timezoneMinutesFromString(input);
  2203. break;
  2204. case 'w':
  2205. case 'ww':
  2206. case 'W':
  2207. case 'WW':
  2208. case 'd':
  2209. case 'dd':
  2210. case 'ddd':
  2211. case 'dddd':
  2212. case 'e':
  2213. case 'E':
  2214. token = token.substr(0, 1);
  2215. /* falls through */
  2216. case 'gg':
  2217. case 'gggg':
  2218. case 'GG':
  2219. case 'GGGG':
  2220. case 'GGGGG':
  2221. token = token.substr(0, 2);
  2222. if (input) {
  2223. config._w = config._w || {};
  2224. config._w[token] = input;
  2225. }
  2226. break;
  2227. }
  2228. }
  2229. // convert an array to a date.
  2230. // the array should mirror the parameters below
  2231. // note: all values past the year are optional and will default to the lowest possible value.
  2232. // [year, month, day , hour, minute, second, millisecond]
  2233. function dateFromConfig(config) {
  2234. var i, date, input = [], currentDate,
  2235. yearToUse, fixYear, w, temp, lang, weekday, week;
  2236. if (config._d) {
  2237. return;
  2238. }
  2239. currentDate = currentDateArray(config);
  2240. //compute day of the year from weeks and weekdays
  2241. if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
  2242. fixYear = function (val) {
  2243. var int_val = parseInt(val, 10);
  2244. return val ?
  2245. (val.length < 3 ? (int_val > 68 ? 1900 + int_val : 2000 + int_val) : int_val) :
  2246. (config._a[YEAR] == null ? moment().weekYear() : config._a[YEAR]);
  2247. };
  2248. w = config._w;
  2249. if (w.GG != null || w.W != null || w.E != null) {
  2250. temp = dayOfYearFromWeeks(fixYear(w.GG), w.W || 1, w.E, 4, 1);
  2251. }
  2252. else {
  2253. lang = getLangDefinition(config._l);
  2254. weekday = w.d != null ? parseWeekday(w.d, lang) :
  2255. (w.e != null ? parseInt(w.e, 10) + lang._week.dow : 0);
  2256. week = parseInt(w.w, 10) || 1;
  2257. //if we're parsing 'd', then the low day numbers may be next week
  2258. if (w.d != null && weekday < lang._week.dow) {
  2259. week++;
  2260. }
  2261. temp = dayOfYearFromWeeks(fixYear(w.gg), week, weekday, lang._week.doy, lang._week.dow);
  2262. }
  2263. config._a[YEAR] = temp.year;
  2264. config._dayOfYear = temp.dayOfYear;
  2265. }
  2266. //if the day of the year is set, figure out what it is
  2267. if (config._dayOfYear) {
  2268. yearToUse = config._a[YEAR] == null ? currentDate[YEAR] : config._a[YEAR];
  2269. if (config._dayOfYear > daysInYear(yearToUse)) {
  2270. config._pf._overflowDayOfYear = true;
  2271. }
  2272. date = makeUTCDate(yearToUse, 0, config._dayOfYear);
  2273. config._a[MONTH] = date.getUTCMonth();
  2274. config._a[DATE] = date.getUTCDate();
  2275. }
  2276. // Default to current date.
  2277. // * if no year, month, day of month are given, default to today
  2278. // * if day of month is given, default month and year
  2279. // * if month is given, default only year
  2280. // * if year is given, don't default anything
  2281. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  2282. config._a[i] = input[i] = currentDate[i];
  2283. }
  2284. // Zero out whatever was not defaulted, including time
  2285. for (; i < 7; i++) {
  2286. config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
  2287. }
  2288. // add the offsets to the time to be parsed so that we can have a clean array for checking isValid
  2289. input[HOUR] += toInt((config._tzm || 0) / 60);
  2290. input[MINUTE] += toInt((config._tzm || 0) % 60);
  2291. config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input);
  2292. }
  2293. function dateFromObject(config) {
  2294. var normalizedInput;
  2295. if (config._d) {
  2296. return;
  2297. }
  2298. normalizedInput = normalizeObjectUnits(config._i);
  2299. config._a = [
  2300. normalizedInput.year,
  2301. normalizedInput.month,
  2302. normalizedInput.day,
  2303. normalizedInput.hour,
  2304. normalizedInput.minute,
  2305. normalizedInput.second,
  2306. normalizedInput.millisecond
  2307. ];
  2308. dateFromConfig(config);
  2309. }
  2310. function currentDateArray(config) {
  2311. var now = new Date();
  2312. if (config._useUTC) {
  2313. return [
  2314. now.getUTCFullYear(),
  2315. now.getUTCMonth(),
  2316. now.getUTCDate()
  2317. ];
  2318. } else {
  2319. return [now.getFullYear(), now.getMonth(), now.getDate()];
  2320. }
  2321. }
  2322. // date from string and format string
  2323. function makeDateFromStringAndFormat(config) {
  2324. config._a = [];
  2325. config._pf.empty = true;
  2326. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  2327. var lang = getLangDefinition(config._l),
  2328. string = '' + config._i,
  2329. i, parsedInput, tokens, token, skipped,
  2330. stringLength = string.length,
  2331. totalParsedInputLength = 0;
  2332. tokens = expandFormat(config._f, lang).match(formattingTokens) || [];
  2333. for (i = 0; i < tokens.length; i++) {
  2334. token = tokens[i];
  2335. parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
  2336. if (parsedInput) {
  2337. skipped = string.substr(0, string.indexOf(parsedInput));
  2338. if (skipped.length > 0) {
  2339. config._pf.unusedInput.push(skipped);
  2340. }
  2341. string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
  2342. totalParsedInputLength += parsedInput.length;
  2343. }
  2344. // don't parse if it's not a known token
  2345. if (formatTokenFunctions[token]) {
  2346. if (parsedInput) {
  2347. config._pf.empty = false;
  2348. }
  2349. else {
  2350. config._pf.unusedTokens.push(token);
  2351. }
  2352. addTimeToArrayFromToken(token, parsedInput, config);
  2353. }
  2354. else if (config._strict && !parsedInput) {
  2355. config._pf.unusedTokens.push(token);
  2356. }
  2357. }
  2358. // add remaining unparsed input length to the string
  2359. config._pf.charsLeftOver = stringLength - totalParsedInputLength;
  2360. if (string.length > 0) {
  2361. config._pf.unusedInput.push(string);
  2362. }
  2363. // handle am pm
  2364. if (config._isPm && config._a[HOUR] < 12) {
  2365. config._a[HOUR] += 12;
  2366. }
  2367. // if is 12 am, change hours to 0
  2368. if (config._isPm === false && config._a[HOUR] === 12) {
  2369. config._a[HOUR] = 0;
  2370. }
  2371. dateFromConfig(config);
  2372. checkOverflow(config);
  2373. }
  2374. function unescapeFormat(s) {
  2375. return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
  2376. return p1 || p2 || p3 || p4;
  2377. });
  2378. }
  2379. // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  2380. function regexpEscape(s) {
  2381. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  2382. }
  2383. // date from string and array of format strings
  2384. function makeDateFromStringAndArray(config) {
  2385. var tempConfig,
  2386. bestMoment,
  2387. scoreToBeat,
  2388. i,
  2389. currentScore;
  2390. if (config._f.length === 0) {
  2391. config._pf.invalidFormat = true;
  2392. config._d = new Date(NaN);
  2393. return;
  2394. }
  2395. for (i = 0; i < config._f.length; i++) {
  2396. currentScore = 0;
  2397. tempConfig = extend({}, config);
  2398. initializeParsingFlags(tempConfig);
  2399. tempConfig._f = config._f[i];
  2400. makeDateFromStringAndFormat(tempConfig);
  2401. if (!isValid(tempConfig)) {
  2402. continue;
  2403. }
  2404. // if there is any input that was not parsed add a penalty for that format
  2405. currentScore += tempConfig._pf.charsLeftOver;
  2406. //or tokens
  2407. currentScore += tempConfig._pf.unusedTokens.length * 10;
  2408. tempConfig._pf.score = currentScore;
  2409. if (scoreToBeat == null || currentScore < scoreToBeat) {
  2410. scoreToBeat = currentScore;
  2411. bestMoment = tempConfig;
  2412. }
  2413. }
  2414. extend(config, bestMoment || tempConfig);
  2415. }
  2416. // date from iso format
  2417. function makeDateFromString(config) {
  2418. var i,
  2419. string = config._i,
  2420. match = isoRegex.exec(string);
  2421. if (match) {
  2422. config._pf.iso = true;
  2423. for (i = 4; i > 0; i--) {
  2424. if (match[i]) {
  2425. // match[5] should be "T" or undefined
  2426. config._f = isoDates[i - 1] + (match[6] || " ");
  2427. break;
  2428. }
  2429. }
  2430. for (i = 0; i < 4; i++) {
  2431. if (isoTimes[i][1].exec(string)) {
  2432. config._f += isoTimes[i][0];
  2433. break;
  2434. }
  2435. }
  2436. if (string.match(parseTokenTimezone)) {
  2437. config._f += "Z";
  2438. }
  2439. makeDateFromStringAndFormat(config);
  2440. }
  2441. else {
  2442. config._d = new Date(string);
  2443. }
  2444. }
  2445. function makeDateFromInput(config) {
  2446. var input = config._i,
  2447. matched = aspNetJsonRegex.exec(input);
  2448. if (input === undefined) {
  2449. config._d = new Date();
  2450. } else if (matched) {
  2451. config._d = new Date(+matched[1]);
  2452. } else if (typeof input === 'string') {
  2453. makeDateFromString(config);
  2454. } else if (isArray(input)) {
  2455. config._a = input.slice(0);
  2456. dateFromConfig(config);
  2457. } else if (isDate(input)) {
  2458. config._d = new Date(+input);
  2459. } else if (typeof(input) === 'object') {
  2460. dateFromObject(config);
  2461. } else {
  2462. config._d = new Date(input);
  2463. }
  2464. }
  2465. function makeDate(y, m, d, h, M, s, ms) {
  2466. //can't just apply() to create a date:
  2467. //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply
  2468. var date = new Date(y, m, d, h, M, s, ms);
  2469. //the date constructor doesn't accept years < 1970
  2470. if (y < 1970) {
  2471. date.setFullYear(y);
  2472. }
  2473. return date;
  2474. }
  2475. function makeUTCDate(y) {
  2476. var date = new Date(Date.UTC.apply(null, arguments));
  2477. if (y < 1970) {
  2478. date.setUTCFullYear(y);
  2479. }
  2480. return date;
  2481. }
  2482. function parseWeekday(input, language) {
  2483. if (typeof input === 'string') {
  2484. if (!isNaN(input)) {
  2485. input = parseInt(input, 10);
  2486. }
  2487. else {
  2488. input = language.weekdaysParse(input);
  2489. if (typeof input !== 'number') {
  2490. return null;
  2491. }
  2492. }
  2493. }
  2494. return input;
  2495. }
  2496. /************************************
  2497. Relative Time
  2498. ************************************/
  2499. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  2500. function substituteTimeAgo(string, number, withoutSuffix, isFuture, lang) {
  2501. return lang.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  2502. }
  2503. function relativeTime(milliseconds, withoutSuffix, lang) {
  2504. var seconds = round(Math.abs(milliseconds) / 1000),
  2505. minutes = round(seconds / 60),
  2506. hours = round(minutes / 60),
  2507. days = round(hours / 24),
  2508. years = round(days / 365),
  2509. args = seconds < 45 && ['s', seconds] ||
  2510. minutes === 1 && ['m'] ||
  2511. minutes < 45 && ['mm', minutes] ||
  2512. hours === 1 && ['h'] ||
  2513. hours < 22 && ['hh', hours] ||
  2514. days === 1 && ['d'] ||
  2515. days <= 25 && ['dd', days] ||
  2516. days <= 45 && ['M'] ||
  2517. days < 345 && ['MM', round(days / 30)] ||
  2518. years === 1 && ['y'] || ['yy', years];
  2519. args[2] = withoutSuffix;
  2520. args[3] = milliseconds > 0;
  2521. args[4] = lang;
  2522. return substituteTimeAgo.apply({}, args);
  2523. }
  2524. /************************************
  2525. Week of Year
  2526. ************************************/
  2527. // firstDayOfWeek 0 = sun, 6 = sat
  2528. // the day of the week that starts the week
  2529. // (usually sunday or monday)
  2530. // firstDayOfWeekOfYear 0 = sun, 6 = sat
  2531. // the first week is the week that contains the first
  2532. // of this day of the week
  2533. // (eg. ISO weeks use thursday (4))
  2534. function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) {
  2535. var end = firstDayOfWeekOfYear - firstDayOfWeek,
  2536. daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(),
  2537. adjustedMoment;
  2538. if (daysToDayOfWeek > end) {
  2539. daysToDayOfWeek -= 7;
  2540. }
  2541. if (daysToDayOfWeek < end - 7) {
  2542. daysToDayOfWeek += 7;
  2543. }
  2544. adjustedMoment = moment(mom).add('d', daysToDayOfWeek);
  2545. return {
  2546. week: Math.ceil(adjustedMoment.dayOfYear() / 7),
  2547. year: adjustedMoment.year()
  2548. };
  2549. }
  2550. //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
  2551. function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) {
  2552. // The only solid way to create an iso date from year is to use
  2553. // a string format (Date.UTC handles only years > 1900). Don't ask why
  2554. // it doesn't need Z at the end.
  2555. var d = new Date(leftZeroFill(year, 6, true) + '-01-01').getUTCDay(),
  2556. daysToAdd, dayOfYear;
  2557. weekday = weekday != null ? weekday : firstDayOfWeek;
  2558. daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0);
  2559. dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1;
  2560. return {
  2561. year: dayOfYear > 0 ? year : year - 1,
  2562. dayOfYear: dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear
  2563. };
  2564. }
  2565. /************************************
  2566. Top Level Functions
  2567. ************************************/
  2568. function makeMoment(config) {
  2569. var input = config._i,
  2570. format = config._f;
  2571. if (typeof config._pf === 'undefined') {
  2572. initializeParsingFlags(config);
  2573. }
  2574. if (input === null) {
  2575. return moment.invalid({nullInput: true});
  2576. }
  2577. if (typeof input === 'string') {
  2578. config._i = input = getLangDefinition().preparse(input);
  2579. }
  2580. if (moment.isMoment(input)) {
  2581. config = extend({}, input);
  2582. config._d = new Date(+input._d);
  2583. } else if (format) {
  2584. if (isArray(format)) {
  2585. makeDateFromStringAndArray(config);
  2586. } else {
  2587. makeDateFromStringAndFormat(config);
  2588. }
  2589. } else {
  2590. makeDateFromInput(config);
  2591. }
  2592. return new Moment(config);
  2593. }
  2594. moment = function (input, format, lang, strict) {
  2595. if (typeof(lang) === "boolean") {
  2596. strict = lang;
  2597. lang = undefined;
  2598. }
  2599. return makeMoment({
  2600. _i : input,
  2601. _f : format,
  2602. _l : lang,
  2603. _strict : strict,
  2604. _isUTC : false
  2605. });
  2606. };
  2607. // creating with utc
  2608. moment.utc = function (input, format, lang, strict) {
  2609. var m;
  2610. if (typeof(lang) === "boolean") {
  2611. strict = lang;
  2612. lang = undefined;
  2613. }
  2614. m = makeMoment({
  2615. _useUTC : true,
  2616. _isUTC : true,
  2617. _l : lang,
  2618. _i : input,
  2619. _f : format,
  2620. _strict : strict
  2621. }).utc();
  2622. return m;
  2623. };
  2624. // creating with unix timestamp (in seconds)
  2625. moment.unix = function (input) {
  2626. return moment(input * 1000);
  2627. };
  2628. // duration
  2629. moment.duration = function (input, key) {
  2630. var duration = input,
  2631. // matching against regexp is expensive, do it on demand
  2632. match = null,
  2633. sign,
  2634. ret,
  2635. parseIso;
  2636. if (moment.isDuration(input)) {
  2637. duration = {
  2638. ms: input._milliseconds,
  2639. d: input._days,
  2640. M: input._months
  2641. };
  2642. } else if (typeof input === 'number') {
  2643. duration = {};
  2644. if (key) {
  2645. duration[key] = input;
  2646. } else {
  2647. duration.milliseconds = input;
  2648. }
  2649. } else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) {
  2650. sign = (match[1] === "-") ? -1 : 1;
  2651. duration = {
  2652. y: 0,
  2653. d: toInt(match[DATE]) * sign,
  2654. h: toInt(match[HOUR]) * sign,
  2655. m: toInt(match[MINUTE]) * sign,
  2656. s: toInt(match[SECOND]) * sign,
  2657. ms: toInt(match[MILLISECOND]) * sign
  2658. };
  2659. } else if (!!(match = isoDurationRegex.exec(input))) {
  2660. sign = (match[1] === "-") ? -1 : 1;
  2661. parseIso = function (inp) {
  2662. // We'd normally use ~~inp for this, but unfortunately it also
  2663. // converts floats to ints.
  2664. // inp may be undefined, so careful calling replace on it.
  2665. var res = inp && parseFloat(inp.replace(',', '.'));
  2666. // apply sign while we're at it
  2667. return (isNaN(res) ? 0 : res) * sign;
  2668. };
  2669. duration = {
  2670. y: parseIso(match[2]),
  2671. M: parseIso(match[3]),
  2672. d: parseIso(match[4]),
  2673. h: parseIso(match[5]),
  2674. m: parseIso(match[6]),
  2675. s: parseIso(match[7]),
  2676. w: parseIso(match[8])
  2677. };
  2678. }
  2679. ret = new Duration(duration);
  2680. if (moment.isDuration(input) && input.hasOwnProperty('_lang')) {
  2681. ret._lang = input._lang;
  2682. }
  2683. return ret;
  2684. };
  2685. // version number
  2686. moment.version = VERSION;
  2687. // default format
  2688. moment.defaultFormat = isoFormat;
  2689. // This function will be called whenever a moment is mutated.
  2690. // It is intended to keep the offset in sync with the timezone.
  2691. moment.updateOffset = function () {};
  2692. // This function will load languages and then set the global language. If
  2693. // no arguments are passed in, it will simply return the current global
  2694. // language key.
  2695. moment.lang = function (key, values) {
  2696. var r;
  2697. if (!key) {
  2698. return moment.fn._lang._abbr;
  2699. }
  2700. if (values) {
  2701. loadLang(normalizeLanguage(key), values);
  2702. } else if (values === null) {
  2703. unloadLang(key);
  2704. key = 'en';
  2705. } else if (!languages[key]) {
  2706. getLangDefinition(key);
  2707. }
  2708. r = moment.duration.fn._lang = moment.fn._lang = getLangDefinition(key);
  2709. return r._abbr;
  2710. };
  2711. // returns language data
  2712. moment.langData = function (key) {
  2713. if (key && key._lang && key._lang._abbr) {
  2714. key = key._lang._abbr;
  2715. }
  2716. return getLangDefinition(key);
  2717. };
  2718. // compare moment object
  2719. moment.isMoment = function (obj) {
  2720. return obj instanceof Moment;
  2721. };
  2722. // for typechecking Duration objects
  2723. moment.isDuration = function (obj) {
  2724. return obj instanceof Duration;
  2725. };
  2726. for (i = lists.length - 1; i >= 0; --i) {
  2727. makeList(lists[i]);
  2728. }
  2729. moment.normalizeUnits = function (units) {
  2730. return normalizeUnits(units);
  2731. };
  2732. moment.invalid = function (flags) {
  2733. var m = moment.utc(NaN);
  2734. if (flags != null) {
  2735. extend(m._pf, flags);
  2736. }
  2737. else {
  2738. m._pf.userInvalidated = true;
  2739. }
  2740. return m;
  2741. };
  2742. moment.parseZone = function (input) {
  2743. return moment(input).parseZone();
  2744. };
  2745. /************************************
  2746. Moment Prototype
  2747. ************************************/
  2748. extend(moment.fn = Moment.prototype, {
  2749. clone : function () {
  2750. return moment(this);
  2751. },
  2752. valueOf : function () {
  2753. return +this._d + ((this._offset || 0) * 60000);
  2754. },
  2755. unix : function () {
  2756. return Math.floor(+this / 1000);
  2757. },
  2758. toString : function () {
  2759. return this.clone().lang('en').format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ");
  2760. },
  2761. toDate : function () {
  2762. return this._offset ? new Date(+this) : this._d;
  2763. },
  2764. toISOString : function () {
  2765. var m = moment(this).utc();
  2766. if (0 < m.year() && m.year() <= 9999) {
  2767. return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  2768. } else {
  2769. return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  2770. }
  2771. },
  2772. toArray : function () {
  2773. var m = this;
  2774. return [
  2775. m.year(),
  2776. m.month(),
  2777. m.date(),
  2778. m.hours(),
  2779. m.minutes(),
  2780. m.seconds(),
  2781. m.milliseconds()
  2782. ];
  2783. },
  2784. isValid : function () {
  2785. return isValid(this);
  2786. },
  2787. isDSTShifted : function () {
  2788. if (this._a) {
  2789. return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0;
  2790. }
  2791. return false;
  2792. },
  2793. parsingFlags : function () {
  2794. return extend({}, this._pf);
  2795. },
  2796. invalidAt: function () {
  2797. return this._pf.overflow;
  2798. },
  2799. utc : function () {
  2800. return this.zone(0);
  2801. },
  2802. local : function () {
  2803. this.zone(0);
  2804. this._isUTC = false;
  2805. return this;
  2806. },
  2807. format : function (inputString) {
  2808. var output = formatMoment(this, inputString || moment.defaultFormat);
  2809. return this.lang().postformat(output);
  2810. },
  2811. add : function (input, val) {
  2812. var dur;
  2813. // switch args to support add('s', 1) and add(1, 's')
  2814. if (typeof input === 'string') {
  2815. dur = moment.duration(+val, input);
  2816. } else {
  2817. dur = moment.duration(input, val);
  2818. }
  2819. addOrSubtractDurationFromMoment(this, dur, 1);
  2820. return this;
  2821. },
  2822. subtract : function (input, val) {
  2823. var dur;
  2824. // switch args to support subtract('s', 1) and subtract(1, 's')
  2825. if (typeof input === 'string') {
  2826. dur = moment.duration(+val, input);
  2827. } else {
  2828. dur = moment.duration(input, val);
  2829. }
  2830. addOrSubtractDurationFromMoment(this, dur, -1);
  2831. return this;
  2832. },
  2833. diff : function (input, units, asFloat) {
  2834. var that = makeAs(input, this),
  2835. zoneDiff = (this.zone() - that.zone()) * 6e4,
  2836. diff, output;
  2837. units = normalizeUnits(units);
  2838. if (units === 'year' || units === 'month') {
  2839. // average number of days in the months in the given dates
  2840. diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2
  2841. // difference in months
  2842. output = ((this.year() - that.year()) * 12) + (this.month() - that.month());
  2843. // adjust by taking difference in days, average number of days
  2844. // and dst in the given months.
  2845. output += ((this - moment(this).startOf('month')) -
  2846. (that - moment(that).startOf('month'))) / diff;
  2847. // same as above but with zones, to negate all dst
  2848. output -= ((this.zone() - moment(this).startOf('month').zone()) -
  2849. (that.zone() - moment(that).startOf('month').zone())) * 6e4 / diff;
  2850. if (units === 'year') {
  2851. output = output / 12;
  2852. }
  2853. } else {
  2854. diff = (this - that);
  2855. output = units === 'second' ? diff / 1e3 : // 1000
  2856. units === 'minute' ? diff / 6e4 : // 1000 * 60
  2857. units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60
  2858. units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
  2859. units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
  2860. diff;
  2861. }
  2862. return asFloat ? output : absRound(output);
  2863. },
  2864. from : function (time, withoutSuffix) {
  2865. return moment.duration(this.diff(time)).lang(this.lang()._abbr).humanize(!withoutSuffix);
  2866. },
  2867. fromNow : function (withoutSuffix) {
  2868. return this.from(moment(), withoutSuffix);
  2869. },
  2870. calendar : function () {
  2871. // We want to compare the start of today, vs this.
  2872. // Getting start-of-today depends on whether we're zone'd or not.
  2873. var sod = makeAs(moment(), this).startOf('day'),
  2874. diff = this.diff(sod, 'days', true),
  2875. format = diff < -6 ? 'sameElse' :
  2876. diff < -1 ? 'lastWeek' :
  2877. diff < 0 ? 'lastDay' :
  2878. diff < 1 ? 'sameDay' :
  2879. diff < 2 ? 'nextDay' :
  2880. diff < 7 ? 'nextWeek' : 'sameElse';
  2881. return this.format(this.lang().calendar(format, this));
  2882. },
  2883. isLeapYear : function () {
  2884. return isLeapYear(this.year());
  2885. },
  2886. isDST : function () {
  2887. return (this.zone() < this.clone().month(0).zone() ||
  2888. this.zone() < this.clone().month(5).zone());
  2889. },
  2890. day : function (input) {
  2891. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  2892. if (input != null) {
  2893. input = parseWeekday(input, this.lang());
  2894. return this.add({ d : input - day });
  2895. } else {
  2896. return day;
  2897. }
  2898. },
  2899. month : function (input) {
  2900. var utc = this._isUTC ? 'UTC' : '',
  2901. dayOfMonth;
  2902. if (input != null) {
  2903. if (typeof input === 'string') {
  2904. input = this.lang().monthsParse(input);
  2905. if (typeof input !== 'number') {
  2906. return this;
  2907. }
  2908. }
  2909. dayOfMonth = this.date();
  2910. this.date(1);
  2911. this._d['set' + utc + 'Month'](input);
  2912. this.date(Math.min(dayOfMonth, this.daysInMonth()));
  2913. moment.updateOffset(this);
  2914. return this;
  2915. } else {
  2916. return this._d['get' + utc + 'Month']();
  2917. }
  2918. },
  2919. startOf: function (units) {
  2920. units = normalizeUnits(units);
  2921. // the following switch intentionally omits break keywords
  2922. // to utilize falling through the cases.
  2923. switch (units) {
  2924. case 'year':
  2925. this.month(0);
  2926. /* falls through */
  2927. case 'month':
  2928. this.date(1);
  2929. /* falls through */
  2930. case 'week':
  2931. case 'isoWeek':
  2932. case 'day':
  2933. this.hours(0);
  2934. /* falls through */
  2935. case 'hour':
  2936. this.minutes(0);
  2937. /* falls through */
  2938. case 'minute':
  2939. this.seconds(0);
  2940. /* falls through */
  2941. case 'second':
  2942. this.milliseconds(0);
  2943. /* falls through */
  2944. }
  2945. // weeks are a special case
  2946. if (units === 'week') {
  2947. this.weekday(0);
  2948. } else if (units === 'isoWeek') {
  2949. this.isoWeekday(1);
  2950. }
  2951. return this;
  2952. },
  2953. endOf: function (units) {
  2954. units = normalizeUnits(units);
  2955. return this.startOf(units).add((units === 'isoWeek' ? 'week' : units), 1).subtract('ms', 1);
  2956. },
  2957. isAfter: function (input, units) {
  2958. units = typeof units !== 'undefined' ? units : 'millisecond';
  2959. return +this.clone().startOf(units) > +moment(input).startOf(units);
  2960. },
  2961. isBefore: function (input, units) {
  2962. units = typeof units !== 'undefined' ? units : 'millisecond';
  2963. return +this.clone().startOf(units) < +moment(input).startOf(units);
  2964. },
  2965. isSame: function (input, units) {
  2966. units = units || 'ms';
  2967. return +this.clone().startOf(units) === +makeAs(input, this).startOf(units);
  2968. },
  2969. min: function (other) {
  2970. other = moment.apply(null, arguments);
  2971. return other < this ? this : other;
  2972. },
  2973. max: function (other) {
  2974. other = moment.apply(null, arguments);
  2975. return other > this ? this : other;
  2976. },
  2977. zone : function (input) {
  2978. var offset = this._offset || 0;
  2979. if (input != null) {
  2980. if (typeof input === "string") {
  2981. input = timezoneMinutesFromString(input);
  2982. }
  2983. if (Math.abs(input) < 16) {
  2984. input = input * 60;
  2985. }
  2986. this._offset = input;
  2987. this._isUTC = true;
  2988. if (offset !== input) {
  2989. addOrSubtractDurationFromMoment(this, moment.duration(offset - input, 'm'), 1, true);
  2990. }
  2991. } else {
  2992. return this._isUTC ? offset : this._d.getTimezoneOffset();
  2993. }
  2994. return this;
  2995. },
  2996. zoneAbbr : function () {
  2997. return this._isUTC ? "UTC" : "";
  2998. },
  2999. zoneName : function () {
  3000. return this._isUTC ? "Coordinated Universal Time" : "";
  3001. },
  3002. parseZone : function () {
  3003. if (this._tzm) {
  3004. this.zone(this._tzm);
  3005. } else if (typeof this._i === 'string') {
  3006. this.zone(this._i);
  3007. }
  3008. return this;
  3009. },
  3010. hasAlignedHourOffset : function (input) {
  3011. if (!input) {
  3012. input = 0;
  3013. }
  3014. else {
  3015. input = moment(input).zone();
  3016. }
  3017. return (this.zone() - input) % 60 === 0;
  3018. },
  3019. daysInMonth : function () {
  3020. return daysInMonth(this.year(), this.month());
  3021. },
  3022. dayOfYear : function (input) {
  3023. var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1;
  3024. return input == null ? dayOfYear : this.add("d", (input - dayOfYear));
  3025. },
  3026. quarter : function () {
  3027. return Math.ceil((this.month() + 1.0) / 3.0);
  3028. },
  3029. weekYear : function (input) {
  3030. var year = weekOfYear(this, this.lang()._week.dow, this.lang()._week.doy).year;
  3031. return input == null ? year : this.add("y", (input - year));
  3032. },
  3033. isoWeekYear : function (input) {
  3034. var year = weekOfYear(this, 1, 4).year;
  3035. return input == null ? year : this.add("y", (input - year));
  3036. },
  3037. week : function (input) {
  3038. var week = this.lang().week(this);
  3039. return input == null ? week : this.add("d", (input - week) * 7);
  3040. },
  3041. isoWeek : function (input) {
  3042. var week = weekOfYear(this, 1, 4).week;
  3043. return input == null ? week : this.add("d", (input - week) * 7);
  3044. },
  3045. weekday : function (input) {
  3046. var weekday = (this.day() + 7 - this.lang()._week.dow) % 7;
  3047. return input == null ? weekday : this.add("d", input - weekday);
  3048. },
  3049. isoWeekday : function (input) {
  3050. // behaves the same as moment#day except
  3051. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  3052. // as a setter, sunday should belong to the previous week.
  3053. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7);
  3054. },
  3055. get : function (units) {
  3056. units = normalizeUnits(units);
  3057. return this[units]();
  3058. },
  3059. set : function (units, value) {
  3060. units = normalizeUnits(units);
  3061. if (typeof this[units] === 'function') {
  3062. this[units](value);
  3063. }
  3064. return this;
  3065. },
  3066. // If passed a language key, it will set the language for this
  3067. // instance. Otherwise, it will return the language configuration
  3068. // variables for this instance.
  3069. lang : function (key) {
  3070. if (key === undefined) {
  3071. return this._lang;
  3072. } else {
  3073. this._lang = getLangDefinition(key);
  3074. return this;
  3075. }
  3076. }
  3077. });
  3078. // helper for adding shortcuts
  3079. function makeGetterAndSetter(name, key) {
  3080. moment.fn[name] = moment.fn[name + 's'] = function (input) {
  3081. var utc = this._isUTC ? 'UTC' : '';
  3082. if (input != null) {
  3083. this._d['set' + utc + key](input);
  3084. moment.updateOffset(this);
  3085. return this;
  3086. } else {
  3087. return this._d['get' + utc + key]();
  3088. }
  3089. };
  3090. }
  3091. // loop through and add shortcuts (Month, Date, Hours, Minutes, Seconds, Milliseconds)
  3092. for (i = 0; i < proxyGettersAndSetters.length; i ++) {
  3093. makeGetterAndSetter(proxyGettersAndSetters[i].toLowerCase().replace(/s$/, ''), proxyGettersAndSetters[i]);
  3094. }
  3095. // add shortcut for year (uses different syntax than the getter/setter 'year' == 'FullYear')
  3096. makeGetterAndSetter('year', 'FullYear');
  3097. // add plural methods
  3098. moment.fn.days = moment.fn.day;
  3099. moment.fn.months = moment.fn.month;
  3100. moment.fn.weeks = moment.fn.week;
  3101. moment.fn.isoWeeks = moment.fn.isoWeek;
  3102. // add aliased format methods
  3103. moment.fn.toJSON = moment.fn.toISOString;
  3104. /************************************
  3105. Duration Prototype
  3106. ************************************/
  3107. extend(moment.duration.fn = Duration.prototype, {
  3108. _bubble : function () {
  3109. var milliseconds = this._milliseconds,
  3110. days = this._days,
  3111. months = this._months,
  3112. data = this._data,
  3113. seconds, minutes, hours, years;
  3114. // The following code bubbles up values, see the tests for
  3115. // examples of what that means.
  3116. data.milliseconds = milliseconds % 1000;
  3117. seconds = absRound(milliseconds / 1000);
  3118. data.seconds = seconds % 60;
  3119. minutes = absRound(seconds / 60);
  3120. data.minutes = minutes % 60;
  3121. hours = absRound(minutes / 60);
  3122. data.hours = hours % 24;
  3123. days += absRound(hours / 24);
  3124. data.days = days % 30;
  3125. months += absRound(days / 30);
  3126. data.months = months % 12;
  3127. years = absRound(months / 12);
  3128. data.years = years;
  3129. },
  3130. weeks : function () {
  3131. return absRound(this.days() / 7);
  3132. },
  3133. valueOf : function () {
  3134. return this._milliseconds +
  3135. this._days * 864e5 +
  3136. (this._months % 12) * 2592e6 +
  3137. toInt(this._months / 12) * 31536e6;
  3138. },
  3139. humanize : function (withSuffix) {
  3140. var difference = +this,
  3141. output = relativeTime(difference, !withSuffix, this.lang());
  3142. if (withSuffix) {
  3143. output = this.lang().pastFuture(difference, output);
  3144. }
  3145. return this.lang().postformat(output);
  3146. },
  3147. add : function (input, val) {
  3148. // supports only 2.0-style add(1, 's') or add(moment)
  3149. var dur = moment.duration(input, val);
  3150. this._milliseconds += dur._milliseconds;
  3151. this._days += dur._days;
  3152. this._months += dur._months;
  3153. this._bubble();
  3154. return this;
  3155. },
  3156. subtract : function (input, val) {
  3157. var dur = moment.duration(input, val);
  3158. this._milliseconds -= dur._milliseconds;
  3159. this._days -= dur._days;
  3160. this._months -= dur._months;
  3161. this._bubble();
  3162. return this;
  3163. },
  3164. get : function (units) {
  3165. units = normalizeUnits(units);
  3166. return this[units.toLowerCase() + 's']();
  3167. },
  3168. as : function (units) {
  3169. units = normalizeUnits(units);
  3170. return this['as' + units.charAt(0).toUpperCase() + units.slice(1) + 's']();
  3171. },
  3172. lang : moment.fn.lang,
  3173. toIsoString : function () {
  3174. // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
  3175. var years = Math.abs(this.years()),
  3176. months = Math.abs(this.months()),
  3177. days = Math.abs(this.days()),
  3178. hours = Math.abs(this.hours()),
  3179. minutes = Math.abs(this.minutes()),
  3180. seconds = Math.abs(this.seconds() + this.milliseconds() / 1000);
  3181. if (!this.asSeconds()) {
  3182. // this is the same as C#'s (Noda) and python (isodate)...
  3183. // but not other JS (goog.date)
  3184. return 'P0D';
  3185. }
  3186. return (this.asSeconds() < 0 ? '-' : '') +
  3187. 'P' +
  3188. (years ? years + 'Y' : '') +
  3189. (months ? months + 'M' : '') +
  3190. (days ? days + 'D' : '') +
  3191. ((hours || minutes || seconds) ? 'T' : '') +
  3192. (hours ? hours + 'H' : '') +
  3193. (minutes ? minutes + 'M' : '') +
  3194. (seconds ? seconds + 'S' : '');
  3195. }
  3196. });
  3197. function makeDurationGetter(name) {
  3198. moment.duration.fn[name] = function () {
  3199. return this._data[name];
  3200. };
  3201. }
  3202. function makeDurationAsGetter(name, factor) {
  3203. moment.duration.fn['as' + name] = function () {
  3204. return +this / factor;
  3205. };
  3206. }
  3207. for (i in unitMillisecondFactors) {
  3208. if (unitMillisecondFactors.hasOwnProperty(i)) {
  3209. makeDurationAsGetter(i, unitMillisecondFactors[i]);
  3210. makeDurationGetter(i.toLowerCase());
  3211. }
  3212. }
  3213. makeDurationAsGetter('Weeks', 6048e5);
  3214. moment.duration.fn.asMonths = function () {
  3215. return (+this - this.years() * 31536e6) / 2592e6 + this.years() * 12;
  3216. };
  3217. /************************************
  3218. Default Lang
  3219. ************************************/
  3220. // Set default language, other languages will inherit from English.
  3221. moment.lang('en', {
  3222. ordinal : function (number) {
  3223. var b = number % 10,
  3224. output = (toInt(number % 100 / 10) === 1) ? 'th' :
  3225. (b === 1) ? 'st' :
  3226. (b === 2) ? 'nd' :
  3227. (b === 3) ? 'rd' : 'th';
  3228. return number + output;
  3229. }
  3230. });
  3231. /* EMBED_LANGUAGES */
  3232. /************************************
  3233. Exposing Moment
  3234. ************************************/
  3235. function makeGlobal(deprecate) {
  3236. var warned = false, local_moment = moment;
  3237. /*global ender:false */
  3238. if (typeof ender !== 'undefined') {
  3239. return;
  3240. }
  3241. // here, `this` means `window` in the browser, or `global` on the server
  3242. // add `moment` as a global object via a string identifier,
  3243. // for Closure Compiler "advanced" mode
  3244. if (deprecate) {
  3245. global.moment = function () {
  3246. if (!warned && console && console.warn) {
  3247. warned = true;
  3248. console.warn(
  3249. "Accessing Moment through the global scope is " +
  3250. "deprecated, and will be removed in an upcoming " +
  3251. "release.");
  3252. }
  3253. return local_moment.apply(null, arguments);
  3254. };
  3255. extend(global.moment, local_moment);
  3256. } else {
  3257. global['moment'] = moment;
  3258. }
  3259. }
  3260. // CommonJS module is defined
  3261. if (hasModule) {
  3262. module.exports = moment;
  3263. makeGlobal(true);
  3264. } else if (typeof define === "function" && define.amd) {
  3265. define("moment", function (require, exports, module) {
  3266. if (module.config && module.config() && module.config().noGlobal !== true) {
  3267. // If user provided noGlobal, he is aware of global
  3268. makeGlobal(module.config().noGlobal === undefined);
  3269. }
  3270. return moment;
  3271. });
  3272. } else {
  3273. makeGlobal();
  3274. }
  3275. }).call(this);
  3276. },{}],3:[function(require,module,exports){
  3277. /**
  3278. * Copyright 2012 Craig Campbell
  3279. *
  3280. * Licensed under the Apache License, Version 2.0 (the "License");
  3281. * you may not use this file except in compliance with the License.
  3282. * You may obtain a copy of the License at
  3283. *
  3284. * http://www.apache.org/licenses/LICENSE-2.0
  3285. *
  3286. * Unless required by applicable law or agreed to in writing, software
  3287. * distributed under the License is distributed on an "AS IS" BASIS,
  3288. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3289. * See the License for the specific language governing permissions and
  3290. * limitations under the License.
  3291. *
  3292. * Mousetrap is a simple keyboard shortcut library for Javascript with
  3293. * no external dependencies
  3294. *
  3295. * @version 1.1.2
  3296. * @url craig.is/killing/mice
  3297. */
  3298. /**
  3299. * mapping of special keycodes to their corresponding keys
  3300. *
  3301. * everything in this dictionary cannot use keypress events
  3302. * so it has to be here to map to the correct keycodes for
  3303. * keyup/keydown events
  3304. *
  3305. * @type {Object}
  3306. */
  3307. var _MAP = {
  3308. 8: 'backspace',
  3309. 9: 'tab',
  3310. 13: 'enter',
  3311. 16: 'shift',
  3312. 17: 'ctrl',
  3313. 18: 'alt',
  3314. 20: 'capslock',
  3315. 27: 'esc',
  3316. 32: 'space',
  3317. 33: 'pageup',
  3318. 34: 'pagedown',
  3319. 35: 'end',
  3320. 36: 'home',
  3321. 37: 'left',
  3322. 38: 'up',
  3323. 39: 'right',
  3324. 40: 'down',
  3325. 45: 'ins',
  3326. 46: 'del',
  3327. 91: 'meta',
  3328. 93: 'meta',
  3329. 224: 'meta'
  3330. },
  3331. /**
  3332. * mapping for special characters so they can support
  3333. *
  3334. * this dictionary is only used incase you want to bind a
  3335. * keyup or keydown event to one of these keys
  3336. *
  3337. * @type {Object}
  3338. */
  3339. _KEYCODE_MAP = {
  3340. 106: '*',
  3341. 107: '+',
  3342. 109: '-',
  3343. 110: '.',
  3344. 111 : '/',
  3345. 186: ';',
  3346. 187: '=',
  3347. 188: ',',
  3348. 189: '-',
  3349. 190: '.',
  3350. 191: '/',
  3351. 192: '`',
  3352. 219: '[',
  3353. 220: '\\',
  3354. 221: ']',
  3355. 222: '\''
  3356. },
  3357. /**
  3358. * this is a mapping of keys that require shift on a US keypad
  3359. * back to the non shift equivelents
  3360. *
  3361. * this is so you can use keyup events with these keys
  3362. *
  3363. * note that this will only work reliably on US keyboards
  3364. *
  3365. * @type {Object}
  3366. */
  3367. _SHIFT_MAP = {
  3368. '~': '`',
  3369. '!': '1',
  3370. '@': '2',
  3371. '#': '3',
  3372. '$': '4',
  3373. '%': '5',
  3374. '^': '6',
  3375. '&': '7',
  3376. '*': '8',
  3377. '(': '9',
  3378. ')': '0',
  3379. '_': '-',
  3380. '+': '=',
  3381. ':': ';',
  3382. '\"': '\'',
  3383. '<': ',',
  3384. '>': '.',
  3385. '?': '/',
  3386. '|': '\\'
  3387. },
  3388. /**
  3389. * this is a list of special strings you can use to map
  3390. * to modifier keys when you specify your keyboard shortcuts
  3391. *
  3392. * @type {Object}
  3393. */
  3394. _SPECIAL_ALIASES = {
  3395. 'option': 'alt',
  3396. 'command': 'meta',
  3397. 'return': 'enter',
  3398. 'escape': 'esc'
  3399. },
  3400. /**
  3401. * variable to store the flipped version of _MAP from above
  3402. * needed to check if we should use keypress or not when no action
  3403. * is specified
  3404. *
  3405. * @type {Object|undefined}
  3406. */
  3407. _REVERSE_MAP,
  3408. /**
  3409. * a list of all the callbacks setup via Mousetrap.bind()
  3410. *
  3411. * @type {Object}
  3412. */
  3413. _callbacks = {},
  3414. /**
  3415. * direct map of string combinations to callbacks used for trigger()
  3416. *
  3417. * @type {Object}
  3418. */
  3419. _direct_map = {},
  3420. /**
  3421. * keeps track of what level each sequence is at since multiple
  3422. * sequences can start out with the same sequence
  3423. *
  3424. * @type {Object}
  3425. */
  3426. _sequence_levels = {},
  3427. /**
  3428. * variable to store the setTimeout call
  3429. *
  3430. * @type {null|number}
  3431. */
  3432. _reset_timer,
  3433. /**
  3434. * temporary state where we will ignore the next keyup
  3435. *
  3436. * @type {boolean|string}
  3437. */
  3438. _ignore_next_keyup = false,
  3439. /**
  3440. * are we currently inside of a sequence?
  3441. * type of action ("keyup" or "keydown" or "keypress") or false
  3442. *
  3443. * @type {boolean|string}
  3444. */
  3445. _inside_sequence = false;
  3446. /**
  3447. * loop through the f keys, f1 to f19 and add them to the map
  3448. * programatically
  3449. */
  3450. for (var i = 1; i < 20; ++i) {
  3451. _MAP[111 + i] = 'f' + i;
  3452. }
  3453. /**
  3454. * loop through to map numbers on the numeric keypad
  3455. */
  3456. for (i = 0; i <= 9; ++i) {
  3457. _MAP[i + 96] = i;
  3458. }
  3459. /**
  3460. * cross browser add event method
  3461. *
  3462. * @param {Element|HTMLDocument} object
  3463. * @param {string} type
  3464. * @param {Function} callback
  3465. * @returns void
  3466. */
  3467. function _addEvent(object, type, callback) {
  3468. if (object.addEventListener) {
  3469. return object.addEventListener(type, callback, false);
  3470. }
  3471. object.attachEvent('on' + type, callback);
  3472. }
  3473. /**
  3474. * takes the event and returns the key character
  3475. *
  3476. * @param {Event} e
  3477. * @return {string}
  3478. */
  3479. function _characterFromEvent(e) {
  3480. // for keypress events we should return the character as is
  3481. if (e.type == 'keypress') {
  3482. return String.fromCharCode(e.which);
  3483. }
  3484. // for non keypress events the special maps are needed
  3485. if (_MAP[e.which]) {
  3486. return _MAP[e.which];
  3487. }
  3488. if (_KEYCODE_MAP[e.which]) {
  3489. return _KEYCODE_MAP[e.which];
  3490. }
  3491. // if it is not in the special map
  3492. return String.fromCharCode(e.which).toLowerCase();
  3493. }
  3494. /**
  3495. * should we stop this event before firing off callbacks
  3496. *
  3497. * @param {Event} e
  3498. * @return {boolean}
  3499. */
  3500. function _stop(e) {
  3501. var element = e.target || e.srcElement,
  3502. tag_name = element.tagName;
  3503. // if the element has the class "mousetrap" then no need to stop
  3504. if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {
  3505. return false;
  3506. }
  3507. // stop for input, select, and textarea
  3508. return tag_name == 'INPUT' || tag_name == 'SELECT' || tag_name == 'TEXTAREA' || (element.contentEditable && element.contentEditable == 'true');
  3509. }
  3510. /**
  3511. * checks if two arrays are equal
  3512. *
  3513. * @param {Array} modifiers1
  3514. * @param {Array} modifiers2
  3515. * @returns {boolean}
  3516. */
  3517. function _modifiersMatch(modifiers1, modifiers2) {
  3518. return modifiers1.sort().join(',') === modifiers2.sort().join(',');
  3519. }
  3520. /**
  3521. * resets all sequence counters except for the ones passed in
  3522. *
  3523. * @param {Object} do_not_reset
  3524. * @returns void
  3525. */
  3526. function _resetSequences(do_not_reset) {
  3527. do_not_reset = do_not_reset || {};
  3528. var active_sequences = false,
  3529. key;
  3530. for (key in _sequence_levels) {
  3531. if (do_not_reset[key]) {
  3532. active_sequences = true;
  3533. continue;
  3534. }
  3535. _sequence_levels[key] = 0;
  3536. }
  3537. if (!active_sequences) {
  3538. _inside_sequence = false;
  3539. }
  3540. }
  3541. /**
  3542. * finds all callbacks that match based on the keycode, modifiers,
  3543. * and action
  3544. *
  3545. * @param {string} character
  3546. * @param {Array} modifiers
  3547. * @param {string} action
  3548. * @param {boolean=} remove - should we remove any matches
  3549. * @param {string=} combination
  3550. * @returns {Array}
  3551. */
  3552. function _getMatches(character, modifiers, action, remove, combination) {
  3553. var i,
  3554. callback,
  3555. matches = [];
  3556. // if there are no events related to this keycode
  3557. if (!_callbacks[character]) {
  3558. return [];
  3559. }
  3560. // if a modifier key is coming up on its own we should allow it
  3561. if (action == 'keyup' && _isModifier(character)) {
  3562. modifiers = [character];
  3563. }
  3564. // loop through all callbacks for the key that was pressed
  3565. // and see if any of them match
  3566. for (i = 0; i < _callbacks[character].length; ++i) {
  3567. callback = _callbacks[character][i];
  3568. // if this is a sequence but it is not at the right level
  3569. // then move onto the next match
  3570. if (callback.seq && _sequence_levels[callback.seq] != callback.level) {
  3571. continue;
  3572. }
  3573. // if the action we are looking for doesn't match the action we got
  3574. // then we should keep going
  3575. if (action != callback.action) {
  3576. continue;
  3577. }
  3578. // if this is a keypress event that means that we need to only
  3579. // look at the character, otherwise check the modifiers as
  3580. // well
  3581. if (action == 'keypress' || _modifiersMatch(modifiers, callback.modifiers)) {
  3582. // remove is used so if you change your mind and call bind a
  3583. // second time with a new function the first one is overwritten
  3584. if (remove && callback.combo == combination) {
  3585. _callbacks[character].splice(i, 1);
  3586. }
  3587. matches.push(callback);
  3588. }
  3589. }
  3590. return matches;
  3591. }
  3592. /**
  3593. * takes a key event and figures out what the modifiers are
  3594. *
  3595. * @param {Event} e
  3596. * @returns {Array}
  3597. */
  3598. function _eventModifiers(e) {
  3599. var modifiers = [];
  3600. if (e.shiftKey) {
  3601. modifiers.push('shift');
  3602. }
  3603. if (e.altKey) {
  3604. modifiers.push('alt');
  3605. }
  3606. if (e.ctrlKey) {
  3607. modifiers.push('ctrl');
  3608. }
  3609. if (e.metaKey) {
  3610. modifiers.push('meta');
  3611. }
  3612. return modifiers;
  3613. }
  3614. /**
  3615. * actually calls the callback function
  3616. *
  3617. * if your callback function returns false this will use the jquery
  3618. * convention - prevent default and stop propogation on the event
  3619. *
  3620. * @param {Function} callback
  3621. * @param {Event} e
  3622. * @returns void
  3623. */
  3624. function _fireCallback(callback, e) {
  3625. if (callback(e) === false) {
  3626. if (e.preventDefault) {
  3627. e.preventDefault();
  3628. }
  3629. if (e.stopPropagation) {
  3630. e.stopPropagation();
  3631. }
  3632. e.returnValue = false;
  3633. e.cancelBubble = true;
  3634. }
  3635. }
  3636. /**
  3637. * handles a character key event
  3638. *
  3639. * @param {string} character
  3640. * @param {Event} e
  3641. * @returns void
  3642. */
  3643. function _handleCharacter(character, e) {
  3644. // if this event should not happen stop here
  3645. if (_stop(e)) {
  3646. return;
  3647. }
  3648. var callbacks = _getMatches(character, _eventModifiers(e), e.type),
  3649. i,
  3650. do_not_reset = {},
  3651. processed_sequence_callback = false;
  3652. // loop through matching callbacks for this key event
  3653. for (i = 0; i < callbacks.length; ++i) {
  3654. // fire for all sequence callbacks
  3655. // this is because if for example you have multiple sequences
  3656. // bound such as "g i" and "g t" they both need to fire the
  3657. // callback for matching g cause otherwise you can only ever
  3658. // match the first one
  3659. if (callbacks[i].seq) {
  3660. processed_sequence_callback = true;
  3661. // keep a list of which sequences were matches for later
  3662. do_not_reset[callbacks[i].seq] = 1;
  3663. _fireCallback(callbacks[i].callback, e);
  3664. continue;
  3665. }
  3666. // if there were no sequence matches but we are still here
  3667. // that means this is a regular match so we should fire that
  3668. if (!processed_sequence_callback && !_inside_sequence) {
  3669. _fireCallback(callbacks[i].callback, e);
  3670. }
  3671. }
  3672. // if you are inside of a sequence and the key you are pressing
  3673. // is not a modifier key then we should reset all sequences
  3674. // that were not matched by this key event
  3675. if (e.type == _inside_sequence && !_isModifier(character)) {
  3676. _resetSequences(do_not_reset);
  3677. }
  3678. }
  3679. /**
  3680. * handles a keydown event
  3681. *
  3682. * @param {Event} e
  3683. * @returns void
  3684. */
  3685. function _handleKey(e) {
  3686. // normalize e.which for key events
  3687. // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion
  3688. e.which = typeof e.which == "number" ? e.which : e.keyCode;
  3689. var character = _characterFromEvent(e);
  3690. // no character found then stop
  3691. if (!character) {
  3692. return;
  3693. }
  3694. if (e.type == 'keyup' && _ignore_next_keyup == character) {
  3695. _ignore_next_keyup = false;
  3696. return;
  3697. }
  3698. _handleCharacter(character, e);
  3699. }
  3700. /**
  3701. * determines if the keycode specified is a modifier key or not
  3702. *
  3703. * @param {string} key
  3704. * @returns {boolean}
  3705. */
  3706. function _isModifier(key) {
  3707. return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta';
  3708. }
  3709. /**
  3710. * called to set a 1 second timeout on the specified sequence
  3711. *
  3712. * this is so after each key press in the sequence you have 1 second
  3713. * to press the next key before you have to start over
  3714. *
  3715. * @returns void
  3716. */
  3717. function _resetSequenceTimer() {
  3718. clearTimeout(_reset_timer);
  3719. _reset_timer = setTimeout(_resetSequences, 1000);
  3720. }
  3721. /**
  3722. * reverses the map lookup so that we can look for specific keys
  3723. * to see what can and can't use keypress
  3724. *
  3725. * @return {Object}
  3726. */
  3727. function _getReverseMap() {
  3728. if (!_REVERSE_MAP) {
  3729. _REVERSE_MAP = {};
  3730. for (var key in _MAP) {
  3731. // pull out the numeric keypad from here cause keypress should
  3732. // be able to detect the keys from the character
  3733. if (key > 95 && key < 112) {
  3734. continue;
  3735. }
  3736. if (_MAP.hasOwnProperty(key)) {
  3737. _REVERSE_MAP[_MAP[key]] = key;
  3738. }
  3739. }
  3740. }
  3741. return _REVERSE_MAP;
  3742. }
  3743. /**
  3744. * picks the best action based on the key combination
  3745. *
  3746. * @param {string} key - character for key
  3747. * @param {Array} modifiers
  3748. * @param {string=} action passed in
  3749. */
  3750. function _pickBestAction(key, modifiers, action) {
  3751. // if no action was picked in we should try to pick the one
  3752. // that we think would work best for this key
  3753. if (!action) {
  3754. action = _getReverseMap()[key] ? 'keydown' : 'keypress';
  3755. }
  3756. // modifier keys don't work as expected with keypress,
  3757. // switch to keydown
  3758. if (action == 'keypress' && modifiers.length) {
  3759. action = 'keydown';
  3760. }
  3761. return action;
  3762. }
  3763. /**
  3764. * binds a key sequence to an event
  3765. *
  3766. * @param {string} combo - combo specified in bind call
  3767. * @param {Array} keys
  3768. * @param {Function} callback
  3769. * @param {string=} action
  3770. * @returns void
  3771. */
  3772. function _bindSequence(combo, keys, callback, action) {
  3773. // start off by adding a sequence level record for this combination
  3774. // and setting the level to 0
  3775. _sequence_levels[combo] = 0;
  3776. // if there is no action pick the best one for the first key
  3777. // in the sequence
  3778. if (!action) {
  3779. action = _pickBestAction(keys[0], []);
  3780. }
  3781. /**
  3782. * callback to increase the sequence level for this sequence and reset
  3783. * all other sequences that were active
  3784. *
  3785. * @param {Event} e
  3786. * @returns void
  3787. */
  3788. var _increaseSequence = function(e) {
  3789. _inside_sequence = action;
  3790. ++_sequence_levels[combo];
  3791. _resetSequenceTimer();
  3792. },
  3793. /**
  3794. * wraps the specified callback inside of another function in order
  3795. * to reset all sequence counters as soon as this sequence is done
  3796. *
  3797. * @param {Event} e
  3798. * @returns void
  3799. */
  3800. _callbackAndReset = function(e) {
  3801. _fireCallback(callback, e);
  3802. // we should ignore the next key up if the action is key down
  3803. // or keypress. this is so if you finish a sequence and
  3804. // release the key the final key will not trigger a keyup
  3805. if (action !== 'keyup') {
  3806. _ignore_next_keyup = _characterFromEvent(e);
  3807. }
  3808. // weird race condition if a sequence ends with the key
  3809. // another sequence begins with
  3810. setTimeout(_resetSequences, 10);
  3811. },
  3812. i;
  3813. // loop through keys one at a time and bind the appropriate callback
  3814. // function. for any key leading up to the final one it should
  3815. // increase the sequence. after the final, it should reset all sequences
  3816. for (i = 0; i < keys.length; ++i) {
  3817. _bindSingle(keys[i], i < keys.length - 1 ? _increaseSequence : _callbackAndReset, action, combo, i);
  3818. }
  3819. }
  3820. /**
  3821. * binds a single keyboard combination
  3822. *
  3823. * @param {string} combination
  3824. * @param {Function} callback
  3825. * @param {string=} action
  3826. * @param {string=} sequence_name - name of sequence if part of sequence
  3827. * @param {number=} level - what part of the sequence the command is
  3828. * @returns void
  3829. */
  3830. function _bindSingle(combination, callback, action, sequence_name, level) {
  3831. // make sure multiple spaces in a row become a single space
  3832. combination = combination.replace(/\s+/g, ' ');
  3833. var sequence = combination.split(' '),
  3834. i,
  3835. key,
  3836. keys,
  3837. modifiers = [];
  3838. // if this pattern is a sequence of keys then run through this method
  3839. // to reprocess each pattern one key at a time
  3840. if (sequence.length > 1) {
  3841. return _bindSequence(combination, sequence, callback, action);
  3842. }
  3843. // take the keys from this pattern and figure out what the actual
  3844. // pattern is all about
  3845. keys = combination === '+' ? ['+'] : combination.split('+');
  3846. for (i = 0; i < keys.length; ++i) {
  3847. key = keys[i];
  3848. // normalize key names
  3849. if (_SPECIAL_ALIASES[key]) {
  3850. key = _SPECIAL_ALIASES[key];
  3851. }
  3852. // if this is not a keypress event then we should
  3853. // be smart about using shift keys
  3854. // this will only work for US keyboards however
  3855. if (action && action != 'keypress' && _SHIFT_MAP[key]) {
  3856. key = _SHIFT_MAP[key];
  3857. modifiers.push('shift');
  3858. }
  3859. // if this key is a modifier then add it to the list of modifiers
  3860. if (_isModifier(key)) {
  3861. modifiers.push(key);
  3862. }
  3863. }
  3864. // depending on what the key combination is
  3865. // we will try to pick the best event for it
  3866. action = _pickBestAction(key, modifiers, action);
  3867. // make sure to initialize array if this is the first time
  3868. // a callback is added for this key
  3869. if (!_callbacks[key]) {
  3870. _callbacks[key] = [];
  3871. }
  3872. // remove an existing match if there is one
  3873. _getMatches(key, modifiers, action, !sequence_name, combination);
  3874. // add this call back to the array
  3875. // if it is a sequence put it at the beginning
  3876. // if not put it at the end
  3877. //
  3878. // this is important because the way these are processed expects
  3879. // the sequence ones to come first
  3880. _callbacks[key][sequence_name ? 'unshift' : 'push']({
  3881. callback: callback,
  3882. modifiers: modifiers,
  3883. action: action,
  3884. seq: sequence_name,
  3885. level: level,
  3886. combo: combination
  3887. });
  3888. }
  3889. /**
  3890. * binds multiple combinations to the same callback
  3891. *
  3892. * @param {Array} combinations
  3893. * @param {Function} callback
  3894. * @param {string|undefined} action
  3895. * @returns void
  3896. */
  3897. function _bindMultiple(combinations, callback, action) {
  3898. for (var i = 0; i < combinations.length; ++i) {
  3899. _bindSingle(combinations[i], callback, action);
  3900. }
  3901. }
  3902. // start!
  3903. _addEvent(document, 'keypress', _handleKey);
  3904. _addEvent(document, 'keydown', _handleKey);
  3905. _addEvent(document, 'keyup', _handleKey);
  3906. var mousetrap = {
  3907. /**
  3908. * binds an event to mousetrap
  3909. *
  3910. * can be a single key, a combination of keys separated with +,
  3911. * a comma separated list of keys, an array of keys, or
  3912. * a sequence of keys separated by spaces
  3913. *
  3914. * be sure to list the modifier keys first to make sure that the
  3915. * correct key ends up getting bound (the last key in the pattern)
  3916. *
  3917. * @param {string|Array} keys
  3918. * @param {Function} callback
  3919. * @param {string=} action - 'keypress', 'keydown', or 'keyup'
  3920. * @returns void
  3921. */
  3922. bind: function(keys, callback, action) {
  3923. _bindMultiple(keys instanceof Array ? keys : [keys], callback, action);
  3924. _direct_map[keys + ':' + action] = callback;
  3925. return this;
  3926. },
  3927. /**
  3928. * unbinds an event to mousetrap
  3929. *
  3930. * the unbinding sets the callback function of the specified key combo
  3931. * to an empty function and deletes the corresponding key in the
  3932. * _direct_map dict.
  3933. *
  3934. * the keycombo+action has to be exactly the same as
  3935. * it was defined in the bind method
  3936. *
  3937. * TODO: actually remove this from the _callbacks dictionary instead
  3938. * of binding an empty function
  3939. *
  3940. * @param {string|Array} keys
  3941. * @param {string} action
  3942. * @returns void
  3943. */
  3944. unbind: function(keys, action) {
  3945. if (_direct_map[keys + ':' + action]) {
  3946. delete _direct_map[keys + ':' + action];
  3947. this.bind(keys, function() {}, action);
  3948. }
  3949. return this;
  3950. },
  3951. /**
  3952. * triggers an event that has already been bound
  3953. *
  3954. * @param {string} keys
  3955. * @param {string=} action
  3956. * @returns void
  3957. */
  3958. trigger: function(keys, action) {
  3959. _direct_map[keys + ':' + action]();
  3960. return this;
  3961. },
  3962. /**
  3963. * resets the library back to its initial state. this is useful
  3964. * if you want to clear out the current keyboard shortcuts and bind
  3965. * new ones - for example if you switch to another page
  3966. *
  3967. * @returns void
  3968. */
  3969. reset: function() {
  3970. _callbacks = {};
  3971. _direct_map = {};
  3972. return this;
  3973. }
  3974. };
  3975. module.exports = mousetrap;
  3976. },{}],4:[function(require,module,exports){
  3977. /**
  3978. * vis.js module imports
  3979. */
  3980. // Try to load dependencies from the global window object.
  3981. // If not available there, load via require.
  3982. var moment = (typeof window !== 'undefined') && window['moment'] || require('moment');
  3983. var Hammer;
  3984. if (typeof window !== 'undefined') {
  3985. // load hammer.js only when running in a browser (where window is available)
  3986. Hammer = window['Hammer'] || require('hammerjs');
  3987. }
  3988. else {
  3989. Hammer = function () {
  3990. throw Error('hammer.js is only available in a browser, not in node.js.');
  3991. }
  3992. }
  3993. var mouseTrap;
  3994. if (typeof window !== 'undefined') {
  3995. // load hammer.js only when running in a browser (where window is available)
  3996. mouseTrap = window['mouseTrap'] || require('mouseTrap');
  3997. }
  3998. else {
  3999. mouseTrap = function () {
  4000. throw Error('mouseTrap is only available in a browser, not in node.js.');
  4001. }
  4002. }
  4003. // Internet Explorer 8 and older does not support Array.indexOf, so we define
  4004. // it here in that case.
  4005. // http://soledadpenades.com/2007/05/17/arrayindexof-in-internet-explorer/
  4006. if(!Array.prototype.indexOf) {
  4007. Array.prototype.indexOf = function(obj){
  4008. for(var i = 0; i < this.length; i++){
  4009. if(this[i] == obj){
  4010. return i;
  4011. }
  4012. }
  4013. return -1;
  4014. };
  4015. try {
  4016. console.log("Warning: Ancient browser detected. Please update your browser");
  4017. }
  4018. catch (err) {
  4019. }
  4020. }
  4021. // Internet Explorer 8 and older does not support Array.forEach, so we define
  4022. // it here in that case.
  4023. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach
  4024. if (!Array.prototype.forEach) {
  4025. Array.prototype.forEach = function(fn, scope) {
  4026. for(var i = 0, len = this.length; i < len; ++i) {
  4027. fn.call(scope || this, this[i], i, this);
  4028. }
  4029. }
  4030. }
  4031. // Internet Explorer 8 and older does not support Array.map, so we define it
  4032. // here in that case.
  4033. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map
  4034. // Production steps of ECMA-262, Edition 5, 15.4.4.19
  4035. // Reference: http://es5.github.com/#x15.4.4.19
  4036. if (!Array.prototype.map) {
  4037. Array.prototype.map = function(callback, thisArg) {
  4038. var T, A, k;
  4039. if (this == null) {
  4040. throw new TypeError(" this is null or not defined");
  4041. }
  4042. // 1. Let O be the result of calling ToObject passing the |this| value as the argument.
  4043. var O = Object(this);
  4044. // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
  4045. // 3. Let len be ToUint32(lenValue).
  4046. var len = O.length >>> 0;
  4047. // 4. If IsCallable(callback) is false, throw a TypeError exception.
  4048. // See: http://es5.github.com/#x9.11
  4049. if (typeof callback !== "function") {
  4050. throw new TypeError(callback + " is not a function");
  4051. }
  4052. // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
  4053. if (thisArg) {
  4054. T = thisArg;
  4055. }
  4056. // 6. Let A be a new array created as if by the expression new Array(len) where Array is
  4057. // the standard built-in constructor with that name and len is the value of len.
  4058. A = new Array(len);
  4059. // 7. Let k be 0
  4060. k = 0;
  4061. // 8. Repeat, while k < len
  4062. while(k < len) {
  4063. var kValue, mappedValue;
  4064. // a. Let Pk be ToString(k).
  4065. // This is implicit for LHS operands of the in operator
  4066. // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
  4067. // This step can be combined with c
  4068. // c. If kPresent is true, then
  4069. if (k in O) {
  4070. // i. Let kValue be the result of calling the Get internal method of O with argument Pk.
  4071. kValue = O[ k ];
  4072. // ii. Let mappedValue be the result of calling the Call internal method of callback
  4073. // with T as the this value and argument list containing kValue, k, and O.
  4074. mappedValue = callback.call(T, kValue, k, O);
  4075. // iii. Call the DefineOwnProperty internal method of A with arguments
  4076. // Pk, Property Descriptor {Value: mappedValue, : true, Enumerable: true, Configurable: true},
  4077. // and false.
  4078. // In browsers that support Object.defineProperty, use the following:
  4079. // Object.defineProperty(A, Pk, { value: mappedValue, writable: true, enumerable: true, configurable: true });
  4080. // For best browser support, use the following:
  4081. A[ k ] = mappedValue;
  4082. }
  4083. // d. Increase k by 1.
  4084. k++;
  4085. }
  4086. // 9. return A
  4087. return A;
  4088. };
  4089. }
  4090. // Internet Explorer 8 and older does not support Array.filter, so we define it
  4091. // here in that case.
  4092. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter
  4093. if (!Array.prototype.filter) {
  4094. Array.prototype.filter = function(fun /*, thisp */) {
  4095. "use strict";
  4096. if (this == null) {
  4097. throw new TypeError();
  4098. }
  4099. var t = Object(this);
  4100. var len = t.length >>> 0;
  4101. if (typeof fun != "function") {
  4102. throw new TypeError();
  4103. }
  4104. var res = [];
  4105. var thisp = arguments[1];
  4106. for (var i = 0; i < len; i++) {
  4107. if (i in t) {
  4108. var val = t[i]; // in case fun mutates this
  4109. if (fun.call(thisp, val, i, t))
  4110. res.push(val);
  4111. }
  4112. }
  4113. return res;
  4114. };
  4115. }
  4116. // Internet Explorer 8 and older does not support Object.keys, so we define it
  4117. // here in that case.
  4118. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/keys
  4119. if (!Object.keys) {
  4120. Object.keys = (function () {
  4121. var hasOwnProperty = Object.prototype.hasOwnProperty,
  4122. hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
  4123. dontEnums = [
  4124. 'toString',
  4125. 'toLocaleString',
  4126. 'valueOf',
  4127. 'hasOwnProperty',
  4128. 'isPrototypeOf',
  4129. 'propertyIsEnumerable',
  4130. 'constructor'
  4131. ],
  4132. dontEnumsLength = dontEnums.length;
  4133. return function (obj) {
  4134. if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) {
  4135. throw new TypeError('Object.keys called on non-object');
  4136. }
  4137. var result = [];
  4138. for (var prop in obj) {
  4139. if (hasOwnProperty.call(obj, prop)) result.push(prop);
  4140. }
  4141. if (hasDontEnumBug) {
  4142. for (var i=0; i < dontEnumsLength; i++) {
  4143. if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
  4144. }
  4145. }
  4146. return result;
  4147. }
  4148. })()
  4149. }
  4150. // Internet Explorer 8 and older does not support Array.isArray,
  4151. // so we define it here in that case.
  4152. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/isArray
  4153. if(!Array.isArray) {
  4154. Array.isArray = function (vArg) {
  4155. return Object.prototype.toString.call(vArg) === "[object Array]";
  4156. };
  4157. }
  4158. // Internet Explorer 8 and older does not support Function.bind,
  4159. // so we define it here in that case.
  4160. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind
  4161. if (!Function.prototype.bind) {
  4162. Function.prototype.bind = function (oThis) {
  4163. if (typeof this !== "function") {
  4164. // closest thing possible to the ECMAScript 5 internal IsCallable function
  4165. throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
  4166. }
  4167. var aArgs = Array.prototype.slice.call(arguments, 1),
  4168. fToBind = this,
  4169. fNOP = function () {},
  4170. fBound = function () {
  4171. return fToBind.apply(this instanceof fNOP && oThis
  4172. ? this
  4173. : oThis,
  4174. aArgs.concat(Array.prototype.slice.call(arguments)));
  4175. };
  4176. fNOP.prototype = this.prototype;
  4177. fBound.prototype = new fNOP();
  4178. return fBound;
  4179. };
  4180. }
  4181. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create
  4182. if (!Object.create) {
  4183. Object.create = function (o) {
  4184. if (arguments.length > 1) {
  4185. throw new Error('Object.create implementation only accepts the first parameter.');
  4186. }
  4187. function F() {}
  4188. F.prototype = o;
  4189. return new F();
  4190. };
  4191. }
  4192. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
  4193. if (!Function.prototype.bind) {
  4194. Function.prototype.bind = function (oThis) {
  4195. if (typeof this !== "function") {
  4196. // closest thing possible to the ECMAScript 5 internal IsCallable function
  4197. throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
  4198. }
  4199. var aArgs = Array.prototype.slice.call(arguments, 1),
  4200. fToBind = this,
  4201. fNOP = function () {},
  4202. fBound = function () {
  4203. return fToBind.apply(this instanceof fNOP && oThis
  4204. ? this
  4205. : oThis,
  4206. aArgs.concat(Array.prototype.slice.call(arguments)));
  4207. };
  4208. fNOP.prototype = this.prototype;
  4209. fBound.prototype = new fNOP();
  4210. return fBound;
  4211. };
  4212. }
  4213. /**
  4214. * utility functions
  4215. */
  4216. var util = {};
  4217. /**
  4218. * Test whether given object is a number
  4219. * @param {*} object
  4220. * @return {Boolean} isNumber
  4221. */
  4222. util.isNumber = function isNumber(object) {
  4223. return (object instanceof Number || typeof object == 'number');
  4224. };
  4225. /**
  4226. * Test whether given object is a string
  4227. * @param {*} object
  4228. * @return {Boolean} isString
  4229. */
  4230. util.isString = function isString(object) {
  4231. return (object instanceof String || typeof object == 'string');
  4232. };
  4233. /**
  4234. * Test whether given object is a Date, or a String containing a Date
  4235. * @param {Date | String} object
  4236. * @return {Boolean} isDate
  4237. */
  4238. util.isDate = function isDate(object) {
  4239. if (object instanceof Date) {
  4240. return true;
  4241. }
  4242. else if (util.isString(object)) {
  4243. // test whether this string contains a date
  4244. var match = ASPDateRegex.exec(object);
  4245. if (match) {
  4246. return true;
  4247. }
  4248. else if (!isNaN(Date.parse(object))) {
  4249. return true;
  4250. }
  4251. }
  4252. return false;
  4253. };
  4254. /**
  4255. * Test whether given object is an instance of google.visualization.DataTable
  4256. * @param {*} object
  4257. * @return {Boolean} isDataTable
  4258. */
  4259. util.isDataTable = function isDataTable(object) {
  4260. return (typeof (google) !== 'undefined') &&
  4261. (google.visualization) &&
  4262. (google.visualization.DataTable) &&
  4263. (object instanceof google.visualization.DataTable);
  4264. };
  4265. /**
  4266. * Create a semi UUID
  4267. * source: http://stackoverflow.com/a/105074/1262753
  4268. * @return {String} uuid
  4269. */
  4270. util.randomUUID = function randomUUID () {
  4271. var S4 = function () {
  4272. return Math.floor(
  4273. Math.random() * 0x10000 /* 65536 */
  4274. ).toString(16);
  4275. };
  4276. return (
  4277. S4() + S4() + '-' +
  4278. S4() + '-' +
  4279. S4() + '-' +
  4280. S4() + '-' +
  4281. S4() + S4() + S4()
  4282. );
  4283. };
  4284. /**
  4285. * Extend object a with the properties of object b or a series of objects
  4286. * Only properties with defined values are copied
  4287. * @param {Object} a
  4288. * @param {... Object} b
  4289. * @return {Object} a
  4290. */
  4291. util.extend = function (a, b) {
  4292. for (var i = 1, len = arguments.length; i < len; i++) {
  4293. var other = arguments[i];
  4294. for (var prop in other) {
  4295. if (other.hasOwnProperty(prop) && other[prop] !== undefined) {
  4296. a[prop] = other[prop];
  4297. }
  4298. }
  4299. }
  4300. return a;
  4301. };
  4302. /**
  4303. * Convert an object to another type
  4304. * @param {Boolean | Number | String | Date | Moment | Null | undefined} object
  4305. * @param {String | undefined} type Name of the type. Available types:
  4306. * 'Boolean', 'Number', 'String',
  4307. * 'Date', 'Moment', ISODate', 'ASPDate'.
  4308. * @return {*} object
  4309. * @throws Error
  4310. */
  4311. util.convert = function convert(object, type) {
  4312. var match;
  4313. if (object === undefined) {
  4314. return undefined;
  4315. }
  4316. if (object === null) {
  4317. return null;
  4318. }
  4319. if (!type) {
  4320. return object;
  4321. }
  4322. if (!(typeof type === 'string') && !(type instanceof String)) {
  4323. throw new Error('Type must be a string');
  4324. }
  4325. //noinspection FallthroughInSwitchStatementJS
  4326. switch (type) {
  4327. case 'boolean':
  4328. case 'Boolean':
  4329. return Boolean(object);
  4330. case 'number':
  4331. case 'Number':
  4332. return Number(object.valueOf());
  4333. case 'string':
  4334. case 'String':
  4335. return String(object);
  4336. case 'Date':
  4337. if (util.isNumber(object)) {
  4338. return new Date(object);
  4339. }
  4340. if (object instanceof Date) {
  4341. return new Date(object.valueOf());
  4342. }
  4343. else if (moment.isMoment(object)) {
  4344. return new Date(object.valueOf());
  4345. }
  4346. if (util.isString(object)) {
  4347. match = ASPDateRegex.exec(object);
  4348. if (match) {
  4349. // object is an ASP date
  4350. return new Date(Number(match[1])); // parse number
  4351. }
  4352. else {
  4353. return moment(object).toDate(); // parse string
  4354. }
  4355. }
  4356. else {
  4357. throw new Error(
  4358. 'Cannot convert object of type ' + util.getType(object) +
  4359. ' to type Date');
  4360. }
  4361. case 'Moment':
  4362. if (util.isNumber(object)) {
  4363. return moment(object);
  4364. }
  4365. if (object instanceof Date) {
  4366. return moment(object.valueOf());
  4367. }
  4368. else if (moment.isMoment(object)) {
  4369. return moment(object);
  4370. }
  4371. if (util.isString(object)) {
  4372. match = ASPDateRegex.exec(object);
  4373. if (match) {
  4374. // object is an ASP date
  4375. return moment(Number(match[1])); // parse number
  4376. }
  4377. else {
  4378. return moment(object); // parse string
  4379. }
  4380. }
  4381. else {
  4382. throw new Error(
  4383. 'Cannot convert object of type ' + util.getType(object) +
  4384. ' to type Date');
  4385. }
  4386. case 'ISODate':
  4387. if (util.isNumber(object)) {
  4388. return new Date(object);
  4389. }
  4390. else if (object instanceof Date) {
  4391. return object.toISOString();
  4392. }
  4393. else if (moment.isMoment(object)) {
  4394. return object.toDate().toISOString();
  4395. }
  4396. else if (util.isString(object)) {
  4397. match = ASPDateRegex.exec(object);
  4398. if (match) {
  4399. // object is an ASP date
  4400. return new Date(Number(match[1])).toISOString(); // parse number
  4401. }
  4402. else {
  4403. return new Date(object).toISOString(); // parse string
  4404. }
  4405. }
  4406. else {
  4407. throw new Error(
  4408. 'Cannot convert object of type ' + util.getType(object) +
  4409. ' to type ISODate');
  4410. }
  4411. case 'ASPDate':
  4412. if (util.isNumber(object)) {
  4413. return '/Date(' + object + ')/';
  4414. }
  4415. else if (object instanceof Date) {
  4416. return '/Date(' + object.valueOf() + ')/';
  4417. }
  4418. else if (util.isString(object)) {
  4419. match = ASPDateRegex.exec(object);
  4420. var value;
  4421. if (match) {
  4422. // object is an ASP date
  4423. value = new Date(Number(match[1])).valueOf(); // parse number
  4424. }
  4425. else {
  4426. value = new Date(object).valueOf(); // parse string
  4427. }
  4428. return '/Date(' + value + ')/';
  4429. }
  4430. else {
  4431. throw new Error(
  4432. 'Cannot convert object of type ' + util.getType(object) +
  4433. ' to type ASPDate');
  4434. }
  4435. default:
  4436. throw new Error('Cannot convert object of type ' + util.getType(object) +
  4437. ' to type "' + type + '"');
  4438. }
  4439. };
  4440. // parse ASP.Net Date pattern,
  4441. // for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/'
  4442. // code from http://momentjs.com/
  4443. var ASPDateRegex = /^\/?Date\((\-?\d+)/i;
  4444. /**
  4445. * Get the type of an object, for example util.getType([]) returns 'Array'
  4446. * @param {*} object
  4447. * @return {String} type
  4448. */
  4449. util.getType = function getType(object) {
  4450. var type = typeof object;
  4451. if (type == 'object') {
  4452. if (object == null) {
  4453. return 'null';
  4454. }
  4455. if (object instanceof Boolean) {
  4456. return 'Boolean';
  4457. }
  4458. if (object instanceof Number) {
  4459. return 'Number';
  4460. }
  4461. if (object instanceof String) {
  4462. return 'String';
  4463. }
  4464. if (object instanceof Array) {
  4465. return 'Array';
  4466. }
  4467. if (object instanceof Date) {
  4468. return 'Date';
  4469. }
  4470. return 'Object';
  4471. }
  4472. else if (type == 'number') {
  4473. return 'Number';
  4474. }
  4475. else if (type == 'boolean') {
  4476. return 'Boolean';
  4477. }
  4478. else if (type == 'string') {
  4479. return 'String';
  4480. }
  4481. return type;
  4482. };
  4483. /**
  4484. * Retrieve the absolute left value of a DOM element
  4485. * @param {Element} elem A dom element, for example a div
  4486. * @return {number} left The absolute left position of this element
  4487. * in the browser page.
  4488. */
  4489. util.getAbsoluteLeft = function getAbsoluteLeft (elem) {
  4490. var doc = document.documentElement;
  4491. var body = document.body;
  4492. var left = elem.offsetLeft;
  4493. var e = elem.offsetParent;
  4494. while (e != null && e != body && e != doc) {
  4495. left += e.offsetLeft;
  4496. left -= e.scrollLeft;
  4497. e = e.offsetParent;
  4498. }
  4499. return left;
  4500. };
  4501. /**
  4502. * Retrieve the absolute top value of a DOM element
  4503. * @param {Element} elem A dom element, for example a div
  4504. * @return {number} top The absolute top position of this element
  4505. * in the browser page.
  4506. */
  4507. util.getAbsoluteTop = function getAbsoluteTop (elem) {
  4508. var doc = document.documentElement;
  4509. var body = document.body;
  4510. var top = elem.offsetTop;
  4511. var e = elem.offsetParent;
  4512. while (e != null && e != body && e != doc) {
  4513. top += e.offsetTop;
  4514. top -= e.scrollTop;
  4515. e = e.offsetParent;
  4516. }
  4517. return top;
  4518. };
  4519. /**
  4520. * Get the absolute, vertical mouse position from an event.
  4521. * @param {Event} event
  4522. * @return {Number} pageY
  4523. */
  4524. util.getPageY = function getPageY (event) {
  4525. if ('pageY' in event) {
  4526. return event.pageY;
  4527. }
  4528. else {
  4529. var clientY;
  4530. if (('targetTouches' in event) && event.targetTouches.length) {
  4531. clientY = event.targetTouches[0].clientY;
  4532. }
  4533. else {
  4534. clientY = event.clientY;
  4535. }
  4536. var doc = document.documentElement;
  4537. var body = document.body;
  4538. return clientY +
  4539. ( doc && doc.scrollTop || body && body.scrollTop || 0 ) -
  4540. ( doc && doc.clientTop || body && body.clientTop || 0 );
  4541. }
  4542. };
  4543. /**
  4544. * Get the absolute, horizontal mouse position from an event.
  4545. * @param {Event} event
  4546. * @return {Number} pageX
  4547. */
  4548. util.getPageX = function getPageX (event) {
  4549. if ('pageY' in event) {
  4550. return event.pageX;
  4551. }
  4552. else {
  4553. var clientX;
  4554. if (('targetTouches' in event) && event.targetTouches.length) {
  4555. clientX = event.targetTouches[0].clientX;
  4556. }
  4557. else {
  4558. clientX = event.clientX;
  4559. }
  4560. var doc = document.documentElement;
  4561. var body = document.body;
  4562. return clientX +
  4563. ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) -
  4564. ( doc && doc.clientLeft || body && body.clientLeft || 0 );
  4565. }
  4566. };
  4567. /**
  4568. * add a className to the given elements style
  4569. * @param {Element} elem
  4570. * @param {String} className
  4571. */
  4572. util.addClassName = function addClassName(elem, className) {
  4573. var classes = elem.className.split(' ');
  4574. if (classes.indexOf(className) == -1) {
  4575. classes.push(className); // add the class to the array
  4576. elem.className = classes.join(' ');
  4577. }
  4578. };
  4579. /**
  4580. * add a className to the given elements style
  4581. * @param {Element} elem
  4582. * @param {String} className
  4583. */
  4584. util.removeClassName = function removeClassname(elem, className) {
  4585. var classes = elem.className.split(' ');
  4586. var index = classes.indexOf(className);
  4587. if (index != -1) {
  4588. classes.splice(index, 1); // remove the class from the array
  4589. elem.className = classes.join(' ');
  4590. }
  4591. };
  4592. /**
  4593. * For each method for both arrays and objects.
  4594. * In case of an array, the built-in Array.forEach() is applied.
  4595. * In case of an Object, the method loops over all properties of the object.
  4596. * @param {Object | Array} object An Object or Array
  4597. * @param {function} callback Callback method, called for each item in
  4598. * the object or array with three parameters:
  4599. * callback(value, index, object)
  4600. */
  4601. util.forEach = function forEach (object, callback) {
  4602. var i,
  4603. len;
  4604. if (object instanceof Array) {
  4605. // array
  4606. for (i = 0, len = object.length; i < len; i++) {
  4607. callback(object[i], i, object);
  4608. }
  4609. }
  4610. else {
  4611. // object
  4612. for (i in object) {
  4613. if (object.hasOwnProperty(i)) {
  4614. callback(object[i], i, object);
  4615. }
  4616. }
  4617. }
  4618. };
  4619. /**
  4620. * Update a property in an object
  4621. * @param {Object} object
  4622. * @param {String} key
  4623. * @param {*} value
  4624. * @return {Boolean} changed
  4625. */
  4626. util.updateProperty = function updateProp (object, key, value) {
  4627. if (object[key] !== value) {
  4628. object[key] = value;
  4629. return true;
  4630. }
  4631. else {
  4632. return false;
  4633. }
  4634. };
  4635. /**
  4636. * Add and event listener. Works for all browsers
  4637. * @param {Element} element An html element
  4638. * @param {string} action The action, for example "click",
  4639. * without the prefix "on"
  4640. * @param {function} listener The callback function to be executed
  4641. * @param {boolean} [useCapture]
  4642. */
  4643. util.addEventListener = function addEventListener(element, action, listener, useCapture) {
  4644. if (element.addEventListener) {
  4645. if (useCapture === undefined)
  4646. useCapture = false;
  4647. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  4648. action = "DOMMouseScroll"; // For Firefox
  4649. }
  4650. element.addEventListener(action, listener, useCapture);
  4651. } else {
  4652. element.attachEvent("on" + action, listener); // IE browsers
  4653. }
  4654. };
  4655. /**
  4656. * Remove an event listener from an element
  4657. * @param {Element} element An html dom element
  4658. * @param {string} action The name of the event, for example "mousedown"
  4659. * @param {function} listener The listener function
  4660. * @param {boolean} [useCapture]
  4661. */
  4662. util.removeEventListener = function removeEventListener(element, action, listener, useCapture) {
  4663. if (element.removeEventListener) {
  4664. // non-IE browsers
  4665. if (useCapture === undefined)
  4666. useCapture = false;
  4667. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  4668. action = "DOMMouseScroll"; // For Firefox
  4669. }
  4670. element.removeEventListener(action, listener, useCapture);
  4671. } else {
  4672. // IE browsers
  4673. element.detachEvent("on" + action, listener);
  4674. }
  4675. };
  4676. /**
  4677. * Get HTML element which is the target of the event
  4678. * @param {Event} event
  4679. * @return {Element} target element
  4680. */
  4681. util.getTarget = function getTarget(event) {
  4682. // code from http://www.quirksmode.org/js/events_properties.html
  4683. if (!event) {
  4684. event = window.event;
  4685. }
  4686. var target;
  4687. if (event.target) {
  4688. target = event.target;
  4689. }
  4690. else if (event.srcElement) {
  4691. target = event.srcElement;
  4692. }
  4693. if (target.nodeType != undefined && target.nodeType == 3) {
  4694. // defeat Safari bug
  4695. target = target.parentNode;
  4696. }
  4697. return target;
  4698. };
  4699. /**
  4700. * Stop event propagation
  4701. */
  4702. util.stopPropagation = function stopPropagation(event) {
  4703. if (!event)
  4704. event = window.event;
  4705. if (event.stopPropagation) {
  4706. event.stopPropagation(); // non-IE browsers
  4707. }
  4708. else {
  4709. event.cancelBubble = true; // IE browsers
  4710. }
  4711. };
  4712. /**
  4713. * Cancels the event if it is cancelable, without stopping further propagation of the event.
  4714. */
  4715. util.preventDefault = function preventDefault (event) {
  4716. if (!event)
  4717. event = window.event;
  4718. if (event.preventDefault) {
  4719. event.preventDefault(); // non-IE browsers
  4720. }
  4721. else {
  4722. event.returnValue = false; // IE browsers
  4723. }
  4724. };
  4725. util.option = {};
  4726. /**
  4727. * Convert a value into a boolean
  4728. * @param {Boolean | function | undefined} value
  4729. * @param {Boolean} [defaultValue]
  4730. * @returns {Boolean} bool
  4731. */
  4732. util.option.asBoolean = function (value, defaultValue) {
  4733. if (typeof value == 'function') {
  4734. value = value();
  4735. }
  4736. if (value != null) {
  4737. return (value != false);
  4738. }
  4739. return defaultValue || null;
  4740. };
  4741. /**
  4742. * Convert a value into a number
  4743. * @param {Boolean | function | undefined} value
  4744. * @param {Number} [defaultValue]
  4745. * @returns {Number} number
  4746. */
  4747. util.option.asNumber = function (value, defaultValue) {
  4748. if (typeof value == 'function') {
  4749. value = value();
  4750. }
  4751. if (value != null) {
  4752. return Number(value) || defaultValue || null;
  4753. }
  4754. return defaultValue || null;
  4755. };
  4756. /**
  4757. * Convert a value into a string
  4758. * @param {String | function | undefined} value
  4759. * @param {String} [defaultValue]
  4760. * @returns {String} str
  4761. */
  4762. util.option.asString = function (value, defaultValue) {
  4763. if (typeof value == 'function') {
  4764. value = value();
  4765. }
  4766. if (value != null) {
  4767. return String(value);
  4768. }
  4769. return defaultValue || null;
  4770. };
  4771. /**
  4772. * Convert a size or location into a string with pixels or a percentage
  4773. * @param {String | Number | function | undefined} value
  4774. * @param {String} [defaultValue]
  4775. * @returns {String} size
  4776. */
  4777. util.option.asSize = function (value, defaultValue) {
  4778. if (typeof value == 'function') {
  4779. value = value();
  4780. }
  4781. if (util.isString(value)) {
  4782. return value;
  4783. }
  4784. else if (util.isNumber(value)) {
  4785. return value + 'px';
  4786. }
  4787. else {
  4788. return defaultValue || null;
  4789. }
  4790. };
  4791. /**
  4792. * Convert a value into a DOM element
  4793. * @param {HTMLElement | function | undefined} value
  4794. * @param {HTMLElement} [defaultValue]
  4795. * @returns {HTMLElement | null} dom
  4796. */
  4797. util.option.asElement = function (value, defaultValue) {
  4798. if (typeof value == 'function') {
  4799. value = value();
  4800. }
  4801. return value || defaultValue || null;
  4802. };
  4803. /**
  4804. * load css from text
  4805. * @param {String} css Text containing css
  4806. */
  4807. util.loadCss = function (css) {
  4808. if (typeof document === 'undefined') {
  4809. return;
  4810. }
  4811. // get the script location, and built the css file name from the js file name
  4812. // http://stackoverflow.com/a/2161748/1262753
  4813. // var scripts = document.getElementsByTagName('script');
  4814. // var jsFile = scripts[scripts.length-1].src.split('?')[0];
  4815. // var cssFile = jsFile.substring(0, jsFile.length - 2) + 'css';
  4816. // inject css
  4817. // http://stackoverflow.com/questions/524696/how-to-create-a-style-tag-with-javascript
  4818. var style = document.createElement('style');
  4819. style.type = 'text/css';
  4820. if (style.styleSheet){
  4821. style.styleSheet.cssText = css;
  4822. } else {
  4823. style.appendChild(document.createTextNode(css));
  4824. }
  4825. document.getElementsByTagName('head')[0].appendChild(style);
  4826. };
  4827. /**
  4828. * Event listener (singleton)
  4829. */
  4830. // TODO: replace usage of the event listener for the EventBus
  4831. var events = {
  4832. 'listeners': [],
  4833. /**
  4834. * Find a single listener by its object
  4835. * @param {Object} object
  4836. * @return {Number} index -1 when not found
  4837. */
  4838. 'indexOf': function (object) {
  4839. var listeners = this.listeners;
  4840. for (var i = 0, iMax = this.listeners.length; i < iMax; i++) {
  4841. var listener = listeners[i];
  4842. if (listener && listener.object == object) {
  4843. return i;
  4844. }
  4845. }
  4846. return -1;
  4847. },
  4848. /**
  4849. * Add an event listener
  4850. * @param {Object} object
  4851. * @param {String} event The name of an event, for example 'select'
  4852. * @param {function} callback The callback method, called when the
  4853. * event takes place
  4854. */
  4855. 'addListener': function (object, event, callback) {
  4856. var index = this.indexOf(object);
  4857. var listener = this.listeners[index];
  4858. if (!listener) {
  4859. listener = {
  4860. 'object': object,
  4861. 'events': {}
  4862. };
  4863. this.listeners.push(listener);
  4864. }
  4865. var callbacks = listener.events[event];
  4866. if (!callbacks) {
  4867. callbacks = [];
  4868. listener.events[event] = callbacks;
  4869. }
  4870. // add the callback if it does not yet exist
  4871. if (callbacks.indexOf(callback) == -1) {
  4872. callbacks.push(callback);
  4873. }
  4874. },
  4875. /**
  4876. * Remove an event listener
  4877. * @param {Object} object
  4878. * @param {String} event The name of an event, for example 'select'
  4879. * @param {function} callback The registered callback method
  4880. */
  4881. 'removeListener': function (object, event, callback) {
  4882. var index = this.indexOf(object);
  4883. var listener = this.listeners[index];
  4884. if (listener) {
  4885. var callbacks = listener.events[event];
  4886. if (callbacks) {
  4887. index = callbacks.indexOf(callback);
  4888. if (index != -1) {
  4889. callbacks.splice(index, 1);
  4890. }
  4891. // remove the array when empty
  4892. if (callbacks.length == 0) {
  4893. delete listener.events[event];
  4894. }
  4895. }
  4896. // count the number of registered events. remove listener when empty
  4897. var count = 0;
  4898. var events = listener.events;
  4899. for (var e in events) {
  4900. if (events.hasOwnProperty(e)) {
  4901. count++;
  4902. }
  4903. }
  4904. if (count == 0) {
  4905. delete this.listeners[index];
  4906. }
  4907. }
  4908. },
  4909. /**
  4910. * Remove all registered event listeners
  4911. */
  4912. 'removeAllListeners': function () {
  4913. this.listeners = [];
  4914. },
  4915. /**
  4916. * Trigger an event. All registered event handlers will be called
  4917. * @param {Object} object
  4918. * @param {String} event
  4919. * @param {Object} properties (optional)
  4920. */
  4921. 'trigger': function (object, event, properties) {
  4922. var index = this.indexOf(object);
  4923. var listener = this.listeners[index];
  4924. if (listener) {
  4925. var callbacks = listener.events[event];
  4926. if (callbacks) {
  4927. for (var i = 0, iMax = callbacks.length; i < iMax; i++) {
  4928. callbacks[i](properties);
  4929. }
  4930. }
  4931. }
  4932. }
  4933. };
  4934. /**
  4935. * An event bus can be used to emit events, and to subscribe to events
  4936. * @constructor EventBus
  4937. */
  4938. function EventBus() {
  4939. this.subscriptions = [];
  4940. }
  4941. /**
  4942. * Subscribe to an event
  4943. * @param {String | RegExp} event The event can be a regular expression, or
  4944. * a string with wildcards, like 'server.*'.
  4945. * @param {function} callback. Callback are called with three parameters:
  4946. * {String} event, {*} [data], {*} [source]
  4947. * @param {*} [target]
  4948. * @returns {String} id A subscription id
  4949. */
  4950. EventBus.prototype.on = function (event, callback, target) {
  4951. var regexp = (event instanceof RegExp) ?
  4952. event :
  4953. new RegExp(event.replace('*', '\\w+'));
  4954. var subscription = {
  4955. id: util.randomUUID(),
  4956. event: event,
  4957. regexp: regexp,
  4958. callback: (typeof callback === 'function') ? callback : null,
  4959. target: target
  4960. };
  4961. this.subscriptions.push(subscription);
  4962. return subscription.id;
  4963. };
  4964. /**
  4965. * Unsubscribe from an event
  4966. * @param {String | Object} filter Filter for subscriptions to be removed
  4967. * Filter can be a string containing a
  4968. * subscription id, or an object containing
  4969. * one or more of the fields id, event,
  4970. * callback, and target.
  4971. */
  4972. EventBus.prototype.off = function (filter) {
  4973. var i = 0;
  4974. while (i < this.subscriptions.length) {
  4975. var subscription = this.subscriptions[i];
  4976. var match = true;
  4977. if (filter instanceof Object) {
  4978. // filter is an object. All fields must match
  4979. for (var prop in filter) {
  4980. if (filter.hasOwnProperty(prop)) {
  4981. if (filter[prop] !== subscription[prop]) {
  4982. match = false;
  4983. }
  4984. }
  4985. }
  4986. }
  4987. else {
  4988. // filter is a string, filter on id
  4989. match = (subscription.id == filter);
  4990. }
  4991. if (match) {
  4992. this.subscriptions.splice(i, 1);
  4993. }
  4994. else {
  4995. i++;
  4996. }
  4997. }
  4998. };
  4999. /**
  5000. * Emit an event
  5001. * @param {String} event
  5002. * @param {*} [data]
  5003. * @param {*} [source]
  5004. */
  5005. EventBus.prototype.emit = function (event, data, source) {
  5006. for (var i =0; i < this.subscriptions.length; i++) {
  5007. var subscription = this.subscriptions[i];
  5008. if (subscription.regexp.test(event)) {
  5009. if (subscription.callback) {
  5010. subscription.callback(event, data, source);
  5011. }
  5012. }
  5013. }
  5014. };
  5015. /**
  5016. * DataSet
  5017. *
  5018. * Usage:
  5019. * var dataSet = new DataSet({
  5020. * fieldId: '_id',
  5021. * convert: {
  5022. * // ...
  5023. * }
  5024. * });
  5025. *
  5026. * dataSet.add(item);
  5027. * dataSet.add(data);
  5028. * dataSet.update(item);
  5029. * dataSet.update(data);
  5030. * dataSet.remove(id);
  5031. * dataSet.remove(ids);
  5032. * var data = dataSet.get();
  5033. * var data = dataSet.get(id);
  5034. * var data = dataSet.get(ids);
  5035. * var data = dataSet.get(ids, options, data);
  5036. * dataSet.clear();
  5037. *
  5038. * A data set can:
  5039. * - add/remove/update data
  5040. * - gives triggers upon changes in the data
  5041. * - can import/export data in various data formats
  5042. *
  5043. * @param {Object} [options] Available options:
  5044. * {String} fieldId Field name of the id in the
  5045. * items, 'id' by default.
  5046. * {Object.<String, String} convert
  5047. * A map with field names as key,
  5048. * and the field type as value.
  5049. * @constructor DataSet
  5050. */
  5051. // TODO: add a DataSet constructor DataSet(data, options)
  5052. function DataSet (options) {
  5053. this.id = util.randomUUID();
  5054. this.options = options || {};
  5055. this.data = {}; // map with data indexed by id
  5056. this.fieldId = this.options.fieldId || 'id'; // name of the field containing id
  5057. this.convert = {}; // field types by field name
  5058. this.showInternalIds = this.options.showInternalIds || false; // show internal ids with the get function
  5059. if (this.options.convert) {
  5060. for (var field in this.options.convert) {
  5061. if (this.options.convert.hasOwnProperty(field)) {
  5062. var value = this.options.convert[field];
  5063. if (value == 'Date' || value == 'ISODate' || value == 'ASPDate') {
  5064. this.convert[field] = 'Date';
  5065. }
  5066. else {
  5067. this.convert[field] = value;
  5068. }
  5069. }
  5070. }
  5071. }
  5072. // event subscribers
  5073. this.subscribers = {};
  5074. this.internalIds = {}; // internally generated id's
  5075. }
  5076. /**
  5077. * Subscribe to an event, add an event listener
  5078. * @param {String} event Event name. Available events: 'put', 'update',
  5079. * 'remove'
  5080. * @param {function} callback Callback method. Called with three parameters:
  5081. * {String} event
  5082. * {Object | null} params
  5083. * {String | Number} senderId
  5084. */
  5085. DataSet.prototype.subscribe = function (event, callback) {
  5086. var subscribers = this.subscribers[event];
  5087. if (!subscribers) {
  5088. subscribers = [];
  5089. this.subscribers[event] = subscribers;
  5090. }
  5091. subscribers.push({
  5092. callback: callback
  5093. });
  5094. };
  5095. /**
  5096. * Unsubscribe from an event, remove an event listener
  5097. * @param {String} event
  5098. * @param {function} callback
  5099. */
  5100. DataSet.prototype.unsubscribe = function (event, callback) {
  5101. var subscribers = this.subscribers[event];
  5102. if (subscribers) {
  5103. this.subscribers[event] = subscribers.filter(function (listener) {
  5104. return (listener.callback != callback);
  5105. });
  5106. }
  5107. };
  5108. /**
  5109. * Trigger an event
  5110. * @param {String} event
  5111. * @param {Object | null} params
  5112. * @param {String} [senderId] Optional id of the sender.
  5113. * @private
  5114. */
  5115. DataSet.prototype._trigger = function (event, params, senderId) {
  5116. if (event == '*') {
  5117. throw new Error('Cannot trigger event *');
  5118. }
  5119. var subscribers = [];
  5120. if (event in this.subscribers) {
  5121. subscribers = subscribers.concat(this.subscribers[event]);
  5122. }
  5123. if ('*' in this.subscribers) {
  5124. subscribers = subscribers.concat(this.subscribers['*']);
  5125. }
  5126. for (var i = 0; i < subscribers.length; i++) {
  5127. var subscriber = subscribers[i];
  5128. if (subscriber.callback) {
  5129. subscriber.callback(event, params, senderId || null);
  5130. }
  5131. }
  5132. };
  5133. /**
  5134. * Add data.
  5135. * Adding an item will fail when there already is an item with the same id.
  5136. * @param {Object | Array | DataTable} data
  5137. * @param {String} [senderId] Optional sender id
  5138. * @return {Array} addedIds Array with the ids of the added items
  5139. */
  5140. DataSet.prototype.add = function (data, senderId) {
  5141. var addedIds = [],
  5142. id,
  5143. me = this;
  5144. if (data instanceof Array) {
  5145. // Array
  5146. for (var i = 0, len = data.length; i < len; i++) {
  5147. id = me._addItem(data[i]);
  5148. addedIds.push(id);
  5149. }
  5150. }
  5151. else if (util.isDataTable(data)) {
  5152. // Google DataTable
  5153. var columns = this._getColumnNames(data);
  5154. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  5155. var item = {};
  5156. for (var col = 0, cols = columns.length; col < cols; col++) {
  5157. var field = columns[col];
  5158. item[field] = data.getValue(row, col);
  5159. }
  5160. id = me._addItem(item);
  5161. addedIds.push(id);
  5162. }
  5163. }
  5164. else if (data instanceof Object) {
  5165. // Single item
  5166. id = me._addItem(data);
  5167. addedIds.push(id);
  5168. }
  5169. else {
  5170. throw new Error('Unknown dataType');
  5171. }
  5172. if (addedIds.length) {
  5173. this._trigger('add', {items: addedIds}, senderId);
  5174. }
  5175. return addedIds;
  5176. };
  5177. /**
  5178. * Update existing items. When an item does not exist, it will be created
  5179. * @param {Object | Array | DataTable} data
  5180. * @param {String} [senderId] Optional sender id
  5181. * @return {Array} updatedIds The ids of the added or updated items
  5182. */
  5183. DataSet.prototype.update = function (data, senderId) {
  5184. var addedIds = [],
  5185. updatedIds = [],
  5186. me = this,
  5187. fieldId = me.fieldId;
  5188. var addOrUpdate = function (item) {
  5189. var id = item[fieldId];
  5190. if (me.data[id]) {
  5191. // update item
  5192. id = me._updateItem(item);
  5193. updatedIds.push(id);
  5194. }
  5195. else {
  5196. // add new item
  5197. id = me._addItem(item);
  5198. addedIds.push(id);
  5199. }
  5200. };
  5201. if (data instanceof Array) {
  5202. // Array
  5203. for (var i = 0, len = data.length; i < len; i++) {
  5204. addOrUpdate(data[i]);
  5205. }
  5206. }
  5207. else if (util.isDataTable(data)) {
  5208. // Google DataTable
  5209. var columns = this._getColumnNames(data);
  5210. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  5211. var item = {};
  5212. for (var col = 0, cols = columns.length; col < cols; col++) {
  5213. var field = columns[col];
  5214. item[field] = data.getValue(row, col);
  5215. }
  5216. addOrUpdate(item);
  5217. }
  5218. }
  5219. else if (data instanceof Object) {
  5220. // Single item
  5221. addOrUpdate(data);
  5222. }
  5223. else {
  5224. throw new Error('Unknown dataType');
  5225. }
  5226. if (addedIds.length) {
  5227. this._trigger('add', {items: addedIds}, senderId);
  5228. }
  5229. if (updatedIds.length) {
  5230. this._trigger('update', {items: updatedIds}, senderId);
  5231. }
  5232. return addedIds.concat(updatedIds);
  5233. };
  5234. /**
  5235. * Get a data item or multiple items.
  5236. *
  5237. * Usage:
  5238. *
  5239. * get()
  5240. * get(options: Object)
  5241. * get(options: Object, data: Array | DataTable)
  5242. *
  5243. * get(id: Number | String)
  5244. * get(id: Number | String, options: Object)
  5245. * get(id: Number | String, options: Object, data: Array | DataTable)
  5246. *
  5247. * get(ids: Number[] | String[])
  5248. * get(ids: Number[] | String[], options: Object)
  5249. * get(ids: Number[] | String[], options: Object, data: Array | DataTable)
  5250. *
  5251. * Where:
  5252. *
  5253. * {Number | String} id The id of an item
  5254. * {Number[] | String{}} ids An array with ids of items
  5255. * {Object} options An Object with options. Available options:
  5256. * {String} [type] Type of data to be returned. Can
  5257. * be 'DataTable' or 'Array' (default)
  5258. * {Object.<String, String>} [convert]
  5259. * {String[]} [fields] field names to be returned
  5260. * {function} [filter] filter items
  5261. * {String | function} [order] Order the items by
  5262. * a field name or custom sort function.
  5263. * {Array | DataTable} [data] If provided, items will be appended to this
  5264. * array or table. Required in case of Google
  5265. * DataTable.
  5266. *
  5267. * @throws Error
  5268. */
  5269. DataSet.prototype.get = function (args) {
  5270. var me = this;
  5271. var globalShowInternalIds = this.showInternalIds;
  5272. // parse the arguments
  5273. var id, ids, options, data;
  5274. var firstType = util.getType(arguments[0]);
  5275. if (firstType == 'String' || firstType == 'Number') {
  5276. // get(id [, options] [, data])
  5277. id = arguments[0];
  5278. options = arguments[1];
  5279. data = arguments[2];
  5280. }
  5281. else if (firstType == 'Array') {
  5282. // get(ids [, options] [, data])
  5283. ids = arguments[0];
  5284. options = arguments[1];
  5285. data = arguments[2];
  5286. }
  5287. else {
  5288. // get([, options] [, data])
  5289. options = arguments[0];
  5290. data = arguments[1];
  5291. }
  5292. // determine the return type
  5293. var type;
  5294. if (options && options.type) {
  5295. type = (options.type == 'DataTable') ? 'DataTable' : 'Array';
  5296. if (data && (type != util.getType(data))) {
  5297. throw new Error('Type of parameter "data" (' + util.getType(data) + ') ' +
  5298. 'does not correspond with specified options.type (' + options.type + ')');
  5299. }
  5300. if (type == 'DataTable' && !util.isDataTable(data)) {
  5301. throw new Error('Parameter "data" must be a DataTable ' +
  5302. 'when options.type is "DataTable"');
  5303. }
  5304. }
  5305. else if (data) {
  5306. type = (util.getType(data) == 'DataTable') ? 'DataTable' : 'Array';
  5307. }
  5308. else {
  5309. type = 'Array';
  5310. }
  5311. // we allow the setting of this value for a single get request.
  5312. if (options != undefined) {
  5313. if (options.showInternalIds != undefined) {
  5314. this.showInternalIds = options.showInternalIds;
  5315. }
  5316. }
  5317. // build options
  5318. var convert = options && options.convert || this.options.convert;
  5319. var filter = options && options.filter;
  5320. var items = [], item, itemId, i, len;
  5321. // convert items
  5322. if (id != undefined) {
  5323. // return a single item
  5324. item = me._getItem(id, convert);
  5325. if (filter && !filter(item)) {
  5326. item = null;
  5327. }
  5328. }
  5329. else if (ids != undefined) {
  5330. // return a subset of items
  5331. for (i = 0, len = ids.length; i < len; i++) {
  5332. item = me._getItem(ids[i], convert);
  5333. if (!filter || filter(item)) {
  5334. items.push(item);
  5335. }
  5336. }
  5337. }
  5338. else {
  5339. // return all items
  5340. for (itemId in this.data) {
  5341. if (this.data.hasOwnProperty(itemId)) {
  5342. item = me._getItem(itemId, convert);
  5343. if (!filter || filter(item)) {
  5344. items.push(item);
  5345. }
  5346. }
  5347. }
  5348. }
  5349. // restore the global value of showInternalIds
  5350. this.showInternalIds = globalShowInternalIds;
  5351. // order the results
  5352. if (options && options.order && id == undefined) {
  5353. this._sort(items, options.order);
  5354. }
  5355. // filter fields of the items
  5356. if (options && options.fields) {
  5357. var fields = options.fields;
  5358. if (id != undefined) {
  5359. item = this._filterFields(item, fields);
  5360. }
  5361. else {
  5362. for (i = 0, len = items.length; i < len; i++) {
  5363. items[i] = this._filterFields(items[i], fields);
  5364. }
  5365. }
  5366. }
  5367. // return the results
  5368. if (type == 'DataTable') {
  5369. var columns = this._getColumnNames(data);
  5370. if (id != undefined) {
  5371. // append a single item to the data table
  5372. me._appendRow(data, columns, item);
  5373. }
  5374. else {
  5375. // copy the items to the provided data table
  5376. for (i = 0, len = items.length; i < len; i++) {
  5377. me._appendRow(data, columns, items[i]);
  5378. }
  5379. }
  5380. return data;
  5381. }
  5382. else {
  5383. // return an array
  5384. if (id != undefined) {
  5385. // a single item
  5386. return item;
  5387. }
  5388. else {
  5389. // multiple items
  5390. if (data) {
  5391. // copy the items to the provided array
  5392. for (i = 0, len = items.length; i < len; i++) {
  5393. data.push(items[i]);
  5394. }
  5395. return data;
  5396. }
  5397. else {
  5398. // just return our array
  5399. return items;
  5400. }
  5401. }
  5402. }
  5403. };
  5404. /**
  5405. * Get ids of all items or from a filtered set of items.
  5406. * @param {Object} [options] An Object with options. Available options:
  5407. * {function} [filter] filter items
  5408. * {String | function} [order] Order the items by
  5409. * a field name or custom sort function.
  5410. * @return {Array} ids
  5411. */
  5412. DataSet.prototype.getIds = function (options) {
  5413. var data = this.data,
  5414. filter = options && options.filter,
  5415. order = options && options.order,
  5416. convert = options && options.convert || this.options.convert,
  5417. i,
  5418. len,
  5419. id,
  5420. item,
  5421. items,
  5422. ids = [];
  5423. if (filter) {
  5424. // get filtered items
  5425. if (order) {
  5426. // create ordered list
  5427. items = [];
  5428. for (id in data) {
  5429. if (data.hasOwnProperty(id)) {
  5430. item = this._getItem(id, convert);
  5431. if (filter(item)) {
  5432. items.push(item);
  5433. }
  5434. }
  5435. }
  5436. this._sort(items, order);
  5437. for (i = 0, len = items.length; i < len; i++) {
  5438. ids[i] = items[i][this.fieldId];
  5439. }
  5440. }
  5441. else {
  5442. // create unordered list
  5443. for (id in data) {
  5444. if (data.hasOwnProperty(id)) {
  5445. item = this._getItem(id, convert);
  5446. if (filter(item)) {
  5447. ids.push(item[this.fieldId]);
  5448. }
  5449. }
  5450. }
  5451. }
  5452. }
  5453. else {
  5454. // get all items
  5455. if (order) {
  5456. // create an ordered list
  5457. items = [];
  5458. for (id in data) {
  5459. if (data.hasOwnProperty(id)) {
  5460. items.push(data[id]);
  5461. }
  5462. }
  5463. this._sort(items, order);
  5464. for (i = 0, len = items.length; i < len; i++) {
  5465. ids[i] = items[i][this.fieldId];
  5466. }
  5467. }
  5468. else {
  5469. // create unordered list
  5470. for (id in data) {
  5471. if (data.hasOwnProperty(id)) {
  5472. item = data[id];
  5473. ids.push(item[this.fieldId]);
  5474. }
  5475. }
  5476. }
  5477. }
  5478. return ids;
  5479. };
  5480. /**
  5481. * Execute a callback function for every item in the dataset.
  5482. * The order of the items is not determined.
  5483. * @param {function} callback
  5484. * @param {Object} [options] Available options:
  5485. * {Object.<String, String>} [convert]
  5486. * {String[]} [fields] filter fields
  5487. * {function} [filter] filter items
  5488. * {String | function} [order] Order the items by
  5489. * a field name or custom sort function.
  5490. */
  5491. DataSet.prototype.forEach = function (callback, options) {
  5492. var filter = options && options.filter,
  5493. convert = options && options.convert || this.options.convert,
  5494. data = this.data,
  5495. item,
  5496. id;
  5497. if (options && options.order) {
  5498. // execute forEach on ordered list
  5499. var items = this.get(options);
  5500. for (var i = 0, len = items.length; i < len; i++) {
  5501. item = items[i];
  5502. id = item[this.fieldId];
  5503. callback(item, id);
  5504. }
  5505. }
  5506. else {
  5507. // unordered
  5508. for (id in data) {
  5509. if (data.hasOwnProperty(id)) {
  5510. item = this._getItem(id, convert);
  5511. if (!filter || filter(item)) {
  5512. callback(item, id);
  5513. }
  5514. }
  5515. }
  5516. }
  5517. };
  5518. /**
  5519. * Map every item in the dataset.
  5520. * @param {function} callback
  5521. * @param {Object} [options] Available options:
  5522. * {Object.<String, String>} [convert]
  5523. * {String[]} [fields] filter fields
  5524. * {function} [filter] filter items
  5525. * {String | function} [order] Order the items by
  5526. * a field name or custom sort function.
  5527. * @return {Object[]} mappedItems
  5528. */
  5529. DataSet.prototype.map = function (callback, options) {
  5530. var filter = options && options.filter,
  5531. convert = options && options.convert || this.options.convert,
  5532. mappedItems = [],
  5533. data = this.data,
  5534. item;
  5535. // convert and filter items
  5536. for (var id in data) {
  5537. if (data.hasOwnProperty(id)) {
  5538. item = this._getItem(id, convert);
  5539. if (!filter || filter(item)) {
  5540. mappedItems.push(callback(item, id));
  5541. }
  5542. }
  5543. }
  5544. // order items
  5545. if (options && options.order) {
  5546. this._sort(mappedItems, options.order);
  5547. }
  5548. return mappedItems;
  5549. };
  5550. /**
  5551. * Filter the fields of an item
  5552. * @param {Object} item
  5553. * @param {String[]} fields Field names
  5554. * @return {Object} filteredItem
  5555. * @private
  5556. */
  5557. DataSet.prototype._filterFields = function (item, fields) {
  5558. var filteredItem = {};
  5559. for (var field in item) {
  5560. if (item.hasOwnProperty(field) && (fields.indexOf(field) != -1)) {
  5561. filteredItem[field] = item[field];
  5562. }
  5563. }
  5564. return filteredItem;
  5565. };
  5566. /**
  5567. * Sort the provided array with items
  5568. * @param {Object[]} items
  5569. * @param {String | function} order A field name or custom sort function.
  5570. * @private
  5571. */
  5572. DataSet.prototype._sort = function (items, order) {
  5573. if (util.isString(order)) {
  5574. // order by provided field name
  5575. var name = order; // field name
  5576. items.sort(function (a, b) {
  5577. var av = a[name];
  5578. var bv = b[name];
  5579. return (av > bv) ? 1 : ((av < bv) ? -1 : 0);
  5580. });
  5581. }
  5582. else if (typeof order === 'function') {
  5583. // order by sort function
  5584. items.sort(order);
  5585. }
  5586. // TODO: extend order by an Object {field:String, direction:String}
  5587. // where direction can be 'asc' or 'desc'
  5588. else {
  5589. throw new TypeError('Order must be a function or a string');
  5590. }
  5591. };
  5592. /**
  5593. * Remove an object by pointer or by id
  5594. * @param {String | Number | Object | Array} id Object or id, or an array with
  5595. * objects or ids to be removed
  5596. * @param {String} [senderId] Optional sender id
  5597. * @return {Array} removedIds
  5598. */
  5599. DataSet.prototype.remove = function (id, senderId) {
  5600. var removedIds = [],
  5601. i, len, removedId;
  5602. if (id instanceof Array) {
  5603. for (i = 0, len = id.length; i < len; i++) {
  5604. removedId = this._remove(id[i]);
  5605. if (removedId != null) {
  5606. removedIds.push(removedId);
  5607. }
  5608. }
  5609. }
  5610. else {
  5611. removedId = this._remove(id);
  5612. if (removedId != null) {
  5613. removedIds.push(removedId);
  5614. }
  5615. }
  5616. if (removedIds.length) {
  5617. this._trigger('remove', {items: removedIds}, senderId);
  5618. }
  5619. return removedIds;
  5620. };
  5621. /**
  5622. * Remove an item by its id
  5623. * @param {Number | String | Object} id id or item
  5624. * @returns {Number | String | null} id
  5625. * @private
  5626. */
  5627. DataSet.prototype._remove = function (id) {
  5628. if (util.isNumber(id) || util.isString(id)) {
  5629. if (this.data[id]) {
  5630. delete this.data[id];
  5631. delete this.internalIds[id];
  5632. return id;
  5633. }
  5634. }
  5635. else if (id instanceof Object) {
  5636. var itemId = id[this.fieldId];
  5637. if (itemId && this.data[itemId]) {
  5638. delete this.data[itemId];
  5639. delete this.internalIds[itemId];
  5640. return itemId;
  5641. }
  5642. }
  5643. return null;
  5644. };
  5645. /**
  5646. * Clear the data
  5647. * @param {String} [senderId] Optional sender id
  5648. * @return {Array} removedIds The ids of all removed items
  5649. */
  5650. DataSet.prototype.clear = function (senderId) {
  5651. var ids = Object.keys(this.data);
  5652. this.data = {};
  5653. this.internalIds = {};
  5654. this._trigger('remove', {items: ids}, senderId);
  5655. return ids;
  5656. };
  5657. /**
  5658. * Find the item with maximum value of a specified field
  5659. * @param {String} field
  5660. * @return {Object | null} item Item containing max value, or null if no items
  5661. */
  5662. DataSet.prototype.max = function (field) {
  5663. var data = this.data,
  5664. max = null,
  5665. maxField = null;
  5666. for (var id in data) {
  5667. if (data.hasOwnProperty(id)) {
  5668. var item = data[id];
  5669. var itemField = item[field];
  5670. if (itemField != null && (!max || itemField > maxField)) {
  5671. max = item;
  5672. maxField = itemField;
  5673. }
  5674. }
  5675. }
  5676. return max;
  5677. };
  5678. /**
  5679. * Find the item with minimum value of a specified field
  5680. * @param {String} field
  5681. * @return {Object | null} item Item containing max value, or null if no items
  5682. */
  5683. DataSet.prototype.min = function (field) {
  5684. var data = this.data,
  5685. min = null,
  5686. minField = null;
  5687. for (var id in data) {
  5688. if (data.hasOwnProperty(id)) {
  5689. var item = data[id];
  5690. var itemField = item[field];
  5691. if (itemField != null && (!min || itemField < minField)) {
  5692. min = item;
  5693. minField = itemField;
  5694. }
  5695. }
  5696. }
  5697. return min;
  5698. };
  5699. /**
  5700. * Find all distinct values of a specified field
  5701. * @param {String} field
  5702. * @return {Array} values Array containing all distinct values. If the data
  5703. * items do not contain the specified field, an array
  5704. * containing a single value undefined is returned.
  5705. * The returned array is unordered.
  5706. */
  5707. DataSet.prototype.distinct = function (field) {
  5708. var data = this.data,
  5709. values = [],
  5710. fieldType = this.options.convert[field],
  5711. count = 0;
  5712. for (var prop in data) {
  5713. if (data.hasOwnProperty(prop)) {
  5714. var item = data[prop];
  5715. var value = util.convert(item[field], fieldType);
  5716. var exists = false;
  5717. for (var i = 0; i < count; i++) {
  5718. if (values[i] == value) {
  5719. exists = true;
  5720. break;
  5721. }
  5722. }
  5723. if (!exists) {
  5724. values[count] = value;
  5725. count++;
  5726. }
  5727. }
  5728. }
  5729. return values;
  5730. };
  5731. /**
  5732. * Add a single item. Will fail when an item with the same id already exists.
  5733. * @param {Object} item
  5734. * @return {String} id
  5735. * @private
  5736. */
  5737. DataSet.prototype._addItem = function (item) {
  5738. var id = item[this.fieldId];
  5739. if (id != undefined) {
  5740. // check whether this id is already taken
  5741. if (this.data[id]) {
  5742. // item already exists
  5743. throw new Error('Cannot add item: item with id ' + id + ' already exists');
  5744. }
  5745. }
  5746. else {
  5747. // generate an id
  5748. id = util.randomUUID();
  5749. item[this.fieldId] = id;
  5750. this.internalIds[id] = item;
  5751. }
  5752. var d = {};
  5753. for (var field in item) {
  5754. if (item.hasOwnProperty(field)) {
  5755. var fieldType = this.convert[field]; // type may be undefined
  5756. d[field] = util.convert(item[field], fieldType);
  5757. }
  5758. }
  5759. this.data[id] = d;
  5760. return id;
  5761. };
  5762. /**
  5763. * Get an item. Fields can be converted to a specific type
  5764. * @param {String} id
  5765. * @param {Object.<String, String>} [convert] field types to convert
  5766. * @return {Object | null} item
  5767. * @private
  5768. */
  5769. DataSet.prototype._getItem = function (id, convert) {
  5770. var field, value;
  5771. // get the item from the dataset
  5772. var raw = this.data[id];
  5773. if (!raw) {
  5774. return null;
  5775. }
  5776. // convert the items field types
  5777. var converted = {},
  5778. fieldId = this.fieldId,
  5779. internalIds = this.internalIds;
  5780. if (convert) {
  5781. for (field in raw) {
  5782. if (raw.hasOwnProperty(field)) {
  5783. value = raw[field];
  5784. // output all fields, except internal ids
  5785. if ((field != fieldId) || (!(value in internalIds) || this.showInternalIds)) {
  5786. converted[field] = util.convert(value, convert[field]);
  5787. }
  5788. }
  5789. }
  5790. }
  5791. else {
  5792. // no field types specified, no converting needed
  5793. for (field in raw) {
  5794. if (raw.hasOwnProperty(field)) {
  5795. value = raw[field];
  5796. // output all fields, except internal ids
  5797. if ((field != fieldId) || (!(value in internalIds) || this.showInternalIds)) {
  5798. converted[field] = value;
  5799. }
  5800. }
  5801. }
  5802. }
  5803. return converted;
  5804. };
  5805. /**
  5806. * Update a single item: merge with existing item.
  5807. * Will fail when the item has no id, or when there does not exist an item
  5808. * with the same id.
  5809. * @param {Object} item
  5810. * @return {String} id
  5811. * @private
  5812. */
  5813. DataSet.prototype._updateItem = function (item) {
  5814. var id = item[this.fieldId];
  5815. if (id == undefined) {
  5816. throw new Error('Cannot update item: item has no id (item: ' + JSON.stringify(item) + ')');
  5817. }
  5818. var d = this.data[id];
  5819. if (!d) {
  5820. // item doesn't exist
  5821. throw new Error('Cannot update item: no item with id ' + id + ' found');
  5822. }
  5823. // merge with current item
  5824. for (var field in item) {
  5825. if (item.hasOwnProperty(field)) {
  5826. var fieldType = this.convert[field]; // type may be undefined
  5827. d[field] = util.convert(item[field], fieldType);
  5828. }
  5829. }
  5830. return id;
  5831. };
  5832. /**
  5833. * check if an id is an internal or external id
  5834. * @param id
  5835. * @returns {boolean}
  5836. * @private
  5837. */
  5838. DataSet.prototype.isInternalId = function(id) {
  5839. return (id in this.internalIds);
  5840. };
  5841. /**
  5842. * Get an array with the column names of a Google DataTable
  5843. * @param {DataTable} dataTable
  5844. * @return {String[]} columnNames
  5845. * @private
  5846. */
  5847. DataSet.prototype._getColumnNames = function (dataTable) {
  5848. var columns = [];
  5849. for (var col = 0, cols = dataTable.getNumberOfColumns(); col < cols; col++) {
  5850. columns[col] = dataTable.getColumnId(col) || dataTable.getColumnLabel(col);
  5851. }
  5852. return columns;
  5853. };
  5854. /**
  5855. * Append an item as a row to the dataTable
  5856. * @param dataTable
  5857. * @param columns
  5858. * @param item
  5859. * @private
  5860. */
  5861. DataSet.prototype._appendRow = function (dataTable, columns, item) {
  5862. var row = dataTable.addRow();
  5863. for (var col = 0, cols = columns.length; col < cols; col++) {
  5864. var field = columns[col];
  5865. dataTable.setValue(row, col, item[field]);
  5866. }
  5867. };
  5868. /**
  5869. * DataView
  5870. *
  5871. * a dataview offers a filtered view on a dataset or an other dataview.
  5872. *
  5873. * @param {DataSet | DataView} data
  5874. * @param {Object} [options] Available options: see method get
  5875. *
  5876. * @constructor DataView
  5877. */
  5878. function DataView (data, options) {
  5879. this.id = util.randomUUID();
  5880. this.data = null;
  5881. this.ids = {}; // ids of the items currently in memory (just contains a boolean true)
  5882. this.options = options || {};
  5883. this.fieldId = 'id'; // name of the field containing id
  5884. this.subscribers = {}; // event subscribers
  5885. var me = this;
  5886. this.listener = function () {
  5887. me._onEvent.apply(me, arguments);
  5888. };
  5889. this.setData(data);
  5890. }
  5891. // TODO: implement a function .config() to dynamically update things like configured filter
  5892. // and trigger changes accordingly
  5893. /**
  5894. * Set a data source for the view
  5895. * @param {DataSet | DataView} data
  5896. */
  5897. DataView.prototype.setData = function (data) {
  5898. var ids, dataItems, i, len;
  5899. if (this.data) {
  5900. // unsubscribe from current dataset
  5901. if (this.data.unsubscribe) {
  5902. this.data.unsubscribe('*', this.listener);
  5903. }
  5904. // trigger a remove of all items in memory
  5905. ids = [];
  5906. for (var id in this.ids) {
  5907. if (this.ids.hasOwnProperty(id)) {
  5908. ids.push(id);
  5909. }
  5910. }
  5911. this.ids = {};
  5912. this._trigger('remove', {items: ids});
  5913. }
  5914. this.data = data;
  5915. if (this.data) {
  5916. // update fieldId
  5917. this.fieldId = this.options.fieldId ||
  5918. (this.data && this.data.options && this.data.options.fieldId) ||
  5919. 'id';
  5920. // trigger an add of all added items
  5921. ids = this.data.getIds({filter: this.options && this.options.filter});
  5922. for (i = 0, len = ids.length; i < len; i++) {
  5923. id = ids[i];
  5924. this.ids[id] = true;
  5925. }
  5926. this._trigger('add', {items: ids});
  5927. // subscribe to new dataset
  5928. if (this.data.subscribe) {
  5929. this.data.subscribe('*', this.listener);
  5930. }
  5931. }
  5932. };
  5933. /**
  5934. * Get data from the data view
  5935. *
  5936. * Usage:
  5937. *
  5938. * get()
  5939. * get(options: Object)
  5940. * get(options: Object, data: Array | DataTable)
  5941. *
  5942. * get(id: Number)
  5943. * get(id: Number, options: Object)
  5944. * get(id: Number, options: Object, data: Array | DataTable)
  5945. *
  5946. * get(ids: Number[])
  5947. * get(ids: Number[], options: Object)
  5948. * get(ids: Number[], options: Object, data: Array | DataTable)
  5949. *
  5950. * Where:
  5951. *
  5952. * {Number | String} id The id of an item
  5953. * {Number[] | String{}} ids An array with ids of items
  5954. * {Object} options An Object with options. Available options:
  5955. * {String} [type] Type of data to be returned. Can
  5956. * be 'DataTable' or 'Array' (default)
  5957. * {Object.<String, String>} [convert]
  5958. * {String[]} [fields] field names to be returned
  5959. * {function} [filter] filter items
  5960. * {String | function} [order] Order the items by
  5961. * a field name or custom sort function.
  5962. * {Array | DataTable} [data] If provided, items will be appended to this
  5963. * array or table. Required in case of Google
  5964. * DataTable.
  5965. * @param args
  5966. */
  5967. DataView.prototype.get = function (args) {
  5968. var me = this;
  5969. // parse the arguments
  5970. var ids, options, data;
  5971. var firstType = util.getType(arguments[0]);
  5972. if (firstType == 'String' || firstType == 'Number' || firstType == 'Array') {
  5973. // get(id(s) [, options] [, data])
  5974. ids = arguments[0]; // can be a single id or an array with ids
  5975. options = arguments[1];
  5976. data = arguments[2];
  5977. }
  5978. else {
  5979. // get([, options] [, data])
  5980. options = arguments[0];
  5981. data = arguments[1];
  5982. }
  5983. // extend the options with the default options and provided options
  5984. var viewOptions = util.extend({}, this.options, options);
  5985. // create a combined filter method when needed
  5986. if (this.options.filter && options && options.filter) {
  5987. viewOptions.filter = function (item) {
  5988. return me.options.filter(item) && options.filter(item);
  5989. }
  5990. }
  5991. // build up the call to the linked data set
  5992. var getArguments = [];
  5993. if (ids != undefined) {
  5994. getArguments.push(ids);
  5995. }
  5996. getArguments.push(viewOptions);
  5997. getArguments.push(data);
  5998. return this.data && this.data.get.apply(this.data, getArguments);
  5999. };
  6000. /**
  6001. * Get ids of all items or from a filtered set of items.
  6002. * @param {Object} [options] An Object with options. Available options:
  6003. * {function} [filter] filter items
  6004. * {String | function} [order] Order the items by
  6005. * a field name or custom sort function.
  6006. * @return {Array} ids
  6007. */
  6008. DataView.prototype.getIds = function (options) {
  6009. var ids;
  6010. if (this.data) {
  6011. var defaultFilter = this.options.filter;
  6012. var filter;
  6013. if (options && options.filter) {
  6014. if (defaultFilter) {
  6015. filter = function (item) {
  6016. return defaultFilter(item) && options.filter(item);
  6017. }
  6018. }
  6019. else {
  6020. filter = options.filter;
  6021. }
  6022. }
  6023. else {
  6024. filter = defaultFilter;
  6025. }
  6026. ids = this.data.getIds({
  6027. filter: filter,
  6028. order: options && options.order
  6029. });
  6030. }
  6031. else {
  6032. ids = [];
  6033. }
  6034. return ids;
  6035. };
  6036. /**
  6037. * Event listener. Will propagate all events from the connected data set to
  6038. * the subscribers of the DataView, but will filter the items and only trigger
  6039. * when there are changes in the filtered data set.
  6040. * @param {String} event
  6041. * @param {Object | null} params
  6042. * @param {String} senderId
  6043. * @private
  6044. */
  6045. DataView.prototype._onEvent = function (event, params, senderId) {
  6046. var i, len, id, item,
  6047. ids = params && params.items,
  6048. data = this.data,
  6049. added = [],
  6050. updated = [],
  6051. removed = [];
  6052. if (ids && data) {
  6053. switch (event) {
  6054. case 'add':
  6055. // filter the ids of the added items
  6056. for (i = 0, len = ids.length; i < len; i++) {
  6057. id = ids[i];
  6058. item = this.get(id);
  6059. if (item) {
  6060. this.ids[id] = true;
  6061. added.push(id);
  6062. }
  6063. }
  6064. break;
  6065. case 'update':
  6066. // determine the event from the views viewpoint: an updated
  6067. // item can be added, updated, or removed from this view.
  6068. for (i = 0, len = ids.length; i < len; i++) {
  6069. id = ids[i];
  6070. item = this.get(id);
  6071. if (item) {
  6072. if (this.ids[id]) {
  6073. updated.push(id);
  6074. }
  6075. else {
  6076. this.ids[id] = true;
  6077. added.push(id);
  6078. }
  6079. }
  6080. else {
  6081. if (this.ids[id]) {
  6082. delete this.ids[id];
  6083. removed.push(id);
  6084. }
  6085. else {
  6086. // nothing interesting for me :-(
  6087. }
  6088. }
  6089. }
  6090. break;
  6091. case 'remove':
  6092. // filter the ids of the removed items
  6093. for (i = 0, len = ids.length; i < len; i++) {
  6094. id = ids[i];
  6095. if (this.ids[id]) {
  6096. delete this.ids[id];
  6097. removed.push(id);
  6098. }
  6099. }
  6100. break;
  6101. }
  6102. if (added.length) {
  6103. this._trigger('add', {items: added}, senderId);
  6104. }
  6105. if (updated.length) {
  6106. this._trigger('update', {items: updated}, senderId);
  6107. }
  6108. if (removed.length) {
  6109. this._trigger('remove', {items: removed}, senderId);
  6110. }
  6111. }
  6112. };
  6113. // copy subscription functionality from DataSet
  6114. DataView.prototype.subscribe = DataSet.prototype.subscribe;
  6115. DataView.prototype.unsubscribe = DataSet.prototype.unsubscribe;
  6116. DataView.prototype._trigger = DataSet.prototype._trigger;
  6117. /**
  6118. * @constructor TimeStep
  6119. * The class TimeStep is an iterator for dates. You provide a start date and an
  6120. * end date. The class itself determines the best scale (step size) based on the
  6121. * provided start Date, end Date, and minimumStep.
  6122. *
  6123. * If minimumStep is provided, the step size is chosen as close as possible
  6124. * to the minimumStep but larger than minimumStep. If minimumStep is not
  6125. * provided, the scale is set to 1 DAY.
  6126. * The minimumStep should correspond with the onscreen size of about 6 characters
  6127. *
  6128. * Alternatively, you can set a scale by hand.
  6129. * After creation, you can initialize the class by executing first(). Then you
  6130. * can iterate from the start date to the end date via next(). You can check if
  6131. * the end date is reached with the function hasNext(). After each step, you can
  6132. * retrieve the current date via getCurrent().
  6133. * The TimeStep has scales ranging from milliseconds, seconds, minutes, hours,
  6134. * days, to years.
  6135. *
  6136. * Version: 1.2
  6137. *
  6138. * @param {Date} [start] The start date, for example new Date(2010, 9, 21)
  6139. * or new Date(2010, 9, 21, 23, 45, 00)
  6140. * @param {Date} [end] The end date
  6141. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  6142. */
  6143. TimeStep = function(start, end, minimumStep) {
  6144. // variables
  6145. this.current = new Date();
  6146. this._start = new Date();
  6147. this._end = new Date();
  6148. this.autoScale = true;
  6149. this.scale = TimeStep.SCALE.DAY;
  6150. this.step = 1;
  6151. // initialize the range
  6152. this.setRange(start, end, minimumStep);
  6153. };
  6154. /// enum scale
  6155. TimeStep.SCALE = {
  6156. MILLISECOND: 1,
  6157. SECOND: 2,
  6158. MINUTE: 3,
  6159. HOUR: 4,
  6160. DAY: 5,
  6161. WEEKDAY: 6,
  6162. MONTH: 7,
  6163. YEAR: 8
  6164. };
  6165. /**
  6166. * Set a new range
  6167. * If minimumStep is provided, the step size is chosen as close as possible
  6168. * to the minimumStep but larger than minimumStep. If minimumStep is not
  6169. * provided, the scale is set to 1 DAY.
  6170. * The minimumStep should correspond with the onscreen size of about 6 characters
  6171. * @param {Date} [start] The start date and time.
  6172. * @param {Date} [end] The end date and time.
  6173. * @param {int} [minimumStep] Optional. Minimum step size in milliseconds
  6174. */
  6175. TimeStep.prototype.setRange = function(start, end, minimumStep) {
  6176. if (!(start instanceof Date) || !(end instanceof Date)) {
  6177. throw "No legal start or end date in method setRange";
  6178. }
  6179. this._start = (start != undefined) ? new Date(start.valueOf()) : new Date();
  6180. this._end = (end != undefined) ? new Date(end.valueOf()) : new Date();
  6181. if (this.autoScale) {
  6182. this.setMinimumStep(minimumStep);
  6183. }
  6184. };
  6185. /**
  6186. * Set the range iterator to the start date.
  6187. */
  6188. TimeStep.prototype.first = function() {
  6189. this.current = new Date(this._start.valueOf());
  6190. this.roundToMinor();
  6191. };
  6192. /**
  6193. * Round the current date to the first minor date value
  6194. * This must be executed once when the current date is set to start Date
  6195. */
  6196. TimeStep.prototype.roundToMinor = function() {
  6197. // round to floor
  6198. // IMPORTANT: we have no breaks in this switch! (this is no bug)
  6199. //noinspection FallthroughInSwitchStatementJS
  6200. switch (this.scale) {
  6201. case TimeStep.SCALE.YEAR:
  6202. this.current.setFullYear(this.step * Math.floor(this.current.getFullYear() / this.step));
  6203. this.current.setMonth(0);
  6204. case TimeStep.SCALE.MONTH: this.current.setDate(1);
  6205. case TimeStep.SCALE.DAY: // intentional fall through
  6206. case TimeStep.SCALE.WEEKDAY: this.current.setHours(0);
  6207. case TimeStep.SCALE.HOUR: this.current.setMinutes(0);
  6208. case TimeStep.SCALE.MINUTE: this.current.setSeconds(0);
  6209. case TimeStep.SCALE.SECOND: this.current.setMilliseconds(0);
  6210. //case TimeStep.SCALE.MILLISECOND: // nothing to do for milliseconds
  6211. }
  6212. if (this.step != 1) {
  6213. // round down to the first minor value that is a multiple of the current step size
  6214. switch (this.scale) {
  6215. case TimeStep.SCALE.MILLISECOND: this.current.setMilliseconds(this.current.getMilliseconds() - this.current.getMilliseconds() % this.step); break;
  6216. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() - this.current.getSeconds() % this.step); break;
  6217. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() - this.current.getMinutes() % this.step); break;
  6218. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() - this.current.getHours() % this.step); break;
  6219. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  6220. case TimeStep.SCALE.DAY: this.current.setDate((this.current.getDate()-1) - (this.current.getDate()-1) % this.step + 1); break;
  6221. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() - this.current.getMonth() % this.step); break;
  6222. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() - this.current.getFullYear() % this.step); break;
  6223. default: break;
  6224. }
  6225. }
  6226. };
  6227. /**
  6228. * Check if the there is a next step
  6229. * @return {boolean} true if the current date has not passed the end date
  6230. */
  6231. TimeStep.prototype.hasNext = function () {
  6232. return (this.current.valueOf() <= this._end.valueOf());
  6233. };
  6234. /**
  6235. * Do the next step
  6236. */
  6237. TimeStep.prototype.next = function() {
  6238. var prev = this.current.valueOf();
  6239. // Two cases, needed to prevent issues with switching daylight savings
  6240. // (end of March and end of October)
  6241. if (this.current.getMonth() < 6) {
  6242. switch (this.scale) {
  6243. case TimeStep.SCALE.MILLISECOND:
  6244. this.current = new Date(this.current.valueOf() + this.step); break;
  6245. case TimeStep.SCALE.SECOND: this.current = new Date(this.current.valueOf() + this.step * 1000); break;
  6246. case TimeStep.SCALE.MINUTE: this.current = new Date(this.current.valueOf() + this.step * 1000 * 60); break;
  6247. case TimeStep.SCALE.HOUR:
  6248. this.current = new Date(this.current.valueOf() + this.step * 1000 * 60 * 60);
  6249. // in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...)
  6250. var h = this.current.getHours();
  6251. this.current.setHours(h - (h % this.step));
  6252. break;
  6253. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  6254. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  6255. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  6256. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  6257. default: break;
  6258. }
  6259. }
  6260. else {
  6261. switch (this.scale) {
  6262. case TimeStep.SCALE.MILLISECOND: this.current = new Date(this.current.valueOf() + this.step); break;
  6263. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() + this.step); break;
  6264. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() + this.step); break;
  6265. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() + this.step); break;
  6266. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  6267. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  6268. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  6269. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  6270. default: break;
  6271. }
  6272. }
  6273. if (this.step != 1) {
  6274. // round down to the correct major value
  6275. switch (this.scale) {
  6276. case TimeStep.SCALE.MILLISECOND: if(this.current.getMilliseconds() < this.step) this.current.setMilliseconds(0); break;
  6277. case TimeStep.SCALE.SECOND: if(this.current.getSeconds() < this.step) this.current.setSeconds(0); break;
  6278. case TimeStep.SCALE.MINUTE: if(this.current.getMinutes() < this.step) this.current.setMinutes(0); break;
  6279. case TimeStep.SCALE.HOUR: if(this.current.getHours() < this.step) this.current.setHours(0); break;
  6280. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  6281. case TimeStep.SCALE.DAY: if(this.current.getDate() < this.step+1) this.current.setDate(1); break;
  6282. case TimeStep.SCALE.MONTH: if(this.current.getMonth() < this.step) this.current.setMonth(0); break;
  6283. case TimeStep.SCALE.YEAR: break; // nothing to do for year
  6284. default: break;
  6285. }
  6286. }
  6287. // safety mechanism: if current time is still unchanged, move to the end
  6288. if (this.current.valueOf() == prev) {
  6289. this.current = new Date(this._end.valueOf());
  6290. }
  6291. };
  6292. /**
  6293. * Get the current datetime
  6294. * @return {Date} current The current date
  6295. */
  6296. TimeStep.prototype.getCurrent = function() {
  6297. return this.current;
  6298. };
  6299. /**
  6300. * Set a custom scale. Autoscaling will be disabled.
  6301. * For example setScale(SCALE.MINUTES, 5) will result
  6302. * in minor steps of 5 minutes, and major steps of an hour.
  6303. *
  6304. * @param {TimeStep.SCALE} newScale
  6305. * A scale. Choose from SCALE.MILLISECOND,
  6306. * SCALE.SECOND, SCALE.MINUTE, SCALE.HOUR,
  6307. * SCALE.WEEKDAY, SCALE.DAY, SCALE.MONTH,
  6308. * SCALE.YEAR.
  6309. * @param {Number} newStep A step size, by default 1. Choose for
  6310. * example 1, 2, 5, or 10.
  6311. */
  6312. TimeStep.prototype.setScale = function(newScale, newStep) {
  6313. this.scale = newScale;
  6314. if (newStep > 0) {
  6315. this.step = newStep;
  6316. }
  6317. this.autoScale = false;
  6318. };
  6319. /**
  6320. * Enable or disable autoscaling
  6321. * @param {boolean} enable If true, autoascaling is set true
  6322. */
  6323. TimeStep.prototype.setAutoScale = function (enable) {
  6324. this.autoScale = enable;
  6325. };
  6326. /**
  6327. * Automatically determine the scale that bests fits the provided minimum step
  6328. * @param {Number} [minimumStep] The minimum step size in milliseconds
  6329. */
  6330. TimeStep.prototype.setMinimumStep = function(minimumStep) {
  6331. if (minimumStep == undefined) {
  6332. return;
  6333. }
  6334. var stepYear = (1000 * 60 * 60 * 24 * 30 * 12);
  6335. var stepMonth = (1000 * 60 * 60 * 24 * 30);
  6336. var stepDay = (1000 * 60 * 60 * 24);
  6337. var stepHour = (1000 * 60 * 60);
  6338. var stepMinute = (1000 * 60);
  6339. var stepSecond = (1000);
  6340. var stepMillisecond= (1);
  6341. // find the smallest step that is larger than the provided minimumStep
  6342. if (stepYear*1000 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1000;}
  6343. if (stepYear*500 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 500;}
  6344. if (stepYear*100 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 100;}
  6345. if (stepYear*50 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 50;}
  6346. if (stepYear*10 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 10;}
  6347. if (stepYear*5 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 5;}
  6348. if (stepYear > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1;}
  6349. if (stepMonth*3 > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 3;}
  6350. if (stepMonth > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 1;}
  6351. if (stepDay*5 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 5;}
  6352. if (stepDay*2 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 2;}
  6353. if (stepDay > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 1;}
  6354. if (stepDay/2 > minimumStep) {this.scale = TimeStep.SCALE.WEEKDAY; this.step = 1;}
  6355. if (stepHour*4 > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 4;}
  6356. if (stepHour > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 1;}
  6357. if (stepMinute*15 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 15;}
  6358. if (stepMinute*10 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 10;}
  6359. if (stepMinute*5 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 5;}
  6360. if (stepMinute > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 1;}
  6361. if (stepSecond*15 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 15;}
  6362. if (stepSecond*10 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 10;}
  6363. if (stepSecond*5 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 5;}
  6364. if (stepSecond > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 1;}
  6365. if (stepMillisecond*200 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 200;}
  6366. if (stepMillisecond*100 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 100;}
  6367. if (stepMillisecond*50 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 50;}
  6368. if (stepMillisecond*10 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 10;}
  6369. if (stepMillisecond*5 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 5;}
  6370. if (stepMillisecond > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 1;}
  6371. };
  6372. /**
  6373. * Snap a date to a rounded value. The snap intervals are dependent on the
  6374. * current scale and step.
  6375. * @param {Date} date the date to be snapped
  6376. */
  6377. TimeStep.prototype.snap = function(date) {
  6378. if (this.scale == TimeStep.SCALE.YEAR) {
  6379. var year = date.getFullYear() + Math.round(date.getMonth() / 12);
  6380. date.setFullYear(Math.round(year / this.step) * this.step);
  6381. date.setMonth(0);
  6382. date.setDate(0);
  6383. date.setHours(0);
  6384. date.setMinutes(0);
  6385. date.setSeconds(0);
  6386. date.setMilliseconds(0);
  6387. }
  6388. else if (this.scale == TimeStep.SCALE.MONTH) {
  6389. if (date.getDate() > 15) {
  6390. date.setDate(1);
  6391. date.setMonth(date.getMonth() + 1);
  6392. // important: first set Date to 1, after that change the month.
  6393. }
  6394. else {
  6395. date.setDate(1);
  6396. }
  6397. date.setHours(0);
  6398. date.setMinutes(0);
  6399. date.setSeconds(0);
  6400. date.setMilliseconds(0);
  6401. }
  6402. else if (this.scale == TimeStep.SCALE.DAY ||
  6403. this.scale == TimeStep.SCALE.WEEKDAY) {
  6404. //noinspection FallthroughInSwitchStatementJS
  6405. switch (this.step) {
  6406. case 5:
  6407. case 2:
  6408. date.setHours(Math.round(date.getHours() / 24) * 24); break;
  6409. default:
  6410. date.setHours(Math.round(date.getHours() / 12) * 12); break;
  6411. }
  6412. date.setMinutes(0);
  6413. date.setSeconds(0);
  6414. date.setMilliseconds(0);
  6415. }
  6416. else if (this.scale == TimeStep.SCALE.HOUR) {
  6417. switch (this.step) {
  6418. case 4:
  6419. date.setMinutes(Math.round(date.getMinutes() / 60) * 60); break;
  6420. default:
  6421. date.setMinutes(Math.round(date.getMinutes() / 30) * 30); break;
  6422. }
  6423. date.setSeconds(0);
  6424. date.setMilliseconds(0);
  6425. } else if (this.scale == TimeStep.SCALE.MINUTE) {
  6426. //noinspection FallthroughInSwitchStatementJS
  6427. switch (this.step) {
  6428. case 15:
  6429. case 10:
  6430. date.setMinutes(Math.round(date.getMinutes() / 5) * 5);
  6431. date.setSeconds(0);
  6432. break;
  6433. case 5:
  6434. date.setSeconds(Math.round(date.getSeconds() / 60) * 60); break;
  6435. default:
  6436. date.setSeconds(Math.round(date.getSeconds() / 30) * 30); break;
  6437. }
  6438. date.setMilliseconds(0);
  6439. }
  6440. else if (this.scale == TimeStep.SCALE.SECOND) {
  6441. //noinspection FallthroughInSwitchStatementJS
  6442. switch (this.step) {
  6443. case 15:
  6444. case 10:
  6445. date.setSeconds(Math.round(date.getSeconds() / 5) * 5);
  6446. date.setMilliseconds(0);
  6447. break;
  6448. case 5:
  6449. date.setMilliseconds(Math.round(date.getMilliseconds() / 1000) * 1000); break;
  6450. default:
  6451. date.setMilliseconds(Math.round(date.getMilliseconds() / 500) * 500); break;
  6452. }
  6453. }
  6454. else if (this.scale == TimeStep.SCALE.MILLISECOND) {
  6455. var step = this.step > 5 ? this.step / 2 : 1;
  6456. date.setMilliseconds(Math.round(date.getMilliseconds() / step) * step);
  6457. }
  6458. };
  6459. /**
  6460. * Check if the current value is a major value (for example when the step
  6461. * is DAY, a major value is each first day of the MONTH)
  6462. * @return {boolean} true if current date is major, else false.
  6463. */
  6464. TimeStep.prototype.isMajor = function() {
  6465. switch (this.scale) {
  6466. case TimeStep.SCALE.MILLISECOND:
  6467. return (this.current.getMilliseconds() == 0);
  6468. case TimeStep.SCALE.SECOND:
  6469. return (this.current.getSeconds() == 0);
  6470. case TimeStep.SCALE.MINUTE:
  6471. return (this.current.getHours() == 0) && (this.current.getMinutes() == 0);
  6472. // Note: this is no bug. Major label is equal for both minute and hour scale
  6473. case TimeStep.SCALE.HOUR:
  6474. return (this.current.getHours() == 0);
  6475. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  6476. case TimeStep.SCALE.DAY:
  6477. return (this.current.getDate() == 1);
  6478. case TimeStep.SCALE.MONTH:
  6479. return (this.current.getMonth() == 0);
  6480. case TimeStep.SCALE.YEAR:
  6481. return false;
  6482. default:
  6483. return false;
  6484. }
  6485. };
  6486. /**
  6487. * Returns formatted text for the minor axislabel, depending on the current
  6488. * date and the scale. For example when scale is MINUTE, the current time is
  6489. * formatted as "hh:mm".
  6490. * @param {Date} [date] custom date. if not provided, current date is taken
  6491. */
  6492. TimeStep.prototype.getLabelMinor = function(date) {
  6493. if (date == undefined) {
  6494. date = this.current;
  6495. }
  6496. switch (this.scale) {
  6497. case TimeStep.SCALE.MILLISECOND: return moment(date).format('SSS');
  6498. case TimeStep.SCALE.SECOND: return moment(date).format('s');
  6499. case TimeStep.SCALE.MINUTE: return moment(date).format('HH:mm');
  6500. case TimeStep.SCALE.HOUR: return moment(date).format('HH:mm');
  6501. case TimeStep.SCALE.WEEKDAY: return moment(date).format('ddd D');
  6502. case TimeStep.SCALE.DAY: return moment(date).format('D');
  6503. case TimeStep.SCALE.MONTH: return moment(date).format('MMM');
  6504. case TimeStep.SCALE.YEAR: return moment(date).format('YYYY');
  6505. default: return '';
  6506. }
  6507. };
  6508. /**
  6509. * Returns formatted text for the major axis label, depending on the current
  6510. * date and the scale. For example when scale is MINUTE, the major scale is
  6511. * hours, and the hour will be formatted as "hh".
  6512. * @param {Date} [date] custom date. if not provided, current date is taken
  6513. */
  6514. TimeStep.prototype.getLabelMajor = function(date) {
  6515. if (date == undefined) {
  6516. date = this.current;
  6517. }
  6518. //noinspection FallthroughInSwitchStatementJS
  6519. switch (this.scale) {
  6520. case TimeStep.SCALE.MILLISECOND:return moment(date).format('HH:mm:ss');
  6521. case TimeStep.SCALE.SECOND: return moment(date).format('D MMMM HH:mm');
  6522. case TimeStep.SCALE.MINUTE:
  6523. case TimeStep.SCALE.HOUR: return moment(date).format('ddd D MMMM');
  6524. case TimeStep.SCALE.WEEKDAY:
  6525. case TimeStep.SCALE.DAY: return moment(date).format('MMMM YYYY');
  6526. case TimeStep.SCALE.MONTH: return moment(date).format('YYYY');
  6527. case TimeStep.SCALE.YEAR: return '';
  6528. default: return '';
  6529. }
  6530. };
  6531. /**
  6532. * @constructor Stack
  6533. * Stacks items on top of each other.
  6534. * @param {ItemSet} parent
  6535. * @param {Object} [options]
  6536. */
  6537. function Stack (parent, options) {
  6538. this.parent = parent;
  6539. this.options = options || {};
  6540. this.defaultOptions = {
  6541. order: function (a, b) {
  6542. //return (b.width - a.width) || (a.left - b.left); // TODO: cleanup
  6543. // Order: ranges over non-ranges, ranged ordered by width, and
  6544. // lastly ordered by start.
  6545. if (a instanceof ItemRange) {
  6546. if (b instanceof ItemRange) {
  6547. var aInt = (a.data.end - a.data.start);
  6548. var bInt = (b.data.end - b.data.start);
  6549. return (aInt - bInt) || (a.data.start - b.data.start);
  6550. }
  6551. else {
  6552. return -1;
  6553. }
  6554. }
  6555. else {
  6556. if (b instanceof ItemRange) {
  6557. return 1;
  6558. }
  6559. else {
  6560. return (a.data.start - b.data.start);
  6561. }
  6562. }
  6563. },
  6564. margin: {
  6565. item: 10
  6566. }
  6567. };
  6568. this.ordered = []; // ordered items
  6569. }
  6570. /**
  6571. * Set options for the stack
  6572. * @param {Object} options Available options:
  6573. * {ItemSet} parent
  6574. * {Number} margin
  6575. * {function} order Stacking order
  6576. */
  6577. Stack.prototype.setOptions = function setOptions (options) {
  6578. util.extend(this.options, options);
  6579. // TODO: register on data changes at the connected parent itemset, and update the changed part only and immediately
  6580. };
  6581. /**
  6582. * Stack the items such that they don't overlap. The items will have a minimal
  6583. * distance equal to options.margin.item.
  6584. */
  6585. Stack.prototype.update = function update() {
  6586. this._order();
  6587. this._stack();
  6588. };
  6589. /**
  6590. * Order the items. The items are ordered by width first, and by left position
  6591. * second.
  6592. * If a custom order function has been provided via the options, then this will
  6593. * be used.
  6594. * @private
  6595. */
  6596. Stack.prototype._order = function _order () {
  6597. var items = this.parent.items;
  6598. if (!items) {
  6599. throw new Error('Cannot stack items: parent does not contain items');
  6600. }
  6601. // TODO: store the sorted items, to have less work later on
  6602. var ordered = [];
  6603. var index = 0;
  6604. // items is a map (no array)
  6605. util.forEach(items, function (item) {
  6606. if (item.visible) {
  6607. ordered[index] = item;
  6608. index++;
  6609. }
  6610. });
  6611. //if a customer stack order function exists, use it.
  6612. var order = this.options.order || this.defaultOptions.order;
  6613. if (!(typeof order === 'function')) {
  6614. throw new Error('Option order must be a function');
  6615. }
  6616. ordered.sort(order);
  6617. this.ordered = ordered;
  6618. };
  6619. /**
  6620. * Adjust vertical positions of the events such that they don't overlap each
  6621. * other.
  6622. * @private
  6623. */
  6624. Stack.prototype._stack = function _stack () {
  6625. var i,
  6626. iMax,
  6627. ordered = this.ordered,
  6628. options = this.options,
  6629. orientation = options.orientation || this.defaultOptions.orientation,
  6630. axisOnTop = (orientation == 'top'),
  6631. margin;
  6632. if (options.margin && options.margin.item !== undefined) {
  6633. margin = options.margin.item;
  6634. }
  6635. else {
  6636. margin = this.defaultOptions.margin.item
  6637. }
  6638. // calculate new, non-overlapping positions
  6639. for (i = 0, iMax = ordered.length; i < iMax; i++) {
  6640. var item = ordered[i];
  6641. var collidingItem = null;
  6642. do {
  6643. // TODO: optimize checking for overlap. when there is a gap without items,
  6644. // you only need to check for items from the next item on, not from zero
  6645. collidingItem = this.checkOverlap(ordered, i, 0, i - 1, margin);
  6646. if (collidingItem != null) {
  6647. // There is a collision. Reposition the event above the colliding element
  6648. if (axisOnTop) {
  6649. item.top = collidingItem.top + collidingItem.height + margin;
  6650. }
  6651. else {
  6652. item.top = collidingItem.top - item.height - margin;
  6653. }
  6654. }
  6655. } while (collidingItem);
  6656. }
  6657. };
  6658. /**
  6659. * Check if the destiny position of given item overlaps with any
  6660. * of the other items from index itemStart to itemEnd.
  6661. * @param {Array} items Array with items
  6662. * @param {int} itemIndex Number of the item to be checked for overlap
  6663. * @param {int} itemStart First item to be checked.
  6664. * @param {int} itemEnd Last item to be checked.
  6665. * @return {Object | null} colliding item, or undefined when no collisions
  6666. * @param {Number} margin A minimum required margin.
  6667. * If margin is provided, the two items will be
  6668. * marked colliding when they overlap or
  6669. * when the margin between the two is smaller than
  6670. * the requested margin.
  6671. */
  6672. Stack.prototype.checkOverlap = function checkOverlap (items, itemIndex,
  6673. itemStart, itemEnd, margin) {
  6674. var collision = this.collision;
  6675. // we loop from end to start, as we suppose that the chance of a
  6676. // collision is larger for items at the end, so check these first.
  6677. var a = items[itemIndex];
  6678. for (var i = itemEnd; i >= itemStart; i--) {
  6679. var b = items[i];
  6680. if (collision(a, b, margin)) {
  6681. if (i != itemIndex) {
  6682. return b;
  6683. }
  6684. }
  6685. }
  6686. return null;
  6687. };
  6688. /**
  6689. * Test if the two provided items collide
  6690. * The items must have parameters left, width, top, and height.
  6691. * @param {Component} a The first item
  6692. * @param {Component} b The second item
  6693. * @param {Number} margin A minimum required margin.
  6694. * If margin is provided, the two items will be
  6695. * marked colliding when they overlap or
  6696. * when the margin between the two is smaller than
  6697. * the requested margin.
  6698. * @return {boolean} true if a and b collide, else false
  6699. */
  6700. Stack.prototype.collision = function collision (a, b, margin) {
  6701. return ((a.left - margin) < (b.left + b.getWidth()) &&
  6702. (a.left + a.getWidth() + margin) > b.left &&
  6703. (a.top - margin) < (b.top + b.height) &&
  6704. (a.top + a.height + margin) > b.top);
  6705. };
  6706. /**
  6707. * @constructor Range
  6708. * A Range controls a numeric range with a start and end value.
  6709. * The Range adjusts the range based on mouse events or programmatic changes,
  6710. * and triggers events when the range is changing or has been changed.
  6711. * @param {Object} [options] See description at Range.setOptions
  6712. * @extends Controller
  6713. */
  6714. function Range(options) {
  6715. this.id = util.randomUUID();
  6716. this.start = null; // Number
  6717. this.end = null; // Number
  6718. this.options = options || {};
  6719. this.setOptions(options);
  6720. }
  6721. /**
  6722. * Set options for the range controller
  6723. * @param {Object} options Available options:
  6724. * {Number} min Minimum value for start
  6725. * {Number} max Maximum value for end
  6726. * {Number} zoomMin Set a minimum value for
  6727. * (end - start).
  6728. * {Number} zoomMax Set a maximum value for
  6729. * (end - start).
  6730. */
  6731. Range.prototype.setOptions = function (options) {
  6732. util.extend(this.options, options);
  6733. // re-apply range with new limitations
  6734. if (this.start !== null && this.end !== null) {
  6735. this.setRange(this.start, this.end);
  6736. }
  6737. };
  6738. /**
  6739. * Test whether direction has a valid value
  6740. * @param {String} direction 'horizontal' or 'vertical'
  6741. */
  6742. function validateDirection (direction) {
  6743. if (direction != 'horizontal' && direction != 'vertical') {
  6744. throw new TypeError('Unknown direction "' + direction + '". ' +
  6745. 'Choose "horizontal" or "vertical".');
  6746. }
  6747. }
  6748. /**
  6749. * Add listeners for mouse and touch events to the component
  6750. * @param {Component} component
  6751. * @param {String} event Available events: 'move', 'zoom'
  6752. * @param {String} direction Available directions: 'horizontal', 'vertical'
  6753. */
  6754. Range.prototype.subscribe = function (component, event, direction) {
  6755. var me = this;
  6756. if (event == 'move') {
  6757. // drag start listener
  6758. component.on('dragstart', function (event) {
  6759. me._onDragStart(event, component);
  6760. });
  6761. // drag listener
  6762. component.on('drag', function (event) {
  6763. me._onDrag(event, component, direction);
  6764. });
  6765. // drag end listener
  6766. component.on('dragend', function (event) {
  6767. me._onDragEnd(event, component);
  6768. });
  6769. }
  6770. else if (event == 'zoom') {
  6771. // mouse wheel
  6772. function mousewheel (event) {
  6773. me._onMouseWheel(event, component, direction);
  6774. }
  6775. component.on('mousewheel', mousewheel);
  6776. component.on('DOMMouseScroll', mousewheel); // For FF
  6777. // pinch
  6778. component.on('touch', function (event) {
  6779. me._onTouch();
  6780. });
  6781. component.on('pinch', function (event) {
  6782. me._onPinch(event, component, direction);
  6783. });
  6784. }
  6785. else {
  6786. throw new TypeError('Unknown event "' + event + '". ' +
  6787. 'Choose "move" or "zoom".');
  6788. }
  6789. };
  6790. /**
  6791. * Event handler
  6792. * @param {String} event name of the event, for example 'click', 'mousemove'
  6793. * @param {function} callback callback handler, invoked with the raw HTML Event
  6794. * as parameter.
  6795. */
  6796. Range.prototype.on = function (event, callback) {
  6797. events.addListener(this, event, callback);
  6798. };
  6799. /**
  6800. * Trigger an event
  6801. * @param {String} event name of the event, available events: 'rangechange',
  6802. * 'rangechanged'
  6803. * @private
  6804. */
  6805. Range.prototype._trigger = function (event) {
  6806. events.trigger(this, event, {
  6807. start: this.start,
  6808. end: this.end
  6809. });
  6810. };
  6811. /**
  6812. * Set a new start and end range
  6813. * @param {Number} [start]
  6814. * @param {Number} [end]
  6815. */
  6816. Range.prototype.setRange = function(start, end) {
  6817. var changed = this._applyRange(start, end);
  6818. if (changed) {
  6819. this._trigger('rangechange');
  6820. this._trigger('rangechanged');
  6821. }
  6822. };
  6823. /**
  6824. * Set a new start and end range. This method is the same as setRange, but
  6825. * does not trigger a range change and range changed event, and it returns
  6826. * true when the range is changed
  6827. * @param {Number} [start]
  6828. * @param {Number} [end]
  6829. * @return {Boolean} changed
  6830. * @private
  6831. */
  6832. Range.prototype._applyRange = function(start, end) {
  6833. var newStart = (start != null) ? util.convert(start, 'Number') : this.start,
  6834. newEnd = (end != null) ? util.convert(end, 'Number') : this.end,
  6835. max = (this.options.max != null) ? util.convert(this.options.max, 'Date').valueOf() : null,
  6836. min = (this.options.min != null) ? util.convert(this.options.min, 'Date').valueOf() : null,
  6837. diff;
  6838. // check for valid number
  6839. if (isNaN(newStart) || newStart === null) {
  6840. throw new Error('Invalid start "' + start + '"');
  6841. }
  6842. if (isNaN(newEnd) || newEnd === null) {
  6843. throw new Error('Invalid end "' + end + '"');
  6844. }
  6845. // prevent start < end
  6846. if (newEnd < newStart) {
  6847. newEnd = newStart;
  6848. }
  6849. // prevent start < min
  6850. if (min !== null) {
  6851. if (newStart < min) {
  6852. diff = (min - newStart);
  6853. newStart += diff;
  6854. newEnd += diff;
  6855. // prevent end > max
  6856. if (max != null) {
  6857. if (newEnd > max) {
  6858. newEnd = max;
  6859. }
  6860. }
  6861. }
  6862. }
  6863. // prevent end > max
  6864. if (max !== null) {
  6865. if (newEnd > max) {
  6866. diff = (newEnd - max);
  6867. newStart -= diff;
  6868. newEnd -= diff;
  6869. // prevent start < min
  6870. if (min != null) {
  6871. if (newStart < min) {
  6872. newStart = min;
  6873. }
  6874. }
  6875. }
  6876. }
  6877. // prevent (end-start) < zoomMin
  6878. if (this.options.zoomMin !== null) {
  6879. var zoomMin = parseFloat(this.options.zoomMin);
  6880. if (zoomMin < 0) {
  6881. zoomMin = 0;
  6882. }
  6883. if ((newEnd - newStart) < zoomMin) {
  6884. if ((this.end - this.start) === zoomMin) {
  6885. // ignore this action, we are already zoomed to the minimum
  6886. newStart = this.start;
  6887. newEnd = this.end;
  6888. }
  6889. else {
  6890. // zoom to the minimum
  6891. diff = (zoomMin - (newEnd - newStart));
  6892. newStart -= diff / 2;
  6893. newEnd += diff / 2;
  6894. }
  6895. }
  6896. }
  6897. // prevent (end-start) > zoomMax
  6898. if (this.options.zoomMax !== null) {
  6899. var zoomMax = parseFloat(this.options.zoomMax);
  6900. if (zoomMax < 0) {
  6901. zoomMax = 0;
  6902. }
  6903. if ((newEnd - newStart) > zoomMax) {
  6904. if ((this.end - this.start) === zoomMax) {
  6905. // ignore this action, we are already zoomed to the maximum
  6906. newStart = this.start;
  6907. newEnd = this.end;
  6908. }
  6909. else {
  6910. // zoom to the maximum
  6911. diff = ((newEnd - newStart) - zoomMax);
  6912. newStart += diff / 2;
  6913. newEnd -= diff / 2;
  6914. }
  6915. }
  6916. }
  6917. var changed = (this.start != newStart || this.end != newEnd);
  6918. this.start = newStart;
  6919. this.end = newEnd;
  6920. return changed;
  6921. };
  6922. /**
  6923. * Retrieve the current range.
  6924. * @return {Object} An object with start and end properties
  6925. */
  6926. Range.prototype.getRange = function() {
  6927. return {
  6928. start: this.start,
  6929. end: this.end
  6930. };
  6931. };
  6932. /**
  6933. * Calculate the conversion offset and scale for current range, based on
  6934. * the provided width
  6935. * @param {Number} width
  6936. * @returns {{offset: number, scale: number}} conversion
  6937. */
  6938. Range.prototype.conversion = function (width) {
  6939. return Range.conversion(this.start, this.end, width);
  6940. };
  6941. /**
  6942. * Static method to calculate the conversion offset and scale for a range,
  6943. * based on the provided start, end, and width
  6944. * @param {Number} start
  6945. * @param {Number} end
  6946. * @param {Number} width
  6947. * @returns {{offset: number, scale: number}} conversion
  6948. */
  6949. Range.conversion = function (start, end, width) {
  6950. if (width != 0 && (end - start != 0)) {
  6951. return {
  6952. offset: start,
  6953. scale: width / (end - start)
  6954. }
  6955. }
  6956. else {
  6957. return {
  6958. offset: 0,
  6959. scale: 1
  6960. };
  6961. }
  6962. };
  6963. // global (private) object to store drag params
  6964. var touchParams = {};
  6965. /**
  6966. * Start dragging horizontally or vertically
  6967. * @param {Event} event
  6968. * @param {Object} component
  6969. * @private
  6970. */
  6971. Range.prototype._onDragStart = function(event, component) {
  6972. // refuse to drag when we where pinching to prevent the timeline make a jump
  6973. // when releasing the fingers in opposite order from the touch screen
  6974. if (touchParams.pinching) return;
  6975. touchParams.start = this.start;
  6976. touchParams.end = this.end;
  6977. var frame = component.frame;
  6978. if (frame) {
  6979. frame.style.cursor = 'move';
  6980. }
  6981. };
  6982. /**
  6983. * Perform dragging operating.
  6984. * @param {Event} event
  6985. * @param {Component} component
  6986. * @param {String} direction 'horizontal' or 'vertical'
  6987. * @private
  6988. */
  6989. Range.prototype._onDrag = function (event, component, direction) {
  6990. validateDirection(direction);
  6991. // refuse to drag when we where pinching to prevent the timeline make a jump
  6992. // when releasing the fingers in opposite order from the touch screen
  6993. if (touchParams.pinching) return;
  6994. var delta = (direction == 'horizontal') ? event.gesture.deltaX : event.gesture.deltaY,
  6995. interval = (touchParams.end - touchParams.start),
  6996. width = (direction == 'horizontal') ? component.width : component.height,
  6997. diffRange = -delta / width * interval;
  6998. this._applyRange(touchParams.start + diffRange, touchParams.end + diffRange);
  6999. // fire a rangechange event
  7000. this._trigger('rangechange');
  7001. };
  7002. /**
  7003. * Stop dragging operating.
  7004. * @param {event} event
  7005. * @param {Component} component
  7006. * @private
  7007. */
  7008. Range.prototype._onDragEnd = function (event, component) {
  7009. // refuse to drag when we where pinching to prevent the timeline make a jump
  7010. // when releasing the fingers in opposite order from the touch screen
  7011. if (touchParams.pinching) return;
  7012. if (component.frame) {
  7013. component.frame.style.cursor = 'auto';
  7014. }
  7015. // fire a rangechanged event
  7016. this._trigger('rangechanged');
  7017. };
  7018. /**
  7019. * Event handler for mouse wheel event, used to zoom
  7020. * Code from http://adomas.org/javascript-mouse-wheel/
  7021. * @param {Event} event
  7022. * @param {Component} component
  7023. * @param {String} direction 'horizontal' or 'vertical'
  7024. * @private
  7025. */
  7026. Range.prototype._onMouseWheel = function(event, component, direction) {
  7027. validateDirection(direction);
  7028. // retrieve delta
  7029. var delta = 0;
  7030. if (event.wheelDelta) { /* IE/Opera. */
  7031. delta = event.wheelDelta / 120;
  7032. } else if (event.detail) { /* Mozilla case. */
  7033. // In Mozilla, sign of delta is different than in IE.
  7034. // Also, delta is multiple of 3.
  7035. delta = -event.detail / 3;
  7036. }
  7037. // If delta is nonzero, handle it.
  7038. // Basically, delta is now positive if wheel was scrolled up,
  7039. // and negative, if wheel was scrolled down.
  7040. if (delta) {
  7041. // perform the zoom action. Delta is normally 1 or -1
  7042. // adjust a negative delta such that zooming in with delta 0.1
  7043. // equals zooming out with a delta -0.1
  7044. var scale;
  7045. if (delta < 0) {
  7046. scale = 1 - (delta / 5);
  7047. }
  7048. else {
  7049. scale = 1 / (1 + (delta / 5)) ;
  7050. }
  7051. // calculate center, the date to zoom around
  7052. var gesture = Hammer.event.collectEventData(this, 'scroll', event),
  7053. pointer = getPointer(gesture.touches[0], component.frame),
  7054. pointerDate = this._pointerToDate(component, direction, pointer);
  7055. this.zoom(scale, pointerDate);
  7056. }
  7057. // Prevent default actions caused by mouse wheel
  7058. // (else the page and timeline both zoom and scroll)
  7059. util.preventDefault(event);
  7060. };
  7061. /**
  7062. * On start of a touch gesture, initialize scale to 1
  7063. * @private
  7064. */
  7065. Range.prototype._onTouch = function () {
  7066. touchParams.start = this.start;
  7067. touchParams.end = this.end;
  7068. touchParams.pinching = false;
  7069. touchParams.center = null;
  7070. };
  7071. /**
  7072. * Handle pinch event
  7073. * @param {Event} event
  7074. * @param {Component} component
  7075. * @param {String} direction 'horizontal' or 'vertical'
  7076. * @private
  7077. */
  7078. Range.prototype._onPinch = function (event, component, direction) {
  7079. touchParams.pinching = true;
  7080. if (event.gesture.touches.length > 1) {
  7081. if (!touchParams.center) {
  7082. touchParams.center = getPointer(event.gesture.center, component.frame);
  7083. }
  7084. var scale = 1 / event.gesture.scale,
  7085. initDate = this._pointerToDate(component, direction, touchParams.center),
  7086. center = getPointer(event.gesture.center, component.frame),
  7087. date = this._pointerToDate(component, direction, center),
  7088. delta = date - initDate; // TODO: utilize delta
  7089. // calculate new start and end
  7090. var newStart = parseInt(initDate + (touchParams.start - initDate) * scale);
  7091. var newEnd = parseInt(initDate + (touchParams.end - initDate) * scale);
  7092. // apply new range
  7093. this.setRange(newStart, newEnd);
  7094. }
  7095. };
  7096. /**
  7097. * Helper function to calculate the center date for zooming
  7098. * @param {Component} component
  7099. * @param {{x: Number, y: Number}} pointer
  7100. * @param {String} direction 'horizontal' or 'vertical'
  7101. * @return {number} date
  7102. * @private
  7103. */
  7104. Range.prototype._pointerToDate = function (component, direction, pointer) {
  7105. var conversion;
  7106. if (direction == 'horizontal') {
  7107. var width = component.width;
  7108. conversion = this.conversion(width);
  7109. return pointer.x / conversion.scale + conversion.offset;
  7110. }
  7111. else {
  7112. var height = component.height;
  7113. conversion = this.conversion(height);
  7114. return pointer.y / conversion.scale + conversion.offset;
  7115. }
  7116. };
  7117. /**
  7118. * Get the pointer location relative to the location of the dom element
  7119. * @param {{pageX: Number, pageY: Number}} touch
  7120. * @param {Element} element HTML DOM element
  7121. * @return {{x: Number, y: Number}} pointer
  7122. * @private
  7123. */
  7124. function getPointer (touch, element) {
  7125. return {
  7126. x: touch.pageX - vis.util.getAbsoluteLeft(element),
  7127. y: touch.pageY - vis.util.getAbsoluteTop(element)
  7128. };
  7129. }
  7130. /**
  7131. * Zoom the range the given scale in or out. Start and end date will
  7132. * be adjusted, and the timeline will be redrawn. You can optionally give a
  7133. * date around which to zoom.
  7134. * For example, try scale = 0.9 or 1.1
  7135. * @param {Number} scale Scaling factor. Values above 1 will zoom out,
  7136. * values below 1 will zoom in.
  7137. * @param {Number} [center] Value representing a date around which will
  7138. * be zoomed.
  7139. */
  7140. Range.prototype.zoom = function(scale, center) {
  7141. // if centerDate is not provided, take it half between start Date and end Date
  7142. if (center == null) {
  7143. center = (this.start + this.end) / 2;
  7144. }
  7145. // calculate new start and end
  7146. var newStart = center + (this.start - center) * scale;
  7147. var newEnd = center + (this.end - center) * scale;
  7148. this.setRange(newStart, newEnd);
  7149. };
  7150. /**
  7151. * Move the range with a given delta to the left or right. Start and end
  7152. * value will be adjusted. For example, try delta = 0.1 or -0.1
  7153. * @param {Number} delta Moving amount. Positive value will move right,
  7154. * negative value will move left
  7155. */
  7156. Range.prototype.move = function(delta) {
  7157. // zoom start Date and end Date relative to the centerDate
  7158. var diff = (this.end - this.start);
  7159. // apply new values
  7160. var newStart = this.start + diff * delta;
  7161. var newEnd = this.end + diff * delta;
  7162. // TODO: reckon with min and max range
  7163. this.start = newStart;
  7164. this.end = newEnd;
  7165. };
  7166. /**
  7167. * Move the range to a new center point
  7168. * @param {Number} moveTo New center point of the range
  7169. */
  7170. Range.prototype.moveTo = function(moveTo) {
  7171. var center = (this.start + this.end) / 2;
  7172. var diff = center - moveTo;
  7173. // calculate new start and end
  7174. var newStart = this.start - diff;
  7175. var newEnd = this.end - diff;
  7176. this.setRange(newStart, newEnd);
  7177. };
  7178. /**
  7179. * @constructor Controller
  7180. *
  7181. * A Controller controls the reflows and repaints of all visual components
  7182. */
  7183. function Controller () {
  7184. this.id = util.randomUUID();
  7185. this.components = {};
  7186. this.repaintTimer = undefined;
  7187. this.reflowTimer = undefined;
  7188. }
  7189. /**
  7190. * Add a component to the controller
  7191. * @param {Component} component
  7192. */
  7193. Controller.prototype.add = function add(component) {
  7194. // validate the component
  7195. if (component.id == undefined) {
  7196. throw new Error('Component has no field id');
  7197. }
  7198. if (!(component instanceof Component) && !(component instanceof Controller)) {
  7199. throw new TypeError('Component must be an instance of ' +
  7200. 'prototype Component or Controller');
  7201. }
  7202. // add the component
  7203. component.controller = this;
  7204. this.components[component.id] = component;
  7205. };
  7206. /**
  7207. * Remove a component from the controller
  7208. * @param {Component | String} component
  7209. */
  7210. Controller.prototype.remove = function remove(component) {
  7211. var id;
  7212. for (id in this.components) {
  7213. if (this.components.hasOwnProperty(id)) {
  7214. if (id == component || this.components[id] == component) {
  7215. break;
  7216. }
  7217. }
  7218. }
  7219. if (id) {
  7220. delete this.components[id];
  7221. }
  7222. };
  7223. /**
  7224. * Request a reflow. The controller will schedule a reflow
  7225. * @param {Boolean} [force] If true, an immediate reflow is forced. Default
  7226. * is false.
  7227. */
  7228. Controller.prototype.requestReflow = function requestReflow(force) {
  7229. if (force) {
  7230. this.reflow();
  7231. }
  7232. else {
  7233. if (!this.reflowTimer) {
  7234. var me = this;
  7235. this.reflowTimer = setTimeout(function () {
  7236. me.reflowTimer = undefined;
  7237. me.reflow();
  7238. }, 0);
  7239. }
  7240. }
  7241. };
  7242. /**
  7243. * Request a repaint. The controller will schedule a repaint
  7244. * @param {Boolean} [force] If true, an immediate repaint is forced. Default
  7245. * is false.
  7246. */
  7247. Controller.prototype.requestRepaint = function requestRepaint(force) {
  7248. if (force) {
  7249. this.repaint();
  7250. }
  7251. else {
  7252. if (!this.repaintTimer) {
  7253. var me = this;
  7254. this.repaintTimer = setTimeout(function () {
  7255. me.repaintTimer = undefined;
  7256. me.repaint();
  7257. }, 0);
  7258. }
  7259. }
  7260. };
  7261. /**
  7262. * Repaint all components
  7263. */
  7264. Controller.prototype.repaint = function repaint() {
  7265. var changed = false;
  7266. // cancel any running repaint request
  7267. if (this.repaintTimer) {
  7268. clearTimeout(this.repaintTimer);
  7269. this.repaintTimer = undefined;
  7270. }
  7271. var done = {};
  7272. function repaint(component, id) {
  7273. if (!(id in done)) {
  7274. // first repaint the components on which this component is dependent
  7275. if (component.depends) {
  7276. component.depends.forEach(function (dep) {
  7277. repaint(dep, dep.id);
  7278. });
  7279. }
  7280. if (component.parent) {
  7281. repaint(component.parent, component.parent.id);
  7282. }
  7283. // repaint the component itself and mark as done
  7284. changed = component.repaint() || changed;
  7285. done[id] = true;
  7286. }
  7287. }
  7288. util.forEach(this.components, repaint);
  7289. // immediately reflow when needed
  7290. if (changed) {
  7291. this.reflow();
  7292. }
  7293. // TODO: limit the number of nested reflows/repaints, prevent loop
  7294. };
  7295. /**
  7296. * Reflow all components
  7297. */
  7298. Controller.prototype.reflow = function reflow() {
  7299. var resized = false;
  7300. // cancel any running repaint request
  7301. if (this.reflowTimer) {
  7302. clearTimeout(this.reflowTimer);
  7303. this.reflowTimer = undefined;
  7304. }
  7305. var done = {};
  7306. function reflow(component, id) {
  7307. if (!(id in done)) {
  7308. // first reflow the components on which this component is dependent
  7309. if (component.depends) {
  7310. component.depends.forEach(function (dep) {
  7311. reflow(dep, dep.id);
  7312. });
  7313. }
  7314. if (component.parent) {
  7315. reflow(component.parent, component.parent.id);
  7316. }
  7317. // reflow the component itself and mark as done
  7318. resized = component.reflow() || resized;
  7319. done[id] = true;
  7320. }
  7321. }
  7322. util.forEach(this.components, reflow);
  7323. // immediately repaint when needed
  7324. if (resized) {
  7325. this.repaint();
  7326. }
  7327. // TODO: limit the number of nested reflows/repaints, prevent loop
  7328. };
  7329. /**
  7330. * Prototype for visual components
  7331. */
  7332. function Component () {
  7333. this.id = null;
  7334. this.parent = null;
  7335. this.depends = null;
  7336. this.controller = null;
  7337. this.options = null;
  7338. this.frame = null; // main DOM element
  7339. this.top = 0;
  7340. this.left = 0;
  7341. this.width = 0;
  7342. this.height = 0;
  7343. }
  7344. /**
  7345. * Set parameters for the frame. Parameters will be merged in current parameter
  7346. * set.
  7347. * @param {Object} options Available parameters:
  7348. * {String | function} [className]
  7349. * {EventBus} [eventBus]
  7350. * {String | Number | function} [left]
  7351. * {String | Number | function} [top]
  7352. * {String | Number | function} [width]
  7353. * {String | Number | function} [height]
  7354. */
  7355. Component.prototype.setOptions = function setOptions(options) {
  7356. if (options) {
  7357. util.extend(this.options, options);
  7358. if (this.controller) {
  7359. this.requestRepaint();
  7360. this.requestReflow();
  7361. }
  7362. }
  7363. };
  7364. /**
  7365. * Get an option value by name
  7366. * The function will first check this.options object, and else will check
  7367. * this.defaultOptions.
  7368. * @param {String} name
  7369. * @return {*} value
  7370. */
  7371. Component.prototype.getOption = function getOption(name) {
  7372. var value;
  7373. if (this.options) {
  7374. value = this.options[name];
  7375. }
  7376. if (value === undefined && this.defaultOptions) {
  7377. value = this.defaultOptions[name];
  7378. }
  7379. return value;
  7380. };
  7381. /**
  7382. * Get the container element of the component, which can be used by a child to
  7383. * add its own widgets. Not all components do have a container for childs, in
  7384. * that case null is returned.
  7385. * @returns {HTMLElement | null} container
  7386. */
  7387. // TODO: get rid of the getContainer and getFrame methods, provide these via the options
  7388. Component.prototype.getContainer = function getContainer() {
  7389. // should be implemented by the component
  7390. return null;
  7391. };
  7392. /**
  7393. * Get the frame element of the component, the outer HTML DOM element.
  7394. * @returns {HTMLElement | null} frame
  7395. */
  7396. Component.prototype.getFrame = function getFrame() {
  7397. return this.frame;
  7398. };
  7399. /**
  7400. * Repaint the component
  7401. * @return {Boolean} changed
  7402. */
  7403. Component.prototype.repaint = function repaint() {
  7404. // should be implemented by the component
  7405. return false;
  7406. };
  7407. /**
  7408. * Reflow the component
  7409. * @return {Boolean} resized
  7410. */
  7411. Component.prototype.reflow = function reflow() {
  7412. // should be implemented by the component
  7413. return false;
  7414. };
  7415. /**
  7416. * Hide the component from the DOM
  7417. * @return {Boolean} changed
  7418. */
  7419. Component.prototype.hide = function hide() {
  7420. if (this.frame && this.frame.parentNode) {
  7421. this.frame.parentNode.removeChild(this.frame);
  7422. return true;
  7423. }
  7424. else {
  7425. return false;
  7426. }
  7427. };
  7428. /**
  7429. * Show the component in the DOM (when not already visible).
  7430. * A repaint will be executed when the component is not visible
  7431. * @return {Boolean} changed
  7432. */
  7433. Component.prototype.show = function show() {
  7434. if (!this.frame || !this.frame.parentNode) {
  7435. return this.repaint();
  7436. }
  7437. else {
  7438. return false;
  7439. }
  7440. };
  7441. /**
  7442. * Request a repaint. The controller will schedule a repaint
  7443. */
  7444. Component.prototype.requestRepaint = function requestRepaint() {
  7445. if (this.controller) {
  7446. this.controller.requestRepaint();
  7447. }
  7448. else {
  7449. throw new Error('Cannot request a repaint: no controller configured');
  7450. // TODO: just do a repaint when no parent is configured?
  7451. }
  7452. };
  7453. /**
  7454. * Request a reflow. The controller will schedule a reflow
  7455. */
  7456. Component.prototype.requestReflow = function requestReflow() {
  7457. if (this.controller) {
  7458. this.controller.requestReflow();
  7459. }
  7460. else {
  7461. throw new Error('Cannot request a reflow: no controller configured');
  7462. // TODO: just do a reflow when no parent is configured?
  7463. }
  7464. };
  7465. /**
  7466. * A panel can contain components
  7467. * @param {Component} [parent]
  7468. * @param {Component[]} [depends] Components on which this components depends
  7469. * (except for the parent)
  7470. * @param {Object} [options] Available parameters:
  7471. * {String | Number | function} [left]
  7472. * {String | Number | function} [top]
  7473. * {String | Number | function} [width]
  7474. * {String | Number | function} [height]
  7475. * {String | function} [className]
  7476. * @constructor Panel
  7477. * @extends Component
  7478. */
  7479. function Panel(parent, depends, options) {
  7480. this.id = util.randomUUID();
  7481. this.parent = parent;
  7482. this.depends = depends;
  7483. this.options = options || {};
  7484. }
  7485. Panel.prototype = new Component();
  7486. /**
  7487. * Set options. Will extend the current options.
  7488. * @param {Object} [options] Available parameters:
  7489. * {String | function} [className]
  7490. * {String | Number | function} [left]
  7491. * {String | Number | function} [top]
  7492. * {String | Number | function} [width]
  7493. * {String | Number | function} [height]
  7494. */
  7495. Panel.prototype.setOptions = Component.prototype.setOptions;
  7496. /**
  7497. * Get the container element of the panel, which can be used by a child to
  7498. * add its own widgets.
  7499. * @returns {HTMLElement} container
  7500. */
  7501. Panel.prototype.getContainer = function () {
  7502. return this.frame;
  7503. };
  7504. /**
  7505. * Repaint the component
  7506. * @return {Boolean} changed
  7507. */
  7508. Panel.prototype.repaint = function () {
  7509. var changed = 0,
  7510. update = util.updateProperty,
  7511. asSize = util.option.asSize,
  7512. options = this.options,
  7513. frame = this.frame;
  7514. if (!frame) {
  7515. frame = document.createElement('div');
  7516. frame.className = 'panel';
  7517. var className = options.className;
  7518. if (className) {
  7519. if (typeof className == 'function') {
  7520. util.addClassName(frame, String(className()));
  7521. }
  7522. else {
  7523. util.addClassName(frame, String(className));
  7524. }
  7525. }
  7526. this.frame = frame;
  7527. changed += 1;
  7528. }
  7529. if (!frame.parentNode) {
  7530. if (!this.parent) {
  7531. throw new Error('Cannot repaint panel: no parent attached');
  7532. }
  7533. var parentContainer = this.parent.getContainer();
  7534. if (!parentContainer) {
  7535. throw new Error('Cannot repaint panel: parent has no container element');
  7536. }
  7537. parentContainer.appendChild(frame);
  7538. changed += 1;
  7539. }
  7540. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  7541. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  7542. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  7543. changed += update(frame.style, 'height', asSize(options.height, '100%'));
  7544. return (changed > 0);
  7545. };
  7546. /**
  7547. * Reflow the component
  7548. * @return {Boolean} resized
  7549. */
  7550. Panel.prototype.reflow = function () {
  7551. var changed = 0,
  7552. update = util.updateProperty,
  7553. frame = this.frame;
  7554. if (frame) {
  7555. changed += update(this, 'top', frame.offsetTop);
  7556. changed += update(this, 'left', frame.offsetLeft);
  7557. changed += update(this, 'width', frame.offsetWidth);
  7558. changed += update(this, 'height', frame.offsetHeight);
  7559. }
  7560. else {
  7561. changed += 1;
  7562. }
  7563. return (changed > 0);
  7564. };
  7565. /**
  7566. * A root panel can hold components. The root panel must be initialized with
  7567. * a DOM element as container.
  7568. * @param {HTMLElement} container
  7569. * @param {Object} [options] Available parameters: see RootPanel.setOptions.
  7570. * @constructor RootPanel
  7571. * @extends Panel
  7572. */
  7573. function RootPanel(container, options) {
  7574. this.id = util.randomUUID();
  7575. this.container = container;
  7576. this.options = options || {};
  7577. this.defaultOptions = {
  7578. autoResize: true
  7579. };
  7580. this.listeners = {}; // event listeners
  7581. }
  7582. RootPanel.prototype = new Panel();
  7583. /**
  7584. * Set options. Will extend the current options.
  7585. * @param {Object} [options] Available parameters:
  7586. * {String | function} [className]
  7587. * {String | Number | function} [left]
  7588. * {String | Number | function} [top]
  7589. * {String | Number | function} [width]
  7590. * {String | Number | function} [height]
  7591. * {Boolean | function} [autoResize]
  7592. */
  7593. RootPanel.prototype.setOptions = Component.prototype.setOptions;
  7594. /**
  7595. * Repaint the component
  7596. * @return {Boolean} changed
  7597. */
  7598. RootPanel.prototype.repaint = function () {
  7599. var changed = 0,
  7600. update = util.updateProperty,
  7601. asSize = util.option.asSize,
  7602. options = this.options,
  7603. frame = this.frame;
  7604. if (!frame) {
  7605. frame = document.createElement('div');
  7606. this.frame = frame;
  7607. changed += 1;
  7608. }
  7609. if (!frame.parentNode) {
  7610. if (!this.container) {
  7611. throw new Error('Cannot repaint root panel: no container attached');
  7612. }
  7613. this.container.appendChild(frame);
  7614. changed += 1;
  7615. }
  7616. frame.className = 'vis timeline rootpanel ' + options.orientation;
  7617. var className = options.className;
  7618. if (className) {
  7619. util.addClassName(frame, util.option.asString(className));
  7620. }
  7621. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  7622. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  7623. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  7624. changed += update(frame.style, 'height', asSize(options.height, '100%'));
  7625. this._updateEventEmitters();
  7626. this._updateWatch();
  7627. return (changed > 0);
  7628. };
  7629. /**
  7630. * Reflow the component
  7631. * @return {Boolean} resized
  7632. */
  7633. RootPanel.prototype.reflow = function () {
  7634. var changed = 0,
  7635. update = util.updateProperty,
  7636. frame = this.frame;
  7637. if (frame) {
  7638. changed += update(this, 'top', frame.offsetTop);
  7639. changed += update(this, 'left', frame.offsetLeft);
  7640. changed += update(this, 'width', frame.offsetWidth);
  7641. changed += update(this, 'height', frame.offsetHeight);
  7642. }
  7643. else {
  7644. changed += 1;
  7645. }
  7646. return (changed > 0);
  7647. };
  7648. /**
  7649. * Update watching for resize, depending on the current option
  7650. * @private
  7651. */
  7652. RootPanel.prototype._updateWatch = function () {
  7653. var autoResize = this.getOption('autoResize');
  7654. if (autoResize) {
  7655. this._watch();
  7656. }
  7657. else {
  7658. this._unwatch();
  7659. }
  7660. };
  7661. /**
  7662. * Watch for changes in the size of the frame. On resize, the Panel will
  7663. * automatically redraw itself.
  7664. * @private
  7665. */
  7666. RootPanel.prototype._watch = function () {
  7667. var me = this;
  7668. this._unwatch();
  7669. var checkSize = function () {
  7670. var autoResize = me.getOption('autoResize');
  7671. if (!autoResize) {
  7672. // stop watching when the option autoResize is changed to false
  7673. me._unwatch();
  7674. return;
  7675. }
  7676. if (me.frame) {
  7677. // check whether the frame is resized
  7678. if ((me.frame.clientWidth != me.width) ||
  7679. (me.frame.clientHeight != me.height)) {
  7680. me.requestReflow();
  7681. }
  7682. }
  7683. };
  7684. // TODO: automatically cleanup the event listener when the frame is deleted
  7685. util.addEventListener(window, 'resize', checkSize);
  7686. this.watchTimer = setInterval(checkSize, 1000);
  7687. };
  7688. /**
  7689. * Stop watching for a resize of the frame.
  7690. * @private
  7691. */
  7692. RootPanel.prototype._unwatch = function () {
  7693. if (this.watchTimer) {
  7694. clearInterval(this.watchTimer);
  7695. this.watchTimer = undefined;
  7696. }
  7697. // TODO: remove event listener on window.resize
  7698. };
  7699. /**
  7700. * Event handler
  7701. * @param {String} event name of the event, for example 'click', 'mousemove'
  7702. * @param {function} callback callback handler, invoked with the raw HTML Event
  7703. * as parameter.
  7704. */
  7705. RootPanel.prototype.on = function (event, callback) {
  7706. // register the listener at this component
  7707. var arr = this.listeners[event];
  7708. if (!arr) {
  7709. arr = [];
  7710. this.listeners[event] = arr;
  7711. }
  7712. arr.push(callback);
  7713. this._updateEventEmitters();
  7714. };
  7715. /**
  7716. * Update the event listeners for all event emitters
  7717. * @private
  7718. */
  7719. RootPanel.prototype._updateEventEmitters = function () {
  7720. if (this.listeners) {
  7721. var me = this;
  7722. util.forEach(this.listeners, function (listeners, event) {
  7723. if (!me.emitters) {
  7724. me.emitters = {};
  7725. }
  7726. if (!(event in me.emitters)) {
  7727. // create event
  7728. var frame = me.frame;
  7729. if (frame) {
  7730. //console.log('Created a listener for event ' + event + ' on component ' + me.id); // TODO: cleanup logging
  7731. var callback = function(event) {
  7732. listeners.forEach(function (listener) {
  7733. // TODO: filter on event target!
  7734. listener(event);
  7735. });
  7736. };
  7737. me.emitters[event] = callback;
  7738. if (!me.hammer) {
  7739. me.hammer = Hammer(frame, {
  7740. prevent_default: true
  7741. });
  7742. }
  7743. me.hammer.on(event, callback);
  7744. }
  7745. }
  7746. });
  7747. // TODO: be able to delete event listeners
  7748. // TODO: be able to move event listeners to a parent when available
  7749. }
  7750. };
  7751. /**
  7752. * A horizontal time axis
  7753. * @param {Component} parent
  7754. * @param {Component[]} [depends] Components on which this components depends
  7755. * (except for the parent)
  7756. * @param {Object} [options] See TimeAxis.setOptions for the available
  7757. * options.
  7758. * @constructor TimeAxis
  7759. * @extends Component
  7760. */
  7761. function TimeAxis (parent, depends, options) {
  7762. this.id = util.randomUUID();
  7763. this.parent = parent;
  7764. this.depends = depends;
  7765. this.dom = {
  7766. majorLines: [],
  7767. majorTexts: [],
  7768. minorLines: [],
  7769. minorTexts: [],
  7770. redundant: {
  7771. majorLines: [],
  7772. majorTexts: [],
  7773. minorLines: [],
  7774. minorTexts: []
  7775. }
  7776. };
  7777. this.props = {
  7778. range: {
  7779. start: 0,
  7780. end: 0,
  7781. minimumStep: 0
  7782. },
  7783. lineTop: 0
  7784. };
  7785. this.options = options || {};
  7786. this.defaultOptions = {
  7787. orientation: 'bottom', // supported: 'top', 'bottom'
  7788. // TODO: implement timeaxis orientations 'left' and 'right'
  7789. showMinorLabels: true,
  7790. showMajorLabels: true
  7791. };
  7792. this.conversion = null;
  7793. this.range = null;
  7794. }
  7795. TimeAxis.prototype = new Component();
  7796. // TODO: comment options
  7797. TimeAxis.prototype.setOptions = Component.prototype.setOptions;
  7798. /**
  7799. * Set a range (start and end)
  7800. * @param {Range | Object} range A Range or an object containing start and end.
  7801. */
  7802. TimeAxis.prototype.setRange = function (range) {
  7803. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  7804. throw new TypeError('Range must be an instance of Range, ' +
  7805. 'or an object containing start and end.');
  7806. }
  7807. this.range = range;
  7808. };
  7809. /**
  7810. * Convert a position on screen (pixels) to a datetime
  7811. * @param {int} x Position on the screen in pixels
  7812. * @return {Date} time The datetime the corresponds with given position x
  7813. */
  7814. TimeAxis.prototype.toTime = function(x) {
  7815. var conversion = this.conversion;
  7816. return new Date(x / conversion.scale + conversion.offset);
  7817. };
  7818. /**
  7819. * Convert a datetime (Date object) into a position on the screen
  7820. * @param {Date} time A date
  7821. * @return {int} x The position on the screen in pixels which corresponds
  7822. * with the given date.
  7823. * @private
  7824. */
  7825. TimeAxis.prototype.toScreen = function(time) {
  7826. var conversion = this.conversion;
  7827. return (time.valueOf() - conversion.offset) * conversion.scale;
  7828. };
  7829. /**
  7830. * Repaint the component
  7831. * @return {Boolean} changed
  7832. */
  7833. TimeAxis.prototype.repaint = function () {
  7834. var changed = 0,
  7835. update = util.updateProperty,
  7836. asSize = util.option.asSize,
  7837. options = this.options,
  7838. orientation = this.getOption('orientation'),
  7839. props = this.props,
  7840. step = this.step;
  7841. var frame = this.frame;
  7842. if (!frame) {
  7843. frame = document.createElement('div');
  7844. this.frame = frame;
  7845. changed += 1;
  7846. }
  7847. frame.className = 'axis';
  7848. // TODO: custom className?
  7849. if (!frame.parentNode) {
  7850. if (!this.parent) {
  7851. throw new Error('Cannot repaint time axis: no parent attached');
  7852. }
  7853. var parentContainer = this.parent.getContainer();
  7854. if (!parentContainer) {
  7855. throw new Error('Cannot repaint time axis: parent has no container element');
  7856. }
  7857. parentContainer.appendChild(frame);
  7858. changed += 1;
  7859. }
  7860. var parent = frame.parentNode;
  7861. if (parent) {
  7862. var beforeChild = frame.nextSibling;
  7863. parent.removeChild(frame); // take frame offline while updating (is almost twice as fast)
  7864. var defaultTop = (orientation == 'bottom' && this.props.parentHeight && this.height) ?
  7865. (this.props.parentHeight - this.height) + 'px' :
  7866. '0px';
  7867. changed += update(frame.style, 'top', asSize(options.top, defaultTop));
  7868. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  7869. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  7870. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  7871. // get characters width and height
  7872. this._repaintMeasureChars();
  7873. if (this.step) {
  7874. this._repaintStart();
  7875. step.first();
  7876. var xFirstMajorLabel = undefined;
  7877. var max = 0;
  7878. while (step.hasNext() && max < 1000) {
  7879. max++;
  7880. var cur = step.getCurrent(),
  7881. x = this.toScreen(cur),
  7882. isMajor = step.isMajor();
  7883. // TODO: lines must have a width, such that we can create css backgrounds
  7884. if (this.getOption('showMinorLabels')) {
  7885. this._repaintMinorText(x, step.getLabelMinor());
  7886. }
  7887. if (isMajor && this.getOption('showMajorLabels')) {
  7888. if (x > 0) {
  7889. if (xFirstMajorLabel == undefined) {
  7890. xFirstMajorLabel = x;
  7891. }
  7892. this._repaintMajorText(x, step.getLabelMajor());
  7893. }
  7894. this._repaintMajorLine(x);
  7895. }
  7896. else {
  7897. this._repaintMinorLine(x);
  7898. }
  7899. step.next();
  7900. }
  7901. // create a major label on the left when needed
  7902. if (this.getOption('showMajorLabels')) {
  7903. var leftTime = this.toTime(0),
  7904. leftText = step.getLabelMajor(leftTime),
  7905. widthText = leftText.length * (props.majorCharWidth || 10) + 10; // upper bound estimation
  7906. if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) {
  7907. this._repaintMajorText(0, leftText);
  7908. }
  7909. }
  7910. this._repaintEnd();
  7911. }
  7912. this._repaintLine();
  7913. // put frame online again
  7914. if (beforeChild) {
  7915. parent.insertBefore(frame, beforeChild);
  7916. }
  7917. else {
  7918. parent.appendChild(frame)
  7919. }
  7920. }
  7921. return (changed > 0);
  7922. };
  7923. /**
  7924. * Start a repaint. Move all DOM elements to a redundant list, where they
  7925. * can be picked for re-use, or can be cleaned up in the end
  7926. * @private
  7927. */
  7928. TimeAxis.prototype._repaintStart = function () {
  7929. var dom = this.dom,
  7930. redundant = dom.redundant;
  7931. redundant.majorLines = dom.majorLines;
  7932. redundant.majorTexts = dom.majorTexts;
  7933. redundant.minorLines = dom.minorLines;
  7934. redundant.minorTexts = dom.minorTexts;
  7935. dom.majorLines = [];
  7936. dom.majorTexts = [];
  7937. dom.minorLines = [];
  7938. dom.minorTexts = [];
  7939. };
  7940. /**
  7941. * End a repaint. Cleanup leftover DOM elements in the redundant list
  7942. * @private
  7943. */
  7944. TimeAxis.prototype._repaintEnd = function () {
  7945. util.forEach(this.dom.redundant, function (arr) {
  7946. while (arr.length) {
  7947. var elem = arr.pop();
  7948. if (elem && elem.parentNode) {
  7949. elem.parentNode.removeChild(elem);
  7950. }
  7951. }
  7952. });
  7953. };
  7954. /**
  7955. * Create a minor label for the axis at position x
  7956. * @param {Number} x
  7957. * @param {String} text
  7958. * @private
  7959. */
  7960. TimeAxis.prototype._repaintMinorText = function (x, text) {
  7961. // reuse redundant label
  7962. var label = this.dom.redundant.minorTexts.shift();
  7963. if (!label) {
  7964. // create new label
  7965. var content = document.createTextNode('');
  7966. label = document.createElement('div');
  7967. label.appendChild(content);
  7968. label.className = 'text minor';
  7969. this.frame.appendChild(label);
  7970. }
  7971. this.dom.minorTexts.push(label);
  7972. label.childNodes[0].nodeValue = text;
  7973. label.style.left = x + 'px';
  7974. label.style.top = this.props.minorLabelTop + 'px';
  7975. //label.title = title; // TODO: this is a heavy operation
  7976. };
  7977. /**
  7978. * Create a Major label for the axis at position x
  7979. * @param {Number} x
  7980. * @param {String} text
  7981. * @private
  7982. */
  7983. TimeAxis.prototype._repaintMajorText = function (x, text) {
  7984. // reuse redundant label
  7985. var label = this.dom.redundant.majorTexts.shift();
  7986. if (!label) {
  7987. // create label
  7988. var content = document.createTextNode(text);
  7989. label = document.createElement('div');
  7990. label.className = 'text major';
  7991. label.appendChild(content);
  7992. this.frame.appendChild(label);
  7993. }
  7994. this.dom.majorTexts.push(label);
  7995. label.childNodes[0].nodeValue = text;
  7996. label.style.top = this.props.majorLabelTop + 'px';
  7997. label.style.left = x + 'px';
  7998. //label.title = title; // TODO: this is a heavy operation
  7999. };
  8000. /**
  8001. * Create a minor line for the axis at position x
  8002. * @param {Number} x
  8003. * @private
  8004. */
  8005. TimeAxis.prototype._repaintMinorLine = function (x) {
  8006. // reuse redundant line
  8007. var line = this.dom.redundant.minorLines.shift();
  8008. if (!line) {
  8009. // create vertical line
  8010. line = document.createElement('div');
  8011. line.className = 'grid vertical minor';
  8012. this.frame.appendChild(line);
  8013. }
  8014. this.dom.minorLines.push(line);
  8015. var props = this.props;
  8016. line.style.top = props.minorLineTop + 'px';
  8017. line.style.height = props.minorLineHeight + 'px';
  8018. line.style.left = (x - props.minorLineWidth / 2) + 'px';
  8019. };
  8020. /**
  8021. * Create a Major line for the axis at position x
  8022. * @param {Number} x
  8023. * @private
  8024. */
  8025. TimeAxis.prototype._repaintMajorLine = function (x) {
  8026. // reuse redundant line
  8027. var line = this.dom.redundant.majorLines.shift();
  8028. if (!line) {
  8029. // create vertical line
  8030. line = document.createElement('DIV');
  8031. line.className = 'grid vertical major';
  8032. this.frame.appendChild(line);
  8033. }
  8034. this.dom.majorLines.push(line);
  8035. var props = this.props;
  8036. line.style.top = props.majorLineTop + 'px';
  8037. line.style.left = (x - props.majorLineWidth / 2) + 'px';
  8038. line.style.height = props.majorLineHeight + 'px';
  8039. };
  8040. /**
  8041. * Repaint the horizontal line for the axis
  8042. * @private
  8043. */
  8044. TimeAxis.prototype._repaintLine = function() {
  8045. var line = this.dom.line,
  8046. frame = this.frame,
  8047. options = this.options;
  8048. // line before all axis elements
  8049. if (this.getOption('showMinorLabels') || this.getOption('showMajorLabels')) {
  8050. if (line) {
  8051. // put this line at the end of all childs
  8052. frame.removeChild(line);
  8053. frame.appendChild(line);
  8054. }
  8055. else {
  8056. // create the axis line
  8057. line = document.createElement('div');
  8058. line.className = 'grid horizontal major';
  8059. frame.appendChild(line);
  8060. this.dom.line = line;
  8061. }
  8062. line.style.top = this.props.lineTop + 'px';
  8063. }
  8064. else {
  8065. if (line && line.parentElement) {
  8066. frame.removeChild(line.line);
  8067. delete this.dom.line;
  8068. }
  8069. }
  8070. };
  8071. /**
  8072. * Create characters used to determine the size of text on the axis
  8073. * @private
  8074. */
  8075. TimeAxis.prototype._repaintMeasureChars = function () {
  8076. // calculate the width and height of a single character
  8077. // this is used to calculate the step size, and also the positioning of the
  8078. // axis
  8079. var dom = this.dom,
  8080. text;
  8081. if (!dom.measureCharMinor) {
  8082. text = document.createTextNode('0');
  8083. var measureCharMinor = document.createElement('DIV');
  8084. measureCharMinor.className = 'text minor measure';
  8085. measureCharMinor.appendChild(text);
  8086. this.frame.appendChild(measureCharMinor);
  8087. dom.measureCharMinor = measureCharMinor;
  8088. }
  8089. if (!dom.measureCharMajor) {
  8090. text = document.createTextNode('0');
  8091. var measureCharMajor = document.createElement('DIV');
  8092. measureCharMajor.className = 'text major measure';
  8093. measureCharMajor.appendChild(text);
  8094. this.frame.appendChild(measureCharMajor);
  8095. dom.measureCharMajor = measureCharMajor;
  8096. }
  8097. };
  8098. /**
  8099. * Reflow the component
  8100. * @return {Boolean} resized
  8101. */
  8102. TimeAxis.prototype.reflow = function () {
  8103. var changed = 0,
  8104. update = util.updateProperty,
  8105. frame = this.frame,
  8106. range = this.range;
  8107. if (!range) {
  8108. throw new Error('Cannot repaint time axis: no range configured');
  8109. }
  8110. if (frame) {
  8111. changed += update(this, 'top', frame.offsetTop);
  8112. changed += update(this, 'left', frame.offsetLeft);
  8113. // calculate size of a character
  8114. var props = this.props,
  8115. showMinorLabels = this.getOption('showMinorLabels'),
  8116. showMajorLabels = this.getOption('showMajorLabels'),
  8117. measureCharMinor = this.dom.measureCharMinor,
  8118. measureCharMajor = this.dom.measureCharMajor;
  8119. if (measureCharMinor) {
  8120. props.minorCharHeight = measureCharMinor.clientHeight;
  8121. props.minorCharWidth = measureCharMinor.clientWidth;
  8122. }
  8123. if (measureCharMajor) {
  8124. props.majorCharHeight = measureCharMajor.clientHeight;
  8125. props.majorCharWidth = measureCharMajor.clientWidth;
  8126. }
  8127. var parentHeight = frame.parentNode ? frame.parentNode.offsetHeight : 0;
  8128. if (parentHeight != props.parentHeight) {
  8129. props.parentHeight = parentHeight;
  8130. changed += 1;
  8131. }
  8132. switch (this.getOption('orientation')) {
  8133. case 'bottom':
  8134. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  8135. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  8136. props.minorLabelTop = 0;
  8137. props.majorLabelTop = props.minorLabelTop + props.minorLabelHeight;
  8138. props.minorLineTop = -this.top;
  8139. props.minorLineHeight = Math.max(this.top + props.majorLabelHeight, 0);
  8140. props.minorLineWidth = 1; // TODO: really calculate width
  8141. props.majorLineTop = -this.top;
  8142. props.majorLineHeight = Math.max(this.top + props.minorLabelHeight + props.majorLabelHeight, 0);
  8143. props.majorLineWidth = 1; // TODO: really calculate width
  8144. props.lineTop = 0;
  8145. break;
  8146. case 'top':
  8147. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  8148. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  8149. props.majorLabelTop = 0;
  8150. props.minorLabelTop = props.majorLabelTop + props.majorLabelHeight;
  8151. props.minorLineTop = props.minorLabelTop;
  8152. props.minorLineHeight = Math.max(parentHeight - props.majorLabelHeight - this.top);
  8153. props.minorLineWidth = 1; // TODO: really calculate width
  8154. props.majorLineTop = 0;
  8155. props.majorLineHeight = Math.max(parentHeight - this.top);
  8156. props.majorLineWidth = 1; // TODO: really calculate width
  8157. props.lineTop = props.majorLabelHeight + props.minorLabelHeight;
  8158. break;
  8159. default:
  8160. throw new Error('Unkown orientation "' + this.getOption('orientation') + '"');
  8161. }
  8162. var height = props.minorLabelHeight + props.majorLabelHeight;
  8163. changed += update(this, 'width', frame.offsetWidth);
  8164. changed += update(this, 'height', height);
  8165. // calculate range and step
  8166. this._updateConversion();
  8167. var start = util.convert(range.start, 'Number'),
  8168. end = util.convert(range.end, 'Number'),
  8169. minimumStep = this.toTime((props.minorCharWidth || 10) * 5).valueOf()
  8170. -this.toTime(0).valueOf();
  8171. this.step = new TimeStep(new Date(start), new Date(end), minimumStep);
  8172. changed += update(props.range, 'start', start);
  8173. changed += update(props.range, 'end', end);
  8174. changed += update(props.range, 'minimumStep', minimumStep.valueOf());
  8175. }
  8176. return (changed > 0);
  8177. };
  8178. /**
  8179. * Calculate the scale and offset to convert a position on screen to the
  8180. * corresponding date and vice versa.
  8181. * After the method _updateConversion is executed once, the methods toTime
  8182. * and toScreen can be used.
  8183. * @private
  8184. */
  8185. TimeAxis.prototype._updateConversion = function() {
  8186. var range = this.range;
  8187. if (!range) {
  8188. throw new Error('No range configured');
  8189. }
  8190. if (range.conversion) {
  8191. this.conversion = range.conversion(this.width);
  8192. }
  8193. else {
  8194. this.conversion = Range.conversion(range.start, range.end, this.width);
  8195. }
  8196. };
  8197. /**
  8198. * A current time bar
  8199. * @param {Component} parent
  8200. * @param {Component[]} [depends] Components on which this components depends
  8201. * (except for the parent)
  8202. * @param {Object} [options] Available parameters:
  8203. * {Boolean} [showCurrentTime]
  8204. * @constructor CurrentTime
  8205. * @extends Component
  8206. */
  8207. function CurrentTime (parent, depends, options) {
  8208. this.id = util.randomUUID();
  8209. this.parent = parent;
  8210. this.depends = depends;
  8211. this.options = options || {};
  8212. this.defaultOptions = {
  8213. showCurrentTime: false
  8214. };
  8215. }
  8216. CurrentTime.prototype = new Component();
  8217. CurrentTime.prototype.setOptions = Component.prototype.setOptions;
  8218. /**
  8219. * Get the container element of the bar, which can be used by a child to
  8220. * add its own widgets.
  8221. * @returns {HTMLElement} container
  8222. */
  8223. CurrentTime.prototype.getContainer = function () {
  8224. return this.frame;
  8225. };
  8226. /**
  8227. * Repaint the component
  8228. * @return {Boolean} changed
  8229. */
  8230. CurrentTime.prototype.repaint = function () {
  8231. var bar = this.frame,
  8232. parent = this.parent,
  8233. parentContainer = parent.parent.getContainer();
  8234. if (!parent) {
  8235. throw new Error('Cannot repaint bar: no parent attached');
  8236. }
  8237. if (!parentContainer) {
  8238. throw new Error('Cannot repaint bar: parent has no container element');
  8239. }
  8240. if (!this.getOption('showCurrentTime')) {
  8241. if (bar) {
  8242. parentContainer.removeChild(bar);
  8243. delete this.frame;
  8244. }
  8245. return;
  8246. }
  8247. if (!bar) {
  8248. bar = document.createElement('div');
  8249. bar.className = 'currenttime';
  8250. bar.style.position = 'absolute';
  8251. bar.style.top = '0px';
  8252. bar.style.height = '100%';
  8253. parentContainer.appendChild(bar);
  8254. this.frame = bar;
  8255. }
  8256. if (!parent.conversion) {
  8257. parent._updateConversion();
  8258. }
  8259. var now = new Date();
  8260. var x = parent.toScreen(now);
  8261. bar.style.left = x + 'px';
  8262. bar.title = 'Current time: ' + now;
  8263. // start a timer to adjust for the new time
  8264. if (this.currentTimeTimer !== undefined) {
  8265. clearTimeout(this.currentTimeTimer);
  8266. delete this.currentTimeTimer;
  8267. }
  8268. var timeline = this;
  8269. var interval = 1 / parent.conversion.scale / 2;
  8270. if (interval < 30) {
  8271. interval = 30;
  8272. }
  8273. this.currentTimeTimer = setTimeout(function() {
  8274. timeline.repaint();
  8275. }, interval);
  8276. return false;
  8277. };
  8278. /**
  8279. * A custom time bar
  8280. * @param {Component} parent
  8281. * @param {Component[]} [depends] Components on which this components depends
  8282. * (except for the parent)
  8283. * @param {Object} [options] Available parameters:
  8284. * {Boolean} [showCustomTime]
  8285. * @constructor CustomTime
  8286. * @extends Component
  8287. */
  8288. function CustomTime (parent, depends, options) {
  8289. this.id = util.randomUUID();
  8290. this.parent = parent;
  8291. this.depends = depends;
  8292. this.options = options || {};
  8293. this.defaultOptions = {
  8294. showCustomTime: false
  8295. };
  8296. this.listeners = [];
  8297. this.customTime = new Date();
  8298. }
  8299. CustomTime.prototype = new Component();
  8300. CustomTime.prototype.setOptions = Component.prototype.setOptions;
  8301. /**
  8302. * Get the container element of the bar, which can be used by a child to
  8303. * add its own widgets.
  8304. * @returns {HTMLElement} container
  8305. */
  8306. CustomTime.prototype.getContainer = function () {
  8307. return this.frame;
  8308. };
  8309. /**
  8310. * Repaint the component
  8311. * @return {Boolean} changed
  8312. */
  8313. CustomTime.prototype.repaint = function () {
  8314. var bar = this.frame,
  8315. parent = this.parent,
  8316. parentContainer = parent.parent.getContainer();
  8317. if (!parent) {
  8318. throw new Error('Cannot repaint bar: no parent attached');
  8319. }
  8320. if (!parentContainer) {
  8321. throw new Error('Cannot repaint bar: parent has no container element');
  8322. }
  8323. if (!this.getOption('showCustomTime')) {
  8324. if (bar) {
  8325. parentContainer.removeChild(bar);
  8326. delete this.frame;
  8327. }
  8328. return;
  8329. }
  8330. if (!bar) {
  8331. bar = document.createElement('div');
  8332. bar.className = 'customtime';
  8333. bar.style.position = 'absolute';
  8334. bar.style.top = '0px';
  8335. bar.style.height = '100%';
  8336. parentContainer.appendChild(bar);
  8337. var drag = document.createElement('div');
  8338. drag.style.position = 'relative';
  8339. drag.style.top = '0px';
  8340. drag.style.left = '-10px';
  8341. drag.style.height = '100%';
  8342. drag.style.width = '20px';
  8343. bar.appendChild(drag);
  8344. this.frame = bar;
  8345. this.subscribe(this, 'movetime');
  8346. }
  8347. if (!parent.conversion) {
  8348. parent._updateConversion();
  8349. }
  8350. var x = parent.toScreen(this.customTime);
  8351. bar.style.left = x + 'px';
  8352. bar.title = 'Time: ' + this.customTime;
  8353. return false;
  8354. };
  8355. /**
  8356. * Set custom time.
  8357. * @param {Date} time
  8358. */
  8359. CustomTime.prototype._setCustomTime = function(time) {
  8360. this.customTime = new Date(time.valueOf());
  8361. this.repaint();
  8362. };
  8363. /**
  8364. * Retrieve the current custom time.
  8365. * @return {Date} customTime
  8366. */
  8367. CustomTime.prototype._getCustomTime = function() {
  8368. return new Date(this.customTime.valueOf());
  8369. };
  8370. /**
  8371. * Add listeners for mouse and touch events to the component
  8372. * @param {Component} component
  8373. */
  8374. CustomTime.prototype.subscribe = function (component, event) {
  8375. var me = this;
  8376. var listener = {
  8377. component: component,
  8378. event: event,
  8379. callback: function (event) {
  8380. me._onMouseDown(event, listener);
  8381. },
  8382. params: {}
  8383. };
  8384. component.on('mousedown', listener.callback);
  8385. me.listeners.push(listener);
  8386. };
  8387. /**
  8388. * Event handler
  8389. * @param {String} event name of the event, for example 'click', 'mousemove'
  8390. * @param {function} callback callback handler, invoked with the raw HTML Event
  8391. * as parameter.
  8392. */
  8393. CustomTime.prototype.on = function (event, callback) {
  8394. var bar = this.frame;
  8395. if (!bar) {
  8396. throw new Error('Cannot add event listener: no parent attached');
  8397. }
  8398. events.addListener(this, event, callback);
  8399. util.addEventListener(bar, event, callback);
  8400. };
  8401. /**
  8402. * Start moving horizontally
  8403. * @param {Event} event
  8404. * @param {Object} listener Listener containing the component and params
  8405. * @private
  8406. */
  8407. CustomTime.prototype._onMouseDown = function(event, listener) {
  8408. event = event || window.event;
  8409. var params = listener.params;
  8410. // only react on left mouse button down
  8411. var leftButtonDown = event.which ? (event.which == 1) : (event.button == 1);
  8412. if (!leftButtonDown) {
  8413. return;
  8414. }
  8415. // get mouse position
  8416. params.mouseX = util.getPageX(event);
  8417. params.moved = false;
  8418. params.customTime = this.customTime;
  8419. // add event listeners to handle moving the custom time bar
  8420. var me = this;
  8421. if (!params.onMouseMove) {
  8422. params.onMouseMove = function (event) {
  8423. me._onMouseMove(event, listener);
  8424. };
  8425. util.addEventListener(document, 'mousemove', params.onMouseMove);
  8426. }
  8427. if (!params.onMouseUp) {
  8428. params.onMouseUp = function (event) {
  8429. me._onMouseUp(event, listener);
  8430. };
  8431. util.addEventListener(document, 'mouseup', params.onMouseUp);
  8432. }
  8433. util.stopPropagation(event);
  8434. util.preventDefault(event);
  8435. };
  8436. /**
  8437. * Perform moving operating.
  8438. * This function activated from within the funcion CustomTime._onMouseDown().
  8439. * @param {Event} event
  8440. * @param {Object} listener
  8441. * @private
  8442. */
  8443. CustomTime.prototype._onMouseMove = function (event, listener) {
  8444. event = event || window.event;
  8445. var params = listener.params;
  8446. var parent = this.parent;
  8447. // calculate change in mouse position
  8448. var mouseX = util.getPageX(event);
  8449. if (params.mouseX === undefined) {
  8450. params.mouseX = mouseX;
  8451. }
  8452. var diff = mouseX - params.mouseX;
  8453. // if mouse movement is big enough, register it as a "moved" event
  8454. if (Math.abs(diff) >= 1) {
  8455. params.moved = true;
  8456. }
  8457. var x = parent.toScreen(params.customTime);
  8458. var xnew = x + diff;
  8459. var time = parent.toTime(xnew);
  8460. this._setCustomTime(time);
  8461. // fire a timechange event
  8462. events.trigger(this, 'timechange', {customTime: this.customTime});
  8463. util.preventDefault(event);
  8464. };
  8465. /**
  8466. * Stop moving operating.
  8467. * This function activated from within the function CustomTime._onMouseDown().
  8468. * @param {event} event
  8469. * @param {Object} listener
  8470. * @private
  8471. */
  8472. CustomTime.prototype._onMouseUp = function (event, listener) {
  8473. event = event || window.event;
  8474. var params = listener.params;
  8475. // remove event listeners here, important for Safari
  8476. if (params.onMouseMove) {
  8477. util.removeEventListener(document, 'mousemove', params.onMouseMove);
  8478. params.onMouseMove = null;
  8479. }
  8480. if (params.onMouseUp) {
  8481. util.removeEventListener(document, 'mouseup', params.onMouseUp);
  8482. params.onMouseUp = null;
  8483. }
  8484. if (params.moved) {
  8485. // fire a timechanged event
  8486. events.trigger(this, 'timechanged', {customTime: this.customTime});
  8487. }
  8488. };
  8489. /**
  8490. * An ItemSet holds a set of items and ranges which can be displayed in a
  8491. * range. The width is determined by the parent of the ItemSet, and the height
  8492. * is determined by the size of the items.
  8493. * @param {Component} parent
  8494. * @param {Component[]} [depends] Components on which this components depends
  8495. * (except for the parent)
  8496. * @param {Object} [options] See ItemSet.setOptions for the available
  8497. * options.
  8498. * @constructor ItemSet
  8499. * @extends Panel
  8500. */
  8501. // TODO: improve performance by replacing all Array.forEach with a for loop
  8502. function ItemSet(parent, depends, options) {
  8503. this.id = util.randomUUID();
  8504. this.parent = parent;
  8505. this.depends = depends;
  8506. // one options object is shared by this itemset and all its items
  8507. this.options = options || {};
  8508. this.defaultOptions = {
  8509. type: 'box',
  8510. align: 'center',
  8511. orientation: 'bottom',
  8512. margin: {
  8513. axis: 20,
  8514. item: 10
  8515. },
  8516. padding: 5
  8517. };
  8518. this.dom = {};
  8519. var me = this;
  8520. this.itemsData = null; // DataSet
  8521. this.range = null; // Range or Object {start: number, end: number}
  8522. this.listeners = {
  8523. 'add': function (event, params, senderId) {
  8524. if (senderId != me.id) {
  8525. me._onAdd(params.items);
  8526. }
  8527. },
  8528. 'update': function (event, params, senderId) {
  8529. if (senderId != me.id) {
  8530. me._onUpdate(params.items);
  8531. }
  8532. },
  8533. 'remove': function (event, params, senderId) {
  8534. if (senderId != me.id) {
  8535. me._onRemove(params.items);
  8536. }
  8537. }
  8538. };
  8539. this.items = {}; // object with an Item for every data item
  8540. this.queue = {}; // queue with id/actions: 'add', 'update', 'delete'
  8541. this.stack = new Stack(this, Object.create(this.options));
  8542. this.conversion = null;
  8543. // TODO: ItemSet should also attach event listeners for rangechange and rangechanged, like timeaxis
  8544. }
  8545. ItemSet.prototype = new Panel();
  8546. // available item types will be registered here
  8547. ItemSet.types = {
  8548. box: ItemBox,
  8549. range: ItemRange,
  8550. rangeoverflow: ItemRangeOverflow,
  8551. point: ItemPoint
  8552. };
  8553. /**
  8554. * Set options for the ItemSet. Existing options will be extended/overwritten.
  8555. * @param {Object} [options] The following options are available:
  8556. * {String | function} [className]
  8557. * class name for the itemset
  8558. * {String} [type]
  8559. * Default type for the items. Choose from 'box'
  8560. * (default), 'point', or 'range'. The default
  8561. * Style can be overwritten by individual items.
  8562. * {String} align
  8563. * Alignment for the items, only applicable for
  8564. * ItemBox. Choose 'center' (default), 'left', or
  8565. * 'right'.
  8566. * {String} orientation
  8567. * Orientation of the item set. Choose 'top' or
  8568. * 'bottom' (default).
  8569. * {Number} margin.axis
  8570. * Margin between the axis and the items in pixels.
  8571. * Default is 20.
  8572. * {Number} margin.item
  8573. * Margin between items in pixels. Default is 10.
  8574. * {Number} padding
  8575. * Padding of the contents of an item in pixels.
  8576. * Must correspond with the items css. Default is 5.
  8577. */
  8578. ItemSet.prototype.setOptions = Component.prototype.setOptions;
  8579. /**
  8580. * Set range (start and end).
  8581. * @param {Range | Object} range A Range or an object containing start and end.
  8582. */
  8583. ItemSet.prototype.setRange = function setRange(range) {
  8584. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  8585. throw new TypeError('Range must be an instance of Range, ' +
  8586. 'or an object containing start and end.');
  8587. }
  8588. this.range = range;
  8589. };
  8590. /**
  8591. * Repaint the component
  8592. * @return {Boolean} changed
  8593. */
  8594. ItemSet.prototype.repaint = function repaint() {
  8595. var changed = 0,
  8596. update = util.updateProperty,
  8597. asSize = util.option.asSize,
  8598. options = this.options,
  8599. orientation = this.getOption('orientation'),
  8600. defaultOptions = this.defaultOptions,
  8601. frame = this.frame;
  8602. if (!frame) {
  8603. frame = document.createElement('div');
  8604. frame.className = 'itemset';
  8605. var className = options.className;
  8606. if (className) {
  8607. util.addClassName(frame, util.option.asString(className));
  8608. }
  8609. // create background panel
  8610. var background = document.createElement('div');
  8611. background.className = 'background';
  8612. frame.appendChild(background);
  8613. this.dom.background = background;
  8614. // create foreground panel
  8615. var foreground = document.createElement('div');
  8616. foreground.className = 'foreground';
  8617. frame.appendChild(foreground);
  8618. this.dom.foreground = foreground;
  8619. // create axis panel
  8620. var axis = document.createElement('div');
  8621. axis.className = 'itemset-axis';
  8622. //frame.appendChild(axis);
  8623. this.dom.axis = axis;
  8624. this.frame = frame;
  8625. changed += 1;
  8626. }
  8627. if (!this.parent) {
  8628. throw new Error('Cannot repaint itemset: no parent attached');
  8629. }
  8630. var parentContainer = this.parent.getContainer();
  8631. if (!parentContainer) {
  8632. throw new Error('Cannot repaint itemset: parent has no container element');
  8633. }
  8634. if (!frame.parentNode) {
  8635. parentContainer.appendChild(frame);
  8636. changed += 1;
  8637. }
  8638. if (!this.dom.axis.parentNode) {
  8639. parentContainer.appendChild(this.dom.axis);
  8640. changed += 1;
  8641. }
  8642. // reposition frame
  8643. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  8644. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  8645. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  8646. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  8647. // reposition axis
  8648. changed += update(this.dom.axis.style, 'left', asSize(options.left, '0px'));
  8649. changed += update(this.dom.axis.style, 'width', asSize(options.width, '100%'));
  8650. if (orientation == 'bottom') {
  8651. changed += update(this.dom.axis.style, 'top', (this.height + this.top) + 'px');
  8652. }
  8653. else { // orientation == 'top'
  8654. changed += update(this.dom.axis.style, 'top', this.top + 'px');
  8655. }
  8656. this._updateConversion();
  8657. var me = this,
  8658. queue = this.queue,
  8659. itemsData = this.itemsData,
  8660. items = this.items,
  8661. dataOptions = {
  8662. // TODO: cleanup
  8663. // fields: [(itemsData && itemsData.fieldId || 'id'), 'start', 'end', 'content', 'type', 'className']
  8664. };
  8665. // show/hide added/changed/removed items
  8666. Object.keys(queue).forEach(function (id) {
  8667. //var entry = queue[id];
  8668. var action = queue[id];
  8669. var item = items[id];
  8670. //var item = entry.item;
  8671. //noinspection FallthroughInSwitchStatementJS
  8672. switch (action) {
  8673. case 'add':
  8674. case 'update':
  8675. var itemData = itemsData && itemsData.get(id, dataOptions);
  8676. if (itemData) {
  8677. var type = itemData.type ||
  8678. (itemData.start && itemData.end && 'range') ||
  8679. options.type ||
  8680. 'box';
  8681. var constructor = ItemSet.types[type];
  8682. // TODO: how to handle items with invalid data? hide them and give a warning? or throw an error?
  8683. if (item) {
  8684. // update item
  8685. if (!constructor || !(item instanceof constructor)) {
  8686. // item type has changed, hide and delete the item
  8687. changed += item.hide();
  8688. item = null;
  8689. }
  8690. else {
  8691. item.data = itemData; // TODO: create a method item.setData ?
  8692. changed++;
  8693. }
  8694. }
  8695. if (!item) {
  8696. // create item
  8697. if (constructor) {
  8698. item = new constructor(me, itemData, options, defaultOptions);
  8699. changed++;
  8700. }
  8701. else {
  8702. throw new TypeError('Unknown item type "' + type + '"');
  8703. }
  8704. }
  8705. // force a repaint (not only a reposition)
  8706. item.repaint();
  8707. items[id] = item;
  8708. }
  8709. // update queue
  8710. delete queue[id];
  8711. break;
  8712. case 'remove':
  8713. if (item) {
  8714. // remove DOM of the item
  8715. changed += item.hide();
  8716. }
  8717. // update lists
  8718. delete items[id];
  8719. delete queue[id];
  8720. break;
  8721. default:
  8722. console.log('Error: unknown action "' + action + '"');
  8723. }
  8724. });
  8725. // reposition all items. Show items only when in the visible area
  8726. util.forEach(this.items, function (item) {
  8727. if (item.visible) {
  8728. changed += item.show();
  8729. item.reposition();
  8730. }
  8731. else {
  8732. changed += item.hide();
  8733. }
  8734. });
  8735. return (changed > 0);
  8736. };
  8737. /**
  8738. * Get the foreground container element
  8739. * @return {HTMLElement} foreground
  8740. */
  8741. ItemSet.prototype.getForeground = function getForeground() {
  8742. return this.dom.foreground;
  8743. };
  8744. /**
  8745. * Get the background container element
  8746. * @return {HTMLElement} background
  8747. */
  8748. ItemSet.prototype.getBackground = function getBackground() {
  8749. return this.dom.background;
  8750. };
  8751. /**
  8752. * Get the axis container element
  8753. * @return {HTMLElement} axis
  8754. */
  8755. ItemSet.prototype.getAxis = function getAxis() {
  8756. return this.dom.axis;
  8757. };
  8758. /**
  8759. * Reflow the component
  8760. * @return {Boolean} resized
  8761. */
  8762. ItemSet.prototype.reflow = function reflow () {
  8763. var changed = 0,
  8764. options = this.options,
  8765. marginAxis = options.margin && options.margin.axis || this.defaultOptions.margin.axis,
  8766. marginItem = options.margin && options.margin.item || this.defaultOptions.margin.item,
  8767. update = util.updateProperty,
  8768. asNumber = util.option.asNumber,
  8769. asSize = util.option.asSize,
  8770. frame = this.frame;
  8771. if (frame) {
  8772. this._updateConversion();
  8773. util.forEach(this.items, function (item) {
  8774. changed += item.reflow();
  8775. });
  8776. // TODO: stack.update should be triggered via an event, in stack itself
  8777. // TODO: only update the stack when there are changed items
  8778. this.stack.update();
  8779. var maxHeight = asNumber(options.maxHeight);
  8780. var fixedHeight = (asSize(options.height) != null);
  8781. var height;
  8782. if (fixedHeight) {
  8783. height = frame.offsetHeight;
  8784. }
  8785. else {
  8786. // height is not specified, determine the height from the height and positioned items
  8787. var visibleItems = this.stack.ordered; // TODO: not so nice way to get the filtered items
  8788. if (visibleItems.length) {
  8789. var min = visibleItems[0].top;
  8790. var max = visibleItems[0].top + visibleItems[0].height;
  8791. util.forEach(visibleItems, function (item) {
  8792. min = Math.min(min, item.top);
  8793. max = Math.max(max, (item.top + item.height));
  8794. });
  8795. height = (max - min) + marginAxis + marginItem;
  8796. }
  8797. else {
  8798. height = marginAxis + marginItem;
  8799. }
  8800. }
  8801. if (maxHeight != null) {
  8802. height = Math.min(height, maxHeight);
  8803. }
  8804. changed += update(this, 'height', height);
  8805. // calculate height from items
  8806. changed += update(this, 'top', frame.offsetTop);
  8807. changed += update(this, 'left', frame.offsetLeft);
  8808. changed += update(this, 'width', frame.offsetWidth);
  8809. }
  8810. else {
  8811. changed += 1;
  8812. }
  8813. return (changed > 0);
  8814. };
  8815. /**
  8816. * Hide this component from the DOM
  8817. * @return {Boolean} changed
  8818. */
  8819. ItemSet.prototype.hide = function hide() {
  8820. var changed = false;
  8821. // remove the DOM
  8822. if (this.frame && this.frame.parentNode) {
  8823. this.frame.parentNode.removeChild(this.frame);
  8824. changed = true;
  8825. }
  8826. if (this.dom.axis && this.dom.axis.parentNode) {
  8827. this.dom.axis.parentNode.removeChild(this.dom.axis);
  8828. changed = true;
  8829. }
  8830. return changed;
  8831. };
  8832. /**
  8833. * Set items
  8834. * @param {vis.DataSet | null} items
  8835. */
  8836. ItemSet.prototype.setItems = function setItems(items) {
  8837. var me = this,
  8838. ids,
  8839. oldItemsData = this.itemsData;
  8840. // replace the dataset
  8841. if (!items) {
  8842. this.itemsData = null;
  8843. }
  8844. else if (items instanceof DataSet || items instanceof DataView) {
  8845. this.itemsData = items;
  8846. }
  8847. else {
  8848. throw new TypeError('Data must be an instance of DataSet');
  8849. }
  8850. if (oldItemsData) {
  8851. // unsubscribe from old dataset
  8852. util.forEach(this.listeners, function (callback, event) {
  8853. oldItemsData.unsubscribe(event, callback);
  8854. });
  8855. // remove all drawn items
  8856. ids = oldItemsData.getIds();
  8857. this._onRemove(ids);
  8858. }
  8859. if (this.itemsData) {
  8860. // subscribe to new dataset
  8861. var id = this.id;
  8862. util.forEach(this.listeners, function (callback, event) {
  8863. me.itemsData.subscribe(event, callback, id);
  8864. });
  8865. // draw all new items
  8866. ids = this.itemsData.getIds();
  8867. this._onAdd(ids);
  8868. }
  8869. };
  8870. /**
  8871. * Get the current items items
  8872. * @returns {vis.DataSet | null}
  8873. */
  8874. ItemSet.prototype.getItems = function getItems() {
  8875. return this.itemsData;
  8876. };
  8877. /**
  8878. * Handle updated items
  8879. * @param {Number[]} ids
  8880. * @private
  8881. */
  8882. ItemSet.prototype._onUpdate = function _onUpdate(ids) {
  8883. this._toQueue('update', ids);
  8884. };
  8885. /**
  8886. * Handle changed items
  8887. * @param {Number[]} ids
  8888. * @private
  8889. */
  8890. ItemSet.prototype._onAdd = function _onAdd(ids) {
  8891. this._toQueue('add', ids);
  8892. };
  8893. /**
  8894. * Handle removed items
  8895. * @param {Number[]} ids
  8896. * @private
  8897. */
  8898. ItemSet.prototype._onRemove = function _onRemove(ids) {
  8899. this._toQueue('remove', ids);
  8900. };
  8901. /**
  8902. * Put items in the queue to be added/updated/remove
  8903. * @param {String} action can be 'add', 'update', 'remove'
  8904. * @param {Number[]} ids
  8905. */
  8906. ItemSet.prototype._toQueue = function _toQueue(action, ids) {
  8907. var queue = this.queue;
  8908. ids.forEach(function (id) {
  8909. queue[id] = action;
  8910. });
  8911. if (this.controller) {
  8912. //this.requestReflow();
  8913. this.requestRepaint();
  8914. }
  8915. };
  8916. /**
  8917. * Calculate the scale and offset to convert a position on screen to the
  8918. * corresponding date and vice versa.
  8919. * After the method _updateConversion is executed once, the methods toTime
  8920. * and toScreen can be used.
  8921. * @private
  8922. */
  8923. ItemSet.prototype._updateConversion = function _updateConversion() {
  8924. var range = this.range;
  8925. if (!range) {
  8926. throw new Error('No range configured');
  8927. }
  8928. if (range.conversion) {
  8929. this.conversion = range.conversion(this.width);
  8930. }
  8931. else {
  8932. this.conversion = Range.conversion(range.start, range.end, this.width);
  8933. }
  8934. };
  8935. /**
  8936. * Convert a position on screen (pixels) to a datetime
  8937. * Before this method can be used, the method _updateConversion must be
  8938. * executed once.
  8939. * @param {int} x Position on the screen in pixels
  8940. * @return {Date} time The datetime the corresponds with given position x
  8941. */
  8942. ItemSet.prototype.toTime = function toTime(x) {
  8943. var conversion = this.conversion;
  8944. return new Date(x / conversion.scale + conversion.offset);
  8945. };
  8946. /**
  8947. * Convert a datetime (Date object) into a position on the screen
  8948. * Before this method can be used, the method _updateConversion must be
  8949. * executed once.
  8950. * @param {Date} time A date
  8951. * @return {int} x The position on the screen in pixels which corresponds
  8952. * with the given date.
  8953. */
  8954. ItemSet.prototype.toScreen = function toScreen(time) {
  8955. var conversion = this.conversion;
  8956. return (time.valueOf() - conversion.offset) * conversion.scale;
  8957. };
  8958. /**
  8959. * @constructor Item
  8960. * @param {ItemSet} parent
  8961. * @param {Object} data Object containing (optional) parameters type,
  8962. * start, end, content, group, className.
  8963. * @param {Object} [options] Options to set initial property values
  8964. * @param {Object} [defaultOptions] default options
  8965. * // TODO: describe available options
  8966. */
  8967. function Item (parent, data, options, defaultOptions) {
  8968. this.parent = parent;
  8969. this.data = data;
  8970. this.dom = null;
  8971. this.options = options || {};
  8972. this.defaultOptions = defaultOptions || {};
  8973. this.selected = false;
  8974. this.visible = false;
  8975. this.top = 0;
  8976. this.left = 0;
  8977. this.width = 0;
  8978. this.height = 0;
  8979. }
  8980. /**
  8981. * Select current item
  8982. */
  8983. Item.prototype.select = function select() {
  8984. this.selected = true;
  8985. };
  8986. /**
  8987. * Unselect current item
  8988. */
  8989. Item.prototype.unselect = function unselect() {
  8990. this.selected = false;
  8991. };
  8992. /**
  8993. * Show the Item in the DOM (when not already visible)
  8994. * @return {Boolean} changed
  8995. */
  8996. Item.prototype.show = function show() {
  8997. return false;
  8998. };
  8999. /**
  9000. * Hide the Item from the DOM (when visible)
  9001. * @return {Boolean} changed
  9002. */
  9003. Item.prototype.hide = function hide() {
  9004. return false;
  9005. };
  9006. /**
  9007. * Repaint the item
  9008. * @return {Boolean} changed
  9009. */
  9010. Item.prototype.repaint = function repaint() {
  9011. // should be implemented by the item
  9012. return false;
  9013. };
  9014. /**
  9015. * Reflow the item
  9016. * @return {Boolean} resized
  9017. */
  9018. Item.prototype.reflow = function reflow() {
  9019. // should be implemented by the item
  9020. return false;
  9021. };
  9022. /**
  9023. * Return the items width
  9024. * @return {Integer} width
  9025. */
  9026. Item.prototype.getWidth = function getWidth() {
  9027. return this.width;
  9028. }
  9029. /**
  9030. * @constructor ItemBox
  9031. * @extends Item
  9032. * @param {ItemSet} parent
  9033. * @param {Object} data Object containing parameters start
  9034. * content, className.
  9035. * @param {Object} [options] Options to set initial property values
  9036. * @param {Object} [defaultOptions] default options
  9037. * // TODO: describe available options
  9038. */
  9039. function ItemBox (parent, data, options, defaultOptions) {
  9040. this.props = {
  9041. dot: {
  9042. left: 0,
  9043. top: 0,
  9044. width: 0,
  9045. height: 0
  9046. },
  9047. line: {
  9048. top: 0,
  9049. left: 0,
  9050. width: 0,
  9051. height: 0
  9052. }
  9053. };
  9054. Item.call(this, parent, data, options, defaultOptions);
  9055. }
  9056. ItemBox.prototype = new Item (null, null);
  9057. /**
  9058. * Select the item
  9059. * @override
  9060. */
  9061. ItemBox.prototype.select = function select() {
  9062. this.selected = true;
  9063. // TODO: select and unselect
  9064. };
  9065. /**
  9066. * Unselect the item
  9067. * @override
  9068. */
  9069. ItemBox.prototype.unselect = function unselect() {
  9070. this.selected = false;
  9071. // TODO: select and unselect
  9072. };
  9073. /**
  9074. * Repaint the item
  9075. * @return {Boolean} changed
  9076. */
  9077. ItemBox.prototype.repaint = function repaint() {
  9078. // TODO: make an efficient repaint
  9079. var changed = false;
  9080. var dom = this.dom;
  9081. if (!dom) {
  9082. this._create();
  9083. dom = this.dom;
  9084. changed = true;
  9085. }
  9086. if (dom) {
  9087. if (!this.parent) {
  9088. throw new Error('Cannot repaint item: no parent attached');
  9089. }
  9090. if (!dom.box.parentNode) {
  9091. var foreground = this.parent.getForeground();
  9092. if (!foreground) {
  9093. throw new Error('Cannot repaint time axis: ' +
  9094. 'parent has no foreground container element');
  9095. }
  9096. foreground.appendChild(dom.box);
  9097. changed = true;
  9098. }
  9099. if (!dom.line.parentNode) {
  9100. var background = this.parent.getBackground();
  9101. if (!background) {
  9102. throw new Error('Cannot repaint time axis: ' +
  9103. 'parent has no background container element');
  9104. }
  9105. background.appendChild(dom.line);
  9106. changed = true;
  9107. }
  9108. if (!dom.dot.parentNode) {
  9109. var axis = this.parent.getAxis();
  9110. if (!background) {
  9111. throw new Error('Cannot repaint time axis: ' +
  9112. 'parent has no axis container element');
  9113. }
  9114. axis.appendChild(dom.dot);
  9115. changed = true;
  9116. }
  9117. // update contents
  9118. if (this.data.content != this.content) {
  9119. this.content = this.data.content;
  9120. if (this.content instanceof Element) {
  9121. dom.content.innerHTML = '';
  9122. dom.content.appendChild(this.content);
  9123. }
  9124. else if (this.data.content != undefined) {
  9125. dom.content.innerHTML = this.content;
  9126. }
  9127. else {
  9128. throw new Error('Property "content" missing in item ' + this.data.id);
  9129. }
  9130. changed = true;
  9131. }
  9132. // update class
  9133. var className = (this.data.className? ' ' + this.data.className : '') +
  9134. (this.selected ? ' selected' : '');
  9135. if (this.className != className) {
  9136. this.className = className;
  9137. dom.box.className = 'item box' + className;
  9138. dom.line.className = 'item line' + className;
  9139. dom.dot.className = 'item dot' + className;
  9140. changed = true;
  9141. }
  9142. }
  9143. return changed;
  9144. };
  9145. /**
  9146. * Show the item in the DOM (when not already visible). The items DOM will
  9147. * be created when needed.
  9148. * @return {Boolean} changed
  9149. */
  9150. ItemBox.prototype.show = function show() {
  9151. if (!this.dom || !this.dom.box.parentNode) {
  9152. return this.repaint();
  9153. }
  9154. else {
  9155. return false;
  9156. }
  9157. };
  9158. /**
  9159. * Hide the item from the DOM (when visible)
  9160. * @return {Boolean} changed
  9161. */
  9162. ItemBox.prototype.hide = function hide() {
  9163. var changed = false,
  9164. dom = this.dom;
  9165. if (dom) {
  9166. if (dom.box.parentNode) {
  9167. dom.box.parentNode.removeChild(dom.box);
  9168. changed = true;
  9169. }
  9170. if (dom.line.parentNode) {
  9171. dom.line.parentNode.removeChild(dom.line);
  9172. }
  9173. if (dom.dot.parentNode) {
  9174. dom.dot.parentNode.removeChild(dom.dot);
  9175. }
  9176. }
  9177. return changed;
  9178. };
  9179. /**
  9180. * Reflow the item: calculate its actual size and position from the DOM
  9181. * @return {boolean} resized returns true if the axis is resized
  9182. * @override
  9183. */
  9184. ItemBox.prototype.reflow = function reflow() {
  9185. var changed = 0,
  9186. update,
  9187. dom,
  9188. props,
  9189. options,
  9190. margin,
  9191. start,
  9192. align,
  9193. orientation,
  9194. top,
  9195. left,
  9196. data,
  9197. range;
  9198. if (this.data.start == undefined) {
  9199. throw new Error('Property "start" missing in item ' + this.data.id);
  9200. }
  9201. data = this.data;
  9202. range = this.parent && this.parent.range;
  9203. if (data && range) {
  9204. // TODO: account for the width of the item
  9205. var interval = (range.end - range.start);
  9206. this.visible = (data.start > range.start - interval) && (data.start < range.end + interval);
  9207. }
  9208. else {
  9209. this.visible = false;
  9210. }
  9211. if (this.visible) {
  9212. dom = this.dom;
  9213. if (dom) {
  9214. update = util.updateProperty;
  9215. props = this.props;
  9216. options = this.options;
  9217. start = this.parent.toScreen(this.data.start);
  9218. align = options.align || this.defaultOptions.align;
  9219. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  9220. orientation = options.orientation || this.defaultOptions.orientation;
  9221. changed += update(props.dot, 'height', dom.dot.offsetHeight);
  9222. changed += update(props.dot, 'width', dom.dot.offsetWidth);
  9223. changed += update(props.line, 'width', dom.line.offsetWidth);
  9224. changed += update(props.line, 'height', dom.line.offsetHeight);
  9225. changed += update(props.line, 'top', dom.line.offsetTop);
  9226. changed += update(this, 'width', dom.box.offsetWidth);
  9227. changed += update(this, 'height', dom.box.offsetHeight);
  9228. if (align == 'right') {
  9229. left = start - this.width;
  9230. }
  9231. else if (align == 'left') {
  9232. left = start;
  9233. }
  9234. else {
  9235. // default or 'center'
  9236. left = start - this.width / 2;
  9237. }
  9238. changed += update(this, 'left', left);
  9239. changed += update(props.line, 'left', start - props.line.width / 2);
  9240. changed += update(props.dot, 'left', start - props.dot.width / 2);
  9241. changed += update(props.dot, 'top', -props.dot.height / 2);
  9242. if (orientation == 'top') {
  9243. top = margin;
  9244. changed += update(this, 'top', top);
  9245. }
  9246. else {
  9247. // default or 'bottom'
  9248. var parentHeight = this.parent.height;
  9249. top = parentHeight - this.height - margin;
  9250. changed += update(this, 'top', top);
  9251. }
  9252. }
  9253. else {
  9254. changed += 1;
  9255. }
  9256. }
  9257. return (changed > 0);
  9258. };
  9259. /**
  9260. * Create an items DOM
  9261. * @private
  9262. */
  9263. ItemBox.prototype._create = function _create() {
  9264. var dom = this.dom;
  9265. if (!dom) {
  9266. this.dom = dom = {};
  9267. // create the box
  9268. dom.box = document.createElement('DIV');
  9269. // className is updated in repaint()
  9270. // contents box (inside the background box). used for making margins
  9271. dom.content = document.createElement('DIV');
  9272. dom.content.className = 'content';
  9273. dom.box.appendChild(dom.content);
  9274. // line to axis
  9275. dom.line = document.createElement('DIV');
  9276. dom.line.className = 'line';
  9277. // dot on axis
  9278. dom.dot = document.createElement('DIV');
  9279. dom.dot.className = 'dot';
  9280. }
  9281. };
  9282. /**
  9283. * Reposition the item, recalculate its left, top, and width, using the current
  9284. * range and size of the items itemset
  9285. * @override
  9286. */
  9287. ItemBox.prototype.reposition = function reposition() {
  9288. var dom = this.dom,
  9289. props = this.props,
  9290. orientation = this.options.orientation || this.defaultOptions.orientation;
  9291. if (dom) {
  9292. var box = dom.box,
  9293. line = dom.line,
  9294. dot = dom.dot;
  9295. box.style.left = this.left + 'px';
  9296. box.style.top = this.top + 'px';
  9297. line.style.left = props.line.left + 'px';
  9298. if (orientation == 'top') {
  9299. line.style.top = 0 + 'px';
  9300. line.style.height = this.top + 'px';
  9301. }
  9302. else {
  9303. // orientation 'bottom'
  9304. line.style.top = (this.top + this.height) + 'px';
  9305. line.style.height = Math.max(this.parent.height - this.top - this.height +
  9306. this.props.dot.height / 2, 0) + 'px';
  9307. }
  9308. dot.style.left = props.dot.left + 'px';
  9309. dot.style.top = props.dot.top + 'px';
  9310. }
  9311. };
  9312. /**
  9313. * @constructor ItemPoint
  9314. * @extends Item
  9315. * @param {ItemSet} parent
  9316. * @param {Object} data Object containing parameters start
  9317. * content, className.
  9318. * @param {Object} [options] Options to set initial property values
  9319. * @param {Object} [defaultOptions] default options
  9320. * // TODO: describe available options
  9321. */
  9322. function ItemPoint (parent, data, options, defaultOptions) {
  9323. this.props = {
  9324. dot: {
  9325. top: 0,
  9326. width: 0,
  9327. height: 0
  9328. },
  9329. content: {
  9330. height: 0,
  9331. marginLeft: 0
  9332. }
  9333. };
  9334. Item.call(this, parent, data, options, defaultOptions);
  9335. }
  9336. ItemPoint.prototype = new Item (null, null);
  9337. /**
  9338. * Select the item
  9339. * @override
  9340. */
  9341. ItemPoint.prototype.select = function select() {
  9342. this.selected = true;
  9343. // TODO: select and unselect
  9344. };
  9345. /**
  9346. * Unselect the item
  9347. * @override
  9348. */
  9349. ItemPoint.prototype.unselect = function unselect() {
  9350. this.selected = false;
  9351. // TODO: select and unselect
  9352. };
  9353. /**
  9354. * Repaint the item
  9355. * @return {Boolean} changed
  9356. */
  9357. ItemPoint.prototype.repaint = function repaint() {
  9358. // TODO: make an efficient repaint
  9359. var changed = false;
  9360. var dom = this.dom;
  9361. if (!dom) {
  9362. this._create();
  9363. dom = this.dom;
  9364. changed = true;
  9365. }
  9366. if (dom) {
  9367. if (!this.parent) {
  9368. throw new Error('Cannot repaint item: no parent attached');
  9369. }
  9370. var foreground = this.parent.getForeground();
  9371. if (!foreground) {
  9372. throw new Error('Cannot repaint time axis: ' +
  9373. 'parent has no foreground container element');
  9374. }
  9375. if (!dom.point.parentNode) {
  9376. foreground.appendChild(dom.point);
  9377. foreground.appendChild(dom.point);
  9378. changed = true;
  9379. }
  9380. // update contents
  9381. if (this.data.content != this.content) {
  9382. this.content = this.data.content;
  9383. if (this.content instanceof Element) {
  9384. dom.content.innerHTML = '';
  9385. dom.content.appendChild(this.content);
  9386. }
  9387. else if (this.data.content != undefined) {
  9388. dom.content.innerHTML = this.content;
  9389. }
  9390. else {
  9391. throw new Error('Property "content" missing in item ' + this.data.id);
  9392. }
  9393. changed = true;
  9394. }
  9395. // update class
  9396. var className = (this.data.className? ' ' + this.data.className : '') +
  9397. (this.selected ? ' selected' : '');
  9398. if (this.className != className) {
  9399. this.className = className;
  9400. dom.point.className = 'item point' + className;
  9401. changed = true;
  9402. }
  9403. }
  9404. return changed;
  9405. };
  9406. /**
  9407. * Show the item in the DOM (when not already visible). The items DOM will
  9408. * be created when needed.
  9409. * @return {Boolean} changed
  9410. */
  9411. ItemPoint.prototype.show = function show() {
  9412. if (!this.dom || !this.dom.point.parentNode) {
  9413. return this.repaint();
  9414. }
  9415. else {
  9416. return false;
  9417. }
  9418. };
  9419. /**
  9420. * Hide the item from the DOM (when visible)
  9421. * @return {Boolean} changed
  9422. */
  9423. ItemPoint.prototype.hide = function hide() {
  9424. var changed = false,
  9425. dom = this.dom;
  9426. if (dom) {
  9427. if (dom.point.parentNode) {
  9428. dom.point.parentNode.removeChild(dom.point);
  9429. changed = true;
  9430. }
  9431. }
  9432. return changed;
  9433. };
  9434. /**
  9435. * Reflow the item: calculate its actual size from the DOM
  9436. * @return {boolean} resized returns true if the axis is resized
  9437. * @override
  9438. */
  9439. ItemPoint.prototype.reflow = function reflow() {
  9440. var changed = 0,
  9441. update,
  9442. dom,
  9443. props,
  9444. options,
  9445. margin,
  9446. orientation,
  9447. start,
  9448. top,
  9449. data,
  9450. range;
  9451. if (this.data.start == undefined) {
  9452. throw new Error('Property "start" missing in item ' + this.data.id);
  9453. }
  9454. data = this.data;
  9455. range = this.parent && this.parent.range;
  9456. if (data && range) {
  9457. // TODO: account for the width of the item
  9458. var interval = (range.end - range.start);
  9459. this.visible = (data.start > range.start - interval) && (data.start < range.end);
  9460. }
  9461. else {
  9462. this.visible = false;
  9463. }
  9464. if (this.visible) {
  9465. dom = this.dom;
  9466. if (dom) {
  9467. update = util.updateProperty;
  9468. props = this.props;
  9469. options = this.options;
  9470. orientation = options.orientation || this.defaultOptions.orientation;
  9471. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  9472. start = this.parent.toScreen(this.data.start);
  9473. changed += update(this, 'width', dom.point.offsetWidth);
  9474. changed += update(this, 'height', dom.point.offsetHeight);
  9475. changed += update(props.dot, 'width', dom.dot.offsetWidth);
  9476. changed += update(props.dot, 'height', dom.dot.offsetHeight);
  9477. changed += update(props.content, 'height', dom.content.offsetHeight);
  9478. if (orientation == 'top') {
  9479. top = margin;
  9480. }
  9481. else {
  9482. // default or 'bottom'
  9483. var parentHeight = this.parent.height;
  9484. top = Math.max(parentHeight - this.height - margin, 0);
  9485. }
  9486. changed += update(this, 'top', top);
  9487. changed += update(this, 'left', start - props.dot.width / 2);
  9488. changed += update(props.content, 'marginLeft', 1.5 * props.dot.width);
  9489. //changed += update(props.content, 'marginRight', 0.5 * props.dot.width); // TODO
  9490. changed += update(props.dot, 'top', (this.height - props.dot.height) / 2);
  9491. }
  9492. else {
  9493. changed += 1;
  9494. }
  9495. }
  9496. return (changed > 0);
  9497. };
  9498. /**
  9499. * Create an items DOM
  9500. * @private
  9501. */
  9502. ItemPoint.prototype._create = function _create() {
  9503. var dom = this.dom;
  9504. if (!dom) {
  9505. this.dom = dom = {};
  9506. // background box
  9507. dom.point = document.createElement('div');
  9508. // className is updated in repaint()
  9509. // contents box, right from the dot
  9510. dom.content = document.createElement('div');
  9511. dom.content.className = 'content';
  9512. dom.point.appendChild(dom.content);
  9513. // dot at start
  9514. dom.dot = document.createElement('div');
  9515. dom.dot.className = 'dot';
  9516. dom.point.appendChild(dom.dot);
  9517. }
  9518. };
  9519. /**
  9520. * Reposition the item, recalculate its left, top, and width, using the current
  9521. * range and size of the items itemset
  9522. * @override
  9523. */
  9524. ItemPoint.prototype.reposition = function reposition() {
  9525. var dom = this.dom,
  9526. props = this.props;
  9527. if (dom) {
  9528. dom.point.style.top = this.top + 'px';
  9529. dom.point.style.left = this.left + 'px';
  9530. dom.content.style.marginLeft = props.content.marginLeft + 'px';
  9531. //dom.content.style.marginRight = props.content.marginRight + 'px'; // TODO
  9532. dom.dot.style.top = props.dot.top + 'px';
  9533. }
  9534. };
  9535. /**
  9536. * @constructor ItemRange
  9537. * @extends Item
  9538. * @param {ItemSet} parent
  9539. * @param {Object} data Object containing parameters start, end
  9540. * content, className.
  9541. * @param {Object} [options] Options to set initial property values
  9542. * @param {Object} [defaultOptions] default options
  9543. * // TODO: describe available options
  9544. */
  9545. function ItemRange (parent, data, options, defaultOptions) {
  9546. this.props = {
  9547. content: {
  9548. left: 0,
  9549. width: 0
  9550. }
  9551. };
  9552. Item.call(this, parent, data, options, defaultOptions);
  9553. }
  9554. ItemRange.prototype = new Item (null, null);
  9555. /**
  9556. * Select the item
  9557. * @override
  9558. */
  9559. ItemRange.prototype.select = function select() {
  9560. this.selected = true;
  9561. // TODO: select and unselect
  9562. };
  9563. /**
  9564. * Unselect the item
  9565. * @override
  9566. */
  9567. ItemRange.prototype.unselect = function unselect() {
  9568. this.selected = false;
  9569. // TODO: select and unselect
  9570. };
  9571. /**
  9572. * Repaint the item
  9573. * @return {Boolean} changed
  9574. */
  9575. ItemRange.prototype.repaint = function repaint() {
  9576. // TODO: make an efficient repaint
  9577. var changed = false;
  9578. var dom = this.dom;
  9579. if (!dom) {
  9580. this._create();
  9581. dom = this.dom;
  9582. changed = true;
  9583. }
  9584. if (dom) {
  9585. if (!this.parent) {
  9586. throw new Error('Cannot repaint item: no parent attached');
  9587. }
  9588. var foreground = this.parent.getForeground();
  9589. if (!foreground) {
  9590. throw new Error('Cannot repaint time axis: ' +
  9591. 'parent has no foreground container element');
  9592. }
  9593. if (!dom.box.parentNode) {
  9594. foreground.appendChild(dom.box);
  9595. changed = true;
  9596. }
  9597. // update content
  9598. if (this.data.content != this.content) {
  9599. this.content = this.data.content;
  9600. if (this.content instanceof Element) {
  9601. dom.content.innerHTML = '';
  9602. dom.content.appendChild(this.content);
  9603. }
  9604. else if (this.data.content != undefined) {
  9605. dom.content.innerHTML = this.content;
  9606. }
  9607. else {
  9608. throw new Error('Property "content" missing in item ' + this.data.id);
  9609. }
  9610. changed = true;
  9611. }
  9612. // update class
  9613. var className = this.data.className ? (' ' + this.data.className) : '';
  9614. if (this.className != className) {
  9615. this.className = className;
  9616. dom.box.className = 'item range' + className;
  9617. changed = true;
  9618. }
  9619. }
  9620. return changed;
  9621. };
  9622. /**
  9623. * Show the item in the DOM (when not already visible). The items DOM will
  9624. * be created when needed.
  9625. * @return {Boolean} changed
  9626. */
  9627. ItemRange.prototype.show = function show() {
  9628. if (!this.dom || !this.dom.box.parentNode) {
  9629. return this.repaint();
  9630. }
  9631. else {
  9632. return false;
  9633. }
  9634. };
  9635. /**
  9636. * Hide the item from the DOM (when visible)
  9637. * @return {Boolean} changed
  9638. */
  9639. ItemRange.prototype.hide = function hide() {
  9640. var changed = false,
  9641. dom = this.dom;
  9642. if (dom) {
  9643. if (dom.box.parentNode) {
  9644. dom.box.parentNode.removeChild(dom.box);
  9645. changed = true;
  9646. }
  9647. }
  9648. return changed;
  9649. };
  9650. /**
  9651. * Reflow the item: calculate its actual size from the DOM
  9652. * @return {boolean} resized returns true if the axis is resized
  9653. * @override
  9654. */
  9655. ItemRange.prototype.reflow = function reflow() {
  9656. var changed = 0,
  9657. dom,
  9658. props,
  9659. options,
  9660. margin,
  9661. padding,
  9662. parent,
  9663. start,
  9664. end,
  9665. data,
  9666. range,
  9667. update,
  9668. box,
  9669. parentWidth,
  9670. contentLeft,
  9671. orientation,
  9672. top;
  9673. if (this.data.start == undefined) {
  9674. throw new Error('Property "start" missing in item ' + this.data.id);
  9675. }
  9676. if (this.data.end == undefined) {
  9677. throw new Error('Property "end" missing in item ' + this.data.id);
  9678. }
  9679. data = this.data;
  9680. range = this.parent && this.parent.range;
  9681. if (data && range) {
  9682. // TODO: account for the width of the item. Take some margin
  9683. this.visible = (data.start < range.end) && (data.end > range.start);
  9684. }
  9685. else {
  9686. this.visible = false;
  9687. }
  9688. if (this.visible) {
  9689. dom = this.dom;
  9690. if (dom) {
  9691. props = this.props;
  9692. options = this.options;
  9693. parent = this.parent;
  9694. start = parent.toScreen(this.data.start);
  9695. end = parent.toScreen(this.data.end);
  9696. update = util.updateProperty;
  9697. box = dom.box;
  9698. parentWidth = parent.width;
  9699. orientation = options.orientation || this.defaultOptions.orientation;
  9700. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  9701. padding = options.padding || this.defaultOptions.padding;
  9702. changed += update(props.content, 'width', dom.content.offsetWidth);
  9703. changed += update(this, 'height', box.offsetHeight);
  9704. // limit the width of the this, as browsers cannot draw very wide divs
  9705. if (start < -parentWidth) {
  9706. start = -parentWidth;
  9707. }
  9708. if (end > 2 * parentWidth) {
  9709. end = 2 * parentWidth;
  9710. }
  9711. // when range exceeds left of the window, position the contents at the left of the visible area
  9712. if (start < 0) {
  9713. contentLeft = Math.min(-start,
  9714. (end - start - props.content.width - 2 * padding));
  9715. // TODO: remove the need for options.padding. it's terrible.
  9716. }
  9717. else {
  9718. contentLeft = 0;
  9719. }
  9720. changed += update(props.content, 'left', contentLeft);
  9721. if (orientation == 'top') {
  9722. top = margin;
  9723. changed += update(this, 'top', top);
  9724. }
  9725. else {
  9726. // default or 'bottom'
  9727. top = parent.height - this.height - margin;
  9728. changed += update(this, 'top', top);
  9729. }
  9730. changed += update(this, 'left', start);
  9731. changed += update(this, 'width', Math.max(end - start, 1)); // TODO: reckon with border width;
  9732. }
  9733. else {
  9734. changed += 1;
  9735. }
  9736. }
  9737. return (changed > 0);
  9738. };
  9739. /**
  9740. * Create an items DOM
  9741. * @private
  9742. */
  9743. ItemRange.prototype._create = function _create() {
  9744. var dom = this.dom;
  9745. if (!dom) {
  9746. this.dom = dom = {};
  9747. // background box
  9748. dom.box = document.createElement('div');
  9749. // className is updated in repaint()
  9750. // contents box
  9751. dom.content = document.createElement('div');
  9752. dom.content.className = 'content';
  9753. dom.box.appendChild(dom.content);
  9754. }
  9755. };
  9756. /**
  9757. * Reposition the item, recalculate its left, top, and width, using the current
  9758. * range and size of the items itemset
  9759. * @override
  9760. */
  9761. ItemRange.prototype.reposition = function reposition() {
  9762. var dom = this.dom,
  9763. props = this.props;
  9764. if (dom) {
  9765. dom.box.style.top = this.top + 'px';
  9766. dom.box.style.left = this.left + 'px';
  9767. dom.box.style.width = this.width + 'px';
  9768. dom.content.style.left = props.content.left + 'px';
  9769. }
  9770. };
  9771. /**
  9772. * @constructor ItemRangeOverflow
  9773. * @extends ItemRange
  9774. * @param {ItemSet} parent
  9775. * @param {Object} data Object containing parameters start, end
  9776. * content, className.
  9777. * @param {Object} [options] Options to set initial property values
  9778. * @param {Object} [defaultOptions] default options
  9779. * // TODO: describe available options
  9780. */
  9781. function ItemRangeOverflow (parent, data, options, defaultOptions) {
  9782. this.props = {
  9783. content: {
  9784. left: 0,
  9785. width: 0
  9786. }
  9787. };
  9788. ItemRange.call(this, parent, data, options, defaultOptions);
  9789. }
  9790. ItemRangeOverflow.prototype = new ItemRange (null, null);
  9791. /**
  9792. * Repaint the item
  9793. * @return {Boolean} changed
  9794. */
  9795. ItemRangeOverflow.prototype.repaint = function repaint() {
  9796. // TODO: make an efficient repaint
  9797. var changed = false;
  9798. var dom = this.dom;
  9799. if (!dom) {
  9800. this._create();
  9801. dom = this.dom;
  9802. changed = true;
  9803. }
  9804. if (dom) {
  9805. if (!this.parent) {
  9806. throw new Error('Cannot repaint item: no parent attached');
  9807. }
  9808. var foreground = this.parent.getForeground();
  9809. if (!foreground) {
  9810. throw new Error('Cannot repaint time axis: ' +
  9811. 'parent has no foreground container element');
  9812. }
  9813. if (!dom.box.parentNode) {
  9814. foreground.appendChild(dom.box);
  9815. changed = true;
  9816. }
  9817. // update content
  9818. if (this.data.content != this.content) {
  9819. this.content = this.data.content;
  9820. if (this.content instanceof Element) {
  9821. dom.content.innerHTML = '';
  9822. dom.content.appendChild(this.content);
  9823. }
  9824. else if (this.data.content != undefined) {
  9825. dom.content.innerHTML = this.content;
  9826. }
  9827. else {
  9828. throw new Error('Property "content" missing in item ' + this.data.id);
  9829. }
  9830. changed = true;
  9831. }
  9832. // update class
  9833. var className = this.data.className ? (' ' + this.data.className) : '';
  9834. if (this.className != className) {
  9835. this.className = className;
  9836. dom.box.className = 'item rangeoverflow' + className;
  9837. changed = true;
  9838. }
  9839. }
  9840. return changed;
  9841. };
  9842. /**
  9843. * Return the items width
  9844. * @return {Number} width
  9845. */
  9846. ItemRangeOverflow.prototype.getWidth = function getWidth() {
  9847. if (this.props.content !== undefined && this.width < this.props.content.width)
  9848. return this.props.content.width;
  9849. else
  9850. return this.width;
  9851. };
  9852. /**
  9853. * @constructor Group
  9854. * @param {GroupSet} parent
  9855. * @param {Number | String} groupId
  9856. * @param {Object} [options] Options to set initial property values
  9857. * // TODO: describe available options
  9858. * @extends Component
  9859. */
  9860. function Group (parent, groupId, options) {
  9861. this.id = util.randomUUID();
  9862. this.parent = parent;
  9863. this.groupId = groupId;
  9864. this.itemset = null; // ItemSet
  9865. this.options = options || {};
  9866. this.options.top = 0;
  9867. this.props = {
  9868. label: {
  9869. width: 0,
  9870. height: 0
  9871. }
  9872. };
  9873. this.top = 0;
  9874. this.left = 0;
  9875. this.width = 0;
  9876. this.height = 0;
  9877. }
  9878. Group.prototype = new Component();
  9879. // TODO: comment
  9880. Group.prototype.setOptions = Component.prototype.setOptions;
  9881. /**
  9882. * Get the container element of the panel, which can be used by a child to
  9883. * add its own widgets.
  9884. * @returns {HTMLElement} container
  9885. */
  9886. Group.prototype.getContainer = function () {
  9887. return this.parent.getContainer();
  9888. };
  9889. /**
  9890. * Set item set for the group. The group will create a view on the itemset,
  9891. * filtered by the groups id.
  9892. * @param {DataSet | DataView} items
  9893. */
  9894. Group.prototype.setItems = function setItems(items) {
  9895. if (this.itemset) {
  9896. // remove current item set
  9897. this.itemset.hide();
  9898. this.itemset.setItems();
  9899. this.parent.controller.remove(this.itemset);
  9900. this.itemset = null;
  9901. }
  9902. if (items) {
  9903. var groupId = this.groupId;
  9904. var itemsetOptions = Object.create(this.options);
  9905. this.itemset = new ItemSet(this, null, itemsetOptions);
  9906. this.itemset.setRange(this.parent.range);
  9907. this.view = new DataView(items, {
  9908. filter: function (item) {
  9909. return item.group == groupId;
  9910. }
  9911. });
  9912. this.itemset.setItems(this.view);
  9913. this.parent.controller.add(this.itemset);
  9914. }
  9915. };
  9916. /**
  9917. * Repaint the item
  9918. * @return {Boolean} changed
  9919. */
  9920. Group.prototype.repaint = function repaint() {
  9921. return false;
  9922. };
  9923. /**
  9924. * Reflow the item
  9925. * @return {Boolean} resized
  9926. */
  9927. Group.prototype.reflow = function reflow() {
  9928. var changed = 0,
  9929. update = util.updateProperty;
  9930. changed += update(this, 'top', this.itemset ? this.itemset.top : 0);
  9931. changed += update(this, 'height', this.itemset ? this.itemset.height : 0);
  9932. // TODO: reckon with the height of the group label
  9933. if (this.label) {
  9934. var inner = this.label.firstChild;
  9935. changed += update(this.props.label, 'width', inner.clientWidth);
  9936. changed += update(this.props.label, 'height', inner.clientHeight);
  9937. }
  9938. else {
  9939. changed += update(this.props.label, 'width', 0);
  9940. changed += update(this.props.label, 'height', 0);
  9941. }
  9942. return (changed > 0);
  9943. };
  9944. /**
  9945. * An GroupSet holds a set of groups
  9946. * @param {Component} parent
  9947. * @param {Component[]} [depends] Components on which this components depends
  9948. * (except for the parent)
  9949. * @param {Object} [options] See GroupSet.setOptions for the available
  9950. * options.
  9951. * @constructor GroupSet
  9952. * @extends Panel
  9953. */
  9954. function GroupSet(parent, depends, options) {
  9955. this.id = util.randomUUID();
  9956. this.parent = parent;
  9957. this.depends = depends;
  9958. this.options = options || {};
  9959. this.range = null; // Range or Object {start: number, end: number}
  9960. this.itemsData = null; // DataSet with items
  9961. this.groupsData = null; // DataSet with groups
  9962. this.groups = {}; // map with groups
  9963. this.dom = {};
  9964. this.props = {
  9965. labels: {
  9966. width: 0
  9967. }
  9968. };
  9969. // TODO: implement right orientation of the labels
  9970. // changes in groups are queued key/value map containing id/action
  9971. this.queue = {};
  9972. var me = this;
  9973. this.listeners = {
  9974. 'add': function (event, params) {
  9975. me._onAdd(params.items);
  9976. },
  9977. 'update': function (event, params) {
  9978. me._onUpdate(params.items);
  9979. },
  9980. 'remove': function (event, params) {
  9981. me._onRemove(params.items);
  9982. }
  9983. };
  9984. }
  9985. GroupSet.prototype = new Panel();
  9986. /**
  9987. * Set options for the GroupSet. Existing options will be extended/overwritten.
  9988. * @param {Object} [options] The following options are available:
  9989. * {String | function} groupsOrder
  9990. * TODO: describe options
  9991. */
  9992. GroupSet.prototype.setOptions = Component.prototype.setOptions;
  9993. GroupSet.prototype.setRange = function (range) {
  9994. // TODO: implement setRange
  9995. };
  9996. /**
  9997. * Set items
  9998. * @param {vis.DataSet | null} items
  9999. */
  10000. GroupSet.prototype.setItems = function setItems(items) {
  10001. this.itemsData = items;
  10002. for (var id in this.groups) {
  10003. if (this.groups.hasOwnProperty(id)) {
  10004. var group = this.groups[id];
  10005. group.setItems(items);
  10006. }
  10007. }
  10008. };
  10009. /**
  10010. * Get items
  10011. * @return {vis.DataSet | null} items
  10012. */
  10013. GroupSet.prototype.getItems = function getItems() {
  10014. return this.itemsData;
  10015. };
  10016. /**
  10017. * Set range (start and end).
  10018. * @param {Range | Object} range A Range or an object containing start and end.
  10019. */
  10020. GroupSet.prototype.setRange = function setRange(range) {
  10021. this.range = range;
  10022. };
  10023. /**
  10024. * Set groups
  10025. * @param {vis.DataSet} groups
  10026. */
  10027. GroupSet.prototype.setGroups = function setGroups(groups) {
  10028. var me = this,
  10029. ids;
  10030. // unsubscribe from current dataset
  10031. if (this.groupsData) {
  10032. util.forEach(this.listeners, function (callback, event) {
  10033. me.groupsData.unsubscribe(event, callback);
  10034. });
  10035. // remove all drawn groups
  10036. ids = this.groupsData.getIds();
  10037. this._onRemove(ids);
  10038. }
  10039. // replace the dataset
  10040. if (!groups) {
  10041. this.groupsData = null;
  10042. }
  10043. else if (groups instanceof DataSet) {
  10044. this.groupsData = groups;
  10045. }
  10046. else {
  10047. this.groupsData = new DataSet({
  10048. convert: {
  10049. start: 'Date',
  10050. end: 'Date'
  10051. }
  10052. });
  10053. this.groupsData.add(groups);
  10054. }
  10055. if (this.groupsData) {
  10056. // subscribe to new dataset
  10057. var id = this.id;
  10058. util.forEach(this.listeners, function (callback, event) {
  10059. me.groupsData.subscribe(event, callback, id);
  10060. });
  10061. // draw all new groups
  10062. ids = this.groupsData.getIds();
  10063. this._onAdd(ids);
  10064. }
  10065. };
  10066. /**
  10067. * Get groups
  10068. * @return {vis.DataSet | null} groups
  10069. */
  10070. GroupSet.prototype.getGroups = function getGroups() {
  10071. return this.groupsData;
  10072. };
  10073. /**
  10074. * Repaint the component
  10075. * @return {Boolean} changed
  10076. */
  10077. GroupSet.prototype.repaint = function repaint() {
  10078. var changed = 0,
  10079. i, id, group, label,
  10080. update = util.updateProperty,
  10081. asSize = util.option.asSize,
  10082. asElement = util.option.asElement,
  10083. options = this.options,
  10084. frame = this.dom.frame,
  10085. labels = this.dom.labels,
  10086. labelSet = this.dom.labelSet;
  10087. // create frame
  10088. if (!this.parent) {
  10089. throw new Error('Cannot repaint groupset: no parent attached');
  10090. }
  10091. var parentContainer = this.parent.getContainer();
  10092. if (!parentContainer) {
  10093. throw new Error('Cannot repaint groupset: parent has no container element');
  10094. }
  10095. if (!frame) {
  10096. frame = document.createElement('div');
  10097. frame.className = 'groupset';
  10098. this.dom.frame = frame;
  10099. var className = options.className;
  10100. if (className) {
  10101. util.addClassName(frame, util.option.asString(className));
  10102. }
  10103. changed += 1;
  10104. }
  10105. if (!frame.parentNode) {
  10106. parentContainer.appendChild(frame);
  10107. changed += 1;
  10108. }
  10109. // create labels
  10110. var labelContainer = asElement(options.labelContainer);
  10111. if (!labelContainer) {
  10112. throw new Error('Cannot repaint groupset: option "labelContainer" not defined');
  10113. }
  10114. if (!labels) {
  10115. labels = document.createElement('div');
  10116. labels.className = 'labels';
  10117. this.dom.labels = labels;
  10118. }
  10119. if (!labelSet) {
  10120. labelSet = document.createElement('div');
  10121. labelSet.className = 'label-set';
  10122. labels.appendChild(labelSet);
  10123. this.dom.labelSet = labelSet;
  10124. }
  10125. if (!labels.parentNode || labels.parentNode != labelContainer) {
  10126. if (labels.parentNode) {
  10127. labels.parentNode.removeChild(labels.parentNode);
  10128. }
  10129. labelContainer.appendChild(labels);
  10130. }
  10131. // reposition frame
  10132. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  10133. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  10134. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  10135. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  10136. // reposition labels
  10137. changed += update(labelSet.style, 'top', asSize(options.top, '0px'));
  10138. changed += update(labelSet.style, 'height', asSize(options.height, this.height + 'px'));
  10139. var me = this,
  10140. queue = this.queue,
  10141. groups = this.groups,
  10142. groupsData = this.groupsData;
  10143. // show/hide added/changed/removed groups
  10144. var ids = Object.keys(queue);
  10145. if (ids.length) {
  10146. ids.forEach(function (id) {
  10147. var action = queue[id];
  10148. var group = groups[id];
  10149. //noinspection FallthroughInSwitchStatementJS
  10150. switch (action) {
  10151. case 'add':
  10152. case 'update':
  10153. if (!group) {
  10154. var groupOptions = Object.create(me.options);
  10155. util.extend(groupOptions, {
  10156. height: null,
  10157. maxHeight: null
  10158. });
  10159. group = new Group(me, id, groupOptions);
  10160. group.setItems(me.itemsData); // attach items data
  10161. groups[id] = group;
  10162. me.controller.add(group);
  10163. }
  10164. // TODO: update group data
  10165. group.data = groupsData.get(id);
  10166. delete queue[id];
  10167. break;
  10168. case 'remove':
  10169. if (group) {
  10170. group.setItems(); // detach items data
  10171. delete groups[id];
  10172. me.controller.remove(group);
  10173. }
  10174. // update lists
  10175. delete queue[id];
  10176. break;
  10177. default:
  10178. console.log('Error: unknown action "' + action + '"');
  10179. }
  10180. });
  10181. // the groupset depends on each of the groups
  10182. //this.depends = this.groups; // TODO: gives a circular reference through the parent
  10183. // TODO: apply dependencies of the groupset
  10184. // update the top positions of the groups in the correct order
  10185. var orderedGroups = this.groupsData.getIds({
  10186. order: this.options.groupOrder
  10187. });
  10188. for (i = 0; i < orderedGroups.length; i++) {
  10189. (function (group, prevGroup) {
  10190. var top = 0;
  10191. if (prevGroup) {
  10192. top = function () {
  10193. // TODO: top must reckon with options.maxHeight
  10194. return prevGroup.top + prevGroup.height;
  10195. }
  10196. }
  10197. group.setOptions({
  10198. top: top
  10199. });
  10200. })(groups[orderedGroups[i]], groups[orderedGroups[i - 1]]);
  10201. }
  10202. // (re)create the labels
  10203. while (labelSet.firstChild) {
  10204. labelSet.removeChild(labelSet.firstChild);
  10205. }
  10206. for (i = 0; i < orderedGroups.length; i++) {
  10207. id = orderedGroups[i];
  10208. label = this._createLabel(id);
  10209. labelSet.appendChild(label);
  10210. }
  10211. changed++;
  10212. }
  10213. // reposition the labels
  10214. // TODO: labels are not displayed correctly when orientation=='top'
  10215. // TODO: width of labelPanel is not immediately updated on a change in groups
  10216. for (id in groups) {
  10217. if (groups.hasOwnProperty(id)) {
  10218. group = groups[id];
  10219. label = group.label;
  10220. if (label) {
  10221. label.style.top = group.top + 'px';
  10222. label.style.height = group.height + 'px';
  10223. }
  10224. }
  10225. }
  10226. return (changed > 0);
  10227. };
  10228. /**
  10229. * Create a label for group with given id
  10230. * @param {Number} id
  10231. * @return {Element} label
  10232. * @private
  10233. */
  10234. GroupSet.prototype._createLabel = function(id) {
  10235. var group = this.groups[id];
  10236. var label = document.createElement('div');
  10237. label.className = 'label';
  10238. var inner = document.createElement('div');
  10239. inner.className = 'inner';
  10240. label.appendChild(inner);
  10241. var content = group.data && group.data.content;
  10242. if (content instanceof Element) {
  10243. inner.appendChild(content);
  10244. }
  10245. else if (content != undefined) {
  10246. inner.innerHTML = content;
  10247. }
  10248. var className = group.data && group.data.className;
  10249. if (className) {
  10250. util.addClassName(label, className);
  10251. }
  10252. group.label = label; // TODO: not so nice, parking labels in the group this way!!!
  10253. return label;
  10254. };
  10255. /**
  10256. * Get container element
  10257. * @return {HTMLElement} container
  10258. */
  10259. GroupSet.prototype.getContainer = function getContainer() {
  10260. return this.dom.frame;
  10261. };
  10262. /**
  10263. * Get the width of the group labels
  10264. * @return {Number} width
  10265. */
  10266. GroupSet.prototype.getLabelsWidth = function getContainer() {
  10267. return this.props.labels.width;
  10268. };
  10269. /**
  10270. * Reflow the component
  10271. * @return {Boolean} resized
  10272. */
  10273. GroupSet.prototype.reflow = function reflow() {
  10274. var changed = 0,
  10275. id, group,
  10276. options = this.options,
  10277. update = util.updateProperty,
  10278. asNumber = util.option.asNumber,
  10279. asSize = util.option.asSize,
  10280. frame = this.dom.frame;
  10281. if (frame) {
  10282. var maxHeight = asNumber(options.maxHeight);
  10283. var fixedHeight = (asSize(options.height) != null);
  10284. var height;
  10285. if (fixedHeight) {
  10286. height = frame.offsetHeight;
  10287. }
  10288. else {
  10289. // height is not specified, calculate the sum of the height of all groups
  10290. height = 0;
  10291. for (id in this.groups) {
  10292. if (this.groups.hasOwnProperty(id)) {
  10293. group = this.groups[id];
  10294. height += group.height;
  10295. }
  10296. }
  10297. }
  10298. if (maxHeight != null) {
  10299. height = Math.min(height, maxHeight);
  10300. }
  10301. changed += update(this, 'height', height);
  10302. changed += update(this, 'top', frame.offsetTop);
  10303. changed += update(this, 'left', frame.offsetLeft);
  10304. changed += update(this, 'width', frame.offsetWidth);
  10305. }
  10306. // calculate the maximum width of the labels
  10307. var width = 0;
  10308. for (id in this.groups) {
  10309. if (this.groups.hasOwnProperty(id)) {
  10310. group = this.groups[id];
  10311. var labelWidth = group.props && group.props.label && group.props.label.width || 0;
  10312. width = Math.max(width, labelWidth);
  10313. }
  10314. }
  10315. changed += update(this.props.labels, 'width', width);
  10316. return (changed > 0);
  10317. };
  10318. /**
  10319. * Hide the component from the DOM
  10320. * @return {Boolean} changed
  10321. */
  10322. GroupSet.prototype.hide = function hide() {
  10323. if (this.dom.frame && this.dom.frame.parentNode) {
  10324. this.dom.frame.parentNode.removeChild(this.dom.frame);
  10325. return true;
  10326. }
  10327. else {
  10328. return false;
  10329. }
  10330. };
  10331. /**
  10332. * Show the component in the DOM (when not already visible).
  10333. * A repaint will be executed when the component is not visible
  10334. * @return {Boolean} changed
  10335. */
  10336. GroupSet.prototype.show = function show() {
  10337. if (!this.dom.frame || !this.dom.frame.parentNode) {
  10338. return this.repaint();
  10339. }
  10340. else {
  10341. return false;
  10342. }
  10343. };
  10344. /**
  10345. * Handle updated groups
  10346. * @param {Number[]} ids
  10347. * @private
  10348. */
  10349. GroupSet.prototype._onUpdate = function _onUpdate(ids) {
  10350. this._toQueue(ids, 'update');
  10351. };
  10352. /**
  10353. * Handle changed groups
  10354. * @param {Number[]} ids
  10355. * @private
  10356. */
  10357. GroupSet.prototype._onAdd = function _onAdd(ids) {
  10358. this._toQueue(ids, 'add');
  10359. };
  10360. /**
  10361. * Handle removed groups
  10362. * @param {Number[]} ids
  10363. * @private
  10364. */
  10365. GroupSet.prototype._onRemove = function _onRemove(ids) {
  10366. this._toQueue(ids, 'remove');
  10367. };
  10368. /**
  10369. * Put groups in the queue to be added/updated/remove
  10370. * @param {Number[]} ids
  10371. * @param {String} action can be 'add', 'update', 'remove'
  10372. */
  10373. GroupSet.prototype._toQueue = function _toQueue(ids, action) {
  10374. var queue = this.queue;
  10375. ids.forEach(function (id) {
  10376. queue[id] = action;
  10377. });
  10378. if (this.controller) {
  10379. //this.requestReflow();
  10380. this.requestRepaint();
  10381. }
  10382. };
  10383. /**
  10384. * Create a timeline visualization
  10385. * @param {HTMLElement} container
  10386. * @param {vis.DataSet | Array | DataTable} [items]
  10387. * @param {Object} [options] See Timeline.setOptions for the available options.
  10388. * @constructor
  10389. */
  10390. function Timeline (container, items, options) {
  10391. var me = this;
  10392. var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0);
  10393. this.options = {
  10394. orientation: 'bottom',
  10395. min: null,
  10396. max: null,
  10397. zoomMin: 10, // milliseconds
  10398. zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000, // milliseconds
  10399. // moveable: true, // TODO: option moveable
  10400. // zoomable: true, // TODO: option zoomable
  10401. showMinorLabels: true,
  10402. showMajorLabels: true,
  10403. showCurrentTime: false,
  10404. showCustomTime: false,
  10405. autoResize: false
  10406. };
  10407. // controller
  10408. this.controller = new Controller();
  10409. // root panel
  10410. if (!container) {
  10411. throw new Error('No container element provided');
  10412. }
  10413. var rootOptions = Object.create(this.options);
  10414. rootOptions.height = function () {
  10415. // TODO: change to height
  10416. if (me.options.height) {
  10417. // fixed height
  10418. return me.options.height;
  10419. }
  10420. else {
  10421. // auto height
  10422. return (me.timeaxis.height + me.content.height) + 'px';
  10423. }
  10424. };
  10425. this.rootPanel = new RootPanel(container, rootOptions);
  10426. this.controller.add(this.rootPanel);
  10427. // item panel
  10428. var itemOptions = Object.create(this.options);
  10429. itemOptions.left = function () {
  10430. return me.labelPanel.width;
  10431. };
  10432. itemOptions.width = function () {
  10433. return me.rootPanel.width - me.labelPanel.width;
  10434. };
  10435. itemOptions.top = null;
  10436. itemOptions.height = null;
  10437. this.itemPanel = new Panel(this.rootPanel, [], itemOptions);
  10438. this.controller.add(this.itemPanel);
  10439. // label panel
  10440. var labelOptions = Object.create(this.options);
  10441. labelOptions.top = null;
  10442. labelOptions.left = null;
  10443. labelOptions.height = null;
  10444. labelOptions.width = function () {
  10445. if (me.content && typeof me.content.getLabelsWidth === 'function') {
  10446. return me.content.getLabelsWidth();
  10447. }
  10448. else {
  10449. return 0;
  10450. }
  10451. };
  10452. this.labelPanel = new Panel(this.rootPanel, [], labelOptions);
  10453. this.controller.add(this.labelPanel);
  10454. // range
  10455. var rangeOptions = Object.create(this.options);
  10456. this.range = new Range(rangeOptions);
  10457. this.range.setRange(
  10458. now.clone().add('days', -3).valueOf(),
  10459. now.clone().add('days', 4).valueOf()
  10460. );
  10461. // TODO: reckon with options moveable and zoomable
  10462. this.range.subscribe(this.rootPanel, 'move', 'horizontal');
  10463. this.range.subscribe(this.rootPanel, 'zoom', 'horizontal');
  10464. this.range.on('rangechange', function () {
  10465. var force = true;
  10466. me.controller.requestReflow(force);
  10467. });
  10468. this.range.on('rangechanged', function () {
  10469. var force = true;
  10470. me.controller.requestReflow(force);
  10471. });
  10472. // TODO: put the listeners in setOptions, be able to dynamically change with options moveable and zoomable
  10473. // time axis
  10474. var timeaxisOptions = Object.create(rootOptions);
  10475. timeaxisOptions.range = this.range;
  10476. timeaxisOptions.left = null;
  10477. timeaxisOptions.top = null;
  10478. timeaxisOptions.width = '100%';
  10479. timeaxisOptions.height = null;
  10480. this.timeaxis = new TimeAxis(this.itemPanel, [], timeaxisOptions);
  10481. this.timeaxis.setRange(this.range);
  10482. this.controller.add(this.timeaxis);
  10483. // current time bar
  10484. this.currenttime = new CurrentTime(this.timeaxis, [], rootOptions);
  10485. this.controller.add(this.currenttime);
  10486. // custom time bar
  10487. this.customtime = new CustomTime(this.timeaxis, [], rootOptions);
  10488. this.controller.add(this.customtime);
  10489. // create groupset
  10490. this.setGroups(null);
  10491. this.itemsData = null; // DataSet
  10492. this.groupsData = null; // DataSet
  10493. // apply options
  10494. if (options) {
  10495. this.setOptions(options);
  10496. }
  10497. // create itemset and groupset
  10498. if (items) {
  10499. this.setItems(items);
  10500. }
  10501. }
  10502. /**
  10503. * Set options
  10504. * @param {Object} options TODO: describe the available options
  10505. */
  10506. Timeline.prototype.setOptions = function (options) {
  10507. util.extend(this.options, options);
  10508. // force update of range
  10509. // options.start and options.end can be undefined
  10510. //this.range.setRange(options.start, options.end);
  10511. this.range.setRange();
  10512. this.controller.reflow();
  10513. this.controller.repaint();
  10514. };
  10515. /**
  10516. * Set a custom time bar
  10517. * @param {Date} time
  10518. */
  10519. Timeline.prototype.setCustomTime = function (time) {
  10520. this.customtime._setCustomTime(time);
  10521. };
  10522. /**
  10523. * Retrieve the current custom time.
  10524. * @return {Date} customTime
  10525. */
  10526. Timeline.prototype.getCustomTime = function() {
  10527. return new Date(this.customtime.customTime.valueOf());
  10528. };
  10529. /**
  10530. * Set items
  10531. * @param {vis.DataSet | Array | DataTable | null} items
  10532. */
  10533. Timeline.prototype.setItems = function(items) {
  10534. var initialLoad = (this.itemsData == null);
  10535. // convert to type DataSet when needed
  10536. var newItemSet;
  10537. if (!items) {
  10538. newItemSet = null;
  10539. }
  10540. else if (items instanceof DataSet) {
  10541. newItemSet = items;
  10542. }
  10543. if (!(items instanceof DataSet)) {
  10544. newItemSet = new DataSet({
  10545. convert: {
  10546. start: 'Date',
  10547. end: 'Date'
  10548. }
  10549. });
  10550. newItemSet.add(items);
  10551. }
  10552. // set items
  10553. this.itemsData = newItemSet;
  10554. this.content.setItems(newItemSet);
  10555. if (initialLoad && (this.options.start == undefined || this.options.end == undefined)) {
  10556. // apply the data range as range
  10557. var dataRange = this.getItemRange();
  10558. // add 5% space on both sides
  10559. var min = dataRange.min;
  10560. var max = dataRange.max;
  10561. if (min != null && max != null) {
  10562. var interval = (max.valueOf() - min.valueOf());
  10563. if (interval <= 0) {
  10564. // prevent an empty interval
  10565. interval = 24 * 60 * 60 * 1000; // 1 day
  10566. }
  10567. min = new Date(min.valueOf() - interval * 0.05);
  10568. max = new Date(max.valueOf() + interval * 0.05);
  10569. }
  10570. // override specified start and/or end date
  10571. if (this.options.start != undefined) {
  10572. min = util.convert(this.options.start, 'Date');
  10573. }
  10574. if (this.options.end != undefined) {
  10575. max = util.convert(this.options.end, 'Date');
  10576. }
  10577. // apply range if there is a min or max available
  10578. if (min != null || max != null) {
  10579. this.range.setRange(min, max);
  10580. }
  10581. }
  10582. };
  10583. /**
  10584. * Set groups
  10585. * @param {vis.DataSet | Array | DataTable} groups
  10586. */
  10587. Timeline.prototype.setGroups = function(groups) {
  10588. var me = this;
  10589. this.groupsData = groups;
  10590. // switch content type between ItemSet or GroupSet when needed
  10591. var Type = this.groupsData ? GroupSet : ItemSet;
  10592. if (!(this.content instanceof Type)) {
  10593. // remove old content set
  10594. if (this.content) {
  10595. this.content.hide();
  10596. if (this.content.setItems) {
  10597. this.content.setItems(); // disconnect from items
  10598. }
  10599. if (this.content.setGroups) {
  10600. this.content.setGroups(); // disconnect from groups
  10601. }
  10602. this.controller.remove(this.content);
  10603. }
  10604. // create new content set
  10605. var options = Object.create(this.options);
  10606. util.extend(options, {
  10607. top: function () {
  10608. if (me.options.orientation == 'top') {
  10609. return me.timeaxis.height;
  10610. }
  10611. else {
  10612. return me.itemPanel.height - me.timeaxis.height - me.content.height;
  10613. }
  10614. },
  10615. left: null,
  10616. width: '100%',
  10617. height: function () {
  10618. if (me.options.height) {
  10619. // fixed height
  10620. return me.itemPanel.height - me.timeaxis.height;
  10621. }
  10622. else {
  10623. // auto height
  10624. return null;
  10625. }
  10626. },
  10627. maxHeight: function () {
  10628. // TODO: change maxHeight to be a css string like '100%' or '300px'
  10629. if (me.options.maxHeight) {
  10630. if (!util.isNumber(me.options.maxHeight)) {
  10631. throw new TypeError('Number expected for property maxHeight');
  10632. }
  10633. return me.options.maxHeight - me.timeaxis.height;
  10634. }
  10635. else {
  10636. return null;
  10637. }
  10638. },
  10639. labelContainer: function () {
  10640. return me.labelPanel.getContainer();
  10641. }
  10642. });
  10643. this.content = new Type(this.itemPanel, [this.timeaxis], options);
  10644. if (this.content.setRange) {
  10645. this.content.setRange(this.range);
  10646. }
  10647. if (this.content.setItems) {
  10648. this.content.setItems(this.itemsData);
  10649. }
  10650. if (this.content.setGroups) {
  10651. this.content.setGroups(this.groupsData);
  10652. }
  10653. this.controller.add(this.content);
  10654. }
  10655. };
  10656. /**
  10657. * Get the data range of the item set.
  10658. * @returns {{min: Date, max: Date}} range A range with a start and end Date.
  10659. * When no minimum is found, min==null
  10660. * When no maximum is found, max==null
  10661. */
  10662. Timeline.prototype.getItemRange = function getItemRange() {
  10663. // calculate min from start filed
  10664. var itemsData = this.itemsData,
  10665. min = null,
  10666. max = null;
  10667. if (itemsData) {
  10668. // calculate the minimum value of the field 'start'
  10669. var minItem = itemsData.min('start');
  10670. min = minItem ? minItem.start.valueOf() : null;
  10671. // calculate maximum value of fields 'start' and 'end'
  10672. var maxStartItem = itemsData.max('start');
  10673. if (maxStartItem) {
  10674. max = maxStartItem.start.valueOf();
  10675. }
  10676. var maxEndItem = itemsData.max('end');
  10677. if (maxEndItem) {
  10678. if (max == null) {
  10679. max = maxEndItem.end.valueOf();
  10680. }
  10681. else {
  10682. max = Math.max(max, maxEndItem.end.valueOf());
  10683. }
  10684. }
  10685. }
  10686. return {
  10687. min: (min != null) ? new Date(min) : null,
  10688. max: (max != null) ? new Date(max) : null
  10689. };
  10690. };
  10691. (function(exports) {
  10692. /**
  10693. * Parse a text source containing data in DOT language into a JSON object.
  10694. * The object contains two lists: one with nodes and one with edges.
  10695. *
  10696. * DOT language reference: http://www.graphviz.org/doc/info/lang.html
  10697. *
  10698. * @param {String} data Text containing a graph in DOT-notation
  10699. * @return {Object} graph An object containing two parameters:
  10700. * {Object[]} nodes
  10701. * {Object[]} edges
  10702. */
  10703. function parseDOT (data) {
  10704. dot = data;
  10705. return parseGraph();
  10706. }
  10707. // token types enumeration
  10708. var TOKENTYPE = {
  10709. NULL : 0,
  10710. DELIMITER : 1,
  10711. IDENTIFIER: 2,
  10712. UNKNOWN : 3
  10713. };
  10714. // map with all delimiters
  10715. var DELIMITERS = {
  10716. '{': true,
  10717. '}': true,
  10718. '[': true,
  10719. ']': true,
  10720. ';': true,
  10721. '=': true,
  10722. ',': true,
  10723. '->': true,
  10724. '--': true
  10725. };
  10726. var dot = ''; // current dot file
  10727. var index = 0; // current index in dot file
  10728. var c = ''; // current token character in expr
  10729. var token = ''; // current token
  10730. var tokenType = TOKENTYPE.NULL; // type of the token
  10731. /**
  10732. * Get the first character from the dot file.
  10733. * The character is stored into the char c. If the end of the dot file is
  10734. * reached, the function puts an empty string in c.
  10735. */
  10736. function first() {
  10737. index = 0;
  10738. c = dot.charAt(0);
  10739. }
  10740. /**
  10741. * Get the next character from the dot file.
  10742. * The character is stored into the char c. If the end of the dot file is
  10743. * reached, the function puts an empty string in c.
  10744. */
  10745. function next() {
  10746. index++;
  10747. c = dot.charAt(index);
  10748. }
  10749. /**
  10750. * Preview the next character from the dot file.
  10751. * @return {String} cNext
  10752. */
  10753. function nextPreview() {
  10754. return dot.charAt(index + 1);
  10755. }
  10756. /**
  10757. * Test whether given character is alphabetic or numeric
  10758. * @param {String} c
  10759. * @return {Boolean} isAlphaNumeric
  10760. */
  10761. var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/;
  10762. function isAlphaNumeric(c) {
  10763. return regexAlphaNumeric.test(c);
  10764. }
  10765. /**
  10766. * Merge all properties of object b into object b
  10767. * @param {Object} a
  10768. * @param {Object} b
  10769. * @return {Object} a
  10770. */
  10771. function merge (a, b) {
  10772. if (!a) {
  10773. a = {};
  10774. }
  10775. if (b) {
  10776. for (var name in b) {
  10777. if (b.hasOwnProperty(name)) {
  10778. a[name] = b[name];
  10779. }
  10780. }
  10781. }
  10782. return a;
  10783. }
  10784. /**
  10785. * Set a value in an object, where the provided parameter name can be a
  10786. * path with nested parameters. For example:
  10787. *
  10788. * var obj = {a: 2};
  10789. * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}}
  10790. *
  10791. * @param {Object} obj
  10792. * @param {String} path A parameter name or dot-separated parameter path,
  10793. * like "color.highlight.border".
  10794. * @param {*} value
  10795. */
  10796. function setValue(obj, path, value) {
  10797. var keys = path.split('.');
  10798. var o = obj;
  10799. while (keys.length) {
  10800. var key = keys.shift();
  10801. if (keys.length) {
  10802. // this isn't the end point
  10803. if (!o[key]) {
  10804. o[key] = {};
  10805. }
  10806. o = o[key];
  10807. }
  10808. else {
  10809. // this is the end point
  10810. o[key] = value;
  10811. }
  10812. }
  10813. }
  10814. /**
  10815. * Add a node to a graph object. If there is already a node with
  10816. * the same id, their attributes will be merged.
  10817. * @param {Object} graph
  10818. * @param {Object} node
  10819. */
  10820. function addNode(graph, node) {
  10821. var i, len;
  10822. var current = null;
  10823. // find root graph (in case of subgraph)
  10824. var graphs = [graph]; // list with all graphs from current graph to root graph
  10825. var root = graph;
  10826. while (root.parent) {
  10827. graphs.push(root.parent);
  10828. root = root.parent;
  10829. }
  10830. // find existing node (at root level) by its id
  10831. if (root.nodes) {
  10832. for (i = 0, len = root.nodes.length; i < len; i++) {
  10833. if (node.id === root.nodes[i].id) {
  10834. current = root.nodes[i];
  10835. break;
  10836. }
  10837. }
  10838. }
  10839. if (!current) {
  10840. // this is a new node
  10841. current = {
  10842. id: node.id
  10843. };
  10844. if (graph.node) {
  10845. // clone default attributes
  10846. current.attr = merge(current.attr, graph.node);
  10847. }
  10848. }
  10849. // add node to this (sub)graph and all its parent graphs
  10850. for (i = graphs.length - 1; i >= 0; i--) {
  10851. var g = graphs[i];
  10852. if (!g.nodes) {
  10853. g.nodes = [];
  10854. }
  10855. if (g.nodes.indexOf(current) == -1) {
  10856. g.nodes.push(current);
  10857. }
  10858. }
  10859. // merge attributes
  10860. if (node.attr) {
  10861. current.attr = merge(current.attr, node.attr);
  10862. }
  10863. }
  10864. /**
  10865. * Add an edge to a graph object
  10866. * @param {Object} graph
  10867. * @param {Object} edge
  10868. */
  10869. function addEdge(graph, edge) {
  10870. if (!graph.edges) {
  10871. graph.edges = [];
  10872. }
  10873. graph.edges.push(edge);
  10874. if (graph.edge) {
  10875. var attr = merge({}, graph.edge); // clone default attributes
  10876. edge.attr = merge(attr, edge.attr); // merge attributes
  10877. }
  10878. }
  10879. /**
  10880. * Create an edge to a graph object
  10881. * @param {Object} graph
  10882. * @param {String | Number | Object} from
  10883. * @param {String | Number | Object} to
  10884. * @param {String} type
  10885. * @param {Object | null} attr
  10886. * @return {Object} edge
  10887. */
  10888. function createEdge(graph, from, to, type, attr) {
  10889. var edge = {
  10890. from: from,
  10891. to: to,
  10892. type: type
  10893. };
  10894. if (graph.edge) {
  10895. edge.attr = merge({}, graph.edge); // clone default attributes
  10896. }
  10897. edge.attr = merge(edge.attr || {}, attr); // merge attributes
  10898. return edge;
  10899. }
  10900. /**
  10901. * Get next token in the current dot file.
  10902. * The token and token type are available as token and tokenType
  10903. */
  10904. function getToken() {
  10905. tokenType = TOKENTYPE.NULL;
  10906. token = '';
  10907. // skip over whitespaces
  10908. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  10909. next();
  10910. }
  10911. do {
  10912. var isComment = false;
  10913. // skip comment
  10914. if (c == '#') {
  10915. // find the previous non-space character
  10916. var i = index - 1;
  10917. while (dot.charAt(i) == ' ' || dot.charAt(i) == '\t') {
  10918. i--;
  10919. }
  10920. if (dot.charAt(i) == '\n' || dot.charAt(i) == '') {
  10921. // the # is at the start of a line, this is indeed a line comment
  10922. while (c != '' && c != '\n') {
  10923. next();
  10924. }
  10925. isComment = true;
  10926. }
  10927. }
  10928. if (c == '/' && nextPreview() == '/') {
  10929. // skip line comment
  10930. while (c != '' && c != '\n') {
  10931. next();
  10932. }
  10933. isComment = true;
  10934. }
  10935. if (c == '/' && nextPreview() == '*') {
  10936. // skip block comment
  10937. while (c != '') {
  10938. if (c == '*' && nextPreview() == '/') {
  10939. // end of block comment found. skip these last two characters
  10940. next();
  10941. next();
  10942. break;
  10943. }
  10944. else {
  10945. next();
  10946. }
  10947. }
  10948. isComment = true;
  10949. }
  10950. // skip over whitespaces
  10951. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  10952. next();
  10953. }
  10954. }
  10955. while (isComment);
  10956. // check for end of dot file
  10957. if (c == '') {
  10958. // token is still empty
  10959. tokenType = TOKENTYPE.DELIMITER;
  10960. return;
  10961. }
  10962. // check for delimiters consisting of 2 characters
  10963. var c2 = c + nextPreview();
  10964. if (DELIMITERS[c2]) {
  10965. tokenType = TOKENTYPE.DELIMITER;
  10966. token = c2;
  10967. next();
  10968. next();
  10969. return;
  10970. }
  10971. // check for delimiters consisting of 1 character
  10972. if (DELIMITERS[c]) {
  10973. tokenType = TOKENTYPE.DELIMITER;
  10974. token = c;
  10975. next();
  10976. return;
  10977. }
  10978. // check for an identifier (number or string)
  10979. // TODO: more precise parsing of numbers/strings (and the port separator ':')
  10980. if (isAlphaNumeric(c) || c == '-') {
  10981. token += c;
  10982. next();
  10983. while (isAlphaNumeric(c)) {
  10984. token += c;
  10985. next();
  10986. }
  10987. if (token == 'false') {
  10988. token = false; // convert to boolean
  10989. }
  10990. else if (token == 'true') {
  10991. token = true; // convert to boolean
  10992. }
  10993. else if (!isNaN(Number(token))) {
  10994. token = Number(token); // convert to number
  10995. }
  10996. tokenType = TOKENTYPE.IDENTIFIER;
  10997. return;
  10998. }
  10999. // check for a string enclosed by double quotes
  11000. if (c == '"') {
  11001. next();
  11002. while (c != '' && (c != '"' || (c == '"' && nextPreview() == '"'))) {
  11003. token += c;
  11004. if (c == '"') { // skip the escape character
  11005. next();
  11006. }
  11007. next();
  11008. }
  11009. if (c != '"') {
  11010. throw newSyntaxError('End of string " expected');
  11011. }
  11012. next();
  11013. tokenType = TOKENTYPE.IDENTIFIER;
  11014. return;
  11015. }
  11016. // something unknown is found, wrong characters, a syntax error
  11017. tokenType = TOKENTYPE.UNKNOWN;
  11018. while (c != '') {
  11019. token += c;
  11020. next();
  11021. }
  11022. throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"');
  11023. }
  11024. /**
  11025. * Parse a graph.
  11026. * @returns {Object} graph
  11027. */
  11028. function parseGraph() {
  11029. var graph = {};
  11030. first();
  11031. getToken();
  11032. // optional strict keyword
  11033. if (token == 'strict') {
  11034. graph.strict = true;
  11035. getToken();
  11036. }
  11037. // graph or digraph keyword
  11038. if (token == 'graph' || token == 'digraph') {
  11039. graph.type = token;
  11040. getToken();
  11041. }
  11042. // optional graph id
  11043. if (tokenType == TOKENTYPE.IDENTIFIER) {
  11044. graph.id = token;
  11045. getToken();
  11046. }
  11047. // open angle bracket
  11048. if (token != '{') {
  11049. throw newSyntaxError('Angle bracket { expected');
  11050. }
  11051. getToken();
  11052. // statements
  11053. parseStatements(graph);
  11054. // close angle bracket
  11055. if (token != '}') {
  11056. throw newSyntaxError('Angle bracket } expected');
  11057. }
  11058. getToken();
  11059. // end of file
  11060. if (token !== '') {
  11061. throw newSyntaxError('End of file expected');
  11062. }
  11063. getToken();
  11064. // remove temporary default properties
  11065. delete graph.node;
  11066. delete graph.edge;
  11067. delete graph.graph;
  11068. return graph;
  11069. }
  11070. /**
  11071. * Parse a list with statements.
  11072. * @param {Object} graph
  11073. */
  11074. function parseStatements (graph) {
  11075. while (token !== '' && token != '}') {
  11076. parseStatement(graph);
  11077. if (token == ';') {
  11078. getToken();
  11079. }
  11080. }
  11081. }
  11082. /**
  11083. * Parse a single statement. Can be a an attribute statement, node
  11084. * statement, a series of node statements and edge statements, or a
  11085. * parameter.
  11086. * @param {Object} graph
  11087. */
  11088. function parseStatement(graph) {
  11089. // parse subgraph
  11090. var subgraph = parseSubgraph(graph);
  11091. if (subgraph) {
  11092. // edge statements
  11093. parseEdge(graph, subgraph);
  11094. return;
  11095. }
  11096. // parse an attribute statement
  11097. var attr = parseAttributeStatement(graph);
  11098. if (attr) {
  11099. return;
  11100. }
  11101. // parse node
  11102. if (tokenType != TOKENTYPE.IDENTIFIER) {
  11103. throw newSyntaxError('Identifier expected');
  11104. }
  11105. var id = token; // id can be a string or a number
  11106. getToken();
  11107. if (token == '=') {
  11108. // id statement
  11109. getToken();
  11110. if (tokenType != TOKENTYPE.IDENTIFIER) {
  11111. throw newSyntaxError('Identifier expected');
  11112. }
  11113. graph[id] = token;
  11114. getToken();
  11115. // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] "
  11116. }
  11117. else {
  11118. parseNodeStatement(graph, id);
  11119. }
  11120. }
  11121. /**
  11122. * Parse a subgraph
  11123. * @param {Object} graph parent graph object
  11124. * @return {Object | null} subgraph
  11125. */
  11126. function parseSubgraph (graph) {
  11127. var subgraph = null;
  11128. // optional subgraph keyword
  11129. if (token == 'subgraph') {
  11130. subgraph = {};
  11131. subgraph.type = 'subgraph';
  11132. getToken();
  11133. // optional graph id
  11134. if (tokenType == TOKENTYPE.IDENTIFIER) {
  11135. subgraph.id = token;
  11136. getToken();
  11137. }
  11138. }
  11139. // open angle bracket
  11140. if (token == '{') {
  11141. getToken();
  11142. if (!subgraph) {
  11143. subgraph = {};
  11144. }
  11145. subgraph.parent = graph;
  11146. subgraph.node = graph.node;
  11147. subgraph.edge = graph.edge;
  11148. subgraph.graph = graph.graph;
  11149. // statements
  11150. parseStatements(subgraph);
  11151. // close angle bracket
  11152. if (token != '}') {
  11153. throw newSyntaxError('Angle bracket } expected');
  11154. }
  11155. getToken();
  11156. // remove temporary default properties
  11157. delete subgraph.node;
  11158. delete subgraph.edge;
  11159. delete subgraph.graph;
  11160. delete subgraph.parent;
  11161. // register at the parent graph
  11162. if (!graph.subgraphs) {
  11163. graph.subgraphs = [];
  11164. }
  11165. graph.subgraphs.push(subgraph);
  11166. }
  11167. return subgraph;
  11168. }
  11169. /**
  11170. * parse an attribute statement like "node [shape=circle fontSize=16]".
  11171. * Available keywords are 'node', 'edge', 'graph'.
  11172. * The previous list with default attributes will be replaced
  11173. * @param {Object} graph
  11174. * @returns {String | null} keyword Returns the name of the parsed attribute
  11175. * (node, edge, graph), or null if nothing
  11176. * is parsed.
  11177. */
  11178. function parseAttributeStatement (graph) {
  11179. // attribute statements
  11180. if (token == 'node') {
  11181. getToken();
  11182. // node attributes
  11183. graph.node = parseAttributeList();
  11184. return 'node';
  11185. }
  11186. else if (token == 'edge') {
  11187. getToken();
  11188. // edge attributes
  11189. graph.edge = parseAttributeList();
  11190. return 'edge';
  11191. }
  11192. else if (token == 'graph') {
  11193. getToken();
  11194. // graph attributes
  11195. graph.graph = parseAttributeList();
  11196. return 'graph';
  11197. }
  11198. return null;
  11199. }
  11200. /**
  11201. * parse a node statement
  11202. * @param {Object} graph
  11203. * @param {String | Number} id
  11204. */
  11205. function parseNodeStatement(graph, id) {
  11206. // node statement
  11207. var node = {
  11208. id: id
  11209. };
  11210. var attr = parseAttributeList();
  11211. if (attr) {
  11212. node.attr = attr;
  11213. }
  11214. addNode(graph, node);
  11215. // edge statements
  11216. parseEdge(graph, id);
  11217. }
  11218. /**
  11219. * Parse an edge or a series of edges
  11220. * @param {Object} graph
  11221. * @param {String | Number} from Id of the from node
  11222. */
  11223. function parseEdge(graph, from) {
  11224. while (token == '->' || token == '--') {
  11225. var to;
  11226. var type = token;
  11227. getToken();
  11228. var subgraph = parseSubgraph(graph);
  11229. if (subgraph) {
  11230. to = subgraph;
  11231. }
  11232. else {
  11233. if (tokenType != TOKENTYPE.IDENTIFIER) {
  11234. throw newSyntaxError('Identifier or subgraph expected');
  11235. }
  11236. to = token;
  11237. addNode(graph, {
  11238. id: to
  11239. });
  11240. getToken();
  11241. }
  11242. // parse edge attributes
  11243. var attr = parseAttributeList();
  11244. // create edge
  11245. var edge = createEdge(graph, from, to, type, attr);
  11246. addEdge(graph, edge);
  11247. from = to;
  11248. }
  11249. }
  11250. /**
  11251. * Parse a set with attributes,
  11252. * for example [label="1.000", shape=solid]
  11253. * @return {Object | null} attr
  11254. */
  11255. function parseAttributeList() {
  11256. var attr = null;
  11257. while (token == '[') {
  11258. getToken();
  11259. attr = {};
  11260. while (token !== '' && token != ']') {
  11261. if (tokenType != TOKENTYPE.IDENTIFIER) {
  11262. throw newSyntaxError('Attribute name expected');
  11263. }
  11264. var name = token;
  11265. getToken();
  11266. if (token != '=') {
  11267. throw newSyntaxError('Equal sign = expected');
  11268. }
  11269. getToken();
  11270. if (tokenType != TOKENTYPE.IDENTIFIER) {
  11271. throw newSyntaxError('Attribute value expected');
  11272. }
  11273. var value = token;
  11274. setValue(attr, name, value); // name can be a path
  11275. getToken();
  11276. if (token ==',') {
  11277. getToken();
  11278. }
  11279. }
  11280. if (token != ']') {
  11281. throw newSyntaxError('Bracket ] expected');
  11282. }
  11283. getToken();
  11284. }
  11285. return attr;
  11286. }
  11287. /**
  11288. * Create a syntax error with extra information on current token and index.
  11289. * @param {String} message
  11290. * @returns {SyntaxError} err
  11291. */
  11292. function newSyntaxError(message) {
  11293. return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')');
  11294. }
  11295. /**
  11296. * Chop off text after a maximum length
  11297. * @param {String} text
  11298. * @param {Number} maxLength
  11299. * @returns {String}
  11300. */
  11301. function chop (text, maxLength) {
  11302. return (text.length <= maxLength) ? text : (text.substr(0, 27) + '...');
  11303. }
  11304. /**
  11305. * Execute a function fn for each pair of elements in two arrays
  11306. * @param {Array | *} array1
  11307. * @param {Array | *} array2
  11308. * @param {function} fn
  11309. */
  11310. function forEach2(array1, array2, fn) {
  11311. if (array1 instanceof Array) {
  11312. array1.forEach(function (elem1) {
  11313. if (array2 instanceof Array) {
  11314. array2.forEach(function (elem2) {
  11315. fn(elem1, elem2);
  11316. });
  11317. }
  11318. else {
  11319. fn(elem1, array2);
  11320. }
  11321. });
  11322. }
  11323. else {
  11324. if (array2 instanceof Array) {
  11325. array2.forEach(function (elem2) {
  11326. fn(array1, elem2);
  11327. });
  11328. }
  11329. else {
  11330. fn(array1, array2);
  11331. }
  11332. }
  11333. }
  11334. /**
  11335. * Convert a string containing a graph in DOT language into a map containing
  11336. * with nodes and edges in the format of graph.
  11337. * @param {String} data Text containing a graph in DOT-notation
  11338. * @return {Object} graphData
  11339. */
  11340. function DOTToGraph (data) {
  11341. // parse the DOT file
  11342. var dotData = parseDOT(data);
  11343. var graphData = {
  11344. nodes: [],
  11345. edges: [],
  11346. options: {}
  11347. };
  11348. // copy the nodes
  11349. if (dotData.nodes) {
  11350. dotData.nodes.forEach(function (dotNode) {
  11351. var graphNode = {
  11352. id: dotNode.id,
  11353. label: String(dotNode.label || dotNode.id)
  11354. };
  11355. merge(graphNode, dotNode.attr);
  11356. if (graphNode.image) {
  11357. graphNode.shape = 'image';
  11358. }
  11359. graphData.nodes.push(graphNode);
  11360. });
  11361. }
  11362. // copy the edges
  11363. if (dotData.edges) {
  11364. /**
  11365. * Convert an edge in DOT format to an edge with VisGraph format
  11366. * @param {Object} dotEdge
  11367. * @returns {Object} graphEdge
  11368. */
  11369. function convertEdge(dotEdge) {
  11370. var graphEdge = {
  11371. from: dotEdge.from,
  11372. to: dotEdge.to
  11373. };
  11374. merge(graphEdge, dotEdge.attr);
  11375. graphEdge.style = (dotEdge.type == '->') ? 'arrow' : 'line';
  11376. return graphEdge;
  11377. }
  11378. dotData.edges.forEach(function (dotEdge) {
  11379. var from, to;
  11380. if (dotEdge.from instanceof Object) {
  11381. from = dotEdge.from.nodes;
  11382. }
  11383. else {
  11384. from = {
  11385. id: dotEdge.from
  11386. }
  11387. }
  11388. if (dotEdge.to instanceof Object) {
  11389. to = dotEdge.to.nodes;
  11390. }
  11391. else {
  11392. to = {
  11393. id: dotEdge.to
  11394. }
  11395. }
  11396. if (dotEdge.from instanceof Object && dotEdge.from.edges) {
  11397. dotEdge.from.edges.forEach(function (subEdge) {
  11398. var graphEdge = convertEdge(subEdge);
  11399. graphData.edges.push(graphEdge);
  11400. });
  11401. }
  11402. forEach2(from, to, function (from, to) {
  11403. var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr);
  11404. var graphEdge = convertEdge(subEdge);
  11405. graphData.edges.push(graphEdge);
  11406. });
  11407. if (dotEdge.to instanceof Object && dotEdge.to.edges) {
  11408. dotEdge.to.edges.forEach(function (subEdge) {
  11409. var graphEdge = convertEdge(subEdge);
  11410. graphData.edges.push(graphEdge);
  11411. });
  11412. }
  11413. });
  11414. }
  11415. // copy the options
  11416. if (dotData.attr) {
  11417. graphData.options = dotData.attr;
  11418. }
  11419. return graphData;
  11420. }
  11421. // exports
  11422. exports.parseDOT = parseDOT;
  11423. exports.DOTToGraph = DOTToGraph;
  11424. })(typeof util !== 'undefined' ? util : exports);
  11425. /**
  11426. * Canvas shapes used by the Graph
  11427. */
  11428. if (typeof CanvasRenderingContext2D !== 'undefined') {
  11429. /**
  11430. * Draw a circle shape
  11431. */
  11432. CanvasRenderingContext2D.prototype.circle = function(x, y, r) {
  11433. this.beginPath();
  11434. this.arc(x, y, r, 0, 2*Math.PI, false);
  11435. };
  11436. /**
  11437. * Draw a square shape
  11438. * @param {Number} x horizontal center
  11439. * @param {Number} y vertical center
  11440. * @param {Number} r size, width and height of the square
  11441. */
  11442. CanvasRenderingContext2D.prototype.square = function(x, y, r) {
  11443. this.beginPath();
  11444. this.rect(x - r, y - r, r * 2, r * 2);
  11445. };
  11446. /**
  11447. * Draw a triangle shape
  11448. * @param {Number} x horizontal center
  11449. * @param {Number} y vertical center
  11450. * @param {Number} r radius, half the length of the sides of the triangle
  11451. */
  11452. CanvasRenderingContext2D.prototype.triangle = function(x, y, r) {
  11453. // http://en.wikipedia.org/wiki/Equilateral_triangle
  11454. this.beginPath();
  11455. var s = r * 2;
  11456. var s2 = s / 2;
  11457. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  11458. var h = Math.sqrt(s * s - s2 * s2); // height
  11459. this.moveTo(x, y - (h - ir));
  11460. this.lineTo(x + s2, y + ir);
  11461. this.lineTo(x - s2, y + ir);
  11462. this.lineTo(x, y - (h - ir));
  11463. this.closePath();
  11464. };
  11465. /**
  11466. * Draw a triangle shape in downward orientation
  11467. * @param {Number} x horizontal center
  11468. * @param {Number} y vertical center
  11469. * @param {Number} r radius
  11470. */
  11471. CanvasRenderingContext2D.prototype.triangleDown = function(x, y, r) {
  11472. // http://en.wikipedia.org/wiki/Equilateral_triangle
  11473. this.beginPath();
  11474. var s = r * 2;
  11475. var s2 = s / 2;
  11476. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  11477. var h = Math.sqrt(s * s - s2 * s2); // height
  11478. this.moveTo(x, y + (h - ir));
  11479. this.lineTo(x + s2, y - ir);
  11480. this.lineTo(x - s2, y - ir);
  11481. this.lineTo(x, y + (h - ir));
  11482. this.closePath();
  11483. };
  11484. /**
  11485. * Draw a star shape, a star with 5 points
  11486. * @param {Number} x horizontal center
  11487. * @param {Number} y vertical center
  11488. * @param {Number} r radius, half the length of the sides of the triangle
  11489. */
  11490. CanvasRenderingContext2D.prototype.star = function(x, y, r) {
  11491. // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/
  11492. this.beginPath();
  11493. for (var n = 0; n < 10; n++) {
  11494. var radius = (n % 2 === 0) ? r * 1.3 : r * 0.5;
  11495. this.lineTo(
  11496. x + radius * Math.sin(n * 2 * Math.PI / 10),
  11497. y - radius * Math.cos(n * 2 * Math.PI / 10)
  11498. );
  11499. }
  11500. this.closePath();
  11501. };
  11502. /**
  11503. * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas
  11504. */
  11505. CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) {
  11506. var r2d = Math.PI/180;
  11507. if( w - ( 2 * r ) < 0 ) { r = ( w / 2 ); } //ensure that the radius isn't too large for x
  11508. if( h - ( 2 * r ) < 0 ) { r = ( h / 2 ); } //ensure that the radius isn't too large for y
  11509. this.beginPath();
  11510. this.moveTo(x+r,y);
  11511. this.lineTo(x+w-r,y);
  11512. this.arc(x+w-r,y+r,r,r2d*270,r2d*360,false);
  11513. this.lineTo(x+w,y+h-r);
  11514. this.arc(x+w-r,y+h-r,r,0,r2d*90,false);
  11515. this.lineTo(x+r,y+h);
  11516. this.arc(x+r,y+h-r,r,r2d*90,r2d*180,false);
  11517. this.lineTo(x,y+r);
  11518. this.arc(x+r,y+r,r,r2d*180,r2d*270,false);
  11519. };
  11520. /**
  11521. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  11522. */
  11523. CanvasRenderingContext2D.prototype.ellipse = function(x, y, w, h) {
  11524. var kappa = .5522848,
  11525. ox = (w / 2) * kappa, // control point offset horizontal
  11526. oy = (h / 2) * kappa, // control point offset vertical
  11527. xe = x + w, // x-end
  11528. ye = y + h, // y-end
  11529. xm = x + w / 2, // x-middle
  11530. ym = y + h / 2; // y-middle
  11531. this.beginPath();
  11532. this.moveTo(x, ym);
  11533. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  11534. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  11535. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  11536. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  11537. };
  11538. /**
  11539. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  11540. */
  11541. CanvasRenderingContext2D.prototype.database = function(x, y, w, h) {
  11542. var f = 1/3;
  11543. var wEllipse = w;
  11544. var hEllipse = h * f;
  11545. var kappa = .5522848,
  11546. ox = (wEllipse / 2) * kappa, // control point offset horizontal
  11547. oy = (hEllipse / 2) * kappa, // control point offset vertical
  11548. xe = x + wEllipse, // x-end
  11549. ye = y + hEllipse, // y-end
  11550. xm = x + wEllipse / 2, // x-middle
  11551. ym = y + hEllipse / 2, // y-middle
  11552. ymb = y + (h - hEllipse/2), // y-midlle, bottom ellipse
  11553. yeb = y + h; // y-end, bottom ellipse
  11554. this.beginPath();
  11555. this.moveTo(xe, ym);
  11556. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  11557. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  11558. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  11559. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  11560. this.lineTo(xe, ymb);
  11561. this.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb);
  11562. this.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb);
  11563. this.lineTo(x, ym);
  11564. };
  11565. /**
  11566. * Draw an arrow point (no line)
  11567. */
  11568. CanvasRenderingContext2D.prototype.arrow = function(x, y, angle, length) {
  11569. // tail
  11570. var xt = x - length * Math.cos(angle);
  11571. var yt = y - length * Math.sin(angle);
  11572. // inner tail
  11573. // TODO: allow to customize different shapes
  11574. var xi = x - length * 0.9 * Math.cos(angle);
  11575. var yi = y - length * 0.9 * Math.sin(angle);
  11576. // left
  11577. var xl = xt + length / 3 * Math.cos(angle + 0.5 * Math.PI);
  11578. var yl = yt + length / 3 * Math.sin(angle + 0.5 * Math.PI);
  11579. // right
  11580. var xr = xt + length / 3 * Math.cos(angle - 0.5 * Math.PI);
  11581. var yr = yt + length / 3 * Math.sin(angle - 0.5 * Math.PI);
  11582. this.beginPath();
  11583. this.moveTo(x, y);
  11584. this.lineTo(xl, yl);
  11585. this.lineTo(xi, yi);
  11586. this.lineTo(xr, yr);
  11587. this.closePath();
  11588. };
  11589. /**
  11590. * Sets up the dashedLine functionality for drawing
  11591. * Original code came from http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
  11592. * @author David Jordan
  11593. * @date 2012-08-08
  11594. */
  11595. CanvasRenderingContext2D.prototype.dashedLine = function(x,y,x2,y2,dashArray){
  11596. if (!dashArray) dashArray=[10,5];
  11597. if (dashLength==0) dashLength = 0.001; // Hack for Safari
  11598. var dashCount = dashArray.length;
  11599. this.moveTo(x, y);
  11600. var dx = (x2-x), dy = (y2-y);
  11601. var slope = dy/dx;
  11602. var distRemaining = Math.sqrt( dx*dx + dy*dy );
  11603. var dashIndex=0, draw=true;
  11604. while (distRemaining>=0.1){
  11605. var dashLength = dashArray[dashIndex++%dashCount];
  11606. if (dashLength > distRemaining) dashLength = distRemaining;
  11607. var xStep = Math.sqrt( dashLength*dashLength / (1 + slope*slope) );
  11608. if (dx<0) xStep = -xStep;
  11609. x += xStep;
  11610. y += slope*xStep;
  11611. this[draw ? 'lineTo' : 'moveTo'](x,y);
  11612. distRemaining -= dashLength;
  11613. draw = !draw;
  11614. }
  11615. };
  11616. // TODO: add diamond shape
  11617. }
  11618. /**
  11619. * @class Node
  11620. * A node. A node can be connected to other nodes via one or multiple edges.
  11621. * @param {object} properties An object containing properties for the node. All
  11622. * properties are optional, except for the id.
  11623. * {number} id Id of the node. Required
  11624. * {string} label Text label for the node
  11625. * {number} x Horizontal position of the node
  11626. * {number} y Vertical position of the node
  11627. * {string} shape Node shape, available:
  11628. * "database", "circle", "ellipse",
  11629. * "box", "image", "text", "dot",
  11630. * "star", "triangle", "triangleDown",
  11631. * "square"
  11632. * {string} image An image url
  11633. * {string} title An title text, can be HTML
  11634. * {anytype} group A group name or number
  11635. * @param {Graph.Images} imagelist A list with images. Only needed
  11636. * when the node has an image
  11637. * @param {Graph.Groups} grouplist A list with groups. Needed for
  11638. * retrieving group properties
  11639. * @param {Object} constants An object with default values for
  11640. * example for the color
  11641. */
  11642. function Node(properties, imagelist, grouplist, constants) {
  11643. this.selected = false;
  11644. this.edges = []; // all edges connected to this node
  11645. this.dynamicEdges = [];
  11646. this.reroutedEdges = {};
  11647. this.group = constants.nodes.group;
  11648. this.fontSize = constants.nodes.fontSize;
  11649. this.fontFace = constants.nodes.fontFace;
  11650. this.fontColor = constants.nodes.fontColor;
  11651. this.color = constants.nodes.color;
  11652. // set defaults for the properties
  11653. this.id = undefined;
  11654. this.shape = constants.nodes.shape;
  11655. this.image = constants.nodes.image;
  11656. this.x = 0;
  11657. this.y = 0;
  11658. this.xFixed = false;
  11659. this.yFixed = false;
  11660. this.radius = constants.nodes.radius;
  11661. this.radiusFixed = false;
  11662. this.radiusMin = constants.nodes.radiusMin;
  11663. this.radiusMax = constants.nodes.radiusMax;
  11664. this.imagelist = imagelist;
  11665. this.grouplist = grouplist;
  11666. this.setProperties(properties, constants);
  11667. // creating the variables for clustering
  11668. this.resetCluster();
  11669. this.dynamicEdgesLength = 0;
  11670. this.clusterSession = 0;
  11671. this.clusterSizeWidthFactor = constants.clustering.clusterSizeWidthFactor;
  11672. this.clusterSizeHeightFactor = constants.clustering.clusterSizeHeightFactor;
  11673. this.clusterSizeRadiusFactor = constants.clustering.clusterSizeRadiusFactor;
  11674. // mass, force, velocity
  11675. this.mass = 50; // kg (mass is adjusted for the number of connected edges)
  11676. this.fx = 0.0; // external force x
  11677. this.fy = 0.0; // external force y
  11678. this.vx = 0.0; // velocity x
  11679. this.vy = 0.0; // velocity y
  11680. this.minForce = constants.minForce;
  11681. this.damping = 0.9; // damping factor
  11682. }
  11683. /**
  11684. * (re)setting the clustering variables and objects
  11685. */
  11686. Node.prototype.resetCluster = function() {
  11687. // clustering variables
  11688. this.formationScale = undefined; // this is used to determine when to open the cluster
  11689. this.clusterSize = 1; // this signifies the total amount of nodes in this cluster
  11690. this.containedNodes = {};
  11691. this.containedEdges = {};
  11692. };
  11693. /**
  11694. * Attach a edge to the node
  11695. * @param {Edge} edge
  11696. */
  11697. Node.prototype.attachEdge = function(edge) {
  11698. if (this.edges.indexOf(edge) == -1) {
  11699. this.edges.push(edge);
  11700. }
  11701. this.dynamicEdges = this.edges;
  11702. this.dynamicEdgesLength = this.edges.length;
  11703. this._updateMass();
  11704. };
  11705. /**
  11706. * Detach a edge from the node
  11707. * @param {Edge} edge
  11708. */
  11709. Node.prototype.detachEdge = function(edge) {
  11710. var index = this.edges.indexOf(edge);
  11711. if (index != -1) {
  11712. this.edges.splice(index, 1);
  11713. }
  11714. this.dynamicEdges = this.edges;
  11715. this.dynamicEdgesLength = this.edges.length;
  11716. this._updateMass();
  11717. };
  11718. /**
  11719. * Update the nodes mass, which is determined by the number of edges connecting
  11720. * to it (more edges -> heavier node).
  11721. * @private
  11722. */
  11723. Node.prototype._updateMass = function() {
  11724. this.mass = 50 + 20 * this.edges.length; // kg
  11725. };
  11726. /**
  11727. * Set or overwrite properties for the node
  11728. * @param {Object} properties an object with properties
  11729. * @param {Object} constants and object with default, global properties
  11730. */
  11731. Node.prototype.setProperties = function(properties, constants) {
  11732. if (!properties) {
  11733. return;
  11734. }
  11735. // basic properties
  11736. if (properties.id != undefined) {this.id = properties.id;}
  11737. if (properties.label != undefined) {this.label = properties.label;}
  11738. if (properties.title != undefined) {this.title = properties.title;}
  11739. if (properties.group != undefined) {this.group = properties.group;}
  11740. if (properties.x != undefined) {this.x = properties.x;}
  11741. if (properties.y != undefined) {this.y = properties.y;}
  11742. if (properties.value != undefined) {this.value = properties.value;}
  11743. if (this.id === undefined) {
  11744. throw "Node must have an id";
  11745. }
  11746. // copy group properties
  11747. if (this.group) {
  11748. var groupObj = this.grouplist.get(this.group);
  11749. for (var prop in groupObj) {
  11750. if (groupObj.hasOwnProperty(prop)) {
  11751. this[prop] = groupObj[prop];
  11752. }
  11753. }
  11754. }
  11755. // individual shape properties
  11756. if (properties.shape != undefined) {this.shape = properties.shape;}
  11757. if (properties.image != undefined) {this.image = properties.image;}
  11758. if (properties.radius != undefined) {this.radius = properties.radius;}
  11759. if (properties.color != undefined) {this.color = Node.parseColor(properties.color);}
  11760. if (properties.fontColor != undefined) {this.fontColor = properties.fontColor;}
  11761. if (properties.fontSize != undefined) {this.fontSize = properties.fontSize;}
  11762. if (properties.fontFace != undefined) {this.fontFace = properties.fontFace;}
  11763. if (this.image != undefined) {
  11764. if (this.imagelist) {
  11765. this.imageObj = this.imagelist.load(this.image);
  11766. }
  11767. else {
  11768. throw "No imagelist provided";
  11769. }
  11770. }
  11771. this.xFixed = this.xFixed || (properties.x != undefined);
  11772. this.yFixed = this.yFixed || (properties.y != undefined);
  11773. this.radiusFixed = this.radiusFixed || (properties.radius != undefined);
  11774. if (this.shape == 'image') {
  11775. this.radiusMin = constants.nodes.widthMin;
  11776. this.radiusMax = constants.nodes.widthMax;
  11777. }
  11778. // choose draw method depending on the shape
  11779. switch (this.shape) {
  11780. case 'database': this.draw = this._drawDatabase; this.resize = this._resizeDatabase; break;
  11781. case 'box': this.draw = this._drawBox; this.resize = this._resizeBox; break;
  11782. case 'circle': this.draw = this._drawCircle; this.resize = this._resizeCircle; break;
  11783. case 'ellipse': this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  11784. // TODO: add diamond shape
  11785. case 'image': this.draw = this._drawImage; this.resize = this._resizeImage; break;
  11786. case 'text': this.draw = this._drawText; this.resize = this._resizeText; break;
  11787. case 'dot': this.draw = this._drawDot; this.resize = this._resizeShape; break;
  11788. case 'square': this.draw = this._drawSquare; this.resize = this._resizeShape; break;
  11789. case 'triangle': this.draw = this._drawTriangle; this.resize = this._resizeShape; break;
  11790. case 'triangleDown': this.draw = this._drawTriangleDown; this.resize = this._resizeShape; break;
  11791. case 'star': this.draw = this._drawStar; this.resize = this._resizeShape; break;
  11792. default: this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  11793. }
  11794. // reset the size of the node, this can be changed
  11795. this._reset();
  11796. };
  11797. /**
  11798. * Parse a color property into an object with border, background, and
  11799. * hightlight colors
  11800. * @param {Object | String} color
  11801. * @return {Object} colorObject
  11802. */
  11803. Node.parseColor = function(color) {
  11804. var c;
  11805. if (util.isString(color)) {
  11806. c = {
  11807. border: color,
  11808. background: color,
  11809. highlight: {
  11810. border: color,
  11811. background: color
  11812. },
  11813. cluster: {
  11814. border: color,
  11815. background: color,
  11816. highlight: {
  11817. border: color,
  11818. background: color
  11819. }
  11820. }
  11821. };
  11822. // TODO: automatically generate a nice highlight color
  11823. }
  11824. else {
  11825. c = {};
  11826. c.background = color.background || 'white';
  11827. c.border = color.border || c.background;
  11828. if (util.isString(color.highlight)) {
  11829. c.highlight = {
  11830. border: color.highlight,
  11831. background: color.highlight
  11832. }
  11833. }
  11834. else {
  11835. c.highlight = {};
  11836. c.highlight.background = color.highlight && color.highlight.background || c.background;
  11837. c.highlight.border = color.highlight && color.highlight.border || c.border;
  11838. }
  11839. // check if cluster colorgroup has been defined
  11840. if (util.isString(color.cluster)) {
  11841. c.cluster = {
  11842. border: color.cluster,
  11843. background: color.cluster
  11844. }
  11845. }
  11846. else {
  11847. c.cluster = {};
  11848. c.cluster.background = color.cluster && color.cluster.background || c.background;
  11849. c.cluster.border = color.cluster && color.cluster.border || c.border;
  11850. }
  11851. // check if cluster highlight colorgroup has been defined
  11852. if (util.isString(color.cluster.highlight)) {
  11853. c.cluster.highlight = {
  11854. border: color.cluster.highlight,
  11855. background: color.cluster.highlight
  11856. }
  11857. }
  11858. else {
  11859. c.cluster.highlight = {};
  11860. c.cluster.highlight.background = color.cluster.highlight && color.cluster.highlight.background || c.background;
  11861. c.cluster.highlight.border = color.cluster.highlight && color.cluster.highlight.border || c.border;
  11862. }
  11863. }
  11864. return c;
  11865. };
  11866. /**
  11867. * select this node
  11868. */
  11869. Node.prototype.select = function() {
  11870. this.selected = true;
  11871. this._reset();
  11872. };
  11873. /**
  11874. * unselect this node
  11875. */
  11876. Node.prototype.unselect = function() {
  11877. this.selected = false;
  11878. this._reset();
  11879. };
  11880. /**
  11881. * Reset the calculated size of the node, forces it to recalculate its size
  11882. */
  11883. Node.prototype.clearSizeCache = function() {
  11884. this._reset();
  11885. };
  11886. /**
  11887. * Reset the calculated size of the node, forces it to recalculate its size
  11888. * @private
  11889. */
  11890. Node.prototype._reset = function() {
  11891. this.width = undefined;
  11892. this.height = undefined;
  11893. };
  11894. /**
  11895. * get the title of this node.
  11896. * @return {string} title The title of the node, or undefined when no title
  11897. * has been set.
  11898. */
  11899. Node.prototype.getTitle = function() {
  11900. return this.title;
  11901. };
  11902. /**
  11903. * Calculate the distance to the border of the Node
  11904. * @param {CanvasRenderingContext2D} ctx
  11905. * @param {Number} angle Angle in radians
  11906. * @returns {number} distance Distance to the border in pixels
  11907. */
  11908. Node.prototype.distanceToBorder = function (ctx, angle) {
  11909. var borderWidth = 1;
  11910. if (!this.width) {
  11911. this.resize(ctx);
  11912. }
  11913. //noinspection FallthroughInSwitchStatementJS
  11914. switch (this.shape) {
  11915. case 'circle':
  11916. case 'dot':
  11917. return this.radius + borderWidth;
  11918. case 'ellipse':
  11919. var a = this.width / 2;
  11920. var b = this.height / 2;
  11921. var w = (Math.sin(angle) * a);
  11922. var h = (Math.cos(angle) * b);
  11923. return a * b / Math.sqrt(w * w + h * h);
  11924. // TODO: implement distanceToBorder for database
  11925. // TODO: implement distanceToBorder for triangle
  11926. // TODO: implement distanceToBorder for triangleDown
  11927. case 'box':
  11928. case 'image':
  11929. case 'text':
  11930. default:
  11931. if (this.width) {
  11932. return Math.min(
  11933. Math.abs(this.width / 2 / Math.cos(angle)),
  11934. Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth;
  11935. // TODO: reckon with border radius too in case of box
  11936. }
  11937. else {
  11938. return 0;
  11939. }
  11940. }
  11941. // TODO: implement calculation of distance to border for all shapes
  11942. };
  11943. /**
  11944. * Set forces acting on the node
  11945. * @param {number} fx Force in horizontal direction
  11946. * @param {number} fy Force in vertical direction
  11947. */
  11948. Node.prototype._setForce = function(fx, fy) {
  11949. this.fx = fx;
  11950. this.fy = fy;
  11951. };
  11952. /**
  11953. * Add forces acting on the node
  11954. * @param {number} fx Force in horizontal direction
  11955. * @param {number} fy Force in vertical direction
  11956. * @private
  11957. */
  11958. Node.prototype._addForce = function(fx, fy) {
  11959. this.fx += fx;
  11960. this.fy += fy;
  11961. };
  11962. /**
  11963. * Perform one discrete step for the node
  11964. * @param {number} interval Time interval in seconds
  11965. */
  11966. Node.prototype.discreteStep = function(interval) {
  11967. if (!this.xFixed) {
  11968. var dx = -this.damping * this.vx; // damping force
  11969. var ax = (this.fx + dx) / this.mass; // acceleration
  11970. this.vx += ax / interval; // velocity
  11971. this.x += this.vx / interval; // position
  11972. }
  11973. if (!this.yFixed) {
  11974. var dy = -this.damping * this.vy; // damping force
  11975. var ay = (this.fy + dy) / this.mass; // acceleration
  11976. this.vy += ay / interval; // velocity
  11977. this.y += this.vy / interval; // position
  11978. }
  11979. };
  11980. /**
  11981. * Check if this node has a fixed x and y position
  11982. * @return {boolean} true if fixed, false if not
  11983. */
  11984. Node.prototype.isFixed = function() {
  11985. return (this.xFixed && this.yFixed);
  11986. };
  11987. /**
  11988. * Check if this node is moving
  11989. * @param {number} vmin the minimum velocity considered as "moving"
  11990. * @return {boolean} true if moving, false if it has no velocity
  11991. */
  11992. // TODO: replace this method with calculating the kinetic energy
  11993. Node.prototype.isMoving = function(vmin) {
  11994. return (Math.abs(this.vx) > vmin || Math.abs(this.vy) > vmin ||
  11995. (!this.xFixed && Math.abs(this.fx) > this.minForce) ||
  11996. (!this.yFixed && Math.abs(this.fy) > this.minForce));
  11997. };
  11998. /**
  11999. * check if this node is selecte
  12000. * @return {boolean} selected True if node is selected, else false
  12001. */
  12002. Node.prototype.isSelected = function() {
  12003. return this.selected;
  12004. };
  12005. /**
  12006. * Retrieve the value of the node. Can be undefined
  12007. * @return {Number} value
  12008. */
  12009. Node.prototype.getValue = function() {
  12010. return this.value;
  12011. };
  12012. /**
  12013. * Calculate the distance from the nodes location to the given location (x,y)
  12014. * @param {Number} x
  12015. * @param {Number} y
  12016. * @return {Number} value
  12017. */
  12018. Node.prototype.getDistance = function(x, y) {
  12019. var dx = this.x - x,
  12020. dy = this.y - y;
  12021. return Math.sqrt(dx * dx + dy * dy);
  12022. };
  12023. /**
  12024. * Adjust the value range of the node. The node will adjust it's radius
  12025. * based on its value.
  12026. * @param {Number} min
  12027. * @param {Number} max
  12028. */
  12029. Node.prototype.setValueRange = function(min, max) {
  12030. if (!this.radiusFixed && this.value !== undefined) {
  12031. if (max == min) {
  12032. this.radius = (this.radiusMin + this.radiusMax) / 2;
  12033. }
  12034. else {
  12035. var scale = (this.radiusMax - this.radiusMin) / (max - min);
  12036. this.radius = (this.value - min) * scale + this.radiusMin;
  12037. }
  12038. }
  12039. };
  12040. /**
  12041. * Draw this node in the given canvas
  12042. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  12043. * @param {CanvasRenderingContext2D} ctx
  12044. */
  12045. Node.prototype.draw = function(ctx) {
  12046. throw "Draw method not initialized for node";
  12047. };
  12048. /**
  12049. * Recalculate the size of this node in the given canvas
  12050. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  12051. * @param {CanvasRenderingContext2D} ctx
  12052. */
  12053. Node.prototype.resize = function(ctx) {
  12054. throw "Resize method not initialized for node";
  12055. };
  12056. /**
  12057. * Check if this object is overlapping with the provided object
  12058. * @param {Object} obj an object with parameters left, top, right, bottom
  12059. * @return {boolean} True if location is located on node
  12060. */
  12061. Node.prototype.isOverlappingWith = function(obj) {
  12062. return (this.left < obj.right &&
  12063. this.left + this.width > obj.left &&
  12064. this.top < obj.bottom &&
  12065. this.top + this.height > obj.top);
  12066. };
  12067. Node.prototype._resizeImage = function (ctx) {
  12068. // TODO: pre calculate the image size
  12069. if (!this.width) { // undefined or 0
  12070. var width, height;
  12071. if (this.value) {
  12072. var scale = this.imageObj.height / this.imageObj.width;
  12073. width = this.radius || this.imageObj.width;
  12074. height = this.radius * scale || this.imageObj.height;
  12075. }
  12076. else {
  12077. width = this.imageObj.width;
  12078. height = this.imageObj.height;
  12079. }
  12080. this.width = width;
  12081. this.height = height;
  12082. this.width += this.clusterSize * this.clusterSizeWidthFactor;
  12083. this.height += this.clusterSize * this.clusterSizeHeightFactor;
  12084. this.radius += this.clusterSize * this.clusterSizeRadiusFactor;
  12085. }
  12086. };
  12087. Node.prototype._drawImage = function (ctx) {
  12088. this._resizeImage(ctx);
  12089. this.left = this.x - this.width / 2;
  12090. this.top = this.y - this.height / 2;
  12091. var yLabel;
  12092. if (this.imageObj) {
  12093. ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height);
  12094. yLabel = this.y + this.height / 2;
  12095. }
  12096. else {
  12097. // image still loading... just draw the label for now
  12098. yLabel = this.y;
  12099. }
  12100. this._label(ctx, this.label, this.x, yLabel, undefined, "top");
  12101. };
  12102. Node.prototype._resizeBox = function (ctx) {
  12103. if (!this.width) {
  12104. var margin = 5;
  12105. var textSize = this.getTextSize(ctx);
  12106. this.width = textSize.width + 2 * margin;
  12107. this.height = textSize.height + 2 * margin;
  12108. this.width += this.clusterSize * this.clusterSizeWidthFactor;
  12109. this.height += this.clusterSize * this.clusterSizeHeightFactor;
  12110. this.radius += this.clusterSize * this.clusterSizeRadiusFactor;
  12111. }
  12112. };
  12113. Node.prototype._drawBox = function (ctx) {
  12114. this._resizeBox(ctx);
  12115. this.left = this.x - this.width / 2;
  12116. this.top = this.y - this.height / 2;
  12117. if (this.clusterSize > 1) {
  12118. ctx.strokeStyle = this.selected ? this.color.cluster.highlight.border : this.color.cluster.border;
  12119. ctx.fillStyle = this.selected ? this.color.cluster.highlight.background : this.color.cluster.background;
  12120. }
  12121. else {
  12122. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  12123. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  12124. }
  12125. ctx.lineWidth = (this.selected ? 2.0 : 1.0) + (this.clusterSize > 1) ? 2.0 : 0.0;
  12126. ctx.roundRect(this.left, this.top, this.width, this.height, this.radius);
  12127. ctx.fill();
  12128. ctx.stroke();
  12129. this._label(ctx, this.label, this.x, this.y);
  12130. };
  12131. Node.prototype._resizeDatabase = function (ctx) {
  12132. if (!this.width) {
  12133. var margin = 5;
  12134. var textSize = this.getTextSize(ctx);
  12135. var size = textSize.width + 2 * margin;
  12136. this.width = size;
  12137. this.height = size;
  12138. // scaling used for clustering
  12139. this.width += this.clusterSize * this.clusterSizeWidthFactor;
  12140. this.height += this.clusterSize * this.clusterSizeHeightFactor;
  12141. this.radius += this.clusterSize * this.clusterSizeRadiusFactor;
  12142. }
  12143. };
  12144. Node.prototype._drawDatabase = function (ctx) {
  12145. this._resizeDatabase(ctx);
  12146. this.left = this.x - this.width / 2;
  12147. this.top = this.y - this.height / 2;
  12148. if (this.clusterSize > 1) {
  12149. ctx.strokeStyle = this.selected ? this.color.cluster.highlight.border : this.color.cluster.border;
  12150. ctx.fillStyle = this.selected ? this.color.cluster.highlight.background : this.color.cluster.background;
  12151. }
  12152. else {
  12153. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  12154. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  12155. }
  12156. ctx.lineWidth = (this.selected ? 2.0 : 1.0) + (this.clusterSize > 1) ? 2.0 : 0.0;
  12157. ctx.database(this.x - this.width/2, this.y - this.height*0.5, this.width, this.height);
  12158. ctx.fill();
  12159. ctx.stroke();
  12160. this._label(ctx, this.label, this.x, this.y);
  12161. };
  12162. Node.prototype._resizeCircle = function (ctx) {
  12163. if (!this.width) {
  12164. var margin = 5;
  12165. var textSize = this.getTextSize(ctx);
  12166. var diameter = Math.max(textSize.width, textSize.height) + 2 * margin;
  12167. this.radius = diameter / 2;
  12168. this.width = diameter;
  12169. this.height = diameter;
  12170. // scaling used for clustering
  12171. this.width += this.clusterSize * this.clusterSizeWidthFactor;
  12172. this.height += this.clusterSize * this.clusterSizeHeightFactor;
  12173. this.radius += this.clusterSize * this.clusterSizeRadiusFactor;
  12174. }
  12175. };
  12176. Node.prototype._drawCircle = function (ctx) {
  12177. this._resizeCircle(ctx);
  12178. this.left = this.x - this.width / 2;
  12179. this.top = this.y - this.height / 2;
  12180. if (this.clusterSize > 1) {
  12181. ctx.strokeStyle = this.selected ? this.color.cluster.highlight.border : this.color.cluster.border;
  12182. ctx.fillStyle = this.selected ? this.color.cluster.highlight.background : this.color.cluster.background;
  12183. }
  12184. else {
  12185. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  12186. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  12187. }
  12188. ctx.lineWidth = (this.selected ? 2.0 : 1.0) + (this.clusterSize > 1) ? 2.0 : 0.0;
  12189. ctx.circle(this.x, this.y, this.radius);
  12190. ctx.fill();
  12191. ctx.stroke();
  12192. this._label(ctx, this.label, this.x, this.y);
  12193. };
  12194. Node.prototype._resizeEllipse = function (ctx) {
  12195. if (!this.width) {
  12196. var textSize = this.getTextSize(ctx);
  12197. this.width = textSize.width * 1.5;
  12198. this.height = textSize.height * 2;
  12199. if (this.width < this.height) {
  12200. this.width = this.height;
  12201. }
  12202. // scaling used for clustering
  12203. this.width += this.clusterSize * this.clusterSizeWidthFactor;
  12204. this.height += this.clusterSize * this.clusterSizeHeightFactor;
  12205. this.radius += this.clusterSize * this.clusterSizeRadiusFactor;
  12206. }
  12207. };
  12208. Node.prototype._drawEllipse = function (ctx) {
  12209. this._resizeEllipse(ctx);
  12210. this.left = this.x - this.width / 2;
  12211. this.top = this.y - this.height / 2;
  12212. if (this.clusterSize > 1) {
  12213. ctx.strokeStyle = this.selected ? this.color.cluster.highlight.border : this.color.cluster.border;
  12214. ctx.fillStyle = this.selected ? this.color.cluster.highlight.background : this.color.cluster.background;
  12215. }
  12216. else {
  12217. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  12218. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  12219. }
  12220. ctx.lineWidth = (this.selected ? 2.0 : 1.0) + (this.clusterSize > 1) ? 2.0 : 0.0;
  12221. ctx.ellipse(this.left, this.top, this.width, this.height);
  12222. ctx.fill();
  12223. ctx.stroke();
  12224. this._label(ctx, this.label, this.x, this.y);
  12225. };
  12226. Node.prototype._drawDot = function (ctx) {
  12227. this._drawShape(ctx, 'circle');
  12228. };
  12229. Node.prototype._drawTriangle = function (ctx) {
  12230. this._drawShape(ctx, 'triangle');
  12231. };
  12232. Node.prototype._drawTriangleDown = function (ctx) {
  12233. this._drawShape(ctx, 'triangleDown');
  12234. };
  12235. Node.prototype._drawSquare = function (ctx) {
  12236. this._drawShape(ctx, 'square');
  12237. };
  12238. Node.prototype._drawStar = function (ctx) {
  12239. this._drawShape(ctx, 'star');
  12240. };
  12241. Node.prototype._resizeShape = function (ctx) {
  12242. if (!this.width) {
  12243. var size = 2 * this.radius;
  12244. this.width = size;
  12245. this.height = size;
  12246. // scaling used for clustering
  12247. this.width += this.clusterSize * this.clusterSizeWidthFactor;
  12248. this.height += this.clusterSize * this.clusterSizeHeightFactor;
  12249. this.radius += this.clusterSize * this.clusterSizeRadiusFactor;
  12250. }
  12251. };
  12252. Node.prototype._drawShape = function (ctx, shape) {
  12253. this._resizeShape(ctx);
  12254. this.left = this.x - this.width / 2;
  12255. this.top = this.y - this.height / 2;
  12256. if (this.clusterSize > 1) {
  12257. ctx.strokeStyle = this.selected ? this.color.cluster.highlight.border : this.color.cluster.border;
  12258. ctx.fillStyle = this.selected ? this.color.cluster.highlight.background : this.color.cluster.background;
  12259. }
  12260. else {
  12261. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  12262. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  12263. }
  12264. ctx.lineWidth = (this.selected ? 2.0 : 1.0) + (this.clusterSize > 1) ? 2.0 : 0.0;
  12265. ctx[shape](this.x, this.y, this.radius);
  12266. ctx.fill();
  12267. ctx.stroke();
  12268. if (this.label) {
  12269. this._label(ctx, this.label, this.x, this.y + this.height / 2, undefined, 'top');
  12270. }
  12271. };
  12272. Node.prototype._resizeText = function (ctx) {
  12273. if (!this.width) {
  12274. var margin = 5;
  12275. var textSize = this.getTextSize(ctx);
  12276. this.width = textSize.width + 2 * margin;
  12277. this.height = textSize.height + 2 * margin;
  12278. // scaling used for clustering
  12279. this.width += this.clusterSize * this.clusterSizeWidthFactor;
  12280. this.height += this.clusterSize * this.clusterSizeHeightFactor;
  12281. this.radius += this.clusterSize * this.clusterSizeRadiusFactor;
  12282. }
  12283. };
  12284. Node.prototype._drawText = function (ctx) {
  12285. this._resizeText(ctx);
  12286. this.left = this.x - this.width / 2;
  12287. this.top = this.y - this.height / 2;
  12288. this._label(ctx, this.label, this.x, this.y);
  12289. };
  12290. Node.prototype._label = function (ctx, text, x, y, align, baseline) {
  12291. if (text) {
  12292. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  12293. ctx.fillStyle = this.fontColor || "black";
  12294. ctx.textAlign = align || "center";
  12295. ctx.textBaseline = baseline || "middle";
  12296. var lines = text.split('\n'),
  12297. lineCount = lines.length,
  12298. fontSize = (this.fontSize + 4),
  12299. yLine = y + (1 - lineCount) / 2 * fontSize;
  12300. for (var i = 0; i < lineCount; i++) {
  12301. ctx.fillText(lines[i], x, yLine);
  12302. yLine += fontSize;
  12303. }
  12304. }
  12305. };
  12306. Node.prototype.getTextSize = function(ctx) {
  12307. if (this.label != undefined) {
  12308. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  12309. var lines = this.label.split('\n'),
  12310. height = (this.fontSize + 4) * lines.length,
  12311. width = 0;
  12312. for (var i = 0, iMax = lines.length; i < iMax; i++) {
  12313. width = Math.max(width, ctx.measureText(lines[i]).width);
  12314. }
  12315. return {"width": width, "height": height};
  12316. }
  12317. else {
  12318. return {"width": 0, "height": 0};
  12319. }
  12320. };
  12321. /**
  12322. * @class Edge
  12323. *
  12324. * A edge connects two nodes
  12325. * @param {Object} properties Object with properties. Must contain
  12326. * At least properties from and to.
  12327. * Available properties: from (number),
  12328. * to (number), label (string, color (string),
  12329. * width (number), style (string),
  12330. * length (number), title (string)
  12331. * @param {Graph} graph A graph object, used to find and edge to
  12332. * nodes.
  12333. * @param {Object} constants An object with default values for
  12334. * example for the color
  12335. */
  12336. function Edge (properties, graph, constants) {
  12337. if (!graph) {
  12338. throw "No graph provided";
  12339. }
  12340. this.graph = graph;
  12341. // initialize constants
  12342. this.widthMin = constants.edges.widthMin;
  12343. this.widthMax = constants.edges.widthMax;
  12344. // initialize variables
  12345. this.id = undefined;
  12346. this.fromId = undefined;
  12347. this.toId = undefined;
  12348. this.style = constants.edges.style;
  12349. this.title = undefined;
  12350. this.width = constants.edges.width;
  12351. this.value = undefined;
  12352. this.length = constants.edges.length;
  12353. this.from = null; // a node
  12354. this.to = null; // a node
  12355. // we use this to be able to reconnect the edge to a cluster if its node is put into a cluster
  12356. // by storing the original information we can revert to the original connection when the cluser is opened.
  12357. this.originalFromID = [];
  12358. this.originalToID = [];
  12359. this.connected = false;
  12360. // Added to support dashed lines
  12361. // David Jordan
  12362. // 2012-08-08
  12363. this.dash = util.extend({}, constants.edges.dash); // contains properties length, gap, altLength
  12364. this.stiffness = undefined; // depends on the length of the edge
  12365. this.color = constants.edges.color;
  12366. this.widthFixed = false;
  12367. this.lengthFixed = false;
  12368. this.setProperties(properties, constants);
  12369. };
  12370. /**
  12371. * Set or overwrite properties for the edge
  12372. * @param {Object} properties an object with properties
  12373. * @param {Object} constants and object with default, global properties
  12374. */
  12375. Edge.prototype.setProperties = function(properties, constants) {
  12376. if (!properties) {
  12377. return;
  12378. }
  12379. if (properties.from != undefined) {this.fromId = properties.from;}
  12380. if (properties.to != undefined) {this.toId = properties.to;}
  12381. if (properties.id != undefined) {this.id = properties.id;}
  12382. if (properties.style != undefined) {this.style = properties.style;}
  12383. if (properties.label != undefined) {this.label = properties.label;}
  12384. if (this.label) {
  12385. this.fontSize = constants.edges.fontSize;
  12386. this.fontFace = constants.edges.fontFace;
  12387. this.fontColor = constants.edges.fontColor;
  12388. if (properties.fontColor != undefined) {this.fontColor = properties.fontColor;}
  12389. if (properties.fontSize != undefined) {this.fontSize = properties.fontSize;}
  12390. if (properties.fontFace != undefined) {this.fontFace = properties.fontFace;}
  12391. }
  12392. if (properties.title != undefined) {this.title = properties.title;}
  12393. if (properties.width != undefined) {this.width = properties.width;}
  12394. if (properties.value != undefined) {this.value = properties.value;}
  12395. if (properties.length != undefined) {this.length = properties.length;}
  12396. // Added to support dashed lines
  12397. // David Jordan
  12398. // 2012-08-08
  12399. if (properties.dash) {
  12400. if (properties.dash.length != undefined) {this.dash.length = properties.dash.length;}
  12401. if (properties.dash.gap != undefined) {this.dash.gap = properties.dash.gap;}
  12402. if (properties.dash.altLength != undefined) {this.dash.altLength = properties.dash.altLength;}
  12403. }
  12404. if (properties.color != undefined) {this.color = properties.color;}
  12405. // A node is connected when it has a from and to node.
  12406. this.connect();
  12407. this.widthFixed = this.widthFixed || (properties.width != undefined);
  12408. this.lengthFixed = this.lengthFixed || (properties.length != undefined);
  12409. this.stiffness = 1 / this.length;
  12410. // set draw method based on style
  12411. switch (this.style) {
  12412. case 'line': this.draw = this._drawLine; break;
  12413. case 'arrow': this.draw = this._drawArrow; break;
  12414. case 'arrow-center': this.draw = this._drawArrowCenter; break;
  12415. case 'dash-line': this.draw = this._drawDashLine; break;
  12416. default: this.draw = this._drawLine; break;
  12417. }
  12418. };
  12419. /**
  12420. * Connect an edge to its nodes
  12421. */
  12422. Edge.prototype.connect = function () {
  12423. this.disconnect();
  12424. this.from = this.graph.nodes[this.fromId] || null;
  12425. this.to = this.graph.nodes[this.toId] || null;
  12426. this.connected = (this.from && this.to);
  12427. if (this.connected) {
  12428. this.from.attachEdge(this);
  12429. this.to.attachEdge(this);
  12430. }
  12431. else {
  12432. if (this.from) {
  12433. this.from.detachEdge(this);
  12434. }
  12435. if (this.to) {
  12436. this.to.detachEdge(this);
  12437. }
  12438. }
  12439. };
  12440. /**
  12441. * Disconnect an edge from its nodes
  12442. */
  12443. Edge.prototype.disconnect = function () {
  12444. if (this.from) {
  12445. this.from.detachEdge(this);
  12446. this.from = null;
  12447. }
  12448. if (this.to) {
  12449. this.to.detachEdge(this);
  12450. this.to = null;
  12451. }
  12452. this.connected = false;
  12453. };
  12454. /**
  12455. * get the title of this edge.
  12456. * @return {string} title The title of the edge, or undefined when no title
  12457. * has been set.
  12458. */
  12459. Edge.prototype.getTitle = function() {
  12460. return this.title;
  12461. };
  12462. /**
  12463. * Retrieve the value of the edge. Can be undefined
  12464. * @return {Number} value
  12465. */
  12466. Edge.prototype.getValue = function() {
  12467. return this.value;
  12468. };
  12469. /**
  12470. * Adjust the value range of the edge. The edge will adjust it's width
  12471. * based on its value.
  12472. * @param {Number} min
  12473. * @param {Number} max
  12474. */
  12475. Edge.prototype.setValueRange = function(min, max) {
  12476. if (!this.widthFixed && this.value !== undefined) {
  12477. var scale = (this.widthMax - this.widthMin) / (max - min);
  12478. this.width = (this.value - min) * scale + this.widthMin;
  12479. }
  12480. };
  12481. /**
  12482. * Redraw a edge
  12483. * Draw this edge in the given canvas
  12484. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  12485. * @param {CanvasRenderingContext2D} ctx
  12486. */
  12487. Edge.prototype.draw = function(ctx) {
  12488. throw "Method draw not initialized in edge";
  12489. };
  12490. /**
  12491. * Check if this object is overlapping with the provided object
  12492. * @param {Object} obj an object with parameters left, top
  12493. * @return {boolean} True if location is located on the edge
  12494. */
  12495. Edge.prototype.isOverlappingWith = function(obj) {
  12496. var distMax = 10;
  12497. var xFrom = this.from.x;
  12498. var yFrom = this.from.y;
  12499. var xTo = this.to.x;
  12500. var yTo = this.to.y;
  12501. var xObj = obj.left;
  12502. var yObj = obj.top;
  12503. var dist = Edge._dist(xFrom, yFrom, xTo, yTo, xObj, yObj);
  12504. return (dist < distMax);
  12505. };
  12506. /**
  12507. * Redraw a edge as a line
  12508. * Draw this edge in the given canvas
  12509. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  12510. * @param {CanvasRenderingContext2D} ctx
  12511. * @private
  12512. */
  12513. Edge.prototype._drawLine = function(ctx) {
  12514. // set style
  12515. ctx.strokeStyle = this.color;
  12516. ctx.lineWidth = this._getLineWidth();
  12517. var point;
  12518. if (this.from != this.to) {
  12519. // draw line
  12520. this._line(ctx);
  12521. // draw label
  12522. if (this.label) {
  12523. point = this._pointOnLine(0.5);
  12524. this._label(ctx, this.label, point.x, point.y);
  12525. }
  12526. }
  12527. else {
  12528. var x, y;
  12529. var radius = this.length / 4;
  12530. var node = this.from;
  12531. if (!node.width) {
  12532. node.resize(ctx);
  12533. }
  12534. if (node.width > node.height) {
  12535. x = node.x + node.width / 2;
  12536. y = node.y - radius;
  12537. }
  12538. else {
  12539. x = node.x + radius;
  12540. y = node.y - node.height / 2;
  12541. }
  12542. this._circle(ctx, x, y, radius);
  12543. point = this._pointOnCircle(x, y, radius, 0.5);
  12544. this._label(ctx, this.label, point.x, point.y);
  12545. }
  12546. };
  12547. /**
  12548. * Get the line width of the edge. Depends on width and whether one of the
  12549. * connected nodes is selected.
  12550. * @return {Number} width
  12551. * @private
  12552. */
  12553. Edge.prototype._getLineWidth = function() {
  12554. if (this.from.selected || this.to.selected) {
  12555. return Math.min(this.width * 2, this.widthMax);
  12556. }
  12557. else {
  12558. return this.width;
  12559. }
  12560. };
  12561. /**
  12562. * Draw a line between two nodes
  12563. * @param {CanvasRenderingContext2D} ctx
  12564. * @private
  12565. */
  12566. Edge.prototype._line = function (ctx) {
  12567. // draw a straight line
  12568. ctx.beginPath();
  12569. ctx.moveTo(this.from.x, this.from.y);
  12570. ctx.lineTo(this.to.x, this.to.y);
  12571. ctx.stroke();
  12572. };
  12573. /**
  12574. * Draw a line from a node to itself, a circle
  12575. * @param {CanvasRenderingContext2D} ctx
  12576. * @param {Number} x
  12577. * @param {Number} y
  12578. * @param {Number} radius
  12579. * @private
  12580. */
  12581. Edge.prototype._circle = function (ctx, x, y, radius) {
  12582. // draw a circle
  12583. ctx.beginPath();
  12584. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  12585. ctx.stroke();
  12586. };
  12587. /**
  12588. * Draw label with white background and with the middle at (x, y)
  12589. * @param {CanvasRenderingContext2D} ctx
  12590. * @param {String} text
  12591. * @param {Number} x
  12592. * @param {Number} y
  12593. * @private
  12594. */
  12595. Edge.prototype._label = function (ctx, text, x, y) {
  12596. if (text) {
  12597. // TODO: cache the calculated size
  12598. ctx.font = ((this.from.selected || this.to.selected) ? "bold " : "") +
  12599. this.fontSize + "px " + this.fontFace;
  12600. ctx.fillStyle = 'white';
  12601. var width = ctx.measureText(text).width;
  12602. var height = this.fontSize;
  12603. var left = x - width / 2;
  12604. var top = y - height / 2;
  12605. ctx.fillRect(left, top, width, height);
  12606. // draw text
  12607. ctx.fillStyle = this.fontColor || "black";
  12608. ctx.textAlign = "left";
  12609. ctx.textBaseline = "top";
  12610. ctx.fillText(text, left, top);
  12611. }
  12612. };
  12613. /**
  12614. * Redraw a edge as a dashed line
  12615. * Draw this edge in the given canvas
  12616. * @author David Jordan
  12617. * @date 2012-08-08
  12618. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  12619. * @param {CanvasRenderingContext2D} ctx
  12620. * @private
  12621. */
  12622. Edge.prototype._drawDashLine = function(ctx) {
  12623. // set style
  12624. ctx.strokeStyle = this.color;
  12625. ctx.lineWidth = this._getLineWidth();
  12626. // draw dashed line
  12627. ctx.beginPath();
  12628. ctx.lineCap = 'round';
  12629. if (this.dash.altLength != undefined) //If an alt dash value has been set add to the array this value
  12630. {
  12631. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  12632. [this.dash.length,this.dash.gap,this.dash.altLength,this.dash.gap]);
  12633. }
  12634. 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
  12635. {
  12636. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  12637. [this.dash.length,this.dash.gap]);
  12638. }
  12639. else //If all else fails draw a line
  12640. {
  12641. ctx.moveTo(this.from.x, this.from.y);
  12642. ctx.lineTo(this.to.x, this.to.y);
  12643. }
  12644. ctx.stroke();
  12645. // draw label
  12646. if (this.label) {
  12647. var point = this._pointOnLine(0.5);
  12648. this._label(ctx, this.label, point.x, point.y);
  12649. }
  12650. };
  12651. /**
  12652. * Get a point on a line
  12653. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  12654. * @return {Object} point
  12655. * @private
  12656. */
  12657. Edge.prototype._pointOnLine = function (percentage) {
  12658. return {
  12659. x: (1 - percentage) * this.from.x + percentage * this.to.x,
  12660. y: (1 - percentage) * this.from.y + percentage * this.to.y
  12661. }
  12662. };
  12663. /**
  12664. * Get a point on a circle
  12665. * @param {Number} x
  12666. * @param {Number} y
  12667. * @param {Number} radius
  12668. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  12669. * @return {Object} point
  12670. * @private
  12671. */
  12672. Edge.prototype._pointOnCircle = function (x, y, radius, percentage) {
  12673. var angle = (percentage - 3/8) * 2 * Math.PI;
  12674. return {
  12675. x: x + radius * Math.cos(angle),
  12676. y: y - radius * Math.sin(angle)
  12677. }
  12678. };
  12679. /**
  12680. * Redraw a edge as a line with an arrow halfway the line
  12681. * Draw this edge in the given canvas
  12682. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  12683. * @param {CanvasRenderingContext2D} ctx
  12684. * @private
  12685. */
  12686. Edge.prototype._drawArrowCenter = function(ctx) {
  12687. var point;
  12688. // set style
  12689. ctx.strokeStyle = this.color;
  12690. ctx.fillStyle = this.color;
  12691. ctx.lineWidth = this._getLineWidth();
  12692. if (this.from != this.to) {
  12693. // draw line
  12694. this._line(ctx);
  12695. // draw an arrow halfway the line
  12696. var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  12697. var length = 10 + 5 * this.width; // TODO: make customizable?
  12698. point = this._pointOnLine(0.5);
  12699. ctx.arrow(point.x, point.y, angle, length);
  12700. ctx.fill();
  12701. ctx.stroke();
  12702. // draw label
  12703. if (this.label) {
  12704. point = this._pointOnLine(0.5);
  12705. this._label(ctx, this.label, point.x, point.y);
  12706. }
  12707. }
  12708. else {
  12709. // draw circle
  12710. var x, y;
  12711. var radius = this.length / 4;
  12712. var node = this.from;
  12713. if (!node.width) {
  12714. node.resize(ctx);
  12715. }
  12716. if (node.width > node.height) {
  12717. x = node.x + node.width / 2;
  12718. y = node.y - radius;
  12719. }
  12720. else {
  12721. x = node.x + radius;
  12722. y = node.y - node.height / 2;
  12723. }
  12724. this._circle(ctx, x, y, radius);
  12725. // draw all arrows
  12726. var angle = 0.2 * Math.PI;
  12727. var length = 10 + 5 * this.width; // TODO: make customizable?
  12728. point = this._pointOnCircle(x, y, radius, 0.5);
  12729. ctx.arrow(point.x, point.y, angle, length);
  12730. ctx.fill();
  12731. ctx.stroke();
  12732. // draw label
  12733. if (this.label) {
  12734. point = this._pointOnCircle(x, y, radius, 0.5);
  12735. this._label(ctx, this.label, point.x, point.y);
  12736. }
  12737. }
  12738. };
  12739. /**
  12740. * Redraw a edge as a line with an arrow
  12741. * Draw this edge in the given canvas
  12742. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  12743. * @param {CanvasRenderingContext2D} ctx
  12744. * @private
  12745. */
  12746. Edge.prototype._drawArrow = function(ctx) {
  12747. // set style
  12748. ctx.strokeStyle = this.color;
  12749. ctx.fillStyle = this.color;
  12750. ctx.lineWidth = this._getLineWidth();
  12751. // draw line
  12752. var angle, length;
  12753. if (this.from != this.to) {
  12754. // calculate length and angle of the line
  12755. angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  12756. var dx = (this.to.x - this.from.x);
  12757. var dy = (this.to.y - this.from.y);
  12758. var lEdge = Math.sqrt(dx * dx + dy * dy);
  12759. var lFrom = this.from.distanceToBorder(ctx, angle + Math.PI);
  12760. var pFrom = (lEdge - lFrom) / lEdge;
  12761. var xFrom = (pFrom) * this.from.x + (1 - pFrom) * this.to.x;
  12762. var yFrom = (pFrom) * this.from.y + (1 - pFrom) * this.to.y;
  12763. var lTo = this.to.distanceToBorder(ctx, angle);
  12764. var pTo = (lEdge - lTo) / lEdge;
  12765. var xTo = (1 - pTo) * this.from.x + pTo * this.to.x;
  12766. var yTo = (1 - pTo) * this.from.y + pTo * this.to.y;
  12767. ctx.beginPath();
  12768. ctx.moveTo(xFrom, yFrom);
  12769. ctx.lineTo(xTo, yTo);
  12770. ctx.stroke();
  12771. // draw arrow at the end of the line
  12772. length = 10 + 5 * this.width; // TODO: make customizable?
  12773. ctx.arrow(xTo, yTo, angle, length);
  12774. ctx.fill();
  12775. ctx.stroke();
  12776. // draw label
  12777. if (this.label) {
  12778. var point = this._pointOnLine(0.5);
  12779. this._label(ctx, this.label, point.x, point.y);
  12780. }
  12781. }
  12782. else {
  12783. // draw circle
  12784. var node = this.from;
  12785. var x, y, arrow;
  12786. var radius = this.length / 4;
  12787. if (!node.width) {
  12788. node.resize(ctx);
  12789. }
  12790. if (node.width > node.height) {
  12791. x = node.x + node.width / 2;
  12792. y = node.y - radius;
  12793. arrow = {
  12794. x: x,
  12795. y: node.y,
  12796. angle: 0.9 * Math.PI
  12797. };
  12798. }
  12799. else {
  12800. x = node.x + radius;
  12801. y = node.y - node.height / 2;
  12802. arrow = {
  12803. x: node.x,
  12804. y: y,
  12805. angle: 0.6 * Math.PI
  12806. };
  12807. }
  12808. ctx.beginPath();
  12809. // TODO: do not draw a circle, but an arc
  12810. // TODO: similarly, for a line without arrows, draw to the border of the nodes instead of the center
  12811. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  12812. ctx.stroke();
  12813. // draw all arrows
  12814. length = 10 + 5 * this.width; // TODO: make customizable?
  12815. ctx.arrow(arrow.x, arrow.y, arrow.angle, length);
  12816. ctx.fill();
  12817. ctx.stroke();
  12818. // draw label
  12819. if (this.label) {
  12820. point = this._pointOnCircle(x, y, radius, 0.5);
  12821. this._label(ctx, this.label, point.x, point.y);
  12822. }
  12823. }
  12824. };
  12825. /**
  12826. * Calculate the distance between a point (x3,y3) and a line segment from
  12827. * (x1,y1) to (x2,y2).
  12828. * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
  12829. * @param {number} x1
  12830. * @param {number} y1
  12831. * @param {number} x2
  12832. * @param {number} y2
  12833. * @param {number} x3
  12834. * @param {number} y3
  12835. * @private
  12836. */
  12837. Edge._dist = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is the point
  12838. var px = x2-x1,
  12839. py = y2-y1,
  12840. something = px*px + py*py,
  12841. u = ((x3 - x1) * px + (y3 - y1) * py) / something;
  12842. if (u > 1) {
  12843. u = 1;
  12844. }
  12845. else if (u < 0) {
  12846. u = 0;
  12847. }
  12848. var x = x1 + u * px,
  12849. y = y1 + u * py,
  12850. dx = x - x3,
  12851. dy = y - y3;
  12852. //# Note: If the actual distance does not matter,
  12853. //# if you only want to compare what this function
  12854. //# returns to other results of this function, you
  12855. //# can just return the squared distance instead
  12856. //# (i.e. remove the sqrt) to gain a little performance
  12857. return Math.sqrt(dx*dx + dy*dy);
  12858. };
  12859. /**
  12860. * Popup is a class to create a popup window with some text
  12861. * @param {Element} container The container object.
  12862. * @param {Number} [x]
  12863. * @param {Number} [y]
  12864. * @param {String} [text]
  12865. */
  12866. function Popup(container, x, y, text) {
  12867. if (container) {
  12868. this.container = container;
  12869. }
  12870. else {
  12871. this.container = document.body;
  12872. }
  12873. this.x = 0;
  12874. this.y = 0;
  12875. this.padding = 5;
  12876. if (x !== undefined && y !== undefined ) {
  12877. this.setPosition(x, y);
  12878. }
  12879. if (text !== undefined) {
  12880. this.setText(text);
  12881. }
  12882. // create the frame
  12883. this.frame = document.createElement("div");
  12884. var style = this.frame.style;
  12885. style.position = "absolute";
  12886. style.visibility = "hidden";
  12887. style.border = "1px solid #666";
  12888. style.color = "black";
  12889. style.padding = this.padding + "px";
  12890. style.backgroundColor = "#FFFFC6";
  12891. style.borderRadius = "3px";
  12892. style.MozBorderRadius = "3px";
  12893. style.WebkitBorderRadius = "3px";
  12894. style.boxShadow = "3px 3px 10px rgba(128, 128, 128, 0.5)";
  12895. style.whiteSpace = "nowrap";
  12896. this.container.appendChild(this.frame);
  12897. };
  12898. /**
  12899. * @param {number} x Horizontal position of the popup window
  12900. * @param {number} y Vertical position of the popup window
  12901. */
  12902. Popup.prototype.setPosition = function(x, y) {
  12903. this.x = parseInt(x);
  12904. this.y = parseInt(y);
  12905. };
  12906. /**
  12907. * Set the text for the popup window. This can be HTML code
  12908. * @param {string} text
  12909. */
  12910. Popup.prototype.setText = function(text) {
  12911. this.frame.innerHTML = text;
  12912. };
  12913. /**
  12914. * Show the popup window
  12915. * @param {boolean} show Optional. Show or hide the window
  12916. */
  12917. Popup.prototype.show = function (show) {
  12918. if (show === undefined) {
  12919. show = true;
  12920. }
  12921. if (show) {
  12922. var height = this.frame.clientHeight;
  12923. var width = this.frame.clientWidth;
  12924. var maxHeight = this.frame.parentNode.clientHeight;
  12925. var maxWidth = this.frame.parentNode.clientWidth;
  12926. var top = (this.y - height);
  12927. if (top + height + this.padding > maxHeight) {
  12928. top = maxHeight - height - this.padding;
  12929. }
  12930. if (top < this.padding) {
  12931. top = this.padding;
  12932. }
  12933. var left = this.x;
  12934. if (left + width + this.padding > maxWidth) {
  12935. left = maxWidth - width - this.padding;
  12936. }
  12937. if (left < this.padding) {
  12938. left = this.padding;
  12939. }
  12940. this.frame.style.left = left + "px";
  12941. this.frame.style.top = top + "px";
  12942. this.frame.style.visibility = "visible";
  12943. }
  12944. else {
  12945. this.hide();
  12946. }
  12947. };
  12948. /**
  12949. * Hide the popup window
  12950. */
  12951. Popup.prototype.hide = function () {
  12952. this.frame.style.visibility = "hidden";
  12953. };
  12954. /**
  12955. * @class Groups
  12956. * This class can store groups and properties specific for groups.
  12957. */
  12958. Groups = function () {
  12959. this.clear();
  12960. this.defaultIndex = 0;
  12961. };
  12962. /**
  12963. * default constants for group colors
  12964. */
  12965. Groups.DEFAULT = [
  12966. {border: "#2B7CE9", background: "#97C2FC", highlight: {border: "#2B7CE9", background: "#D2E5FF"}}, // blue
  12967. {border: "#FFA500", background: "#FFFF00", highlight: {border: "#FFA500", background: "#FFFFA3"}}, // yellow
  12968. {border: "#FA0A10", background: "#FB7E81", highlight: {border: "#FA0A10", background: "#FFAFB1"}}, // red
  12969. {border: "#41A906", background: "#7BE141", highlight: {border: "#41A906", background: "#A1EC76"}}, // green
  12970. {border: "#E129F0", background: "#EB7DF4", highlight: {border: "#E129F0", background: "#F0B3F5"}}, // magenta
  12971. {border: "#7C29F0", background: "#AD85E4", highlight: {border: "#7C29F0", background: "#D3BDF0"}}, // purple
  12972. {border: "#C37F00", background: "#FFA807", highlight: {border: "#C37F00", background: "#FFCA66"}}, // orange
  12973. {border: "#4220FB", background: "#6E6EFD", highlight: {border: "#4220FB", background: "#9B9BFD"}}, // darkblue
  12974. {border: "#FD5A77", background: "#FFC0CB", highlight: {border: "#FD5A77", background: "#FFD1D9"}}, // pink
  12975. {border: "#4AD63A", background: "#C2FABC", highlight: {border: "#4AD63A", background: "#E6FFE3"}} // mint
  12976. ];
  12977. /**
  12978. * Clear all groups
  12979. */
  12980. Groups.prototype.clear = function () {
  12981. this.groups = {};
  12982. this.groups.length = function()
  12983. {
  12984. var i = 0;
  12985. for ( var p in this ) {
  12986. if (this.hasOwnProperty(p)) {
  12987. i++;
  12988. }
  12989. }
  12990. return i;
  12991. }
  12992. };
  12993. /**
  12994. * get group properties of a groupname. If groupname is not found, a new group
  12995. * is added.
  12996. * @param {*} groupname Can be a number, string, Date, etc.
  12997. * @return {Object} group The created group, containing all group properties
  12998. */
  12999. Groups.prototype.get = function (groupname) {
  13000. var group = this.groups[groupname];
  13001. if (group == undefined) {
  13002. // create new group
  13003. var index = this.defaultIndex % Groups.DEFAULT.length;
  13004. this.defaultIndex++;
  13005. group = {};
  13006. group.color = Groups.DEFAULT[index];
  13007. this.groups[groupname] = group;
  13008. }
  13009. return group;
  13010. };
  13011. /**
  13012. * Add a custom group style
  13013. * @param {String} groupname
  13014. * @param {Object} style An object containing borderColor,
  13015. * backgroundColor, etc.
  13016. * @return {Object} group The created group object
  13017. */
  13018. Groups.prototype.add = function (groupname, style) {
  13019. this.groups[groupname] = style;
  13020. if (style.color) {
  13021. style.color = Node.parseColor(style.color);
  13022. }
  13023. return style;
  13024. };
  13025. /**
  13026. * @class Images
  13027. * This class loads images and keeps them stored.
  13028. */
  13029. Images = function () {
  13030. this.images = {};
  13031. this.callback = undefined;
  13032. };
  13033. /**
  13034. * Set an onload callback function. This will be called each time an image
  13035. * is loaded
  13036. * @param {function} callback
  13037. */
  13038. Images.prototype.setOnloadCallback = function(callback) {
  13039. this.callback = callback;
  13040. };
  13041. /**
  13042. *
  13043. * @param {string} url Url of the image
  13044. * @return {Image} img The image object
  13045. */
  13046. Images.prototype.load = function(url) {
  13047. var img = this.images[url];
  13048. if (img == undefined) {
  13049. // create the image
  13050. var images = this;
  13051. img = new Image();
  13052. this.images[url] = img;
  13053. img.onload = function() {
  13054. if (images.callback) {
  13055. images.callback(this);
  13056. }
  13057. };
  13058. img.src = url;
  13059. }
  13060. return img;
  13061. };
  13062. /**
  13063. * @constructor Cluster
  13064. * Contains the cluster properties for the graph object
  13065. */
  13066. function Cluster() {
  13067. this.clusterSession = 0;
  13068. this.hubThreshold = 5;
  13069. }
  13070. /**
  13071. * This function can be called to increase the cluster level. This means that the nodes with only one edge connection will
  13072. * be clustered with their connected node. This can be repeated as many times as needed.
  13073. * This can be called externally (by a keybind for instance) to reduce the complexity of big datasets.
  13074. */
  13075. Cluster.prototype.increaseClusterLevel = function() {
  13076. var isMovingBeforeClustering = this.moving;
  13077. this._formClusters(true);
  13078. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  13079. if (this.moving != isMovingBeforeClustering) {
  13080. this.start();
  13081. }
  13082. };
  13083. /**
  13084. * This function can be called to decrease the cluster level. This means that the nodes with only one edge connection will
  13085. * be unpacked if they are a cluster. This can be repeated as many times as needed.
  13086. * This can be called externally (by a key-bind for instance) to look into clusters without zooming.
  13087. */
  13088. Cluster.prototype.decreaseClusterLevel = function() {
  13089. var isMovingBeforeClustering = this.moving;
  13090. for (var i = 0; i < this.nodeIndices.length; i++) {
  13091. var node = this.nodes[this.nodeIndices[i]];
  13092. if (node.clusterSize > 1) {
  13093. this._expandClusterNode(node,false,true);
  13094. }
  13095. }
  13096. this._updateNodeIndexList();
  13097. this.clusterSession = (this.clusterSession == 0) ? 0 : this.clusterSession - 1;
  13098. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  13099. if (this.moving != isMovingBeforeClustering) {
  13100. this.start();
  13101. }
  13102. this._updateLabels();
  13103. };
  13104. /**
  13105. * This function can be called to open up a specific cluster.
  13106. * It will unpack the cluster back one level.
  13107. *
  13108. * @param node | Node object: cluster to open.
  13109. */
  13110. Cluster.prototype.openCluster = function(node) {
  13111. var isMovingBeforeClustering = this.moving;
  13112. this._expandClusterNode(node,false,true);
  13113. this._updateNodeIndexList();
  13114. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  13115. if (this.moving != isMovingBeforeClustering) {
  13116. this.start();
  13117. }
  13118. };
  13119. /**
  13120. * This function checks if the zoom action is in or out.
  13121. * If out, check if we can form clusters, if in, check if we can open clusters.
  13122. * This function is only called from _zoom()
  13123. *
  13124. * @private
  13125. */
  13126. Cluster.prototype._updateClusters = function() {
  13127. var isMovingBeforeClustering = this.moving;
  13128. if (this.previousScale > this.scale) { // zoom out
  13129. this._formClusters(false);
  13130. }
  13131. else if (this.previousScale < this.scale) { // zoom out
  13132. this._openClusters();
  13133. }
  13134. this._updateClusterLabels();
  13135. this._updateNodeLabels();
  13136. this._updateLabels();
  13137. this.previousScale = this.scale;
  13138. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  13139. if (this.moving != isMovingBeforeClustering) {
  13140. this.start();
  13141. }
  13142. };
  13143. /**
  13144. * This updates the node labels for all nodes (for debugging purposes)
  13145. * @private
  13146. */
  13147. Cluster.prototype._updateLabels = function() {
  13148. // update node labels
  13149. //this._updateClusterLabels();
  13150. // this._updateNodeLabels();
  13151. // Debug :
  13152. for (var nodeID in this.nodes) {
  13153. if (this.nodes.hasOwnProperty(nodeID)) {
  13154. var node = this.nodes[nodeID];
  13155. node.label = String(node.dynamicEdges.length).concat(":",node.dynamicEdgesLength,":",String(node.clusterSize),":::",String(node.id));
  13156. }
  13157. }
  13158. };
  13159. /**
  13160. * This updates the node labels for all clusters
  13161. * @private
  13162. */
  13163. Cluster.prototype._updateClusterLabels = function() {
  13164. // update node labels
  13165. for (var nodeID in this.nodes) {
  13166. if (this.nodes.hasOwnProperty(nodeID)) {
  13167. var node = this.nodes[nodeID];
  13168. if (node.clusterSize > 1) {
  13169. node.label = "[".concat(String(node.clusterSize),"]");
  13170. }
  13171. }
  13172. }
  13173. };
  13174. /**
  13175. * This updates the node labels for all nodes that are NOT clusters
  13176. * @private
  13177. */
  13178. Cluster.prototype._updateNodeLabels = function() {
  13179. // update node labels
  13180. for (var nodeID in this.nodes) {
  13181. var node = this.nodes[nodeID];
  13182. if (node.clusterSize == 1) {
  13183. node.label = String(node.id);
  13184. }
  13185. }
  13186. };
  13187. /**
  13188. * This function loops over all nodes in the nodeIndices list. For each node it checks if it is a cluster and if it
  13189. * has to be opened based on the current zoom level.
  13190. *
  13191. * @private
  13192. */
  13193. Cluster.prototype._openClusters = function() {
  13194. var amountOfNodes = this.nodeIndices.length;
  13195. for (var i = 0; i < this.nodeIndices.length; i++) {
  13196. var node = this.nodes[this.nodeIndices[i]];
  13197. this._expandClusterNode(node,true,false);
  13198. }
  13199. this._updateNodeIndexList();
  13200. if (this.nodeIndices.length != amountOfNodes) { // this means a clustering operation has taken place
  13201. this.clusterSession -= 1;
  13202. }
  13203. };
  13204. /**
  13205. * This function checks if a node has to be opened. This is done by checking the zoom level.
  13206. * If the node contains child nodes, this function is recursively called on the child nodes as well.
  13207. * This recursive behaviour is optional and can be set by the recursive argument.
  13208. *
  13209. * @param parentNode | Node object: to check for cluster and expand
  13210. * @param recursive | Boolean: enable or disable recursive calling
  13211. * @param forceExpand | Boolean: enable or disable forcing the last node to join the cluster to be expelled
  13212. * @private
  13213. */
  13214. Cluster.prototype._expandClusterNode = function(parentNode, recursive, forceExpand) {
  13215. // first check if node is a cluster
  13216. if (parentNode.clusterSize > 1) {
  13217. // if the last child has been added on a smaller scale than current scale (@optimization)
  13218. if (parentNode.formationScale < this.scale || forceExpand == true) {
  13219. // we will check if any of the contained child nodes should be removed from the cluster
  13220. for (var containedNodeID in parentNode.containedNodes) {
  13221. if (parentNode.containedNodes.hasOwnProperty(containedNodeID)) {
  13222. var childNode = parentNode.containedNodes[containedNodeID];
  13223. // force expand will expand the largest cluster size clusters. Since we cluster from outside in, we assume that
  13224. // the largest cluster is the one that comes from outside
  13225. if (forceExpand == true) {
  13226. if (childNode.clusterSession == this.clusterSession - 1) {
  13227. this._expelChildFromParent(parentNode,containedNodeID,recursive,forceExpand);
  13228. }
  13229. }
  13230. else {
  13231. if (this._parentNodeInActiveArea(parentNode)) {
  13232. this._expelChildFromParent(parentNode,containedNodeID,recursive,forceExpand);
  13233. }
  13234. }
  13235. }
  13236. }
  13237. }
  13238. }
  13239. };
  13240. Cluster.prototype._parentNodeInActiveArea = function(node) {
  13241. if (Math.abs(node.x - this.zoomCenter.x) <= this.constants.clustering.activeAreaRadius/this.scale &&
  13242. Math.abs(node.y - this.zoomCenter.y) <= this.constants.clustering.activeAreaRadius/this.scale) {
  13243. return true;
  13244. }
  13245. else {
  13246. return false;
  13247. }
  13248. };
  13249. /**
  13250. * This function will expel a child_node from a parent_node. This is to de-cluster the node. This function will remove
  13251. * the child node from the parent contained_node object and put it back into the global nodes object.
  13252. * The same holds for the edge that was connected to the child node. It is moved back into the global edges object.
  13253. *
  13254. * @param parentNode | Node object: the parent node
  13255. * @param containedNodeID | String: child_node id as it is contained in the containedNodes object of the parent node
  13256. * @param recursive | Boolean: This will also check if the child needs to be expanded.
  13257. * With force and recursive both true, the entire cluster is unpacked
  13258. * @param forceExpand | Boolean: This will disregard the zoom level and will expel this child from the parent
  13259. * @private
  13260. */
  13261. Cluster.prototype._expelChildFromParent = function(parentNode, containedNodeID, recursive, forceExpand) {
  13262. var childNode = parentNode.containedNodes[containedNodeID];
  13263. // if child node has been added on smaller scale than current, kick out
  13264. if (childNode.formationScale < this.scale || forceExpand == true) {
  13265. // put the child node back in the global nodes object
  13266. this.nodes[containedNodeID] = childNode;
  13267. // release the contained edges from this childNode back into the global edges
  13268. this._releaseContainedEdges(parentNode,childNode)
  13269. // reconnect rerouted edges to the childNode
  13270. this._connectEdgeBackToChild(parentNode,childNode);
  13271. // undo the changes from the clustering operation on the parent node
  13272. parentNode.mass -= this.constants.clustering.massTransferCoefficient * childNode.mass;
  13273. parentNode.fontSize -= this.constants.clustering.fontSizeMultiplier * childNode.clusterSize;
  13274. parentNode.clusterSize -= childNode.clusterSize;
  13275. parentNode.dynamicEdgesLength = parentNode.dynamicEdges.length;
  13276. // place the child node near the parent, not at the exact same location to avoid chaos in the system
  13277. childNode.x = parentNode.x + this.constants.edges.length * 0.2 * (0.5 - Math.random()) * parentNode.clusterSize;
  13278. childNode.y = parentNode.y + this.constants.edges.length * 0.2 * (0.5 - Math.random()) * parentNode.clusterSize;
  13279. // remove the clusterSession from the child node
  13280. childNode.clusterSession = 0;
  13281. // remove node from the list
  13282. delete parentNode.containedNodes[containedNodeID];
  13283. // restart the simulation to reorganise all nodes
  13284. this.moving = true;
  13285. // recalculate the size of the node on the next time the node is rendered
  13286. parentNode.clearSizeCache();
  13287. }
  13288. // check if a further expansion step is possible if recursivity is enabled
  13289. if (recursive == true) {
  13290. this._expandClusterNode(childNode,recursive,forceExpand);
  13291. }
  13292. };
  13293. /**
  13294. * This function checks if any nodes at the end of their trees have edges below a threshold length
  13295. * This function is called only from _updateClusters()
  13296. * forceLevelCollapse ignores the length of the edge and collapses one level
  13297. * This means that a node with only one edge will be clustered with its connected node
  13298. *
  13299. * @private
  13300. * @param force_level_collapse | Boolean
  13301. */
  13302. Cluster.prototype._formClusters = function(forceLevelCollapse) {
  13303. var amountOfNodes = this.nodeIndices.length;
  13304. if (forceLevelCollapse == false) {
  13305. this._formClustersByZoom();
  13306. }
  13307. else {
  13308. this._forceClustersByZoom();
  13309. }
  13310. if (this.nodeIndices.length != amountOfNodes) { // this means a clustering operation has taken place
  13311. this.clusterSession += 1;
  13312. }
  13313. };
  13314. /**
  13315. * This function handles the clustering by zooming out, this is based on minimum edge distance
  13316. *
  13317. * @private
  13318. */
  13319. Cluster.prototype._formClustersByZoom = function() {
  13320. var dx,dy,length,
  13321. minLength = this.constants.clustering.clusterLength/this.scale;
  13322. // create an array of edge ids
  13323. var edgesIDarray = []
  13324. for (var id in this.edges) {
  13325. if (this.edges.hasOwnProperty(id)) {
  13326. edgesIDarray.push(id);
  13327. }
  13328. }
  13329. // check if any edges are shorter than minLength and start the clustering
  13330. // the clustering favours the node with the larger mass
  13331. for (var i = 0; i < edgesIDarray.length; i++) {
  13332. var edgeID = edgesIDarray[i];
  13333. var edge = this.edges[edgeID];
  13334. if (edge.connected) {
  13335. dx = (edge.to.x - edge.from.x);
  13336. dy = (edge.to.y - edge.from.y);
  13337. length = Math.sqrt(dx * dx + dy * dy);
  13338. if (length < minLength) {
  13339. // first check which node is larger
  13340. var parentNode = edge.from
  13341. var childNode = edge.to
  13342. if (edge.to.mass > edge.from.mass) {
  13343. parentNode = edge.to
  13344. childNode = edge.from
  13345. }
  13346. // we allow clustering from outside in
  13347. // if we do not cluster from outside in, we would have to reconnect edges or keep
  13348. // a second set of edges for the clusters.
  13349. // This will also have to be altered in the force calculation and rendering.
  13350. // This method is non-destructive and does not require a second set of data.
  13351. if (childNode.dynamicEdgesLength == 1) {
  13352. this._addToCluster(parentNode,childNode,edge,false);
  13353. }
  13354. else if (parentNode.dynamicEdgesLength == 1) {
  13355. this._addToCluster(childNode,parentNode,edge,false);
  13356. }
  13357. }
  13358. }
  13359. }
  13360. this._updateNodeIndexList();
  13361. };
  13362. /**
  13363. * This function forces the graph to cluster all nodes with only one connecting edge to their
  13364. * connected node.
  13365. *
  13366. * @private
  13367. */
  13368. Cluster.prototype._forceClustersByZoom = function() {
  13369. for (var nodeID = 0; nodeID < this.nodeIndices.length; nodeID++) {
  13370. var childNode = this.nodes[this.nodeIndices[nodeID]];
  13371. if (childNode.dynamicEdgesLength == 1) {
  13372. var edge = childNode.dynamicEdges[0];
  13373. var parentNode = (edge.toId == childNode.id) ? this.nodes[edge.fromId] : this.nodes[edge.toId];
  13374. this._addToCluster(parentNode,childNode,true);
  13375. }
  13376. }
  13377. this._updateNodeIndexList();
  13378. this._updateDynamicEdges();
  13379. };
  13380. /**
  13381. * this functions starts clustering by hubs
  13382. * The minimum hub threshold is set globally
  13383. */
  13384. Cluster.prototype.aggregateHubs = function() {
  13385. var isMovingBeforeClustering = this.moving;
  13386. this._forceClustersByHub();
  13387. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  13388. if (this.moving != isMovingBeforeClustering) {
  13389. this.start();
  13390. }
  13391. };
  13392. Cluster.prototype._getHubSize = function() {
  13393. var distribution = {};
  13394. for (var i = 0; i < this.nodeIndices.length; i++) {
  13395. // TODO get the distribution
  13396. }
  13397. };
  13398. /**
  13399. *
  13400. * @param hubThreshold
  13401. * @private
  13402. */
  13403. Cluster.prototype._forceClustersByHub = function() {
  13404. // we loop over all nodes in the list
  13405. for (var i = 0; i < this.nodeIndices.length; i++) {
  13406. // we check if it is still available since it can be used by the clustering in this loop
  13407. if (this.nodes.hasOwnProperty(this.nodeIndices[i])) {
  13408. var hubNode = this.nodes[this.nodeIndices[i]];
  13409. // we decide if the node is a hub
  13410. // TODO: check if dynamicEdgesLength is required
  13411. if (hubNode.dynamicEdges.length >= this.hubThreshold) {
  13412. // we create a list of edges because the dynamicEdges change over the course of this loop
  13413. var edgesIDarray = []
  13414. var amountOfInitialEdges = hubNode.dynamicEdges.length;
  13415. for (var j = 0; j < amountOfInitialEdges; j++) {
  13416. edgesIDarray.push(hubNode.dynamicEdges[j].id);
  13417. }
  13418. // we loop over all edges INITIALLY connected to this hub
  13419. for (var j = 0; j < amountOfInitialEdges; j++) {
  13420. var edge = this.edges[edgesIDarray[j]];
  13421. var childNode = this.nodes[(edge.fromId == hubNode.id) ? edge.toId : edge.fromId];
  13422. this._addToCluster(hubNode,childNode,true);
  13423. }
  13424. break;
  13425. }
  13426. }
  13427. }
  13428. this._updateNodeIndexList();
  13429. //this._updateDynamicEdges();
  13430. this._updateLabels();
  13431. };
  13432. /**
  13433. * This function adds the child node to the parent node, creating a cluster if it is not already.
  13434. * This function is called only from _updateClusters()
  13435. *
  13436. * @param parent_node | Node object: this is the node that will house the child node
  13437. * @param child_node | Node object: this node will be deleted from the global this.nodes and stored in the parent node
  13438. * @param force_level_collapse | Boolean: true will only update the remainingEdges at the very end of the clustering, ensuring single level collapse
  13439. * @private
  13440. */
  13441. Cluster.prototype._addToCluster = function(parentNode, childNode, forceLevelCollapse) {
  13442. // join child node in the parent node
  13443. parentNode.containedNodes[childNode.id] = childNode;
  13444. /*
  13445. if (forceLevelCollapse == false) {
  13446. parentNode.dynamicEdgesLength += childNode.dynamicEdges.length - 2;
  13447. }
  13448. */
  13449. for (var i = 0; i < childNode.dynamicEdges.length; i++) {
  13450. var edge = childNode.dynamicEdges[i];
  13451. if (edge.toId == parentNode.id || edge.fromId == parentNode.id) { // edge connected to parentNode
  13452. this._addToContainedEdges(parentNode,childNode,edge);
  13453. }
  13454. else {
  13455. this._connectEdgeToCluster(parentNode,childNode,edge);
  13456. }
  13457. }
  13458. childNode.dynamicEdges = [];
  13459. // remove the childNode from the global nodes object
  13460. delete this.nodes[childNode.id];
  13461. childNode.clusterSession = this.clusterSession;
  13462. parentNode.mass += this.constants.clustering.massTransferCoefficient * childNode.mass;
  13463. parentNode.clusterSize += childNode.clusterSize;
  13464. parentNode.fontSize += this.constants.clustering.fontSizeMultiplier * childNode.clusterSize
  13465. // giving the clusters a dynamic formationScale to ensure not all clusters open up when zoomed
  13466. if (forceLevelCollapse == true) {
  13467. parentNode.formationScale = this.scale * Math.pow(1.0/11.0,this.clusterSession);
  13468. }
  13469. else {
  13470. parentNode.formationScale = this.scale; // The latest child has been added on this scale
  13471. }
  13472. parentNode.dynamicEdgesLength = parentNode.dynamicEdges.length;
  13473. // recalculate the size of the node on the next time the node is rendered
  13474. parentNode.clearSizeCache();
  13475. parentNode.containedNodes[childNode.id].formationScale = this.scale; // this child has been added at this scale.
  13476. // restart the simulation to reorganise all nodes
  13477. this.moving = true;
  13478. };
  13479. /**
  13480. * This function will apply the changes made to the remainingEdges during the formation of the clusters.
  13481. * This is a seperate function to allow for level-wise collapsing of the node tree.
  13482. * It has to be called if a level is collapsed. It is called by _formClusters().
  13483. * @private
  13484. */
  13485. Cluster.prototype._updateDynamicEdges = function() {
  13486. for (var i = 0; i < this.nodeIndices.length; i++) {
  13487. var node = this.nodes[this.nodeIndices[i]];
  13488. node.dynamicEdgesLength = node.dynamicEdges.length;
  13489. }
  13490. };
  13491. Cluster.prototype._repositionNodes = function() {
  13492. for (var i = 0; i < this.nodeIndices.length; i++) {
  13493. var node = this.nodes[this.nodeIndices[i]];
  13494. if (!node.isFixed()) {
  13495. // TODO: position new nodes in a smarter way!
  13496. var radius = this.constants.edges.length * (1 + 0.5*node.clusterSize);
  13497. var angle = 2 * Math.PI * Math.random();
  13498. node.x = radius * Math.cos(angle);
  13499. node.y = radius * Math.sin(angle);
  13500. }
  13501. }
  13502. };
  13503. /**
  13504. * This adds an edge from the childNode to the contained edges of the parent node
  13505. *
  13506. * @param parentNode | Node object
  13507. * @param childNode | Node object
  13508. * @param edge | Edge object
  13509. * @private
  13510. */
  13511. Cluster.prototype._addToContainedEdges = function(parentNode, childNode, edge) {
  13512. // create an array object if it does not yet exist for this childNode
  13513. if (!(parentNode.containedEdges.hasOwnProperty(childNode.id))) {
  13514. parentNode.containedEdges[childNode.id] = []
  13515. }
  13516. // add this edge to the list
  13517. parentNode.containedEdges[childNode.id].push(edge);
  13518. // remove the edge from the global edges object
  13519. delete this.edges[edge.id];
  13520. // remove the edge from the parent object
  13521. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  13522. if (parentNode.dynamicEdges[i].id == edge.id) {
  13523. parentNode.dynamicEdges.splice(i,1);
  13524. break;
  13525. }
  13526. }
  13527. };
  13528. /**
  13529. * This function connects an edge that was connected to a child node to the parent node.
  13530. * It keeps track of which nodes it has been connected to with the originalID array.
  13531. *
  13532. * @param parentNode | Node object
  13533. * @param childNode | Node object
  13534. * @param edge | Edge object
  13535. * @private
  13536. */
  13537. Cluster.prototype._connectEdgeToCluster = function(parentNode, childNode, edge) {
  13538. if (edge.toId == childNode.id) { // edge connected to other node on the "to" side
  13539. edge.originalToID.push(childNode.id);
  13540. edge.to = parentNode;
  13541. edge.toId = parentNode.id;
  13542. }
  13543. else { // edge connected to other node with the "from" side
  13544. edge.originalFromID.push(childNode.id);
  13545. edge.from = parentNode;
  13546. edge.fromId = parentNode.id;
  13547. }
  13548. this._addToReroutedEdges(parentNode,childNode,edge);
  13549. };
  13550. /**
  13551. * This adds an edge from the childNode to the rerouted edges of the parent node
  13552. *
  13553. * @param parentNode | Node object
  13554. * @param childNode | Node object
  13555. * @param edge | Edge object
  13556. * @private
  13557. */
  13558. Cluster.prototype._addToReroutedEdges = function(parentNode, childNode, edge) {
  13559. // create an array object if it does not yet exist for this childNode
  13560. // we store the edge in the rerouted edges so we can restore it when the cluster pops open
  13561. if (!(parentNode.reroutedEdges.hasOwnProperty(childNode.id))) {
  13562. parentNode.reroutedEdges[childNode.id] = [];
  13563. }
  13564. parentNode.reroutedEdges[childNode.id].push(edge);
  13565. // this edge becomes part of the dynamicEdges of the cluster node
  13566. parentNode.dynamicEdges.push(edge);
  13567. };
  13568. /**
  13569. * This function connects an edge that was connected to a cluster node back to the child node.
  13570. *
  13571. * @param parentNode | Node object
  13572. * @param childNode | Node object
  13573. * @private
  13574. */
  13575. Cluster.prototype._connectEdgeBackToChild = function(parentNode, childNode) {
  13576. if (parentNode.reroutedEdges[childNode.id] != undefined) {
  13577. for (var i = 0; i < parentNode.reroutedEdges[childNode.id].length; i++) {
  13578. var edge = parentNode.reroutedEdges[childNode.id][i];
  13579. if (edge.originalFromID[edge.originalFromID.length-1] == childNode.id) {
  13580. edge.originalFromID.pop();
  13581. edge.fromId = childNode.id;
  13582. edge.from = childNode;
  13583. }
  13584. else {
  13585. edge.originalToID.pop();
  13586. edge.toId = childNode.id;
  13587. edge.to = childNode;
  13588. }
  13589. // append this edge to the list of edges connecting to the childnode
  13590. childNode.dynamicEdges.push(edge);
  13591. // remove the edge from the parent object
  13592. for (var j = 0; j < parentNode.dynamicEdges.length; j++) {
  13593. if (parentNode.dynamicEdges[j].id == edge.id) {
  13594. parentNode.dynamicEdges.splice(j,1);
  13595. break;
  13596. }
  13597. }
  13598. }
  13599. // remove the entry from the rerouted edges
  13600. delete parentNode.reroutedEdges[childNode.id];
  13601. }
  13602. };
  13603. /**
  13604. * This function released the contained edges back into the global domain and puts them back into the
  13605. * dynamic edges of both parent and child.
  13606. *
  13607. * @param parentNode | Node object
  13608. * @param childNode | Node object
  13609. * @private
  13610. */
  13611. Cluster.prototype._releaseContainedEdges = function(parentNode, childNode) {
  13612. for (var i = 0; i < parentNode.containedEdges[childNode.id].length; i++) {
  13613. var edge = parentNode.containedEdges[childNode.id][i];
  13614. // put the edge back in the global edges object
  13615. this.edges[edge.id] = edge;
  13616. // put the edge back in the dynamic edges of the child and parent
  13617. childNode.dynamicEdges.push(edge);
  13618. parentNode.dynamicEdges.push(edge);
  13619. }
  13620. // remove the entry from the contained edges
  13621. delete parentNode.containedEdges[childNode.id];
  13622. };
  13623. /**
  13624. * @constructor Graph
  13625. * Create a graph visualization, displaying nodes and edges.
  13626. *
  13627. * @param {Element} container The DOM element in which the Graph will
  13628. * be created. Normally a div element.
  13629. * @param {Object} data An object containing parameters
  13630. * {Array} nodes
  13631. * {Array} edges
  13632. * @param {Object} options Options
  13633. */
  13634. function Graph (container, data, options) {
  13635. // create variables and set default values
  13636. this.containerElement = container;
  13637. this.width = '100%';
  13638. this.height = '100%';
  13639. this.refreshRate = 50; // milliseconds
  13640. this.stabilize = true; // stabilize before displaying the graph
  13641. this.selectable = true;
  13642. // set constant values
  13643. this.constants = {
  13644. nodes: {
  13645. radiusMin: 5,
  13646. radiusMax: 20,
  13647. radius: 5,
  13648. distance: 100, // px
  13649. shape: 'ellipse',
  13650. image: undefined,
  13651. widthMin: 16, // px
  13652. widthMax: 64, // px
  13653. fontColor: 'black',
  13654. fontSize: 14, // px
  13655. //fontFace: verdana,
  13656. fontFace: 'arial',
  13657. color: {
  13658. border: '#2B7CE9',
  13659. background: '#97C2FC',
  13660. highlight: {
  13661. border: '#2B7CE9',
  13662. background: '#D2E5FF'
  13663. },
  13664. cluster: {
  13665. border: '#256a2d',
  13666. background: '#2cd140',
  13667. highlight: {
  13668. border: '#899539',
  13669. background: '#c5dc29'
  13670. }
  13671. }
  13672. },
  13673. borderColor: '#2B7CE9',
  13674. backgroundColor: '#97C2FC',
  13675. highlightColor: '#D2E5FF',
  13676. group: undefined
  13677. },
  13678. edges: {
  13679. widthMin: 1,
  13680. widthMax: 15,
  13681. width: 10,
  13682. style: 'line',
  13683. color: '#343434',
  13684. fontColor: '#343434',
  13685. fontSize: 14, // px
  13686. fontFace: 'arial',
  13687. //distance: 100, //px
  13688. length: 100, // px
  13689. dash: {
  13690. length: 10,
  13691. gap: 5,
  13692. altLength: undefined
  13693. }
  13694. },
  13695. clustering: {
  13696. clusterLength: 30, // threshold edge length for clustering
  13697. fontSizeMultiplier: 2, // how much the cluster font size grows per node (in px)
  13698. forceAmplification: 0.6, // amount of clusterSize between two nodes multiply this value (+1) with the repulsion force
  13699. distanceAmplification: 0.1, // amount of clusterSize between two nodes multiply this value (+1) with the repulsion force
  13700. edgeGrowth: 10, // amount of clusterSize connected to the edge is multiplied with this and added to edgeLength
  13701. clusterSizeWidthFactor: 10,
  13702. clusterSizeHeightFactor: 10,
  13703. clusterSizeRadiusFactor: 10,
  13704. activeAreaRadius: 200, // box area around the curser where clusters are popped open
  13705. massTransferCoefficient: 1 // parent.mass += massTransferCoefficient * child.mass
  13706. },
  13707. minForce: 0.05,
  13708. minVelocity: 0.02, // px/s
  13709. maxIterations: 1000 // maximum number of iteration to stabilize
  13710. };
  13711. // call the constructor of the cluster object
  13712. Cluster.call(this);
  13713. var graph = this;
  13714. this.nodeIndices = []; // the node indices list is used to speed up the computation of the repulsion fields
  13715. this.nodes = {}; // object with Node objects
  13716. this.edges = {}; // object with Edge objects
  13717. this.zoomCenter = {}; // object with x and y elements used for determining the center of the zoom action
  13718. this.scale = 1; // defining the global scale variable in the constructor
  13719. this.previousScale = this.scale; // this is used to check if the zoom operation is zooming in or out
  13720. // TODO: create a counter to keep track on the number of nodes having values
  13721. // TODO: create a counter to keep track on the number of nodes currently moving
  13722. // TODO: create a counter to keep track on the number of edges having values
  13723. this.nodesData = null; // A DataSet or DataView
  13724. this.edgesData = null; // A DataSet or DataView
  13725. // create event listeners used to subscribe on the DataSets of the nodes and edges
  13726. var me = this;
  13727. this.nodesListeners = {
  13728. 'add': function (event, params) {
  13729. me._addNodes(params.items);
  13730. me.start();
  13731. },
  13732. 'update': function (event, params) {
  13733. me._updateNodes(params.items);
  13734. me.start();
  13735. },
  13736. 'remove': function (event, params) {
  13737. me._removeNodes(params.items);
  13738. me.start();
  13739. }
  13740. };
  13741. this.edgesListeners = {
  13742. 'add': function (event, params) {
  13743. me._addEdges(params.items);
  13744. me.start();
  13745. },
  13746. 'update': function (event, params) {
  13747. me._updateEdges(params.items);
  13748. me.start();
  13749. },
  13750. 'remove': function (event, params) {
  13751. me._removeEdges(params.items);
  13752. me.start();
  13753. }
  13754. };
  13755. console.log("here")
  13756. this.groups = new Groups(); // object with groups
  13757. this.images = new Images(); // object with images
  13758. this.images.setOnloadCallback(function () {
  13759. graph._redraw();
  13760. });
  13761. // properties of the data
  13762. this.moving = false; // True if any of the nodes have an undefined position
  13763. this.selection = [];
  13764. this.timer = undefined;
  13765. // create a frame and canvas
  13766. this._create();
  13767. // apply options
  13768. this.setOptions(options);
  13769. // draw data
  13770. this.setData(data);
  13771. // zoom so all data will fit on the screen
  13772. this.zoomToFit();
  13773. // cluster if the data set is big
  13774. this.clusterToFit();
  13775. // updates the lables after clustering
  13776. this._updateLabels();
  13777. // find a stable position or start animating to a stable position
  13778. if (this.stabilize) {
  13779. this._doStabilize();
  13780. }
  13781. this.start();
  13782. }
  13783. /**
  13784. * We add the functionality of the cluster object to the graph object
  13785. * @type {Cluster.prototype}
  13786. */
  13787. Graph.prototype = Object.create(Cluster.prototype);
  13788. /**
  13789. * This function clusters untill the maxNumberOfNodes has been reached
  13790. */
  13791. Graph.prototype.clusterToFit = function() {
  13792. var numberOfNodes = this.nodeIndices.length;
  13793. var maxNumberOfNodes = 100; // TODO: set in constants
  13794. var maxLevels = 10;
  13795. var level = 0;
  13796. while (numberOfNodes >= maxNumberOfNodes && level < maxLevels) {
  13797. if (level % 2 == 0) {
  13798. this.increaseClusterLevel();
  13799. }
  13800. else {
  13801. this.aggregateHubs();
  13802. }
  13803. numberOfNodes = this.nodeIndices.length;
  13804. level += 1;
  13805. }
  13806. // after the clustering we reposition the nodes to avoid initial chaos
  13807. if (level > 1) {
  13808. this._repositionNodes();
  13809. }
  13810. };
  13811. Graph.prototype.zoomToFit = function() {
  13812. var numberOfNodes = this.nodeIndices.length;
  13813. var zoomLevel = 105 / (numberOfNodes + 80); // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  13814. if (zoomLevel > 1.0) {
  13815. zoomLevel = 1.0;
  13816. }
  13817. if (!('mousewheelScale' in this.pinch)) {
  13818. this.pinch.mousewheelScale = zoomLevel;
  13819. }
  13820. this._setScale(zoomLevel);
  13821. };
  13822. /**
  13823. * Update the this.nodeIndices with the most recent node index list
  13824. * @private
  13825. */
  13826. Graph.prototype._updateNodeIndexList = function() {
  13827. this.nodeIndices = [];
  13828. for (var idx in this.nodes) {
  13829. if (this.nodes.hasOwnProperty(idx)) {
  13830. this.nodeIndices.push(idx);
  13831. }
  13832. }
  13833. };
  13834. /**
  13835. * Set nodes and edges, and optionally options as well.
  13836. *
  13837. * @param {Object} data Object containing parameters:
  13838. * {Array | DataSet | DataView} [nodes] Array with nodes
  13839. * {Array | DataSet | DataView} [edges] Array with edges
  13840. * {String} [dot] String containing data in DOT format
  13841. * {Options} [options] Object with options
  13842. */
  13843. Graph.prototype.setData = function(data) {
  13844. if (data && data.dot && (data.nodes || data.edges)) {
  13845. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  13846. ' parameter pair "nodes" and "edges", but not both.');
  13847. }
  13848. // set options
  13849. this.setOptions(data && data.options);
  13850. // set all data
  13851. if (data && data.dot) {
  13852. // parse DOT file
  13853. if(data && data.dot) {
  13854. var dotData = vis.util.DOTToGraph(data.dot);
  13855. this.setData(dotData);
  13856. return;
  13857. }
  13858. }
  13859. else {
  13860. this._setNodes(data && data.nodes);
  13861. this._setEdges(data && data.edges);
  13862. }
  13863. // updating the list of node indices
  13864. };
  13865. /**
  13866. * Set options
  13867. * @param {Object} options
  13868. */
  13869. Graph.prototype.setOptions = function (options) {
  13870. if (options) {
  13871. // retrieve parameter values
  13872. if (options.width != undefined) {this.width = options.width;}
  13873. if (options.height != undefined) {this.height = options.height;}
  13874. if (options.stabilize != undefined) {this.stabilize = options.stabilize;}
  13875. if (options.selectable != undefined) {this.selectable = options.selectable;}
  13876. // TODO: work out these options and document them
  13877. if (options.edges) {
  13878. for (var prop in options.edges) {
  13879. if (options.edges.hasOwnProperty(prop)) {
  13880. this.constants.edges[prop] = options.edges[prop];
  13881. }
  13882. }
  13883. if (options.edges.length != undefined &&
  13884. options.nodes && options.nodes.distance == undefined) {
  13885. this.constants.edges.length = options.edges.length;
  13886. this.constants.nodes.distance = options.edges.length * 1.25;
  13887. }
  13888. if (!options.edges.fontColor) {
  13889. this.constants.edges.fontColor = options.edges.color;
  13890. }
  13891. // Added to support dashed lines
  13892. // David Jordan
  13893. // 2012-08-08
  13894. if (options.edges.dash) {
  13895. if (options.edges.dash.length != undefined) {
  13896. this.constants.edges.dash.length = options.edges.dash.length;
  13897. }
  13898. if (options.edges.dash.gap != undefined) {
  13899. this.constants.edges.dash.gap = options.edges.dash.gap;
  13900. }
  13901. if (options.edges.dash.altLength != undefined) {
  13902. this.constants.edges.dash.altLength = options.edges.dash.altLength;
  13903. }
  13904. }
  13905. }
  13906. if (options.nodes) {
  13907. for (prop in options.nodes) {
  13908. if (options.nodes.hasOwnProperty(prop)) {
  13909. this.constants.nodes[prop] = options.nodes[prop];
  13910. }
  13911. }
  13912. if (options.nodes.color) {
  13913. this.constants.nodes.color = Node.parseColor(options.nodes.color);
  13914. }
  13915. /*
  13916. if (options.nodes.widthMin) this.constants.nodes.radiusMin = options.nodes.widthMin;
  13917. if (options.nodes.widthMax) this.constants.nodes.radiusMax = options.nodes.widthMax;
  13918. */
  13919. }
  13920. if (options.groups) {
  13921. for (var groupname in options.groups) {
  13922. if (options.groups.hasOwnProperty(groupname)) {
  13923. var group = options.groups[groupname];
  13924. this.groups.add(groupname, group);
  13925. }
  13926. }
  13927. }
  13928. }
  13929. this.setSize(this.width, this.height);
  13930. this._setTranslation(this.frame.clientWidth / 2, this.frame.clientHeight / 2);
  13931. this._setScale(1);
  13932. };
  13933. /**
  13934. * fire an event
  13935. * @param {String} event The name of an event, for example 'select'
  13936. * @param {Object} params Optional object with event parameters
  13937. * @private
  13938. */
  13939. Graph.prototype._trigger = function (event, params) {
  13940. events.trigger(this, event, params);
  13941. };
  13942. /**
  13943. * Create the main frame for the Graph.
  13944. * This function is executed once when a Graph object is created. The frame
  13945. * contains a canvas, and this canvas contains all objects like the axis and
  13946. * nodes.
  13947. * @private
  13948. */
  13949. Graph.prototype._create = function () {
  13950. // remove all elements from the container element.
  13951. while (this.containerElement.hasChildNodes()) {
  13952. this.containerElement.removeChild(this.containerElement.firstChild);
  13953. }
  13954. this.frame = document.createElement('div');
  13955. this.frame.className = 'graph-frame';
  13956. this.frame.style.position = 'relative';
  13957. this.frame.style.overflow = 'hidden';
  13958. // create the graph canvas (HTML canvas element)
  13959. this.frame.canvas = document.createElement( 'canvas' );
  13960. this.frame.canvas.style.position = 'relative';
  13961. this.frame.appendChild(this.frame.canvas);
  13962. if (!this.frame.canvas.getContext) {
  13963. var noCanvas = document.createElement( 'DIV' );
  13964. noCanvas.style.color = 'red';
  13965. noCanvas.style.fontWeight = 'bold' ;
  13966. noCanvas.style.padding = '10px';
  13967. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  13968. this.frame.canvas.appendChild(noCanvas);
  13969. }
  13970. var me = this;
  13971. this.drag = {};
  13972. this.pinch = {};
  13973. this.hammer = Hammer(this.frame.canvas, {
  13974. prevent_default: true
  13975. });
  13976. this.hammer.on('tap', me._onTap.bind(me) );
  13977. this.hammer.on('hold', me._onHold.bind(me) );
  13978. this.hammer.on('pinch', me._onPinch.bind(me) );
  13979. this.hammer.on('touch', me._onTouch.bind(me) );
  13980. this.hammer.on('dragstart', me._onDragStart.bind(me) );
  13981. this.hammer.on('drag', me._onDrag.bind(me) );
  13982. this.hammer.on('dragend', me._onDragEnd.bind(me) );
  13983. this.hammer.on('mousewheel',me._onMouseWheel.bind(me) );
  13984. this.hammer.on('DOMMouseScroll',me._onMouseWheel.bind(me) ); // for FF
  13985. this.hammer.on('mousemove', me._onMouseMoveTitle.bind(me) );
  13986. this.mouseTrap = mouseTrap;
  13987. this.mouseTrap.bind("=",this.decreaseClusterLevel.bind(me));
  13988. this.mouseTrap.bind("-",this.increaseClusterLevel.bind(me));
  13989. this.mouseTrap.bind("s",this.singleStep.bind(me));
  13990. this.mouseTrap.bind("h",this._forceClustersByHub.bind(me));
  13991. // add the frame to the container element
  13992. this.containerElement.appendChild(this.frame);
  13993. };
  13994. /**
  13995. *
  13996. * @param {{x: Number, y: Number}} pointer
  13997. * @return {Number | null} node
  13998. * @private
  13999. */
  14000. Graph.prototype._getNodeAt = function (pointer) {
  14001. var x = this._canvasToX(pointer.x);
  14002. var y = this._canvasToY(pointer.y);
  14003. var obj = {
  14004. left: x,
  14005. top: y,
  14006. right: x,
  14007. bottom: y
  14008. };
  14009. // if there are overlapping nodes, select the last one, this is the
  14010. // one which is drawn on top of the others
  14011. var overlappingNodes = this._getNodesOverlappingWith(obj);
  14012. return (overlappingNodes.length > 0) ?
  14013. overlappingNodes[overlappingNodes.length - 1] : null;
  14014. };
  14015. /**
  14016. * Get the pointer location from a touch location
  14017. * @param {{pageX: Number, pageY: Number}} touch
  14018. * @return {{x: Number, y: Number}} pointer
  14019. * @private
  14020. */
  14021. Graph.prototype._getPointer = function (touch) {
  14022. return {
  14023. x: touch.pageX - vis.util.getAbsoluteLeft(this.frame.canvas),
  14024. y: touch.pageY - vis.util.getAbsoluteTop(this.frame.canvas)
  14025. };
  14026. };
  14027. /**
  14028. * On start of a touch gesture, store the pointer
  14029. * @param event
  14030. * @private
  14031. */
  14032. Graph.prototype._onTouch = function (event) {
  14033. this.drag.pointer = this._getPointer(event.gesture.touches[0]);
  14034. this.drag.pinched = false;
  14035. this.pinch.scale = this._getScale();
  14036. };
  14037. /**
  14038. * handle drag start event
  14039. * @private
  14040. */
  14041. Graph.prototype._onDragStart = function () {
  14042. var drag = this.drag;
  14043. drag.selection = [];
  14044. drag.translation = this._getTranslation();
  14045. drag.nodeId = this._getNodeAt(drag.pointer);
  14046. // note: drag.pointer is set in _onTouch to get the initial touch location
  14047. var node = this.nodes[drag.nodeId];
  14048. if (node) {
  14049. // select the clicked node if not yet selected
  14050. if (!node.isSelected()) {
  14051. this._selectNodes([drag.nodeId]);
  14052. }
  14053. // create an array with the selected nodes and their original location and status
  14054. var me = this;
  14055. this.selection.forEach(function (id) {
  14056. var node = me.nodes[id];
  14057. if (node) {
  14058. var s = {
  14059. id: id,
  14060. node: node,
  14061. // store original x, y, xFixed and yFixed, make the node temporarily Fixed
  14062. x: node.x,
  14063. y: node.y,
  14064. xFixed: node.xFixed,
  14065. yFixed: node.yFixed
  14066. };
  14067. node.xFixed = true;
  14068. node.yFixed = true;
  14069. drag.selection.push(s);
  14070. }
  14071. });
  14072. }
  14073. };
  14074. /**
  14075. * handle drag event
  14076. * @private
  14077. */
  14078. Graph.prototype._onDrag = function (event) {
  14079. if (this.drag.pinched) {
  14080. return;
  14081. }
  14082. var pointer = this._getPointer(event.gesture.touches[0]);
  14083. var me = this,
  14084. drag = this.drag,
  14085. selection = drag.selection;
  14086. if (selection && selection.length) {
  14087. // calculate delta's and new location
  14088. var deltaX = pointer.x - drag.pointer.x,
  14089. deltaY = pointer.y - drag.pointer.y;
  14090. // update position of all selected nodes
  14091. selection.forEach(function (s) {
  14092. var node = s.node;
  14093. if (!s.xFixed) {
  14094. node.x = me._canvasToX(me._xToCanvas(s.x) + deltaX);
  14095. }
  14096. if (!s.yFixed) {
  14097. node.y = me._canvasToY(me._yToCanvas(s.y) + deltaY);
  14098. }
  14099. });
  14100. // start animation if not yet running
  14101. if (!this.moving) {
  14102. this.moving = true;
  14103. this.start();
  14104. }
  14105. }
  14106. else {
  14107. // move the graph
  14108. var diffX = pointer.x - this.drag.pointer.x;
  14109. var diffY = pointer.y - this.drag.pointer.y;
  14110. this._setTranslation(
  14111. this.drag.translation.x + diffX,
  14112. this.drag.translation.y + diffY);
  14113. this._redraw();
  14114. this.moved = true;
  14115. }
  14116. };
  14117. /**
  14118. * handle drag start event
  14119. * @private
  14120. */
  14121. Graph.prototype._onDragEnd = function () {
  14122. var selection = this.drag.selection;
  14123. if (selection) {
  14124. selection.forEach(function (s) {
  14125. // restore original xFixed and yFixed
  14126. s.node.xFixed = s.xFixed;
  14127. s.node.yFixed = s.yFixed;
  14128. });
  14129. }
  14130. };
  14131. /**
  14132. * handle tap/click event: select/unselect a node
  14133. * @private
  14134. */
  14135. Graph.prototype._onTap = function (event) {
  14136. var pointer = this._getPointer(event.gesture.touches[0]);
  14137. var nodeId = this._getNodeAt(pointer);
  14138. var node = this.nodes[nodeId];
  14139. if (node) {
  14140. // select this node
  14141. this._selectNodes([nodeId]);
  14142. if (!this.moving) {
  14143. this._redraw();
  14144. }
  14145. }
  14146. else {
  14147. // remove selection
  14148. this._unselectNodes();
  14149. this._redraw();
  14150. }
  14151. };
  14152. /**
  14153. * handle long tap event: multi select nodes
  14154. * @private
  14155. */
  14156. Graph.prototype._onHold = function (event) {
  14157. var pointer = this._getPointer(event.gesture.touches[0]);
  14158. var nodeId = this._getNodeAt(pointer);
  14159. var node = this.nodes[nodeId];
  14160. if (node) {
  14161. if (!node.isSelected()) {
  14162. // select this node, keep previous selection
  14163. var append = true;
  14164. this._selectNodes([nodeId], append);
  14165. }
  14166. else {
  14167. this._unselectNodes([nodeId]);
  14168. }
  14169. if (!this.moving) {
  14170. this._redraw();
  14171. }
  14172. }
  14173. else {
  14174. // Do nothing
  14175. }
  14176. };
  14177. /**
  14178. * Handle pinch event
  14179. * @param event
  14180. * @private
  14181. */
  14182. Graph.prototype._onPinch = function (event) {
  14183. var pointer = this._getPointer(event.gesture.center);
  14184. this.drag.pinched = true;
  14185. if (!('scale' in this.pinch)) {
  14186. this.pinch.scale = 1;
  14187. }
  14188. // TODO: enable moving while pinching?
  14189. var scale = this.pinch.scale * event.gesture.scale;
  14190. this._zoom(scale, pointer)
  14191. };
  14192. /**
  14193. * Zoom the graph in or out
  14194. * @param {Number} scale a number around 1, and between 0.01 and 10
  14195. * @param {{x: Number, y: Number}} pointer
  14196. * @return {Number} appliedScale scale is limited within the boundaries
  14197. * @private
  14198. */
  14199. Graph.prototype._zoom = function(scale, pointer) {
  14200. var scaleOld = this._getScale();
  14201. if (scale < 0.01) {
  14202. scale = 0.01;
  14203. }
  14204. if (scale > 10) {
  14205. scale = 10;
  14206. }
  14207. // + this.frame.canvas.clientHeight / 2
  14208. var translation = this._getTranslation();
  14209. var scaleFrac = scale / scaleOld;
  14210. var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac;
  14211. var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac;
  14212. this.zoomCenter = {"x" : this._canvasToX(pointer.x),
  14213. "y" : this._canvasToY(pointer.y)};
  14214. // this.zoomCenter = {"x" : pointer.x,"y" : pointer.y };
  14215. this._setScale(scale);
  14216. this._setTranslation(tx, ty);
  14217. this._updateClusters();
  14218. this._redraw();
  14219. return scale;
  14220. };
  14221. /**
  14222. * Event handler for mouse wheel event, used to zoom the timeline
  14223. * See http://adomas.org/javascript-mouse-wheel/
  14224. * https://github.com/EightMedia/hammer.js/issues/256
  14225. * @param {MouseEvent} event
  14226. * @private
  14227. */
  14228. Graph.prototype._onMouseWheel = function(event) {
  14229. // retrieve delta
  14230. var delta = 0;
  14231. if (event.wheelDelta) { /* IE/Opera. */
  14232. delta = event.wheelDelta/120;
  14233. } else if (event.detail) { /* Mozilla case. */
  14234. // In Mozilla, sign of delta is different than in IE.
  14235. // Also, delta is multiple of 3.
  14236. delta = -event.detail/3;
  14237. }
  14238. // If delta is nonzero, handle it.
  14239. // Basically, delta is now positive if wheel was scrolled up,
  14240. // and negative, if wheel was scrolled down.
  14241. if (delta) {
  14242. if (!('mousewheelScale' in this.pinch)) {
  14243. this.pinch.mousewheelScale = 1;
  14244. }
  14245. // calculate the new scale
  14246. var scale = this.pinch.mousewheelScale;
  14247. var zoom = delta / 10;
  14248. if (delta < 0) {
  14249. zoom = zoom / (1 - zoom);
  14250. }
  14251. scale *= (1 + zoom);
  14252. // calculate the pointer location
  14253. var gesture = Hammer.event.collectEventData(this, 'scroll', event);
  14254. var pointer = this._getPointer(gesture.center);
  14255. // apply the new scale
  14256. scale = this._zoom(scale, pointer);
  14257. // store the new, applied scale
  14258. this.pinch.mousewheelScale = scale;
  14259. }
  14260. // Prevent default actions caused by mouse wheel.
  14261. event.preventDefault();
  14262. };
  14263. /**
  14264. * Mouse move handler for checking whether the title moves over a node with a title.
  14265. * @param {Event} event
  14266. * @private
  14267. */
  14268. Graph.prototype._onMouseMoveTitle = function (event) {
  14269. var gesture = Hammer.event.collectEventData(this, 'mousemove', event);
  14270. var pointer = this._getPointer(gesture.center);
  14271. // check if the previously selected node is still selected
  14272. if (this.popupNode) {
  14273. this._checkHidePopup(pointer);
  14274. }
  14275. // start a timeout that will check if the mouse is positioned above
  14276. // an element
  14277. var me = this;
  14278. var checkShow = function() {
  14279. me._checkShowPopup(pointer);
  14280. };
  14281. if (this.popupTimer) {
  14282. clearInterval(this.popupTimer); // stop any running timer
  14283. }
  14284. if (!this.leftButtonDown) {
  14285. this.popupTimer = setTimeout(checkShow, 300);
  14286. }
  14287. };
  14288. /**
  14289. * Check if there is an element on the given position in the graph
  14290. * (a node or edge). If so, and if this element has a title,
  14291. * show a popup window with its title.
  14292. *
  14293. * @param {{x:Number, y:Number}} pointer
  14294. * @private
  14295. */
  14296. Graph.prototype._checkShowPopup = function (pointer) {
  14297. var obj = {
  14298. left: this._canvasToX(pointer.x),
  14299. top: this._canvasToY(pointer.y),
  14300. right: this._canvasToX(pointer.x),
  14301. bottom: this._canvasToY(pointer.y)
  14302. };
  14303. var id;
  14304. var lastPopupNode = this.popupNode;
  14305. if (this.popupNode == undefined) {
  14306. // search the nodes for overlap, select the top one in case of multiple nodes
  14307. var nodes = this.nodes;
  14308. for (id in nodes) {
  14309. if (nodes.hasOwnProperty(id)) {
  14310. var node = nodes[id];
  14311. if (node.getTitle() != undefined && node.isOverlappingWith(obj)) {
  14312. this.popupNode = node;
  14313. break;
  14314. }
  14315. }
  14316. }
  14317. }
  14318. if (this.popupNode == undefined) {
  14319. // search the edges for overlap
  14320. var edges = this.edges;
  14321. for (id in edges) {
  14322. if (edges.hasOwnProperty(id)) {
  14323. var edge = edges[id];
  14324. if (edge.connected && (edge.getTitle() != undefined) &&
  14325. edge.isOverlappingWith(obj)) {
  14326. this.popupNode = edge;
  14327. break;
  14328. }
  14329. }
  14330. }
  14331. }
  14332. if (this.popupNode) {
  14333. // show popup message window
  14334. if (this.popupNode != lastPopupNode) {
  14335. var me = this;
  14336. if (!me.popup) {
  14337. me.popup = new Popup(me.frame);
  14338. }
  14339. // adjust a small offset such that the mouse cursor is located in the
  14340. // bottom left location of the popup, and you can easily move over the
  14341. // popup area
  14342. me.popup.setPosition(pointer.x - 3, pointer.y - 3);
  14343. me.popup.setText(me.popupNode.getTitle());
  14344. me.popup.show();
  14345. }
  14346. }
  14347. else {
  14348. if (this.popup) {
  14349. this.popup.hide();
  14350. }
  14351. }
  14352. };
  14353. /**
  14354. * Check if the popup must be hided, which is the case when the mouse is no
  14355. * longer hovering on the object
  14356. * @param {{x:Number, y:Number}} pointer
  14357. * @private
  14358. */
  14359. Graph.prototype._checkHidePopup = function (pointer) {
  14360. if (!this.popupNode || !this._getNodeAt(pointer) ) {
  14361. this.popupNode = undefined;
  14362. if (this.popup) {
  14363. this.popup.hide();
  14364. }
  14365. }
  14366. };
  14367. /**
  14368. * Unselect selected nodes. If no selection array is provided, all nodes
  14369. * are unselected
  14370. * @param {Object[]} selection Array with selection objects, each selection
  14371. * object has a parameter row. Optional
  14372. * @param {Boolean} triggerSelect If true (default), the select event
  14373. * is triggered when nodes are unselected
  14374. * @return {Boolean} changed True if the selection is changed
  14375. * @private
  14376. */
  14377. Graph.prototype._unselectNodes = function(selection, triggerSelect) {
  14378. var changed = false;
  14379. var i, iMax, id;
  14380. if (selection) {
  14381. // remove provided selections
  14382. for (i = 0, iMax = selection.length; i < iMax; i++) {
  14383. id = selection[i];
  14384. this.nodes[id].unselect();
  14385. var j = 0;
  14386. while (j < this.selection.length) {
  14387. if (this.selection[j] == id) {
  14388. this.selection.splice(j, 1);
  14389. changed = true;
  14390. }
  14391. else {
  14392. j++;
  14393. }
  14394. }
  14395. }
  14396. }
  14397. else if (this.selection && this.selection.length) {
  14398. // remove all selections
  14399. for (i = 0, iMax = this.selection.length; i < iMax; i++) {
  14400. id = this.selection[i];
  14401. this.nodes[id].unselect();
  14402. changed = true;
  14403. }
  14404. this.selection = [];
  14405. }
  14406. if (changed && (triggerSelect == true || triggerSelect == undefined)) {
  14407. // fire the select event
  14408. this._trigger('select');
  14409. }
  14410. return changed;
  14411. };
  14412. /**
  14413. * select all nodes on given location x, y
  14414. * @param {Array} selection an array with node ids
  14415. * @param {boolean} append If true, the new selection will be appended to the
  14416. * current selection (except for duplicate entries)
  14417. * @return {Boolean} changed True if the selection is changed
  14418. * @private
  14419. */
  14420. Graph.prototype._selectNodes = function(selection, append) {
  14421. var changed = false;
  14422. var i, iMax;
  14423. // TODO: the selectNodes method is a little messy, rework this
  14424. // check if the current selection equals the desired selection
  14425. var selectionAlreadyThere = true;
  14426. if (selection.length != this.selection.length) {
  14427. selectionAlreadyThere = false;
  14428. }
  14429. else {
  14430. for (i = 0, iMax = Math.min(selection.length, this.selection.length); i < iMax; i++) {
  14431. if (selection[i] != this.selection[i]) {
  14432. selectionAlreadyThere = false;
  14433. break;
  14434. }
  14435. }
  14436. }
  14437. if (selectionAlreadyThere) {
  14438. return changed;
  14439. }
  14440. if (append == undefined || append == false) {
  14441. // first deselect any selected node
  14442. var triggerSelect = false;
  14443. changed = this._unselectNodes(undefined, triggerSelect);
  14444. }
  14445. for (i = 0, iMax = selection.length; i < iMax; i++) {
  14446. // add each of the new selections, but only when they are not duplicate
  14447. var id = selection[i];
  14448. var isDuplicate = (this.selection.indexOf(id) != -1);
  14449. if (!isDuplicate) {
  14450. this.nodes[id].select();
  14451. this.selection.push(id);
  14452. changed = true;
  14453. }
  14454. }
  14455. if (changed) {
  14456. // fire the select event
  14457. this._trigger('select');
  14458. }
  14459. return changed;
  14460. };
  14461. /**
  14462. * retrieve all nodes overlapping with given object
  14463. * @param {Object} obj An object with parameters left, top, right, bottom
  14464. * @return {Number[]} An array with id's of the overlapping nodes
  14465. * @private
  14466. */
  14467. Graph.prototype._getNodesOverlappingWith = function (obj) {
  14468. var nodes = this.nodes,
  14469. overlappingNodes = [];
  14470. for (var id in nodes) {
  14471. if (nodes.hasOwnProperty(id)) {
  14472. if (nodes[id].isOverlappingWith(obj)) {
  14473. overlappingNodes.push(id);
  14474. }
  14475. }
  14476. }
  14477. return overlappingNodes;
  14478. };
  14479. /**
  14480. * retrieve the currently selected nodes
  14481. * @return {Number[] | String[]} selection An array with the ids of the
  14482. * selected nodes.
  14483. */
  14484. Graph.prototype.getSelection = function() {
  14485. return this.selection.concat([]);
  14486. };
  14487. /**
  14488. * select zero or more nodes
  14489. * @param {Number[] | String[]} selection An array with the ids of the
  14490. * selected nodes.
  14491. */
  14492. Graph.prototype.setSelection = function(selection) {
  14493. var i, iMax, id;
  14494. if (!selection || (selection.length == undefined))
  14495. throw 'Selection must be an array with ids';
  14496. // first unselect any selected node
  14497. for (i = 0, iMax = this.selection.length; i < iMax; i++) {
  14498. id = this.selection[i];
  14499. this.nodes[id].unselect();
  14500. }
  14501. this.selection = [];
  14502. for (i = 0, iMax = selection.length; i < iMax; i++) {
  14503. id = selection[i];
  14504. var node = this.nodes[id];
  14505. if (!node) {
  14506. throw new RangeError('Node with id "' + id + '" not found');
  14507. }
  14508. node.select();
  14509. this.selection.push(id);
  14510. }
  14511. this.redraw();
  14512. };
  14513. /**
  14514. * Validate the selection: remove ids of nodes which no longer exist
  14515. * @private
  14516. */
  14517. Graph.prototype._updateSelection = function () {
  14518. var i = 0;
  14519. while (i < this.selection.length) {
  14520. var id = this.selection[i];
  14521. if (!this.nodes[id]) {
  14522. this.selection.splice(i, 1);
  14523. }
  14524. else {
  14525. i++;
  14526. }
  14527. }
  14528. };
  14529. /**
  14530. * Temporary method to test calculating a hub value for the nodes
  14531. * @param {number} level Maximum number edges between two nodes in order
  14532. * to call them connected. Optional, 1 by default
  14533. * @return {Number[]} connectioncount array with the connection count
  14534. * for each node
  14535. * @private
  14536. */
  14537. Graph.prototype._getConnectionCount = function(level) {
  14538. if (level == undefined) {
  14539. level = 1;
  14540. }
  14541. // get the nodes connected to given nodes
  14542. function getConnectedNodes(nodes) {
  14543. var connectedNodes = [];
  14544. for (var j = 0, jMax = nodes.length; j < jMax; j++) {
  14545. var node = nodes[j];
  14546. // find all nodes connected to this node
  14547. var edges = node.edges;
  14548. for (var i = 0, iMax = edges.length; i < iMax; i++) {
  14549. var edge = edges[i];
  14550. var other = null;
  14551. // check if connected
  14552. if (edge.from == node)
  14553. other = edge.to;
  14554. else if (edge.to == node)
  14555. other = edge.from;
  14556. // check if the other node is not already in the list with nodes
  14557. var k, kMax;
  14558. if (other) {
  14559. for (k = 0, kMax = nodes.length; k < kMax; k++) {
  14560. if (nodes[k] == other) {
  14561. other = null;
  14562. break;
  14563. }
  14564. }
  14565. }
  14566. if (other) {
  14567. for (k = 0, kMax = connectedNodes.length; k < kMax; k++) {
  14568. if (connectedNodes[k] == other) {
  14569. other = null;
  14570. break;
  14571. }
  14572. }
  14573. }
  14574. if (other)
  14575. connectedNodes.push(other);
  14576. }
  14577. }
  14578. return connectedNodes;
  14579. }
  14580. var connections = [];
  14581. var nodes = this.nodes;
  14582. for (var id in nodes) {
  14583. if (nodes.hasOwnProperty(id)) {
  14584. var c = [nodes[id]];
  14585. for (var l = 0; l < level; l++) {
  14586. c = c.concat(getConnectedNodes(c));
  14587. }
  14588. connections.push(c);
  14589. }
  14590. }
  14591. var hubs = [];
  14592. for (var i = 0, len = connections.length; i < len; i++) {
  14593. hubs.push(connections[i].length);
  14594. }
  14595. return hubs;
  14596. };
  14597. /**
  14598. * Set a new size for the graph
  14599. * @param {string} width Width in pixels or percentage (for example '800px'
  14600. * or '50%')
  14601. * @param {string} height Height in pixels or percentage (for example '400px'
  14602. * or '30%')
  14603. */
  14604. Graph.prototype.setSize = function(width, height) {
  14605. this.frame.style.width = width;
  14606. this.frame.style.height = height;
  14607. this.frame.canvas.style.width = '100%';
  14608. this.frame.canvas.style.height = '100%';
  14609. this.frame.canvas.width = this.frame.canvas.clientWidth;
  14610. this.frame.canvas.height = this.frame.canvas.clientHeight;
  14611. };
  14612. /**
  14613. * Set a data set with nodes for the graph
  14614. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  14615. * @private
  14616. */
  14617. Graph.prototype._setNodes = function(nodes) {
  14618. var oldNodesData = this.nodesData;
  14619. if (nodes instanceof DataSet || nodes instanceof DataView) {
  14620. this.nodesData = nodes;
  14621. }
  14622. else if (nodes instanceof Array) {
  14623. this.nodesData = new DataSet();
  14624. this.nodesData.add(nodes);
  14625. }
  14626. else if (!nodes) {
  14627. this.nodesData = new DataSet();
  14628. }
  14629. else {
  14630. throw new TypeError('Array or DataSet expected');
  14631. }
  14632. if (oldNodesData) {
  14633. // unsubscribe from old dataset
  14634. util.forEach(this.nodesListeners, function (callback, event) {
  14635. oldNodesData.unsubscribe(event, callback);
  14636. });
  14637. }
  14638. // remove drawn nodes
  14639. this.nodes = {};
  14640. if (this.nodesData) {
  14641. // subscribe to new dataset
  14642. var me = this;
  14643. util.forEach(this.nodesListeners, function (callback, event) {
  14644. me.nodesData.subscribe(event, callback);
  14645. });
  14646. // draw all new nodes
  14647. var ids = this.nodesData.getIds();
  14648. this._addNodes(ids);
  14649. }
  14650. this._updateSelection();
  14651. };
  14652. /**
  14653. * Add nodes
  14654. * @param {Number[] | String[]} ids
  14655. * @private
  14656. */
  14657. Graph.prototype._addNodes = function(ids) {
  14658. var id;
  14659. for (var i = 0, len = ids.length; i < len; i++) {
  14660. id = ids[i];
  14661. var data = this.nodesData.get(id);
  14662. var node = new Node(data, this.images, this.groups, this.constants);
  14663. this.nodes[id] = node; // note: this may replace an existing node
  14664. if (!node.isFixed()) {
  14665. // TODO: position new nodes in a smarter way!
  14666. var radius = this.constants.edges.length * 2;
  14667. var count = ids.length;
  14668. var angle = 2 * Math.PI * (i / count);
  14669. node.x = radius * Math.cos(angle);
  14670. node.y = radius * Math.sin(angle);
  14671. // note: no not use node.isMoving() here, as that gives the current
  14672. // velocity of the node, which is zero after creation of the node.
  14673. this.moving = true;
  14674. }
  14675. }
  14676. this._updateNodeIndexList();
  14677. this._reconnectEdges();
  14678. this._updateValueRange(this.nodes);
  14679. };
  14680. /**
  14681. * Update existing nodes, or create them when not yet existing
  14682. * @param {Number[] | String[]} ids
  14683. * @private
  14684. */
  14685. Graph.prototype._updateNodes = function(ids) {
  14686. var nodes = this.nodes,
  14687. nodesData = this.nodesData;
  14688. for (var i = 0, len = ids.length; i < len; i++) {
  14689. var id = ids[i];
  14690. var node = nodes[id];
  14691. var data = nodesData.get(id);
  14692. if (node) {
  14693. // update node
  14694. node.setProperties(data, this.constants);
  14695. }
  14696. else {
  14697. // create node
  14698. node = new Node(properties, this.images, this.groups, this.constants);
  14699. nodes[id] = node;
  14700. if (!node.isFixed()) {
  14701. this.moving = true;
  14702. }
  14703. }
  14704. }
  14705. this._updateNodeIndexList();
  14706. this._reconnectEdges();
  14707. this._updateValueRange(nodes);
  14708. };
  14709. /**
  14710. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  14711. * @param {Number[] | String[]} ids
  14712. * @private
  14713. */
  14714. Graph.prototype._removeNodes = function(ids) {
  14715. var nodes = this.nodes;
  14716. for (var i = 0, len = ids.length; i < len; i++) {
  14717. var id = ids[i];
  14718. delete nodes[id];
  14719. }
  14720. this._updateNodeIndexList();
  14721. this._reconnectEdges();
  14722. this._updateSelection();
  14723. this._updateValueRange(nodes);
  14724. };
  14725. /**
  14726. * Load edges by reading the data table
  14727. * @param {Array | DataSet | DataView} edges The data containing the edges.
  14728. * @private
  14729. * @private
  14730. */
  14731. Graph.prototype._setEdges = function(edges) {
  14732. var oldEdgesData = this.edgesData;
  14733. if (edges instanceof DataSet || edges instanceof DataView) {
  14734. this.edgesData = edges;
  14735. }
  14736. else if (edges instanceof Array) {
  14737. this.edgesData = new DataSet();
  14738. this.edgesData.add(edges);
  14739. }
  14740. else if (!edges) {
  14741. this.edgesData = new DataSet();
  14742. }
  14743. else {
  14744. throw new TypeError('Array or DataSet expected');
  14745. }
  14746. if (oldEdgesData) {
  14747. // unsubscribe from old dataset
  14748. util.forEach(this.edgesListeners, function (callback, event) {
  14749. oldEdgesData.unsubscribe(event, callback);
  14750. });
  14751. }
  14752. // remove drawn edges
  14753. this.edges = {};
  14754. if (this.edgesData) {
  14755. // subscribe to new dataset
  14756. var me = this;
  14757. util.forEach(this.edgesListeners, function (callback, event) {
  14758. me.edgesData.subscribe(event, callback);
  14759. });
  14760. // draw all new nodes
  14761. var ids = this.edgesData.getIds();
  14762. this._addEdges(ids);
  14763. }
  14764. this._reconnectEdges();
  14765. };
  14766. /**
  14767. * Add edges
  14768. * @param {Number[] | String[]} ids
  14769. * @private
  14770. */
  14771. Graph.prototype._addEdges = function (ids) {
  14772. var edges = this.edges,
  14773. edgesData = this.edgesData;
  14774. for (var i = 0, len = ids.length; i < len; i++) {
  14775. var id = ids[i];
  14776. var oldEdge = edges[id];
  14777. if (oldEdge) {
  14778. oldEdge.disconnect();
  14779. }
  14780. var data = edgesData.get(id, {"showInternalIds" : true});
  14781. edges[id] = new Edge(data, this, this.constants);
  14782. }
  14783. this.moving = true;
  14784. this._updateValueRange(edges);
  14785. };
  14786. /**
  14787. * Update existing edges, or create them when not yet existing
  14788. * @param {Number[] | String[]} ids
  14789. * @private
  14790. */
  14791. Graph.prototype._updateEdges = function (ids) {
  14792. var edges = this.edges,
  14793. edgesData = this.edgesData;
  14794. for (var i = 0, len = ids.length; i < len; i++) {
  14795. var id = ids[i];
  14796. var data = edgesData.get(id);
  14797. var edge = edges[id];
  14798. if (edge) {
  14799. // update edge
  14800. edge.disconnect();
  14801. edge.setProperties(data, this.constants);
  14802. edge.connect();
  14803. }
  14804. else {
  14805. // create edge
  14806. edge = new Edge(data, this, this.constants);
  14807. this.edges[id] = edge;
  14808. }
  14809. }
  14810. this.moving = true;
  14811. this._updateValueRange(edges);
  14812. };
  14813. /**
  14814. * Remove existing edges. Non existing ids will be ignored
  14815. * @param {Number[] | String[]} ids
  14816. * @private
  14817. */
  14818. Graph.prototype._removeEdges = function (ids) {
  14819. var edges = this.edges;
  14820. for (var i = 0, len = ids.length; i < len; i++) {
  14821. var id = ids[i];
  14822. var edge = edges[id];
  14823. if (edge) {
  14824. edge.disconnect();
  14825. delete edges[id];
  14826. }
  14827. }
  14828. this.moving = true;
  14829. this._updateValueRange(edges);
  14830. };
  14831. /**
  14832. * Reconnect all edges
  14833. * @private
  14834. */
  14835. Graph.prototype._reconnectEdges = function() {
  14836. var id,
  14837. nodes = this.nodes,
  14838. edges = this.edges;
  14839. for (id in nodes) {
  14840. if (nodes.hasOwnProperty(id)) {
  14841. nodes[id].edges = [];
  14842. }
  14843. }
  14844. for (id in edges) {
  14845. if (edges.hasOwnProperty(id)) {
  14846. var edge = edges[id];
  14847. edge.from = null;
  14848. edge.to = null;
  14849. edge.connect();
  14850. }
  14851. }
  14852. };
  14853. /**
  14854. * Update the values of all object in the given array according to the current
  14855. * value range of the objects in the array.
  14856. * @param {Object} obj An object containing a set of Edges or Nodes
  14857. * The objects must have a method getValue() and
  14858. * setValueRange(min, max).
  14859. * @private
  14860. */
  14861. Graph.prototype._updateValueRange = function(obj) {
  14862. var id;
  14863. // determine the range of the objects
  14864. var valueMin = undefined;
  14865. var valueMax = undefined;
  14866. for (id in obj) {
  14867. if (obj.hasOwnProperty(id)) {
  14868. var value = obj[id].getValue();
  14869. if (value !== undefined) {
  14870. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  14871. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  14872. }
  14873. }
  14874. }
  14875. // adjust the range of all objects
  14876. if (valueMin !== undefined && valueMax !== undefined) {
  14877. for (id in obj) {
  14878. if (obj.hasOwnProperty(id)) {
  14879. obj[id].setValueRange(valueMin, valueMax);
  14880. }
  14881. }
  14882. }
  14883. };
  14884. /**
  14885. * Redraw the graph with the current data
  14886. * chart will be resized too.
  14887. */
  14888. Graph.prototype.redraw = function() {
  14889. this.setSize(this.width, this.height);
  14890. this._redraw();
  14891. };
  14892. /**
  14893. * Redraw the graph with the current data
  14894. * @private
  14895. */
  14896. Graph.prototype._redraw = function() {
  14897. var ctx = this.frame.canvas.getContext('2d');
  14898. // clear the canvas
  14899. var w = this.frame.canvas.width;
  14900. var h = this.frame.canvas.height;
  14901. ctx.clearRect(0, 0, w, h);
  14902. // set scaling and translation
  14903. ctx.save();
  14904. ctx.translate(this.translation.x, this.translation.y);
  14905. ctx.scale(this.scale, this.scale);
  14906. this._drawEdges(ctx);
  14907. this._drawNodes(ctx);
  14908. // restore original scaling and translation
  14909. ctx.restore();
  14910. };
  14911. /**
  14912. * Set the translation of the graph
  14913. * @param {Number} offsetX Horizontal offset
  14914. * @param {Number} offsetY Vertical offset
  14915. * @private
  14916. */
  14917. Graph.prototype._setTranslation = function(offsetX, offsetY) {
  14918. if (this.translation === undefined) {
  14919. this.translation = {
  14920. x: 0,
  14921. y: 0
  14922. };
  14923. }
  14924. if (offsetX !== undefined) {
  14925. this.translation.x = offsetX;
  14926. }
  14927. if (offsetY !== undefined) {
  14928. this.translation.y = offsetY;
  14929. }
  14930. };
  14931. /**
  14932. * Get the translation of the graph
  14933. * @return {Object} translation An object with parameters x and y, both a number
  14934. * @private
  14935. */
  14936. Graph.prototype._getTranslation = function() {
  14937. return {
  14938. x: this.translation.x,
  14939. y: this.translation.y
  14940. };
  14941. };
  14942. /**
  14943. * Scale the graph
  14944. * @param {Number} scale Scaling factor 1.0 is unscaled
  14945. * @private
  14946. */
  14947. Graph.prototype._setScale = function(scale) {
  14948. this.scale = scale;
  14949. };
  14950. /**
  14951. * Get the current scale of the graph
  14952. * @return {Number} scale Scaling factor 1.0 is unscaled
  14953. * @private
  14954. */
  14955. Graph.prototype._getScale = function() {
  14956. return this.scale;
  14957. };
  14958. /**
  14959. * Convert a horizontal point on the HTML canvas to the x-value of the model
  14960. * @param {number} x
  14961. * @returns {number}
  14962. * @private
  14963. */
  14964. Graph.prototype._canvasToX = function(x) {
  14965. return (x - this.translation.x) / this.scale;
  14966. };
  14967. /**
  14968. * Convert an x-value in the model to a horizontal point on the HTML canvas
  14969. * @param {number} x
  14970. * @returns {number}
  14971. * @private
  14972. */
  14973. Graph.prototype._xToCanvas = function(x) {
  14974. return x * this.scale + this.translation.x;
  14975. };
  14976. /**
  14977. * Convert a vertical point on the HTML canvas to the y-value of the model
  14978. * @param {number} y
  14979. * @returns {number}
  14980. * @private
  14981. */
  14982. Graph.prototype._canvasToY = function(y) {
  14983. return (y - this.translation.y) / this.scale;
  14984. };
  14985. /**
  14986. * Convert an y-value in the model to a vertical point on the HTML canvas
  14987. * @param {number} y
  14988. * @returns {number}
  14989. * @private
  14990. */
  14991. Graph.prototype._yToCanvas = function(y) {
  14992. return y * this.scale + this.translation.y ;
  14993. };
  14994. /**
  14995. * Redraw all nodes
  14996. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  14997. * @param {CanvasRenderingContext2D} ctx
  14998. * @private
  14999. */
  15000. Graph.prototype._drawNodes = function(ctx) {
  15001. // first draw the unselected nodes
  15002. var nodes = this.nodes;
  15003. var selected = [];
  15004. for (var id in nodes) {
  15005. if (nodes.hasOwnProperty(id)) {
  15006. if (nodes[id].isSelected()) {
  15007. selected.push(id);
  15008. }
  15009. else {
  15010. nodes[id].draw(ctx);
  15011. }
  15012. }
  15013. }
  15014. // draw the selected nodes on top
  15015. for (var s = 0, sMax = selected.length; s < sMax; s++) {
  15016. nodes[selected[s]].draw(ctx);
  15017. }
  15018. };
  15019. /**
  15020. * Redraw all edges
  15021. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  15022. * @param {CanvasRenderingContext2D} ctx
  15023. * @private
  15024. */
  15025. Graph.prototype._drawEdges = function(ctx) {
  15026. var edges = this.edges;
  15027. for (var id in edges) {
  15028. if (edges.hasOwnProperty(id)) {
  15029. var edge = edges[id];
  15030. if (edge.connected) {
  15031. edges[id].draw(ctx);
  15032. }
  15033. }
  15034. }
  15035. };
  15036. /**
  15037. * Find a stable position for all nodes
  15038. * @private
  15039. */
  15040. Graph.prototype._doStabilize = function() {
  15041. var start = new Date();
  15042. // find stable position
  15043. var count = 0;
  15044. var vmin = this.constants.minVelocity;
  15045. var stable = false;
  15046. while (!stable && count < this.constants.maxIterations) {
  15047. this._calculateForces();
  15048. this._discreteStepNodes();
  15049. stable = !this._isMoving(vmin);
  15050. count++;
  15051. }
  15052. var end = new Date();
  15053. // console.log('Stabilized in ' + (end-start) + ' ms, ' + count + ' iterations' ); // TODO: cleanup
  15054. };
  15055. /**
  15056. * Calculate the external forces acting on the nodes
  15057. * Forces are caused by: edges, repulsing forces between nodes, gravity
  15058. * @private
  15059. */
  15060. Graph.prototype._calculateForces = function() {
  15061. // create a local edge to the nodes and edges, that is faster
  15062. var id, dx, dy, angle, distance, fx, fy,
  15063. repulsingForce, springForce, length, edgeLength,
  15064. nodes = this.nodes,
  15065. edges = this.edges;
  15066. // gravity, add a small constant force to pull the nodes towards the center of
  15067. // the graph
  15068. // Also, the forces are reset to zero in this loop by using _setForce instead
  15069. // of _addForce
  15070. var gravity = 0.05;
  15071. for (id in nodes) {
  15072. if (nodes.hasOwnProperty(id)) {
  15073. var node = nodes[id];
  15074. dx = -node.x;
  15075. dy = -node.y;
  15076. angle = Math.atan2(dy, dx);
  15077. fx = Math.cos(angle) * gravity;
  15078. fy = Math.sin(angle) * gravity;
  15079. node._setForce(fx, fy);
  15080. }
  15081. }
  15082. // repulsing forces between nodes
  15083. var minimumDistance = this.constants.nodes.distance,
  15084. steepness = 10; // higher value gives steeper slope of the force around the given minimumDistance
  15085. // we loop from i over all but the last entree in the array
  15086. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  15087. for (var i = 0; i < this.nodeIndices.length-1; i++) {
  15088. var node1 = nodes[this.nodeIndices[i]];
  15089. for (var j = i+1; j < this.nodeIndices.length; j++) {
  15090. var node2 = nodes[this.nodeIndices[j]];
  15091. var clusterSize = (node1.clusterSize + node2.clusterSize - 2);
  15092. dx = node2.x - node1.x;
  15093. dy = node2.y - node1.y;
  15094. distance = Math.sqrt(dx * dx + dy * dy);
  15095. // clusters have a larger region of influence
  15096. minimumDistance = (clusterSize == 0) ? this.constants.nodes.distance : (this.constants.nodes.distance * (1 + clusterSize * this.constants.clustering.distanceAmplification));
  15097. if (distance < 2*minimumDistance) { // at 2.0 * the minimum distance, the force is 0.000045
  15098. angle = Math.atan2(dy, dx);
  15099. if (distance < 0.5*minimumDistance) { // at 0.5 * the minimum distance, the force is 0.993307
  15100. repulsingForce = 1.0;
  15101. }
  15102. else {
  15103. // TODO: correct factor for repulsing force
  15104. //repulsingForce = 2 * Math.exp(-5 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  15105. //repulsingForce = Math.exp(-1 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  15106. repulsingForce = 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness)); // TODO: customize the repulsing force
  15107. }
  15108. // amplify the repulsion for clusters.
  15109. repulsingForce *= (clusterSize == 0) ? 1 : 1 + clusterSize * this.constants.clustering.forceAmplification;
  15110. fx = Math.cos(angle) * repulsingForce;
  15111. fy = Math.sin(angle) * repulsingForce;
  15112. node1._addForce(-fx, -fy);
  15113. node2._addForce(fx, fy);
  15114. }
  15115. }
  15116. }
  15117. /* TODO: re-implement repulsion of edges
  15118. for (var n = 0; n < nodes.length; n++) {
  15119. for (var l = 0; l < edges.length; l++) {
  15120. var lx = edges[l].from.x+(edges[l].to.x - edges[l].from.x)/2,
  15121. ly = edges[l].from.y+(edges[l].to.y - edges[l].from.y)/2,
  15122. // calculate normally distributed force
  15123. dx = nodes[n].x - lx,
  15124. dy = nodes[n].y - ly,
  15125. distance = Math.sqrt(dx * dx + dy * dy),
  15126. angle = Math.atan2(dy, dx),
  15127. // TODO: correct factor for repulsing force
  15128. //var repulsingforce = 2 * Math.exp(-5 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  15129. //repulsingforce = Math.exp(-1 * (distance * distance) / (dmin * dmin) ), // TODO: customize the repulsing force
  15130. repulsingforce = 1 / (1 + Math.exp((distance / (minimumDistance / 2) - 1) * steepness)), // TODO: customize the repulsing force
  15131. fx = Math.cos(angle) * repulsingforce,
  15132. fy = Math.sin(angle) * repulsingforce;
  15133. nodes[n]._addForce(fx, fy);
  15134. edges[l].from._addForce(-fx/2,-fy/2);
  15135. edges[l].to._addForce(-fx/2,-fy/2);
  15136. }
  15137. }
  15138. */
  15139. // forces caused by the edges, modelled as springs
  15140. for (id in edges) {
  15141. if (edges.hasOwnProperty(id)) {
  15142. var edge = edges[id];
  15143. if (edge.connected) {
  15144. dx = (edge.to.x - edge.from.x);
  15145. dy = (edge.to.y - edge.from.y);
  15146. //edgeLength = (edge.from.width + edge.from.height + edge.to.width + edge.to.height)/2 || edge.length; // TODO: dmin
  15147. //edgeLength = (edge.from.width + edge.to.width)/2 || edge.length; // TODO: dmin
  15148. //edgeLength = 20 + ((edge.from.width + edge.to.width) || 0) / 2;
  15149. edgeLength = edge.length;
  15150. // this implies that the edges between big clusters are longer
  15151. edgeLength += (edge.to.clusterSize + edge.from.clusterSize - 2) * this.constants.clustering.edgeGrowth;
  15152. length = Math.sqrt(dx * dx + dy * dy);
  15153. angle = Math.atan2(dy, dx);
  15154. springForce = edge.stiffness * (edgeLength - length);
  15155. fx = Math.cos(angle) * springForce;
  15156. fy = Math.sin(angle) * springForce;
  15157. edge.from._addForce(-fx, -fy);
  15158. edge.to._addForce(fx, fy);
  15159. }
  15160. }
  15161. }
  15162. /*
  15163. // TODO: re-implement repulsion of edges
  15164. // repulsing forces between edges
  15165. var minimumDistance = this.constants.edges.distance,
  15166. steepness = 10; // higher value gives steeper slope of the force around the given minimumDistance
  15167. for (var l = 0; l < edges.length; l++) {
  15168. //Keep distance from other edge centers
  15169. for (var l2 = l + 1; l2 < this.edges.length; l2++) {
  15170. //var dmin = (nodes[n].width + nodes[n].height + nodes[n2].width + nodes[n2].height) / 1 || minimumDistance, // TODO: dmin
  15171. //var dmin = (nodes[n].width + nodes[n2].width)/2 || minimumDistance, // TODO: dmin
  15172. //dmin = 40 + ((nodes[n].width/2 + nodes[n2].width/2) || 0),
  15173. var lx = edges[l].from.x+(edges[l].to.x - edges[l].from.x)/2,
  15174. ly = edges[l].from.y+(edges[l].to.y - edges[l].from.y)/2,
  15175. l2x = edges[l2].from.x+(edges[l2].to.x - edges[l2].from.x)/2,
  15176. l2y = edges[l2].from.y+(edges[l2].to.y - edges[l2].from.y)/2,
  15177. // calculate normally distributed force
  15178. dx = l2x - lx,
  15179. dy = l2y - ly,
  15180. distance = Math.sqrt(dx * dx + dy * dy),
  15181. angle = Math.atan2(dy, dx),
  15182. // TODO: correct factor for repulsing force
  15183. //var repulsingforce = 2 * Math.exp(-5 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  15184. //repulsingforce = Math.exp(-1 * (distance * distance) / (dmin * dmin) ), // TODO: customize the repulsing force
  15185. repulsingforce = 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness)), // TODO: customize the repulsing force
  15186. fx = Math.cos(angle) * repulsingforce,
  15187. fy = Math.sin(angle) * repulsingforce;
  15188. edges[l].from._addForce(-fx, -fy);
  15189. edges[l].to._addForce(-fx, -fy);
  15190. edges[l2].from._addForce(fx, fy);
  15191. edges[l2].to._addForce(fx, fy);
  15192. }
  15193. }
  15194. */
  15195. this.simulationStep += 1;
  15196. };
  15197. /**
  15198. * Check if any of the nodes is still moving
  15199. * @param {number} vmin the minimum velocity considered as 'moving'
  15200. * @return {boolean} true if moving, false if non of the nodes is moving
  15201. * @private
  15202. */
  15203. Graph.prototype._isMoving = function(vmin) {
  15204. // TODO: ismoving does not work well: should check the kinetic energy, not its velocity
  15205. var nodes = this.nodes;
  15206. for (var id in nodes) {
  15207. if (nodes.hasOwnProperty(id) && nodes[id].isMoving(vmin)) {
  15208. return true;
  15209. }
  15210. }
  15211. return false;
  15212. };
  15213. /**
  15214. * Perform one discrete step for all nodes
  15215. * @private
  15216. */
  15217. Graph.prototype._discreteStepNodes = function() {
  15218. var interval = this.refreshRate / 1000.0; // in seconds
  15219. var nodes = this.nodes;
  15220. for (var id in nodes) {
  15221. if (nodes.hasOwnProperty(id)) {
  15222. nodes[id].discreteStep(interval);
  15223. }
  15224. }
  15225. };
  15226. /**
  15227. * Start animating nodes and edges
  15228. */
  15229. Graph.prototype.start = function() {
  15230. if (this.moving) {
  15231. this._calculateForces();
  15232. this._discreteStepNodes();
  15233. var vmin = this.constants.minVelocity;
  15234. this.moving = this._isMoving(vmin);
  15235. }
  15236. if (this.moving) {
  15237. // start animation. only start timer if it is not already running
  15238. if (!this.timer) {
  15239. var graph = this;
  15240. this.timer = window.setTimeout(function () {
  15241. graph.timer = undefined;
  15242. // benchmark the calculation
  15243. // var start = window.performance.now();
  15244. graph.start();
  15245. // Optionally call this twice for faster convergence
  15246. // graph.start();
  15247. // var end = window.performance.now();
  15248. // var time = end - start;
  15249. // console.log('Simulation time: ' + time);
  15250. // start = window.performance.now();
  15251. graph._redraw();
  15252. // end = window.performance.now();
  15253. // time = end - start;
  15254. // console.log('Drawing time: ' + time);
  15255. }, this.refreshRate);
  15256. }
  15257. }
  15258. else {
  15259. this._redraw();
  15260. }
  15261. };
  15262. Graph.prototype.singleStep = function() {
  15263. if (this.moving) {
  15264. this._calculateForces();
  15265. this._discreteStepNodes();
  15266. var vmin = this.constants.minVelocity;
  15267. this.moving = this._isMoving(vmin);
  15268. this._redraw();
  15269. }
  15270. };
  15271. /**
  15272. * Stop animating nodes and edges.
  15273. */
  15274. Graph.prototype.stop = function () {
  15275. if (this.timer) {
  15276. window.clearInterval(this.timer);
  15277. this.timer = undefined;
  15278. }
  15279. };
  15280. /**
  15281. * vis.js module exports
  15282. */
  15283. var vis = {
  15284. util: util,
  15285. events: events,
  15286. Controller: Controller,
  15287. DataSet: DataSet,
  15288. DataView: DataView,
  15289. Range: Range,
  15290. Stack: Stack,
  15291. TimeStep: TimeStep,
  15292. EventBus: EventBus,
  15293. components: {
  15294. items: {
  15295. Item: Item,
  15296. ItemBox: ItemBox,
  15297. ItemPoint: ItemPoint,
  15298. ItemRange: ItemRange
  15299. },
  15300. Component: Component,
  15301. Panel: Panel,
  15302. RootPanel: RootPanel,
  15303. ItemSet: ItemSet,
  15304. TimeAxis: TimeAxis
  15305. },
  15306. graph: {
  15307. Node: Node,
  15308. Edge: Edge,
  15309. Popup: Popup,
  15310. Groups: Groups,
  15311. Images: Images
  15312. },
  15313. Timeline: Timeline,
  15314. Graph: Graph
  15315. };
  15316. /**
  15317. * CommonJS module exports
  15318. */
  15319. if (typeof exports !== 'undefined') {
  15320. exports = vis;
  15321. }
  15322. if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  15323. module.exports = vis;
  15324. }
  15325. /**
  15326. * AMD module exports
  15327. */
  15328. if (typeof(define) === 'function') {
  15329. define(function () {
  15330. return vis;
  15331. });
  15332. }
  15333. /**
  15334. * Window exports
  15335. */
  15336. if (typeof window !== 'undefined') {
  15337. // attach the module to the window, load as a regular javascript file
  15338. window['vis'] = vis;
  15339. }
  15340. // inject css
  15341. util.loadCss("/* vis.js stylesheet */\n.vis.timeline {\r\n}\r\n\n\r\n.vis.timeline.rootpanel {\r\n position: relative;\r\n overflow: hidden;\r\n\r\n border: 1px solid #bfbfbf;\r\n -moz-box-sizing: border-box;\r\n box-sizing: border-box;\r\n}\r\n\r\n.vis.timeline .panel {\r\n position: absolute;\r\n overflow: hidden;\r\n}\r\n\n\r\n.vis.timeline .groupset {\r\n position: absolute;\r\n padding: 0;\r\n margin: 0;\r\n}\r\n\r\n.vis.timeline .labels {\r\n position: absolute;\r\n top: 0;\r\n left: 0;\r\n width: 100%;\r\n height: 100%;\r\n\r\n padding: 0;\r\n margin: 0;\r\n\r\n border-right: 1px solid #bfbfbf;\r\n box-sizing: border-box;\r\n -moz-box-sizing: border-box;\r\n}\r\n\r\n.vis.timeline .labels .label-set {\r\n position: absolute;\r\n top: 0;\r\n left: 0;\r\n width: 100%;\r\n height: 100%;\r\n\r\n overflow: hidden;\r\n\r\n border-top: none;\r\n border-bottom: 1px solid #bfbfbf;\r\n}\r\n\r\n.vis.timeline .labels .label-set .label {\r\n position: absolute;\r\n left: 0;\r\n top: 0;\r\n width: 100%;\r\n color: #4d4d4d;\r\n}\r\n\r\n.vis.timeline.top .labels .label-set .label,\r\n.vis.timeline.top .groupset .itemset-axis {\r\n border-top: 1px solid #bfbfbf;\r\n border-bottom: none;\r\n}\r\n\r\n.vis.timeline.bottom .labels .label-set .label,\r\n.vis.timeline.bottom .groupset .itemset-axis {\r\n border-top: none;\r\n border-bottom: 1px solid #bfbfbf;\r\n}\r\n\r\n.vis.timeline .labels .label-set .label .inner {\r\n display: inline-block;\r\n padding: 5px;\r\n}\r\n\n\r\n.vis.timeline .itemset {\r\n position: absolute;\r\n padding: 0;\r\n margin: 0;\r\n overflow: hidden;\r\n}\r\n\r\n.vis.timeline .background {\r\n}\r\n\r\n.vis.timeline .foreground {\r\n}\r\n\r\n.vis.timeline .itemset-axis {\r\n position: absolute;\r\n}\r\n\n\r\n.vis.timeline .item {\r\n position: absolute;\r\n color: #1A1A1A;\r\n border-color: #97B0F8;\r\n background-color: #D5DDF6;\r\n display: inline-block;\r\n}\r\n\r\n.vis.timeline .item.selected {\r\n border-color: #FFC200;\r\n background-color: #FFF785;\r\n z-index: 999;\r\n}\r\n\r\n.vis.timeline .item.cluster {\r\n /* TODO: use another color or pattern? */\r\n background: #97B0F8 url('img/cluster_bg.png');\r\n color: white;\r\n}\r\n.vis.timeline .item.cluster.point {\r\n border-color: #D5DDF6;\r\n}\r\n\r\n.vis.timeline .item.box {\r\n text-align: center;\r\n border-style: solid;\r\n border-width: 1px;\r\n border-radius: 5px;\r\n -moz-border-radius: 5px; /* For Firefox 3.6 and older */\r\n}\r\n\r\n.vis.timeline .item.point {\r\n background: none;\r\n}\r\n\r\n.vis.timeline .dot {\r\n border: 5px solid #97B0F8;\r\n position: absolute;\r\n border-radius: 5px;\r\n -moz-border-radius: 5px; /* For Firefox 3.6 and older */\r\n}\r\n\r\n.vis.timeline .item.range {\r\n overflow: hidden;\r\n border-style: solid;\r\n border-width: 1px;\r\n border-radius: 2px;\r\n -moz-border-radius: 2px; /* For Firefox 3.6 and older */\r\n}\r\n\r\n.vis.timeline .item.rangeoverflow {\r\n border-style: solid;\r\n border-width: 1px;\r\n border-radius: 2px;\r\n -moz-border-radius: 2px; /* For Firefox 3.6 and older */\r\n}\r\n\r\n.vis.timeline .item.range .drag-left, .vis.timeline .item.rangeoverflow .drag-left {\r\n cursor: w-resize;\r\n z-index: 1000;\r\n}\r\n\r\n.vis.timeline .item.range .drag-right, .vis.timeline .item.rangeoverflow .drag-right {\r\n cursor: e-resize;\r\n z-index: 1000;\r\n}\r\n\r\n.vis.timeline .item.range .content, .vis.timeline .item.rangeoverflow .content {\r\n position: relative;\r\n display: inline-block;\r\n}\r\n\r\n.vis.timeline .item.line {\r\n position: absolute;\r\n width: 0;\r\n border-left-width: 1px;\r\n border-left-style: solid;\r\n}\r\n\r\n.vis.timeline .item .content {\r\n margin: 5px;\r\n white-space: nowrap;\r\n overflow: hidden;\r\n}\r\n\n.vis.timeline .axis {\r\n position: relative;\r\n}\r\n\r\n.vis.timeline .axis .text {\r\n position: absolute;\r\n color: #4d4d4d;\r\n padding: 3px;\r\n white-space: nowrap;\r\n}\r\n\r\n.vis.timeline .axis .text.measure {\r\n position: absolute;\r\n padding-left: 0;\r\n p
  15342. },{"hammerjs":1,"moment":2,"mouseTrap":3}]},{},[4])
  15343. (4)
  15344. });