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