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.

890 lines
28 KiB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
  1. var util = require('../util');
  2. var moment = require('../module/moment');
  3. var Component = require('./component/Component');
  4. var DateUtil = require('./DateUtil');
  5. /**
  6. * A Range controls a numeric range with a start and end value.
  7. * The Range adjusts the range based on mouse events or programmatic changes,
  8. * and triggers events when the range is changing or has been changed.
  9. * @param {{dom: Object, domProps: Object, emitter: Emitter}} body
  10. * @param {Object} [options] See description at Range.setOptions
  11. * @constructor Range
  12. * @extends Component
  13. */
  14. function Range(body, options) {
  15. var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0);
  16. var start = now.clone().add(-3, 'days').valueOf();
  17. var end = now.clone().add(3, 'days').valueOf();
  18. this.millisecondsPerPixelCache = undefined;
  19. if(options === undefined) {
  20. this.start = start;
  21. this.end = end;
  22. } else {
  23. this.start = options.start || start;
  24. this.end = options.end || end
  25. }
  26. this.rolling = false;
  27. this.body = body;
  28. this.deltaDifference = 0;
  29. this.scaleOffset = 0;
  30. this.startToFront = false;
  31. this.endToFront = true;
  32. // default options
  33. this.defaultOptions = {
  34. rtl: false,
  35. start: null,
  36. end: null,
  37. moment: moment,
  38. direction: 'horizontal', // 'horizontal' or 'vertical'
  39. moveable: true,
  40. zoomable: true,
  41. min: null,
  42. max: null,
  43. zoomMin: 10, // milliseconds
  44. zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000, // milliseconds
  45. rollingMode: {
  46. follow: false,
  47. offset: 0.5
  48. }
  49. };
  50. this.options = util.extend({}, this.defaultOptions);
  51. this.props = {
  52. touch: {}
  53. };
  54. this.animationTimer = null;
  55. // drag listeners for dragging
  56. this.body.emitter.on('panstart', this._onDragStart.bind(this));
  57. this.body.emitter.on('panmove', this._onDrag.bind(this));
  58. this.body.emitter.on('panend', this._onDragEnd.bind(this));
  59. // mouse wheel for zooming
  60. this.body.emitter.on('mousewheel', this._onMouseWheel.bind(this));
  61. // pinch to zoom
  62. this.body.emitter.on('touch', this._onTouch.bind(this));
  63. this.body.emitter.on('pinch', this._onPinch.bind(this));
  64. // on click of rolling mode button
  65. this.body.dom.rollingModeBtn.addEventListener('click', this.startRolling.bind(this));
  66. this.setOptions(options);
  67. }
  68. Range.prototype = new Component();
  69. /**
  70. * Set options for the range controller
  71. * @param {Object} options Available options:
  72. * {number | Date | String} start Start date for the range
  73. * {number | Date | String} end End date for the range
  74. * {number} min Minimum value for start
  75. * {number} max Maximum value for end
  76. * {number} zoomMin Set a minimum value for
  77. * (end - start).
  78. * {number} zoomMax Set a maximum value for
  79. * (end - start).
  80. * {boolean} moveable Enable moving of the range
  81. * by dragging. True by default
  82. * {boolean} zoomable Enable zooming of the range
  83. * by pinching/scrolling. True by default
  84. */
  85. Range.prototype.setOptions = function (options) {
  86. if (options) {
  87. // copy the options that we know
  88. var fields = [
  89. 'animation', 'direction', 'min', 'max', 'zoomMin', 'zoomMax', 'moveable', 'zoomable',
  90. 'moment', 'activate', 'hiddenDates', 'zoomKey', 'rtl', 'showCurrentTime', 'rollingMode', 'horizontalScroll'
  91. ];
  92. util.selectiveExtend(fields, this.options, options);
  93. if (options.rollingMode && options.rollingMode.follow) {
  94. this.startRolling();
  95. }
  96. if ('start' in options || 'end' in options) {
  97. // apply a new range. both start and end are optional
  98. this.setRange(options.start, options.end);
  99. }
  100. }
  101. };
  102. /**
  103. * Test whether direction has a valid value
  104. * @param {string} direction 'horizontal' or 'vertical'
  105. */
  106. function validateDirection (direction) {
  107. if (direction != 'horizontal' && direction != 'vertical') {
  108. throw new TypeError('Unknown direction "' + direction + '". ' +
  109. 'Choose "horizontal" or "vertical".');
  110. }
  111. }
  112. /**
  113. * Start auto refreshing the current time bar
  114. */
  115. Range.prototype.startRolling = function() {
  116. var me = this;
  117. /**
  118. * Updates the current time.
  119. */
  120. function update () {
  121. me.stopRolling();
  122. me.rolling = true;
  123. var interval = me.end - me.start;
  124. var t = util.convert(new Date(), 'Date').valueOf();
  125. var start = t - interval * (me.options.rollingMode.offset);
  126. var end = t + interval * (1 - me.options.rollingMode.offset);
  127. var options = {
  128. animation: false
  129. };
  130. me.setRange(start, end, options);
  131. // determine interval to refresh
  132. var scale = me.conversion(me.body.domProps.center.width).scale;
  133. interval = 1 / scale / 10;
  134. if (interval < 30) interval = 30;
  135. if (interval > 1000) interval = 1000;
  136. me.body.dom.rollingModeBtn.style.visibility = "hidden";
  137. // start a renderTimer to adjust for the new time
  138. me.currentTimeTimer = setTimeout(update, interval);
  139. }
  140. update();
  141. };
  142. /**
  143. * Stop auto refreshing the current time bar
  144. */
  145. Range.prototype.stopRolling = function() {
  146. if (this.currentTimeTimer !== undefined) {
  147. clearTimeout(this.currentTimeTimer);
  148. this.rolling = false;
  149. this.body.dom.rollingModeBtn.style.visibility = "visible";
  150. }
  151. };
  152. /**
  153. * Set a new start and end range
  154. * @param {Date | number | string} [start]
  155. * @param {Date | number | string} [end]
  156. * @param {Object} options Available options:
  157. * {boolean | {duration: number, easingFunction: string}} [animation=false]
  158. * If true, the range is animated
  159. * smoothly to the new window. An object can be
  160. * provided to specify duration and easing function.
  161. * Default duration is 500 ms, and default easing
  162. * function is 'easeInOutQuad'.
  163. * {boolean} [byUser=false]
  164. * {Event} event Mouse event
  165. * {Function} a callback funtion to be executed at the end of this function
  166. *
  167. */
  168. Range.prototype.setRange = function(start, end, options, callback) {
  169. if (!options) {
  170. options = {};
  171. }
  172. if (options.byUser !== true) {
  173. options.byUser = false;
  174. }
  175. var me = this;
  176. var finalStart = start != undefined ? util.convert(start, 'Date').valueOf() : null;
  177. var finalEnd = end != undefined ? util.convert(end, 'Date').valueOf() : null;
  178. this._cancelAnimation();
  179. this.millisecondsPerPixelCache = undefined;
  180. if (options.animation) { // true or an Object
  181. var initStart = this.start;
  182. var initEnd = this.end;
  183. var duration = (typeof options.animation === 'object' && 'duration' in options.animation) ? options.animation.duration : 500;
  184. var easingName = (typeof options.animation === 'object' && 'easingFunction' in options.animation) ? options.animation.easingFunction : 'easeInOutQuad';
  185. var easingFunction = util.easingFunctions[easingName];
  186. if (!easingFunction) {
  187. throw new Error('Unknown easing function ' + JSON.stringify(easingName) + '. ' +
  188. 'Choose from: ' + Object.keys(util.easingFunctions).join(', '));
  189. }
  190. var initTime = new Date().valueOf();
  191. var anyChanged = false;
  192. var next = function () {
  193. if (!me.props.touch.dragging) {
  194. var now = new Date().valueOf();
  195. var time = now - initTime;
  196. var ease = easingFunction(time / duration);
  197. var done = time > duration;
  198. var s = (done || finalStart === null) ? finalStart : initStart + (finalStart - initStart) * ease;
  199. var e = (done || finalEnd === null) ? finalEnd : initEnd + (finalEnd - initEnd) * ease;
  200. changed = me._applyRange(s, e);
  201. DateUtil.updateHiddenDates(me.options.moment, me.body, me.options.hiddenDates);
  202. anyChanged = anyChanged || changed;
  203. var params = {
  204. start: new Date(me.start),
  205. end: new Date(me.end),
  206. byUser: options.byUser,
  207. event: options.event
  208. };
  209. if (changed) {
  210. me.body.emitter.emit('rangechange', params);
  211. }
  212. if (done) {
  213. if (anyChanged) {
  214. me.body.emitter.emit('rangechanged', params);
  215. if (callback) { return callback() }
  216. }
  217. }
  218. else {
  219. // animate with as high as possible frame rate, leave 20 ms in between
  220. // each to prevent the browser from blocking
  221. me.animationTimer = setTimeout(next, 20);
  222. }
  223. }
  224. };
  225. return next();
  226. }
  227. else {
  228. var changed = this._applyRange(finalStart, finalEnd);
  229. DateUtil.updateHiddenDates(this.options.moment, this.body, this.options.hiddenDates);
  230. if (changed) {
  231. var params = {
  232. start: new Date(this.start),
  233. end: new Date(this.end),
  234. byUser: options.byUser,
  235. event: options.event
  236. };
  237. this.body.emitter.emit('rangechange', params);
  238. clearTimeout( me.timeoutID );
  239. me.timeoutID = setTimeout( function () {
  240. me.body.emitter.emit('rangechanged', params);
  241. }, 200 );
  242. if (callback) { return callback() }
  243. }
  244. }
  245. };
  246. /**
  247. * Get the number of milliseconds per pixel.
  248. *
  249. * @returns {undefined|number}
  250. */
  251. Range.prototype.getMillisecondsPerPixel = function() {
  252. if (this.millisecondsPerPixelCache === undefined) {
  253. this.millisecondsPerPixelCache = (this.end - this.start) / this.body.dom.center.clientWidth;
  254. }
  255. return this.millisecondsPerPixelCache;
  256. };
  257. /**
  258. * Stop an animation
  259. * @private
  260. */
  261. Range.prototype._cancelAnimation = function () {
  262. if (this.animationTimer) {
  263. clearTimeout(this.animationTimer);
  264. this.animationTimer = null;
  265. }
  266. };
  267. /**
  268. * Set a new start and end range. This method is the same as setRange, but
  269. * does not trigger a range change and range changed event, and it returns
  270. * true when the range is changed
  271. * @param {number} [start]
  272. * @param {number} [end]
  273. * @return {boolean} changed
  274. * @private
  275. */
  276. Range.prototype._applyRange = function(start, end) {
  277. var newStart = (start != null) ? util.convert(start, 'Date').valueOf() : this.start,
  278. newEnd = (end != null) ? util.convert(end, 'Date').valueOf() : this.end,
  279. max = (this.options.max != null) ? util.convert(this.options.max, 'Date').valueOf() : null,
  280. min = (this.options.min != null) ? util.convert(this.options.min, 'Date').valueOf() : null,
  281. diff;
  282. // check for valid number
  283. if (isNaN(newStart) || newStart === null) {
  284. throw new Error('Invalid start "' + start + '"');
  285. }
  286. if (isNaN(newEnd) || newEnd === null) {
  287. throw new Error('Invalid end "' + end + '"');
  288. }
  289. // prevent end < start
  290. if (newEnd < newStart) {
  291. newEnd = newStart;
  292. }
  293. // prevent start < min
  294. if (min !== null) {
  295. if (newStart < min) {
  296. diff = (min - newStart);
  297. newStart += diff;
  298. newEnd += diff;
  299. // prevent end > max
  300. if (max != null) {
  301. if (newEnd > max) {
  302. newEnd = max;
  303. }
  304. }
  305. }
  306. }
  307. // prevent end > max
  308. if (max !== null) {
  309. if (newEnd > max) {
  310. diff = (newEnd - max);
  311. newStart -= diff;
  312. newEnd -= diff;
  313. // prevent start < min
  314. if (min != null) {
  315. if (newStart < min) {
  316. newStart = min;
  317. }
  318. }
  319. }
  320. }
  321. // prevent (end-start) < zoomMin
  322. if (this.options.zoomMin !== null) {
  323. var zoomMin = parseFloat(this.options.zoomMin);
  324. if (zoomMin < 0) {
  325. zoomMin = 0;
  326. }
  327. if ((newEnd - newStart) < zoomMin) {
  328. // compensate for a scale of 0.5 ms
  329. var compensation = 0.5;
  330. if ((this.end - this.start) === zoomMin && newStart >= this.start - compensation && newEnd <= this.end) {
  331. // ignore this action, we are already zoomed to the minimum
  332. newStart = this.start;
  333. newEnd = this.end;
  334. }
  335. else {
  336. // zoom to the minimum
  337. diff = (zoomMin - (newEnd - newStart));
  338. newStart -= diff / 2;
  339. newEnd += diff / 2;
  340. }
  341. }
  342. }
  343. // prevent (end-start) > zoomMax
  344. if (this.options.zoomMax !== null) {
  345. var zoomMax = parseFloat(this.options.zoomMax);
  346. if (zoomMax < 0) {
  347. zoomMax = 0;
  348. }
  349. if ((newEnd - newStart) > zoomMax) {
  350. if ((this.end - this.start) === zoomMax && newStart < this.start && newEnd > this.end) {
  351. // ignore this action, we are already zoomed to the maximum
  352. newStart = this.start;
  353. newEnd = this.end;
  354. }
  355. else {
  356. // zoom to the maximum
  357. diff = ((newEnd - newStart) - zoomMax);
  358. newStart += diff / 2;
  359. newEnd -= diff / 2;
  360. }
  361. }
  362. }
  363. var changed = (this.start != newStart || this.end != newEnd);
  364. // if the new range does NOT overlap with the old range, emit checkRangedItems to avoid not showing ranged items (ranged meaning has end time, not necessarily of type Range)
  365. if (!((newStart >= this.start && newStart <= this.end) || (newEnd >= this.start && newEnd <= this.end)) &&
  366. !((this.start >= newStart && this.start <= newEnd) || (this.end >= newStart && this.end <= newEnd) )) {
  367. this.body.emitter.emit('checkRangedItems');
  368. }
  369. this.start = newStart;
  370. this.end = newEnd;
  371. return changed;
  372. };
  373. /**
  374. * Retrieve the current range.
  375. * @return {Object} An object with start and end properties
  376. */
  377. Range.prototype.getRange = function() {
  378. return {
  379. start: this.start,
  380. end: this.end
  381. };
  382. };
  383. /**
  384. * Calculate the conversion offset and scale for current range, based on
  385. * the provided width
  386. * @param {number} width
  387. * @param {number} [totalHidden=0]
  388. * @returns {{offset: number, scale: number}} conversion
  389. */
  390. Range.prototype.conversion = function (width, totalHidden) {
  391. return Range.conversion(this.start, this.end, width, totalHidden);
  392. };
  393. /**
  394. * Static method to calculate the conversion offset and scale for a range,
  395. * based on the provided start, end, and width
  396. * @param {number} start
  397. * @param {number} end
  398. * @param {number} width
  399. * @param {number} [totalHidden=0]
  400. * @returns {{offset: number, scale: number}} conversion
  401. */
  402. Range.conversion = function (start, end, width, totalHidden) {
  403. if (totalHidden === undefined) {
  404. totalHidden = 0;
  405. }
  406. if (width != 0 && (end - start != 0)) {
  407. return {
  408. offset: start,
  409. scale: width / (end - start - totalHidden)
  410. }
  411. }
  412. else {
  413. return {
  414. offset: 0,
  415. scale: 1
  416. };
  417. }
  418. };
  419. /**
  420. * Start dragging horizontally or vertically
  421. * @param {Event} event
  422. * @private
  423. */
  424. Range.prototype._onDragStart = function(event) {
  425. this.deltaDifference = 0;
  426. this.previousDelta = 0;
  427. // only allow dragging when configured as movable
  428. if (!this.options.moveable) return;
  429. // only start dragging when the mouse is inside the current range
  430. if (!this._isInsideRange(event)) return;
  431. // refuse to drag when we where pinching to prevent the timeline make a jump
  432. // when releasing the fingers in opposite order from the touch screen
  433. if (!this.props.touch.allowDragging) return;
  434. this.stopRolling();
  435. this.props.touch.start = this.start;
  436. this.props.touch.end = this.end;
  437. this.props.touch.dragging = true;
  438. if (this.body.dom.root) {
  439. this.body.dom.root.style.cursor = 'move';
  440. }
  441. };
  442. /**
  443. * Perform dragging operation
  444. * @param {Event} event
  445. * @private
  446. */
  447. Range.prototype._onDrag = function (event) {
  448. if (!event) return;
  449. if (!this.props.touch.dragging) return;
  450. // only allow dragging when configured as movable
  451. if (!this.options.moveable) return;
  452. // TODO: this may be redundant in hammerjs2
  453. // refuse to drag when we where pinching to prevent the timeline make a jump
  454. // when releasing the fingers in opposite order from the touch screen
  455. if (!this.props.touch.allowDragging) return;
  456. var direction = this.options.direction;
  457. validateDirection(direction);
  458. var delta = (direction == 'horizontal') ? event.deltaX : event.deltaY;
  459. delta -= this.deltaDifference;
  460. var interval = (this.props.touch.end - this.props.touch.start);
  461. // normalize dragging speed if cutout is in between.
  462. var duration = DateUtil.getHiddenDurationBetween(this.body.hiddenDates, this.start, this.end);
  463. interval -= duration;
  464. var width = (direction == 'horizontal') ? this.body.domProps.center.width : this.body.domProps.center.height;
  465. var diffRange;
  466. if (this.options.rtl) {
  467. diffRange = delta / width * interval;
  468. } else {
  469. diffRange = -delta / width * interval;
  470. }
  471. var newStart = this.props.touch.start + diffRange;
  472. var newEnd = this.props.touch.end + diffRange;
  473. // snapping times away from hidden zones
  474. var safeStart = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newStart, this.previousDelta-delta, true);
  475. var safeEnd = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newEnd, this.previousDelta-delta, true);
  476. if (safeStart != newStart || safeEnd != newEnd) {
  477. this.deltaDifference += delta;
  478. this.props.touch.start = safeStart;
  479. this.props.touch.end = safeEnd;
  480. this._onDrag(event);
  481. return;
  482. }
  483. this.previousDelta = delta;
  484. this._applyRange(newStart, newEnd);
  485. var startDate = new Date(this.start);
  486. var endDate = new Date(this.end);
  487. // fire a rangechange event
  488. this.body.emitter.emit('rangechange', {
  489. start: startDate,
  490. end: endDate,
  491. byUser: true,
  492. event: event
  493. });
  494. // fire a panmove event
  495. this.body.emitter.emit('panmove');
  496. };
  497. /**
  498. * Stop dragging operation
  499. * @param {event} event
  500. * @private
  501. */
  502. Range.prototype._onDragEnd = function (event) {
  503. if (!this.props.touch.dragging) return;
  504. // only allow dragging when configured as movable
  505. if (!this.options.moveable) return;
  506. // TODO: this may be redundant in hammerjs2
  507. // refuse to drag when we where pinching to prevent the timeline make a jump
  508. // when releasing the fingers in opposite order from the touch screen
  509. if (!this.props.touch.allowDragging) return;
  510. this.props.touch.dragging = false;
  511. if (this.body.dom.root) {
  512. this.body.dom.root.style.cursor = 'auto';
  513. }
  514. // fire a rangechanged event
  515. this.body.emitter.emit('rangechanged', {
  516. start: new Date(this.start),
  517. end: new Date(this.end),
  518. byUser: true,
  519. event: event
  520. });
  521. };
  522. /**
  523. * Event handler for mouse wheel event, used to zoom
  524. * Code from http://adomas.org/javascript-mouse-wheel/
  525. * @param {Event} event
  526. * @private
  527. */
  528. Range.prototype._onMouseWheel = function(event) {
  529. // retrieve delta
  530. var delta = 0;
  531. if (event.wheelDelta) { /* IE/Opera. */
  532. delta = event.wheelDelta / 120;
  533. } else if (event.detail) { /* Mozilla case. */
  534. // In Mozilla, sign of delta is different than in IE.
  535. // Also, delta is multiple of 3.
  536. delta = -event.detail / 3;
  537. }
  538. // don't allow zoom when the according key is pressed and the zoomKey option or not zoomable but movable
  539. if ((this.options.zoomKey && !event[this.options.zoomKey] && this.options.zoomable)
  540. || (!this.options.zoomable && this.options.moveable)) {
  541. return;
  542. }
  543. // only allow zooming when configured as zoomable and moveable
  544. if (!(this.options.zoomable && this.options.moveable)) return;
  545. // only zoom when the mouse is inside the current range
  546. if (!this._isInsideRange(event)) return;
  547. // If delta is nonzero, handle it.
  548. // Basically, delta is now positive if wheel was scrolled up,
  549. // and negative, if wheel was scrolled down.
  550. if (delta) {
  551. // perform the zoom action. Delta is normally 1 or -1
  552. // adjust a negative delta such that zooming in with delta 0.1
  553. // equals zooming out with a delta -0.1
  554. var scale;
  555. if (delta < 0) {
  556. scale = 1 - (delta / 5);
  557. }
  558. else {
  559. scale = 1 / (1 + (delta / 5)) ;
  560. }
  561. // calculate center, the date to zoom around
  562. var pointerDate;
  563. if (this.rolling) {
  564. pointerDate = this.start + ((this.end - this.start) * this.options.rollingMode.offset);
  565. } else {
  566. var pointer = this.getPointer({x: event.clientX, y: event.clientY}, this.body.dom.center);
  567. pointerDate = this._pointerToDate(pointer);
  568. }
  569. this.zoom(scale, pointerDate, delta, event);
  570. // Prevent default actions caused by mouse wheel
  571. // (else the page and timeline both scroll)
  572. event.preventDefault();
  573. }
  574. };
  575. /**
  576. * Start of a touch gesture
  577. * @param {Event} event
  578. * @private
  579. */
  580. Range.prototype._onTouch = function (event) { // eslint-disable-line no-unused-vars
  581. this.props.touch.start = this.start;
  582. this.props.touch.end = this.end;
  583. this.props.touch.allowDragging = true;
  584. this.props.touch.center = null;
  585. this.scaleOffset = 0;
  586. this.deltaDifference = 0;
  587. // Disable the browser default handling of this event.
  588. util.preventDefault(event);
  589. };
  590. /**
  591. * Handle pinch event
  592. * @param {Event} event
  593. * @private
  594. */
  595. Range.prototype._onPinch = function (event) {
  596. // only allow zooming when configured as zoomable and moveable
  597. if (!(this.options.zoomable && this.options.moveable)) return;
  598. // Disable the browser default handling of this event.
  599. util.preventDefault(event);
  600. this.props.touch.allowDragging = false;
  601. if (!this.props.touch.center) {
  602. this.props.touch.center = this.getPointer(event.center, this.body.dom.center);
  603. }
  604. this.stopRolling();
  605. var scale = 1 / (event.scale + this.scaleOffset);
  606. var centerDate = this._pointerToDate(this.props.touch.center);
  607. var hiddenDuration = DateUtil.getHiddenDurationBetween(this.body.hiddenDates, this.start, this.end);
  608. var hiddenDurationBefore = DateUtil.getHiddenDurationBefore(this.options.moment, this.body.hiddenDates, this, centerDate);
  609. var hiddenDurationAfter = hiddenDuration - hiddenDurationBefore;
  610. // calculate new start and end
  611. var newStart = (centerDate - hiddenDurationBefore) + (this.props.touch.start - (centerDate - hiddenDurationBefore)) * scale;
  612. var newEnd = (centerDate + hiddenDurationAfter) + (this.props.touch.end - (centerDate + hiddenDurationAfter)) * scale;
  613. // snapping times away from hidden zones
  614. this.startToFront = 1 - scale <= 0; // used to do the right auto correction with periodic hidden times
  615. this.endToFront = scale - 1 <= 0; // used to do the right auto correction with periodic hidden times
  616. var safeStart = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newStart, 1 - scale, true);
  617. var safeEnd = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newEnd, scale - 1, true);
  618. if (safeStart != newStart || safeEnd != newEnd) {
  619. this.props.touch.start = safeStart;
  620. this.props.touch.end = safeEnd;
  621. this.scaleOffset = 1 - event.scale;
  622. newStart = safeStart;
  623. newEnd = safeEnd;
  624. }
  625. var options = {
  626. animation: false,
  627. byUser: true,
  628. event: event
  629. };
  630. this.setRange(newStart, newEnd, options);
  631. this.startToFront = false; // revert to default
  632. this.endToFront = true; // revert to default
  633. };
  634. /**
  635. * Test whether the mouse from a mouse event is inside the visible window,
  636. * between the current start and end date
  637. * @param {Object} event
  638. * @return {boolean} Returns true when inside the visible window
  639. * @private
  640. */
  641. Range.prototype._isInsideRange = function(event) {
  642. // calculate the time where the mouse is, check whether inside
  643. // and no scroll action should happen.
  644. var clientX = event.center ? event.center.x : event.clientX;
  645. var x;
  646. if (this.options.rtl) {
  647. x = clientX - util.getAbsoluteLeft(this.body.dom.centerContainer);
  648. } else {
  649. x = util.getAbsoluteRight(this.body.dom.centerContainer) - clientX;
  650. }
  651. var time = this.body.util.toTime(x);
  652. return time >= this.start && time <= this.end;
  653. };
  654. /**
  655. * Helper function to calculate the center date for zooming
  656. * @param {{x: number, y: number}} pointer
  657. * @return {number} date
  658. * @private
  659. */
  660. Range.prototype._pointerToDate = function (pointer) {
  661. var conversion;
  662. var direction = this.options.direction;
  663. validateDirection(direction);
  664. if (direction == 'horizontal') {
  665. return this.body.util.toTime(pointer.x).valueOf();
  666. }
  667. else {
  668. var height = this.body.domProps.center.height;
  669. conversion = this.conversion(height);
  670. return pointer.y / conversion.scale + conversion.offset;
  671. }
  672. };
  673. /**
  674. * Get the pointer location relative to the location of the dom element
  675. * @param {{x: number, y: number}} touch
  676. * @param {Element} element HTML DOM element
  677. * @return {{x: number, y: number}} pointer
  678. * @private
  679. */
  680. Range.prototype.getPointer = function (touch, element) {
  681. if (this.options.rtl) {
  682. return {
  683. x: util.getAbsoluteRight(element) - touch.x,
  684. y: touch.y - util.getAbsoluteTop(element)
  685. };
  686. } else {
  687. return {
  688. x: touch.x - util.getAbsoluteLeft(element),
  689. y: touch.y - util.getAbsoluteTop(element)
  690. };
  691. }
  692. };
  693. /**
  694. * Zoom the range the given scale in or out. Start and end date will
  695. * be adjusted, and the timeline will be redrawn. You can optionally give a
  696. * date around which to zoom.
  697. * For example, try scale = 0.9 or 1.1
  698. * @param {number} scale Scaling factor. Values above 1 will zoom out,
  699. * values below 1 will zoom in.
  700. * @param {number} [center] Value representing a date around which will
  701. * be zoomed.
  702. * @param {number} delta
  703. * @param {Event} event
  704. */
  705. Range.prototype.zoom = function(scale, center, delta, event) {
  706. // if centerDate is not provided, take it half between start Date and end Date
  707. if (center == null) {
  708. center = (this.start + this.end) / 2;
  709. }
  710. var hiddenDuration = DateUtil.getHiddenDurationBetween(this.body.hiddenDates, this.start, this.end);
  711. var hiddenDurationBefore = DateUtil.getHiddenDurationBefore(this.options.moment, this.body.hiddenDates, this, center);
  712. var hiddenDurationAfter = hiddenDuration - hiddenDurationBefore;
  713. // calculate new start and end
  714. var newStart = (center-hiddenDurationBefore) + (this.start - (center-hiddenDurationBefore)) * scale;
  715. var newEnd = (center+hiddenDurationAfter) + (this.end - (center+hiddenDurationAfter)) * scale;
  716. // snapping times away from hidden zones
  717. this.startToFront = delta > 0 ? false : true; // used to do the right autocorrection with periodic hidden times
  718. this.endToFront = -delta > 0 ? false : true; // used to do the right autocorrection with periodic hidden times
  719. var safeStart = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newStart, delta, true);
  720. var safeEnd = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newEnd, -delta, true);
  721. if (safeStart != newStart || safeEnd != newEnd) {
  722. newStart = safeStart;
  723. newEnd = safeEnd;
  724. }
  725. var options = {
  726. animation: false,
  727. byUser: true,
  728. event: event
  729. };
  730. this.setRange(newStart, newEnd, options);
  731. this.startToFront = false; // revert to default
  732. this.endToFront = true; // revert to default
  733. };
  734. /**
  735. * Move the range with a given delta to the left or right. Start and end
  736. * value will be adjusted. For example, try delta = 0.1 or -0.1
  737. * @param {number} delta Moving amount. Positive value will move right,
  738. * negative value will move left
  739. */
  740. Range.prototype.move = function(delta) {
  741. // zoom start Date and end Date relative to the centerDate
  742. var diff = (this.end - this.start);
  743. // apply new values
  744. var newStart = this.start + diff * delta;
  745. var newEnd = this.end + diff * delta;
  746. // TODO: reckon with min and max range
  747. this.start = newStart;
  748. this.end = newEnd;
  749. };
  750. /**
  751. * Move the range to a new center point
  752. * @param {number} moveTo New center point of the range
  753. */
  754. Range.prototype.moveTo = function(moveTo) {
  755. var center = (this.start + this.end) / 2;
  756. var diff = center - moveTo;
  757. // calculate new start and end
  758. var newStart = this.start - diff;
  759. var newEnd = this.end - diff;
  760. var options = {
  761. animation: false,
  762. byUser: true,
  763. event: null
  764. };
  765. this.setRange(newStart, newEnd, options);
  766. };
  767. module.exports = Range;