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.

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