Fix conflicts in index.html
[dygraphs.git] / dygraph.js
index 0390a6f..b043d06 100644 (file)
@@ -24,7 +24,6 @@
 
  If the 'errorBars' option is set in the constructor, the input should be of
  the form
-
    Date,SeriesA,SeriesB,...
    YYYYMMDD,A1,sigmaA1,B1,sigmaB1,...
    YYYYMMDD,A2,sigmaA2,B2,sigmaB2,...
@@ -199,6 +198,10 @@ Dygraph.prototype.__init__ = function(div, file, attrs) {
   this.is_initial_draw_ = true;
   this.annotations_ = [];
 
+  // Zoomed indicators - These indicate when the graph has been zoomed and on what axis.
+  this.zoomed_x_ = false;
+  this.zoomed_y_ = false;
+
   // Clear the div. This ensure that, if multiple dygraphs are passed the same
   // div, then only one will be drawn.
   div.innerHTML = "";
@@ -261,6 +264,20 @@ Dygraph.prototype.__init__ = function(div, file, attrs) {
   this.start_();
 };
 
+// Axis is an optional parameter. Can be set to 'x' or 'y'.
+Dygraph.prototype.isZoomed = function(axis) {
+  if (axis == null) return this.zoomed_x_ || this.zoomed_y_;
+  if (axis == 'x') return this.zoomed_x_;
+  if (axis == 'y') return this.zoomed_y_;
+  throw "axis parameter to Dygraph.isZoomed must be missing, 'x' or 'y'.";
+};
+
+Dygraph.prototype.toString = function() {
+  var maindiv = this.maindiv_;
+  var id = (maindiv && maindiv.id) ? maindiv.id : maindiv
+  return "[Dygraph " + id + "]";
+}
+
 Dygraph.prototype.attr_ = function(name, seriesName) {
   if (seriesName &&
       typeof(this.user_attrs_[seriesName]) != 'undefined' &&
@@ -442,7 +459,8 @@ Dygraph.prototype.toDataYCoord = function(y, axis) {
   var area = this.plotter_.area;
   var yRange = this.yAxisRange(axis);
 
-  if (!axis.logscale) {
+  if (typeof(axis) == "undefined") axis = 0;
+  if (!this.axes_[axis].logscale) {
     return yRange[0] + (area.h - y) / area.h * (yRange[1] - yRange[0]);
   } else {
     // Computing the inverse of toDomCoord.
@@ -912,6 +930,8 @@ Dygraph.startPan = function(event, g, context) {
   context.isPanning = true;
   var xRange = g.xAxisRange();
   context.dateRange = xRange[1] - xRange[0];
+  context.initialLeftmostDate = xRange[0];
+  context.xUnitsPerPixel = context.dateRange / (g.plotter_.area.w - 1);
 
   // Record the range of each y-axis at the start of the drag.
   // If any axis has a valueRange or valueWindow, then we want a 2D pan.
@@ -919,14 +939,20 @@ Dygraph.startPan = function(event, g, context) {
   for (var i = 0; i < g.axes_.length; i++) {
     var axis = g.axes_[i];
     var yRange = g.yAxisRange(i);
-    axis.dragValueRange = yRange[1] - yRange[0];
-    axis.draggingValue = g.toDataYCoord(context.dragStartY, i);
+    // TODO(konigsberg): These values should be in |context|.
+    // In log scale, initialTopValue, dragValueRange and unitsPerPixel are log scale.
+    if (axis.logscale) {
+      axis.initialTopValue = Dygraph.log10(yRange[1]);
+      axis.dragValueRange = Dygraph.log10(yRange[1]) - Dygraph.log10(yRange[0]);
+    } else {
+      axis.initialTopValue = yRange[1];
+      axis.dragValueRange = yRange[1] - yRange[0];
+    }
+    axis.unitsPerPixel = axis.dragValueRange / (g.plotter_.area.h - 1);
+
+    // While calculating axes, set 2dpan.
     if (axis.valueWindow || axis.valueRange) context.is2DPan = true;
   }
-
-  // TODO(konigsberg): Switch from all this math to toDataCoords?
-  // Seems to work for the dragging value.
-  context.draggingDate = (context.dragStartX / g.width_) * context.dateRange + xRange[0];
 };
 
 // Called in response to an interaction model operation that
@@ -940,32 +966,29 @@ Dygraph.movePan = function(event, g, context) {
   context.dragEndX = g.dragGetX_(event, context);
   context.dragEndY = g.dragGetY_(event, context);
 
-  // TODO(danvk): update this comment
-  // Want to have it so that:
-  // 1. draggingDate appears at dragEndX, draggingValue appears at dragEndY.
-  // 2. daterange = (dateWindow_[1] - dateWindow_[0]) is unaltered.
-  // 3. draggingValue appears at dragEndY.
-  // 4. valueRange is unaltered.
-
-  var minDate = context.draggingDate - (context.dragEndX / g.width_) * context.dateRange;
+  var minDate = context.initialLeftmostDate -
+    (context.dragEndX - context.dragStartX) * context.xUnitsPerPixel;
   var maxDate = minDate + context.dateRange;
   g.dateWindow_ = [minDate, maxDate];
 
   // y-axis scaling is automatic unless this is a full 2D pan.
   if (context.is2DPan) {
     // Adjust each axis appropriately.
-    // NOTE(konigsberg): I don't think this computation for y_frac is correct.
-    // I think it doesn't take into account the display of the x axis.
-    // See, when I tested this with console.log(y_frac), and move the mouse
-    // cursor to the botom, the largest y_frac was 0.94, and not 1.0. That
-    // could also explain why panning tends to start with a small jumpy shift.
-    var y_frac = context.dragEndY / g.height_;
-
     for (var i = 0; i < g.axes_.length; i++) {
       var axis = g.axes_[i];
-      var maxValue = axis.draggingValue + y_frac * axis.dragValueRange;
+
+      var pixelsDragged = context.dragEndY - context.dragStartY;
+      var unitsDragged = pixelsDragged * axis.unitsPerPixel;
+
+      // In log scale, maxValue and minValue are the logs of those values.
+      var maxValue = axis.initialTopValue + unitsDragged;
       var minValue = maxValue - axis.dragValueRange;
-      axis.valueWindow = [ minValue, maxValue ];
+      if (axis.logscale) {
+        axis.valueWindow = [ Math.pow(Dygraph.LOG_SCALE, minValue),
+                             Math.pow(Dygraph.LOG_SCALE, maxValue) ];
+      } else {
+        axis.valueWindow = [ minValue, maxValue ];
+      }
     }
   }
 
@@ -980,9 +1003,12 @@ Dygraph.movePan = function(event, g, context) {
 // panning behavior.
 //
 Dygraph.endPan = function(event, g, context) {
+  // TODO(konigsberg): Clear the context data from the axis.
+  // TODO(konigsberg): mouseup should just delete the
+  // context object, and mousedown should create a new one.
   context.isPanning = false;
   context.is2DPan = false;
-  context.draggingDate = null;
+  context.initialLeftmostDate = null;
   context.dateRange = null;
   context.valueRange = null;
 }
@@ -1158,12 +1184,12 @@ Dygraph.prototype.createDragInterface_ = function() {
     prevEndY: null,
     prevDragDirection: null,
 
-    // TODO(danvk): update this comment
-    // draggingDate and draggingValue represent the [date,value] point on the
-    // graph at which the mouse was pressed. As the mouse moves while panning,
-    // the viewport must pan so that the mouse position points to
-    // [draggingDate, draggingValue]
-    draggingDate: null,
+    // The value on the left side of the graph when a pan operation starts.
+    initialLeftmostDate: null,
+
+    // The number of units each pixel spans. (This won't be valid for log
+    // scales)
+    xUnitsPerPixel: null,
 
     // TODO(danvk): update this comment
     // The range in second/value units that the viewport encompasses during a
@@ -1310,6 +1336,7 @@ Dygraph.prototype.doZoomX_ = function(lowX, highX) {
  */
 Dygraph.prototype.doZoomXDates_ = function(minDate, maxDate) {
   this.dateWindow_ = [minDate, maxDate];
+  this.zoomed_x_ = true;
   this.drawGraph_();
   if (this.attr_("zoomCallback")) {
     this.attr_("zoomCallback")(minDate, maxDate, this.yAxisRanges());
@@ -1337,9 +1364,11 @@ Dygraph.prototype.doZoomY_ = function(lowY, highY) {
     valueRanges.push([low, hi]);
   }
 
+  this.zoomed_y_ = true;
   this.drawGraph_();
   if (this.attr_("zoomCallback")) {
     var xRange = this.xAxisRange();
+    var yRange = this.yAxisRange();
     this.attr_("zoomCallback")(xRange[0], xRange[1], this.yAxisRanges());
   }
 };
@@ -1367,6 +1396,8 @@ Dygraph.prototype.doUnzoom_ = function() {
   if (dirty) {
     // Putting the drawing operation before the callback because it resets
     // yAxisRange.
+    this.zoomed_x_ = false;
+    this.zoomed_y_ = false;
     this.drawGraph_();
     if (this.attr_("zoomCallback")) {
       var minDate = this.rawData_[0][0];
@@ -1403,10 +1434,6 @@ Dygraph.prototype.mouseMove_ = function(event) {
     idx = i;
   }
   if (idx >= 0) lastx = points[idx].xval;
-  // Check that you can really highlight the last day's data
-  var last = points[points.length-1];
-  if (last != null && canvasx > last.canvasx)
-    lastx = points[points.length-1].xval;
 
   // Extract the points we've selected
   this.selPoints_ = [];
@@ -1914,6 +1941,69 @@ Dygraph.dateTicker = function(startDate, endDate, self) {
   }
 };
 
+// This is a list of human-friendly values at which to show tick marks on a log
+// scale. It is k * 10^n, where k=1..9 and n=-39..+39, so:
+// ..., 1, 2, 3, 4, 5, ..., 9, 10, 20, 30, ..., 90, 100, 200, 300, ...
+// NOTE: this assumes that Dygraph.LOG_SCALE = 10.
+Dygraph.PREFERRED_LOG_TICK_VALUES = function() {
+  var vals = [];
+  for (var power = -39; power <= 39; power++) {
+    var range = Math.pow(10, power);
+    for (var mult = 1; mult <= 9; mult++) {
+      var val = range * mult;
+      vals.push(val);
+    }
+  }
+  return vals;
+}();
+
+// val is the value to search for
+// arry is the value over which to search
+// if abs > 0, find the lowest entry greater than val
+// if abs < 0, find the highest entry less than val
+// if abs == 0, find the entry that equals val.
+// Currently does not work when val is outside the range of arry's values.
+Dygraph.binarySearch = function(val, arry, abs, low, high) {
+  if (low == null || high == null) {
+    low = 0;
+    high = arry.length - 1;
+  }
+  if (low > high) {
+    return -1;
+  }
+  if (abs == null) {
+    abs = 0;
+  }
+  var validIndex = function(idx) {
+    return idx >= 0 && idx < arry.length;
+  }
+  var mid = parseInt((low + high) / 2);
+  var element = arry[mid];
+  if (element == val) {
+    return mid;
+  }
+  if (element > val) {
+    if (abs > 0) {
+      // Accept if element > val, but also if prior element < val.
+      var idx = mid - 1;
+      if (validIndex(idx) && arry[idx] < val) {
+        return mid;
+      }
+    }
+    return Dygraph.binarySearch(val, arry, abs, low, mid - 1);
+  }
+  if (element < val) {
+    if (abs < 0) {
+      // Accept if element < val, but also if prior element > val.
+      var idx = mid + 1;
+      if (validIndex(idx) && arry[idx] > val) {
+        return mid;
+      }
+    }
+    return Dygraph.binarySearch(val, arry, abs, mid + 1, high);
+  }
+};
+
 /**
  * Add ticks when the x axis has numbers on it (instead of dates)
  * TODO(konigsberg): Update comment.
@@ -1938,23 +2028,50 @@ Dygraph.numericTicks = function(minV, maxV, self, axis_props, vals) {
     }
   } else {
     if (axis_props && attr("logscale")) {
-      // As opposed to the other ways for computing ticks, we're just going
-      // for nearby values. There's no reasonable way to scale the values
-      // (unless we want to show strings like "log(" + x + ")") in which case
-      // x can be integer values.
-
-      // so compute height / pixelsPerTick and move on.
       var pixelsPerTick = attr('pixelsPerYLabel');
       // NOTE(konigsberg): Dan, should self.height_ be self.plotter_.area.h?
       var nTicks  = Math.floor(self.height_ / pixelsPerTick);
-      var vv = minV;
-
-      // Construct the set of ticks.
-      for (var i = 0; i < nTicks; i++) {
-        ticks.push( {v: vv} );
-        vv = vv * Dygraph.LOG_SCALE;
+      var minIdx = Dygraph.binarySearch(minV, Dygraph.PREFERRED_LOG_TICK_VALUES, 1);
+      var maxIdx = Dygraph.binarySearch(maxV, Dygraph.PREFERRED_LOG_TICK_VALUES, -1);
+      if (minIdx == -1) {
+        minIdx = 0;
       }
-    } else {
+      if (maxIdx == -1) {
+        maxIdx = Dygraph.PREFERRED_LOG_TICK_VALUES.length - 1;
+      }
+      // Count the number of tick values would appear, if we can get at least
+      // nTicks / 4 accept them.
+      var lastDisplayed = null;
+      if (maxIdx - minIdx >= nTicks / 4) {
+        var axisId = axis_props.yAxisId;
+        for (var idx = maxIdx; idx >= minIdx; idx--) {
+          var tickValue = Dygraph.PREFERRED_LOG_TICK_VALUES[idx];
+          var domCoord = axis_props.g.toDomYCoord(tickValue, axisId);
+          var tick = { v: tickValue };
+          if (lastDisplayed == null) {
+            lastDisplayed = {
+              tickValue : tickValue,
+              domCoord : domCoord
+            };
+          } else {
+            if (domCoord - lastDisplayed.domCoord >= pixelsPerTick) {
+              lastDisplayed = {
+                tickValue : tickValue,
+                domCoord : domCoord
+              };
+            } else {
+              tick.label = "";
+            }
+          }
+          ticks.push(tick);
+        }
+        // Since we went in backwards order.
+        ticks.reverse();
+      }
+    }
+
+    // ticks.length won't be 0 if the log scale function finds values to insert.
+    if (ticks.length == 0) {
       // Basic idea:
       // Try labels every 1, 2, 5, 10, 20, 50, 100, etc.
       // Calculate the resulting tick spacing (i.e. this.height_ / nTicks).
@@ -2010,26 +2127,29 @@ Dygraph.numericTicks = function(minV, maxV, self, axis_props, vals) {
   }
   var formatter = attr('yAxisLabelFormatter') ? attr('yAxisLabelFormatter') : attr('yValueFormatter'); 
 
+  // Add labels to the ticks.
   for (var i = 0; i < ticks.length; i++) {
-    var tickV = ticks[i].v;
-    var absTickV = Math.abs(tickV);
-    var label;
-    if (formatter != undefined) {
-      label = formatter(tickV);
-    } else {
-      label = Dygraph.round_(tickV, 2);
-    }
-    if (k_labels.length) {
-      // Round up to an appropriate unit.
-      var n = k*k*k*k;
-      for (var j = 3; j >= 0; j--, n /= k) {
-        if (absTickV >= n) {
-          label = Dygraph.round_(tickV / n, 1) + k_labels[j];
-          break;
+    if (ticks[i].label == null) {
+      var tickV = ticks[i].v;
+      var absTickV = Math.abs(tickV);
+      var label;
+      if (formatter != undefined) {
+        label = formatter(tickV);
+      } else {
+        label = Dygraph.round_(tickV, 2);
+      }
+      if (k_labels.length) {
+        // Round up to an appropriate unit.
+        var n = k*k*k*k;
+        for (var j = 3; j >= 0; j--, n /= k) {
+          if (absTickV >= n) {
+            label = Dygraph.round_(tickV / n, 1) + k_labels[j];
+            break;
+          }
         }
       }
+      ticks[i].label = label;
     }
-    ticks[i].label = label;
   }
   return ticks;
 };
@@ -2082,7 +2202,7 @@ Dygraph.prototype.extremeValues_ = function(series) {
  * number of axes, rolling averages, etc.
  */
 Dygraph.prototype.predraw_ = function() {
-  // TODO(danvk): movabilitye more computations out of drawGraph_ and into here.
+  // TODO(danvk): move more computations out of drawGraph_ and into here.
   this.computeYAxes_();
 
   // Create a new plotter.
@@ -2146,7 +2266,7 @@ Dygraph.prototype.drawGraph_ = function() {
         // On the log scale, points less than zero do not exist.
         // This will create a gap in the chart. Note that this ignores
         // connectSeparatedPoints.
-        if (point < 0) {
+        if (point <= 0) {
           point = null;
         }
         series.push([date, point]);
@@ -2233,18 +2353,22 @@ Dygraph.prototype.drawGraph_ = function() {
     this.layout_.addDataset(this.attr_("labels")[i], datasets[i]);
   }
 
-  // TODO(danvk): this method doesn't need to return anything.
-  var out = this.computeYAxisRanges_(extremes);
-  var axes = out[0];
-  var seriesToAxisMap = out[1];
-  this.layout_.updateOptions( { yAxes: axes,
-                                seriesToAxisMap: seriesToAxisMap
-                              } );
-
+  if (datasets.length > 0) {
+    // TODO(danvk): this method doesn't need to return anything.
+    var out = this.computeYAxisRanges_(extremes);
+    var axes = out[0];
+    var seriesToAxisMap = out[1];
+    this.layout_.updateOptions( { yAxes: axes,
+                                  seriesToAxisMap: seriesToAxisMap
+                                } );
+  }
   this.addXTicks_();
 
+  // Save the X axis zoomed status as the updateOptions call will tend to set it errorneously
+  var tmp_zoomed_x = this.zoomed_x_;
   // Tell PlotKit to use this new data and render itself
   this.layout_.updateOptions({dateWindow: this.dateWindow_});
+  this.zoomed_x_ = tmp_zoomed_x;
   this.layout_.evaluateWithError();
   this.plotter_.clear();
   this.plotter_.render();
@@ -2267,7 +2391,16 @@ Dygraph.prototype.drawGraph_ = function() {
  *   indices are into the axes_ array.
  */
 Dygraph.prototype.computeYAxes_ = function() {
-  this.axes_ = [{}];  // always have at least one y-axis.
+  var valueWindows;
+  if (this.axes_ != undefined) {
+    // Preserve valueWindow settings.
+    valueWindows = [];
+    for (var index = 0; index < this.axes_.length; index++) {
+      valueWindows.push(this.axes_[index].valueWindow);
+    }
+  }
+
+  this.axes_ = [{ yAxisId : 0, g : this }];  // always have at least one y-axis.
   this.seriesToAxisMap_ = {};
 
   // Get a list of series names.
@@ -2308,9 +2441,12 @@ Dygraph.prototype.computeYAxes_ = function() {
       var opts = {};
       Dygraph.update(opts, this.axes_[0]);
       Dygraph.update(opts, { valueRange: null });  // shouldn't inherit this.
+      var yAxisId = this.axes_.length;
+      opts.yAxisId = yAxisId;
+      opts.g = this;
       Dygraph.update(opts, axis);
       this.axes_.push(opts);
-      this.seriesToAxisMap_[seriesName] = this.axes_.length - 1;
+      this.seriesToAxisMap_[seriesName] = yAxisId;
     }
   }
 
@@ -2340,6 +2476,13 @@ Dygraph.prototype.computeYAxes_ = function() {
     if (vis[i - 1]) seriesToAxisFiltered[s] = this.seriesToAxisMap_[s];
   }
   this.seriesToAxisMap_ = seriesToAxisFiltered;
+
+  if (valueWindows != undefined) {
+    // Restore valueWindow settings.
+    for (var index = 0; index < valueWindows.length; index++) {
+      this.axes_[index].valueWindow = valueWindows[index];
+    }
+  }
 };
 
 /**
@@ -2630,7 +2773,7 @@ Dygraph.dateParser = function(dateStr, self) {
  */
 Dygraph.prototype.detectTypeFromString_ = function(str) {
   var isDate = false;
-  if (str.indexOf('-') >= 0 ||
+  if (str.indexOf('-') > 0 ||
       str.indexOf('/') >= 0 ||
       isNaN(parseFloat(str))) {
     isDate = true;
@@ -3043,6 +3186,12 @@ Dygraph.prototype.updateOptions = function(attrs) {
   }
   if ('dateWindow' in attrs) {
     this.dateWindow_ = attrs.dateWindow;
+    if (!('noZoomFlagChange' in attrs)) {
+      this.zoomed_x_ = attrs.dateWindow != null;
+    }
+  }
+  if ('valueRange' in attrs && !('noZoomFlagChange' in attrs)) {
+    this.zoomed_y_ = attrs.valueRange != null;
   }
 
   // TODO(danvk): validate per-series options.