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.

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