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.

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