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.

1250 lines
43 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. * @param {Object} [options] Available options:
  619. * `animation: boolean | {duration: number, easingFunction: string}`
  620. * If true (default), the range is animated
  621. * smoothly to the new window. An object can be
  622. * provided to specify duration and easing function.
  623. * Default duration is 500 ms, and default easing
  624. * function is 'easeInOutQuad'.
  625. */
  626. Core.prototype.zoomIn = function(percentage, options) {
  627. if (!percentage || percentage < 0 || percentage > 1) return
  628. var range = this.getWindow();
  629. var start = range.start.valueOf();
  630. var end = range.end.valueOf();
  631. var interval = end - start;
  632. var newInterval = interval / (1 + percentage);
  633. var distance = (interval - newInterval) / 2;
  634. var newStart = start + distance;
  635. var newEnd = end - distance;
  636. this.setWindow(newStart, newEnd, options);
  637. };
  638. /**
  639. * Zoom out the window such that given time is centered on screen.
  640. * @param {Number} percentage - must be between [0..1]
  641. * @param {Object} [options] Available options:
  642. * `animation: boolean | {duration: number, easingFunction: string}`
  643. * If true (default), the range is animated
  644. * smoothly to the new window. An object can be
  645. * provided to specify duration and easing function.
  646. * Default duration is 500 ms, and default easing
  647. * function is 'easeInOutQuad'.
  648. */
  649. Core.prototype.zoomOut = function(percentage, options) {
  650. if (!percentage || percentage < 0 || percentage > 1) return
  651. var range = this.getWindow();
  652. var start = range.start.valueOf();
  653. var end = range.end.valueOf();
  654. var interval = end - start;
  655. var newStart = start - interval * percentage / 2;
  656. var newEnd = end + interval * percentage / 2;
  657. this.setWindow(newStart, newEnd, options);
  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. props.borderRootHeight= dom.root.offsetHeight - dom.root.clientHeight;
  699. props.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. props.borderRootWidth = props.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. props.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 - props.borderRootHeight;
  726. var containerHeight = props.root.height - props.top.height - props.bottom.height -
  727. props.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 - props.borderRootWidth;
  734. if (!this.initialDrawDone) {
  735. props.scrollbarWidth = util.getScrollBarWidth();
  736. }
  737. if (options.verticalScroll) {
  738. if (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. this._setDOM();
  750. // update the scrollTop, feasible range for the offset can be changed
  751. // when the height of the Core or of the contents of the center changed
  752. var offset = this._updateScrollTop();
  753. // reposition the scrollable contents
  754. if (options.orientation.item != 'top') {
  755. offset += Math.max(props.centerContainer.height - props.center.height -
  756. props.border.top - props.border.bottom, 0);
  757. }
  758. dom.center.style.top = offset + 'px';
  759. // show shadows when vertical scrolling is available
  760. var visibilityTop = props.scrollTop == 0 ? 'hidden' : '';
  761. var visibilityBottom = props.scrollTop == props.scrollTopMin ? 'hidden' : '';
  762. dom.shadowTop.style.visibility = visibilityTop;
  763. dom.shadowBottom.style.visibility = visibilityBottom;
  764. dom.shadowTopLeft.style.visibility = visibilityTop;
  765. dom.shadowBottomLeft.style.visibility = visibilityBottom;
  766. dom.shadowTopRight.style.visibility = visibilityTop;
  767. dom.shadowBottomRight.style.visibility = visibilityBottom;
  768. if (options.verticalScroll) {
  769. dom.rightContainer.className = 'vis-panel vis-right vis-vertical-scroll';
  770. dom.leftContainer.className = 'vis-panel vis-left vis-vertical-scroll';
  771. dom.shadowTopRight.style.visibility = "hidden";
  772. dom.shadowBottomRight.style.visibility = "hidden";
  773. dom.shadowTopLeft.style.visibility = "hidden";
  774. dom.shadowBottomLeft.style.visibility = "hidden";
  775. dom.left.style.top = '0px';
  776. dom.right.style.top = '0px';
  777. }
  778. if (!options.verticalScroll || props.center.height < props.centerContainer.height) {
  779. dom.left.style.top = offset + 'px';
  780. dom.right.style.top = offset + 'px';
  781. dom.rightContainer.className = dom.rightContainer.className.replace(new RegExp('(?:^|\\s)'+ 'vis-vertical-scroll' + '(?:\\s|$)'), ' ');
  782. dom.leftContainer.className = dom.leftContainer.className.replace(new RegExp('(?:^|\\s)'+ 'vis-vertical-scroll' + '(?:\\s|$)'), ' ');
  783. props.left.width = dom.leftContainer.clientWidth || -props.border.left;
  784. props.right.width = dom.rightContainer.clientWidth || -props.border.right;
  785. this._setDOM();
  786. }
  787. // enable/disable vertical panning
  788. var contentsOverflow = props.center.height > props.centerContainer.height;
  789. this.hammer.get('pan').set({
  790. direction: contentsOverflow ? Hammer.DIRECTION_ALL : Hammer.DIRECTION_HORIZONTAL
  791. });
  792. // redraw all components
  793. this.components.forEach(function (component) {
  794. resized = component.redraw() || resized;
  795. });
  796. var MAX_REDRAW = 5;
  797. if (resized) {
  798. if (this.redrawCount < MAX_REDRAW) {
  799. this.body.emitter.emit('_change');
  800. return;
  801. }
  802. else {
  803. console.log('WARNING: infinite loop in redraw?');
  804. }
  805. } else {
  806. this.redrawCount = 0;
  807. }
  808. this.initialDrawDone = true;
  809. //Emit public 'changed' event for UI updates, see issue #1592
  810. this.body.emitter.emit("changed");
  811. };
  812. Core.prototype._setDOM = function () {
  813. var props = this.props;
  814. var dom = this.dom;
  815. props.leftContainer.width = props.left.width;
  816. props.rightContainer.width = props.right.width;
  817. var centerWidth = props.root.width - props.left.width - props.right.width - props.borderRootWidth;
  818. props.center.width = centerWidth;
  819. props.centerContainer.width = centerWidth;
  820. props.top.width = centerWidth;
  821. props.bottom.width = centerWidth;
  822. // resize the panels
  823. dom.background.style.height = props.background.height + 'px';
  824. dom.backgroundVertical.style.height = props.background.height + 'px';
  825. dom.backgroundHorizontal.style.height = props.centerContainer.height + 'px';
  826. dom.centerContainer.style.height = props.centerContainer.height + 'px';
  827. dom.leftContainer.style.height = props.leftContainer.height + 'px';
  828. dom.rightContainer.style.height = props.rightContainer.height + 'px';
  829. dom.background.style.width = props.background.width + 'px';
  830. dom.backgroundVertical.style.width = props.centerContainer.width + 'px';
  831. dom.backgroundHorizontal.style.width = props.background.width + 'px';
  832. dom.centerContainer.style.width = props.center.width + 'px';
  833. dom.top.style.width = props.top.width + 'px';
  834. dom.bottom.style.width = props.bottom.width + 'px';
  835. // reposition the panels
  836. dom.background.style.left = '0';
  837. dom.background.style.top = '0';
  838. dom.backgroundVertical.style.left = (props.left.width + props.border.left) + 'px';
  839. dom.backgroundVertical.style.top = '0';
  840. dom.backgroundHorizontal.style.left = '0';
  841. dom.backgroundHorizontal.style.top = props.top.height + 'px';
  842. dom.centerContainer.style.left = props.left.width + 'px';
  843. dom.centerContainer.style.top = props.top.height + 'px';
  844. dom.leftContainer.style.left = '0';
  845. dom.leftContainer.style.top = props.top.height + 'px';
  846. dom.rightContainer.style.left = (props.left.width + props.center.width) + 'px';
  847. dom.rightContainer.style.top = props.top.height + 'px';
  848. dom.top.style.left = props.left.width + 'px';
  849. dom.top.style.top = '0';
  850. dom.bottom.style.left = props.left.width + 'px';
  851. dom.bottom.style.top = (props.top.height + props.centerContainer.height) + 'px';
  852. dom.center.style.left = '0';
  853. dom.left.style.left = '0';
  854. dom.right.style.left = '0';
  855. }
  856. // TODO: deprecated since version 1.1.0, remove some day
  857. Core.prototype.repaint = function () {
  858. throw new Error('Function repaint is deprecated. Use redraw instead.');
  859. };
  860. /**
  861. * Set a current time. This can be used for example to ensure that a client's
  862. * time is synchronized with a shared server time.
  863. * Only applicable when option `showCurrentTime` is true.
  864. * @param {Date | String | Number} time A Date, unix timestamp, or
  865. * ISO date string.
  866. */
  867. Core.prototype.setCurrentTime = function(time) {
  868. if (!this.currentTime) {
  869. throw new Error('Option showCurrentTime must be true');
  870. }
  871. this.currentTime.setCurrentTime(time);
  872. };
  873. /**
  874. * Get the current time.
  875. * Only applicable when option `showCurrentTime` is true.
  876. * @return {Date} Returns the current time.
  877. */
  878. Core.prototype.getCurrentTime = function() {
  879. if (!this.currentTime) {
  880. throw new Error('Option showCurrentTime must be true');
  881. }
  882. return this.currentTime.getCurrentTime();
  883. };
  884. /**
  885. * Convert a position on screen (pixels) to a datetime
  886. * @param {int} x Position on the screen in pixels
  887. * @return {Date} time The datetime the corresponds with given position x
  888. * @protected
  889. */
  890. // TODO: move this function to Range
  891. Core.prototype._toTime = function(x) {
  892. return DateUtil.toTime(this, x, this.props.center.width);
  893. };
  894. /**
  895. * Convert a position on the global screen (pixels) to a datetime
  896. * @param {int} x Position on the screen in pixels
  897. * @return {Date} time The datetime the corresponds with given position x
  898. * @protected
  899. */
  900. // TODO: move this function to Range
  901. Core.prototype._toGlobalTime = function(x) {
  902. return DateUtil.toTime(this, x, this.props.root.width);
  903. //var conversion = this.range.conversion(this.props.root.width);
  904. //return new Date(x / conversion.scale + conversion.offset);
  905. };
  906. /**
  907. * Convert a datetime (Date object) into a position on the screen
  908. * @param {Date} time A date
  909. * @return {int} x The position on the screen in pixels which corresponds
  910. * with the given date.
  911. * @protected
  912. */
  913. // TODO: move this function to Range
  914. Core.prototype._toScreen = function(time) {
  915. return DateUtil.toScreen(this, time, this.props.center.width);
  916. };
  917. /**
  918. * Convert a datetime (Date object) into a position on the root
  919. * This is used to get the pixel density estimate for the screen, not the center panel
  920. * @param {Date} time A date
  921. * @return {int} x The position on root in pixels which corresponds
  922. * with the given date.
  923. * @protected
  924. */
  925. // TODO: move this function to Range
  926. Core.prototype._toGlobalScreen = function(time) {
  927. return DateUtil.toScreen(this, time, this.props.root.width);
  928. //var conversion = this.range.conversion(this.props.root.width);
  929. //return (time.valueOf() - conversion.offset) * conversion.scale;
  930. };
  931. /**
  932. * Initialize watching when option autoResize is true
  933. * @private
  934. */
  935. Core.prototype._initAutoResize = function () {
  936. if (this.options.autoResize == true) {
  937. this._startAutoResize();
  938. }
  939. else {
  940. this._stopAutoResize();
  941. }
  942. };
  943. /**
  944. * Watch for changes in the size of the container. On resize, the Panel will
  945. * automatically redraw itself.
  946. * @private
  947. */
  948. Core.prototype._startAutoResize = function () {
  949. var me = this;
  950. this._stopAutoResize();
  951. this._onResize = function() {
  952. if (me.options.autoResize != true) {
  953. // stop watching when the option autoResize is changed to false
  954. me._stopAutoResize();
  955. return;
  956. }
  957. if (me.dom.root) {
  958. // check whether the frame is resized
  959. // Note: we compare offsetWidth here, not clientWidth. For some reason,
  960. // IE does not restore the clientWidth from 0 to the actual width after
  961. // changing the timeline's container display style from none to visible
  962. if ((me.dom.root.offsetWidth != me.props.lastWidth) ||
  963. (me.dom.root.offsetHeight != me.props.lastHeight)) {
  964. me.props.lastWidth = me.dom.root.offsetWidth;
  965. me.props.lastHeight = me.dom.root.offsetHeight;
  966. me.props.scrollbarWidth = util.getScrollBarWidth();
  967. me.body.emitter.emit('_change');
  968. }
  969. }
  970. };
  971. // add event listener to window resize
  972. util.addEventListener(window, 'resize', this._onResize);
  973. //Prevent initial unnecessary redraw
  974. if (me.dom.root) {
  975. me.props.lastWidth = me.dom.root.offsetWidth;
  976. me.props.lastHeight = me.dom.root.offsetHeight;
  977. }
  978. this.watchTimer = setInterval(this._onResize, 1000);
  979. };
  980. /**
  981. * Stop watching for a resize of the frame.
  982. * @private
  983. */
  984. Core.prototype._stopAutoResize = function () {
  985. if (this.watchTimer) {
  986. clearInterval(this.watchTimer);
  987. this.watchTimer = undefined;
  988. }
  989. // remove event listener on window.resize
  990. if (this._onResize) {
  991. util.removeEventListener(window, 'resize', this._onResize);
  992. this._onResize = null;
  993. }
  994. };
  995. /**
  996. * Start moving the timeline vertically
  997. * @param {Event} event
  998. * @private
  999. */
  1000. Core.prototype._onTouch = function (event) {
  1001. this.touch.allowDragging = true;
  1002. this.touch.initialScrollTop = this.props.scrollTop;
  1003. };
  1004. /**
  1005. * Start moving the timeline vertically
  1006. * @param {Event} event
  1007. * @private
  1008. */
  1009. Core.prototype._onPinch = function (event) {
  1010. this.touch.allowDragging = false;
  1011. };
  1012. /**
  1013. * Move the timeline vertically
  1014. * @param {Event} event
  1015. * @private
  1016. */
  1017. Core.prototype._onDrag = function (event) {
  1018. if (!event) return
  1019. // refuse to drag when we where pinching to prevent the timeline make a jump
  1020. // when releasing the fingers in opposite order from the touch screen
  1021. if (!this.touch.allowDragging) return;
  1022. var delta = event.deltaY;
  1023. var oldScrollTop = this._getScrollTop();
  1024. var newScrollTop = this._setScrollTop(this.touch.initialScrollTop + delta);
  1025. if (this.options.verticalScroll) {
  1026. this.dom.left.parentNode.scrollTop = -this.props.scrollTop;
  1027. this.dom.right.parentNode.scrollTop = -this.props.scrollTop;
  1028. }
  1029. if (newScrollTop != oldScrollTop) {
  1030. this.emit("verticalDrag");
  1031. }
  1032. };
  1033. /**
  1034. * Apply a scrollTop
  1035. * @param {Number} scrollTop
  1036. * @returns {Number} scrollTop Returns the applied scrollTop
  1037. * @private
  1038. */
  1039. Core.prototype._setScrollTop = function (scrollTop) {
  1040. this.props.scrollTop = scrollTop;
  1041. this._updateScrollTop();
  1042. return this.props.scrollTop;
  1043. };
  1044. /**
  1045. * Update the current scrollTop when the height of the containers has been changed
  1046. * @returns {Number} scrollTop Returns the applied scrollTop
  1047. * @private
  1048. */
  1049. Core.prototype._updateScrollTop = function () {
  1050. // recalculate the scrollTopMin
  1051. var scrollTopMin = Math.min(this.props.centerContainer.height - this.props.center.height, 0); // is negative or zero
  1052. if (scrollTopMin != this.props.scrollTopMin) {
  1053. // in case of bottom orientation, change the scrollTop such that the contents
  1054. // do not move relative to the time axis at the bottom
  1055. if (this.options.orientation.item != 'top') {
  1056. this.props.scrollTop += (scrollTopMin - this.props.scrollTopMin);
  1057. }
  1058. this.props.scrollTopMin = scrollTopMin;
  1059. }
  1060. // limit the scrollTop to the feasible scroll range
  1061. if (this.props.scrollTop > 0) this.props.scrollTop = 0;
  1062. if (this.props.scrollTop < scrollTopMin) this.props.scrollTop = scrollTopMin;
  1063. if (this.options.verticalScroll) {
  1064. this.dom.left.parentNode.scrollTop = -this.props.scrollTop;
  1065. this.dom.right.parentNode.scrollTop = -this.props.scrollTop;
  1066. }
  1067. return this.props.scrollTop;
  1068. };
  1069. /**
  1070. * Get the current scrollTop
  1071. * @returns {number} scrollTop
  1072. * @private
  1073. */
  1074. Core.prototype._getScrollTop = function () {
  1075. return this.props.scrollTop;
  1076. };
  1077. /**
  1078. * Load a configurator
  1079. * @return {Object}
  1080. * @private
  1081. */
  1082. Core.prototype._createConfigurator = function () {
  1083. throw new Error('Cannot invoke abstract method _createConfigurator');
  1084. };
  1085. module.exports = Core;