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.

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