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.

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