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.

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