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