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.

1062 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. var animation = (options && options.animation !== undefined) ? options.animation : true;
  473. this.range.setRange(min, max, animation);
  474. };
  475. /**
  476. * Calculate the data range of the items start and end dates
  477. * @returns {{min: Date | null, max: Date | null}}
  478. * @protected
  479. */
  480. Core.prototype.getDataRange = function() {
  481. // must be implemented by Timeline and Graph2d
  482. throw new Error('Cannot invoke abstract method getDataRange');
  483. };
  484. /**
  485. * Set the visible window. Both parameters are optional, you can change only
  486. * start or only end. Syntax:
  487. *
  488. * TimeLine.setWindow(start, end)
  489. * TimeLine.setWindow(start, end, options)
  490. * TimeLine.setWindow(range)
  491. *
  492. * Where start and end can be a Date, number, or string, and range is an
  493. * object with properties start and end.
  494. *
  495. * @param {Date | Number | String | Object} [start] Start date of visible window
  496. * @param {Date | Number | String} [end] End date of visible window
  497. * @param {Object} [options] Available options:
  498. * `animation: boolean | {duration: number, easingFunction: string}`
  499. * If true (default), the range is animated
  500. * smoothly to the new window. An object can be
  501. * provided to specify duration and easing function.
  502. * Default duration is 500 ms, and default easing
  503. * function is 'easeInOutQuad'.
  504. */
  505. Core.prototype.setWindow = function(start, end, options) {
  506. var animation;
  507. if (arguments.length == 1) {
  508. var range = arguments[0];
  509. animation = (range.animation !== undefined) ? range.animation : true;
  510. this.range.setRange(range.start, range.end, animation);
  511. }
  512. else {
  513. animation = (options && options.animation !== undefined) ? options.animation : true;
  514. this.range.setRange(start, end, animation);
  515. }
  516. };
  517. /**
  518. * Move the window such that given time is centered on screen.
  519. * @param {Date | Number | String} time
  520. * @param {Object} [options] Available options:
  521. * `animation: boolean | {duration: number, easingFunction: string}`
  522. * If true (default), the range is animated
  523. * smoothly to the new window. An object can be
  524. * provided to specify duration and easing function.
  525. * Default duration is 500 ms, and default easing
  526. * function is 'easeInOutQuad'.
  527. */
  528. Core.prototype.moveTo = function(time, options) {
  529. var interval = this.range.end - this.range.start;
  530. var t = util.convert(time, 'Date').valueOf();
  531. var start = t - interval / 2;
  532. var end = t + interval / 2;
  533. var animation = (options && options.animation !== undefined) ? options.animation : true;
  534. this.range.setRange(start, end, animation);
  535. };
  536. /**
  537. * Get the visible window
  538. * @return {{start: Date, end: Date}} Visible range
  539. */
  540. Core.prototype.getWindow = function() {
  541. var range = this.range.getRange();
  542. return {
  543. start: new Date(range.start),
  544. end: new Date(range.end)
  545. };
  546. };
  547. /**
  548. * Force a redraw. Can be overridden by implementations of Core
  549. *
  550. * Note: this function will be overridden on construction with a trottled version
  551. */
  552. Core.prototype.redraw = function() {
  553. this._redraw();
  554. };
  555. /**
  556. * Redraw for internal use. Redraws all components. See also the public
  557. * method redraw.
  558. * @protected
  559. */
  560. Core.prototype._redraw = function() {
  561. this.redrawCount++;
  562. var resized = false;
  563. var options = this.options;
  564. var props = this.props;
  565. var dom = this.dom;
  566. if (!dom || !dom.container || dom.root.offsetWidth == 0) return; // when destroyed, or invisible
  567. DateUtil.updateHiddenDates(this.options.moment, this.body, this.options.hiddenDates);
  568. // update class names
  569. if (options.orientation == 'top') {
  570. util.addClassName(dom.root, 'vis-top');
  571. util.removeClassName(dom.root, 'vis-bottom');
  572. }
  573. else {
  574. util.removeClassName(dom.root, 'vis-top');
  575. util.addClassName(dom.root, 'vis-bottom');
  576. }
  577. // update root width and height options
  578. dom.root.style.maxHeight = util.option.asSize(options.maxHeight, '');
  579. dom.root.style.minHeight = util.option.asSize(options.minHeight, '');
  580. dom.root.style.width = util.option.asSize(options.width, '');
  581. // calculate border widths
  582. props.border.left = (dom.centerContainer.offsetWidth - dom.centerContainer.clientWidth) / 2;
  583. props.border.right = props.border.left;
  584. props.border.top = (dom.centerContainer.offsetHeight - dom.centerContainer.clientHeight) / 2;
  585. props.border.bottom = props.border.top;
  586. var borderRootHeight= dom.root.offsetHeight - dom.root.clientHeight;
  587. var borderRootWidth = dom.root.offsetWidth - dom.root.clientWidth;
  588. // workaround for a bug in IE: the clientWidth of an element with
  589. // a height:0px and overflow:hidden is not calculated and always has value 0
  590. if (dom.centerContainer.clientHeight === 0) {
  591. props.border.left = props.border.top;
  592. props.border.right = props.border.left;
  593. }
  594. if (dom.root.clientHeight === 0) {
  595. borderRootWidth = borderRootHeight;
  596. }
  597. // calculate the heights. If any of the side panels is empty, we set the height to
  598. // minus the border width, such that the border will be invisible
  599. props.center.height = dom.center.offsetHeight;
  600. props.left.height = dom.left.offsetHeight;
  601. props.right.height = dom.right.offsetHeight;
  602. props.top.height = dom.top.clientHeight || -props.border.top;
  603. props.bottom.height = dom.bottom.clientHeight || -props.border.bottom;
  604. // TODO: compensate borders when any of the panels is empty.
  605. // apply auto height
  606. // TODO: only calculate autoHeight when needed (else we cause an extra reflow/repaint of the DOM)
  607. var contentHeight = Math.max(props.left.height, props.center.height, props.right.height);
  608. var autoHeight = props.top.height + contentHeight + props.bottom.height +
  609. borderRootHeight + props.border.top + props.border.bottom;
  610. dom.root.style.height = util.option.asSize(options.height, autoHeight + 'px');
  611. // calculate heights of the content panels
  612. props.root.height = dom.root.offsetHeight;
  613. props.background.height = props.root.height - borderRootHeight;
  614. var containerHeight = props.root.height - props.top.height - props.bottom.height -
  615. borderRootHeight;
  616. props.centerContainer.height = containerHeight;
  617. props.leftContainer.height = containerHeight;
  618. props.rightContainer.height = props.leftContainer.height;
  619. // calculate the widths of the panels
  620. props.root.width = dom.root.offsetWidth;
  621. props.background.width = props.root.width - borderRootWidth;
  622. props.left.width = dom.leftContainer.clientWidth || -props.border.left;
  623. props.leftContainer.width = props.left.width;
  624. props.right.width = dom.rightContainer.clientWidth || -props.border.right;
  625. props.rightContainer.width = props.right.width;
  626. var centerWidth = props.root.width - props.left.width - props.right.width - borderRootWidth;
  627. props.center.width = centerWidth;
  628. props.centerContainer.width = centerWidth;
  629. props.top.width = centerWidth;
  630. props.bottom.width = centerWidth;
  631. // resize the panels
  632. dom.background.style.height = props.background.height + 'px';
  633. dom.backgroundVertical.style.height = props.background.height + 'px';
  634. dom.backgroundHorizontal.style.height = props.centerContainer.height + 'px';
  635. dom.centerContainer.style.height = props.centerContainer.height + 'px';
  636. dom.leftContainer.style.height = props.leftContainer.height + 'px';
  637. dom.rightContainer.style.height = props.rightContainer.height + 'px';
  638. dom.background.style.width = props.background.width + 'px';
  639. dom.backgroundVertical.style.width = props.centerContainer.width + 'px';
  640. dom.backgroundHorizontal.style.width = props.background.width + 'px';
  641. dom.centerContainer.style.width = props.center.width + 'px';
  642. dom.top.style.width = props.top.width + 'px';
  643. dom.bottom.style.width = props.bottom.width + 'px';
  644. // reposition the panels
  645. dom.background.style.left = '0';
  646. dom.background.style.top = '0';
  647. dom.backgroundVertical.style.left = (props.left.width + props.border.left) + 'px';
  648. dom.backgroundVertical.style.top = '0';
  649. dom.backgroundHorizontal.style.left = '0';
  650. dom.backgroundHorizontal.style.top = props.top.height + 'px';
  651. dom.centerContainer.style.left = props.left.width + 'px';
  652. dom.centerContainer.style.top = props.top.height + 'px';
  653. dom.leftContainer.style.left = '0';
  654. dom.leftContainer.style.top = props.top.height + 'px';
  655. dom.rightContainer.style.left = (props.left.width + props.center.width) + 'px';
  656. dom.rightContainer.style.top = props.top.height + 'px';
  657. dom.top.style.left = props.left.width + 'px';
  658. dom.top.style.top = '0';
  659. dom.bottom.style.left = props.left.width + 'px';
  660. dom.bottom.style.top = (props.top.height + props.centerContainer.height) + 'px';
  661. // update the scrollTop, feasible range for the offset can be changed
  662. // when the height of the Core or of the contents of the center changed
  663. this._updateScrollTop();
  664. // reposition the scrollable contents
  665. var offset = this.props.scrollTop;
  666. if (options.orientation.item != 'top') {
  667. offset += Math.max(this.props.centerContainer.height - this.props.center.height -
  668. this.props.border.top - this.props.border.bottom, 0);
  669. }
  670. dom.center.style.left = '0';
  671. dom.center.style.top = offset + 'px';
  672. dom.left.style.left = '0';
  673. dom.left.style.top = offset + 'px';
  674. dom.right.style.left = '0';
  675. dom.right.style.top = offset + 'px';
  676. // show shadows when vertical scrolling is available
  677. var visibilityTop = this.props.scrollTop == 0 ? 'hidden' : '';
  678. var visibilityBottom = this.props.scrollTop == this.props.scrollTopMin ? 'hidden' : '';
  679. dom.shadowTop.style.visibility = visibilityTop;
  680. dom.shadowBottom.style.visibility = visibilityBottom;
  681. dom.shadowTopLeft.style.visibility = visibilityTop;
  682. dom.shadowBottomLeft.style.visibility = visibilityBottom;
  683. dom.shadowTopRight.style.visibility = visibilityTop;
  684. dom.shadowBottomRight.style.visibility = visibilityBottom;
  685. // enable/disable vertical panning
  686. var contentsOverflow = this.props.center.height > this.props.centerContainer.height;
  687. this.hammer.get('pan').set({
  688. direction: contentsOverflow ? Hammer.DIRECTION_ALL : Hammer.DIRECTION_HORIZONTAL
  689. });
  690. // redraw all components
  691. this.components.forEach(function (component) {
  692. resized = component.redraw() || resized;
  693. });
  694. var MAX_REDRAW = 5;
  695. if (resized) {
  696. if (this.redrawCount < MAX_REDRAW) {
  697. this.body.emitter.emit('_change');
  698. return;
  699. }
  700. else {
  701. console.log('WARNING: infinite loop in redraw?');
  702. }
  703. } else {
  704. this.redrawCount = 0;
  705. }
  706. this.initialDrawDone = true;
  707. //Emit public 'changed' event for UI updates, see issue #1592
  708. this.body.emitter.emit("changed");
  709. };
  710. // TODO: deprecated since version 1.1.0, remove some day
  711. Core.prototype.repaint = function () {
  712. throw new Error('Function repaint is deprecated. Use redraw instead.');
  713. };
  714. /**
  715. * Set a current time. This can be used for example to ensure that a client's
  716. * time is synchronized with a shared server time.
  717. * Only applicable when option `showCurrentTime` is true.
  718. * @param {Date | String | Number} time A Date, unix timestamp, or
  719. * ISO date string.
  720. */
  721. Core.prototype.setCurrentTime = function(time) {
  722. if (!this.currentTime) {
  723. throw new Error('Option showCurrentTime must be true');
  724. }
  725. this.currentTime.setCurrentTime(time);
  726. };
  727. /**
  728. * Get the current time.
  729. * Only applicable when option `showCurrentTime` is true.
  730. * @return {Date} Returns the current time.
  731. */
  732. Core.prototype.getCurrentTime = function() {
  733. if (!this.currentTime) {
  734. throw new Error('Option showCurrentTime must be true');
  735. }
  736. return this.currentTime.getCurrentTime();
  737. };
  738. /**
  739. * Convert a position on screen (pixels) to a datetime
  740. * @param {int} x Position on the screen in pixels
  741. * @return {Date} time The datetime the corresponds with given position x
  742. * @protected
  743. */
  744. // TODO: move this function to Range
  745. Core.prototype._toTime = function(x) {
  746. return DateUtil.toTime(this, x, this.props.center.width);
  747. };
  748. /**
  749. * Convert a position on the global screen (pixels) to a datetime
  750. * @param {int} x Position on the screen in pixels
  751. * @return {Date} time The datetime the corresponds with given position x
  752. * @protected
  753. */
  754. // TODO: move this function to Range
  755. Core.prototype._toGlobalTime = function(x) {
  756. return DateUtil.toTime(this, x, this.props.root.width);
  757. //var conversion = this.range.conversion(this.props.root.width);
  758. //return new Date(x / conversion.scale + conversion.offset);
  759. };
  760. /**
  761. * Convert a datetime (Date object) into a position on the screen
  762. * @param {Date} time A date
  763. * @return {int} x The position on the screen in pixels which corresponds
  764. * with the given date.
  765. * @protected
  766. */
  767. // TODO: move this function to Range
  768. Core.prototype._toScreen = function(time) {
  769. return DateUtil.toScreen(this, time, this.props.center.width);
  770. };
  771. /**
  772. * Convert a datetime (Date object) into a position on the root
  773. * This is used to get the pixel density estimate for the screen, not the center panel
  774. * @param {Date} time A date
  775. * @return {int} x The position on root in pixels which corresponds
  776. * with the given date.
  777. * @protected
  778. */
  779. // TODO: move this function to Range
  780. Core.prototype._toGlobalScreen = function(time) {
  781. return DateUtil.toScreen(this, time, this.props.root.width);
  782. //var conversion = this.range.conversion(this.props.root.width);
  783. //return (time.valueOf() - conversion.offset) * conversion.scale;
  784. };
  785. /**
  786. * Initialize watching when option autoResize is true
  787. * @private
  788. */
  789. Core.prototype._initAutoResize = function () {
  790. if (this.options.autoResize == true) {
  791. this._startAutoResize();
  792. }
  793. else {
  794. this._stopAutoResize();
  795. }
  796. };
  797. /**
  798. * Watch for changes in the size of the container. On resize, the Panel will
  799. * automatically redraw itself.
  800. * @private
  801. */
  802. Core.prototype._startAutoResize = function () {
  803. var me = this;
  804. this._stopAutoResize();
  805. this._onResize = function() {
  806. if (me.options.autoResize != true) {
  807. // stop watching when the option autoResize is changed to false
  808. me._stopAutoResize();
  809. return;
  810. }
  811. if (me.dom.root) {
  812. // check whether the frame is resized
  813. // Note: we compare offsetWidth here, not clientWidth. For some reason,
  814. // IE does not restore the clientWidth from 0 to the actual width after
  815. // changing the timeline's container display style from none to visible
  816. if ((me.dom.root.offsetWidth != me.props.lastWidth) ||
  817. (me.dom.root.offsetHeight != me.props.lastHeight)) {
  818. me.props.lastWidth = me.dom.root.offsetWidth;
  819. me.props.lastHeight = me.dom.root.offsetHeight;
  820. me.body.emitter.emit('_change');
  821. }
  822. }
  823. };
  824. // add event listener to window resize
  825. util.addEventListener(window, 'resize', this._onResize);
  826. //Prevent initial unnecessary redraw
  827. if (me.dom.root) {
  828. me.props.lastWidth = me.dom.root.offsetWidth;
  829. me.props.lastHeight = me.dom.root.offsetHeight;
  830. }
  831. this.watchTimer = setInterval(this._onResize, 1000);
  832. };
  833. /**
  834. * Stop watching for a resize of the frame.
  835. * @private
  836. */
  837. Core.prototype._stopAutoResize = function () {
  838. if (this.watchTimer) {
  839. clearInterval(this.watchTimer);
  840. this.watchTimer = undefined;
  841. }
  842. // remove event listener on window.resize
  843. if (this._onResize) {
  844. util.removeEventListener(window, 'resize', this._onResize);
  845. this._onResize = null;
  846. }
  847. };
  848. /**
  849. * Start moving the timeline vertically
  850. * @param {Event} event
  851. * @private
  852. */
  853. Core.prototype._onTouch = function (event) {
  854. this.touch.allowDragging = true;
  855. this.touch.initialScrollTop = this.props.scrollTop;
  856. };
  857. /**
  858. * Start moving the timeline vertically
  859. * @param {Event} event
  860. * @private
  861. */
  862. Core.prototype._onPinch = function (event) {
  863. this.touch.allowDragging = false;
  864. };
  865. /**
  866. * Move the timeline vertically
  867. * @param {Event} event
  868. * @private
  869. */
  870. Core.prototype._onDrag = function (event) {
  871. // refuse to drag when we where pinching to prevent the timeline make a jump
  872. // when releasing the fingers in opposite order from the touch screen
  873. if (!this.touch.allowDragging) return;
  874. var delta = event.deltaY;
  875. var oldScrollTop = this._getScrollTop();
  876. var newScrollTop = this._setScrollTop(this.touch.initialScrollTop + delta);
  877. if (newScrollTop != oldScrollTop) {
  878. this.emit("verticalDrag");
  879. }
  880. };
  881. /**
  882. * Apply a scrollTop
  883. * @param {Number} scrollTop
  884. * @returns {Number} scrollTop Returns the applied scrollTop
  885. * @private
  886. */
  887. Core.prototype._setScrollTop = function (scrollTop) {
  888. this.props.scrollTop = scrollTop;
  889. this._updateScrollTop();
  890. return this.props.scrollTop;
  891. };
  892. /**
  893. * Update the current scrollTop when the height of the containers has been changed
  894. * @returns {Number} scrollTop Returns the applied scrollTop
  895. * @private
  896. */
  897. Core.prototype._updateScrollTop = function () {
  898. // recalculate the scrollTopMin
  899. var scrollTopMin = Math.min(this.props.centerContainer.height - this.props.center.height, 0); // is negative or zero
  900. if (scrollTopMin != this.props.scrollTopMin) {
  901. // in case of bottom orientation, change the scrollTop such that the contents
  902. // do not move relative to the time axis at the bottom
  903. if (this.options.orientation.item != 'top') {
  904. this.props.scrollTop += (scrollTopMin - this.props.scrollTopMin);
  905. }
  906. this.props.scrollTopMin = scrollTopMin;
  907. }
  908. // limit the scrollTop to the feasible scroll range
  909. if (this.props.scrollTop > 0) this.props.scrollTop = 0;
  910. if (this.props.scrollTop < scrollTopMin) this.props.scrollTop = scrollTopMin;
  911. return this.props.scrollTop;
  912. };
  913. /**
  914. * Get the current scrollTop
  915. * @returns {number} scrollTop
  916. * @private
  917. */
  918. Core.prototype._getScrollTop = function () {
  919. return this.props.scrollTop;
  920. };
  921. /**
  922. * Load a configurator
  923. * @return {Object}
  924. * @private
  925. */
  926. Core.prototype._createConfigurator = function () {
  927. throw new Error('Cannot invoke abstract method _createConfigurator');
  928. };
  929. module.exports = Core;