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.

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