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.

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