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