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.

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