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