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.

1144 lines
39 KiB

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