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.

1324 lines
46 KiB

  1. var Emitter = require('emitter-component');
  2. var Hammer = require('../module/hammer');
  3. var hammerUtil = require('../hammerUtil');
  4. var util = require('../util');
  5. var TimeAxis = require('./component/TimeAxis');
  6. var Activator = require('../shared/Activator');
  7. var DateUtil = require('./DateUtil');
  8. var CustomTime = require('./component/CustomTime');
  9. /**
  10. * Create a timeline visualization
  11. * @constructor
  12. */
  13. function Core () {}
  14. // turn Core into an event emitter
  15. Emitter(Core.prototype);
  16. /**
  17. * Create the main DOM for the Core: a root panel containing left, right,
  18. * top, bottom, content, and background panel.
  19. * @param {Element} container The container element where the Core will
  20. * be attached.
  21. * @protected
  22. */
  23. Core.prototype._create = function (container) {
  24. this.dom = {};
  25. this.dom.container = container;
  26. this.dom.root = document.createElement('div');
  27. this.dom.background = document.createElement('div');
  28. this.dom.backgroundVertical = document.createElement('div');
  29. this.dom.backgroundHorizontal = document.createElement('div');
  30. this.dom.centerContainer = document.createElement('div');
  31. this.dom.leftContainer = document.createElement('div');
  32. this.dom.rightContainer = document.createElement('div');
  33. this.dom.center = document.createElement('div');
  34. this.dom.left = document.createElement('div');
  35. this.dom.right = document.createElement('div');
  36. this.dom.top = document.createElement('div');
  37. this.dom.bottom = document.createElement('div');
  38. this.dom.shadowTop = document.createElement('div');
  39. this.dom.shadowBottom = document.createElement('div');
  40. this.dom.shadowTopLeft = document.createElement('div');
  41. this.dom.shadowBottomLeft = document.createElement('div');
  42. this.dom.shadowTopRight = document.createElement('div');
  43. this.dom.shadowBottomRight = document.createElement('div');
  44. this.dom.rollingModeBtn = document.createElement('div');
  45. this.dom.root.className = 'vis-timeline';
  46. this.dom.background.className = 'vis-panel vis-background';
  47. this.dom.backgroundVertical.className = 'vis-panel vis-background vis-vertical';
  48. this.dom.backgroundHorizontal.className = 'vis-panel vis-background vis-horizontal';
  49. this.dom.centerContainer.className = 'vis-panel vis-center';
  50. this.dom.leftContainer.className = 'vis-panel vis-left';
  51. this.dom.rightContainer.className = 'vis-panel vis-right';
  52. this.dom.top.className = 'vis-panel vis-top';
  53. this.dom.bottom.className = 'vis-panel vis-bottom';
  54. this.dom.left.className = 'vis-content';
  55. this.dom.center.className = 'vis-content';
  56. this.dom.right.className = 'vis-content';
  57. this.dom.shadowTop.className = 'vis-shadow vis-top';
  58. this.dom.shadowBottom.className = 'vis-shadow vis-bottom';
  59. this.dom.shadowTopLeft.className = 'vis-shadow vis-top';
  60. this.dom.shadowBottomLeft.className = 'vis-shadow vis-bottom';
  61. this.dom.shadowTopRight.className = 'vis-shadow vis-top';
  62. this.dom.shadowBottomRight.className = 'vis-shadow vis-bottom';
  63. this.dom.rollingModeBtn.className = 'vis-rolling-mode-btn';
  64. this.dom.root.appendChild(this.dom.background);
  65. this.dom.root.appendChild(this.dom.backgroundVertical);
  66. this.dom.root.appendChild(this.dom.backgroundHorizontal);
  67. this.dom.root.appendChild(this.dom.centerContainer);
  68. this.dom.root.appendChild(this.dom.leftContainer);
  69. this.dom.root.appendChild(this.dom.rightContainer);
  70. this.dom.root.appendChild(this.dom.top);
  71. this.dom.root.appendChild(this.dom.bottom);
  72. this.dom.root.appendChild(this.dom.bottom);
  73. this.dom.root.appendChild(this.dom.rollingModeBtn);
  74. this.dom.centerContainer.appendChild(this.dom.center);
  75. this.dom.leftContainer.appendChild(this.dom.left);
  76. this.dom.rightContainer.appendChild(this.dom.right);
  77. this.dom.centerContainer.appendChild(this.dom.shadowTop);
  78. this.dom.centerContainer.appendChild(this.dom.shadowBottom);
  79. this.dom.leftContainer.appendChild(this.dom.shadowTopLeft);
  80. this.dom.leftContainer.appendChild(this.dom.shadowBottomLeft);
  81. this.dom.rightContainer.appendChild(this.dom.shadowTopRight);
  82. this.dom.rightContainer.appendChild(this.dom.shadowBottomRight);
  83. // size properties of each of the panels
  84. this.props = {
  85. root: {},
  86. background: {},
  87. centerContainer: {},
  88. leftContainer: {},
  89. rightContainer: {},
  90. center: {},
  91. left: {},
  92. right: {},
  93. top: {},
  94. bottom: {},
  95. border: {},
  96. scrollTop: 0,
  97. scrollTopMin: 0
  98. };
  99. this.on('rangechange', function () {
  100. if (this.initialDrawDone === true) {
  101. this._redraw();
  102. }
  103. }.bind(this));
  104. this.on('touch', this._onTouch.bind(this));
  105. this.on('panmove', this._onDrag.bind(this));
  106. var me = this;
  107. this._origRedraw = this._redraw.bind(this);
  108. this._redraw = util.throttle(this._origRedraw);
  109. this.on('_change', function (properties) {
  110. if (me.itemSet && me.itemSet.initialItemSetDrawn && properties && properties.queue == true) {
  111. me._redraw()
  112. } else {
  113. me._origRedraw();
  114. }
  115. });
  116. // create event listeners for all interesting events, these events will be
  117. // emitted via emitter
  118. this.hammer = new Hammer(this.dom.root);
  119. var pinchRecognizer = this.hammer.get('pinch').set({enable: true});
  120. hammerUtil.disablePreventDefaultVertically(pinchRecognizer);
  121. this.hammer.get('pan').set({threshold:5, direction: Hammer.DIRECTION_HORIZONTAL});
  122. this.listeners = {};
  123. var events = [
  124. 'tap', 'doubletap', 'press',
  125. 'pinch',
  126. 'pan', 'panstart', 'panmove', 'panend'
  127. // TODO: cleanup
  128. //'touch', 'pinch',
  129. //'tap', 'doubletap', 'hold',
  130. //'dragstart', 'drag', 'dragend',
  131. //'mousewheel', 'DOMMouseScroll' // DOMMouseScroll is needed for Firefox
  132. ];
  133. events.forEach(function (type) {
  134. var listener = function (event) {
  135. if (me.isActive()) {
  136. me.emit(type, event);
  137. }
  138. };
  139. me.hammer.on(type, listener);
  140. me.listeners[type] = listener;
  141. });
  142. // emulate a touch event (emitted before the start of a pan, pinch, tap, or press)
  143. hammerUtil.onTouch(this.hammer, function (event) {
  144. me.emit('touch', event);
  145. }.bind(this));
  146. // emulate a release event (emitted after a pan, pinch, tap, or press)
  147. hammerUtil.onRelease(this.hammer, function (event) {
  148. me.emit('release', event);
  149. }.bind(this));
  150. /**
  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. */
  489. Core.prototype.setCustomTimeTitle = function(title, id) {
  490. var customTimes = this.customTimes.filter(function (component) {
  491. return component.options.id === id;
  492. });
  493. if (customTimes.length === 0) {
  494. throw new Error('No custom time bar found with id ' + JSON.stringify(id))
  495. }
  496. if (customTimes.length > 0) {
  497. return customTimes[0].setCustomTitle(title);
  498. }
  499. };
  500. /**
  501. * Retrieve meta information from an event.
  502. * Should be overridden by classes extending Core
  503. * @param {Event} event
  504. * @return {Object} An object with related information.
  505. */
  506. Core.prototype.getEventProperties = function (event) {
  507. return { event: event };
  508. };
  509. /**
  510. * Add custom vertical bar
  511. * @param {Date | String | Number} [time] A Date, unix timestamp, or
  512. * ISO date string. Time point where
  513. * the new bar should be placed.
  514. * If not provided, `new Date()` will
  515. * be used.
  516. * @param {Number | String} [id=undefined] Id of the new bar. Optional
  517. * @return {Number | String} Returns the id of the new bar
  518. */
  519. Core.prototype.addCustomTime = function (time, id) {
  520. var timestamp = time !== undefined
  521. ? util.convert(time, 'Date').valueOf()
  522. : new Date();
  523. var exists = this.customTimes.some(function (customTime) {
  524. return customTime.options.id === id;
  525. });
  526. if (exists) {
  527. throw new Error('A custom time with id ' + JSON.stringify(id) + ' already exists');
  528. }
  529. var customTime = new CustomTime(this.body, util.extend({}, this.options, {
  530. time : timestamp,
  531. id : id
  532. }));
  533. this.customTimes.push(customTime);
  534. this.components.push(customTime);
  535. this._redraw();
  536. return id;
  537. };
  538. /**
  539. * Remove previously added custom bar
  540. * @param {int} id ID of the custom bar to be removed
  541. * @return {boolean} True if the bar exists and is removed, false otherwise
  542. */
  543. Core.prototype.removeCustomTime = function (id) {
  544. var customTimes = this.customTimes.filter(function (bar) {
  545. return (bar.options.id === id);
  546. });
  547. if (customTimes.length === 0) {
  548. throw new Error('No custom time bar found with id ' + JSON.stringify(id))
  549. }
  550. customTimes.forEach(function (customTime) {
  551. this.customTimes.splice(this.customTimes.indexOf(customTime), 1);
  552. this.components.splice(this.components.indexOf(customTime), 1);
  553. customTime.destroy();
  554. }.bind(this))
  555. };
  556. /**
  557. * Get the id's of the currently visible items.
  558. * @returns {Array} The ids of the visible items
  559. */
  560. Core.prototype.getVisibleItems = function() {
  561. return this.itemSet && this.itemSet.getVisibleItems() || [];
  562. };
  563. /**
  564. * Set Core window such that it fits all items
  565. * @param {Object} [options] Available options:
  566. * `animation: boolean | {duration: number, easingFunction: string}`
  567. * If true (default), the range is animated
  568. * smoothly to the new window. An object can be
  569. * provided to specify duration and easing function.
  570. * Default duration is 500 ms, and default easing
  571. * function is 'easeInOutQuad'.
  572. * @param {Function} a callback funtion to be executed at the end of this function
  573. */
  574. Core.prototype.fit = function(options, callback) {
  575. var range = this.getDataRange();
  576. // skip range set if there is no min and max date
  577. if (range.min === null && range.max === null) {
  578. return;
  579. }
  580. // apply a margin of 1% left and right of the data
  581. var interval = range.max - range.min;
  582. var min = new Date(range.min.valueOf() - interval * 0.01);
  583. var max = new Date(range.max.valueOf() + interval * 0.01);
  584. var animation = (options && options.animation !== undefined) ? options.animation : true;
  585. this.range.setRange(min, max, { animation: animation }, callback);
  586. };
  587. /**
  588. * Calculate the data range of the items start and end dates
  589. * @returns {{min: Date | null, max: Date | null}}
  590. * @protected
  591. */
  592. Core.prototype.getDataRange = function() {
  593. // must be implemented by Timeline and Graph2d
  594. throw new Error('Cannot invoke abstract method getDataRange');
  595. };
  596. /**
  597. * Set the visible window. Both parameters are optional, you can change only
  598. * start or only end. Syntax:
  599. *
  600. * TimeLine.setWindow(start, end)
  601. * TimeLine.setWindow(start, end, options)
  602. * TimeLine.setWindow(range)
  603. *
  604. * Where start and end can be a Date, number, or string, and range is an
  605. * object with properties start and end.
  606. *
  607. * @param {Date | Number | String | Object} [start] Start date of visible window
  608. * @param {Date | Number | String} [end] End date of visible window
  609. * @param {Object} [options] Available options:
  610. * `animation: boolean | {duration: number, easingFunction: string}`
  611. * If true (default), the range is animated
  612. * smoothly to the new window. An object can be
  613. * provided to specify duration and easing function.
  614. * Default duration is 500 ms, and default easing
  615. * function is 'easeInOutQuad'.
  616. * @param {Function} a callback funtion to be executed at the end of this function
  617. */
  618. Core.prototype.setWindow = function(start, end, options, callback) {
  619. if (typeof arguments[2] == "function") {
  620. callback = arguments[2]
  621. options = {};
  622. }
  623. var animation;
  624. var range;
  625. if (arguments.length == 1) {
  626. range = arguments[0];
  627. animation = (range.animation !== undefined) ? range.animation : true;
  628. this.range.setRange(range.start, range.end, { animation: animation });
  629. }
  630. else if (arguments.length == 2 && typeof arguments[1] == "function") {
  631. range = arguments[0];
  632. callback = arguments[1];
  633. animation = (range.animation !== undefined) ? range.animation : true;
  634. this.range.setRange(range.start, range.end, { animation: animation }, callback);
  635. }
  636. else {
  637. animation = (options && options.animation !== undefined) ? options.animation : true;
  638. this.range.setRange(start, end, { animation: animation }, callback);
  639. }
  640. };
  641. /**
  642. * Move the window such that given time is centered on screen.
  643. * @param {Date | Number | String} time
  644. * @param {Object} [options] Available options:
  645. * `animation: boolean | {duration: number, easingFunction: string}`
  646. * If true (default), the range is animated
  647. * smoothly to the new window. An object can be
  648. * provided to specify duration and easing function.
  649. * Default duration is 500 ms, and default easing
  650. * function is 'easeInOutQuad'.
  651. * @param {Function} a callback funtion to be executed at the end of this function
  652. */
  653. Core.prototype.moveTo = function(time, options, callback) {
  654. if (typeof arguments[1] == "function") {
  655. callback = arguments[1]
  656. options = {};
  657. }
  658. var interval = this.range.end - this.range.start;
  659. var t = util.convert(time, 'Date').valueOf();
  660. var start = t - interval / 2;
  661. var end = t + interval / 2;
  662. var animation = (options && options.animation !== undefined) ? options.animation : true;
  663. this.range.setRange(start, end, { animation: animation }, callback);
  664. };
  665. /**
  666. * Get the visible window
  667. * @return {{start: Date, end: Date}} Visible range
  668. */
  669. Core.prototype.getWindow = function() {
  670. var range = this.range.getRange();
  671. return {
  672. start: new Date(range.start),
  673. end: new Date(range.end)
  674. };
  675. };
  676. /**
  677. * Zoom in the window such that given time is centered on screen.
  678. * @param {Number} percentage - must be between [0..1]
  679. * @param {Object} [options] Available options:
  680. * `animation: boolean | {duration: number, easingFunction: string}`
  681. * If true (default), the range is animated
  682. * smoothly to the new window. An object can be
  683. * provided to specify duration and easing function.
  684. * Default duration is 500 ms, and default easing
  685. * function is 'easeInOutQuad'.
  686. * @param {Function} a callback funtion to be executed at the end of this function
  687. */
  688. Core.prototype.zoomIn = function(percentage, options, callback) {
  689. if (!percentage || percentage < 0 || percentage > 1) return
  690. if (typeof arguments[1] == "function") {
  691. callback = arguments[1]
  692. options = {};
  693. }
  694. var range = this.getWindow();
  695. var start = range.start.valueOf();
  696. var end = range.end.valueOf();
  697. var interval = end - start;
  698. var newInterval = interval / (1 + percentage);
  699. var distance = (interval - newInterval) / 2;
  700. var newStart = start + distance;
  701. var newEnd = end - distance;
  702. this.setWindow(newStart, newEnd, options, callback);
  703. };
  704. /**
  705. * Zoom out the window such that given time is centered on screen.
  706. * @param {Number} percentage - must be between [0..1]
  707. * @param {Object} [options] Available options:
  708. * `animation: boolean | {duration: number, easingFunction: string}`
  709. * If true (default), the range is animated
  710. * smoothly to the new window. An object can be
  711. * provided to specify duration and easing function.
  712. * Default duration is 500 ms, and default easing
  713. * function is 'easeInOutQuad'.
  714. * @param {Function} a callback funtion to be executed at the end of this function
  715. */
  716. Core.prototype.zoomOut = function(percentage, options, callback) {
  717. if (!percentage || percentage < 0 || percentage > 1) return
  718. if (typeof arguments[1] == "function") {
  719. callback = arguments[1]
  720. options = {};
  721. }
  722. var range = this.getWindow();
  723. var start = range.start.valueOf();
  724. var end = range.end.valueOf();
  725. var interval = end - start;
  726. var newStart = start - interval * percentage / 2;
  727. var newEnd = end + interval * percentage / 2;
  728. this.setWindow(newStart, newEnd, options, callback);
  729. };
  730. /**
  731. * Force a redraw. Can be overridden by implementations of Core
  732. *
  733. * Note: this function will be overridden on construction with a trottled version
  734. */
  735. Core.prototype.redraw = function() {
  736. this._redraw();
  737. };
  738. /**
  739. * Redraw for internal use. Redraws all components. See also the public
  740. * method redraw.
  741. * @protected
  742. */
  743. Core.prototype._redraw = function() {
  744. this.redrawCount++;
  745. var resized = false;
  746. var options = this.options;
  747. var props = this.props;
  748. var dom = this.dom;
  749. if (!dom || !dom.container || dom.root.offsetWidth == 0) return; // when destroyed, or invisible
  750. DateUtil.updateHiddenDates(this.options.moment, this.body, this.options.hiddenDates);
  751. // update class names
  752. if (options.orientation == 'top') {
  753. util.addClassName(dom.root, 'vis-top');
  754. util.removeClassName(dom.root, 'vis-bottom');
  755. }
  756. else {
  757. util.removeClassName(dom.root, 'vis-top');
  758. util.addClassName(dom.root, 'vis-bottom');
  759. }
  760. // update root width and height options
  761. dom.root.style.maxHeight = util.option.asSize(options.maxHeight, '');
  762. dom.root.style.minHeight = util.option.asSize(options.minHeight, '');
  763. dom.root.style.width = util.option.asSize(options.width, '');
  764. // calculate border widths
  765. props.border.left = (dom.centerContainer.offsetWidth - dom.centerContainer.clientWidth) / 2;
  766. props.border.right = props.border.left;
  767. props.border.top = (dom.centerContainer.offsetHeight - dom.centerContainer.clientHeight) / 2;
  768. props.border.bottom = props.border.top;
  769. props.borderRootHeight= dom.root.offsetHeight - dom.root.clientHeight;
  770. props.borderRootWidth = dom.root.offsetWidth - dom.root.clientWidth;
  771. // workaround for a bug in IE: the clientWidth of an element with
  772. // a height:0px and overflow:hidden is not calculated and always has value 0
  773. if (dom.centerContainer.clientHeight === 0) {
  774. props.border.left = props.border.top;
  775. props.border.right = props.border.left;
  776. }
  777. if (dom.root.clientHeight === 0) {
  778. props.borderRootWidth = props.borderRootHeight;
  779. }
  780. // calculate the heights. If any of the side panels is empty, we set the height to
  781. // minus the border width, such that the border will be invisible
  782. props.center.height = dom.center.offsetHeight;
  783. props.left.height = dom.left.offsetHeight;
  784. props.right.height = dom.right.offsetHeight;
  785. props.top.height = dom.top.clientHeight || -props.border.top;
  786. props.bottom.height = dom.bottom.clientHeight || -props.border.bottom;
  787. // TODO: compensate borders when any of the panels is empty.
  788. // apply auto height
  789. // TODO: only calculate autoHeight when needed (else we cause an extra reflow/repaint of the DOM)
  790. var contentHeight = Math.max(props.left.height, props.center.height, props.right.height);
  791. var autoHeight = props.top.height + contentHeight + props.bottom.height +
  792. props.borderRootHeight + props.border.top + props.border.bottom;
  793. dom.root.style.height = util.option.asSize(options.height, autoHeight + 'px');
  794. // calculate heights of the content panels
  795. props.root.height = dom.root.offsetHeight;
  796. props.background.height = props.root.height - props.borderRootHeight;
  797. var containerHeight = props.root.height - props.top.height - props.bottom.height -
  798. props.borderRootHeight;
  799. props.centerContainer.height = containerHeight;
  800. props.leftContainer.height = containerHeight;
  801. props.rightContainer.height = props.leftContainer.height;
  802. // calculate the widths of the panels
  803. props.root.width = dom.root.offsetWidth;
  804. props.background.width = props.root.width - props.borderRootWidth;
  805. if (!this.initialDrawDone) {
  806. props.scrollbarWidth = util.getScrollBarWidth();
  807. }
  808. if (options.verticalScroll) {
  809. if (options.rtl) {
  810. props.left.width = dom.leftContainer.clientWidth || -props.border.left;
  811. props.right.width = dom.rightContainer.clientWidth + props.scrollbarWidth || -props.border.right;
  812. } else {
  813. props.left.width = dom.leftContainer.clientWidth + props.scrollbarWidth || -props.border.left;
  814. props.right.width = dom.rightContainer.clientWidth || -props.border.right;
  815. }
  816. } else {
  817. props.left.width = dom.leftContainer.clientWidth || -props.border.left;
  818. props.right.width = dom.rightContainer.clientWidth || -props.border.right;
  819. }
  820. this._setDOM();
  821. // update the scrollTop, feasible range for the offset can be changed
  822. // when the height of the Core or of the contents of the center changed
  823. var offset = this._updateScrollTop();
  824. // reposition the scrollable contents
  825. if (options.orientation.item != 'top') {
  826. offset += Math.max(props.centerContainer.height - props.center.height -
  827. props.border.top - props.border.bottom, 0);
  828. }
  829. dom.center.style.top = offset + 'px';
  830. // show shadows when vertical scrolling is available
  831. var visibilityTop = props.scrollTop == 0 ? 'hidden' : '';
  832. var visibilityBottom = props.scrollTop == props.scrollTopMin ? 'hidden' : '';
  833. dom.shadowTop.style.visibility = visibilityTop;
  834. dom.shadowBottom.style.visibility = visibilityBottom;
  835. dom.shadowTopLeft.style.visibility = visibilityTop;
  836. dom.shadowBottomLeft.style.visibility = visibilityBottom;
  837. dom.shadowTopRight.style.visibility = visibilityTop;
  838. dom.shadowBottomRight.style.visibility = visibilityBottom;
  839. if (options.verticalScroll) {
  840. dom.rightContainer.className = 'vis-panel vis-right vis-vertical-scroll';
  841. dom.leftContainer.className = 'vis-panel vis-left vis-vertical-scroll';
  842. dom.shadowTopRight.style.visibility = "hidden";
  843. dom.shadowBottomRight.style.visibility = "hidden";
  844. dom.shadowTopLeft.style.visibility = "hidden";
  845. dom.shadowBottomLeft.style.visibility = "hidden";
  846. dom.left.style.top = '0px';
  847. dom.right.style.top = '0px';
  848. }
  849. if (!options.verticalScroll || props.center.height < props.centerContainer.height) {
  850. dom.left.style.top = offset + 'px';
  851. dom.right.style.top = offset + 'px';
  852. dom.rightContainer.className = dom.rightContainer.className.replace(new RegExp('(?:^|\\s)'+ 'vis-vertical-scroll' + '(?:\\s|$)'), ' ');
  853. dom.leftContainer.className = dom.leftContainer.className.replace(new RegExp('(?:^|\\s)'+ 'vis-vertical-scroll' + '(?:\\s|$)'), ' ');
  854. props.left.width = dom.leftContainer.clientWidth || -props.border.left;
  855. props.right.width = dom.rightContainer.clientWidth || -props.border.right;
  856. this._setDOM();
  857. }
  858. // enable/disable vertical panning
  859. var contentsOverflow = props.center.height > props.centerContainer.height;
  860. this.hammer.get('pan').set({
  861. direction: contentsOverflow ? Hammer.DIRECTION_ALL : Hammer.DIRECTION_HORIZONTAL
  862. });
  863. // redraw all components
  864. this.components.forEach(function (component) {
  865. resized = component.redraw() || resized;
  866. });
  867. var MAX_REDRAW = 5;
  868. if (resized) {
  869. if (this.redrawCount < MAX_REDRAW) {
  870. this.body.emitter.emit('_change');
  871. return;
  872. }
  873. else {
  874. console.log('WARNING: infinite loop in redraw?');
  875. }
  876. } else {
  877. this.redrawCount = 0;
  878. }
  879. this.initialDrawDone = true;
  880. //Emit public 'changed' event for UI updates, see issue #1592
  881. this.body.emitter.emit("changed");
  882. };
  883. Core.prototype._setDOM = function () {
  884. var props = this.props;
  885. var dom = this.dom;
  886. props.leftContainer.width = props.left.width;
  887. props.rightContainer.width = props.right.width;
  888. var centerWidth = props.root.width - props.left.width - props.right.width - props.borderRootWidth;
  889. props.center.width = centerWidth;
  890. props.centerContainer.width = centerWidth;
  891. props.top.width = centerWidth;
  892. props.bottom.width = centerWidth;
  893. // resize the panels
  894. dom.background.style.height = props.background.height + 'px';
  895. dom.backgroundVertical.style.height = props.background.height + 'px';
  896. dom.backgroundHorizontal.style.height = props.centerContainer.height + 'px';
  897. dom.centerContainer.style.height = props.centerContainer.height + 'px';
  898. dom.leftContainer.style.height = props.leftContainer.height + 'px';
  899. dom.rightContainer.style.height = props.rightContainer.height + 'px';
  900. dom.background.style.width = props.background.width + 'px';
  901. dom.backgroundVertical.style.width = props.centerContainer.width + 'px';
  902. dom.backgroundHorizontal.style.width = props.background.width + 'px';
  903. dom.centerContainer.style.width = props.center.width + 'px';
  904. dom.top.style.width = props.top.width + 'px';
  905. dom.bottom.style.width = props.bottom.width + 'px';
  906. // reposition the panels
  907. dom.background.style.left = '0';
  908. dom.background.style.top = '0';
  909. dom.backgroundVertical.style.left = (props.left.width + props.border.left) + 'px';
  910. dom.backgroundVertical.style.top = '0';
  911. dom.backgroundHorizontal.style.left = '0';
  912. dom.backgroundHorizontal.style.top = props.top.height + 'px';
  913. dom.centerContainer.style.left = props.left.width + 'px';
  914. dom.centerContainer.style.top = props.top.height + 'px';
  915. dom.leftContainer.style.left = '0';
  916. dom.leftContainer.style.top = props.top.height + 'px';
  917. dom.rightContainer.style.left = (props.left.width + props.center.width) + 'px';
  918. dom.rightContainer.style.top = props.top.height + 'px';
  919. dom.top.style.left = props.left.width + 'px';
  920. dom.top.style.top = '0';
  921. dom.bottom.style.left = props.left.width + 'px';
  922. dom.bottom.style.top = (props.top.height + props.centerContainer.height) + 'px';
  923. dom.center.style.left = '0';
  924. dom.left.style.left = '0';
  925. dom.right.style.left = '0';
  926. };
  927. // TODO: deprecated since version 1.1.0, remove some day
  928. Core.prototype.repaint = function () {
  929. throw new Error('Function repaint is deprecated. Use redraw instead.');
  930. };
  931. /**
  932. * Set a current time. This can be used for example to ensure that a client's
  933. * time is synchronized with a shared server time.
  934. * Only applicable when option `showCurrentTime` is true.
  935. * @param {Date | String | Number} time A Date, unix timestamp, or
  936. * ISO date string.
  937. */
  938. Core.prototype.setCurrentTime = function(time) {
  939. if (!this.currentTime) {
  940. throw new Error('Option showCurrentTime must be true');
  941. }
  942. this.currentTime.setCurrentTime(time);
  943. };
  944. /**
  945. * Get the current time.
  946. * Only applicable when option `showCurrentTime` is true.
  947. * @return {Date} Returns the current time.
  948. */
  949. Core.prototype.getCurrentTime = function() {
  950. if (!this.currentTime) {
  951. throw new Error('Option showCurrentTime must be true');
  952. }
  953. return this.currentTime.getCurrentTime();
  954. };
  955. /**
  956. * Convert a position on screen (pixels) to a datetime
  957. * @param {int} x Position on the screen in pixels
  958. * @return {Date} time The datetime the corresponds with given position x
  959. * @protected
  960. */
  961. // TODO: move this function to Range
  962. Core.prototype._toTime = function(x) {
  963. return DateUtil.toTime(this, x, this.props.center.width);
  964. };
  965. /**
  966. * Convert a position on the global screen (pixels) to a datetime
  967. * @param {int} x Position on the screen in pixels
  968. * @return {Date} time The datetime the corresponds with given position x
  969. * @protected
  970. */
  971. // TODO: move this function to Range
  972. Core.prototype._toGlobalTime = function(x) {
  973. return DateUtil.toTime(this, x, this.props.root.width);
  974. //var conversion = this.range.conversion(this.props.root.width);
  975. //return new Date(x / conversion.scale + conversion.offset);
  976. };
  977. /**
  978. * Convert a datetime (Date object) into a position on the screen
  979. * @param {Date} time A date
  980. * @return {int} x The position on the screen in pixels which corresponds
  981. * with the given date.
  982. * @protected
  983. */
  984. // TODO: move this function to Range
  985. Core.prototype._toScreen = function(time) {
  986. return DateUtil.toScreen(this, time, this.props.center.width);
  987. };
  988. /**
  989. * Convert a datetime (Date object) into a position on the root
  990. * This is used to get the pixel density estimate for the screen, not the center panel
  991. * @param {Date} time A date
  992. * @return {int} x The position on root in pixels which corresponds
  993. * with the given date.
  994. * @protected
  995. */
  996. // TODO: move this function to Range
  997. Core.prototype._toGlobalScreen = function(time) {
  998. return DateUtil.toScreen(this, time, this.props.root.width);
  999. //var conversion = this.range.conversion(this.props.root.width);
  1000. //return (time.valueOf() - conversion.offset) * conversion.scale;
  1001. };
  1002. /**
  1003. * Initialize watching when option autoResize is true
  1004. * @private
  1005. */
  1006. Core.prototype._initAutoResize = function () {
  1007. if (this.options.autoResize == true) {
  1008. this._startAutoResize();
  1009. }
  1010. else {
  1011. this._stopAutoResize();
  1012. }
  1013. };
  1014. /**
  1015. * Watch for changes in the size of the container. On resize, the Panel will
  1016. * automatically redraw itself.
  1017. * @private
  1018. */
  1019. Core.prototype._startAutoResize = function () {
  1020. var me = this;
  1021. this._stopAutoResize();
  1022. this._onResize = function() {
  1023. if (me.options.autoResize != true) {
  1024. // stop watching when the option autoResize is changed to false
  1025. me._stopAutoResize();
  1026. return;
  1027. }
  1028. if (me.dom.root) {
  1029. // check whether the frame is resized
  1030. // Note: we compare offsetWidth here, not clientWidth. For some reason,
  1031. // IE does not restore the clientWidth from 0 to the actual width after
  1032. // changing the timeline's container display style from none to visible
  1033. if ((me.dom.root.offsetWidth != me.props.lastWidth) ||
  1034. (me.dom.root.offsetHeight != me.props.lastHeight)) {
  1035. me.props.lastWidth = me.dom.root.offsetWidth;
  1036. me.props.lastHeight = me.dom.root.offsetHeight;
  1037. me.props.scrollbarWidth = util.getScrollBarWidth();
  1038. me.body.emitter.emit('_change');
  1039. }
  1040. }
  1041. };
  1042. // add event listener to window resize
  1043. util.addEventListener(window, 'resize', this._onResize);
  1044. //Prevent initial unnecessary redraw
  1045. if (me.dom.root) {
  1046. me.props.lastWidth = me.dom.root.offsetWidth;
  1047. me.props.lastHeight = me.dom.root.offsetHeight;
  1048. }
  1049. this.watchTimer = setInterval(this._onResize, 1000);
  1050. };
  1051. /**
  1052. * Stop watching for a resize of the frame.
  1053. * @private
  1054. */
  1055. Core.prototype._stopAutoResize = function () {
  1056. if (this.watchTimer) {
  1057. clearInterval(this.watchTimer);
  1058. this.watchTimer = undefined;
  1059. }
  1060. // remove event listener on window.resize
  1061. if (this._onResize) {
  1062. util.removeEventListener(window, 'resize', this._onResize);
  1063. this._onResize = null;
  1064. }
  1065. };
  1066. /**
  1067. * Start moving the timeline vertically
  1068. * @param {Event} event
  1069. * @private
  1070. */
  1071. Core.prototype._onTouch = function (event) { // eslint-disable-line no-unused-vars
  1072. this.touch.allowDragging = true;
  1073. this.touch.initialScrollTop = this.props.scrollTop;
  1074. };
  1075. /**
  1076. * Start moving the timeline vertically
  1077. * @param {Event} event
  1078. * @private
  1079. */
  1080. Core.prototype._onPinch = function (event) { // eslint-disable-line no-unused-vars
  1081. this.touch.allowDragging = false;
  1082. };
  1083. /**
  1084. * Move the timeline vertically
  1085. * @param {Event} event
  1086. * @private
  1087. */
  1088. Core.prototype._onDrag = function (event) {
  1089. if (!event) return
  1090. // refuse to drag when we where pinching to prevent the timeline make a jump
  1091. // when releasing the fingers in opposite order from the touch screen
  1092. if (!this.touch.allowDragging) return;
  1093. var delta = event.deltaY;
  1094. var oldScrollTop = this._getScrollTop();
  1095. var newScrollTop = this._setScrollTop(this.touch.initialScrollTop + delta);
  1096. if (this.options.verticalScroll) {
  1097. this.dom.left.parentNode.scrollTop = -this.props.scrollTop;
  1098. this.dom.right.parentNode.scrollTop = -this.props.scrollTop;
  1099. }
  1100. if (newScrollTop != oldScrollTop) {
  1101. this.emit("verticalDrag");
  1102. }
  1103. };
  1104. /**
  1105. * Apply a scrollTop
  1106. * @param {Number} scrollTop
  1107. * @returns {Number} scrollTop Returns the applied scrollTop
  1108. * @private
  1109. */
  1110. Core.prototype._setScrollTop = function (scrollTop) {
  1111. this.props.scrollTop = scrollTop;
  1112. this._updateScrollTop();
  1113. return this.props.scrollTop;
  1114. };
  1115. /**
  1116. * Update the current scrollTop when the height of the containers has been changed
  1117. * @returns {Number} scrollTop Returns the applied scrollTop
  1118. * @private
  1119. */
  1120. Core.prototype._updateScrollTop = function () {
  1121. // recalculate the scrollTopMin
  1122. var scrollTopMin = Math.min(this.props.centerContainer.height - this.props.center.height, 0); // is negative or zero
  1123. if (scrollTopMin != this.props.scrollTopMin) {
  1124. // in case of bottom orientation, change the scrollTop such that the contents
  1125. // do not move relative to the time axis at the bottom
  1126. if (this.options.orientation.item != 'top') {
  1127. this.props.scrollTop += (scrollTopMin - this.props.scrollTopMin);
  1128. }
  1129. this.props.scrollTopMin = scrollTopMin;
  1130. }
  1131. // limit the scrollTop to the feasible scroll range
  1132. if (this.props.scrollTop > 0) this.props.scrollTop = 0;
  1133. if (this.props.scrollTop < scrollTopMin) this.props.scrollTop = scrollTopMin;
  1134. if (this.options.verticalScroll) {
  1135. this.dom.left.parentNode.scrollTop = -this.props.scrollTop;
  1136. this.dom.right.parentNode.scrollTop = -this.props.scrollTop;
  1137. }
  1138. return this.props.scrollTop;
  1139. };
  1140. /**
  1141. * Get the current scrollTop
  1142. * @returns {number} scrollTop
  1143. * @private
  1144. */
  1145. Core.prototype._getScrollTop = function () {
  1146. return this.props.scrollTop;
  1147. };
  1148. /**
  1149. * Load a configurator
  1150. * @return {Object}
  1151. * @private
  1152. */
  1153. Core.prototype._createConfigurator = function () {
  1154. throw new Error('Cannot invoke abstract method _createConfigurator');
  1155. };
  1156. module.exports = Core;