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.

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