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.

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