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.

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