Merge branch 'PR723'
[dygraphs.git] / src / dygraph-interaction-model.js
CommitLineData
88e95c46
DV
1/**
2 * @license
3 * Copyright 2011 Robert Konigsberg (konigsberg@google.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
5 */
846f3d2d 6
88e95c46 7/**
846f3d2d
DV
8 * @fileoverview The default interaction model for Dygraphs. This is kept out
9 * of dygraph.js for better navigability.
10 * @author Robert Konigsberg (konigsberg@google.com)
11 */
12
758a629f 13/*global Dygraph:false */
c0f54d4f
DV
14"use strict";
15
6ecc0739
DV
16import * as utils from './dygraph-utils';
17
846f3d2d 18/**
3f50dabb
DV
19 * You can drag this many pixels past the edge of the chart and still have it
20 * be considered a zoom. This makes it easier to zoom to the exact edge of the
21 * chart, a fairly common operation.
22 */
7a2b5176 23var DRAG_EDGE_MARGIN = 100;
3f50dabb
DV
24
25/**
846f3d2d
DV
26 * A collection of functions to facilitate build custom interaction models.
27 * @class
28 */
6ecc0739 29var DygraphInteraction = {};
846f3d2d
DV
30
31/**
3f50dabb
DV
32 * Checks whether the beginning & ending of an event were close enough that it
33 * should be considered a click. If it should, dispatch appropriate events.
34 * Returns true if the event was treated as a click.
35 *
36 * @param {Event} event
37 * @param {Dygraph} g
38 * @param {Object} context
39 */
6ecc0739
DV
40DygraphInteraction.maybeTreatMouseOpAsClick = function(event, g, context) {
41 context.dragEndX = utils.dragGetX_(event, context);
42 context.dragEndY = utils.dragGetY_(event, context);
3f50dabb
DV
43 var regionWidth = Math.abs(context.dragEndX - context.dragStartX);
44 var regionHeight = Math.abs(context.dragEndY - context.dragStartY);
45
46 if (regionWidth < 2 && regionHeight < 2 &&
47 g.lastx_ !== undefined && g.lastx_ != -1) {
6ecc0739 48 DygraphInteraction.treatMouseOpAsClick(g, event, context);
3f50dabb
DV
49 }
50
51 context.regionWidth = regionWidth;
52 context.regionHeight = regionHeight;
46fd9089 53};
3f50dabb
DV
54
55/**
846f3d2d
DV
56 * Called in response to an interaction model operation that
57 * should start the default panning behavior.
58 *
59 * It's used in the default callback for "mousedown" operations.
60 * Custom interaction model builders can use it to provide the default
61 * panning behavior.
62 *
d67a4279
DV
63 * @param {Event} event the event object which led to the startPan call.
64 * @param {Dygraph} g The dygraph on which to act.
65 * @param {Object} context The dragging context object (with
66 * dragStartX/dragStartY/etc. properties). This function modifies the
67 * context.
846f3d2d 68 */
6ecc0739 69DygraphInteraction.startPan = function(event, g, context) {
758a629f 70 var i, axis;
846f3d2d
DV
71 context.isPanning = true;
72 var xRange = g.xAxisRange();
5b9b2142 73
5ec8b8ae 74 if (g.getOptionForAxis("logscale", "x")) {
6ecc0739
DV
75 context.initialLeftmostDate = utils.log10(xRange[0]);
76 context.dateRange = utils.log10(xRange[1]) - utils.log10(xRange[0]);
5b9b2142 77 } else {
6e207211 78 context.initialLeftmostDate = xRange[0];
5b9b2142
RK
79 context.dateRange = xRange[1] - xRange[0];
80 }
846f3d2d
DV
81 context.xUnitsPerPixel = context.dateRange / (g.plotter_.area.w - 1);
82
b0963cdb
DV
83 if (g.getNumericOption("panEdgeFraction")) {
84 var maxXPixelsToDraw = g.width_ * g.getNumericOption("panEdgeFraction");
846f3d2d
DV
85 var xExtremes = g.xAxisExtremes(); // I REALLY WANT TO CALL THIS xTremes!
86
87 var boundedLeftX = g.toDomXCoord(xExtremes[0]) - maxXPixelsToDraw;
88 var boundedRightX = g.toDomXCoord(xExtremes[1]) + maxXPixelsToDraw;
89
90 var boundedLeftDate = g.toDataXCoord(boundedLeftX);
91 var boundedRightDate = g.toDataXCoord(boundedRightX);
92 context.boundedDates = [boundedLeftDate, boundedRightDate];
93
94 var boundedValues = [];
b0963cdb 95 var maxYPixelsToDraw = g.height_ * g.getNumericOption("panEdgeFraction");
846f3d2d 96
758a629f
DV
97 for (i = 0; i < g.axes_.length; i++) {
98 axis = g.axes_[i];
846f3d2d
DV
99 var yExtremes = axis.extremeRange;
100
101 var boundedTopY = g.toDomYCoord(yExtremes[0], i) + maxYPixelsToDraw;
102 var boundedBottomY = g.toDomYCoord(yExtremes[1], i) - maxYPixelsToDraw;
103
f93af875
RK
104 var boundedTopValue = g.toDataYCoord(boundedTopY, i);
105 var boundedBottomValue = g.toDataYCoord(boundedBottomY, i);
846f3d2d
DV
106
107 boundedValues[i] = [boundedTopValue, boundedBottomValue];
108 }
109 context.boundedValues = boundedValues;
110 }
111
112 // Record the range of each y-axis at the start of the drag.
6e207211 113 // If any axis has a valueRange, then we want a 2D pan.
97583b90
DV
114 // We can't store data directly in g.axes_, because it does not belong to us
115 // and could change out from under us during a pan (say if there's a data
116 // update).
846f3d2d 117 context.is2DPan = false;
97583b90 118 context.axes = [];
758a629f
DV
119 for (i = 0; i < g.axes_.length; i++) {
120 axis = g.axes_[i];
97583b90 121 var axis_data = {};
846f3d2d
DV
122 var yRange = g.yAxisRange(i);
123 // TODO(konigsberg): These values should be in |context|.
124 // In log scale, initialTopValue, dragValueRange and unitsPerPixel are log scale.
1ca77443
RK
125 var logscale = g.attributes_.getForAxis("logscale", i);
126 if (logscale) {
6ecc0739
DV
127 axis_data.initialTopValue = utils.log10(yRange[1]);
128 axis_data.dragValueRange = utils.log10(yRange[1]) - utils.log10(yRange[0]);
846f3d2d 129 } else {
97583b90
DV
130 axis_data.initialTopValue = yRange[1];
131 axis_data.dragValueRange = yRange[1] - yRange[0];
846f3d2d 132 }
97583b90
DV
133 axis_data.unitsPerPixel = axis_data.dragValueRange / (g.plotter_.area.h - 1);
134 context.axes.push(axis_data);
846f3d2d
DV
135
136 // While calculating axes, set 2dpan.
6e207211 137 if (axis.valueRange) context.is2DPan = true;
846f3d2d
DV
138 }
139};
140
141/**
142 * Called in response to an interaction model operation that
143 * responds to an event that pans the view.
144 *
145 * It's used in the default callback for "mousemove" operations.
146 * Custom interaction model builders can use it to provide the default
147 * panning behavior.
148 *
d67a4279
DV
149 * @param {Event} event the event object which led to the movePan call.
150 * @param {Dygraph} g The dygraph on which to act.
151 * @param {Object} context The dragging context object (with
152 * dragStartX/dragStartY/etc. properties). This function modifies the
153 * context.
846f3d2d 154 */
6ecc0739
DV
155DygraphInteraction.movePan = function(event, g, context) {
156 context.dragEndX = utils.dragGetX_(event, context);
157 context.dragEndY = utils.dragGetY_(event, context);
846f3d2d
DV
158
159 var minDate = context.initialLeftmostDate -
160 (context.dragEndX - context.dragStartX) * context.xUnitsPerPixel;
161 if (context.boundedDates) {
162 minDate = Math.max(minDate, context.boundedDates[0]);
163 }
164 var maxDate = minDate + context.dateRange;
165 if (context.boundedDates) {
166 if (maxDate > context.boundedDates[1]) {
167 // Adjust minDate, and recompute maxDate.
168 minDate = minDate - (maxDate - context.boundedDates[1]);
169 maxDate = minDate + context.dateRange;
170 }
171 }
172
5ec8b8ae 173 if (g.getOptionForAxis("logscale", "x")) {
6ecc0739
DV
174 g.dateWindow_ = [ Math.pow(utils.LOG_SCALE, minDate),
175 Math.pow(utils.LOG_SCALE, maxDate) ];
5b9b2142 176 } else {
6e207211 177 g.dateWindow_ = [minDate, maxDate];
5b9b2142 178 }
846f3d2d
DV
179
180 // y-axis scaling is automatic unless this is a full 2D pan.
181 if (context.is2DPan) {
f93af875
RK
182
183 var pixelsDragged = context.dragEndY - context.dragStartY;
184
846f3d2d
DV
185 // Adjust each axis appropriately.
186 for (var i = 0; i < g.axes_.length; i++) {
187 var axis = g.axes_[i];
97583b90 188 var axis_data = context.axes[i];
97583b90 189 var unitsDragged = pixelsDragged * axis_data.unitsPerPixel;
920208fb 190
846f3d2d
DV
191 var boundedValue = context.boundedValues ? context.boundedValues[i] : null;
192
193 // In log scale, maxValue and minValue are the logs of those values.
97583b90 194 var maxValue = axis_data.initialTopValue + unitsDragged;
846f3d2d
DV
195 if (boundedValue) {
196 maxValue = Math.min(maxValue, boundedValue[1]);
197 }
97583b90 198 var minValue = maxValue - axis_data.dragValueRange;
846f3d2d
DV
199 if (boundedValue) {
200 if (minValue < boundedValue[0]) {
201 // Adjust maxValue, and recompute minValue.
202 maxValue = maxValue - (minValue - boundedValue[0]);
97583b90 203 minValue = maxValue - axis_data.dragValueRange;
846f3d2d
DV
204 }
205 }
5b9b2142 206 if (g.attributes_.getForAxis("logscale", i)) {
6e207211
DV
207 axis.valueRange = [ Math.pow(utils.LOG_SCALE, minValue),
208 Math.pow(utils.LOG_SCALE, maxValue) ];
846f3d2d 209 } else {
6e207211 210 axis.valueRange = [ minValue, maxValue ];
846f3d2d
DV
211 }
212 }
213 }
214
215 g.drawGraph_(false);
216};
217
218/**
219 * Called in response to an interaction model operation that
220 * responds to an event that ends panning.
221 *
222 * It's used in the default callback for "mouseup" operations.
223 * Custom interaction model builders can use it to provide the default
224 * panning behavior.
225 *
d67a4279
DV
226 * @param {Event} event the event object which led to the endPan call.
227 * @param {Dygraph} g The dygraph on which to act.
228 * @param {Object} context The dragging context object (with
229 * dragStartX/dragStartY/etc. properties). This function modifies the
230 * context.
846f3d2d 231 */
6ecc0739 232DygraphInteraction.endPan = DygraphInteraction.maybeTreatMouseOpAsClick;
846f3d2d
DV
233
234/**
235 * Called in response to an interaction model operation that
236 * responds to an event that starts zooming.
237 *
238 * It's used in the default callback for "mousedown" operations.
239 * Custom interaction model builders can use it to provide the default
240 * zooming behavior.
241 *
d67a4279
DV
242 * @param {Event} event the event object which led to the startZoom call.
243 * @param {Dygraph} g The dygraph on which to act.
244 * @param {Object} context The dragging context object (with
245 * dragStartX/dragStartY/etc. properties). This function modifies the
246 * context.
846f3d2d 247 */
6ecc0739 248DygraphInteraction.startZoom = function(event, g, context) {
846f3d2d 249 context.isZooming = true;
214083b4 250 context.zoomMoved = false;
846f3d2d
DV
251};
252
253/**
254 * Called in response to an interaction model operation that
255 * responds to an event that defines zoom boundaries.
256 *
257 * It's used in the default callback for "mousemove" operations.
258 * Custom interaction model builders can use it to provide the default
259 * zooming behavior.
260 *
d67a4279
DV
261 * @param {Event} event the event object which led to the moveZoom call.
262 * @param {Dygraph} g The dygraph on which to act.
263 * @param {Object} context The dragging context object (with
264 * dragStartX/dragStartY/etc. properties). This function modifies the
265 * context.
846f3d2d 266 */
6ecc0739 267DygraphInteraction.moveZoom = function(event, g, context) {
214083b4 268 context.zoomMoved = true;
6ecc0739
DV
269 context.dragEndX = utils.dragGetX_(event, context);
270 context.dragEndY = utils.dragGetY_(event, context);
846f3d2d
DV
271
272 var xDelta = Math.abs(context.dragStartX - context.dragEndX);
273 var yDelta = Math.abs(context.dragStartY - context.dragEndY);
274
275 // drag direction threshold for y axis is twice as large as x axis
6ecc0739 276 context.dragDirection = (xDelta < yDelta / 2) ? utils.VERTICAL : utils.HORIZONTAL;
846f3d2d
DV
277
278 g.drawZoomRect_(
279 context.dragDirection,
280 context.dragStartX,
281 context.dragEndX,
282 context.dragStartY,
283 context.dragEndY,
284 context.prevDragDirection,
285 context.prevEndX,
286 context.prevEndY);
287
288 context.prevEndX = context.dragEndX;
289 context.prevEndY = context.dragEndY;
290 context.prevDragDirection = context.dragDirection;
291};
292
d67a4279 293/**
6f5f0b2b 294 * TODO(danvk): move this logic into dygraph.js
d67a4279
DV
295 * @param {Dygraph} g
296 * @param {Event} event
297 * @param {Object} context
298 */
6ecc0739 299DygraphInteraction.treatMouseOpAsClick = function(g, event, context) {
b0963cdb
DV
300 var clickCallback = g.getFunctionOption('clickCallback');
301 var pointClickCallback = g.getFunctionOption('pointClickCallback');
846f3d2d
DV
302
303 var selectedPoint = null;
304
6f5f0b2b
DV
305 // Find out if the click occurs on a point.
306 var closestIdx = -1;
307 var closestDistance = Number.MAX_VALUE;
308
309 // check if the click was on a particular point.
310 for (var i = 0; i < g.selPoints_.length; i++) {
311 var p = g.selPoints_[i];
312 var distance = Math.pow(p.canvasx - context.dragEndX, 2) +
313 Math.pow(p.canvasy - context.dragEndY, 2);
314 if (!isNaN(distance) &&
315 (closestIdx == -1 || distance < closestDistance)) {
316 closestDistance = distance;
317 closestIdx = i;
846f3d2d 318 }
6f5f0b2b 319 }
846f3d2d 320
6f5f0b2b
DV
321 // Allow any click within two pixels of the dot.
322 var radius = g.getNumericOption('highlightCircleSize') + 2;
323 if (closestDistance <= radius * radius) {
324 selectedPoint = g.selPoints_[closestIdx];
846f3d2d
DV
325 }
326
327 if (selectedPoint) {
6f5f0b2b
DV
328 var e = {
329 cancelable: true,
330 point: selectedPoint,
331 canvasx: context.dragEndX,
332 canvasy: context.dragEndY
333 };
334 var defaultPrevented = g.cascadeEvents_('pointClick', e);
335 if (defaultPrevented) {
336 // Note: this also prevents click / clickCallback from firing.
337 return;
338 }
339 if (pointClickCallback) {
340 pointClickCallback.call(g, event, selectedPoint);
341 }
846f3d2d
DV
342 }
343
6f5f0b2b 344 var e = {
48238e1d 345 cancelable: true,
6f5f0b2b
DV
346 xval: g.lastx_, // closest point by x value
347 pts: g.selPoints_,
348 canvasx: context.dragEndX,
349 canvasy: context.dragEndY
350 };
351 if (!g.cascadeEvents_('click', e)) {
352 if (clickCallback) {
353 // TODO(danvk): pass along more info about the points, e.g. 'x'
354 clickCallback.call(g, event, g.lastx_, g.selPoints_);
355 }
846f3d2d
DV
356 }
357};
358
359/**
360 * Called in response to an interaction model operation that
361 * responds to an event that performs a zoom based on previously defined
362 * bounds..
363 *
364 * It's used in the default callback for "mouseup" operations.
365 * Custom interaction model builders can use it to provide the default
366 * zooming behavior.
367 *
d67a4279
DV
368 * @param {Event} event the event object which led to the endZoom call.
369 * @param {Dygraph} g The dygraph on which to end the zoom.
370 * @param {Object} context The dragging context object (with
371 * dragStartX/dragStartY/etc. properties). This function modifies the
372 * context.
846f3d2d 373 */
6ecc0739 374DygraphInteraction.endZoom = function(event, g, context) {
7c39bb3a 375 g.clearZoomRect_();
846f3d2d 376 context.isZooming = false;
6ecc0739 377 DygraphInteraction.maybeTreatMouseOpAsClick(event, g, context);
846f3d2d 378
b04888cc
DV
379 // The zoom rectangle is visibly clipped to the plot area, so its behavior
380 // should be as well.
381 // See http://code.google.com/p/dygraphs/issues/detail?id=280
382 var plotArea = g.getArea();
3f50dabb 383 if (context.regionWidth >= 10 &&
6ecc0739 384 context.dragDirection == utils.HORIZONTAL) {
b04888cc
DV
385 var left = Math.min(context.dragStartX, context.dragEndX),
386 right = Math.max(context.dragStartX, context.dragEndX);
5ee26cc1
DV
387 left = Math.max(left, plotArea.x);
388 right = Math.min(right, plotArea.x + plotArea.w);
389 if (left < right) {
390 g.doZoomX_(left, right);
391 }
421f1773 392 context.cancelNextDblclick = true;
3f50dabb 393 } else if (context.regionHeight >= 10 &&
6ecc0739 394 context.dragDirection == utils.VERTICAL) {
b04888cc
DV
395 var top = Math.min(context.dragStartY, context.dragEndY),
396 bottom = Math.max(context.dragStartY, context.dragEndY);
5ee26cc1
DV
397 top = Math.max(top, plotArea.y);
398 bottom = Math.min(bottom, plotArea.y + plotArea.h);
399 if (top < bottom) {
400 g.doZoomY_(top, bottom);
401 }
421f1773 402 context.cancelNextDblclick = true;
846f3d2d
DV
403 }
404 context.dragStartX = null;
405 context.dragStartY = null;
406};
407
408/**
6125fedf
DV
409 * @private
410 */
6ecc0739 411DygraphInteraction.startTouch = function(event, g, context) {
6125fedf 412 event.preventDefault(); // touch browsers are all nice.
b19d7411
DV
413 if (event.touches.length > 1) {
414 // If the user ever puts two fingers down, it's not a double tap.
415 context.startTimeForDoubleTapMs = null;
416 }
417
6125fedf
DV
418 var touches = [];
419 for (var i = 0; i < event.touches.length; i++) {
420 var t = event.touches[i];
421 // we dispense with 'dragGetX_' because all touchBrowsers support pageX
422 touches.push({
423 pageX: t.pageX,
424 pageY: t.pageY,
425 dataX: g.toDataXCoord(t.pageX),
426 dataY: g.toDataYCoord(t.pageY)
427 // identifier: t.identifier
428 });
429 }
430 context.initialTouches = touches;
431
432 if (touches.length == 1) {
86ca574e
KB
433 // This is possbily a touchOVER, save the last touch to check
434 context.lastTouch = event;
435 // or This is just a swipe.
6125fedf
DV
436 context.initialPinchCenter = touches[0];
437 context.touchDirections = { x: true, y: true };
48cdd6c4 438 } else if (touches.length >= 2) {
6125fedf 439 // It's become a pinch!
48cdd6c4 440 // In case there are 3+ touches, we ignore all but the "first" two.
6125fedf
DV
441
442 // only screen coordinates can be averaged (data coords could be log scale).
443 context.initialPinchCenter = {
444 pageX: 0.5 * (touches[0].pageX + touches[1].pageX),
445 pageY: 0.5 * (touches[0].pageY + touches[1].pageY),
446
447 // TODO(danvk): remove
448 dataX: 0.5 * (touches[0].dataX + touches[1].dataX),
e446c952 449 dataY: 0.5 * (touches[0].dataY + touches[1].dataY)
6125fedf
DV
450 };
451
452 // Make pinches in a 45-degree swath around either axis 1-dimensional zooms.
453 var initialAngle = 180 / Math.PI * Math.atan2(
454 context.initialPinchCenter.pageY - touches[0].pageY,
455 touches[0].pageX - context.initialPinchCenter.pageX);
456
457 // use symmetry to get it into the first quadrant.
458 initialAngle = Math.abs(initialAngle);
459 if (initialAngle > 90) initialAngle = 90 - initialAngle;
460
461 context.touchDirections = {
462 x: (initialAngle < (90 - 45/2)),
463 y: (initialAngle > 45/2)
464 };
465 }
466
467 // save the full x & y ranges.
468 context.initialRange = {
469 x: g.xAxisRange(),
470 y: g.yAxisRange()
471 };
472};
473
474/**
475 * @private
476 */
6ecc0739 477DygraphInteraction.moveTouch = function(event, g, context) {
b19d7411
DV
478 // If the tap moves, then it's definitely not part of a double-tap.
479 context.startTimeForDoubleTapMs = null;
7775fca8
KB
480
481 // clear the last touch if it's doing something else
482 context.lastTouch = null;
b19d7411 483
e446c952
DV
484 var i, touches = [];
485 for (i = 0; i < event.touches.length; i++) {
6125fedf
DV
486 var t = event.touches[i];
487 touches.push({
488 pageX: t.pageX,
e446c952 489 pageY: t.pageY
6125fedf
DV
490 });
491 }
492 var initialTouches = context.initialTouches;
493
494 var c_now;
495
496 // old and new centers.
497 var c_init = context.initialPinchCenter;
498 if (touches.length == 1) {
499 c_now = touches[0];
500 } else {
501 c_now = {
502 pageX: 0.5 * (touches[0].pageX + touches[1].pageX),
503 pageY: 0.5 * (touches[0].pageY + touches[1].pageY)
504 };
505 }
506
507 // this is the "swipe" component
508 // we toss it out for now, but could use it in the future.
509 var swipe = {
510 pageX: c_now.pageX - c_init.pageX,
e446c952 511 pageY: c_now.pageY - c_init.pageY
6125fedf
DV
512 };
513 var dataWidth = context.initialRange.x[1] - context.initialRange.x[0];
514 var dataHeight = context.initialRange.y[0] - context.initialRange.y[1];
515 swipe.dataX = (swipe.pageX / g.plotter_.area.w) * dataWidth;
516 swipe.dataY = (swipe.pageY / g.plotter_.area.h) * dataHeight;
517 var xScale, yScale;
518
519 // The residual bits are usually split into scale & rotate bits, but we split
520 // them into x-scale and y-scale bits.
521 if (touches.length == 1) {
522 xScale = 1.0;
523 yScale = 1.0;
48cdd6c4 524 } else if (touches.length >= 2) {
6125fedf
DV
525 var initHalfWidth = (initialTouches[1].pageX - c_init.pageX);
526 xScale = (touches[1].pageX - c_now.pageX) / initHalfWidth;
527
528 var initHalfHeight = (initialTouches[1].pageY - c_init.pageY);
529 yScale = (touches[1].pageY - c_now.pageY) / initHalfHeight;
530 }
531
532 // Clip scaling to [1/8, 8] to prevent too much blowup.
533 xScale = Math.min(8, Math.max(0.125, xScale));
534 yScale = Math.min(8, Math.max(0.125, yScale));
535
b38afae5 536 var didZoom = false;
6125fedf
DV
537 if (context.touchDirections.x) {
538 g.dateWindow_ = [
539 c_init.dataX - swipe.dataX + (context.initialRange.x[0] - c_init.dataX) / xScale,
e446c952 540 c_init.dataX - swipe.dataX + (context.initialRange.x[1] - c_init.dataX) / xScale
6125fedf 541 ];
b38afae5 542 didZoom = true;
6125fedf 543 }
6e207211 544
6125fedf 545 if (context.touchDirections.y) {
e446c952 546 for (i = 0; i < 1 /*g.axes_.length*/; i++) {
6125fedf 547 var axis = g.axes_[i];
1ca77443
RK
548 var logscale = g.attributes_.getForAxis("logscale", i);
549 if (logscale) {
6125fedf
DV
550 // TODO(danvk): implement
551 } else {
6e207211 552 axis.valueRange = [
6125fedf 553 c_init.dataY - swipe.dataY + (context.initialRange.y[0] - c_init.dataY) / yScale,
e446c952 554 c_init.dataY - swipe.dataY + (context.initialRange.y[1] - c_init.dataY) / yScale
6125fedf 555 ];
b38afae5 556 didZoom = true;
6125fedf
DV
557 }
558 }
559 }
560
561 g.drawGraph_(false);
b38afae5
DV
562
563 // We only call zoomCallback on zooms, not pans, to mirror desktop behavior.
b0963cdb 564 if (didZoom && touches.length > 1 && g.getFunctionOption('zoomCallback')) {
b38afae5 565 var viewWindow = g.xAxisRange();
4ee251cb 566 g.getFunctionOption("zoomCallback").call(g, viewWindow[0], viewWindow[1], g.yAxisRanges());
b38afae5 567 }
6125fedf
DV
568};
569
570/**
571 * @private
572 */
6ecc0739 573DygraphInteraction.endTouch = function(event, g, context) {
42a9ebb8 574 if (event.touches.length !== 0) {
6125fedf 575 // this is effectively a "reset"
6ecc0739 576 DygraphInteraction.startTouch(event, g, context);
b19d7411
DV
577 } else if (event.changedTouches.length == 1) {
578 // Could be part of a "double tap"
579 // The heuristic here is that it's a double-tap if the two touchend events
580 // occur within 500ms and within a 50x50 pixel box.
581 var now = new Date().getTime();
582 var t = event.changedTouches[0];
583 if (context.startTimeForDoubleTapMs &&
584 now - context.startTimeForDoubleTapMs < 500 &&
585 context.doubleTapX && Math.abs(context.doubleTapX - t.screenX) < 50 &&
586 context.doubleTapY && Math.abs(context.doubleTapY - t.screenY) < 50) {
587 g.resetZoom();
588 } else {
7775fca8
KB
589
590 if (context.lastTouch !== null){
591 // no double-tap, pan or pinch so it's a touchOVER
3ca097d8 592 event.isTouchOver = true;
7775fca8
KB
593 g.mouseMove(event);
594 }
595
b19d7411
DV
596 context.startTimeForDoubleTapMs = now;
597 context.doubleTapX = t.screenX;
598 context.doubleTapY = t.screenY;
599 }
6125fedf
DV
600 }
601};
602
3f50dabb
DV
603// Determine the distance from x to [left, right].
604var distanceFromInterval = function(x, left, right) {
605 if (x < left) {
606 return left - x;
607 } else if (x > right) {
608 return x - right;
609 } else {
610 return 0;
611 }
612};
613
614/**
615 * Returns the number of pixels by which the event happens from the nearest
616 * edge of the chart. For events in the interior of the chart, this returns zero.
617 */
618var distanceFromChart = function(event, g) {
6ecc0739 619 var chartPos = utils.findPos(g.canvas_);
3f50dabb
DV
620 var box = {
621 left: chartPos.x,
622 right: chartPos.x + g.canvas_.offsetWidth,
623 top: chartPos.y,
624 bottom: chartPos.y + g.canvas_.offsetHeight
625 };
626
627 var pt = {
6ecc0739
DV
628 x: utils.pageX(event),
629 y: utils.pageY(event)
3f50dabb
DV
630 };
631
632 var dx = distanceFromInterval(pt.x, box.left, box.right),
633 dy = distanceFromInterval(pt.y, box.top, box.bottom);
634 return Math.max(dx, dy);
635};
636
6125fedf 637/**
846f3d2d
DV
638 * Default interation model for dygraphs. You can refer to specific elements of
639 * this when constructing your own interaction model, e.g.:
640 * g.updateOptions( {
641 * interactionModel: {
6ecc0739 642 * mousedown: DygraphInteraction.defaultInteractionModel.mousedown
846f3d2d
DV
643 * }
644 * } );
645 */
6ecc0739 646DygraphInteraction.defaultModel = {
846f3d2d
DV
647 // Track the beginning of drag events
648 mousedown: function(event, g, context) {
e992d194
DV
649 // Right-click should not initiate a zoom.
650 if (event.button && event.button == 2) return;
651
846f3d2d
DV
652 context.initializeMouseDown(event, g, context);
653
654 if (event.altKey || event.shiftKey) {
6ecc0739 655 DygraphInteraction.startPan(event, g, context);
846f3d2d 656 } else {
6ecc0739 657 DygraphInteraction.startZoom(event, g, context);
846f3d2d 658 }
846f3d2d 659
3f50dabb
DV
660 // Note: we register mousemove/mouseup on document to allow some leeway for
661 // events to move outside of the chart. Interaction model events get
662 // registered on the canvas, which is too small to allow this.
663 var mousemove = function(event) {
664 if (context.isZooming) {
665 // When the mouse moves >200px from the chart edge, cancel the zoom.
666 var d = distanceFromChart(event, g);
5e1abda5 667 if (d < DRAG_EDGE_MARGIN) {
6ecc0739 668 DygraphInteraction.moveZoom(event, g, context);
3f50dabb
DV
669 } else {
670 if (context.dragEndX !== null) {
671 context.dragEndX = null;
672 context.dragEndY = null;
673 g.clearZoomRect_();
674 }
675 }
676 } else if (context.isPanning) {
6ecc0739 677 DygraphInteraction.movePan(event, g, context);
3f50dabb
DV
678 }
679 };
680 var mouseup = function(event) {
681 if (context.isZooming) {
682 if (context.dragEndX !== null) {
6ecc0739 683 DygraphInteraction.endZoom(event, g, context);
3f50dabb 684 } else {
6ecc0739 685 DygraphInteraction.maybeTreatMouseOpAsClick(event, g, context);
3f50dabb
DV
686 }
687 } else if (context.isPanning) {
6ecc0739 688 DygraphInteraction.endPan(event, g, context);
3f50dabb 689 }
846f3d2d 690
6ecc0739
DV
691 utils.removeEvent(document, 'mousemove', mousemove);
692 utils.removeEvent(document, 'mouseup', mouseup);
3f50dabb
DV
693 context.destroy();
694 };
695
696 g.addAndTrackEvent(document, 'mousemove', mousemove);
697 g.addAndTrackEvent(document, 'mouseup', mouseup);
846f3d2d 698 },
3f50dabb 699 willDestroyContextMyself: true,
846f3d2d 700
6125fedf 701 touchstart: function(event, g, context) {
6ecc0739 702 DygraphInteraction.startTouch(event, g, context);
6125fedf
DV
703 },
704 touchmove: function(event, g, context) {
6ecc0739 705 DygraphInteraction.moveTouch(event, g, context);
6125fedf
DV
706 },
707 touchend: function(event, g, context) {
6ecc0739 708 DygraphInteraction.endTouch(event, g, context);
6125fedf
DV
709 },
710
846f3d2d
DV
711 // Disable zooming out if panning.
712 dblclick: function(event, g, context) {
421f1773
DV
713 if (context.cancelNextDblclick) {
714 context.cancelNextDblclick = false;
715 return;
716 }
6f5f0b2b
DV
717
718 // Give plugins a chance to grab this event.
719 var e = {
720 canvasx: context.dragEndX,
aa0b189f
DV
721 canvasy: context.dragEndY,
722 cancelable: true,
6f5f0b2b
DV
723 };
724 if (g.cascadeEvents_('dblclick', e)) {
725 return;
726 }
727
846f3d2d
DV
728 if (event.altKey || event.shiftKey) {
729 return;
730 }
e4f6e11a 731 g.resetZoom();
846f3d2d
DV
732 }
733};
734
6ecc0739
DV
735/*
736Dygraph.DEFAULT_ATTRS.interactionModel = DygraphInteraction.defaultModel;
846f3d2d
DV
737
738// old ways of accessing these methods/properties
6ecc0739
DV
739Dygraph.defaultInteractionModel = DygraphInteraction.defaultModel;
740Dygraph.endZoom = DygraphInteraction.endZoom;
741Dygraph.moveZoom = DygraphInteraction.moveZoom;
742Dygraph.startZoom = DygraphInteraction.startZoom;
743Dygraph.endPan = DygraphInteraction.endPan;
744Dygraph.movePan = DygraphInteraction.movePan;
745Dygraph.startPan = DygraphInteraction.startPan;
746*/
747
748DygraphInteraction.nonInteractiveModel_ = {
027e9e9b
DV
749 mousedown: function(event, g, context) {
750 context.initializeMouseDown(event, g, context);
751 },
6ecc0739 752 mouseup: DygraphInteraction.maybeTreatMouseOpAsClick
027e9e9b 753};
3417f017
DV
754
755// Default interaction model when using the range selector.
6ecc0739 756DygraphInteraction.dragIsPanInteractionModel = {
3417f017
DV
757 mousedown: function(event, g, context) {
758 context.initializeMouseDown(event, g, context);
6ecc0739 759 DygraphInteraction.startPan(event, g, context);
3417f017
DV
760 },
761 mousemove: function(event, g, context) {
762 if (context.isPanning) {
6ecc0739 763 DygraphInteraction.movePan(event, g, context);
3417f017
DV
764 }
765 },
766 mouseup: function(event, g, context) {
767 if (context.isPanning) {
6ecc0739 768 DygraphInteraction.endPan(event, g, context);
3417f017
DV
769 }
770 }
771};
3f50dabb 772
6ecc0739 773export default DygraphInteraction;