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.

988 lines
34 KiB

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