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.

1033 lines
35 KiB

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