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.

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