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.

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