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.

1306 lines
46 KiB

  1. var Emitter = require('emitter-component');
  2. var Hammer = require('../module/hammer');
  3. var hammerUtil = require('../hammerUtil');
  4. var util = require('../util');
  5. var TimeAxis = require('./component/TimeAxis');
  6. var Activator = require('../shared/Activator');
  7. var DateUtil = require('./DateUtil');
  8. var CustomTime = require('./component/CustomTime');
  9. /**
  10. * Create a timeline visualization
  11. * @constructor
  12. */
  13. function Core () {}
  14. // turn Core into an event emitter
  15. Emitter(Core.prototype);
  16. /**
  17. * Create the main DOM for the Core: a root panel containing left, right,
  18. * top, bottom, content, and background panel.
  19. * @param {Element} container The container element where the Core will
  20. * be attached.
  21. * @protected
  22. */
  23. Core.prototype._create = function (container) {
  24. this.dom = {};
  25. this.dom.container = container;
  26. this.dom.root = document.createElement('div');
  27. this.dom.background = document.createElement('div');
  28. this.dom.backgroundVertical = document.createElement('div');
  29. this.dom.backgroundHorizontal = document.createElement('div');
  30. this.dom.centerContainer = document.createElement('div');
  31. this.dom.leftContainer = document.createElement('div');
  32. this.dom.rightContainer = document.createElement('div');
  33. this.dom.center = document.createElement('div');
  34. this.dom.left = document.createElement('div');
  35. this.dom.right = document.createElement('div');
  36. this.dom.top = document.createElement('div');
  37. this.dom.bottom = document.createElement('div');
  38. this.dom.shadowTop = document.createElement('div');
  39. this.dom.shadowBottom = document.createElement('div');
  40. this.dom.shadowTopLeft = document.createElement('div');
  41. this.dom.shadowBottomLeft = document.createElement('div');
  42. this.dom.shadowTopRight = document.createElement('div');
  43. this.dom.shadowBottomRight = document.createElement('div');
  44. this.dom.rollingModeBtn = document.createElement('div');
  45. this.dom.root.className = 'vis-timeline';
  46. this.dom.background.className = 'vis-panel vis-background';
  47. this.dom.backgroundVertical.className = 'vis-panel vis-background vis-vertical';
  48. this.dom.backgroundHorizontal.className = 'vis-panel vis-background vis-horizontal';
  49. this.dom.centerContainer.className = 'vis-panel vis-center';
  50. this.dom.leftContainer.className = 'vis-panel vis-left';
  51. this.dom.rightContainer.className = 'vis-panel vis-right';
  52. this.dom.top.className = 'vis-panel vis-top';
  53. this.dom.bottom.className = 'vis-panel vis-bottom';
  54. this.dom.left.className = 'vis-content';
  55. this.dom.center.className = 'vis-content';
  56. this.dom.right.className = 'vis-content';
  57. this.dom.shadowTop.className = 'vis-shadow vis-top';
  58. this.dom.shadowBottom.className = 'vis-shadow vis-bottom';
  59. this.dom.shadowTopLeft.className = 'vis-shadow vis-top';
  60. this.dom.shadowBottomLeft.className = 'vis-shadow vis-bottom';
  61. this.dom.shadowTopRight.className = 'vis-shadow vis-top';
  62. this.dom.shadowBottomRight.className = 'vis-shadow vis-bottom';
  63. this.dom.rollingModeBtn.className = 'vis-rolling-mode-btn';
  64. this.dom.root.appendChild(this.dom.background);
  65. this.dom.root.appendChild(this.dom.backgroundVertical);
  66. this.dom.root.appendChild(this.dom.backgroundHorizontal);
  67. this.dom.root.appendChild(this.dom.centerContainer);
  68. this.dom.root.appendChild(this.dom.leftContainer);
  69. this.dom.root.appendChild(this.dom.rightContainer);
  70. this.dom.root.appendChild(this.dom.top);
  71. this.dom.root.appendChild(this.dom.bottom);
  72. this.dom.root.appendChild(this.dom.bottom);
  73. this.dom.root.appendChild(this.dom.rollingModeBtn);
  74. this.dom.centerContainer.appendChild(this.dom.center);
  75. this.dom.leftContainer.appendChild(this.dom.left);
  76. this.dom.rightContainer.appendChild(this.dom.right);
  77. this.dom.centerContainer.appendChild(this.dom.shadowTop);
  78. this.dom.centerContainer.appendChild(this.dom.shadowBottom);
  79. this.dom.leftContainer.appendChild(this.dom.shadowTopLeft);
  80. this.dom.leftContainer.appendChild(this.dom.shadowBottomLeft);
  81. this.dom.rightContainer.appendChild(this.dom.shadowTopRight);
  82. this.dom.rightContainer.appendChild(this.dom.shadowBottomRight);
  83. // size properties of each of the panels
  84. this.props = {
  85. root: {},
  86. background: {},
  87. centerContainer: {},
  88. leftContainer: {},
  89. rightContainer: {},
  90. center: {},
  91. left: {},
  92. right: {},
  93. top: {},
  94. bottom: {},
  95. border: {},
  96. scrollTop: 0,
  97. scrollTopMin: 0
  98. };
  99. this.on('rangechange', function () {
  100. if (this.initialDrawDone === true) {
  101. this._redraw();
  102. }
  103. }.bind(this));
  104. this.on('touch', this._onTouch.bind(this));
  105. this.on('panmove', this._onDrag.bind(this));
  106. var me = this;
  107. this._origRedraw = this._redraw.bind(this);
  108. this._redraw = util.throttle(this._origRedraw);
  109. this.on('_change', function (properties) {
  110. if (me.itemSet && me.itemSet.initialItemSetDrawn && properties && properties.queue == true) {
  111. me._redraw()
  112. } else {
  113. me._origRedraw();
  114. }
  115. });
  116. // create event listeners for all interesting events, these events will be
  117. // emitted via emitter
  118. this.hammer = new Hammer(this.dom.root);
  119. var pinchRecognizer = this.hammer.get('pinch').set({enable: true});
  120. hammerUtil.disablePreventDefaultVertically(pinchRecognizer);
  121. this.hammer.get('pan').set({threshold:5, direction: Hammer.DIRECTION_HORIZONTAL});
  122. this.listeners = {};
  123. var events = [
  124. 'tap', 'doubletap', 'press',
  125. 'pinch',
  126. 'pan', 'panstart', 'panmove', 'panend'
  127. // TODO: cleanup
  128. //'touch', 'pinch',
  129. //'tap', 'doubletap', 'hold',
  130. //'dragstart', 'drag', 'dragend',
  131. //'mousewheel', 'DOMMouseScroll' // DOMMouseScroll is needed for Firefox
  132. ];
  133. events.forEach(function (type) {
  134. var listener = function (event) {
  135. if (me.isActive()) {
  136. me.emit(type, event);
  137. }
  138. };
  139. me.hammer.on(type, listener);
  140. me.listeners[type] = listener;
  141. });
  142. // emulate a touch event (emitted before the start of a pan, pinch, tap, or press)
  143. hammerUtil.onTouch(this.hammer, function (event) {
  144. me.emit('touch', event);
  145. }.bind(this));
  146. // emulate a release event (emitted after a pan, pinch, tap, or press)
  147. hammerUtil.onRelease(this.hammer, function (event) {
  148. me.emit('release', event);
  149. }.bind(this));
  150. function onMouseWheel(event) {
  151. if (this.isActive()) {
  152. this.emit('mousewheel', event);
  153. }
  154. // deltaX and deltaY normalization from jquery.mousewheel.js
  155. var deltaX = 0;
  156. var deltaY = 0;
  157. // Old school scrollwheel delta
  158. if ( 'detail' in event ) { deltaY = event.detail * -1; }
  159. if ( 'wheelDelta' in event ) { deltaY = event.wheelDelta; }
  160. if ( 'wheelDeltaY' in event ) { deltaY = event.wheelDeltaY; }
  161. if ( 'wheelDeltaX' in event ) { deltaX = event.wheelDeltaX * -1; }
  162. // Firefox < 17 horizontal scrolling related to DOMMouseScroll event
  163. if ( 'axis' in event && event.axis === event.HORIZONTAL_AXIS ) {
  164. deltaX = deltaY * -1;
  165. deltaY = 0;
  166. }
  167. // New school wheel delta (wheel event)
  168. if ( 'deltaY' in event ) {
  169. deltaY = event.deltaY * -1;
  170. }
  171. if ( 'deltaX' in event ) {
  172. deltaX = event.deltaX;
  173. }
  174. // prevent scrolling when zoomKey defined or activated
  175. if (!this.options.zoomKey || event[this.options.zoomKey]) return;
  176. // Prevent default actions caused by mouse wheel
  177. // (else the page and timeline both scroll)
  178. event.preventDefault();
  179. if (this.options.verticalScroll && Math.abs(deltaY) >= Math.abs(deltaX)) {
  180. var current = this.props.scrollTop;
  181. var adjusted = current + deltaY;
  182. if (this.isActive()) {
  183. this._setScrollTop(adjusted);
  184. this._redraw();
  185. this.emit('scroll', event);
  186. }
  187. } else if (this.options.horizontalScroll) {
  188. var delta = Math.abs(deltaX) >= Math.abs(deltaY) ? deltaX : deltaY;
  189. // calculate a single scroll jump relative to the range scale
  190. var diff = (delta / 120) * (this.range.end - this.range.start) / 20;
  191. // calculate new start and end
  192. var newStart = this.range.start + diff;
  193. var newEnd = this.range.end + diff;
  194. var options = {
  195. animation: false,
  196. byUser: true,
  197. event: event
  198. }
  199. this.range.setRange(newStart, newEnd, options);
  200. }
  201. }
  202. if (this.dom.centerContainer.addEventListener) {
  203. // IE9, Chrome, Safari, Opera
  204. this.dom.centerContainer.addEventListener("mousewheel", onMouseWheel.bind(this), false);
  205. // Firefox
  206. this.dom.centerContainer.addEventListener("DOMMouseScroll", onMouseWheel.bind(this), false);
  207. } else {
  208. // IE 6/7/8
  209. this.dom.centerContainer.attachEvent("onmousewheel", onMouseWheel.bind(this));
  210. }
  211. function onMouseScrollSide(event) {
  212. if (!me.options.verticalScroll) return;
  213. event.preventDefault();
  214. if (me.isActive()) {
  215. var adjusted = -event.target.scrollTop;
  216. me._setScrollTop(adjusted);
  217. me._redraw();
  218. me.emit('scrollSide', event);
  219. }
  220. }
  221. this.dom.left.parentNode.addEventListener('scroll', onMouseScrollSide.bind(this));
  222. this.dom.right.parentNode.addEventListener('scroll', onMouseScrollSide.bind(this));
  223. var itemAddedToTimeline = false;
  224. function handleDragOver(event) {
  225. if (event.preventDefault) {
  226. event.preventDefault(); // Necessary. Allows us to drop.
  227. }
  228. // make sure your target is a vis element
  229. if (!event.target.className.indexOf("vis") > -1) return;
  230. // make sure only one item is added every time you're over the timeline
  231. if (itemAddedToTimeline) return;
  232. event.dataTransfer.dropEffect = 'move';
  233. itemAddedToTimeline = true;
  234. return false;
  235. }
  236. function handleDrop(event) {
  237. // prevent redirect to blank page - Firefox
  238. if(event.preventDefault) { event.preventDefault(); }
  239. if(event.stopPropagation) { event.stopPropagation(); }
  240. // return when dropping non-vis items
  241. try {
  242. var itemData = JSON.parse(event.dataTransfer.getData("text"))
  243. if (!itemData.content) return
  244. } catch (err) {
  245. return false;
  246. }
  247. itemAddedToTimeline = false;
  248. event.center = {
  249. x: event.clientX,
  250. y: event.clientY
  251. }
  252. me.itemSet._onAddItem(event);
  253. me.emit('drop', me.getEventProperties(event))
  254. return false;
  255. }
  256. this.dom.center.addEventListener('dragover', handleDragOver.bind(this), false);
  257. this.dom.center.addEventListener('drop', handleDrop.bind(this), false);
  258. this.customTimes = [];
  259. // store state information needed for touch events
  260. this.touch = {};
  261. this.redrawCount = 0;
  262. this.initialDrawDone = false;
  263. // attach the root panel to the provided container
  264. if (!container) throw new Error('No container provided');
  265. container.appendChild(this.dom.root);
  266. };
  267. /**
  268. * Set options. Options will be passed to all components loaded in the Timeline.
  269. * @param {Object} [options]
  270. * {String} orientation
  271. * Vertical orientation for the Timeline,
  272. * can be 'bottom' (default) or 'top'.
  273. * {String | Number} width
  274. * Width for the timeline, a number in pixels or
  275. * a css string like '1000px' or '75%'. '100%' by default.
  276. * {String | Number} height
  277. * Fixed height for the Timeline, a number in pixels or
  278. * a css string like '400px' or '75%'. If undefined,
  279. * The Timeline will automatically size such that
  280. * its contents fit.
  281. * {String | Number} minHeight
  282. * Minimum height for the Timeline, a number in pixels or
  283. * a css string like '400px' or '75%'.
  284. * {String | Number} maxHeight
  285. * Maximum height for the Timeline, a number in pixels or
  286. * a css string like '400px' or '75%'.
  287. * {Number | Date | String} start
  288. * Start date for the visible window
  289. * {Number | Date | String} end
  290. * End date for the visible window
  291. */
  292. Core.prototype.setOptions = function (options) {
  293. if (options) {
  294. // copy the known options
  295. var fields = [
  296. 'width', 'height', 'minHeight', 'maxHeight', 'autoResize',
  297. 'start', 'end', 'clickToUse', 'dataAttributes', 'hiddenDates',
  298. 'locale', 'locales', 'moment', 'rtl', 'zoomKey', 'horizontalScroll', 'verticalScroll'
  299. ];
  300. util.selectiveExtend(fields, this.options, options);
  301. this.dom.rollingModeBtn.style.visibility = 'hidden';
  302. if (this.options.rtl) {
  303. this.dom.container.style.direction = "rtl";
  304. this.dom.backgroundVertical.className = 'vis-panel vis-background vis-vertical-rtl';
  305. }
  306. if (this.options.verticalScroll) {
  307. if (this.options.rtl) {
  308. this.dom.rightContainer.className = 'vis-panel vis-right vis-vertical-scroll';
  309. } else {
  310. this.dom.leftContainer.className = 'vis-panel vis-left vis-vertical-scroll';
  311. }
  312. }
  313. this.options.orientation = {item:undefined,axis:undefined};
  314. if ('orientation' in options) {
  315. if (typeof options.orientation === 'string') {
  316. this.options.orientation = {
  317. item: options.orientation,
  318. axis: options.orientation
  319. };
  320. }
  321. else if (typeof options.orientation === 'object') {
  322. if ('item' in options.orientation) {
  323. this.options.orientation.item = options.orientation.item;
  324. }
  325. if ('axis' in options.orientation) {
  326. this.options.orientation.axis = options.orientation.axis;
  327. }
  328. }
  329. }
  330. if (this.options.orientation.axis === 'both') {
  331. if (!this.timeAxis2) {
  332. var timeAxis2 = this.timeAxis2 = new TimeAxis(this.body);
  333. timeAxis2.setOptions = function (options) {
  334. var _options = options ? util.extend({}, options) : {};
  335. _options.orientation = 'top'; // override the orientation option, always top
  336. TimeAxis.prototype.setOptions.call(timeAxis2, _options);
  337. };
  338. this.components.push(timeAxis2);
  339. }
  340. }
  341. else {
  342. if (this.timeAxis2) {
  343. var index = this.components.indexOf(this.timeAxis2);
  344. if (index !== -1) {
  345. this.components.splice(index, 1);
  346. }
  347. this.timeAxis2.destroy();
  348. this.timeAxis2 = null;
  349. }
  350. }
  351. // if the graph2d's drawPoints is a function delegate the callback to the onRender property
  352. if (typeof options.drawPoints == 'function') {
  353. options.drawPoints = {
  354. onRender: options.drawPoints
  355. };
  356. }
  357. if ('hiddenDates' in this.options) {
  358. DateUtil.convertHiddenOptions(this.options.moment, this.body, this.options.hiddenDates);
  359. }
  360. if ('clickToUse' in options) {
  361. if (options.clickToUse) {
  362. if (!this.activator) {
  363. this.activator = new Activator(this.dom.root);
  364. }
  365. }
  366. else {
  367. if (this.activator) {
  368. this.activator.destroy();
  369. delete this.activator;
  370. }
  371. }
  372. }
  373. if ('showCustomTime' in options) {
  374. throw new Error('Option `showCustomTime` is deprecated. Create a custom time bar via timeline.addCustomTime(time [, id])');
  375. }
  376. // enable/disable autoResize
  377. this._initAutoResize();
  378. }
  379. // propagate options to all components
  380. this.components.forEach(component => component.setOptions(options));
  381. // enable/disable configure
  382. if ('configure' in options) {
  383. if (!this.configurator) {
  384. this.configurator = this._createConfigurator();
  385. }
  386. this.configurator.setOptions(options.configure);
  387. // collect the settings of all components, and pass them to the configuration system
  388. var appliedOptions = util.deepExtend({}, this.options);
  389. this.components.forEach(function (component) {
  390. util.deepExtend(appliedOptions, component.options);
  391. });
  392. this.configurator.setModuleOptions({global: appliedOptions});
  393. }
  394. this._redraw();
  395. };
  396. /**
  397. * Returns true when the Timeline is active.
  398. * @returns {boolean}
  399. */
  400. Core.prototype.isActive = function () {
  401. return !this.activator || this.activator.active;
  402. };
  403. /**
  404. * Destroy the Core, clean up all DOM elements and event listeners.
  405. */
  406. Core.prototype.destroy = function () {
  407. // unbind datasets
  408. this.setItems(null);
  409. this.setGroups(null);
  410. // remove all event listeners
  411. this.off();
  412. // stop checking for changed size
  413. this._stopAutoResize();
  414. // remove from DOM
  415. if (this.dom.root.parentNode) {
  416. this.dom.root.parentNode.removeChild(this.dom.root);
  417. }
  418. this.dom = null;
  419. // remove Activator
  420. if (this.activator) {
  421. this.activator.destroy();
  422. delete this.activator;
  423. }
  424. // cleanup hammer touch events
  425. for (var event in this.listeners) {
  426. if (this.listeners.hasOwnProperty(event)) {
  427. delete this.listeners[event];
  428. }
  429. }
  430. this.listeners = null;
  431. this.hammer = null;
  432. // give all components the opportunity to cleanup
  433. this.components.forEach(component => component.destroy());
  434. this.body = null;
  435. };
  436. /**
  437. * Set a custom time bar
  438. * @param {Date} time
  439. * @param {number} [id=undefined] Optional id of the custom time bar to be adjusted.
  440. */
  441. Core.prototype.setCustomTime = function (time, id) {
  442. var customTimes = this.customTimes.filter(function (component) {
  443. return id === component.options.id;
  444. });
  445. if (customTimes.length === 0) {
  446. throw new Error('No custom time bar found with id ' + JSON.stringify(id))
  447. }
  448. if (customTimes.length > 0) {
  449. customTimes[0].setCustomTime(time);
  450. }
  451. };
  452. /**
  453. * Retrieve the current custom time.
  454. * @param {number} [id=undefined] Id of the custom time bar.
  455. * @return {Date | undefined} customTime
  456. */
  457. Core.prototype.getCustomTime = function(id) {
  458. var customTimes = this.customTimes.filter(function (component) {
  459. return component.options.id === id;
  460. });
  461. if (customTimes.length === 0) {
  462. throw new Error('No custom time bar found with id ' + JSON.stringify(id))
  463. }
  464. return customTimes[0].getCustomTime();
  465. };
  466. /**
  467. * Set a custom title for the custom time bar.
  468. * @param {String} [title] Custom title
  469. * @param {number} [id=undefined] Id of the custom time bar.
  470. */
  471. Core.prototype.setCustomTimeTitle = function(title, id) {
  472. var customTimes = this.customTimes.filter(function (component) {
  473. return component.options.id === id;
  474. });
  475. if (customTimes.length === 0) {
  476. throw new Error('No custom time bar found with id ' + JSON.stringify(id))
  477. }
  478. if (customTimes.length > 0) {
  479. return customTimes[0].setCustomTitle(title);
  480. }
  481. };
  482. /**
  483. * Retrieve meta information from an event.
  484. * Should be overridden by classes extending Core
  485. * @param {Event} event
  486. * @return {Object} An object with related information.
  487. */
  488. Core.prototype.getEventProperties = function (event) {
  489. return { event: event };
  490. };
  491. /**
  492. * Add custom vertical bar
  493. * @param {Date | String | Number} [time] A Date, unix timestamp, or
  494. * ISO date string. Time point where
  495. * the new bar should be placed.
  496. * If not provided, `new Date()` will
  497. * be used.
  498. * @param {Number | String} [id=undefined] Id of the new bar. Optional
  499. * @return {Number | String} Returns the id of the new bar
  500. */
  501. Core.prototype.addCustomTime = function (time, id) {
  502. var timestamp = time !== undefined
  503. ? util.convert(time, 'Date').valueOf()
  504. : new Date();
  505. var exists = this.customTimes.some(function (customTime) {
  506. return customTime.options.id === id;
  507. });
  508. if (exists) {
  509. throw new Error('A custom time with id ' + JSON.stringify(id) + ' already exists');
  510. }
  511. var customTime = new CustomTime(this.body, util.extend({}, this.options, {
  512. time : timestamp,
  513. id : id
  514. }));
  515. this.customTimes.push(customTime);
  516. this.components.push(customTime);
  517. this._redraw();
  518. return id;
  519. };
  520. /**
  521. * Remove previously added custom bar
  522. * @param {int} id ID of the custom bar to be removed
  523. * @return {boolean} True if the bar exists and is removed, false otherwise
  524. */
  525. Core.prototype.removeCustomTime = function (id) {
  526. var customTimes = this.customTimes.filter(function (bar) {
  527. return (bar.options.id === id);
  528. });
  529. if (customTimes.length === 0) {
  530. throw new Error('No custom time bar found with id ' + JSON.stringify(id))
  531. }
  532. customTimes.forEach(function (customTime) {
  533. this.customTimes.splice(this.customTimes.indexOf(customTime), 1);
  534. this.components.splice(this.components.indexOf(customTime), 1);
  535. customTime.destroy();
  536. }.bind(this))
  537. };
  538. /**
  539. * Get the id's of the currently visible items.
  540. * @returns {Array} The ids of the visible items
  541. */
  542. Core.prototype.getVisibleItems = function() {
  543. return this.itemSet && this.itemSet.getVisibleItems() || [];
  544. };
  545. /**
  546. * Set Core window such that it fits all items
  547. * @param {Object} [options] Available options:
  548. * `animation: boolean | {duration: number, easingFunction: string}`
  549. * If true (default), the range is animated
  550. * smoothly to the new window. An object can be
  551. * provided to specify duration and easing function.
  552. * Default duration is 500 ms, and default easing
  553. * function is 'easeInOutQuad'.
  554. * @param {Function} a callback funtion to be executed at the end of this function
  555. */
  556. Core.prototype.fit = function(options, callback) {
  557. var range = this.getDataRange();
  558. // skip range set if there is no min and max date
  559. if (range.min === null && range.max === null) {
  560. return;
  561. }
  562. // apply a margin of 1% left and right of the data
  563. var interval = range.max - range.min;
  564. var min = new Date(range.min.valueOf() - interval * 0.01);
  565. var max = new Date(range.max.valueOf() + interval * 0.01);
  566. var animation = (options && options.animation !== undefined) ? options.animation : true;
  567. this.range.setRange(min, max, { animation: animation }, callback);
  568. };
  569. /**
  570. * Calculate the data range of the items start and end dates
  571. * @returns {{min: Date | null, max: Date | null}}
  572. * @protected
  573. */
  574. Core.prototype.getDataRange = function() {
  575. // must be implemented by Timeline and Graph2d
  576. throw new Error('Cannot invoke abstract method getDataRange');
  577. };
  578. /**
  579. * Set the visible window. Both parameters are optional, you can change only
  580. * start or only end. Syntax:
  581. *
  582. * TimeLine.setWindow(start, end)
  583. * TimeLine.setWindow(start, end, options)
  584. * TimeLine.setWindow(range)
  585. *
  586. * Where start and end can be a Date, number, or string, and range is an
  587. * object with properties start and end.
  588. *
  589. * @param {Date | Number | String | Object} [start] Start date of visible window
  590. * @param {Date | Number | String} [end] End date of visible window
  591. * @param {Object} [options] Available options:
  592. * `animation: boolean | {duration: number, easingFunction: string}`
  593. * If true (default), the range is animated
  594. * smoothly to the new window. An object can be
  595. * provided to specify duration and easing function.
  596. * Default duration is 500 ms, and default easing
  597. * function is 'easeInOutQuad'.
  598. * @param {Function} a callback funtion to be executed at the end of this function
  599. */
  600. Core.prototype.setWindow = function(start, end, options, callback) {
  601. if (typeof arguments[2] == "function") {
  602. callback = arguments[2]
  603. options = {};
  604. }
  605. var animation;
  606. var range;
  607. if (arguments.length == 1) {
  608. range = arguments[0];
  609. animation = (range.animation !== undefined) ? range.animation : true;
  610. this.range.setRange(range.start, range.end, { animation: animation });
  611. }
  612. else if (arguments.length == 2 && typeof arguments[1] == "function") {
  613. range = arguments[0];
  614. callback = arguments[1];
  615. animation = (range.animation !== undefined) ? range.animation : true;
  616. this.range.setRange(range.start, range.end, { animation: animation }, callback);
  617. }
  618. else {
  619. animation = (options && options.animation !== undefined) ? options.animation : true;
  620. this.range.setRange(start, end, { animation: animation }, callback);
  621. }
  622. };
  623. /**
  624. * Move the window such that given time is centered on screen.
  625. * @param {Date | Number | String} time
  626. * @param {Object} [options] Available options:
  627. * `animation: boolean | {duration: number, easingFunction: string}`
  628. * If true (default), the range is animated
  629. * smoothly to the new window. An object can be
  630. * provided to specify duration and easing function.
  631. * Default duration is 500 ms, and default easing
  632. * function is 'easeInOutQuad'.
  633. * @param {Function} a callback funtion to be executed at the end of this function
  634. */
  635. Core.prototype.moveTo = function(time, options, callback) {
  636. if (typeof arguments[1] == "function") {
  637. callback = arguments[1]
  638. options = {};
  639. }
  640. var interval = this.range.end - this.range.start;
  641. var t = util.convert(time, 'Date').valueOf();
  642. var start = t - interval / 2;
  643. var end = t + interval / 2;
  644. var animation = (options && options.animation !== undefined) ? options.animation : true;
  645. this.range.setRange(start, end, { animation: animation }, callback);
  646. };
  647. /**
  648. * Get the visible window
  649. * @return {{start: Date, end: Date}} Visible range
  650. */
  651. Core.prototype.getWindow = function() {
  652. var range = this.range.getRange();
  653. return {
  654. start: new Date(range.start),
  655. end: new Date(range.end)
  656. };
  657. };
  658. /**
  659. * Zoom in the window such that given time is centered on screen.
  660. * @param {Number} percentage - must be between [0..1]
  661. * @param {Object} [options] Available options:
  662. * `animation: boolean | {duration: number, easingFunction: string}`
  663. * If true (default), the range is animated
  664. * smoothly to the new window. An object can be
  665. * provided to specify duration and easing function.
  666. * Default duration is 500 ms, and default easing
  667. * function is 'easeInOutQuad'.
  668. * @param {Function} a callback funtion to be executed at the end of this function
  669. */
  670. Core.prototype.zoomIn = function(percentage, options, callback) {
  671. if (!percentage || percentage < 0 || percentage > 1) return
  672. if (typeof arguments[1] == "function") {
  673. callback = arguments[1]
  674. options = {};
  675. }
  676. var range = this.getWindow();
  677. var start = range.start.valueOf();
  678. var end = range.end.valueOf();
  679. var interval = end - start;
  680. var newInterval = interval / (1 + percentage);
  681. var distance = (interval - newInterval) / 2;
  682. var newStart = start + distance;
  683. var newEnd = end - distance;
  684. this.setWindow(newStart, newEnd, options, callback);
  685. };
  686. /**
  687. * Zoom out the window such that given time is centered on screen.
  688. * @param {Number} percentage - must be between [0..1]
  689. * @param {Object} [options] Available options:
  690. * `animation: boolean | {duration: number, easingFunction: string}`
  691. * If true (default), the range is animated
  692. * smoothly to the new window. An object can be
  693. * provided to specify duration and easing function.
  694. * Default duration is 500 ms, and default easing
  695. * function is 'easeInOutQuad'.
  696. * @param {Function} a callback funtion to be executed at the end of this function
  697. */
  698. Core.prototype.zoomOut = function(percentage, options, callback) {
  699. if (!percentage || percentage < 0 || percentage > 1) return
  700. if (typeof arguments[1] == "function") {
  701. callback = arguments[1]
  702. options = {};
  703. }
  704. var range = this.getWindow();
  705. var start = range.start.valueOf();
  706. var end = range.end.valueOf();
  707. var interval = end - start;
  708. var newStart = start - interval * percentage / 2;
  709. var newEnd = end + interval * percentage / 2;
  710. this.setWindow(newStart, newEnd, options, callback);
  711. };
  712. /**
  713. * Force a redraw. Can be overridden by implementations of Core
  714. *
  715. * Note: this function will be overridden on construction with a trottled version
  716. */
  717. Core.prototype.redraw = function() {
  718. this._redraw();
  719. };
  720. /**
  721. * Redraw for internal use. Redraws all components. See also the public
  722. * method redraw.
  723. * @protected
  724. */
  725. Core.prototype._redraw = function() {
  726. this.redrawCount++;
  727. var resized = false;
  728. var options = this.options;
  729. var props = this.props;
  730. var dom = this.dom;
  731. if (!dom || !dom.container || dom.root.offsetWidth == 0) return; // when destroyed, or invisible
  732. DateUtil.updateHiddenDates(this.options.moment, this.body, this.options.hiddenDates);
  733. // update class names
  734. if (options.orientation == 'top') {
  735. util.addClassName(dom.root, 'vis-top');
  736. util.removeClassName(dom.root, 'vis-bottom');
  737. }
  738. else {
  739. util.removeClassName(dom.root, 'vis-top');
  740. util.addClassName(dom.root, 'vis-bottom');
  741. }
  742. // update root width and height options
  743. dom.root.style.maxHeight = util.option.asSize(options.maxHeight, '');
  744. dom.root.style.minHeight = util.option.asSize(options.minHeight, '');
  745. dom.root.style.width = util.option.asSize(options.width, '');
  746. // calculate border widths
  747. props.border.left = (dom.centerContainer.offsetWidth - dom.centerContainer.clientWidth) / 2;
  748. props.border.right = props.border.left;
  749. props.border.top = (dom.centerContainer.offsetHeight - dom.centerContainer.clientHeight) / 2;
  750. props.border.bottom = props.border.top;
  751. props.borderRootHeight= dom.root.offsetHeight - dom.root.clientHeight;
  752. props.borderRootWidth = dom.root.offsetWidth - dom.root.clientWidth;
  753. // workaround for a bug in IE: the clientWidth of an element with
  754. // a height:0px and overflow:hidden is not calculated and always has value 0
  755. if (dom.centerContainer.clientHeight === 0) {
  756. props.border.left = props.border.top;
  757. props.border.right = props.border.left;
  758. }
  759. if (dom.root.clientHeight === 0) {
  760. props.borderRootWidth = props.borderRootHeight;
  761. }
  762. // calculate the heights. If any of the side panels is empty, we set the height to
  763. // minus the border width, such that the border will be invisible
  764. props.center.height = dom.center.offsetHeight;
  765. props.left.height = dom.left.offsetHeight;
  766. props.right.height = dom.right.offsetHeight;
  767. props.top.height = dom.top.clientHeight || -props.border.top;
  768. props.bottom.height = dom.bottom.clientHeight || -props.border.bottom;
  769. // TODO: compensate borders when any of the panels is empty.
  770. // apply auto height
  771. // TODO: only calculate autoHeight when needed (else we cause an extra reflow/repaint of the DOM)
  772. var contentHeight = Math.max(props.left.height, props.center.height, props.right.height);
  773. var autoHeight = props.top.height + contentHeight + props.bottom.height +
  774. props.borderRootHeight + props.border.top + props.border.bottom;
  775. dom.root.style.height = util.option.asSize(options.height, autoHeight + 'px');
  776. // calculate heights of the content panels
  777. props.root.height = dom.root.offsetHeight;
  778. props.background.height = props.root.height - props.borderRootHeight;
  779. var containerHeight = props.root.height - props.top.height - props.bottom.height -
  780. props.borderRootHeight;
  781. props.centerContainer.height = containerHeight;
  782. props.leftContainer.height = containerHeight;
  783. props.rightContainer.height = props.leftContainer.height;
  784. // calculate the widths of the panels
  785. props.root.width = dom.root.offsetWidth;
  786. props.background.width = props.root.width - props.borderRootWidth;
  787. if (!this.initialDrawDone) {
  788. props.scrollbarWidth = util.getScrollBarWidth();
  789. }
  790. if (options.verticalScroll) {
  791. if (options.rtl) {
  792. props.left.width = dom.leftContainer.clientWidth || -props.border.left;
  793. props.right.width = dom.rightContainer.clientWidth + props.scrollbarWidth || -props.border.right;
  794. } else {
  795. props.left.width = dom.leftContainer.clientWidth + props.scrollbarWidth || -props.border.left;
  796. props.right.width = dom.rightContainer.clientWidth || -props.border.right;
  797. }
  798. } else {
  799. props.left.width = dom.leftContainer.clientWidth || -props.border.left;
  800. props.right.width = dom.rightContainer.clientWidth || -props.border.right;
  801. }
  802. this._setDOM();
  803. // update the scrollTop, feasible range for the offset can be changed
  804. // when the height of the Core or of the contents of the center changed
  805. var offset = this._updateScrollTop();
  806. // reposition the scrollable contents
  807. if (options.orientation.item != 'top') {
  808. offset += Math.max(props.centerContainer.height - props.center.height -
  809. props.border.top - props.border.bottom, 0);
  810. }
  811. dom.center.style.top = offset + 'px';
  812. // show shadows when vertical scrolling is available
  813. var visibilityTop = props.scrollTop == 0 ? 'hidden' : '';
  814. var visibilityBottom = props.scrollTop == props.scrollTopMin ? 'hidden' : '';
  815. dom.shadowTop.style.visibility = visibilityTop;
  816. dom.shadowBottom.style.visibility = visibilityBottom;
  817. dom.shadowTopLeft.style.visibility = visibilityTop;
  818. dom.shadowBottomLeft.style.visibility = visibilityBottom;
  819. dom.shadowTopRight.style.visibility = visibilityTop;
  820. dom.shadowBottomRight.style.visibility = visibilityBottom;
  821. if (options.verticalScroll) {
  822. dom.rightContainer.className = 'vis-panel vis-right vis-vertical-scroll';
  823. dom.leftContainer.className = 'vis-panel vis-left vis-vertical-scroll';
  824. dom.shadowTopRight.style.visibility = "hidden";
  825. dom.shadowBottomRight.style.visibility = "hidden";
  826. dom.shadowTopLeft.style.visibility = "hidden";
  827. dom.shadowBottomLeft.style.visibility = "hidden";
  828. dom.left.style.top = '0px';
  829. dom.right.style.top = '0px';
  830. }
  831. if (!options.verticalScroll || props.center.height < props.centerContainer.height) {
  832. dom.left.style.top = offset + 'px';
  833. dom.right.style.top = offset + 'px';
  834. dom.rightContainer.className = dom.rightContainer.className.replace(new RegExp('(?:^|\\s)'+ 'vis-vertical-scroll' + '(?:\\s|$)'), ' ');
  835. dom.leftContainer.className = dom.leftContainer.className.replace(new RegExp('(?:^|\\s)'+ 'vis-vertical-scroll' + '(?:\\s|$)'), ' ');
  836. props.left.width = dom.leftContainer.clientWidth || -props.border.left;
  837. props.right.width = dom.rightContainer.clientWidth || -props.border.right;
  838. this._setDOM();
  839. }
  840. // enable/disable vertical panning
  841. var contentsOverflow = props.center.height > props.centerContainer.height;
  842. this.hammer.get('pan').set({
  843. direction: contentsOverflow ? Hammer.DIRECTION_ALL : Hammer.DIRECTION_HORIZONTAL
  844. });
  845. // redraw all components
  846. this.components.forEach(function (component) {
  847. resized = component.redraw() || resized;
  848. });
  849. var MAX_REDRAW = 5;
  850. if (resized) {
  851. if (this.redrawCount < MAX_REDRAW) {
  852. this.body.emitter.emit('_change');
  853. return;
  854. }
  855. else {
  856. console.log('WARNING: infinite loop in redraw?');
  857. }
  858. } else {
  859. this.redrawCount = 0;
  860. }
  861. this.initialDrawDone = true;
  862. //Emit public 'changed' event for UI updates, see issue #1592
  863. this.body.emitter.emit("changed");
  864. };
  865. Core.prototype._setDOM = function () {
  866. var props = this.props;
  867. var dom = this.dom;
  868. props.leftContainer.width = props.left.width;
  869. props.rightContainer.width = props.right.width;
  870. var centerWidth = props.root.width - props.left.width - props.right.width - props.borderRootWidth;
  871. props.center.width = centerWidth;
  872. props.centerContainer.width = centerWidth;
  873. props.top.width = centerWidth;
  874. props.bottom.width = centerWidth;
  875. // resize the panels
  876. dom.background.style.height = props.background.height + 'px';
  877. dom.backgroundVertical.style.height = props.background.height + 'px';
  878. dom.backgroundHorizontal.style.height = props.centerContainer.height + 'px';
  879. dom.centerContainer.style.height = props.centerContainer.height + 'px';
  880. dom.leftContainer.style.height = props.leftContainer.height + 'px';
  881. dom.rightContainer.style.height = props.rightContainer.height + 'px';
  882. dom.background.style.width = props.background.width + 'px';
  883. dom.backgroundVertical.style.width = props.centerContainer.width + 'px';
  884. dom.backgroundHorizontal.style.width = props.background.width + 'px';
  885. dom.centerContainer.style.width = props.center.width + 'px';
  886. dom.top.style.width = props.top.width + 'px';
  887. dom.bottom.style.width = props.bottom.width + 'px';
  888. // reposition the panels
  889. dom.background.style.left = '0';
  890. dom.background.style.top = '0';
  891. dom.backgroundVertical.style.left = (props.left.width + props.border.left) + 'px';
  892. dom.backgroundVertical.style.top = '0';
  893. dom.backgroundHorizontal.style.left = '0';
  894. dom.backgroundHorizontal.style.top = props.top.height + 'px';
  895. dom.centerContainer.style.left = props.left.width + 'px';
  896. dom.centerContainer.style.top = props.top.height + 'px';
  897. dom.leftContainer.style.left = '0';
  898. dom.leftContainer.style.top = props.top.height + 'px';
  899. dom.rightContainer.style.left = (props.left.width + props.center.width) + 'px';
  900. dom.rightContainer.style.top = props.top.height + 'px';
  901. dom.top.style.left = props.left.width + 'px';
  902. dom.top.style.top = '0';
  903. dom.bottom.style.left = props.left.width + 'px';
  904. dom.bottom.style.top = (props.top.height + props.centerContainer.height) + 'px';
  905. dom.center.style.left = '0';
  906. dom.left.style.left = '0';
  907. dom.right.style.left = '0';
  908. }
  909. // TODO: deprecated since version 1.1.0, remove some day
  910. Core.prototype.repaint = function () {
  911. throw new Error('Function repaint is deprecated. Use redraw instead.');
  912. };
  913. /**
  914. * Set a current time. This can be used for example to ensure that a client's
  915. * time is synchronized with a shared server time.
  916. * Only applicable when option `showCurrentTime` is true.
  917. * @param {Date | String | Number} time A Date, unix timestamp, or
  918. * ISO date string.
  919. */
  920. Core.prototype.setCurrentTime = function(time) {
  921. if (!this.currentTime) {
  922. throw new Error('Option showCurrentTime must be true');
  923. }
  924. this.currentTime.setCurrentTime(time);
  925. };
  926. /**
  927. * Get the current time.
  928. * Only applicable when option `showCurrentTime` is true.
  929. * @return {Date} Returns the current time.
  930. */
  931. Core.prototype.getCurrentTime = function() {
  932. if (!this.currentTime) {
  933. throw new Error('Option showCurrentTime must be true');
  934. }
  935. return this.currentTime.getCurrentTime();
  936. };
  937. /**
  938. * Convert a position on screen (pixels) to a datetime
  939. * @param {int} x Position on the screen in pixels
  940. * @return {Date} time The datetime the corresponds with given position x
  941. * @protected
  942. */
  943. // TODO: move this function to Range
  944. Core.prototype._toTime = function(x) {
  945. return DateUtil.toTime(this, x, this.props.center.width);
  946. };
  947. /**
  948. * Convert a position on the global screen (pixels) to a datetime
  949. * @param {int} x Position on the screen in pixels
  950. * @return {Date} time The datetime the corresponds with given position x
  951. * @protected
  952. */
  953. // TODO: move this function to Range
  954. Core.prototype._toGlobalTime = function(x) {
  955. return DateUtil.toTime(this, x, this.props.root.width);
  956. //var conversion = this.range.conversion(this.props.root.width);
  957. //return new Date(x / conversion.scale + conversion.offset);
  958. };
  959. /**
  960. * Convert a datetime (Date object) into a position on the screen
  961. * @param {Date} time A date
  962. * @return {int} x The position on the screen in pixels which corresponds
  963. * with the given date.
  964. * @protected
  965. */
  966. // TODO: move this function to Range
  967. Core.prototype._toScreen = function(time) {
  968. return DateUtil.toScreen(this, time, this.props.center.width);
  969. };
  970. /**
  971. * Convert a datetime (Date object) into a position on the root
  972. * This is used to get the pixel density estimate for the screen, not the center panel
  973. * @param {Date} time A date
  974. * @return {int} x The position on root in pixels which corresponds
  975. * with the given date.
  976. * @protected
  977. */
  978. // TODO: move this function to Range
  979. Core.prototype._toGlobalScreen = function(time) {
  980. return DateUtil.toScreen(this, time, this.props.root.width);
  981. //var conversion = this.range.conversion(this.props.root.width);
  982. //return (time.valueOf() - conversion.offset) * conversion.scale;
  983. };
  984. /**
  985. * Initialize watching when option autoResize is true
  986. * @private
  987. */
  988. Core.prototype._initAutoResize = function () {
  989. if (this.options.autoResize == true) {
  990. this._startAutoResize();
  991. }
  992. else {
  993. this._stopAutoResize();
  994. }
  995. };
  996. /**
  997. * Watch for changes in the size of the container. On resize, the Panel will
  998. * automatically redraw itself.
  999. * @private
  1000. */
  1001. Core.prototype._startAutoResize = function () {
  1002. var me = this;
  1003. this._stopAutoResize();
  1004. this._onResize = function() {
  1005. if (me.options.autoResize != true) {
  1006. // stop watching when the option autoResize is changed to false
  1007. me._stopAutoResize();
  1008. return;
  1009. }
  1010. if (me.dom.root) {
  1011. // check whether the frame is resized
  1012. // Note: we compare offsetWidth here, not clientWidth. For some reason,
  1013. // IE does not restore the clientWidth from 0 to the actual width after
  1014. // changing the timeline's container display style from none to visible
  1015. if ((me.dom.root.offsetWidth != me.props.lastWidth) ||
  1016. (me.dom.root.offsetHeight != me.props.lastHeight)) {
  1017. me.props.lastWidth = me.dom.root.offsetWidth;
  1018. me.props.lastHeight = me.dom.root.offsetHeight;
  1019. me.props.scrollbarWidth = util.getScrollBarWidth();
  1020. me.body.emitter.emit('_change');
  1021. }
  1022. }
  1023. };
  1024. // add event listener to window resize
  1025. util.addEventListener(window, 'resize', this._onResize);
  1026. //Prevent initial unnecessary redraw
  1027. if (me.dom.root) {
  1028. me.props.lastWidth = me.dom.root.offsetWidth;
  1029. me.props.lastHeight = me.dom.root.offsetHeight;
  1030. }
  1031. this.watchTimer = setInterval(this._onResize, 1000);
  1032. };
  1033. /**
  1034. * Stop watching for a resize of the frame.
  1035. * @private
  1036. */
  1037. Core.prototype._stopAutoResize = function () {
  1038. if (this.watchTimer) {
  1039. clearInterval(this.watchTimer);
  1040. this.watchTimer = undefined;
  1041. }
  1042. // remove event listener on window.resize
  1043. if (this._onResize) {
  1044. util.removeEventListener(window, 'resize', this._onResize);
  1045. this._onResize = null;
  1046. }
  1047. };
  1048. /**
  1049. * Start moving the timeline vertically
  1050. * @param {Event} event
  1051. * @private
  1052. */
  1053. Core.prototype._onTouch = function (event) { // eslint-disable-line no-unused-vars
  1054. this.touch.allowDragging = true;
  1055. this.touch.initialScrollTop = this.props.scrollTop;
  1056. };
  1057. /**
  1058. * Start moving the timeline vertically
  1059. * @param {Event} event
  1060. * @private
  1061. */
  1062. Core.prototype._onPinch = function (event) { // eslint-disable-line no-unused-vars
  1063. this.touch.allowDragging = false;
  1064. };
  1065. /**
  1066. * Move the timeline vertically
  1067. * @param {Event} event
  1068. * @private
  1069. */
  1070. Core.prototype._onDrag = function (event) {
  1071. if (!event) return
  1072. // refuse to drag when we where pinching to prevent the timeline make a jump
  1073. // when releasing the fingers in opposite order from the touch screen
  1074. if (!this.touch.allowDragging) return;
  1075. var delta = event.deltaY;
  1076. var oldScrollTop = this._getScrollTop();
  1077. var newScrollTop = this._setScrollTop(this.touch.initialScrollTop + delta);
  1078. if (this.options.verticalScroll) {
  1079. this.dom.left.parentNode.scrollTop = -this.props.scrollTop;
  1080. this.dom.right.parentNode.scrollTop = -this.props.scrollTop;
  1081. }
  1082. if (newScrollTop != oldScrollTop) {
  1083. this.emit("verticalDrag");
  1084. }
  1085. };
  1086. /**
  1087. * Apply a scrollTop
  1088. * @param {Number} scrollTop
  1089. * @returns {Number} scrollTop Returns the applied scrollTop
  1090. * @private
  1091. */
  1092. Core.prototype._setScrollTop = function (scrollTop) {
  1093. this.props.scrollTop = scrollTop;
  1094. this._updateScrollTop();
  1095. return this.props.scrollTop;
  1096. };
  1097. /**
  1098. * Update the current scrollTop when the height of the containers has been changed
  1099. * @returns {Number} scrollTop Returns the applied scrollTop
  1100. * @private
  1101. */
  1102. Core.prototype._updateScrollTop = function () {
  1103. // recalculate the scrollTopMin
  1104. var scrollTopMin = Math.min(this.props.centerContainer.height - this.props.center.height, 0); // is negative or zero
  1105. if (scrollTopMin != this.props.scrollTopMin) {
  1106. // in case of bottom orientation, change the scrollTop such that the contents
  1107. // do not move relative to the time axis at the bottom
  1108. if (this.options.orientation.item != 'top') {
  1109. this.props.scrollTop += (scrollTopMin - this.props.scrollTopMin);
  1110. }
  1111. this.props.scrollTopMin = scrollTopMin;
  1112. }
  1113. // limit the scrollTop to the feasible scroll range
  1114. if (this.props.scrollTop > 0) this.props.scrollTop = 0;
  1115. if (this.props.scrollTop < scrollTopMin) this.props.scrollTop = scrollTopMin;
  1116. if (this.options.verticalScroll) {
  1117. this.dom.left.parentNode.scrollTop = -this.props.scrollTop;
  1118. this.dom.right.parentNode.scrollTop = -this.props.scrollTop;
  1119. }
  1120. return this.props.scrollTop;
  1121. };
  1122. /**
  1123. * Get the current scrollTop
  1124. * @returns {number} scrollTop
  1125. * @private
  1126. */
  1127. Core.prototype._getScrollTop = function () {
  1128. return this.props.scrollTop;
  1129. };
  1130. /**
  1131. * Load a configurator
  1132. * @return {Object}
  1133. * @private
  1134. */
  1135. Core.prototype._createConfigurator = function () {
  1136. throw new Error('Cannot invoke abstract method _createConfigurator');
  1137. };
  1138. module.exports = Core;