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.

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