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.

669 lines
21 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
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. this.start = now.clone().add(-3, 'days').valueOf(); // Number
  17. this.end = now.clone().add(4, 'days').valueOf(); // Number
  18. this.body = body;
  19. this.deltaDifference = 0;
  20. this.scaleOffset = 0;
  21. this.startToFront = false;
  22. this.endToFront = true;
  23. // default options
  24. this.defaultOptions = {
  25. start: null,
  26. end: null,
  27. direction: 'horizontal', // 'horizontal' or 'vertical'
  28. moveable: true,
  29. zoomable: true,
  30. min: null,
  31. max: null,
  32. zoomMin: 10, // milliseconds
  33. zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000 // milliseconds
  34. };
  35. this.options = util.extend({}, this.defaultOptions);
  36. this.props = {
  37. touch: {}
  38. };
  39. this.animateTimer = null;
  40. // drag listeners for dragging
  41. this.body.emitter.on('panstart', this._onDragStart.bind(this));
  42. this.body.emitter.on('panmove', this._onDrag.bind(this));
  43. this.body.emitter.on('panend', this._onDragEnd.bind(this));
  44. // mouse wheel for zooming
  45. this.body.emitter.on('mousewheel', this._onMouseWheel.bind(this));
  46. // pinch to zoom
  47. this.body.emitter.on('touch', this._onTouch.bind(this));
  48. this.body.emitter.on('pinch', this._onPinch.bind(this));
  49. this.setOptions(options);
  50. }
  51. Range.prototype = new Component();
  52. /**
  53. * Set options for the range controller
  54. * @param {Object} options Available options:
  55. * {Number | Date | String} start Start date for the range
  56. * {Number | Date | String} end End date for the range
  57. * {Number} min Minimum value for start
  58. * {Number} max Maximum value for end
  59. * {Number} zoomMin Set a minimum value for
  60. * (end - start).
  61. * {Number} zoomMax Set a maximum value for
  62. * (end - start).
  63. * {Boolean} moveable Enable moving of the range
  64. * by dragging. True by default
  65. * {Boolean} zoomable Enable zooming of the range
  66. * by pinching/scrolling. True by default
  67. */
  68. Range.prototype.setOptions = function (options) {
  69. if (options) {
  70. // copy the options that we know
  71. var fields = ['direction', 'min', 'max', 'zoomMin', 'zoomMax', 'moveable', 'zoomable', 'activate', 'hiddenDates'];
  72. util.selectiveExtend(fields, this.options, options);
  73. if ('start' in options || 'end' in options) {
  74. // apply a new range. both start and end are optional
  75. this.setRange(options.start, options.end);
  76. }
  77. }
  78. };
  79. /**
  80. * Test whether direction has a valid value
  81. * @param {String} direction 'horizontal' or 'vertical'
  82. */
  83. function validateDirection (direction) {
  84. if (direction != 'horizontal' && direction != 'vertical') {
  85. throw new TypeError('Unknown direction "' + direction + '". ' +
  86. 'Choose "horizontal" or "vertical".');
  87. }
  88. }
  89. /**
  90. * Set a new start and end range
  91. * @param {Date | Number | String} [start]
  92. * @param {Date | Number | String} [end]
  93. * @param {boolean | number} [animate=false] If true, the range is animated
  94. * smoothly to the new window.
  95. * If animate is a number, the
  96. * number is taken as duration
  97. * Default duration is 500 ms.
  98. * @param {Boolean} [byUser=false]
  99. *
  100. */
  101. Range.prototype.setRange = function(start, end, animate, byUser) {
  102. if (byUser !== true) {
  103. byUser = false;
  104. }
  105. var _start = start != undefined ? util.convert(start, 'Date').valueOf() : null;
  106. var _end = end != undefined ? util.convert(end, 'Date').valueOf() : null;
  107. this._cancelAnimation();
  108. if (animate) {
  109. var me = this;
  110. var initStart = this.start;
  111. var initEnd = this.end;
  112. var duration = typeof animate === 'number' ? animate : 500;
  113. var initTime = new Date().valueOf();
  114. var anyChanged = false;
  115. var next = function () {
  116. if (!me.props.touch.dragging) {
  117. var now = new Date().valueOf();
  118. var time = now - initTime;
  119. var done = time > duration;
  120. var s = (done || _start === null) ? _start : util.easeInOutQuad(time, initStart, _start, duration);
  121. var e = (done || _end === null) ? _end : util.easeInOutQuad(time, initEnd, _end, duration);
  122. changed = me._applyRange(s, e);
  123. DateUtil.updateHiddenDates(me.body, me.options.hiddenDates);
  124. anyChanged = anyChanged || changed;
  125. if (changed) {
  126. me.body.emitter.emit('rangechange', {start: new Date(me.start), end: new Date(me.end), byUser:byUser});
  127. }
  128. if (done) {
  129. if (anyChanged) {
  130. me.body.emitter.emit('rangechanged', {start: new Date(me.start), end: new Date(me.end), byUser:byUser});
  131. }
  132. }
  133. else {
  134. // animate with as high as possible frame rate, leave 20 ms in between
  135. // each to prevent the browser from blocking
  136. me.animateTimer = setTimeout(next, 20);
  137. }
  138. }
  139. };
  140. return next();
  141. }
  142. else {
  143. var changed = this._applyRange(_start, _end);
  144. DateUtil.updateHiddenDates(this.body, this.options.hiddenDates);
  145. if (changed) {
  146. var params = {start: new Date(this.start), end: new Date(this.end), byUser:byUser};
  147. this.body.emitter.emit('rangechange', params);
  148. this.body.emitter.emit('rangechanged', params);
  149. }
  150. }
  151. };
  152. /**
  153. * Stop an animation
  154. * @private
  155. */
  156. Range.prototype._cancelAnimation = function () {
  157. if (this.animateTimer) {
  158. clearTimeout(this.animateTimer);
  159. this.animateTimer = null;
  160. }
  161. };
  162. /**
  163. * Set a new start and end range. This method is the same as setRange, but
  164. * does not trigger a range change and range changed event, and it returns
  165. * true when the range is changed
  166. * @param {Number} [start]
  167. * @param {Number} [end]
  168. * @return {Boolean} changed
  169. * @private
  170. */
  171. Range.prototype._applyRange = function(start, end) {
  172. var newStart = (start != null) ? util.convert(start, 'Date').valueOf() : this.start,
  173. newEnd = (end != null) ? util.convert(end, 'Date').valueOf() : this.end,
  174. max = (this.options.max != null) ? util.convert(this.options.max, 'Date').valueOf() : null,
  175. min = (this.options.min != null) ? util.convert(this.options.min, 'Date').valueOf() : null,
  176. diff;
  177. // check for valid number
  178. if (isNaN(newStart) || newStart === null) {
  179. throw new Error('Invalid start "' + start + '"');
  180. }
  181. if (isNaN(newEnd) || newEnd === null) {
  182. throw new Error('Invalid end "' + end + '"');
  183. }
  184. // prevent start < end
  185. if (newEnd < newStart) {
  186. newEnd = newStart;
  187. }
  188. // prevent start < min
  189. if (min !== null) {
  190. if (newStart < min) {
  191. diff = (min - newStart);
  192. newStart += diff;
  193. newEnd += diff;
  194. // prevent end > max
  195. if (max != null) {
  196. if (newEnd > max) {
  197. newEnd = max;
  198. }
  199. }
  200. }
  201. }
  202. // prevent end > max
  203. if (max !== null) {
  204. if (newEnd > max) {
  205. diff = (newEnd - max);
  206. newStart -= diff;
  207. newEnd -= diff;
  208. // prevent start < min
  209. if (min != null) {
  210. if (newStart < min) {
  211. newStart = min;
  212. }
  213. }
  214. }
  215. }
  216. // prevent (end-start) < zoomMin
  217. if (this.options.zoomMin !== null) {
  218. var zoomMin = parseFloat(this.options.zoomMin);
  219. if (zoomMin < 0) {
  220. zoomMin = 0;
  221. }
  222. if ((newEnd - newStart) < zoomMin) {
  223. if ((this.end - this.start) === zoomMin && newStart > this.start && newEnd < this.end) {
  224. // ignore this action, we are already zoomed to the minimum
  225. newStart = this.start;
  226. newEnd = this.end;
  227. }
  228. else {
  229. // zoom to the minimum
  230. diff = (zoomMin - (newEnd - newStart));
  231. newStart -= diff / 2;
  232. newEnd += diff / 2;
  233. }
  234. }
  235. }
  236. // prevent (end-start) > zoomMax
  237. if (this.options.zoomMax !== null) {
  238. var zoomMax = parseFloat(this.options.zoomMax);
  239. if (zoomMax < 0) {
  240. zoomMax = 0;
  241. }
  242. if ((newEnd - newStart) > zoomMax) {
  243. if ((this.end - this.start) === zoomMax && newStart < this.start && newEnd > this.end) {
  244. // ignore this action, we are already zoomed to the maximum
  245. newStart = this.start;
  246. newEnd = this.end;
  247. }
  248. else {
  249. // zoom to the maximum
  250. diff = ((newEnd - newStart) - zoomMax);
  251. newStart += diff / 2;
  252. newEnd -= diff / 2;
  253. }
  254. }
  255. }
  256. var changed = (this.start != newStart || this.end != newEnd);
  257. // 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)
  258. if (!((newStart >= this.start && newStart <= this.end) || (newEnd >= this.start && newEnd <= this.end)) &&
  259. !((this.start >= newStart && this.start <= newEnd) || (this.end >= newStart && this.end <= newEnd) )) {
  260. this.body.emitter.emit('checkRangedItems');
  261. }
  262. this.start = newStart;
  263. this.end = newEnd;
  264. return changed;
  265. };
  266. /**
  267. * Retrieve the current range.
  268. * @return {Object} An object with start and end properties
  269. */
  270. Range.prototype.getRange = function() {
  271. return {
  272. start: this.start,
  273. end: this.end
  274. };
  275. };
  276. /**
  277. * Calculate the conversion offset and scale for current range, based on
  278. * the provided width
  279. * @param {Number} width
  280. * @returns {{offset: number, scale: number}} conversion
  281. */
  282. Range.prototype.conversion = function (width, totalHidden) {
  283. return Range.conversion(this.start, this.end, width, totalHidden);
  284. };
  285. /**
  286. * Static method to calculate the conversion offset and scale for a range,
  287. * based on the provided start, end, and width
  288. * @param {Number} start
  289. * @param {Number} end
  290. * @param {Number} width
  291. * @returns {{offset: number, scale: number}} conversion
  292. */
  293. Range.conversion = function (start, end, width, totalHidden) {
  294. if (totalHidden === undefined) {
  295. totalHidden = 0;
  296. }
  297. if (width != 0 && (end - start != 0)) {
  298. return {
  299. offset: start,
  300. scale: width / (end - start - totalHidden)
  301. }
  302. }
  303. else {
  304. return {
  305. offset: 0,
  306. scale: 1
  307. };
  308. }
  309. };
  310. /**
  311. * Start dragging horizontally or vertically
  312. * @param {Event} event
  313. * @private
  314. */
  315. Range.prototype._onDragStart = function(event) {
  316. this.deltaDifference = 0;
  317. this.previousDelta = 0;
  318. // only allow dragging when configured as movable
  319. if (!this.options.moveable) return;
  320. // refuse to drag when we where pinching to prevent the timeline make a jump
  321. // when releasing the fingers in opposite order from the touch screen
  322. if (!this.props.touch.allowDragging) return;
  323. this.props.touch.start = this.start;
  324. this.props.touch.end = this.end;
  325. this.props.touch.dragging = true;
  326. if (this.body.dom.root) {
  327. this.body.dom.root.style.cursor = 'move';
  328. }
  329. };
  330. /**
  331. * Perform dragging operation
  332. * @param {Event} event
  333. * @private
  334. */
  335. Range.prototype._onDrag = function (event) {
  336. // only allow dragging when configured as movable
  337. if (!this.options.moveable) return;
  338. // TODO: this may be redundant in hammerjs2
  339. // refuse to drag when we where pinching to prevent the timeline make a jump
  340. // when releasing the fingers in opposite order from the touch screen
  341. if (!this.props.touch.allowDragging) return;
  342. var direction = this.options.direction;
  343. validateDirection(direction);
  344. var delta = (direction == 'horizontal') ? event.deltaX : event.deltaY;
  345. delta -= this.deltaDifference;
  346. var interval = (this.props.touch.end - this.props.touch.start);
  347. // normalize dragging speed if cutout is in between.
  348. var duration = DateUtil.getHiddenDurationBetween(this.body.hiddenDates, this.start, this.end);
  349. interval -= duration;
  350. var width = (direction == 'horizontal') ? this.body.domProps.center.width : this.body.domProps.center.height;
  351. var diffRange = -delta / width * interval;
  352. var newStart = this.props.touch.start + diffRange;
  353. var newEnd = this.props.touch.end + diffRange;
  354. // snapping times away from hidden zones
  355. var safeStart = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newStart, this.previousDelta-delta, true);
  356. var safeEnd = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newEnd, this.previousDelta-delta, true);
  357. if (safeStart != newStart || safeEnd != newEnd) {
  358. this.deltaDifference += delta;
  359. this.props.touch.start = safeStart;
  360. this.props.touch.end = safeEnd;
  361. this._onDrag(event);
  362. return;
  363. }
  364. this.previousDelta = delta;
  365. this._applyRange(newStart, newEnd);
  366. // fire a rangechange event
  367. this.body.emitter.emit('rangechange', {
  368. start: new Date(this.start),
  369. end: new Date(this.end),
  370. byUser: true
  371. });
  372. };
  373. /**
  374. * Stop dragging operation
  375. * @param {event} event
  376. * @private
  377. */
  378. Range.prototype._onDragEnd = function (event) {
  379. // only allow dragging when configured as movable
  380. if (!this.options.moveable) return;
  381. // TODO: this may be redundant in hammerjs2
  382. // refuse to drag when we where pinching to prevent the timeline make a jump
  383. // when releasing the fingers in opposite order from the touch screen
  384. if (!this.props.touch.allowDragging) return;
  385. this.props.touch.dragging = false;
  386. if (this.body.dom.root) {
  387. this.body.dom.root.style.cursor = 'auto';
  388. }
  389. // fire a rangechanged event
  390. this.body.emitter.emit('rangechanged', {
  391. start: new Date(this.start),
  392. end: new Date(this.end),
  393. byUser: true
  394. });
  395. };
  396. /**
  397. * Event handler for mouse wheel event, used to zoom
  398. * Code from http://adomas.org/javascript-mouse-wheel/
  399. * @param {Event} event
  400. * @private
  401. */
  402. Range.prototype._onMouseWheel = function(event) {
  403. // only allow zooming when configured as zoomable and moveable
  404. if (!(this.options.zoomable && this.options.moveable)) return;
  405. // retrieve delta
  406. var delta = 0;
  407. if (event.wheelDelta) { /* IE/Opera. */
  408. delta = event.wheelDelta / 120;
  409. } else if (event.detail) { /* Mozilla case. */
  410. // In Mozilla, sign of delta is different than in IE.
  411. // Also, delta is multiple of 3.
  412. delta = -event.detail / 3;
  413. }
  414. // If delta is nonzero, handle it.
  415. // Basically, delta is now positive if wheel was scrolled up,
  416. // and negative, if wheel was scrolled down.
  417. if (delta) {
  418. // perform the zoom action. Delta is normally 1 or -1
  419. // adjust a negative delta such that zooming in with delta 0.1
  420. // equals zooming out with a delta -0.1
  421. var scale;
  422. if (delta < 0) {
  423. scale = 1 - (delta / 5);
  424. }
  425. else {
  426. scale = 1 / (1 + (delta / 5)) ;
  427. }
  428. // calculate center, the date to zoom around
  429. var pointer = getPointer({x: event.pageX, y: event.pageY}, this.body.dom.center);
  430. var pointerDate = this._pointerToDate(pointer);
  431. this.zoom(scale, pointerDate, delta);
  432. }
  433. // Prevent default actions caused by mouse wheel
  434. // (else the page and timeline both zoom and scroll)
  435. event.preventDefault();
  436. };
  437. /**
  438. * Start of a touch gesture
  439. * @private
  440. */
  441. Range.prototype._onTouch = function (event) {
  442. this.props.touch.start = this.start;
  443. this.props.touch.end = this.end;
  444. this.props.touch.allowDragging = true;
  445. this.props.touch.center = null;
  446. this.scaleOffset = 0;
  447. this.deltaDifference = 0;
  448. };
  449. /**
  450. * Handle pinch event
  451. * @param {Event} event
  452. * @private
  453. */
  454. Range.prototype._onPinch = function (event) {
  455. // only allow zooming when configured as zoomable and moveable
  456. if (!(this.options.zoomable && this.options.moveable)) return;
  457. this.props.touch.allowDragging = false;
  458. if (!this.props.touch.center) {
  459. this.props.touch.center = getPointer(event.center, this.body.dom.center);
  460. }
  461. var scale = 1 / (event.scale + this.scaleOffset);
  462. var centerDate = this._pointerToDate(this.props.touch.center);
  463. var hiddenDuration = DateUtil.getHiddenDurationBetween(this.body.hiddenDates, this.start, this.end);
  464. var hiddenDurationBefore = DateUtil.getHiddenDurationBefore(this.body.hiddenDates, this, centerDate);
  465. var hiddenDurationAfter = hiddenDuration - hiddenDurationBefore;
  466. // calculate new start and end
  467. var newStart = (centerDate - hiddenDurationBefore) + (this.props.touch.start - (centerDate - hiddenDurationBefore)) * scale;
  468. var newEnd = (centerDate + hiddenDurationAfter) + (this.props.touch.end - (centerDate + hiddenDurationAfter)) * scale;
  469. // snapping times away from hidden zones
  470. this.startToFront = 1 - scale <= 0; // used to do the right auto correction with periodic hidden times
  471. this.endToFront = scale - 1 <= 0; // used to do the right auto correction with periodic hidden times
  472. var safeStart = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newStart, 1 - scale, true);
  473. var safeEnd = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newEnd, scale - 1, true);
  474. if (safeStart != newStart || safeEnd != newEnd) {
  475. this.props.touch.start = safeStart;
  476. this.props.touch.end = safeEnd;
  477. this.scaleOffset = 1 - event.scale;
  478. newStart = safeStart;
  479. newEnd = safeEnd;
  480. }
  481. this.setRange(newStart, newEnd, false, true);
  482. this.startToFront = false; // revert to default
  483. this.endToFront = true; // revert to default
  484. };
  485. /**
  486. * Helper function to calculate the center date for zooming
  487. * @param {{x: Number, y: Number}} pointer
  488. * @return {number} date
  489. * @private
  490. */
  491. Range.prototype._pointerToDate = function (pointer) {
  492. var conversion;
  493. var direction = this.options.direction;
  494. validateDirection(direction);
  495. if (direction == 'horizontal') {
  496. return this.body.util.toTime(pointer.x).valueOf();
  497. }
  498. else {
  499. var height = this.body.domProps.center.height;
  500. conversion = this.conversion(height);
  501. return pointer.y / conversion.scale + conversion.offset;
  502. }
  503. };
  504. /**
  505. * Get the pointer location relative to the location of the dom element
  506. * @param {{x: Number, y: Number}} touch
  507. * @param {Element} element HTML DOM element
  508. * @return {{x: Number, y: Number}} pointer
  509. * @private
  510. */
  511. function getPointer (touch, element) {
  512. return {
  513. x: touch.x - util.getAbsoluteLeft(element),
  514. y: touch.y - util.getAbsoluteTop(element)
  515. };
  516. }
  517. /**
  518. * Zoom the range the given scale in or out. Start and end date will
  519. * be adjusted, and the timeline will be redrawn. You can optionally give a
  520. * date around which to zoom.
  521. * For example, try scale = 0.9 or 1.1
  522. * @param {Number} scale Scaling factor. Values above 1 will zoom out,
  523. * values below 1 will zoom in.
  524. * @param {Number} [center] Value representing a date around which will
  525. * be zoomed.
  526. */
  527. Range.prototype.zoom = function(scale, center, delta) {
  528. // if centerDate is not provided, take it half between start Date and end Date
  529. if (center == null) {
  530. center = (this.start + this.end) / 2;
  531. }
  532. var hiddenDuration = DateUtil.getHiddenDurationBetween(this.body.hiddenDates, this.start, this.end);
  533. var hiddenDurationBefore = DateUtil.getHiddenDurationBefore(this.body.hiddenDates, this, center);
  534. var hiddenDurationAfter = hiddenDuration - hiddenDurationBefore;
  535. // calculate new start and end
  536. var newStart = (center-hiddenDurationBefore) + (this.start - (center-hiddenDurationBefore)) * scale;
  537. var newEnd = (center+hiddenDurationAfter) + (this.end - (center+hiddenDurationAfter)) * scale;
  538. // snapping times away from hidden zones
  539. this.startToFront = delta > 0 ? false : true; // used to do the right autocorrection with periodic hidden times
  540. this.endToFront = -delta > 0 ? false : true; // used to do the right autocorrection with periodic hidden times
  541. var safeStart = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newStart, delta, true);
  542. var safeEnd = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newEnd, -delta, true);
  543. if (safeStart != newStart || safeEnd != newEnd) {
  544. newStart = safeStart;
  545. newEnd = safeEnd;
  546. }
  547. this.setRange(newStart, newEnd, false, true);
  548. this.startToFront = false; // revert to default
  549. this.endToFront = true; // revert to default
  550. };
  551. /**
  552. * Move the range with a given delta to the left or right. Start and end
  553. * value will be adjusted. For example, try delta = 0.1 or -0.1
  554. * @param {Number} delta Moving amount. Positive value will move right,
  555. * negative value will move left
  556. */
  557. Range.prototype.move = function(delta) {
  558. // zoom start Date and end Date relative to the centerDate
  559. var diff = (this.end - this.start);
  560. // apply new values
  561. var newStart = this.start + diff * delta;
  562. var newEnd = this.end + diff * delta;
  563. // TODO: reckon with min and max range
  564. this.start = newStart;
  565. this.end = newEnd;
  566. };
  567. /**
  568. * Move the range to a new center point
  569. * @param {Number} moveTo New center point of the range
  570. */
  571. Range.prototype.moveTo = function(moveTo) {
  572. var center = (this.start + this.end) / 2;
  573. var diff = center - moveTo;
  574. // calculate new start and end
  575. var newStart = this.start - diff;
  576. var newEnd = this.end - diff;
  577. this.setRange(newStart, newEnd);
  578. };
  579. module.exports = Range;