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.

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