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.

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