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.

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