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.

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