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.

1000 lines
33 KiB

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