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.

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