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.

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