Merge branch 'master' into remove-old-options
authorRobert Konigsberg <konigsberg@google.com>
Sat, 24 Nov 2012 15:45:26 +0000 (10:45 -0500)
committerRobert Konigsberg <konigsberg@google.com>
Sat, 24 Nov 2012 15:46:38 +0000 (10:46 -0500)
Conflicts:
dygraph-options.js
dygraph.js

16 files changed:
auto_tests/tests/callback.js
auto_tests/tests/formats.js
auto_tests/tests/pathological_cases.js
closure-todo.txt [new file with mode: 0644]
dashed-canvas.js
dygraph-externs.js [new file with mode: 0644]
dygraph-gviz.js
dygraph-interaction-model.js
dygraph-options-reference.js
dygraph-options.js
dygraph-range-selector.js
dygraph-tickers.js
dygraph-utils.js
dygraph.js
gallery/highlighted-series.js
lint.sh

index 6e59787..0e6b4fa 100644 (file)
@@ -304,7 +304,7 @@ CallbackTestCase.prototype.testClosestPointCallbackCss2 = function() {
 /**
  * Closest-point highlighting with locked series.
  */
-CallbackTestCase.prototype.testClosestPointCallbackCss1 = function() {
+CallbackTestCase.prototype.testSetSelectionLocking = function() {
   var g = runClosestTest(false, 2, 4);
 
   // Default behavior, 'b' is closest
index 78e2240..38ba88e 100644 (file)
@@ -58,6 +58,28 @@ FormatsTestCase.prototype.testFunctionDefinesArray = function() {
   this.assertData(g);
 };
 
+FormatsTestCase.prototype.testXValueParser = function() {
+  var data =
+    "X,Y\n" +
+    "d,-1\n" +
+    "e,0\n" +
+    "f,1\n" +
+    "g,0\n";
+
+  var graph = document.getElementById("graph");
+  var g = new Dygraph(graph, data, {
+    xValueParser : function(str) {
+      assertEquals(1, str.length);
+      return str.charCodeAt(0) - "a".charCodeAt(0);
+    }
+  });
+
+  assertEquals(3, g.getValue(0, 0));
+  assertEquals(4, g.getValue(1, 0));
+  assertEquals(5, g.getValue(2, 0));
+  assertEquals(6, g.getValue(3, 0));
+};
+
 FormatsTestCase.prototype.assertData = function(g) {
   var expected = this.dataArray;
 
index 21ff30a..83cba83 100644 (file)
@@ -48,3 +48,10 @@ pathologicalCasesTestCase.prototype.testNullLegend = function() {
   var graph = document.getElementById("graph");
   var g = new Dygraph(graph, data, opts);
 };
+
+pathologicalCasesTestCase.prototype.testDivAsString = function() {
+  var data = "X,Y\n" +
+             "1,2\n";
+
+  var g = new Dygraph('graph', data, {});
+}
diff --git a/closure-todo.txt b/closure-todo.txt
new file mode 100644 (file)
index 0000000..081b9ed
--- /dev/null
@@ -0,0 +1,37 @@
+Many of the functions and methods in the dygraphs source have some form of
+Closure annotations on them ("@param", "@return", "@private", etc.).
+
+These provide some documentation value, but they were largely written by
+developers who had never used the Closure Compiler and so the syntax is
+often not quite correct.
+
+This file tracks which files have been fully "closurized", i.e. compile
+under the Closure Compiler without any errors or warnings.
+
+Core:
+- dygraph-canvas.js
+- dygraph-interaction-model.js
+- dygraph-layout.js
+- dygraph-options.js
+- dygraph-range-selector.js
+- dygraph.js
+x dygraph-gviz.js
+x dygraph-tickers.js
+x dygraph-options-reference.js
+x dygraph-utils.js
+x dashed-canvas.js
+
+Plugins:
+- plugins/annotations.js
+- plugins/axes.js
+- plugins/base.js
+- plugins/chart-labels.js
+- plugins/grid.js
+- plugins/install.js
+- plugins/legend.js
+
+Here's a command that can be used to build dygraphs using the closure
+compiler:
+java -jar ../../closure-compiler-read-only/build/compiler.jar --js=dygraph-utils.js --js=dashed-canvas.js --js=dygraph-options-reference.js --js=dygraph-tickers.js --js=dygraph-gviz.js --js_output_file=/tmp/out.js --compilation_level ADVANCED_OPTIMIZATIONS --warning_level VERBOSE --externs dygraph-externs.js
+
+As each file is closurized, it can be added as a "--js" parameter.
index 853d67b..cec7729 100644 (file)
@@ -40,7 +40,7 @@
  * property and "uninstallPattern" method to this particular canvas context.
  * You must call uninstallPattern() before calling installPattern() again.
  *
- * @param {pattern | Array<Number>} A description of the stroke pattern. Even
+ * @param {Array.<number>} pattern A description of the stroke pattern. Even
  * indices indicate a draw and odd indices indicate a gap (in pixels). The
  * array should have a even length as any odd lengthed array could be expressed
  * as a smaller even length array.
@@ -65,6 +65,7 @@ CanvasRenderingContext2D.prototype.installPattern = function(pattern) {
   var realMoveTo = this.moveTo;
   var realStroke = this.stroke;
 
+  /** @type {function()|undefined} */
   this.uninstallPattern = function() {
     this.beginPath = realBeginPath;
     this.lineTo = realLineTo;
diff --git a/dygraph-externs.js b/dygraph-externs.js
new file mode 100644 (file)
index 0000000..6e487fd
--- /dev/null
@@ -0,0 +1,84 @@
+/**
+ * @param {Object} dict
+ * @return {!Array.<string>}
+ */
+function printStackTrace(dict) {}
+
+
+/**
+ * @constructor
+ */
+function G_vmlCanvasManager() {}
+
+/**
+ * @param {!HTMLCanvasElement} canvas
+ */
+G_vmlCanvasManager.initElement = function(canvas) {};
+
+// For IE
+/**
+ * @param {string} type
+ * @param {Object} fn
+ */
+Element.prototype.detachEvent = function(type, fn) {};
+
+
+/**
+ * @typedef {function(
+ *   (number|Date),
+ *   number,
+ *   function(string):*,
+ *   (Dygraph|undefined)
+ * ):string}
+ */
+var AxisLabelFormatter;
+
+
+/**
+ * @typedef {function(number,function(string),Dygraph):string}
+ */
+var ValueFormatter;
+
+
+/**
+ * @typedef {Array.<Array.<string|number|Array.<number>>>}
+ */
+var DygraphDataArray;
+
+/**
+ * @constructor
+ */
+function GVizDataTable() {}
+
+// TODO(danvk): move the Dygraph definitions out of here once I closure-ify dygraphs.js
+/**
+ * @param {!HTMLDivElement|string} div
+ * @param {DygraphDataArray|
+ *     GVizDataTable|
+ *     string|
+ *     function():(DygraphDataArray|GVizDataTable|string)} file
+ * @param {Object} attrs
+ * @constructor
+ */
+function Dygraph(div, file, attrs) {}
+
+/**
+ * @constructor
+ */
+function DygraphLayout() {}
+
+/**
+ * @type {Array}
+ */
+DygraphLayout.prototype.datasets;
+
+/**
+ * @type {DygraphLayout}
+ */
+Dygraph.prototype.layout_;
+
+/** @type {Array.<{elem:Element,type:string,fn:function(!Event):(boolean|undefined|null)}>} */
+Dygraph.prototype.registeredEvents_;
+
+/** @type {Object} */
+Dygraph.DEFAULT_ATTRS;
index 114263a..49feac5 100644 (file)
 
 /**
  * A wrapper around Dygraph that implements the gviz API.
- * @param {Object} container The DOM object the visualization should live in.
+ * @param {!HTMLDivElement} container The DOM object the visualization should
+ *     live in.
+ * @constructor
  */
 Dygraph.GVizChart = function(container) {
   this.container = container;
 };
 
+/**
+ * @param {GVizDataTable} data
+ * @param {Object.<*>} options
+ */
 Dygraph.GVizChart.prototype.draw = function(data, options) {
   // Clear out any existing dygraph.
   // TODO(danvk): would it make more sense to simply redraw using the current
@@ -44,7 +50,7 @@ Dygraph.GVizChart.prototype.draw = function(data, options) {
 /**
  * Google charts compatible setSelection
  * Only row selection is supported, all points in the row will be highlighted
- * @param {Array} array of the selected cells
+ * @param {Array.<{row:number}>} selection_array array of the selected cells
  * @public
  */
 Dygraph.GVizChart.prototype.setSelection = function(selection_array) {
@@ -57,7 +63,7 @@ Dygraph.GVizChart.prototype.setSelection = function(selection_array) {
 
 /**
  * Google charts compatible getSelection implementation
- * @return {Array} array of the selected cells
+ * @return {Array.<{row:number,column:number}>} array of the selected cells
  * @public
  */
 Dygraph.GVizChart.prototype.getSelection = function() {
index 4df6799..d335f15 100644 (file)
@@ -28,10 +28,11 @@ Dygraph.Interaction = {};
  * Custom interaction model builders can use it to provide the default
  * panning behavior.
  *
- * @param { Event } event the event object which led to the startPan call.
- * @param { Dygraph} g The dygraph on which to act.
- * @param { Object} context The dragging context object (with
- * dragStartX/dragStartY/etc. properties). This function modifies the context.
+ * @param {Event} event the event object which led to the startPan call.
+ * @param {Dygraph} g The dygraph on which to act.
+ * @param {Object} context The dragging context object (with
+ *     dragStartX/dragStartY/etc. properties). This function modifies the
+ *     context.
  */
 Dygraph.Interaction.startPan = function(event, g, context) {
   var i, axis;
@@ -106,10 +107,11 @@ Dygraph.Interaction.startPan = function(event, g, context) {
  * Custom interaction model builders can use it to provide the default
  * panning behavior.
  *
- * @param { Event } event the event object which led to the movePan call.
- * @param { Dygraph} g The dygraph on which to act.
- * @param { Object} context The dragging context object (with
- * dragStartX/dragStartY/etc. properties). This function modifies the context.
+ * @param {Event} event the event object which led to the movePan call.
+ * @param {Dygraph} g The dygraph on which to act.
+ * @param {Object} context The dragging context object (with
+ *     dragStartX/dragStartY/etc. properties). This function modifies the
+ *     context.
  */
 Dygraph.Interaction.movePan = function(event, g, context) {
   context.dragEndX = g.dragGetX_(event, context);
@@ -176,10 +178,11 @@ Dygraph.Interaction.movePan = function(event, g, context) {
  * Custom interaction model builders can use it to provide the default
  * panning behavior.
  *
- * @param { Event } event the event object which led to the endPan call.
- * @param { Dygraph} g The dygraph on which to act.
- * @param { Object} context The dragging context object (with
- * dragStartX/dragStartY/etc. properties). This function modifies the context.
+ * @param {Event} event the event object which led to the endPan call.
+ * @param {Dygraph} g The dygraph on which to act.
+ * @param {Object} context The dragging context object (with
+ *     dragStartX/dragStartY/etc. properties). This function modifies the
+ *     context.
  */
 Dygraph.Interaction.endPan = function(event, g, context) {
   context.dragEndX = g.dragGetX_(event, context);
@@ -213,10 +216,11 @@ Dygraph.Interaction.endPan = function(event, g, context) {
  * Custom interaction model builders can use it to provide the default
  * zooming behavior.
  *
- * @param { Event } event the event object which led to the startZoom call.
- * @param { Dygraph} g The dygraph on which to act.
- * @param { Object} context The dragging context object (with
- * dragStartX/dragStartY/etc. properties). This function modifies the context.
+ * @param {Event} event the event object which led to the startZoom call.
+ * @param {Dygraph} g The dygraph on which to act.
+ * @param {Object} context The dragging context object (with
+ *     dragStartX/dragStartY/etc. properties). This function modifies the
+ *     context.
  */
 Dygraph.Interaction.startZoom = function(event, g, context) {
   context.isZooming = true;
@@ -231,10 +235,11 @@ Dygraph.Interaction.startZoom = function(event, g, context) {
  * Custom interaction model builders can use it to provide the default
  * zooming behavior.
  *
- * @param { Event } event the event object which led to the moveZoom call.
- * @param { Dygraph} g The dygraph on which to act.
- * @param { Object} context The dragging context object (with
- * dragStartX/dragStartY/etc. properties). This function modifies the context.
+ * @param {Event} event the event object which led to the moveZoom call.
+ * @param {Dygraph} g The dygraph on which to act.
+ * @param {Object} context The dragging context object (with
+ *     dragStartX/dragStartY/etc. properties). This function modifies the
+ *     context.
  */
 Dygraph.Interaction.moveZoom = function(event, g, context) {
   context.zoomMoved = true;
@@ -262,13 +267,19 @@ Dygraph.Interaction.moveZoom = function(event, g, context) {
   context.prevDragDirection = context.dragDirection;
 };
 
+/**
+ * @param {Dygraph} g
+ * @param {Event} event
+ * @param {Object} context
+ */
 Dygraph.Interaction.treatMouseOpAsClick = function(g, event, context) {
   var clickCallback = g.attr_('clickCallback');
   var pointClickCallback = g.attr_('pointClickCallback');
 
   var selectedPoint = null;
 
-  // Find out if the click occurs on a point. This only matters if there's a pointClickCallback.
+  // Find out if the click occurs on a point. This only matters if there's a
+  // pointClickCallback.
   if (pointClickCallback) {
     var closestIdx = -1;
     var closestDistance = Number.MAX_VALUE;
@@ -311,10 +322,11 @@ Dygraph.Interaction.treatMouseOpAsClick = function(g, event, context) {
  * Custom interaction model builders can use it to provide the default
  * zooming behavior.
  *
- * @param { Event } event the event object which led to the endZoom call.
- * @param { Dygraph} g The dygraph on which to end the zoom.
- * @param { Object} context The dragging context object (with
- * dragStartX/dragStartY/etc. properties). This function modifies the context.
+ * @param {Event} event the event object which led to the endZoom call.
+ * @param {Dygraph} g The dygraph on which to end the zoom.
+ * @param {Object} context The dragging context object (with
+ *     dragStartX/dragStartY/etc. properties). This function modifies the
+ *     context.
  */
 Dygraph.Interaction.endZoom = function(event, g, context) {
   context.isZooming = false;
index abdb015..5aa7f05 100644 (file)
@@ -770,7 +770,7 @@ Dygraph.OPTIONS_REFERENCE =  // <JSON>
 // Do a quick sanity check on the options reference.
 (function() {
   "use strict";
-  var warn = function(msg) { if (console) console.warn(msg); };
+  var warn = function(msg) { if (window.console) window.console.warn(msg); };
   var flds = ['type', 'default', 'description'];
   var valid_cats = [
    'Annotations',
index 0f65f39..dd7bb6b 100644 (file)
  * Interesting member variables:
  * dygraph_ - the graph.
  * global_ - global attributes (common among all graphs, AIUI)
- * user_ - attributes set by the user
+ * user - attributes set by the user
  * axes_ - array of axis index to { series : [ series names ] , options : { axis-specific options. }
- * series_ - { seriesName -> { idx, yAxis, options }
+ * series_ - { seriesName -> { idx, yAxis, options }}
  * labels_ - used as mapping from index to series name.
  */
 
 /**
- * @constructor
- *
  * This parses attributes into an object that can be easily queried.
  *
+ * It doesn't necessarily mean that all options are available, specifically
+ * if labels are not yet available, since those drive details of the per-series
+ * and per-axis options.
+ *
  * @param {Dyraph} dygraph The chart to which these options belong.
+ * @constructor
  */
 var DygraphOptions = function(dygraph) {
   this.dygraph_ = dygraph;
   this.axes_ = [];
   this.series_ = {};
 
-  // Once these two objects are initialized, you can call find();
+  // Once these two objects are initialized, you can call get();
   this.global_ = this.dygraph_.attrs_;
   this.user_ = this.dygraph_.user_attrs_ || {};
 
-  this.highlightSeries_ = this.find("highlightSeriesOpts") || {};
+  this.highlightSeries_ = this.get("highlightSeriesOpts") || {};
   // Get a list of series names.
 
-  var labels = this.find("labels");
+  var labels = this.get("labels");
   if (!labels) {
     return; // -- can't do more for now, will parse after getting the labels.
-  };
+  }
 
   this.reparseSeries();
-}
+};
 
+/**
+ * Reparses options that are all related to series. This typically occurs when
+ * options are either updated, or source data has been made avaialble.
+ *
+ * TODO(konigsberg): The method name is kind of weak; fix.
+ */
 DygraphOptions.prototype.reparseSeries = function() {
-  this.labels = this.find("labels").slice(1);
+  this.labels = this.get("labels").slice(1);
 
   this.axes_ = [ { series : [], options : {}} ]; // Always one axis at least.
   this.series_ = {};
@@ -106,7 +115,12 @@ DygraphOptions.prototype.reparseSeries = function() {
   }
 };
 
-DygraphOptions.prototype.find = function(name) {
+/**
+ * Get a global value.
+ *
+ * @param {String} name the name of the option.
+ */
+DygraphOptions.prototype.get = function(name) {
   if (this.user_.hasOwnProperty(name)) {
     return this.user_[name];
   }
@@ -114,19 +128,41 @@ DygraphOptions.prototype.find = function(name) {
     return this.global_[name];
   }
   return null;
-}
+};
 
-DygraphOptions.prototype.findForAxis = function(name, axis) {
-  var axisIdx = (axis == "y2" || axis == "y2" || axis == 1) ? 1 : 0;
+/**
+ * Get a value for a specific axis. If there is no specific value for the axis,
+ * the global value is returned.
+ *
+ * @param {String} name the name of the option.
+ * @param {String|number} axis the axis to search. Can be the string representation
+ * ("y", "y2") or the axis number (0, 1).
+ */
+DygraphOptions.prototype.getForAxis = function(name, axis) {
+  var axisIdx = 0;
+  if (typeof(axis) == 'number') {
+    axisIdx = axis;
+  } else {
+    // TODO(konigsberg): Accept only valid axis strings?
+    axisIdx = (axis == "y2") ? 1 : 0;
+  }
 
   var axisOptions = this.axes_[axisIdx].options;
   if (axisOptions.hasOwnProperty(name)) {
     return axisOptions[name];
   }
-  return this.find(name);
-}
+  return this.get(name);
+};
 
-DygraphOptions.prototype.findForSeries = function(name, series) {
+/**
+ * Get a value for a specific series. If there is no specific value for the series,
+ * the value for the axis is returned (and afterwards, the global value.)
+ *
+ * @param {String} name the name of the option.
+ * @param {String|number} series the series to search. Can be the string representation
+ * or 0-offset series number.
+ */
+DygraphOptions.prototype.getForSeries = function(name, series) {
   // Honors indexes as series.
   var seriesName = (typeof(series) == "number") ? this.labels[series] : series;
 
@@ -146,8 +182,8 @@ DygraphOptions.prototype.findForSeries = function(name, series) {
     return seriesOptions[name];
   }
 
-  return this.findForAxis(name, seriesObj["yAxis"]);
-}
+  return this.getForAxis(name, seriesObj["yAxis"]);
+};
 
 /**
  * Returns the number of y-axes on the chart.
index e2973b0..b777470 100644 (file)
@@ -480,6 +480,8 @@ DygraphRangeSelector.prototype.drawMiniPlot_ = function() {
     return;
   }
 
+  var stepPlot = this.attr_('stepPlot');
+
   var combinedSeriesData = this.computeCombinedSeriesAndLimits_();
   var yRange = combinedSeriesData.yMax - combinedSeriesData.yMin;
 
@@ -494,14 +496,36 @@ DygraphRangeSelector.prototype.drawMiniPlot_ = function() {
   var canvasWidth = this.canvasRect_.w - margin;
   var canvasHeight = this.canvasRect_.h - margin;
 
+  var prevX = null, prevY = null;
+
   ctx.beginPath();
   ctx.moveTo(margin, canvasHeight);
   for (var i = 0; i < combinedSeriesData.data.length; i++) {
     var dataPoint = combinedSeriesData.data[i];
-    var x = (dataPoint[0] - xExtremes[0])*xFact;
-    var y = canvasHeight - (dataPoint[1] - combinedSeriesData.yMin)*yFact;
+    var x = ((dataPoint[0] !== null) ? ((dataPoint[0] - xExtremes[0])*xFact) : NaN);
+    var y = ((dataPoint[1] !== null) ? (canvasHeight - (dataPoint[1] - combinedSeriesData.yMin)*yFact) : NaN);
     if (isFinite(x) && isFinite(y)) {
+      if(prevX === null) {
+        ctx.lineTo(x, canvasHeight);
+      }
+      else if (stepPlot) {
+        ctx.lineTo(x, prevY);
+      }
       ctx.lineTo(x, y);
+      prevX = x;
+      prevY = y;
+    }
+    else {
+      if(prevX !== null) {
+        if (stepPlot) {
+          ctx.lineTo(x, prevY);
+          ctx.lineTo(x, canvasHeight);
+        }
+        else {
+          ctx.lineTo(prevX, canvasHeight);
+        }
+      }
+      prevX = prevY = null;
     }
   }
   ctx.lineTo(canvasWidth, canvasHeight);
index dada4cd..fa8d342 100644 (file)
 /*global Dygraph:false */
 "use strict";
 
+/** @typedef {Array.<{v:number, label:string, label_v:(string|undefined)}>} */
+Dygraph.TickList;
+
+/** @typedef {function(
+ *    number,
+ *    number,
+ *    number,
+ *    function(string):*,
+ *    Dygraph=,
+ *    Array.<number>=
+ *  ): Dygraph.TickList}
+ */
+Dygraph.Ticker;
+
+
+/** @type {Dygraph.Ticker} */
 Dygraph.numericLinearTicks = function(a, b, pixels, opts, dygraph, vals) {
   var nonLogscaleOpts = function(opt) {
     if (opt === 'logscale') return false;
@@ -70,9 +86,11 @@ Dygraph.numericLinearTicks = function(a, b, pixels, opts, dygraph, vals) {
   return Dygraph.numericTicks(a, b, pixels, nonLogscaleOpts, dygraph, vals);
 };
 
+/** @type {Dygraph.Ticker} */
 Dygraph.numericTicks = function(a, b, pixels, opts, dygraph, vals) {
   // This masks some numeric issues in older versions of Firefox,
   // where 1.0/Math.pow(10,2) != Math.pow(10,-2).
+  /** @type {function(number,number):number} */
   var pow = function(base, exp) {
     if (exp < 0) {
       return 1.0 / Math.pow(base, -exp);
@@ -80,7 +98,7 @@ Dygraph.numericTicks = function(a, b, pixels, opts, dygraph, vals) {
     return Math.pow(base, exp);
   };
 
-  var pixels_per_tick = opts('pixelsPerLabel');
+  var pixels_per_tick = /** @type{number} */(opts('pixelsPerLabel'));
   var ticks = [];
   var i, j, tickV, nTicks;
   if (vals) {
@@ -175,7 +193,7 @@ Dygraph.numericTicks = function(a, b, pixels, opts, dygraph, vals) {
   }
 
   // Add formatted labels to the ticks.
-  var k;
+  var k = 1;
   var k_labels = [];
   var m_labels = [];
   if (opts("labelsKMB")) {
@@ -189,9 +207,10 @@ Dygraph.numericTicks = function(a, b, pixels, opts, dygraph, vals) {
     m_labels = [ "m", "u", "n", "p", "f", "a", "z", "y" ];
   }
 
-  var formatter = opts('axisLabelFormatter');
+  var formatter = /**@type{AxisLabelFormatter}*/(opts('axisLabelFormatter'));
 
   // Add labels to the ticks.
+  var digitsAfterDecimal = /** @type{number} */(opts('digitsAfterDecimal'));
   for (i = 0; i < ticks.length; i++) {
     if (ticks[i].label !== undefined) continue;  // Use current label.
     tickV = ticks[i].v;
@@ -204,8 +223,7 @@ Dygraph.numericTicks = function(a, b, pixels, opts, dygraph, vals) {
       var n = pow(k, k_labels.length);
       for (j = k_labels.length - 1; j >= 0; j--, n /= k) {
         if (absTickV >= n) {
-          label = Dygraph.round_(tickV / n, opts('digitsAfterDecimal')) +
-              k_labels[j];
+          label = Dygraph.round_(tickV / n, digitsAfterDecimal) + k_labels[j];
           break;
         }
       }
@@ -216,7 +234,7 @@ Dygraph.numericTicks = function(a, b, pixels, opts, dygraph, vals) {
         if(tickV.split('e-')[1] % 3 > 0) {
           label = Dygraph.round_(tickV.split('e-')[0] /
               pow(10,(tickV.split('e-')[1] % 3)),
-              opts('digitsAfterDecimal'));
+              digitsAfterDecimal);
         } else {
           label = Number(tickV.split('e-')[0]).toFixed(2);
         }
@@ -230,6 +248,7 @@ Dygraph.numericTicks = function(a, b, pixels, opts, dygraph, vals) {
 };
 
 
+/** @type {Dygraph.Ticker} */
 Dygraph.dateTicker = function(a, b, pixels, opts, dygraph, vals) {
   var chosen = Dygraph.pickDateTickGranularity(a, b, pixels, opts);
 
@@ -242,6 +261,7 @@ Dygraph.dateTicker = function(a, b, pixels, opts, dygraph, vals) {
 };
 
 // Time granularity enumeration
+// TODO(danvk): make this an @enum
 Dygraph.SECONDLY = 0;
 Dygraph.TWO_SECONDLY = 1;
 Dygraph.FIVE_SECONDLY = 2;
@@ -265,6 +285,7 @@ Dygraph.DECADAL = 19;
 Dygraph.CENTENNIAL = 20;
 Dygraph.NUM_GRANULARITIES = 21;
 
+/** @type {Array.<number>} */
 Dygraph.SHORT_SPACINGS = [];
 Dygraph.SHORT_SPACINGS[Dygraph.SECONDLY]        = 1000 * 1;
 Dygraph.SHORT_SPACINGS[Dygraph.TWO_SECONDLY]    = 1000 * 2;
@@ -283,11 +304,11 @@ Dygraph.SHORT_SPACINGS[Dygraph.DAILY]           = 1000 * 86400;
 Dygraph.SHORT_SPACINGS[Dygraph.WEEKLY]          = 1000 * 604800;
 
 /**
- * @private
  * 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.
+ * @type {Array.<number>}
  */
 Dygraph.PREFERRED_LOG_TICK_VALUES = function() {
   var vals = [];
@@ -304,15 +325,16 @@ Dygraph.PREFERRED_LOG_TICK_VALUES = function() {
 /**
  * Determine the correct granularity of ticks on a date axis.
  *
- * @param {Number} a Left edge of the chart (ms)
- * @param {Number} b Right edge of the chart (ms)
- * @param {Number} pixels Size of the chart in the relevant dimension (width).
- * @param {Function} opts Function mapping from option name -> value.
- * @return {Number} The appropriate axis granularity for this chart. See the
- * enumeration of possible values in dygraph-tickers.js.
+ * @param {number} a Left edge of the chart (ms)
+ * @param {number} b Right edge of the chart (ms)
+ * @param {number} pixels Size of the chart in the relevant dimension (width).
+ * @param {function(string):*} opts Function mapping from option name ->
+ *     value.
+ * @return {number} The appropriate axis granularity for this chart. See the
+ *     enumeration of possible values in dygraph-tickers.js.
  */
 Dygraph.pickDateTickGranularity = function(a, b, pixels, opts) {
-  var pixels_per_tick = opts('pixelsPerLabel');
+  var pixels_per_tick = /** @type{number} */(opts('pixelsPerLabel'));
   for (var i = 0; i < Dygraph.NUM_GRANULARITIES; i++) {
     var num_ticks = Dygraph.numDateTicks(a, b, i);
     if (pixels / num_ticks >= pixels_per_tick) {
@@ -322,6 +344,12 @@ Dygraph.pickDateTickGranularity = function(a, b, pixels, opts) {
   return -1;
 };
 
+/**
+ * @param {number} start_time
+ * @param {number} end_time
+ * @param {number} granularity (one of the granularities enumerated above)
+ * @return {number} Number of ticks that would result.
+ */
 Dygraph.numDateTicks = function(start_time, end_time, granularity) {
   if (granularity < Dygraph.MONTHLY) {
     // Generate one tick mark for every fixed interval of time.
@@ -342,8 +370,17 @@ Dygraph.numDateTicks = function(start_time, end_time, granularity) {
   }
 };
 
+/**
+ * @param {number} start_time
+ * @param {number} end_time
+ * @param {number} granularity (one of the granularities enumerated above)
+ * @param {function(string):*} opts Function mapping from option name -&gt; value.
+ * @param {Dygraph=} dg
+ * @return {!Dygraph.TickList}
+ */
 Dygraph.getDateAxis = function(start_time, end_time, granularity, opts, dg) {
-  var formatter = opts("axisLabelFormatter");
+  var formatter = /** @type{AxisLabelFormatter} */(
+      opts("axisLabelFormatter"));
   var ticks = [];
   var t;
 
@@ -432,6 +469,6 @@ Dygraph.getDateAxis = function(start_time, end_time, granularity, opts, dg) {
 };
 
 // These are set here so that this file can be included after dygraph.js.
-Dygraph.DEFAULT_ATTRS.axes.x.ticker = Dygraph.dateTicker;
-Dygraph.DEFAULT_ATTRS.axes.y.ticker = Dygraph.numericTicks;
-Dygraph.DEFAULT_ATTRS.axes.y2.ticker = Dygraph.numericTicks;
+Dygraph.DEFAULT_ATTRS['axes']['x']['ticker'] = Dygraph.dateTicker;
+Dygraph.DEFAULT_ATTRS['axes']['y']['ticker'] = Dygraph.numericTicks;
+Dygraph.DEFAULT_ATTRS['axes']['y2']['ticker'] = Dygraph.numericTicks;
index 04d2ae3..e306b3e 100644 (file)
 Dygraph.LOG_SCALE = 10;
 Dygraph.LN_TEN = Math.log(Dygraph.LOG_SCALE);
 
-/** @private */
+/**
+ * @private
+ * @param {number} x
+ * @return {number}
+ */
 Dygraph.log10 = function(x) {
   return Math.log(x) / Dygraph.LN_TEN;
 };
@@ -43,10 +47,10 @@ Dygraph.DASHED_LINE = [7, 3];
 Dygraph.DOT_DASH_LINE = [7, 2, 2, 2];
 
 /**
- * @private
  * Log an error on the JS console at the given severity.
- * @param { Integer } severity One of Dygraph.{DEBUG,INFO,WARNING,ERROR}
- * @param { String } The message to log.
+ * @param {number} severity One of Dygraph.{DEBUG,INFO,WARNING,ERROR}
+ * @param {string} message The message to log.
+ * @private
  */
 Dygraph.log = function(severity, message) {
   var st;
@@ -71,51 +75,68 @@ Dygraph.log = function(severity, message) {
     }
   }
 
-  if (typeof(console) != 'undefined') {
+  if (typeof(window.console) != 'undefined') {
     switch (severity) {
       case Dygraph.DEBUG:
-        console.debug('dygraphs: ' + message);
+        window.console.debug('dygraphs: ' + message);
         break;
       case Dygraph.INFO:
-        console.info('dygraphs: ' + message);
+        window.console.info('dygraphs: ' + message);
         break;
       case Dygraph.WARNING:
-        console.warn('dygraphs: ' + message);
+        window.console.warn('dygraphs: ' + message);
         break;
       case Dygraph.ERROR:
-        console.error('dygraphs: ' + message);
+        window.console.error('dygraphs: ' + message);
         break;
     }
   }
 
   if (Dygraph.LOG_STACK_TRACES) {
-    console.log(st.join('\n'));
+    window.console.log(st.join('\n'));
   }
 };
 
-/** @private */
+/**
+ * @param {string} message
+ * @private
+ */
 Dygraph.info = function(message) {
   Dygraph.log(Dygraph.INFO, message);
 };
-/** @private */
+/**
+ * @param {string} message
+ * @private
+ */
 Dygraph.prototype.info = Dygraph.info;
 
-/** @private */
+/**
+ * @param {string} message
+ * @private
+ */
 Dygraph.warn = function(message) {
   Dygraph.log(Dygraph.WARNING, message);
 };
-/** @private */
+/**
+ * @param {string} message
+ * @private
+ */
 Dygraph.prototype.warn = Dygraph.warn;
 
-/** @private */
+/**
+ * @param {string} message
+ * @private
+ */
 Dygraph.error = function(message) {
   Dygraph.log(Dygraph.ERROR, message);
 };
-/** @private */
+/**
+ * @param {string} message
+ * @private
+ */
 Dygraph.prototype.error = Dygraph.error;
 
 /**
- * @private
  * Return the 2d context for a dygraph canvas.
  *
  * This method is only exposed for the sake of replacing the function in
@@ -126,19 +147,22 @@ Dygraph.prototype.error = Dygraph.error;
  *   var realContext = oldFunc(canvas);
  *   return new Proxy(realContext);
  * };
+ * @param {!HTMLCanvasElement} canvas
+ * @return {!CanvasRenderingContext2D}
+ * @private
  */
 Dygraph.getContext = function(canvas) {
-  return canvas.getContext("2d");
+  return /** @type{!CanvasRenderingContext2D}*/(canvas.getContext("2d"));
 };
 
 /**
- * @private
  * Add an event handler. This smooths a difference between IE and the rest of
  * the world.
- * @param { DOM element } elem The element to add the event to.
- * @param { String } type The type of the event, e.g. 'click' or 'mousemove'.
- * @param { Function } fn The function to call on the event. The function takes
- * one parameter: the event object.
+ * @param { !Element } elem The element to add the event to.
+ * @param { string } type The type of the event, e.g. 'click' or 'mousemove'.
+ * @param { function(Event):(boolean|undefined) } fn The function to call
+ *     on the event. The function takes one parameter: the event object.
+ * @private
  */
 Dygraph.addEvent = function addEvent(elem, type, fn) {
   if (elem.addEventListener) {
@@ -150,14 +174,14 @@ Dygraph.addEvent = function addEvent(elem, type, fn) {
 };
 
 /**
- * @private
  * Add an event handler. This event handler is kept until the graph is
  * destroyed with a call to graph.destroy().
  *
- * @param { DOM element } elem The element to add the event to.
- * @param { String } type The type of the event, e.g. 'click' or 'mousemove'.
- * @param { Function } fn The function to call on the event. The function takes
- * one parameter: the event object.
+ * @param { !Element } elem The element to add the event to.
+ * @param { string } type The type of the event, e.g. 'click' or 'mousemove'.
+ * @param { function(Event):(boolean|undefined) } fn The function to call
+ *     on the event. The function takes one parameter: the event object.
+ * @private
  */
 Dygraph.prototype.addEvent = function addEvent(elem, type, fn) {
   Dygraph.addEvent(elem, type, fn);
@@ -165,13 +189,13 @@ Dygraph.prototype.addEvent = function addEvent(elem, type, fn) {
 };
 
 /**
+ * Remove an event handler. This smooths a difference between IE and the rest
+ * of the world.
+ * @param {!Element} elem The element to add the event to.
+ * @param {string} type The type of the event, e.g. 'click' or 'mousemove'.
+ * @param {function(Event):(boolean|undefined)} fn The function to call
+ *     on the event. The function takes one parameter: the event object.
  * @private
- * Remove an event handler. This smooths a difference between IE and the rest of
- * the world.
- * @param { DOM element } elem The element to add the event to.
- * @param { String } type The type of the event, e.g. 'click' or 'mousemove'.
- * @param { Function } fn The function to call on the event. The function takes
- * one parameter: the event object.
  */
 Dygraph.removeEvent = function addEvent(elem, type, fn) {
   if (elem.removeEventListener) {
@@ -188,12 +212,12 @@ Dygraph.removeEvent = function addEvent(elem, type, fn) {
 };
 
 /**
- * @private
  * Cancels further processing of an event. This is useful to prevent default
  * browser actions, e.g. highlighting text on a double-click.
  * Based on the article at
  * http://www.switchonthecode.com/tutorials/javascript-tutorial-the-scroll-wheel
- * @param { Event } e The event whose normal behavior should be canceled.
+ * @param { !Event } e The event whose normal behavior should be canceled.
+ * @private
  */
 Dygraph.cancelEvent = function(e) {
   e = e ? e : window.event;
@@ -213,10 +237,10 @@ Dygraph.cancelEvent = function(e) {
  * Convert hsv values to an rgb(r,g,b) string. Taken from MochiKit.Color. This
  * is used to generate default series colors which are evenly spaced on the
  * color wheel.
- * @param { Number } hue Range is 0.0-1.0.
- * @param { Number } saturation Range is 0.0-1.0.
- * @param { Number } value Range is 0.0-1.0.
- * @return { String } "rgb(r,g,b)" where r, g and b range from 0-255.
+ * @param { number } hue Range is 0.0-1.0.
+ * @param { number } saturation Range is 0.0-1.0.
+ * @param { number } value Range is 0.0-1.0.
+ * @return { string } "rgb(r,g,b)" where r, g and b range from 0-255.
  * @private
  */
 Dygraph.hsvToRGB = function (hue, saturation, value) {
@@ -257,6 +281,9 @@ Dygraph.hsvToRGB = function (hue, saturation, value) {
 /**
  * Find the x-coordinate of the supplied object relative to the left side
  * of the page.
+ * TODO(danvk): change obj type from Node -&gt; !Node
+ * @param {Node} obj
+ * @return {number}
  * @private
  */
 Dygraph.findPosX = function(obj) {
@@ -284,6 +311,10 @@ Dygraph.findPosX = function(obj) {
 /**
  * Find the y-coordinate of the supplied object relative to the top of the
  * page.
+ * TODO(danvk): change obj type from Node -&gt; !Node
+ * TODO(danvk): consolidate with findPosX and return an {x, y} object.
+ * @param {Node} obj
+ * @return {number}
  * @private
  */
 Dygraph.findPosY = function(obj) {
@@ -309,16 +340,18 @@ Dygraph.findPosY = function(obj) {
 };
 
 /**
- * @private
  * Returns the x-coordinate of the event in a coordinate system where the
  * top-left corner of the page (not the window) is (0,0).
  * Taken from MochiKit.Signal
+ * @param {!Event} e
+ * @return {number}
+ * @private
  */
 Dygraph.pageX = function(e) {
   if (e.pageX) {
     return (!e.pageX || e.pageX < 0) ? 0 : e.pageX;
   } else {
-    var de = document;
+    var de = document.documentElement;
     var b = document.body;
     return e.clientX +
         (de.scrollLeft || b.scrollLeft) -
@@ -327,16 +360,18 @@ Dygraph.pageX = function(e) {
 };
 
 /**
- * @private
  * Returns the y-coordinate of the event in a coordinate system where the
  * top-left corner of the page (not the window) is (0,0).
  * Taken from MochiKit.Signal
+ * @param {!Event} e
+ * @return {number}
+ * @private
  */
 Dygraph.pageY = function(e) {
   if (e.pageY) {
     return (!e.pageY || e.pageY < 0) ? 0 : e.pageY;
   } else {
-    var de = document;
+    var de = document.documentElement;
     var b = document.body;
     return e.clientY +
         (de.scrollTop || b.scrollTop) -
@@ -345,25 +380,27 @@ Dygraph.pageY = function(e) {
 };
 
 /**
+ * This returns true unless the parameter is 0, null, undefined or NaN.
+ * TODO(danvk): rename this function to something like 'isNonZeroNan'.
+ *
+ * @param {number} x The number to consider.
+ * @return {boolean} Whether the number is zero or NaN.
  * @private
- * @param { Number } x The number to consider.
- * @return { Boolean } Whether the number is zero or NaN.
  */
-// TODO(danvk): rename this function to something like 'isNonZeroNan'.
-// TODO(danvk): determine when else this returns false (e.g. for undefined or null)
 Dygraph.isOK = function(x) {
-  return x && !isNaN(x);
+  return !!x && !isNaN(x);
 };
 
 /**
+ * @param { {x:?number,y:?number,yval:?number} } p The point to consider, valid
+ *     points are {x, y} objects
+ * @param { boolean } allowNaNY Treat point with y=NaN as valid
+ * @return { boolean } Whether the point has numeric x and y.
  * @private
- * @param { Object } p The point to consider, valid points are {x, y} objects
- * @param { Boolean } allowNaNY Treat point with y=NaN as valid
- * @return { Boolean } Whether the point has numeric x and y.
  */
 Dygraph.isValidPoint = function(p, allowNaNY) {
-  if (!p) return false; // null or undefined object
-  if (p.yval === null) return false; // missing point
+  if (!p) return false;  // null or undefined object
+  if (p.yval === null) return false;  // missing point
   if (p.x === null || p.x === undefined) return false;
   if (p.y === null || p.y === undefined) return false;
   if (isNaN(p.x) || (!allowNaNY && isNaN(p.y))) return false;
@@ -383,9 +420,9 @@ Dygraph.isValidPoint = function(p, allowNaNY) {
  * 10^-6, e.g. '0.00001' instead of '1e-5'. See tests/number-format.html for
  * output examples.
  *
- * @param {Number} x The number to format
- * @param {Number} opt_precision The precision to use, default 2.
- * @return {String} A string formatted like %g in printf.  The max generated
+ * @param {number} x The number to format
+ * @param {number=} opt_precision The precision to use, default 2.
+ * @return {string} A string formatted like %g in printf.  The max generated
  *                  string length should be precision + 6 (e.g 1.123e+300).
  */
 Dygraph.floatFormat = function(x, opt_precision) {
@@ -413,8 +450,10 @@ Dygraph.floatFormat = function(x, opt_precision) {
 };
 
 /**
- * @private
  * Converts '9' to '09' (useful for dates)
+ * @param {number} x
+ * @return {string}
+ * @private
  */
 Dygraph.zeropad = function(x) {
   if (x < 10) return "0" + x; else return "" + x;
@@ -422,8 +461,9 @@ Dygraph.zeropad = function(x) {
 
 /**
  * Return a string version of the hours, minutes and seconds portion of a date.
- * @param {Number} date The JavaScript date (ms since epoch)
- * @return {String} A time of the form "HH:MM:SS"
+ *
+ * @param {number} date The JavaScript date (ms since epoch)
+ * @return {string} A time of the form "HH:MM:SS"
  * @private
  */
 Dygraph.hmsString_ = function(date) {
@@ -440,9 +480,9 @@ Dygraph.hmsString_ = function(date) {
 
 /**
  * Round a number to the specified number of digits past the decimal point.
- * @param {Number} num The number to round
- * @param {Number} places The number of decimals to which to round
- * @return {Number} The rounded number
+ * @param {number} num The number to round
+ * @param {number} places The number of decimals to which to round
+ * @return {number} The rounded number
  * @private
  */
 Dygraph.round_ = function(num, places) {
@@ -451,16 +491,17 @@ Dygraph.round_ = function(num, places) {
 };
 
 /**
- * @private
  * Implementation of binary search over an array.
  * Currently does not work when val is outside the range of arry's values.
- * @param { Integer } val the value to search for
- * @param { Integer[] } arry is the value over which to search
- * @param { Integer } abs 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.
- * @param { Integer } [low] The first index in arry to consider (optional)
- * @param { Integer } [high] The last index in arry to consider (optional)
+ * @param {number} val the value to search for
+ * @param {Array.<number>} arry is the value over which to search
+ * @param {number} abs 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.
+ * @param {number=} low The first index in arry to consider (optional)
+ * @param {number=} high The last index in arry to consider (optional)
+ * @return {number} Index of the element, or -1 if it isn't found.
+ * @private
  */
 Dygraph.binarySearch = function(val, arry, abs, low, high) {
   if (low === null || low === undefined ||
@@ -479,12 +520,10 @@ Dygraph.binarySearch = function(val, arry, abs, low, high) {
   };
   var mid = parseInt((low + high) / 2, 10);
   var element = arry[mid];
+  var idx;
   if (element == val) {
     return mid;
-  }
-
-  var idx;
-  if (element > val) {
+  } else if (element > val) {
     if (abs > 0) {
       // Accept if element > val, but also if prior element < val.
       idx = mid - 1;
@@ -493,8 +532,7 @@ Dygraph.binarySearch = function(val, arry, abs, low, high) {
       }
     }
     return Dygraph.binarySearch(val, arry, abs, low, mid - 1);
-  }
-  if (element < val) {
+  } else if (element < val) {
     if (abs < 0) {
       // Accept if element < val, but also if prior element > val.
       idx = mid + 1;
@@ -504,15 +542,17 @@ Dygraph.binarySearch = function(val, arry, abs, low, high) {
     }
     return Dygraph.binarySearch(val, arry, abs, mid + 1, high);
   }
+  return -1;  // can't actually happen, but makes closure compiler happy
 };
 
 /**
- * @private
  * Parses a date, returning the number of milliseconds since epoch. This can be
  * passed in as an xValueParser in the Dygraph constructor.
  * TODO(danvk): enumerate formats that this understands.
- * @param {String} A date in YYYYMMDD format.
- * @return {Number} Milliseconds since epoch.
+ *
+ * @param {string} dateStr A date in a variety of possible string formats.
+ * @return {number} Milliseconds since epoch.
+ * @private
  */
 Dygraph.dateParser = function(dateStr) {
   var dateStrSlashed;
@@ -554,12 +594,12 @@ Dygraph.dateParser = function(dateStr) {
 };
 
 /**
- * @private
  * This is identical to JavaScript's built-in Date.parse() method, except that
  * it doesn't get replaced with an incompatible method by aggressive JS
  * libraries like MooTools or Joomla.
- * @param { String } str The date string, e.g. "2011/05/06"
- * @return { Integer } millis since epoch
+ * @param {string} str The date string, e.g. "2011/05/06"
+ * @return {number} millis since epoch
+ * @private
  */
 Dygraph.dateStrToMillis = function(str) {
   return new Date(str).getTime();
@@ -569,9 +609,12 @@ Dygraph.dateStrToMillis = function(str) {
 /**
  * Copies all the properties from o to self.
  *
+ * @param {!Object} self
+ * @param {!Object} o
+ * @return {!Object}
  * @private
  */
-Dygraph.update = function (self, o) {
+Dygraph.update = function(self, o) {
   if (typeof(o) != 'undefined' && o !== null) {
     for (var k in o) {
       if (o.hasOwnProperty(k)) {
@@ -585,6 +628,9 @@ Dygraph.update = function (self, o) {
 /**
  * Copies all the properties from o to self.
  *
+ * @param {!Object} self
+ * @param {!Object} o
+ * @return {!Object}
  * @private
  */
 Dygraph.updateDeep = function (self, o) {
@@ -621,9 +667,11 @@ Dygraph.updateDeep = function (self, o) {
 };
 
 /**
+ * @param {Object} o
+ * @return {boolean}
  * @private
  */
-Dygraph.isArrayLike = function (o) {
+Dygraph.isArrayLike = function(o) {
   var typ = typeof(o);
   if (
       (typ != 'object' && !(typ == 'function' &&
@@ -638,6 +686,8 @@ Dygraph.isArrayLike = function (o) {
 };
 
 /**
+ * @param {Object} o
+ * @return {boolean}
  * @private
  */
 Dygraph.isDateLike = function (o) {
@@ -650,6 +700,8 @@ Dygraph.isDateLike = function (o) {
 
 /**
  * Note: this only seems to work for arrays.
+ * @param {!Array} o
+ * @return {!Array}
  * @private
  */
 Dygraph.clone = function(o) {
@@ -666,30 +718,43 @@ Dygraph.clone = function(o) {
 };
 
 /**
- * @private
  * Create a new canvas element. This is more complex than a simple
  * document.createElement("canvas") because of IE and excanvas.
+ *
+ * @return {!HTMLCanvasElement}
+ * @private
  */
 Dygraph.createCanvas = function() {
   var canvas = document.createElement("canvas");
 
   var isIE = (/MSIE/.test(navigator.userAgent) && !window.opera);
   if (isIE && (typeof(G_vmlCanvasManager) != 'undefined')) {
-    canvas = G_vmlCanvasManager.initElement(canvas);
+    canvas = G_vmlCanvasManager.initElement(
+        /**@type{!HTMLCanvasElement}*/(canvas));
   }
 
   return canvas;
 };
 
 /**
- * @private
  * Checks whether the user is on an Android browser.
  * Android does not fully support the <canvas> tag, e.g. w/r/t/ clipping.
+ * @return {boolean}
+ * @private
  */
 Dygraph.isAndroid = function() {
   return (/Android/).test(navigator.userAgent);
 };
 
+
+/**
+ * TODO(danvk): use @template here when it's better supported for classes.
+ * @param {!Array} array
+ * @param {number} start
+ * @param {number} length
+ * @param {function(!Array,?):boolean=} predicate
+ * @constructor
+ */
 Dygraph.Iterator = function(array, start, length, predicate) {
   start = start || 0;
   length = length || array.length;
@@ -703,6 +768,9 @@ Dygraph.Iterator = function(array, start, length, predicate) {
   this.next(); // ignoring result.
 };
 
+/**
+ * @return {Object}
+ */
 Dygraph.Iterator.prototype.next = function() {
   if (!this.hasNext) {
     return null;
@@ -728,34 +796,33 @@ Dygraph.Iterator.prototype.next = function() {
 };
 
 /**
- * @private
  * Returns a new iterator over array, between indexes start and 
  * start + length, and only returns entries that pass the accept function
  *
- * @param array the array to iterate over.
- * @param start the first index to iterate over, 0 if absent.
- * @param length the number of elements in the array to iterate over.
- * This, along with start, defines a slice of the array, and so length
- * doesn't imply the number of elements in the iterator when accept
- * doesn't always accept all values. array.length when absent.
- * @param predicate a function that takes parameters array and idx, which
- * returns true when the element should be returned. If omitted, all
- * elements are accepted.
+ * @param {!Array} array the array to iterate over.
+ * @param {number} start the first index to iterate over, 0 if absent.
+ * @param {number} length the number of elements in the array to iterate over.
+ *     This, along with start, defines a slice of the array, and so length
+ *     doesn't imply the number of elements in the iterator when accept doesn't
+ *     always accept all values. array.length when absent.
+ * @param {function(?):boolean=} opt_predicate a function that takes
+ *     parameters array and idx, which returns true when the element should be
+ *     returned.  If omitted, all elements are accepted.
+ * @private
  */
-Dygraph.createIterator = function(array, start, length, predicate) {
-  return new Dygraph.Iterator(array, start, length, predicate);
+Dygraph.createIterator = function(array, start, length, opt_predicate) {
+  return new Dygraph.Iterator(array, start, length, opt_predicate);
 };
 
 /**
- * @private
  * Call a function N times at a given interval, then call a cleanup function
  * once. repeat_fn is called once immediately, then (times - 1) times
  * asynchronously. If times=1, then cleanup_fn() is also called synchronously.
- * @param repeat_fn {Function} Called repeatedly -- takes the number of calls
- * (from 0 to times-1) as an argument.
- * @param times {number} The number of times to call repeat_fn
- * @param every_ms {number} Milliseconds between calls
- * @param cleanup_fn {Function} A function to call after all repeat_fn calls.
+ * @param {function(number)} repeat_fn Called repeatedly -- takes the number of
+ *     calls (from 0 to times-1) as an argument.
+ * @param {number} times The number of times to call repeat_fn
+ * @param {number} every_ms Milliseconds between calls
+ * @param {function()} cleanup_fn A function to call after all repeat_fn calls.
  * @private
  */
 Dygraph.repeatAndCleanup = function(repeat_fn, times, every_ms, cleanup_fn) {
@@ -784,11 +851,12 @@ Dygraph.repeatAndCleanup = function(repeat_fn, times, every_ms, cleanup_fn) {
 };
 
 /**
- * @private
  * This function will scan the option list and determine if they
  * require us to recalculate the pixel positions of each point.
- * @param { List } a list of options to check.
- * @return { Boolean } true if the graph needs new points else false.
+ * @param {!Array.<string>} labels a list of options to check.
+ * @param {!Object} attrs 
+ * @return {boolean} true if the graph needs new points else false.
+ * @private
  */
 Dygraph.isPixelChangingOptionList = function(labels, attrs) {
   // A whitelist of options that do not change pixel positions.
@@ -892,9 +960,10 @@ Dygraph.isPixelChangingOptionList = function(labels, attrs) {
  * Compares two arrays to see if they are equal. If either parameter is not an
  * array it will return false. Does a shallow compare 
  * Dygraph.compareArrays([[1,2], [3, 4]], [[1,2], [3,4]]) === false.
- * @param array1 first array
- * @param array2 second array
- * @return True if both parameters are arrays, and contents are equal.
+ * @param {!Array.<T>} array1 first array
+ * @param {!Array.<T>} array2 second array
+ * @return {boolean} True if both parameters are arrays, and contents are equal.
+ * @template T
  */
 Dygraph.compareArrays = function(array1, array2) {
   if (!Dygraph.isArrayLike(array1) || !Dygraph.isArrayLike(array2)) {
@@ -912,19 +981,20 @@ Dygraph.compareArrays = function(array1, array2) {
 };
 
 /**
- * ctx: the canvas context
- * sides: the number of sides in the shape.
- * radius: the radius of the image.
- * cx: center x coordate
- * cy: center y coordinate
- * rotationRadians: the shift of the initial angle, in radians.
- * delta: the angle shift for each line. If missing, creates a regular
- *   polygon.
+ * @param {!CanvasRenderingContext2D} ctx the canvas context
+ * @param {number} sides the number of sides in the shape.
+ * @param {number} radius the radius of the image.
+ * @param {number} cx center x coordate
+ * @param {number} cy center y coordinate
+ * @param {number=} rotationRadians the shift of the initial angle, in radians.
+ * @param {number=} delta the angle shift for each line. If missing, creates a
+ *     regular polygon.
+ * @private
  */
 Dygraph.regularShape_ = function(
     ctx, sides, radius, cx, cy, rotationRadians, delta) {
-  rotationRadians = rotationRadians ? rotationRadians : 0;
-  delta = delta ? delta : Math.PI * 2 / sides;
+  rotationRadians = rotationRadians || 0;
+  delta = delta || Math.PI * 2 / sides;
 
   ctx.beginPath();
   var first = true;
@@ -951,6 +1021,14 @@ Dygraph.regularShape_ = function(
   ctx.stroke();
 };
 
+/**
+ * TODO(danvk): be more specific on the return type.
+ * @param {number} sides
+ * @param {number=} rotationRadians
+ * @param {number=} delta
+ * @return {Function}
+ * @private
+ */
 Dygraph.shapeFunction_ = function(sides, rotationRadians, delta) {
   return function(g, name, ctx, cx, cy, color, radius) {
     ctx.strokeStyle = color;
@@ -959,10 +1037,6 @@ Dygraph.shapeFunction_ = function(sides, rotationRadians, delta) {
   };
 };
 
-Dygraph.DrawPolygon_ = function(sides, rotationRadians, ctx, cx, cy, color, radius, delta) {
-  new Dygraph.RegularShape_(sides, rotationRadians, delta).draw(ctx, cx, cy, radius);
-};
-
 Dygraph.Circles = {
   DEFAULT : function(g, name, ctx, canvasx, canvasy, color, radius) {
     ctx.beginPath();
@@ -1039,10 +1113,10 @@ Dygraph.Circles = {
  *   window.addEventListener('mouseup', mouseUpHandler);
  * };
  * 
- *
  * @constructor
  */
 Dygraph.IFrameTarp = function() {
+  /** @type {Array.<!HTMLDivElement>} */
   this.tarps = [];
 };
 
@@ -1084,7 +1158,7 @@ Dygraph.IFrameTarp.prototype.uncover = function() {
 /**
  * Determine whether |data| is delimited by CR, CRLF, LF, LFCR.
  * @param {string} data
- * @return {string|null} the delimiter that was detected.
+ * @return {?string} the delimiter that was detected (or null on failure).
  */
 Dygraph.detectLineDelimiter = function(data) {
   for (var i = 0; i < data.length; i++) {
index 42761cf..b2ac6bd 100644 (file)
@@ -355,6 +355,10 @@ Dygraph.prototype.__init__ = function(div, file, attrs) {
 
   attrs = Dygraph.mapLegacyOptions_(attrs);
 
+  if (typeof(div) == 'string') {
+    div = document.getElementById(div);
+  }
+
   if (!div) {
     Dygraph.error("Constructing dygraph with a non-existent div!");
     return;
@@ -569,7 +573,12 @@ Dygraph.prototype.attr_ = function(name, seriesName) {
     Dygraph.OPTIONS_REFERENCE[name] = true;
   }
 // </REMOVE_FOR_COMBINED>
+<<<<<<< HEAD
   return seriesName ? this.attributes_.findForSeries(name, seriesName) : this.attributes_.find(name);
+=======
+
+  return seriesName ? this.attributes_.getForSeries(name, seriesName) : this.attributes_.get(name);
+>>>>>>> 5daa462d93e850a64a7f6644afb8122336ccf84d
 };
 
 /**
@@ -1648,7 +1657,7 @@ Dygraph.prototype.findClosestPoint = function(domX, domY) {
   var minDist = Infinity;
   var idx = -1;
   var dist, dx, dy, point, closestPoint, closestSeries;
-  for (var setIdx = 0; setIdx < this.layout_.datasets.length; ++setIdx) {
+  for ( var setIdx = this.layout_.datasets.length - 1 ; setIdx >= 0 ; --setIdx ) {
     var points = this.layout_.points[setIdx];
     for (var i = 0; i < points.length; ++i) {
       var point = points[i];
@@ -1749,7 +1758,7 @@ Dygraph.prototype.mouseMove_ = function(event) {
 
   var highlightSeriesOpts = this.attr_("highlightSeriesOpts");
   var selectionChanged = false;
-  if (highlightSeriesOpts && !this.lockedSet_) {
+  if (highlightSeriesOpts && !this.isSeriesLocked()) {
     var closest;
     if (this.attr_("stackedGraph")) {
       closest = this.findStackedPoint(canvasx, canvasy);
@@ -2042,6 +2051,14 @@ Dygraph.prototype.getHighlightSeries = function() {
 };
 
 /**
+ * Returns true if the currently-highlighted series was locked
+ * via setSelection(..., seriesName, true).
+ */
+Dygraph.prototype.isSeriesLocked = function() {
+  return this.lockedSet_;
+};
+
+/**
  * Fires when there's data available to be graphed.
  * @param {String} data Raw CSV data to be plotted
  * @private
index 27a6458..2fdd1cf 100644 (file)
@@ -27,19 +27,6 @@ var getData = function(numSeries, numRows, isStacked) {
   return data;
 };
 
-var makeClickCallback = function(graph) {
-  var isLocked = false;
-  return function(ev) {
-    if (isLocked) {
-      graph.clearSelection();
-      isLocked = false;
-    } else {
-      graph.setSelection(graph.getSelection(), graph.getHighlightSeries(), true);
-      isLocked = true;
-    }
-  };
-};
-
 var makeGraph = function(className, numSeries, numRows, isStacked) {
   var demo = document.getElementById('demo');
   var div = document.createElement('div');
@@ -73,7 +60,14 @@ var makeGraph = function(className, numSeries, numRows, isStacked) {
           highlightCircleSize: 5,
         },
       });
-  g.updateOptions({clickCallback: makeClickCallback(g)}, true);
+  var onclick = function(ev) {
+    if (g.isSeriesLocked()) {
+      g.clearSelection();
+    } else {
+      g.setSelection(g.getSelection(), g.getHighlightSeries(), true);
+    }
+  };
+  g.updateOptions({clickCallback: onclick}, true);
   g.setSelection(false, 's005');
   //console.log(g);
 };
diff --git a/lint.sh b/lint.sh
index c316a72..a45d901 100755 (executable)
--- a/lint.sh
+++ b/lint.sh
@@ -19,7 +19,7 @@ if [ $# -gt 1 ]; then
 fi
 
 if [ $# -eq 0 ]; then
-  files=$(ls dygraph*.js plugins/*.js | grep -v combined | grep -v dev.js)
+  files=$(ls dygraph*.js plugins/*.js | grep -v combined | grep -v dev.js| grep -v externs)
 else
   files=$1
 fi