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.

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