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