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