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