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.

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