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.

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