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.

1253 lines
43 KiB

  1. var Emitter = require('emitter-component');
  2. var Hammer = require('../module/hammer');
  3. var hammerUtil = require('../hammerUtil');
  4. var util = require('../util');
  5. var DataSet = require('../DataSet');
  6. var DataView = require('../DataView');
  7. var Range = require('./Range');
  8. var ItemSet = require('./component/ItemSet');
  9. var TimeAxis = require('./component/TimeAxis');
  10. var Activator = require('../shared/Activator');
  11. var DateUtil = require('./DateUtil');
  12. var CustomTime = require('./component/CustomTime');
  13. /**
  14. * Create a timeline visualization
  15. * @constructor
  16. */
  17. function Core () {}
  18. // turn Core into an event emitter
  19. Emitter(Core.prototype);
  20. /**
  21. * Create the main DOM for the Core: a root panel containing left, right,
  22. * top, bottom, content, and background panel.
  23. * @param {Element} container The container element where the Core will
  24. * be attached.
  25. * @protected
  26. */
  27. Core.prototype._create = function (container) {
  28. this.dom = {};
  29. this.dom.container = container;
  30. this.dom.root = document.createElement('div');
  31. this.dom.background = document.createElement('div');
  32. this.dom.backgroundVertical = document.createElement('div');
  33. this.dom.backgroundHorizontal = document.createElement('div');
  34. this.dom.centerContainer = document.createElement('div');
  35. this.dom.leftContainer = document.createElement('div');
  36. this.dom.rightContainer = document.createElement('div');
  37. this.dom.center = document.createElement('div');
  38. this.dom.left = document.createElement('div');
  39. this.dom.right = document.createElement('div');
  40. this.dom.top = document.createElement('div');
  41. this.dom.bottom = document.createElement('div');
  42. this.dom.shadowTop = document.createElement('div');
  43. this.dom.shadowBottom = document.createElement('div');
  44. this.dom.shadowTopLeft = document.createElement('div');
  45. this.dom.shadowBottomLeft = document.createElement('div');
  46. this.dom.shadowTopRight = document.createElement('div');
  47. this.dom.shadowBottomRight = document.createElement('div');
  48. this.dom.rollingModeBtn = document.createElement('div');
  49. this.dom.root.className = 'vis-timeline';
  50. this.dom.background.className = 'vis-panel vis-background';
  51. this.dom.backgroundVertical.className = 'vis-panel vis-background vis-vertical';
  52. this.dom.backgroundHorizontal.className = 'vis-panel vis-background vis-horizontal';
  53. this.dom.centerContainer.className = 'vis-panel vis-center';
  54. this.dom.leftContainer.className = 'vis-panel vis-left';
  55. this.dom.rightContainer.className = 'vis-panel vis-right';
  56. this.dom.top.className = 'vis-panel vis-top';
  57. this.dom.bottom.className = 'vis-panel vis-bottom';
  58. this.dom.left.className = 'vis-content';
  59. this.dom.center.className = 'vis-content';
  60. this.dom.right.className = 'vis-content';
  61. this.dom.shadowTop.className = 'vis-shadow vis-top';
  62. this.dom.shadowBottom.className = 'vis-shadow vis-bottom';
  63. this.dom.shadowTopLeft.className = 'vis-shadow vis-top';
  64. this.dom.shadowBottomLeft.className = 'vis-shadow vis-bottom';
  65. this.dom.shadowTopRight.className = 'vis-shadow vis-top';
  66. this.dom.shadowBottomRight.className = 'vis-shadow vis-bottom';
  67. this.dom.rollingModeBtn.className = 'vis-rolling-mode-btn';
  68. this.dom.root.appendChild(this.dom.background);
  69. this.dom.root.appendChild(this.dom.backgroundVertical);
  70. this.dom.root.appendChild(this.dom.backgroundHorizontal);
  71. this.dom.root.appendChild(this.dom.centerContainer);
  72. this.dom.root.appendChild(this.dom.leftContainer);
  73. this.dom.root.appendChild(this.dom.rightContainer);
  74. this.dom.root.appendChild(this.dom.top);
  75. this.dom.root.appendChild(this.dom.bottom);
  76. this.dom.root.appendChild(this.dom.bottom);
  77. this.dom.root.appendChild(this.dom.rollingModeBtn);
  78. this.dom.centerContainer.appendChild(this.dom.center);
  79. this.dom.leftContainer.appendChild(this.dom.left);
  80. this.dom.rightContainer.appendChild(this.dom.right);
  81. this.dom.centerContainer.appendChild(this.dom.shadowTop);
  82. this.dom.centerContainer.appendChild(this.dom.shadowBottom);
  83. this.dom.leftContainer.appendChild(this.dom.shadowTopLeft);
  84. this.dom.leftContainer.appendChild(this.dom.shadowBottomLeft);
  85. this.dom.rightContainer.appendChild(this.dom.shadowTopRight);
  86. this.dom.rightContainer.appendChild(this.dom.shadowBottomRight);
  87. // size properties of each of the panels
  88. this.props = {
  89. root: {},
  90. background: {},
  91. centerContainer: {},
  92. leftContainer: {},
  93. rightContainer: {},
  94. center: {},
  95. left: {},
  96. right: {},
  97. top: {},
  98. bottom: {},
  99. border: {},
  100. scrollTop: 0,
  101. scrollTopMin: 0
  102. };
  103. this.on('rangechange', function () {
  104. if (this.initialDrawDone === true) {
  105. this._redraw();
  106. }
  107. }.bind(this));
  108. this.on('touch', this._onTouch.bind(this));
  109. this.on('panmove', this._onDrag.bind(this));
  110. var me = this;
  111. this._origRedraw = this._redraw.bind(this);
  112. this._redraw = util.throttle(this._origRedraw);
  113. this.on('_change', function (properties) {
  114. if (me.itemSet && me.itemSet.initialItemSetDrawn && properties && properties.queue == true) {
  115. me._redraw()
  116. } else {
  117. me._origRedraw();
  118. }
  119. });
  120. // create event listeners for all interesting events, these events will be
  121. // emitted via emitter
  122. this.hammer = new Hammer(this.dom.root);
  123. var pinchRecognizer = this.hammer.get('pinch').set({enable: true});
  124. hammerUtil.disablePreventDefaultVertically(pinchRecognizer);
  125. this.hammer.get('pan').set({threshold:5, direction: Hammer.DIRECTION_HORIZONTAL});
  126. this.listeners = {};
  127. var events = [
  128. 'tap', 'doubletap', 'press',
  129. 'pinch',
  130. 'pan', 'panstart', 'panmove', 'panend'
  131. // TODO: cleanup
  132. //'touch', 'pinch',
  133. //'tap', 'doubletap', 'hold',
  134. //'dragstart', 'drag', 'dragend',
  135. //'mousewheel', 'DOMMouseScroll' // DOMMouseScroll is needed for Firefox
  136. ];
  137. events.forEach(function (type) {
  138. var listener = function (event) {
  139. if (me.isActive()) {
  140. me.emit(type, event);
  141. }
  142. };
  143. me.hammer.on(type, listener);
  144. me.listeners[type] = listener;
  145. });
  146. // emulate a touch event (emitted before the start of a pan, pinch, tap, or press)
  147. hammerUtil.onTouch(this.hammer, function (event) {
  148. me.emit('touch', event);
  149. }.bind(this));
  150. // emulate a release event (emitted after a pan, pinch, tap, or press)
  151. hammerUtil.onRelease(this.hammer, function (event) {
  152. me.emit('release', event);
  153. }.bind(this));
  154. function onMouseWheel(event) {
  155. if (this.isActive()) {
  156. this.emit('mousewheel', event);
  157. }
  158. // prevent scrolling if not specified explicitly or when horizontalScroll is true
  159. if (!this.options.verticalScroll || this.options.horizontalScroll) return;
  160. // prevent scrolling when zoomKey defined or activated
  161. if (!this.options.zoomKey || event[this.options.zoomKey]) return;
  162. // Prevent default actions caused by mouse wheel
  163. // (else the page and timeline both scroll)
  164. event.preventDefault();
  165. var delta = 0;
  166. if (event.wheelDelta) { /* IE/Opera. */
  167. delta = event.wheelDelta / 120;
  168. } else if (event.detail) { /* Mozilla case. */
  169. // In Mozilla, sign of delta is different than in IE.
  170. // Also, delta is multiple of 3.
  171. delta = -event.detail / 3;
  172. }
  173. var current = this.props.scrollTop;
  174. var adjusted = current + delta * 120;
  175. if (this.isActive()) {
  176. this._setScrollTop(adjusted);
  177. this._redraw();
  178. this.emit('scroll', event);
  179. }
  180. }
  181. if (this.dom.centerContainer.addEventListener) {
  182. // IE9, Chrome, Safari, Opera
  183. this.dom.centerContainer.addEventListener("mousewheel", onMouseWheel.bind(this), false);
  184. // Firefox
  185. this.dom.centerContainer.addEventListener("DOMMouseScroll", onMouseWheel.bind(this), false);
  186. } else {
  187. // IE 6/7/8
  188. this.dom.centerContainer.attachEvent("onmousewheel", onMouseWheel.bind(this));
  189. }
  190. function onMouseScrollSide(event) {
  191. if (!me.options.verticalScroll) return;
  192. event.preventDefault();
  193. if (me.isActive()) {
  194. var adjusted = -event.target.scrollTop;
  195. me._setScrollTop(adjusted);
  196. me._redraw();
  197. me.emit('scrollSide', event);
  198. }
  199. }
  200. this.dom.left.parentNode.addEventListener('scroll', onMouseScrollSide.bind(this));
  201. this.dom.right.parentNode.addEventListener('scroll', onMouseScrollSide.bind(this));
  202. var itemAddedToTimeline = false;
  203. function handleDragOver(event) {
  204. if (event.preventDefault) {
  205. event.preventDefault(); // Necessary. Allows us to drop.
  206. }
  207. // make sure your target is a vis element
  208. if (!event.target.className.indexOf("vis") > -1) return;
  209. // make sure only one item is added every time you're over the timeline
  210. if (itemAddedToTimeline) return;
  211. event.dataTransfer.dropEffect = 'move';
  212. itemAddedToTimeline = true;
  213. return false;
  214. }
  215. function handleDrop(event) {
  216. // 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. */
  533. Core.prototype.fit = function(options) {
  534. var range = this.getDataRange();
  535. // skip range set if there is no min and max date
  536. if (range.min === null && range.max === null) {
  537. return;
  538. }
  539. // apply a margin of 1% left and right of the data
  540. var interval = range.max - range.min;
  541. var min = new Date(range.min.valueOf() - interval * 0.01);
  542. var max = new Date(range.max.valueOf() + interval * 0.01);
  543. var animation = (options && options.animation !== undefined) ? options.animation : true;
  544. this.range.setRange(min, max, animation);
  545. };
  546. /**
  547. * Calculate the data range of the items start and end dates
  548. * @returns {{min: Date | null, max: Date | null}}
  549. * @protected
  550. */
  551. Core.prototype.getDataRange = function() {
  552. // must be implemented by Timeline and Graph2d
  553. throw new Error('Cannot invoke abstract method getDataRange');
  554. };
  555. /**
  556. * Set the visible window. Both parameters are optional, you can change only
  557. * start or only end. Syntax:
  558. *
  559. * TimeLine.setWindow(start, end)
  560. * TimeLine.setWindow(start, end, options)
  561. * TimeLine.setWindow(range)
  562. *
  563. * Where start and end can be a Date, number, or string, and range is an
  564. * object with properties start and end.
  565. *
  566. * @param {Date | Number | String | Object} [start] Start date of visible window
  567. * @param {Date | Number | String} [end] End date of visible window
  568. * @param {Object} [options] Available options:
  569. * `animation: boolean | {duration: number, easingFunction: string}`
  570. * If true (default), the range is animated
  571. * smoothly to the new window. An object can be
  572. * provided to specify duration and easing function.
  573. * Default duration is 500 ms, and default easing
  574. * function is 'easeInOutQuad'.
  575. */
  576. Core.prototype.setWindow = function(start, end, options) {
  577. var animation;
  578. if (arguments.length == 1) {
  579. var range = arguments[0];
  580. animation = (range.animation !== undefined) ? range.animation : true;
  581. this.range.setRange(range.start, range.end, animation);
  582. }
  583. else {
  584. animation = (options && options.animation !== undefined) ? options.animation : true;
  585. this.range.setRange(start, end, animation);
  586. }
  587. };
  588. /**
  589. * Move the window such that given time is centered on screen.
  590. * @param {Date | Number | String} time
  591. * @param {Object} [options] Available options:
  592. * `animation: boolean | {duration: number, easingFunction: string}`
  593. * If true (default), the range is animated
  594. * smoothly to the new window. An object can be
  595. * provided to specify duration and easing function.
  596. * Default duration is 500 ms, and default easing
  597. * function is 'easeInOutQuad'.
  598. */
  599. Core.prototype.moveTo = function(time, options) {
  600. var interval = this.range.end - this.range.start;
  601. var t = util.convert(time, 'Date').valueOf();
  602. var start = t - interval / 2;
  603. var end = t + interval / 2;
  604. var animation = (options && options.animation !== undefined) ? options.animation : true;
  605. this.range.setRange(start, end, animation);
  606. };
  607. /**
  608. * Get the visible window
  609. * @return {{start: Date, end: Date}} Visible range
  610. */
  611. Core.prototype.getWindow = function() {
  612. var range = this.range.getRange();
  613. return {
  614. start: new Date(range.start),
  615. end: new Date(range.end)
  616. };
  617. };
  618. /**
  619. * Zoom in the window such that given time is centered on screen.
  620. * @param {Number} percentage - must be between [0..1]
  621. * @param {Object} [options] Available options:
  622. * `animation: boolean | {duration: number, easingFunction: string}`
  623. * If true (default), the range is animated
  624. * smoothly to the new window. An object can be
  625. * provided to specify duration and easing function.
  626. * Default duration is 500 ms, and default easing
  627. * function is 'easeInOutQuad'.
  628. */
  629. Core.prototype.zoomIn = function(percentage, options) {
  630. if (!percentage || percentage < 0 || percentage > 1) return
  631. var range = this.getWindow();
  632. var start = range.start.valueOf();
  633. var end = range.end.valueOf();
  634. var interval = end - start;
  635. var newInterval = interval / (1 + percentage);
  636. var distance = (interval - newInterval) / 2;
  637. var newStart = start + distance;
  638. var newEnd = end - distance;
  639. this.setWindow(newStart, newEnd, options);
  640. };
  641. /**
  642. * Zoom out the window such that given time is centered on screen.
  643. * @param {Number} percentage - must be between [0..1]
  644. * @param {Object} [options] Available options:
  645. * `animation: boolean | {duration: number, easingFunction: string}`
  646. * If true (default), the range is animated
  647. * smoothly to the new window. An object can be
  648. * provided to specify duration and easing function.
  649. * Default duration is 500 ms, and default easing
  650. * function is 'easeInOutQuad'.
  651. */
  652. Core.prototype.zoomOut = function(percentage, options) {
  653. if (!percentage || percentage < 0 || percentage > 1) return
  654. var range = this.getWindow();
  655. var start = range.start.valueOf();
  656. var end = range.end.valueOf();
  657. var interval = end - start;
  658. var newStart = start - interval * percentage / 2;
  659. var newEnd = end + interval * percentage / 2;
  660. this.setWindow(newStart, newEnd, options);
  661. };
  662. /**
  663. * Force a redraw. Can be overridden by implementations of Core
  664. *
  665. * Note: this function will be overridden on construction with a trottled version
  666. */
  667. Core.prototype.redraw = function() {
  668. this._redraw();
  669. };
  670. /**
  671. * Redraw for internal use. Redraws all components. See also the public
  672. * method redraw.
  673. * @protected
  674. */
  675. Core.prototype._redraw = function() {
  676. this.redrawCount++;
  677. var resized = false;
  678. var options = this.options;
  679. var props = this.props;
  680. var dom = this.dom;
  681. if (!dom || !dom.container || dom.root.offsetWidth == 0) return; // when destroyed, or invisible
  682. DateUtil.updateHiddenDates(this.options.moment, this.body, this.options.hiddenDates);
  683. // update class names
  684. if (options.orientation == 'top') {
  685. util.addClassName(dom.root, 'vis-top');
  686. util.removeClassName(dom.root, 'vis-bottom');
  687. }
  688. else {
  689. util.removeClassName(dom.root, 'vis-top');
  690. util.addClassName(dom.root, 'vis-bottom');
  691. }
  692. // update root width and height options
  693. dom.root.style.maxHeight = util.option.asSize(options.maxHeight, '');
  694. dom.root.style.minHeight = util.option.asSize(options.minHeight, '');
  695. dom.root.style.width = util.option.asSize(options.width, '');
  696. // calculate border widths
  697. props.border.left = (dom.centerContainer.offsetWidth - dom.centerContainer.clientWidth) / 2;
  698. props.border.right = props.border.left;
  699. props.border.top = (dom.centerContainer.offsetHeight - dom.centerContainer.clientHeight) / 2;
  700. props.border.bottom = props.border.top;
  701. props.borderRootHeight= dom.root.offsetHeight - dom.root.clientHeight;
  702. props.borderRootWidth = dom.root.offsetWidth - dom.root.clientWidth;
  703. // workaround for a bug in IE: the clientWidth of an element with
  704. // a height:0px and overflow:hidden is not calculated and always has value 0
  705. if (dom.centerContainer.clientHeight === 0) {
  706. props.border.left = props.border.top;
  707. props.border.right = props.border.left;
  708. }
  709. if (dom.root.clientHeight === 0) {
  710. props.borderRootWidth = props.borderRootHeight;
  711. }
  712. // calculate the heights. If any of the side panels is empty, we set the height to
  713. // minus the border width, such that the border will be invisible
  714. props.center.height = dom.center.offsetHeight;
  715. props.left.height = dom.left.offsetHeight;
  716. props.right.height = dom.right.offsetHeight;
  717. props.top.height = dom.top.clientHeight || -props.border.top;
  718. props.bottom.height = dom.bottom.clientHeight || -props.border.bottom;
  719. // TODO: compensate borders when any of the panels is empty.
  720. // apply auto height
  721. // TODO: only calculate autoHeight when needed (else we cause an extra reflow/repaint of the DOM)
  722. var contentHeight = Math.max(props.left.height, props.center.height, props.right.height);
  723. var autoHeight = props.top.height + contentHeight + props.bottom.height +
  724. props.borderRootHeight + props.border.top + props.border.bottom;
  725. dom.root.style.height = util.option.asSize(options.height, autoHeight + 'px');
  726. // calculate heights of the content panels
  727. props.root.height = dom.root.offsetHeight;
  728. props.background.height = props.root.height - props.borderRootHeight;
  729. var containerHeight = props.root.height - props.top.height - props.bottom.height -
  730. props.borderRootHeight;
  731. props.centerContainer.height = containerHeight;
  732. props.leftContainer.height = containerHeight;
  733. props.rightContainer.height = props.leftContainer.height;
  734. // calculate the widths of the panels
  735. props.root.width = dom.root.offsetWidth;
  736. props.background.width = props.root.width - props.borderRootWidth;
  737. if (!this.initialDrawDone) {
  738. props.scrollbarWidth = util.getScrollBarWidth();
  739. }
  740. if (options.verticalScroll) {
  741. if (options.rtl) {
  742. props.left.width = dom.leftContainer.clientWidth || -props.border.left;
  743. props.right.width = dom.rightContainer.clientWidth + props.scrollbarWidth || -props.border.right;
  744. } else {
  745. props.left.width = dom.leftContainer.clientWidth + props.scrollbarWidth || -props.border.left;
  746. props.right.width = dom.rightContainer.clientWidth || -props.border.right;
  747. }
  748. } else {
  749. props.left.width = dom.leftContainer.clientWidth || -props.border.left;
  750. props.right.width = dom.rightContainer.clientWidth || -props.border.right;
  751. }
  752. this._setDOM();
  753. // update the scrollTop, feasible range for the offset can be changed
  754. // when the height of the Core or of the contents of the center changed
  755. var offset = this._updateScrollTop();
  756. // reposition the scrollable contents
  757. if (options.orientation.item != 'top') {
  758. offset += Math.max(props.centerContainer.height - props.center.height -
  759. props.border.top - props.border.bottom, 0);
  760. }
  761. dom.center.style.top = offset + 'px';
  762. // show shadows when vertical scrolling is available
  763. var visibilityTop = props.scrollTop == 0 ? 'hidden' : '';
  764. var visibilityBottom = props.scrollTop == props.scrollTopMin ? 'hidden' : '';
  765. dom.shadowTop.style.visibility = visibilityTop;
  766. dom.shadowBottom.style.visibility = visibilityBottom;
  767. dom.shadowTopLeft.style.visibility = visibilityTop;
  768. dom.shadowBottomLeft.style.visibility = visibilityBottom;
  769. dom.shadowTopRight.style.visibility = visibilityTop;
  770. dom.shadowBottomRight.style.visibility = visibilityBottom;
  771. if (options.verticalScroll) {
  772. dom.rightContainer.className = 'vis-panel vis-right vis-vertical-scroll';
  773. dom.leftContainer.className = 'vis-panel vis-left vis-vertical-scroll';
  774. dom.shadowTopRight.style.visibility = "hidden";
  775. dom.shadowBottomRight.style.visibility = "hidden";
  776. dom.shadowTopLeft.style.visibility = "hidden";
  777. dom.shadowBottomLeft.style.visibility = "hidden";
  778. dom.left.style.top = '0px';
  779. dom.right.style.top = '0px';
  780. }
  781. if (!options.verticalScroll || props.center.height < props.centerContainer.height) {
  782. dom.left.style.top = offset + 'px';
  783. dom.right.style.top = offset + 'px';
  784. dom.rightContainer.className = dom.rightContainer.className.replace(new RegExp('(?:^|\\s)'+ 'vis-vertical-scroll' + '(?:\\s|$)'), ' ');
  785. dom.leftContainer.className = dom.leftContainer.className.replace(new RegExp('(?:^|\\s)'+ 'vis-vertical-scroll' + '(?:\\s|$)'), ' ');
  786. props.left.width = dom.leftContainer.clientWidth || -props.border.left;
  787. props.right.width = dom.rightContainer.clientWidth || -props.border.right;
  788. this._setDOM();
  789. }
  790. // enable/disable vertical panning
  791. var contentsOverflow = props.center.height > props.centerContainer.height;
  792. this.hammer.get('pan').set({
  793. direction: contentsOverflow ? Hammer.DIRECTION_ALL : Hammer.DIRECTION_HORIZONTAL
  794. });
  795. // redraw all components
  796. this.components.forEach(function (component) {
  797. resized = component.redraw() || resized;
  798. });
  799. var MAX_REDRAW = 5;
  800. if (resized) {
  801. if (this.redrawCount < MAX_REDRAW) {
  802. this.body.emitter.emit('_change');
  803. return;
  804. }
  805. else {
  806. console.log('WARNING: infinite loop in redraw?');
  807. }
  808. } else {
  809. this.redrawCount = 0;
  810. }
  811. this.initialDrawDone = true;
  812. //Emit public 'changed' event for UI updates, see issue #1592
  813. this.body.emitter.emit("changed");
  814. };
  815. Core.prototype._setDOM = function () {
  816. var props = this.props;
  817. var dom = this.dom;
  818. props.leftContainer.width = props.left.width;
  819. props.rightContainer.width = props.right.width;
  820. var centerWidth = props.root.width - props.left.width - props.right.width - props.borderRootWidth;
  821. props.center.width = centerWidth;
  822. props.centerContainer.width = centerWidth;
  823. props.top.width = centerWidth;
  824. props.bottom.width = centerWidth;
  825. // resize the panels
  826. dom.background.style.height = props.background.height + 'px';
  827. dom.backgroundVertical.style.height = props.background.height + 'px';
  828. dom.backgroundHorizontal.style.height = props.centerContainer.height + 'px';
  829. dom.centerContainer.style.height = props.centerContainer.height + 'px';
  830. dom.leftContainer.style.height = props.leftContainer.height + 'px';
  831. dom.rightContainer.style.height = props.rightContainer.height + 'px';
  832. dom.background.style.width = props.background.width + 'px';
  833. dom.backgroundVertical.style.width = props.centerContainer.width + 'px';
  834. dom.backgroundHorizontal.style.width = props.background.width + 'px';
  835. dom.centerContainer.style.width = props.center.width + 'px';
  836. dom.top.style.width = props.top.width + 'px';
  837. dom.bottom.style.width = props.bottom.width + 'px';
  838. // reposition the panels
  839. dom.background.style.left = '0';
  840. dom.background.style.top = '0';
  841. dom.backgroundVertical.style.left = (props.left.width + props.border.left) + 'px';
  842. dom.backgroundVertical.style.top = '0';
  843. dom.backgroundHorizontal.style.left = '0';
  844. dom.backgroundHorizontal.style.top = props.top.height + 'px';
  845. dom.centerContainer.style.left = props.left.width + 'px';
  846. dom.centerContainer.style.top = props.top.height + 'px';
  847. dom.leftContainer.style.left = '0';
  848. dom.leftContainer.style.top = props.top.height + 'px';
  849. dom.rightContainer.style.left = (props.left.width + props.center.width) + 'px';
  850. dom.rightContainer.style.top = props.top.height + 'px';
  851. dom.top.style.left = props.left.width + 'px';
  852. dom.top.style.top = '0';
  853. dom.bottom.style.left = props.left.width + 'px';
  854. dom.bottom.style.top = (props.top.height + props.centerContainer.height) + 'px';
  855. dom.center.style.left = '0';
  856. dom.left.style.left = '0';
  857. dom.right.style.left = '0';
  858. }
  859. // TODO: deprecated since version 1.1.0, remove some day
  860. Core.prototype.repaint = function () {
  861. throw new Error('Function repaint is deprecated. Use redraw instead.');
  862. };
  863. /**
  864. * Set a current time. This can be used for example to ensure that a client's
  865. * time is synchronized with a shared server time.
  866. * Only applicable when option `showCurrentTime` is true.
  867. * @param {Date | String | Number} time A Date, unix timestamp, or
  868. * ISO date string.
  869. */
  870. Core.prototype.setCurrentTime = function(time) {
  871. if (!this.currentTime) {
  872. throw new Error('Option showCurrentTime must be true');
  873. }
  874. this.currentTime.setCurrentTime(time);
  875. };
  876. /**
  877. * Get the current time.
  878. * Only applicable when option `showCurrentTime` is true.
  879. * @return {Date} Returns the current time.
  880. */
  881. Core.prototype.getCurrentTime = function() {
  882. if (!this.currentTime) {
  883. throw new Error('Option showCurrentTime must be true');
  884. }
  885. return this.currentTime.getCurrentTime();
  886. };
  887. /**
  888. * Convert a position on screen (pixels) to a datetime
  889. * @param {int} x Position on the screen in pixels
  890. * @return {Date} time The datetime the corresponds with given position x
  891. * @protected
  892. */
  893. // TODO: move this function to Range
  894. Core.prototype._toTime = function(x) {
  895. return DateUtil.toTime(this, x, this.props.center.width);
  896. };
  897. /**
  898. * Convert a position on the global screen (pixels) to a datetime
  899. * @param {int} x Position on the screen in pixels
  900. * @return {Date} time The datetime the corresponds with given position x
  901. * @protected
  902. */
  903. // TODO: move this function to Range
  904. Core.prototype._toGlobalTime = function(x) {
  905. return DateUtil.toTime(this, x, this.props.root.width);
  906. //var conversion = this.range.conversion(this.props.root.width);
  907. //return new Date(x / conversion.scale + conversion.offset);
  908. };
  909. /**
  910. * Convert a datetime (Date object) into a position on the screen
  911. * @param {Date} time A date
  912. * @return {int} x The position on the screen in pixels which corresponds
  913. * with the given date.
  914. * @protected
  915. */
  916. // TODO: move this function to Range
  917. Core.prototype._toScreen = function(time) {
  918. return DateUtil.toScreen(this, time, this.props.center.width);
  919. };
  920. /**
  921. * Convert a datetime (Date object) into a position on the root
  922. * This is used to get the pixel density estimate for the screen, not the center panel
  923. * @param {Date} time A date
  924. * @return {int} x The position on root in pixels which corresponds
  925. * with the given date.
  926. * @protected
  927. */
  928. // TODO: move this function to Range
  929. Core.prototype._toGlobalScreen = function(time) {
  930. return DateUtil.toScreen(this, time, this.props.root.width);
  931. //var conversion = this.range.conversion(this.props.root.width);
  932. //return (time.valueOf() - conversion.offset) * conversion.scale;
  933. };
  934. /**
  935. * Initialize watching when option autoResize is true
  936. * @private
  937. */
  938. Core.prototype._initAutoResize = function () {
  939. if (this.options.autoResize == true) {
  940. this._startAutoResize();
  941. }
  942. else {
  943. this._stopAutoResize();
  944. }
  945. };
  946. /**
  947. * Watch for changes in the size of the container. On resize, the Panel will
  948. * automatically redraw itself.
  949. * @private
  950. */
  951. Core.prototype._startAutoResize = function () {
  952. var me = this;
  953. this._stopAutoResize();
  954. this._onResize = function() {
  955. if (me.options.autoResize != true) {
  956. // stop watching when the option autoResize is changed to false
  957. me._stopAutoResize();
  958. return;
  959. }
  960. if (me.dom.root) {
  961. // check whether the frame is resized
  962. // Note: we compare offsetWidth here, not clientWidth. For some reason,
  963. // IE does not restore the clientWidth from 0 to the actual width after
  964. // changing the timeline's container display style from none to visible
  965. if ((me.dom.root.offsetWidth != me.props.lastWidth) ||
  966. (me.dom.root.offsetHeight != me.props.lastHeight)) {
  967. me.props.lastWidth = me.dom.root.offsetWidth;
  968. me.props.lastHeight = me.dom.root.offsetHeight;
  969. me.props.scrollbarWidth = util.getScrollBarWidth();
  970. me.body.emitter.emit('_change');
  971. }
  972. }
  973. };
  974. // add event listener to window resize
  975. util.addEventListener(window, 'resize', this._onResize);
  976. //Prevent initial unnecessary redraw
  977. if (me.dom.root) {
  978. me.props.lastWidth = me.dom.root.offsetWidth;
  979. me.props.lastHeight = me.dom.root.offsetHeight;
  980. }
  981. this.watchTimer = setInterval(this._onResize, 1000);
  982. };
  983. /**
  984. * Stop watching for a resize of the frame.
  985. * @private
  986. */
  987. Core.prototype._stopAutoResize = function () {
  988. if (this.watchTimer) {
  989. clearInterval(this.watchTimer);
  990. this.watchTimer = undefined;
  991. }
  992. // remove event listener on window.resize
  993. if (this._onResize) {
  994. util.removeEventListener(window, 'resize', this._onResize);
  995. this._onResize = null;
  996. }
  997. };
  998. /**
  999. * Start moving the timeline vertically
  1000. * @param {Event} event
  1001. * @private
  1002. */
  1003. Core.prototype._onTouch = function (event) {
  1004. this.touch.allowDragging = true;
  1005. this.touch.initialScrollTop = this.props.scrollTop;
  1006. };
  1007. /**
  1008. * Start moving the timeline vertically
  1009. * @param {Event} event
  1010. * @private
  1011. */
  1012. Core.prototype._onPinch = function (event) {
  1013. this.touch.allowDragging = false;
  1014. };
  1015. /**
  1016. * Move the timeline vertically
  1017. * @param {Event} event
  1018. * @private
  1019. */
  1020. Core.prototype._onDrag = function (event) {
  1021. if (!event) return
  1022. // refuse to drag when we where pinching to prevent the timeline make a jump
  1023. // when releasing the fingers in opposite order from the touch screen
  1024. if (!this.touch.allowDragging) return;
  1025. var delta = event.deltaY;
  1026. var oldScrollTop = this._getScrollTop();
  1027. var newScrollTop = this._setScrollTop(this.touch.initialScrollTop + delta);
  1028. if (this.options.verticalScroll) {
  1029. this.dom.left.parentNode.scrollTop = -this.props.scrollTop;
  1030. this.dom.right.parentNode.scrollTop = -this.props.scrollTop;
  1031. }
  1032. if (newScrollTop != oldScrollTop) {
  1033. this.emit("verticalDrag");
  1034. }
  1035. };
  1036. /**
  1037. * Apply a scrollTop
  1038. * @param {Number} scrollTop
  1039. * @returns {Number} scrollTop Returns the applied scrollTop
  1040. * @private
  1041. */
  1042. Core.prototype._setScrollTop = function (scrollTop) {
  1043. this.props.scrollTop = scrollTop;
  1044. this._updateScrollTop();
  1045. return this.props.scrollTop;
  1046. };
  1047. /**
  1048. * Update the current scrollTop when the height of the containers has been changed
  1049. * @returns {Number} scrollTop Returns the applied scrollTop
  1050. * @private
  1051. */
  1052. Core.prototype._updateScrollTop = function () {
  1053. // recalculate the scrollTopMin
  1054. var scrollTopMin = Math.min(this.props.centerContainer.height - this.props.center.height, 0); // is negative or zero
  1055. if (scrollTopMin != this.props.scrollTopMin) {
  1056. // in case of bottom orientation, change the scrollTop such that the contents
  1057. // do not move relative to the time axis at the bottom
  1058. if (this.options.orientation.item != 'top') {
  1059. this.props.scrollTop += (scrollTopMin - this.props.scrollTopMin);
  1060. }
  1061. this.props.scrollTopMin = scrollTopMin;
  1062. }
  1063. // limit the scrollTop to the feasible scroll range
  1064. if (this.props.scrollTop > 0) this.props.scrollTop = 0;
  1065. if (this.props.scrollTop < scrollTopMin) this.props.scrollTop = scrollTopMin;
  1066. if (this.options.verticalScroll) {
  1067. this.dom.left.parentNode.scrollTop = -this.props.scrollTop;
  1068. this.dom.right.parentNode.scrollTop = -this.props.scrollTop;
  1069. }
  1070. return this.props.scrollTop;
  1071. };
  1072. /**
  1073. * Get the current scrollTop
  1074. * @returns {number} scrollTop
  1075. * @private
  1076. */
  1077. Core.prototype._getScrollTop = function () {
  1078. return this.props.scrollTop;
  1079. };
  1080. /**
  1081. * Load a configurator
  1082. * @return {Object}
  1083. * @private
  1084. */
  1085. Core.prototype._createConfigurator = function () {
  1086. throw new Error('Cannot invoke abstract method _createConfigurator');
  1087. };
  1088. module.exports = Core;