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.

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