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.

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