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