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.

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