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.

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