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.

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