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.

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