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.

961 lines
33 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. * @param {HTMLElement} container
  16. * @param {vis.DataSet | Array} [items]
  17. * @param {Object} [options] See Core.setOptions for the available options.
  18. * @constructor
  19. */
  20. function Core () {}
  21. // turn Core into an event emitter
  22. Emitter(Core.prototype);
  23. /**
  24. * Create the main DOM for the Core: a root panel containing left, right,
  25. * top, bottom, content, and background panel.
  26. * @param {Element} container The container element where the Core will
  27. * be attached.
  28. * @protected
  29. */
  30. Core.prototype._create = function (container) {
  31. this.dom = {};
  32. this.dom.root = document.createElement('div');
  33. this.dom.background = document.createElement('div');
  34. this.dom.backgroundVertical = document.createElement('div');
  35. this.dom.backgroundHorizontal = document.createElement('div');
  36. this.dom.centerContainer = document.createElement('div');
  37. this.dom.leftContainer = document.createElement('div');
  38. this.dom.rightContainer = document.createElement('div');
  39. this.dom.center = document.createElement('div');
  40. this.dom.left = document.createElement('div');
  41. this.dom.right = document.createElement('div');
  42. this.dom.top = document.createElement('div');
  43. this.dom.bottom = document.createElement('div');
  44. this.dom.shadowTop = document.createElement('div');
  45. this.dom.shadowBottom = document.createElement('div');
  46. this.dom.shadowTopLeft = document.createElement('div');
  47. this.dom.shadowBottomLeft = document.createElement('div');
  48. this.dom.shadowTopRight = document.createElement('div');
  49. this.dom.shadowBottomRight = document.createElement('div');
  50. this.dom.root.className = 'vis-timeline';
  51. this.dom.background.className = 'vis-panel vis-background';
  52. this.dom.backgroundVertical.className = 'vis-panel vis-background vis-vertical';
  53. this.dom.backgroundHorizontal.className = 'vis-panel vis-background vis-horizontal';
  54. this.dom.centerContainer.className = 'vis-panel vis-center';
  55. this.dom.leftContainer.className = 'vis-panel vis-left';
  56. this.dom.rightContainer.className = 'vis-panel vis-right';
  57. this.dom.top.className = 'vis-panel vis-top';
  58. this.dom.bottom.className = 'vis-panel vis-bottom';
  59. this.dom.left.className = 'vis-content';
  60. this.dom.center.className = 'vis-content';
  61. this.dom.right.className = 'vis-content';
  62. this.dom.shadowTop.className = 'vis-shadow vis-top';
  63. this.dom.shadowBottom.className = 'vis-shadow vis-bottom';
  64. this.dom.shadowTopLeft.className = 'vis-shadow vis-top';
  65. this.dom.shadowBottomLeft.className = 'vis-shadow vis-bottom';
  66. this.dom.shadowTopRight.className = 'vis-shadow vis-top';
  67. this.dom.shadowBottomRight.className = 'vis-shadow vis-bottom';
  68. this.dom.root.appendChild(this.dom.background);
  69. this.dom.root.appendChild(this.dom.backgroundVertical);
  70. this.dom.root.appendChild(this.dom.backgroundHorizontal);
  71. this.dom.root.appendChild(this.dom.centerContainer);
  72. this.dom.root.appendChild(this.dom.leftContainer);
  73. this.dom.root.appendChild(this.dom.rightContainer);
  74. this.dom.root.appendChild(this.dom.top);
  75. this.dom.root.appendChild(this.dom.bottom);
  76. this.dom.centerContainer.appendChild(this.dom.center);
  77. this.dom.leftContainer.appendChild(this.dom.left);
  78. this.dom.rightContainer.appendChild(this.dom.right);
  79. this.dom.centerContainer.appendChild(this.dom.shadowTop);
  80. this.dom.centerContainer.appendChild(this.dom.shadowBottom);
  81. this.dom.leftContainer.appendChild(this.dom.shadowTopLeft);
  82. this.dom.leftContainer.appendChild(this.dom.shadowBottomLeft);
  83. this.dom.rightContainer.appendChild(this.dom.shadowTopRight);
  84. this.dom.rightContainer.appendChild(this.dom.shadowBottomRight);
  85. this.on('rangechange', this.redraw.bind(this));
  86. this.on('touch', this._onTouch.bind(this));
  87. this.on('pan', this._onDrag.bind(this));
  88. var me = this;
  89. this.on('change', function (properties) {
  90. if (properties && properties.queue == true) {
  91. // redraw once on next tick
  92. if (!me._redrawTimer) {
  93. me._redrawTimer = setTimeout(function () {
  94. me._redrawTimer = null;
  95. me._redraw();
  96. }, 0)
  97. }
  98. }
  99. else {
  100. // redraw immediately
  101. me._redraw();
  102. }
  103. });
  104. // create event listeners for all interesting events, these events will be
  105. // emitted via emitter
  106. this.hammer = new Hammer(this.dom.root);
  107. this.hammer.get('pinch').set({enable: true});
  108. this.listeners = {};
  109. var events = [
  110. 'tap', 'doubletap', 'press',
  111. 'pinch',
  112. 'pan', 'panstart', 'panmove', 'panend'
  113. // TODO: cleanup
  114. //'touch', 'pinch',
  115. //'tap', 'doubletap', 'hold',
  116. //'dragstart', 'drag', 'dragend',
  117. //'mousewheel', 'DOMMouseScroll' // DOMMouseScroll is needed for Firefox
  118. ];
  119. events.forEach(function (type) {
  120. var listener = function (event) {
  121. if (me.isActive()) {
  122. me.emit(type, event);
  123. }
  124. };
  125. me.hammer.on(type, listener);
  126. me.listeners[type] = listener;
  127. });
  128. // emulate a touch event (emitted before the start of a pan, pinch, tap, or press)
  129. hammerUtil.onTouch(this.hammer, function (event) {
  130. me.emit('touch', event);
  131. }.bind(this));
  132. // emulate a release event (emitted after a pan, pinch, tap, or press)
  133. hammerUtil.onRelease(this.hammer, function (event) {
  134. me.emit('release', event);
  135. }.bind(this));
  136. function onMouseWheel(event) {
  137. if (me.isActive()) {
  138. me.emit('mousewheel', event);
  139. }
  140. }
  141. this.dom.root.addEventListener('mousewheel', onMouseWheel);
  142. this.dom.root.addEventListener('DOMMouseScroll', onMouseWheel);
  143. // size properties of each of the panels
  144. this.props = {
  145. root: {},
  146. background: {},
  147. centerContainer: {},
  148. leftContainer: {},
  149. rightContainer: {},
  150. center: {},
  151. left: {},
  152. right: {},
  153. top: {},
  154. bottom: {},
  155. border: {},
  156. scrollTop: 0,
  157. scrollTopMin: 0
  158. };
  159. this.customTimes = [];
  160. // store state information needed for touch events
  161. this.touch = {};
  162. this.redrawCount = 0;
  163. // attach the root panel to the provided container
  164. if (!container) throw new Error('No container provided');
  165. container.appendChild(this.dom.root);
  166. };
  167. /**
  168. * Set options. Options will be passed to all components loaded in the Timeline.
  169. * @param {Object} [options]
  170. * {String} orientation
  171. * Vertical orientation for the Timeline,
  172. * can be 'bottom' (default) or 'top'.
  173. * {String | Number} width
  174. * Width for the timeline, a number in pixels or
  175. * a css string like '1000px' or '75%'. '100%' by default.
  176. * {String | Number} height
  177. * Fixed height for the Timeline, a number in pixels or
  178. * a css string like '400px' or '75%'. If undefined,
  179. * The Timeline will automatically size such that
  180. * its contents fit.
  181. * {String | Number} minHeight
  182. * Minimum height for the Timeline, a number in pixels or
  183. * a css string like '400px' or '75%'.
  184. * {String | Number} maxHeight
  185. * Maximum height for the Timeline, a number in pixels or
  186. * a css string like '400px' or '75%'.
  187. * {Number | Date | String} start
  188. * Start date for the visible window
  189. * {Number | Date | String} end
  190. * End date for the visible window
  191. */
  192. Core.prototype.setOptions = function (options) {
  193. if (options) {
  194. // copy the known options
  195. var fields = ['width', 'height', 'minHeight', 'maxHeight', 'autoResize', 'start', 'end', 'clickToUse', 'dataAttributes', 'hiddenDates'];
  196. util.selectiveExtend(fields, this.options, options);
  197. if ('orientation' in options) {
  198. if (typeof options.orientation === 'string') {
  199. this.options.orientation = options.orientation;
  200. }
  201. else if (typeof options.orientation === 'object' && 'axis' in options.orientation) {
  202. this.options.orientation = options.orientation.axis;
  203. }
  204. }
  205. if (this.options.orientation === 'both') {
  206. if (!this.timeAxis2) {
  207. var timeAxis2 = this.timeAxis2 = new TimeAxis(this.body);
  208. timeAxis2.setOptions = function (options) {
  209. var _options = options ? util.extend({}, options) : {};
  210. _options.orientation = 'top'; // override the orientation option, always top
  211. TimeAxis.prototype.setOptions.call(timeAxis2, _options);
  212. };
  213. this.components.push(timeAxis2);
  214. }
  215. }
  216. else {
  217. if (this.timeAxis2) {
  218. var index = this.components.indexOf(this.timeAxis2);
  219. if (index !== -1) {
  220. this.components.splice(index, 1);
  221. }
  222. this.timeAxis2.destroy();
  223. this.timeAxis2 = null;
  224. }
  225. }
  226. if ('hiddenDates' in this.options) {
  227. DateUtil.convertHiddenOptions(this.body, this.options.hiddenDates);
  228. }
  229. if ('clickToUse' in options) {
  230. if (options.clickToUse) {
  231. if (!this.activator) {
  232. this.activator = new Activator(this.dom.root);
  233. }
  234. }
  235. else {
  236. if (this.activator) {
  237. this.activator.destroy();
  238. delete this.activator;
  239. }
  240. }
  241. }
  242. if ('showCustomTime' in options) {
  243. throw new Error('Option `showCustomTime` is deprecated. Create a custom time bar via timeline.addCustomTime(time [, id])');
  244. }
  245. // enable/disable autoResize
  246. this._initAutoResize();
  247. }
  248. // propagate options to all components
  249. this.components.forEach(component => component.setOptions(options));
  250. // redraw everything
  251. this._redraw();
  252. };
  253. /**
  254. * Returns true when the Timeline is active.
  255. * @returns {boolean}
  256. */
  257. Core.prototype.isActive = function () {
  258. return !this.activator || this.activator.active;
  259. };
  260. /**
  261. * Destroy the Core, clean up all DOM elements and event listeners.
  262. */
  263. Core.prototype.destroy = function () {
  264. // unbind datasets
  265. this.setItems(null);
  266. this.setGroups(null);
  267. // remove all event listeners
  268. this.off();
  269. // stop checking for changed size
  270. this._stopAutoResize();
  271. // remove from DOM
  272. if (this.dom.root.parentNode) {
  273. this.dom.root.parentNode.removeChild(this.dom.root);
  274. }
  275. this.dom = null;
  276. // remove Activator
  277. if (this.activator) {
  278. this.activator.destroy();
  279. delete this.activator;
  280. }
  281. // cleanup hammer touch events
  282. for (var event in this.listeners) {
  283. if (this.listeners.hasOwnProperty(event)) {
  284. delete this.listeners[event];
  285. }
  286. }
  287. this.listeners = null;
  288. this.hammer = null;
  289. // give all components the opportunity to cleanup
  290. this.components.forEach(component => component.destroy());
  291. this.body = null;
  292. };
  293. /**
  294. * Set a custom time bar
  295. * @param {Date} time
  296. * @param {number} [id=undefined] Optional id of the custom time bar to be adjusted.
  297. */
  298. Core.prototype.setCustomTime = function (time, id) {
  299. var customTimes = this.customTimes.filter(function (component) {
  300. return id === component.options.id;
  301. });
  302. if (customTimes.length === 0) {
  303. throw new Error('No custom time bar found with id ' + JSON.stringify(id))
  304. }
  305. if (customTimes.length > 0) {
  306. customTimes[0].setCustomTime(time);
  307. }
  308. };
  309. /**
  310. * Retrieve the current custom time.
  311. * @param {number} [id=undefined] Id of the custom time bar.
  312. * @return {Date | undefined} customTime
  313. */
  314. Core.prototype.getCustomTime = function(id) {
  315. var customTimes = this.customTimes.filter(function (component) {
  316. return component.options.id === id;
  317. });
  318. if (customTimes.length === 0) {
  319. throw new Error('No custom time bar found with id ' + JSON.stringify(id))
  320. }
  321. return customTimes[0].getCustomTime();
  322. };
  323. /**
  324. * Add custom vertical bar
  325. * @param {Date | String | Number} [time] A Date, unix timestamp, or
  326. * ISO date string. Time point where
  327. * the new bar should be placed.
  328. * If not provided, `new Date()` will
  329. * be used.
  330. * @param {Number | String} [id=undefined] Id of the new bar. Optional
  331. * @return {Number | String} Returns the id of the new bar
  332. */
  333. Core.prototype.addCustomTime = function (time, id) {
  334. var timestamp = time !== undefined
  335. ? util.convert(time, 'Date').valueOf()
  336. : new Date();
  337. var exists = this.customTimes.some(function (customTime) {
  338. return customTime.options.id === id;
  339. });
  340. if (exists) {
  341. throw new Error('A custom time with id ' + JSON.stringify(id) + ' already exists');
  342. }
  343. var customTime = new CustomTime(this.body, {
  344. time : timestamp,
  345. id : id
  346. });
  347. this.customTimes.push(customTime);
  348. this.components.push(customTime);
  349. this.redraw();
  350. return id;
  351. };
  352. /**
  353. * Remove previously added custom bar
  354. * @param {int} id ID of the custom bar to be removed
  355. * @return {boolean} True if the bar exists and is removed, false otherwise
  356. */
  357. Core.prototype.removeCustomTime = function (id) {
  358. var customTimes = this.customTimes.filter(function (bar) {
  359. return (bar.options.id === id);
  360. });
  361. if (customTimes.length === 0) {
  362. throw new Error('No custom time bar found with id ' + JSON.stringify(id))
  363. }
  364. customTimes.forEach(function (customTime) {
  365. this.customTimes.splice(this.customTimes.indexOf(customTime), 1);
  366. this.components.splice(this.components.indexOf(customTime), 1);
  367. customTime.destroy();
  368. }.bind(this))
  369. };
  370. /**
  371. * Get the id's of the currently visible items.
  372. * @returns {Array} The ids of the visible items
  373. */
  374. Core.prototype.getVisibleItems = function() {
  375. return this.itemSet && this.itemSet.getVisibleItems() || [];
  376. };
  377. /**
  378. * Set Core window such that it fits all items
  379. * @param {Object} [options] Available options:
  380. * `animation: boolean | {duration: number, easingFunction: string}`
  381. * If true (default), the range is animated
  382. * smoothly to the new window. An object can be
  383. * provided to specify duration and easing function.
  384. * Default duration is 500 ms, and default easing
  385. * function is 'easeInOutQuad'.
  386. */
  387. Core.prototype.fit = function(options) {
  388. var range = this._getDataRange();
  389. // skip range set if there is no start and end date
  390. if (range.start === null && range.end === null) {
  391. return;
  392. }
  393. var animation = (options && options.animation !== undefined) ? options.animation : true;
  394. this.range.setRange(range.start, range.end, animation);
  395. };
  396. /**
  397. * Calculate the data range of the items and applies a 5% window around it.
  398. * @returns {{start: Date | null, end: Date | null}}
  399. * @protected
  400. */
  401. Core.prototype._getDataRange = function() {
  402. // apply the data range as range
  403. var dataRange = this.getItemRange();
  404. // add 5% space on both sides
  405. var start = dataRange.min;
  406. var end = dataRange.max;
  407. if (start != null && end != null) {
  408. var interval = (end.valueOf() - start.valueOf());
  409. if (interval <= 0) {
  410. // prevent an empty interval
  411. interval = 24 * 60 * 60 * 1000; // 1 day
  412. }
  413. start = new Date(start.valueOf() - interval * 0.05);
  414. end = new Date(end.valueOf() + interval * 0.05);
  415. }
  416. return {
  417. start: start,
  418. end: end
  419. }
  420. };
  421. /**
  422. * Set the visible window. Both parameters are optional, you can change only
  423. * start or only end. Syntax:
  424. *
  425. * TimeLine.setWindow(start, end)
  426. * TimeLine.setWindow(start, end, options)
  427. * TimeLine.setWindow(range)
  428. *
  429. * Where start and end can be a Date, number, or string, and range is an
  430. * object with properties start and end.
  431. *
  432. * @param {Date | Number | String | Object} [start] Start date of visible window
  433. * @param {Date | Number | String} [end] End date of visible window
  434. * @param {Object} [options] Available options:
  435. * `animation: boolean | {duration: number, easingFunction: string}`
  436. * If true (default), the range is animated
  437. * smoothly to the new window. An object can be
  438. * provided to specify duration and easing function.
  439. * Default duration is 500 ms, and default easing
  440. * function is 'easeInOutQuad'.
  441. */
  442. Core.prototype.setWindow = function(start, end, options) {
  443. var animation;
  444. if (arguments.length == 1) {
  445. var range = arguments[0];
  446. animation = (range.animation !== undefined) ? range.animation : true;
  447. this.range.setRange(range.start, range.end, animation);
  448. }
  449. else {
  450. animation = (options && options.animation !== undefined) ? options.animation : true;
  451. this.range.setRange(start, end, animation);
  452. }
  453. };
  454. /**
  455. * Move the window such that given time is centered on screen.
  456. * @param {Date | Number | String} time
  457. * @param {Object} [options] Available options:
  458. * `animation: boolean | {duration: number, easingFunction: string}`
  459. * If true (default), the range is animated
  460. * smoothly to the new window. An object can be
  461. * provided to specify duration and easing function.
  462. * Default duration is 500 ms, and default easing
  463. * function is 'easeInOutQuad'.
  464. */
  465. Core.prototype.moveTo = function(time, options) {
  466. var interval = this.range.end - this.range.start;
  467. var t = util.convert(time, 'Date').valueOf();
  468. var start = t - interval / 2;
  469. var end = t + interval / 2;
  470. var animation = (options && options.animation !== undefined) ? options.animation : true;
  471. this.range.setRange(start, end, animation);
  472. };
  473. /**
  474. * Get the visible window
  475. * @return {{start: Date, end: Date}} Visible range
  476. */
  477. Core.prototype.getWindow = function() {
  478. var range = this.range.getRange();
  479. return {
  480. start: new Date(range.start),
  481. end: new Date(range.end)
  482. };
  483. };
  484. /**
  485. * Force a redraw. Can be overridden by implementations of Core
  486. */
  487. Core.prototype.redraw = function() {
  488. this._redraw();
  489. };
  490. /**
  491. * Redraw for internal use. Redraws all components. See also the public
  492. * method redraw.
  493. * @protected
  494. */
  495. Core.prototype._redraw = function() {
  496. var resized = false;
  497. var options = this.options;
  498. var props = this.props;
  499. var dom = this.dom;
  500. if (!dom) return; // when destroyed
  501. DateUtil.updateHiddenDates(this.body, this.options.hiddenDates);
  502. // update class names
  503. if (options.orientation == 'top') {
  504. util.addClassName(dom.root, 'vis-top');
  505. util.removeClassName(dom.root, 'vis-bottom');
  506. }
  507. else {
  508. util.removeClassName(dom.root, 'vis-top');
  509. util.addClassName(dom.root, 'vis-bottom');
  510. }
  511. // update root width and height options
  512. dom.root.style.maxHeight = util.option.asSize(options.maxHeight, '');
  513. dom.root.style.minHeight = util.option.asSize(options.minHeight, '');
  514. dom.root.style.width = util.option.asSize(options.width, '');
  515. // calculate border widths
  516. props.border.left = (dom.centerContainer.offsetWidth - dom.centerContainer.clientWidth) / 2;
  517. props.border.right = props.border.left;
  518. props.border.top = (dom.centerContainer.offsetHeight - dom.centerContainer.clientHeight) / 2;
  519. props.border.bottom = props.border.top;
  520. var borderRootHeight= dom.root.offsetHeight - dom.root.clientHeight;
  521. var borderRootWidth = dom.root.offsetWidth - dom.root.clientWidth;
  522. // workaround for a bug in IE: the clientWidth of an element with
  523. // a height:0px and overflow:hidden is not calculated and always has value 0
  524. if (dom.centerContainer.clientHeight === 0) {
  525. props.border.left = props.border.top;
  526. props.border.right = props.border.left;
  527. }
  528. if (dom.root.clientHeight === 0) {
  529. borderRootWidth = borderRootHeight;
  530. }
  531. // calculate the heights. If any of the side panels is empty, we set the height to
  532. // minus the border width, such that the border will be invisible
  533. props.center.height = dom.center.offsetHeight;
  534. props.left.height = dom.left.offsetHeight;
  535. props.right.height = dom.right.offsetHeight;
  536. props.top.height = dom.top.clientHeight || -props.border.top;
  537. props.bottom.height = dom.bottom.clientHeight || -props.border.bottom;
  538. // TODO: compensate borders when any of the panels is empty.
  539. // apply auto height
  540. // TODO: only calculate autoHeight when needed (else we cause an extra reflow/repaint of the DOM)
  541. var contentHeight = Math.max(props.left.height, props.center.height, props.right.height);
  542. var autoHeight = props.top.height + contentHeight + props.bottom.height +
  543. borderRootHeight + props.border.top + props.border.bottom;
  544. dom.root.style.height = util.option.asSize(options.height, autoHeight + 'px');
  545. // calculate heights of the content panels
  546. props.root.height = dom.root.offsetHeight;
  547. props.background.height = props.root.height - borderRootHeight;
  548. var containerHeight = props.root.height - props.top.height - props.bottom.height -
  549. borderRootHeight;
  550. props.centerContainer.height = containerHeight;
  551. props.leftContainer.height = containerHeight;
  552. props.rightContainer.height = props.leftContainer.height;
  553. // calculate the widths of the panels
  554. props.root.width = dom.root.offsetWidth;
  555. props.background.width = props.root.width - borderRootWidth;
  556. props.left.width = dom.leftContainer.clientWidth || -props.border.left;
  557. props.leftContainer.width = props.left.width;
  558. props.right.width = dom.rightContainer.clientWidth || -props.border.right;
  559. props.rightContainer.width = props.right.width;
  560. var centerWidth = props.root.width - props.left.width - props.right.width - borderRootWidth;
  561. props.center.width = centerWidth;
  562. props.centerContainer.width = centerWidth;
  563. props.top.width = centerWidth;
  564. props.bottom.width = centerWidth;
  565. // resize the panels
  566. dom.background.style.height = props.background.height + 'px';
  567. dom.backgroundVertical.style.height = props.background.height + 'px';
  568. dom.backgroundHorizontal.style.height = props.centerContainer.height + 'px';
  569. dom.centerContainer.style.height = props.centerContainer.height + 'px';
  570. dom.leftContainer.style.height = props.leftContainer.height + 'px';
  571. dom.rightContainer.style.height = props.rightContainer.height + 'px';
  572. dom.background.style.width = props.background.width + 'px';
  573. dom.backgroundVertical.style.width = props.centerContainer.width + 'px';
  574. dom.backgroundHorizontal.style.width = props.background.width + 'px';
  575. dom.centerContainer.style.width = props.center.width + 'px';
  576. dom.top.style.width = props.top.width + 'px';
  577. dom.bottom.style.width = props.bottom.width + 'px';
  578. // reposition the panels
  579. dom.background.style.left = '0';
  580. dom.background.style.top = '0';
  581. dom.backgroundVertical.style.left = (props.left.width + props.border.left) + 'px';
  582. dom.backgroundVertical.style.top = '0';
  583. dom.backgroundHorizontal.style.left = '0';
  584. dom.backgroundHorizontal.style.top = props.top.height + 'px';
  585. dom.centerContainer.style.left = props.left.width + 'px';
  586. dom.centerContainer.style.top = props.top.height + 'px';
  587. dom.leftContainer.style.left = '0';
  588. dom.leftContainer.style.top = props.top.height + 'px';
  589. dom.rightContainer.style.left = (props.left.width + props.center.width) + 'px';
  590. dom.rightContainer.style.top = props.top.height + 'px';
  591. dom.top.style.left = props.left.width + 'px';
  592. dom.top.style.top = '0';
  593. dom.bottom.style.left = props.left.width + 'px';
  594. dom.bottom.style.top = (props.top.height + props.centerContainer.height) + 'px';
  595. // update the scrollTop, feasible range for the offset can be changed
  596. // when the height of the Core or of the contents of the center changed
  597. this._updateScrollTop();
  598. // reposition the scrollable contents
  599. var offset = this.props.scrollTop;
  600. if (options.orientation == 'bottom') {
  601. offset += Math.max(this.props.centerContainer.height - this.props.center.height -
  602. this.props.border.top - this.props.border.bottom, 0);
  603. }
  604. dom.center.style.left = '0';
  605. dom.center.style.top = offset + 'px';
  606. dom.left.style.left = '0';
  607. dom.left.style.top = offset + 'px';
  608. dom.right.style.left = '0';
  609. dom.right.style.top = offset + 'px';
  610. // show shadows when vertical scrolling is available
  611. var visibilityTop = this.props.scrollTop == 0 ? 'hidden' : '';
  612. var visibilityBottom = this.props.scrollTop == this.props.scrollTopMin ? 'hidden' : '';
  613. dom.shadowTop.style.visibility = visibilityTop;
  614. dom.shadowBottom.style.visibility = visibilityBottom;
  615. dom.shadowTopLeft.style.visibility = visibilityTop;
  616. dom.shadowBottomLeft.style.visibility = visibilityBottom;
  617. dom.shadowTopRight.style.visibility = visibilityTop;
  618. dom.shadowBottomRight.style.visibility = visibilityBottom;
  619. // redraw all components
  620. this.components.forEach(function (component) {
  621. resized = component.redraw() || resized;
  622. });
  623. if (resized) {
  624. // keep repainting until all sizes are settled
  625. var MAX_REDRAWS = 3; // maximum number of consecutive redraws
  626. if (this.redrawCount < MAX_REDRAWS) {
  627. this.redrawCount++;
  628. this._redraw();
  629. }
  630. else {
  631. console.log('WARNING: infinite loop in redraw?');
  632. }
  633. this.redrawCount = 0;
  634. }
  635. };
  636. // TODO: deprecated since version 1.1.0, remove some day
  637. Core.prototype.repaint = function () {
  638. throw new Error('Function repaint is deprecated. Use redraw instead.');
  639. };
  640. /**
  641. * Set a current time. This can be used for example to ensure that a client's
  642. * time is synchronized with a shared server time.
  643. * Only applicable when option `showCurrentTime` is true.
  644. * @param {Date | String | Number} time A Date, unix timestamp, or
  645. * ISO date string.
  646. */
  647. Core.prototype.setCurrentTime = function(time) {
  648. if (!this.currentTime) {
  649. throw new Error('Option showCurrentTime must be true');
  650. }
  651. this.currentTime.setCurrentTime(time);
  652. };
  653. /**
  654. * Get the current time.
  655. * Only applicable when option `showCurrentTime` is true.
  656. * @return {Date} Returns the current time.
  657. */
  658. Core.prototype.getCurrentTime = function() {
  659. if (!this.currentTime) {
  660. throw new Error('Option showCurrentTime must be true');
  661. }
  662. return this.currentTime.getCurrentTime();
  663. };
  664. /**
  665. * Convert a position on screen (pixels) to a datetime
  666. * @param {int} x Position on the screen in pixels
  667. * @return {Date} time The datetime the corresponds with given position x
  668. * @protected
  669. */
  670. // TODO: move this function to Range
  671. Core.prototype._toTime = function(x) {
  672. return DateUtil.toTime(this, x, this.props.center.width);
  673. };
  674. /**
  675. * Convert a position on the global screen (pixels) to a datetime
  676. * @param {int} x Position on the screen in pixels
  677. * @return {Date} time The datetime the corresponds with given position x
  678. * @protected
  679. */
  680. // TODO: move this function to Range
  681. Core.prototype._toGlobalTime = function(x) {
  682. return DateUtil.toTime(this, x, this.props.root.width);
  683. //var conversion = this.range.conversion(this.props.root.width);
  684. //return new Date(x / conversion.scale + conversion.offset);
  685. };
  686. /**
  687. * Convert a datetime (Date object) into a position on the screen
  688. * @param {Date} time A date
  689. * @return {int} x The position on the screen in pixels which corresponds
  690. * with the given date.
  691. * @protected
  692. */
  693. // TODO: move this function to Range
  694. Core.prototype._toScreen = function(time) {
  695. return DateUtil.toScreen(this, time, this.props.center.width);
  696. };
  697. /**
  698. * Convert a datetime (Date object) into a position on the root
  699. * This is used to get the pixel density estimate for the screen, not the center panel
  700. * @param {Date} time A date
  701. * @return {int} x The position on root in pixels which corresponds
  702. * with the given date.
  703. * @protected
  704. */
  705. // TODO: move this function to Range
  706. Core.prototype._toGlobalScreen = function(time) {
  707. return DateUtil.toScreen(this, time, this.props.root.width);
  708. //var conversion = this.range.conversion(this.props.root.width);
  709. //return (time.valueOf() - conversion.offset) * conversion.scale;
  710. };
  711. /**
  712. * Initialize watching when option autoResize is true
  713. * @private
  714. */
  715. Core.prototype._initAutoResize = function () {
  716. if (this.options.autoResize == true) {
  717. this._startAutoResize();
  718. }
  719. else {
  720. this._stopAutoResize();
  721. }
  722. };
  723. /**
  724. * Watch for changes in the size of the container. On resize, the Panel will
  725. * automatically redraw itself.
  726. * @private
  727. */
  728. Core.prototype._startAutoResize = function () {
  729. var me = this;
  730. this._stopAutoResize();
  731. this._onResize = function() {
  732. if (me.options.autoResize != true) {
  733. // stop watching when the option autoResize is changed to false
  734. me._stopAutoResize();
  735. return;
  736. }
  737. if (me.dom.root) {
  738. // check whether the frame is resized
  739. // Note: we compare offsetWidth here, not clientWidth. For some reason,
  740. // IE does not restore the clientWidth from 0 to the actual width after
  741. // changing the timeline's container display style from none to visible
  742. if ((me.dom.root.offsetWidth != me.props.lastWidth) ||
  743. (me.dom.root.offsetHeight != me.props.lastHeight)) {
  744. me.props.lastWidth = me.dom.root.offsetWidth;
  745. me.props.lastHeight = me.dom.root.offsetHeight;
  746. me.emit('change');
  747. }
  748. }
  749. };
  750. // add event listener to window resize
  751. util.addEventListener(window, 'resize', this._onResize);
  752. this.watchTimer = setInterval(this._onResize, 1000);
  753. };
  754. /**
  755. * Stop watching for a resize of the frame.
  756. * @private
  757. */
  758. Core.prototype._stopAutoResize = function () {
  759. if (this.watchTimer) {
  760. clearInterval(this.watchTimer);
  761. this.watchTimer = undefined;
  762. }
  763. // remove event listener on window.resize
  764. util.removeEventListener(window, 'resize', this._onResize);
  765. this._onResize = null;
  766. };
  767. /**
  768. * Start moving the timeline vertically
  769. * @param {Event} event
  770. * @private
  771. */
  772. Core.prototype._onTouch = function (event) {
  773. this.touch.allowDragging = true;
  774. this.touch.initialScrollTop = this.props.scrollTop;
  775. };
  776. /**
  777. * Start moving the timeline vertically
  778. * @param {Event} event
  779. * @private
  780. */
  781. Core.prototype._onPinch = function (event) {
  782. this.touch.allowDragging = false;
  783. };
  784. /**
  785. * Move the timeline vertically
  786. * @param {Event} event
  787. * @private
  788. */
  789. Core.prototype._onDrag = function (event) {
  790. // refuse to drag when we where pinching to prevent the timeline make a jump
  791. // when releasing the fingers in opposite order from the touch screen
  792. if (!this.touch.allowDragging) return;
  793. var delta = event.deltaY;
  794. var oldScrollTop = this._getScrollTop();
  795. var newScrollTop = this._setScrollTop(this.touch.initialScrollTop + delta);
  796. if (newScrollTop != oldScrollTop) {
  797. this._redraw(); // TODO: this causes two redraws when dragging, the other is triggered by rangechange already
  798. this.emit("verticalDrag");
  799. }
  800. };
  801. /**
  802. * Apply a scrollTop
  803. * @param {Number} scrollTop
  804. * @returns {Number} scrollTop Returns the applied scrollTop
  805. * @private
  806. */
  807. Core.prototype._setScrollTop = function (scrollTop) {
  808. this.props.scrollTop = scrollTop;
  809. this._updateScrollTop();
  810. return this.props.scrollTop;
  811. };
  812. /**
  813. * Update the current scrollTop when the height of the containers has been changed
  814. * @returns {Number} scrollTop Returns the applied scrollTop
  815. * @private
  816. */
  817. Core.prototype._updateScrollTop = function () {
  818. // recalculate the scrollTopMin
  819. var scrollTopMin = Math.min(this.props.centerContainer.height - this.props.center.height, 0); // is negative or zero
  820. if (scrollTopMin != this.props.scrollTopMin) {
  821. // in case of bottom orientation, change the scrollTop such that the contents
  822. // do not move relative to the time axis at the bottom
  823. if (this.options.orientation == 'bottom') {
  824. this.props.scrollTop += (scrollTopMin - this.props.scrollTopMin);
  825. }
  826. this.props.scrollTopMin = scrollTopMin;
  827. }
  828. // limit the scrollTop to the feasible scroll range
  829. if (this.props.scrollTop > 0) this.props.scrollTop = 0;
  830. if (this.props.scrollTop < scrollTopMin) this.props.scrollTop = scrollTopMin;
  831. return this.props.scrollTop;
  832. };
  833. /**
  834. * Get the current scrollTop
  835. * @returns {number} scrollTop
  836. * @private
  837. */
  838. Core.prototype._getScrollTop = function () {
  839. return this.props.scrollTop;
  840. };
  841. module.exports = Core;