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.

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