Fix retina support on desktop browsers; add retina range selector
[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, opt_series) {
56 return this.dygraph_.getOption(name, opt_series);
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 console.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, context, rect) {
170 var canvasScale = Dygraph.getContextPixelRatio(context);
171
172 canvas.style.top = rect.y + 'px';
173 canvas.style.left = rect.x + 'px';
174 canvas.width = rect.w * canvasScale;
175 canvas.height = rect.h * canvasScale;
176 canvas.style.width = rect.w + 'px';
177 canvas.style.height = rect.h + 'px';
178
179 if(canvasScale != 1) {
180 context.scale(canvasScale, canvasScale);
181 }
182 }
183
184 var plotArea = this.dygraph_.layout_.getPlotArea();
185
186 var xAxisLabelHeight = 0;
187 if (this.dygraph_.getOptionForAxis('drawAxis', 'x')) {
188 xAxisLabelHeight = this.getOption_('xAxisHeight') || (this.getOption_('axisLabelFontSize') + 2 * this.getOption_('axisTickSize'));
189 }
190 this.canvasRect_ = {
191 x: plotArea.x,
192 y: plotArea.y + plotArea.h + xAxisLabelHeight + 4,
193 w: plotArea.w,
194 h: this.getOption_('rangeSelectorHeight')
195 };
196
197 setElementRect(this.bgcanvas_, this.bgcanvas_ctx_, this.canvasRect_);
198 setElementRect(this.fgcanvas_, this.fgcanvas_ctx_, this.canvasRect_);
199 };
200
201 /**
202 * @private
203 * Creates the background and foreground canvases.
204 */
205 rangeSelector.prototype.createCanvases_ = function() {
206 this.bgcanvas_ = Dygraph.createCanvas();
207 this.bgcanvas_.className = 'dygraph-rangesel-bgcanvas';
208 this.bgcanvas_.style.position = 'absolute';
209 this.bgcanvas_.style.zIndex = 9;
210 this.bgcanvas_ctx_ = Dygraph.getContext(this.bgcanvas_);
211
212 this.fgcanvas_ = Dygraph.createCanvas();
213 this.fgcanvas_.className = 'dygraph-rangesel-fgcanvas';
214 this.fgcanvas_.style.position = 'absolute';
215 this.fgcanvas_.style.zIndex = 9;
216 this.fgcanvas_.style.cursor = 'default';
217 this.fgcanvas_ctx_ = Dygraph.getContext(this.fgcanvas_);
218 };
219
220 /**
221 * @private
222 * Creates overlay divs for IE/Excanvas so that mouse events are handled properly.
223 */
224 rangeSelector.prototype.createIEPanOverlay_ = function() {
225 this.iePanOverlay_ = document.createElement("div");
226 this.iePanOverlay_.style.position = 'absolute';
227 this.iePanOverlay_.style.backgroundColor = 'white';
228 this.iePanOverlay_.style.filter = 'alpha(opacity=0)';
229 this.iePanOverlay_.style.display = 'none';
230 this.iePanOverlay_.style.cursor = 'move';
231 this.fgcanvas_.appendChild(this.iePanOverlay_);
232 };
233
234 /**
235 * @private
236 * Creates the zoom handle elements.
237 */
238 rangeSelector.prototype.createZoomHandles_ = function() {
239 var img = new Image();
240 img.className = 'dygraph-rangesel-zoomhandle';
241 img.style.position = 'absolute';
242 img.style.zIndex = 10;
243 img.style.visibility = 'hidden'; // Initially hidden so they don't show up in the wrong place.
244 img.style.cursor = 'col-resize';
245
246 if (/MSIE 7/.test(navigator.userAgent)) { // IE7 doesn't support embedded src data.
247 img.width = 7;
248 img.height = 14;
249 img.style.backgroundColor = 'white';
250 img.style.border = '1px solid #333333'; // Just show box in IE7.
251 } else {
252 img.width = 9;
253 img.height = 16;
254 img.src = 'data:image/png;base64,' +
255 'iVBORw0KGgoAAAANSUhEUgAAAAkAAAAQCAYAAADESFVDAAAAAXNSR0IArs4c6QAAAAZiS0dEANAA' +
256 'zwDP4Z7KegAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAAd0SU1FB9sHGw0cMqdt1UwAAAAZdEVYdENv' +
257 'bW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAaElEQVQoz+3SsRFAQBCF4Z9WJM8KCDVwownl' +
258 '6YXsTmCUsyKGkZzcl7zkz3YLkypgAnreFmDEpHkIwVOMfpdi9CEEN2nGpFdwD03yEqDtOgCaun7s' +
259 'qSTDH32I1pQA2Pb9sZecAxc5r3IAb21d6878xsAAAAAASUVORK5CYII=';
260 }
261
262 if (this.isMobileDevice_) {
263 img.width *= 2;
264 img.height *= 2;
265 }
266
267 this.leftZoomHandle_ = img;
268 this.rightZoomHandle_ = img.cloneNode(false);
269 };
270
271 /**
272 * @private
273 * Sets up the interaction for the range selector.
274 */
275 rangeSelector.prototype.initInteraction_ = function() {
276 var self = this;
277 var topElem = document;
278 var clientXLast = 0;
279 var handle = null;
280 var isZooming = false;
281 var isPanning = false;
282 var dynamic = !this.isMobileDevice_ && !this.isUsingExcanvas_;
283
284 // We cover iframes during mouse interactions. See comments in
285 // dygraph-utils.js for more info on why this is a good idea.
286 var tarp = new Dygraph.IFrameTarp();
287
288 // functions, defined below. Defining them this way (rather than with
289 // "function foo() {...}" makes JSHint happy.
290 var toXDataWindow, onZoomStart, onZoom, onZoomEnd, doZoom, isMouseInPanZone,
291 onPanStart, onPan, onPanEnd, doPan, onCanvasHover;
292
293 // Touch event functions
294 var onZoomHandleTouchEvent, onCanvasTouchEvent, addTouchEvents;
295
296 toXDataWindow = function(zoomHandleStatus) {
297 var xDataLimits = self.dygraph_.xAxisExtremes();
298 var fact = (xDataLimits[1] - xDataLimits[0])/self.canvasRect_.w;
299 var xDataMin = xDataLimits[0] + (zoomHandleStatus.leftHandlePos - self.canvasRect_.x)*fact;
300 var xDataMax = xDataLimits[0] + (zoomHandleStatus.rightHandlePos - self.canvasRect_.x)*fact;
301 return [xDataMin, xDataMax];
302 };
303
304 onZoomStart = function(e) {
305 Dygraph.cancelEvent(e);
306 isZooming = true;
307 clientXLast = e.clientX;
308 handle = e.target ? e.target : e.srcElement;
309 if (e.type === 'mousedown' || e.type === 'dragstart') {
310 // These events are removed manually.
311 Dygraph.addEvent(topElem, 'mousemove', onZoom);
312 Dygraph.addEvent(topElem, 'mouseup', onZoomEnd);
313 }
314 self.fgcanvas_.style.cursor = 'col-resize';
315 tarp.cover();
316 return true;
317 };
318
319 onZoom = function(e) {
320 if (!isZooming) {
321 return false;
322 }
323 Dygraph.cancelEvent(e);
324
325 var delX = e.clientX - clientXLast;
326 if (Math.abs(delX) < 4) {
327 return true;
328 }
329 clientXLast = e.clientX;
330
331 // Move handle.
332 var zoomHandleStatus = self.getZoomHandleStatus_();
333 var newPos;
334 if (handle == self.leftZoomHandle_) {
335 newPos = zoomHandleStatus.leftHandlePos + delX;
336 newPos = Math.min(newPos, zoomHandleStatus.rightHandlePos - handle.width - 3);
337 newPos = Math.max(newPos, self.canvasRect_.x);
338 } else {
339 newPos = zoomHandleStatus.rightHandlePos + delX;
340 newPos = Math.min(newPos, self.canvasRect_.x + self.canvasRect_.w);
341 newPos = Math.max(newPos, zoomHandleStatus.leftHandlePos + handle.width + 3);
342 }
343 var halfHandleWidth = handle.width/2;
344 handle.style.left = (newPos - halfHandleWidth) + 'px';
345 self.drawInteractiveLayer_();
346
347 // Zoom on the fly (if not using excanvas).
348 if (dynamic) {
349 doZoom();
350 }
351 return true;
352 };
353
354 onZoomEnd = function(e) {
355 if (!isZooming) {
356 return false;
357 }
358 isZooming = false;
359 tarp.uncover();
360 Dygraph.removeEvent(topElem, 'mousemove', onZoom);
361 Dygraph.removeEvent(topElem, 'mouseup', onZoomEnd);
362 self.fgcanvas_.style.cursor = 'default';
363
364 // If using excanvas, Zoom now.
365 if (!dynamic) {
366 doZoom();
367 }
368 return true;
369 };
370
371 doZoom = function() {
372 try {
373 var zoomHandleStatus = self.getZoomHandleStatus_();
374 self.isChangingRange_ = true;
375 if (!zoomHandleStatus.isZoomed) {
376 self.dygraph_.resetZoom();
377 } else {
378 var xDataWindow = toXDataWindow(zoomHandleStatus);
379 self.dygraph_.doZoomXDates_(xDataWindow[0], xDataWindow[1]);
380 }
381 } finally {
382 self.isChangingRange_ = false;
383 }
384 };
385
386 isMouseInPanZone = function(e) {
387 if (self.isUsingExcanvas_) {
388 return e.srcElement == self.iePanOverlay_;
389 } else {
390 var rect = self.leftZoomHandle_.getBoundingClientRect();
391 var leftHandleClientX = rect.left + rect.width/2;
392 rect = self.rightZoomHandle_.getBoundingClientRect();
393 var rightHandleClientX = rect.left + rect.width/2;
394 return (e.clientX > leftHandleClientX && e.clientX < rightHandleClientX);
395 }
396 };
397
398 onPanStart = function(e) {
399 if (!isPanning && isMouseInPanZone(e) && self.getZoomHandleStatus_().isZoomed) {
400 Dygraph.cancelEvent(e);
401 isPanning = true;
402 clientXLast = e.clientX;
403 if (e.type === 'mousedown') {
404 // These events are removed manually.
405 Dygraph.addEvent(topElem, 'mousemove', onPan);
406 Dygraph.addEvent(topElem, 'mouseup', onPanEnd);
407 }
408 return true;
409 }
410 return false;
411 };
412
413 onPan = function(e) {
414 if (!isPanning) {
415 return false;
416 }
417 Dygraph.cancelEvent(e);
418
419 var delX = e.clientX - clientXLast;
420 if (Math.abs(delX) < 4) {
421 return true;
422 }
423 clientXLast = e.clientX;
424
425 // Move range view
426 var zoomHandleStatus = self.getZoomHandleStatus_();
427 var leftHandlePos = zoomHandleStatus.leftHandlePos;
428 var rightHandlePos = zoomHandleStatus.rightHandlePos;
429 var rangeSize = rightHandlePos - leftHandlePos;
430 if (leftHandlePos + delX <= self.canvasRect_.x) {
431 leftHandlePos = self.canvasRect_.x;
432 rightHandlePos = leftHandlePos + rangeSize;
433 } else if (rightHandlePos + delX >= self.canvasRect_.x + self.canvasRect_.w) {
434 rightHandlePos = self.canvasRect_.x + self.canvasRect_.w;
435 leftHandlePos = rightHandlePos - rangeSize;
436 } else {
437 leftHandlePos += delX;
438 rightHandlePos += delX;
439 }
440 var halfHandleWidth = self.leftZoomHandle_.width/2;
441 self.leftZoomHandle_.style.left = (leftHandlePos - halfHandleWidth) + 'px';
442 self.rightZoomHandle_.style.left = (rightHandlePos - halfHandleWidth) + 'px';
443 self.drawInteractiveLayer_();
444
445 // Do pan on the fly (if not using excanvas).
446 if (dynamic) {
447 doPan();
448 }
449 return true;
450 };
451
452 onPanEnd = function(e) {
453 if (!isPanning) {
454 return false;
455 }
456 isPanning = false;
457 Dygraph.removeEvent(topElem, 'mousemove', onPan);
458 Dygraph.removeEvent(topElem, 'mouseup', onPanEnd);
459 // If using excanvas, do pan now.
460 if (!dynamic) {
461 doPan();
462 }
463 return true;
464 };
465
466 doPan = function() {
467 try {
468 self.isChangingRange_ = true;
469 self.dygraph_.dateWindow_ = toXDataWindow(self.getZoomHandleStatus_());
470 self.dygraph_.drawGraph_(false);
471 } finally {
472 self.isChangingRange_ = false;
473 }
474 };
475
476 onCanvasHover = function(e) {
477 if (isZooming || isPanning) {
478 return;
479 }
480 var cursor = isMouseInPanZone(e) ? 'move' : 'default';
481 if (cursor != self.fgcanvas_.style.cursor) {
482 self.fgcanvas_.style.cursor = cursor;
483 }
484 };
485
486 onZoomHandleTouchEvent = function(e) {
487 if (e.type == 'touchstart' && e.targetTouches.length == 1) {
488 if (onZoomStart(e.targetTouches[0])) {
489 Dygraph.cancelEvent(e);
490 }
491 } else if (e.type == 'touchmove' && e.targetTouches.length == 1) {
492 if (onZoom(e.targetTouches[0])) {
493 Dygraph.cancelEvent(e);
494 }
495 } else {
496 onZoomEnd(e);
497 }
498 };
499
500 onCanvasTouchEvent = function(e) {
501 if (e.type == 'touchstart' && e.targetTouches.length == 1) {
502 if (onPanStart(e.targetTouches[0])) {
503 Dygraph.cancelEvent(e);
504 }
505 } else if (e.type == 'touchmove' && e.targetTouches.length == 1) {
506 if (onPan(e.targetTouches[0])) {
507 Dygraph.cancelEvent(e);
508 }
509 } else {
510 onPanEnd(e);
511 }
512 };
513
514 addTouchEvents = function(elem, fn) {
515 var types = ['touchstart', 'touchend', 'touchmove', 'touchcancel'];
516 for (var i = 0; i < types.length; i++) {
517 self.dygraph_.addAndTrackEvent(elem, types[i], fn);
518 }
519 };
520
521 this.setDefaultOption_('interactionModel', Dygraph.Interaction.dragIsPanInteractionModel);
522 this.setDefaultOption_('panEdgeFraction', 0.0001);
523
524 var dragStartEvent = window.opera ? 'mousedown' : 'dragstart';
525 this.dygraph_.addAndTrackEvent(this.leftZoomHandle_, dragStartEvent, onZoomStart);
526 this.dygraph_.addAndTrackEvent(this.rightZoomHandle_, dragStartEvent, onZoomStart);
527
528 if (this.isUsingExcanvas_) {
529 this.dygraph_.addAndTrackEvent(this.iePanOverlay_, 'mousedown', onPanStart);
530 } else {
531 this.dygraph_.addAndTrackEvent(this.fgcanvas_, 'mousedown', onPanStart);
532 this.dygraph_.addAndTrackEvent(this.fgcanvas_, 'mousemove', onCanvasHover);
533 }
534
535 // Touch events
536 if (this.hasTouchInterface_) {
537 addTouchEvents(this.leftZoomHandle_, onZoomHandleTouchEvent);
538 addTouchEvents(this.rightZoomHandle_, onZoomHandleTouchEvent);
539 addTouchEvents(this.fgcanvas_, onCanvasTouchEvent);
540 }
541 };
542
543 /**
544 * @private
545 * Draws the static layer in the background canvas.
546 */
547 rangeSelector.prototype.drawStaticLayer_ = function() {
548 var ctx = this.bgcanvas_ctx_;
549 ctx.clearRect(0, 0, this.canvasRect_.w, this.canvasRect_.h);
550 try {
551 this.drawMiniPlot_();
552 } catch(ex) {
553 console.warn(ex);
554 }
555
556 var margin = 0.5;
557 this.bgcanvas_ctx_.lineWidth = 1;
558 ctx.strokeStyle = 'gray';
559 ctx.beginPath();
560 ctx.moveTo(margin, margin);
561 ctx.lineTo(margin, this.canvasRect_.h-margin);
562 ctx.lineTo(this.canvasRect_.w-margin, this.canvasRect_.h-margin);
563 ctx.lineTo(this.canvasRect_.w-margin, margin);
564 ctx.stroke();
565 };
566
567
568 /**
569 * @private
570 * Draws the mini plot in the background canvas.
571 */
572 rangeSelector.prototype.drawMiniPlot_ = function() {
573 var fillStyle = this.getOption_('rangeSelectorPlotFillColor');
574 var strokeStyle = this.getOption_('rangeSelectorPlotStrokeColor');
575 if (!fillStyle && !strokeStyle) {
576 return;
577 }
578
579 var stepPlot = this.getOption_('stepPlot');
580
581 var combinedSeriesData = this.computeCombinedSeriesAndLimits_();
582 var yRange = combinedSeriesData.yMax - combinedSeriesData.yMin;
583
584 // Draw the mini plot.
585 var ctx = this.bgcanvas_ctx_;
586 var margin = 0.5;
587
588 var xExtremes = this.dygraph_.xAxisExtremes();
589 var xRange = Math.max(xExtremes[1] - xExtremes[0], 1.e-30);
590 var xFact = (this.canvasRect_.w - margin)/xRange;
591 var yFact = (this.canvasRect_.h - margin)/yRange;
592 var canvasWidth = this.canvasRect_.w - margin;
593 var canvasHeight = this.canvasRect_.h - margin;
594
595 var prevX = null, prevY = null;
596
597 ctx.beginPath();
598 ctx.moveTo(margin, canvasHeight);
599 for (var i = 0; i < combinedSeriesData.data.length; i++) {
600 var dataPoint = combinedSeriesData.data[i];
601 var x = ((dataPoint[0] !== null) ? ((dataPoint[0] - xExtremes[0])*xFact) : NaN);
602 var y = ((dataPoint[1] !== null) ? (canvasHeight - (dataPoint[1] - combinedSeriesData.yMin)*yFact) : NaN);
603
604 // Skip points that don't change the x-value. Overly fine-grained points
605 // can cause major slowdowns with the ctx.fill() call below.
606 if (!stepPlot && prevX !== null && Math.round(x) == Math.round(prevX)) {
607 continue;
608 }
609
610 if (isFinite(x) && isFinite(y)) {
611 if(prevX === null) {
612 ctx.lineTo(x, canvasHeight);
613 }
614 else if (stepPlot) {
615 ctx.lineTo(x, prevY);
616 }
617 ctx.lineTo(x, y);
618 prevX = x;
619 prevY = y;
620 }
621 else {
622 if(prevX !== null) {
623 if (stepPlot) {
624 ctx.lineTo(x, prevY);
625 ctx.lineTo(x, canvasHeight);
626 }
627 else {
628 ctx.lineTo(prevX, canvasHeight);
629 }
630 }
631 prevX = prevY = null;
632 }
633 }
634 ctx.lineTo(canvasWidth, canvasHeight);
635 ctx.closePath();
636
637 if (fillStyle) {
638 var lingrad = this.bgcanvas_ctx_.createLinearGradient(0, 0, 0, canvasHeight);
639 lingrad.addColorStop(0, 'white');
640 lingrad.addColorStop(1, fillStyle);
641 this.bgcanvas_ctx_.fillStyle = lingrad;
642 ctx.fill();
643 }
644
645 if (strokeStyle) {
646 this.bgcanvas_ctx_.strokeStyle = strokeStyle;
647 this.bgcanvas_ctx_.lineWidth = 1.5;
648 ctx.stroke();
649 }
650 };
651
652 /**
653 * @private
654 * Computes and returns the combined series data along with min/max for the mini plot.
655 * The combined series consists of averaged values for all series.
656 * When series have error bars, the error bars are ignored.
657 * @return {Object} An object containing combined series array, ymin, ymax.
658 */
659 rangeSelector.prototype.computeCombinedSeriesAndLimits_ = function() {
660 var g = this.dygraph_;
661 var logscale = this.getOption_('logscale');
662 var i;
663
664 // Select series to combine. By default, all series are combined.
665 var numColumns = g.numColumns();
666 var labels = g.getLabels();
667 var includeSeries = new Array(numColumns);
668 var anySet = false;
669 for (i = 1; i < numColumns; i++) {
670 var include = this.getOption_('showInRangeSelector', labels[i]);
671 includeSeries[i] = include;
672 if (include !== null) anySet = true; // it's set explicitly for this series
673 }
674 if (!anySet) {
675 for (i = 0; i < includeSeries.length; i++) includeSeries[i] = true;
676 }
677
678 // Create a combined series (average of selected series values).
679 // TODO(danvk): short-circuit if there's only one series.
680 var rolledSeries = [];
681 var dataHandler = g.dataHandler_;
682 var options = g.attributes_;
683 for (i = 1; i < g.numColumns(); i++) {
684 if (!includeSeries[i]) continue;
685 var series = dataHandler.extractSeries(g.rawData_, i, options);
686 if (g.rollPeriod() > 1) {
687 series = dataHandler.rollingAverage(series, g.rollPeriod(), options);
688 }
689
690 rolledSeries.push(series);
691 }
692
693 var combinedSeries = [];
694 for (i = 0; i < rolledSeries[0].length; i++) {
695 var sum = 0;
696 var count = 0;
697 for (var j = 0; j < rolledSeries.length; j++) {
698 var y = rolledSeries[j][i][1];
699 if (y === null || isNaN(y)) continue;
700 count++;
701 sum += y;
702 }
703 combinedSeries.push([rolledSeries[0][i][0], sum / count]);
704 }
705
706 // Compute the y range.
707 var yMin = Number.MAX_VALUE;
708 var yMax = -Number.MAX_VALUE;
709 for (i = 0; i < combinedSeries.length; i++) {
710 var yVal = combinedSeries[i][1];
711 if (yVal !== null && isFinite(yVal) && (!logscale || yVal > 0)) {
712 yMin = Math.min(yMin, yVal);
713 yMax = Math.max(yMax, yVal);
714 }
715 }
716
717 // Convert Y data to log scale if needed.
718 // Also, expand the Y range to compress the mini plot a little.
719 var extraPercent = 0.25;
720 if (logscale) {
721 yMax = Dygraph.log10(yMax);
722 yMax += yMax*extraPercent;
723 yMin = Dygraph.log10(yMin);
724 for (i = 0; i < combinedSeries.length; i++) {
725 combinedSeries[i][1] = Dygraph.log10(combinedSeries[i][1]);
726 }
727 } else {
728 var yExtra;
729 var yRange = yMax - yMin;
730 if (yRange <= Number.MIN_VALUE) {
731 yExtra = yMax*extraPercent;
732 } else {
733 yExtra = yRange*extraPercent;
734 }
735 yMax += yExtra;
736 yMin -= yExtra;
737 }
738
739 return {data: combinedSeries, yMin: yMin, yMax: yMax};
740 };
741
742 /**
743 * @private
744 * Places the zoom handles in the proper position based on the current X data window.
745 */
746 rangeSelector.prototype.placeZoomHandles_ = function() {
747 var xExtremes = this.dygraph_.xAxisExtremes();
748 var xWindowLimits = this.dygraph_.xAxisRange();
749 var xRange = xExtremes[1] - xExtremes[0];
750 var leftPercent = Math.max(0, (xWindowLimits[0] - xExtremes[0])/xRange);
751 var rightPercent = Math.max(0, (xExtremes[1] - xWindowLimits[1])/xRange);
752 var leftCoord = this.canvasRect_.x + this.canvasRect_.w*leftPercent;
753 var rightCoord = this.canvasRect_.x + this.canvasRect_.w*(1 - rightPercent);
754 var handleTop = Math.max(this.canvasRect_.y, this.canvasRect_.y + (this.canvasRect_.h - this.leftZoomHandle_.height)/2);
755 var halfHandleWidth = this.leftZoomHandle_.width/2;
756 this.leftZoomHandle_.style.left = (leftCoord - halfHandleWidth) + 'px';
757 this.leftZoomHandle_.style.top = handleTop + 'px';
758 this.rightZoomHandle_.style.left = (rightCoord - halfHandleWidth) + 'px';
759 this.rightZoomHandle_.style.top = this.leftZoomHandle_.style.top;
760
761 this.leftZoomHandle_.style.visibility = 'visible';
762 this.rightZoomHandle_.style.visibility = 'visible';
763 };
764
765 /**
766 * @private
767 * Draws the interactive layer in the foreground canvas.
768 */
769 rangeSelector.prototype.drawInteractiveLayer_ = function() {
770 var ctx = this.fgcanvas_ctx_;
771 ctx.clearRect(0, 0, this.canvasRect_.w, this.canvasRect_.h);
772 var margin = 1;
773 var width = this.canvasRect_.w - margin;
774 var height = this.canvasRect_.h - margin;
775 var zoomHandleStatus = this.getZoomHandleStatus_();
776
777 ctx.strokeStyle = 'black';
778 if (!zoomHandleStatus.isZoomed) {
779 ctx.beginPath();
780 ctx.moveTo(margin, margin);
781 ctx.lineTo(margin, height);
782 ctx.lineTo(width, height);
783 ctx.lineTo(width, margin);
784 ctx.stroke();
785 if (this.iePanOverlay_) {
786 this.iePanOverlay_.style.display = 'none';
787 }
788 } else {
789 var leftHandleCanvasPos = Math.max(margin, zoomHandleStatus.leftHandlePos - this.canvasRect_.x);
790 var rightHandleCanvasPos = Math.min(width, zoomHandleStatus.rightHandlePos - this.canvasRect_.x);
791
792 ctx.fillStyle = 'rgba(240, 240, 240, 0.6)';
793 ctx.fillRect(0, 0, leftHandleCanvasPos, this.canvasRect_.h);
794 ctx.fillRect(rightHandleCanvasPos, 0, this.canvasRect_.w - rightHandleCanvasPos, this.canvasRect_.h);
795
796 ctx.beginPath();
797 ctx.moveTo(margin, margin);
798 ctx.lineTo(leftHandleCanvasPos, margin);
799 ctx.lineTo(leftHandleCanvasPos, height);
800 ctx.lineTo(rightHandleCanvasPos, height);
801 ctx.lineTo(rightHandleCanvasPos, margin);
802 ctx.lineTo(width, margin);
803 ctx.stroke();
804
805 if (this.isUsingExcanvas_) {
806 this.iePanOverlay_.style.width = (rightHandleCanvasPos - leftHandleCanvasPos) + 'px';
807 this.iePanOverlay_.style.left = leftHandleCanvasPos + 'px';
808 this.iePanOverlay_.style.height = height + 'px';
809 this.iePanOverlay_.style.display = 'inline';
810 }
811 }
812 };
813
814 /**
815 * @private
816 * Returns the current zoom handle position information.
817 * @return {Object} The zoom handle status.
818 */
819 rangeSelector.prototype.getZoomHandleStatus_ = function() {
820 var halfHandleWidth = this.leftZoomHandle_.width/2;
821 var leftHandlePos = parseFloat(this.leftZoomHandle_.style.left) + halfHandleWidth;
822 var rightHandlePos = parseFloat(this.rightZoomHandle_.style.left) + halfHandleWidth;
823 return {
824 leftHandlePos: leftHandlePos,
825 rightHandlePos: rightHandlePos,
826 isZoomed: (leftHandlePos - 1 > this.canvasRect_.x || rightHandlePos + 1 < this.canvasRect_.x+this.canvasRect_.w)
827 };
828 };
829
830 return rangeSelector;
831
832 })();