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.

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