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.

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