Merge pull request #250 from wimme/patch-4
authorRobert Konigsberg <konigsberg@gmail.com>
Thu, 6 Jun 2013 02:11:44 +0000 (19:11 -0700)
committerRobert Konigsberg <konigsberg@gmail.com>
Thu, 6 Jun 2013 02:11:44 +0000 (19:11 -0700)
LogScale and customBars with negative values

14 files changed:
auto_tests/misc/fake-jstestdriver.js
auto_tests/misc/local.html
auto_tests/misc/local.js [new file with mode: 0644]
auto_tests/tests/error_bars.js
auto_tests/tests/grid_per_axis.js
auto_tests/tests/simple_drawing.js
dygraph-layout.js
dygraph-utils.js
dygraph.js
extras/unzoom.js
phantom-driver.js
plugins/annotations.js
plugins/range-selector.js
test.sh

index 6f4f464..772e10a 100644 (file)
  * @author konigsberg@google.com (Robert Konigsberg)
  */
 var jstestdriver = {
-  jQuery : jQuery
+  jQuery : jQuery,
+  listeners_ : [],
+  announce_ : function(name, args) {
+    for (var idx = 0; idx < jstestdriver.listeners_.length; idx++) {
+      var listener = jstestdriver.listeners_[idx];
+      if (listener[name]) {
+        listener[name].apply(null, args);
+      }
+    }
+  },
+  attachListener: function(listener) {
+    jstestdriver.listeners_.push(listener);
+  }
 };
 
 if (!console) {
@@ -55,6 +67,7 @@ function TestCase(name) {
 
   testCase.prototype.setUp = function() { };
   testCase.prototype.tearDown = function() { };
+  testCase.prototype.name = name;
   /**
    * name can be a string, which is looked up in this object, or it can be a
    * function, in which case it's run.
@@ -68,29 +81,35 @@ function TestCase(name) {
    * Chrome's console completion.
    */
   testCase.prototype.runTest = function(func) {
+    var result = false;
+    var ex = null;
+    var name = typeof(func) == "string" ? func : "(anonymous function)";
+    jstestdriver.announce_("start", [this, name]);
     try {
-      this.setUp();
-
-      var fn = null;
-      var parameterType = typeof(func);
-      if (typeof(func) == "function") {
-        fn = func;
-      } else if (typeof(func) == "string") {
-        fn = this[func];
-      } else {
-        fail("can't supply " + typeof(func) + " to runTest");
-      }
-
-      fn.apply(this, []);
-      this.tearDown();
-      return true;
+      result = this.runTest_(func);
     } catch (e) {
-      console.log(e);
-      if (e.stack) {
-        console.log(e.stack);
-      }
-      return false;
+      ex = e;
     }
+    jstestdriver.announce_("finish", [this, name, result, ex]);
+    return result; // TODO(konigsberg): Remove this, and return value from runAllTests.
+  }
+
+  testCase.prototype.runTest_ = function(func) {
+    this.setUp();
+
+    var fn = null;
+    var parameterType = typeof(func);
+    if (typeof(func) == "function") {
+      fn = func;
+    } else if (typeof(func) == "string") {
+      fn = this[func];
+    } else {
+      fail("can't supply " + typeof(func) + " to runTest");
+    }
+
+    fn.apply(this, []);
+    this.tearDown();
+    return true;
   };
 
   testCase.prototype.runAllTests = function() {
@@ -152,3 +171,15 @@ function addGlobalTestSymbols() {
 function getAllTestCases() {
   return testCaseList;
 }
+
+jstestdriver.attachListener({
+  finish : function(tc, name, result, e) {
+    if (e) {
+      console.log(e);
+      if (e.stack) {
+        console.log(e.stack);
+      }
+    }
+  }
+});
+
index e168de0..6950a0a 100644 (file)
@@ -17,6 +17,7 @@
   <script type="text/javascript" src="../tests/DygraphOps.js"></script>
   <script type="text/javascript" src="../tests/PixelSampler.js"></script>
   <script type="text/javascript" src="../tests/Util.js"></script>
+  <script type="text/javascript" src="local.js"></script>
 
   <!-- Scripts for automated tests -->
   <script type="text/javascript" src="../tests/annotations.js"></script>
     color: black;
     text-decoration: none;
   }
-</style>
-  <script type="text/javascript">
-
-  // save Dygraph.warn so we can catch warnings.
-  if (false) { // Set true if you want warnings to cause failures.
-    var originalDygraphWarn = Dygraph.warn;
-    Dygraph.warn = function(msg) {
-      if (msg == "Using default labels. Set labels explicitly via 'labels' in the options parameter") {
-        originalDygraphWarn(msg);
-        return;
-      }
-      throw "Warnings not permitted: " + msg;
-    }
-    Dygraph.prototype.warn = Dygraph.warn;
-  }
-
-  var tc = null; // Selected test case
-  var name = null; 
-
-  var resultDiv = null;
-
-  function processVariables() {
-    var splitVariables = function() { // http://www.idealog.us/2006/06/javascript_to_p.html
-      var query = window.location.search.substring(1); 
-      var args = {};
-      var vars = query.split("&"); 
-      for (var i = 0; i < vars.length; i++) { 
-        if (vars[i].length > 0) {
-          var pair = vars[i].split("="); 
-          args[pair[0]] = pair[1];
-        }
-      }
-      return args;
-    }
-
-    var args = splitVariables();
-    var test = args.test;
-    var command = args.command;
-
-    // args.testCaseName uses the string name of the test.
-    if (args.testCaseName) {
-      var testCases = getAllTestCases();
-      name = args.testCaseName;
-      for (var idx in testCases) {
-        var entry = testCases[idx];
-        if (entry.name == args.testCaseName) {
-          var prototype = entry.testCase;
-          tc = new entry.testCase();
-          break;
-        }
-      }
-    } else if (args.testCase) { // The class name of the test.
-      name = args.testCase;
-      eval("tc = new " + args.testCase + "()");
-    }
-
-    var results = null;
-    // If the test class is defined.
-    if (tc != null) {
-      if (args.command == "runAllTests") {
-        console.log("Running all tests for " + args.testCase);
-        results = tc.runAllTests();
-      } else if (args.command == "runTest") {
-        console.log("Running test " + args.testCase + "." + args.test);
-        results = tc.runTest(args.test);
-      }
-    } else {
-      if (args.command == "runAllTests") {
-        console.log("Running all tests for all test cases");
-        var testCases = getAllTestCases();
-        results = {};
-        for (var idx in testCases) {
-          var entry = testCases[idx];
-          var prototype = entry.testCase;
-          tc = new entry.testCase();
-          results[entry.name] = tc.runAllTests();
-        }
-      }
-    }
-    resultsDiv = createResultsDiv();
-    var summary = { failed: 0, passed: 0 };
-    postResults(results, summary);
-    resultsDiv.appendChild(document.createElement("hr"));
-    document.getElementById('summary').innerHTML = "(" + summary.failed + " failed, " + summary.passed + " passed)";
-  }
-
-  function createResultsDiv() {
-    var body = document.getElementsByTagName("body")[0];
-    div = document.createElement("div");
-    div.id='results';
-    div.innerHTML = "Test results: <span id='summary'></span> <a href='#' id='passed'>passed</a> <a href='#' id='failed'>failed</a> <a href='#' id='all'>all</a><br/>";
-    body.insertBefore(div, body.firstChild);
-
-    var setByClassName = function(name, displayStyle) {
-      var elements = div.getElementsByClassName(name);
-      for (var i = 0; i < elements.length; i++) {
-        elements[i].style.display = displayStyle;
-      }
-    }
 
-    var passedAnchor = document.getElementById('passed');
-    var failedAnchor = document.getElementById('failed');
-    var allAnchor = document.getElementById('all');
-    passedAnchor.onclick = function() {
-      setByClassName('fail', 'none');
-      setByClassName('pass', 'block');
-
-      passedAnchor.setAttribute("class", 'activeAnchor');
-      failedAnchor.setAttribute("class", '');
-    };
-    failedAnchor.onclick = function() {
-      setByClassName('fail', 'block');
-      setByClassName('pass', 'none');
-      passedAnchor.setAttribute("class", '');
-      failedAnchor.setAttribute("class", 'activeAnchor');
-    };
-    allAnchor.onclick = function() {
-      setByClassName('fail', 'block');
-      setByClassName('pass', 'block');
-      passedAnchor.setAttribute("class", '');
-      failedAnchor.setAttribute("class", '');
-    };
-    return div;
-  }
-
-  function postResults(results, summary, title) {
-    if (typeof(results) == "boolean") {
-      var elem = document.createElement("div");
-      elem.setAttribute("class", results ? 'pass' : 'fail');
-
-      var prefix = title ? (title + ": ") : "";
-      elem.innerHTML = prefix + '<span class=\'outcome\'>' + (results ? 'pass' : 'fail') + '</span>';
-      resultsDiv.appendChild(elem);
-      if (results) {
-        summary.passed++;
-      } else {
-        summary.failed++;
-      }
-    } else { // hash
-      var failed = 0;
-      var html = "";
-      for (var key in results) {
-        if (results.hasOwnProperty(key)) {
-          var elem = results[key];
-          if (typeof(elem) == "boolean" && title) {
-            postResults(results[key], summary, title + "." + key);
-          } else {
-            postResults(results[key], summary, key);
-          }
-        }
-      }
-    }
+  .anchor:hover {
+    color:blue;
   }
-
-  </script>
+</style>
 </head>
 <body>
   <div id='graph'></div>
   Example: <code>local.html?testCase=ScrollingDivTestCase&test=testNestedDiv_Scrolled&command=runTest</code>
   <p/>
 </body>
-<script>
-processVariables();
-addGlobalTestSymbols();
-
-var selector = document.getElementById("selector");
-
-if (selector != null) { // running a test
-  var createAttached = function(name, parent) {
-    var elem = document.createElement(name);
-    parent.appendChild(elem);
-    return elem;
-  }
-
-  var description = createAttached("div", selector);
-  var list = createAttached("ul", selector);
-  var parent = list.parentElement;
-  var createLink = function(parent, text, url) {
-    var li = createAttached("li", parent);
-    var a = createAttached("a", li);
-    a.innerHTML = text;
-    a.href = url;
-  }
-  if (tc == null) {
-    description.innerHTML = "Test cases:";
-    var testCases = getAllTestCases();
-    createLink(list, "(run all tests)", document.URL + "?command=runAllTests");
-    for (var idx in testCases) {
-      var entryName = testCases[idx].name;
-      createLink(list, entryName, document.URL + "?testCaseName=" + entryName);
-    }
-  } else {
-    description.innerHTML = "Tests for " + name;
-    var names = tc.getTestNames();
-    createLink(list, "Run All Tests", document.URL + "&command=runAllTests");
-    for (var idx in names) {
-      var name = names[idx];
-      createLink(list, name, document.URL + "&test=" + name + "&command=runTest");
-    }
-  }
-}
+<script type="text/javascript">
+  var tester = new DygraphsLocalTester();
+  // tester.overrideWarn(); // uncomment if you want warnings to be errors.
+  tester.processVariables();
+  addGlobalTestSymbols();
+  tester.run();
 </script>
 </html>
diff --git a/auto_tests/misc/local.js b/auto_tests/misc/local.js
new file mode 100644 (file)
index 0000000..39a3cb5
--- /dev/null
@@ -0,0 +1,248 @@
+var DygraphsLocalTester = function() {
+  this.tc = null; // Selected test case
+  this.name = null; 
+  this.resultsDiv = null;
+  this.results = [];
+  this.summary = { failed: 0, passed: 0 };
+
+  var self = this;
+  jstestdriver.attachListener({
+    start : function(tc) {
+      self.start_(tc);
+    },
+    finish : function(tc, name, result, e) {
+      self.finish_(tc, name, result, e);
+    }
+  });
+};
+
+/**
+ * Call this to replace Dygraphs.warn so it throws an error.
+ *
+ * In some cases we will still allow warnings to be warnings, however.
+ */
+DygraphsLocalTester.prototype.overrideWarn = function() {
+  // save Dygraph.warn so we can catch warnings.
+  var originalDygraphWarn = Dygraph.warn;
+  Dygraph.warn = function(msg) {
+    // This warning is still
+    if (msg == "Using default labels. Set labels explicitly via 'labels' in the options parameter") {
+      originalDygraphWarn(msg);
+      return;
+    }
+    throw "Warnings not permitted: " + msg;
+  }
+  Dygraph.prototype.warn = Dygraph.warn;
+};
+
+DygraphsLocalTester.prototype.processVariables = function() {
+  var splitVariables = function() { // http://www.idealog.us/2006/06/javascript_to_p.html
+    var query = window.location.search.substring(1); 
+    var args = {};
+    var vars = query.split("&"); 
+    for (var i = 0; i < vars.length; i++) { 
+      if (vars[i].length > 0) {
+        var pair = vars[i].split("="); 
+        args[pair[0]] = pair[1];
+      }
+    }
+    return args;
+  }
+
+  var args = splitVariables();
+  var test = args.test;
+  var command = args.command;
+
+  // args.testCaseName uses the string name of the test.
+  if (args.testCaseName) {
+    var testCases = getAllTestCases();
+    name = args.testCaseName;
+    for (var idx in testCases) {
+      var entry = testCases[idx];
+      if (entry.name == args.testCaseName) {
+        var prototype = entry.testCase;
+        this.tc = new entry.testCase();
+        break;
+      }
+    }
+  } else if (args.testCase) { // The class name of the test.
+    name = args.testCase;
+    eval("tc__= new " + args.testCase + "()");
+    this.tc = tc_;
+  }
+
+  // If the test class is defined.
+  if (this.tc != null) {
+    if (args.command == "runAllTests") {
+      console.log("Running all tests for " + args.testCase);
+      this.tc.runAllTests();
+    } else if (args.command == "runTest") {
+      console.log("Running test " + args.testCase + "." + args.test);
+      this.tc.runTest(args.test);
+    }
+  } else {
+    if (args.command == "runAllTests") {
+      console.log("Running all tests for all test cases");
+      var testCases = getAllTestCases();
+      for (var idx in testCases) {
+        var entry = testCases[idx];
+        var prototype = entry.testCase;
+        this.tc = new entry.testCase();
+        this.tc.runAllTests();
+      }
+    }
+  }
+  this.resultsDiv = this.createResultsDiv();
+  this.postResults();
+  this.resultsDiv.appendChild(document.createElement("hr"));
+  document.getElementById('summary').innerHTML = "(" + this.summary.failed + " failed, " + this.summary.passed + " passed)";
+}
+
+DygraphsLocalTester.prototype.createResultsDiv = function() {
+  div = document.createElement("div");
+  div.id='results';
+  div.innerHTML = "Test results: <span id='summary'></span> <a href='#' id='passed'>passed</a> <a href='#' id='failed'>failed</a> <a href='#' id='all'>all</a><br/>";
+
+  var body = document.getElementsByTagName("body")[0];
+  body.insertBefore(div, body.firstChild);
+
+  var setByClassName = function(name, displayStyle) {
+    var elements = div.getElementsByClassName(name);
+    for (var i = 0; i < elements.length; i++) {
+      elements[i].style.display = displayStyle;
+    }
+  }
+
+  var passedAnchor = document.getElementById('passed');
+  var failedAnchor = document.getElementById('failed');
+  var allAnchor = document.getElementById('all');
+  passedAnchor.onclick = function() {
+    setByClassName('fail', 'none');
+    setByClassName('pass', 'block');
+
+    passedAnchor.setAttribute("class", 'activeAnchor');
+    failedAnchor.setAttribute("class", '');
+  };
+  failedAnchor.onclick = function() {
+    setByClassName('fail', 'block');
+    setByClassName('pass', 'none');
+    passedAnchor.setAttribute("class", '');
+    failedAnchor.setAttribute("class", 'activeAnchor');
+  };
+  allAnchor.onclick = function() {
+    setByClassName('fail', 'block');
+    setByClassName('pass', 'block');
+    passedAnchor.setAttribute("class", '');
+    failedAnchor.setAttribute("class", '');
+  };
+  return div;
+}
+
+DygraphsLocalTester.prototype.postResults = function() {
+  var table = document.createElement("table");
+  this.resultsDiv.appendChild(table);
+  for (var idx = 0; idx < this.results.length; idx++) {
+    var result = this.results[idx];
+    var tr = document.createElement("tr");
+    tr.setAttribute("class", result.result ? 'pass' : 'fail');
+
+    var tdResult = document.createElement("td");
+    tdResult.setAttribute("class", "outcome");
+    tdResult.innerText = result.result ? 'pass' : 'fail';
+    tr.appendChild(tdResult);
+
+    var tdName = document.createElement("td");
+    var div = document.createElement("div");
+    div.innerText = result.name;
+    div.onclick = function(name) {
+      return function() {
+        var s = name.split(".");
+        var testCase = s[0];
+        var testName = s[1];
+        url = window.location.pathname +
+            "?testCaseName=" + testCase +
+            "&test=" + testName +
+            "&command=runTest";
+        window.location.href = url;
+      };
+    }(result.name);
+    div.setAttribute("class", "anchor");
+    tdName.appendChild(div);
+    tr.appendChild(tdName);
+
+    var tdDuration = document.createElement("td");
+    tdDuration.innerText = result.duration;
+    tr.appendChild(tdDuration);
+
+    if (result.e) {
+      var tdDetails = document.createElement("td");
+      div = document.createElement("div");
+      div.innerText = "more...";
+      div.setAttribute("class", "anchor");
+      div.onclick = function(e) {
+        return function() {
+          alert(e + "\n" + e.stack);
+        };
+      }(result.e);
+      tdDetails.appendChild(div);
+      tr.appendChild(tdDetails);
+    }
+
+    table.appendChild(tr);
+  }
+}
+
+DygraphsLocalTester.prototype.run = function() {
+  var selector = document.getElementById("selector");
+
+  if (selector != null) { // running a test
+    var createAttached = function(name, parent) {
+      var elem = document.createElement(name);
+      parent.appendChild(elem);
+      return elem;
+    }
+  
+    var description = createAttached("div", selector);
+    var list = createAttached("ul", selector);
+    var parent = list.parentElement;
+    var createLink = function(parent, text, url) {
+      var li = createAttached("li", parent);
+      var a = createAttached("a", li);
+      a.innerHTML = text;
+      a.href = url;
+    }
+    if (this.tc == null) {
+      description.innerHTML = "Test cases:";
+      var testCases = getAllTestCases();
+      createLink(list, "(run all tests)", document.URL + "?command=runAllTests");
+      for (var idx in testCases) {
+        var entryName = testCases[idx].name;
+        createLink(list, entryName, document.URL + "?testCaseName=" + entryName);
+      }
+    } else {
+      description.innerHTML = "Tests for " + name;
+      var names = this.tc.getTestNames();
+      createLink(list, "Run All Tests", document.URL + "&command=runAllTests");
+      for (var idx in names) {
+        var name = names[idx];
+        createLink(list, name, document.URL + "&test=" + name + "&command=runTest");
+      }
+    }
+  }
+}
+
+DygraphsLocalTester.prototype.start_ = function(tc) {
+  this.startms_ = new Date().getTime();
+}
+
+DygraphsLocalTester.prototype.finish_ = function(tc, name, result, e) {
+  var endms_ = new Date().getTime();
+  this.results.push({
+    name : tc.name + "." + name,
+    result : result,
+    duration : endms_ - this.startms_,
+    e : e
+  });
+  this.summary.passed += result ? 1 : 0;
+  this.summary.failed += result ? 0 : 1;
+}
index 7e50e42..1e9d0f4 100644 (file)
@@ -86,6 +86,7 @@ errorBarsTestCase.prototype.testErrorBarsDrawn = function() {
     xy2 = g.toDomCoords(data[i + 1][0], data[i + 1][1][1]);
     CanvasAssertions.assertLineDrawn(htx, xy1, xy2, attrs);
   }
+  g.destroy(); // Restore balanced saves and restores.
   CanvasAssertions.assertBalancedSaveRestore(htx);
 };
 
index e5c960f..9731514 100644 (file)
@@ -251,7 +251,7 @@ GridPerAxisTestCase.prototype.testPerAxisGridWidth = function() {
 };
 GridPerAxisTestCase.prototype.testGridLinePattern = function() {
   var opts = {
-    width : 480,
+    width : 120,
     height : 320,
     errorBars : false,
     drawXGrid : false,
@@ -291,7 +291,7 @@ GridPerAxisTestCase.prototype.testGridLinePattern = function() {
   }
   var x, y;
   // Step through all gridlines of the axis
-  for ( var i = 0; i < yGridlines.length; i++) {
+  for (var i = 0; i < yGridlines.length; i++) {
     y = halfDown(g.toDomYCoord(yGridlines[i], 0));
     // Step through the pixels of the line and test the pattern.
     for (x = halfUp(g.plotter_.area.x); x < g.plotter_.area.w; x++) {
@@ -304,11 +304,11 @@ GridPerAxisTestCase.prototype.testGridLinePattern = function() {
       var pattern = (Math.floor((x) / 10)) % 2;
       switch (pattern) {
       case 0: // fill
-        assertEquals("Unexpected filled grid-pattern color found at pixel: x: " + x + "y: "
+        assertEquals("Unexpected filled grid-pattern color found at pixel: x: " + x + " y: "
             + y, [ 0, 0, 255 ], drawnPixel);
         break;
       case 1: // no fill
-        assertEquals("Unexpected empty grid-pattern color found at pixel: x: " + x + "y: "
+        assertEquals("Unexpected empty grid-pattern color found at pixel: x: " + x + " y: "
             + y, [ 0, 0, 0 ], drawnPixel);
         break;
       }
index 75a6e87..27e9a1a 100644 (file)
@@ -55,6 +55,7 @@ SimpleDrawingTestCase.prototype.testDrawSimpleRangePlusOne = function() {
     strokeStyle: "#008080",
     lineWidth: 1
   });
+  g.destroy(); // to balance context saves and destroys.
   CanvasAssertions.assertBalancedSaveRestore(htx);
 };
 
@@ -76,6 +77,7 @@ SimpleDrawingTestCase.prototype.testDrawSimpleRangeZeroToFifty = function() {
     lineWidth: 1
   });
   assertEquals(1, lines.length);
+  g.destroy(); // to balance context saves and destroys.
   CanvasAssertions.assertBalancedSaveRestore(htx);
 };
 
@@ -84,6 +86,7 @@ SimpleDrawingTestCase.prototype.testDrawWithAxis = function() {
   var g = new Dygraph(graph, ZERO_TO_FIFTY);
 
   var htx = g.hidden_ctx_;
+  g.destroy(); // to balance context saves and destroys.
   CanvasAssertions.assertBalancedSaveRestore(htx);
 };
 
@@ -110,6 +113,7 @@ SimpleDrawingTestCase.prototype.testDrawSimpleDash = function() {
 
   // TODO(danvk): figure out a good way to restore this test.
   // assertEquals(29, CanvasAssertions.numLinesDrawn(htx, "#ff0000"));
+  g.destroy(); // to balance context saves and destroys.
   CanvasAssertions.assertBalancedSaveRestore(htx);
 };
 
@@ -146,5 +150,6 @@ SimpleDrawingTestCase.prototype.testDrawThickLine = function() {
 
   // TODO(danvk): figure out a good way to restore this test.
   // assertEquals(29, CanvasAssertions.numLinesDrawn(htx, "#ff0000"));
+  g.destroy(); // to balance context saves and destroys.
   CanvasAssertions.assertBalancedSaveRestore(htx);
 };
index 4b600f7..54496aa 100644 (file)
@@ -63,7 +63,7 @@ DygraphLayout.prototype.getPlotArea = function() {
 };
 
 // Compute the box which the chart should be drawn in. This is the canvas's
-// box, less space needed for axis and chart labels.
+// box, less space needed for axis, chart labels, and other plug-ins.
 // NOTE: This should only be called by Dygraph.predraw_().
 DygraphLayout.prototype.computePlotArea = function() {
   var area = {
@@ -162,10 +162,6 @@ DygraphLayout.prototype.setYAxes = function (yAxes) {
   this.yAxes_ = yAxes;
 };
 
-DygraphLayout.prototype.setDateWindow = function(dateWindow) {
-  this.dateWindow_ = dateWindow;
-};
-
 DygraphLayout.prototype.evaluate = function() {
   this._evaluateLimits();
   this._evaluateLineCharts();
index 223360b..1ec1795 100644 (file)
@@ -192,7 +192,7 @@ Dygraph.addEvent = function addEvent(elem, type, fn) {
  *     on the event. The function takes one parameter: the event object.
  * @private
  */
-Dygraph.prototype.addEvent = function(elem, type, fn) {
+Dygraph.prototype.addAndTrackEvent = function(elem, type, fn) {
   Dygraph.addEvent(elem, type, fn);
   this.registeredEvents_.push({ elem : elem, type : type, fn : fn });
 };
@@ -220,6 +220,17 @@ Dygraph.removeEvent = function(elem, type, fn) {
   }
 };
 
+Dygraph.prototype.removeTrackedEvents_ = function() {
+  if (this.registeredEvents_) {
+    for (var idx = 0; idx < this.registeredEvents_.length; idx++) {
+      var reg = this.registeredEvents_[idx];
+      Dygraph.removeEvent(reg.elem, reg.type, reg.fn);
+    }
+  }
+
+  this.registeredEvents_ = [];
+};
+
 /**
  * Cancels further processing of an event. This is useful to prevent default
  * browser actions, e.g. highlighting text on a double-click.
index 752c94d..dc3b798 100644 (file)
@@ -985,8 +985,7 @@ Dygraph.prototype.createInterface_ = function() {
   var enclosing = this.maindiv_;
 
   this.graphDiv = document.createElement("div");
-  this.graphDiv.style.width = this.width_ + "px";
-  this.graphDiv.style.height = this.height_ + "px";
+
   // TODO(danvk): any other styles that are useful to set here?
   this.graphDiv.style.textAlign = 'left';  // This is a CSS "reset"
   enclosing.appendChild(this.graphDiv);
@@ -994,10 +993,8 @@ Dygraph.prototype.createInterface_ = function() {
   // Create the canvas for interactive parts of the chart.
   this.canvas_ = Dygraph.createCanvas();
   this.canvas_.style.position = "absolute";
-  this.canvas_.width = this.width_;
-  this.canvas_.height = this.height_;
-  this.canvas_.style.width = this.width_ + "px";    // for IE
-  this.canvas_.style.height = this.height_ + "px";  // for IE
+
+  this.resizeElements_();
 
   this.canvas_ctx_ = Dygraph.getContext(this.canvas_);
 
@@ -1031,8 +1028,8 @@ Dygraph.prototype.createInterface_ = function() {
     }
   };
 
-  this.addEvent(window, 'mouseout', this.mouseOutHandler_);
-  this.addEvent(this.mouseEventElement_, 'mousemove', this.mouseMoveHandler_);
+  this.addAndTrackEvent(window, 'mouseout', this.mouseOutHandler_);
+  this.addAndTrackEvent(this.mouseEventElement_, 'mousemove', this.mouseMoveHandler_);
 
   // Don't recreate and register the resize handler on subsequent calls.
   // This happens when the graph is resized.
@@ -1043,16 +1040,28 @@ Dygraph.prototype.createInterface_ = function() {
 
     // Update when the window is resized.
     // TODO(danvk): drop frames depending on complexity of the chart.
-    this.addEvent(window, 'resize', this.resizeHandler_);
+    this.addAndTrackEvent(window, 'resize', this.resizeHandler_);
   }
 };
 
+Dygraph.prototype.resizeElements_ = function() {
+  this.graphDiv.style.width = this.width_ + "px";
+  this.graphDiv.style.height = this.height_ + "px";
+  this.canvas_.width = this.width_;
+  this.canvas_.height = this.height_;
+  this.canvas_.style.width = this.width_ + "px";    // for IE
+  this.canvas_.style.height = this.height_ + "px";  // for IE
+};
+
 /**
  * Detach DOM elements in the dygraph and null out all data references.
  * Calling this when you're done with a dygraph can dramatically reduce memory
  * usage. See, e.g., the tests/perf.html example.
  */
 Dygraph.prototype.destroy = function() {
+  this.canvas_ctx_.restore();
+  this.hidden_ctx_.restore();
+
   var removeRecursive = function(node) {
     while (node.hasChildNodes()) {
       removeRecursive(node.firstChild);
@@ -1060,19 +1069,11 @@ Dygraph.prototype.destroy = function() {
     }
   };
 
-  if (this.registeredEvents_) {
-    for (var idx = 0; idx < this.registeredEvents_.length; idx++) {
-      var reg = this.registeredEvents_[idx];
-      Dygraph.removeEvent(reg.elem, reg.type, reg.fn);
-    }
-  }
-
-  this.registeredEvents_ = [];
+  this.removeTrackedEvents_();
 
   // remove mouse event handlers (This may not be necessary anymore)
   Dygraph.removeEvent(window, 'mouseout', this.mouseOutHandler_);
   Dygraph.removeEvent(this.mouseEventElement_, 'mousemove', this.mouseMoveHandler_);
-  Dygraph.removeEvent(this.mouseEventElement_, 'mouseup', this.mouseUpHandler_);
 
   // remove window handlers
   Dygraph.removeEvent(window,'resize',this.resizeHandler_);
@@ -1344,19 +1345,13 @@ Dygraph.prototype.createDragInterface_ = function() {
 
   for (var eventName in interactionModel) {
     if (!interactionModel.hasOwnProperty(eventName)) continue;
-    this.addEvent(this.mouseEventElement_, eventName,
+    this.addAndTrackEvent(this.mouseEventElement_, eventName,
         bindHandler(interactionModel[eventName]));
   }
 
-  // unregister the handler on subsequent calls.
-  // This happens when the graph is resized.
-  if (this.mouseUpHandler_) {
-    Dygraph.removeEvent(document, 'mouseup', this.mouseUpHandler_);
-  }
-
   // If the user releases the mouse button during a drag, but not over the
   // canvas, then it doesn't count as a zooming action.
-  this.mouseUpHandler_ = function(event) {
+  var mouseUpHandler = function(event) {
     if (context.isZooming || context.isPanning) {
       context.isZooming = false;
       context.dragStartX = null;
@@ -1376,7 +1371,7 @@ Dygraph.prototype.createDragInterface_ = function() {
     context.tarp.uncover();
   };
 
-  this.addEvent(document, 'mouseup', this.mouseUpHandler_);
+  this.addAndTrackEvent(document, 'mouseup', mouseUpHandler);
 };
 
 /**
@@ -2236,6 +2231,15 @@ Dygraph.prototype.predraw_ = function() {
     this.cascadeEvents_('clearChart');
     this.plotter_.clear();
   }
+
+  if(!this.is_initial_draw_) {
+    this.canvas_ctx_.restore();
+    this.hidden_ctx_.restore();
+  }
+
+  this.canvas_ctx_.save();
+  this.hidden_ctx_.save();
+
   this.plotter_ = new DygraphCanvasRenderer(this,
                                             this.hidden_,
                                             this.hidden_ctx_,
@@ -2480,7 +2484,6 @@ Dygraph.prototype.drawGraph_ = function() {
   // Save the X axis zoomed status as the updateOptions call will tend to set it erroneously
   var tmp_zoomed_x = this.zoomed_x_;
   // Tell PlotKit to use this new data and render itself
-  this.layout_.setDateWindow(this.dateWindow_);
   this.zoomed_x_ = tmp_zoomed_x;
   this.layout_.evaluateWithError();
   this.renderGraph_(is_initial_draw);
@@ -3602,17 +3605,9 @@ Dygraph.prototype.resize = function(width, height) {
     this.height_ = this.maindiv_.clientHeight;
   }
 
+  this.resizeElements_();
+
   if (old_width != this.width_ || old_height != this.height_) {
-    // TODO(danvk): there should be a clear() method.
-    this.maindiv_.innerHTML = "";
-    this.roller_ = null;
-    this.attrs_.labelsDiv = null;
-    this.createInterface_();
-    if (this.annotations_.length) {
-      // createInterface_ reset the layout, so we need to do this.
-      this.layout_.setAnnotations(this.annotations_);
-    }
-    this.createDragInterface_();
     this.predraw_();
   }
 
index 802c31b..fac1bbc 100644 (file)
@@ -79,14 +79,14 @@ Dygraph.Plugins.Unzoom = (function() {
       g.resetZoom();
     };
 
-    g.addEvent(parent, 'mouseover', function() {
+    g.addAndTrackEvent(parent, 'mouseover', function() {
       if (g.isZoomed()) {
         self.show(true);
       }
       self.over_ = true;
     });
 
-    g.addEvent(parent, 'mouseout', function() {
+    g.addAndTrackEvent(parent, 'mouseout', function() {
       self.show(false);
       self.over_ = false;
     });
index 9b98fdf..22f4687 100644 (file)
@@ -22,10 +22,16 @@ page.open(url, function(status) {
   }
 
   var testCase, test;
-  if (phantom.args.length == 1) {
-    var parts = phantom.args[0].split('.');
+  var verbose = false;
+  var optIdx = 0;
+  if (phantom.args.length > 0 && phantom.args[0] === "--verbose") {
+    verbose = true;
+    optIdx = 1;
+  }
+  if (phantom.args.length == optIdx + 1) {
+    var parts = phantom.args[optIdx].split('.');
     if (2 != parts.length) {
-      console.warn('Usage: phantomjs phantom-driver.js [testCase.test]');
+      console.warn('Usage: phantomjs phantom-driver.js [--verbose] [testCase.test]');
       phantom.exit();
     }
     testCase = parts[0];
@@ -33,13 +39,14 @@ page.open(url, function(status) {
   }
 
   var loggingOn = false;
+
   page.onConsoleMessage = function (msg) {
     if (msg == 'Running ' + test) {
       loggingOn = true;
     } else if (msg.substr(0, 'Running'.length) == 'Running') {
       loggingOn = false;
     }
-    if (loggingOn) console.log(msg);
+    if (verbose || loggingOn) console.log(msg);
   };
 
   page.onError = function (msg, trace) {
@@ -54,49 +61,50 @@ page.open(url, function(status) {
   // Run all tests.
   var start = new Date().getTime();
   results = page.evaluate(function() {
+    var num_passing = 0, num_failing = 0;
+    var failures = [];
     // Phantom doesn't like stacktrace.js using the "arguments" object
     // in stacktrace.js, which it interprets in strict mode.
     printStackTrace = undefined;
 
+    jstestdriver.attachListener({
+      finish : function(tc, name, result, e) {
+        console.log("Result:", tc.name, name, result, e);
+        if (result) {
+          // console.log(testCase + '.' + test + ' passed');
+          num_passing++;
+        } else {
+          num_failing++;
+          failures.push(tc.name + '.' + name);
+        }
+      }
+    });
     var testCases = getAllTestCases();
-    var results = {};
     for (var idx in testCases) {
       var entry = testCases[idx];
 
       var prototype = entry.testCase;
       var tc = new entry.testCase();
       var result = tc.runAllTests();
-      results[entry.name] = result;
     }
-    return results;
+    return {
+      num_passing : num_passing,
+      num_failing : num_failing,
+      failures : failures
+    };
   });
   var end = new Date().getTime();
   var elapsed = (end - start) / 1000;
 
-  var num_passing = 0, num_failing = 0;
-  var failures = [];
-  for (var testCase in results) {
-    var caseResults = results[testCase];
-    for (var test in caseResults) {
-      if (caseResults[test] !== true) {
-        num_failing++;
-        failures.push(testCase + '.' + test);
-      } else {
-        // console.log(testCase + '.' + test + ' passed');
-        num_passing++;
-      }
-    }
-  }
-
-  console.log('Ran ' + (num_passing + num_failing) + ' tests in ' + elapsed + 's.');
-  console.log(num_passing + ' test(s) passed');
-  console.log(num_failing + ' test(s) failed:');
-  for (var i = 0; i < failures.length; i++) {
+  console.log('Ran ' + (results.num_passing + results.num_failing) + ' tests in ' + elapsed + 's.');
+  console.log(results.num_passing + ' test(s) passed');
+  console.log(results.num_failing + ' test(s) failed:');
+  for (var i = 0; i < results.failures.length; i++) {
     // TODO(danvk): print an auto_test/misc/local URL that runs this test.
-    console.log('  ' + failures[i] + ' failed.');
+    console.log('  ' + results.failures[i] + ' failed.');
   }
 
-  done_callback(num_failing, num_passing);
+  done_callback(results.num_failing, results.num_passing);
 });
 
 };
index 04ebb8f..8576104 100644 (file)
@@ -143,13 +143,13 @@ annotations.prototype.didDrawChart = function(e) {
     div.style.borderColor = g.colorsMap_[p.name];
     a.div = div;
 
-    g.addEvent(div, 'click',
+    g.addAndTrackEvent(div, 'click',
         bindEvt('clickHandler', 'annotationClickHandler', p, this));
-    g.addEvent(div, 'mouseover',
+    g.addAndTrackEvent(div, 'mouseover',
         bindEvt('mouseOverHandler', 'annotationMouseOverHandler', p, this));
-    g.addEvent(div, 'mouseout',
+    g.addAndTrackEvent(div, 'mouseout',
         bindEvt('mouseOutHandler', 'annotationMouseOutHandler', p, this));
-    g.addEvent(div, 'dblclick',
+    g.addAndTrackEvent(div, 'dblclick',
         bindEvt('dblClickHandler', 'annotationDblClickHandler', p, this));
 
     containerDiv.appendChild(div);
index d45a29a..089e64a 100644 (file)
@@ -508,7 +508,7 @@ rangeSelector.prototype.initInteraction_ = function() {
   addTouchEvents = function(elem, fn) {
     var types = ['touchstart', 'touchend', 'touchmove', 'touchcancel'];
     for (var i = 0; i < types.length; i++) {
-      self.dygraph_.addEvent(elem, types[i], fn);
+      self.dygraph_.addAndTrackEvent(elem, types[i], fn);
     }
   };
 
@@ -516,14 +516,14 @@ rangeSelector.prototype.initInteraction_ = function() {
   this.setDefaultOption_('panEdgeFraction', 0.0001);
 
   var dragStartEvent = window.opera ? 'mousedown' : 'dragstart';
-  this.dygraph_.addEvent(this.leftZoomHandle_, dragStartEvent, onZoomStart);
-  this.dygraph_.addEvent(this.rightZoomHandle_, dragStartEvent, onZoomStart);
+  this.dygraph_.addAndTrackEvent(this.leftZoomHandle_, dragStartEvent, onZoomStart);
+  this.dygraph_.addAndTrackEvent(this.rightZoomHandle_, dragStartEvent, onZoomStart);
 
   if (this.isUsingExcanvas_) {
-    this.dygraph_.addEvent(this.iePanOverlay_, 'mousedown', onPanStart);
+    this.dygraph_.addAndTrackEvent(this.iePanOverlay_, 'mousedown', onPanStart);
   } else {
-    this.dygraph_.addEvent(this.fgcanvas_, 'mousedown', onPanStart);
-    this.dygraph_.addEvent(this.fgcanvas_, 'mousemove', onCanvasHover);
+    this.dygraph_.addAndTrackEvent(this.fgcanvas_, 'mousedown', onPanStart);
+    this.dygraph_.addAndTrackEvent(this.fgcanvas_, 'mousemove', onCanvasHover);
   }
 
   // Touch events
diff --git a/test.sh b/test.sh
index f54d6e0..9ca252e 100755 (executable)
--- a/test.sh
+++ b/test.sh
@@ -16,4 +16,4 @@ if [ $? != 0 ]; then
   exit 1
 fi
 
-phantomjs phantom-driver.js
+phantomjs phantom-driver.js $*