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.

662 lines
22 KiB

  1. var Emitter = require('emitter-component');
  2. var Hammer = require('../module/hammer');
  3. var util = require('../util');
  4. var DataSet = require('../DataSet');
  5. var DataView = require('../DataView');
  6. var Range = require('./Range');
  7. var TimeAxis = require('./component/TimeAxis');
  8. var CurrentTime = require('./component/CurrentTime');
  9. var CustomTime = require('./component/CustomTime');
  10. var ItemSet = require('./component/ItemSet');
  11. /**
  12. * Create a timeline visualization
  13. * @param {HTMLElement} container
  14. * @param {vis.DataSet | Array | google.visualization.DataTable} [items]
  15. * @param {Object} [options] See Core.setOptions for the available options.
  16. * @constructor
  17. */
  18. function Core () {}
  19. // turn Core into an event emitter
  20. Emitter(Core.prototype);
  21. /**
  22. * Create the main DOM for the Core: a root panel containing left, right,
  23. * top, bottom, content, and background panel.
  24. * @param {Element} container The container element where the Core will
  25. * be attached.
  26. * @private
  27. */
  28. Core.prototype._create = function (container) {
  29. this.dom = {};
  30. this.dom.root = document.createElement('div');
  31. this.dom.background = document.createElement('div');
  32. this.dom.backgroundVertical = document.createElement('div');
  33. this.dom.backgroundHorizontal = document.createElement('div');
  34. this.dom.centerContainer = document.createElement('div');
  35. this.dom.leftContainer = document.createElement('div');
  36. this.dom.rightContainer = document.createElement('div');
  37. this.dom.center = document.createElement('div');
  38. this.dom.left = document.createElement('div');
  39. this.dom.right = document.createElement('div');
  40. this.dom.top = document.createElement('div');
  41. this.dom.bottom = document.createElement('div');
  42. this.dom.shadowTop = document.createElement('div');
  43. this.dom.shadowBottom = document.createElement('div');
  44. this.dom.shadowTopLeft = document.createElement('div');
  45. this.dom.shadowBottomLeft = document.createElement('div');
  46. this.dom.shadowTopRight = document.createElement('div');
  47. this.dom.shadowBottomRight = document.createElement('div');
  48. this.dom.background.className = 'vispanel background';
  49. this.dom.backgroundVertical.className = 'vispanel background vertical';
  50. this.dom.backgroundHorizontal.className = 'vispanel background horizontal';
  51. this.dom.centerContainer.className = 'vispanel center';
  52. this.dom.leftContainer.className = 'vispanel left';
  53. this.dom.rightContainer.className = 'vispanel right';
  54. this.dom.top.className = 'vispanel top';
  55. this.dom.bottom.className = 'vispanel bottom';
  56. this.dom.left.className = 'content';
  57. this.dom.center.className = 'content';
  58. this.dom.right.className = 'content';
  59. this.dom.shadowTop.className = 'shadow top';
  60. this.dom.shadowBottom.className = 'shadow bottom';
  61. this.dom.shadowTopLeft.className = 'shadow top';
  62. this.dom.shadowBottomLeft.className = 'shadow bottom';
  63. this.dom.shadowTopRight.className = 'shadow top';
  64. this.dom.shadowBottomRight.className = 'shadow bottom';
  65. this.dom.root.appendChild(this.dom.background);
  66. this.dom.root.appendChild(this.dom.backgroundVertical);
  67. this.dom.root.appendChild(this.dom.backgroundHorizontal);
  68. this.dom.root.appendChild(this.dom.centerContainer);
  69. this.dom.root.appendChild(this.dom.leftContainer);
  70. this.dom.root.appendChild(this.dom.rightContainer);
  71. this.dom.root.appendChild(this.dom.top);
  72. this.dom.root.appendChild(this.dom.bottom);
  73. this.dom.centerContainer.appendChild(this.dom.center);
  74. this.dom.leftContainer.appendChild(this.dom.left);
  75. this.dom.rightContainer.appendChild(this.dom.right);
  76. this.dom.centerContainer.appendChild(this.dom.shadowTop);
  77. this.dom.centerContainer.appendChild(this.dom.shadowBottom);
  78. this.dom.leftContainer.appendChild(this.dom.shadowTopLeft);
  79. this.dom.leftContainer.appendChild(this.dom.shadowBottomLeft);
  80. this.dom.rightContainer.appendChild(this.dom.shadowTopRight);
  81. this.dom.rightContainer.appendChild(this.dom.shadowBottomRight);
  82. this.on('rangechange', this.redraw.bind(this));
  83. this.on('change', this.redraw.bind(this));
  84. this.on('touch', this._onTouch.bind(this));
  85. this.on('pinch', this._onPinch.bind(this));
  86. this.on('dragstart', this._onDragStart.bind(this));
  87. this.on('drag', this._onDrag.bind(this));
  88. // create event listeners for all interesting events, these events will be
  89. // emitted via emitter
  90. this.hammer = Hammer(this.dom.root, {
  91. prevent_default: true
  92. });
  93. this.listeners = {};
  94. var me = this;
  95. var events = [
  96. 'touch', 'pinch',
  97. 'tap', 'doubletap', 'hold',
  98. 'dragstart', 'drag', 'dragend',
  99. 'mousewheel', 'DOMMouseScroll' // DOMMouseScroll is needed for Firefox
  100. ];
  101. events.forEach(function (event) {
  102. var listener = function () {
  103. var args = [event].concat(Array.prototype.slice.call(arguments, 0));
  104. me.emit.apply(me, args);
  105. };
  106. me.hammer.on(event, listener);
  107. me.listeners[event] = listener;
  108. });
  109. // size properties of each of the panels
  110. this.props = {
  111. root: {},
  112. background: {},
  113. centerContainer: {},
  114. leftContainer: {},
  115. rightContainer: {},
  116. center: {},
  117. left: {},
  118. right: {},
  119. top: {},
  120. bottom: {},
  121. border: {},
  122. scrollTop: 0,
  123. scrollTopMin: 0
  124. };
  125. this.touch = {}; // store state information needed for touch events
  126. // attach the root panel to the provided container
  127. if (!container) throw new Error('No container provided');
  128. container.appendChild(this.dom.root);
  129. };
  130. /**
  131. * Destroy the Core, clean up all DOM elements and event listeners.
  132. */
  133. Core.prototype.destroy = function () {
  134. // unbind datasets
  135. this.clear();
  136. // remove all event listeners
  137. this.off();
  138. // stop checking for changed size
  139. this._stopAutoResize();
  140. // remove from DOM
  141. if (this.dom.root.parentNode) {
  142. this.dom.root.parentNode.removeChild(this.dom.root);
  143. }
  144. this.dom = null;
  145. // cleanup hammer touch events
  146. for (var event in this.listeners) {
  147. if (this.listeners.hasOwnProperty(event)) {
  148. delete this.listeners[event];
  149. }
  150. }
  151. this.listeners = null;
  152. this.hammer = null;
  153. // give all components the opportunity to cleanup
  154. this.components.forEach(function (component) {
  155. component.destroy();
  156. });
  157. this.body = null;
  158. };
  159. /**
  160. * Set a custom time bar
  161. * @param {Date} time
  162. */
  163. Core.prototype.setCustomTime = function (time) {
  164. if (!this.customTime) {
  165. throw new Error('Cannot get custom time: Custom time bar is not enabled');
  166. }
  167. this.customTime.setCustomTime(time);
  168. };
  169. /**
  170. * Retrieve the current custom time.
  171. * @return {Date} customTime
  172. */
  173. Core.prototype.getCustomTime = function() {
  174. if (!this.customTime) {
  175. throw new Error('Cannot get custom time: Custom time bar is not enabled');
  176. }
  177. return this.customTime.getCustomTime();
  178. };
  179. /**
  180. * Get the id's of the currently visible items.
  181. * @returns {Array} The ids of the visible items
  182. */
  183. Core.prototype.getVisibleItems = function() {
  184. return this.itemSet && this.itemSet.getVisibleItems() || [];
  185. };
  186. /**
  187. * Clear the Core. By Default, items, groups and options are cleared.
  188. * Example usage:
  189. *
  190. * timeline.clear(); // clear items, groups, and options
  191. * timeline.clear({options: true}); // clear options only
  192. *
  193. * @param {Object} [what] Optionally specify what to clear. By default:
  194. * {items: true, groups: true, options: true}
  195. */
  196. Core.prototype.clear = function(what) {
  197. // clear items
  198. if (!what || what.items) {
  199. this.setItems(null);
  200. }
  201. // clear groups
  202. if (!what || what.groups) {
  203. this.setGroups(null);
  204. }
  205. // clear options of timeline and of each of the components
  206. if (!what || what.options) {
  207. this.components.forEach(function (component) {
  208. component.setOptions(component.defaultOptions);
  209. });
  210. this.setOptions(this.defaultOptions); // this will also do a redraw
  211. }
  212. };
  213. /**
  214. * Set Core window such that it fits all items
  215. */
  216. Core.prototype.fit = function() {
  217. // apply the data range as range
  218. var dataRange = this.getItemRange();
  219. // add 5% space on both sides
  220. var start = dataRange.min;
  221. var end = dataRange.max;
  222. if (start != null && end != null) {
  223. var interval = (end.valueOf() - start.valueOf());
  224. if (interval <= 0) {
  225. // prevent an empty interval
  226. interval = 24 * 60 * 60 * 1000; // 1 day
  227. }
  228. start = new Date(start.valueOf() - interval * 0.05);
  229. end = new Date(end.valueOf() + interval * 0.05);
  230. }
  231. // skip range set if there is no start and end date
  232. if (start === null && end === null) {
  233. return;
  234. }
  235. this.range.setRange(start, end);
  236. };
  237. /**
  238. * Set the visible window. Both parameters are optional, you can change only
  239. * start or only end. Syntax:
  240. *
  241. * TimeLine.setWindow(start, end)
  242. * TimeLine.setWindow(range)
  243. *
  244. * Where start and end can be a Date, number, or string, and range is an
  245. * object with properties start and end.
  246. *
  247. * @param {Date | Number | String | Object} [start] Start date of visible window
  248. * @param {Date | Number | String} [end] End date of visible window
  249. */
  250. Core.prototype.setWindow = function(start, end) {
  251. if (arguments.length == 1) {
  252. var range = arguments[0];
  253. this.range.setRange(range.start, range.end);
  254. }
  255. else {
  256. this.range.setRange(start, end);
  257. }
  258. };
  259. /**
  260. * Get the visible window
  261. * @return {{start: Date, end: Date}} Visible range
  262. */
  263. Core.prototype.getWindow = function() {
  264. var range = this.range.getRange();
  265. return {
  266. start: new Date(range.start),
  267. end: new Date(range.end)
  268. };
  269. };
  270. /**
  271. * Force a redraw of the Core. Can be useful to manually redraw when
  272. * option autoResize=false
  273. */
  274. Core.prototype.redraw = function() {
  275. var resized = false,
  276. options = this.options,
  277. props = this.props,
  278. dom = this.dom;
  279. if (!dom) return; // when destroyed
  280. // update class names
  281. dom.root.className = 'vis timeline root ' + options.orientation;
  282. // update root width and height options
  283. dom.root.style.maxHeight = util.option.asSize(options.maxHeight, '');
  284. dom.root.style.minHeight = util.option.asSize(options.minHeight, '');
  285. dom.root.style.width = util.option.asSize(options.width, '');
  286. // calculate border widths
  287. props.border.left = (dom.centerContainer.offsetWidth - dom.centerContainer.clientWidth) / 2;
  288. props.border.right = props.border.left;
  289. props.border.top = (dom.centerContainer.offsetHeight - dom.centerContainer.clientHeight) / 2;
  290. props.border.bottom = props.border.top;
  291. var borderRootHeight= dom.root.offsetHeight - dom.root.clientHeight;
  292. var borderRootWidth = dom.root.offsetWidth - dom.root.clientWidth;
  293. // calculate the heights. If any of the side panels is empty, we set the height to
  294. // minus the border width, such that the border will be invisible
  295. props.center.height = dom.center.offsetHeight;
  296. props.left.height = dom.left.offsetHeight;
  297. props.right.height = dom.right.offsetHeight;
  298. props.top.height = dom.top.clientHeight || -props.border.top;
  299. props.bottom.height = dom.bottom.clientHeight || -props.border.bottom;
  300. // TODO: compensate borders when any of the panels is empty.
  301. // apply auto height
  302. // TODO: only calculate autoHeight when needed (else we cause an extra reflow/repaint of the DOM)
  303. var contentHeight = Math.max(props.left.height, props.center.height, props.right.height);
  304. var autoHeight = props.top.height + contentHeight + props.bottom.height +
  305. borderRootHeight + props.border.top + props.border.bottom;
  306. dom.root.style.height = util.option.asSize(options.height, autoHeight + 'px');
  307. // calculate heights of the content panels
  308. props.root.height = dom.root.offsetHeight;
  309. props.background.height = props.root.height - borderRootHeight;
  310. var containerHeight = props.root.height - props.top.height - props.bottom.height -
  311. borderRootHeight;
  312. props.centerContainer.height = containerHeight;
  313. props.leftContainer.height = containerHeight;
  314. props.rightContainer.height = props.leftContainer.height;
  315. // calculate the widths of the panels
  316. props.root.width = dom.root.offsetWidth;
  317. props.background.width = props.root.width - borderRootWidth;
  318. props.left.width = dom.leftContainer.clientWidth || -props.border.left;
  319. props.leftContainer.width = props.left.width;
  320. props.right.width = dom.rightContainer.clientWidth || -props.border.right;
  321. props.rightContainer.width = props.right.width;
  322. var centerWidth = props.root.width - props.left.width - props.right.width - borderRootWidth;
  323. props.center.width = centerWidth;
  324. props.centerContainer.width = centerWidth;
  325. props.top.width = centerWidth;
  326. props.bottom.width = centerWidth;
  327. // resize the panels
  328. dom.background.style.height = props.background.height + 'px';
  329. dom.backgroundVertical.style.height = props.background.height + 'px';
  330. dom.backgroundHorizontal.style.height = props.centerContainer.height + 'px';
  331. dom.centerContainer.style.height = props.centerContainer.height + 'px';
  332. dom.leftContainer.style.height = props.leftContainer.height + 'px';
  333. dom.rightContainer.style.height = props.rightContainer.height + 'px';
  334. dom.background.style.width = props.background.width + 'px';
  335. dom.backgroundVertical.style.width = props.centerContainer.width + 'px';
  336. dom.backgroundHorizontal.style.width = props.background.width + 'px';
  337. dom.centerContainer.style.width = props.center.width + 'px';
  338. dom.top.style.width = props.top.width + 'px';
  339. dom.bottom.style.width = props.bottom.width + 'px';
  340. // reposition the panels
  341. dom.background.style.left = '0';
  342. dom.background.style.top = '0';
  343. dom.backgroundVertical.style.left = props.left.width + 'px';
  344. dom.backgroundVertical.style.top = '0';
  345. dom.backgroundHorizontal.style.left = '0';
  346. dom.backgroundHorizontal.style.top = props.top.height + 'px';
  347. dom.centerContainer.style.left = props.left.width + 'px';
  348. dom.centerContainer.style.top = props.top.height + 'px';
  349. dom.leftContainer.style.left = '0';
  350. dom.leftContainer.style.top = props.top.height + 'px';
  351. dom.rightContainer.style.left = (props.left.width + props.center.width) + 'px';
  352. dom.rightContainer.style.top = props.top.height + 'px';
  353. dom.top.style.left = props.left.width + 'px';
  354. dom.top.style.top = '0';
  355. dom.bottom.style.left = props.left.width + 'px';
  356. dom.bottom.style.top = (props.top.height + props.centerContainer.height) + 'px';
  357. // update the scrollTop, feasible range for the offset can be changed
  358. // when the height of the Core or of the contents of the center changed
  359. this._updateScrollTop();
  360. // reposition the scrollable contents
  361. var offset = this.props.scrollTop;
  362. if (options.orientation == 'bottom') {
  363. offset += Math.max(this.props.centerContainer.height - this.props.center.height -
  364. this.props.border.top - this.props.border.bottom, 0);
  365. }
  366. dom.center.style.left = '0';
  367. dom.center.style.top = offset + 'px';
  368. dom.left.style.left = '0';
  369. dom.left.style.top = offset + 'px';
  370. dom.right.style.left = '0';
  371. dom.right.style.top = offset + 'px';
  372. // show shadows when vertical scrolling is available
  373. var visibilityTop = this.props.scrollTop == 0 ? 'hidden' : '';
  374. var visibilityBottom = this.props.scrollTop == this.props.scrollTopMin ? 'hidden' : '';
  375. dom.shadowTop.style.visibility = visibilityTop;
  376. dom.shadowBottom.style.visibility = visibilityBottom;
  377. dom.shadowTopLeft.style.visibility = visibilityTop;
  378. dom.shadowBottomLeft.style.visibility = visibilityBottom;
  379. dom.shadowTopRight.style.visibility = visibilityTop;
  380. dom.shadowBottomRight.style.visibility = visibilityBottom;
  381. // redraw all components
  382. this.components.forEach(function (component) {
  383. resized = component.redraw() || resized;
  384. });
  385. if (resized) {
  386. // keep repainting until all sizes are settled
  387. this.redraw();
  388. }
  389. };
  390. // TODO: deprecated since version 1.1.0, remove some day
  391. Core.prototype.repaint = function () {
  392. throw new Error('Function repaint is deprecated. Use redraw instead.');
  393. };
  394. /**
  395. * Convert a position on screen (pixels) to a datetime
  396. * @param {int} x Position on the screen in pixels
  397. * @return {Date} time The datetime the corresponds with given position x
  398. * @private
  399. */
  400. // TODO: move this function to Range
  401. Core.prototype._toTime = function(x) {
  402. var conversion = this.range.conversion(this.props.center.width);
  403. return new Date(x / conversion.scale + conversion.offset);
  404. };
  405. /**
  406. * Convert a position on the global screen (pixels) to a datetime
  407. * @param {int} x Position on the screen in pixels
  408. * @return {Date} time The datetime the corresponds with given position x
  409. * @private
  410. */
  411. // TODO: move this function to Range
  412. Core.prototype._toGlobalTime = function(x) {
  413. var conversion = this.range.conversion(this.props.root.width);
  414. return new Date(x / conversion.scale + conversion.offset);
  415. };
  416. /**
  417. * Convert a datetime (Date object) into a position on the screen
  418. * @param {Date} time A date
  419. * @return {int} x The position on the screen in pixels which corresponds
  420. * with the given date.
  421. * @private
  422. */
  423. // TODO: move this function to Range
  424. Core.prototype._toScreen = function(time) {
  425. var conversion = this.range.conversion(this.props.center.width);
  426. return (time.valueOf() - conversion.offset) * conversion.scale;
  427. };
  428. /**
  429. * Convert a datetime (Date object) into a position on the root
  430. * This is used to get the pixel density estimate for the screen, not the center panel
  431. * @param {Date} time A date
  432. * @return {int} x The position on root in pixels which corresponds
  433. * with the given date.
  434. * @private
  435. */
  436. // TODO: move this function to Range
  437. Core.prototype._toGlobalScreen = function(time) {
  438. var conversion = this.range.conversion(this.props.root.width);
  439. return (time.valueOf() - conversion.offset) * conversion.scale;
  440. };
  441. /**
  442. * Initialize watching when option autoResize is true
  443. * @private
  444. */
  445. Core.prototype._initAutoResize = function () {
  446. if (this.options.autoResize == true) {
  447. this._startAutoResize();
  448. }
  449. else {
  450. this._stopAutoResize();
  451. }
  452. };
  453. /**
  454. * Watch for changes in the size of the container. On resize, the Panel will
  455. * automatically redraw itself.
  456. * @private
  457. */
  458. Core.prototype._startAutoResize = function () {
  459. var me = this;
  460. this._stopAutoResize();
  461. this._onResize = function() {
  462. if (me.options.autoResize != true) {
  463. // stop watching when the option autoResize is changed to false
  464. me._stopAutoResize();
  465. return;
  466. }
  467. if (me.dom.root) {
  468. // check whether the frame is resized
  469. if ((me.dom.root.clientWidth != me.props.lastWidth) ||
  470. (me.dom.root.clientHeight != me.props.lastHeight)) {
  471. me.props.lastWidth = me.dom.root.clientWidth;
  472. me.props.lastHeight = me.dom.root.clientHeight;
  473. me.emit('change');
  474. }
  475. }
  476. };
  477. // add event listener to window resize
  478. util.addEventListener(window, 'resize', this._onResize);
  479. this.watchTimer = setInterval(this._onResize, 1000);
  480. };
  481. /**
  482. * Stop watching for a resize of the frame.
  483. * @private
  484. */
  485. Core.prototype._stopAutoResize = function () {
  486. if (this.watchTimer) {
  487. clearInterval(this.watchTimer);
  488. this.watchTimer = undefined;
  489. }
  490. // remove event listener on window.resize
  491. util.removeEventListener(window, 'resize', this._onResize);
  492. this._onResize = null;
  493. };
  494. /**
  495. * Start moving the timeline vertically
  496. * @param {Event} event
  497. * @private
  498. */
  499. Core.prototype._onTouch = function (event) {
  500. this.touch.allowDragging = true;
  501. };
  502. /**
  503. * Start moving the timeline vertically
  504. * @param {Event} event
  505. * @private
  506. */
  507. Core.prototype._onPinch = function (event) {
  508. this.touch.allowDragging = false;
  509. };
  510. /**
  511. * Start moving the timeline vertically
  512. * @param {Event} event
  513. * @private
  514. */
  515. Core.prototype._onDragStart = function (event) {
  516. this.touch.initialScrollTop = this.props.scrollTop;
  517. };
  518. /**
  519. * Move the timeline vertically
  520. * @param {Event} event
  521. * @private
  522. */
  523. Core.prototype._onDrag = function (event) {
  524. // refuse to drag when we where pinching to prevent the timeline make a jump
  525. // when releasing the fingers in opposite order from the touch screen
  526. if (!this.touch.allowDragging) return;
  527. var delta = event.gesture.deltaY;
  528. var oldScrollTop = this._getScrollTop();
  529. var newScrollTop = this._setScrollTop(this.touch.initialScrollTop + delta);
  530. if (newScrollTop != oldScrollTop) {
  531. this.redraw(); // TODO: this causes two redraws when dragging, the other is triggered by rangechange already
  532. }
  533. };
  534. /**
  535. * Apply a scrollTop
  536. * @param {Number} scrollTop
  537. * @returns {Number} scrollTop Returns the applied scrollTop
  538. * @private
  539. */
  540. Core.prototype._setScrollTop = function (scrollTop) {
  541. this.props.scrollTop = scrollTop;
  542. this._updateScrollTop();
  543. return this.props.scrollTop;
  544. };
  545. /**
  546. * Update the current scrollTop when the height of the containers has been changed
  547. * @returns {Number} scrollTop Returns the applied scrollTop
  548. * @private
  549. */
  550. Core.prototype._updateScrollTop = function () {
  551. // recalculate the scrollTopMin
  552. var scrollTopMin = Math.min(this.props.centerContainer.height - this.props.center.height, 0); // is negative or zero
  553. if (scrollTopMin != this.props.scrollTopMin) {
  554. // in case of bottom orientation, change the scrollTop such that the contents
  555. // do not move relative to the time axis at the bottom
  556. if (this.options.orientation == 'bottom') {
  557. this.props.scrollTop += (scrollTopMin - this.props.scrollTopMin);
  558. }
  559. this.props.scrollTopMin = scrollTopMin;
  560. }
  561. // limit the scrollTop to the feasible scroll range
  562. if (this.props.scrollTop > 0) this.props.scrollTop = 0;
  563. if (this.props.scrollTop < scrollTopMin) this.props.scrollTop = scrollTopMin;
  564. return this.props.scrollTop;
  565. };
  566. /**
  567. * Get the current scrollTop
  568. * @returns {number} scrollTop
  569. * @private
  570. */
  571. Core.prototype._getScrollTop = function () {
  572. return this.props.scrollTop;
  573. };
  574. module.exports = Core;