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.

17247 lines
490 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
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
  1. /**
  2. * vis.js
  3. * https://github.com/almende/vis
  4. *
  5. * A dynamic, browser-based visualization library.
  6. *
  7. * @version 0.3.0-SNAPSHOT
  8. * @date 2014-01-10
  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. if (this.options.convert) {
  5059. for (var field in this.options.convert) {
  5060. if (this.options.convert.hasOwnProperty(field)) {
  5061. var value = this.options.convert[field];
  5062. if (value == 'Date' || value == 'ISODate' || value == 'ASPDate') {
  5063. this.convert[field] = 'Date';
  5064. }
  5065. else {
  5066. this.convert[field] = value;
  5067. }
  5068. }
  5069. }
  5070. }
  5071. // event subscribers
  5072. this.subscribers = {};
  5073. this.internalIds = {}; // internally generated id's
  5074. }
  5075. /**
  5076. * Subscribe to an event, add an event listener
  5077. * @param {String} event Event name. Available events: 'put', 'update',
  5078. * 'remove'
  5079. * @param {function} callback Callback method. Called with three parameters:
  5080. * {String} event
  5081. * {Object | null} params
  5082. * {String | Number} senderId
  5083. */
  5084. DataSet.prototype.subscribe = function (event, callback) {
  5085. var subscribers = this.subscribers[event];
  5086. if (!subscribers) {
  5087. subscribers = [];
  5088. this.subscribers[event] = subscribers;
  5089. }
  5090. subscribers.push({
  5091. callback: callback
  5092. });
  5093. };
  5094. /**
  5095. * Unsubscribe from an event, remove an event listener
  5096. * @param {String} event
  5097. * @param {function} callback
  5098. */
  5099. DataSet.prototype.unsubscribe = function (event, callback) {
  5100. var subscribers = this.subscribers[event];
  5101. if (subscribers) {
  5102. this.subscribers[event] = subscribers.filter(function (listener) {
  5103. return (listener.callback != callback);
  5104. });
  5105. }
  5106. };
  5107. /**
  5108. * Trigger an event
  5109. * @param {String} event
  5110. * @param {Object | null} params
  5111. * @param {String} [senderId] Optional id of the sender.
  5112. * @private
  5113. */
  5114. DataSet.prototype._trigger = function (event, params, senderId) {
  5115. if (event == '*') {
  5116. throw new Error('Cannot trigger event *');
  5117. }
  5118. var subscribers = [];
  5119. if (event in this.subscribers) {
  5120. subscribers = subscribers.concat(this.subscribers[event]);
  5121. }
  5122. if ('*' in this.subscribers) {
  5123. subscribers = subscribers.concat(this.subscribers['*']);
  5124. }
  5125. for (var i = 0; i < subscribers.length; i++) {
  5126. var subscriber = subscribers[i];
  5127. if (subscriber.callback) {
  5128. subscriber.callback(event, params, senderId || null);
  5129. }
  5130. }
  5131. };
  5132. /**
  5133. * Add data.
  5134. * Adding an item will fail when there already is an item with the same id.
  5135. * @param {Object | Array | DataTable} data
  5136. * @param {String} [senderId] Optional sender id
  5137. * @return {Array} addedIds Array with the ids of the added items
  5138. */
  5139. DataSet.prototype.add = function (data, senderId) {
  5140. var addedIds = [],
  5141. id,
  5142. me = this;
  5143. if (data instanceof Array) {
  5144. // Array
  5145. for (var i = 0, len = data.length; i < len; i++) {
  5146. id = me._addItem(data[i]);
  5147. addedIds.push(id);
  5148. }
  5149. }
  5150. else if (util.isDataTable(data)) {
  5151. // Google DataTable
  5152. var columns = this._getColumnNames(data);
  5153. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  5154. var item = {};
  5155. for (var col = 0, cols = columns.length; col < cols; col++) {
  5156. var field = columns[col];
  5157. item[field] = data.getValue(row, col);
  5158. }
  5159. id = me._addItem(item);
  5160. addedIds.push(id);
  5161. }
  5162. }
  5163. else if (data instanceof Object) {
  5164. // Single item
  5165. id = me._addItem(data);
  5166. addedIds.push(id);
  5167. }
  5168. else {
  5169. throw new Error('Unknown dataType');
  5170. }
  5171. if (addedIds.length) {
  5172. this._trigger('add', {items: addedIds}, senderId);
  5173. }
  5174. return addedIds;
  5175. };
  5176. /**
  5177. * Update existing items. When an item does not exist, it will be created
  5178. * @param {Object | Array | DataTable} data
  5179. * @param {String} [senderId] Optional sender id
  5180. * @return {Array} updatedIds The ids of the added or updated items
  5181. */
  5182. DataSet.prototype.update = function (data, senderId) {
  5183. var addedIds = [],
  5184. updatedIds = [],
  5185. me = this,
  5186. fieldId = me.fieldId;
  5187. var addOrUpdate = function (item) {
  5188. var id = item[fieldId];
  5189. if (me.data[id]) {
  5190. // update item
  5191. id = me._updateItem(item);
  5192. updatedIds.push(id);
  5193. }
  5194. else {
  5195. // add new item
  5196. id = me._addItem(item);
  5197. addedIds.push(id);
  5198. }
  5199. };
  5200. if (data instanceof Array) {
  5201. // Array
  5202. for (var i = 0, len = data.length; i < len; i++) {
  5203. addOrUpdate(data[i]);
  5204. }
  5205. }
  5206. else if (util.isDataTable(data)) {
  5207. // Google DataTable
  5208. var columns = this._getColumnNames(data);
  5209. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  5210. var item = {};
  5211. for (var col = 0, cols = columns.length; col < cols; col++) {
  5212. var field = columns[col];
  5213. item[field] = data.getValue(row, col);
  5214. }
  5215. addOrUpdate(item);
  5216. }
  5217. }
  5218. else if (data instanceof Object) {
  5219. // Single item
  5220. addOrUpdate(data);
  5221. }
  5222. else {
  5223. throw new Error('Unknown dataType');
  5224. }
  5225. if (addedIds.length) {
  5226. this._trigger('add', {items: addedIds}, senderId);
  5227. }
  5228. if (updatedIds.length) {
  5229. this._trigger('update', {items: updatedIds}, senderId);
  5230. }
  5231. return addedIds.concat(updatedIds);
  5232. };
  5233. /**
  5234. * Get a data item or multiple items.
  5235. *
  5236. * Usage:
  5237. *
  5238. * get()
  5239. * get(options: Object)
  5240. * get(options: Object, data: Array | DataTable)
  5241. *
  5242. * get(id: Number | String)
  5243. * get(id: Number | String, options: Object)
  5244. * get(id: Number | String, options: Object, data: Array | DataTable)
  5245. *
  5246. * get(ids: Number[] | String[])
  5247. * get(ids: Number[] | String[], options: Object)
  5248. * get(ids: Number[] | String[], options: Object, data: Array | DataTable)
  5249. *
  5250. * Where:
  5251. *
  5252. * {Number | String} id The id of an item
  5253. * {Number[] | String{}} ids An array with ids of items
  5254. * {Object} options An Object with options. Available options:
  5255. * {String} [type] Type of data to be returned. Can
  5256. * be 'DataTable' or 'Array' (default)
  5257. * {Object.<String, String>} [convert]
  5258. * {String[]} [fields] field names to be returned
  5259. * {function} [filter] filter items
  5260. * {String | function} [order] Order the items by
  5261. * a field name or custom sort function.
  5262. * {Array | DataTable} [data] If provided, items will be appended to this
  5263. * array or table. Required in case of Google
  5264. * DataTable.
  5265. *
  5266. * @throws Error
  5267. */
  5268. DataSet.prototype.get = function (args) {
  5269. var me = this;
  5270. // parse the arguments
  5271. var id, ids, options, data;
  5272. var firstType = util.getType(arguments[0]);
  5273. if (firstType == 'String' || firstType == 'Number') {
  5274. // get(id [, options] [, data])
  5275. id = arguments[0];
  5276. options = arguments[1];
  5277. data = arguments[2];
  5278. }
  5279. else if (firstType == 'Array') {
  5280. // get(ids [, options] [, data])
  5281. ids = arguments[0];
  5282. options = arguments[1];
  5283. data = arguments[2];
  5284. }
  5285. else {
  5286. // get([, options] [, data])
  5287. options = arguments[0];
  5288. data = arguments[1];
  5289. }
  5290. // determine the return type
  5291. var type;
  5292. if (options && options.type) {
  5293. type = (options.type == 'DataTable') ? 'DataTable' : 'Array';
  5294. if (data && (type != util.getType(data))) {
  5295. throw new Error('Type of parameter "data" (' + util.getType(data) + ') ' +
  5296. 'does not correspond with specified options.type (' + options.type + ')');
  5297. }
  5298. if (type == 'DataTable' && !util.isDataTable(data)) {
  5299. throw new Error('Parameter "data" must be a DataTable ' +
  5300. 'when options.type is "DataTable"');
  5301. }
  5302. }
  5303. else if (data) {
  5304. type = (util.getType(data) == 'DataTable') ? 'DataTable' : 'Array';
  5305. }
  5306. else {
  5307. type = 'Array';
  5308. }
  5309. // build options
  5310. var convert = options && options.convert || this.options.convert;
  5311. var filter = options && options.filter;
  5312. var items = [], item, itemId, i, len;
  5313. // convert items
  5314. if (id != undefined) {
  5315. // return a single item
  5316. item = me._getItem(id, convert);
  5317. if (filter && !filter(item)) {
  5318. item = null;
  5319. }
  5320. }
  5321. else if (ids != undefined) {
  5322. // return a subset of items
  5323. for (i = 0, len = ids.length; i < len; i++) {
  5324. item = me._getItem(ids[i], convert);
  5325. if (!filter || filter(item)) {
  5326. items.push(item);
  5327. }
  5328. }
  5329. }
  5330. else {
  5331. // return all items
  5332. for (itemId in this.data) {
  5333. if (this.data.hasOwnProperty(itemId)) {
  5334. item = me._getItem(itemId, convert);
  5335. if (!filter || filter(item)) {
  5336. items.push(item);
  5337. }
  5338. }
  5339. }
  5340. }
  5341. // order the results
  5342. if (options && options.order && id == undefined) {
  5343. this._sort(items, options.order);
  5344. }
  5345. // filter fields of the items
  5346. if (options && options.fields) {
  5347. var fields = options.fields;
  5348. if (id != undefined) {
  5349. item = this._filterFields(item, fields);
  5350. }
  5351. else {
  5352. for (i = 0, len = items.length; i < len; i++) {
  5353. items[i] = this._filterFields(items[i], fields);
  5354. }
  5355. }
  5356. }
  5357. // return the results
  5358. if (type == 'DataTable') {
  5359. var columns = this._getColumnNames(data);
  5360. if (id != undefined) {
  5361. // append a single item to the data table
  5362. me._appendRow(data, columns, item);
  5363. }
  5364. else {
  5365. // copy the items to the provided data table
  5366. for (i = 0, len = items.length; i < len; i++) {
  5367. me._appendRow(data, columns, items[i]);
  5368. }
  5369. }
  5370. return data;
  5371. }
  5372. else {
  5373. // return an array
  5374. if (id != undefined) {
  5375. // a single item
  5376. return item;
  5377. }
  5378. else {
  5379. // multiple items
  5380. if (data) {
  5381. // copy the items to the provided array
  5382. for (i = 0, len = items.length; i < len; i++) {
  5383. data.push(items[i]);
  5384. }
  5385. return data;
  5386. }
  5387. else {
  5388. // just return our array
  5389. return items;
  5390. }
  5391. }
  5392. }
  5393. };
  5394. /**
  5395. * Get ids of all items or from a filtered set of items.
  5396. * @param {Object} [options] An Object with options. Available options:
  5397. * {function} [filter] filter items
  5398. * {String | function} [order] Order the items by
  5399. * a field name or custom sort function.
  5400. * @return {Array} ids
  5401. */
  5402. DataSet.prototype.getIds = function (options) {
  5403. var data = this.data,
  5404. filter = options && options.filter,
  5405. order = options && options.order,
  5406. convert = options && options.convert || this.options.convert,
  5407. i,
  5408. len,
  5409. id,
  5410. item,
  5411. items,
  5412. ids = [];
  5413. if (filter) {
  5414. // get filtered items
  5415. if (order) {
  5416. // create ordered list
  5417. items = [];
  5418. for (id in data) {
  5419. if (data.hasOwnProperty(id)) {
  5420. item = this._getItem(id, convert);
  5421. if (filter(item)) {
  5422. items.push(item);
  5423. }
  5424. }
  5425. }
  5426. this._sort(items, order);
  5427. for (i = 0, len = items.length; i < len; i++) {
  5428. ids[i] = items[i][this.fieldId];
  5429. }
  5430. }
  5431. else {
  5432. // create unordered list
  5433. for (id in data) {
  5434. if (data.hasOwnProperty(id)) {
  5435. item = this._getItem(id, convert);
  5436. if (filter(item)) {
  5437. ids.push(item[this.fieldId]);
  5438. }
  5439. }
  5440. }
  5441. }
  5442. }
  5443. else {
  5444. // get all items
  5445. if (order) {
  5446. // create an ordered list
  5447. items = [];
  5448. for (id in data) {
  5449. if (data.hasOwnProperty(id)) {
  5450. items.push(data[id]);
  5451. }
  5452. }
  5453. this._sort(items, order);
  5454. for (i = 0, len = items.length; i < len; i++) {
  5455. ids[i] = items[i][this.fieldId];
  5456. }
  5457. }
  5458. else {
  5459. // create unordered list
  5460. for (id in data) {
  5461. if (data.hasOwnProperty(id)) {
  5462. item = data[id];
  5463. ids.push(item[this.fieldId]);
  5464. }
  5465. }
  5466. }
  5467. }
  5468. return ids;
  5469. };
  5470. /**
  5471. * Execute a callback function for every item in the dataset.
  5472. * The order of the items is not determined.
  5473. * @param {function} callback
  5474. * @param {Object} [options] Available options:
  5475. * {Object.<String, String>} [convert]
  5476. * {String[]} [fields] filter fields
  5477. * {function} [filter] filter items
  5478. * {String | function} [order] Order the items by
  5479. * a field name or custom sort function.
  5480. */
  5481. DataSet.prototype.forEach = function (callback, options) {
  5482. var filter = options && options.filter,
  5483. convert = options && options.convert || this.options.convert,
  5484. data = this.data,
  5485. item,
  5486. id;
  5487. if (options && options.order) {
  5488. // execute forEach on ordered list
  5489. var items = this.get(options);
  5490. for (var i = 0, len = items.length; i < len; i++) {
  5491. item = items[i];
  5492. id = item[this.fieldId];
  5493. callback(item, id);
  5494. }
  5495. }
  5496. else {
  5497. // unordered
  5498. for (id in data) {
  5499. if (data.hasOwnProperty(id)) {
  5500. item = this._getItem(id, convert);
  5501. if (!filter || filter(item)) {
  5502. callback(item, id);
  5503. }
  5504. }
  5505. }
  5506. }
  5507. };
  5508. /**
  5509. * Map every item in the dataset.
  5510. * @param {function} callback
  5511. * @param {Object} [options] Available options:
  5512. * {Object.<String, String>} [convert]
  5513. * {String[]} [fields] filter fields
  5514. * {function} [filter] filter items
  5515. * {String | function} [order] Order the items by
  5516. * a field name or custom sort function.
  5517. * @return {Object[]} mappedItems
  5518. */
  5519. DataSet.prototype.map = function (callback, options) {
  5520. var filter = options && options.filter,
  5521. convert = options && options.convert || this.options.convert,
  5522. mappedItems = [],
  5523. data = this.data,
  5524. item;
  5525. // convert and filter items
  5526. for (var id in data) {
  5527. if (data.hasOwnProperty(id)) {
  5528. item = this._getItem(id, convert);
  5529. if (!filter || filter(item)) {
  5530. mappedItems.push(callback(item, id));
  5531. }
  5532. }
  5533. }
  5534. // order items
  5535. if (options && options.order) {
  5536. this._sort(mappedItems, options.order);
  5537. }
  5538. return mappedItems;
  5539. };
  5540. /**
  5541. * Filter the fields of an item
  5542. * @param {Object} item
  5543. * @param {String[]} fields Field names
  5544. * @return {Object} filteredItem
  5545. * @private
  5546. */
  5547. DataSet.prototype._filterFields = function (item, fields) {
  5548. var filteredItem = {};
  5549. for (var field in item) {
  5550. if (item.hasOwnProperty(field) && (fields.indexOf(field) != -1)) {
  5551. filteredItem[field] = item[field];
  5552. }
  5553. }
  5554. return filteredItem;
  5555. };
  5556. /**
  5557. * Sort the provided array with items
  5558. * @param {Object[]} items
  5559. * @param {String | function} order A field name or custom sort function.
  5560. * @private
  5561. */
  5562. DataSet.prototype._sort = function (items, order) {
  5563. if (util.isString(order)) {
  5564. // order by provided field name
  5565. var name = order; // field name
  5566. items.sort(function (a, b) {
  5567. var av = a[name];
  5568. var bv = b[name];
  5569. return (av > bv) ? 1 : ((av < bv) ? -1 : 0);
  5570. });
  5571. }
  5572. else if (typeof order === 'function') {
  5573. // order by sort function
  5574. items.sort(order);
  5575. }
  5576. // TODO: extend order by an Object {field:String, direction:String}
  5577. // where direction can be 'asc' or 'desc'
  5578. else {
  5579. throw new TypeError('Order must be a function or a string');
  5580. }
  5581. };
  5582. /**
  5583. * Remove an object by pointer or by id
  5584. * @param {String | Number | Object | Array} id Object or id, or an array with
  5585. * objects or ids to be removed
  5586. * @param {String} [senderId] Optional sender id
  5587. * @return {Array} removedIds
  5588. */
  5589. DataSet.prototype.remove = function (id, senderId) {
  5590. var removedIds = [],
  5591. i, len, removedId;
  5592. if (id instanceof Array) {
  5593. for (i = 0, len = id.length; i < len; i++) {
  5594. removedId = this._remove(id[i]);
  5595. if (removedId != null) {
  5596. removedIds.push(removedId);
  5597. }
  5598. }
  5599. }
  5600. else {
  5601. removedId = this._remove(id);
  5602. if (removedId != null) {
  5603. removedIds.push(removedId);
  5604. }
  5605. }
  5606. if (removedIds.length) {
  5607. this._trigger('remove', {items: removedIds}, senderId);
  5608. }
  5609. return removedIds;
  5610. };
  5611. /**
  5612. * Remove an item by its id
  5613. * @param {Number | String | Object} id id or item
  5614. * @returns {Number | String | null} id
  5615. * @private
  5616. */
  5617. DataSet.prototype._remove = function (id) {
  5618. if (util.isNumber(id) || util.isString(id)) {
  5619. if (this.data[id]) {
  5620. delete this.data[id];
  5621. delete this.internalIds[id];
  5622. return id;
  5623. }
  5624. }
  5625. else if (id instanceof Object) {
  5626. var itemId = id[this.fieldId];
  5627. if (itemId && this.data[itemId]) {
  5628. delete this.data[itemId];
  5629. delete this.internalIds[itemId];
  5630. return itemId;
  5631. }
  5632. }
  5633. return null;
  5634. };
  5635. /**
  5636. * Clear the data
  5637. * @param {String} [senderId] Optional sender id
  5638. * @return {Array} removedIds The ids of all removed items
  5639. */
  5640. DataSet.prototype.clear = function (senderId) {
  5641. var ids = Object.keys(this.data);
  5642. this.data = {};
  5643. this.internalIds = {};
  5644. this._trigger('remove', {items: ids}, senderId);
  5645. return ids;
  5646. };
  5647. /**
  5648. * Find the item with maximum value of a specified field
  5649. * @param {String} field
  5650. * @return {Object | null} item Item containing max value, or null if no items
  5651. */
  5652. DataSet.prototype.max = function (field) {
  5653. var data = this.data,
  5654. max = null,
  5655. maxField = null;
  5656. for (var id in data) {
  5657. if (data.hasOwnProperty(id)) {
  5658. var item = data[id];
  5659. var itemField = item[field];
  5660. if (itemField != null && (!max || itemField > maxField)) {
  5661. max = item;
  5662. maxField = itemField;
  5663. }
  5664. }
  5665. }
  5666. return max;
  5667. };
  5668. /**
  5669. * Find the item with minimum value of a specified field
  5670. * @param {String} field
  5671. * @return {Object | null} item Item containing max value, or null if no items
  5672. */
  5673. DataSet.prototype.min = function (field) {
  5674. var data = this.data,
  5675. min = null,
  5676. minField = null;
  5677. for (var id in data) {
  5678. if (data.hasOwnProperty(id)) {
  5679. var item = data[id];
  5680. var itemField = item[field];
  5681. if (itemField != null && (!min || itemField < minField)) {
  5682. min = item;
  5683. minField = itemField;
  5684. }
  5685. }
  5686. }
  5687. return min;
  5688. };
  5689. /**
  5690. * Find all distinct values of a specified field
  5691. * @param {String} field
  5692. * @return {Array} values Array containing all distinct values. If the data
  5693. * items do not contain the specified field, an array
  5694. * containing a single value undefined is returned.
  5695. * The returned array is unordered.
  5696. */
  5697. DataSet.prototype.distinct = function (field) {
  5698. var data = this.data,
  5699. values = [],
  5700. fieldType = this.options.convert[field],
  5701. count = 0;
  5702. for (var prop in data) {
  5703. if (data.hasOwnProperty(prop)) {
  5704. var item = data[prop];
  5705. var value = util.convert(item[field], fieldType);
  5706. var exists = false;
  5707. for (var i = 0; i < count; i++) {
  5708. if (values[i] == value) {
  5709. exists = true;
  5710. break;
  5711. }
  5712. }
  5713. if (!exists) {
  5714. values[count] = value;
  5715. count++;
  5716. }
  5717. }
  5718. }
  5719. return values;
  5720. };
  5721. /**
  5722. * Add a single item. Will fail when an item with the same id already exists.
  5723. * @param {Object} item
  5724. * @return {String} id
  5725. * @private
  5726. */
  5727. DataSet.prototype._addItem = function (item) {
  5728. var id = item[this.fieldId];
  5729. if (id != undefined) {
  5730. // check whether this id is already taken
  5731. if (this.data[id]) {
  5732. // item already exists
  5733. throw new Error('Cannot add item: item with id ' + id + ' already exists');
  5734. }
  5735. }
  5736. else {
  5737. // generate an id
  5738. id = util.randomUUID();
  5739. item[this.fieldId] = id;
  5740. this.internalIds[id] = item;
  5741. }
  5742. var d = {};
  5743. for (var field in item) {
  5744. if (item.hasOwnProperty(field)) {
  5745. var fieldType = this.convert[field]; // type may be undefined
  5746. d[field] = util.convert(item[field], fieldType);
  5747. }
  5748. }
  5749. this.data[id] = d;
  5750. return id;
  5751. };
  5752. /**
  5753. * Get an item. Fields can be converted to a specific type
  5754. * @param {String} id
  5755. * @param {Object.<String, String>} [convert] field types to convert
  5756. * @return {Object | null} item
  5757. * @private
  5758. */
  5759. DataSet.prototype._getItem = function (id, convert) {
  5760. var field, value;
  5761. // get the item from the dataset
  5762. var raw = this.data[id];
  5763. if (!raw) {
  5764. return null;
  5765. }
  5766. // convert the items field types
  5767. var converted = {},
  5768. fieldId = this.fieldId,
  5769. internalIds = this.internalIds;
  5770. if (convert) {
  5771. for (field in raw) {
  5772. if (raw.hasOwnProperty(field)) {
  5773. value = raw[field];
  5774. // output all fields, except internal ids
  5775. if ((field != fieldId) || !(value in internalIds)) {
  5776. converted[field] = util.convert(value, convert[field]);
  5777. }
  5778. }
  5779. }
  5780. }
  5781. else {
  5782. // no field types specified, no converting needed
  5783. for (field in raw) {
  5784. if (raw.hasOwnProperty(field)) {
  5785. value = raw[field];
  5786. // output all fields, except internal ids
  5787. if ((field != fieldId) || !(value in internalIds)) {
  5788. converted[field] = value;
  5789. }
  5790. }
  5791. }
  5792. }
  5793. return converted;
  5794. };
  5795. /**
  5796. * Update a single item: merge with existing item.
  5797. * Will fail when the item has no id, or when there does not exist an item
  5798. * with the same id.
  5799. * @param {Object} item
  5800. * @return {String} id
  5801. * @private
  5802. */
  5803. DataSet.prototype._updateItem = function (item) {
  5804. var id = item[this.fieldId];
  5805. if (id == undefined) {
  5806. throw new Error('Cannot update item: item has no id (item: ' + JSON.stringify(item) + ')');
  5807. }
  5808. var d = this.data[id];
  5809. if (!d) {
  5810. // item doesn't exist
  5811. throw new Error('Cannot update item: no item with id ' + id + ' found');
  5812. }
  5813. // merge with current item
  5814. for (var field in item) {
  5815. if (item.hasOwnProperty(field)) {
  5816. var fieldType = this.convert[field]; // type may be undefined
  5817. d[field] = util.convert(item[field], fieldType);
  5818. }
  5819. }
  5820. return id;
  5821. };
  5822. /**
  5823. * Get an array with the column names of a Google DataTable
  5824. * @param {DataTable} dataTable
  5825. * @return {String[]} columnNames
  5826. * @private
  5827. */
  5828. DataSet.prototype._getColumnNames = function (dataTable) {
  5829. var columns = [];
  5830. for (var col = 0, cols = dataTable.getNumberOfColumns(); col < cols; col++) {
  5831. columns[col] = dataTable.getColumnId(col) || dataTable.getColumnLabel(col);
  5832. }
  5833. return columns;
  5834. };
  5835. /**
  5836. * Append an item as a row to the dataTable
  5837. * @param dataTable
  5838. * @param columns
  5839. * @param item
  5840. * @private
  5841. */
  5842. DataSet.prototype._appendRow = function (dataTable, columns, item) {
  5843. var row = dataTable.addRow();
  5844. for (var col = 0, cols = columns.length; col < cols; col++) {
  5845. var field = columns[col];
  5846. dataTable.setValue(row, col, item[field]);
  5847. }
  5848. };
  5849. /**
  5850. * DataView
  5851. *
  5852. * a dataview offers a filtered view on a dataset or an other dataview.
  5853. *
  5854. * @param {DataSet | DataView} data
  5855. * @param {Object} [options] Available options: see method get
  5856. *
  5857. * @constructor DataView
  5858. */
  5859. function DataView (data, options) {
  5860. this.id = util.randomUUID();
  5861. this.data = null;
  5862. this.ids = {}; // ids of the items currently in memory (just contains a boolean true)
  5863. this.options = options || {};
  5864. this.fieldId = 'id'; // name of the field containing id
  5865. this.subscribers = {}; // event subscribers
  5866. var me = this;
  5867. this.listener = function () {
  5868. me._onEvent.apply(me, arguments);
  5869. };
  5870. this.setData(data);
  5871. }
  5872. // TODO: implement a function .config() to dynamically update things like configured filter
  5873. // and trigger changes accordingly
  5874. /**
  5875. * Set a data source for the view
  5876. * @param {DataSet | DataView} data
  5877. */
  5878. DataView.prototype.setData = function (data) {
  5879. var ids, dataItems, i, len;
  5880. if (this.data) {
  5881. // unsubscribe from current dataset
  5882. if (this.data.unsubscribe) {
  5883. this.data.unsubscribe('*', this.listener);
  5884. }
  5885. // trigger a remove of all items in memory
  5886. ids = [];
  5887. for (var id in this.ids) {
  5888. if (this.ids.hasOwnProperty(id)) {
  5889. ids.push(id);
  5890. }
  5891. }
  5892. this.ids = {};
  5893. this._trigger('remove', {items: ids});
  5894. }
  5895. this.data = data;
  5896. if (this.data) {
  5897. // update fieldId
  5898. this.fieldId = this.options.fieldId ||
  5899. (this.data && this.data.options && this.data.options.fieldId) ||
  5900. 'id';
  5901. // trigger an add of all added items
  5902. ids = this.data.getIds({filter: this.options && this.options.filter});
  5903. for (i = 0, len = ids.length; i < len; i++) {
  5904. id = ids[i];
  5905. this.ids[id] = true;
  5906. }
  5907. this._trigger('add', {items: ids});
  5908. // subscribe to new dataset
  5909. if (this.data.subscribe) {
  5910. this.data.subscribe('*', this.listener);
  5911. }
  5912. }
  5913. };
  5914. /**
  5915. * Get data from the data view
  5916. *
  5917. * Usage:
  5918. *
  5919. * get()
  5920. * get(options: Object)
  5921. * get(options: Object, data: Array | DataTable)
  5922. *
  5923. * get(id: Number)
  5924. * get(id: Number, options: Object)
  5925. * get(id: Number, options: Object, data: Array | DataTable)
  5926. *
  5927. * get(ids: Number[])
  5928. * get(ids: Number[], options: Object)
  5929. * get(ids: Number[], options: Object, data: Array | DataTable)
  5930. *
  5931. * Where:
  5932. *
  5933. * {Number | String} id The id of an item
  5934. * {Number[] | String{}} ids An array with ids of items
  5935. * {Object} options An Object with options. Available options:
  5936. * {String} [type] Type of data to be returned. Can
  5937. * be 'DataTable' or 'Array' (default)
  5938. * {Object.<String, String>} [convert]
  5939. * {String[]} [fields] field names to be returned
  5940. * {function} [filter] filter items
  5941. * {String | function} [order] Order the items by
  5942. * a field name or custom sort function.
  5943. * {Array | DataTable} [data] If provided, items will be appended to this
  5944. * array or table. Required in case of Google
  5945. * DataTable.
  5946. * @param args
  5947. */
  5948. DataView.prototype.get = function (args) {
  5949. var me = this;
  5950. // parse the arguments
  5951. var ids, options, data;
  5952. var firstType = util.getType(arguments[0]);
  5953. if (firstType == 'String' || firstType == 'Number' || firstType == 'Array') {
  5954. // get(id(s) [, options] [, data])
  5955. ids = arguments[0]; // can be a single id or an array with ids
  5956. options = arguments[1];
  5957. data = arguments[2];
  5958. }
  5959. else {
  5960. // get([, options] [, data])
  5961. options = arguments[0];
  5962. data = arguments[1];
  5963. }
  5964. // extend the options with the default options and provided options
  5965. var viewOptions = util.extend({}, this.options, options);
  5966. // create a combined filter method when needed
  5967. if (this.options.filter && options && options.filter) {
  5968. viewOptions.filter = function (item) {
  5969. return me.options.filter(item) && options.filter(item);
  5970. }
  5971. }
  5972. // build up the call to the linked data set
  5973. var getArguments = [];
  5974. if (ids != undefined) {
  5975. getArguments.push(ids);
  5976. }
  5977. getArguments.push(viewOptions);
  5978. getArguments.push(data);
  5979. return this.data && this.data.get.apply(this.data, getArguments);
  5980. };
  5981. /**
  5982. * Get ids of all items or from a filtered set of items.
  5983. * @param {Object} [options] An Object with options. Available options:
  5984. * {function} [filter] filter items
  5985. * {String | function} [order] Order the items by
  5986. * a field name or custom sort function.
  5987. * @return {Array} ids
  5988. */
  5989. DataView.prototype.getIds = function (options) {
  5990. var ids;
  5991. if (this.data) {
  5992. var defaultFilter = this.options.filter;
  5993. var filter;
  5994. if (options && options.filter) {
  5995. if (defaultFilter) {
  5996. filter = function (item) {
  5997. return defaultFilter(item) && options.filter(item);
  5998. }
  5999. }
  6000. else {
  6001. filter = options.filter;
  6002. }
  6003. }
  6004. else {
  6005. filter = defaultFilter;
  6006. }
  6007. ids = this.data.getIds({
  6008. filter: filter,
  6009. order: options && options.order
  6010. });
  6011. }
  6012. else {
  6013. ids = [];
  6014. }
  6015. return ids;
  6016. };
  6017. /**
  6018. * Event listener. Will propagate all events from the connected data set to
  6019. * the subscribers of the DataView, but will filter the items and only trigger
  6020. * when there are changes in the filtered data set.
  6021. * @param {String} event
  6022. * @param {Object | null} params
  6023. * @param {String} senderId
  6024. * @private
  6025. */
  6026. DataView.prototype._onEvent = function (event, params, senderId) {
  6027. var i, len, id, item,
  6028. ids = params && params.items,
  6029. data = this.data,
  6030. added = [],
  6031. updated = [],
  6032. removed = [];
  6033. if (ids && data) {
  6034. switch (event) {
  6035. case 'add':
  6036. // filter the ids of the added items
  6037. for (i = 0, len = ids.length; i < len; i++) {
  6038. id = ids[i];
  6039. item = this.get(id);
  6040. if (item) {
  6041. this.ids[id] = true;
  6042. added.push(id);
  6043. }
  6044. }
  6045. break;
  6046. case 'update':
  6047. // determine the event from the views viewpoint: an updated
  6048. // item can be added, updated, or removed from this view.
  6049. for (i = 0, len = ids.length; i < len; i++) {
  6050. id = ids[i];
  6051. item = this.get(id);
  6052. if (item) {
  6053. if (this.ids[id]) {
  6054. updated.push(id);
  6055. }
  6056. else {
  6057. this.ids[id] = true;
  6058. added.push(id);
  6059. }
  6060. }
  6061. else {
  6062. if (this.ids[id]) {
  6063. delete this.ids[id];
  6064. removed.push(id);
  6065. }
  6066. else {
  6067. // nothing interesting for me :-(
  6068. }
  6069. }
  6070. }
  6071. break;
  6072. case 'remove':
  6073. // filter the ids of the removed items
  6074. for (i = 0, len = ids.length; i < len; i++) {
  6075. id = ids[i];
  6076. if (this.ids[id]) {
  6077. delete this.ids[id];
  6078. removed.push(id);
  6079. }
  6080. }
  6081. break;
  6082. }
  6083. if (added.length) {
  6084. this._trigger('add', {items: added}, senderId);
  6085. }
  6086. if (updated.length) {
  6087. this._trigger('update', {items: updated}, senderId);
  6088. }
  6089. if (removed.length) {
  6090. this._trigger('remove', {items: removed}, senderId);
  6091. }
  6092. }
  6093. };
  6094. // copy subscription functionality from DataSet
  6095. DataView.prototype.subscribe = DataSet.prototype.subscribe;
  6096. DataView.prototype.unsubscribe = DataSet.prototype.unsubscribe;
  6097. DataView.prototype._trigger = DataSet.prototype._trigger;
  6098. /**
  6099. * @constructor TimeStep
  6100. * The class TimeStep is an iterator for dates. You provide a start date and an
  6101. * end date. The class itself determines the best scale (step size) based on the
  6102. * provided start Date, end Date, and minimumStep.
  6103. *
  6104. * If minimumStep is provided, the step size is chosen as close as possible
  6105. * to the minimumStep but larger than minimumStep. If minimumStep is not
  6106. * provided, the scale is set to 1 DAY.
  6107. * The minimumStep should correspond with the onscreen size of about 6 characters
  6108. *
  6109. * Alternatively, you can set a scale by hand.
  6110. * After creation, you can initialize the class by executing first(). Then you
  6111. * can iterate from the start date to the end date via next(). You can check if
  6112. * the end date is reached with the function hasNext(). After each step, you can
  6113. * retrieve the current date via getCurrent().
  6114. * The TimeStep has scales ranging from milliseconds, seconds, minutes, hours,
  6115. * days, to years.
  6116. *
  6117. * Version: 1.2
  6118. *
  6119. * @param {Date} [start] The start date, for example new Date(2010, 9, 21)
  6120. * or new Date(2010, 9, 21, 23, 45, 00)
  6121. * @param {Date} [end] The end date
  6122. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  6123. */
  6124. TimeStep = function(start, end, minimumStep) {
  6125. // variables
  6126. this.current = new Date();
  6127. this._start = new Date();
  6128. this._end = new Date();
  6129. this.autoScale = true;
  6130. this.scale = TimeStep.SCALE.DAY;
  6131. this.step = 1;
  6132. // initialize the range
  6133. this.setRange(start, end, minimumStep);
  6134. };
  6135. /// enum scale
  6136. TimeStep.SCALE = {
  6137. MILLISECOND: 1,
  6138. SECOND: 2,
  6139. MINUTE: 3,
  6140. HOUR: 4,
  6141. DAY: 5,
  6142. WEEKDAY: 6,
  6143. MONTH: 7,
  6144. YEAR: 8
  6145. };
  6146. /**
  6147. * Set a new range
  6148. * If minimumStep is provided, the step size is chosen as close as possible
  6149. * to the minimumStep but larger than minimumStep. If minimumStep is not
  6150. * provided, the scale is set to 1 DAY.
  6151. * The minimumStep should correspond with the onscreen size of about 6 characters
  6152. * @param {Date} [start] The start date and time.
  6153. * @param {Date} [end] The end date and time.
  6154. * @param {int} [minimumStep] Optional. Minimum step size in milliseconds
  6155. */
  6156. TimeStep.prototype.setRange = function(start, end, minimumStep) {
  6157. if (!(start instanceof Date) || !(end instanceof Date)) {
  6158. throw "No legal start or end date in method setRange";
  6159. }
  6160. this._start = (start != undefined) ? new Date(start.valueOf()) : new Date();
  6161. this._end = (end != undefined) ? new Date(end.valueOf()) : new Date();
  6162. if (this.autoScale) {
  6163. this.setMinimumStep(minimumStep);
  6164. }
  6165. };
  6166. /**
  6167. * Set the range iterator to the start date.
  6168. */
  6169. TimeStep.prototype.first = function() {
  6170. this.current = new Date(this._start.valueOf());
  6171. this.roundToMinor();
  6172. };
  6173. /**
  6174. * Round the current date to the first minor date value
  6175. * This must be executed once when the current date is set to start Date
  6176. */
  6177. TimeStep.prototype.roundToMinor = function() {
  6178. // round to floor
  6179. // IMPORTANT: we have no breaks in this switch! (this is no bug)
  6180. //noinspection FallthroughInSwitchStatementJS
  6181. switch (this.scale) {
  6182. case TimeStep.SCALE.YEAR:
  6183. this.current.setFullYear(this.step * Math.floor(this.current.getFullYear() / this.step));
  6184. this.current.setMonth(0);
  6185. case TimeStep.SCALE.MONTH: this.current.setDate(1);
  6186. case TimeStep.SCALE.DAY: // intentional fall through
  6187. case TimeStep.SCALE.WEEKDAY: this.current.setHours(0);
  6188. case TimeStep.SCALE.HOUR: this.current.setMinutes(0);
  6189. case TimeStep.SCALE.MINUTE: this.current.setSeconds(0);
  6190. case TimeStep.SCALE.SECOND: this.current.setMilliseconds(0);
  6191. //case TimeStep.SCALE.MILLISECOND: // nothing to do for milliseconds
  6192. }
  6193. if (this.step != 1) {
  6194. // round down to the first minor value that is a multiple of the current step size
  6195. switch (this.scale) {
  6196. case TimeStep.SCALE.MILLISECOND: this.current.setMilliseconds(this.current.getMilliseconds() - this.current.getMilliseconds() % this.step); break;
  6197. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() - this.current.getSeconds() % this.step); break;
  6198. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() - this.current.getMinutes() % this.step); break;
  6199. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() - this.current.getHours() % this.step); break;
  6200. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  6201. case TimeStep.SCALE.DAY: this.current.setDate((this.current.getDate()-1) - (this.current.getDate()-1) % this.step + 1); break;
  6202. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() - this.current.getMonth() % this.step); break;
  6203. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() - this.current.getFullYear() % this.step); break;
  6204. default: break;
  6205. }
  6206. }
  6207. };
  6208. /**
  6209. * Check if the there is a next step
  6210. * @return {boolean} true if the current date has not passed the end date
  6211. */
  6212. TimeStep.prototype.hasNext = function () {
  6213. return (this.current.valueOf() <= this._end.valueOf());
  6214. };
  6215. /**
  6216. * Do the next step
  6217. */
  6218. TimeStep.prototype.next = function() {
  6219. var prev = this.current.valueOf();
  6220. // Two cases, needed to prevent issues with switching daylight savings
  6221. // (end of March and end of October)
  6222. if (this.current.getMonth() < 6) {
  6223. switch (this.scale) {
  6224. case TimeStep.SCALE.MILLISECOND:
  6225. this.current = new Date(this.current.valueOf() + this.step); break;
  6226. case TimeStep.SCALE.SECOND: this.current = new Date(this.current.valueOf() + this.step * 1000); break;
  6227. case TimeStep.SCALE.MINUTE: this.current = new Date(this.current.valueOf() + this.step * 1000 * 60); break;
  6228. case TimeStep.SCALE.HOUR:
  6229. this.current = new Date(this.current.valueOf() + this.step * 1000 * 60 * 60);
  6230. // in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...)
  6231. var h = this.current.getHours();
  6232. this.current.setHours(h - (h % this.step));
  6233. break;
  6234. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  6235. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  6236. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  6237. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  6238. default: break;
  6239. }
  6240. }
  6241. else {
  6242. switch (this.scale) {
  6243. case TimeStep.SCALE.MILLISECOND: this.current = new Date(this.current.valueOf() + this.step); break;
  6244. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() + this.step); break;
  6245. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() + this.step); break;
  6246. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() + this.step); break;
  6247. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  6248. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  6249. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  6250. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  6251. default: break;
  6252. }
  6253. }
  6254. if (this.step != 1) {
  6255. // round down to the correct major value
  6256. switch (this.scale) {
  6257. case TimeStep.SCALE.MILLISECOND: if(this.current.getMilliseconds() < this.step) this.current.setMilliseconds(0); break;
  6258. case TimeStep.SCALE.SECOND: if(this.current.getSeconds() < this.step) this.current.setSeconds(0); break;
  6259. case TimeStep.SCALE.MINUTE: if(this.current.getMinutes() < this.step) this.current.setMinutes(0); break;
  6260. case TimeStep.SCALE.HOUR: if(this.current.getHours() < this.step) this.current.setHours(0); break;
  6261. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  6262. case TimeStep.SCALE.DAY: if(this.current.getDate() < this.step+1) this.current.setDate(1); break;
  6263. case TimeStep.SCALE.MONTH: if(this.current.getMonth() < this.step) this.current.setMonth(0); break;
  6264. case TimeStep.SCALE.YEAR: break; // nothing to do for year
  6265. default: break;
  6266. }
  6267. }
  6268. // safety mechanism: if current time is still unchanged, move to the end
  6269. if (this.current.valueOf() == prev) {
  6270. this.current = new Date(this._end.valueOf());
  6271. }
  6272. };
  6273. /**
  6274. * Get the current datetime
  6275. * @return {Date} current The current date
  6276. */
  6277. TimeStep.prototype.getCurrent = function() {
  6278. return this.current;
  6279. };
  6280. /**
  6281. * Set a custom scale. Autoscaling will be disabled.
  6282. * For example setScale(SCALE.MINUTES, 5) will result
  6283. * in minor steps of 5 minutes, and major steps of an hour.
  6284. *
  6285. * @param {TimeStep.SCALE} newScale
  6286. * A scale. Choose from SCALE.MILLISECOND,
  6287. * SCALE.SECOND, SCALE.MINUTE, SCALE.HOUR,
  6288. * SCALE.WEEKDAY, SCALE.DAY, SCALE.MONTH,
  6289. * SCALE.YEAR.
  6290. * @param {Number} newStep A step size, by default 1. Choose for
  6291. * example 1, 2, 5, or 10.
  6292. */
  6293. TimeStep.prototype.setScale = function(newScale, newStep) {
  6294. this.scale = newScale;
  6295. if (newStep > 0) {
  6296. this.step = newStep;
  6297. }
  6298. this.autoScale = false;
  6299. };
  6300. /**
  6301. * Enable or disable autoscaling
  6302. * @param {boolean} enable If true, autoascaling is set true
  6303. */
  6304. TimeStep.prototype.setAutoScale = function (enable) {
  6305. this.autoScale = enable;
  6306. };
  6307. /**
  6308. * Automatically determine the scale that bests fits the provided minimum step
  6309. * @param {Number} [minimumStep] The minimum step size in milliseconds
  6310. */
  6311. TimeStep.prototype.setMinimumStep = function(minimumStep) {
  6312. if (minimumStep == undefined) {
  6313. return;
  6314. }
  6315. var stepYear = (1000 * 60 * 60 * 24 * 30 * 12);
  6316. var stepMonth = (1000 * 60 * 60 * 24 * 30);
  6317. var stepDay = (1000 * 60 * 60 * 24);
  6318. var stepHour = (1000 * 60 * 60);
  6319. var stepMinute = (1000 * 60);
  6320. var stepSecond = (1000);
  6321. var stepMillisecond= (1);
  6322. // find the smallest step that is larger than the provided minimumStep
  6323. if (stepYear*1000 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1000;}
  6324. if (stepYear*500 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 500;}
  6325. if (stepYear*100 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 100;}
  6326. if (stepYear*50 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 50;}
  6327. if (stepYear*10 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 10;}
  6328. if (stepYear*5 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 5;}
  6329. if (stepYear > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1;}
  6330. if (stepMonth*3 > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 3;}
  6331. if (stepMonth > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 1;}
  6332. if (stepDay*5 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 5;}
  6333. if (stepDay*2 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 2;}
  6334. if (stepDay > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 1;}
  6335. if (stepDay/2 > minimumStep) {this.scale = TimeStep.SCALE.WEEKDAY; this.step = 1;}
  6336. if (stepHour*4 > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 4;}
  6337. if (stepHour > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 1;}
  6338. if (stepMinute*15 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 15;}
  6339. if (stepMinute*10 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 10;}
  6340. if (stepMinute*5 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 5;}
  6341. if (stepMinute > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 1;}
  6342. if (stepSecond*15 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 15;}
  6343. if (stepSecond*10 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 10;}
  6344. if (stepSecond*5 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 5;}
  6345. if (stepSecond > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 1;}
  6346. if (stepMillisecond*200 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 200;}
  6347. if (stepMillisecond*100 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 100;}
  6348. if (stepMillisecond*50 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 50;}
  6349. if (stepMillisecond*10 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 10;}
  6350. if (stepMillisecond*5 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 5;}
  6351. if (stepMillisecond > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 1;}
  6352. };
  6353. /**
  6354. * Snap a date to a rounded value. The snap intervals are dependent on the
  6355. * current scale and step.
  6356. * @param {Date} date the date to be snapped
  6357. */
  6358. TimeStep.prototype.snap = function(date) {
  6359. if (this.scale == TimeStep.SCALE.YEAR) {
  6360. var year = date.getFullYear() + Math.round(date.getMonth() / 12);
  6361. date.setFullYear(Math.round(year / this.step) * this.step);
  6362. date.setMonth(0);
  6363. date.setDate(0);
  6364. date.setHours(0);
  6365. date.setMinutes(0);
  6366. date.setSeconds(0);
  6367. date.setMilliseconds(0);
  6368. }
  6369. else if (this.scale == TimeStep.SCALE.MONTH) {
  6370. if (date.getDate() > 15) {
  6371. date.setDate(1);
  6372. date.setMonth(date.getMonth() + 1);
  6373. // important: first set Date to 1, after that change the month.
  6374. }
  6375. else {
  6376. date.setDate(1);
  6377. }
  6378. date.setHours(0);
  6379. date.setMinutes(0);
  6380. date.setSeconds(0);
  6381. date.setMilliseconds(0);
  6382. }
  6383. else if (this.scale == TimeStep.SCALE.DAY ||
  6384. this.scale == TimeStep.SCALE.WEEKDAY) {
  6385. //noinspection FallthroughInSwitchStatementJS
  6386. switch (this.step) {
  6387. case 5:
  6388. case 2:
  6389. date.setHours(Math.round(date.getHours() / 24) * 24); break;
  6390. default:
  6391. date.setHours(Math.round(date.getHours() / 12) * 12); break;
  6392. }
  6393. date.setMinutes(0);
  6394. date.setSeconds(0);
  6395. date.setMilliseconds(0);
  6396. }
  6397. else if (this.scale == TimeStep.SCALE.HOUR) {
  6398. switch (this.step) {
  6399. case 4:
  6400. date.setMinutes(Math.round(date.getMinutes() / 60) * 60); break;
  6401. default:
  6402. date.setMinutes(Math.round(date.getMinutes() / 30) * 30); break;
  6403. }
  6404. date.setSeconds(0);
  6405. date.setMilliseconds(0);
  6406. } else if (this.scale == TimeStep.SCALE.MINUTE) {
  6407. //noinspection FallthroughInSwitchStatementJS
  6408. switch (this.step) {
  6409. case 15:
  6410. case 10:
  6411. date.setMinutes(Math.round(date.getMinutes() / 5) * 5);
  6412. date.setSeconds(0);
  6413. break;
  6414. case 5:
  6415. date.setSeconds(Math.round(date.getSeconds() / 60) * 60); break;
  6416. default:
  6417. date.setSeconds(Math.round(date.getSeconds() / 30) * 30); break;
  6418. }
  6419. date.setMilliseconds(0);
  6420. }
  6421. else if (this.scale == TimeStep.SCALE.SECOND) {
  6422. //noinspection FallthroughInSwitchStatementJS
  6423. switch (this.step) {
  6424. case 15:
  6425. case 10:
  6426. date.setSeconds(Math.round(date.getSeconds() / 5) * 5);
  6427. date.setMilliseconds(0);
  6428. break;
  6429. case 5:
  6430. date.setMilliseconds(Math.round(date.getMilliseconds() / 1000) * 1000); break;
  6431. default:
  6432. date.setMilliseconds(Math.round(date.getMilliseconds() / 500) * 500); break;
  6433. }
  6434. }
  6435. else if (this.scale == TimeStep.SCALE.MILLISECOND) {
  6436. var step = this.step > 5 ? this.step / 2 : 1;
  6437. date.setMilliseconds(Math.round(date.getMilliseconds() / step) * step);
  6438. }
  6439. };
  6440. /**
  6441. * Check if the current value is a major value (for example when the step
  6442. * is DAY, a major value is each first day of the MONTH)
  6443. * @return {boolean} true if current date is major, else false.
  6444. */
  6445. TimeStep.prototype.isMajor = function() {
  6446. switch (this.scale) {
  6447. case TimeStep.SCALE.MILLISECOND:
  6448. return (this.current.getMilliseconds() == 0);
  6449. case TimeStep.SCALE.SECOND:
  6450. return (this.current.getSeconds() == 0);
  6451. case TimeStep.SCALE.MINUTE:
  6452. return (this.current.getHours() == 0) && (this.current.getMinutes() == 0);
  6453. // Note: this is no bug. Major label is equal for both minute and hour scale
  6454. case TimeStep.SCALE.HOUR:
  6455. return (this.current.getHours() == 0);
  6456. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  6457. case TimeStep.SCALE.DAY:
  6458. return (this.current.getDate() == 1);
  6459. case TimeStep.SCALE.MONTH:
  6460. return (this.current.getMonth() == 0);
  6461. case TimeStep.SCALE.YEAR:
  6462. return false;
  6463. default:
  6464. return false;
  6465. }
  6466. };
  6467. /**
  6468. * Returns formatted text for the minor axislabel, depending on the current
  6469. * date and the scale. For example when scale is MINUTE, the current time is
  6470. * formatted as "hh:mm".
  6471. * @param {Date} [date] custom date. if not provided, current date is taken
  6472. */
  6473. TimeStep.prototype.getLabelMinor = function(date) {
  6474. if (date == undefined) {
  6475. date = this.current;
  6476. }
  6477. switch (this.scale) {
  6478. case TimeStep.SCALE.MILLISECOND: return moment(date).format('SSS');
  6479. case TimeStep.SCALE.SECOND: return moment(date).format('s');
  6480. case TimeStep.SCALE.MINUTE: return moment(date).format('HH:mm');
  6481. case TimeStep.SCALE.HOUR: return moment(date).format('HH:mm');
  6482. case TimeStep.SCALE.WEEKDAY: return moment(date).format('ddd D');
  6483. case TimeStep.SCALE.DAY: return moment(date).format('D');
  6484. case TimeStep.SCALE.MONTH: return moment(date).format('MMM');
  6485. case TimeStep.SCALE.YEAR: return moment(date).format('YYYY');
  6486. default: return '';
  6487. }
  6488. };
  6489. /**
  6490. * Returns formatted text for the major axis label, depending on the current
  6491. * date and the scale. For example when scale is MINUTE, the major scale is
  6492. * hours, and the hour will be formatted as "hh".
  6493. * @param {Date} [date] custom date. if not provided, current date is taken
  6494. */
  6495. TimeStep.prototype.getLabelMajor = function(date) {
  6496. if (date == undefined) {
  6497. date = this.current;
  6498. }
  6499. //noinspection FallthroughInSwitchStatementJS
  6500. switch (this.scale) {
  6501. case TimeStep.SCALE.MILLISECOND:return moment(date).format('HH:mm:ss');
  6502. case TimeStep.SCALE.SECOND: return moment(date).format('D MMMM HH:mm');
  6503. case TimeStep.SCALE.MINUTE:
  6504. case TimeStep.SCALE.HOUR: return moment(date).format('ddd D MMMM');
  6505. case TimeStep.SCALE.WEEKDAY:
  6506. case TimeStep.SCALE.DAY: return moment(date).format('MMMM YYYY');
  6507. case TimeStep.SCALE.MONTH: return moment(date).format('YYYY');
  6508. case TimeStep.SCALE.YEAR: return '';
  6509. default: return '';
  6510. }
  6511. };
  6512. /**
  6513. * @constructor Stack
  6514. * Stacks items on top of each other.
  6515. * @param {ItemSet} parent
  6516. * @param {Object} [options]
  6517. */
  6518. function Stack (parent, options) {
  6519. this.parent = parent;
  6520. this.options = options || {};
  6521. this.defaultOptions = {
  6522. order: function (a, b) {
  6523. //return (b.width - a.width) || (a.left - b.left); // TODO: cleanup
  6524. // Order: ranges over non-ranges, ranged ordered by width, and
  6525. // lastly ordered by start.
  6526. if (a instanceof ItemRange) {
  6527. if (b instanceof ItemRange) {
  6528. var aInt = (a.data.end - a.data.start);
  6529. var bInt = (b.data.end - b.data.start);
  6530. return (aInt - bInt) || (a.data.start - b.data.start);
  6531. }
  6532. else {
  6533. return -1;
  6534. }
  6535. }
  6536. else {
  6537. if (b instanceof ItemRange) {
  6538. return 1;
  6539. }
  6540. else {
  6541. return (a.data.start - b.data.start);
  6542. }
  6543. }
  6544. },
  6545. margin: {
  6546. item: 10
  6547. }
  6548. };
  6549. this.ordered = []; // ordered items
  6550. }
  6551. /**
  6552. * Set options for the stack
  6553. * @param {Object} options Available options:
  6554. * {ItemSet} parent
  6555. * {Number} margin
  6556. * {function} order Stacking order
  6557. */
  6558. Stack.prototype.setOptions = function setOptions (options) {
  6559. util.extend(this.options, options);
  6560. // TODO: register on data changes at the connected parent itemset, and update the changed part only and immediately
  6561. };
  6562. /**
  6563. * Stack the items such that they don't overlap. The items will have a minimal
  6564. * distance equal to options.margin.item.
  6565. */
  6566. Stack.prototype.update = function update() {
  6567. this._order();
  6568. this._stack();
  6569. };
  6570. /**
  6571. * Order the items. The items are ordered by width first, and by left position
  6572. * second.
  6573. * If a custom order function has been provided via the options, then this will
  6574. * be used.
  6575. * @private
  6576. */
  6577. Stack.prototype._order = function _order () {
  6578. var items = this.parent.items;
  6579. if (!items) {
  6580. throw new Error('Cannot stack items: parent does not contain items');
  6581. }
  6582. // TODO: store the sorted items, to have less work later on
  6583. var ordered = [];
  6584. var index = 0;
  6585. // items is a map (no array)
  6586. util.forEach(items, function (item) {
  6587. if (item.visible) {
  6588. ordered[index] = item;
  6589. index++;
  6590. }
  6591. });
  6592. //if a customer stack order function exists, use it.
  6593. var order = this.options.order || this.defaultOptions.order;
  6594. if (!(typeof order === 'function')) {
  6595. throw new Error('Option order must be a function');
  6596. }
  6597. ordered.sort(order);
  6598. this.ordered = ordered;
  6599. };
  6600. /**
  6601. * Adjust vertical positions of the events such that they don't overlap each
  6602. * other.
  6603. * @private
  6604. */
  6605. Stack.prototype._stack = function _stack () {
  6606. var i,
  6607. iMax,
  6608. ordered = this.ordered,
  6609. options = this.options,
  6610. orientation = options.orientation || this.defaultOptions.orientation,
  6611. axisOnTop = (orientation == 'top'),
  6612. margin;
  6613. if (options.margin && options.margin.item !== undefined) {
  6614. margin = options.margin.item;
  6615. }
  6616. else {
  6617. margin = this.defaultOptions.margin.item
  6618. }
  6619. // calculate new, non-overlapping positions
  6620. for (i = 0, iMax = ordered.length; i < iMax; i++) {
  6621. var item = ordered[i];
  6622. var collidingItem = null;
  6623. do {
  6624. // TODO: optimize checking for overlap. when there is a gap without items,
  6625. // you only need to check for items from the next item on, not from zero
  6626. collidingItem = this.checkOverlap(ordered, i, 0, i - 1, margin);
  6627. if (collidingItem != null) {
  6628. // There is a collision. Reposition the event above the colliding element
  6629. if (axisOnTop) {
  6630. item.top = collidingItem.top + collidingItem.height + margin;
  6631. }
  6632. else {
  6633. item.top = collidingItem.top - item.height - margin;
  6634. }
  6635. }
  6636. } while (collidingItem);
  6637. }
  6638. };
  6639. /**
  6640. * Check if the destiny position of given item overlaps with any
  6641. * of the other items from index itemStart to itemEnd.
  6642. * @param {Array} items Array with items
  6643. * @param {int} itemIndex Number of the item to be checked for overlap
  6644. * @param {int} itemStart First item to be checked.
  6645. * @param {int} itemEnd Last item to be checked.
  6646. * @return {Object | null} colliding item, or undefined when no collisions
  6647. * @param {Number} margin A minimum required margin.
  6648. * If margin is provided, the two items will be
  6649. * marked colliding when they overlap or
  6650. * when the margin between the two is smaller than
  6651. * the requested margin.
  6652. */
  6653. Stack.prototype.checkOverlap = function checkOverlap (items, itemIndex,
  6654. itemStart, itemEnd, margin) {
  6655. var collision = this.collision;
  6656. // we loop from end to start, as we suppose that the chance of a
  6657. // collision is larger for items at the end, so check these first.
  6658. var a = items[itemIndex];
  6659. for (var i = itemEnd; i >= itemStart; i--) {
  6660. var b = items[i];
  6661. if (collision(a, b, margin)) {
  6662. if (i != itemIndex) {
  6663. return b;
  6664. }
  6665. }
  6666. }
  6667. return null;
  6668. };
  6669. /**
  6670. * Test if the two provided items collide
  6671. * The items must have parameters left, width, top, and height.
  6672. * @param {Component} a The first item
  6673. * @param {Component} b The second item
  6674. * @param {Number} margin A minimum required margin.
  6675. * If margin is provided, the two items will be
  6676. * marked colliding when they overlap or
  6677. * when the margin between the two is smaller than
  6678. * the requested margin.
  6679. * @return {boolean} true if a and b collide, else false
  6680. */
  6681. Stack.prototype.collision = function collision (a, b, margin) {
  6682. return ((a.left - margin) < (b.left + b.getWidth()) &&
  6683. (a.left + a.getWidth() + margin) > b.left &&
  6684. (a.top - margin) < (b.top + b.height) &&
  6685. (a.top + a.height + margin) > b.top);
  6686. };
  6687. /**
  6688. * @constructor Range
  6689. * A Range controls a numeric range with a start and end value.
  6690. * The Range adjusts the range based on mouse events or programmatic changes,
  6691. * and triggers events when the range is changing or has been changed.
  6692. * @param {Object} [options] See description at Range.setOptions
  6693. * @extends Controller
  6694. */
  6695. function Range(options) {
  6696. this.id = util.randomUUID();
  6697. this.start = null; // Number
  6698. this.end = null; // Number
  6699. this.options = options || {};
  6700. this.setOptions(options);
  6701. }
  6702. /**
  6703. * Set options for the range controller
  6704. * @param {Object} options Available options:
  6705. * {Number} min Minimum value for start
  6706. * {Number} max Maximum value for end
  6707. * {Number} zoomMin Set a minimum value for
  6708. * (end - start).
  6709. * {Number} zoomMax Set a maximum value for
  6710. * (end - start).
  6711. */
  6712. Range.prototype.setOptions = function (options) {
  6713. util.extend(this.options, options);
  6714. // re-apply range with new limitations
  6715. if (this.start !== null && this.end !== null) {
  6716. this.setRange(this.start, this.end);
  6717. }
  6718. };
  6719. /**
  6720. * Test whether direction has a valid value
  6721. * @param {String} direction 'horizontal' or 'vertical'
  6722. */
  6723. function validateDirection (direction) {
  6724. if (direction != 'horizontal' && direction != 'vertical') {
  6725. throw new TypeError('Unknown direction "' + direction + '". ' +
  6726. 'Choose "horizontal" or "vertical".');
  6727. }
  6728. }
  6729. /**
  6730. * Add listeners for mouse and touch events to the component
  6731. * @param {Component} component
  6732. * @param {String} event Available events: 'move', 'zoom'
  6733. * @param {String} direction Available directions: 'horizontal', 'vertical'
  6734. */
  6735. Range.prototype.subscribe = function (component, event, direction) {
  6736. var me = this;
  6737. if (event == 'move') {
  6738. // drag start listener
  6739. component.on('dragstart', function (event) {
  6740. me._onDragStart(event, component);
  6741. });
  6742. // drag listener
  6743. component.on('drag', function (event) {
  6744. me._onDrag(event, component, direction);
  6745. });
  6746. // drag end listener
  6747. component.on('dragend', function (event) {
  6748. me._onDragEnd(event, component);
  6749. });
  6750. }
  6751. else if (event == 'zoom') {
  6752. // mouse wheel
  6753. function mousewheel (event) {
  6754. me._onMouseWheel(event, component, direction);
  6755. }
  6756. component.on('mousewheel', mousewheel);
  6757. component.on('DOMMouseScroll', mousewheel); // For FF
  6758. // pinch
  6759. component.on('touch', function (event) {
  6760. me._onTouch();
  6761. });
  6762. component.on('pinch', function (event) {
  6763. me._onPinch(event, component, direction);
  6764. });
  6765. }
  6766. else {
  6767. throw new TypeError('Unknown event "' + event + '". ' +
  6768. 'Choose "move" or "zoom".');
  6769. }
  6770. };
  6771. /**
  6772. * Event handler
  6773. * @param {String} event name of the event, for example 'click', 'mousemove'
  6774. * @param {function} callback callback handler, invoked with the raw HTML Event
  6775. * as parameter.
  6776. */
  6777. Range.prototype.on = function (event, callback) {
  6778. events.addListener(this, event, callback);
  6779. };
  6780. /**
  6781. * Trigger an event
  6782. * @param {String} event name of the event, available events: 'rangechange',
  6783. * 'rangechanged'
  6784. * @private
  6785. */
  6786. Range.prototype._trigger = function (event) {
  6787. events.trigger(this, event, {
  6788. start: this.start,
  6789. end: this.end
  6790. });
  6791. };
  6792. /**
  6793. * Set a new start and end range
  6794. * @param {Number} [start]
  6795. * @param {Number} [end]
  6796. */
  6797. Range.prototype.setRange = function(start, end) {
  6798. var changed = this._applyRange(start, end);
  6799. if (changed) {
  6800. this._trigger('rangechange');
  6801. this._trigger('rangechanged');
  6802. }
  6803. };
  6804. /**
  6805. * Set a new start and end range. This method is the same as setRange, but
  6806. * does not trigger a range change and range changed event, and it returns
  6807. * true when the range is changed
  6808. * @param {Number} [start]
  6809. * @param {Number} [end]
  6810. * @return {Boolean} changed
  6811. * @private
  6812. */
  6813. Range.prototype._applyRange = function(start, end) {
  6814. var newStart = (start != null) ? util.convert(start, 'Number') : this.start,
  6815. newEnd = (end != null) ? util.convert(end, 'Number') : this.end,
  6816. max = (this.options.max != null) ? util.convert(this.options.max, 'Date').valueOf() : null,
  6817. min = (this.options.min != null) ? util.convert(this.options.min, 'Date').valueOf() : null,
  6818. diff;
  6819. // check for valid number
  6820. if (isNaN(newStart) || newStart === null) {
  6821. throw new Error('Invalid start "' + start + '"');
  6822. }
  6823. if (isNaN(newEnd) || newEnd === null) {
  6824. throw new Error('Invalid end "' + end + '"');
  6825. }
  6826. // prevent start < end
  6827. if (newEnd < newStart) {
  6828. newEnd = newStart;
  6829. }
  6830. // prevent start < min
  6831. if (min !== null) {
  6832. if (newStart < min) {
  6833. diff = (min - newStart);
  6834. newStart += diff;
  6835. newEnd += diff;
  6836. // prevent end > max
  6837. if (max != null) {
  6838. if (newEnd > max) {
  6839. newEnd = max;
  6840. }
  6841. }
  6842. }
  6843. }
  6844. // prevent end > max
  6845. if (max !== null) {
  6846. if (newEnd > max) {
  6847. diff = (newEnd - max);
  6848. newStart -= diff;
  6849. newEnd -= diff;
  6850. // prevent start < min
  6851. if (min != null) {
  6852. if (newStart < min) {
  6853. newStart = min;
  6854. }
  6855. }
  6856. }
  6857. }
  6858. // prevent (end-start) < zoomMin
  6859. if (this.options.zoomMin !== null) {
  6860. var zoomMin = parseFloat(this.options.zoomMin);
  6861. if (zoomMin < 0) {
  6862. zoomMin = 0;
  6863. }
  6864. if ((newEnd - newStart) < zoomMin) {
  6865. if ((this.end - this.start) === zoomMin) {
  6866. // ignore this action, we are already zoomed to the minimum
  6867. newStart = this.start;
  6868. newEnd = this.end;
  6869. }
  6870. else {
  6871. // zoom to the minimum
  6872. diff = (zoomMin - (newEnd - newStart));
  6873. newStart -= diff / 2;
  6874. newEnd += diff / 2;
  6875. }
  6876. }
  6877. }
  6878. // prevent (end-start) > zoomMax
  6879. if (this.options.zoomMax !== null) {
  6880. var zoomMax = parseFloat(this.options.zoomMax);
  6881. if (zoomMax < 0) {
  6882. zoomMax = 0;
  6883. }
  6884. if ((newEnd - newStart) > zoomMax) {
  6885. if ((this.end - this.start) === zoomMax) {
  6886. // ignore this action, we are already zoomed to the maximum
  6887. newStart = this.start;
  6888. newEnd = this.end;
  6889. }
  6890. else {
  6891. // zoom to the maximum
  6892. diff = ((newEnd - newStart) - zoomMax);
  6893. newStart += diff / 2;
  6894. newEnd -= diff / 2;
  6895. }
  6896. }
  6897. }
  6898. var changed = (this.start != newStart || this.end != newEnd);
  6899. this.start = newStart;
  6900. this.end = newEnd;
  6901. return changed;
  6902. };
  6903. /**
  6904. * Retrieve the current range.
  6905. * @return {Object} An object with start and end properties
  6906. */
  6907. Range.prototype.getRange = function() {
  6908. return {
  6909. start: this.start,
  6910. end: this.end
  6911. };
  6912. };
  6913. /**
  6914. * Calculate the conversion offset and scale for current range, based on
  6915. * the provided width
  6916. * @param {Number} width
  6917. * @returns {{offset: number, scale: number}} conversion
  6918. */
  6919. Range.prototype.conversion = function (width) {
  6920. return Range.conversion(this.start, this.end, width);
  6921. };
  6922. /**
  6923. * Static method to calculate the conversion offset and scale for a range,
  6924. * based on the provided start, end, and width
  6925. * @param {Number} start
  6926. * @param {Number} end
  6927. * @param {Number} width
  6928. * @returns {{offset: number, scale: number}} conversion
  6929. */
  6930. Range.conversion = function (start, end, width) {
  6931. if (width != 0 && (end - start != 0)) {
  6932. return {
  6933. offset: start,
  6934. scale: width / (end - start)
  6935. }
  6936. }
  6937. else {
  6938. return {
  6939. offset: 0,
  6940. scale: 1
  6941. };
  6942. }
  6943. };
  6944. // global (private) object to store drag params
  6945. var touchParams = {};
  6946. /**
  6947. * Start dragging horizontally or vertically
  6948. * @param {Event} event
  6949. * @param {Object} component
  6950. * @private
  6951. */
  6952. Range.prototype._onDragStart = function(event, component) {
  6953. // refuse to drag when we where pinching to prevent the timeline make a jump
  6954. // when releasing the fingers in opposite order from the touch screen
  6955. if (touchParams.pinching) return;
  6956. touchParams.start = this.start;
  6957. touchParams.end = this.end;
  6958. var frame = component.frame;
  6959. if (frame) {
  6960. frame.style.cursor = 'move';
  6961. }
  6962. };
  6963. /**
  6964. * Perform dragging operating.
  6965. * @param {Event} event
  6966. * @param {Component} component
  6967. * @param {String} direction 'horizontal' or 'vertical'
  6968. * @private
  6969. */
  6970. Range.prototype._onDrag = function (event, component, direction) {
  6971. validateDirection(direction);
  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. var delta = (direction == 'horizontal') ? event.gesture.deltaX : event.gesture.deltaY,
  6976. interval = (touchParams.end - touchParams.start),
  6977. width = (direction == 'horizontal') ? component.width : component.height,
  6978. diffRange = -delta / width * interval;
  6979. this._applyRange(touchParams.start + diffRange, touchParams.end + diffRange);
  6980. // fire a rangechange event
  6981. this._trigger('rangechange');
  6982. };
  6983. /**
  6984. * Stop dragging operating.
  6985. * @param {event} event
  6986. * @param {Component} component
  6987. * @private
  6988. */
  6989. Range.prototype._onDragEnd = function (event, component) {
  6990. // refuse to drag when we where pinching to prevent the timeline make a jump
  6991. // when releasing the fingers in opposite order from the touch screen
  6992. if (touchParams.pinching) return;
  6993. if (component.frame) {
  6994. component.frame.style.cursor = 'auto';
  6995. }
  6996. // fire a rangechanged event
  6997. this._trigger('rangechanged');
  6998. };
  6999. /**
  7000. * Event handler for mouse wheel event, used to zoom
  7001. * Code from http://adomas.org/javascript-mouse-wheel/
  7002. * @param {Event} event
  7003. * @param {Component} component
  7004. * @param {String} direction 'horizontal' or 'vertical'
  7005. * @private
  7006. */
  7007. Range.prototype._onMouseWheel = function(event, component, direction) {
  7008. validateDirection(direction);
  7009. // retrieve delta
  7010. var delta = 0;
  7011. if (event.wheelDelta) { /* IE/Opera. */
  7012. delta = event.wheelDelta / 120;
  7013. } else if (event.detail) { /* Mozilla case. */
  7014. // In Mozilla, sign of delta is different than in IE.
  7015. // Also, delta is multiple of 3.
  7016. delta = -event.detail / 3;
  7017. }
  7018. // If delta is nonzero, handle it.
  7019. // Basically, delta is now positive if wheel was scrolled up,
  7020. // and negative, if wheel was scrolled down.
  7021. if (delta) {
  7022. // perform the zoom action. Delta is normally 1 or -1
  7023. // adjust a negative delta such that zooming in with delta 0.1
  7024. // equals zooming out with a delta -0.1
  7025. var scale;
  7026. if (delta < 0) {
  7027. scale = 1 - (delta / 5);
  7028. }
  7029. else {
  7030. scale = 1 / (1 + (delta / 5)) ;
  7031. }
  7032. // calculate center, the date to zoom around
  7033. var gesture = Hammer.event.collectEventData(this, 'scroll', event),
  7034. pointer = getPointer(gesture.touches[0], component.frame),
  7035. pointerDate = this._pointerToDate(component, direction, pointer);
  7036. this.zoom(scale, pointerDate);
  7037. }
  7038. // Prevent default actions caused by mouse wheel
  7039. // (else the page and timeline both zoom and scroll)
  7040. util.preventDefault(event);
  7041. };
  7042. /**
  7043. * On start of a touch gesture, initialize scale to 1
  7044. * @private
  7045. */
  7046. Range.prototype._onTouch = function () {
  7047. touchParams.start = this.start;
  7048. touchParams.end = this.end;
  7049. touchParams.pinching = false;
  7050. touchParams.center = null;
  7051. };
  7052. /**
  7053. * Handle pinch event
  7054. * @param {Event} event
  7055. * @param {Component} component
  7056. * @param {String} direction 'horizontal' or 'vertical'
  7057. * @private
  7058. */
  7059. Range.prototype._onPinch = function (event, component, direction) {
  7060. touchParams.pinching = true;
  7061. if (event.gesture.touches.length > 1) {
  7062. if (!touchParams.center) {
  7063. touchParams.center = getPointer(event.gesture.center, component.frame);
  7064. }
  7065. var scale = 1 / event.gesture.scale,
  7066. initDate = this._pointerToDate(component, direction, touchParams.center),
  7067. center = getPointer(event.gesture.center, component.frame),
  7068. date = this._pointerToDate(component, direction, center),
  7069. delta = date - initDate; // TODO: utilize delta
  7070. // calculate new start and end
  7071. var newStart = parseInt(initDate + (touchParams.start - initDate) * scale);
  7072. var newEnd = parseInt(initDate + (touchParams.end - initDate) * scale);
  7073. // apply new range
  7074. this.setRange(newStart, newEnd);
  7075. }
  7076. };
  7077. /**
  7078. * Helper function to calculate the center date for zooming
  7079. * @param {Component} component
  7080. * @param {{x: Number, y: Number}} pointer
  7081. * @param {String} direction 'horizontal' or 'vertical'
  7082. * @return {number} date
  7083. * @private
  7084. */
  7085. Range.prototype._pointerToDate = function (component, direction, pointer) {
  7086. var conversion;
  7087. if (direction == 'horizontal') {
  7088. var width = component.width;
  7089. conversion = this.conversion(width);
  7090. return pointer.x / conversion.scale + conversion.offset;
  7091. }
  7092. else {
  7093. var height = component.height;
  7094. conversion = this.conversion(height);
  7095. return pointer.y / conversion.scale + conversion.offset;
  7096. }
  7097. };
  7098. /**
  7099. * Get the pointer location relative to the location of the dom element
  7100. * @param {{pageX: Number, pageY: Number}} touch
  7101. * @param {Element} element HTML DOM element
  7102. * @return {{x: Number, y: Number}} pointer
  7103. * @private
  7104. */
  7105. function getPointer (touch, element) {
  7106. return {
  7107. x: touch.pageX - vis.util.getAbsoluteLeft(element),
  7108. y: touch.pageY - vis.util.getAbsoluteTop(element)
  7109. };
  7110. }
  7111. /**
  7112. * Zoom the range the given scale in or out. Start and end date will
  7113. * be adjusted, and the timeline will be redrawn. You can optionally give a
  7114. * date around which to zoom.
  7115. * For example, try scale = 0.9 or 1.1
  7116. * @param {Number} scale Scaling factor. Values above 1 will zoom out,
  7117. * values below 1 will zoom in.
  7118. * @param {Number} [center] Value representing a date around which will
  7119. * be zoomed.
  7120. */
  7121. Range.prototype.zoom = function(scale, center) {
  7122. // if centerDate is not provided, take it half between start Date and end Date
  7123. if (center == null) {
  7124. center = (this.start + this.end) / 2;
  7125. }
  7126. // calculate new start and end
  7127. var newStart = center + (this.start - center) * scale;
  7128. var newEnd = center + (this.end - center) * scale;
  7129. this.setRange(newStart, newEnd);
  7130. };
  7131. /**
  7132. * Move the range with a given delta to the left or right. Start and end
  7133. * value will be adjusted. For example, try delta = 0.1 or -0.1
  7134. * @param {Number} delta Moving amount. Positive value will move right,
  7135. * negative value will move left
  7136. */
  7137. Range.prototype.move = function(delta) {
  7138. // zoom start Date and end Date relative to the centerDate
  7139. var diff = (this.end - this.start);
  7140. // apply new values
  7141. var newStart = this.start + diff * delta;
  7142. var newEnd = this.end + diff * delta;
  7143. // TODO: reckon with min and max range
  7144. this.start = newStart;
  7145. this.end = newEnd;
  7146. };
  7147. /**
  7148. * Move the range to a new center point
  7149. * @param {Number} moveTo New center point of the range
  7150. */
  7151. Range.prototype.moveTo = function(moveTo) {
  7152. var center = (this.start + this.end) / 2;
  7153. var diff = center - moveTo;
  7154. // calculate new start and end
  7155. var newStart = this.start - diff;
  7156. var newEnd = this.end - diff;
  7157. this.setRange(newStart, newEnd);
  7158. };
  7159. /**
  7160. * @constructor Controller
  7161. *
  7162. * A Controller controls the reflows and repaints of all visual components
  7163. */
  7164. function Controller () {
  7165. this.id = util.randomUUID();
  7166. this.components = {};
  7167. this.repaintTimer = undefined;
  7168. this.reflowTimer = undefined;
  7169. }
  7170. /**
  7171. * Add a component to the controller
  7172. * @param {Component} component
  7173. */
  7174. Controller.prototype.add = function add(component) {
  7175. // validate the component
  7176. if (component.id == undefined) {
  7177. throw new Error('Component has no field id');
  7178. }
  7179. if (!(component instanceof Component) && !(component instanceof Controller)) {
  7180. throw new TypeError('Component must be an instance of ' +
  7181. 'prototype Component or Controller');
  7182. }
  7183. // add the component
  7184. component.controller = this;
  7185. this.components[component.id] = component;
  7186. };
  7187. /**
  7188. * Remove a component from the controller
  7189. * @param {Component | String} component
  7190. */
  7191. Controller.prototype.remove = function remove(component) {
  7192. var id;
  7193. for (id in this.components) {
  7194. if (this.components.hasOwnProperty(id)) {
  7195. if (id == component || this.components[id] == component) {
  7196. break;
  7197. }
  7198. }
  7199. }
  7200. if (id) {
  7201. delete this.components[id];
  7202. }
  7203. };
  7204. /**
  7205. * Request a reflow. The controller will schedule a reflow
  7206. * @param {Boolean} [force] If true, an immediate reflow is forced. Default
  7207. * is false.
  7208. */
  7209. Controller.prototype.requestReflow = function requestReflow(force) {
  7210. if (force) {
  7211. this.reflow();
  7212. }
  7213. else {
  7214. if (!this.reflowTimer) {
  7215. var me = this;
  7216. this.reflowTimer = setTimeout(function () {
  7217. me.reflowTimer = undefined;
  7218. me.reflow();
  7219. }, 0);
  7220. }
  7221. }
  7222. };
  7223. /**
  7224. * Request a repaint. The controller will schedule a repaint
  7225. * @param {Boolean} [force] If true, an immediate repaint is forced. Default
  7226. * is false.
  7227. */
  7228. Controller.prototype.requestRepaint = function requestRepaint(force) {
  7229. if (force) {
  7230. this.repaint();
  7231. }
  7232. else {
  7233. if (!this.repaintTimer) {
  7234. var me = this;
  7235. this.repaintTimer = setTimeout(function () {
  7236. me.repaintTimer = undefined;
  7237. me.repaint();
  7238. }, 0);
  7239. }
  7240. }
  7241. };
  7242. /**
  7243. * Repaint all components
  7244. */
  7245. Controller.prototype.repaint = function repaint() {
  7246. var changed = false;
  7247. // cancel any running repaint request
  7248. if (this.repaintTimer) {
  7249. clearTimeout(this.repaintTimer);
  7250. this.repaintTimer = undefined;
  7251. }
  7252. var done = {};
  7253. function repaint(component, id) {
  7254. if (!(id in done)) {
  7255. // first repaint the components on which this component is dependent
  7256. if (component.depends) {
  7257. component.depends.forEach(function (dep) {
  7258. repaint(dep, dep.id);
  7259. });
  7260. }
  7261. if (component.parent) {
  7262. repaint(component.parent, component.parent.id);
  7263. }
  7264. // repaint the component itself and mark as done
  7265. changed = component.repaint() || changed;
  7266. done[id] = true;
  7267. }
  7268. }
  7269. util.forEach(this.components, repaint);
  7270. // immediately reflow when needed
  7271. if (changed) {
  7272. this.reflow();
  7273. }
  7274. // TODO: limit the number of nested reflows/repaints, prevent loop
  7275. };
  7276. /**
  7277. * Reflow all components
  7278. */
  7279. Controller.prototype.reflow = function reflow() {
  7280. var resized = false;
  7281. // cancel any running repaint request
  7282. if (this.reflowTimer) {
  7283. clearTimeout(this.reflowTimer);
  7284. this.reflowTimer = undefined;
  7285. }
  7286. var done = {};
  7287. function reflow(component, id) {
  7288. if (!(id in done)) {
  7289. // first reflow the components on which this component is dependent
  7290. if (component.depends) {
  7291. component.depends.forEach(function (dep) {
  7292. reflow(dep, dep.id);
  7293. });
  7294. }
  7295. if (component.parent) {
  7296. reflow(component.parent, component.parent.id);
  7297. }
  7298. // reflow the component itself and mark as done
  7299. resized = component.reflow() || resized;
  7300. done[id] = true;
  7301. }
  7302. }
  7303. util.forEach(this.components, reflow);
  7304. // immediately repaint when needed
  7305. if (resized) {
  7306. this.repaint();
  7307. }
  7308. // TODO: limit the number of nested reflows/repaints, prevent loop
  7309. };
  7310. /**
  7311. * Prototype for visual components
  7312. */
  7313. function Component () {
  7314. this.id = null;
  7315. this.parent = null;
  7316. this.depends = null;
  7317. this.controller = null;
  7318. this.options = null;
  7319. this.frame = null; // main DOM element
  7320. this.top = 0;
  7321. this.left = 0;
  7322. this.width = 0;
  7323. this.height = 0;
  7324. }
  7325. /**
  7326. * Set parameters for the frame. Parameters will be merged in current parameter
  7327. * set.
  7328. * @param {Object} options Available parameters:
  7329. * {String | function} [className]
  7330. * {EventBus} [eventBus]
  7331. * {String | Number | function} [left]
  7332. * {String | Number | function} [top]
  7333. * {String | Number | function} [width]
  7334. * {String | Number | function} [height]
  7335. */
  7336. Component.prototype.setOptions = function setOptions(options) {
  7337. if (options) {
  7338. util.extend(this.options, options);
  7339. if (this.controller) {
  7340. this.requestRepaint();
  7341. this.requestReflow();
  7342. }
  7343. }
  7344. };
  7345. /**
  7346. * Get an option value by name
  7347. * The function will first check this.options object, and else will check
  7348. * this.defaultOptions.
  7349. * @param {String} name
  7350. * @return {*} value
  7351. */
  7352. Component.prototype.getOption = function getOption(name) {
  7353. var value;
  7354. if (this.options) {
  7355. value = this.options[name];
  7356. }
  7357. if (value === undefined && this.defaultOptions) {
  7358. value = this.defaultOptions[name];
  7359. }
  7360. return value;
  7361. };
  7362. /**
  7363. * Get the container element of the component, which can be used by a child to
  7364. * add its own widgets. Not all components do have a container for childs, in
  7365. * that case null is returned.
  7366. * @returns {HTMLElement | null} container
  7367. */
  7368. // TODO: get rid of the getContainer and getFrame methods, provide these via the options
  7369. Component.prototype.getContainer = function getContainer() {
  7370. // should be implemented by the component
  7371. return null;
  7372. };
  7373. /**
  7374. * Get the frame element of the component, the outer HTML DOM element.
  7375. * @returns {HTMLElement | null} frame
  7376. */
  7377. Component.prototype.getFrame = function getFrame() {
  7378. return this.frame;
  7379. };
  7380. /**
  7381. * Repaint the component
  7382. * @return {Boolean} changed
  7383. */
  7384. Component.prototype.repaint = function repaint() {
  7385. // should be implemented by the component
  7386. return false;
  7387. };
  7388. /**
  7389. * Reflow the component
  7390. * @return {Boolean} resized
  7391. */
  7392. Component.prototype.reflow = function reflow() {
  7393. // should be implemented by the component
  7394. return false;
  7395. };
  7396. /**
  7397. * Hide the component from the DOM
  7398. * @return {Boolean} changed
  7399. */
  7400. Component.prototype.hide = function hide() {
  7401. if (this.frame && this.frame.parentNode) {
  7402. this.frame.parentNode.removeChild(this.frame);
  7403. return true;
  7404. }
  7405. else {
  7406. return false;
  7407. }
  7408. };
  7409. /**
  7410. * Show the component in the DOM (when not already visible).
  7411. * A repaint will be executed when the component is not visible
  7412. * @return {Boolean} changed
  7413. */
  7414. Component.prototype.show = function show() {
  7415. if (!this.frame || !this.frame.parentNode) {
  7416. return this.repaint();
  7417. }
  7418. else {
  7419. return false;
  7420. }
  7421. };
  7422. /**
  7423. * Request a repaint. The controller will schedule a repaint
  7424. */
  7425. Component.prototype.requestRepaint = function requestRepaint() {
  7426. if (this.controller) {
  7427. this.controller.requestRepaint();
  7428. }
  7429. else {
  7430. throw new Error('Cannot request a repaint: no controller configured');
  7431. // TODO: just do a repaint when no parent is configured?
  7432. }
  7433. };
  7434. /**
  7435. * Request a reflow. The controller will schedule a reflow
  7436. */
  7437. Component.prototype.requestReflow = function requestReflow() {
  7438. if (this.controller) {
  7439. this.controller.requestReflow();
  7440. }
  7441. else {
  7442. throw new Error('Cannot request a reflow: no controller configured');
  7443. // TODO: just do a reflow when no parent is configured?
  7444. }
  7445. };
  7446. /**
  7447. * A panel can contain components
  7448. * @param {Component} [parent]
  7449. * @param {Component[]} [depends] Components on which this components depends
  7450. * (except for the parent)
  7451. * @param {Object} [options] Available parameters:
  7452. * {String | Number | function} [left]
  7453. * {String | Number | function} [top]
  7454. * {String | Number | function} [width]
  7455. * {String | Number | function} [height]
  7456. * {String | function} [className]
  7457. * @constructor Panel
  7458. * @extends Component
  7459. */
  7460. function Panel(parent, depends, options) {
  7461. this.id = util.randomUUID();
  7462. this.parent = parent;
  7463. this.depends = depends;
  7464. this.options = options || {};
  7465. }
  7466. Panel.prototype = new Component();
  7467. /**
  7468. * Set options. Will extend the current options.
  7469. * @param {Object} [options] Available parameters:
  7470. * {String | function} [className]
  7471. * {String | Number | function} [left]
  7472. * {String | Number | function} [top]
  7473. * {String | Number | function} [width]
  7474. * {String | Number | function} [height]
  7475. */
  7476. Panel.prototype.setOptions = Component.prototype.setOptions;
  7477. /**
  7478. * Get the container element of the panel, which can be used by a child to
  7479. * add its own widgets.
  7480. * @returns {HTMLElement} container
  7481. */
  7482. Panel.prototype.getContainer = function () {
  7483. return this.frame;
  7484. };
  7485. /**
  7486. * Repaint the component
  7487. * @return {Boolean} changed
  7488. */
  7489. Panel.prototype.repaint = function () {
  7490. var changed = 0,
  7491. update = util.updateProperty,
  7492. asSize = util.option.asSize,
  7493. options = this.options,
  7494. frame = this.frame;
  7495. if (!frame) {
  7496. frame = document.createElement('div');
  7497. frame.className = 'panel';
  7498. var className = options.className;
  7499. if (className) {
  7500. if (typeof className == 'function') {
  7501. util.addClassName(frame, String(className()));
  7502. }
  7503. else {
  7504. util.addClassName(frame, String(className));
  7505. }
  7506. }
  7507. this.frame = frame;
  7508. changed += 1;
  7509. }
  7510. if (!frame.parentNode) {
  7511. if (!this.parent) {
  7512. throw new Error('Cannot repaint panel: no parent attached');
  7513. }
  7514. var parentContainer = this.parent.getContainer();
  7515. if (!parentContainer) {
  7516. throw new Error('Cannot repaint panel: parent has no container element');
  7517. }
  7518. parentContainer.appendChild(frame);
  7519. changed += 1;
  7520. }
  7521. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  7522. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  7523. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  7524. changed += update(frame.style, 'height', asSize(options.height, '100%'));
  7525. return (changed > 0);
  7526. };
  7527. /**
  7528. * Reflow the component
  7529. * @return {Boolean} resized
  7530. */
  7531. Panel.prototype.reflow = function () {
  7532. var changed = 0,
  7533. update = util.updateProperty,
  7534. frame = this.frame;
  7535. if (frame) {
  7536. changed += update(this, 'top', frame.offsetTop);
  7537. changed += update(this, 'left', frame.offsetLeft);
  7538. changed += update(this, 'width', frame.offsetWidth);
  7539. changed += update(this, 'height', frame.offsetHeight);
  7540. }
  7541. else {
  7542. changed += 1;
  7543. }
  7544. return (changed > 0);
  7545. };
  7546. /**
  7547. * A root panel can hold components. The root panel must be initialized with
  7548. * a DOM element as container.
  7549. * @param {HTMLElement} container
  7550. * @param {Object} [options] Available parameters: see RootPanel.setOptions.
  7551. * @constructor RootPanel
  7552. * @extends Panel
  7553. */
  7554. function RootPanel(container, options) {
  7555. this.id = util.randomUUID();
  7556. this.container = container;
  7557. this.options = options || {};
  7558. this.defaultOptions = {
  7559. autoResize: true
  7560. };
  7561. this.listeners = {}; // event listeners
  7562. }
  7563. RootPanel.prototype = new Panel();
  7564. /**
  7565. * Set options. Will extend the current options.
  7566. * @param {Object} [options] Available parameters:
  7567. * {String | function} [className]
  7568. * {String | Number | function} [left]
  7569. * {String | Number | function} [top]
  7570. * {String | Number | function} [width]
  7571. * {String | Number | function} [height]
  7572. * {Boolean | function} [autoResize]
  7573. */
  7574. RootPanel.prototype.setOptions = Component.prototype.setOptions;
  7575. /**
  7576. * Repaint the component
  7577. * @return {Boolean} changed
  7578. */
  7579. RootPanel.prototype.repaint = function () {
  7580. var changed = 0,
  7581. update = util.updateProperty,
  7582. asSize = util.option.asSize,
  7583. options = this.options,
  7584. frame = this.frame;
  7585. if (!frame) {
  7586. frame = document.createElement('div');
  7587. this.frame = frame;
  7588. changed += 1;
  7589. }
  7590. if (!frame.parentNode) {
  7591. if (!this.container) {
  7592. throw new Error('Cannot repaint root panel: no container attached');
  7593. }
  7594. this.container.appendChild(frame);
  7595. changed += 1;
  7596. }
  7597. frame.className = 'vis timeline rootpanel ' + options.orientation;
  7598. var className = options.className;
  7599. if (className) {
  7600. util.addClassName(frame, util.option.asString(className));
  7601. }
  7602. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  7603. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  7604. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  7605. changed += update(frame.style, 'height', asSize(options.height, '100%'));
  7606. this._updateEventEmitters();
  7607. this._updateWatch();
  7608. return (changed > 0);
  7609. };
  7610. /**
  7611. * Reflow the component
  7612. * @return {Boolean} resized
  7613. */
  7614. RootPanel.prototype.reflow = function () {
  7615. var changed = 0,
  7616. update = util.updateProperty,
  7617. frame = this.frame;
  7618. if (frame) {
  7619. changed += update(this, 'top', frame.offsetTop);
  7620. changed += update(this, 'left', frame.offsetLeft);
  7621. changed += update(this, 'width', frame.offsetWidth);
  7622. changed += update(this, 'height', frame.offsetHeight);
  7623. }
  7624. else {
  7625. changed += 1;
  7626. }
  7627. return (changed > 0);
  7628. };
  7629. /**
  7630. * Update watching for resize, depending on the current option
  7631. * @private
  7632. */
  7633. RootPanel.prototype._updateWatch = function () {
  7634. var autoResize = this.getOption('autoResize');
  7635. if (autoResize) {
  7636. this._watch();
  7637. }
  7638. else {
  7639. this._unwatch();
  7640. }
  7641. };
  7642. /**
  7643. * Watch for changes in the size of the frame. On resize, the Panel will
  7644. * automatically redraw itself.
  7645. * @private
  7646. */
  7647. RootPanel.prototype._watch = function () {
  7648. var me = this;
  7649. this._unwatch();
  7650. var checkSize = function () {
  7651. var autoResize = me.getOption('autoResize');
  7652. if (!autoResize) {
  7653. // stop watching when the option autoResize is changed to false
  7654. me._unwatch();
  7655. return;
  7656. }
  7657. if (me.frame) {
  7658. // check whether the frame is resized
  7659. if ((me.frame.clientWidth != me.width) ||
  7660. (me.frame.clientHeight != me.height)) {
  7661. me.requestReflow();
  7662. }
  7663. }
  7664. };
  7665. // TODO: automatically cleanup the event listener when the frame is deleted
  7666. util.addEventListener(window, 'resize', checkSize);
  7667. this.watchTimer = setInterval(checkSize, 1000);
  7668. };
  7669. /**
  7670. * Stop watching for a resize of the frame.
  7671. * @private
  7672. */
  7673. RootPanel.prototype._unwatch = function () {
  7674. if (this.watchTimer) {
  7675. clearInterval(this.watchTimer);
  7676. this.watchTimer = undefined;
  7677. }
  7678. // TODO: remove event listener on window.resize
  7679. };
  7680. /**
  7681. * Event handler
  7682. * @param {String} event name of the event, for example 'click', 'mousemove'
  7683. * @param {function} callback callback handler, invoked with the raw HTML Event
  7684. * as parameter.
  7685. */
  7686. RootPanel.prototype.on = function (event, callback) {
  7687. // register the listener at this component
  7688. var arr = this.listeners[event];
  7689. if (!arr) {
  7690. arr = [];
  7691. this.listeners[event] = arr;
  7692. }
  7693. arr.push(callback);
  7694. this._updateEventEmitters();
  7695. };
  7696. /**
  7697. * Update the event listeners for all event emitters
  7698. * @private
  7699. */
  7700. RootPanel.prototype._updateEventEmitters = function () {
  7701. if (this.listeners) {
  7702. var me = this;
  7703. util.forEach(this.listeners, function (listeners, event) {
  7704. if (!me.emitters) {
  7705. me.emitters = {};
  7706. }
  7707. if (!(event in me.emitters)) {
  7708. // create event
  7709. var frame = me.frame;
  7710. if (frame) {
  7711. //console.log('Created a listener for event ' + event + ' on component ' + me.id); // TODO: cleanup logging
  7712. var callback = function(event) {
  7713. listeners.forEach(function (listener) {
  7714. // TODO: filter on event target!
  7715. listener(event);
  7716. });
  7717. };
  7718. me.emitters[event] = callback;
  7719. if (!me.hammer) {
  7720. me.hammer = Hammer(frame, {
  7721. prevent_default: true
  7722. });
  7723. }
  7724. me.hammer.on(event, callback);
  7725. }
  7726. }
  7727. });
  7728. // TODO: be able to delete event listeners
  7729. // TODO: be able to move event listeners to a parent when available
  7730. }
  7731. };
  7732. /**
  7733. * A horizontal time axis
  7734. * @param {Component} parent
  7735. * @param {Component[]} [depends] Components on which this components depends
  7736. * (except for the parent)
  7737. * @param {Object} [options] See TimeAxis.setOptions for the available
  7738. * options.
  7739. * @constructor TimeAxis
  7740. * @extends Component
  7741. */
  7742. function TimeAxis (parent, depends, options) {
  7743. this.id = util.randomUUID();
  7744. this.parent = parent;
  7745. this.depends = depends;
  7746. this.dom = {
  7747. majorLines: [],
  7748. majorTexts: [],
  7749. minorLines: [],
  7750. minorTexts: [],
  7751. redundant: {
  7752. majorLines: [],
  7753. majorTexts: [],
  7754. minorLines: [],
  7755. minorTexts: []
  7756. }
  7757. };
  7758. this.props = {
  7759. range: {
  7760. start: 0,
  7761. end: 0,
  7762. minimumStep: 0
  7763. },
  7764. lineTop: 0
  7765. };
  7766. this.options = options || {};
  7767. this.defaultOptions = {
  7768. orientation: 'bottom', // supported: 'top', 'bottom'
  7769. // TODO: implement timeaxis orientations 'left' and 'right'
  7770. showMinorLabels: true,
  7771. showMajorLabels: true
  7772. };
  7773. this.conversion = null;
  7774. this.range = null;
  7775. }
  7776. TimeAxis.prototype = new Component();
  7777. // TODO: comment options
  7778. TimeAxis.prototype.setOptions = Component.prototype.setOptions;
  7779. /**
  7780. * Set a range (start and end)
  7781. * @param {Range | Object} range A Range or an object containing start and end.
  7782. */
  7783. TimeAxis.prototype.setRange = function (range) {
  7784. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  7785. throw new TypeError('Range must be an instance of Range, ' +
  7786. 'or an object containing start and end.');
  7787. }
  7788. this.range = range;
  7789. };
  7790. /**
  7791. * Convert a position on screen (pixels) to a datetime
  7792. * @param {int} x Position on the screen in pixels
  7793. * @return {Date} time The datetime the corresponds with given position x
  7794. */
  7795. TimeAxis.prototype.toTime = function(x) {
  7796. var conversion = this.conversion;
  7797. return new Date(x / conversion.scale + conversion.offset);
  7798. };
  7799. /**
  7800. * Convert a datetime (Date object) into a position on the screen
  7801. * @param {Date} time A date
  7802. * @return {int} x The position on the screen in pixels which corresponds
  7803. * with the given date.
  7804. * @private
  7805. */
  7806. TimeAxis.prototype.toScreen = function(time) {
  7807. var conversion = this.conversion;
  7808. return (time.valueOf() - conversion.offset) * conversion.scale;
  7809. };
  7810. /**
  7811. * Repaint the component
  7812. * @return {Boolean} changed
  7813. */
  7814. TimeAxis.prototype.repaint = function () {
  7815. var changed = 0,
  7816. update = util.updateProperty,
  7817. asSize = util.option.asSize,
  7818. options = this.options,
  7819. orientation = this.getOption('orientation'),
  7820. props = this.props,
  7821. step = this.step;
  7822. var frame = this.frame;
  7823. if (!frame) {
  7824. frame = document.createElement('div');
  7825. this.frame = frame;
  7826. changed += 1;
  7827. }
  7828. frame.className = 'axis';
  7829. // TODO: custom className?
  7830. if (!frame.parentNode) {
  7831. if (!this.parent) {
  7832. throw new Error('Cannot repaint time axis: no parent attached');
  7833. }
  7834. var parentContainer = this.parent.getContainer();
  7835. if (!parentContainer) {
  7836. throw new Error('Cannot repaint time axis: parent has no container element');
  7837. }
  7838. parentContainer.appendChild(frame);
  7839. changed += 1;
  7840. }
  7841. var parent = frame.parentNode;
  7842. if (parent) {
  7843. var beforeChild = frame.nextSibling;
  7844. parent.removeChild(frame); // take frame offline while updating (is almost twice as fast)
  7845. var defaultTop = (orientation == 'bottom' && this.props.parentHeight && this.height) ?
  7846. (this.props.parentHeight - this.height) + 'px' :
  7847. '0px';
  7848. changed += update(frame.style, 'top', asSize(options.top, defaultTop));
  7849. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  7850. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  7851. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  7852. // get characters width and height
  7853. this._repaintMeasureChars();
  7854. if (this.step) {
  7855. this._repaintStart();
  7856. step.first();
  7857. var xFirstMajorLabel = undefined;
  7858. var max = 0;
  7859. while (step.hasNext() && max < 1000) {
  7860. max++;
  7861. var cur = step.getCurrent(),
  7862. x = this.toScreen(cur),
  7863. isMajor = step.isMajor();
  7864. // TODO: lines must have a width, such that we can create css backgrounds
  7865. if (this.getOption('showMinorLabels')) {
  7866. this._repaintMinorText(x, step.getLabelMinor());
  7867. }
  7868. if (isMajor && this.getOption('showMajorLabels')) {
  7869. if (x > 0) {
  7870. if (xFirstMajorLabel == undefined) {
  7871. xFirstMajorLabel = x;
  7872. }
  7873. this._repaintMajorText(x, step.getLabelMajor());
  7874. }
  7875. this._repaintMajorLine(x);
  7876. }
  7877. else {
  7878. this._repaintMinorLine(x);
  7879. }
  7880. step.next();
  7881. }
  7882. // create a major label on the left when needed
  7883. if (this.getOption('showMajorLabels')) {
  7884. var leftTime = this.toTime(0),
  7885. leftText = step.getLabelMajor(leftTime),
  7886. widthText = leftText.length * (props.majorCharWidth || 10) + 10; // upper bound estimation
  7887. if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) {
  7888. this._repaintMajorText(0, leftText);
  7889. }
  7890. }
  7891. this._repaintEnd();
  7892. }
  7893. this._repaintLine();
  7894. // put frame online again
  7895. if (beforeChild) {
  7896. parent.insertBefore(frame, beforeChild);
  7897. }
  7898. else {
  7899. parent.appendChild(frame)
  7900. }
  7901. }
  7902. return (changed > 0);
  7903. };
  7904. /**
  7905. * Start a repaint. Move all DOM elements to a redundant list, where they
  7906. * can be picked for re-use, or can be cleaned up in the end
  7907. * @private
  7908. */
  7909. TimeAxis.prototype._repaintStart = function () {
  7910. var dom = this.dom,
  7911. redundant = dom.redundant;
  7912. redundant.majorLines = dom.majorLines;
  7913. redundant.majorTexts = dom.majorTexts;
  7914. redundant.minorLines = dom.minorLines;
  7915. redundant.minorTexts = dom.minorTexts;
  7916. dom.majorLines = [];
  7917. dom.majorTexts = [];
  7918. dom.minorLines = [];
  7919. dom.minorTexts = [];
  7920. };
  7921. /**
  7922. * End a repaint. Cleanup leftover DOM elements in the redundant list
  7923. * @private
  7924. */
  7925. TimeAxis.prototype._repaintEnd = function () {
  7926. util.forEach(this.dom.redundant, function (arr) {
  7927. while (arr.length) {
  7928. var elem = arr.pop();
  7929. if (elem && elem.parentNode) {
  7930. elem.parentNode.removeChild(elem);
  7931. }
  7932. }
  7933. });
  7934. };
  7935. /**
  7936. * Create a minor label for the axis at position x
  7937. * @param {Number} x
  7938. * @param {String} text
  7939. * @private
  7940. */
  7941. TimeAxis.prototype._repaintMinorText = function (x, text) {
  7942. // reuse redundant label
  7943. var label = this.dom.redundant.minorTexts.shift();
  7944. if (!label) {
  7945. // create new label
  7946. var content = document.createTextNode('');
  7947. label = document.createElement('div');
  7948. label.appendChild(content);
  7949. label.className = 'text minor';
  7950. this.frame.appendChild(label);
  7951. }
  7952. this.dom.minorTexts.push(label);
  7953. label.childNodes[0].nodeValue = text;
  7954. label.style.left = x + 'px';
  7955. label.style.top = this.props.minorLabelTop + 'px';
  7956. //label.title = title; // TODO: this is a heavy operation
  7957. };
  7958. /**
  7959. * Create a Major label for the axis at position x
  7960. * @param {Number} x
  7961. * @param {String} text
  7962. * @private
  7963. */
  7964. TimeAxis.prototype._repaintMajorText = function (x, text) {
  7965. // reuse redundant label
  7966. var label = this.dom.redundant.majorTexts.shift();
  7967. if (!label) {
  7968. // create label
  7969. var content = document.createTextNode(text);
  7970. label = document.createElement('div');
  7971. label.className = 'text major';
  7972. label.appendChild(content);
  7973. this.frame.appendChild(label);
  7974. }
  7975. this.dom.majorTexts.push(label);
  7976. label.childNodes[0].nodeValue = text;
  7977. label.style.top = this.props.majorLabelTop + 'px';
  7978. label.style.left = x + 'px';
  7979. //label.title = title; // TODO: this is a heavy operation
  7980. };
  7981. /**
  7982. * Create a minor line for the axis at position x
  7983. * @param {Number} x
  7984. * @private
  7985. */
  7986. TimeAxis.prototype._repaintMinorLine = function (x) {
  7987. // reuse redundant line
  7988. var line = this.dom.redundant.minorLines.shift();
  7989. if (!line) {
  7990. // create vertical line
  7991. line = document.createElement('div');
  7992. line.className = 'grid vertical minor';
  7993. this.frame.appendChild(line);
  7994. }
  7995. this.dom.minorLines.push(line);
  7996. var props = this.props;
  7997. line.style.top = props.minorLineTop + 'px';
  7998. line.style.height = props.minorLineHeight + 'px';
  7999. line.style.left = (x - props.minorLineWidth / 2) + 'px';
  8000. };
  8001. /**
  8002. * Create a Major line for the axis at position x
  8003. * @param {Number} x
  8004. * @private
  8005. */
  8006. TimeAxis.prototype._repaintMajorLine = function (x) {
  8007. // reuse redundant line
  8008. var line = this.dom.redundant.majorLines.shift();
  8009. if (!line) {
  8010. // create vertical line
  8011. line = document.createElement('DIV');
  8012. line.className = 'grid vertical major';
  8013. this.frame.appendChild(line);
  8014. }
  8015. this.dom.majorLines.push(line);
  8016. var props = this.props;
  8017. line.style.top = props.majorLineTop + 'px';
  8018. line.style.left = (x - props.majorLineWidth / 2) + 'px';
  8019. line.style.height = props.majorLineHeight + 'px';
  8020. };
  8021. /**
  8022. * Repaint the horizontal line for the axis
  8023. * @private
  8024. */
  8025. TimeAxis.prototype._repaintLine = function() {
  8026. var line = this.dom.line,
  8027. frame = this.frame,
  8028. options = this.options;
  8029. // line before all axis elements
  8030. if (this.getOption('showMinorLabels') || this.getOption('showMajorLabels')) {
  8031. if (line) {
  8032. // put this line at the end of all childs
  8033. frame.removeChild(line);
  8034. frame.appendChild(line);
  8035. }
  8036. else {
  8037. // create the axis line
  8038. line = document.createElement('div');
  8039. line.className = 'grid horizontal major';
  8040. frame.appendChild(line);
  8041. this.dom.line = line;
  8042. }
  8043. line.style.top = this.props.lineTop + 'px';
  8044. }
  8045. else {
  8046. if (line && line.parentElement) {
  8047. frame.removeChild(line.line);
  8048. delete this.dom.line;
  8049. }
  8050. }
  8051. };
  8052. /**
  8053. * Create characters used to determine the size of text on the axis
  8054. * @private
  8055. */
  8056. TimeAxis.prototype._repaintMeasureChars = function () {
  8057. // calculate the width and height of a single character
  8058. // this is used to calculate the step size, and also the positioning of the
  8059. // axis
  8060. var dom = this.dom,
  8061. text;
  8062. if (!dom.measureCharMinor) {
  8063. text = document.createTextNode('0');
  8064. var measureCharMinor = document.createElement('DIV');
  8065. measureCharMinor.className = 'text minor measure';
  8066. measureCharMinor.appendChild(text);
  8067. this.frame.appendChild(measureCharMinor);
  8068. dom.measureCharMinor = measureCharMinor;
  8069. }
  8070. if (!dom.measureCharMajor) {
  8071. text = document.createTextNode('0');
  8072. var measureCharMajor = document.createElement('DIV');
  8073. measureCharMajor.className = 'text major measure';
  8074. measureCharMajor.appendChild(text);
  8075. this.frame.appendChild(measureCharMajor);
  8076. dom.measureCharMajor = measureCharMajor;
  8077. }
  8078. };
  8079. /**
  8080. * Reflow the component
  8081. * @return {Boolean} resized
  8082. */
  8083. TimeAxis.prototype.reflow = function () {
  8084. var changed = 0,
  8085. update = util.updateProperty,
  8086. frame = this.frame,
  8087. range = this.range;
  8088. if (!range) {
  8089. throw new Error('Cannot repaint time axis: no range configured');
  8090. }
  8091. if (frame) {
  8092. changed += update(this, 'top', frame.offsetTop);
  8093. changed += update(this, 'left', frame.offsetLeft);
  8094. // calculate size of a character
  8095. var props = this.props,
  8096. showMinorLabels = this.getOption('showMinorLabels'),
  8097. showMajorLabels = this.getOption('showMajorLabels'),
  8098. measureCharMinor = this.dom.measureCharMinor,
  8099. measureCharMajor = this.dom.measureCharMajor;
  8100. if (measureCharMinor) {
  8101. props.minorCharHeight = measureCharMinor.clientHeight;
  8102. props.minorCharWidth = measureCharMinor.clientWidth;
  8103. }
  8104. if (measureCharMajor) {
  8105. props.majorCharHeight = measureCharMajor.clientHeight;
  8106. props.majorCharWidth = measureCharMajor.clientWidth;
  8107. }
  8108. var parentHeight = frame.parentNode ? frame.parentNode.offsetHeight : 0;
  8109. if (parentHeight != props.parentHeight) {
  8110. props.parentHeight = parentHeight;
  8111. changed += 1;
  8112. }
  8113. switch (this.getOption('orientation')) {
  8114. case 'bottom':
  8115. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  8116. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  8117. props.minorLabelTop = 0;
  8118. props.majorLabelTop = props.minorLabelTop + props.minorLabelHeight;
  8119. props.minorLineTop = -this.top;
  8120. props.minorLineHeight = Math.max(this.top + props.majorLabelHeight, 0);
  8121. props.minorLineWidth = 1; // TODO: really calculate width
  8122. props.majorLineTop = -this.top;
  8123. props.majorLineHeight = Math.max(this.top + props.minorLabelHeight + props.majorLabelHeight, 0);
  8124. props.majorLineWidth = 1; // TODO: really calculate width
  8125. props.lineTop = 0;
  8126. break;
  8127. case 'top':
  8128. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  8129. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  8130. props.majorLabelTop = 0;
  8131. props.minorLabelTop = props.majorLabelTop + props.majorLabelHeight;
  8132. props.minorLineTop = props.minorLabelTop;
  8133. props.minorLineHeight = Math.max(parentHeight - props.majorLabelHeight - this.top);
  8134. props.minorLineWidth = 1; // TODO: really calculate width
  8135. props.majorLineTop = 0;
  8136. props.majorLineHeight = Math.max(parentHeight - this.top);
  8137. props.majorLineWidth = 1; // TODO: really calculate width
  8138. props.lineTop = props.majorLabelHeight + props.minorLabelHeight;
  8139. break;
  8140. default:
  8141. throw new Error('Unkown orientation "' + this.getOption('orientation') + '"');
  8142. }
  8143. var height = props.minorLabelHeight + props.majorLabelHeight;
  8144. changed += update(this, 'width', frame.offsetWidth);
  8145. changed += update(this, 'height', height);
  8146. // calculate range and step
  8147. this._updateConversion();
  8148. var start = util.convert(range.start, 'Number'),
  8149. end = util.convert(range.end, 'Number'),
  8150. minimumStep = this.toTime((props.minorCharWidth || 10) * 5).valueOf()
  8151. -this.toTime(0).valueOf();
  8152. this.step = new TimeStep(new Date(start), new Date(end), minimumStep);
  8153. changed += update(props.range, 'start', start);
  8154. changed += update(props.range, 'end', end);
  8155. changed += update(props.range, 'minimumStep', minimumStep.valueOf());
  8156. }
  8157. return (changed > 0);
  8158. };
  8159. /**
  8160. * Calculate the scale and offset to convert a position on screen to the
  8161. * corresponding date and vice versa.
  8162. * After the method _updateConversion is executed once, the methods toTime
  8163. * and toScreen can be used.
  8164. * @private
  8165. */
  8166. TimeAxis.prototype._updateConversion = function() {
  8167. var range = this.range;
  8168. if (!range) {
  8169. throw new Error('No range configured');
  8170. }
  8171. if (range.conversion) {
  8172. this.conversion = range.conversion(this.width);
  8173. }
  8174. else {
  8175. this.conversion = Range.conversion(range.start, range.end, this.width);
  8176. }
  8177. };
  8178. /**
  8179. * A current time bar
  8180. * @param {Component} parent
  8181. * @param {Component[]} [depends] Components on which this components depends
  8182. * (except for the parent)
  8183. * @param {Object} [options] Available parameters:
  8184. * {Boolean} [showCurrentTime]
  8185. * @constructor CurrentTime
  8186. * @extends Component
  8187. */
  8188. function CurrentTime (parent, depends, options) {
  8189. this.id = util.randomUUID();
  8190. this.parent = parent;
  8191. this.depends = depends;
  8192. this.options = options || {};
  8193. this.defaultOptions = {
  8194. showCurrentTime: false
  8195. };
  8196. }
  8197. CurrentTime.prototype = new Component();
  8198. CurrentTime.prototype.setOptions = Component.prototype.setOptions;
  8199. /**
  8200. * Get the container element of the bar, which can be used by a child to
  8201. * add its own widgets.
  8202. * @returns {HTMLElement} container
  8203. */
  8204. CurrentTime.prototype.getContainer = function () {
  8205. return this.frame;
  8206. };
  8207. /**
  8208. * Repaint the component
  8209. * @return {Boolean} changed
  8210. */
  8211. CurrentTime.prototype.repaint = function () {
  8212. var bar = this.frame,
  8213. parent = this.parent,
  8214. parentContainer = parent.parent.getContainer();
  8215. if (!parent) {
  8216. throw new Error('Cannot repaint bar: no parent attached');
  8217. }
  8218. if (!parentContainer) {
  8219. throw new Error('Cannot repaint bar: parent has no container element');
  8220. }
  8221. if (!this.getOption('showCurrentTime')) {
  8222. if (bar) {
  8223. parentContainer.removeChild(bar);
  8224. delete this.frame;
  8225. }
  8226. return;
  8227. }
  8228. if (!bar) {
  8229. bar = document.createElement('div');
  8230. bar.className = 'currenttime';
  8231. bar.style.position = 'absolute';
  8232. bar.style.top = '0px';
  8233. bar.style.height = '100%';
  8234. parentContainer.appendChild(bar);
  8235. this.frame = bar;
  8236. }
  8237. if (!parent.conversion) {
  8238. parent._updateConversion();
  8239. }
  8240. var now = new Date();
  8241. var x = parent.toScreen(now);
  8242. bar.style.left = x + 'px';
  8243. bar.title = 'Current time: ' + now;
  8244. // start a timer to adjust for the new time
  8245. if (this.currentTimeTimer !== undefined) {
  8246. clearTimeout(this.currentTimeTimer);
  8247. delete this.currentTimeTimer;
  8248. }
  8249. var timeline = this;
  8250. var interval = 1 / parent.conversion.scale / 2;
  8251. if (interval < 30) {
  8252. interval = 30;
  8253. }
  8254. this.currentTimeTimer = setTimeout(function() {
  8255. timeline.repaint();
  8256. }, interval);
  8257. return false;
  8258. };
  8259. /**
  8260. * A custom time bar
  8261. * @param {Component} parent
  8262. * @param {Component[]} [depends] Components on which this components depends
  8263. * (except for the parent)
  8264. * @param {Object} [options] Available parameters:
  8265. * {Boolean} [showCustomTime]
  8266. * @constructor CustomTime
  8267. * @extends Component
  8268. */
  8269. function CustomTime (parent, depends, options) {
  8270. this.id = util.randomUUID();
  8271. this.parent = parent;
  8272. this.depends = depends;
  8273. this.options = options || {};
  8274. this.defaultOptions = {
  8275. showCustomTime: false
  8276. };
  8277. this.listeners = [];
  8278. this.customTime = new Date();
  8279. }
  8280. CustomTime.prototype = new Component();
  8281. CustomTime.prototype.setOptions = Component.prototype.setOptions;
  8282. /**
  8283. * Get the container element of the bar, which can be used by a child to
  8284. * add its own widgets.
  8285. * @returns {HTMLElement} container
  8286. */
  8287. CustomTime.prototype.getContainer = function () {
  8288. return this.frame;
  8289. };
  8290. /**
  8291. * Repaint the component
  8292. * @return {Boolean} changed
  8293. */
  8294. CustomTime.prototype.repaint = function () {
  8295. var bar = this.frame,
  8296. parent = this.parent,
  8297. parentContainer = parent.parent.getContainer();
  8298. if (!parent) {
  8299. throw new Error('Cannot repaint bar: no parent attached');
  8300. }
  8301. if (!parentContainer) {
  8302. throw new Error('Cannot repaint bar: parent has no container element');
  8303. }
  8304. if (!this.getOption('showCustomTime')) {
  8305. if (bar) {
  8306. parentContainer.removeChild(bar);
  8307. delete this.frame;
  8308. }
  8309. return;
  8310. }
  8311. if (!bar) {
  8312. bar = document.createElement('div');
  8313. bar.className = 'customtime';
  8314. bar.style.position = 'absolute';
  8315. bar.style.top = '0px';
  8316. bar.style.height = '100%';
  8317. parentContainer.appendChild(bar);
  8318. var drag = document.createElement('div');
  8319. drag.style.position = 'relative';
  8320. drag.style.top = '0px';
  8321. drag.style.left = '-10px';
  8322. drag.style.height = '100%';
  8323. drag.style.width = '20px';
  8324. bar.appendChild(drag);
  8325. this.frame = bar;
  8326. this.subscribe(this, 'movetime');
  8327. }
  8328. if (!parent.conversion) {
  8329. parent._updateConversion();
  8330. }
  8331. var x = parent.toScreen(this.customTime);
  8332. bar.style.left = x + 'px';
  8333. bar.title = 'Time: ' + this.customTime;
  8334. return false;
  8335. };
  8336. /**
  8337. * Set custom time.
  8338. * @param {Date} time
  8339. */
  8340. CustomTime.prototype._setCustomTime = function(time) {
  8341. this.customTime = new Date(time.valueOf());
  8342. this.repaint();
  8343. };
  8344. /**
  8345. * Retrieve the current custom time.
  8346. * @return {Date} customTime
  8347. */
  8348. CustomTime.prototype._getCustomTime = function() {
  8349. return new Date(this.customTime.valueOf());
  8350. };
  8351. /**
  8352. * Add listeners for mouse and touch events to the component
  8353. * @param {Component} component
  8354. */
  8355. CustomTime.prototype.subscribe = function (component, event) {
  8356. var me = this;
  8357. var listener = {
  8358. component: component,
  8359. event: event,
  8360. callback: function (event) {
  8361. me._onMouseDown(event, listener);
  8362. },
  8363. params: {}
  8364. };
  8365. component.on('mousedown', listener.callback);
  8366. me.listeners.push(listener);
  8367. };
  8368. /**
  8369. * Event handler
  8370. * @param {String} event name of the event, for example 'click', 'mousemove'
  8371. * @param {function} callback callback handler, invoked with the raw HTML Event
  8372. * as parameter.
  8373. */
  8374. CustomTime.prototype.on = function (event, callback) {
  8375. var bar = this.frame;
  8376. if (!bar) {
  8377. throw new Error('Cannot add event listener: no parent attached');
  8378. }
  8379. events.addListener(this, event, callback);
  8380. util.addEventListener(bar, event, callback);
  8381. };
  8382. /**
  8383. * Start moving horizontally
  8384. * @param {Event} event
  8385. * @param {Object} listener Listener containing the component and params
  8386. * @private
  8387. */
  8388. CustomTime.prototype._onMouseDown = function(event, listener) {
  8389. event = event || window.event;
  8390. var params = listener.params;
  8391. // only react on left mouse button down
  8392. var leftButtonDown = event.which ? (event.which == 1) : (event.button == 1);
  8393. if (!leftButtonDown) {
  8394. return;
  8395. }
  8396. // get mouse position
  8397. params.mouseX = util.getPageX(event);
  8398. params.moved = false;
  8399. params.customTime = this.customTime;
  8400. // add event listeners to handle moving the custom time bar
  8401. var me = this;
  8402. if (!params.onMouseMove) {
  8403. params.onMouseMove = function (event) {
  8404. me._onMouseMove(event, listener);
  8405. };
  8406. util.addEventListener(document, 'mousemove', params.onMouseMove);
  8407. }
  8408. if (!params.onMouseUp) {
  8409. params.onMouseUp = function (event) {
  8410. me._onMouseUp(event, listener);
  8411. };
  8412. util.addEventListener(document, 'mouseup', params.onMouseUp);
  8413. }
  8414. util.stopPropagation(event);
  8415. util.preventDefault(event);
  8416. };
  8417. /**
  8418. * Perform moving operating.
  8419. * This function activated from within the funcion CustomTime._onMouseDown().
  8420. * @param {Event} event
  8421. * @param {Object} listener
  8422. * @private
  8423. */
  8424. CustomTime.prototype._onMouseMove = function (event, listener) {
  8425. event = event || window.event;
  8426. var params = listener.params;
  8427. var parent = this.parent;
  8428. // calculate change in mouse position
  8429. var mouseX = util.getPageX(event);
  8430. if (params.mouseX === undefined) {
  8431. params.mouseX = mouseX;
  8432. }
  8433. var diff = mouseX - params.mouseX;
  8434. // if mouse movement is big enough, register it as a "moved" event
  8435. if (Math.abs(diff) >= 1) {
  8436. params.moved = true;
  8437. }
  8438. var x = parent.toScreen(params.customTime);
  8439. var xnew = x + diff;
  8440. var time = parent.toTime(xnew);
  8441. this._setCustomTime(time);
  8442. // fire a timechange event
  8443. events.trigger(this, 'timechange', {customTime: this.customTime});
  8444. util.preventDefault(event);
  8445. };
  8446. /**
  8447. * Stop moving operating.
  8448. * This function activated from within the function CustomTime._onMouseDown().
  8449. * @param {event} event
  8450. * @param {Object} listener
  8451. * @private
  8452. */
  8453. CustomTime.prototype._onMouseUp = function (event, listener) {
  8454. event = event || window.event;
  8455. var params = listener.params;
  8456. // remove event listeners here, important for Safari
  8457. if (params.onMouseMove) {
  8458. util.removeEventListener(document, 'mousemove', params.onMouseMove);
  8459. params.onMouseMove = null;
  8460. }
  8461. if (params.onMouseUp) {
  8462. util.removeEventListener(document, 'mouseup', params.onMouseUp);
  8463. params.onMouseUp = null;
  8464. }
  8465. if (params.moved) {
  8466. // fire a timechanged event
  8467. events.trigger(this, 'timechanged', {customTime: this.customTime});
  8468. }
  8469. };
  8470. /**
  8471. * An ItemSet holds a set of items and ranges which can be displayed in a
  8472. * range. The width is determined by the parent of the ItemSet, and the height
  8473. * is determined by the size of the items.
  8474. * @param {Component} parent
  8475. * @param {Component[]} [depends] Components on which this components depends
  8476. * (except for the parent)
  8477. * @param {Object} [options] See ItemSet.setOptions for the available
  8478. * options.
  8479. * @constructor ItemSet
  8480. * @extends Panel
  8481. */
  8482. // TODO: improve performance by replacing all Array.forEach with a for loop
  8483. function ItemSet(parent, depends, options) {
  8484. this.id = util.randomUUID();
  8485. this.parent = parent;
  8486. this.depends = depends;
  8487. // one options object is shared by this itemset and all its items
  8488. this.options = options || {};
  8489. this.defaultOptions = {
  8490. type: 'box',
  8491. align: 'center',
  8492. orientation: 'bottom',
  8493. margin: {
  8494. axis: 20,
  8495. item: 10
  8496. },
  8497. padding: 5
  8498. };
  8499. this.dom = {};
  8500. var me = this;
  8501. this.itemsData = null; // DataSet
  8502. this.range = null; // Range or Object {start: number, end: number}
  8503. this.listeners = {
  8504. 'add': function (event, params, senderId) {
  8505. if (senderId != me.id) {
  8506. me._onAdd(params.items);
  8507. }
  8508. },
  8509. 'update': function (event, params, senderId) {
  8510. if (senderId != me.id) {
  8511. me._onUpdate(params.items);
  8512. }
  8513. },
  8514. 'remove': function (event, params, senderId) {
  8515. if (senderId != me.id) {
  8516. me._onRemove(params.items);
  8517. }
  8518. }
  8519. };
  8520. this.items = {}; // object with an Item for every data item
  8521. this.queue = {}; // queue with id/actions: 'add', 'update', 'delete'
  8522. this.stack = new Stack(this, Object.create(this.options));
  8523. this.conversion = null;
  8524. // TODO: ItemSet should also attach event listeners for rangechange and rangechanged, like timeaxis
  8525. }
  8526. ItemSet.prototype = new Panel();
  8527. // available item types will be registered here
  8528. ItemSet.types = {
  8529. box: ItemBox,
  8530. range: ItemRange,
  8531. rangeoverflow: ItemRangeOverflow,
  8532. point: ItemPoint
  8533. };
  8534. /**
  8535. * Set options for the ItemSet. Existing options will be extended/overwritten.
  8536. * @param {Object} [options] The following options are available:
  8537. * {String | function} [className]
  8538. * class name for the itemset
  8539. * {String} [type]
  8540. * Default type for the items. Choose from 'box'
  8541. * (default), 'point', or 'range'. The default
  8542. * Style can be overwritten by individual items.
  8543. * {String} align
  8544. * Alignment for the items, only applicable for
  8545. * ItemBox. Choose 'center' (default), 'left', or
  8546. * 'right'.
  8547. * {String} orientation
  8548. * Orientation of the item set. Choose 'top' or
  8549. * 'bottom' (default).
  8550. * {Number} margin.axis
  8551. * Margin between the axis and the items in pixels.
  8552. * Default is 20.
  8553. * {Number} margin.item
  8554. * Margin between items in pixels. Default is 10.
  8555. * {Number} padding
  8556. * Padding of the contents of an item in pixels.
  8557. * Must correspond with the items css. Default is 5.
  8558. */
  8559. ItemSet.prototype.setOptions = Component.prototype.setOptions;
  8560. /**
  8561. * Set range (start and end).
  8562. * @param {Range | Object} range A Range or an object containing start and end.
  8563. */
  8564. ItemSet.prototype.setRange = function setRange(range) {
  8565. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  8566. throw new TypeError('Range must be an instance of Range, ' +
  8567. 'or an object containing start and end.');
  8568. }
  8569. this.range = range;
  8570. };
  8571. /**
  8572. * Repaint the component
  8573. * @return {Boolean} changed
  8574. */
  8575. ItemSet.prototype.repaint = function repaint() {
  8576. var changed = 0,
  8577. update = util.updateProperty,
  8578. asSize = util.option.asSize,
  8579. options = this.options,
  8580. orientation = this.getOption('orientation'),
  8581. defaultOptions = this.defaultOptions,
  8582. frame = this.frame;
  8583. if (!frame) {
  8584. frame = document.createElement('div');
  8585. frame.className = 'itemset';
  8586. var className = options.className;
  8587. if (className) {
  8588. util.addClassName(frame, util.option.asString(className));
  8589. }
  8590. // create background panel
  8591. var background = document.createElement('div');
  8592. background.className = 'background';
  8593. frame.appendChild(background);
  8594. this.dom.background = background;
  8595. // create foreground panel
  8596. var foreground = document.createElement('div');
  8597. foreground.className = 'foreground';
  8598. frame.appendChild(foreground);
  8599. this.dom.foreground = foreground;
  8600. // create axis panel
  8601. var axis = document.createElement('div');
  8602. axis.className = 'itemset-axis';
  8603. //frame.appendChild(axis);
  8604. this.dom.axis = axis;
  8605. this.frame = frame;
  8606. changed += 1;
  8607. }
  8608. if (!this.parent) {
  8609. throw new Error('Cannot repaint itemset: no parent attached');
  8610. }
  8611. var parentContainer = this.parent.getContainer();
  8612. if (!parentContainer) {
  8613. throw new Error('Cannot repaint itemset: parent has no container element');
  8614. }
  8615. if (!frame.parentNode) {
  8616. parentContainer.appendChild(frame);
  8617. changed += 1;
  8618. }
  8619. if (!this.dom.axis.parentNode) {
  8620. parentContainer.appendChild(this.dom.axis);
  8621. changed += 1;
  8622. }
  8623. // reposition frame
  8624. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  8625. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  8626. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  8627. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  8628. // reposition axis
  8629. changed += update(this.dom.axis.style, 'left', asSize(options.left, '0px'));
  8630. changed += update(this.dom.axis.style, 'width', asSize(options.width, '100%'));
  8631. if (orientation == 'bottom') {
  8632. changed += update(this.dom.axis.style, 'top', (this.height + this.top) + 'px');
  8633. }
  8634. else { // orientation == 'top'
  8635. changed += update(this.dom.axis.style, 'top', this.top + 'px');
  8636. }
  8637. this._updateConversion();
  8638. var me = this,
  8639. queue = this.queue,
  8640. itemsData = this.itemsData,
  8641. items = this.items,
  8642. dataOptions = {
  8643. // TODO: cleanup
  8644. // fields: [(itemsData && itemsData.fieldId || 'id'), 'start', 'end', 'content', 'type', 'className']
  8645. };
  8646. // show/hide added/changed/removed items
  8647. Object.keys(queue).forEach(function (id) {
  8648. //var entry = queue[id];
  8649. var action = queue[id];
  8650. var item = items[id];
  8651. //var item = entry.item;
  8652. //noinspection FallthroughInSwitchStatementJS
  8653. switch (action) {
  8654. case 'add':
  8655. case 'update':
  8656. var itemData = itemsData && itemsData.get(id, dataOptions);
  8657. if (itemData) {
  8658. var type = itemData.type ||
  8659. (itemData.start && itemData.end && 'range') ||
  8660. options.type ||
  8661. 'box';
  8662. var constructor = ItemSet.types[type];
  8663. // TODO: how to handle items with invalid data? hide them and give a warning? or throw an error?
  8664. if (item) {
  8665. // update item
  8666. if (!constructor || !(item instanceof constructor)) {
  8667. // item type has changed, hide and delete the item
  8668. changed += item.hide();
  8669. item = null;
  8670. }
  8671. else {
  8672. item.data = itemData; // TODO: create a method item.setData ?
  8673. changed++;
  8674. }
  8675. }
  8676. if (!item) {
  8677. // create item
  8678. if (constructor) {
  8679. item = new constructor(me, itemData, options, defaultOptions);
  8680. changed++;
  8681. }
  8682. else {
  8683. throw new TypeError('Unknown item type "' + type + '"');
  8684. }
  8685. }
  8686. // force a repaint (not only a reposition)
  8687. item.repaint();
  8688. items[id] = item;
  8689. }
  8690. // update queue
  8691. delete queue[id];
  8692. break;
  8693. case 'remove':
  8694. if (item) {
  8695. // remove DOM of the item
  8696. changed += item.hide();
  8697. }
  8698. // update lists
  8699. delete items[id];
  8700. delete queue[id];
  8701. break;
  8702. default:
  8703. console.log('Error: unknown action "' + action + '"');
  8704. }
  8705. });
  8706. // reposition all items. Show items only when in the visible area
  8707. util.forEach(this.items, function (item) {
  8708. if (item.visible) {
  8709. changed += item.show();
  8710. item.reposition();
  8711. }
  8712. else {
  8713. changed += item.hide();
  8714. }
  8715. });
  8716. return (changed > 0);
  8717. };
  8718. /**
  8719. * Get the foreground container element
  8720. * @return {HTMLElement} foreground
  8721. */
  8722. ItemSet.prototype.getForeground = function getForeground() {
  8723. return this.dom.foreground;
  8724. };
  8725. /**
  8726. * Get the background container element
  8727. * @return {HTMLElement} background
  8728. */
  8729. ItemSet.prototype.getBackground = function getBackground() {
  8730. return this.dom.background;
  8731. };
  8732. /**
  8733. * Get the axis container element
  8734. * @return {HTMLElement} axis
  8735. */
  8736. ItemSet.prototype.getAxis = function getAxis() {
  8737. return this.dom.axis;
  8738. };
  8739. /**
  8740. * Reflow the component
  8741. * @return {Boolean} resized
  8742. */
  8743. ItemSet.prototype.reflow = function reflow () {
  8744. var changed = 0,
  8745. options = this.options,
  8746. marginAxis = options.margin && options.margin.axis || this.defaultOptions.margin.axis,
  8747. marginItem = options.margin && options.margin.item || this.defaultOptions.margin.item,
  8748. update = util.updateProperty,
  8749. asNumber = util.option.asNumber,
  8750. asSize = util.option.asSize,
  8751. frame = this.frame;
  8752. if (frame) {
  8753. this._updateConversion();
  8754. util.forEach(this.items, function (item) {
  8755. changed += item.reflow();
  8756. });
  8757. // TODO: stack.update should be triggered via an event, in stack itself
  8758. // TODO: only update the stack when there are changed items
  8759. this.stack.update();
  8760. var maxHeight = asNumber(options.maxHeight);
  8761. var fixedHeight = (asSize(options.height) != null);
  8762. var height;
  8763. if (fixedHeight) {
  8764. height = frame.offsetHeight;
  8765. }
  8766. else {
  8767. // height is not specified, determine the height from the height and positioned items
  8768. var visibleItems = this.stack.ordered; // TODO: not so nice way to get the filtered items
  8769. if (visibleItems.length) {
  8770. var min = visibleItems[0].top;
  8771. var max = visibleItems[0].top + visibleItems[0].height;
  8772. util.forEach(visibleItems, function (item) {
  8773. min = Math.min(min, item.top);
  8774. max = Math.max(max, (item.top + item.height));
  8775. });
  8776. height = (max - min) + marginAxis + marginItem;
  8777. }
  8778. else {
  8779. height = marginAxis + marginItem;
  8780. }
  8781. }
  8782. if (maxHeight != null) {
  8783. height = Math.min(height, maxHeight);
  8784. }
  8785. changed += update(this, 'height', height);
  8786. // calculate height from items
  8787. changed += update(this, 'top', frame.offsetTop);
  8788. changed += update(this, 'left', frame.offsetLeft);
  8789. changed += update(this, 'width', frame.offsetWidth);
  8790. }
  8791. else {
  8792. changed += 1;
  8793. }
  8794. return (changed > 0);
  8795. };
  8796. /**
  8797. * Hide this component from the DOM
  8798. * @return {Boolean} changed
  8799. */
  8800. ItemSet.prototype.hide = function hide() {
  8801. var changed = false;
  8802. // remove the DOM
  8803. if (this.frame && this.frame.parentNode) {
  8804. this.frame.parentNode.removeChild(this.frame);
  8805. changed = true;
  8806. }
  8807. if (this.dom.axis && this.dom.axis.parentNode) {
  8808. this.dom.axis.parentNode.removeChild(this.dom.axis);
  8809. changed = true;
  8810. }
  8811. return changed;
  8812. };
  8813. /**
  8814. * Set items
  8815. * @param {vis.DataSet | null} items
  8816. */
  8817. ItemSet.prototype.setItems = function setItems(items) {
  8818. var me = this,
  8819. ids,
  8820. oldItemsData = this.itemsData;
  8821. // replace the dataset
  8822. if (!items) {
  8823. this.itemsData = null;
  8824. }
  8825. else if (items instanceof DataSet || items instanceof DataView) {
  8826. this.itemsData = items;
  8827. }
  8828. else {
  8829. throw new TypeError('Data must be an instance of DataSet');
  8830. }
  8831. if (oldItemsData) {
  8832. // unsubscribe from old dataset
  8833. util.forEach(this.listeners, function (callback, event) {
  8834. oldItemsData.unsubscribe(event, callback);
  8835. });
  8836. // remove all drawn items
  8837. ids = oldItemsData.getIds();
  8838. this._onRemove(ids);
  8839. }
  8840. if (this.itemsData) {
  8841. // subscribe to new dataset
  8842. var id = this.id;
  8843. util.forEach(this.listeners, function (callback, event) {
  8844. me.itemsData.subscribe(event, callback, id);
  8845. });
  8846. // draw all new items
  8847. ids = this.itemsData.getIds();
  8848. this._onAdd(ids);
  8849. }
  8850. };
  8851. /**
  8852. * Get the current items items
  8853. * @returns {vis.DataSet | null}
  8854. */
  8855. ItemSet.prototype.getItems = function getItems() {
  8856. return this.itemsData;
  8857. };
  8858. /**
  8859. * Handle updated items
  8860. * @param {Number[]} ids
  8861. * @private
  8862. */
  8863. ItemSet.prototype._onUpdate = function _onUpdate(ids) {
  8864. this._toQueue('update', ids);
  8865. };
  8866. /**
  8867. * Handle changed items
  8868. * @param {Number[]} ids
  8869. * @private
  8870. */
  8871. ItemSet.prototype._onAdd = function _onAdd(ids) {
  8872. this._toQueue('add', ids);
  8873. };
  8874. /**
  8875. * Handle removed items
  8876. * @param {Number[]} ids
  8877. * @private
  8878. */
  8879. ItemSet.prototype._onRemove = function _onRemove(ids) {
  8880. this._toQueue('remove', ids);
  8881. };
  8882. /**
  8883. * Put items in the queue to be added/updated/remove
  8884. * @param {String} action can be 'add', 'update', 'remove'
  8885. * @param {Number[]} ids
  8886. */
  8887. ItemSet.prototype._toQueue = function _toQueue(action, ids) {
  8888. var queue = this.queue;
  8889. ids.forEach(function (id) {
  8890. queue[id] = action;
  8891. });
  8892. if (this.controller) {
  8893. //this.requestReflow();
  8894. this.requestRepaint();
  8895. }
  8896. };
  8897. /**
  8898. * Calculate the scale and offset to convert a position on screen to the
  8899. * corresponding date and vice versa.
  8900. * After the method _updateConversion is executed once, the methods toTime
  8901. * and toScreen can be used.
  8902. * @private
  8903. */
  8904. ItemSet.prototype._updateConversion = function _updateConversion() {
  8905. var range = this.range;
  8906. if (!range) {
  8907. throw new Error('No range configured');
  8908. }
  8909. if (range.conversion) {
  8910. this.conversion = range.conversion(this.width);
  8911. }
  8912. else {
  8913. this.conversion = Range.conversion(range.start, range.end, this.width);
  8914. }
  8915. };
  8916. /**
  8917. * Convert a position on screen (pixels) to a datetime
  8918. * Before this method can be used, the method _updateConversion must be
  8919. * executed once.
  8920. * @param {int} x Position on the screen in pixels
  8921. * @return {Date} time The datetime the corresponds with given position x
  8922. */
  8923. ItemSet.prototype.toTime = function toTime(x) {
  8924. var conversion = this.conversion;
  8925. return new Date(x / conversion.scale + conversion.offset);
  8926. };
  8927. /**
  8928. * Convert a datetime (Date object) into a position on the screen
  8929. * Before this method can be used, the method _updateConversion must be
  8930. * executed once.
  8931. * @param {Date} time A date
  8932. * @return {int} x The position on the screen in pixels which corresponds
  8933. * with the given date.
  8934. */
  8935. ItemSet.prototype.toScreen = function toScreen(time) {
  8936. var conversion = this.conversion;
  8937. return (time.valueOf() - conversion.offset) * conversion.scale;
  8938. };
  8939. /**
  8940. * @constructor Item
  8941. * @param {ItemSet} parent
  8942. * @param {Object} data Object containing (optional) parameters type,
  8943. * start, end, content, group, className.
  8944. * @param {Object} [options] Options to set initial property values
  8945. * @param {Object} [defaultOptions] default options
  8946. * // TODO: describe available options
  8947. */
  8948. function Item (parent, data, options, defaultOptions) {
  8949. this.parent = parent;
  8950. this.data = data;
  8951. this.dom = null;
  8952. this.options = options || {};
  8953. this.defaultOptions = defaultOptions || {};
  8954. this.selected = false;
  8955. this.visible = false;
  8956. this.top = 0;
  8957. this.left = 0;
  8958. this.width = 0;
  8959. this.height = 0;
  8960. }
  8961. /**
  8962. * Select current item
  8963. */
  8964. Item.prototype.select = function select() {
  8965. this.selected = true;
  8966. };
  8967. /**
  8968. * Unselect current item
  8969. */
  8970. Item.prototype.unselect = function unselect() {
  8971. this.selected = false;
  8972. };
  8973. /**
  8974. * Show the Item in the DOM (when not already visible)
  8975. * @return {Boolean} changed
  8976. */
  8977. Item.prototype.show = function show() {
  8978. return false;
  8979. };
  8980. /**
  8981. * Hide the Item from the DOM (when visible)
  8982. * @return {Boolean} changed
  8983. */
  8984. Item.prototype.hide = function hide() {
  8985. return false;
  8986. };
  8987. /**
  8988. * Repaint the item
  8989. * @return {Boolean} changed
  8990. */
  8991. Item.prototype.repaint = function repaint() {
  8992. // should be implemented by the item
  8993. return false;
  8994. };
  8995. /**
  8996. * Reflow the item
  8997. * @return {Boolean} resized
  8998. */
  8999. Item.prototype.reflow = function reflow() {
  9000. // should be implemented by the item
  9001. return false;
  9002. };
  9003. /**
  9004. * Return the items width
  9005. * @return {Integer} width
  9006. */
  9007. Item.prototype.getWidth = function getWidth() {
  9008. return this.width;
  9009. }
  9010. /**
  9011. * @constructor ItemBox
  9012. * @extends Item
  9013. * @param {ItemSet} parent
  9014. * @param {Object} data Object containing parameters start
  9015. * content, className.
  9016. * @param {Object} [options] Options to set initial property values
  9017. * @param {Object} [defaultOptions] default options
  9018. * // TODO: describe available options
  9019. */
  9020. function ItemBox (parent, data, options, defaultOptions) {
  9021. this.props = {
  9022. dot: {
  9023. left: 0,
  9024. top: 0,
  9025. width: 0,
  9026. height: 0
  9027. },
  9028. line: {
  9029. top: 0,
  9030. left: 0,
  9031. width: 0,
  9032. height: 0
  9033. }
  9034. };
  9035. Item.call(this, parent, data, options, defaultOptions);
  9036. }
  9037. ItemBox.prototype = new Item (null, null);
  9038. /**
  9039. * Select the item
  9040. * @override
  9041. */
  9042. ItemBox.prototype.select = function select() {
  9043. this.selected = true;
  9044. // TODO: select and unselect
  9045. };
  9046. /**
  9047. * Unselect the item
  9048. * @override
  9049. */
  9050. ItemBox.prototype.unselect = function unselect() {
  9051. this.selected = false;
  9052. // TODO: select and unselect
  9053. };
  9054. /**
  9055. * Repaint the item
  9056. * @return {Boolean} changed
  9057. */
  9058. ItemBox.prototype.repaint = function repaint() {
  9059. // TODO: make an efficient repaint
  9060. var changed = false;
  9061. var dom = this.dom;
  9062. if (!dom) {
  9063. this._create();
  9064. dom = this.dom;
  9065. changed = true;
  9066. }
  9067. if (dom) {
  9068. if (!this.parent) {
  9069. throw new Error('Cannot repaint item: no parent attached');
  9070. }
  9071. if (!dom.box.parentNode) {
  9072. var foreground = this.parent.getForeground();
  9073. if (!foreground) {
  9074. throw new Error('Cannot repaint time axis: ' +
  9075. 'parent has no foreground container element');
  9076. }
  9077. foreground.appendChild(dom.box);
  9078. changed = true;
  9079. }
  9080. if (!dom.line.parentNode) {
  9081. var background = this.parent.getBackground();
  9082. if (!background) {
  9083. throw new Error('Cannot repaint time axis: ' +
  9084. 'parent has no background container element');
  9085. }
  9086. background.appendChild(dom.line);
  9087. changed = true;
  9088. }
  9089. if (!dom.dot.parentNode) {
  9090. var axis = this.parent.getAxis();
  9091. if (!background) {
  9092. throw new Error('Cannot repaint time axis: ' +
  9093. 'parent has no axis container element');
  9094. }
  9095. axis.appendChild(dom.dot);
  9096. changed = true;
  9097. }
  9098. // update contents
  9099. if (this.data.content != this.content) {
  9100. this.content = this.data.content;
  9101. if (this.content instanceof Element) {
  9102. dom.content.innerHTML = '';
  9103. dom.content.appendChild(this.content);
  9104. }
  9105. else if (this.data.content != undefined) {
  9106. dom.content.innerHTML = this.content;
  9107. }
  9108. else {
  9109. throw new Error('Property "content" missing in item ' + this.data.id);
  9110. }
  9111. changed = true;
  9112. }
  9113. // update class
  9114. var className = (this.data.className? ' ' + this.data.className : '') +
  9115. (this.selected ? ' selected' : '');
  9116. if (this.className != className) {
  9117. this.className = className;
  9118. dom.box.className = 'item box' + className;
  9119. dom.line.className = 'item line' + className;
  9120. dom.dot.className = 'item dot' + className;
  9121. changed = true;
  9122. }
  9123. }
  9124. return changed;
  9125. };
  9126. /**
  9127. * Show the item in the DOM (when not already visible). The items DOM will
  9128. * be created when needed.
  9129. * @return {Boolean} changed
  9130. */
  9131. ItemBox.prototype.show = function show() {
  9132. if (!this.dom || !this.dom.box.parentNode) {
  9133. return this.repaint();
  9134. }
  9135. else {
  9136. return false;
  9137. }
  9138. };
  9139. /**
  9140. * Hide the item from the DOM (when visible)
  9141. * @return {Boolean} changed
  9142. */
  9143. ItemBox.prototype.hide = function hide() {
  9144. var changed = false,
  9145. dom = this.dom;
  9146. if (dom) {
  9147. if (dom.box.parentNode) {
  9148. dom.box.parentNode.removeChild(dom.box);
  9149. changed = true;
  9150. }
  9151. if (dom.line.parentNode) {
  9152. dom.line.parentNode.removeChild(dom.line);
  9153. }
  9154. if (dom.dot.parentNode) {
  9155. dom.dot.parentNode.removeChild(dom.dot);
  9156. }
  9157. }
  9158. return changed;
  9159. };
  9160. /**
  9161. * Reflow the item: calculate its actual size and position from the DOM
  9162. * @return {boolean} resized returns true if the axis is resized
  9163. * @override
  9164. */
  9165. ItemBox.prototype.reflow = function reflow() {
  9166. var changed = 0,
  9167. update,
  9168. dom,
  9169. props,
  9170. options,
  9171. margin,
  9172. start,
  9173. align,
  9174. orientation,
  9175. top,
  9176. left,
  9177. data,
  9178. range;
  9179. if (this.data.start == undefined) {
  9180. throw new Error('Property "start" missing in item ' + this.data.id);
  9181. }
  9182. data = this.data;
  9183. range = this.parent && this.parent.range;
  9184. if (data && range) {
  9185. // TODO: account for the width of the item
  9186. var interval = (range.end - range.start);
  9187. this.visible = (data.start > range.start - interval) && (data.start < range.end + interval);
  9188. }
  9189. else {
  9190. this.visible = false;
  9191. }
  9192. if (this.visible) {
  9193. dom = this.dom;
  9194. if (dom) {
  9195. update = util.updateProperty;
  9196. props = this.props;
  9197. options = this.options;
  9198. start = this.parent.toScreen(this.data.start);
  9199. align = options.align || this.defaultOptions.align;
  9200. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  9201. orientation = options.orientation || this.defaultOptions.orientation;
  9202. changed += update(props.dot, 'height', dom.dot.offsetHeight);
  9203. changed += update(props.dot, 'width', dom.dot.offsetWidth);
  9204. changed += update(props.line, 'width', dom.line.offsetWidth);
  9205. changed += update(props.line, 'height', dom.line.offsetHeight);
  9206. changed += update(props.line, 'top', dom.line.offsetTop);
  9207. changed += update(this, 'width', dom.box.offsetWidth);
  9208. changed += update(this, 'height', dom.box.offsetHeight);
  9209. if (align == 'right') {
  9210. left = start - this.width;
  9211. }
  9212. else if (align == 'left') {
  9213. left = start;
  9214. }
  9215. else {
  9216. // default or 'center'
  9217. left = start - this.width / 2;
  9218. }
  9219. changed += update(this, 'left', left);
  9220. changed += update(props.line, 'left', start - props.line.width / 2);
  9221. changed += update(props.dot, 'left', start - props.dot.width / 2);
  9222. changed += update(props.dot, 'top', -props.dot.height / 2);
  9223. if (orientation == 'top') {
  9224. top = margin;
  9225. changed += update(this, 'top', top);
  9226. }
  9227. else {
  9228. // default or 'bottom'
  9229. var parentHeight = this.parent.height;
  9230. top = parentHeight - this.height - margin;
  9231. changed += update(this, 'top', top);
  9232. }
  9233. }
  9234. else {
  9235. changed += 1;
  9236. }
  9237. }
  9238. return (changed > 0);
  9239. };
  9240. /**
  9241. * Create an items DOM
  9242. * @private
  9243. */
  9244. ItemBox.prototype._create = function _create() {
  9245. var dom = this.dom;
  9246. if (!dom) {
  9247. this.dom = dom = {};
  9248. // create the box
  9249. dom.box = document.createElement('DIV');
  9250. // className is updated in repaint()
  9251. // contents box (inside the background box). used for making margins
  9252. dom.content = document.createElement('DIV');
  9253. dom.content.className = 'content';
  9254. dom.box.appendChild(dom.content);
  9255. // line to axis
  9256. dom.line = document.createElement('DIV');
  9257. dom.line.className = 'line';
  9258. // dot on axis
  9259. dom.dot = document.createElement('DIV');
  9260. dom.dot.className = 'dot';
  9261. }
  9262. };
  9263. /**
  9264. * Reposition the item, recalculate its left, top, and width, using the current
  9265. * range and size of the items itemset
  9266. * @override
  9267. */
  9268. ItemBox.prototype.reposition = function reposition() {
  9269. var dom = this.dom,
  9270. props = this.props,
  9271. orientation = this.options.orientation || this.defaultOptions.orientation;
  9272. if (dom) {
  9273. var box = dom.box,
  9274. line = dom.line,
  9275. dot = dom.dot;
  9276. box.style.left = this.left + 'px';
  9277. box.style.top = this.top + 'px';
  9278. line.style.left = props.line.left + 'px';
  9279. if (orientation == 'top') {
  9280. line.style.top = 0 + 'px';
  9281. line.style.height = this.top + 'px';
  9282. }
  9283. else {
  9284. // orientation 'bottom'
  9285. line.style.top = (this.top + this.height) + 'px';
  9286. line.style.height = Math.max(this.parent.height - this.top - this.height +
  9287. this.props.dot.height / 2, 0) + 'px';
  9288. }
  9289. dot.style.left = props.dot.left + 'px';
  9290. dot.style.top = props.dot.top + 'px';
  9291. }
  9292. };
  9293. /**
  9294. * @constructor ItemPoint
  9295. * @extends Item
  9296. * @param {ItemSet} parent
  9297. * @param {Object} data Object containing parameters start
  9298. * content, className.
  9299. * @param {Object} [options] Options to set initial property values
  9300. * @param {Object} [defaultOptions] default options
  9301. * // TODO: describe available options
  9302. */
  9303. function ItemPoint (parent, data, options, defaultOptions) {
  9304. this.props = {
  9305. dot: {
  9306. top: 0,
  9307. width: 0,
  9308. height: 0
  9309. },
  9310. content: {
  9311. height: 0,
  9312. marginLeft: 0
  9313. }
  9314. };
  9315. Item.call(this, parent, data, options, defaultOptions);
  9316. }
  9317. ItemPoint.prototype = new Item (null, null);
  9318. /**
  9319. * Select the item
  9320. * @override
  9321. */
  9322. ItemPoint.prototype.select = function select() {
  9323. this.selected = true;
  9324. // TODO: select and unselect
  9325. };
  9326. /**
  9327. * Unselect the item
  9328. * @override
  9329. */
  9330. ItemPoint.prototype.unselect = function unselect() {
  9331. this.selected = false;
  9332. // TODO: select and unselect
  9333. };
  9334. /**
  9335. * Repaint the item
  9336. * @return {Boolean} changed
  9337. */
  9338. ItemPoint.prototype.repaint = function repaint() {
  9339. // TODO: make an efficient repaint
  9340. var changed = false;
  9341. var dom = this.dom;
  9342. if (!dom) {
  9343. this._create();
  9344. dom = this.dom;
  9345. changed = true;
  9346. }
  9347. if (dom) {
  9348. if (!this.parent) {
  9349. throw new Error('Cannot repaint item: no parent attached');
  9350. }
  9351. var foreground = this.parent.getForeground();
  9352. if (!foreground) {
  9353. throw new Error('Cannot repaint time axis: ' +
  9354. 'parent has no foreground container element');
  9355. }
  9356. if (!dom.point.parentNode) {
  9357. foreground.appendChild(dom.point);
  9358. foreground.appendChild(dom.point);
  9359. changed = true;
  9360. }
  9361. // update contents
  9362. if (this.data.content != this.content) {
  9363. this.content = this.data.content;
  9364. if (this.content instanceof Element) {
  9365. dom.content.innerHTML = '';
  9366. dom.content.appendChild(this.content);
  9367. }
  9368. else if (this.data.content != undefined) {
  9369. dom.content.innerHTML = this.content;
  9370. }
  9371. else {
  9372. throw new Error('Property "content" missing in item ' + this.data.id);
  9373. }
  9374. changed = true;
  9375. }
  9376. // update class
  9377. var className = (this.data.className? ' ' + this.data.className : '') +
  9378. (this.selected ? ' selected' : '');
  9379. if (this.className != className) {
  9380. this.className = className;
  9381. dom.point.className = 'item point' + className;
  9382. changed = true;
  9383. }
  9384. }
  9385. return changed;
  9386. };
  9387. /**
  9388. * Show the item in the DOM (when not already visible). The items DOM will
  9389. * be created when needed.
  9390. * @return {Boolean} changed
  9391. */
  9392. ItemPoint.prototype.show = function show() {
  9393. if (!this.dom || !this.dom.point.parentNode) {
  9394. return this.repaint();
  9395. }
  9396. else {
  9397. return false;
  9398. }
  9399. };
  9400. /**
  9401. * Hide the item from the DOM (when visible)
  9402. * @return {Boolean} changed
  9403. */
  9404. ItemPoint.prototype.hide = function hide() {
  9405. var changed = false,
  9406. dom = this.dom;
  9407. if (dom) {
  9408. if (dom.point.parentNode) {
  9409. dom.point.parentNode.removeChild(dom.point);
  9410. changed = true;
  9411. }
  9412. }
  9413. return changed;
  9414. };
  9415. /**
  9416. * Reflow the item: calculate its actual size from the DOM
  9417. * @return {boolean} resized returns true if the axis is resized
  9418. * @override
  9419. */
  9420. ItemPoint.prototype.reflow = function reflow() {
  9421. var changed = 0,
  9422. update,
  9423. dom,
  9424. props,
  9425. options,
  9426. margin,
  9427. orientation,
  9428. start,
  9429. top,
  9430. data,
  9431. range;
  9432. if (this.data.start == undefined) {
  9433. throw new Error('Property "start" missing in item ' + this.data.id);
  9434. }
  9435. data = this.data;
  9436. range = this.parent && this.parent.range;
  9437. if (data && range) {
  9438. // TODO: account for the width of the item
  9439. var interval = (range.end - range.start);
  9440. this.visible = (data.start > range.start - interval) && (data.start < range.end);
  9441. }
  9442. else {
  9443. this.visible = false;
  9444. }
  9445. if (this.visible) {
  9446. dom = this.dom;
  9447. if (dom) {
  9448. update = util.updateProperty;
  9449. props = this.props;
  9450. options = this.options;
  9451. orientation = options.orientation || this.defaultOptions.orientation;
  9452. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  9453. start = this.parent.toScreen(this.data.start);
  9454. changed += update(this, 'width', dom.point.offsetWidth);
  9455. changed += update(this, 'height', dom.point.offsetHeight);
  9456. changed += update(props.dot, 'width', dom.dot.offsetWidth);
  9457. changed += update(props.dot, 'height', dom.dot.offsetHeight);
  9458. changed += update(props.content, 'height', dom.content.offsetHeight);
  9459. if (orientation == 'top') {
  9460. top = margin;
  9461. }
  9462. else {
  9463. // default or 'bottom'
  9464. var parentHeight = this.parent.height;
  9465. top = Math.max(parentHeight - this.height - margin, 0);
  9466. }
  9467. changed += update(this, 'top', top);
  9468. changed += update(this, 'left', start - props.dot.width / 2);
  9469. changed += update(props.content, 'marginLeft', 1.5 * props.dot.width);
  9470. //changed += update(props.content, 'marginRight', 0.5 * props.dot.width); // TODO
  9471. changed += update(props.dot, 'top', (this.height - props.dot.height) / 2);
  9472. }
  9473. else {
  9474. changed += 1;
  9475. }
  9476. }
  9477. return (changed > 0);
  9478. };
  9479. /**
  9480. * Create an items DOM
  9481. * @private
  9482. */
  9483. ItemPoint.prototype._create = function _create() {
  9484. var dom = this.dom;
  9485. if (!dom) {
  9486. this.dom = dom = {};
  9487. // background box
  9488. dom.point = document.createElement('div');
  9489. // className is updated in repaint()
  9490. // contents box, right from the dot
  9491. dom.content = document.createElement('div');
  9492. dom.content.className = 'content';
  9493. dom.point.appendChild(dom.content);
  9494. // dot at start
  9495. dom.dot = document.createElement('div');
  9496. dom.dot.className = 'dot';
  9497. dom.point.appendChild(dom.dot);
  9498. }
  9499. };
  9500. /**
  9501. * Reposition the item, recalculate its left, top, and width, using the current
  9502. * range and size of the items itemset
  9503. * @override
  9504. */
  9505. ItemPoint.prototype.reposition = function reposition() {
  9506. var dom = this.dom,
  9507. props = this.props;
  9508. if (dom) {
  9509. dom.point.style.top = this.top + 'px';
  9510. dom.point.style.left = this.left + 'px';
  9511. dom.content.style.marginLeft = props.content.marginLeft + 'px';
  9512. //dom.content.style.marginRight = props.content.marginRight + 'px'; // TODO
  9513. dom.dot.style.top = props.dot.top + 'px';
  9514. }
  9515. };
  9516. /**
  9517. * @constructor ItemRange
  9518. * @extends Item
  9519. * @param {ItemSet} parent
  9520. * @param {Object} data Object containing parameters start, end
  9521. * content, className.
  9522. * @param {Object} [options] Options to set initial property values
  9523. * @param {Object} [defaultOptions] default options
  9524. * // TODO: describe available options
  9525. */
  9526. function ItemRange (parent, data, options, defaultOptions) {
  9527. this.props = {
  9528. content: {
  9529. left: 0,
  9530. width: 0
  9531. }
  9532. };
  9533. Item.call(this, parent, data, options, defaultOptions);
  9534. }
  9535. ItemRange.prototype = new Item (null, null);
  9536. /**
  9537. * Select the item
  9538. * @override
  9539. */
  9540. ItemRange.prototype.select = function select() {
  9541. this.selected = true;
  9542. // TODO: select and unselect
  9543. };
  9544. /**
  9545. * Unselect the item
  9546. * @override
  9547. */
  9548. ItemRange.prototype.unselect = function unselect() {
  9549. this.selected = false;
  9550. // TODO: select and unselect
  9551. };
  9552. /**
  9553. * Repaint the item
  9554. * @return {Boolean} changed
  9555. */
  9556. ItemRange.prototype.repaint = function repaint() {
  9557. // TODO: make an efficient repaint
  9558. var changed = false;
  9559. var dom = this.dom;
  9560. if (!dom) {
  9561. this._create();
  9562. dom = this.dom;
  9563. changed = true;
  9564. }
  9565. if (dom) {
  9566. if (!this.parent) {
  9567. throw new Error('Cannot repaint item: no parent attached');
  9568. }
  9569. var foreground = this.parent.getForeground();
  9570. if (!foreground) {
  9571. throw new Error('Cannot repaint time axis: ' +
  9572. 'parent has no foreground container element');
  9573. }
  9574. if (!dom.box.parentNode) {
  9575. foreground.appendChild(dom.box);
  9576. changed = true;
  9577. }
  9578. // update content
  9579. if (this.data.content != this.content) {
  9580. this.content = this.data.content;
  9581. if (this.content instanceof Element) {
  9582. dom.content.innerHTML = '';
  9583. dom.content.appendChild(this.content);
  9584. }
  9585. else if (this.data.content != undefined) {
  9586. dom.content.innerHTML = this.content;
  9587. }
  9588. else {
  9589. throw new Error('Property "content" missing in item ' + this.data.id);
  9590. }
  9591. changed = true;
  9592. }
  9593. // update class
  9594. var className = this.data.className ? (' ' + this.data.className) : '';
  9595. if (this.className != className) {
  9596. this.className = className;
  9597. dom.box.className = 'item range' + className;
  9598. changed = true;
  9599. }
  9600. }
  9601. return changed;
  9602. };
  9603. /**
  9604. * Show the item in the DOM (when not already visible). The items DOM will
  9605. * be created when needed.
  9606. * @return {Boolean} changed
  9607. */
  9608. ItemRange.prototype.show = function show() {
  9609. if (!this.dom || !this.dom.box.parentNode) {
  9610. return this.repaint();
  9611. }
  9612. else {
  9613. return false;
  9614. }
  9615. };
  9616. /**
  9617. * Hide the item from the DOM (when visible)
  9618. * @return {Boolean} changed
  9619. */
  9620. ItemRange.prototype.hide = function hide() {
  9621. var changed = false,
  9622. dom = this.dom;
  9623. if (dom) {
  9624. if (dom.box.parentNode) {
  9625. dom.box.parentNode.removeChild(dom.box);
  9626. changed = true;
  9627. }
  9628. }
  9629. return changed;
  9630. };
  9631. /**
  9632. * Reflow the item: calculate its actual size from the DOM
  9633. * @return {boolean} resized returns true if the axis is resized
  9634. * @override
  9635. */
  9636. ItemRange.prototype.reflow = function reflow() {
  9637. var changed = 0,
  9638. dom,
  9639. props,
  9640. options,
  9641. margin,
  9642. padding,
  9643. parent,
  9644. start,
  9645. end,
  9646. data,
  9647. range,
  9648. update,
  9649. box,
  9650. parentWidth,
  9651. contentLeft,
  9652. orientation,
  9653. top;
  9654. if (this.data.start == undefined) {
  9655. throw new Error('Property "start" missing in item ' + this.data.id);
  9656. }
  9657. if (this.data.end == undefined) {
  9658. throw new Error('Property "end" missing in item ' + this.data.id);
  9659. }
  9660. data = this.data;
  9661. range = this.parent && this.parent.range;
  9662. if (data && range) {
  9663. // TODO: account for the width of the item. Take some margin
  9664. this.visible = (data.start < range.end) && (data.end > range.start);
  9665. }
  9666. else {
  9667. this.visible = false;
  9668. }
  9669. if (this.visible) {
  9670. dom = this.dom;
  9671. if (dom) {
  9672. props = this.props;
  9673. options = this.options;
  9674. parent = this.parent;
  9675. start = parent.toScreen(this.data.start);
  9676. end = parent.toScreen(this.data.end);
  9677. update = util.updateProperty;
  9678. box = dom.box;
  9679. parentWidth = parent.width;
  9680. orientation = options.orientation || this.defaultOptions.orientation;
  9681. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  9682. padding = options.padding || this.defaultOptions.padding;
  9683. changed += update(props.content, 'width', dom.content.offsetWidth);
  9684. changed += update(this, 'height', box.offsetHeight);
  9685. // limit the width of the this, as browsers cannot draw very wide divs
  9686. if (start < -parentWidth) {
  9687. start = -parentWidth;
  9688. }
  9689. if (end > 2 * parentWidth) {
  9690. end = 2 * parentWidth;
  9691. }
  9692. // when range exceeds left of the window, position the contents at the left of the visible area
  9693. if (start < 0) {
  9694. contentLeft = Math.min(-start,
  9695. (end - start - props.content.width - 2 * padding));
  9696. // TODO: remove the need for options.padding. it's terrible.
  9697. }
  9698. else {
  9699. contentLeft = 0;
  9700. }
  9701. changed += update(props.content, 'left', contentLeft);
  9702. if (orientation == 'top') {
  9703. top = margin;
  9704. changed += update(this, 'top', top);
  9705. }
  9706. else {
  9707. // default or 'bottom'
  9708. top = parent.height - this.height - margin;
  9709. changed += update(this, 'top', top);
  9710. }
  9711. changed += update(this, 'left', start);
  9712. changed += update(this, 'width', Math.max(end - start, 1)); // TODO: reckon with border width;
  9713. }
  9714. else {
  9715. changed += 1;
  9716. }
  9717. }
  9718. return (changed > 0);
  9719. };
  9720. /**
  9721. * Create an items DOM
  9722. * @private
  9723. */
  9724. ItemRange.prototype._create = function _create() {
  9725. var dom = this.dom;
  9726. if (!dom) {
  9727. this.dom = dom = {};
  9728. // background box
  9729. dom.box = document.createElement('div');
  9730. // className is updated in repaint()
  9731. // contents box
  9732. dom.content = document.createElement('div');
  9733. dom.content.className = 'content';
  9734. dom.box.appendChild(dom.content);
  9735. }
  9736. };
  9737. /**
  9738. * Reposition the item, recalculate its left, top, and width, using the current
  9739. * range and size of the items itemset
  9740. * @override
  9741. */
  9742. ItemRange.prototype.reposition = function reposition() {
  9743. var dom = this.dom,
  9744. props = this.props;
  9745. if (dom) {
  9746. dom.box.style.top = this.top + 'px';
  9747. dom.box.style.left = this.left + 'px';
  9748. dom.box.style.width = this.width + 'px';
  9749. dom.content.style.left = props.content.left + 'px';
  9750. }
  9751. };
  9752. /**
  9753. * @constructor ItemRangeOverflow
  9754. * @extends ItemRange
  9755. * @param {ItemSet} parent
  9756. * @param {Object} data Object containing parameters start, end
  9757. * content, className.
  9758. * @param {Object} [options] Options to set initial property values
  9759. * @param {Object} [defaultOptions] default options
  9760. * // TODO: describe available options
  9761. */
  9762. function ItemRangeOverflow (parent, data, options, defaultOptions) {
  9763. this.props = {
  9764. content: {
  9765. left: 0,
  9766. width: 0
  9767. }
  9768. };
  9769. ItemRange.call(this, parent, data, options, defaultOptions);
  9770. }
  9771. ItemRangeOverflow.prototype = new ItemRange (null, null);
  9772. /**
  9773. * Repaint the item
  9774. * @return {Boolean} changed
  9775. */
  9776. ItemRangeOverflow.prototype.repaint = function repaint() {
  9777. // TODO: make an efficient repaint
  9778. var changed = false;
  9779. var dom = this.dom;
  9780. if (!dom) {
  9781. this._create();
  9782. dom = this.dom;
  9783. changed = true;
  9784. }
  9785. if (dom) {
  9786. if (!this.parent) {
  9787. throw new Error('Cannot repaint item: no parent attached');
  9788. }
  9789. var foreground = this.parent.getForeground();
  9790. if (!foreground) {
  9791. throw new Error('Cannot repaint time axis: ' +
  9792. 'parent has no foreground container element');
  9793. }
  9794. if (!dom.box.parentNode) {
  9795. foreground.appendChild(dom.box);
  9796. changed = true;
  9797. }
  9798. // update content
  9799. if (this.data.content != this.content) {
  9800. this.content = this.data.content;
  9801. if (this.content instanceof Element) {
  9802. dom.content.innerHTML = '';
  9803. dom.content.appendChild(this.content);
  9804. }
  9805. else if (this.data.content != undefined) {
  9806. dom.content.innerHTML = this.content;
  9807. }
  9808. else {
  9809. throw new Error('Property "content" missing in item ' + this.data.id);
  9810. }
  9811. changed = true;
  9812. }
  9813. // update class
  9814. var className = this.data.className ? (' ' + this.data.className) : '';
  9815. if (this.className != className) {
  9816. this.className = className;
  9817. dom.box.className = 'item rangeoverflow' + className;
  9818. changed = true;
  9819. }
  9820. }
  9821. return changed;
  9822. };
  9823. /**
  9824. * Return the items width
  9825. * @return {Number} width
  9826. */
  9827. ItemRangeOverflow.prototype.getWidth = function getWidth() {
  9828. if (this.props.content !== undefined && this.width < this.props.content.width)
  9829. return this.props.content.width;
  9830. else
  9831. return this.width;
  9832. };
  9833. /**
  9834. * @constructor Group
  9835. * @param {GroupSet} parent
  9836. * @param {Number | String} groupId
  9837. * @param {Object} [options] Options to set initial property values
  9838. * // TODO: describe available options
  9839. * @extends Component
  9840. */
  9841. function Group (parent, groupId, options) {
  9842. this.id = util.randomUUID();
  9843. this.parent = parent;
  9844. this.groupId = groupId;
  9845. this.itemset = null; // ItemSet
  9846. this.options = options || {};
  9847. this.options.top = 0;
  9848. this.props = {
  9849. label: {
  9850. width: 0,
  9851. height: 0
  9852. }
  9853. };
  9854. this.top = 0;
  9855. this.left = 0;
  9856. this.width = 0;
  9857. this.height = 0;
  9858. }
  9859. Group.prototype = new Component();
  9860. // TODO: comment
  9861. Group.prototype.setOptions = Component.prototype.setOptions;
  9862. /**
  9863. * Get the container element of the panel, which can be used by a child to
  9864. * add its own widgets.
  9865. * @returns {HTMLElement} container
  9866. */
  9867. Group.prototype.getContainer = function () {
  9868. return this.parent.getContainer();
  9869. };
  9870. /**
  9871. * Set item set for the group. The group will create a view on the itemset,
  9872. * filtered by the groups id.
  9873. * @param {DataSet | DataView} items
  9874. */
  9875. Group.prototype.setItems = function setItems(items) {
  9876. if (this.itemset) {
  9877. // remove current item set
  9878. this.itemset.hide();
  9879. this.itemset.setItems();
  9880. this.parent.controller.remove(this.itemset);
  9881. this.itemset = null;
  9882. }
  9883. if (items) {
  9884. var groupId = this.groupId;
  9885. var itemsetOptions = Object.create(this.options);
  9886. this.itemset = new ItemSet(this, null, itemsetOptions);
  9887. this.itemset.setRange(this.parent.range);
  9888. this.view = new DataView(items, {
  9889. filter: function (item) {
  9890. return item.group == groupId;
  9891. }
  9892. });
  9893. this.itemset.setItems(this.view);
  9894. this.parent.controller.add(this.itemset);
  9895. }
  9896. };
  9897. /**
  9898. * Repaint the item
  9899. * @return {Boolean} changed
  9900. */
  9901. Group.prototype.repaint = function repaint() {
  9902. return false;
  9903. };
  9904. /**
  9905. * Reflow the item
  9906. * @return {Boolean} resized
  9907. */
  9908. Group.prototype.reflow = function reflow() {
  9909. var changed = 0,
  9910. update = util.updateProperty;
  9911. changed += update(this, 'top', this.itemset ? this.itemset.top : 0);
  9912. changed += update(this, 'height', this.itemset ? this.itemset.height : 0);
  9913. // TODO: reckon with the height of the group label
  9914. if (this.label) {
  9915. var inner = this.label.firstChild;
  9916. changed += update(this.props.label, 'width', inner.clientWidth);
  9917. changed += update(this.props.label, 'height', inner.clientHeight);
  9918. }
  9919. else {
  9920. changed += update(this.props.label, 'width', 0);
  9921. changed += update(this.props.label, 'height', 0);
  9922. }
  9923. return (changed > 0);
  9924. };
  9925. /**
  9926. * An GroupSet holds a set of groups
  9927. * @param {Component} parent
  9928. * @param {Component[]} [depends] Components on which this components depends
  9929. * (except for the parent)
  9930. * @param {Object} [options] See GroupSet.setOptions for the available
  9931. * options.
  9932. * @constructor GroupSet
  9933. * @extends Panel
  9934. */
  9935. function GroupSet(parent, depends, options) {
  9936. this.id = util.randomUUID();
  9937. this.parent = parent;
  9938. this.depends = depends;
  9939. this.options = options || {};
  9940. this.range = null; // Range or Object {start: number, end: number}
  9941. this.itemsData = null; // DataSet with items
  9942. this.groupsData = null; // DataSet with groups
  9943. this.groups = {}; // map with groups
  9944. this.dom = {};
  9945. this.props = {
  9946. labels: {
  9947. width: 0
  9948. }
  9949. };
  9950. // TODO: implement right orientation of the labels
  9951. // changes in groups are queued key/value map containing id/action
  9952. this.queue = {};
  9953. var me = this;
  9954. this.listeners = {
  9955. 'add': function (event, params) {
  9956. me._onAdd(params.items);
  9957. },
  9958. 'update': function (event, params) {
  9959. me._onUpdate(params.items);
  9960. },
  9961. 'remove': function (event, params) {
  9962. me._onRemove(params.items);
  9963. }
  9964. };
  9965. }
  9966. GroupSet.prototype = new Panel();
  9967. /**
  9968. * Set options for the GroupSet. Existing options will be extended/overwritten.
  9969. * @param {Object} [options] The following options are available:
  9970. * {String | function} groupsOrder
  9971. * TODO: describe options
  9972. */
  9973. GroupSet.prototype.setOptions = Component.prototype.setOptions;
  9974. GroupSet.prototype.setRange = function (range) {
  9975. // TODO: implement setRange
  9976. };
  9977. /**
  9978. * Set items
  9979. * @param {vis.DataSet | null} items
  9980. */
  9981. GroupSet.prototype.setItems = function setItems(items) {
  9982. this.itemsData = items;
  9983. for (var id in this.groups) {
  9984. if (this.groups.hasOwnProperty(id)) {
  9985. var group = this.groups[id];
  9986. group.setItems(items);
  9987. }
  9988. }
  9989. };
  9990. /**
  9991. * Get items
  9992. * @return {vis.DataSet | null} items
  9993. */
  9994. GroupSet.prototype.getItems = function getItems() {
  9995. return this.itemsData;
  9996. };
  9997. /**
  9998. * Set range (start and end).
  9999. * @param {Range | Object} range A Range or an object containing start and end.
  10000. */
  10001. GroupSet.prototype.setRange = function setRange(range) {
  10002. this.range = range;
  10003. };
  10004. /**
  10005. * Set groups
  10006. * @param {vis.DataSet} groups
  10007. */
  10008. GroupSet.prototype.setGroups = function setGroups(groups) {
  10009. var me = this,
  10010. ids;
  10011. // unsubscribe from current dataset
  10012. if (this.groupsData) {
  10013. util.forEach(this.listeners, function (callback, event) {
  10014. me.groupsData.unsubscribe(event, callback);
  10015. });
  10016. // remove all drawn groups
  10017. ids = this.groupsData.getIds();
  10018. this._onRemove(ids);
  10019. }
  10020. // replace the dataset
  10021. if (!groups) {
  10022. this.groupsData = null;
  10023. }
  10024. else if (groups instanceof DataSet) {
  10025. this.groupsData = groups;
  10026. }
  10027. else {
  10028. this.groupsData = new DataSet({
  10029. convert: {
  10030. start: 'Date',
  10031. end: 'Date'
  10032. }
  10033. });
  10034. this.groupsData.add(groups);
  10035. }
  10036. if (this.groupsData) {
  10037. // subscribe to new dataset
  10038. var id = this.id;
  10039. util.forEach(this.listeners, function (callback, event) {
  10040. me.groupsData.subscribe(event, callback, id);
  10041. });
  10042. // draw all new groups
  10043. ids = this.groupsData.getIds();
  10044. this._onAdd(ids);
  10045. }
  10046. };
  10047. /**
  10048. * Get groups
  10049. * @return {vis.DataSet | null} groups
  10050. */
  10051. GroupSet.prototype.getGroups = function getGroups() {
  10052. return this.groupsData;
  10053. };
  10054. /**
  10055. * Repaint the component
  10056. * @return {Boolean} changed
  10057. */
  10058. GroupSet.prototype.repaint = function repaint() {
  10059. var changed = 0,
  10060. i, id, group, label,
  10061. update = util.updateProperty,
  10062. asSize = util.option.asSize,
  10063. asElement = util.option.asElement,
  10064. options = this.options,
  10065. frame = this.dom.frame,
  10066. labels = this.dom.labels,
  10067. labelSet = this.dom.labelSet;
  10068. // create frame
  10069. if (!this.parent) {
  10070. throw new Error('Cannot repaint groupset: no parent attached');
  10071. }
  10072. var parentContainer = this.parent.getContainer();
  10073. if (!parentContainer) {
  10074. throw new Error('Cannot repaint groupset: parent has no container element');
  10075. }
  10076. if (!frame) {
  10077. frame = document.createElement('div');
  10078. frame.className = 'groupset';
  10079. this.dom.frame = frame;
  10080. var className = options.className;
  10081. if (className) {
  10082. util.addClassName(frame, util.option.asString(className));
  10083. }
  10084. changed += 1;
  10085. }
  10086. if (!frame.parentNode) {
  10087. parentContainer.appendChild(frame);
  10088. changed += 1;
  10089. }
  10090. // create labels
  10091. var labelContainer = asElement(options.labelContainer);
  10092. if (!labelContainer) {
  10093. throw new Error('Cannot repaint groupset: option "labelContainer" not defined');
  10094. }
  10095. if (!labels) {
  10096. labels = document.createElement('div');
  10097. labels.className = 'labels';
  10098. this.dom.labels = labels;
  10099. }
  10100. if (!labelSet) {
  10101. labelSet = document.createElement('div');
  10102. labelSet.className = 'label-set';
  10103. labels.appendChild(labelSet);
  10104. this.dom.labelSet = labelSet;
  10105. }
  10106. if (!labels.parentNode || labels.parentNode != labelContainer) {
  10107. if (labels.parentNode) {
  10108. labels.parentNode.removeChild(labels.parentNode);
  10109. }
  10110. labelContainer.appendChild(labels);
  10111. }
  10112. // reposition frame
  10113. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  10114. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  10115. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  10116. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  10117. // reposition labels
  10118. changed += update(labelSet.style, 'top', asSize(options.top, '0px'));
  10119. changed += update(labelSet.style, 'height', asSize(options.height, this.height + 'px'));
  10120. var me = this,
  10121. queue = this.queue,
  10122. groups = this.groups,
  10123. groupsData = this.groupsData;
  10124. // show/hide added/changed/removed groups
  10125. var ids = Object.keys(queue);
  10126. if (ids.length) {
  10127. ids.forEach(function (id) {
  10128. var action = queue[id];
  10129. var group = groups[id];
  10130. //noinspection FallthroughInSwitchStatementJS
  10131. switch (action) {
  10132. case 'add':
  10133. case 'update':
  10134. if (!group) {
  10135. var groupOptions = Object.create(me.options);
  10136. util.extend(groupOptions, {
  10137. height: null,
  10138. maxHeight: null
  10139. });
  10140. group = new Group(me, id, groupOptions);
  10141. group.setItems(me.itemsData); // attach items data
  10142. groups[id] = group;
  10143. me.controller.add(group);
  10144. }
  10145. // TODO: update group data
  10146. group.data = groupsData.get(id);
  10147. delete queue[id];
  10148. break;
  10149. case 'remove':
  10150. if (group) {
  10151. group.setItems(); // detach items data
  10152. delete groups[id];
  10153. me.controller.remove(group);
  10154. }
  10155. // update lists
  10156. delete queue[id];
  10157. break;
  10158. default:
  10159. console.log('Error: unknown action "' + action + '"');
  10160. }
  10161. });
  10162. // the groupset depends on each of the groups
  10163. //this.depends = this.groups; // TODO: gives a circular reference through the parent
  10164. // TODO: apply dependencies of the groupset
  10165. // update the top positions of the groups in the correct order
  10166. var orderedGroups = this.groupsData.getIds({
  10167. order: this.options.groupOrder
  10168. });
  10169. for (i = 0; i < orderedGroups.length; i++) {
  10170. (function (group, prevGroup) {
  10171. var top = 0;
  10172. if (prevGroup) {
  10173. top = function () {
  10174. // TODO: top must reckon with options.maxHeight
  10175. return prevGroup.top + prevGroup.height;
  10176. }
  10177. }
  10178. group.setOptions({
  10179. top: top
  10180. });
  10181. })(groups[orderedGroups[i]], groups[orderedGroups[i - 1]]);
  10182. }
  10183. // (re)create the labels
  10184. while (labelSet.firstChild) {
  10185. labelSet.removeChild(labelSet.firstChild);
  10186. }
  10187. for (i = 0; i < orderedGroups.length; i++) {
  10188. id = orderedGroups[i];
  10189. label = this._createLabel(id);
  10190. labelSet.appendChild(label);
  10191. }
  10192. changed++;
  10193. }
  10194. // reposition the labels
  10195. // TODO: labels are not displayed correctly when orientation=='top'
  10196. // TODO: width of labelPanel is not immediately updated on a change in groups
  10197. for (id in groups) {
  10198. if (groups.hasOwnProperty(id)) {
  10199. group = groups[id];
  10200. label = group.label;
  10201. if (label) {
  10202. label.style.top = group.top + 'px';
  10203. label.style.height = group.height + 'px';
  10204. }
  10205. }
  10206. }
  10207. return (changed > 0);
  10208. };
  10209. /**
  10210. * Create a label for group with given id
  10211. * @param {Number} id
  10212. * @return {Element} label
  10213. * @private
  10214. */
  10215. GroupSet.prototype._createLabel = function(id) {
  10216. var group = this.groups[id];
  10217. var label = document.createElement('div');
  10218. label.className = 'label';
  10219. var inner = document.createElement('div');
  10220. inner.className = 'inner';
  10221. label.appendChild(inner);
  10222. var content = group.data && group.data.content;
  10223. if (content instanceof Element) {
  10224. inner.appendChild(content);
  10225. }
  10226. else if (content != undefined) {
  10227. inner.innerHTML = content;
  10228. }
  10229. var className = group.data && group.data.className;
  10230. if (className) {
  10231. util.addClassName(label, className);
  10232. }
  10233. group.label = label; // TODO: not so nice, parking labels in the group this way!!!
  10234. return label;
  10235. };
  10236. /**
  10237. * Get container element
  10238. * @return {HTMLElement} container
  10239. */
  10240. GroupSet.prototype.getContainer = function getContainer() {
  10241. return this.dom.frame;
  10242. };
  10243. /**
  10244. * Get the width of the group labels
  10245. * @return {Number} width
  10246. */
  10247. GroupSet.prototype.getLabelsWidth = function getContainer() {
  10248. return this.props.labels.width;
  10249. };
  10250. /**
  10251. * Reflow the component
  10252. * @return {Boolean} resized
  10253. */
  10254. GroupSet.prototype.reflow = function reflow() {
  10255. var changed = 0,
  10256. id, group,
  10257. options = this.options,
  10258. update = util.updateProperty,
  10259. asNumber = util.option.asNumber,
  10260. asSize = util.option.asSize,
  10261. frame = this.dom.frame;
  10262. if (frame) {
  10263. var maxHeight = asNumber(options.maxHeight);
  10264. var fixedHeight = (asSize(options.height) != null);
  10265. var height;
  10266. if (fixedHeight) {
  10267. height = frame.offsetHeight;
  10268. }
  10269. else {
  10270. // height is not specified, calculate the sum of the height of all groups
  10271. height = 0;
  10272. for (id in this.groups) {
  10273. if (this.groups.hasOwnProperty(id)) {
  10274. group = this.groups[id];
  10275. height += group.height;
  10276. }
  10277. }
  10278. }
  10279. if (maxHeight != null) {
  10280. height = Math.min(height, maxHeight);
  10281. }
  10282. changed += update(this, 'height', height);
  10283. changed += update(this, 'top', frame.offsetTop);
  10284. changed += update(this, 'left', frame.offsetLeft);
  10285. changed += update(this, 'width', frame.offsetWidth);
  10286. }
  10287. // calculate the maximum width of the labels
  10288. var width = 0;
  10289. for (id in this.groups) {
  10290. if (this.groups.hasOwnProperty(id)) {
  10291. group = this.groups[id];
  10292. var labelWidth = group.props && group.props.label && group.props.label.width || 0;
  10293. width = Math.max(width, labelWidth);
  10294. }
  10295. }
  10296. changed += update(this.props.labels, 'width', width);
  10297. return (changed > 0);
  10298. };
  10299. /**
  10300. * Hide the component from the DOM
  10301. * @return {Boolean} changed
  10302. */
  10303. GroupSet.prototype.hide = function hide() {
  10304. if (this.dom.frame && this.dom.frame.parentNode) {
  10305. this.dom.frame.parentNode.removeChild(this.dom.frame);
  10306. return true;
  10307. }
  10308. else {
  10309. return false;
  10310. }
  10311. };
  10312. /**
  10313. * Show the component in the DOM (when not already visible).
  10314. * A repaint will be executed when the component is not visible
  10315. * @return {Boolean} changed
  10316. */
  10317. GroupSet.prototype.show = function show() {
  10318. if (!this.dom.frame || !this.dom.frame.parentNode) {
  10319. return this.repaint();
  10320. }
  10321. else {
  10322. return false;
  10323. }
  10324. };
  10325. /**
  10326. * Handle updated groups
  10327. * @param {Number[]} ids
  10328. * @private
  10329. */
  10330. GroupSet.prototype._onUpdate = function _onUpdate(ids) {
  10331. this._toQueue(ids, 'update');
  10332. };
  10333. /**
  10334. * Handle changed groups
  10335. * @param {Number[]} ids
  10336. * @private
  10337. */
  10338. GroupSet.prototype._onAdd = function _onAdd(ids) {
  10339. this._toQueue(ids, 'add');
  10340. };
  10341. /**
  10342. * Handle removed groups
  10343. * @param {Number[]} ids
  10344. * @private
  10345. */
  10346. GroupSet.prototype._onRemove = function _onRemove(ids) {
  10347. this._toQueue(ids, 'remove');
  10348. };
  10349. /**
  10350. * Put groups in the queue to be added/updated/remove
  10351. * @param {Number[]} ids
  10352. * @param {String} action can be 'add', 'update', 'remove'
  10353. */
  10354. GroupSet.prototype._toQueue = function _toQueue(ids, action) {
  10355. var queue = this.queue;
  10356. ids.forEach(function (id) {
  10357. queue[id] = action;
  10358. });
  10359. if (this.controller) {
  10360. //this.requestReflow();
  10361. this.requestRepaint();
  10362. }
  10363. };
  10364. /**
  10365. * Create a timeline visualization
  10366. * @param {HTMLElement} container
  10367. * @param {vis.DataSet | Array | DataTable} [items]
  10368. * @param {Object} [options] See Timeline.setOptions for the available options.
  10369. * @constructor
  10370. */
  10371. function Timeline (container, items, options) {
  10372. var me = this;
  10373. var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0);
  10374. this.options = {
  10375. orientation: 'bottom',
  10376. min: null,
  10377. max: null,
  10378. zoomMin: 10, // milliseconds
  10379. zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000, // milliseconds
  10380. // moveable: true, // TODO: option moveable
  10381. // zoomable: true, // TODO: option zoomable
  10382. showMinorLabels: true,
  10383. showMajorLabels: true,
  10384. showCurrentTime: false,
  10385. showCustomTime: false,
  10386. autoResize: false
  10387. };
  10388. // controller
  10389. this.controller = new Controller();
  10390. // root panel
  10391. if (!container) {
  10392. throw new Error('No container element provided');
  10393. }
  10394. var rootOptions = Object.create(this.options);
  10395. rootOptions.height = function () {
  10396. // TODO: change to height
  10397. if (me.options.height) {
  10398. // fixed height
  10399. return me.options.height;
  10400. }
  10401. else {
  10402. // auto height
  10403. return (me.timeaxis.height + me.content.height) + 'px';
  10404. }
  10405. };
  10406. this.rootPanel = new RootPanel(container, rootOptions);
  10407. this.controller.add(this.rootPanel);
  10408. // item panel
  10409. var itemOptions = Object.create(this.options);
  10410. itemOptions.left = function () {
  10411. return me.labelPanel.width;
  10412. };
  10413. itemOptions.width = function () {
  10414. return me.rootPanel.width - me.labelPanel.width;
  10415. };
  10416. itemOptions.top = null;
  10417. itemOptions.height = null;
  10418. this.itemPanel = new Panel(this.rootPanel, [], itemOptions);
  10419. this.controller.add(this.itemPanel);
  10420. // label panel
  10421. var labelOptions = Object.create(this.options);
  10422. labelOptions.top = null;
  10423. labelOptions.left = null;
  10424. labelOptions.height = null;
  10425. labelOptions.width = function () {
  10426. if (me.content && typeof me.content.getLabelsWidth === 'function') {
  10427. return me.content.getLabelsWidth();
  10428. }
  10429. else {
  10430. return 0;
  10431. }
  10432. };
  10433. this.labelPanel = new Panel(this.rootPanel, [], labelOptions);
  10434. this.controller.add(this.labelPanel);
  10435. // range
  10436. var rangeOptions = Object.create(this.options);
  10437. this.range = new Range(rangeOptions);
  10438. this.range.setRange(
  10439. now.clone().add('days', -3).valueOf(),
  10440. now.clone().add('days', 4).valueOf()
  10441. );
  10442. // TODO: reckon with options moveable and zoomable
  10443. this.range.subscribe(this.rootPanel, 'move', 'horizontal');
  10444. this.range.subscribe(this.rootPanel, 'zoom', 'horizontal');
  10445. this.range.on('rangechange', function () {
  10446. var force = true;
  10447. me.controller.requestReflow(force);
  10448. });
  10449. this.range.on('rangechanged', function () {
  10450. var force = true;
  10451. me.controller.requestReflow(force);
  10452. });
  10453. // TODO: put the listeners in setOptions, be able to dynamically change with options moveable and zoomable
  10454. // time axis
  10455. var timeaxisOptions = Object.create(rootOptions);
  10456. timeaxisOptions.range = this.range;
  10457. timeaxisOptions.left = null;
  10458. timeaxisOptions.top = null;
  10459. timeaxisOptions.width = '100%';
  10460. timeaxisOptions.height = null;
  10461. this.timeaxis = new TimeAxis(this.itemPanel, [], timeaxisOptions);
  10462. this.timeaxis.setRange(this.range);
  10463. this.controller.add(this.timeaxis);
  10464. // current time bar
  10465. this.currenttime = new CurrentTime(this.timeaxis, [], rootOptions);
  10466. this.controller.add(this.currenttime);
  10467. // custom time bar
  10468. this.customtime = new CustomTime(this.timeaxis, [], rootOptions);
  10469. this.controller.add(this.customtime);
  10470. // create groupset
  10471. this.setGroups(null);
  10472. this.itemsData = null; // DataSet
  10473. this.groupsData = null; // DataSet
  10474. // apply options
  10475. if (options) {
  10476. this.setOptions(options);
  10477. }
  10478. // create itemset and groupset
  10479. if (items) {
  10480. this.setItems(items);
  10481. }
  10482. }
  10483. /**
  10484. * Set options
  10485. * @param {Object} options TODO: describe the available options
  10486. */
  10487. Timeline.prototype.setOptions = function (options) {
  10488. util.extend(this.options, options);
  10489. // force update of range
  10490. // options.start and options.end can be undefined
  10491. //this.range.setRange(options.start, options.end);
  10492. this.range.setRange();
  10493. this.controller.reflow();
  10494. this.controller.repaint();
  10495. };
  10496. /**
  10497. * Set a custom time bar
  10498. * @param {Date} time
  10499. */
  10500. Timeline.prototype.setCustomTime = function (time) {
  10501. this.customtime._setCustomTime(time);
  10502. };
  10503. /**
  10504. * Retrieve the current custom time.
  10505. * @return {Date} customTime
  10506. */
  10507. Timeline.prototype.getCustomTime = function() {
  10508. return new Date(this.customtime.customTime.valueOf());
  10509. };
  10510. /**
  10511. * Set items
  10512. * @param {vis.DataSet | Array | DataTable | null} items
  10513. */
  10514. Timeline.prototype.setItems = function(items) {
  10515. var initialLoad = (this.itemsData == null);
  10516. // convert to type DataSet when needed
  10517. var newItemSet;
  10518. if (!items) {
  10519. newItemSet = null;
  10520. }
  10521. else if (items instanceof DataSet) {
  10522. newItemSet = items;
  10523. }
  10524. if (!(items instanceof DataSet)) {
  10525. newItemSet = new DataSet({
  10526. convert: {
  10527. start: 'Date',
  10528. end: 'Date'
  10529. }
  10530. });
  10531. newItemSet.add(items);
  10532. }
  10533. // set items
  10534. this.itemsData = newItemSet;
  10535. this.content.setItems(newItemSet);
  10536. if (initialLoad && (this.options.start == undefined || this.options.end == undefined)) {
  10537. // apply the data range as range
  10538. var dataRange = this.getItemRange();
  10539. // add 5% space on both sides
  10540. var min = dataRange.min;
  10541. var max = dataRange.max;
  10542. if (min != null && max != null) {
  10543. var interval = (max.valueOf() - min.valueOf());
  10544. if (interval <= 0) {
  10545. // prevent an empty interval
  10546. interval = 24 * 60 * 60 * 1000; // 1 day
  10547. }
  10548. min = new Date(min.valueOf() - interval * 0.05);
  10549. max = new Date(max.valueOf() + interval * 0.05);
  10550. }
  10551. // override specified start and/or end date
  10552. if (this.options.start != undefined) {
  10553. min = util.convert(this.options.start, 'Date');
  10554. }
  10555. if (this.options.end != undefined) {
  10556. max = util.convert(this.options.end, 'Date');
  10557. }
  10558. // apply range if there is a min or max available
  10559. if (min != null || max != null) {
  10560. this.range.setRange(min, max);
  10561. }
  10562. }
  10563. };
  10564. /**
  10565. * Set groups
  10566. * @param {vis.DataSet | Array | DataTable} groups
  10567. */
  10568. Timeline.prototype.setGroups = function(groups) {
  10569. var me = this;
  10570. this.groupsData = groups;
  10571. // switch content type between ItemSet or GroupSet when needed
  10572. var Type = this.groupsData ? GroupSet : ItemSet;
  10573. if (!(this.content instanceof Type)) {
  10574. // remove old content set
  10575. if (this.content) {
  10576. this.content.hide();
  10577. if (this.content.setItems) {
  10578. this.content.setItems(); // disconnect from items
  10579. }
  10580. if (this.content.setGroups) {
  10581. this.content.setGroups(); // disconnect from groups
  10582. }
  10583. this.controller.remove(this.content);
  10584. }
  10585. // create new content set
  10586. var options = Object.create(this.options);
  10587. util.extend(options, {
  10588. top: function () {
  10589. if (me.options.orientation == 'top') {
  10590. return me.timeaxis.height;
  10591. }
  10592. else {
  10593. return me.itemPanel.height - me.timeaxis.height - me.content.height;
  10594. }
  10595. },
  10596. left: null,
  10597. width: '100%',
  10598. height: function () {
  10599. if (me.options.height) {
  10600. // fixed height
  10601. return me.itemPanel.height - me.timeaxis.height;
  10602. }
  10603. else {
  10604. // auto height
  10605. return null;
  10606. }
  10607. },
  10608. maxHeight: function () {
  10609. // TODO: change maxHeight to be a css string like '100%' or '300px'
  10610. if (me.options.maxHeight) {
  10611. if (!util.isNumber(me.options.maxHeight)) {
  10612. throw new TypeError('Number expected for property maxHeight');
  10613. }
  10614. return me.options.maxHeight - me.timeaxis.height;
  10615. }
  10616. else {
  10617. return null;
  10618. }
  10619. },
  10620. labelContainer: function () {
  10621. return me.labelPanel.getContainer();
  10622. }
  10623. });
  10624. this.content = new Type(this.itemPanel, [this.timeaxis], options);
  10625. if (this.content.setRange) {
  10626. this.content.setRange(this.range);
  10627. }
  10628. if (this.content.setItems) {
  10629. this.content.setItems(this.itemsData);
  10630. }
  10631. if (this.content.setGroups) {
  10632. this.content.setGroups(this.groupsData);
  10633. }
  10634. this.controller.add(this.content);
  10635. }
  10636. };
  10637. /**
  10638. * Get the data range of the item set.
  10639. * @returns {{min: Date, max: Date}} range A range with a start and end Date.
  10640. * When no minimum is found, min==null
  10641. * When no maximum is found, max==null
  10642. */
  10643. Timeline.prototype.getItemRange = function getItemRange() {
  10644. // calculate min from start filed
  10645. var itemsData = this.itemsData,
  10646. min = null,
  10647. max = null;
  10648. if (itemsData) {
  10649. // calculate the minimum value of the field 'start'
  10650. var minItem = itemsData.min('start');
  10651. min = minItem ? minItem.start.valueOf() : null;
  10652. // calculate maximum value of fields 'start' and 'end'
  10653. var maxStartItem = itemsData.max('start');
  10654. if (maxStartItem) {
  10655. max = maxStartItem.start.valueOf();
  10656. }
  10657. var maxEndItem = itemsData.max('end');
  10658. if (maxEndItem) {
  10659. if (max == null) {
  10660. max = maxEndItem.end.valueOf();
  10661. }
  10662. else {
  10663. max = Math.max(max, maxEndItem.end.valueOf());
  10664. }
  10665. }
  10666. }
  10667. return {
  10668. min: (min != null) ? new Date(min) : null,
  10669. max: (max != null) ? new Date(max) : null
  10670. };
  10671. };
  10672. (function(exports) {
  10673. /**
  10674. * Parse a text source containing data in DOT language into a JSON object.
  10675. * The object contains two lists: one with nodes and one with edges.
  10676. *
  10677. * DOT language reference: http://www.graphviz.org/doc/info/lang.html
  10678. *
  10679. * @param {String} data Text containing a graph in DOT-notation
  10680. * @return {Object} graph An object containing two parameters:
  10681. * {Object[]} nodes
  10682. * {Object[]} edges
  10683. */
  10684. function parseDOT (data) {
  10685. dot = data;
  10686. return parseGraph();
  10687. }
  10688. // token types enumeration
  10689. var TOKENTYPE = {
  10690. NULL : 0,
  10691. DELIMITER : 1,
  10692. IDENTIFIER: 2,
  10693. UNKNOWN : 3
  10694. };
  10695. // map with all delimiters
  10696. var DELIMITERS = {
  10697. '{': true,
  10698. '}': true,
  10699. '[': true,
  10700. ']': true,
  10701. ';': true,
  10702. '=': true,
  10703. ',': true,
  10704. '->': true,
  10705. '--': true
  10706. };
  10707. var dot = ''; // current dot file
  10708. var index = 0; // current index in dot file
  10709. var c = ''; // current token character in expr
  10710. var token = ''; // current token
  10711. var tokenType = TOKENTYPE.NULL; // type of the token
  10712. /**
  10713. * Get the first character from the dot file.
  10714. * The character is stored into the char c. If the end of the dot file is
  10715. * reached, the function puts an empty string in c.
  10716. */
  10717. function first() {
  10718. index = 0;
  10719. c = dot.charAt(0);
  10720. }
  10721. /**
  10722. * Get the next character from the dot file.
  10723. * The character is stored into the char c. If the end of the dot file is
  10724. * reached, the function puts an empty string in c.
  10725. */
  10726. function next() {
  10727. index++;
  10728. c = dot.charAt(index);
  10729. }
  10730. /**
  10731. * Preview the next character from the dot file.
  10732. * @return {String} cNext
  10733. */
  10734. function nextPreview() {
  10735. return dot.charAt(index + 1);
  10736. }
  10737. /**
  10738. * Test whether given character is alphabetic or numeric
  10739. * @param {String} c
  10740. * @return {Boolean} isAlphaNumeric
  10741. */
  10742. var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/;
  10743. function isAlphaNumeric(c) {
  10744. return regexAlphaNumeric.test(c);
  10745. }
  10746. /**
  10747. * Merge all properties of object b into object b
  10748. * @param {Object} a
  10749. * @param {Object} b
  10750. * @return {Object} a
  10751. */
  10752. function merge (a, b) {
  10753. if (!a) {
  10754. a = {};
  10755. }
  10756. if (b) {
  10757. for (var name in b) {
  10758. if (b.hasOwnProperty(name)) {
  10759. a[name] = b[name];
  10760. }
  10761. }
  10762. }
  10763. return a;
  10764. }
  10765. /**
  10766. * Set a value in an object, where the provided parameter name can be a
  10767. * path with nested parameters. For example:
  10768. *
  10769. * var obj = {a: 2};
  10770. * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}}
  10771. *
  10772. * @param {Object} obj
  10773. * @param {String} path A parameter name or dot-separated parameter path,
  10774. * like "color.highlight.border".
  10775. * @param {*} value
  10776. */
  10777. function setValue(obj, path, value) {
  10778. var keys = path.split('.');
  10779. var o = obj;
  10780. while (keys.length) {
  10781. var key = keys.shift();
  10782. if (keys.length) {
  10783. // this isn't the end point
  10784. if (!o[key]) {
  10785. o[key] = {};
  10786. }
  10787. o = o[key];
  10788. }
  10789. else {
  10790. // this is the end point
  10791. o[key] = value;
  10792. }
  10793. }
  10794. }
  10795. /**
  10796. * Add a node to a graph object. If there is already a node with
  10797. * the same id, their attributes will be merged.
  10798. * @param {Object} graph
  10799. * @param {Object} node
  10800. */
  10801. function addNode(graph, node) {
  10802. var i, len;
  10803. var current = null;
  10804. // find root graph (in case of subgraph)
  10805. var graphs = [graph]; // list with all graphs from current graph to root graph
  10806. var root = graph;
  10807. while (root.parent) {
  10808. graphs.push(root.parent);
  10809. root = root.parent;
  10810. }
  10811. // find existing node (at root level) by its id
  10812. if (root.nodes) {
  10813. for (i = 0, len = root.nodes.length; i < len; i++) {
  10814. if (node.id === root.nodes[i].id) {
  10815. current = root.nodes[i];
  10816. break;
  10817. }
  10818. }
  10819. }
  10820. if (!current) {
  10821. // this is a new node
  10822. current = {
  10823. id: node.id
  10824. };
  10825. if (graph.node) {
  10826. // clone default attributes
  10827. current.attr = merge(current.attr, graph.node);
  10828. }
  10829. }
  10830. // add node to this (sub)graph and all its parent graphs
  10831. for (i = graphs.length - 1; i >= 0; i--) {
  10832. var g = graphs[i];
  10833. if (!g.nodes) {
  10834. g.nodes = [];
  10835. }
  10836. if (g.nodes.indexOf(current) == -1) {
  10837. g.nodes.push(current);
  10838. }
  10839. }
  10840. // merge attributes
  10841. if (node.attr) {
  10842. current.attr = merge(current.attr, node.attr);
  10843. }
  10844. }
  10845. /**
  10846. * Add an edge to a graph object
  10847. * @param {Object} graph
  10848. * @param {Object} edge
  10849. */
  10850. function addEdge(graph, edge) {
  10851. if (!graph.edges) {
  10852. graph.edges = [];
  10853. }
  10854. graph.edges.push(edge);
  10855. if (graph.edge) {
  10856. var attr = merge({}, graph.edge); // clone default attributes
  10857. edge.attr = merge(attr, edge.attr); // merge attributes
  10858. }
  10859. }
  10860. /**
  10861. * Create an edge to a graph object
  10862. * @param {Object} graph
  10863. * @param {String | Number | Object} from
  10864. * @param {String | Number | Object} to
  10865. * @param {String} type
  10866. * @param {Object | null} attr
  10867. * @return {Object} edge
  10868. */
  10869. function createEdge(graph, from, to, type, attr) {
  10870. var edge = {
  10871. from: from,
  10872. to: to,
  10873. type: type
  10874. };
  10875. if (graph.edge) {
  10876. edge.attr = merge({}, graph.edge); // clone default attributes
  10877. }
  10878. edge.attr = merge(edge.attr || {}, attr); // merge attributes
  10879. return edge;
  10880. }
  10881. /**
  10882. * Get next token in the current dot file.
  10883. * The token and token type are available as token and tokenType
  10884. */
  10885. function getToken() {
  10886. tokenType = TOKENTYPE.NULL;
  10887. token = '';
  10888. // skip over whitespaces
  10889. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  10890. next();
  10891. }
  10892. do {
  10893. var isComment = false;
  10894. // skip comment
  10895. if (c == '#') {
  10896. // find the previous non-space character
  10897. var i = index - 1;
  10898. while (dot.charAt(i) == ' ' || dot.charAt(i) == '\t') {
  10899. i--;
  10900. }
  10901. if (dot.charAt(i) == '\n' || dot.charAt(i) == '') {
  10902. // the # is at the start of a line, this is indeed a line comment
  10903. while (c != '' && c != '\n') {
  10904. next();
  10905. }
  10906. isComment = true;
  10907. }
  10908. }
  10909. if (c == '/' && nextPreview() == '/') {
  10910. // skip line comment
  10911. while (c != '' && c != '\n') {
  10912. next();
  10913. }
  10914. isComment = true;
  10915. }
  10916. if (c == '/' && nextPreview() == '*') {
  10917. // skip block comment
  10918. while (c != '') {
  10919. if (c == '*' && nextPreview() == '/') {
  10920. // end of block comment found. skip these last two characters
  10921. next();
  10922. next();
  10923. break;
  10924. }
  10925. else {
  10926. next();
  10927. }
  10928. }
  10929. isComment = true;
  10930. }
  10931. // skip over whitespaces
  10932. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  10933. next();
  10934. }
  10935. }
  10936. while (isComment);
  10937. // check for end of dot file
  10938. if (c == '') {
  10939. // token is still empty
  10940. tokenType = TOKENTYPE.DELIMITER;
  10941. return;
  10942. }
  10943. // check for delimiters consisting of 2 characters
  10944. var c2 = c + nextPreview();
  10945. if (DELIMITERS[c2]) {
  10946. tokenType = TOKENTYPE.DELIMITER;
  10947. token = c2;
  10948. next();
  10949. next();
  10950. return;
  10951. }
  10952. // check for delimiters consisting of 1 character
  10953. if (DELIMITERS[c]) {
  10954. tokenType = TOKENTYPE.DELIMITER;
  10955. token = c;
  10956. next();
  10957. return;
  10958. }
  10959. // check for an identifier (number or string)
  10960. // TODO: more precise parsing of numbers/strings (and the port separator ':')
  10961. if (isAlphaNumeric(c) || c == '-') {
  10962. token += c;
  10963. next();
  10964. while (isAlphaNumeric(c)) {
  10965. token += c;
  10966. next();
  10967. }
  10968. if (token == 'false') {
  10969. token = false; // convert to boolean
  10970. }
  10971. else if (token == 'true') {
  10972. token = true; // convert to boolean
  10973. }
  10974. else if (!isNaN(Number(token))) {
  10975. token = Number(token); // convert to number
  10976. }
  10977. tokenType = TOKENTYPE.IDENTIFIER;
  10978. return;
  10979. }
  10980. // check for a string enclosed by double quotes
  10981. if (c == '"') {
  10982. next();
  10983. while (c != '' && (c != '"' || (c == '"' && nextPreview() == '"'))) {
  10984. token += c;
  10985. if (c == '"') { // skip the escape character
  10986. next();
  10987. }
  10988. next();
  10989. }
  10990. if (c != '"') {
  10991. throw newSyntaxError('End of string " expected');
  10992. }
  10993. next();
  10994. tokenType = TOKENTYPE.IDENTIFIER;
  10995. return;
  10996. }
  10997. // something unknown is found, wrong characters, a syntax error
  10998. tokenType = TOKENTYPE.UNKNOWN;
  10999. while (c != '') {
  11000. token += c;
  11001. next();
  11002. }
  11003. throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"');
  11004. }
  11005. /**
  11006. * Parse a graph.
  11007. * @returns {Object} graph
  11008. */
  11009. function parseGraph() {
  11010. var graph = {};
  11011. first();
  11012. getToken();
  11013. // optional strict keyword
  11014. if (token == 'strict') {
  11015. graph.strict = true;
  11016. getToken();
  11017. }
  11018. // graph or digraph keyword
  11019. if (token == 'graph' || token == 'digraph') {
  11020. graph.type = token;
  11021. getToken();
  11022. }
  11023. // optional graph id
  11024. if (tokenType == TOKENTYPE.IDENTIFIER) {
  11025. graph.id = token;
  11026. getToken();
  11027. }
  11028. // open angle bracket
  11029. if (token != '{') {
  11030. throw newSyntaxError('Angle bracket { expected');
  11031. }
  11032. getToken();
  11033. // statements
  11034. parseStatements(graph);
  11035. // close angle bracket
  11036. if (token != '}') {
  11037. throw newSyntaxError('Angle bracket } expected');
  11038. }
  11039. getToken();
  11040. // end of file
  11041. if (token !== '') {
  11042. throw newSyntaxError('End of file expected');
  11043. }
  11044. getToken();
  11045. // remove temporary default properties
  11046. delete graph.node;
  11047. delete graph.edge;
  11048. delete graph.graph;
  11049. return graph;
  11050. }
  11051. /**
  11052. * Parse a list with statements.
  11053. * @param {Object} graph
  11054. */
  11055. function parseStatements (graph) {
  11056. while (token !== '' && token != '}') {
  11057. parseStatement(graph);
  11058. if (token == ';') {
  11059. getToken();
  11060. }
  11061. }
  11062. }
  11063. /**
  11064. * Parse a single statement. Can be a an attribute statement, node
  11065. * statement, a series of node statements and edge statements, or a
  11066. * parameter.
  11067. * @param {Object} graph
  11068. */
  11069. function parseStatement(graph) {
  11070. // parse subgraph
  11071. var subgraph = parseSubgraph(graph);
  11072. if (subgraph) {
  11073. // edge statements
  11074. parseEdge(graph, subgraph);
  11075. return;
  11076. }
  11077. // parse an attribute statement
  11078. var attr = parseAttributeStatement(graph);
  11079. if (attr) {
  11080. return;
  11081. }
  11082. // parse node
  11083. if (tokenType != TOKENTYPE.IDENTIFIER) {
  11084. throw newSyntaxError('Identifier expected');
  11085. }
  11086. var id = token; // id can be a string or a number
  11087. getToken();
  11088. if (token == '=') {
  11089. // id statement
  11090. getToken();
  11091. if (tokenType != TOKENTYPE.IDENTIFIER) {
  11092. throw newSyntaxError('Identifier expected');
  11093. }
  11094. graph[id] = token;
  11095. getToken();
  11096. // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] "
  11097. }
  11098. else {
  11099. parseNodeStatement(graph, id);
  11100. }
  11101. }
  11102. /**
  11103. * Parse a subgraph
  11104. * @param {Object} graph parent graph object
  11105. * @return {Object | null} subgraph
  11106. */
  11107. function parseSubgraph (graph) {
  11108. var subgraph = null;
  11109. // optional subgraph keyword
  11110. if (token == 'subgraph') {
  11111. subgraph = {};
  11112. subgraph.type = 'subgraph';
  11113. getToken();
  11114. // optional graph id
  11115. if (tokenType == TOKENTYPE.IDENTIFIER) {
  11116. subgraph.id = token;
  11117. getToken();
  11118. }
  11119. }
  11120. // open angle bracket
  11121. if (token == '{') {
  11122. getToken();
  11123. if (!subgraph) {
  11124. subgraph = {};
  11125. }
  11126. subgraph.parent = graph;
  11127. subgraph.node = graph.node;
  11128. subgraph.edge = graph.edge;
  11129. subgraph.graph = graph.graph;
  11130. // statements
  11131. parseStatements(subgraph);
  11132. // close angle bracket
  11133. if (token != '}') {
  11134. throw newSyntaxError('Angle bracket } expected');
  11135. }
  11136. getToken();
  11137. // remove temporary default properties
  11138. delete subgraph.node;
  11139. delete subgraph.edge;
  11140. delete subgraph.graph;
  11141. delete subgraph.parent;
  11142. // register at the parent graph
  11143. if (!graph.subgraphs) {
  11144. graph.subgraphs = [];
  11145. }
  11146. graph.subgraphs.push(subgraph);
  11147. }
  11148. return subgraph;
  11149. }
  11150. /**
  11151. * parse an attribute statement like "node [shape=circle fontSize=16]".
  11152. * Available keywords are 'node', 'edge', 'graph'.
  11153. * The previous list with default attributes will be replaced
  11154. * @param {Object} graph
  11155. * @returns {String | null} keyword Returns the name of the parsed attribute
  11156. * (node, edge, graph), or null if nothing
  11157. * is parsed.
  11158. */
  11159. function parseAttributeStatement (graph) {
  11160. // attribute statements
  11161. if (token == 'node') {
  11162. getToken();
  11163. // node attributes
  11164. graph.node = parseAttributeList();
  11165. return 'node';
  11166. }
  11167. else if (token == 'edge') {
  11168. getToken();
  11169. // edge attributes
  11170. graph.edge = parseAttributeList();
  11171. return 'edge';
  11172. }
  11173. else if (token == 'graph') {
  11174. getToken();
  11175. // graph attributes
  11176. graph.graph = parseAttributeList();
  11177. return 'graph';
  11178. }
  11179. return null;
  11180. }
  11181. /**
  11182. * parse a node statement
  11183. * @param {Object} graph
  11184. * @param {String | Number} id
  11185. */
  11186. function parseNodeStatement(graph, id) {
  11187. // node statement
  11188. var node = {
  11189. id: id
  11190. };
  11191. var attr = parseAttributeList();
  11192. if (attr) {
  11193. node.attr = attr;
  11194. }
  11195. addNode(graph, node);
  11196. // edge statements
  11197. parseEdge(graph, id);
  11198. }
  11199. /**
  11200. * Parse an edge or a series of edges
  11201. * @param {Object} graph
  11202. * @param {String | Number} from Id of the from node
  11203. */
  11204. function parseEdge(graph, from) {
  11205. while (token == '->' || token == '--') {
  11206. var to;
  11207. var type = token;
  11208. getToken();
  11209. var subgraph = parseSubgraph(graph);
  11210. if (subgraph) {
  11211. to = subgraph;
  11212. }
  11213. else {
  11214. if (tokenType != TOKENTYPE.IDENTIFIER) {
  11215. throw newSyntaxError('Identifier or subgraph expected');
  11216. }
  11217. to = token;
  11218. addNode(graph, {
  11219. id: to
  11220. });
  11221. getToken();
  11222. }
  11223. // parse edge attributes
  11224. var attr = parseAttributeList();
  11225. // create edge
  11226. var edge = createEdge(graph, from, to, type, attr);
  11227. addEdge(graph, edge);
  11228. from = to;
  11229. }
  11230. }
  11231. /**
  11232. * Parse a set with attributes,
  11233. * for example [label="1.000", shape=solid]
  11234. * @return {Object | null} attr
  11235. */
  11236. function parseAttributeList() {
  11237. var attr = null;
  11238. while (token == '[') {
  11239. getToken();
  11240. attr = {};
  11241. while (token !== '' && token != ']') {
  11242. if (tokenType != TOKENTYPE.IDENTIFIER) {
  11243. throw newSyntaxError('Attribute name expected');
  11244. }
  11245. var name = token;
  11246. getToken();
  11247. if (token != '=') {
  11248. throw newSyntaxError('Equal sign = expected');
  11249. }
  11250. getToken();
  11251. if (tokenType != TOKENTYPE.IDENTIFIER) {
  11252. throw newSyntaxError('Attribute value expected');
  11253. }
  11254. var value = token;
  11255. setValue(attr, name, value); // name can be a path
  11256. getToken();
  11257. if (token ==',') {
  11258. getToken();
  11259. }
  11260. }
  11261. if (token != ']') {
  11262. throw newSyntaxError('Bracket ] expected');
  11263. }
  11264. getToken();
  11265. }
  11266. return attr;
  11267. }
  11268. /**
  11269. * Create a syntax error with extra information on current token and index.
  11270. * @param {String} message
  11271. * @returns {SyntaxError} err
  11272. */
  11273. function newSyntaxError(message) {
  11274. return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')');
  11275. }
  11276. /**
  11277. * Chop off text after a maximum length
  11278. * @param {String} text
  11279. * @param {Number} maxLength
  11280. * @returns {String}
  11281. */
  11282. function chop (text, maxLength) {
  11283. return (text.length <= maxLength) ? text : (text.substr(0, 27) + '...');
  11284. }
  11285. /**
  11286. * Execute a function fn for each pair of elements in two arrays
  11287. * @param {Array | *} array1
  11288. * @param {Array | *} array2
  11289. * @param {function} fn
  11290. */
  11291. function forEach2(array1, array2, fn) {
  11292. if (array1 instanceof Array) {
  11293. array1.forEach(function (elem1) {
  11294. if (array2 instanceof Array) {
  11295. array2.forEach(function (elem2) {
  11296. fn(elem1, elem2);
  11297. });
  11298. }
  11299. else {
  11300. fn(elem1, array2);
  11301. }
  11302. });
  11303. }
  11304. else {
  11305. if (array2 instanceof Array) {
  11306. array2.forEach(function (elem2) {
  11307. fn(array1, elem2);
  11308. });
  11309. }
  11310. else {
  11311. fn(array1, array2);
  11312. }
  11313. }
  11314. }
  11315. /**
  11316. * Convert a string containing a graph in DOT language into a map containing
  11317. * with nodes and edges in the format of graph.
  11318. * @param {String} data Text containing a graph in DOT-notation
  11319. * @return {Object} graphData
  11320. */
  11321. function DOTToGraph (data) {
  11322. // parse the DOT file
  11323. var dotData = parseDOT(data);
  11324. var graphData = {
  11325. nodes: [],
  11326. edges: [],
  11327. options: {}
  11328. };
  11329. // copy the nodes
  11330. if (dotData.nodes) {
  11331. dotData.nodes.forEach(function (dotNode) {
  11332. var graphNode = {
  11333. id: dotNode.id,
  11334. label: String(dotNode.label || dotNode.id)
  11335. };
  11336. merge(graphNode, dotNode.attr);
  11337. if (graphNode.image) {
  11338. graphNode.shape = 'image';
  11339. }
  11340. graphData.nodes.push(graphNode);
  11341. });
  11342. }
  11343. // copy the edges
  11344. if (dotData.edges) {
  11345. /**
  11346. * Convert an edge in DOT format to an edge with VisGraph format
  11347. * @param {Object} dotEdge
  11348. * @returns {Object} graphEdge
  11349. */
  11350. function convertEdge(dotEdge) {
  11351. var graphEdge = {
  11352. from: dotEdge.from,
  11353. to: dotEdge.to
  11354. };
  11355. merge(graphEdge, dotEdge.attr);
  11356. graphEdge.style = (dotEdge.type == '->') ? 'arrow' : 'line';
  11357. return graphEdge;
  11358. }
  11359. dotData.edges.forEach(function (dotEdge) {
  11360. var from, to;
  11361. if (dotEdge.from instanceof Object) {
  11362. from = dotEdge.from.nodes;
  11363. }
  11364. else {
  11365. from = {
  11366. id: dotEdge.from
  11367. }
  11368. }
  11369. if (dotEdge.to instanceof Object) {
  11370. to = dotEdge.to.nodes;
  11371. }
  11372. else {
  11373. to = {
  11374. id: dotEdge.to
  11375. }
  11376. }
  11377. if (dotEdge.from instanceof Object && dotEdge.from.edges) {
  11378. dotEdge.from.edges.forEach(function (subEdge) {
  11379. var graphEdge = convertEdge(subEdge);
  11380. graphData.edges.push(graphEdge);
  11381. });
  11382. }
  11383. forEach2(from, to, function (from, to) {
  11384. var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr);
  11385. var graphEdge = convertEdge(subEdge);
  11386. graphData.edges.push(graphEdge);
  11387. });
  11388. if (dotEdge.to instanceof Object && dotEdge.to.edges) {
  11389. dotEdge.to.edges.forEach(function (subEdge) {
  11390. var graphEdge = convertEdge(subEdge);
  11391. graphData.edges.push(graphEdge);
  11392. });
  11393. }
  11394. });
  11395. }
  11396. // copy the options
  11397. if (dotData.attr) {
  11398. graphData.options = dotData.attr;
  11399. }
  11400. return graphData;
  11401. }
  11402. // exports
  11403. exports.parseDOT = parseDOT;
  11404. exports.DOTToGraph = DOTToGraph;
  11405. })(typeof util !== 'undefined' ? util : exports);
  11406. /**
  11407. * Canvas shapes used by the Graph
  11408. */
  11409. if (typeof CanvasRenderingContext2D !== 'undefined') {
  11410. /**
  11411. * Draw a circle shape
  11412. */
  11413. CanvasRenderingContext2D.prototype.circle = function(x, y, r) {
  11414. this.beginPath();
  11415. this.arc(x, y, r, 0, 2*Math.PI, false);
  11416. };
  11417. /**
  11418. * Draw a square shape
  11419. * @param {Number} x horizontal center
  11420. * @param {Number} y vertical center
  11421. * @param {Number} r size, width and height of the square
  11422. */
  11423. CanvasRenderingContext2D.prototype.square = function(x, y, r) {
  11424. this.beginPath();
  11425. this.rect(x - r, y - r, r * 2, r * 2);
  11426. };
  11427. /**
  11428. * Draw a triangle shape
  11429. * @param {Number} x horizontal center
  11430. * @param {Number} y vertical center
  11431. * @param {Number} r radius, half the length of the sides of the triangle
  11432. */
  11433. CanvasRenderingContext2D.prototype.triangle = function(x, y, r) {
  11434. // http://en.wikipedia.org/wiki/Equilateral_triangle
  11435. this.beginPath();
  11436. var s = r * 2;
  11437. var s2 = s / 2;
  11438. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  11439. var h = Math.sqrt(s * s - s2 * s2); // height
  11440. this.moveTo(x, y - (h - ir));
  11441. this.lineTo(x + s2, y + ir);
  11442. this.lineTo(x - s2, y + ir);
  11443. this.lineTo(x, y - (h - ir));
  11444. this.closePath();
  11445. };
  11446. /**
  11447. * Draw a triangle shape in downward orientation
  11448. * @param {Number} x horizontal center
  11449. * @param {Number} y vertical center
  11450. * @param {Number} r radius
  11451. */
  11452. CanvasRenderingContext2D.prototype.triangleDown = 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 star shape, a star with 5 points
  11467. * @param {Number} x horizontal center
  11468. * @param {Number} y vertical center
  11469. * @param {Number} r radius, half the length of the sides of the triangle
  11470. */
  11471. CanvasRenderingContext2D.prototype.star = function(x, y, r) {
  11472. // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/
  11473. this.beginPath();
  11474. for (var n = 0; n < 10; n++) {
  11475. var radius = (n % 2 === 0) ? r * 1.3 : r * 0.5;
  11476. this.lineTo(
  11477. x + radius * Math.sin(n * 2 * Math.PI / 10),
  11478. y - radius * Math.cos(n * 2 * Math.PI / 10)
  11479. );
  11480. }
  11481. this.closePath();
  11482. };
  11483. /**
  11484. * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas
  11485. */
  11486. CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) {
  11487. var r2d = Math.PI/180;
  11488. if( w - ( 2 * r ) < 0 ) { r = ( w / 2 ); } //ensure that the radius isn't too large for x
  11489. if( h - ( 2 * r ) < 0 ) { r = ( h / 2 ); } //ensure that the radius isn't too large for y
  11490. this.beginPath();
  11491. this.moveTo(x+r,y);
  11492. this.lineTo(x+w-r,y);
  11493. this.arc(x+w-r,y+r,r,r2d*270,r2d*360,false);
  11494. this.lineTo(x+w,y+h-r);
  11495. this.arc(x+w-r,y+h-r,r,0,r2d*90,false);
  11496. this.lineTo(x+r,y+h);
  11497. this.arc(x+r,y+h-r,r,r2d*90,r2d*180,false);
  11498. this.lineTo(x,y+r);
  11499. this.arc(x+r,y+r,r,r2d*180,r2d*270,false);
  11500. };
  11501. /**
  11502. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  11503. */
  11504. CanvasRenderingContext2D.prototype.ellipse = function(x, y, w, h) {
  11505. var kappa = .5522848,
  11506. ox = (w / 2) * kappa, // control point offset horizontal
  11507. oy = (h / 2) * kappa, // control point offset vertical
  11508. xe = x + w, // x-end
  11509. ye = y + h, // y-end
  11510. xm = x + w / 2, // x-middle
  11511. ym = y + h / 2; // y-middle
  11512. this.beginPath();
  11513. this.moveTo(x, ym);
  11514. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  11515. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  11516. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  11517. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  11518. };
  11519. /**
  11520. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  11521. */
  11522. CanvasRenderingContext2D.prototype.database = function(x, y, w, h) {
  11523. var f = 1/3;
  11524. var wEllipse = w;
  11525. var hEllipse = h * f;
  11526. var kappa = .5522848,
  11527. ox = (wEllipse / 2) * kappa, // control point offset horizontal
  11528. oy = (hEllipse / 2) * kappa, // control point offset vertical
  11529. xe = x + wEllipse, // x-end
  11530. ye = y + hEllipse, // y-end
  11531. xm = x + wEllipse / 2, // x-middle
  11532. ym = y + hEllipse / 2, // y-middle
  11533. ymb = y + (h - hEllipse/2), // y-midlle, bottom ellipse
  11534. yeb = y + h; // y-end, bottom ellipse
  11535. this.beginPath();
  11536. this.moveTo(xe, ym);
  11537. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  11538. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  11539. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  11540. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  11541. this.lineTo(xe, ymb);
  11542. this.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb);
  11543. this.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb);
  11544. this.lineTo(x, ym);
  11545. };
  11546. /**
  11547. * Draw an arrow point (no line)
  11548. */
  11549. CanvasRenderingContext2D.prototype.arrow = function(x, y, angle, length) {
  11550. // tail
  11551. var xt = x - length * Math.cos(angle);
  11552. var yt = y - length * Math.sin(angle);
  11553. // inner tail
  11554. // TODO: allow to customize different shapes
  11555. var xi = x - length * 0.9 * Math.cos(angle);
  11556. var yi = y - length * 0.9 * Math.sin(angle);
  11557. // left
  11558. var xl = xt + length / 3 * Math.cos(angle + 0.5 * Math.PI);
  11559. var yl = yt + length / 3 * Math.sin(angle + 0.5 * Math.PI);
  11560. // right
  11561. var xr = xt + length / 3 * Math.cos(angle - 0.5 * Math.PI);
  11562. var yr = yt + length / 3 * Math.sin(angle - 0.5 * Math.PI);
  11563. this.beginPath();
  11564. this.moveTo(x, y);
  11565. this.lineTo(xl, yl);
  11566. this.lineTo(xi, yi);
  11567. this.lineTo(xr, yr);
  11568. this.closePath();
  11569. };
  11570. /**
  11571. * Sets up the dashedLine functionality for drawing
  11572. * Original code came from http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
  11573. * @author David Jordan
  11574. * @date 2012-08-08
  11575. */
  11576. CanvasRenderingContext2D.prototype.dashedLine = function(x,y,x2,y2,dashArray){
  11577. if (!dashArray) dashArray=[10,5];
  11578. if (dashLength==0) dashLength = 0.001; // Hack for Safari
  11579. var dashCount = dashArray.length;
  11580. this.moveTo(x, y);
  11581. var dx = (x2-x), dy = (y2-y);
  11582. var slope = dy/dx;
  11583. var distRemaining = Math.sqrt( dx*dx + dy*dy );
  11584. var dashIndex=0, draw=true;
  11585. while (distRemaining>=0.1){
  11586. var dashLength = dashArray[dashIndex++%dashCount];
  11587. if (dashLength > distRemaining) dashLength = distRemaining;
  11588. var xStep = Math.sqrt( dashLength*dashLength / (1 + slope*slope) );
  11589. if (dx<0) xStep = -xStep;
  11590. x += xStep;
  11591. y += slope*xStep;
  11592. this[draw ? 'lineTo' : 'moveTo'](x,y);
  11593. distRemaining -= dashLength;
  11594. draw = !draw;
  11595. }
  11596. };
  11597. // TODO: add diamond shape
  11598. }
  11599. /**
  11600. * @class Node
  11601. * A node. A node can be connected to other nodes via one or multiple edges.
  11602. * @param {object} properties An object containing properties for the node. All
  11603. * properties are optional, except for the id.
  11604. * {number} id Id of the node. Required
  11605. * {string} label Text label for the node
  11606. * {number} x Horizontal position of the node
  11607. * {number} y Vertical position of the node
  11608. * {string} shape Node shape, available:
  11609. * "database", "circle", "ellipse",
  11610. * "box", "image", "text", "dot",
  11611. * "star", "triangle", "triangleDown",
  11612. * "square"
  11613. * {string} image An image url
  11614. * {string} title An title text, can be HTML
  11615. * {anytype} group A group name or number
  11616. * @param {Graph.Images} imagelist A list with images. Only needed
  11617. * when the node has an image
  11618. * @param {Graph.Groups} grouplist A list with groups. Needed for
  11619. * retrieving group properties
  11620. * @param {Object} constants An object with default values for
  11621. * example for the color
  11622. */
  11623. function Node(properties, imagelist, grouplist, constants) {
  11624. this.selected = false;
  11625. this.edges = []; // all edges connected to this node
  11626. this.group = constants.nodes.group;
  11627. this.fontSize = constants.nodes.fontSize;
  11628. this.fontFace = constants.nodes.fontFace;
  11629. this.fontColor = constants.nodes.fontColor;
  11630. this.color = constants.nodes.color;
  11631. // set defaults for the properties
  11632. this.id = undefined;
  11633. this.shape = constants.nodes.shape;
  11634. this.image = constants.nodes.image;
  11635. this.x = 0;
  11636. this.y = 0;
  11637. this.xFixed = false;
  11638. this.yFixed = false;
  11639. this.radius = constants.nodes.radius;
  11640. this.radiusFixed = false;
  11641. this.radiusMin = constants.nodes.radiusMin;
  11642. this.radiusMax = constants.nodes.radiusMax;
  11643. this.imagelist = imagelist;
  11644. this.grouplist = grouplist;
  11645. this.setProperties(properties, constants);
  11646. // creating the variables for clustering
  11647. this.resetCluster();
  11648. this.remainingEdges = 0;
  11649. this.remainingEdges_unapplied = 0;
  11650. this.clusterSession = 0;
  11651. this.clusterSizeWidthFactor = constants.clustering.clusterSizeWidthFactor;
  11652. this.clusterSizeHeightFactor = constants.clustering.clusterSizeHeightFactor;
  11653. this.clusterSizeRadiusFactor = constants.clustering.clusterSizeRadiusFactor;
  11654. // mass, force, velocity
  11655. this.mass = 50; // kg (mass is adjusted for the number of connected edges)
  11656. this.fx = 0.0; // external force x
  11657. this.fy = 0.0; // external force y
  11658. this.vx = 0.0; // velocity x
  11659. this.vy = 0.0; // velocity y
  11660. this.minForce = constants.minForce;
  11661. this.damping = 0.9; // damping factor
  11662. }
  11663. /**
  11664. * (re)setting the clustering variables and objects
  11665. */
  11666. Node.prototype.resetCluster = function() {
  11667. // clustering variables
  11668. this.formationScale = undefined; // this is used to determine when to open the cluster
  11669. this.clusterSize = 1; // this signifies the total amount of nodes in this cluster
  11670. this.containedNodes = {};
  11671. this.containedEdges = {};
  11672. };
  11673. /**
  11674. * Attach a edge to the node
  11675. * @param {Edge} edge
  11676. */
  11677. Node.prototype.attachEdge = function(edge) {
  11678. if (this.edges.indexOf(edge) == -1) {
  11679. this.edges.push(edge);
  11680. }
  11681. this.remainingEdges = this.edges.length;
  11682. this.remainingEdges_unapplied = this.remainingEdges;
  11683. this._updateMass();
  11684. };
  11685. /**
  11686. * Detach a edge from the node
  11687. * @param {Edge} edge
  11688. */
  11689. Node.prototype.detachEdge = function(edge) {
  11690. var index = this.edges.indexOf(edge);
  11691. if (index != -1) {
  11692. this.edges.splice(index, 1);
  11693. }
  11694. this.remainingEdges = this.edges.length;
  11695. this.remainingEdges_unapplied = this.remainingEdges;
  11696. this._updateMass();
  11697. };
  11698. /**
  11699. * Update the nodes mass, which is determined by the number of edges connecting
  11700. * to it (more edges -> heavier node).
  11701. * @private
  11702. */
  11703. Node.prototype._updateMass = function() {
  11704. this.mass = 50 + 20 * this.edges.length; // kg
  11705. };
  11706. /**
  11707. * Set or overwrite properties for the node
  11708. * @param {Object} properties an object with properties
  11709. * @param {Object} constants and object with default, global properties
  11710. */
  11711. Node.prototype.setProperties = function(properties, constants) {
  11712. if (!properties) {
  11713. return;
  11714. }
  11715. // basic properties
  11716. if (properties.id != undefined) {this.id = properties.id;}
  11717. if (properties.label != undefined) {this.label = properties.label;}
  11718. if (properties.title != undefined) {this.title = properties.title;}
  11719. if (properties.group != undefined) {this.group = properties.group;}
  11720. if (properties.x != undefined) {this.x = properties.x;}
  11721. if (properties.y != undefined) {this.y = properties.y;}
  11722. if (properties.value != undefined) {this.value = properties.value;}
  11723. if (this.id === undefined) {
  11724. throw "Node must have an id";
  11725. }
  11726. // copy group properties
  11727. if (this.group) {
  11728. var groupObj = this.grouplist.get(this.group);
  11729. for (var prop in groupObj) {
  11730. if (groupObj.hasOwnProperty(prop)) {
  11731. this[prop] = groupObj[prop];
  11732. }
  11733. }
  11734. }
  11735. // individual shape properties
  11736. if (properties.shape != undefined) {this.shape = properties.shape;}
  11737. if (properties.image != undefined) {this.image = properties.image;}
  11738. if (properties.radius != undefined) {this.radius = properties.radius;}
  11739. if (properties.color != undefined) {this.color = Node.parseColor(properties.color);}
  11740. if (properties.fontColor != undefined) {this.fontColor = properties.fontColor;}
  11741. if (properties.fontSize != undefined) {this.fontSize = properties.fontSize;}
  11742. if (properties.fontFace != undefined) {this.fontFace = properties.fontFace;}
  11743. if (this.image != undefined) {
  11744. if (this.imagelist) {
  11745. this.imageObj = this.imagelist.load(this.image);
  11746. }
  11747. else {
  11748. throw "No imagelist provided";
  11749. }
  11750. }
  11751. this.xFixed = this.xFixed || (properties.x != undefined);
  11752. this.yFixed = this.yFixed || (properties.y != undefined);
  11753. this.radiusFixed = this.radiusFixed || (properties.radius != undefined);
  11754. if (this.shape == 'image') {
  11755. this.radiusMin = constants.nodes.widthMin;
  11756. this.radiusMax = constants.nodes.widthMax;
  11757. }
  11758. // choose draw method depending on the shape
  11759. switch (this.shape) {
  11760. case 'database': this.draw = this._drawDatabase; this.resize = this._resizeDatabase; break;
  11761. case 'box': this.draw = this._drawBox; this.resize = this._resizeBox; break;
  11762. case 'circle': this.draw = this._drawCircle; this.resize = this._resizeCircle; break;
  11763. case 'ellipse': this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  11764. // TODO: add diamond shape
  11765. case 'image': this.draw = this._drawImage; this.resize = this._resizeImage; break;
  11766. case 'text': this.draw = this._drawText; this.resize = this._resizeText; break;
  11767. case 'dot': this.draw = this._drawDot; this.resize = this._resizeShape; break;
  11768. case 'square': this.draw = this._drawSquare; this.resize = this._resizeShape; break;
  11769. case 'triangle': this.draw = this._drawTriangle; this.resize = this._resizeShape; break;
  11770. case 'triangleDown': this.draw = this._drawTriangleDown; this.resize = this._resizeShape; break;
  11771. case 'star': this.draw = this._drawStar; this.resize = this._resizeShape; break;
  11772. default: this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  11773. }
  11774. // reset the size of the node, this can be changed
  11775. this._reset();
  11776. };
  11777. /**
  11778. * Parse a color property into an object with border, background, and
  11779. * hightlight colors
  11780. * @param {Object | String} color
  11781. * @return {Object} colorObject
  11782. */
  11783. Node.parseColor = function(color) {
  11784. var c;
  11785. if (util.isString(color)) {
  11786. c = {
  11787. border: color,
  11788. background: color,
  11789. highlight: {
  11790. border: color,
  11791. background: color
  11792. },
  11793. cluster: {
  11794. border: color,
  11795. background: color,
  11796. highlight: {
  11797. border: color,
  11798. background: color
  11799. }
  11800. }
  11801. };
  11802. // TODO: automatically generate a nice highlight color
  11803. }
  11804. else {
  11805. c = {};
  11806. c.background = color.background || 'white';
  11807. c.border = color.border || c.background;
  11808. if (util.isString(color.highlight)) {
  11809. c.highlight = {
  11810. border: color.highlight,
  11811. background: color.highlight
  11812. }
  11813. }
  11814. else {
  11815. c.highlight = {};
  11816. c.highlight.background = color.highlight && color.highlight.background || c.background;
  11817. c.highlight.border = color.highlight && color.highlight.border || c.border;
  11818. }
  11819. // check if cluster colorgroup has been defined
  11820. if (util.isString(color.cluster)) {
  11821. c.cluster = {
  11822. border: color.cluster,
  11823. background: color.cluster
  11824. }
  11825. }
  11826. else {
  11827. c.cluster = {};
  11828. c.cluster.background = color.cluster && color.cluster.background || c.background;
  11829. c.cluster.border = color.cluster && color.cluster.border || c.border;
  11830. }
  11831. // check if cluster highlight colorgroup has been defined
  11832. if (util.isString(color.cluster.highlight)) {
  11833. c.cluster.highlight = {
  11834. border: color.cluster.highlight,
  11835. background: color.cluster.highlight
  11836. }
  11837. }
  11838. else {
  11839. c.cluster.highlight = {};
  11840. c.cluster.highlight.background = color.cluster.highlight && color.cluster.highlight.background || c.background;
  11841. c.cluster.highlight.border = color.cluster.highlight && color.cluster.highlight.border || c.border;
  11842. }
  11843. }
  11844. return c;
  11845. };
  11846. /**
  11847. * select this node
  11848. */
  11849. Node.prototype.select = function() {
  11850. this.selected = true;
  11851. this._reset();
  11852. };
  11853. /**
  11854. * unselect this node
  11855. */
  11856. Node.prototype.unselect = function() {
  11857. this.selected = false;
  11858. this._reset();
  11859. };
  11860. /**
  11861. * Reset the calculated size of the node, forces it to recalculate its size
  11862. */
  11863. Node.prototype.clearSizeCache = function() {
  11864. this._reset();
  11865. };
  11866. /**
  11867. * Reset the calculated size of the node, forces it to recalculate its size
  11868. * @private
  11869. */
  11870. Node.prototype._reset = function() {
  11871. this.width = undefined;
  11872. this.height = undefined;
  11873. };
  11874. /**
  11875. * get the title of this node.
  11876. * @return {string} title The title of the node, or undefined when no title
  11877. * has been set.
  11878. */
  11879. Node.prototype.getTitle = function() {
  11880. return this.title;
  11881. };
  11882. /**
  11883. * Calculate the distance to the border of the Node
  11884. * @param {CanvasRenderingContext2D} ctx
  11885. * @param {Number} angle Angle in radians
  11886. * @returns {number} distance Distance to the border in pixels
  11887. */
  11888. Node.prototype.distanceToBorder = function (ctx, angle) {
  11889. var borderWidth = 1;
  11890. if (!this.width) {
  11891. this.resize(ctx);
  11892. }
  11893. //noinspection FallthroughInSwitchStatementJS
  11894. switch (this.shape) {
  11895. case 'circle':
  11896. case 'dot':
  11897. return this.radius + borderWidth;
  11898. case 'ellipse':
  11899. var a = this.width / 2;
  11900. var b = this.height / 2;
  11901. var w = (Math.sin(angle) * a);
  11902. var h = (Math.cos(angle) * b);
  11903. return a * b / Math.sqrt(w * w + h * h);
  11904. // TODO: implement distanceToBorder for database
  11905. // TODO: implement distanceToBorder for triangle
  11906. // TODO: implement distanceToBorder for triangleDown
  11907. case 'box':
  11908. case 'image':
  11909. case 'text':
  11910. default:
  11911. if (this.width) {
  11912. return Math.min(
  11913. Math.abs(this.width / 2 / Math.cos(angle)),
  11914. Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth;
  11915. // TODO: reckon with border radius too in case of box
  11916. }
  11917. else {
  11918. return 0;
  11919. }
  11920. }
  11921. // TODO: implement calculation of distance to border for all shapes
  11922. };
  11923. /**
  11924. * Set forces acting on the node
  11925. * @param {number} fx Force in horizontal direction
  11926. * @param {number} fy Force in vertical direction
  11927. */
  11928. Node.prototype._setForce = function(fx, fy) {
  11929. this.fx = fx;
  11930. this.fy = fy;
  11931. };
  11932. /**
  11933. * Add forces acting on the node
  11934. * @param {number} fx Force in horizontal direction
  11935. * @param {number} fy Force in vertical direction
  11936. * @private
  11937. */
  11938. Node.prototype._addForce = function(fx, fy) {
  11939. this.fx += fx;
  11940. this.fy += fy;
  11941. };
  11942. /**
  11943. * Perform one discrete step for the node
  11944. * @param {number} interval Time interval in seconds
  11945. */
  11946. Node.prototype.discreteStep = function(interval) {
  11947. if (!this.xFixed) {
  11948. var dx = -this.damping * this.vx; // damping force
  11949. var ax = (this.fx + dx) / this.mass; // acceleration
  11950. this.vx += ax / interval; // velocity
  11951. this.x += this.vx / interval; // position
  11952. }
  11953. if (!this.yFixed) {
  11954. var dy = -this.damping * this.vy; // damping force
  11955. var ay = (this.fy + dy) / this.mass; // acceleration
  11956. this.vy += ay / interval; // velocity
  11957. this.y += this.vy / interval; // position
  11958. }
  11959. };
  11960. /**
  11961. * Check if this node has a fixed x and y position
  11962. * @return {boolean} true if fixed, false if not
  11963. */
  11964. Node.prototype.isFixed = function() {
  11965. return (this.xFixed && this.yFixed);
  11966. };
  11967. /**
  11968. * Check if this node is moving
  11969. * @param {number} vmin the minimum velocity considered as "moving"
  11970. * @return {boolean} true if moving, false if it has no velocity
  11971. */
  11972. // TODO: replace this method with calculating the kinetic energy
  11973. Node.prototype.isMoving = function(vmin) {
  11974. return (Math.abs(this.vx) > vmin || Math.abs(this.vy) > vmin ||
  11975. (!this.xFixed && Math.abs(this.fx) > this.minForce) ||
  11976. (!this.yFixed && Math.abs(this.fy) > this.minForce));
  11977. };
  11978. /**
  11979. * check if this node is selecte
  11980. * @return {boolean} selected True if node is selected, else false
  11981. */
  11982. Node.prototype.isSelected = function() {
  11983. return this.selected;
  11984. };
  11985. /**
  11986. * Retrieve the value of the node. Can be undefined
  11987. * @return {Number} value
  11988. */
  11989. Node.prototype.getValue = function() {
  11990. return this.value;
  11991. };
  11992. /**
  11993. * Calculate the distance from the nodes location to the given location (x,y)
  11994. * @param {Number} x
  11995. * @param {Number} y
  11996. * @return {Number} value
  11997. */
  11998. Node.prototype.getDistance = function(x, y) {
  11999. var dx = this.x - x,
  12000. dy = this.y - y;
  12001. return Math.sqrt(dx * dx + dy * dy);
  12002. };
  12003. /**
  12004. * Adjust the value range of the node. The node will adjust it's radius
  12005. * based on its value.
  12006. * @param {Number} min
  12007. * @param {Number} max
  12008. */
  12009. Node.prototype.setValueRange = function(min, max) {
  12010. if (!this.radiusFixed && this.value !== undefined) {
  12011. if (max == min) {
  12012. this.radius = (this.radiusMin + this.radiusMax) / 2;
  12013. }
  12014. else {
  12015. var scale = (this.radiusMax - this.radiusMin) / (max - min);
  12016. this.radius = (this.value - min) * scale + this.radiusMin;
  12017. }
  12018. }
  12019. };
  12020. /**
  12021. * Draw this node in the given canvas
  12022. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  12023. * @param {CanvasRenderingContext2D} ctx
  12024. */
  12025. Node.prototype.draw = function(ctx) {
  12026. throw "Draw method not initialized for node";
  12027. };
  12028. /**
  12029. * Recalculate the size of this node in the given canvas
  12030. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  12031. * @param {CanvasRenderingContext2D} ctx
  12032. */
  12033. Node.prototype.resize = function(ctx) {
  12034. throw "Resize method not initialized for node";
  12035. };
  12036. /**
  12037. * Check if this object is overlapping with the provided object
  12038. * @param {Object} obj an object with parameters left, top, right, bottom
  12039. * @return {boolean} True if location is located on node
  12040. */
  12041. Node.prototype.isOverlappingWith = function(obj) {
  12042. return (this.left < obj.right &&
  12043. this.left + this.width > obj.left &&
  12044. this.top < obj.bottom &&
  12045. this.top + this.height > obj.top);
  12046. };
  12047. Node.prototype._resizeImage = function (ctx) {
  12048. // TODO: pre calculate the image size
  12049. if (!this.width) { // undefined or 0
  12050. var width, height;
  12051. if (this.value) {
  12052. var scale = this.imageObj.height / this.imageObj.width;
  12053. width = this.radius || this.imageObj.width;
  12054. height = this.radius * scale || this.imageObj.height;
  12055. }
  12056. else {
  12057. width = this.imageObj.width;
  12058. height = this.imageObj.height;
  12059. }
  12060. this.width = width;
  12061. this.height = height;
  12062. this.width += this.clusterSize * this.clusterSizeWidthFactor;
  12063. this.height += this.clusterSize * this.clusterSizeHeightFactor;
  12064. this.radius += this.clusterSize * this.clusterSizeRadiusFactor;
  12065. }
  12066. };
  12067. Node.prototype._drawImage = function (ctx) {
  12068. this._resizeImage(ctx);
  12069. this.left = this.x - this.width / 2;
  12070. this.top = this.y - this.height / 2;
  12071. var yLabel;
  12072. if (this.imageObj) {
  12073. ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height);
  12074. yLabel = this.y + this.height / 2;
  12075. }
  12076. else {
  12077. // image still loading... just draw the label for now
  12078. yLabel = this.y;
  12079. }
  12080. this._label(ctx, this.label, this.x, yLabel, undefined, "top");
  12081. };
  12082. Node.prototype._resizeBox = function (ctx) {
  12083. if (!this.width) {
  12084. var margin = 5;
  12085. var textSize = this.getTextSize(ctx);
  12086. this.width = textSize.width + 2 * margin;
  12087. this.height = textSize.height + 2 * margin;
  12088. this.width += this.clusterSize * this.clusterSizeWidthFactor;
  12089. this.height += this.clusterSize * this.clusterSizeHeightFactor;
  12090. this.radius += this.clusterSize * this.clusterSizeRadiusFactor;
  12091. }
  12092. };
  12093. Node.prototype._drawBox = function (ctx) {
  12094. this._resizeBox(ctx);
  12095. this.left = this.x - this.width / 2;
  12096. this.top = this.y - this.height / 2;
  12097. if (this.clusterSize > 1) {
  12098. ctx.strokeStyle = this.selected ? this.color.cluster.highlight.border : this.color.cluster.border;
  12099. ctx.fillStyle = this.selected ? this.color.cluster.highlight.background : this.color.cluster.background;
  12100. }
  12101. else {
  12102. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  12103. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  12104. }
  12105. ctx.lineWidth = (this.selected ? 2.0 : 1.0) + (this.clusterSize > 1) ? 2.0 : 0.0;
  12106. ctx.roundRect(this.left, this.top, this.width, this.height, this.radius);
  12107. ctx.fill();
  12108. ctx.stroke();
  12109. this._label(ctx, this.label, this.x, this.y);
  12110. };
  12111. Node.prototype._resizeDatabase = function (ctx) {
  12112. if (!this.width) {
  12113. var margin = 5;
  12114. var textSize = this.getTextSize(ctx);
  12115. var size = textSize.width + 2 * margin;
  12116. this.width = size;
  12117. this.height = size;
  12118. // scaling used for clustering
  12119. this.width += this.clusterSize * this.clusterSizeWidthFactor;
  12120. this.height += this.clusterSize * this.clusterSizeHeightFactor;
  12121. this.radius += this.clusterSize * this.clusterSizeRadiusFactor;
  12122. }
  12123. };
  12124. Node.prototype._drawDatabase = function (ctx) {
  12125. this._resizeDatabase(ctx);
  12126. this.left = this.x - this.width / 2;
  12127. this.top = this.y - this.height / 2;
  12128. if (this.clusterSize > 1) {
  12129. ctx.strokeStyle = this.selected ? this.color.cluster.highlight.border : this.color.cluster.border;
  12130. ctx.fillStyle = this.selected ? this.color.cluster.highlight.background : this.color.cluster.background;
  12131. }
  12132. else {
  12133. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  12134. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  12135. }
  12136. ctx.lineWidth = (this.selected ? 2.0 : 1.0) + (this.clusterSize > 1) ? 2.0 : 0.0;
  12137. ctx.database(this.x - this.width/2, this.y - this.height*0.5, this.width, this.height);
  12138. ctx.fill();
  12139. ctx.stroke();
  12140. this._label(ctx, this.label, this.x, this.y);
  12141. };
  12142. Node.prototype._resizeCircle = function (ctx) {
  12143. if (!this.width) {
  12144. var margin = 5;
  12145. var textSize = this.getTextSize(ctx);
  12146. var diameter = Math.max(textSize.width, textSize.height) + 2 * margin;
  12147. this.radius = diameter / 2;
  12148. this.width = diameter;
  12149. this.height = diameter;
  12150. // scaling used for clustering
  12151. this.width += this.clusterSize * this.clusterSizeWidthFactor;
  12152. this.height += this.clusterSize * this.clusterSizeHeightFactor;
  12153. this.radius += this.clusterSize * this.clusterSizeRadiusFactor;
  12154. }
  12155. };
  12156. Node.prototype._drawCircle = function (ctx) {
  12157. this._resizeCircle(ctx);
  12158. this.left = this.x - this.width / 2;
  12159. this.top = this.y - this.height / 2;
  12160. if (this.clusterSize > 1) {
  12161. ctx.strokeStyle = this.selected ? this.color.cluster.highlight.border : this.color.cluster.border;
  12162. ctx.fillStyle = this.selected ? this.color.cluster.highlight.background : this.color.cluster.background;
  12163. }
  12164. else {
  12165. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  12166. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  12167. }
  12168. ctx.lineWidth = (this.selected ? 2.0 : 1.0) + (this.clusterSize > 1) ? 2.0 : 0.0;
  12169. ctx.circle(this.x, this.y, this.radius);
  12170. ctx.fill();
  12171. ctx.stroke();
  12172. this._label(ctx, this.label, this.x, this.y);
  12173. };
  12174. Node.prototype._resizeEllipse = function (ctx) {
  12175. if (!this.width) {
  12176. var textSize = this.getTextSize(ctx);
  12177. this.width = textSize.width * 1.5;
  12178. this.height = textSize.height * 2;
  12179. if (this.width < this.height) {
  12180. this.width = this.height;
  12181. }
  12182. // scaling used for clustering
  12183. this.width += this.clusterSize * this.clusterSizeWidthFactor;
  12184. this.height += this.clusterSize * this.clusterSizeHeightFactor;
  12185. this.radius += this.clusterSize * this.clusterSizeRadiusFactor;
  12186. }
  12187. };
  12188. Node.prototype._drawEllipse = function (ctx) {
  12189. this._resizeEllipse(ctx);
  12190. this.left = this.x - this.width / 2;
  12191. this.top = this.y - this.height / 2;
  12192. if (this.clusterSize > 1) {
  12193. ctx.strokeStyle = this.selected ? this.color.cluster.highlight.border : this.color.cluster.border;
  12194. ctx.fillStyle = this.selected ? this.color.cluster.highlight.background : this.color.cluster.background;
  12195. }
  12196. else {
  12197. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  12198. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  12199. }
  12200. ctx.lineWidth = (this.selected ? 2.0 : 1.0) + (this.clusterSize > 1) ? 2.0 : 0.0;
  12201. ctx.ellipse(this.left, this.top, this.width, this.height);
  12202. ctx.fill();
  12203. ctx.stroke();
  12204. this._label(ctx, this.label, this.x, this.y);
  12205. };
  12206. Node.prototype._drawDot = function (ctx) {
  12207. this._drawShape(ctx, 'circle');
  12208. };
  12209. Node.prototype._drawTriangle = function (ctx) {
  12210. this._drawShape(ctx, 'triangle');
  12211. };
  12212. Node.prototype._drawTriangleDown = function (ctx) {
  12213. this._drawShape(ctx, 'triangleDown');
  12214. };
  12215. Node.prototype._drawSquare = function (ctx) {
  12216. this._drawShape(ctx, 'square');
  12217. };
  12218. Node.prototype._drawStar = function (ctx) {
  12219. this._drawShape(ctx, 'star');
  12220. };
  12221. Node.prototype._resizeShape = function (ctx) {
  12222. if (!this.width) {
  12223. var size = 2 * this.radius;
  12224. this.width = size;
  12225. this.height = size;
  12226. // scaling used for clustering
  12227. this.width += this.clusterSize * this.clusterSizeWidthFactor;
  12228. this.height += this.clusterSize * this.clusterSizeHeightFactor;
  12229. this.radius += this.clusterSize * this.clusterSizeRadiusFactor;
  12230. }
  12231. };
  12232. Node.prototype._drawShape = function (ctx, shape) {
  12233. this._resizeShape(ctx);
  12234. this.left = this.x - this.width / 2;
  12235. this.top = this.y - this.height / 2;
  12236. if (this.clusterSize > 1) {
  12237. ctx.strokeStyle = this.selected ? this.color.cluster.highlight.border : this.color.cluster.border;
  12238. ctx.fillStyle = this.selected ? this.color.cluster.highlight.background : this.color.cluster.background;
  12239. }
  12240. else {
  12241. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  12242. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  12243. }
  12244. ctx.lineWidth = (this.selected ? 2.0 : 1.0) + (this.clusterSize > 1) ? 2.0 : 0.0;
  12245. ctx[shape](this.x, this.y, this.radius);
  12246. ctx.fill();
  12247. ctx.stroke();
  12248. if (this.label) {
  12249. this._label(ctx, this.label, this.x, this.y + this.height / 2, undefined, 'top');
  12250. }
  12251. };
  12252. Node.prototype._resizeText = function (ctx) {
  12253. if (!this.width) {
  12254. var margin = 5;
  12255. var textSize = this.getTextSize(ctx);
  12256. this.width = textSize.width + 2 * margin;
  12257. this.height = textSize.height + 2 * margin;
  12258. // scaling used for clustering
  12259. this.width += this.clusterSize * this.clusterSizeWidthFactor;
  12260. this.height += this.clusterSize * this.clusterSizeHeightFactor;
  12261. this.radius += this.clusterSize * this.clusterSizeRadiusFactor;
  12262. }
  12263. };
  12264. Node.prototype._drawText = function (ctx) {
  12265. this._resizeText(ctx);
  12266. this.left = this.x - this.width / 2;
  12267. this.top = this.y - this.height / 2;
  12268. this._label(ctx, this.label, this.x, this.y);
  12269. };
  12270. Node.prototype._label = function (ctx, text, x, y, align, baseline) {
  12271. if (text) {
  12272. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  12273. ctx.fillStyle = this.fontColor || "black";
  12274. ctx.textAlign = align || "center";
  12275. ctx.textBaseline = baseline || "middle";
  12276. var lines = text.split('\n'),
  12277. lineCount = lines.length,
  12278. fontSize = (this.fontSize + 4),
  12279. yLine = y + (1 - lineCount) / 2 * fontSize;
  12280. for (var i = 0; i < lineCount; i++) {
  12281. ctx.fillText(lines[i], x, yLine);
  12282. yLine += fontSize;
  12283. }
  12284. }
  12285. };
  12286. Node.prototype.getTextSize = function(ctx) {
  12287. if (this.label != undefined) {
  12288. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  12289. var lines = this.label.split('\n'),
  12290. height = (this.fontSize + 4) * lines.length,
  12291. width = 0;
  12292. for (var i = 0, iMax = lines.length; i < iMax; i++) {
  12293. width = Math.max(width, ctx.measureText(lines[i]).width);
  12294. }
  12295. return {"width": width, "height": height};
  12296. }
  12297. else {
  12298. return {"width": 0, "height": 0};
  12299. }
  12300. };
  12301. /**
  12302. * @class Edge
  12303. *
  12304. * A edge connects two nodes
  12305. * @param {Object} properties Object with properties. Must contain
  12306. * At least properties from and to.
  12307. * Available properties: from (number),
  12308. * to (number), label (string, color (string),
  12309. * width (number), style (string),
  12310. * length (number), title (string)
  12311. * @param {Graph} graph A graph object, used to find and edge to
  12312. * nodes.
  12313. * @param {Object} constants An object with default values for
  12314. * example for the color
  12315. */
  12316. function Edge (properties, graph, constants) {
  12317. if (!graph) {
  12318. throw "No graph provided";
  12319. }
  12320. this.graph = graph;
  12321. // initialize constants
  12322. this.widthMin = constants.edges.widthMin;
  12323. this.widthMax = constants.edges.widthMax;
  12324. // initialize variables
  12325. this.id = undefined;
  12326. this.fromId = undefined;
  12327. this.toId = undefined;
  12328. this.style = constants.edges.style;
  12329. this.title = undefined;
  12330. this.width = constants.edges.width;
  12331. this.value = undefined;
  12332. this.length = constants.edges.length;
  12333. this.from = null; // a node
  12334. this.to = null; // a node
  12335. this.connected = false;
  12336. // Added to support dashed lines
  12337. // David Jordan
  12338. // 2012-08-08
  12339. this.dash = util.extend({}, constants.edges.dash); // contains properties length, gap, altLength
  12340. this.stiffness = undefined; // depends on the length of the edge
  12341. this.color = constants.edges.color;
  12342. this.widthFixed = false;
  12343. this.lengthFixed = false;
  12344. this.setProperties(properties, constants);
  12345. };
  12346. /**
  12347. * Set or overwrite properties for the edge
  12348. * @param {Object} properties an object with properties
  12349. * @param {Object} constants and object with default, global properties
  12350. */
  12351. Edge.prototype.setProperties = function(properties, constants) {
  12352. if (!properties) {
  12353. return;
  12354. }
  12355. if (properties.from != undefined) {this.fromId = properties.from;}
  12356. if (properties.to != undefined) {this.toId = properties.to;}
  12357. if (properties.id != undefined) {this.id = properties.id;}
  12358. if (properties.style != undefined) {this.style = properties.style;}
  12359. if (properties.label != undefined) {this.label = properties.label;}
  12360. if (this.label) {
  12361. this.fontSize = constants.edges.fontSize;
  12362. this.fontFace = constants.edges.fontFace;
  12363. this.fontColor = constants.edges.fontColor;
  12364. if (properties.fontColor != undefined) {this.fontColor = properties.fontColor;}
  12365. if (properties.fontSize != undefined) {this.fontSize = properties.fontSize;}
  12366. if (properties.fontFace != undefined) {this.fontFace = properties.fontFace;}
  12367. }
  12368. if (properties.title != undefined) {this.title = properties.title;}
  12369. if (properties.width != undefined) {this.width = properties.width;}
  12370. if (properties.value != undefined) {this.value = properties.value;}
  12371. if (properties.length != undefined) {this.length = properties.length;}
  12372. // Added to support dashed lines
  12373. // David Jordan
  12374. // 2012-08-08
  12375. if (properties.dash) {
  12376. if (properties.dash.length != undefined) {this.dash.length = properties.dash.length;}
  12377. if (properties.dash.gap != undefined) {this.dash.gap = properties.dash.gap;}
  12378. if (properties.dash.altLength != undefined) {this.dash.altLength = properties.dash.altLength;}
  12379. }
  12380. if (properties.color != undefined) {this.color = properties.color;}
  12381. // A node is connected when it has a from and to node.
  12382. this.connect();
  12383. this.widthFixed = this.widthFixed || (properties.width != undefined);
  12384. this.lengthFixed = this.lengthFixed || (properties.length != undefined);
  12385. this.stiffness = 1 / this.length;
  12386. // set draw method based on style
  12387. switch (this.style) {
  12388. case 'line': this.draw = this._drawLine; break;
  12389. case 'arrow': this.draw = this._drawArrow; break;
  12390. case 'arrow-center': this.draw = this._drawArrowCenter; break;
  12391. case 'dash-line': this.draw = this._drawDashLine; break;
  12392. default: this.draw = this._drawLine; break;
  12393. }
  12394. };
  12395. /**
  12396. * Connect an edge to its nodes
  12397. */
  12398. Edge.prototype.connect = function () {
  12399. this.disconnect();
  12400. this.from = this.graph.nodes[this.fromId] || null;
  12401. this.to = this.graph.nodes[this.toId] || null;
  12402. this.connected = (this.from && this.to);
  12403. if (this.connected) {
  12404. this.from.attachEdge(this);
  12405. this.to.attachEdge(this);
  12406. }
  12407. else {
  12408. if (this.from) {
  12409. this.from.detachEdge(this);
  12410. }
  12411. if (this.to) {
  12412. this.to.detachEdge(this);
  12413. }
  12414. }
  12415. };
  12416. /**
  12417. * Disconnect an edge from its nodes
  12418. */
  12419. Edge.prototype.disconnect = function () {
  12420. if (this.from) {
  12421. this.from.detachEdge(this);
  12422. this.from = null;
  12423. }
  12424. if (this.to) {
  12425. this.to.detachEdge(this);
  12426. this.to = null;
  12427. }
  12428. this.connected = false;
  12429. };
  12430. /**
  12431. * get the title of this edge.
  12432. * @return {string} title The title of the edge, or undefined when no title
  12433. * has been set.
  12434. */
  12435. Edge.prototype.getTitle = function() {
  12436. return this.title;
  12437. };
  12438. /**
  12439. * Retrieve the value of the edge. Can be undefined
  12440. * @return {Number} value
  12441. */
  12442. Edge.prototype.getValue = function() {
  12443. return this.value;
  12444. };
  12445. /**
  12446. * Adjust the value range of the edge. The edge will adjust it's width
  12447. * based on its value.
  12448. * @param {Number} min
  12449. * @param {Number} max
  12450. */
  12451. Edge.prototype.setValueRange = function(min, max) {
  12452. if (!this.widthFixed && this.value !== undefined) {
  12453. var scale = (this.widthMax - this.widthMin) / (max - min);
  12454. this.width = (this.value - min) * scale + this.widthMin;
  12455. }
  12456. };
  12457. /**
  12458. * Redraw a edge
  12459. * Draw this edge in the given canvas
  12460. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  12461. * @param {CanvasRenderingContext2D} ctx
  12462. */
  12463. Edge.prototype.draw = function(ctx) {
  12464. throw "Method draw not initialized in edge";
  12465. };
  12466. /**
  12467. * Check if this object is overlapping with the provided object
  12468. * @param {Object} obj an object with parameters left, top
  12469. * @return {boolean} True if location is located on the edge
  12470. */
  12471. Edge.prototype.isOverlappingWith = function(obj) {
  12472. var distMax = 10;
  12473. var xFrom = this.from.x;
  12474. var yFrom = this.from.y;
  12475. var xTo = this.to.x;
  12476. var yTo = this.to.y;
  12477. var xObj = obj.left;
  12478. var yObj = obj.top;
  12479. var dist = Edge._dist(xFrom, yFrom, xTo, yTo, xObj, yObj);
  12480. return (dist < distMax);
  12481. };
  12482. /**
  12483. * Redraw a edge as a line
  12484. * Draw this edge in the given canvas
  12485. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  12486. * @param {CanvasRenderingContext2D} ctx
  12487. * @private
  12488. */
  12489. Edge.prototype._drawLine = function(ctx) {
  12490. // set style
  12491. ctx.strokeStyle = this.color;
  12492. ctx.lineWidth = this._getLineWidth();
  12493. var point;
  12494. if (this.from != this.to) {
  12495. // draw line
  12496. this._line(ctx);
  12497. // draw label
  12498. if (this.label) {
  12499. point = this._pointOnLine(0.5);
  12500. this._label(ctx, this.label, point.x, point.y);
  12501. }
  12502. }
  12503. else {
  12504. var x, y;
  12505. var radius = this.length / 4;
  12506. var node = this.from;
  12507. if (!node.width) {
  12508. node.resize(ctx);
  12509. }
  12510. if (node.width > node.height) {
  12511. x = node.x + node.width / 2;
  12512. y = node.y - radius;
  12513. }
  12514. else {
  12515. x = node.x + radius;
  12516. y = node.y - node.height / 2;
  12517. }
  12518. this._circle(ctx, x, y, radius);
  12519. point = this._pointOnCircle(x, y, radius, 0.5);
  12520. this._label(ctx, this.label, point.x, point.y);
  12521. }
  12522. };
  12523. /**
  12524. * Get the line width of the edge. Depends on width and whether one of the
  12525. * connected nodes is selected.
  12526. * @return {Number} width
  12527. * @private
  12528. */
  12529. Edge.prototype._getLineWidth = function() {
  12530. if (this.from.selected || this.to.selected) {
  12531. return Math.min(this.width * 2, this.widthMax);
  12532. }
  12533. else {
  12534. return this.width;
  12535. }
  12536. };
  12537. /**
  12538. * Draw a line between two nodes
  12539. * @param {CanvasRenderingContext2D} ctx
  12540. * @private
  12541. */
  12542. Edge.prototype._line = function (ctx) {
  12543. // draw a straight line
  12544. ctx.beginPath();
  12545. ctx.moveTo(this.from.x, this.from.y);
  12546. ctx.lineTo(this.to.x, this.to.y);
  12547. ctx.stroke();
  12548. };
  12549. /**
  12550. * Draw a line from a node to itself, a circle
  12551. * @param {CanvasRenderingContext2D} ctx
  12552. * @param {Number} x
  12553. * @param {Number} y
  12554. * @param {Number} radius
  12555. * @private
  12556. */
  12557. Edge.prototype._circle = function (ctx, x, y, radius) {
  12558. // draw a circle
  12559. ctx.beginPath();
  12560. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  12561. ctx.stroke();
  12562. };
  12563. /**
  12564. * Draw label with white background and with the middle at (x, y)
  12565. * @param {CanvasRenderingContext2D} ctx
  12566. * @param {String} text
  12567. * @param {Number} x
  12568. * @param {Number} y
  12569. * @private
  12570. */
  12571. Edge.prototype._label = function (ctx, text, x, y) {
  12572. if (text) {
  12573. // TODO: cache the calculated size
  12574. ctx.font = ((this.from.selected || this.to.selected) ? "bold " : "") +
  12575. this.fontSize + "px " + this.fontFace;
  12576. ctx.fillStyle = 'white';
  12577. var width = ctx.measureText(text).width;
  12578. var height = this.fontSize;
  12579. var left = x - width / 2;
  12580. var top = y - height / 2;
  12581. ctx.fillRect(left, top, width, height);
  12582. // draw text
  12583. ctx.fillStyle = this.fontColor || "black";
  12584. ctx.textAlign = "left";
  12585. ctx.textBaseline = "top";
  12586. ctx.fillText(text, left, top);
  12587. }
  12588. };
  12589. /**
  12590. * Redraw a edge as a dashed line
  12591. * Draw this edge in the given canvas
  12592. * @author David Jordan
  12593. * @date 2012-08-08
  12594. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  12595. * @param {CanvasRenderingContext2D} ctx
  12596. * @private
  12597. */
  12598. Edge.prototype._drawDashLine = function(ctx) {
  12599. // set style
  12600. ctx.strokeStyle = this.color;
  12601. ctx.lineWidth = this._getLineWidth();
  12602. // draw dashed line
  12603. ctx.beginPath();
  12604. ctx.lineCap = 'round';
  12605. if (this.dash.altLength != undefined) //If an alt dash value has been set add to the array this value
  12606. {
  12607. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  12608. [this.dash.length,this.dash.gap,this.dash.altLength,this.dash.gap]);
  12609. }
  12610. 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
  12611. {
  12612. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  12613. [this.dash.length,this.dash.gap]);
  12614. }
  12615. else //If all else fails draw a line
  12616. {
  12617. ctx.moveTo(this.from.x, this.from.y);
  12618. ctx.lineTo(this.to.x, this.to.y);
  12619. }
  12620. ctx.stroke();
  12621. // draw label
  12622. if (this.label) {
  12623. var point = this._pointOnLine(0.5);
  12624. this._label(ctx, this.label, point.x, point.y);
  12625. }
  12626. };
  12627. /**
  12628. * Get a point on a line
  12629. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  12630. * @return {Object} point
  12631. * @private
  12632. */
  12633. Edge.prototype._pointOnLine = function (percentage) {
  12634. return {
  12635. x: (1 - percentage) * this.from.x + percentage * this.to.x,
  12636. y: (1 - percentage) * this.from.y + percentage * this.to.y
  12637. }
  12638. };
  12639. /**
  12640. * Get a point on a circle
  12641. * @param {Number} x
  12642. * @param {Number} y
  12643. * @param {Number} radius
  12644. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  12645. * @return {Object} point
  12646. * @private
  12647. */
  12648. Edge.prototype._pointOnCircle = function (x, y, radius, percentage) {
  12649. var angle = (percentage - 3/8) * 2 * Math.PI;
  12650. return {
  12651. x: x + radius * Math.cos(angle),
  12652. y: y - radius * Math.sin(angle)
  12653. }
  12654. };
  12655. /**
  12656. * Redraw a edge as a line with an arrow halfway the line
  12657. * Draw this edge in the given canvas
  12658. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  12659. * @param {CanvasRenderingContext2D} ctx
  12660. * @private
  12661. */
  12662. Edge.prototype._drawArrowCenter = function(ctx) {
  12663. var point;
  12664. // set style
  12665. ctx.strokeStyle = this.color;
  12666. ctx.fillStyle = this.color;
  12667. ctx.lineWidth = this._getLineWidth();
  12668. if (this.from != this.to) {
  12669. // draw line
  12670. this._line(ctx);
  12671. // draw an arrow halfway the line
  12672. var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  12673. var length = 10 + 5 * this.width; // TODO: make customizable?
  12674. point = this._pointOnLine(0.5);
  12675. ctx.arrow(point.x, point.y, angle, length);
  12676. ctx.fill();
  12677. ctx.stroke();
  12678. // draw label
  12679. if (this.label) {
  12680. point = this._pointOnLine(0.5);
  12681. this._label(ctx, this.label, point.x, point.y);
  12682. }
  12683. }
  12684. else {
  12685. // draw circle
  12686. var x, y;
  12687. var radius = this.length / 4;
  12688. var node = this.from;
  12689. if (!node.width) {
  12690. node.resize(ctx);
  12691. }
  12692. if (node.width > node.height) {
  12693. x = node.x + node.width / 2;
  12694. y = node.y - radius;
  12695. }
  12696. else {
  12697. x = node.x + radius;
  12698. y = node.y - node.height / 2;
  12699. }
  12700. this._circle(ctx, x, y, radius);
  12701. // draw all arrows
  12702. var angle = 0.2 * Math.PI;
  12703. var length = 10 + 5 * this.width; // TODO: make customizable?
  12704. point = this._pointOnCircle(x, y, radius, 0.5);
  12705. ctx.arrow(point.x, point.y, angle, length);
  12706. ctx.fill();
  12707. ctx.stroke();
  12708. // draw label
  12709. if (this.label) {
  12710. point = this._pointOnCircle(x, y, radius, 0.5);
  12711. this._label(ctx, this.label, point.x, point.y);
  12712. }
  12713. }
  12714. };
  12715. /**
  12716. * Redraw a edge as a line with an arrow
  12717. * Draw this edge in the given canvas
  12718. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  12719. * @param {CanvasRenderingContext2D} ctx
  12720. * @private
  12721. */
  12722. Edge.prototype._drawArrow = function(ctx) {
  12723. // set style
  12724. ctx.strokeStyle = this.color;
  12725. ctx.fillStyle = this.color;
  12726. ctx.lineWidth = this._getLineWidth();
  12727. // draw line
  12728. var angle, length;
  12729. if (this.from != this.to) {
  12730. // calculate length and angle of the line
  12731. angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  12732. var dx = (this.to.x - this.from.x);
  12733. var dy = (this.to.y - this.from.y);
  12734. var lEdge = Math.sqrt(dx * dx + dy * dy);
  12735. var lFrom = this.from.distanceToBorder(ctx, angle + Math.PI);
  12736. var pFrom = (lEdge - lFrom) / lEdge;
  12737. var xFrom = (pFrom) * this.from.x + (1 - pFrom) * this.to.x;
  12738. var yFrom = (pFrom) * this.from.y + (1 - pFrom) * this.to.y;
  12739. var lTo = this.to.distanceToBorder(ctx, angle);
  12740. var pTo = (lEdge - lTo) / lEdge;
  12741. var xTo = (1 - pTo) * this.from.x + pTo * this.to.x;
  12742. var yTo = (1 - pTo) * this.from.y + pTo * this.to.y;
  12743. ctx.beginPath();
  12744. ctx.moveTo(xFrom, yFrom);
  12745. ctx.lineTo(xTo, yTo);
  12746. ctx.stroke();
  12747. // draw arrow at the end of the line
  12748. length = 10 + 5 * this.width; // TODO: make customizable?
  12749. ctx.arrow(xTo, yTo, angle, length);
  12750. ctx.fill();
  12751. ctx.stroke();
  12752. // draw label
  12753. if (this.label) {
  12754. var point = this._pointOnLine(0.5);
  12755. this._label(ctx, this.label, point.x, point.y);
  12756. }
  12757. }
  12758. else {
  12759. // draw circle
  12760. var node = this.from;
  12761. var x, y, arrow;
  12762. var radius = this.length / 4;
  12763. if (!node.width) {
  12764. node.resize(ctx);
  12765. }
  12766. if (node.width > node.height) {
  12767. x = node.x + node.width / 2;
  12768. y = node.y - radius;
  12769. arrow = {
  12770. x: x,
  12771. y: node.y,
  12772. angle: 0.9 * Math.PI
  12773. };
  12774. }
  12775. else {
  12776. x = node.x + radius;
  12777. y = node.y - node.height / 2;
  12778. arrow = {
  12779. x: node.x,
  12780. y: y,
  12781. angle: 0.6 * Math.PI
  12782. };
  12783. }
  12784. ctx.beginPath();
  12785. // TODO: do not draw a circle, but an arc
  12786. // TODO: similarly, for a line without arrows, draw to the border of the nodes instead of the center
  12787. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  12788. ctx.stroke();
  12789. // draw all arrows
  12790. length = 10 + 5 * this.width; // TODO: make customizable?
  12791. ctx.arrow(arrow.x, arrow.y, arrow.angle, length);
  12792. ctx.fill();
  12793. ctx.stroke();
  12794. // draw label
  12795. if (this.label) {
  12796. point = this._pointOnCircle(x, y, radius, 0.5);
  12797. this._label(ctx, this.label, point.x, point.y);
  12798. }
  12799. }
  12800. };
  12801. /**
  12802. * Calculate the distance between a point (x3,y3) and a line segment from
  12803. * (x1,y1) to (x2,y2).
  12804. * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
  12805. * @param {number} x1
  12806. * @param {number} y1
  12807. * @param {number} x2
  12808. * @param {number} y2
  12809. * @param {number} x3
  12810. * @param {number} y3
  12811. * @private
  12812. */
  12813. Edge._dist = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is the point
  12814. var px = x2-x1,
  12815. py = y2-y1,
  12816. something = px*px + py*py,
  12817. u = ((x3 - x1) * px + (y3 - y1) * py) / something;
  12818. if (u > 1) {
  12819. u = 1;
  12820. }
  12821. else if (u < 0) {
  12822. u = 0;
  12823. }
  12824. var x = x1 + u * px,
  12825. y = y1 + u * py,
  12826. dx = x - x3,
  12827. dy = y - y3;
  12828. //# Note: If the actual distance does not matter,
  12829. //# if you only want to compare what this function
  12830. //# returns to other results of this function, you
  12831. //# can just return the squared distance instead
  12832. //# (i.e. remove the sqrt) to gain a little performance
  12833. return Math.sqrt(dx*dx + dy*dy);
  12834. };
  12835. /**
  12836. * Popup is a class to create a popup window with some text
  12837. * @param {Element} container The container object.
  12838. * @param {Number} [x]
  12839. * @param {Number} [y]
  12840. * @param {String} [text]
  12841. */
  12842. function Popup(container, x, y, text) {
  12843. if (container) {
  12844. this.container = container;
  12845. }
  12846. else {
  12847. this.container = document.body;
  12848. }
  12849. this.x = 0;
  12850. this.y = 0;
  12851. this.padding = 5;
  12852. if (x !== undefined && y !== undefined ) {
  12853. this.setPosition(x, y);
  12854. }
  12855. if (text !== undefined) {
  12856. this.setText(text);
  12857. }
  12858. // create the frame
  12859. this.frame = document.createElement("div");
  12860. var style = this.frame.style;
  12861. style.position = "absolute";
  12862. style.visibility = "hidden";
  12863. style.border = "1px solid #666";
  12864. style.color = "black";
  12865. style.padding = this.padding + "px";
  12866. style.backgroundColor = "#FFFFC6";
  12867. style.borderRadius = "3px";
  12868. style.MozBorderRadius = "3px";
  12869. style.WebkitBorderRadius = "3px";
  12870. style.boxShadow = "3px 3px 10px rgba(128, 128, 128, 0.5)";
  12871. style.whiteSpace = "nowrap";
  12872. this.container.appendChild(this.frame);
  12873. };
  12874. /**
  12875. * @param {number} x Horizontal position of the popup window
  12876. * @param {number} y Vertical position of the popup window
  12877. */
  12878. Popup.prototype.setPosition = function(x, y) {
  12879. this.x = parseInt(x);
  12880. this.y = parseInt(y);
  12881. };
  12882. /**
  12883. * Set the text for the popup window. This can be HTML code
  12884. * @param {string} text
  12885. */
  12886. Popup.prototype.setText = function(text) {
  12887. this.frame.innerHTML = text;
  12888. };
  12889. /**
  12890. * Show the popup window
  12891. * @param {boolean} show Optional. Show or hide the window
  12892. */
  12893. Popup.prototype.show = function (show) {
  12894. if (show === undefined) {
  12895. show = true;
  12896. }
  12897. if (show) {
  12898. var height = this.frame.clientHeight;
  12899. var width = this.frame.clientWidth;
  12900. var maxHeight = this.frame.parentNode.clientHeight;
  12901. var maxWidth = this.frame.parentNode.clientWidth;
  12902. var top = (this.y - height);
  12903. if (top + height + this.padding > maxHeight) {
  12904. top = maxHeight - height - this.padding;
  12905. }
  12906. if (top < this.padding) {
  12907. top = this.padding;
  12908. }
  12909. var left = this.x;
  12910. if (left + width + this.padding > maxWidth) {
  12911. left = maxWidth - width - this.padding;
  12912. }
  12913. if (left < this.padding) {
  12914. left = this.padding;
  12915. }
  12916. this.frame.style.left = left + "px";
  12917. this.frame.style.top = top + "px";
  12918. this.frame.style.visibility = "visible";
  12919. }
  12920. else {
  12921. this.hide();
  12922. }
  12923. };
  12924. /**
  12925. * Hide the popup window
  12926. */
  12927. Popup.prototype.hide = function () {
  12928. this.frame.style.visibility = "hidden";
  12929. };
  12930. /**
  12931. * @class Groups
  12932. * This class can store groups and properties specific for groups.
  12933. */
  12934. Groups = function () {
  12935. this.clear();
  12936. this.defaultIndex = 0;
  12937. };
  12938. /**
  12939. * default constants for group colors
  12940. */
  12941. Groups.DEFAULT = [
  12942. {border: "#2B7CE9", background: "#97C2FC", highlight: {border: "#2B7CE9", background: "#D2E5FF"}}, // blue
  12943. {border: "#FFA500", background: "#FFFF00", highlight: {border: "#FFA500", background: "#FFFFA3"}}, // yellow
  12944. {border: "#FA0A10", background: "#FB7E81", highlight: {border: "#FA0A10", background: "#FFAFB1"}}, // red
  12945. {border: "#41A906", background: "#7BE141", highlight: {border: "#41A906", background: "#A1EC76"}}, // green
  12946. {border: "#E129F0", background: "#EB7DF4", highlight: {border: "#E129F0", background: "#F0B3F5"}}, // magenta
  12947. {border: "#7C29F0", background: "#AD85E4", highlight: {border: "#7C29F0", background: "#D3BDF0"}}, // purple
  12948. {border: "#C37F00", background: "#FFA807", highlight: {border: "#C37F00", background: "#FFCA66"}}, // orange
  12949. {border: "#4220FB", background: "#6E6EFD", highlight: {border: "#4220FB", background: "#9B9BFD"}}, // darkblue
  12950. {border: "#FD5A77", background: "#FFC0CB", highlight: {border: "#FD5A77", background: "#FFD1D9"}}, // pink
  12951. {border: "#4AD63A", background: "#C2FABC", highlight: {border: "#4AD63A", background: "#E6FFE3"}} // mint
  12952. ];
  12953. /**
  12954. * Clear all groups
  12955. */
  12956. Groups.prototype.clear = function () {
  12957. this.groups = {};
  12958. this.groups.length = function()
  12959. {
  12960. var i = 0;
  12961. for ( var p in this ) {
  12962. if (this.hasOwnProperty(p)) {
  12963. i++;
  12964. }
  12965. }
  12966. return i;
  12967. }
  12968. };
  12969. /**
  12970. * get group properties of a groupname. If groupname is not found, a new group
  12971. * is added.
  12972. * @param {*} groupname Can be a number, string, Date, etc.
  12973. * @return {Object} group The created group, containing all group properties
  12974. */
  12975. Groups.prototype.get = function (groupname) {
  12976. var group = this.groups[groupname];
  12977. if (group == undefined) {
  12978. // create new group
  12979. var index = this.defaultIndex % Groups.DEFAULT.length;
  12980. this.defaultIndex++;
  12981. group = {};
  12982. group.color = Groups.DEFAULT[index];
  12983. this.groups[groupname] = group;
  12984. }
  12985. return group;
  12986. };
  12987. /**
  12988. * Add a custom group style
  12989. * @param {String} groupname
  12990. * @param {Object} style An object containing borderColor,
  12991. * backgroundColor, etc.
  12992. * @return {Object} group The created group object
  12993. */
  12994. Groups.prototype.add = function (groupname, style) {
  12995. this.groups[groupname] = style;
  12996. if (style.color) {
  12997. style.color = Node.parseColor(style.color);
  12998. }
  12999. return style;
  13000. };
  13001. /**
  13002. * @class Images
  13003. * This class loads images and keeps them stored.
  13004. */
  13005. Images = function () {
  13006. this.images = {};
  13007. this.callback = undefined;
  13008. };
  13009. /**
  13010. * Set an onload callback function. This will be called each time an image
  13011. * is loaded
  13012. * @param {function} callback
  13013. */
  13014. Images.prototype.setOnloadCallback = function(callback) {
  13015. this.callback = callback;
  13016. };
  13017. /**
  13018. *
  13019. * @param {string} url Url of the image
  13020. * @return {Image} img The image object
  13021. */
  13022. Images.prototype.load = function(url) {
  13023. var img = this.images[url];
  13024. if (img == undefined) {
  13025. // create the image
  13026. var images = this;
  13027. img = new Image();
  13028. this.images[url] = img;
  13029. img.onload = function() {
  13030. if (images.callback) {
  13031. images.callback(this);
  13032. }
  13033. };
  13034. img.src = url;
  13035. }
  13036. return img;
  13037. };
  13038. /**
  13039. * @constructor Cluster
  13040. * Contains the cluster properties for the graph object
  13041. */
  13042. function Cluster() {
  13043. this.clusterSession = 0;
  13044. }
  13045. /**
  13046. * This function can be called to increase the cluster level. This means that the nodes with only one edge connection will
  13047. * be clustered with their connected node. This can be repeated as many times as needed.
  13048. * This can be called externally (by a keybind for instance) to reduce the complexity of big datasets.
  13049. */
  13050. Cluster.prototype.increaseClusterLevel = function() {
  13051. var isMovingBeforeClustering = this.moving;
  13052. this._formClusters(true);
  13053. this._updateLabels();
  13054. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  13055. if (this.moving != isMovingBeforeClustering) {
  13056. this.start();
  13057. }
  13058. };
  13059. /**
  13060. * This function can be called to decrease the cluster level. This means that the nodes with only one edge connection will
  13061. * be unpacked if they are a cluster. This can be repeated as many times as needed.
  13062. * This can be called externally (by a key-bind for instance) to look into clusters without zooming.
  13063. */
  13064. Cluster.prototype.decreaseClusterLevel = function() {
  13065. var isMovingBeforeClustering = this.moving;
  13066. for (var i = 0; i < this.nodeIndices.length; i++) {
  13067. var node = this.nodes[this.nodeIndices[i]];
  13068. if (node.clusterSize > 1) {
  13069. this._expandClusterNode(node,false,true);
  13070. }
  13071. }
  13072. this._updateNodeIndexList();
  13073. this._updateLabels();
  13074. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  13075. if (this.moving != isMovingBeforeClustering) {
  13076. this.start();
  13077. }
  13078. this.clusterSession = (this.clusterSession == 0) ? 0 : this.clusterSession - 1;
  13079. };
  13080. /**
  13081. * This function can be called to open up a specific cluster.
  13082. * It will recursively unpack the entire cluster back to individual nodes.
  13083. *
  13084. * @param node | Node object: cluster to open.
  13085. */
  13086. Cluster.prototype.fullyOpenCluster = function(node) {
  13087. var isMovingBeforeClustering = this.moving;
  13088. this._expandClusterNode(node,true,true);
  13089. this._updateNodeIndexList();
  13090. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  13091. if (this.moving != isMovingBeforeClustering) {
  13092. this.start();
  13093. }
  13094. };
  13095. /**
  13096. * This function can be called to open up a specific cluster.
  13097. * It will unpack the cluster back one level.
  13098. *
  13099. * @param node | Node object: cluster to open.
  13100. */
  13101. Cluster.prototype.openCluster = function(node) {
  13102. var isMovingBeforeClustering = this.moving;
  13103. this._expandClusterNode(node,false,true);
  13104. this._updateNodeIndexList();
  13105. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  13106. if (this.moving != isMovingBeforeClustering) {
  13107. this.start();
  13108. }
  13109. };
  13110. /**
  13111. * This function checks if the zoom action is in or out.
  13112. * If out, check if we can form clusters, if in, check if we can open clusters.
  13113. * This function is only called from _zoom()
  13114. *
  13115. * @private
  13116. */
  13117. Cluster.prototype._updateClusters = function() {
  13118. var isMovingBeforeClustering = this.moving;
  13119. if (this.previousScale > this.scale) { // zoom out
  13120. this._formClusters(false);
  13121. }
  13122. else if (this.previousScale < this.scale) { // zoom out
  13123. this._openClusters();
  13124. }
  13125. this._updateClusterLabels();
  13126. this._updateNodeLabels();
  13127. this._updateLabels();
  13128. this.previousScale = this.scale;
  13129. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  13130. if (this.moving != isMovingBeforeClustering) {
  13131. this.start();
  13132. }
  13133. };
  13134. /**
  13135. * This updates the node labels for all nodes (for debugging purposes)
  13136. * @private
  13137. */
  13138. Cluster.prototype._updateLabels = function() {
  13139. // update node labels
  13140. for (var nodeID in this.nodes) {
  13141. if (this.nodes.hasOwnProperty(nodeID)) {
  13142. var node = this.nodes[nodeID];
  13143. node.label = String(node.remainingEdges).concat(":",node.remainingEdges_unapplied,":",String(node.clusterSize));
  13144. }
  13145. }
  13146. };
  13147. /**
  13148. * This updates the node labels for all clusters
  13149. * @private
  13150. */
  13151. Cluster.prototype._updateClusterLabels = function() {
  13152. // update node labels
  13153. for (var nodeID in this.nodes) {
  13154. if (this.nodes.hasOwnProperty(nodeID)) {
  13155. var node = this.nodes[nodeID];
  13156. if (node.clusterSize > 1) {
  13157. node.label = "[".concat(String(node.clusterSize),"]");
  13158. }
  13159. }
  13160. }
  13161. };
  13162. /**
  13163. * This updates the node labels for all nodes that are NOT clusters
  13164. * @private
  13165. */
  13166. Cluster.prototype._updateNodeLabels = function() {
  13167. // update node labels
  13168. for (var nodeID in this.nodes) {
  13169. var node = this.nodes[nodeID];
  13170. if (node.clusterSize == 1) {
  13171. node.label = String(node.id);
  13172. }
  13173. }
  13174. };
  13175. /**
  13176. * This function loops over all nodes in the nodeIndices list. For each node it checks if it is a cluster and if it
  13177. * has to be opened based on the current zoom level.
  13178. *
  13179. * @private
  13180. */
  13181. Cluster.prototype._openClusters = function() {
  13182. var amountOfNodes = this.nodeIndices.length;
  13183. for (var i = 0; i < this.nodeIndices.length; i++) {
  13184. var node = this.nodes[this.nodeIndices[i]];
  13185. this._expandClusterNode(node,true,false);
  13186. }
  13187. this._updateNodeIndexList();
  13188. if (this.nodeIndices.length != amountOfNodes) { // this means a clustering operation has taken place
  13189. this.clusterSession -= 1;
  13190. }
  13191. };
  13192. /**
  13193. * This function checks if a node has to be opened. This is done by checking the zoom level.
  13194. * If the node contains child nodes, this function is recursively called on the child nodes as well.
  13195. * This recursive behaviour is optional and can be set by the recursive argument.
  13196. *
  13197. * @param parentNode | Node object: to check for cluster and expand
  13198. * @param recursive | Boolean: enable or disable recursive calling
  13199. * @param forceExpand | Boolean: enable or disable forcing the last node to join the cluster to be expelled
  13200. * @private
  13201. */
  13202. Cluster.prototype._expandClusterNode = function(parentNode, recursive, forceExpand) {
  13203. // first check if node is a cluster
  13204. if (parentNode.clusterSize > 1) {
  13205. // if the last child has been added on a smaller scale than current scale (@optimization)
  13206. if (parentNode.formationScale < this.scale || forceExpand == true) {
  13207. // we will check if any of the contained child nodes should be removed from the cluster
  13208. for (var containedNodeID in parentNode.containedNodes) {
  13209. if (parentNode.containedNodes.hasOwnProperty(containedNodeID)) {
  13210. var childNode = parentNode.containedNodes[containedNodeID];
  13211. // force expand will expand the largest cluster size clusters. Since we cluster from outside in, we assume that
  13212. // the largest cluster is the one that comes from outside
  13213. if (forceExpand == true) {
  13214. if (childNode.clusterSession == this.clusterSession - 1) {
  13215. this._expelChildFromParent(parentNode,containedNodeID,recursive,forceExpand);
  13216. }
  13217. }
  13218. else {
  13219. this._expelChildFromParent(parentNode,containedNodeID,recursive,forceExpand);
  13220. }
  13221. }
  13222. }
  13223. }
  13224. }
  13225. };
  13226. /**
  13227. * This function will expel a child_node from a parent_node. This is to de-cluster the node. This function will remove
  13228. * the child node from the parent contained_node object and put it back into the global nodes object.
  13229. * The same holds for the edge that was connected to the child node. It is moved back into the global edges object.
  13230. *
  13231. * @param parentNode | Node object: the parent node
  13232. * @param containedNodeID | String: child_node id as it is contained in the containedNodes object of the parent node
  13233. * @param recursive | Boolean: This will also check if the child needs to be expanded.
  13234. * With force and recursive both true, the entire cluster is unpacked
  13235. * @param forceExpand | Boolean: This will disregard the zoom level and will expel this child from the parent
  13236. * @private
  13237. */
  13238. Cluster.prototype._expelChildFromParent = function(parentNode, containedNodeID, recursive, forceExpand) {
  13239. var childNode = parentNode.containedNodes[containedNodeID];
  13240. // if child node has been added on smaller scale than current, kick out
  13241. if (childNode.formationScale < this.scale || forceExpand == true) {
  13242. // put the child node back in the global nodes object and the corresponding edge in the global edges object
  13243. this.nodes[containedNodeID] = childNode;
  13244. this.edges[parentNode.containedEdges[containedNodeID].id] = parentNode.containedEdges[containedNodeID];
  13245. // undo the changes from the clustering operation on the parent node
  13246. parentNode.mass -= this.constants.clustering.massTransferCoefficient * childNode.mass;
  13247. parentNode.fontSize -= this.constants.clustering.fontSizeMultiplier * childNode.clusterSize;
  13248. parentNode.clusterSize -= childNode.clusterSize;
  13249. parentNode.remainingEdges += 1;
  13250. parentNode.remainingEdges_unapplied = parentNode.remainingEdges;
  13251. // place the child node near the parent, not at the exact same location to avoid chaos in the system
  13252. childNode.x = parentNode.x;
  13253. childNode.y = parentNode.y;
  13254. // remove the clusterSession from the child node
  13255. childNode.clusterSession = 0;
  13256. // remove node from the list
  13257. delete parentNode.containedNodes[containedNodeID];
  13258. delete parentNode.containedEdges[containedNodeID];
  13259. // restart the simulation to reorganise all nodes
  13260. this.moving = true;
  13261. // recalculate the size of the node on the next time the node is rendered
  13262. parentNode.clearSizeCache();
  13263. }
  13264. // check if a further expansion step is possible if recursivity is enabled
  13265. if (recursive == true) {
  13266. this._expandClusterNode(childNode,recursive,forceExpand);
  13267. }
  13268. };
  13269. /**
  13270. * This function checks if any nodes at the end of their trees have edges below a threshold length
  13271. * This function is called only from _updateClusters()
  13272. * forceLevelCollapse ignores the length of the edge and collapses one level
  13273. * This means that a node with only one edge will be clustered with its connected node
  13274. *
  13275. * @private
  13276. * @param force_level_collapse | Boolean
  13277. */
  13278. Cluster.prototype._formClusters = function(forceLevelCollapse) {
  13279. var amountOfNodes = this.nodeIndices.length;
  13280. var min_length = this.constants.clustering.clusterLength/this.scale;
  13281. var dx,dy,length,
  13282. edges = this.edges;
  13283. // create an array of edge ids
  13284. var edgesIDarray = []
  13285. for (var id in edges) {
  13286. if (edges.hasOwnProperty(id)) {
  13287. edgesIDarray.push(id);
  13288. }
  13289. }
  13290. // check if any edges are shorter than min_length and start the clustering
  13291. // the clustering favours the node with the larger mass
  13292. for (var i = 0; i < edgesIDarray.length; i++) {
  13293. var edgeID = edgesIDarray[i];
  13294. var edge = edges[edgeID];
  13295. edge.id = edgeID;
  13296. if (edge.connected) {
  13297. dx = (edge.to.x - edge.from.x);
  13298. dy = (edge.to.y - edge.from.y);
  13299. length = Math.sqrt(dx * dx + dy * dy);
  13300. if (length < min_length || forceLevelCollapse == true) {
  13301. // checking for clustering possibilities
  13302. // first check which node is larger
  13303. var parentNode = edge.from
  13304. var childNode = edge.to
  13305. if (edge.to.mass > edge.from.mass) {
  13306. parentNode = edge.to
  13307. childNode = edge.from
  13308. }
  13309. // we allow clustering from outside in, ideally the child node in on the outside
  13310. // if we do not cluster from outside in, we would have to reconnect edges or keep a second set of edges for the
  13311. // clusters. This will also have to be altered in the force calculation and rendering.
  13312. // This method is non-destructive and does not require a second set of data.
  13313. if (childNode.remainingEdges == 1 && childNode.remainingEdges_unapplied != 0) {
  13314. this._addToCluster(parentNode,childNode,edge,forceLevelCollapse);
  13315. delete this.edges[edgesIDarray[i]];
  13316. }
  13317. else if (parentNode.remainingEdges == 1 && parentNode.remainingEdges_unapplied != 0) {
  13318. this._addToCluster(childNode,parentNode,edge,forceLevelCollapse);
  13319. delete this.edges[edgesIDarray[i]];
  13320. }
  13321. }
  13322. }
  13323. }
  13324. this._updateNodeIndexList();
  13325. if (forceLevelCollapse == true) {
  13326. this._applyClusterLevel();
  13327. }
  13328. if (this.nodeIndices.length != amountOfNodes) { // this means a clustering operation has taken place
  13329. this.clusterSession += 1;
  13330. }
  13331. console.log(this.clusterSession)
  13332. };
  13333. /**
  13334. * This function adds the child node to the parent node, creating a cluster if it is not already.
  13335. * This function is called only from _updateClusters()
  13336. *
  13337. * @param parent_node | Node object: this is the node that will house the child node
  13338. * @param child_node | Node object: this node will be deleted from the global this.nodes and stored in the parent node
  13339. * @param edge | Edge object: this edge will be deleted from the global this.edges and stored in the parent node
  13340. * @param force_level_collapse | Boolean: true will only update the remainingEdges at the very end of the clustering, ensuring single level collapse
  13341. * @private
  13342. */
  13343. Cluster.prototype._addToCluster = function(parentNode, childNode, edge, forceLevelCollapse) {
  13344. // join child node and edge in parent node
  13345. parentNode.containedNodes[childNode.id] = childNode;
  13346. parentNode.containedEdges[childNode.id] = edge; // the edge gets the node ID so we can easily recover it when expanding the cluster
  13347. if (this.nodes.hasOwnProperty(childNode.id)) {
  13348. delete this.nodes[childNode.id];
  13349. }
  13350. childNode.clusterSession = this.clusterSession;
  13351. parentNode.mass += this.constants.clustering.massTransferCoefficient * childNode.mass;
  13352. parentNode.clusterSize += childNode.clusterSize;
  13353. parentNode.fontSize += this.constants.clustering.fontSizeMultiplier * childNode.clusterSize;
  13354. parentNode.formationScale = this.scale; // The latest child has been added on this scale
  13355. // recalculate the size of the node on the next time the node is rendered
  13356. parentNode.clearSizeCache();
  13357. parentNode.containedNodes[childNode.id].formationScale = this.scale; // this child has been added at this scale.
  13358. if (forceLevelCollapse == true) {
  13359. parentNode.remainingEdges_unapplied -= 1;
  13360. }
  13361. else {
  13362. parentNode.remainingEdges -= 1;
  13363. }
  13364. // restart the simulation to reorganise all nodes
  13365. this.moving = true;
  13366. };
  13367. /**
  13368. * This function will apply the changes made to the remainingEdges during the formation of the clusters.
  13369. * This is a seperate function to allow for level-wise collapsing of the node tree.
  13370. * It has to be called if a level is collapsed. It is called by _formClusters().
  13371. * @private
  13372. */
  13373. Cluster.prototype._applyClusterLevel = function() {
  13374. for (var i = 0; i < this.nodeIndices.length; i++) {
  13375. var node = this.nodes[this.nodeIndices[i]];
  13376. node.remainingEdges = node.remainingEdges_unapplied;
  13377. }
  13378. };
  13379. /**
  13380. * @constructor Graph
  13381. * Create a graph visualization, displaying nodes and edges.
  13382. *
  13383. * @param {Element} container The DOM element in which the Graph will
  13384. * be created. Normally a div element.
  13385. * @param {Object} data An object containing parameters
  13386. * {Array} nodes
  13387. * {Array} edges
  13388. * @param {Object} options Options
  13389. */
  13390. function Graph (container, data, options) {
  13391. // create variables and set default values
  13392. this.containerElement = container;
  13393. this.width = '100%';
  13394. this.height = '100%';
  13395. this.refreshRate = 50; // milliseconds
  13396. this.stabilize = true; // stabilize before displaying the graph
  13397. this.selectable = true;
  13398. // set constant values
  13399. this.constants = {
  13400. nodes: {
  13401. radiusMin: 5,
  13402. radiusMax: 20,
  13403. radius: 5,
  13404. distance: 100, // px
  13405. shape: 'ellipse',
  13406. image: undefined,
  13407. widthMin: 16, // px
  13408. widthMax: 64, // px
  13409. fontColor: 'black',
  13410. fontSize: 14, // px
  13411. //fontFace: verdana,
  13412. fontFace: 'arial',
  13413. color: {
  13414. border: '#2B7CE9',
  13415. background: '#97C2FC',
  13416. highlight: {
  13417. border: '#2B7CE9',
  13418. background: '#D2E5FF'
  13419. },
  13420. cluster: {
  13421. border: '#256a2d',
  13422. background: '#2cd140',
  13423. highlight: {
  13424. border: '#899539',
  13425. background: '#c5dc29'
  13426. }
  13427. }
  13428. },
  13429. borderColor: '#2B7CE9',
  13430. backgroundColor: '#97C2FC',
  13431. highlightColor: '#D2E5FF',
  13432. group: undefined
  13433. },
  13434. edges: {
  13435. widthMin: 1,
  13436. widthMax: 15,
  13437. width: 1,
  13438. style: 'line',
  13439. color: '#343434',
  13440. fontColor: '#343434',
  13441. fontSize: 14, // px
  13442. fontFace: 'arial',
  13443. //distance: 100, //px
  13444. length: 100, // px
  13445. dash: {
  13446. length: 10,
  13447. gap: 5,
  13448. altLength: undefined
  13449. }
  13450. },
  13451. clustering: {
  13452. clusterLength: 30, // threshold edge length for clustering
  13453. fontSizeMultiplier: 2, // how much the cluster font size grows per node (in px)
  13454. forceAmplification: 0.6, // amount of clusterSize between two nodes multiply this value (+1) with the repulsion force
  13455. distanceAmplification: 0.1, // amount of clusterSize between two nodes multiply this value (+1) with the repulsion force
  13456. edgeGrowth: 10, // amount of clusterSize connected to the edge is multiplied with this and added to edgeLength
  13457. clusterSizeWidthFactor: 10,
  13458. clusterSizeHeightFactor: 10,
  13459. clusterSizeRadiusFactor: 10,
  13460. massTransferCoefficient: 0.2 // parent.mass += massTransferCoefficient * child.mass
  13461. },
  13462. minForce: 0.05,
  13463. minVelocity: 0.02, // px/s
  13464. maxIterations: 1000 // maximum number of iteration to stabilize
  13465. };
  13466. Cluster.call(this);
  13467. var graph = this;
  13468. this.nodeIndices = []; // the node indices list is used to speed up the computation of the repulsion fields
  13469. this.nodes = {}; // object with Node objects
  13470. this.edges = {}; // object with Edge objects
  13471. this.scale = 1; // defining the global scale variable in the constructor
  13472. this.previousScale = this.scale; // this is used to check if the zoom operation is zooming in or out
  13473. // TODO: create a counter to keep track on the number of nodes having values
  13474. // TODO: create a counter to keep track on the number of nodes currently moving
  13475. // TODO: create a counter to keep track on the number of edges having values
  13476. this.nodesData = null; // A DataSet or DataView
  13477. this.edgesData = null; // A DataSet or DataView
  13478. // create event listeners used to subscribe on the DataSets of the nodes and edges
  13479. var me = this;
  13480. this.nodesListeners = {
  13481. 'add': function (event, params) {
  13482. me._addNodes(params.items);
  13483. me.start();
  13484. },
  13485. 'update': function (event, params) {
  13486. me._updateNodes(params.items);
  13487. me.start();
  13488. },
  13489. 'remove': function (event, params) {
  13490. me._removeNodes(params.items);
  13491. me.start();
  13492. }
  13493. };
  13494. this.edgesListeners = {
  13495. 'add': function (event, params) {
  13496. me._addEdges(params.items);
  13497. me.start();
  13498. },
  13499. 'update': function (event, params) {
  13500. me._updateEdges(params.items);
  13501. me.start();
  13502. },
  13503. 'remove': function (event, params) {
  13504. me._removeEdges(params.items);
  13505. me.start();
  13506. }
  13507. };
  13508. this.groups = new Groups(); // object with groups
  13509. this.images = new Images(); // object with images
  13510. this.images.setOnloadCallback(function () {
  13511. graph._redraw();
  13512. });
  13513. // properties of the data
  13514. this.moving = false; // True if any of the nodes have an undefined position
  13515. this.selection = [];
  13516. this.timer = undefined;
  13517. // create a frame and canvas
  13518. this._create();
  13519. // apply options
  13520. this.setOptions(options);
  13521. // draw data
  13522. this.setData(data);
  13523. // zoom so all data will fit on the screen
  13524. this.zoomToFit();
  13525. // cluster if the data set is big
  13526. this.clusterToFit();
  13527. }
  13528. Graph.prototype = Object.create(Cluster.prototype);
  13529. Graph.prototype.clusterToFit = function() {
  13530. var numberOfNodes = this.nodeIndices.length;
  13531. var maxNumberOfNodes = 100;
  13532. var maxLevels = 10;
  13533. var level = 0;
  13534. while (numberOfNodes >= maxNumberOfNodes && level < maxLevels) {
  13535. this.increaseClusterLevel();
  13536. numberOfNodes = this.nodeIndices.length;
  13537. level += 1;
  13538. }
  13539. };
  13540. Graph.prototype.zoomToFit = function() {
  13541. var numberOfNodes = this.nodeIndices.length;
  13542. var zoomLevel = 105 / (numberOfNodes + 80); // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  13543. if (zoomLevel > 1.0) {
  13544. zoomLevel = 1.0;
  13545. }
  13546. if (!('mousewheelScale' in this.pinch)) {
  13547. this.pinch.mousewheelScale = zoomLevel;
  13548. }
  13549. this._setScale(zoomLevel);
  13550. };
  13551. /**
  13552. * Update the this.nodeIndices with the most recent node index list
  13553. * @private
  13554. */
  13555. Graph.prototype._updateNodeIndexList = function() {
  13556. this.nodeIndices = [];
  13557. for (var idx in this.nodes) {
  13558. if (this.nodes.hasOwnProperty(idx)) {
  13559. this.nodeIndices.push(idx);
  13560. }
  13561. }
  13562. };
  13563. /**
  13564. * Set nodes and edges, and optionally options as well.
  13565. *
  13566. * @param {Object} data Object containing parameters:
  13567. * {Array | DataSet | DataView} [nodes] Array with nodes
  13568. * {Array | DataSet | DataView} [edges] Array with edges
  13569. * {String} [dot] String containing data in DOT format
  13570. * {Options} [options] Object with options
  13571. */
  13572. Graph.prototype.setData = function(data) {
  13573. if (data && data.dot && (data.nodes || data.edges)) {
  13574. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  13575. ' parameter pair "nodes" and "edges", but not both.');
  13576. }
  13577. // set options
  13578. this.setOptions(data && data.options);
  13579. // set all data
  13580. if (data && data.dot) {
  13581. // parse DOT file
  13582. if(data && data.dot) {
  13583. var dotData = vis.util.DOTToGraph(data.dot);
  13584. this.setData(dotData);
  13585. return;
  13586. }
  13587. }
  13588. else {
  13589. this._setNodes(data && data.nodes);
  13590. this._setEdges(data && data.edges);
  13591. }
  13592. // updating the list of node indices
  13593. // find a stable position or start animating to a stable position
  13594. if (this.stabilize) {
  13595. this._doStabilize();
  13596. }
  13597. this.start();
  13598. };
  13599. /**
  13600. * Set options
  13601. * @param {Object} options
  13602. */
  13603. Graph.prototype.setOptions = function (options) {
  13604. if (options) {
  13605. // retrieve parameter values
  13606. if (options.width != undefined) {this.width = options.width;}
  13607. if (options.height != undefined) {this.height = options.height;}
  13608. if (options.stabilize != undefined) {this.stabilize = options.stabilize;}
  13609. if (options.selectable != undefined) {this.selectable = options.selectable;}
  13610. // TODO: work out these options and document them
  13611. if (options.edges) {
  13612. for (var prop in options.edges) {
  13613. if (options.edges.hasOwnProperty(prop)) {
  13614. this.constants.edges[prop] = options.edges[prop];
  13615. }
  13616. }
  13617. if (options.edges.length != undefined &&
  13618. options.nodes && options.nodes.distance == undefined) {
  13619. this.constants.edges.length = options.edges.length;
  13620. this.constants.nodes.distance = options.edges.length * 1.25;
  13621. }
  13622. if (!options.edges.fontColor) {
  13623. this.constants.edges.fontColor = options.edges.color;
  13624. }
  13625. // Added to support dashed lines
  13626. // David Jordan
  13627. // 2012-08-08
  13628. if (options.edges.dash) {
  13629. if (options.edges.dash.length != undefined) {
  13630. this.constants.edges.dash.length = options.edges.dash.length;
  13631. }
  13632. if (options.edges.dash.gap != undefined) {
  13633. this.constants.edges.dash.gap = options.edges.dash.gap;
  13634. }
  13635. if (options.edges.dash.altLength != undefined) {
  13636. this.constants.edges.dash.altLength = options.edges.dash.altLength;
  13637. }
  13638. }
  13639. }
  13640. if (options.nodes) {
  13641. for (prop in options.nodes) {
  13642. if (options.nodes.hasOwnProperty(prop)) {
  13643. this.constants.nodes[prop] = options.nodes[prop];
  13644. }
  13645. }
  13646. if (options.nodes.color) {
  13647. this.constants.nodes.color = Node.parseColor(options.nodes.color);
  13648. }
  13649. /*
  13650. if (options.nodes.widthMin) this.constants.nodes.radiusMin = options.nodes.widthMin;
  13651. if (options.nodes.widthMax) this.constants.nodes.radiusMax = options.nodes.widthMax;
  13652. */
  13653. }
  13654. if (options.groups) {
  13655. for (var groupname in options.groups) {
  13656. if (options.groups.hasOwnProperty(groupname)) {
  13657. var group = options.groups[groupname];
  13658. this.groups.add(groupname, group);
  13659. }
  13660. }
  13661. }
  13662. }
  13663. this.setSize(this.width, this.height);
  13664. this._setTranslation(this.frame.clientWidth / 2, this.frame.clientHeight / 2);
  13665. this._setScale(1);
  13666. };
  13667. /**
  13668. * fire an event
  13669. * @param {String} event The name of an event, for example 'select'
  13670. * @param {Object} params Optional object with event parameters
  13671. * @private
  13672. */
  13673. Graph.prototype._trigger = function (event, params) {
  13674. events.trigger(this, event, params);
  13675. };
  13676. /**
  13677. * Create the main frame for the Graph.
  13678. * This function is executed once when a Graph object is created. The frame
  13679. * contains a canvas, and this canvas contains all objects like the axis and
  13680. * nodes.
  13681. * @private
  13682. */
  13683. Graph.prototype._create = function () {
  13684. // remove all elements from the container element.
  13685. while (this.containerElement.hasChildNodes()) {
  13686. this.containerElement.removeChild(this.containerElement.firstChild);
  13687. }
  13688. this.frame = document.createElement('div');
  13689. this.frame.className = 'graph-frame';
  13690. this.frame.style.position = 'relative';
  13691. this.frame.style.overflow = 'hidden';
  13692. // create the graph canvas (HTML canvas element)
  13693. this.frame.canvas = document.createElement( 'canvas' );
  13694. this.frame.canvas.style.position = 'relative';
  13695. this.frame.appendChild(this.frame.canvas);
  13696. if (!this.frame.canvas.getContext) {
  13697. var noCanvas = document.createElement( 'DIV' );
  13698. noCanvas.style.color = 'red';
  13699. noCanvas.style.fontWeight = 'bold' ;
  13700. noCanvas.style.padding = '10px';
  13701. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  13702. this.frame.canvas.appendChild(noCanvas);
  13703. }
  13704. var me = this;
  13705. this.drag = {};
  13706. this.pinch = {};
  13707. this.hammer = Hammer(this.frame.canvas, {
  13708. prevent_default: true
  13709. });
  13710. this.hammer.on('tap', me._onTap.bind(me) );
  13711. this.hammer.on('hold', me._onHold.bind(me) );
  13712. this.hammer.on('pinch', me._onPinch.bind(me) );
  13713. this.hammer.on('touch', me._onTouch.bind(me) );
  13714. this.hammer.on('dragstart', me._onDragStart.bind(me) );
  13715. this.hammer.on('drag', me._onDrag.bind(me) );
  13716. this.hammer.on('dragend', me._onDragEnd.bind(me) );
  13717. this.hammer.on('mousewheel',me._onMouseWheel.bind(me) );
  13718. this.hammer.on('DOMMouseScroll',me._onMouseWheel.bind(me) ); // for FF
  13719. this.hammer.on('mousemove', me._onMouseMoveTitle.bind(me) );
  13720. this.mouseTrap = mouseTrap;
  13721. this.mouseTrap.bind("=", this.decreaseClusterLevel.bind(me));
  13722. this.mouseTrap.bind("-",this.increaseClusterLevel.bind(me));
  13723. // add the frame to the container element
  13724. this.containerElement.appendChild(this.frame);
  13725. };
  13726. /**
  13727. *
  13728. * @param {{x: Number, y: Number}} pointer
  13729. * @return {Number | null} node
  13730. * @private
  13731. */
  13732. Graph.prototype._getNodeAt = function (pointer) {
  13733. var x = this._canvasToX(pointer.x);
  13734. var y = this._canvasToY(pointer.y);
  13735. var obj = {
  13736. left: x,
  13737. top: y,
  13738. right: x,
  13739. bottom: y
  13740. };
  13741. // if there are overlapping nodes, select the last one, this is the
  13742. // one which is drawn on top of the others
  13743. var overlappingNodes = this._getNodesOverlappingWith(obj);
  13744. return (overlappingNodes.length > 0) ?
  13745. overlappingNodes[overlappingNodes.length - 1] : null;
  13746. };
  13747. /**
  13748. * Get the pointer location from a touch location
  13749. * @param {{pageX: Number, pageY: Number}} touch
  13750. * @return {{x: Number, y: Number}} pointer
  13751. * @private
  13752. */
  13753. Graph.prototype._getPointer = function (touch) {
  13754. return {
  13755. x: touch.pageX - vis.util.getAbsoluteLeft(this.frame.canvas),
  13756. y: touch.pageY - vis.util.getAbsoluteTop(this.frame.canvas)
  13757. };
  13758. };
  13759. /**
  13760. * On start of a touch gesture, store the pointer
  13761. * @param event
  13762. * @private
  13763. */
  13764. Graph.prototype._onTouch = function (event) {
  13765. this.drag.pointer = this._getPointer(event.gesture.touches[0]);
  13766. this.drag.pinched = false;
  13767. this.pinch.scale = this._getScale();
  13768. };
  13769. /**
  13770. * handle drag start event
  13771. * @private
  13772. */
  13773. Graph.prototype._onDragStart = function () {
  13774. var drag = this.drag;
  13775. drag.selection = [];
  13776. drag.translation = this._getTranslation();
  13777. drag.nodeId = this._getNodeAt(drag.pointer);
  13778. // note: drag.pointer is set in _onTouch to get the initial touch location
  13779. var node = this.nodes[drag.nodeId];
  13780. if (node) {
  13781. // select the clicked node if not yet selected
  13782. if (!node.isSelected()) {
  13783. this._selectNodes([drag.nodeId]);
  13784. }
  13785. // create an array with the selected nodes and their original location and status
  13786. var me = this;
  13787. this.selection.forEach(function (id) {
  13788. var node = me.nodes[id];
  13789. if (node) {
  13790. var s = {
  13791. id: id,
  13792. node: node,
  13793. // store original x, y, xFixed and yFixed, make the node temporarily Fixed
  13794. x: node.x,
  13795. y: node.y,
  13796. xFixed: node.xFixed,
  13797. yFixed: node.yFixed
  13798. };
  13799. node.xFixed = true;
  13800. node.yFixed = true;
  13801. drag.selection.push(s);
  13802. }
  13803. });
  13804. }
  13805. };
  13806. /**
  13807. * handle drag event
  13808. * @private
  13809. */
  13810. Graph.prototype._onDrag = function (event) {
  13811. if (this.drag.pinched) {
  13812. return;
  13813. }
  13814. var pointer = this._getPointer(event.gesture.touches[0]);
  13815. var me = this,
  13816. drag = this.drag,
  13817. selection = drag.selection;
  13818. if (selection && selection.length) {
  13819. // calculate delta's and new location
  13820. var deltaX = pointer.x - drag.pointer.x,
  13821. deltaY = pointer.y - drag.pointer.y;
  13822. // update position of all selected nodes
  13823. selection.forEach(function (s) {
  13824. var node = s.node;
  13825. if (!s.xFixed) {
  13826. node.x = me._canvasToX(me._xToCanvas(s.x) + deltaX);
  13827. }
  13828. if (!s.yFixed) {
  13829. node.y = me._canvasToY(me._yToCanvas(s.y) + deltaY);
  13830. }
  13831. });
  13832. // start animation if not yet running
  13833. if (!this.moving) {
  13834. this.moving = true;
  13835. this.start();
  13836. }
  13837. }
  13838. else {
  13839. // move the graph
  13840. var diffX = pointer.x - this.drag.pointer.x;
  13841. var diffY = pointer.y - this.drag.pointer.y;
  13842. this._setTranslation(
  13843. this.drag.translation.x + diffX,
  13844. this.drag.translation.y + diffY);
  13845. this._redraw();
  13846. this.moved = true;
  13847. }
  13848. };
  13849. /**
  13850. * handle drag start event
  13851. * @private
  13852. */
  13853. Graph.prototype._onDragEnd = function () {
  13854. var selection = this.drag.selection;
  13855. if (selection) {
  13856. selection.forEach(function (s) {
  13857. // restore original xFixed and yFixed
  13858. s.node.xFixed = s.xFixed;
  13859. s.node.yFixed = s.yFixed;
  13860. });
  13861. }
  13862. };
  13863. /**
  13864. * handle tap/click event: select/unselect a node
  13865. * @private
  13866. */
  13867. Graph.prototype._onTap = function (event) {
  13868. var pointer = this._getPointer(event.gesture.touches[0]);
  13869. var nodeId = this._getNodeAt(pointer);
  13870. var node = this.nodes[nodeId];
  13871. if (node) {
  13872. // select this node
  13873. this._selectNodes([nodeId]);
  13874. if (!this.moving) {
  13875. this._redraw();
  13876. }
  13877. }
  13878. else {
  13879. // remove selection
  13880. this._unselectNodes();
  13881. this._redraw();
  13882. }
  13883. };
  13884. /**
  13885. * handle long tap event: multi select nodes
  13886. * @private
  13887. */
  13888. Graph.prototype._onHold = function (event) {
  13889. var pointer = this._getPointer(event.gesture.touches[0]);
  13890. var nodeId = this._getNodeAt(pointer);
  13891. var node = this.nodes[nodeId];
  13892. if (node) {
  13893. if (!node.isSelected()) {
  13894. // select this node, keep previous selection
  13895. var append = true;
  13896. this._selectNodes([nodeId], append);
  13897. }
  13898. else {
  13899. this._unselectNodes([nodeId]);
  13900. }
  13901. if (!this.moving) {
  13902. this._redraw();
  13903. }
  13904. }
  13905. else {
  13906. // Do nothing
  13907. }
  13908. };
  13909. /**
  13910. * Handle pinch event
  13911. * @param event
  13912. * @private
  13913. */
  13914. Graph.prototype._onPinch = function (event) {
  13915. var pointer = this._getPointer(event.gesture.center);
  13916. this.drag.pinched = true;
  13917. if (!('scale' in this.pinch)) {
  13918. this.pinch.scale = 1;
  13919. }
  13920. // TODO: enable moving while pinching?
  13921. var scale = this.pinch.scale * event.gesture.scale;
  13922. this._zoom(scale, pointer)
  13923. };
  13924. /**
  13925. * Zoom the graph in or out
  13926. * @param {Number} scale a number around 1, and between 0.01 and 10
  13927. * @param {{x: Number, y: Number}} pointer
  13928. * @return {Number} appliedScale scale is limited within the boundaries
  13929. * @private
  13930. */
  13931. Graph.prototype._zoom = function(scale, pointer) {
  13932. var scaleOld = this._getScale();
  13933. if (scale < 0.01) {
  13934. scale = 0.01;
  13935. }
  13936. if (scale > 10) {
  13937. scale = 10;
  13938. }
  13939. var translation = this._getTranslation();
  13940. var scaleFrac = scale / scaleOld;
  13941. var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac;
  13942. var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac;
  13943. this._setScale(scale);
  13944. this._setTranslation(tx, ty);
  13945. this._updateClusters();
  13946. this._redraw();
  13947. return scale;
  13948. };
  13949. /**
  13950. * Event handler for mouse wheel event, used to zoom the timeline
  13951. * See http://adomas.org/javascript-mouse-wheel/
  13952. * https://github.com/EightMedia/hammer.js/issues/256
  13953. * @param {MouseEvent} event
  13954. * @private
  13955. */
  13956. Graph.prototype._onMouseWheel = function(event) {
  13957. // retrieve delta
  13958. var delta = 0;
  13959. if (event.wheelDelta) { /* IE/Opera. */
  13960. delta = event.wheelDelta/120;
  13961. } else if (event.detail) { /* Mozilla case. */
  13962. // In Mozilla, sign of delta is different than in IE.
  13963. // Also, delta is multiple of 3.
  13964. delta = -event.detail/3;
  13965. }
  13966. // If delta is nonzero, handle it.
  13967. // Basically, delta is now positive if wheel was scrolled up,
  13968. // and negative, if wheel was scrolled down.
  13969. if (delta) {
  13970. if (!('mousewheelScale' in this.pinch)) {
  13971. this.pinch.mousewheelScale = 1;
  13972. }
  13973. // calculate the new scale
  13974. var scale = this.pinch.mousewheelScale;
  13975. var zoom = delta / 10;
  13976. if (delta < 0) {
  13977. zoom = zoom / (1 - zoom);
  13978. }
  13979. scale *= (1 + zoom);
  13980. // calculate the pointer location
  13981. var gesture = Hammer.event.collectEventData(this, 'scroll', event);
  13982. var pointer = this._getPointer(gesture.center);
  13983. // apply the new scale
  13984. scale = this._zoom(scale, pointer);
  13985. // store the new, applied scale
  13986. this.pinch.mousewheelScale = scale;
  13987. }
  13988. // Prevent default actions caused by mouse wheel.
  13989. event.preventDefault();
  13990. };
  13991. /**
  13992. * Mouse move handler for checking whether the title moves over a node with a title.
  13993. * @param {Event} event
  13994. * @private
  13995. */
  13996. Graph.prototype._onMouseMoveTitle = function (event) {
  13997. var gesture = Hammer.event.collectEventData(this, 'mousemove', event);
  13998. var pointer = this._getPointer(gesture.center);
  13999. // check if the previously selected node is still selected
  14000. if (this.popupNode) {
  14001. this._checkHidePopup(pointer);
  14002. }
  14003. // start a timeout that will check if the mouse is positioned above
  14004. // an element
  14005. var me = this;
  14006. var checkShow = function() {
  14007. me._checkShowPopup(pointer);
  14008. };
  14009. if (this.popupTimer) {
  14010. clearInterval(this.popupTimer); // stop any running timer
  14011. }
  14012. if (!this.leftButtonDown) {
  14013. this.popupTimer = setTimeout(checkShow, 300);
  14014. }
  14015. };
  14016. /**
  14017. * Check if there is an element on the given position in the graph
  14018. * (a node or edge). If so, and if this element has a title,
  14019. * show a popup window with its title.
  14020. *
  14021. * @param {{x:Number, y:Number}} pointer
  14022. * @private
  14023. */
  14024. Graph.prototype._checkShowPopup = function (pointer) {
  14025. var obj = {
  14026. left: this._canvasToX(pointer.x),
  14027. top: this._canvasToY(pointer.y),
  14028. right: this._canvasToX(pointer.x),
  14029. bottom: this._canvasToY(pointer.y)
  14030. };
  14031. var id;
  14032. var lastPopupNode = this.popupNode;
  14033. if (this.popupNode == undefined) {
  14034. // search the nodes for overlap, select the top one in case of multiple nodes
  14035. var nodes = this.nodes;
  14036. for (id in nodes) {
  14037. if (nodes.hasOwnProperty(id)) {
  14038. var node = nodes[id];
  14039. if (node.getTitle() != undefined && node.isOverlappingWith(obj)) {
  14040. this.popupNode = node;
  14041. break;
  14042. }
  14043. }
  14044. }
  14045. }
  14046. if (this.popupNode == undefined) {
  14047. // search the edges for overlap
  14048. var edges = this.edges;
  14049. for (id in edges) {
  14050. if (edges.hasOwnProperty(id)) {
  14051. var edge = edges[id];
  14052. if (edge.connected && (edge.getTitle() != undefined) &&
  14053. edge.isOverlappingWith(obj)) {
  14054. this.popupNode = edge;
  14055. break;
  14056. }
  14057. }
  14058. }
  14059. }
  14060. if (this.popupNode) {
  14061. // show popup message window
  14062. if (this.popupNode != lastPopupNode) {
  14063. var me = this;
  14064. if (!me.popup) {
  14065. me.popup = new Popup(me.frame);
  14066. }
  14067. // adjust a small offset such that the mouse cursor is located in the
  14068. // bottom left location of the popup, and you can easily move over the
  14069. // popup area
  14070. me.popup.setPosition(pointer.x - 3, pointer.y - 3);
  14071. me.popup.setText(me.popupNode.getTitle());
  14072. me.popup.show();
  14073. }
  14074. }
  14075. else {
  14076. if (this.popup) {
  14077. this.popup.hide();
  14078. }
  14079. }
  14080. };
  14081. /**
  14082. * Check if the popup must be hided, which is the case when the mouse is no
  14083. * longer hovering on the object
  14084. * @param {{x:Number, y:Number}} pointer
  14085. * @private
  14086. */
  14087. Graph.prototype._checkHidePopup = function (pointer) {
  14088. if (!this.popupNode || !this._getNodeAt(pointer) ) {
  14089. this.popupNode = undefined;
  14090. if (this.popup) {
  14091. this.popup.hide();
  14092. }
  14093. }
  14094. };
  14095. /**
  14096. * Unselect selected nodes. If no selection array is provided, all nodes
  14097. * are unselected
  14098. * @param {Object[]} selection Array with selection objects, each selection
  14099. * object has a parameter row. Optional
  14100. * @param {Boolean} triggerSelect If true (default), the select event
  14101. * is triggered when nodes are unselected
  14102. * @return {Boolean} changed True if the selection is changed
  14103. * @private
  14104. */
  14105. Graph.prototype._unselectNodes = function(selection, triggerSelect) {
  14106. var changed = false;
  14107. var i, iMax, id;
  14108. if (selection) {
  14109. // remove provided selections
  14110. for (i = 0, iMax = selection.length; i < iMax; i++) {
  14111. id = selection[i];
  14112. this.nodes[id].unselect();
  14113. var j = 0;
  14114. while (j < this.selection.length) {
  14115. if (this.selection[j] == id) {
  14116. this.selection.splice(j, 1);
  14117. changed = true;
  14118. }
  14119. else {
  14120. j++;
  14121. }
  14122. }
  14123. }
  14124. }
  14125. else if (this.selection && this.selection.length) {
  14126. // remove all selections
  14127. for (i = 0, iMax = this.selection.length; i < iMax; i++) {
  14128. id = this.selection[i];
  14129. this.nodes[id].unselect();
  14130. changed = true;
  14131. }
  14132. this.selection = [];
  14133. }
  14134. if (changed && (triggerSelect == true || triggerSelect == undefined)) {
  14135. // fire the select event
  14136. this._trigger('select');
  14137. }
  14138. return changed;
  14139. };
  14140. /**
  14141. * select all nodes on given location x, y
  14142. * @param {Array} selection an array with node ids
  14143. * @param {boolean} append If true, the new selection will be appended to the
  14144. * current selection (except for duplicate entries)
  14145. * @return {Boolean} changed True if the selection is changed
  14146. * @private
  14147. */
  14148. Graph.prototype._selectNodes = function(selection, append) {
  14149. var changed = false;
  14150. var i, iMax;
  14151. // TODO: the selectNodes method is a little messy, rework this
  14152. // check if the current selection equals the desired selection
  14153. var selectionAlreadyThere = true;
  14154. if (selection.length != this.selection.length) {
  14155. selectionAlreadyThere = false;
  14156. }
  14157. else {
  14158. for (i = 0, iMax = Math.min(selection.length, this.selection.length); i < iMax; i++) {
  14159. if (selection[i] != this.selection[i]) {
  14160. selectionAlreadyThere = false;
  14161. break;
  14162. }
  14163. }
  14164. }
  14165. if (selectionAlreadyThere) {
  14166. return changed;
  14167. }
  14168. if (append == undefined || append == false) {
  14169. // first deselect any selected node
  14170. var triggerSelect = false;
  14171. changed = this._unselectNodes(undefined, triggerSelect);
  14172. }
  14173. for (i = 0, iMax = selection.length; i < iMax; i++) {
  14174. // add each of the new selections, but only when they are not duplicate
  14175. var id = selection[i];
  14176. var isDuplicate = (this.selection.indexOf(id) != -1);
  14177. if (!isDuplicate) {
  14178. this.nodes[id].select();
  14179. this.selection.push(id);
  14180. changed = true;
  14181. }
  14182. }
  14183. if (changed) {
  14184. // fire the select event
  14185. this._trigger('select');
  14186. }
  14187. return changed;
  14188. };
  14189. /**
  14190. * retrieve all nodes overlapping with given object
  14191. * @param {Object} obj An object with parameters left, top, right, bottom
  14192. * @return {Number[]} An array with id's of the overlapping nodes
  14193. * @private
  14194. */
  14195. Graph.prototype._getNodesOverlappingWith = function (obj) {
  14196. var nodes = this.nodes,
  14197. overlappingNodes = [];
  14198. for (var id in nodes) {
  14199. if (nodes.hasOwnProperty(id)) {
  14200. if (nodes[id].isOverlappingWith(obj)) {
  14201. overlappingNodes.push(id);
  14202. }
  14203. }
  14204. }
  14205. return overlappingNodes;
  14206. };
  14207. /**
  14208. * retrieve the currently selected nodes
  14209. * @return {Number[] | String[]} selection An array with the ids of the
  14210. * selected nodes.
  14211. */
  14212. Graph.prototype.getSelection = function() {
  14213. return this.selection.concat([]);
  14214. };
  14215. /**
  14216. * select zero or more nodes
  14217. * @param {Number[] | String[]} selection An array with the ids of the
  14218. * selected nodes.
  14219. */
  14220. Graph.prototype.setSelection = function(selection) {
  14221. var i, iMax, id;
  14222. if (!selection || (selection.length == undefined))
  14223. throw 'Selection must be an array with ids';
  14224. // first unselect any selected node
  14225. for (i = 0, iMax = this.selection.length; i < iMax; i++) {
  14226. id = this.selection[i];
  14227. this.nodes[id].unselect();
  14228. }
  14229. this.selection = [];
  14230. for (i = 0, iMax = selection.length; i < iMax; i++) {
  14231. id = selection[i];
  14232. var node = this.nodes[id];
  14233. if (!node) {
  14234. throw new RangeError('Node with id "' + id + '" not found');
  14235. }
  14236. node.select();
  14237. this.selection.push(id);
  14238. }
  14239. this.redraw();
  14240. };
  14241. /**
  14242. * Validate the selection: remove ids of nodes which no longer exist
  14243. * @private
  14244. */
  14245. Graph.prototype._updateSelection = function () {
  14246. var i = 0;
  14247. while (i < this.selection.length) {
  14248. var id = this.selection[i];
  14249. if (!this.nodes[id]) {
  14250. this.selection.splice(i, 1);
  14251. }
  14252. else {
  14253. i++;
  14254. }
  14255. }
  14256. };
  14257. /**
  14258. * Temporary method to test calculating a hub value for the nodes
  14259. * @param {number} level Maximum number edges between two nodes in order
  14260. * to call them connected. Optional, 1 by default
  14261. * @return {Number[]} connectioncount array with the connection count
  14262. * for each node
  14263. * @private
  14264. */
  14265. Graph.prototype._getConnectionCount = function(level) {
  14266. if (level == undefined) {
  14267. level = 1;
  14268. }
  14269. // get the nodes connected to given nodes
  14270. function getConnectedNodes(nodes) {
  14271. var connectedNodes = [];
  14272. for (var j = 0, jMax = nodes.length; j < jMax; j++) {
  14273. var node = nodes[j];
  14274. // find all nodes connected to this node
  14275. var edges = node.edges;
  14276. for (var i = 0, iMax = edges.length; i < iMax; i++) {
  14277. var edge = edges[i];
  14278. var other = null;
  14279. // check if connected
  14280. if (edge.from == node)
  14281. other = edge.to;
  14282. else if (edge.to == node)
  14283. other = edge.from;
  14284. // check if the other node is not already in the list with nodes
  14285. var k, kMax;
  14286. if (other) {
  14287. for (k = 0, kMax = nodes.length; k < kMax; k++) {
  14288. if (nodes[k] == other) {
  14289. other = null;
  14290. break;
  14291. }
  14292. }
  14293. }
  14294. if (other) {
  14295. for (k = 0, kMax = connectedNodes.length; k < kMax; k++) {
  14296. if (connectedNodes[k] == other) {
  14297. other = null;
  14298. break;
  14299. }
  14300. }
  14301. }
  14302. if (other)
  14303. connectedNodes.push(other);
  14304. }
  14305. }
  14306. return connectedNodes;
  14307. }
  14308. var connections = [];
  14309. var nodes = this.nodes;
  14310. for (var id in nodes) {
  14311. if (nodes.hasOwnProperty(id)) {
  14312. var c = [nodes[id]];
  14313. for (var l = 0; l < level; l++) {
  14314. c = c.concat(getConnectedNodes(c));
  14315. }
  14316. connections.push(c);
  14317. }
  14318. }
  14319. var hubs = [];
  14320. for (var i = 0, len = connections.length; i < len; i++) {
  14321. hubs.push(connections[i].length);
  14322. }
  14323. return hubs;
  14324. };
  14325. /**
  14326. * Set a new size for the graph
  14327. * @param {string} width Width in pixels or percentage (for example '800px'
  14328. * or '50%')
  14329. * @param {string} height Height in pixels or percentage (for example '400px'
  14330. * or '30%')
  14331. */
  14332. Graph.prototype.setSize = function(width, height) {
  14333. this.frame.style.width = width;
  14334. this.frame.style.height = height;
  14335. this.frame.canvas.style.width = '100%';
  14336. this.frame.canvas.style.height = '100%';
  14337. this.frame.canvas.width = this.frame.canvas.clientWidth;
  14338. this.frame.canvas.height = this.frame.canvas.clientHeight;
  14339. };
  14340. /**
  14341. * Set a data set with nodes for the graph
  14342. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  14343. * @private
  14344. */
  14345. Graph.prototype._setNodes = function(nodes) {
  14346. var oldNodesData = this.nodesData;
  14347. if (nodes instanceof DataSet || nodes instanceof DataView) {
  14348. this.nodesData = nodes;
  14349. }
  14350. else if (nodes instanceof Array) {
  14351. this.nodesData = new DataSet();
  14352. this.nodesData.add(nodes);
  14353. }
  14354. else if (!nodes) {
  14355. this.nodesData = new DataSet();
  14356. }
  14357. else {
  14358. throw new TypeError('Array or DataSet expected');
  14359. }
  14360. if (oldNodesData) {
  14361. // unsubscribe from old dataset
  14362. util.forEach(this.nodesListeners, function (callback, event) {
  14363. oldNodesData.unsubscribe(event, callback);
  14364. });
  14365. }
  14366. // remove drawn nodes
  14367. this.nodes = {};
  14368. if (this.nodesData) {
  14369. // subscribe to new dataset
  14370. var me = this;
  14371. util.forEach(this.nodesListeners, function (callback, event) {
  14372. me.nodesData.subscribe(event, callback);
  14373. });
  14374. // draw all new nodes
  14375. var ids = this.nodesData.getIds();
  14376. this._addNodes(ids);
  14377. }
  14378. this._updateSelection();
  14379. };
  14380. /**
  14381. * Add nodes
  14382. * @param {Number[] | String[]} ids
  14383. * @private
  14384. */
  14385. Graph.prototype._addNodes = function(ids) {
  14386. var id;
  14387. for (var i = 0, len = ids.length; i < len; i++) {
  14388. id = ids[i];
  14389. var data = this.nodesData.get(id);
  14390. var node = new Node(data, this.images, this.groups, this.constants);
  14391. this.nodes[id] = node; // note: this may replace an existing node
  14392. if (!node.isFixed()) {
  14393. // TODO: position new nodes in a smarter way!
  14394. var radius = this.constants.edges.length * 2;
  14395. var count = ids.length;
  14396. var angle = 2 * Math.PI * (i / count);
  14397. node.x = radius * Math.cos(angle);
  14398. node.y = radius * Math.sin(angle);
  14399. // note: no not use node.isMoving() here, as that gives the current
  14400. // velocity of the node, which is zero after creation of the node.
  14401. this.moving = true;
  14402. }
  14403. }
  14404. this._updateNodeIndexList();
  14405. this._reconnectEdges();
  14406. this._updateValueRange(this.nodes);
  14407. };
  14408. /**
  14409. * Update existing nodes, or create them when not yet existing
  14410. * @param {Number[] | String[]} ids
  14411. * @private
  14412. */
  14413. Graph.prototype._updateNodes = function(ids) {
  14414. var nodes = this.nodes,
  14415. nodesData = this.nodesData;
  14416. for (var i = 0, len = ids.length; i < len; i++) {
  14417. var id = ids[i];
  14418. var node = nodes[id];
  14419. var data = nodesData.get(id);
  14420. if (node) {
  14421. // update node
  14422. node.setProperties(data, this.constants);
  14423. }
  14424. else {
  14425. // create node
  14426. node = new Node(properties, this.images, this.groups, this.constants);
  14427. nodes[id] = node;
  14428. if (!node.isFixed()) {
  14429. this.moving = true;
  14430. }
  14431. }
  14432. }
  14433. this._updateNodeIndexList();
  14434. this._reconnectEdges();
  14435. this._updateValueRange(nodes);
  14436. };
  14437. /**
  14438. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  14439. * @param {Number[] | String[]} ids
  14440. * @private
  14441. */
  14442. Graph.prototype._removeNodes = function(ids) {
  14443. var nodes = this.nodes;
  14444. for (var i = 0, len = ids.length; i < len; i++) {
  14445. var id = ids[i];
  14446. delete nodes[id];
  14447. }
  14448. this._updateNodeIndexList();
  14449. this._reconnectEdges();
  14450. this._updateSelection();
  14451. this._updateValueRange(nodes);
  14452. };
  14453. /**
  14454. * Load edges by reading the data table
  14455. * @param {Array | DataSet | DataView} edges The data containing the edges.
  14456. * @private
  14457. * @private
  14458. */
  14459. Graph.prototype._setEdges = function(edges) {
  14460. var oldEdgesData = this.edgesData;
  14461. if (edges instanceof DataSet || edges instanceof DataView) {
  14462. this.edgesData = edges;
  14463. }
  14464. else if (edges instanceof Array) {
  14465. this.edgesData = new DataSet();
  14466. this.edgesData.add(edges);
  14467. }
  14468. else if (!edges) {
  14469. this.edgesData = new DataSet();
  14470. }
  14471. else {
  14472. throw new TypeError('Array or DataSet expected');
  14473. }
  14474. if (oldEdgesData) {
  14475. // unsubscribe from old dataset
  14476. util.forEach(this.edgesListeners, function (callback, event) {
  14477. oldEdgesData.unsubscribe(event, callback);
  14478. });
  14479. }
  14480. // remove drawn edges
  14481. this.edges = {};
  14482. if (this.edgesData) {
  14483. // subscribe to new dataset
  14484. var me = this;
  14485. util.forEach(this.edgesListeners, function (callback, event) {
  14486. me.edgesData.subscribe(event, callback);
  14487. });
  14488. // draw all new nodes
  14489. var ids = this.edgesData.getIds();
  14490. this._addEdges(ids);
  14491. }
  14492. this._reconnectEdges();
  14493. };
  14494. /**
  14495. * Add edges
  14496. * @param {Number[] | String[]} ids
  14497. * @private
  14498. */
  14499. Graph.prototype._addEdges = function (ids) {
  14500. var edges = this.edges,
  14501. edgesData = this.edgesData;
  14502. for (var i = 0, len = ids.length; i < len; i++) {
  14503. var id = ids[i];
  14504. var oldEdge = edges[id];
  14505. if (oldEdge) {
  14506. oldEdge.disconnect();
  14507. }
  14508. var data = edgesData.get(id);
  14509. edges[id] = new Edge(data, this, this.constants);
  14510. }
  14511. this.moving = true;
  14512. this._updateValueRange(edges);
  14513. };
  14514. /**
  14515. * Update existing edges, or create them when not yet existing
  14516. * @param {Number[] | String[]} ids
  14517. * @private
  14518. */
  14519. Graph.prototype._updateEdges = function (ids) {
  14520. var edges = this.edges,
  14521. edgesData = this.edgesData;
  14522. for (var i = 0, len = ids.length; i < len; i++) {
  14523. var id = ids[i];
  14524. var data = edgesData.get(id);
  14525. var edge = edges[id];
  14526. if (edge) {
  14527. // update edge
  14528. edge.disconnect();
  14529. edge.setProperties(data, this.constants);
  14530. edge.connect();
  14531. }
  14532. else {
  14533. // create edge
  14534. edge = new Edge(data, this, this.constants);
  14535. this.edges[id] = edge;
  14536. }
  14537. }
  14538. this.moving = true;
  14539. this._updateValueRange(edges);
  14540. };
  14541. /**
  14542. * Remove existing edges. Non existing ids will be ignored
  14543. * @param {Number[] | String[]} ids
  14544. * @private
  14545. */
  14546. Graph.prototype._removeEdges = function (ids) {
  14547. var edges = this.edges;
  14548. for (var i = 0, len = ids.length; i < len; i++) {
  14549. var id = ids[i];
  14550. var edge = edges[id];
  14551. if (edge) {
  14552. edge.disconnect();
  14553. delete edges[id];
  14554. }
  14555. }
  14556. this.moving = true;
  14557. this._updateValueRange(edges);
  14558. };
  14559. /**
  14560. * Reconnect all edges
  14561. * @private
  14562. */
  14563. Graph.prototype._reconnectEdges = function() {
  14564. var id,
  14565. nodes = this.nodes,
  14566. edges = this.edges;
  14567. for (id in nodes) {
  14568. if (nodes.hasOwnProperty(id)) {
  14569. nodes[id].edges = [];
  14570. }
  14571. }
  14572. for (id in edges) {
  14573. if (edges.hasOwnProperty(id)) {
  14574. var edge = edges[id];
  14575. edge.from = null;
  14576. edge.to = null;
  14577. edge.connect();
  14578. }
  14579. }
  14580. };
  14581. /**
  14582. * Update the values of all object in the given array according to the current
  14583. * value range of the objects in the array.
  14584. * @param {Object} obj An object containing a set of Edges or Nodes
  14585. * The objects must have a method getValue() and
  14586. * setValueRange(min, max).
  14587. * @private
  14588. */
  14589. Graph.prototype._updateValueRange = function(obj) {
  14590. var id;
  14591. // determine the range of the objects
  14592. var valueMin = undefined;
  14593. var valueMax = undefined;
  14594. for (id in obj) {
  14595. if (obj.hasOwnProperty(id)) {
  14596. var value = obj[id].getValue();
  14597. if (value !== undefined) {
  14598. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  14599. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  14600. }
  14601. }
  14602. }
  14603. // adjust the range of all objects
  14604. if (valueMin !== undefined && valueMax !== undefined) {
  14605. for (id in obj) {
  14606. if (obj.hasOwnProperty(id)) {
  14607. obj[id].setValueRange(valueMin, valueMax);
  14608. }
  14609. }
  14610. }
  14611. };
  14612. /**
  14613. * Redraw the graph with the current data
  14614. * chart will be resized too.
  14615. */
  14616. Graph.prototype.redraw = function() {
  14617. this.setSize(this.width, this.height);
  14618. this._redraw();
  14619. };
  14620. /**
  14621. * Redraw the graph with the current data
  14622. * @private
  14623. */
  14624. Graph.prototype._redraw = function() {
  14625. var ctx = this.frame.canvas.getContext('2d');
  14626. // clear the canvas
  14627. var w = this.frame.canvas.width;
  14628. var h = this.frame.canvas.height;
  14629. ctx.clearRect(0, 0, w, h);
  14630. // set scaling and translation
  14631. ctx.save();
  14632. ctx.translate(this.translation.x, this.translation.y);
  14633. ctx.scale(this.scale, this.scale);
  14634. this._drawEdges(ctx);
  14635. this._drawNodes(ctx);
  14636. // restore original scaling and translation
  14637. ctx.restore();
  14638. };
  14639. /**
  14640. * Set the translation of the graph
  14641. * @param {Number} offsetX Horizontal offset
  14642. * @param {Number} offsetY Vertical offset
  14643. * @private
  14644. */
  14645. Graph.prototype._setTranslation = function(offsetX, offsetY) {
  14646. if (this.translation === undefined) {
  14647. this.translation = {
  14648. x: 0,
  14649. y: 0
  14650. };
  14651. }
  14652. if (offsetX !== undefined) {
  14653. this.translation.x = offsetX;
  14654. }
  14655. if (offsetY !== undefined) {
  14656. this.translation.y = offsetY;
  14657. }
  14658. };
  14659. /**
  14660. * Get the translation of the graph
  14661. * @return {Object} translation An object with parameters x and y, both a number
  14662. * @private
  14663. */
  14664. Graph.prototype._getTranslation = function() {
  14665. return {
  14666. x: this.translation.x,
  14667. y: this.translation.y
  14668. };
  14669. };
  14670. /**
  14671. * Scale the graph
  14672. * @param {Number} scale Scaling factor 1.0 is unscaled
  14673. * @private
  14674. */
  14675. Graph.prototype._setScale = function(scale) {
  14676. this.scale = scale;
  14677. };
  14678. /**
  14679. * Get the current scale of the graph
  14680. * @return {Number} scale Scaling factor 1.0 is unscaled
  14681. * @private
  14682. */
  14683. Graph.prototype._getScale = function() {
  14684. return this.scale;
  14685. };
  14686. /**
  14687. * Convert a horizontal point on the HTML canvas to the x-value of the model
  14688. * @param {number} x
  14689. * @returns {number}
  14690. * @private
  14691. */
  14692. Graph.prototype._canvasToX = function(x) {
  14693. return (x - this.translation.x) / this.scale;
  14694. };
  14695. /**
  14696. * Convert an x-value in the model to a horizontal point on the HTML canvas
  14697. * @param {number} x
  14698. * @returns {number}
  14699. * @private
  14700. */
  14701. Graph.prototype._xToCanvas = function(x) {
  14702. return x * this.scale + this.translation.x;
  14703. };
  14704. /**
  14705. * Convert a vertical point on the HTML canvas to the y-value of the model
  14706. * @param {number} y
  14707. * @returns {number}
  14708. * @private
  14709. */
  14710. Graph.prototype._canvasToY = function(y) {
  14711. return (y - this.translation.y) / this.scale;
  14712. };
  14713. /**
  14714. * Convert an y-value in the model to a vertical point on the HTML canvas
  14715. * @param {number} y
  14716. * @returns {number}
  14717. * @private
  14718. */
  14719. Graph.prototype._yToCanvas = function(y) {
  14720. return y * this.scale + this.translation.y ;
  14721. };
  14722. /**
  14723. * Redraw all nodes
  14724. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  14725. * @param {CanvasRenderingContext2D} ctx
  14726. * @private
  14727. */
  14728. Graph.prototype._drawNodes = function(ctx) {
  14729. // first draw the unselected nodes
  14730. var nodes = this.nodes;
  14731. var selected = [];
  14732. for (var id in nodes) {
  14733. if (nodes.hasOwnProperty(id)) {
  14734. if (nodes[id].isSelected()) {
  14735. selected.push(id);
  14736. }
  14737. else {
  14738. nodes[id].draw(ctx);
  14739. }
  14740. }
  14741. }
  14742. // draw the selected nodes on top
  14743. for (var s = 0, sMax = selected.length; s < sMax; s++) {
  14744. nodes[selected[s]].draw(ctx);
  14745. }
  14746. };
  14747. /**
  14748. * Redraw all edges
  14749. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  14750. * @param {CanvasRenderingContext2D} ctx
  14751. * @private
  14752. */
  14753. Graph.prototype._drawEdges = function(ctx) {
  14754. var edges = this.edges;
  14755. for (var id in edges) {
  14756. if (edges.hasOwnProperty(id)) {
  14757. var edge = edges[id];
  14758. if (edge.connected) {
  14759. edges[id].draw(ctx);
  14760. }
  14761. }
  14762. }
  14763. };
  14764. /**
  14765. * Find a stable position for all nodes
  14766. * @private
  14767. */
  14768. Graph.prototype._doStabilize = function() {
  14769. var start = new Date();
  14770. // find stable position
  14771. var count = 0;
  14772. var vmin = this.constants.minVelocity;
  14773. var stable = false;
  14774. while (!stable && count < this.constants.maxIterations) {
  14775. this._calculateForces();
  14776. this._discreteStepNodes();
  14777. stable = !this._isMoving(vmin);
  14778. count++;
  14779. }
  14780. var end = new Date();
  14781. // console.log('Stabilized in ' + (end-start) + ' ms, ' + count + ' iterations' ); // TODO: cleanup
  14782. };
  14783. /**
  14784. * Calculate the external forces acting on the nodes
  14785. * Forces are caused by: edges, repulsing forces between nodes, gravity
  14786. * @private
  14787. */
  14788. Graph.prototype._calculateForces = function() {
  14789. // create a local edge to the nodes and edges, that is faster
  14790. var id, dx, dy, angle, distance, fx, fy,
  14791. repulsingForce, springForce, length, edgeLength,
  14792. nodes = this.nodes,
  14793. edges = this.edges;
  14794. // gravity, add a small constant force to pull the nodes towards the center of
  14795. // the graph
  14796. // Also, the forces are reset to zero in this loop by using _setForce instead
  14797. // of _addForce
  14798. var gravity = 0.01,
  14799. gx = this.frame.canvas.clientWidth / 2,
  14800. gy = this.frame.canvas.clientHeight / 2;
  14801. for (id in nodes) {
  14802. if (nodes.hasOwnProperty(id)) {
  14803. var node = nodes[id];
  14804. dx = gx - node.x;
  14805. dy = gy - node.y;
  14806. angle = Math.atan2(dy, dx);
  14807. fx = Math.cos(angle) * gravity;
  14808. fy = Math.sin(angle) * gravity;
  14809. node._setForce(fx, fy);
  14810. }
  14811. }
  14812. // repulsing forces between nodes
  14813. var minimumDistance = this.constants.nodes.distance,
  14814. steepness = 10; // higher value gives steeper slope of the force around the given minimumDistance
  14815. // we loop from i over all but the last entree in the array
  14816. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  14817. for (var i = 0; i < this.nodeIndices.length-1; i++) {
  14818. var node1 = nodes[this.nodeIndices[i]];
  14819. for (var j = i+1; j < this.nodeIndices.length; j++) {
  14820. var node2 = nodes[this.nodeIndices[j]];
  14821. var clusterSize = (node1.clusterSize + node2.clusterSize - 2);
  14822. dx = node2.x - node1.x;
  14823. dy = node2.y - node1.y;
  14824. distance = Math.sqrt(dx * dx + dy * dy);
  14825. // clusters have a larger region of influence
  14826. minimumDistance = (clusterSize == 0) ? this.constants.nodes.distance : (this.constants.nodes.distance * (1 + clusterSize * this.constants.clustering.distanceAmplification));
  14827. if (distance < 2*minimumDistance) { // at 2.0 * the minimum distance, the force is 0.000045
  14828. angle = Math.atan2(dy, dx);
  14829. if (distance < 0.5*minimumDistance) { // at 0.5 * the minimum distance, the force is 0.993307
  14830. repulsingForce = 1.0;
  14831. }
  14832. else {
  14833. // TODO: correct factor for repulsing force
  14834. //repulsingForce = 2 * Math.exp(-5 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  14835. //repulsingForce = Math.exp(-1 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  14836. repulsingForce = 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness)); // TODO: customize the repulsing force
  14837. }
  14838. // amplify the repulsion for clusters.
  14839. repulsingForce *= (clusterSize == 0) ? 1 : 1 + clusterSize * this.constants.clustering.forceAmplification;
  14840. fx = Math.cos(angle) * repulsingForce;
  14841. fy = Math.sin(angle) * repulsingForce;
  14842. node1._addForce(-fx, -fy);
  14843. node2._addForce(fx, fy);
  14844. }
  14845. }
  14846. }
  14847. /* TODO: re-implement repulsion of edges
  14848. for (var n = 0; n < nodes.length; n++) {
  14849. for (var l = 0; l < edges.length; l++) {
  14850. var lx = edges[l].from.x+(edges[l].to.x - edges[l].from.x)/2,
  14851. ly = edges[l].from.y+(edges[l].to.y - edges[l].from.y)/2,
  14852. // calculate normally distributed force
  14853. dx = nodes[n].x - lx,
  14854. dy = nodes[n].y - ly,
  14855. distance = Math.sqrt(dx * dx + dy * dy),
  14856. angle = Math.atan2(dy, dx),
  14857. // TODO: correct factor for repulsing force
  14858. //var repulsingforce = 2 * Math.exp(-5 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  14859. //repulsingforce = Math.exp(-1 * (distance * distance) / (dmin * dmin) ), // TODO: customize the repulsing force
  14860. repulsingforce = 1 / (1 + Math.exp((distance / (minimumDistance / 2) - 1) * steepness)), // TODO: customize the repulsing force
  14861. fx = Math.cos(angle) * repulsingforce,
  14862. fy = Math.sin(angle) * repulsingforce;
  14863. nodes[n]._addForce(fx, fy);
  14864. edges[l].from._addForce(-fx/2,-fy/2);
  14865. edges[l].to._addForce(-fx/2,-fy/2);
  14866. }
  14867. }
  14868. */
  14869. // forces caused by the edges, modelled as springs
  14870. for (id in edges) {
  14871. if (edges.hasOwnProperty(id)) {
  14872. var edge = edges[id];
  14873. if (edge.connected) {
  14874. dx = (edge.to.x - edge.from.x);
  14875. dy = (edge.to.y - edge.from.y);
  14876. //edgeLength = (edge.from.width + edge.from.height + edge.to.width + edge.to.height)/2 || edge.length; // TODO: dmin
  14877. //edgeLength = (edge.from.width + edge.to.width)/2 || edge.length; // TODO: dmin
  14878. //edgeLength = 20 + ((edge.from.width + edge.to.width) || 0) / 2;
  14879. edgeLength = edge.length;
  14880. // this implies that the edges between big clusters are longer
  14881. edgeLength += (edge.to.clusterSize + edge.from.clusterSize - 2) * this.constants.clustering.edgeGrowth;
  14882. length = Math.sqrt(dx * dx + dy * dy);
  14883. angle = Math.atan2(dy, dx);
  14884. springForce = edge.stiffness * (edgeLength - length);
  14885. fx = Math.cos(angle) * springForce;
  14886. fy = Math.sin(angle) * springForce;
  14887. edge.from._addForce(-fx, -fy);
  14888. edge.to._addForce(fx, fy);
  14889. }
  14890. }
  14891. }
  14892. /*
  14893. // TODO: re-implement repulsion of edges
  14894. // repulsing forces between edges
  14895. var minimumDistance = this.constants.edges.distance,
  14896. steepness = 10; // higher value gives steeper slope of the force around the given minimumDistance
  14897. for (var l = 0; l < edges.length; l++) {
  14898. //Keep distance from other edge centers
  14899. for (var l2 = l + 1; l2 < this.edges.length; l2++) {
  14900. //var dmin = (nodes[n].width + nodes[n].height + nodes[n2].width + nodes[n2].height) / 1 || minimumDistance, // TODO: dmin
  14901. //var dmin = (nodes[n].width + nodes[n2].width)/2 || minimumDistance, // TODO: dmin
  14902. //dmin = 40 + ((nodes[n].width/2 + nodes[n2].width/2) || 0),
  14903. var lx = edges[l].from.x+(edges[l].to.x - edges[l].from.x)/2,
  14904. ly = edges[l].from.y+(edges[l].to.y - edges[l].from.y)/2,
  14905. l2x = edges[l2].from.x+(edges[l2].to.x - edges[l2].from.x)/2,
  14906. l2y = edges[l2].from.y+(edges[l2].to.y - edges[l2].from.y)/2,
  14907. // calculate normally distributed force
  14908. dx = l2x - lx,
  14909. dy = l2y - ly,
  14910. distance = Math.sqrt(dx * dx + dy * dy),
  14911. angle = Math.atan2(dy, dx),
  14912. // TODO: correct factor for repulsing force
  14913. //var repulsingforce = 2 * Math.exp(-5 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  14914. //repulsingforce = Math.exp(-1 * (distance * distance) / (dmin * dmin) ), // TODO: customize the repulsing force
  14915. repulsingforce = 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness)), // TODO: customize the repulsing force
  14916. fx = Math.cos(angle) * repulsingforce,
  14917. fy = Math.sin(angle) * repulsingforce;
  14918. edges[l].from._addForce(-fx, -fy);
  14919. edges[l].to._addForce(-fx, -fy);
  14920. edges[l2].from._addForce(fx, fy);
  14921. edges[l2].to._addForce(fx, fy);
  14922. }
  14923. }
  14924. */
  14925. };
  14926. /**
  14927. * Check if any of the nodes is still moving
  14928. * @param {number} vmin the minimum velocity considered as 'moving'
  14929. * @return {boolean} true if moving, false if non of the nodes is moving
  14930. * @private
  14931. */
  14932. Graph.prototype._isMoving = function(vmin) {
  14933. // TODO: ismoving does not work well: should check the kinetic energy, not its velocity
  14934. var nodes = this.nodes;
  14935. for (var id in nodes) {
  14936. if (nodes.hasOwnProperty(id) && nodes[id].isMoving(vmin)) {
  14937. return true;
  14938. }
  14939. }
  14940. return false;
  14941. };
  14942. /**
  14943. * Perform one discrete step for all nodes
  14944. * @private
  14945. */
  14946. Graph.prototype._discreteStepNodes = function() {
  14947. var interval = this.refreshRate / 1000.0; // in seconds
  14948. var nodes = this.nodes;
  14949. for (var id in nodes) {
  14950. if (nodes.hasOwnProperty(id)) {
  14951. nodes[id].discreteStep(interval);
  14952. }
  14953. }
  14954. };
  14955. /**
  14956. * Start animating nodes and edges
  14957. */
  14958. Graph.prototype.start = function() {
  14959. if (this.moving) {
  14960. this._calculateForces();
  14961. this._discreteStepNodes();
  14962. var vmin = this.constants.minVelocity;
  14963. this.moving = this._isMoving(vmin);
  14964. }
  14965. if (this.moving) {
  14966. // start animation. only start timer if it is not already running
  14967. if (!this.timer) {
  14968. var graph = this;
  14969. this.timer = window.setTimeout(function () {
  14970. graph.timer = undefined;
  14971. // benchmark the calculation
  14972. // var start = window.performance.now();
  14973. graph.start();
  14974. // Optionally call this twice for faster convergence
  14975. // graph.start();
  14976. // var end = window.performance.now();
  14977. // var time = end - start;
  14978. // console.log('Simulation time: ' + time);
  14979. // start = window.performance.now();
  14980. graph._redraw();
  14981. // end = window.performance.now();
  14982. // time = end - start;
  14983. // console.log('Drawing time: ' + time);
  14984. }, this.refreshRate);
  14985. }
  14986. }
  14987. else {
  14988. this._redraw();
  14989. }
  14990. };
  14991. /**
  14992. * Stop animating nodes and edges.
  14993. */
  14994. Graph.prototype.stop = function () {
  14995. if (this.timer) {
  14996. window.clearInterval(this.timer);
  14997. this.timer = undefined;
  14998. }
  14999. };
  15000. /**
  15001. * vis.js module exports
  15002. */
  15003. var vis = {
  15004. util: util,
  15005. events: events,
  15006. Controller: Controller,
  15007. DataSet: DataSet,
  15008. DataView: DataView,
  15009. Range: Range,
  15010. Stack: Stack,
  15011. TimeStep: TimeStep,
  15012. EventBus: EventBus,
  15013. components: {
  15014. items: {
  15015. Item: Item,
  15016. ItemBox: ItemBox,
  15017. ItemPoint: ItemPoint,
  15018. ItemRange: ItemRange
  15019. },
  15020. Component: Component,
  15021. Panel: Panel,
  15022. RootPanel: RootPanel,
  15023. ItemSet: ItemSet,
  15024. TimeAxis: TimeAxis
  15025. },
  15026. graph: {
  15027. Node: Node,
  15028. Edge: Edge,
  15029. Popup: Popup,
  15030. Groups: Groups,
  15031. Images: Images
  15032. },
  15033. Timeline: Timeline,
  15034. Graph: Graph
  15035. };
  15036. /**
  15037. * CommonJS module exports
  15038. */
  15039. if (typeof exports !== 'undefined') {
  15040. exports = vis;
  15041. }
  15042. if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  15043. module.exports = vis;
  15044. }
  15045. /**
  15046. * AMD module exports
  15047. */
  15048. if (typeof(define) === 'function') {
  15049. define(function () {
  15050. return vis;
  15051. });
  15052. }
  15053. /**
  15054. * Window exports
  15055. */
  15056. if (typeof window !== 'undefined') {
  15057. // attach the module to the window, load as a regular javascript file
  15058. window['vis'] = vis;
  15059. }
  15060. // inject css
  15061. 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
  15062. },{"hammerjs":1,"moment":2,"mouseTrap":3}]},{},[4])
  15063. (4)
  15064. });