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.

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