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