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.

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