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.

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