Merge branch 'master' of github.com:danvk/dygraphs
[dygraphs.git] / plugins / range-selector.js
1 /**
2 * @license
3 * Copyright 2011 Paul Felix (paul.eric.felix@gmail.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
5 */
6 /*global Dygraph:false,TouchEvent:false */
7
8 /**
9 * @fileoverview This file contains the RangeSelector plugin used to provide
10 * a timeline range selector widget for dygraphs.
11 */
12
13 Dygraph.Plugins.RangeSelector = (function() {
14
15 /*jshint globalstrict: true */
16 /*global Dygraph:false */
17 "use strict";
18
19 var rangeSelector = function() {
20 this.isIE_ = /MSIE/.test(navigator.userAgent) && !window.opera;
21 this.hasTouchInterface_ = typeof(TouchEvent) != 'undefined';
22 this.isMobileDevice_ = /mobile|android/gi.test(navigator.appVersion);
23 this.interfaceCreated_ = false;
24 };
25
26 rangeSelector.prototype.toString = function() {
27 return "RangeSelector Plugin";
28 };
29
30 rangeSelector.prototype.activate = function(dygraph) {
31 this.dygraph_ = dygraph;
32 this.isUsingExcanvas_ = dygraph.isUsingExcanvas_;
33 if (this.getOption_('showRangeSelector')) {
34 this.createInterface_();
35 }
36 return {
37 layout: this.reserveSpace_,
38 predraw: this.renderStaticLayer_,
39 didDrawChart: this.renderInteractiveLayer_
40 };
41 };
42
43 rangeSelector.prototype.destroy = function() {
44 this.bgcanvas_ = null;
45 this.fgcanvas_ = null;
46 this.leftZoomHandle_ = null;
47 this.rightZoomHandle_ = null;
48 this.iePanOverlay_ = null;
49 };
50
51 //------------------------------------------------------------------
52 // Private methods
53 //------------------------------------------------------------------
54
55 rangeSelector.prototype.getOption_ = function(name) {
56 return this.dygraph_.getOption(name);
57 };
58
59 rangeSelector.prototype.setDefaultOption_ = function(name, value) {
60 return this.dygraph_.attrs_[name] = value;
61 };
62
63 /**
64 * @private
65 * Creates the range selector elements and adds them to the graph.
66 */
67 rangeSelector.prototype.createInterface_ = function() {
68 this.createCanvases_();
69 if (this.isUsingExcanvas_) {
70 this.createIEPanOverlay_();
71 }
72 this.createZoomHandles_();
73 this.initInteraction_();
74
75 // Range selector and animatedZooms have a bad interaction. See issue 359.
76 if (this.getOption_('animatedZooms')) {
77 this.dygraph_.warn('Animated zooms and range selector are not compatible; disabling animatedZooms.');
78 this.dygraph_.updateOptions({animatedZooms: false}, true);
79 }
80
81 this.interfaceCreated_ = true;
82 this.addToGraph_();
83 };
84
85 /**
86 * @private
87 * Adds the range selector to the graph.
88 */
89 rangeSelector.prototype.addToGraph_ = function() {
90 var graphDiv = this.graphDiv_ = this.dygraph_.graphDiv;
91 graphDiv.appendChild(this.bgcanvas_);
92 graphDiv.appendChild(this.fgcanvas_);
93 graphDiv.appendChild(this.leftZoomHandle_);
94 graphDiv.appendChild(this.rightZoomHandle_);
95 };
96
97 /**
98 * @private
99 * Removes the range selector from the graph.
100 */
101 rangeSelector.prototype.removeFromGraph_ = function() {
102 var graphDiv = this.graphDiv_;
103 graphDiv.removeChild(this.bgcanvas_);
104 graphDiv.removeChild(this.fgcanvas_);
105 graphDiv.removeChild(this.leftZoomHandle_);
106 graphDiv.removeChild(this.rightZoomHandle_);
107 this.graphDiv_ = null;
108 };
109
110 /**
111 * @private
112 * Called by Layout to allow range selector to reserve its space.
113 */
114 rangeSelector.prototype.reserveSpace_ = function(e) {
115 if (this.getOption_('showRangeSelector')) {
116 e.reserveSpaceBottom(this.getOption_('rangeSelectorHeight') + 4);
117 }
118 };
119
120 /**
121 * @private
122 * Renders the static portion of the range selector at the predraw stage.
123 */
124 rangeSelector.prototype.renderStaticLayer_ = function() {
125 if (!this.updateVisibility_()) {
126 return;
127 }
128 this.resize_();
129 this.drawStaticLayer_();
130 };
131
132 /**
133 * @private
134 * Renders the interactive portion of the range selector after the chart has been drawn.
135 */
136 rangeSelector.prototype.renderInteractiveLayer_ = function() {
137 if (!this.updateVisibility_() || this.isChangingRange_) {
138 return;
139 }
140 this.placeZoomHandles_();
141 this.drawInteractiveLayer_();
142 };
143
144 /**
145 * @private
146 * Check to see if the range selector is enabled/disabled and update visibility accordingly.
147 */
148 rangeSelector.prototype.updateVisibility_ = function() {
149 var enabled = this.getOption_('showRangeSelector');
150 if (enabled) {
151 if (!this.interfaceCreated_) {
152 this.createInterface_();
153 } else if (!this.graphDiv_ || !this.graphDiv_.parentNode) {
154 this.addToGraph_();
155 }
156 } else if (this.graphDiv_) {
157 this.removeFromGraph_();
158 var dygraph = this.dygraph_;
159 setTimeout(function() { dygraph.width_ = 0; dygraph.resize(); }, 1);
160 }
161 return enabled;
162 };
163
164 /**
165 * @private
166 * Resizes the range selector.
167 */
168 rangeSelector.prototype.resize_ = function() {
169 function setElementRect(canvas, rect) {
170 canvas.style.top = rect.y + 'px';
171 canvas.style.left = rect.x + 'px';
172 canvas.width = rect.w;
173 canvas.height = rect.h;
174 canvas.style.width = canvas.width + 'px'; // for IE
175 canvas.style.height = canvas.height + 'px'; // for IE
176 }
177
178 var plotArea = this.dygraph_.layout_.getPlotArea();
179 var xAxisLabelHeight = this.getOption_('xAxisHeight') || (this.getOption_('axisLabelFontSize') + 2 * this.getOption_('axisTickSize'));
180 this.canvasRect_ = {
181 x: plotArea.x,
182 y: plotArea.y + plotArea.h + xAxisLabelHeight + 4,
183 w: plotArea.w,
184 h: this.getOption_('rangeSelectorHeight')
185 };
186
187 setElementRect(this.bgcanvas_, this.canvasRect_);
188 setElementRect(this.fgcanvas_, this.canvasRect_);
189 };
190
191 /**
192 * @private
193 * Creates the background and foreground canvases.
194 */
195 rangeSelector.prototype.createCanvases_ = function() {
196 this.bgcanvas_ = Dygraph.createCanvas();
197 this.bgcanvas_.className = 'dygraph-rangesel-bgcanvas';
198 this.bgcanvas_.style.position = 'absolute';
199 this.bgcanvas_.style.zIndex = 9;
200 this.bgcanvas_ctx_ = Dygraph.getContext(this.bgcanvas_);
201
202 this.fgcanvas_ = Dygraph.createCanvas();
203 this.fgcanvas_.className = 'dygraph-rangesel-fgcanvas';
204 this.fgcanvas_.style.position = 'absolute';
205 this.fgcanvas_.style.zIndex = 9;
206 this.fgcanvas_.style.cursor = 'default';
207 this.fgcanvas_ctx_ = Dygraph.getContext(this.fgcanvas_);
208 };
209
210 /**
211 * @private
212 * Creates overlay divs for IE/Excanvas so that mouse events are handled properly.
213 */
214 rangeSelector.prototype.createIEPanOverlay_ = function() {
215 this.iePanOverlay_ = document.createElement("div");
216 this.iePanOverlay_.style.position = 'absolute';
217 this.iePanOverlay_.style.backgroundColor = 'white';
218 this.iePanOverlay_.style.filter = 'alpha(opacity=0)';
219 this.iePanOverlay_.style.display = 'none';
220 this.iePanOverlay_.style.cursor = 'move';
221 this.fgcanvas_.appendChild(this.iePanOverlay_);
222 };
223
224 /**
225 * @private
226 * Creates the zoom handle elements.
227 */
228 rangeSelector.prototype.createZoomHandles_ = function() {
229 var img = new Image();
230 img.className = 'dygraph-rangesel-zoomhandle';
231 img.style.position = 'absolute';
232 img.style.zIndex = 10;
233 img.style.visibility = 'hidden'; // Initially hidden so they don't show up in the wrong place.
234 img.style.cursor = 'col-resize';
235
236 if (/MSIE 7/.test(navigator.userAgent)) { // IE7 doesn't support embedded src data.
237 img.width = 7;
238 img.height = 14;
239 img.style.backgroundColor = 'white';
240 img.style.border = '1px solid #333333'; // Just show box in IE7.
241 } else {
242 img.width = 9;
243 img.height = 16;
244 img.src = 'data:image/png;base64,' +
245 'iVBORw0KGgoAAAANSUhEUgAAAAkAAAAQCAYAAADESFVDAAAAAXNSR0IArs4c6QAAAAZiS0dEANAA' +
246 'zwDP4Z7KegAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAAd0SU1FB9sHGw0cMqdt1UwAAAAZdEVYdENv' +
247 'bW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAaElEQVQoz+3SsRFAQBCF4Z9WJM8KCDVwownl' +
248 '6YXsTmCUsyKGkZzcl7zkz3YLkypgAnreFmDEpHkIwVOMfpdi9CEEN2nGpFdwD03yEqDtOgCaun7s' +
249 'qSTDH32I1pQA2Pb9sZecAxc5r3IAb21d6878xsAAAAAASUVORK5CYII=';
250 }
251
252 if (this.isMobileDevice_) {
253 img.width *= 2;
254 img.height *= 2;
255 }
256
257 this.leftZoomHandle_ = img;
258 this.rightZoomHandle_ = img.cloneNode(false);
259 };
260
261 /**
262 * @private
263 * Sets up the interaction for the range selector.
264 */
265 rangeSelector.prototype.initInteraction_ = function() {
266 var self = this;
267 var topElem = this.isIE_ ? document : window;
268 var pageXLast = 0;
269 var handle = null;
270 var isZooming = false;
271 var isPanning = false;
272 var dynamic = !this.isMobileDevice_ && !this.isUsingExcanvas_;
273
274 // We cover iframes during mouse interactions. See comments in
275 // dygraph-utils.js for more info on why this is a good idea.
276 var tarp = new Dygraph.IFrameTarp();
277
278 // functions, defined below. Defining them this way (rather than with
279 // "function foo() {...}" makes JSHint happy.
280 var toXDataWindow, onZoomStart, onZoom, onZoomEnd, doZoom, isMouseInPanZone,
281 onPanStart, onPan, onPanEnd, doPan, onCanvasHover, getCursorPageX;
282
283 // Touch event functions
284 var onZoomHandleTouchEvent, onCanvasTouchEvent, addTouchEvents;
285
286 toXDataWindow = function(zoomHandleStatus) {
287 var xDataLimits = self.dygraph_.xAxisExtremes();
288 var fact = (xDataLimits[1] - xDataLimits[0])/self.canvasRect_.w;
289 var xDataMin = xDataLimits[0] + (zoomHandleStatus.leftHandlePos - self.canvasRect_.x)*fact;
290 var xDataMax = xDataLimits[0] + (zoomHandleStatus.rightHandlePos - self.canvasRect_.x)*fact;
291 return [xDataMin, xDataMax];
292 };
293
294 getCursorPageX = function(e) {
295 if (e.pageX !== null) {
296 return e.pageX;
297 } else {
298 // Taken from jQuery.
299 var target = e.target || e.srcElement || document;
300 var eventDoc = target.ownerDocument || target.document || document;
301 var doc = eventDoc.documentElement, body = eventDoc.body;
302 return e.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
303 }
304 };
305
306 onZoomStart = function(e) {
307 Dygraph.cancelEvent(e);
308 isZooming = true;
309 pageXLast = getCursorPageX(e);
310 handle = e.target ? e.target : e.srcElement;
311 if (e.type === 'mousedown' || e.type === 'dragstart') {
312 Dygraph.addEvent(topElem, 'mousemove', onZoom);
313 Dygraph.addEvent(topElem, 'mouseup', onZoomEnd);
314 }
315 self.fgcanvas_.style.cursor = 'col-resize';
316 tarp.cover();
317 return true;
318 };
319
320 onZoom = function(e) {
321 if (!isZooming) {
322 return false;
323 }
324 Dygraph.cancelEvent(e);
325
326 var pageX = getCursorPageX(e);
327 var delX = pageX - pageXLast;
328 if (Math.abs(delX) < 4) {
329 return true;
330 }
331 pageXLast = pageX;
332
333 // Move handle.
334 var zoomHandleStatus = self.getZoomHandleStatus_();
335 var newPos;
336 if (handle == self.leftZoomHandle_) {
337 newPos = pageX;
338 newPos = Math.min(newPos, zoomHandleStatus.rightHandlePos - handle.width - 3);
339 newPos = Math.max(newPos, self.canvasRect_.x);
340 } else {
341 newPos = pageX;
342 newPos = Math.min(newPos, self.canvasRect_.x + self.canvasRect_.w);
343 newPos = Math.max(newPos, zoomHandleStatus.leftHandlePos + handle.width + 3);
344 }
345 var halfHandleWidth = handle.width/2;
346 handle.style.left = (newPos - halfHandleWidth) + 'px';
347 self.drawInteractiveLayer_();
348
349 // Zoom on the fly (if not using excanvas).
350 if (dynamic) {
351 doZoom();
352 }
353 return true;
354 };
355
356 onZoomEnd = function(e) {
357 if (!isZooming) {
358 return false;
359 }
360 isZooming = false;
361 tarp.uncover();
362 Dygraph.removeEvent(topElem, 'mousemove', onZoom);
363 Dygraph.removeEvent(topElem, 'mouseup', onZoomEnd);
364 self.fgcanvas_.style.cursor = 'default';
365
366 // If using excanvas, Zoom now.
367 if (!dynamic) {
368 doZoom();
369 }
370 return true;
371 };
372
373 doZoom = function() {
374 try {
375 var zoomHandleStatus = self.getZoomHandleStatus_();
376 self.isChangingRange_ = true;
377 if (!zoomHandleStatus.isZoomed) {
378 self.dygraph_.resetZoom();
379 } else {
380 var xDataWindow = toXDataWindow(zoomHandleStatus);
381 self.dygraph_.doZoomXDates_(xDataWindow[0], xDataWindow[1]);
382 }
383 } finally {
384 self.isChangingRange_ = false;
385 }
386 };
387
388 isMouseInPanZone = function(e) {
389 if (self.isUsingExcanvas_) {
390 return e.srcElement == self.iePanOverlay_;
391 } else {
392 var rect = self.leftZoomHandle_.getBoundingClientRect();
393 var leftHandleClientX = rect.left + rect.width/2;
394 rect = self.rightZoomHandle_.getBoundingClientRect();
395 var rightHandleClientX = rect.left + rect.width/2;
396 return (e.clientX > leftHandleClientX && e.clientX < rightHandleClientX);
397 }
398 };
399
400 onPanStart = function(e) {
401 if (!isPanning && isMouseInPanZone(e) && self.getZoomHandleStatus_().isZoomed) {
402 Dygraph.cancelEvent(e);
403 isPanning = true;
404 pageXLast = getCursorPageX(e);
405 if (e.type === 'mousedown') {
406 Dygraph.addEvent(topElem, 'mousemove', onPan);
407 Dygraph.addEvent(topElem, 'mouseup', onPanEnd);
408 }
409 return true;
410 }
411 return false;
412 };
413
414 onPan = function(e) {
415 if (!isPanning) {
416 return false;
417 }
418 Dygraph.cancelEvent(e);
419
420 var pageX = getCursorPageX(e);
421 var delX = pageX - pageXLast;
422 if (Math.abs(delX) < 4) {
423 return true;
424 }
425 pageXLast = pageX;
426
427 // Move range view
428 var zoomHandleStatus = self.getZoomHandleStatus_();
429 var leftHandlePos = zoomHandleStatus.leftHandlePos;
430 var rightHandlePos = zoomHandleStatus.rightHandlePos;
431 var rangeSize = rightHandlePos - leftHandlePos;
432 if (leftHandlePos + delX <= self.canvasRect_.x) {
433 leftHandlePos = self.canvasRect_.x;
434 rightHandlePos = leftHandlePos + rangeSize;
435 } else if (rightHandlePos + delX >= self.canvasRect_.x + self.canvasRect_.w) {
436 rightHandlePos = self.canvasRect_.x + self.canvasRect_.w;
437 leftHandlePos = rightHandlePos - rangeSize;
438 } else {
439 leftHandlePos += delX;
440 rightHandlePos += delX;
441 }
442 var halfHandleWidth = self.leftZoomHandle_.width/2;
443 self.leftZoomHandle_.style.left = (leftHandlePos - halfHandleWidth) + 'px';
444 self.rightZoomHandle_.style.left = (rightHandlePos - halfHandleWidth) + 'px';
445 self.drawInteractiveLayer_();
446
447 // Do pan on the fly (if not using excanvas).
448 if (dynamic) {
449 doPan();
450 }
451 return true;
452 };
453
454 onPanEnd = function(e) {
455 if (!isPanning) {
456 return false;
457 }
458 isPanning = false;
459 Dygraph.removeEvent(topElem, 'mousemove', onPan);
460 Dygraph.removeEvent(topElem, 'mouseup', onPanEnd);
461 // If using excanvas, do pan now.
462 if (!dynamic) {
463 doPan();
464 }
465 return true;
466 };
467
468 doPan = function() {
469 try {
470 self.isChangingRange_ = true;
471 self.dygraph_.dateWindow_ = toXDataWindow(self.getZoomHandleStatus_());
472 self.dygraph_.drawGraph_(false);
473 } finally {
474 self.isChangingRange_ = false;
475 }
476 };
477
478 onCanvasHover = function(e) {
479 if (isZooming || isPanning) {
480 return;
481 }
482 var cursor = isMouseInPanZone(e) ? 'move' : 'default';
483 if (cursor != self.fgcanvas_.style.cursor) {
484 self.fgcanvas_.style.cursor = cursor;
485 }
486 };
487
488 onZoomHandleTouchEvent = function(e) {
489 if (e.type == 'touchstart' && e.targetTouches.length == 1) {
490 if (onZoomStart(e.targetTouches[0])) {
491 Dygraph.cancelEvent(e);
492 }
493 } else if (e.type == 'touchmove' && e.targetTouches.length == 1) {
494 if (onZoom(e.targetTouches[0])) {
495 Dygraph.cancelEvent(e);
496 }
497 } else {
498 onZoomEnd(e);
499 }
500 };
501
502 onCanvasTouchEvent = function(e) {
503 if (e.type == 'touchstart' && e.targetTouches.length == 1) {
504 if (onPanStart(e.targetTouches[0])) {
505 Dygraph.cancelEvent(e);
506 }
507 } else if (e.type == 'touchmove' && e.targetTouches.length == 1) {
508 if (onPan(e.targetTouches[0])) {
509 Dygraph.cancelEvent(e);
510 }
511 } else {
512 onPanEnd(e);
513 }
514 };
515
516 addTouchEvents = function(elem, fn) {
517 var types = ['touchstart', 'touchend', 'touchmove', 'touchcancel'];
518 for (var i = 0; i < types.length; i++) {
519 Dygraph.addEvent(elem, types[i], fn);
520 }
521 };
522
523 this.setDefaultOption_('interactionModel', Dygraph.Interaction.dragIsPanInteractionModel);
524 this.setDefaultOption_('panEdgeFraction', 0.0001);
525
526 var dragStartEvent = window.opera ? 'mousedown' : 'dragstart';
527 Dygraph.addEvent(this.leftZoomHandle_, dragStartEvent, onZoomStart);
528 Dygraph.addEvent(this.rightZoomHandle_, dragStartEvent, onZoomStart);
529
530 if (this.isUsingExcanvas_) {
531 Dygraph.addEvent(this.iePanOverlay_, 'mousedown', onPanStart);
532 } else {
533 Dygraph.addEvent(this.fgcanvas_, 'mousedown', onPanStart);
534 Dygraph.addEvent(this.fgcanvas_, 'mousemove', onCanvasHover);
535 }
536
537 // Touch events
538 if (this.hasTouchInterface_) {
539 addTouchEvents(this.leftZoomHandle_, onZoomHandleTouchEvent);
540 addTouchEvents(this.rightZoomHandle_, onZoomHandleTouchEvent);
541 addTouchEvents(this.fgcanvas_, onCanvasTouchEvent);
542 }
543 };
544
545 /**
546 * @private
547 * Draws the static layer in the background canvas.
548 */
549 rangeSelector.prototype.drawStaticLayer_ = function() {
550 var ctx = this.bgcanvas_ctx_;
551 ctx.clearRect(0, 0, this.canvasRect_.w, this.canvasRect_.h);
552 try {
553 this.drawMiniPlot_();
554 } catch(ex) {
555 Dygraph.warn(ex);
556 }
557
558 var margin = 0.5;
559 this.bgcanvas_ctx_.lineWidth = 1;
560 ctx.strokeStyle = 'gray';
561 ctx.beginPath();
562 ctx.moveTo(margin, margin);
563 ctx.lineTo(margin, this.canvasRect_.h-margin);
564 ctx.lineTo(this.canvasRect_.w-margin, this.canvasRect_.h-margin);
565 ctx.lineTo(this.canvasRect_.w-margin, margin);
566 ctx.stroke();
567 };
568
569
570 /**
571 * @private
572 * Draws the mini plot in the background canvas.
573 */
574 rangeSelector.prototype.drawMiniPlot_ = function() {
575 var fillStyle = this.getOption_('rangeSelectorPlotFillColor');
576 var strokeStyle = this.getOption_('rangeSelectorPlotStrokeColor');
577 if (!fillStyle && !strokeStyle) {
578 return;
579 }
580
581 var stepPlot = this.getOption_('stepPlot');
582
583 var combinedSeriesData = this.computeCombinedSeriesAndLimits_();
584 var yRange = combinedSeriesData.yMax - combinedSeriesData.yMin;
585
586 // Draw the mini plot.
587 var ctx = this.bgcanvas_ctx_;
588 var margin = 0.5;
589
590 var xExtremes = this.dygraph_.xAxisExtremes();
591 var xRange = Math.max(xExtremes[1] - xExtremes[0], 1.e-30);
592 var xFact = (this.canvasRect_.w - margin)/xRange;
593 var yFact = (this.canvasRect_.h - margin)/yRange;
594 var canvasWidth = this.canvasRect_.w - margin;
595 var canvasHeight = this.canvasRect_.h - margin;
596
597 var prevX = null, prevY = null;
598
599 ctx.beginPath();
600 ctx.moveTo(margin, canvasHeight);
601 for (var i = 0; i < combinedSeriesData.data.length; i++) {
602 var dataPoint = combinedSeriesData.data[i];
603 var x = ((dataPoint[0] !== null) ? ((dataPoint[0] - xExtremes[0])*xFact) : NaN);
604 var y = ((dataPoint[1] !== null) ? (canvasHeight - (dataPoint[1] - combinedSeriesData.yMin)*yFact) : NaN);
605 if (isFinite(x) && isFinite(y)) {
606 if(prevX === null) {
607 ctx.lineTo(x, canvasHeight);
608 }
609 else if (stepPlot) {
610 ctx.lineTo(x, prevY);
611 }
612 ctx.lineTo(x, y);
613 prevX = x;
614 prevY = y;
615 }
616 else {
617 if(prevX !== null) {
618 if (stepPlot) {
619 ctx.lineTo(x, prevY);
620 ctx.lineTo(x, canvasHeight);
621 }
622 else {
623 ctx.lineTo(prevX, canvasHeight);
624 }
625 }
626 prevX = prevY = null;
627 }
628 }
629 ctx.lineTo(canvasWidth, canvasHeight);
630 ctx.closePath();
631
632 if (fillStyle) {
633 var lingrad = this.bgcanvas_ctx_.createLinearGradient(0, 0, 0, canvasHeight);
634 lingrad.addColorStop(0, 'white');
635 lingrad.addColorStop(1, fillStyle);
636 this.bgcanvas_ctx_.fillStyle = lingrad;
637 ctx.fill();
638 }
639
640 if (strokeStyle) {
641 this.bgcanvas_ctx_.strokeStyle = strokeStyle;
642 this.bgcanvas_ctx_.lineWidth = 1.5;
643 ctx.stroke();
644 }
645 };
646
647 /**
648 * @private
649 * Computes and returns the combinded series data along with min/max for the mini plot.
650 * @return {Object} An object containing combinded series array, ymin, ymax.
651 */
652 rangeSelector.prototype.computeCombinedSeriesAndLimits_ = function() {
653 var data = this.dygraph_.rawData_;
654 var logscale = this.getOption_('logscale');
655
656 // Create a combined series (average of all series values).
657 var combinedSeries = [];
658 var sum;
659 var count;
660 var mutipleValues;
661 var i, j, k;
662 var xVal, yVal;
663
664 // Find out if data has multiple values per datapoint.
665 // Go to first data point that actually has values (see http://code.google.com/p/dygraphs/issues/detail?id=246)
666 for (i = 0; i < data.length; i++) {
667 if (data[i].length > 1 && data[i][1] !== null) {
668 mutipleValues = typeof data[i][1] != 'number';
669 if (mutipleValues) {
670 sum = [];
671 count = [];
672 for (k = 0; k < data[i][1].length; k++) {
673 sum.push(0);
674 count.push(0);
675 }
676 }
677 break;
678 }
679 }
680
681 for (i = 0; i < data.length; i++) {
682 var dataPoint = data[i];
683 xVal = dataPoint[0];
684
685 if (mutipleValues) {
686 for (k = 0; k < sum.length; k++) {
687 sum[k] = count[k] = 0;
688 }
689 } else {
690 sum = count = 0;
691 }
692
693 for (j = 1; j < dataPoint.length; j++) {
694 if (this.dygraph_.visibility()[j-1]) {
695 var y;
696 if (mutipleValues) {
697 for (k = 0; k < sum.length; k++) {
698 y = dataPoint[j][k];
699 if (y === null || isNaN(y)) continue;
700 sum[k] += y;
701 count[k]++;
702 }
703 } else {
704 y = dataPoint[j];
705 if (y === null || isNaN(y)) continue;
706 sum += y;
707 count++;
708 }
709 }
710 }
711
712 if (mutipleValues) {
713 for (k = 0; k < sum.length; k++) {
714 sum[k] /= count[k];
715 }
716 yVal = sum.slice(0);
717 } else {
718 yVal = sum/count;
719 }
720
721 combinedSeries.push([xVal, yVal]);
722 }
723
724 // Account for roll period, fractions.
725 combinedSeries = this.dygraph_.rollingAverage(combinedSeries, this.dygraph_.rollPeriod_);
726
727 if (typeof combinedSeries[0][1] != 'number') {
728 for (i = 0; i < combinedSeries.length; i++) {
729 yVal = combinedSeries[i][1];
730 combinedSeries[i][1] = yVal[0];
731 }
732 }
733
734 // Compute the y range.
735 var yMin = Number.MAX_VALUE;
736 var yMax = -Number.MAX_VALUE;
737 for (i = 0; i < combinedSeries.length; i++) {
738 yVal = combinedSeries[i][1];
739 if (yVal !== null && isFinite(yVal) && (!logscale || yVal > 0)) {
740 yMin = Math.min(yMin, yVal);
741 yMax = Math.max(yMax, yVal);
742 }
743 }
744
745 // Convert Y data to log scale if needed.
746 // Also, expand the Y range to compress the mini plot a little.
747 var extraPercent = 0.25;
748 if (logscale) {
749 yMax = Dygraph.log10(yMax);
750 yMax += yMax*extraPercent;
751 yMin = Dygraph.log10(yMin);
752 for (i = 0; i < combinedSeries.length; i++) {
753 combinedSeries[i][1] = Dygraph.log10(combinedSeries[i][1]);
754 }
755 } else {
756 var yExtra;
757 var yRange = yMax - yMin;
758 if (yRange <= Number.MIN_VALUE) {
759 yExtra = yMax*extraPercent;
760 } else {
761 yExtra = yRange*extraPercent;
762 }
763 yMax += yExtra;
764 yMin -= yExtra;
765 }
766
767 return {data: combinedSeries, yMin: yMin, yMax: yMax};
768 };
769
770 /**
771 * @private
772 * Places the zoom handles in the proper position based on the current X data window.
773 */
774 rangeSelector.prototype.placeZoomHandles_ = function() {
775 var xExtremes = this.dygraph_.xAxisExtremes();
776 var xWindowLimits = this.dygraph_.xAxisRange();
777 var xRange = xExtremes[1] - xExtremes[0];
778 var leftPercent = Math.max(0, (xWindowLimits[0] - xExtremes[0])/xRange);
779 var rightPercent = Math.max(0, (xExtremes[1] - xWindowLimits[1])/xRange);
780 var leftCoord = this.canvasRect_.x + this.canvasRect_.w*leftPercent;
781 var rightCoord = this.canvasRect_.x + this.canvasRect_.w*(1 - rightPercent);
782 var handleTop = Math.max(this.canvasRect_.y, this.canvasRect_.y + (this.canvasRect_.h - this.leftZoomHandle_.height)/2);
783 var halfHandleWidth = this.leftZoomHandle_.width/2;
784 this.leftZoomHandle_.style.left = (leftCoord - halfHandleWidth) + 'px';
785 this.leftZoomHandle_.style.top = handleTop + 'px';
786 this.rightZoomHandle_.style.left = (rightCoord - halfHandleWidth) + 'px';
787 this.rightZoomHandle_.style.top = this.leftZoomHandle_.style.top;
788
789 this.leftZoomHandle_.style.visibility = 'visible';
790 this.rightZoomHandle_.style.visibility = 'visible';
791 };
792
793 /**
794 * @private
795 * Draws the interactive layer in the foreground canvas.
796 */
797 rangeSelector.prototype.drawInteractiveLayer_ = function() {
798 var ctx = this.fgcanvas_ctx_;
799 ctx.clearRect(0, 0, this.canvasRect_.w, this.canvasRect_.h);
800 var margin = 1;
801 var width = this.canvasRect_.w - margin;
802 var height = this.canvasRect_.h - margin;
803 var zoomHandleStatus = this.getZoomHandleStatus_();
804
805 ctx.strokeStyle = 'black';
806 if (!zoomHandleStatus.isZoomed) {
807 ctx.beginPath();
808 ctx.moveTo(margin, margin);
809 ctx.lineTo(margin, height);
810 ctx.lineTo(width, height);
811 ctx.lineTo(width, margin);
812 ctx.stroke();
813 if (this.iePanOverlay_) {
814 this.iePanOverlay_.style.display = 'none';
815 }
816 } else {
817 var leftHandleCanvasPos = Math.max(margin, zoomHandleStatus.leftHandlePos - this.canvasRect_.x);
818 var rightHandleCanvasPos = Math.min(width, zoomHandleStatus.rightHandlePos - this.canvasRect_.x);
819
820 ctx.fillStyle = 'rgba(240, 240, 240, 0.6)';
821 ctx.fillRect(0, 0, leftHandleCanvasPos, this.canvasRect_.h);
822 ctx.fillRect(rightHandleCanvasPos, 0, this.canvasRect_.w - rightHandleCanvasPos, this.canvasRect_.h);
823
824 ctx.beginPath();
825 ctx.moveTo(margin, margin);
826 ctx.lineTo(leftHandleCanvasPos, margin);
827 ctx.lineTo(leftHandleCanvasPos, height);
828 ctx.lineTo(rightHandleCanvasPos, height);
829 ctx.lineTo(rightHandleCanvasPos, margin);
830 ctx.lineTo(width, margin);
831 ctx.stroke();
832
833 if (this.isUsingExcanvas_) {
834 this.iePanOverlay_.style.width = (rightHandleCanvasPos - leftHandleCanvasPos) + 'px';
835 this.iePanOverlay_.style.left = leftHandleCanvasPos + 'px';
836 this.iePanOverlay_.style.height = height + 'px';
837 this.iePanOverlay_.style.display = 'inline';
838 }
839 }
840 };
841
842 /**
843 * @private
844 * Returns the current zoom handle position information.
845 * @return {Object} The zoom handle status.
846 */
847 rangeSelector.prototype.getZoomHandleStatus_ = function() {
848 var halfHandleWidth = this.leftZoomHandle_.width/2;
849 var leftHandlePos = parseFloat(this.leftZoomHandle_.style.left) + halfHandleWidth;
850 var rightHandlePos = parseFloat(this.rightZoomHandle_.style.left) + halfHandleWidth;
851 return {
852 leftHandlePos: leftHandlePos,
853 rightHandlePos: rightHandlePos,
854 isZoomed: (leftHandlePos - 1 > this.canvasRect_.x || rightHandlePos + 1 < this.canvasRect_.x+this.canvasRect_.w)
855 };
856 };
857
858 return rangeSelector;
859
860 })();