From 3fcd12cca6f3237f9c66cb3f1fc82db14922defe Mon Sep 17 00:00:00 2001 From: Dan Vanderkam Date: Mon, 1 Jun 2015 14:07:54 -0700 Subject: [PATCH] Generate combined files for distribution --- dygraph-combined-dev.js | 12172 ++++++++++++++++++++++++++++++++++++++++++++++ dygraph-combined.js | 13 +- dygraph-combined.js.map | 1 + 3 files changed, 12179 insertions(+), 7 deletions(-) create mode 100644 dygraph-combined-dev.js create mode 100644 dygraph-combined.js.map diff --git a/dygraph-combined-dev.js b/dygraph-combined-dev.js new file mode 100644 index 0000000..b3a0fbc --- /dev/null +++ b/dygraph-combined-dev.js @@ -0,0 +1,12172 @@ +/*! @license Copyright 2014 Dan Vanderkam (danvdk@gmail.com) MIT-licensed (http://opensource.org/licenses/MIT) */ +// Console-polyfill. MIT license. +// https://github.com/paulmillr/console-polyfill +// Make it safe to do console.log() always. +(function(con) { + 'use strict'; + var prop, method; + var empty = {}; + var dummy = function() {}; + var properties = 'memory'.split(','); + var methods = ('assert,clear,count,debug,dir,dirxml,error,exception,group,' + + 'groupCollapsed,groupEnd,info,log,markTimeline,profile,profiles,profileEnd,' + + 'show,table,time,timeEnd,timeline,timelineEnd,timeStamp,trace,warn').split(','); + while (prop = properties.pop()) con[prop] = con[prop] || empty; + while (method = methods.pop()) con[method] = con[method] || dummy; +})(this.console = this.console || {}); // Using `this` for web workers. +/** + * @license + * Copyright 2012 Dan Vanderkam (danvdk@gmail.com) + * MIT-licensed (http://opensource.org/licenses/MIT) + */ + +(function() { +'use strict'; + +/** + * @fileoverview Adds support for dashed lines to the HTML5 canvas. + * + * Usage: + * var ctx = canvas.getContext("2d"); + * ctx.installPattern([10, 5]) // draw 10 pixels, skip 5 pixels, repeat. + * ctx.beginPath(); + * ctx.moveTo(100, 100); // start the first line segment. + * ctx.lineTo(150, 200); + * ctx.lineTo(200, 100); + * ctx.moveTo(300, 150); // start a second, unconnected line + * ctx.lineTo(400, 250); + * ... + * ctx.stroke(); // draw the dashed line. + * ctx.uninstallPattern(); + * + * This is designed to leave the canvas untouched when it's not used. + * If you never install a pattern, or call uninstallPattern(), then the canvas + * will be exactly as it would have if you'd never used this library. The only + * difference from the standard canvas will be the "installPattern" method of + * the drawing context. + */ + +/** + * Change the stroking style of the canvas drawing context from a solid line to + * a pattern (e.g. dashes, dash-dot-dash, etc.) + * + * Once you've installed the pattern, you can draw with it by using the + * beginPath(), moveTo(), lineTo() and stroke() method calls. Note that some + * more advanced methods (e.g. quadraticCurveTo() and bezierCurveTo()) are not + * supported. See file overview for a working example. + * + * Side effects of calling this method include adding an "isPatternInstalled" + * property and "uninstallPattern" method to this particular canvas context. + * You must call uninstallPattern() before calling installPattern() again. + * + * @param {Array.} 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. + */ +CanvasRenderingContext2D.prototype.installPattern = function(pattern) { + if (typeof(this.isPatternInstalled) !== 'undefined') { + throw "Must un-install old line pattern before installing a new one."; + } + this.isPatternInstalled = true; + + var dashedLineToHistory = [0, 0]; + + // list of connected line segements: + // [ [x1, y1], ..., [xn, yn] ], [ [x1, y1], ..., [xn, yn] ] + var segments = []; + + // Stash away copies of the unmodified line-drawing functions. + var realBeginPath = this.beginPath; + var realLineTo = this.lineTo; + var realMoveTo = this.moveTo; + var realStroke = this.stroke; + + /** @type {function()|undefined} */ + this.uninstallPattern = function() { + this.beginPath = realBeginPath; + this.lineTo = realLineTo; + this.moveTo = realMoveTo; + this.stroke = realStroke; + this.uninstallPattern = undefined; + this.isPatternInstalled = undefined; + }; + + // Keep our own copies of the line segments as they're drawn. + this.beginPath = function() { + segments = []; + realBeginPath.call(this); + }; + this.moveTo = function(x, y) { + segments.push([[x, y]]); + realMoveTo.call(this, x, y); + }; + this.lineTo = function(x, y) { + var last = segments[segments.length - 1]; + last.push([x, y]); + }; + + this.stroke = function() { + if (segments.length === 0) { + // Maybe the user is drawing something other than a line. + // TODO(danvk): test this case. + realStroke.call(this); + return; + } + + for (var i = 0; i < segments.length; i++) { + var seg = segments[i]; + var x1 = seg[0][0], y1 = seg[0][1]; + for (var j = 1; j < seg.length; j++) { + // Draw a dashed line from (x1, y1) - (x2, y2) + var x2 = seg[j][0], y2 = seg[j][1]; + this.save(); + + // Calculate transformation parameters + var dx = (x2-x1); + var dy = (y2-y1); + var len = Math.sqrt(dx*dx + dy*dy); + var rot = Math.atan2(dy, dx); + + // Set transformation + this.translate(x1, y1); + realMoveTo.call(this, 0, 0); + this.rotate(rot); + + // Set last pattern index we used for this pattern. + var patternIndex = dashedLineToHistory[0]; + var x = 0; + while (len > x) { + // Get the length of the pattern segment we are dealing with. + var segment = pattern[patternIndex]; + // If our last draw didn't complete the pattern segment all the way + // we will try to finish it. Otherwise we will try to do the whole + // segment. + if (dashedLineToHistory[1]) { + x += dashedLineToHistory[1]; + } else { + x += segment; + } + + if (x > len) { + // We were unable to complete this pattern index all the way, keep + // where we are the history so our next draw continues where we + // left off in the pattern. + dashedLineToHistory = [patternIndex, x-len]; + x = len; + } else { + // We completed this patternIndex, we put in the history that we + // are on the beginning of the next segment. + dashedLineToHistory = [(patternIndex+1)%pattern.length, 0]; + } + + // We do a line on a even pattern index and just move on a odd + // pattern index. The move is the empty space in the dash. + if (patternIndex % 2 === 0) { + realLineTo.call(this, x, 0); + } else { + realMoveTo.call(this, x, 0); + } + + // If we are not done, next loop process the next pattern segment, or + // the first segment again if we are at the end of the pattern. + patternIndex = (patternIndex+1) % pattern.length; + } + + this.restore(); + x1 = x2; + y1 = y2; + } + } + realStroke.call(this); + segments = []; + }; +}; + +/** + * Removes the previously-installed pattern. + * You must call installPattern() before calling this. You can install at most + * one pattern at a time--there is no pattern stack. + */ +CanvasRenderingContext2D.prototype.uninstallPattern = function() { + // This will be replaced by a non-error version when a pattern is installed. + throw "Must install a line pattern before uninstalling it."; +}; + +})(); +/** + * @license + * Copyright 2011 Dan Vanderkam (danvdk@gmail.com) + * MIT-licensed (http://opensource.org/licenses/MIT) + */ + +/** + * @fileoverview DygraphOptions is responsible for parsing and returning information about options. + * + * Still tightly coupled to Dygraphs, we could remove some of that, you know. + */ + +var DygraphOptions = (function() { +/*jshint strict:false */ + +// For "production" code, this gets set to false by uglifyjs. +// Need to define it outside of "use strict", hence the nested IIFEs. +if (typeof(DEBUG) === 'undefined') DEBUG=true; + +return (function() { + +// TODO: remove this jshint directive & fix the warnings. +/*jshint sub:true */ +/*global Dygraph:false */ +"use strict"; + +/* + * Interesting member variables: (REMOVING THIS LIST AS I CLOSURIZE) + * global_ - global attributes (common among all graphs, AIUI) + * user - attributes set by the user + * series_ - { seriesName -> { idx, yAxis, options }} + */ + +/** + * 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 {Dygraph} dygraph The chart to which these options belong. + * @constructor + */ +var DygraphOptions = function(dygraph) { + /** + * The dygraph. + * @type {!Dygraph} + */ + this.dygraph_ = dygraph; + + /** + * Array of axis index to { series : [ series names ] , options : { axis-specific options. } + * @type {Array.<{series : Array., options : Object}>} @private + */ + this.yAxes_ = []; + + /** + * Contains x-axis specific options, which are stored in the options key. + * This matches the yAxes_ object structure (by being a dictionary with an + * options element) allowing for shared code. + * @type {options: Object} @private + */ + this.xAxis_ = {}; + this.series_ = {}; + + // Once these two objects are initialized, you can call get(); + this.global_ = this.dygraph_.attrs_; + this.user_ = this.dygraph_.user_attrs_ || {}; + + /** + * A list of series in columnar order. + * @type {Array.} + */ + this.labels_ = []; + + this.highlightSeries_ = this.get("highlightSeriesOpts") || {}; + this.reparseSeries(); +}; + +/** + * Not optimal, but does the trick when you're only using two axes. + * If we move to more axes, this can just become a function. + * + * @type {Object.} + * @private + */ +DygraphOptions.AXIS_STRING_MAPPINGS_ = { + 'y' : 0, + 'Y' : 0, + 'y1' : 0, + 'Y1' : 0, + 'y2' : 1, + 'Y2' : 1 +}; + +/** + * @param {string|number} axis + * @private + */ +DygraphOptions.axisToIndex_ = function(axis) { + if (typeof(axis) == "string") { + if (DygraphOptions.AXIS_STRING_MAPPINGS_.hasOwnProperty(axis)) { + return DygraphOptions.AXIS_STRING_MAPPINGS_[axis]; + } + throw "Unknown axis : " + axis; + } + if (typeof(axis) == "number") { + if (axis === 0 || axis === 1) { + return axis; + } + throw "Dygraphs only supports two y-axes, indexed from 0-1."; + } + if (axis) { + throw "Unknown axis : " + axis; + } + // No axis specification means axis 0. + return 0; +}; + +/** + * Reparses options that are all related to series. This typically occurs when + * options are either updated, or source data has been made available. + * + * TODO(konigsberg): The method name is kind of weak; fix. + */ +DygraphOptions.prototype.reparseSeries = function() { + var labels = this.get("labels"); + if (!labels) { + return; // -- can't do more for now, will parse after getting the labels. + } + + this.labels_ = labels.slice(1); + + this.yAxes_ = [ { series : [], options : {}} ]; // Always one axis at least. + this.xAxis_ = { options : {} }; + this.series_ = {}; + + // Traditionally, per-series options were specified right up there with the options. For instance + // { + // labels: [ "X", "foo", "bar" ], + // pointSize: 3, + // foo : {}, // options for foo + // bar : {} // options for bar + // } + // + // Moving forward, series really should be specified in the series element, separating them. + // like so: + // + // { + // labels: [ "X", "foo", "bar" ], + // pointSize: 3, + // series : { + // foo : {}, // options for foo + // bar : {} // options for bar + // } + // } + // + // So, if series is found, it's expected to contain per-series data, otherwise we fall + // back. + var oldStyleSeries = !this.user_["series"]; + + if (oldStyleSeries) { + var axisId = 0; // 0-offset; there's always one. + // Go through once, add all the series, and for those with {} axis options, add a new axis. + for (var idx = 0; idx < this.labels_.length; idx++) { + var seriesName = this.labels_[idx]; + + var optionsForSeries = this.user_[seriesName] || {}; + + var yAxis = 0; + var axis = optionsForSeries["axis"]; + if (typeof(axis) == 'object') { + yAxis = ++axisId; + this.yAxes_[yAxis] = { series : [ seriesName ], options : axis }; + } + + // Associate series without axis options with axis 0. + if (!axis) { // undefined + this.yAxes_[0].series.push(seriesName); + } + + this.series_[seriesName] = { idx: idx, yAxis: yAxis, options : optionsForSeries }; + } + + // Go through one more time and assign series to an axis defined by another + // series, e.g. { 'Y1: { axis: {} }, 'Y2': { axis: 'Y1' } } + for (var idx = 0; idx < this.labels_.length; idx++) { + var seriesName = this.labels_[idx]; + var optionsForSeries = this.series_[seriesName]["options"]; + var axis = optionsForSeries["axis"]; + + if (typeof(axis) == 'string') { + if (!this.series_.hasOwnProperty(axis)) { + console.error("Series " + seriesName + " wants to share a y-axis with " + + "series " + axis + ", which does not define its own axis."); + return; + } + var yAxis = this.series_[axis].yAxis; + this.series_[seriesName].yAxis = yAxis; + this.yAxes_[yAxis].series.push(seriesName); + } + } + } else { + for (var idx = 0; idx < this.labels_.length; idx++) { + var seriesName = this.labels_[idx]; + var optionsForSeries = this.user_.series[seriesName] || {}; + var yAxis = DygraphOptions.axisToIndex_(optionsForSeries["axis"]); + + this.series_[seriesName] = { + idx: idx, + yAxis: yAxis, + options : optionsForSeries }; + + if (!this.yAxes_[yAxis]) { + this.yAxes_[yAxis] = { series : [ seriesName ], options : {} }; + } else { + this.yAxes_[yAxis].series.push(seriesName); + } + } + } + + var axis_opts = this.user_["axes"] || {}; + Dygraph.update(this.yAxes_[0].options, axis_opts["y"] || {}); + if (this.yAxes_.length > 1) { + Dygraph.update(this.yAxes_[1].options, axis_opts["y2"] || {}); + } + Dygraph.update(this.xAxis_.options, axis_opts["x"] || {}); + + if (DEBUG) this.validateOptions_(); +}; + +/** + * Get a global value. + * + * @param {string} name the name of the option. + */ +DygraphOptions.prototype.get = function(name) { + var result = this.getGlobalUser_(name); + if (result !== null) { + return result; + } + return this.getGlobalDefault_(name); +}; + +DygraphOptions.prototype.getGlobalUser_ = function(name) { + if (this.user_.hasOwnProperty(name)) { + return this.user_[name]; + } + return null; +}; + +DygraphOptions.prototype.getGlobalDefault_ = function(name) { + if (this.global_.hasOwnProperty(name)) { + return this.global_[name]; + } + if (Dygraph.DEFAULT_ATTRS.hasOwnProperty(name)) { + return Dygraph.DEFAULT_ATTRS[name]; + } + return null; +}; + +/** + * 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; + var axisString; + + // Since axis can be a number or a string, straighten everything out here. + if (typeof(axis) == 'number') { + axisIdx = axis; + axisString = axisIdx === 0 ? "y" : "y2"; + } else { + if (axis == "y1") { axis = "y"; } // Standardize on 'y'. Is this bad? I think so. + if (axis == "y") { + axisIdx = 0; + } else if (axis == "y2") { + axisIdx = 1; + } else if (axis == "x") { + axisIdx = -1; // simply a placeholder for below. + } else { + throw "Unknown axis " + axis; + } + axisString = axis; + } + + var userAxis = (axisIdx == -1) ? this.xAxis_ : this.yAxes_[axisIdx]; + + // Search the user-specified axis option first. + if (userAxis) { // This condition could be removed if we always set up this.yAxes_ for y2. + var axisOptions = userAxis.options; + if (axisOptions.hasOwnProperty(name)) { + return axisOptions[name]; + } + } + + // User-specified global options second. + // But, hack, ignore globally-specified 'logscale' for 'x' axis declaration. + if (!(axis === 'x' && name === 'logscale')) { + var result = this.getGlobalUser_(name); + if (result !== null) { + return result; + } + } + // Default axis options third. + var defaultAxisOptions = Dygraph.DEFAULT_ATTRS.axes[axisString]; + if (defaultAxisOptions.hasOwnProperty(name)) { + return defaultAxisOptions[name]; + } + + // Default global options last. + return this.getGlobalDefault_(name); +}; + +/** + * 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} series the series to search. + */ +DygraphOptions.prototype.getForSeries = function(name, series) { + // Honors indexes as series. + if (series === this.dygraph_.getHighlightSeries()) { + if (this.highlightSeries_.hasOwnProperty(name)) { + return this.highlightSeries_[name]; + } + } + + if (!this.series_.hasOwnProperty(series)) { + throw "Unknown series: " + series; + } + + var seriesObj = this.series_[series]; + var seriesOptions = seriesObj["options"]; + if (seriesOptions.hasOwnProperty(name)) { + return seriesOptions[name]; + } + + return this.getForAxis(name, seriesObj["yAxis"]); +}; + +/** + * Returns the number of y-axes on the chart. + * @return {number} the number of axes. + */ +DygraphOptions.prototype.numAxes = function() { + return this.yAxes_.length; +}; + +/** + * Return the y-axis for a given series, specified by name. + */ +DygraphOptions.prototype.axisForSeries = function(series) { + return this.series_[series].yAxis; +}; + +/** + * Returns the options for the specified axis. + */ +// TODO(konigsberg): this is y-axis specific. Support the x axis. +DygraphOptions.prototype.axisOptions = function(yAxis) { + return this.yAxes_[yAxis].options; +}; + +/** + * Return the series associated with an axis. + */ +DygraphOptions.prototype.seriesForAxis = function(yAxis) { + return this.yAxes_[yAxis].series; +}; + +/** + * Return the list of all series, in their columnar order. + */ +DygraphOptions.prototype.seriesNames = function() { + return this.labels_; +}; + +if (DEBUG) { + +/** + * Validate all options. + * This requires Dygraph.OPTIONS_REFERENCE, which is only available in debug builds. + * @private + */ +DygraphOptions.prototype.validateOptions_ = function() { + if (typeof Dygraph.OPTIONS_REFERENCE === 'undefined') { + throw 'Called validateOptions_ in prod build.'; + } + + var that = this; + var validateOption = function(optionName) { + if (!Dygraph.OPTIONS_REFERENCE[optionName]) { + that.warnInvalidOption_(optionName); + } + }; + + var optionsDicts = [this.xAxis_.options, + this.yAxes_[0].options, + this.yAxes_[1] && this.yAxes_[1].options, + this.global_, + this.user_, + this.highlightSeries_]; + var names = this.seriesNames(); + for (var i = 0; i < names.length; i++) { + var name = names[i]; + if (this.series_.hasOwnProperty(name)) { + optionsDicts.push(this.series_[name].options); + } + } + for (var i = 0; i < optionsDicts.length; i++) { + var dict = optionsDicts[i]; + if (!dict) continue; + for (var optionName in dict) { + if (dict.hasOwnProperty(optionName)) { + validateOption(optionName); + } + } + } +}; + +var WARNINGS = {}; // Only show any particular warning once. + +/** + * Logs a warning about invalid options. + * TODO: make this throw for testing + * @private + */ +DygraphOptions.prototype.warnInvalidOption_ = function(optionName) { + if (!WARNINGS[optionName]) { + WARNINGS[optionName] = true; + var isSeries = (this.labels_.indexOf(optionName) >= 0); + if (isSeries) { + console.warn('Use new-style per-series options (saw ' + optionName + ' as top-level options key). See http://bit.ly/1tceaJs'); + } else { + console.warn('Unknown option ' + optionName + ' (full list of options at dygraphs.com/options.html'); + throw "invalid option " + optionName; + } + } +}; + +// Reset list of previously-shown warnings. Used for testing. +DygraphOptions.resetWarnings_ = function() { + WARNINGS = {}; +}; + +} + +return DygraphOptions; + +})(); +})(); +/** + * @license + * Copyright 2011 Dan Vanderkam (danvdk@gmail.com) + * MIT-licensed (http://opensource.org/licenses/MIT) + */ + +/** + * @fileoverview Based on PlotKitLayout, but modified to meet the needs of + * dygraphs. + */ + +var DygraphLayout = (function() { + +/*global Dygraph:false */ +"use strict"; + +/** + * Creates a new DygraphLayout object. + * + * This class contains all the data to be charted. + * It uses data coordinates, but also records the chart range (in data + * coordinates) and hence is able to calculate percentage positions ('In this + * view, Point A lies 25% down the x-axis.') + * + * Two things that it does not do are: + * 1. Record pixel coordinates for anything. + * 2. (oddly) determine anything about the layout of chart elements. + * + * The naming is a vestige of Dygraph's original PlotKit roots. + * + * @constructor + */ +var DygraphLayout = function(dygraph) { + this.dygraph_ = dygraph; + /** + * Array of points for each series. + * + * [series index][row index in series] = |Point| structure, + * where series index refers to visible series only, and the + * point index is for the reduced set of points for the current + * zoom region (including one point just outside the window). + * All points in the same row index share the same X value. + * + * @type {Array.>} + */ + this.points = []; + this.setNames = []; + this.annotations = []; + this.yAxes_ = null; + + // TODO(danvk): it's odd that xTicks_ and yTicks_ are inputs, but xticks and + // yticks are outputs. Clean this up. + this.xTicks_ = null; + this.yTicks_ = null; +}; + +/** + * Add points for a single series. + * + * @param {string} setname Name of the series. + * @param {Array.} set_xy Points for the series. + */ +DygraphLayout.prototype.addDataset = function(setname, set_xy) { + this.points.push(set_xy); + this.setNames.push(setname); +}; + +/** + * Returns the box which the chart should be drawn in. This is the canvas's + * box, less space needed for the axis and chart labels. + * + * @return {{x: number, y: number, w: number, h: number}} + */ +DygraphLayout.prototype.getPlotArea = function() { + return this.area_; +}; + +// Compute the box which the chart should be drawn in. This is the canvas's +// 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 = { + // TODO(danvk): per-axis setting. + x: 0, + y: 0 + }; + + area.w = this.dygraph_.width_ - area.x - this.dygraph_.getOption('rightGap'); + area.h = this.dygraph_.height_; + + // Let plugins reserve space. + var e = { + chart_div: this.dygraph_.graphDiv, + reserveSpaceLeft: function(px) { + var r = { + x: area.x, + y: area.y, + w: px, + h: area.h + }; + area.x += px; + area.w -= px; + return r; + }, + reserveSpaceRight: function(px) { + var r = { + x: area.x + area.w - px, + y: area.y, + w: px, + h: area.h + }; + area.w -= px; + return r; + }, + reserveSpaceTop: function(px) { + var r = { + x: area.x, + y: area.y, + w: area.w, + h: px + }; + area.y += px; + area.h -= px; + return r; + }, + reserveSpaceBottom: function(px) { + var r = { + x: area.x, + y: area.y + area.h - px, + w: area.w, + h: px + }; + area.h -= px; + return r; + }, + chartRect: function() { + return {x:area.x, y:area.y, w:area.w, h:area.h}; + } + }; + this.dygraph_.cascadeEvents_('layout', e); + + this.area_ = area; +}; + +DygraphLayout.prototype.setAnnotations = function(ann) { + // The Dygraph object's annotations aren't parsed. We parse them here and + // save a copy. If there is no parser, then the user must be using raw format. + this.annotations = []; + var parse = this.dygraph_.getOption('xValueParser') || function(x) { return x; }; + for (var i = 0; i < ann.length; i++) { + var a = {}; + if (!ann[i].xval && ann[i].x === undefined) { + console.error("Annotations must have an 'x' property"); + return; + } + if (ann[i].icon && + !(ann[i].hasOwnProperty('width') && + ann[i].hasOwnProperty('height'))) { + console.error("Must set width and height when setting " + + "annotation.icon property"); + return; + } + Dygraph.update(a, ann[i]); + if (!a.xval) a.xval = parse(a.x); + this.annotations.push(a); + } +}; + +DygraphLayout.prototype.setXTicks = function(xTicks) { + this.xTicks_ = xTicks; +}; + +// TODO(danvk): add this to the Dygraph object's API or move it into Layout. +DygraphLayout.prototype.setYAxes = function (yAxes) { + this.yAxes_ = yAxes; +}; + +DygraphLayout.prototype.evaluate = function() { + this._xAxis = {}; + this._evaluateLimits(); + this._evaluateLineCharts(); + this._evaluateLineTicks(); + this._evaluateAnnotations(); +}; + +DygraphLayout.prototype._evaluateLimits = function() { + var xlimits = this.dygraph_.xAxisRange(); + this._xAxis.minval = xlimits[0]; + this._xAxis.maxval = xlimits[1]; + var xrange = xlimits[1] - xlimits[0]; + this._xAxis.scale = (xrange !== 0 ? 1 / xrange : 1.0); + + if (this.dygraph_.getOptionForAxis("logscale", 'x')) { + this._xAxis.xlogrange = Dygraph.log10(this._xAxis.maxval) - Dygraph.log10(this._xAxis.minval); + this._xAxis.xlogscale = (this._xAxis.xlogrange !== 0 ? 1.0 / this._xAxis.xlogrange : 1.0); + } + for (var i = 0; i < this.yAxes_.length; i++) { + var axis = this.yAxes_[i]; + axis.minyval = axis.computedValueRange[0]; + axis.maxyval = axis.computedValueRange[1]; + axis.yrange = axis.maxyval - axis.minyval; + axis.yscale = (axis.yrange !== 0 ? 1.0 / axis.yrange : 1.0); + + if (this.dygraph_.getOption("logscale")) { + axis.ylogrange = Dygraph.log10(axis.maxyval) - Dygraph.log10(axis.minyval); + axis.ylogscale = (axis.ylogrange !== 0 ? 1.0 / axis.ylogrange : 1.0); + if (!isFinite(axis.ylogrange) || isNaN(axis.ylogrange)) { + console.error('axis ' + i + ' of graph at ' + axis.g + + ' can\'t be displayed in log scale for range [' + + axis.minyval + ' - ' + axis.maxyval + ']'); + } + } + } +}; + +DygraphLayout.calcXNormal_ = function(value, xAxis, logscale) { + if (logscale) { + return ((Dygraph.log10(value) - Dygraph.log10(xAxis.minval)) * xAxis.xlogscale); + } else { + return (value - xAxis.minval) * xAxis.scale; + } +}; + +/** + * @param {DygraphAxisType} axis + * @param {number} value + * @param {boolean} logscale + * @return {number} + */ +DygraphLayout.calcYNormal_ = function(axis, value, logscale) { + if (logscale) { + var x = 1.0 - ((Dygraph.log10(value) - Dygraph.log10(axis.minyval)) * axis.ylogscale); + return isFinite(x) ? x : NaN; // shim for v8 issue; see pull request 276 + } else { + return 1.0 - ((value - axis.minyval) * axis.yscale); + } +}; + +DygraphLayout.prototype._evaluateLineCharts = function() { + var isStacked = this.dygraph_.getOption("stackedGraph"); + var isLogscaleForX = this.dygraph_.getOptionForAxis("logscale", 'x'); + + for (var setIdx = 0; setIdx < this.points.length; setIdx++) { + var points = this.points[setIdx]; + var setName = this.setNames[setIdx]; + var connectSeparated = this.dygraph_.getOption('connectSeparatedPoints', setName); + var axis = this.dygraph_.axisPropertiesForSeries(setName); + // TODO (konigsberg): use optionsForAxis instead. + var logscale = this.dygraph_.attributes_.getForSeries("logscale", setName); + + for (var j = 0; j < points.length; j++) { + var point = points[j]; + + // Range from 0-1 where 0 represents left and 1 represents right. + point.x = DygraphLayout.calcXNormal_(point.xval, this._xAxis, isLogscaleForX); + // Range from 0-1 where 0 represents top and 1 represents bottom + var yval = point.yval; + if (isStacked) { + point.y_stacked = DygraphLayout.calcYNormal_( + axis, point.yval_stacked, logscale); + if (yval !== null && !isNaN(yval)) { + yval = point.yval_stacked; + } + } + if (yval === null) { + yval = NaN; + if (!connectSeparated) { + point.yval = NaN; + } + } + point.y = DygraphLayout.calcYNormal_(axis, yval, logscale); + } + + this.dygraph_.dataHandler_.onLineEvaluated(points, axis, logscale); + } +}; + +DygraphLayout.prototype._evaluateLineTicks = function() { + var i, tick, label, pos; + this.xticks = []; + for (i = 0; i < this.xTicks_.length; i++) { + tick = this.xTicks_[i]; + label = tick.label; + pos = this.dygraph_.toPercentXCoord(tick.v); + if ((pos >= 0.0) && (pos < 1.0)) { + this.xticks.push([pos, label]); + } + } + + this.yticks = []; + for (i = 0; i < this.yAxes_.length; i++ ) { + var axis = this.yAxes_[i]; + for (var j = 0; j < axis.ticks.length; j++) { + tick = axis.ticks[j]; + label = tick.label; + pos = this.dygraph_.toPercentYCoord(tick.v, i); + if ((pos > 0.0) && (pos <= 1.0)) { + this.yticks.push([i, pos, label]); + } + } + } +}; + +DygraphLayout.prototype._evaluateAnnotations = function() { + // Add the annotations to the point to which they belong. + // Make a map from (setName, xval) to annotation for quick lookups. + var i; + var annotations = {}; + for (i = 0; i < this.annotations.length; i++) { + var a = this.annotations[i]; + annotations[a.xval + "," + a.series] = a; + } + + this.annotated_points = []; + + // Exit the function early if there are no annotations. + if (!this.annotations || !this.annotations.length) { + return; + } + + // TODO(antrob): loop through annotations not points. + for (var setIdx = 0; setIdx < this.points.length; setIdx++) { + var points = this.points[setIdx]; + for (i = 0; i < points.length; i++) { + var p = points[i]; + var k = p.xval + "," + p.name; + if (k in annotations) { + p.annotation = annotations[k]; + this.annotated_points.push(p); + } + } + } +}; + +/** + * Convenience function to remove all the data sets from a graph + */ +DygraphLayout.prototype.removeAllDatasets = function() { + delete this.points; + delete this.setNames; + delete this.setPointsLengths; + delete this.setPointsOffsets; + this.points = []; + this.setNames = []; + this.setPointsLengths = []; + this.setPointsOffsets = []; +}; + +return DygraphLayout; + +})(); +/** + * @license + * Copyright 2006 Dan Vanderkam (danvdk@gmail.com) + * MIT-licensed (http://opensource.org/licenses/MIT) + */ + +/** + * @fileoverview Based on PlotKit.CanvasRenderer, but modified to meet the + * needs of dygraphs. + * + * In particular, support for: + * - grid overlays + * - error bars + * - dygraphs attribute system + */ + +/** + * The DygraphCanvasRenderer class does the actual rendering of the chart onto + * a canvas. It's based on PlotKit.CanvasRenderer. + * @param {Object} element The canvas to attach to + * @param {Object} elementContext The 2d context of the canvas (injected so it + * can be mocked for testing.) + * @param {Layout} layout The DygraphLayout object for this graph. + * @constructor + */ + +var DygraphCanvasRenderer = (function() { +/*global Dygraph:false */ +"use strict"; + + +/** + * @constructor + * + * This gets called when there are "new points" to chart. This is generally the + * case when the underlying data being charted has changed. It is _not_ called + * in the common case that the user has zoomed or is panning the view. + * + * The chart canvas has already been created by the Dygraph object. The + * renderer simply gets a drawing context. + * + * @param {Dygraph} dygraph The chart to which this renderer belongs. + * @param {HTMLCanvasElement} element The <canvas> DOM element on which to draw. + * @param {CanvasRenderingContext2D} elementContext The drawing context. + * @param {DygraphLayout} layout The chart's DygraphLayout object. + * + * TODO(danvk): remove the elementContext property. + */ +var DygraphCanvasRenderer = function(dygraph, element, elementContext, layout) { + this.dygraph_ = dygraph; + + this.layout = layout; + this.element = element; + this.elementContext = elementContext; + + this.height = dygraph.height_; + this.width = dygraph.width_; + + // --- check whether everything is ok before we return + // NOTE(konigsberg): isIE is never defined in this object. Bug of some sort. + if (!this.isIE && !(Dygraph.isCanvasSupported(this.element))) + throw "Canvas is not supported."; + + // internal state + this.area = layout.getPlotArea(); + + // Set up a clipping area for the canvas (and the interaction canvas). + // This ensures that we don't overdraw. + if (this.dygraph_.isUsingExcanvas_) { + this._createIEClipArea(); + } else { + // on Android 3 and 4, setting a clipping area on a canvas prevents it from + // displaying anything. + if (!Dygraph.isAndroid()) { + var ctx = this.dygraph_.canvas_ctx_; + ctx.beginPath(); + ctx.rect(this.area.x, this.area.y, this.area.w, this.area.h); + ctx.clip(); + + ctx = this.dygraph_.hidden_ctx_; + ctx.beginPath(); + ctx.rect(this.area.x, this.area.y, this.area.w, this.area.h); + ctx.clip(); + } + } +}; + +/** + * Clears out all chart content and DOM elements. + * This is called immediately before render() on every frame, including + * during zooms and pans. + * @private + */ +DygraphCanvasRenderer.prototype.clear = function() { + var context; + if (this.isIE) { + // VML takes a while to start up, so we just poll every this.IEDelay + try { + if (this.clearDelay) { + this.clearDelay.cancel(); + this.clearDelay = null; + } + context = this.elementContext; + } + catch (e) { + // TODO(danvk): this is broken, since MochiKit.Async is gone. + // this.clearDelay = MochiKit.Async.wait(this.IEDelay); + // this.clearDelay.addCallback(bind(this.clear, this)); + return; + } + } + + context = this.elementContext; + context.clearRect(0, 0, this.width, this.height); +}; + +/** + * This method is responsible for drawing everything on the chart, including + * lines, error bars, fills and axes. + * It is called immediately after clear() on every frame, including during pans + * and zooms. + * @private + */ +DygraphCanvasRenderer.prototype.render = function() { + // attaches point.canvas{x,y} + this._updatePoints(); + + // actually draws the chart. + this._renderLineChart(); +}; + +DygraphCanvasRenderer.prototype._createIEClipArea = function() { + var className = 'dygraph-clip-div'; + var graphDiv = this.dygraph_.graphDiv; + + // Remove old clip divs. + for (var i = graphDiv.childNodes.length-1; i >= 0; i--) { + if (graphDiv.childNodes[i].className == className) { + graphDiv.removeChild(graphDiv.childNodes[i]); + } + } + + // Determine background color to give clip divs. + var backgroundColor = document.bgColor; + var element = this.dygraph_.graphDiv; + while (element != document) { + var bgcolor = element.currentStyle.backgroundColor; + if (bgcolor && bgcolor != 'transparent') { + backgroundColor = bgcolor; + break; + } + element = element.parentNode; + } + + function createClipDiv(area) { + if (area.w === 0 || area.h === 0) { + return; + } + var elem = document.createElement('div'); + elem.className = className; + elem.style.backgroundColor = backgroundColor; + elem.style.position = 'absolute'; + elem.style.left = area.x + 'px'; + elem.style.top = area.y + 'px'; + elem.style.width = area.w + 'px'; + elem.style.height = area.h + 'px'; + graphDiv.appendChild(elem); + } + + var plotArea = this.area; + // Left side + createClipDiv({ + x:0, y:0, + w:plotArea.x, + h:this.height + }); + + // Top + createClipDiv({ + x: plotArea.x, y: 0, + w: this.width - plotArea.x, + h: plotArea.y + }); + + // Right side + createClipDiv({ + x: plotArea.x + plotArea.w, y: 0, + w: this.width - plotArea.x - plotArea.w, + h: this.height + }); + + // Bottom + createClipDiv({ + x: plotArea.x, + y: plotArea.y + plotArea.h, + w: this.width - plotArea.x, + h: this.height - plotArea.h - plotArea.y + }); +}; + + +/** + * Returns a predicate to be used with an iterator, which will + * iterate over points appropriately, depending on whether + * connectSeparatedPoints is true. When it's false, the predicate will + * skip over points with missing yVals. + */ +DygraphCanvasRenderer._getIteratorPredicate = function(connectSeparatedPoints) { + return connectSeparatedPoints ? + DygraphCanvasRenderer._predicateThatSkipsEmptyPoints : + null; +}; + +DygraphCanvasRenderer._predicateThatSkipsEmptyPoints = + function(array, idx) { + return array[idx].yval !== null; +}; + +/** + * Draws a line with the styles passed in and calls all the drawPointCallbacks. + * @param {Object} e The dictionary passed to the plotter function. + * @private + */ +DygraphCanvasRenderer._drawStyledLine = function(e, + color, strokeWidth, strokePattern, drawPoints, + drawPointCallback, pointSize) { + var g = e.dygraph; + // TODO(konigsberg): Compute attributes outside this method call. + var stepPlot = g.getBooleanOption("stepPlot", e.setName); + + if (!Dygraph.isArrayLike(strokePattern)) { + strokePattern = null; + } + + var drawGapPoints = g.getBooleanOption('drawGapEdgePoints', e.setName); + + var points = e.points; + var setName = e.setName; + var iter = Dygraph.createIterator(points, 0, points.length, + DygraphCanvasRenderer._getIteratorPredicate( + g.getBooleanOption("connectSeparatedPoints", setName))); + + var stroking = strokePattern && (strokePattern.length >= 2); + + var ctx = e.drawingContext; + ctx.save(); + if (stroking) { + ctx.installPattern(strokePattern); + } + + var pointsOnLine = DygraphCanvasRenderer._drawSeries( + e, iter, strokeWidth, pointSize, drawPoints, drawGapPoints, stepPlot, color); + DygraphCanvasRenderer._drawPointsOnLine( + e, pointsOnLine, drawPointCallback, color, pointSize); + + if (stroking) { + ctx.uninstallPattern(); + } + + ctx.restore(); +}; + +/** + * This does the actual drawing of lines on the canvas, for just one series. + * Returns a list of [canvasx, canvasy] pairs for points for which a + * drawPointCallback should be fired. These include isolated points, or all + * points if drawPoints=true. + * @param {Object} e The dictionary passed to the plotter function. + * @private + */ +DygraphCanvasRenderer._drawSeries = function(e, + iter, strokeWidth, pointSize, drawPoints, drawGapPoints, stepPlot, color) { + + var prevCanvasX = null; + var prevCanvasY = null; + var nextCanvasY = null; + var isIsolated; // true if this point is isolated (no line segments) + var point; // the point being processed in the while loop + var pointsOnLine = []; // Array of [canvasx, canvasy] pairs. + var first = true; // the first cycle through the while loop + + var ctx = e.drawingContext; + ctx.beginPath(); + ctx.strokeStyle = color; + ctx.lineWidth = strokeWidth; + + // NOTE: we break the iterator's encapsulation here for about a 25% speedup. + var arr = iter.array_; + var limit = iter.end_; + var predicate = iter.predicate_; + + for (var i = iter.start_; i < limit; i++) { + point = arr[i]; + if (predicate) { + while (i < limit && !predicate(arr, i)) { + i++; + } + if (i == limit) break; + point = arr[i]; + } + + // FIXME: The 'canvasy != canvasy' test here catches NaN values but the test + // doesn't catch Infinity values. Could change this to + // !isFinite(point.canvasy), but I assume it avoids isNaN for performance? + if (point.canvasy === null || point.canvasy != point.canvasy) { + if (stepPlot && prevCanvasX !== null) { + // Draw a horizontal line to the start of the missing data + ctx.moveTo(prevCanvasX, prevCanvasY); + ctx.lineTo(point.canvasx, prevCanvasY); + } + prevCanvasX = prevCanvasY = null; + } else { + isIsolated = false; + if (drawGapPoints || !prevCanvasX) { + iter.nextIdx_ = i; + iter.next(); + nextCanvasY = iter.hasNext ? iter.peek.canvasy : null; + + var isNextCanvasYNullOrNaN = nextCanvasY === null || + nextCanvasY != nextCanvasY; + isIsolated = (!prevCanvasX && isNextCanvasYNullOrNaN); + if (drawGapPoints) { + // Also consider a point to be "isolated" if it's adjacent to a + // null point, excluding the graph edges. + if ((!first && !prevCanvasX) || + (iter.hasNext && isNextCanvasYNullOrNaN)) { + isIsolated = true; + } + } + } + + if (prevCanvasX !== null) { + if (strokeWidth) { + if (stepPlot) { + ctx.moveTo(prevCanvasX, prevCanvasY); + ctx.lineTo(point.canvasx, prevCanvasY); + } + + ctx.lineTo(point.canvasx, point.canvasy); + } + } else { + ctx.moveTo(point.canvasx, point.canvasy); + } + if (drawPoints || isIsolated) { + pointsOnLine.push([point.canvasx, point.canvasy, point.idx]); + } + prevCanvasX = point.canvasx; + prevCanvasY = point.canvasy; + } + first = false; + } + ctx.stroke(); + return pointsOnLine; +}; + +/** + * This fires the drawPointCallback functions, which draw dots on the points by + * default. This gets used when the "drawPoints" option is set, or when there + * are isolated points. + * @param {Object} e The dictionary passed to the plotter function. + * @private + */ +DygraphCanvasRenderer._drawPointsOnLine = function( + e, pointsOnLine, drawPointCallback, color, pointSize) { + var ctx = e.drawingContext; + for (var idx = 0; idx < pointsOnLine.length; idx++) { + var cb = pointsOnLine[idx]; + ctx.save(); + drawPointCallback.call(e.dygraph, + e.dygraph, e.setName, ctx, cb[0], cb[1], color, pointSize, cb[2]); + ctx.restore(); + } +}; + +/** + * Attaches canvas coordinates to the points array. + * @private + */ +DygraphCanvasRenderer.prototype._updatePoints = function() { + // Update Points + // TODO(danvk): here + // + // TODO(bhs): this loop is a hot-spot for high-point-count charts. These + // transformations can be pushed into the canvas via linear transformation + // matrices. + // NOTE(danvk): this is trickier than it sounds at first. The transformation + // needs to be done before the .moveTo() and .lineTo() calls, but must be + // undone before the .stroke() call to ensure that the stroke width is + // unaffected. An alternative is to reduce the stroke width in the + // transformed coordinate space, but you can't specify different values for + // each dimension (as you can with .scale()). The speedup here is ~12%. + var sets = this.layout.points; + for (var i = sets.length; i--;) { + var points = sets[i]; + for (var j = points.length; j--;) { + var point = points[j]; + point.canvasx = this.area.w * point.x + this.area.x; + point.canvasy = this.area.h * point.y + this.area.y; + } + } +}; + +/** + * Add canvas Actually draw the lines chart, including error bars. + * + * This function can only be called if DygraphLayout's points array has been + * updated with canvas{x,y} attributes, i.e. by + * DygraphCanvasRenderer._updatePoints. + * + * @param {string=} opt_seriesName when specified, only that series will + * be drawn. (This is used for expedited redrawing with highlightSeriesOpts) + * @param {CanvasRenderingContext2D} opt_ctx when specified, the drawing + * context. However, lines are typically drawn on the object's + * elementContext. + * @private + */ +DygraphCanvasRenderer.prototype._renderLineChart = function(opt_seriesName, opt_ctx) { + var ctx = opt_ctx || this.elementContext; + var i; + + var sets = this.layout.points; + var setNames = this.layout.setNames; + var setName; + + this.colors = this.dygraph_.colorsMap_; + + // Determine which series have specialized plotters. + var plotter_attr = this.dygraph_.getOption("plotter"); + var plotters = plotter_attr; + if (!Dygraph.isArrayLike(plotters)) { + plotters = [plotters]; + } + + var setPlotters = {}; // series name -> plotter fn. + for (i = 0; i < setNames.length; i++) { + setName = setNames[i]; + var setPlotter = this.dygraph_.getOption("plotter", setName); + if (setPlotter == plotter_attr) continue; // not specialized. + + setPlotters[setName] = setPlotter; + } + + for (i = 0; i < plotters.length; i++) { + var plotter = plotters[i]; + var is_last = (i == plotters.length - 1); + + for (var j = 0; j < sets.length; j++) { + setName = setNames[j]; + if (opt_seriesName && setName != opt_seriesName) continue; + + var points = sets[j]; + + // Only throw in the specialized plotters on the last iteration. + var p = plotter; + if (setName in setPlotters) { + if (is_last) { + p = setPlotters[setName]; + } else { + // Don't use the standard plotters in this case. + continue; + } + } + + var color = this.colors[setName]; + var strokeWidth = this.dygraph_.getOption("strokeWidth", setName); + + ctx.save(); + ctx.strokeStyle = color; + ctx.lineWidth = strokeWidth; + p({ + points: points, + setName: setName, + drawingContext: ctx, + color: color, + strokeWidth: strokeWidth, + dygraph: this.dygraph_, + axis: this.dygraph_.axisPropertiesForSeries(setName), + plotArea: this.area, + seriesIndex: j, + seriesCount: sets.length, + singleSeriesName: opt_seriesName, + allSeriesPoints: sets + }); + ctx.restore(); + } + } +}; + +/** + * Standard plotters. These may be used by clients via Dygraph.Plotters. + * See comments there for more details. + */ +DygraphCanvasRenderer._Plotters = { + linePlotter: function(e) { + DygraphCanvasRenderer._linePlotter(e); + }, + + fillPlotter: function(e) { + DygraphCanvasRenderer._fillPlotter(e); + }, + + errorPlotter: function(e) { + DygraphCanvasRenderer._errorPlotter(e); + } +}; + +/** + * Plotter which draws the central lines for a series. + * @private + */ +DygraphCanvasRenderer._linePlotter = function(e) { + var g = e.dygraph; + var setName = e.setName; + var strokeWidth = e.strokeWidth; + + // TODO(danvk): Check if there's any performance impact of just calling + // getOption() inside of _drawStyledLine. Passing in so many parameters makes + // this code a bit nasty. + var borderWidth = g.getNumericOption("strokeBorderWidth", setName); + var drawPointCallback = g.getOption("drawPointCallback", setName) || + Dygraph.Circles.DEFAULT; + var strokePattern = g.getOption("strokePattern", setName); + var drawPoints = g.getBooleanOption("drawPoints", setName); + var pointSize = g.getNumericOption("pointSize", setName); + + if (borderWidth && strokeWidth) { + DygraphCanvasRenderer._drawStyledLine(e, + g.getOption("strokeBorderColor", setName), + strokeWidth + 2 * borderWidth, + strokePattern, + drawPoints, + drawPointCallback, + pointSize + ); + } + + DygraphCanvasRenderer._drawStyledLine(e, + e.color, + strokeWidth, + strokePattern, + drawPoints, + drawPointCallback, + pointSize + ); +}; + +/** + * Draws the shaded error bars/confidence intervals for each series. + * This happens before the center lines are drawn, since the center lines + * need to be drawn on top of the error bars for all series. + * @private + */ +DygraphCanvasRenderer._errorPlotter = function(e) { + var g = e.dygraph; + var setName = e.setName; + var errorBars = g.getBooleanOption("errorBars") || + g.getBooleanOption("customBars"); + if (!errorBars) return; + + var fillGraph = g.getBooleanOption("fillGraph", setName); + if (fillGraph) { + console.warn("Can't use fillGraph option with error bars"); + } + + var ctx = e.drawingContext; + var color = e.color; + var fillAlpha = g.getNumericOption('fillAlpha', setName); + var stepPlot = g.getBooleanOption("stepPlot", setName); + var points = e.points; + + var iter = Dygraph.createIterator(points, 0, points.length, + DygraphCanvasRenderer._getIteratorPredicate( + g.getBooleanOption("connectSeparatedPoints", setName))); + + var newYs; + + // setup graphics context + var prevX = NaN; + var prevY = NaN; + var prevYs = [-1, -1]; + // should be same color as the lines but only 15% opaque. + var rgb = Dygraph.toRGB_(color); + var err_color = + 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + fillAlpha + ')'; + ctx.fillStyle = err_color; + ctx.beginPath(); + + var isNullUndefinedOrNaN = function(x) { + return (x === null || + x === undefined || + isNaN(x)); + }; + + while (iter.hasNext) { + var point = iter.next(); + if ((!stepPlot && isNullUndefinedOrNaN(point.y)) || + (stepPlot && !isNaN(prevY) && isNullUndefinedOrNaN(prevY))) { + prevX = NaN; + continue; + } + + newYs = [ point.y_bottom, point.y_top ]; + if (stepPlot) { + prevY = point.y; + } + + // The documentation specifically disallows nulls inside the point arrays, + // but in case it happens we should do something sensible. + if (isNaN(newYs[0])) newYs[0] = point.y; + if (isNaN(newYs[1])) newYs[1] = point.y; + + newYs[0] = e.plotArea.h * newYs[0] + e.plotArea.y; + newYs[1] = e.plotArea.h * newYs[1] + e.plotArea.y; + if (!isNaN(prevX)) { + if (stepPlot) { + ctx.moveTo(prevX, prevYs[0]); + ctx.lineTo(point.canvasx, prevYs[0]); + ctx.lineTo(point.canvasx, prevYs[1]); + } else { + ctx.moveTo(prevX, prevYs[0]); + ctx.lineTo(point.canvasx, newYs[0]); + ctx.lineTo(point.canvasx, newYs[1]); + } + ctx.lineTo(prevX, prevYs[1]); + ctx.closePath(); + } + prevYs = newYs; + prevX = point.canvasx; + } + ctx.fill(); +}; + + +/** + * Proxy for CanvasRenderingContext2D which drops moveTo/lineTo calls which are + * superfluous. It accumulates all movements which haven't changed the x-value + * and only applies the two with the most extreme y-values. + * + * Calls to lineTo/moveTo must have non-decreasing x-values. + */ +DygraphCanvasRenderer._fastCanvasProxy = function(context) { + var pendingActions = []; // array of [type, x, y] tuples + var lastRoundedX = null; + var lastFlushedX = null; + + var LINE_TO = 1, + MOVE_TO = 2; + + var actionCount = 0; // number of moveTos and lineTos passed to context. + + // Drop superfluous motions + // Assumes all pendingActions have the same (rounded) x-value. + var compressActions = function(opt_losslessOnly) { + if (pendingActions.length <= 1) return; + + // Lossless compression: drop inconsequential moveTos. + for (var i = pendingActions.length - 1; i > 0; i--) { + var action = pendingActions[i]; + if (action[0] == MOVE_TO) { + var prevAction = pendingActions[i - 1]; + if (prevAction[1] == action[1] && prevAction[2] == action[2]) { + pendingActions.splice(i, 1); + } + } + } + + // Lossless compression: ... drop consecutive moveTos ... + for (var i = 0; i < pendingActions.length - 1; /* incremented internally */) { + var action = pendingActions[i]; + if (action[0] == MOVE_TO && pendingActions[i + 1][0] == MOVE_TO) { + pendingActions.splice(i, 1); + } else { + i++; + } + } + + // Lossy compression: ... drop all but the extreme y-values ... + if (pendingActions.length > 2 && !opt_losslessOnly) { + // keep an initial moveTo, but drop all others. + var startIdx = 0; + if (pendingActions[0][0] == MOVE_TO) startIdx++; + var minIdx = null, maxIdx = null; + for (var i = startIdx; i < pendingActions.length; i++) { + var action = pendingActions[i]; + if (action[0] != LINE_TO) continue; + if (minIdx === null && maxIdx === null) { + minIdx = i; + maxIdx = i; + } else { + var y = action[2]; + if (y < pendingActions[minIdx][2]) { + minIdx = i; + } else if (y > pendingActions[maxIdx][2]) { + maxIdx = i; + } + } + } + var minAction = pendingActions[minIdx], + maxAction = pendingActions[maxIdx]; + pendingActions.splice(startIdx, pendingActions.length - startIdx); + if (minIdx < maxIdx) { + pendingActions.push(minAction); + pendingActions.push(maxAction); + } else if (minIdx > maxIdx) { + pendingActions.push(maxAction); + pendingActions.push(minAction); + } else { + pendingActions.push(minAction); + } + } + }; + + var flushActions = function(opt_noLossyCompression) { + compressActions(opt_noLossyCompression); + for (var i = 0, len = pendingActions.length; i < len; i++) { + var action = pendingActions[i]; + if (action[0] == LINE_TO) { + context.lineTo(action[1], action[2]); + } else if (action[0] == MOVE_TO) { + context.moveTo(action[1], action[2]); + } + } + if (pendingActions.length) { + lastFlushedX = pendingActions[pendingActions.length - 1][1]; + } + actionCount += pendingActions.length; + pendingActions = []; + }; + + var addAction = function(action, x, y) { + var rx = Math.round(x); + if (lastRoundedX === null || rx != lastRoundedX) { + // if there are large gaps on the x-axis, it's essential to keep the + // first and last point as well. + var hasGapOnLeft = (lastRoundedX - lastFlushedX > 1), + hasGapOnRight = (rx - lastRoundedX > 1), + hasGap = hasGapOnLeft || hasGapOnRight; + flushActions(hasGap); + lastRoundedX = rx; + } + pendingActions.push([action, x, y]); + }; + + return { + moveTo: function(x, y) { + addAction(MOVE_TO, x, y); + }, + lineTo: function(x, y) { + addAction(LINE_TO, x, y); + }, + + // for major operations like stroke/fill, we skip compression to ensure + // that there are no artifacts at the right edge. + stroke: function() { flushActions(true); context.stroke(); }, + fill: function() { flushActions(true); context.fill(); }, + beginPath: function() { flushActions(true); context.beginPath(); }, + closePath: function() { flushActions(true); context.closePath(); }, + + _count: function() { return actionCount; } + }; +}; + +/** + * Draws the shaded regions when "fillGraph" is set. Not to be confused with + * error bars. + * + * For stacked charts, it's more convenient to handle all the series + * simultaneously. So this plotter plots all the points on the first series + * it's asked to draw, then ignores all the other series. + * + * @private + */ +DygraphCanvasRenderer._fillPlotter = function(e) { + // Skip if we're drawing a single series for interactive highlight overlay. + if (e.singleSeriesName) return; + + // We'll handle all the series at once, not one-by-one. + if (e.seriesIndex !== 0) return; + + var g = e.dygraph; + var setNames = g.getLabels().slice(1); // remove x-axis + + // getLabels() includes names for invisible series, which are not included in + // allSeriesPoints. We remove those to make the two match. + // TODO(danvk): provide a simpler way to get this information. + for (var i = setNames.length; i >= 0; i--) { + if (!g.visibility()[i]) setNames.splice(i, 1); + } + + var anySeriesFilled = (function() { + for (var i = 0; i < setNames.length; i++) { + if (g.getBooleanOption("fillGraph", setNames[i])) return true; + } + return false; + })(); + + if (!anySeriesFilled) return; + + var area = e.plotArea; + var sets = e.allSeriesPoints; + var setCount = sets.length; + + var fillAlpha = g.getNumericOption('fillAlpha'); + var stackedGraph = g.getBooleanOption("stackedGraph"); + var colors = g.getColors(); + + // For stacked graphs, track the baseline for filling. + // + // The filled areas below graph lines are trapezoids with two + // vertical edges. The top edge is the line segment being drawn, and + // the baseline is the bottom edge. Each baseline corresponds to the + // top line segment from the previous stacked line. In the case of + // step plots, the trapezoids are rectangles. + var baseline = {}; + var currBaseline; + var prevStepPlot; // for different line drawing modes (line/step) per series + + // Helper function to trace a line back along the baseline. + var traceBackPath = function(ctx, baselineX, baselineY, pathBack) { + ctx.lineTo(baselineX, baselineY); + if (stackedGraph) { + for (var i = pathBack.length - 1; i >= 0; i--) { + var pt = pathBack[i]; + ctx.lineTo(pt[0], pt[1]); + } + } + }; + + // process sets in reverse order (needed for stacked graphs) + for (var setIdx = setCount - 1; setIdx >= 0; setIdx--) { + var ctx = e.drawingContext; + var setName = setNames[setIdx]; + if (!g.getBooleanOption('fillGraph', setName)) continue; + + var stepPlot = g.getBooleanOption('stepPlot', setName); + var color = colors[setIdx]; + var axis = g.axisPropertiesForSeries(setName); + var axisY = 1.0 + axis.minyval * axis.yscale; + if (axisY < 0.0) axisY = 0.0; + else if (axisY > 1.0) axisY = 1.0; + axisY = area.h * axisY + area.y; + + var points = sets[setIdx]; + var iter = Dygraph.createIterator(points, 0, points.length, + DygraphCanvasRenderer._getIteratorPredicate( + g.getBooleanOption("connectSeparatedPoints", setName))); + + // setup graphics context + var prevX = NaN; + var prevYs = [-1, -1]; + var newYs; + // should be same color as the lines but only 15% opaque. + var rgb = Dygraph.toRGB_(color); + var err_color = + 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + fillAlpha + ')'; + ctx.fillStyle = err_color; + ctx.beginPath(); + var last_x, is_first = true; + + // If the point density is high enough, dropping segments on their way to + // the canvas justifies the overhead of doing so. + if (points.length > 2 * g.width_ || Dygraph.FORCE_FAST_PROXY) { + ctx = DygraphCanvasRenderer._fastCanvasProxy(ctx); + } + + // For filled charts, we draw points from left to right, then back along + // the x-axis to complete a shape for filling. + // For stacked plots, this "back path" is a more complex shape. This array + // stores the [x, y] values needed to trace that shape. + var pathBack = []; + + // TODO(danvk): there are a lot of options at play in this loop. + // The logic would be much clearer if some (e.g. stackGraph and + // stepPlot) were split off into separate sub-plotters. + var point; + while (iter.hasNext) { + point = iter.next(); + if (!Dygraph.isOK(point.y) && !stepPlot) { + traceBackPath(ctx, prevX, prevYs[1], pathBack); + pathBack = []; + prevX = NaN; + if (point.y_stacked !== null && !isNaN(point.y_stacked)) { + baseline[point.canvasx] = area.h * point.y_stacked + area.y; + } + continue; + } + if (stackedGraph) { + if (!is_first && last_x == point.xval) { + continue; + } else { + is_first = false; + last_x = point.xval; + } + + currBaseline = baseline[point.canvasx]; + var lastY; + if (currBaseline === undefined) { + lastY = axisY; + } else { + if(prevStepPlot) { + lastY = currBaseline[0]; + } else { + lastY = currBaseline; + } + } + newYs = [ point.canvasy, lastY ]; + + if (stepPlot) { + // Step plots must keep track of the top and bottom of + // the baseline at each point. + if (prevYs[0] === -1) { + baseline[point.canvasx] = [ point.canvasy, axisY ]; + } else { + baseline[point.canvasx] = [ point.canvasy, prevYs[0] ]; + } + } else { + baseline[point.canvasx] = point.canvasy; + } + + } else { + if (isNaN(point.canvasy) && stepPlot) { + newYs = [ area.y + area.h, axisY ]; + } else { + newYs = [ point.canvasy, axisY ]; + } + } + if (!isNaN(prevX)) { + // Move to top fill point + if (stepPlot) { + ctx.lineTo(point.canvasx, prevYs[0]); + ctx.lineTo(point.canvasx, newYs[0]); + } else { + ctx.lineTo(point.canvasx, newYs[0]); + } + + // Record the baseline for the reverse path. + if (stackedGraph) { + pathBack.push([prevX, prevYs[1]]); + if (prevStepPlot && currBaseline) { + // Draw to the bottom of the baseline + pathBack.push([point.canvasx, currBaseline[1]]); + } else { + pathBack.push([point.canvasx, newYs[1]]); + } + } + } else { + ctx.moveTo(point.canvasx, newYs[1]); + ctx.lineTo(point.canvasx, newYs[0]); + } + prevYs = newYs; + prevX = point.canvasx; + } + prevStepPlot = stepPlot; + if (newYs && point) { + traceBackPath(ctx, point.canvasx, newYs[1], pathBack); + pathBack = []; + } + ctx.fill(); + } +}; + +return DygraphCanvasRenderer; + +})(); +/** + * @license + * Copyright 2006 Dan Vanderkam (danvdk@gmail.com) + * MIT-licensed (http://opensource.org/licenses/MIT) + */ + +/** + * @fileoverview Creates an interactive, zoomable graph based on a CSV file or + * string. Dygraph can handle multiple series with or without error bars. The + * date/value ranges will be automatically set. Dygraph uses the + * <canvas> tag, so it only works in FF1.5+. + * @author danvdk@gmail.com (Dan Vanderkam) + + Usage: +
+ + + The CSV file is of the form + + Date,SeriesA,SeriesB,SeriesC + YYYYMMDD,A1,B1,C1 + YYYYMMDD,A2,B2,C2 + + If the 'errorBars' option is set in the constructor, the input should be of + the form + Date,SeriesA,SeriesB,... + YYYYMMDD,A1,sigmaA1,B1,sigmaB1,... + YYYYMMDD,A2,sigmaA2,B2,sigmaB2,... + + If the 'fractions' option is set, the input should be of the form: + + Date,SeriesA,SeriesB,... + YYYYMMDD,A1/B1,A2/B2,... + YYYYMMDD,A1/B1,A2/B2,... + + And error bars will be calculated automatically using a binomial distribution. + + For further documentation and examples, see http://dygraphs.com/ + + */ + +// For "production" code, this gets set to false by uglifyjs. +if (typeof(DEBUG) === 'undefined') DEBUG=true; + +var Dygraph = (function() { +/*global DygraphLayout:false, DygraphCanvasRenderer:false, DygraphOptions:false, G_vmlCanvasManager:false,ActiveXObject:false */ +"use strict"; + +/** + * Creates an interactive, zoomable chart. + * + * @constructor + * @param {div | String} div A div or the id of a div into which to construct + * the chart. + * @param {String | Function} file A file containing CSV data or a function + * that returns this data. The most basic expected format for each line is + * "YYYY/MM/DD,val1,val2,...". For more information, see + * http://dygraphs.com/data.html. + * @param {Object} attrs Various other attributes, e.g. errorBars determines + * whether the input data contains error ranges. For a complete list of + * options, see http://dygraphs.com/options.html. + */ +var Dygraph = function(div, data, opts, opt_fourth_param) { + // These have to go above the "Hack for IE" in __init__ since .ready() can be + // called as soon as the constructor returns. Once support for OldIE is + // dropped, this can go down with the rest of the initializers. + this.is_initial_draw_ = true; + this.readyFns_ = []; + + if (opt_fourth_param !== undefined) { + // Old versions of dygraphs took in the series labels as a constructor + // parameter. This doesn't make sense anymore, but it's easy to continue + // to support this usage. + console.warn("Using deprecated four-argument dygraph constructor"); + this.__old_init__(div, data, opts, opt_fourth_param); + } else { + this.__init__(div, data, opts); + } +}; + +Dygraph.NAME = "Dygraph"; +Dygraph.VERSION = "1.1.1"; +Dygraph.__repr__ = function() { + return "[" + Dygraph.NAME + " " + Dygraph.VERSION + "]"; +}; + +/** + * Returns information about the Dygraph class. + */ +Dygraph.toString = function() { + return Dygraph.__repr__(); +}; + +// Various default values +Dygraph.DEFAULT_ROLL_PERIOD = 1; +Dygraph.DEFAULT_WIDTH = 480; +Dygraph.DEFAULT_HEIGHT = 320; + +// For max 60 Hz. animation: +Dygraph.ANIMATION_STEPS = 12; +Dygraph.ANIMATION_DURATION = 200; + +// Label constants for the labelsKMB and labelsKMG2 options. +// (i.e. '100000' -> '100K') +Dygraph.KMB_LABELS = [ 'K', 'M', 'B', 'T', 'Q' ]; +Dygraph.KMG2_BIG_LABELS = [ 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y' ]; +Dygraph.KMG2_SMALL_LABELS = [ 'm', 'u', 'n', 'p', 'f', 'a', 'z', 'y' ]; + +// These are defined before DEFAULT_ATTRS so that it can refer to them. +/** + * @private + * Return a string version of a number. This respects the digitsAfterDecimal + * and maxNumberWidth options. + * @param {number} x The number to be formatted + * @param {Dygraph} opts An options view + */ +Dygraph.numberValueFormatter = function(x, opts) { + var sigFigs = opts('sigFigs'); + + if (sigFigs !== null) { + // User has opted for a fixed number of significant figures. + return Dygraph.floatFormat(x, sigFigs); + } + + var digits = opts('digitsAfterDecimal'); + var maxNumberWidth = opts('maxNumberWidth'); + + var kmb = opts('labelsKMB'); + var kmg2 = opts('labelsKMG2'); + + var label; + + // switch to scientific notation if we underflow or overflow fixed display. + if (x !== 0.0 && + (Math.abs(x) >= Math.pow(10, maxNumberWidth) || + Math.abs(x) < Math.pow(10, -digits))) { + label = x.toExponential(digits); + } else { + label = '' + Dygraph.round_(x, digits); + } + + if (kmb || kmg2) { + var k; + var k_labels = []; + var m_labels = []; + if (kmb) { + k = 1000; + k_labels = Dygraph.KMB_LABELS; + } + if (kmg2) { + if (kmb) console.warn("Setting both labelsKMB and labelsKMG2. Pick one!"); + k = 1024; + k_labels = Dygraph.KMG2_BIG_LABELS; + m_labels = Dygraph.KMG2_SMALL_LABELS; + } + + var absx = Math.abs(x); + var n = Dygraph.pow(k, k_labels.length); + for (var j = k_labels.length - 1; j >= 0; j--, n /= k) { + if (absx >= n) { + label = Dygraph.round_(x / n, digits) + k_labels[j]; + break; + } + } + if (kmg2) { + // TODO(danvk): clean up this logic. Why so different than kmb? + var x_parts = String(x.toExponential()).split('e-'); + if (x_parts.length === 2 && x_parts[1] >= 3 && x_parts[1] <= 24) { + if (x_parts[1] % 3 > 0) { + label = Dygraph.round_(x_parts[0] / + Dygraph.pow(10, (x_parts[1] % 3)), + digits); + } else { + label = Number(x_parts[0]).toFixed(2); + } + label += m_labels[Math.floor(x_parts[1] / 3) - 1]; + } + } + } + + return label; +}; + +/** + * variant for use as an axisLabelFormatter. + * @private + */ +Dygraph.numberAxisLabelFormatter = function(x, granularity, opts) { + return Dygraph.numberValueFormatter.call(this, x, opts); +}; + +/** + * @type {!Array.} + * @private + * @constant + */ +Dygraph.SHORT_MONTH_NAMES_ = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; + + +/** + * Convert a JS date to a string appropriate to display on an axis that + * is displaying values at the stated granularity. This respects the + * labelsUTC option. + * @param {Date} date The date to format + * @param {number} granularity One of the Dygraph granularity constants + * @param {Dygraph} opts An options view + * @return {string} The date formatted as local time + * @private + */ +Dygraph.dateAxisLabelFormatter = function(date, granularity, opts) { + var utc = opts('labelsUTC'); + var accessors = utc ? Dygraph.DateAccessorsUTC : Dygraph.DateAccessorsLocal; + + var year = accessors.getFullYear(date), + month = accessors.getMonth(date), + day = accessors.getDate(date), + hours = accessors.getHours(date), + mins = accessors.getMinutes(date), + secs = accessors.getSeconds(date), + millis = accessors.getSeconds(date); + + if (granularity >= Dygraph.DECADAL) { + return '' + year; + } else if (granularity >= Dygraph.MONTHLY) { + return Dygraph.SHORT_MONTH_NAMES_[month] + ' ' + year; + } else { + var frac = hours * 3600 + mins * 60 + secs + 1e-3 * millis; + if (frac === 0 || granularity >= Dygraph.DAILY) { + // e.g. '21 Jan' (%d%b) + return Dygraph.zeropad(day) + ' ' + Dygraph.SHORT_MONTH_NAMES_[month]; + } else { + return Dygraph.hmsString_(hours, mins, secs); + } + } +}; +// alias in case anyone is referencing the old method. +Dygraph.dateAxisFormatter = Dygraph.dateAxisLabelFormatter; + +/** + * Return a string version of a JS date for a value label. This respects the + * labelsUTC option. + * @param {Date} date The date to be formatted + * @param {Dygraph} opts An options view + * @private + */ +Dygraph.dateValueFormatter = function(d, opts) { + return Dygraph.dateString_(d, opts('labelsUTC')); +}; + +/** + * Standard plotters. These may be used by clients. + * Available plotters are: + * - Dygraph.Plotters.linePlotter: draws central lines (most common) + * - Dygraph.Plotters.errorPlotter: draws error bars + * - Dygraph.Plotters.fillPlotter: draws fills under lines (used with fillGraph) + * + * By default, the plotter is [fillPlotter, errorPlotter, linePlotter]. + * This causes all the lines to be drawn over all the fills/error bars. + */ +Dygraph.Plotters = DygraphCanvasRenderer._Plotters; + + +// Default attribute values. +Dygraph.DEFAULT_ATTRS = { + highlightCircleSize: 3, + highlightSeriesOpts: null, + highlightSeriesBackgroundAlpha: 0.5, + + labelsDivWidth: 250, + labelsDivStyles: { + // TODO(danvk): move defaults from createStatusMessage_ here. + }, + labelsSeparateLines: false, + labelsShowZeroValues: true, + labelsKMB: false, + labelsKMG2: false, + showLabelsOnHighlight: true, + + digitsAfterDecimal: 2, + maxNumberWidth: 6, + sigFigs: null, + + strokeWidth: 1.0, + strokeBorderWidth: 0, + strokeBorderColor: "white", + + axisTickSize: 3, + axisLabelFontSize: 14, + rightGap: 5, + + showRoller: false, + xValueParser: Dygraph.dateParser, + + delimiter: ',', + + sigma: 2.0, + errorBars: false, + fractions: false, + wilsonInterval: true, // only relevant if fractions is true + customBars: false, + fillGraph: false, + fillAlpha: 0.15, + connectSeparatedPoints: false, + + stackedGraph: false, + stackedGraphNaNFill: 'all', + hideOverlayOnMouseOut: true, + + legend: 'onmouseover', + stepPlot: false, + avoidMinZero: false, + xRangePad: 0, + yRangePad: null, + drawAxesAtZero: false, + + // Sizes of the various chart labels. + titleHeight: 28, + xLabelHeight: 18, + yLabelWidth: 18, + + drawXAxis: true, + drawYAxis: true, + axisLineColor: "black", + axisLineWidth: 0.3, + gridLineWidth: 0.3, + axisLabelColor: "black", + axisLabelWidth: 50, + drawYGrid: true, + drawXGrid: true, + gridLineColor: "rgb(128,128,128)", + + interactionModel: null, // will be set to Dygraph.Interaction.defaultModel + animatedZooms: false, // (for now) + + // Range selector options + showRangeSelector: false, + rangeSelectorHeight: 40, + rangeSelectorPlotStrokeColor: "#808FAB", + rangeSelectorPlotFillColor: "#A7B1C4", + showInRangeSelector: null, + + // The ordering here ensures that central lines always appear above any + // fill bars/error bars. + plotter: [ + Dygraph.Plotters.fillPlotter, + Dygraph.Plotters.errorPlotter, + Dygraph.Plotters.linePlotter + ], + + plugins: [ ], + + // per-axis options + axes: { + x: { + pixelsPerLabel: 70, + axisLabelWidth: 60, + axisLabelFormatter: Dygraph.dateAxisLabelFormatter, + valueFormatter: Dygraph.dateValueFormatter, + drawGrid: true, + drawAxis: true, + independentTicks: true, + ticker: null // will be set in dygraph-tickers.js + }, + y: { + axisLabelWidth: 50, + pixelsPerLabel: 30, + valueFormatter: Dygraph.numberValueFormatter, + axisLabelFormatter: Dygraph.numberAxisLabelFormatter, + drawGrid: true, + drawAxis: true, + independentTicks: true, + ticker: null // will be set in dygraph-tickers.js + }, + y2: { + axisLabelWidth: 50, + pixelsPerLabel: 30, + valueFormatter: Dygraph.numberValueFormatter, + axisLabelFormatter: Dygraph.numberAxisLabelFormatter, + drawAxis: true, // only applies when there are two axes of data. + drawGrid: false, + independentTicks: false, + ticker: null // will be set in dygraph-tickers.js + } + } +}; + +// Directions for panning and zooming. Use bit operations when combined +// values are possible. +Dygraph.HORIZONTAL = 1; +Dygraph.VERTICAL = 2; + +// Installed plugins, in order of precedence (most-general to most-specific). +// Plugins are installed after they are defined, in plugins/install.js. +Dygraph.PLUGINS = [ +]; + +// Used for initializing annotation CSS rules only once. +Dygraph.addedAnnotationCSS = false; + +Dygraph.prototype.__old_init__ = function(div, file, labels, attrs) { + // Labels is no longer a constructor parameter, since it's typically set + // directly from the data source. It also conains a name for the x-axis, + // which the previous constructor form did not. + if (labels !== null) { + var new_labels = ["Date"]; + for (var i = 0; i < labels.length; i++) new_labels.push(labels[i]); + Dygraph.update(attrs, { 'labels': new_labels }); + } + this.__init__(div, file, attrs); +}; + +/** + * Initializes the Dygraph. This creates a new DIV and constructs the PlotKit + * and context <canvas> inside of it. See the constructor for details. + * on the parameters. + * @param {Element} div the Element to render the graph into. + * @param {string | Function} file Source data + * @param {Object} attrs Miscellaneous other options + * @private + */ +Dygraph.prototype.__init__ = function(div, file, attrs) { + // Hack for IE: if we're using excanvas and the document hasn't finished + // loading yet (and hence may not have initialized whatever it needs to + // initialize), then keep calling this routine periodically until it has. + if (/MSIE/.test(navigator.userAgent) && !window.opera && + typeof(G_vmlCanvasManager) != 'undefined' && + document.readyState != 'complete') { + var self = this; + setTimeout(function() { self.__init__(div, file, attrs); }, 100); + return; + } + + // Support two-argument constructor + if (attrs === null || attrs === undefined) { attrs = {}; } + + attrs = Dygraph.mapLegacyOptions_(attrs); + + if (typeof(div) == 'string') { + div = document.getElementById(div); + } + + if (!div) { + console.error("Constructing dygraph with a non-existent div!"); + return; + } + + this.isUsingExcanvas_ = typeof(G_vmlCanvasManager) != 'undefined'; + + // Copy the important bits into the object + // TODO(danvk): most of these should just stay in the attrs_ dictionary. + this.maindiv_ = div; + this.file_ = file; + this.rollPeriod_ = attrs.rollPeriod || Dygraph.DEFAULT_ROLL_PERIOD; + this.previousVerticalX_ = -1; + this.fractions_ = attrs.fractions || false; + this.dateWindow_ = attrs.dateWindow || null; + + this.annotations_ = []; + + // Zoomed indicators - These indicate when the graph has been zoomed and on what axis. + this.zoomed_x_ = false; + this.zoomed_y_ = false; + + // Clear the div. This ensure that, if multiple dygraphs are passed the same + // div, then only one will be drawn. + div.innerHTML = ""; + + // For historical reasons, the 'width' and 'height' options trump all CSS + // rules _except_ for an explicit 'width' or 'height' on the div. + // As an added convenience, if the div has zero height (like
does + // without any styles), then we use a default height/width. + if (div.style.width === '' && attrs.width) { + div.style.width = attrs.width + "px"; + } + if (div.style.height === '' && attrs.height) { + div.style.height = attrs.height + "px"; + } + if (div.style.height === '' && div.clientHeight === 0) { + div.style.height = Dygraph.DEFAULT_HEIGHT + "px"; + if (div.style.width === '') { + div.style.width = Dygraph.DEFAULT_WIDTH + "px"; + } + } + // These will be zero if the dygraph's div is hidden. In that case, + // use the user-specified attributes if present. If not, use zero + // and assume the user will call resize to fix things later. + this.width_ = div.clientWidth || attrs.width || 0; + this.height_ = div.clientHeight || attrs.height || 0; + + // TODO(danvk): set fillGraph to be part of attrs_ here, not user_attrs_. + if (attrs.stackedGraph) { + attrs.fillGraph = true; + // TODO(nikhilk): Add any other stackedGraph checks here. + } + + // DEPRECATION WARNING: All option processing should be moved from + // attrs_ and user_attrs_ to options_, which holds all this information. + // + // Dygraphs has many options, some of which interact with one another. + // To keep track of everything, we maintain two sets of options: + // + // this.user_attrs_ only options explicitly set by the user. + // this.attrs_ defaults, options derived from user_attrs_, data. + // + // Options are then accessed this.attr_('attr'), which first looks at + // user_attrs_ and then computed attrs_. This way Dygraphs can set intelligent + // defaults without overriding behavior that the user specifically asks for. + this.user_attrs_ = {}; + Dygraph.update(this.user_attrs_, attrs); + + // This sequence ensures that Dygraph.DEFAULT_ATTRS is never modified. + this.attrs_ = {}; + Dygraph.updateDeep(this.attrs_, Dygraph.DEFAULT_ATTRS); + + this.boundaryIds_ = []; + this.setIndexByName_ = {}; + this.datasetIndex_ = []; + + this.registeredEvents_ = []; + this.eventListeners_ = {}; + + this.attributes_ = new DygraphOptions(this); + + // Create the containing DIV and other interactive elements + this.createInterface_(); + + // Activate plugins. + this.plugins_ = []; + var plugins = Dygraph.PLUGINS.concat(this.getOption('plugins')); + for (var i = 0; i < plugins.length; i++) { + // the plugins option may contain either plugin classes or instances. + // Plugin instances contain an activate method. + var Plugin = plugins[i]; // either a constructor or an instance. + var pluginInstance; + if (typeof(Plugin.activate) !== 'undefined') { + pluginInstance = Plugin; + } else { + pluginInstance = new Plugin(); + } + + var pluginDict = { + plugin: pluginInstance, + events: {}, + options: {}, + pluginOptions: {} + }; + + var handlers = pluginInstance.activate(this); + for (var eventName in handlers) { + if (!handlers.hasOwnProperty(eventName)) continue; + // TODO(danvk): validate eventName. + pluginDict.events[eventName] = handlers[eventName]; + } + + this.plugins_.push(pluginDict); + } + + // At this point, plugins can no longer register event handlers. + // Construct a map from event -> ordered list of [callback, plugin]. + for (var i = 0; i < this.plugins_.length; i++) { + var plugin_dict = this.plugins_[i]; + for (var eventName in plugin_dict.events) { + if (!plugin_dict.events.hasOwnProperty(eventName)) continue; + var callback = plugin_dict.events[eventName]; + + var pair = [plugin_dict.plugin, callback]; + if (!(eventName in this.eventListeners_)) { + this.eventListeners_[eventName] = [pair]; + } else { + this.eventListeners_[eventName].push(pair); + } + } + } + + this.createDragInterface_(); + + this.start_(); +}; + +/** + * Triggers a cascade of events to the various plugins which are interested in them. + * Returns true if the "default behavior" should be prevented, i.e. if one + * of the event listeners called event.preventDefault(). + * @private + */ +Dygraph.prototype.cascadeEvents_ = function(name, extra_props) { + if (!(name in this.eventListeners_)) return false; + + // QUESTION: can we use objects & prototypes to speed this up? + var e = { + dygraph: this, + cancelable: false, + defaultPrevented: false, + preventDefault: function() { + if (!e.cancelable) throw "Cannot call preventDefault on non-cancelable event."; + e.defaultPrevented = true; + }, + propagationStopped: false, + stopPropagation: function() { + e.propagationStopped = true; + } + }; + Dygraph.update(e, extra_props); + + var callback_plugin_pairs = this.eventListeners_[name]; + if (callback_plugin_pairs) { + for (var i = callback_plugin_pairs.length - 1; i >= 0; i--) { + var plugin = callback_plugin_pairs[i][0]; + var callback = callback_plugin_pairs[i][1]; + callback.call(plugin, e); + if (e.propagationStopped) break; + } + } + return e.defaultPrevented; +}; + +/** + * Fetch a plugin instance of a particular class. Only for testing. + * @private + * @param {!Class} type The type of the plugin. + * @return {Object} Instance of the plugin, or null if there is none. + */ +Dygraph.prototype.getPluginInstance_ = function(type) { + for (var i = 0; i < this.plugins_.length; i++) { + var p = this.plugins_[i]; + if (p.plugin instanceof type) { + return p.plugin; + } + } + return null; +}; + +/** + * Returns the zoomed status of the chart for one or both axes. + * + * Axis is an optional parameter. Can be set to 'x' or 'y'. + * + * The zoomed status for an axis is set whenever a user zooms using the mouse + * or when the dateWindow or valueRange are updated (unless the + * isZoomedIgnoreProgrammaticZoom option is also specified). + */ +Dygraph.prototype.isZoomed = function(axis) { + if (axis === null || axis === undefined) { + return this.zoomed_x_ || this.zoomed_y_; + } + if (axis === 'x') return this.zoomed_x_; + if (axis === 'y') return this.zoomed_y_; + throw "axis parameter is [" + axis + "] must be null, 'x' or 'y'."; +}; + +/** + * Returns information about the Dygraph object, including its containing ID. + */ +Dygraph.prototype.toString = function() { + var maindiv = this.maindiv_; + var id = (maindiv && maindiv.id) ? maindiv.id : maindiv; + return "[Dygraph " + id + "]"; +}; + +/** + * @private + * Returns the value of an option. This may be set by the user (either in the + * constructor or by calling updateOptions) or by dygraphs, and may be set to a + * per-series value. + * @param {string} name The name of the option, e.g. 'rollPeriod'. + * @param {string} [seriesName] The name of the series to which the option + * will be applied. If no per-series value of this option is available, then + * the global value is returned. This is optional. + * @return { ... } The value of the option. + */ +Dygraph.prototype.attr_ = function(name, seriesName) { + if (DEBUG) { + if (typeof(Dygraph.OPTIONS_REFERENCE) === 'undefined') { + console.error('Must include options reference JS for testing'); + } else if (!Dygraph.OPTIONS_REFERENCE.hasOwnProperty(name)) { + console.error('Dygraphs is using property ' + name + ', which has no ' + + 'entry in the Dygraphs.OPTIONS_REFERENCE listing.'); + // Only log this error once. + Dygraph.OPTIONS_REFERENCE[name] = true; + } + } + return seriesName ? this.attributes_.getForSeries(name, seriesName) : this.attributes_.get(name); +}; + +/** + * Returns the current value for an option, as set in the constructor or via + * updateOptions. You may pass in an (optional) series name to get per-series + * values for the option. + * + * All values returned by this method should be considered immutable. If you + * modify them, there is no guarantee that the changes will be honored or that + * dygraphs will remain in a consistent state. If you want to modify an option, + * use updateOptions() instead. + * + * @param {string} name The name of the option (e.g. 'strokeWidth') + * @param {string=} opt_seriesName Series name to get per-series values. + * @return {*} The value of the option. + */ +Dygraph.prototype.getOption = function(name, opt_seriesName) { + return this.attr_(name, opt_seriesName); +}; + +/** + * Like getOption(), but specifically returns a number. + * This is a convenience function for working with the Closure Compiler. + * @param {string} name The name of the option (e.g. 'strokeWidth') + * @param {string=} opt_seriesName Series name to get per-series values. + * @return {number} The value of the option. + * @private + */ +Dygraph.prototype.getNumericOption = function(name, opt_seriesName) { + return /** @type{number} */(this.getOption(name, opt_seriesName)); +}; + +/** + * Like getOption(), but specifically returns a string. + * This is a convenience function for working with the Closure Compiler. + * @param {string} name The name of the option (e.g. 'strokeWidth') + * @param {string=} opt_seriesName Series name to get per-series values. + * @return {string} The value of the option. + * @private + */ +Dygraph.prototype.getStringOption = function(name, opt_seriesName) { + return /** @type{string} */(this.getOption(name, opt_seriesName)); +}; + +/** + * Like getOption(), but specifically returns a boolean. + * This is a convenience function for working with the Closure Compiler. + * @param {string} name The name of the option (e.g. 'strokeWidth') + * @param {string=} opt_seriesName Series name to get per-series values. + * @return {boolean} The value of the option. + * @private + */ +Dygraph.prototype.getBooleanOption = function(name, opt_seriesName) { + return /** @type{boolean} */(this.getOption(name, opt_seriesName)); +}; + +/** + * Like getOption(), but specifically returns a function. + * This is a convenience function for working with the Closure Compiler. + * @param {string} name The name of the option (e.g. 'strokeWidth') + * @param {string=} opt_seriesName Series name to get per-series values. + * @return {function(...)} The value of the option. + * @private + */ +Dygraph.prototype.getFunctionOption = function(name, opt_seriesName) { + return /** @type{function(...)} */(this.getOption(name, opt_seriesName)); +}; + +Dygraph.prototype.getOptionForAxis = function(name, axis) { + return this.attributes_.getForAxis(name, axis); +}; + +/** + * @private + * @param {string} axis The name of the axis (i.e. 'x', 'y' or 'y2') + * @return { ... } A function mapping string -> option value + */ +Dygraph.prototype.optionsViewForAxis_ = function(axis) { + var self = this; + return function(opt) { + var axis_opts = self.user_attrs_.axes; + if (axis_opts && axis_opts[axis] && axis_opts[axis].hasOwnProperty(opt)) { + return axis_opts[axis][opt]; + } + + // I don't like that this is in a second spot. + if (axis === 'x' && opt === 'logscale') { + // return the default value. + // TODO(konigsberg): pull the default from a global default. + return false; + } + + // user-specified attributes always trump defaults, even if they're less + // specific. + if (typeof(self.user_attrs_[opt]) != 'undefined') { + return self.user_attrs_[opt]; + } + + axis_opts = self.attrs_.axes; + if (axis_opts && axis_opts[axis] && axis_opts[axis].hasOwnProperty(opt)) { + return axis_opts[axis][opt]; + } + // check old-style axis options + // TODO(danvk): add a deprecation warning if either of these match. + if (axis == 'y' && self.axes_[0].hasOwnProperty(opt)) { + return self.axes_[0][opt]; + } else if (axis == 'y2' && self.axes_[1].hasOwnProperty(opt)) { + return self.axes_[1][opt]; + } + return self.attr_(opt); + }; +}; + +/** + * Returns the current rolling period, as set by the user or an option. + * @return {number} The number of points in the rolling window + */ +Dygraph.prototype.rollPeriod = function() { + return this.rollPeriod_; +}; + +/** + * Returns the currently-visible x-range. This can be affected by zooming, + * panning or a call to updateOptions. + * Returns a two-element array: [left, right]. + * If the Dygraph has dates on the x-axis, these will be millis since epoch. + */ +Dygraph.prototype.xAxisRange = function() { + return this.dateWindow_ ? this.dateWindow_ : this.xAxisExtremes(); +}; + +/** + * Returns the lower- and upper-bound x-axis values of the + * data set. + */ +Dygraph.prototype.xAxisExtremes = function() { + var pad = this.getNumericOption('xRangePad') / this.plotter_.area.w; + if (this.numRows() === 0) { + return [0 - pad, 1 + pad]; + } + var left = this.rawData_[0][0]; + var right = this.rawData_[this.rawData_.length - 1][0]; + if (pad) { + // Must keep this in sync with dygraph-layout _evaluateLimits() + var range = right - left; + left -= range * pad; + right += range * pad; + } + return [left, right]; +}; + +/** + * Returns the currently-visible y-range for an axis. This can be affected by + * zooming, panning or a call to updateOptions. Axis indices are zero-based. If + * called with no arguments, returns the range of the first axis. + * Returns a two-element array: [bottom, top]. + */ +Dygraph.prototype.yAxisRange = function(idx) { + if (typeof(idx) == "undefined") idx = 0; + if (idx < 0 || idx >= this.axes_.length) { + return null; + } + var axis = this.axes_[idx]; + return [ axis.computedValueRange[0], axis.computedValueRange[1] ]; +}; + +/** + * Returns the currently-visible y-ranges for each axis. This can be affected by + * zooming, panning, calls to updateOptions, etc. + * Returns an array of [bottom, top] pairs, one for each y-axis. + */ +Dygraph.prototype.yAxisRanges = function() { + var ret = []; + for (var i = 0; i < this.axes_.length; i++) { + ret.push(this.yAxisRange(i)); + } + return ret; +}; + +// TODO(danvk): use these functions throughout dygraphs. +/** + * Convert from data coordinates to canvas/div X/Y coordinates. + * If specified, do this conversion for the coordinate system of a particular + * axis. Uses the first axis by default. + * Returns a two-element array: [X, Y] + * + * Note: use toDomXCoord instead of toDomCoords(x, null) and use toDomYCoord + * instead of toDomCoords(null, y, axis). + */ +Dygraph.prototype.toDomCoords = function(x, y, axis) { + return [ this.toDomXCoord(x), this.toDomYCoord(y, axis) ]; +}; + +/** + * Convert from data x coordinates to canvas/div X coordinate. + * If specified, do this conversion for the coordinate system of a particular + * axis. + * Returns a single value or null if x is null. + */ +Dygraph.prototype.toDomXCoord = function(x) { + if (x === null) { + return null; + } + + var area = this.plotter_.area; + var xRange = this.xAxisRange(); + return area.x + (x - xRange[0]) / (xRange[1] - xRange[0]) * area.w; +}; + +/** + * Convert from data x coordinates to canvas/div Y coordinate and optional + * axis. Uses the first axis by default. + * + * returns a single value or null if y is null. + */ +Dygraph.prototype.toDomYCoord = function(y, axis) { + var pct = this.toPercentYCoord(y, axis); + + if (pct === null) { + return null; + } + var area = this.plotter_.area; + return area.y + pct * area.h; +}; + +/** + * Convert from canvas/div coords to data coordinates. + * If specified, do this conversion for the coordinate system of a particular + * axis. Uses the first axis by default. + * Returns a two-element array: [X, Y]. + * + * Note: use toDataXCoord instead of toDataCoords(x, null) and use toDataYCoord + * instead of toDataCoords(null, y, axis). + */ +Dygraph.prototype.toDataCoords = function(x, y, axis) { + return [ this.toDataXCoord(x), this.toDataYCoord(y, axis) ]; +}; + +/** + * Convert from canvas/div x coordinate to data coordinate. + * + * If x is null, this returns null. + */ +Dygraph.prototype.toDataXCoord = function(x) { + if (x === null) { + return null; + } + + var area = this.plotter_.area; + var xRange = this.xAxisRange(); + + if (!this.attributes_.getForAxis("logscale", 'x')) { + return xRange[0] + (x - area.x) / area.w * (xRange[1] - xRange[0]); + } else { + // TODO: remove duplicate code? + // Computing the inverse of toDomCoord. + var pct = (x - area.x) / area.w; + + // Computing the inverse of toPercentXCoord. The function was arrived at with + // the following steps: + // + // Original calcuation: + // pct = (log(x) - log(xRange[0])) / (log(xRange[1]) - log(xRange[0]))); + // + // Multiply both sides by the right-side demoninator. + // pct * (log(xRange[1] - log(xRange[0]))) = log(x) - log(xRange[0]) + // + // add log(xRange[0]) to both sides + // log(xRange[0]) + (pct * (log(xRange[1]) - log(xRange[0])) = log(x); + // + // Swap both sides of the equation, + // log(x) = log(xRange[0]) + (pct * (log(xRange[1]) - log(xRange[0])) + // + // Use both sides as the exponent in 10^exp and we're done. + // x = 10 ^ (log(xRange[0]) + (pct * (log(xRange[1]) - log(xRange[0]))) + var logr0 = Dygraph.log10(xRange[0]); + var logr1 = Dygraph.log10(xRange[1]); + var exponent = logr0 + (pct * (logr1 - logr0)); + var value = Math.pow(Dygraph.LOG_SCALE, exponent); + return value; + } +}; + +/** + * Convert from canvas/div y coord to value. + * + * If y is null, this returns null. + * if axis is null, this uses the first axis. + */ +Dygraph.prototype.toDataYCoord = function(y, axis) { + if (y === null) { + return null; + } + + var area = this.plotter_.area; + var yRange = this.yAxisRange(axis); + + if (typeof(axis) == "undefined") axis = 0; + if (!this.attributes_.getForAxis("logscale", axis)) { + return yRange[0] + (area.y + area.h - y) / area.h * (yRange[1] - yRange[0]); + } else { + // Computing the inverse of toDomCoord. + var pct = (y - area.y) / area.h; + + // Computing the inverse of toPercentYCoord. The function was arrived at with + // the following steps: + // + // Original calcuation: + // pct = (log(yRange[1]) - log(y)) / (log(yRange[1]) - log(yRange[0])); + // + // Multiply both sides by the right-side demoninator. + // pct * (log(yRange[1]) - log(yRange[0])) = log(yRange[1]) - log(y); + // + // subtract log(yRange[1]) from both sides. + // (pct * (log(yRange[1]) - log(yRange[0]))) - log(yRange[1]) = -log(y); + // + // and multiply both sides by -1. + // log(yRange[1]) - (pct * (logr1 - log(yRange[0])) = log(y); + // + // Swap both sides of the equation, + // log(y) = log(yRange[1]) - (pct * (log(yRange[1]) - log(yRange[0]))); + // + // Use both sides as the exponent in 10^exp and we're done. + // y = 10 ^ (log(yRange[1]) - (pct * (log(yRange[1]) - log(yRange[0])))); + var logr0 = Dygraph.log10(yRange[0]); + var logr1 = Dygraph.log10(yRange[1]); + var exponent = logr1 - (pct * (logr1 - logr0)); + var value = Math.pow(Dygraph.LOG_SCALE, exponent); + return value; + } +}; + +/** + * Converts a y for an axis to a percentage from the top to the + * bottom of the drawing area. + * + * If the coordinate represents a value visible on the canvas, then + * the value will be between 0 and 1, where 0 is the top of the canvas. + * However, this method will return values outside the range, as + * values can fall outside the canvas. + * + * If y is null, this returns null. + * if axis is null, this uses the first axis. + * + * @param {number} y The data y-coordinate. + * @param {number} [axis] The axis number on which the data coordinate lives. + * @return {number} A fraction in [0, 1] where 0 = the top edge. + */ +Dygraph.prototype.toPercentYCoord = function(y, axis) { + if (y === null) { + return null; + } + if (typeof(axis) == "undefined") axis = 0; + + var yRange = this.yAxisRange(axis); + + var pct; + var logscale = this.attributes_.getForAxis("logscale", axis); + if (logscale) { + var logr0 = Dygraph.log10(yRange[0]); + var logr1 = Dygraph.log10(yRange[1]); + pct = (logr1 - Dygraph.log10(y)) / (logr1 - logr0); + } else { + // yRange[1] - y is unit distance from the bottom. + // yRange[1] - yRange[0] is the scale of the range. + // (yRange[1] - y) / (yRange[1] - yRange[0]) is the % from the bottom. + pct = (yRange[1] - y) / (yRange[1] - yRange[0]); + } + return pct; +}; + +/** + * Converts an x value to a percentage from the left to the right of + * the drawing area. + * + * If the coordinate represents a value visible on the canvas, then + * the value will be between 0 and 1, where 0 is the left of the canvas. + * However, this method will return values outside the range, as + * values can fall outside the canvas. + * + * If x is null, this returns null. + * @param {number} x The data x-coordinate. + * @return {number} A fraction in [0, 1] where 0 = the left edge. + */ +Dygraph.prototype.toPercentXCoord = function(x) { + if (x === null) { + return null; + } + + var xRange = this.xAxisRange(); + var pct; + var logscale = this.attributes_.getForAxis("logscale", 'x') ; + if (logscale === true) { // logscale can be null so we test for true explicitly. + var logr0 = Dygraph.log10(xRange[0]); + var logr1 = Dygraph.log10(xRange[1]); + pct = (Dygraph.log10(x) - logr0) / (logr1 - logr0); + } else { + // x - xRange[0] is unit distance from the left. + // xRange[1] - xRange[0] is the scale of the range. + // The full expression below is the % from the left. + pct = (x - xRange[0]) / (xRange[1] - xRange[0]); + } + return pct; +}; + +/** + * Returns the number of columns (including the independent variable). + * @return {number} The number of columns. + */ +Dygraph.prototype.numColumns = function() { + if (!this.rawData_) return 0; + return this.rawData_[0] ? this.rawData_[0].length : this.attr_("labels").length; +}; + +/** + * Returns the number of rows (excluding any header/label row). + * @return {number} The number of rows, less any header. + */ +Dygraph.prototype.numRows = function() { + if (!this.rawData_) return 0; + return this.rawData_.length; +}; + +/** + * Returns the value in the given row and column. If the row and column exceed + * the bounds on the data, returns null. Also returns null if the value is + * missing. + * @param {number} row The row number of the data (0-based). Row 0 is the + * first row of data, not a header row. + * @param {number} col The column number of the data (0-based) + * @return {number} The value in the specified cell or null if the row/col + * were out of range. + */ +Dygraph.prototype.getValue = function(row, col) { + if (row < 0 || row > this.rawData_.length) return null; + if (col < 0 || col > this.rawData_[row].length) return null; + + return this.rawData_[row][col]; +}; + +/** + * Generates interface elements for the Dygraph: a containing div, a div to + * display the current point, and a textbox to adjust the rolling average + * period. Also creates the Renderer/Layout elements. + * @private + */ +Dygraph.prototype.createInterface_ = function() { + // Create the all-enclosing graph div + var enclosing = this.maindiv_; + + this.graphDiv = document.createElement("div"); + + // TODO(danvk): any other styles that are useful to set here? + this.graphDiv.style.textAlign = 'left'; // This is a CSS "reset" + this.graphDiv.style.position = 'relative'; + enclosing.appendChild(this.graphDiv); + + // Create the canvas for interactive parts of the chart. + this.canvas_ = Dygraph.createCanvas(); + this.canvas_.style.position = "absolute"; + + // ... and for static parts of the chart. + this.hidden_ = this.createPlotKitCanvas_(this.canvas_); + + this.canvas_ctx_ = Dygraph.getContext(this.canvas_); + this.hidden_ctx_ = Dygraph.getContext(this.hidden_); + + this.resizeElements_(); + + // The interactive parts of the graph are drawn on top of the chart. + this.graphDiv.appendChild(this.hidden_); + this.graphDiv.appendChild(this.canvas_); + this.mouseEventElement_ = this.createMouseEventElement_(); + + // Create the grapher + this.layout_ = new DygraphLayout(this); + + var dygraph = this; + + this.mouseMoveHandler_ = function(e) { + dygraph.mouseMove_(e); + }; + + this.mouseOutHandler_ = function(e) { + // The mouse has left the chart if: + // 1. e.target is inside the chart + // 2. e.relatedTarget is outside the chart + var target = e.target || e.fromElement; + var relatedTarget = e.relatedTarget || e.toElement; + if (Dygraph.isNodeContainedBy(target, dygraph.graphDiv) && + !Dygraph.isNodeContainedBy(relatedTarget, dygraph.graphDiv)) { + dygraph.mouseOut_(e); + } + }; + + 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. + if (!this.resizeHandler_) { + this.resizeHandler_ = function(e) { + dygraph.resize(); + }; + + // Update when the window is resized. + // TODO(danvk): drop frames depending on complexity of the chart. + this.addAndTrackEvent(window, 'resize', this.resizeHandler_); + } +}; + +Dygraph.prototype.resizeElements_ = function() { + this.graphDiv.style.width = this.width_ + "px"; + this.graphDiv.style.height = this.height_ + "px"; + + var canvasScale = Dygraph.getContextPixelRatio(this.canvas_ctx_); + this.canvas_.width = this.width_ * canvasScale; + this.canvas_.height = this.height_ * canvasScale; + this.canvas_.style.width = this.width_ + "px"; // for IE + this.canvas_.style.height = this.height_ + "px"; // for IE + if (canvasScale !== 1) { + this.canvas_ctx_.scale(canvasScale, canvasScale); + } + + var hiddenScale = Dygraph.getContextPixelRatio(this.hidden_ctx_); + this.hidden_.width = this.width_ * hiddenScale; + this.hidden_.height = this.height_ * hiddenScale; + this.hidden_.style.width = this.width_ + "px"; // for IE + this.hidden_.style.height = this.height_ + "px"; // for IE + if (hiddenScale !== 1) { + this.hidden_ctx_.scale(hiddenScale, hiddenScale); + } +}; + +/** + * 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(); + + // Destroy any plugins, in the reverse order that they were registered. + for (var i = this.plugins_.length - 1; i >= 0; i--) { + var p = this.plugins_.pop(); + if (p.plugin.destroy) p.plugin.destroy(); + } + + var removeRecursive = function(node) { + while (node.hasChildNodes()) { + removeRecursive(node.firstChild); + node.removeChild(node.firstChild); + } + }; + + 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_); + + // remove window handlers + Dygraph.removeEvent(window,'resize', this.resizeHandler_); + this.resizeHandler_ = null; + + removeRecursive(this.maindiv_); + + var nullOut = function(obj) { + for (var n in obj) { + if (typeof(obj[n]) === 'object') { + obj[n] = null; + } + } + }; + // These may not all be necessary, but it can't hurt... + nullOut(this.layout_); + nullOut(this.plotter_); + nullOut(this); +}; + +/** + * Creates the canvas on which the chart will be drawn. Only the Renderer ever + * draws on this particular canvas. All Dygraph work (i.e. drawing hover dots + * or the zoom rectangles) is done on this.canvas_. + * @param {Object} canvas The Dygraph canvas over which to overlay the plot + * @return {Object} The newly-created canvas + * @private + */ +Dygraph.prototype.createPlotKitCanvas_ = function(canvas) { + var h = Dygraph.createCanvas(); + h.style.position = "absolute"; + // TODO(danvk): h should be offset from canvas. canvas needs to include + // some extra area to make it easier to zoom in on the far left and far + // right. h needs to be precisely the plot area, so that clipping occurs. + h.style.top = canvas.style.top; + h.style.left = canvas.style.left; + h.width = this.width_; + h.height = this.height_; + h.style.width = this.width_ + "px"; // for IE + h.style.height = this.height_ + "px"; // for IE + return h; +}; + +/** + * Creates an overlay element used to handle mouse events. + * @return {Object} The mouse event element. + * @private + */ +Dygraph.prototype.createMouseEventElement_ = function() { + if (this.isUsingExcanvas_) { + var elem = document.createElement("div"); + elem.style.position = 'absolute'; + elem.style.backgroundColor = 'white'; + elem.style.filter = 'alpha(opacity=0)'; + elem.style.width = this.width_ + "px"; + elem.style.height = this.height_ + "px"; + this.graphDiv.appendChild(elem); + return elem; + } else { + return this.canvas_; + } +}; + +/** + * Generate a set of distinct colors for the data series. This is done with a + * color wheel. Saturation/Value are customizable, and the hue is + * equally-spaced around the color wheel. If a custom set of colors is + * specified, that is used instead. + * @private + */ +Dygraph.prototype.setColors_ = function() { + var labels = this.getLabels(); + var num = labels.length - 1; + this.colors_ = []; + this.colorsMap_ = {}; + + // These are used for when no custom colors are specified. + var sat = this.getNumericOption('colorSaturation') || 1.0; + var val = this.getNumericOption('colorValue') || 0.5; + var half = Math.ceil(num / 2); + + var colors = this.getOption('colors'); + var visibility = this.visibility(); + for (var i = 0; i < num; i++) { + if (!visibility[i]) { + continue; + } + var label = labels[i + 1]; + var colorStr = this.attributes_.getForSeries('color', label); + if (!colorStr) { + if (colors) { + colorStr = colors[i % colors.length]; + } else { + // alternate colors for high contrast. + var idx = i % 2 ? (half + (i + 1)/ 2) : Math.ceil((i + 1) / 2); + var hue = (1.0 * idx / (1 + num)); + colorStr = Dygraph.hsvToRGB(hue, sat, val); + } + } + this.colors_.push(colorStr); + this.colorsMap_[label] = colorStr; + } +}; + +/** + * Return the list of colors. This is either the list of colors passed in the + * attributes or the autogenerated list of rgb(r,g,b) strings. + * This does not return colors for invisible series. + * @return {Array.} The list of colors. + */ +Dygraph.prototype.getColors = function() { + return this.colors_; +}; + +/** + * Returns a few attributes of a series, i.e. its color, its visibility, which + * axis it's assigned to, and its column in the original data. + * Returns null if the series does not exist. + * Otherwise, returns an object with column, visibility, color and axis properties. + * The "axis" property will be set to 1 for y1 and 2 for y2. + * The "column" property can be fed back into getValue(row, column) to get + * values for this series. + */ +Dygraph.prototype.getPropertiesForSeries = function(series_name) { + var idx = -1; + var labels = this.getLabels(); + for (var i = 1; i < labels.length; i++) { + if (labels[i] == series_name) { + idx = i; + break; + } + } + if (idx == -1) return null; + + return { + name: series_name, + column: idx, + visible: this.visibility()[idx - 1], + color: this.colorsMap_[series_name], + axis: 1 + this.attributes_.axisForSeries(series_name) + }; +}; + +/** + * Create the text box to adjust the averaging period + * @private + */ +Dygraph.prototype.createRollInterface_ = function() { + // Create a roller if one doesn't exist already. + if (!this.roller_) { + this.roller_ = document.createElement("input"); + this.roller_.type = "text"; + this.roller_.style.display = "none"; + this.graphDiv.appendChild(this.roller_); + } + + var display = this.getBooleanOption('showRoller') ? 'block' : 'none'; + + var area = this.plotter_.area; + var textAttr = { "position": "absolute", + "zIndex": 10, + "top": (area.y + area.h - 25) + "px", + "left": (area.x + 1) + "px", + "display": display + }; + this.roller_.size = "2"; + this.roller_.value = this.rollPeriod_; + for (var name in textAttr) { + if (textAttr.hasOwnProperty(name)) { + this.roller_.style[name] = textAttr[name]; + } + } + + var dygraph = this; + this.roller_.onchange = function() { dygraph.adjustRoll(dygraph.roller_.value); }; +}; + +/** + * Set up all the mouse handlers needed to capture dragging behavior for zoom + * events. + * @private + */ +Dygraph.prototype.createDragInterface_ = function() { + var context = { + // Tracks whether the mouse is down right now + isZooming: false, + isPanning: false, // is this drag part of a pan? + is2DPan: false, // if so, is that pan 1- or 2-dimensional? + dragStartX: null, // pixel coordinates + dragStartY: null, // pixel coordinates + dragEndX: null, // pixel coordinates + dragEndY: null, // pixel coordinates + dragDirection: null, + prevEndX: null, // pixel coordinates + prevEndY: null, // pixel coordinates + prevDragDirection: null, + cancelNextDblclick: false, // see comment in dygraph-interaction-model.js + + // The value on the left side of the graph when a pan operation starts. + initialLeftmostDate: null, + + // The number of units each pixel spans. (This won't be valid for log + // scales) + xUnitsPerPixel: null, + + // TODO(danvk): update this comment + // The range in second/value units that the viewport encompasses during a + // panning operation. + dateRange: null, + + // Top-left corner of the canvas, in DOM coords + // TODO(konigsberg): Rename topLeftCanvasX, topLeftCanvasY. + px: 0, + py: 0, + + // Values for use with panEdgeFraction, which limit how far outside the + // graph's data boundaries it can be panned. + boundedDates: null, // [minDate, maxDate] + boundedValues: null, // [[minValue, maxValue] ...] + + // We cover iframes during mouse interactions. See comments in + // dygraph-utils.js for more info on why this is a good idea. + tarp: new Dygraph.IFrameTarp(), + + // contextB is the same thing as this context object but renamed. + initializeMouseDown: function(event, g, contextB) { + // prevents mouse drags from selecting page text. + if (event.preventDefault) { + event.preventDefault(); // Firefox, Chrome, etc. + } else { + event.returnValue = false; // IE + event.cancelBubble = true; + } + + var canvasPos = Dygraph.findPos(g.canvas_); + contextB.px = canvasPos.x; + contextB.py = canvasPos.y; + contextB.dragStartX = Dygraph.dragGetX_(event, contextB); + contextB.dragStartY = Dygraph.dragGetY_(event, contextB); + contextB.cancelNextDblclick = false; + contextB.tarp.cover(); + }, + destroy: function() { + var context = this; + if (context.isZooming || context.isPanning) { + context.isZooming = false; + context.dragStartX = null; + context.dragStartY = null; + } + + if (context.isPanning) { + context.isPanning = false; + context.draggingDate = null; + context.dateRange = null; + for (var i = 0; i < self.axes_.length; i++) { + delete self.axes_[i].draggingValue; + delete self.axes_[i].dragValueRange; + } + } + + context.tarp.uncover(); + } + }; + + var interactionModel = this.getOption("interactionModel"); + + // Self is the graph. + var self = this; + + // Function that binds the graph and context to the handler. + var bindHandler = function(handler) { + return function(event) { + handler(event, self, context); + }; + }; + + for (var eventName in interactionModel) { + if (!interactionModel.hasOwnProperty(eventName)) continue; + this.addAndTrackEvent(this.mouseEventElement_, eventName, + bindHandler(interactionModel[eventName])); + } + + // If the user releases the mouse button during a drag, but not over the + // canvas, then it doesn't count as a zooming action. + if (!interactionModel.willDestroyContextMyself) { + var mouseUpHandler = function(event) { + context.destroy(); + }; + + this.addAndTrackEvent(document, 'mouseup', mouseUpHandler); + } +}; + +/** + * Draw a gray zoom rectangle over the desired area of the canvas. Also clears + * up any previous zoom rectangles that were drawn. This could be optimized to + * avoid extra redrawing, but it's tricky to avoid interactions with the status + * dots. + * + * @param {number} direction the direction of the zoom rectangle. Acceptable + * values are Dygraph.HORIZONTAL and Dygraph.VERTICAL. + * @param {number} startX The X position where the drag started, in canvas + * coordinates. + * @param {number} endX The current X position of the drag, in canvas coords. + * @param {number} startY The Y position where the drag started, in canvas + * coordinates. + * @param {number} endY The current Y position of the drag, in canvas coords. + * @param {number} prevDirection the value of direction on the previous call to + * this function. Used to avoid excess redrawing + * @param {number} prevEndX The value of endX on the previous call to this + * function. Used to avoid excess redrawing + * @param {number} prevEndY The value of endY on the previous call to this + * function. Used to avoid excess redrawing + * @private + */ +Dygraph.prototype.drawZoomRect_ = function(direction, startX, endX, startY, + endY, prevDirection, prevEndX, + prevEndY) { + var ctx = this.canvas_ctx_; + + // Clean up from the previous rect if necessary + if (prevDirection == Dygraph.HORIZONTAL) { + ctx.clearRect(Math.min(startX, prevEndX), this.layout_.getPlotArea().y, + Math.abs(startX - prevEndX), this.layout_.getPlotArea().h); + } else if (prevDirection == Dygraph.VERTICAL) { + ctx.clearRect(this.layout_.getPlotArea().x, Math.min(startY, prevEndY), + this.layout_.getPlotArea().w, Math.abs(startY - prevEndY)); + } + + // Draw a light-grey rectangle to show the new viewing area + if (direction == Dygraph.HORIZONTAL) { + if (endX && startX) { + ctx.fillStyle = "rgba(128,128,128,0.33)"; + ctx.fillRect(Math.min(startX, endX), this.layout_.getPlotArea().y, + Math.abs(endX - startX), this.layout_.getPlotArea().h); + } + } else if (direction == Dygraph.VERTICAL) { + if (endY && startY) { + ctx.fillStyle = "rgba(128,128,128,0.33)"; + ctx.fillRect(this.layout_.getPlotArea().x, Math.min(startY, endY), + this.layout_.getPlotArea().w, Math.abs(endY - startY)); + } + } + + if (this.isUsingExcanvas_) { + this.currentZoomRectArgs_ = [direction, startX, endX, startY, endY, 0, 0, 0]; + } +}; + +/** + * Clear the zoom rectangle (and perform no zoom). + * @private + */ +Dygraph.prototype.clearZoomRect_ = function() { + this.currentZoomRectArgs_ = null; + this.canvas_ctx_.clearRect(0, 0, this.width_, this.height_); +}; + +/** + * Zoom to something containing [lowX, highX]. These are pixel coordinates in + * the canvas. The exact zoom window may be slightly larger if there are no data + * points near lowX or highX. Don't confuse this function with doZoomXDates, + * which accepts dates that match the raw data. This function redraws the graph. + * + * @param {number} lowX The leftmost pixel value that should be visible. + * @param {number} highX The rightmost pixel value that should be visible. + * @private + */ +Dygraph.prototype.doZoomX_ = function(lowX, highX) { + this.currentZoomRectArgs_ = null; + // Find the earliest and latest dates contained in this canvasx range. + // Convert the call to date ranges of the raw data. + var minDate = this.toDataXCoord(lowX); + var maxDate = this.toDataXCoord(highX); + this.doZoomXDates_(minDate, maxDate); +}; + +/** + * Zoom to something containing [minDate, maxDate] values. Don't confuse this + * method with doZoomX which accepts pixel coordinates. This function redraws + * the graph. + * + * @param {number} minDate The minimum date that should be visible. + * @param {number} maxDate The maximum date that should be visible. + * @private + */ +Dygraph.prototype.doZoomXDates_ = function(minDate, maxDate) { + // TODO(danvk): when xAxisRange is null (i.e. "fit to data", the animation + // can produce strange effects. Rather than the x-axis transitioning slowly + // between values, it can jerk around.) + var old_window = this.xAxisRange(); + var new_window = [minDate, maxDate]; + this.zoomed_x_ = true; + var that = this; + this.doAnimatedZoom(old_window, new_window, null, null, function() { + if (that.getFunctionOption("zoomCallback")) { + that.getFunctionOption("zoomCallback").call(that, + minDate, maxDate, that.yAxisRanges()); + } + }); +}; + +/** + * Zoom to something containing [lowY, highY]. These are pixel coordinates in + * the canvas. This function redraws the graph. + * + * @param {number} lowY The topmost pixel value that should be visible. + * @param {number} highY The lowest pixel value that should be visible. + * @private + */ +Dygraph.prototype.doZoomY_ = function(lowY, highY) { + this.currentZoomRectArgs_ = null; + // Find the highest and lowest values in pixel range for each axis. + // Note that lowY (in pixels) corresponds to the max Value (in data coords). + // This is because pixels increase as you go down on the screen, whereas data + // coordinates increase as you go up the screen. + var oldValueRanges = this.yAxisRanges(); + var newValueRanges = []; + for (var i = 0; i < this.axes_.length; i++) { + var hi = this.toDataYCoord(lowY, i); + var low = this.toDataYCoord(highY, i); + newValueRanges.push([low, hi]); + } + + this.zoomed_y_ = true; + var that = this; + this.doAnimatedZoom(null, null, oldValueRanges, newValueRanges, function() { + if (that.getFunctionOption("zoomCallback")) { + var xRange = that.xAxisRange(); + that.getFunctionOption("zoomCallback").call(that, + xRange[0], xRange[1], that.yAxisRanges()); + } + }); +}; + +/** + * Transition function to use in animations. Returns values between 0.0 + * (totally old values) and 1.0 (totally new values) for each frame. + * @private + */ +Dygraph.zoomAnimationFunction = function(frame, numFrames) { + var k = 1.5; + return (1.0 - Math.pow(k, -frame)) / (1.0 - Math.pow(k, -numFrames)); +}; + +/** + * Reset the zoom to the original view coordinates. This is the same as + * double-clicking on the graph. + */ +Dygraph.prototype.resetZoom = function() { + var dirty = false, dirtyX = false, dirtyY = false; + if (this.dateWindow_ !== null) { + dirty = true; + dirtyX = true; + } + + for (var i = 0; i < this.axes_.length; i++) { + if (typeof(this.axes_[i].valueWindow) !== 'undefined' && this.axes_[i].valueWindow !== null) { + dirty = true; + dirtyY = true; + } + } + + // Clear any selection, since it's likely to be drawn in the wrong place. + this.clearSelection(); + + if (dirty) { + this.zoomed_x_ = false; + this.zoomed_y_ = false; + + var minDate = this.rawData_[0][0]; + var maxDate = this.rawData_[this.rawData_.length - 1][0]; + + // With only one frame, don't bother calculating extreme ranges. + // TODO(danvk): merge this block w/ the code below. + if (!this.getBooleanOption("animatedZooms")) { + this.dateWindow_ = null; + for (i = 0; i < this.axes_.length; i++) { + if (this.axes_[i].valueWindow !== null) { + delete this.axes_[i].valueWindow; + } + } + this.drawGraph_(); + if (this.getFunctionOption("zoomCallback")) { + this.getFunctionOption("zoomCallback").call(this, + minDate, maxDate, this.yAxisRanges()); + } + return; + } + + var oldWindow=null, newWindow=null, oldValueRanges=null, newValueRanges=null; + if (dirtyX) { + oldWindow = this.xAxisRange(); + newWindow = [minDate, maxDate]; + } + + if (dirtyY) { + oldValueRanges = this.yAxisRanges(); + // TODO(danvk): this is pretty inefficient + var packed = this.gatherDatasets_(this.rolledSeries_, null); + var extremes = packed.extremes; + + // this has the side-effect of modifying this.axes_. + // this doesn't make much sense in this context, but it's convenient (we + // need this.axes_[*].extremeValues) and not harmful since we'll be + // calling drawGraph_ shortly, which clobbers these values. + this.computeYAxisRanges_(extremes); + + newValueRanges = []; + for (i = 0; i < this.axes_.length; i++) { + var axis = this.axes_[i]; + newValueRanges.push((axis.valueRange !== null && + axis.valueRange !== undefined) ? + axis.valueRange : axis.extremeRange); + } + } + + var that = this; + this.doAnimatedZoom(oldWindow, newWindow, oldValueRanges, newValueRanges, + function() { + that.dateWindow_ = null; + for (var i = 0; i < that.axes_.length; i++) { + if (that.axes_[i].valueWindow !== null) { + delete that.axes_[i].valueWindow; + } + } + if (that.getFunctionOption("zoomCallback")) { + that.getFunctionOption("zoomCallback").call(that, + minDate, maxDate, that.yAxisRanges()); + } + }); + } +}; + +/** + * Combined animation logic for all zoom functions. + * either the x parameters or y parameters may be null. + * @private + */ +Dygraph.prototype.doAnimatedZoom = function(oldXRange, newXRange, oldYRanges, newYRanges, callback) { + var steps = this.getBooleanOption("animatedZooms") ? + Dygraph.ANIMATION_STEPS : 1; + + var windows = []; + var valueRanges = []; + var step, frac; + + if (oldXRange !== null && newXRange !== null) { + for (step = 1; step <= steps; step++) { + frac = Dygraph.zoomAnimationFunction(step, steps); + windows[step-1] = [oldXRange[0]*(1-frac) + frac*newXRange[0], + oldXRange[1]*(1-frac) + frac*newXRange[1]]; + } + } + + if (oldYRanges !== null && newYRanges !== null) { + for (step = 1; step <= steps; step++) { + frac = Dygraph.zoomAnimationFunction(step, steps); + var thisRange = []; + for (var j = 0; j < this.axes_.length; j++) { + thisRange.push([oldYRanges[j][0]*(1-frac) + frac*newYRanges[j][0], + oldYRanges[j][1]*(1-frac) + frac*newYRanges[j][1]]); + } + valueRanges[step-1] = thisRange; + } + } + + var that = this; + Dygraph.repeatAndCleanup(function(step) { + if (valueRanges.length) { + for (var i = 0; i < that.axes_.length; i++) { + var w = valueRanges[step][i]; + that.axes_[i].valueWindow = [w[0], w[1]]; + } + } + if (windows.length) { + that.dateWindow_ = windows[step]; + } + that.drawGraph_(); + }, steps, Dygraph.ANIMATION_DURATION / steps, callback); +}; + +/** + * Get the current graph's area object. + * + * Returns: {x, y, w, h} + */ +Dygraph.prototype.getArea = function() { + return this.plotter_.area; +}; + +/** + * Convert a mouse event to DOM coordinates relative to the graph origin. + * + * Returns a two-element array: [X, Y]. + */ +Dygraph.prototype.eventToDomCoords = function(event) { + if (event.offsetX && event.offsetY) { + return [ event.offsetX, event.offsetY ]; + } else { + var eventElementPos = Dygraph.findPos(this.mouseEventElement_); + var canvasx = Dygraph.pageX(event) - eventElementPos.x; + var canvasy = Dygraph.pageY(event) - eventElementPos.y; + return [canvasx, canvasy]; + } +}; + +/** + * Given a canvas X coordinate, find the closest row. + * @param {number} domX graph-relative DOM X coordinate + * Returns {number} row number. + * @private + */ +Dygraph.prototype.findClosestRow = function(domX) { + var minDistX = Infinity; + var closestRow = -1; + var sets = this.layout_.points; + for (var i = 0; i < sets.length; i++) { + var points = sets[i]; + var len = points.length; + for (var j = 0; j < len; j++) { + var point = points[j]; + if (!Dygraph.isValidPoint(point, true)) continue; + var dist = Math.abs(point.canvasx - domX); + if (dist < minDistX) { + minDistX = dist; + closestRow = point.idx; + } + } + } + + return closestRow; +}; + +/** + * Given canvas X,Y coordinates, find the closest point. + * + * This finds the individual data point across all visible series + * that's closest to the supplied DOM coordinates using the standard + * Euclidean X,Y distance. + * + * @param {number} domX graph-relative DOM X coordinate + * @param {number} domY graph-relative DOM Y coordinate + * Returns: {row, seriesName, point} + * @private + */ +Dygraph.prototype.findClosestPoint = function(domX, domY) { + var minDist = Infinity; + var dist, dx, dy, point, closestPoint, closestSeries, closestRow; + for ( var setIdx = this.layout_.points.length - 1 ; setIdx >= 0 ; --setIdx ) { + var points = this.layout_.points[setIdx]; + for (var i = 0; i < points.length; ++i) { + point = points[i]; + if (!Dygraph.isValidPoint(point)) continue; + dx = point.canvasx - domX; + dy = point.canvasy - domY; + dist = dx * dx + dy * dy; + if (dist < minDist) { + minDist = dist; + closestPoint = point; + closestSeries = setIdx; + closestRow = point.idx; + } + } + } + var name = this.layout_.setNames[closestSeries]; + return { + row: closestRow, + seriesName: name, + point: closestPoint + }; +}; + +/** + * Given canvas X,Y coordinates, find the touched area in a stacked graph. + * + * This first finds the X data point closest to the supplied DOM X coordinate, + * then finds the series which puts the Y coordinate on top of its filled area, + * using linear interpolation between adjacent point pairs. + * + * @param {number} domX graph-relative DOM X coordinate + * @param {number} domY graph-relative DOM Y coordinate + * Returns: {row, seriesName, point} + * @private + */ +Dygraph.prototype.findStackedPoint = function(domX, domY) { + var row = this.findClosestRow(domX); + var closestPoint, closestSeries; + for (var setIdx = 0; setIdx < this.layout_.points.length; ++setIdx) { + var boundary = this.getLeftBoundary_(setIdx); + var rowIdx = row - boundary; + var points = this.layout_.points[setIdx]; + if (rowIdx >= points.length) continue; + var p1 = points[rowIdx]; + if (!Dygraph.isValidPoint(p1)) continue; + var py = p1.canvasy; + if (domX > p1.canvasx && rowIdx + 1 < points.length) { + // interpolate series Y value using next point + var p2 = points[rowIdx + 1]; + if (Dygraph.isValidPoint(p2)) { + var dx = p2.canvasx - p1.canvasx; + if (dx > 0) { + var r = (domX - p1.canvasx) / dx; + py += r * (p2.canvasy - p1.canvasy); + } + } + } else if (domX < p1.canvasx && rowIdx > 0) { + // interpolate series Y value using previous point + var p0 = points[rowIdx - 1]; + if (Dygraph.isValidPoint(p0)) { + var dx = p1.canvasx - p0.canvasx; + if (dx > 0) { + var r = (p1.canvasx - domX) / dx; + py += r * (p0.canvasy - p1.canvasy); + } + } + } + // Stop if the point (domX, py) is above this series' upper edge + if (setIdx === 0 || py < domY) { + closestPoint = p1; + closestSeries = setIdx; + } + } + var name = this.layout_.setNames[closestSeries]; + return { + row: row, + seriesName: name, + point: closestPoint + }; +}; + +/** + * When the mouse moves in the canvas, display information about a nearby data + * point and draw dots over those points in the data series. This function + * takes care of cleanup of previously-drawn dots. + * @param {Object} event The mousemove event from the browser. + * @private + */ +Dygraph.prototype.mouseMove_ = function(event) { + // This prevents JS errors when mousing over the canvas before data loads. + var points = this.layout_.points; + if (points === undefined || points === null) return; + + var canvasCoords = this.eventToDomCoords(event); + var canvasx = canvasCoords[0]; + var canvasy = canvasCoords[1]; + + var highlightSeriesOpts = this.getOption("highlightSeriesOpts"); + var selectionChanged = false; + if (highlightSeriesOpts && !this.isSeriesLocked()) { + var closest; + if (this.getBooleanOption("stackedGraph")) { + closest = this.findStackedPoint(canvasx, canvasy); + } else { + closest = this.findClosestPoint(canvasx, canvasy); + } + selectionChanged = this.setSelection(closest.row, closest.seriesName); + } else { + var idx = this.findClosestRow(canvasx); + selectionChanged = this.setSelection(idx); + } + + var callback = this.getFunctionOption("highlightCallback"); + if (callback && selectionChanged) { + callback.call(this, event, + this.lastx_, + this.selPoints_, + this.lastRow_, + this.highlightSet_); + } +}; + +/** + * Fetch left offset from the specified set index or if not passed, the + * first defined boundaryIds record (see bug #236). + * @private + */ +Dygraph.prototype.getLeftBoundary_ = function(setIdx) { + if (this.boundaryIds_[setIdx]) { + return this.boundaryIds_[setIdx][0]; + } else { + for (var i = 0; i < this.boundaryIds_.length; i++) { + if (this.boundaryIds_[i] !== undefined) { + return this.boundaryIds_[i][0]; + } + } + return 0; + } +}; + +Dygraph.prototype.animateSelection_ = function(direction) { + var totalSteps = 10; + var millis = 30; + if (this.fadeLevel === undefined) this.fadeLevel = 0; + if (this.animateId === undefined) this.animateId = 0; + var start = this.fadeLevel; + var steps = direction < 0 ? start : totalSteps - start; + if (steps <= 0) { + if (this.fadeLevel) { + this.updateSelection_(1.0); + } + return; + } + + var thisId = ++this.animateId; + var that = this; + Dygraph.repeatAndCleanup( + function(n) { + // ignore simultaneous animations + if (that.animateId != thisId) return; + + that.fadeLevel += direction; + if (that.fadeLevel === 0) { + that.clearSelection(); + } else { + that.updateSelection_(that.fadeLevel / totalSteps); + } + }, + steps, millis, function() {}); +}; + +/** + * Draw dots over the selectied points in the data series. This function + * takes care of cleanup of previously-drawn dots. + * @private + */ +Dygraph.prototype.updateSelection_ = function(opt_animFraction) { + /*var defaultPrevented = */ + this.cascadeEvents_('select', { + selectedRow: this.lastRow_, + selectedX: this.lastx_, + selectedPoints: this.selPoints_ + }); + // TODO(danvk): use defaultPrevented here? + + // Clear the previously drawn vertical, if there is one + var i; + var ctx = this.canvas_ctx_; + if (this.getOption('highlightSeriesOpts')) { + ctx.clearRect(0, 0, this.width_, this.height_); + var alpha = 1.0 - this.getNumericOption('highlightSeriesBackgroundAlpha'); + if (alpha) { + // Activating background fade includes an animation effect for a gradual + // fade. TODO(klausw): make this independently configurable if it causes + // issues? Use a shared preference to control animations? + var animateBackgroundFade = true; + if (animateBackgroundFade) { + if (opt_animFraction === undefined) { + // start a new animation + this.animateSelection_(1); + return; + } + alpha *= opt_animFraction; + } + ctx.fillStyle = 'rgba(255,255,255,' + alpha + ')'; + ctx.fillRect(0, 0, this.width_, this.height_); + } + + // Redraw only the highlighted series in the interactive canvas (not the + // static plot canvas, which is where series are usually drawn). + this.plotter_._renderLineChart(this.highlightSet_, ctx); + } else if (this.previousVerticalX_ >= 0) { + // Determine the maximum highlight circle size. + var maxCircleSize = 0; + var labels = this.attr_('labels'); + for (i = 1; i < labels.length; i++) { + var r = this.getNumericOption('highlightCircleSize', labels[i]); + if (r > maxCircleSize) maxCircleSize = r; + } + var px = this.previousVerticalX_; + ctx.clearRect(px - maxCircleSize - 1, 0, + 2 * maxCircleSize + 2, this.height_); + } + + if (this.isUsingExcanvas_ && this.currentZoomRectArgs_) { + Dygraph.prototype.drawZoomRect_.apply(this, this.currentZoomRectArgs_); + } + + if (this.selPoints_.length > 0) { + // Draw colored circles over the center of each selected point + var canvasx = this.selPoints_[0].canvasx; + ctx.save(); + for (i = 0; i < this.selPoints_.length; i++) { + var pt = this.selPoints_[i]; + if (!Dygraph.isOK(pt.canvasy)) continue; + + var circleSize = this.getNumericOption('highlightCircleSize', pt.name); + var callback = this.getFunctionOption("drawHighlightPointCallback", pt.name); + var color = this.plotter_.colors[pt.name]; + if (!callback) { + callback = Dygraph.Circles.DEFAULT; + } + ctx.lineWidth = this.getNumericOption('strokeWidth', pt.name); + ctx.strokeStyle = color; + ctx.fillStyle = color; + callback.call(this, this, pt.name, ctx, canvasx, pt.canvasy, + color, circleSize, pt.idx); + } + ctx.restore(); + + this.previousVerticalX_ = canvasx; + } +}; + +/** + * Manually set the selected points and display information about them in the + * legend. The selection can be cleared using clearSelection() and queried + * using getSelection(). + * @param {number} row Row number that should be highlighted (i.e. appear with + * hover dots on the chart). + * @param {seriesName} optional series name to highlight that series with the + * the highlightSeriesOpts setting. + * @param { locked } optional If true, keep seriesName selected when mousing + * over the graph, disabling closest-series highlighting. Call clearSelection() + * to unlock it. + */ +Dygraph.prototype.setSelection = function(row, opt_seriesName, opt_locked) { + // Extract the points we've selected + this.selPoints_ = []; + + var changed = false; + if (row !== false && row >= 0) { + if (row != this.lastRow_) changed = true; + this.lastRow_ = row; + for (var setIdx = 0; setIdx < this.layout_.points.length; ++setIdx) { + var points = this.layout_.points[setIdx]; + // Check if the point at the appropriate index is the point we're looking + // for. If it is, just use it, otherwise search the array for a point + // in the proper place. + var setRow = row - this.getLeftBoundary_(setIdx); + if (setRow < points.length && points[setRow].idx == row) { + var point = points[setRow]; + if (point.yval !== null) this.selPoints_.push(point); + } else { + for (var pointIdx = 0; pointIdx < points.length; ++pointIdx) { + var point = points[pointIdx]; + if (point.idx == row) { + if (point.yval !== null) { + this.selPoints_.push(point); + } + break; + } + } + } + } + } else { + if (this.lastRow_ >= 0) changed = true; + this.lastRow_ = -1; + } + + if (this.selPoints_.length) { + this.lastx_ = this.selPoints_[0].xval; + } else { + this.lastx_ = -1; + } + + if (opt_seriesName !== undefined) { + if (this.highlightSet_ !== opt_seriesName) changed = true; + this.highlightSet_ = opt_seriesName; + } + + if (opt_locked !== undefined) { + this.lockedSet_ = opt_locked; + } + + if (changed) { + this.updateSelection_(undefined); + } + return changed; +}; + +/** + * The mouse has left the canvas. Clear out whatever artifacts remain + * @param {Object} event the mouseout event from the browser. + * @private + */ +Dygraph.prototype.mouseOut_ = function(event) { + if (this.getFunctionOption("unhighlightCallback")) { + this.getFunctionOption("unhighlightCallback").call(this, event); + } + + if (this.getBooleanOption("hideOverlayOnMouseOut") && !this.lockedSet_) { + this.clearSelection(); + } +}; + +/** + * Clears the current selection (i.e. points that were highlighted by moving + * the mouse over the chart). + */ +Dygraph.prototype.clearSelection = function() { + this.cascadeEvents_('deselect', {}); + + this.lockedSet_ = false; + // Get rid of the overlay data + if (this.fadeLevel) { + this.animateSelection_(-1); + return; + } + this.canvas_ctx_.clearRect(0, 0, this.width_, this.height_); + this.fadeLevel = 0; + this.selPoints_ = []; + this.lastx_ = -1; + this.lastRow_ = -1; + this.highlightSet_ = null; +}; + +/** + * Returns the number of the currently selected row. To get data for this row, + * you can use the getValue method. + * @return {number} row number, or -1 if nothing is selected + */ +Dygraph.prototype.getSelection = function() { + if (!this.selPoints_ || this.selPoints_.length < 1) { + return -1; + } + + for (var setIdx = 0; setIdx < this.layout_.points.length; setIdx++) { + var points = this.layout_.points[setIdx]; + for (var row = 0; row < points.length; row++) { + if (points[row].x == this.selPoints_[0].x) { + return points[row].idx; + } + } + } + return -1; +}; + +/** + * Returns the name of the currently-highlighted series. + * Only available when the highlightSeriesOpts option is in use. + */ +Dygraph.prototype.getHighlightSeries = function() { + return this.highlightSet_; +}; + +/** + * 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 + */ +Dygraph.prototype.loadedEvent_ = function(data) { + this.rawData_ = this.parseCSV_(data); + this.cascadeDataDidUpdateEvent_(); + this.predraw_(); +}; + +/** + * Add ticks on the x-axis representing years, months, quarters, weeks, or days + * @private + */ +Dygraph.prototype.addXTicks_ = function() { + // Determine the correct ticks scale on the x-axis: quarterly, monthly, ... + var range; + if (this.dateWindow_) { + range = [this.dateWindow_[0], this.dateWindow_[1]]; + } else { + range = this.xAxisExtremes(); + } + + var xAxisOptionsView = this.optionsViewForAxis_('x'); + var xTicks = xAxisOptionsView('ticker')( + range[0], + range[1], + this.plotter_.area.w, // TODO(danvk): should be area.width + xAxisOptionsView, + this); + // var msg = 'ticker(' + range[0] + ', ' + range[1] + ', ' + this.width_ + ', ' + this.attr_('pixelsPerXLabel') + ') -> ' + JSON.stringify(xTicks); + // console.log(msg); + this.layout_.setXTicks(xTicks); +}; + +/** + * Returns the correct handler class for the currently set options. + * @private + */ +Dygraph.prototype.getHandlerClass_ = function() { + var handlerClass; + if (this.attr_('dataHandler')) { + handlerClass = this.attr_('dataHandler'); + } else if (this.fractions_) { + if (this.getBooleanOption('errorBars')) { + handlerClass = Dygraph.DataHandlers.FractionsBarsHandler; + } else { + handlerClass = Dygraph.DataHandlers.DefaultFractionHandler; + } + } else if (this.getBooleanOption('customBars')) { + handlerClass = Dygraph.DataHandlers.CustomBarsHandler; + } else if (this.getBooleanOption('errorBars')) { + handlerClass = Dygraph.DataHandlers.ErrorBarsHandler; + } else { + handlerClass = Dygraph.DataHandlers.DefaultHandler; + } + return handlerClass; +}; + +/** + * @private + * This function is called once when the chart's data is changed or the options + * dictionary is updated. It is _not_ called when the user pans or zooms. The + * idea is that values derived from the chart's data can be computed here, + * rather than every time the chart is drawn. This includes things like the + * number of axes, rolling averages, etc. + */ +Dygraph.prototype.predraw_ = function() { + var start = new Date(); + + // Create the correct dataHandler + this.dataHandler_ = new (this.getHandlerClass_())(); + + this.layout_.computePlotArea(); + + // TODO(danvk): move more computations out of drawGraph_ and into here. + this.computeYAxes_(); + + if (!this.is_initial_draw_) { + this.canvas_ctx_.restore(); + this.hidden_ctx_.restore(); + } + + this.canvas_ctx_.save(); + this.hidden_ctx_.save(); + + // Create a new plotter. + this.plotter_ = new DygraphCanvasRenderer(this, + this.hidden_, + this.hidden_ctx_, + this.layout_); + + // The roller sits in the bottom left corner of the chart. We don't know where + // this will be until the options are available, so it's positioned here. + this.createRollInterface_(); + + this.cascadeEvents_('predraw'); + + // Convert the raw data (a 2D array) into the internal format and compute + // rolling averages. + this.rolledSeries_ = [null]; // x-axis is the first series and it's special + for (var i = 1; i < this.numColumns(); i++) { + // var logScale = this.attr_('logscale', i); // TODO(klausw): this looks wrong // konigsberg thinks so too. + var series = this.dataHandler_.extractSeries(this.rawData_, i, this.attributes_); + if (this.rollPeriod_ > 1) { + series = this.dataHandler_.rollingAverage(series, this.rollPeriod_, this.attributes_); + } + + this.rolledSeries_.push(series); + } + + // If the data or options have changed, then we'd better redraw. + this.drawGraph_(); + + // This is used to determine whether to do various animations. + var end = new Date(); + this.drawingTimeMs_ = (end - start); +}; + +/** + * Point structure. + * + * xval_* and yval_* are the original unscaled data values, + * while x_* and y_* are scaled to the range (0.0-1.0) for plotting. + * yval_stacked is the cumulative Y value used for stacking graphs, + * and bottom/top/minus/plus are used for error bar graphs. + * + * @typedef {{ + * idx: number, + * name: string, + * x: ?number, + * xval: ?number, + * y_bottom: ?number, + * y: ?number, + * y_stacked: ?number, + * y_top: ?number, + * yval_minus: ?number, + * yval: ?number, + * yval_plus: ?number, + * yval_stacked + * }} + */ +Dygraph.PointType = undefined; + +/** + * Calculates point stacking for stackedGraph=true. + * + * For stacking purposes, interpolate or extend neighboring data across + * NaN values based on stackedGraphNaNFill settings. This is for display + * only, the underlying data value as shown in the legend remains NaN. + * + * @param {Array.} points Point array for a single series. + * Updates each Point's yval_stacked property. + * @param {Array.} cumulativeYval Accumulated top-of-graph stacked Y + * values for the series seen so far. Index is the row number. Updated + * based on the current series's values. + * @param {Array.} seriesExtremes Min and max values, updated + * to reflect the stacked values. + * @param {string} fillMethod Interpolation method, one of 'all', 'inside', or + * 'none'. + * @private + */ +Dygraph.stackPoints_ = function( + points, cumulativeYval, seriesExtremes, fillMethod) { + var lastXval = null; + var prevPoint = null; + var nextPoint = null; + var nextPointIdx = -1; + + // Find the next stackable point starting from the given index. + var updateNextPoint = function(idx) { + // If we've previously found a non-NaN point and haven't gone past it yet, + // just use that. + if (nextPointIdx >= idx) return; + + // We haven't found a non-NaN point yet or have moved past it, + // look towards the right to find a non-NaN point. + for (var j = idx; j < points.length; ++j) { + // Clear out a previously-found point (if any) since it's no longer + // valid, we shouldn't use it for interpolation anymore. + nextPoint = null; + if (!isNaN(points[j].yval) && points[j].yval !== null) { + nextPointIdx = j; + nextPoint = points[j]; + break; + } + } + }; + + for (var i = 0; i < points.length; ++i) { + var point = points[i]; + var xval = point.xval; + if (cumulativeYval[xval] === undefined) { + cumulativeYval[xval] = 0; + } + + var actualYval = point.yval; + if (isNaN(actualYval) || actualYval === null) { + if(fillMethod == 'none') { + actualYval = 0; + } else { + // Interpolate/extend for stacking purposes if possible. + updateNextPoint(i); + if (prevPoint && nextPoint && fillMethod != 'none') { + // Use linear interpolation between prevPoint and nextPoint. + actualYval = prevPoint.yval + (nextPoint.yval - prevPoint.yval) * + ((xval - prevPoint.xval) / (nextPoint.xval - prevPoint.xval)); + } else if (prevPoint && fillMethod == 'all') { + actualYval = prevPoint.yval; + } else if (nextPoint && fillMethod == 'all') { + actualYval = nextPoint.yval; + } else { + actualYval = 0; + } + } + } else { + prevPoint = point; + } + + var stackedYval = cumulativeYval[xval]; + if (lastXval != xval) { + // If an x-value is repeated, we ignore the duplicates. + stackedYval += actualYval; + cumulativeYval[xval] = stackedYval; + } + lastXval = xval; + + point.yval_stacked = stackedYval; + + if (stackedYval > seriesExtremes[1]) { + seriesExtremes[1] = stackedYval; + } + if (stackedYval < seriesExtremes[0]) { + seriesExtremes[0] = stackedYval; + } + } +}; + + +/** + * Loop over all fields and create datasets, calculating extreme y-values for + * each series and extreme x-indices as we go. + * + * dateWindow is passed in as an explicit parameter so that we can compute + * extreme values "speculatively", i.e. without actually setting state on the + * dygraph. + * + * @param {Array.)>>} rolledSeries, where + * rolledSeries[seriesIndex][row] = raw point, where + * seriesIndex is the column number starting with 1, and + * rawPoint is [x,y] or [x, [y, err]] or [x, [y, yminus, yplus]]. + * @param {?Array.} dateWindow [xmin, xmax] pair, or null. + * @return {{ + * points: Array.>, + * seriesExtremes: Array.>, + * boundaryIds: Array.}} + * @private + */ +Dygraph.prototype.gatherDatasets_ = function(rolledSeries, dateWindow) { + var boundaryIds = []; + var points = []; + var cumulativeYval = []; // For stacked series. + var extremes = {}; // series name -> [low, high] + var seriesIdx, sampleIdx; + var firstIdx, lastIdx; + var axisIdx; + + // Loop over the fields (series). Go from the last to the first, + // because if they're stacked that's how we accumulate the values. + var num_series = rolledSeries.length - 1; + var series; + for (seriesIdx = num_series; seriesIdx >= 1; seriesIdx--) { + if (!this.visibility()[seriesIdx - 1]) continue; + + // Prune down to the desired range, if necessary (for zooming) + // Because there can be lines going to points outside of the visible area, + // we actually prune to visible points, plus one on either side. + if (dateWindow) { + series = rolledSeries[seriesIdx]; + var low = dateWindow[0]; + var high = dateWindow[1]; + + // TODO(danvk): do binary search instead of linear search. + // TODO(danvk): pass firstIdx and lastIdx directly to the renderer. + firstIdx = null; + lastIdx = null; + for (sampleIdx = 0; sampleIdx < series.length; sampleIdx++) { + if (series[sampleIdx][0] >= low && firstIdx === null) { + firstIdx = sampleIdx; + } + if (series[sampleIdx][0] <= high) { + lastIdx = sampleIdx; + } + } + + if (firstIdx === null) firstIdx = 0; + var correctedFirstIdx = firstIdx; + var isInvalidValue = true; + while (isInvalidValue && correctedFirstIdx > 0) { + correctedFirstIdx--; + // check if the y value is null. + isInvalidValue = series[correctedFirstIdx][1] === null; + } + + if (lastIdx === null) lastIdx = series.length - 1; + var correctedLastIdx = lastIdx; + isInvalidValue = true; + while (isInvalidValue && correctedLastIdx < series.length - 1) { + correctedLastIdx++; + isInvalidValue = series[correctedLastIdx][1] === null; + } + + if (correctedFirstIdx!==firstIdx) { + firstIdx = correctedFirstIdx; + } + if (correctedLastIdx !== lastIdx) { + lastIdx = correctedLastIdx; + } + + boundaryIds[seriesIdx-1] = [firstIdx, lastIdx]; + + // .slice's end is exclusive, we want to include lastIdx. + series = series.slice(firstIdx, lastIdx + 1); + } else { + series = rolledSeries[seriesIdx]; + boundaryIds[seriesIdx-1] = [0, series.length-1]; + } + + var seriesName = this.attr_("labels")[seriesIdx]; + var seriesExtremes = this.dataHandler_.getExtremeYValues(series, + dateWindow, this.getBooleanOption("stepPlot",seriesName)); + + var seriesPoints = this.dataHandler_.seriesToPoints(series, + seriesName, boundaryIds[seriesIdx-1][0]); + + if (this.getBooleanOption("stackedGraph")) { + axisIdx = this.attributes_.axisForSeries(seriesName); + if (cumulativeYval[axisIdx] === undefined) { + cumulativeYval[axisIdx] = []; + } + Dygraph.stackPoints_(seriesPoints, cumulativeYval[axisIdx], seriesExtremes, + this.getBooleanOption("stackedGraphNaNFill")); + } + + extremes[seriesName] = seriesExtremes; + points[seriesIdx] = seriesPoints; + } + + return { points: points, extremes: extremes, boundaryIds: boundaryIds }; +}; + +/** + * Update the graph with new data. This method is called when the viewing area + * has changed. If the underlying data or options have changed, predraw_ will + * be called before drawGraph_ is called. + * + * @private + */ +Dygraph.prototype.drawGraph_ = function() { + var start = new Date(); + + // This is used to set the second parameter to drawCallback, below. + var is_initial_draw = this.is_initial_draw_; + this.is_initial_draw_ = false; + + this.layout_.removeAllDatasets(); + this.setColors_(); + this.attrs_.pointSize = 0.5 * this.getNumericOption('highlightCircleSize'); + + var packed = this.gatherDatasets_(this.rolledSeries_, this.dateWindow_); + var points = packed.points; + var extremes = packed.extremes; + this.boundaryIds_ = packed.boundaryIds; + + this.setIndexByName_ = {}; + var labels = this.attr_("labels"); + if (labels.length > 0) { + this.setIndexByName_[labels[0]] = 0; + } + var dataIdx = 0; + for (var i = 1; i < points.length; i++) { + this.setIndexByName_[labels[i]] = i; + if (!this.visibility()[i - 1]) continue; + this.layout_.addDataset(labels[i], points[i]); + this.datasetIndex_[i] = dataIdx++; + } + + this.computeYAxisRanges_(extremes); + this.layout_.setYAxes(this.axes_); + + this.addXTicks_(); + + // 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.zoomed_x_ = tmp_zoomed_x; + this.layout_.evaluate(); + this.renderGraph_(is_initial_draw); + + if (this.getStringOption("timingName")) { + var end = new Date(); + console.log(this.getStringOption("timingName") + " - drawGraph: " + (end - start) + "ms"); + } +}; + +/** + * This does the work of drawing the chart. It assumes that the layout and axis + * scales have already been set (e.g. by predraw_). + * + * @private + */ +Dygraph.prototype.renderGraph_ = function(is_initial_draw) { + this.cascadeEvents_('clearChart'); + this.plotter_.clear(); + + if (this.getFunctionOption('underlayCallback')) { + // NOTE: we pass the dygraph object to this callback twice to avoid breaking + // users who expect a deprecated form of this callback. + this.getFunctionOption('underlayCallback').call(this, + this.hidden_ctx_, this.layout_.getPlotArea(), this, this); + } + + var e = { + canvas: this.hidden_, + drawingContext: this.hidden_ctx_ + }; + this.cascadeEvents_('willDrawChart', e); + this.plotter_.render(); + this.cascadeEvents_('didDrawChart', e); + this.lastRow_ = -1; // because plugins/legend.js clears the legend + + // TODO(danvk): is this a performance bottleneck when panning? + // The interaction canvas should already be empty in that situation. + this.canvas_.getContext('2d').clearRect(0, 0, this.width_, this.height_); + + if (this.getFunctionOption("drawCallback") !== null) { + this.getFunctionOption("drawCallback").call(this, this, is_initial_draw); + } + if (is_initial_draw) { + this.readyFired_ = true; + while (this.readyFns_.length > 0) { + var fn = this.readyFns_.pop(); + fn(this); + } + } +}; + +/** + * @private + * Determine properties of the y-axes which are independent of the data + * currently being displayed. This includes things like the number of axes and + * the style of the axes. It does not include the range of each axis and its + * tick marks. + * This fills in this.axes_. + * axes_ = [ { options } ] + * indices are into the axes_ array. + */ +Dygraph.prototype.computeYAxes_ = function() { + // Preserve valueWindow settings if they exist, and if the user hasn't + // specified a new valueRange. + var valueWindows, axis, index, opts, v; + if (this.axes_ !== undefined && this.user_attrs_.hasOwnProperty("valueRange") === false) { + valueWindows = []; + for (index = 0; index < this.axes_.length; index++) { + valueWindows.push(this.axes_[index].valueWindow); + } + } + + // this.axes_ doesn't match this.attributes_.axes_.options. It's used for + // data computation as well as options storage. + // Go through once and add all the axes. + this.axes_ = []; + + for (axis = 0; axis < this.attributes_.numAxes(); axis++) { + // Add a new axis, making a copy of its per-axis options. + opts = { g : this }; + Dygraph.update(opts, this.attributes_.axisOptions(axis)); + this.axes_[axis] = opts; + } + + + // Copy global valueRange option over to the first axis. + // NOTE(konigsberg): Are these two statements necessary? + // I tried removing it. The automated tests pass, and manually + // messing with tests/zoom.html showed no trouble. + v = this.attr_('valueRange'); + if (v) this.axes_[0].valueRange = v; + + if (valueWindows !== undefined) { + // Restore valueWindow settings. + + // When going from two axes back to one, we only restore + // one axis. + var idxCount = Math.min(valueWindows.length, this.axes_.length); + + for (index = 0; index < idxCount; index++) { + this.axes_[index].valueWindow = valueWindows[index]; + } + } + + for (axis = 0; axis < this.axes_.length; axis++) { + if (axis === 0) { + opts = this.optionsViewForAxis_('y' + (axis ? '2' : '')); + v = opts("valueRange"); + if (v) this.axes_[axis].valueRange = v; + } else { // To keep old behavior + var axes = this.user_attrs_.axes; + if (axes && axes.y2) { + v = axes.y2.valueRange; + if (v) this.axes_[axis].valueRange = v; + } + } + } +}; + +/** + * Returns the number of y-axes on the chart. + * @return {number} the number of axes. + */ +Dygraph.prototype.numAxes = function() { + return this.attributes_.numAxes(); +}; + +/** + * @private + * Returns axis properties for the given series. + * @param {string} setName The name of the series for which to get axis + * properties, e.g. 'Y1'. + * @return {Object} The axis properties. + */ +Dygraph.prototype.axisPropertiesForSeries = function(series) { + // TODO(danvk): handle errors. + return this.axes_[this.attributes_.axisForSeries(series)]; +}; + +/** + * @private + * Determine the value range and tick marks for each axis. + * @param {Object} extremes A mapping from seriesName -> [low, high] + * This fills in the valueRange and ticks fields in each entry of this.axes_. + */ +Dygraph.prototype.computeYAxisRanges_ = function(extremes) { + var isNullUndefinedOrNaN = function(num) { + return isNaN(parseFloat(num)); + }; + var numAxes = this.attributes_.numAxes(); + var ypadCompat, span, series, ypad; + + var p_axis; + + // Compute extreme values, a span and tick marks for each axis. + for (var i = 0; i < numAxes; i++) { + var axis = this.axes_[i]; + var logscale = this.attributes_.getForAxis("logscale", i); + var includeZero = this.attributes_.getForAxis("includeZero", i); + var independentTicks = this.attributes_.getForAxis("independentTicks", i); + series = this.attributes_.seriesForAxis(i); + + // Add some padding. This supports two Y padding operation modes: + // + // - backwards compatible (yRangePad not set): + // 10% padding for automatic Y ranges, but not for user-supplied + // ranges, and move a close-to-zero edge to zero except if + // avoidMinZero is set, since drawing at the edge results in + // invisible lines. Unfortunately lines drawn at the edge of a + // user-supplied range will still be invisible. If logscale is + // set, add a variable amount of padding at the top but + // none at the bottom. + // + // - new-style (yRangePad set by the user): + // always add the specified Y padding. + // + ypadCompat = true; + ypad = 0.1; // add 10% + if (this.getNumericOption('yRangePad') !== null) { + ypadCompat = false; + // Convert pixel padding to ratio + ypad = this.getNumericOption('yRangePad') / this.plotter_.area.h; + } + + if (series.length === 0) { + // If no series are defined or visible then use a reasonable default + axis.extremeRange = [0, 1]; + } else { + // Calculate the extremes of extremes. + var minY = Infinity; // extremes[series[0]][0]; + var maxY = -Infinity; // extremes[series[0]][1]; + var extremeMinY, extremeMaxY; + + for (var j = 0; j < series.length; j++) { + // this skips invisible series + if (!extremes.hasOwnProperty(series[j])) continue; + + // Only use valid extremes to stop null data series' from corrupting the scale. + extremeMinY = extremes[series[j]][0]; + if (extremeMinY !== null) { + minY = Math.min(extremeMinY, minY); + } + extremeMaxY = extremes[series[j]][1]; + if (extremeMaxY !== null) { + maxY = Math.max(extremeMaxY, maxY); + } + } + + // Include zero if requested by the user. + if (includeZero && !logscale) { + if (minY > 0) minY = 0; + if (maxY < 0) maxY = 0; + } + + // Ensure we have a valid scale, otherwise default to [0, 1] for safety. + if (minY == Infinity) minY = 0; + if (maxY == -Infinity) maxY = 1; + + span = maxY - minY; + // special case: if we have no sense of scale, center on the sole value. + if (span === 0) { + if (maxY !== 0) { + span = Math.abs(maxY); + } else { + // ... and if the sole value is zero, use range 0-1. + maxY = 1; + span = 1; + } + } + + var maxAxisY, minAxisY; + if (logscale) { + if (ypadCompat) { + maxAxisY = maxY + ypad * span; + minAxisY = minY; + } else { + var logpad = Math.exp(Math.log(span) * ypad); + maxAxisY = maxY * logpad; + minAxisY = minY / logpad; + } + } else { + maxAxisY = maxY + ypad * span; + minAxisY = minY - ypad * span; + + // Backwards-compatible behavior: Move the span to start or end at zero if it's + // close to zero, but not if avoidMinZero is set. + if (ypadCompat && !this.getBooleanOption("avoidMinZero")) { + if (minAxisY < 0 && minY >= 0) minAxisY = 0; + if (maxAxisY > 0 && maxY <= 0) maxAxisY = 0; + } + } + axis.extremeRange = [minAxisY, maxAxisY]; + } + if (axis.valueWindow) { + // This is only set if the user has zoomed on the y-axis. It is never set + // by a user. It takes precedence over axis.valueRange because, if you set + // valueRange, you'd still expect to be able to pan. + axis.computedValueRange = [axis.valueWindow[0], axis.valueWindow[1]]; + } else if (axis.valueRange) { + // This is a user-set value range for this axis. + var y0 = isNullUndefinedOrNaN(axis.valueRange[0]) ? axis.extremeRange[0] : axis.valueRange[0]; + var y1 = isNullUndefinedOrNaN(axis.valueRange[1]) ? axis.extremeRange[1] : axis.valueRange[1]; + if (!ypadCompat) { + if (axis.logscale) { + var logpad = Math.exp(Math.log(span) * ypad); + y0 *= logpad; + y1 /= logpad; + } else { + span = y1 - y0; + y0 -= span * ypad; + y1 += span * ypad; + } + } + axis.computedValueRange = [y0, y1]; + } else { + axis.computedValueRange = axis.extremeRange; + } + + + if (independentTicks) { + axis.independentTicks = independentTicks; + var opts = this.optionsViewForAxis_('y' + (i ? '2' : '')); + var ticker = opts('ticker'); + axis.ticks = ticker(axis.computedValueRange[0], + axis.computedValueRange[1], + this.plotter_.area.h, + opts, + this); + // Define the first independent axis as primary axis. + if (!p_axis) p_axis = axis; + } + } + if (p_axis === undefined) { + throw ("Configuration Error: At least one axis has to have the \"independentTicks\" option activated."); + } + // Add ticks. By default, all axes inherit the tick positions of the + // primary axis. However, if an axis is specifically marked as having + // independent ticks, then that is permissible as well. + for (var i = 0; i < numAxes; i++) { + var axis = this.axes_[i]; + + if (!axis.independentTicks) { + var opts = this.optionsViewForAxis_('y' + (i ? '2' : '')); + var ticker = opts('ticker'); + var p_ticks = p_axis.ticks; + var p_scale = p_axis.computedValueRange[1] - p_axis.computedValueRange[0]; + var scale = axis.computedValueRange[1] - axis.computedValueRange[0]; + var tick_values = []; + for (var k = 0; k < p_ticks.length; k++) { + var y_frac = (p_ticks[k].v - p_axis.computedValueRange[0]) / p_scale; + var y_val = axis.computedValueRange[0] + y_frac * scale; + tick_values.push(y_val); + } + + axis.ticks = ticker(axis.computedValueRange[0], + axis.computedValueRange[1], + this.plotter_.area.h, + opts, + this, + tick_values); + } + } +}; + +/** + * Detects the type of the str (date or numeric) and sets the various + * formatting attributes in this.attrs_ based on this type. + * @param {string} str An x value. + * @private + */ +Dygraph.prototype.detectTypeFromString_ = function(str) { + var isDate = false; + var dashPos = str.indexOf('-'); // could be 2006-01-01 _or_ 1.0e-2 + if ((dashPos > 0 && (str[dashPos-1] != 'e' && str[dashPos-1] != 'E')) || + str.indexOf('/') >= 0 || + isNaN(parseFloat(str))) { + isDate = true; + } else if (str.length == 8 && str > '19700101' && str < '20371231') { + // TODO(danvk): remove support for this format. + isDate = true; + } + + this.setXAxisOptions_(isDate); +}; + +Dygraph.prototype.setXAxisOptions_ = function(isDate) { + if (isDate) { + this.attrs_.xValueParser = Dygraph.dateParser; + this.attrs_.axes.x.valueFormatter = Dygraph.dateValueFormatter; + this.attrs_.axes.x.ticker = Dygraph.dateTicker; + this.attrs_.axes.x.axisLabelFormatter = Dygraph.dateAxisLabelFormatter; + } else { + /** @private (shut up, jsdoc!) */ + this.attrs_.xValueParser = function(x) { return parseFloat(x); }; + // TODO(danvk): use Dygraph.numberValueFormatter here? + /** @private (shut up, jsdoc!) */ + this.attrs_.axes.x.valueFormatter = function(x) { return x; }; + this.attrs_.axes.x.ticker = Dygraph.numericTicks; + this.attrs_.axes.x.axisLabelFormatter = this.attrs_.axes.x.valueFormatter; + } +}; + +/** + * @private + * Parses a string in a special csv format. We expect a csv file where each + * line is a date point, and the first field in each line is the date string. + * We also expect that all remaining fields represent series. + * if the errorBars attribute is set, then interpret the fields as: + * date, series1, stddev1, series2, stddev2, ... + * @param {[Object]} data See above. + * + * @return [Object] An array with one entry for each row. These entries + * are an array of cells in that row. The first entry is the parsed x-value for + * the row. The second, third, etc. are the y-values. These can take on one of + * three forms, depending on the CSV and constructor parameters: + * 1. numeric value + * 2. [ value, stddev ] + * 3. [ low value, center value, high value ] + */ +Dygraph.prototype.parseCSV_ = function(data) { + var ret = []; + var line_delimiter = Dygraph.detectLineDelimiter(data); + var lines = data.split(line_delimiter || "\n"); + var vals, j; + + // Use the default delimiter or fall back to a tab if that makes sense. + var delim = this.getStringOption('delimiter'); + if (lines[0].indexOf(delim) == -1 && lines[0].indexOf('\t') >= 0) { + delim = '\t'; + } + + var start = 0; + if (!('labels' in this.user_attrs_)) { + // User hasn't explicitly set labels, so they're (presumably) in the CSV. + start = 1; + this.attrs_.labels = lines[0].split(delim); // NOTE: _not_ user_attrs_. + this.attributes_.reparseSeries(); + } + var line_no = 0; + + var xParser; + var defaultParserSet = false; // attempt to auto-detect x value type + var expectedCols = this.attr_("labels").length; + var outOfOrder = false; + for (var i = start; i < lines.length; i++) { + var line = lines[i]; + line_no = i; + if (line.length === 0) continue; // skip blank lines + if (line[0] == '#') continue; // skip comment lines + var inFields = line.split(delim); + if (inFields.length < 2) continue; + + var fields = []; + if (!defaultParserSet) { + this.detectTypeFromString_(inFields[0]); + xParser = this.getFunctionOption("xValueParser"); + defaultParserSet = true; + } + fields[0] = xParser(inFields[0], this); + + // If fractions are expected, parse the numbers as "A/B" + if (this.fractions_) { + for (j = 1; j < inFields.length; j++) { + // TODO(danvk): figure out an appropriate way to flag parse errors. + vals = inFields[j].split("/"); + if (vals.length != 2) { + console.error('Expected fractional "num/den" values in CSV data ' + + "but found a value '" + inFields[j] + "' on line " + + (1 + i) + " ('" + line + "') which is not of this form."); + fields[j] = [0, 0]; + } else { + fields[j] = [Dygraph.parseFloat_(vals[0], i, line), + Dygraph.parseFloat_(vals[1], i, line)]; + } + } + } else if (this.getBooleanOption("errorBars")) { + // If there are error bars, values are (value, stddev) pairs + if (inFields.length % 2 != 1) { + console.error('Expected alternating (value, stdev.) pairs in CSV data ' + + 'but line ' + (1 + i) + ' has an odd number of values (' + + (inFields.length - 1) + "): '" + line + "'"); + } + for (j = 1; j < inFields.length; j += 2) { + fields[(j + 1) / 2] = [Dygraph.parseFloat_(inFields[j], i, line), + Dygraph.parseFloat_(inFields[j + 1], i, line)]; + } + } else if (this.getBooleanOption("customBars")) { + // Bars are a low;center;high tuple + for (j = 1; j < inFields.length; j++) { + var val = inFields[j]; + if (/^ *$/.test(val)) { + fields[j] = [null, null, null]; + } else { + vals = val.split(";"); + if (vals.length == 3) { + fields[j] = [ Dygraph.parseFloat_(vals[0], i, line), + Dygraph.parseFloat_(vals[1], i, line), + Dygraph.parseFloat_(vals[2], i, line) ]; + } else { + console.warn('When using customBars, values must be either blank ' + + 'or "low;center;high" tuples (got "' + val + + '" on line ' + (1+i)); + } + } + } + } else { + // Values are just numbers + for (j = 1; j < inFields.length; j++) { + fields[j] = Dygraph.parseFloat_(inFields[j], i, line); + } + } + if (ret.length > 0 && fields[0] < ret[ret.length - 1][0]) { + outOfOrder = true; + } + + if (fields.length != expectedCols) { + console.error("Number of columns in line " + i + " (" + fields.length + + ") does not agree with number of labels (" + expectedCols + + ") " + line); + } + + // If the user specified the 'labels' option and none of the cells of the + // first row parsed correctly, then they probably double-specified the + // labels. We go with the values set in the option, discard this row and + // log a warning to the JS console. + if (i === 0 && this.attr_('labels')) { + var all_null = true; + for (j = 0; all_null && j < fields.length; j++) { + if (fields[j]) all_null = false; + } + if (all_null) { + console.warn("The dygraphs 'labels' option is set, but the first row " + + "of CSV data ('" + line + "') appears to also contain " + + "labels. Will drop the CSV labels and use the option " + + "labels."); + continue; + } + } + ret.push(fields); + } + + if (outOfOrder) { + console.warn("CSV is out of order; order it correctly to speed loading."); + ret.sort(function(a,b) { return a[0] - b[0]; }); + } + + return ret; +}; + +/** + * The user has provided their data as a pre-packaged JS array. If the x values + * are numeric, this is the same as dygraphs' internal format. If the x values + * are dates, we need to convert them from Date objects to ms since epoch. + * @param {!Array} data + * @return {Object} data with numeric x values. + * @private + */ +Dygraph.prototype.parseArray_ = function(data) { + // Peek at the first x value to see if it's numeric. + if (data.length === 0) { + console.error("Can't plot empty data set"); + return null; + } + if (data[0].length === 0) { + console.error("Data set cannot contain an empty row"); + return null; + } + + var i; + if (this.attr_("labels") === null) { + console.warn("Using default labels. Set labels explicitly via 'labels' " + + "in the options parameter"); + this.attrs_.labels = [ "X" ]; + for (i = 1; i < data[0].length; i++) { + this.attrs_.labels.push("Y" + i); // Not user_attrs_. + } + this.attributes_.reparseSeries(); + } else { + var num_labels = this.attr_("labels"); + if (num_labels.length != data[0].length) { + console.error("Mismatch between number of labels (" + num_labels + ")" + + " and number of columns in array (" + data[0].length + ")"); + return null; + } + } + + if (Dygraph.isDateLike(data[0][0])) { + // Some intelligent defaults for a date x-axis. + this.attrs_.axes.x.valueFormatter = Dygraph.dateValueFormatter; + this.attrs_.axes.x.ticker = Dygraph.dateTicker; + this.attrs_.axes.x.axisLabelFormatter = Dygraph.dateAxisLabelFormatter; + + // Assume they're all dates. + var parsedData = Dygraph.clone(data); + for (i = 0; i < data.length; i++) { + if (parsedData[i].length === 0) { + console.error("Row " + (1 + i) + " of data is empty"); + return null; + } + if (parsedData[i][0] === null || + typeof(parsedData[i][0].getTime) != 'function' || + isNaN(parsedData[i][0].getTime())) { + console.error("x value in row " + (1 + i) + " is not a Date"); + return null; + } + parsedData[i][0] = parsedData[i][0].getTime(); + } + return parsedData; + } else { + // Some intelligent defaults for a numeric x-axis. + /** @private (shut up, jsdoc!) */ + this.attrs_.axes.x.valueFormatter = function(x) { return x; }; + this.attrs_.axes.x.ticker = Dygraph.numericTicks; + this.attrs_.axes.x.axisLabelFormatter = Dygraph.numberAxisLabelFormatter; + return data; + } +}; + +/** + * Parses a DataTable object from gviz. + * The data is expected to have a first column that is either a date or a + * number. All subsequent columns must be numbers. If there is a clear mismatch + * between this.xValueParser_ and the type of the first column, it will be + * fixed. Fills out rawData_. + * @param {!google.visualization.DataTable} data See above. + * @private + */ +Dygraph.prototype.parseDataTable_ = function(data) { + var shortTextForAnnotationNum = function(num) { + // converts [0-9]+ [A-Z][a-z]* + // example: 0=A, 1=B, 25=Z, 26=Aa, 27=Ab + // and continues like.. Ba Bb .. Za .. Zz..Aaa...Zzz Aaaa Zzzz + var shortText = String.fromCharCode(65 /* A */ + num % 26); + num = Math.floor(num / 26); + while ( num > 0 ) { + shortText = String.fromCharCode(65 /* A */ + (num - 1) % 26 ) + shortText.toLowerCase(); + num = Math.floor((num - 1) / 26); + } + return shortText; + }; + + var cols = data.getNumberOfColumns(); + var rows = data.getNumberOfRows(); + + var indepType = data.getColumnType(0); + if (indepType == 'date' || indepType == 'datetime') { + this.attrs_.xValueParser = Dygraph.dateParser; + this.attrs_.axes.x.valueFormatter = Dygraph.dateValueFormatter; + this.attrs_.axes.x.ticker = Dygraph.dateTicker; + this.attrs_.axes.x.axisLabelFormatter = Dygraph.dateAxisLabelFormatter; + } else if (indepType == 'number') { + this.attrs_.xValueParser = function(x) { return parseFloat(x); }; + this.attrs_.axes.x.valueFormatter = function(x) { return x; }; + this.attrs_.axes.x.ticker = Dygraph.numericTicks; + this.attrs_.axes.x.axisLabelFormatter = this.attrs_.axes.x.valueFormatter; + } else { + console.error("only 'date', 'datetime' and 'number' types are supported " + + "for column 1 of DataTable input (Got '" + indepType + "')"); + return null; + } + + // Array of the column indices which contain data (and not annotations). + var colIdx = []; + var annotationCols = {}; // data index -> [annotation cols] + var hasAnnotations = false; + var i, j; + for (i = 1; i < cols; i++) { + var type = data.getColumnType(i); + if (type == 'number') { + colIdx.push(i); + } else if (type == 'string' && this.getBooleanOption('displayAnnotations')) { + // This is OK -- it's an annotation column. + var dataIdx = colIdx[colIdx.length - 1]; + if (!annotationCols.hasOwnProperty(dataIdx)) { + annotationCols[dataIdx] = [i]; + } else { + annotationCols[dataIdx].push(i); + } + hasAnnotations = true; + } else { + console.error("Only 'number' is supported as a dependent type with Gviz." + + " 'string' is only supported if displayAnnotations is true"); + } + } + + // Read column labels + // TODO(danvk): add support back for errorBars + var labels = [data.getColumnLabel(0)]; + for (i = 0; i < colIdx.length; i++) { + labels.push(data.getColumnLabel(colIdx[i])); + if (this.getBooleanOption("errorBars")) i += 1; + } + this.attrs_.labels = labels; + cols = labels.length; + + var ret = []; + var outOfOrder = false; + var annotations = []; + for (i = 0; i < rows; i++) { + var row = []; + if (typeof(data.getValue(i, 0)) === 'undefined' || + data.getValue(i, 0) === null) { + console.warn("Ignoring row " + i + + " of DataTable because of undefined or null first column."); + continue; + } + + if (indepType == 'date' || indepType == 'datetime') { + row.push(data.getValue(i, 0).getTime()); + } else { + row.push(data.getValue(i, 0)); + } + if (!this.getBooleanOption("errorBars")) { + for (j = 0; j < colIdx.length; j++) { + var col = colIdx[j]; + row.push(data.getValue(i, col)); + if (hasAnnotations && + annotationCols.hasOwnProperty(col) && + data.getValue(i, annotationCols[col][0]) !== null) { + var ann = {}; + ann.series = data.getColumnLabel(col); + ann.xval = row[0]; + ann.shortText = shortTextForAnnotationNum(annotations.length); + ann.text = ''; + for (var k = 0; k < annotationCols[col].length; k++) { + if (k) ann.text += "\n"; + ann.text += data.getValue(i, annotationCols[col][k]); + } + annotations.push(ann); + } + } + + // Strip out infinities, which give dygraphs problems later on. + for (j = 0; j < row.length; j++) { + if (!isFinite(row[j])) row[j] = null; + } + } else { + for (j = 0; j < cols - 1; j++) { + row.push([ data.getValue(i, 1 + 2 * j), data.getValue(i, 2 + 2 * j) ]); + } + } + if (ret.length > 0 && row[0] < ret[ret.length - 1][0]) { + outOfOrder = true; + } + ret.push(row); + } + + if (outOfOrder) { + console.warn("DataTable is out of order; order it correctly to speed loading."); + ret.sort(function(a,b) { return a[0] - b[0]; }); + } + this.rawData_ = ret; + + if (annotations.length > 0) { + this.setAnnotations(annotations, true); + } + this.attributes_.reparseSeries(); +}; + +/** + * Signals to plugins that the chart data has updated. + * This happens after the data has updated but before the chart has redrawn. + */ +Dygraph.prototype.cascadeDataDidUpdateEvent_ = function() { + // TODO(danvk): there are some issues checking xAxisRange() and using + // toDomCoords from handlers of this event. The visible range should be set + // when the chart is drawn, not derived from the data. + this.cascadeEvents_('dataDidUpdate', {}); +}; + +/** + * Get the CSV data. If it's in a function, call that function. If it's in a + * file, do an XMLHttpRequest to get it. + * @private + */ +Dygraph.prototype.start_ = function() { + var data = this.file_; + + // Functions can return references of all other types. + if (typeof data == 'function') { + data = data(); + } + + if (Dygraph.isArrayLike(data)) { + this.rawData_ = this.parseArray_(data); + this.cascadeDataDidUpdateEvent_(); + this.predraw_(); + } else if (typeof data == 'object' && + typeof data.getColumnRange == 'function') { + // must be a DataTable from gviz. + this.parseDataTable_(data); + this.cascadeDataDidUpdateEvent_(); + this.predraw_(); + } else if (typeof data == 'string') { + // Heuristic: a newline means it's CSV data. Otherwise it's an URL. + var line_delimiter = Dygraph.detectLineDelimiter(data); + if (line_delimiter) { + this.loadedEvent_(data); + } else { + // REMOVE_FOR_IE + var req; + if (window.XMLHttpRequest) { + // Firefox, Opera, IE7, and other browsers will use the native object + req = new XMLHttpRequest(); + } else { + // IE 5 and 6 will use the ActiveX control + req = new ActiveXObject("Microsoft.XMLHTTP"); + } + + var caller = this; + req.onreadystatechange = function () { + if (req.readyState == 4) { + if (req.status === 200 || // Normal http + req.status === 0) { // Chrome w/ --allow-file-access-from-files + caller.loadedEvent_(req.responseText); + } + } + }; + + req.open("GET", data, true); + req.send(null); + } + } else { + console.error("Unknown data format: " + (typeof data)); + } +}; + +/** + * Changes various properties of the graph. These can include: + *
    + *
  • file: changes the source data for the graph
  • + *
  • errorBars: changes whether the data contains stddev
  • + *
+ * + * There's a huge variety of options that can be passed to this method. For a + * full list, see http://dygraphs.com/options.html. + * + * @param {Object} input_attrs The new properties and values + * @param {boolean} block_redraw Usually the chart is redrawn after every + * call to updateOptions(). If you know better, you can pass true to + * explicitly block the redraw. This can be useful for chaining + * updateOptions() calls, avoiding the occasional infinite loop and + * preventing redraws when it's not necessary (e.g. when updating a + * callback). + */ +Dygraph.prototype.updateOptions = function(input_attrs, block_redraw) { + if (typeof(block_redraw) == 'undefined') block_redraw = false; + + // mapLegacyOptions_ drops the "file" parameter as a convenience to us. + var file = input_attrs.file; + var attrs = Dygraph.mapLegacyOptions_(input_attrs); + + // TODO(danvk): this is a mess. Move these options into attr_. + if ('rollPeriod' in attrs) { + this.rollPeriod_ = attrs.rollPeriod; + } + if ('dateWindow' in attrs) { + this.dateWindow_ = attrs.dateWindow; + if (!('isZoomedIgnoreProgrammaticZoom' in attrs)) { + this.zoomed_x_ = (attrs.dateWindow !== null); + } + } + if ('valueRange' in attrs && !('isZoomedIgnoreProgrammaticZoom' in attrs)) { + this.zoomed_y_ = (attrs.valueRange !== null); + } + + // TODO(danvk): validate per-series options. + // Supported: + // strokeWidth + // pointSize + // drawPoints + // highlightCircleSize + + // Check if this set options will require new points. + var requiresNewPoints = Dygraph.isPixelChangingOptionList(this.attr_("labels"), attrs); + + Dygraph.updateDeep(this.user_attrs_, attrs); + + this.attributes_.reparseSeries(); + + if (file) { + // This event indicates that the data is about to change, but hasn't yet. + // TODO(danvk): support cancelation of the update via this event. + this.cascadeEvents_('dataWillUpdate', {}); + + this.file_ = file; + if (!block_redraw) this.start_(); + } else { + if (!block_redraw) { + if (requiresNewPoints) { + this.predraw_(); + } else { + this.renderGraph_(false); + } + } + } +}; + +/** + * Returns a copy of the options with deprecated names converted into current + * names. Also drops the (potentially-large) 'file' attribute. If the caller is + * interested in that, they should save a copy before calling this. + * @private + */ +Dygraph.mapLegacyOptions_ = function(attrs) { + var my_attrs = {}; + for (var k in attrs) { + if (!attrs.hasOwnProperty(k)) continue; + if (k == 'file') continue; + if (attrs.hasOwnProperty(k)) my_attrs[k] = attrs[k]; + } + + var set = function(axis, opt, value) { + if (!my_attrs.axes) my_attrs.axes = {}; + if (!my_attrs.axes[axis]) my_attrs.axes[axis] = {}; + my_attrs.axes[axis][opt] = value; + }; + var map = function(opt, axis, new_opt) { + if (typeof(attrs[opt]) != 'undefined') { + console.warn("Option " + opt + " is deprecated. Use the " + + new_opt + " option for the " + axis + " axis instead. " + + "(e.g. { axes : { " + axis + " : { " + new_opt + " : ... } } } " + + "(see http://dygraphs.com/per-axis.html for more information."); + set(axis, new_opt, attrs[opt]); + delete my_attrs[opt]; + } + }; + + // This maps, e.g., xValueFormater -> axes: { x: { valueFormatter: ... } } + map('xValueFormatter', 'x', 'valueFormatter'); + map('pixelsPerXLabel', 'x', 'pixelsPerLabel'); + map('xAxisLabelFormatter', 'x', 'axisLabelFormatter'); + map('xTicker', 'x', 'ticker'); + map('yValueFormatter', 'y', 'valueFormatter'); + map('pixelsPerYLabel', 'y', 'pixelsPerLabel'); + map('yAxisLabelFormatter', 'y', 'axisLabelFormatter'); + map('yTicker', 'y', 'ticker'); + map('drawXGrid', 'x', 'drawGrid'); + map('drawXAxis', 'x', 'drawAxis'); + map('drawYGrid', 'y', 'drawGrid'); + map('drawYAxis', 'y', 'drawAxis'); + map('xAxisLabelWidth', 'x', 'axisLabelWidth'); + map('yAxisLabelWidth', 'y', 'axisLabelWidth'); + return my_attrs; +}; + +/** + * Resizes the dygraph. If no parameters are specified, resizes to fill the + * containing div (which has presumably changed size since the dygraph was + * instantiated. If the width/height are specified, the div will be resized. + * + * This is far more efficient than destroying and re-instantiating a + * Dygraph, since it doesn't have to reparse the underlying data. + * + * @param {number} width Width (in pixels) + * @param {number} height Height (in pixels) + */ +Dygraph.prototype.resize = function(width, height) { + if (this.resize_lock) { + return; + } + this.resize_lock = true; + + if ((width === null) != (height === null)) { + console.warn("Dygraph.resize() should be called with zero parameters or " + + "two non-NULL parameters. Pretending it was zero."); + width = height = null; + } + + var old_width = this.width_; + var old_height = this.height_; + + if (width) { + this.maindiv_.style.width = width + "px"; + this.maindiv_.style.height = height + "px"; + this.width_ = width; + this.height_ = height; + } else { + this.width_ = this.maindiv_.clientWidth; + this.height_ = this.maindiv_.clientHeight; + } + + if (old_width != this.width_ || old_height != this.height_) { + // Resizing a canvas erases it, even when the size doesn't change, so + // any resize needs to be followed by a redraw. + this.resizeElements_(); + this.predraw_(); + } + + this.resize_lock = false; +}; + +/** + * Adjusts the number of points in the rolling average. Updates the graph to + * reflect the new averaging period. + * @param {number} length Number of points over which to average the data. + */ +Dygraph.prototype.adjustRoll = function(length) { + this.rollPeriod_ = length; + this.predraw_(); +}; + +/** + * Returns a boolean array of visibility statuses. + */ +Dygraph.prototype.visibility = function() { + // Do lazy-initialization, so that this happens after we know the number of + // data series. + if (!this.getOption("visibility")) { + this.attrs_.visibility = []; + } + // TODO(danvk): it looks like this could go into an infinite loop w/ user_attrs. + while (this.getOption("visibility").length < this.numColumns() - 1) { + this.attrs_.visibility.push(true); + } + return this.getOption("visibility"); +}; + +/** + * Changes the visiblity of a series. + * + * @param {number} num the series index + * @param {boolean} value true or false, identifying the visibility. + */ +Dygraph.prototype.setVisibility = function(num, value) { + var x = this.visibility(); + if (num < 0 || num >= x.length) { + console.warn("invalid series number in setVisibility: " + num); + } else { + x[num] = value; + this.predraw_(); + } +}; + +/** + * How large of an area will the dygraph render itself in? + * This is used for testing. + * @return A {width: w, height: h} object. + * @private + */ +Dygraph.prototype.size = function() { + return { width: this.width_, height: this.height_ }; +}; + +/** + * Update the list of annotations and redraw the chart. + * See dygraphs.com/annotations.html for more info on how to use annotations. + * @param ann {Array} An array of annotation objects. + * @param suppressDraw {Boolean} Set to "true" to block chart redraw (optional). + */ +Dygraph.prototype.setAnnotations = function(ann, suppressDraw) { + // Only add the annotation CSS rule once we know it will be used. + Dygraph.addAnnotationRule(); + this.annotations_ = ann; + if (!this.layout_) { + console.warn("Tried to setAnnotations before dygraph was ready. " + + "Try setting them in a ready() block. See " + + "dygraphs.com/tests/annotation.html"); + return; + } + + this.layout_.setAnnotations(this.annotations_); + if (!suppressDraw) { + this.predraw_(); + } +}; + +/** + * Return the list of annotations. + */ +Dygraph.prototype.annotations = function() { + return this.annotations_; +}; + +/** + * Get the list of label names for this graph. The first column is the + * x-axis, so the data series names start at index 1. + * + * Returns null when labels have not yet been defined. + */ +Dygraph.prototype.getLabels = function() { + var labels = this.attr_("labels"); + return labels ? labels.slice() : null; +}; + +/** + * Get the index of a series (column) given its name. The first column is the + * x-axis, so the data series start with index 1. + */ +Dygraph.prototype.indexFromSetName = function(name) { + return this.setIndexByName_[name]; +}; + +/** + * Trigger a callback when the dygraph has drawn itself and is ready to be + * manipulated. This is primarily useful when dygraphs has to do an XHR for the + * data (i.e. a URL is passed as the data source) and the chart is drawn + * asynchronously. If the chart has already drawn, the callback will fire + * immediately. + * + * This is a good place to call setAnnotation(). + * + * @param {function(!Dygraph)} callback The callback to trigger when the chart + * is ready. + */ +Dygraph.prototype.ready = function(callback) { + if (this.is_initial_draw_) { + this.readyFns_.push(callback); + } else { + callback.call(this, this); + } +}; + +/** + * @private + * Adds a default style for the annotation CSS classes to the document. This is + * only executed when annotations are actually used. It is designed to only be + * called once -- all calls after the first will return immediately. + */ +Dygraph.addAnnotationRule = function() { + // TODO(danvk): move this function into plugins/annotations.js? + if (Dygraph.addedAnnotationCSS) return; + + var rule = "border: 1px solid black; " + + "background-color: white; " + + "text-align: center;"; + + var styleSheetElement = document.createElement("style"); + styleSheetElement.type = "text/css"; + document.getElementsByTagName("head")[0].appendChild(styleSheetElement); + + // Find the first style sheet that we can access. + // We may not add a rule to a style sheet from another domain for security + // reasons. This sometimes comes up when using gviz, since the Google gviz JS + // adds its own style sheets from google.com. + for (var i = 0; i < document.styleSheets.length; i++) { + if (document.styleSheets[i].disabled) continue; + var mysheet = document.styleSheets[i]; + try { + if (mysheet.insertRule) { // Firefox + var idx = mysheet.cssRules ? mysheet.cssRules.length : 0; + mysheet.insertRule(".dygraphDefaultAnnotation { " + rule + " }", idx); + } else if (mysheet.addRule) { // IE + mysheet.addRule(".dygraphDefaultAnnotation", rule); + } + Dygraph.addedAnnotationCSS = true; + return; + } catch(err) { + // Was likely a security exception. + } + } + + console.warn("Unable to add default annotation CSS rule; display may be off."); +}; + +if (typeof exports === "object" && typeof module !== "undefined") { + module.exports = Dygraph; +} + +return Dygraph; + +})(); +/** + * @license + * Copyright 2011 Dan Vanderkam (danvdk@gmail.com) + * MIT-licensed (http://opensource.org/licenses/MIT) + */ + +/** + * @fileoverview This file contains utility functions used by dygraphs. These + * are typically static (i.e. not related to any particular dygraph). Examples + * include date/time formatting functions, basic algorithms (e.g. binary + * search) and generic DOM-manipulation functions. + */ + +(function() { + +/*global Dygraph:false, G_vmlCanvasManager:false, Node:false */ +"use strict"; + +Dygraph.LOG_SCALE = 10; +Dygraph.LN_TEN = Math.log(Dygraph.LOG_SCALE); + +/** + * @private + * @param {number} x + * @return {number} + */ +Dygraph.log10 = function(x) { + return Math.log(x) / Dygraph.LN_TEN; +}; + +/** A dotted line stroke pattern. */ +Dygraph.DOTTED_LINE = [2, 2]; +/** A dashed line stroke pattern. */ +Dygraph.DASHED_LINE = [7, 3]; +/** A dot dash stroke pattern. */ +Dygraph.DOT_DASH_LINE = [7, 2, 2, 2]; + +/** + * Return the 2d context for a dygraph canvas. + * + * This method is only exposed for the sake of replacing the function in + * automated tests, e.g. + * + * var oldFunc = Dygraph.getContext(); + * Dygraph.getContext = function(canvas) { + * var realContext = oldFunc(canvas); + * return new Proxy(realContext); + * }; + * @param {!HTMLCanvasElement} canvas + * @return {!CanvasRenderingContext2D} + * @private + */ +Dygraph.getContext = function(canvas) { + return /** @type{!CanvasRenderingContext2D}*/(canvas.getContext("2d")); +}; + +/** + * Add an event handler. This smooths a difference between IE and the rest of + * the world. + * @param {!Node} 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) { + elem.addEventListener(type, fn, false); + } else { + elem[type+fn] = function(){fn(window.event);}; + elem.attachEvent('on'+type, elem[type+fn]); + } +}; + +/** + * Add an event handler. This event handler is kept until the graph is + * destroyed with a call to graph.destroy(). + * + * @param {!Node} 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.addAndTrackEvent = function(elem, type, fn) { + Dygraph.addEvent(elem, type, fn); + this.registeredEvents_.push({ elem : elem, type : type, fn : fn }); +}; + +/** + * Remove an event handler. This smooths a difference between IE and the rest + * of the world. + * @param {!Node} elem The element to remove the event from. + * @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.removeEvent = function(elem, type, fn) { + if (elem.removeEventListener) { + elem.removeEventListener(type, fn, false); + } else { + try { + elem.detachEvent('on'+type, elem[type+fn]); + } catch(e) { + // We only detach event listeners on a "best effort" basis in IE. See: + // http://stackoverflow.com/questions/2553632/detachevent-not-working-with-named-inline-functions + } + elem[type+fn] = null; + } +}; + +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. + * 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. + * @private + */ +Dygraph.cancelEvent = function(e) { + e = e ? e : window.event; + if (e.stopPropagation) { + e.stopPropagation(); + } + if (e.preventDefault) { + e.preventDefault(); + } + e.cancelBubble = true; + e.cancel = true; + e.returnValue = false; + return false; +}; + +/** + * 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. + * @private + */ +Dygraph.hsvToRGB = function (hue, saturation, value) { + var red; + var green; + var blue; + if (saturation === 0) { + red = value; + green = value; + blue = value; + } else { + var i = Math.floor(hue * 6); + var f = (hue * 6) - i; + var p = value * (1 - saturation); + var q = value * (1 - (saturation * f)); + var t = value * (1 - (saturation * (1 - f))); + switch (i) { + case 1: red = q; green = value; blue = p; break; + case 2: red = p; green = value; blue = t; break; + case 3: red = p; green = q; blue = value; break; + case 4: red = t; green = p; blue = value; break; + case 5: red = value; green = p; blue = q; break; + case 6: // fall through + case 0: red = value; green = t; blue = p; break; + } + } + red = Math.floor(255 * red + 0.5); + green = Math.floor(255 * green + 0.5); + blue = Math.floor(255 * blue + 0.5); + return 'rgb(' + red + ',' + green + ',' + blue + ')'; +}; + +// The following functions are from quirksmode.org with a modification for Safari from +// http://blog.firetree.net/2005/07/04/javascript-find-position/ +// http://www.quirksmode.org/js/findpos.html +// ... and modifications to support scrolling divs. + +/** + * Find the coordinates of an object relative to the top left of the page. + * + * TODO(danvk): change obj type from Node -> !Node + * @param {Node} obj + * @return {{x:number,y:number}} + * @private + */ +Dygraph.findPos = function(obj) { + var curleft = 0, curtop = 0; + if (obj.offsetParent) { + var copyObj = obj; + while (1) { + // NOTE: the if statement here is for IE8. + var borderLeft = "0", borderTop = "0"; + if (window.getComputedStyle) { + var computedStyle = window.getComputedStyle(copyObj, null); + borderLeft = computedStyle.borderLeft || "0"; + borderTop = computedStyle.borderTop || "0"; + } + curleft += parseInt(borderLeft, 10) ; + curtop += parseInt(borderTop, 10) ; + curleft += copyObj.offsetLeft; + curtop += copyObj.offsetTop; + if (!copyObj.offsetParent) { + break; + } + copyObj = copyObj.offsetParent; + } + } else { + // TODO(danvk): why would obj ever have these properties? + if (obj.x) curleft += obj.x; + if (obj.y) curtop += obj.y; + } + + // This handles the case where the object is inside a scrolled div. + while (obj && obj != document.body) { + curleft -= obj.scrollLeft; + curtop -= obj.scrollTop; + obj = obj.parentNode; + } + return {x: curleft, y: curtop}; +}; + +/** + * 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.documentElement; + var b = document.body; + return e.clientX + + (de.scrollLeft || b.scrollLeft) - + (de.clientLeft || 0); + } +}; + +/** + * 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.documentElement; + var b = document.body; + return e.clientY + + (de.scrollTop || b.scrollTop) - + (de.clientTop || 0); + } +}; + +/** + * Converts page the x-coordinate of the event to pixel x-coordinates on the + * canvas (i.e. DOM Coords). + * @param {!Event} e Drag event. + * @param {!DygraphInteractionContext} context Interaction context object. + * @return {number} The amount by which the drag has moved to the right. + */ +Dygraph.dragGetX_ = function(e, context) { + return Dygraph.pageX(e) - context.px; +}; + +/** + * Converts page the y-coordinate of the event to pixel y-coordinates on the + * canvas (i.e. DOM Coords). + * @param {!Event} e Drag event. + * @param {!DygraphInteractionContext} context Interaction context object. + * @return {number} The amount by which the drag has moved down. + */ +Dygraph.dragGetY_ = function(e, context) { + return Dygraph.pageY(e) - context.py; +}; + +/** + * 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 + */ +Dygraph.isOK = function(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=} opt_allowNaNY Treat point with y=NaN as valid + * @return {boolean} Whether the point has numeric x and y. + * @private + */ +Dygraph.isValidPoint = function(p, opt_allowNaNY) { + 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) || (!opt_allowNaNY && isNaN(p.y))) return false; + return true; +}; + +/** + * Number formatting function which mimicks the behavior of %g in printf, i.e. + * either exponential or fixed format (without trailing 0s) is used depending on + * the length of the generated string. The advantage of this format is that + * there is a predictable upper bound on the resulting string length, + * significant figures are not dropped, and normal numbers are not displayed in + * exponential notation. + * + * NOTE: JavaScript's native toPrecision() is NOT a drop-in replacement for %g. + * It creates strings which are too long for absolute values between 10^-4 and + * 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 + * string length should be precision + 6 (e.g 1.123e+300). + */ +Dygraph.floatFormat = function(x, opt_precision) { + // Avoid invalid precision values; [1, 21] is the valid range. + var p = Math.min(Math.max(1, opt_precision || 2), 21); + + // This is deceptively simple. The actual algorithm comes from: + // + // Max allowed length = p + 4 + // where 4 comes from 'e+n' and '.'. + // + // Length of fixed format = 2 + y + p + // where 2 comes from '0.' and y = # of leading zeroes. + // + // Equating the two and solving for y yields y = 2, or 0.00xxxx which is + // 1.0e-3. + // + // Since the behavior of toPrecision() is identical for larger numbers, we + // don't have to worry about the other bound. + // + // Finally, the argument for toExponential() is the number of trailing digits, + // so we take off 1 for the value before the '.'. + return (Math.abs(x) < 1.0e-3 && x !== 0.0) ? + x.toExponential(p - 1) : x.toPrecision(p); +}; + +/** + * 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; +}; + +/** + * Date accessors to get the parts of a calendar date (year, month, + * day, hour, minute, second and millisecond) according to local time, + * and factory method to call the Date constructor with an array of arguments. + */ +Dygraph.DateAccessorsLocal = { + getFullYear: function(d) {return d.getFullYear();}, + getMonth: function(d) {return d.getMonth();}, + getDate: function(d) {return d.getDate();}, + getHours: function(d) {return d.getHours();}, + getMinutes: function(d) {return d.getMinutes();}, + getSeconds: function(d) {return d.getSeconds();}, + getMilliseconds: function(d) {return d.getMilliseconds();}, + getDay: function(d) {return d.getDay();}, + makeDate: function(y, m, d, hh, mm, ss, ms) { + return new Date(y, m, d, hh, mm, ss, ms); + } +}; + +/** + * Date accessors to get the parts of a calendar date (year, month, + * day of month, hour, minute, second and millisecond) according to UTC time, + * and factory method to call the Date constructor with an array of arguments. + */ +Dygraph.DateAccessorsUTC = { + getFullYear: function(d) {return d.getUTCFullYear();}, + getMonth: function(d) {return d.getUTCMonth();}, + getDate: function(d) {return d.getUTCDate();}, + getHours: function(d) {return d.getUTCHours();}, + getMinutes: function(d) {return d.getUTCMinutes();}, + getSeconds: function(d) {return d.getUTCSeconds();}, + getMilliseconds: function(d) {return d.getUTCMilliseconds();}, + getDay: function(d) {return d.getUTCDay();}, + makeDate: function(y, m, d, hh, mm, ss, ms) { + return new Date(Date.UTC(y, m, d, hh, mm, ss, ms)); + } +}; + +/** + * Return a string version of the hours, minutes and seconds portion of a date. + * @param {number} hh The hours (from 0-23) + * @param {number} mm The minutes (from 0-59) + * @param {number} ss The seconds (from 0-59) + * @return {string} A time of the form "HH:MM" or "HH:MM:SS" + * @private + */ +Dygraph.hmsString_ = function(hh, mm, ss) { + var zeropad = Dygraph.zeropad; + var ret = zeropad(hh) + ":" + zeropad(mm); + if (ss) { + ret += ":" + zeropad(ss); + } + return ret; +}; + +/** + * Convert a JS date (millis since epoch) to a formatted string. + * @param {number} time The JavaScript time value (ms since epoch) + * @param {boolean} utc Wether output UTC or local time + * @return {string} A date of one of these forms: + * "YYYY/MM/DD", "YYYY/MM/DD HH:MM" or "YYYY/MM/DD HH:MM:SS" + * @private + */ +Dygraph.dateString_ = function(time, utc) { + var zeropad = Dygraph.zeropad; + var accessors = utc ? Dygraph.DateAccessorsUTC : Dygraph.DateAccessorsLocal; + var date = new Date(time); + var y = accessors.getFullYear(date); + var m = accessors.getMonth(date); + var d = accessors.getDate(date); + var hh = accessors.getHours(date); + var mm = accessors.getMinutes(date); + var ss = accessors.getSeconds(date); + // Get a year string: + var year = "" + y; + // Get a 0 padded month string + var month = zeropad(m + 1); //months are 0-offset, sigh + // Get a 0 padded day string + var day = zeropad(d); + var frac = hh * 3600 + mm * 60 + ss; + var ret = year + "/" + month + "/" + day; + if (frac) { + ret += " " + Dygraph.hmsString_(hh, mm, ss); + } + return ret; +}; + +/** + * 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 + * @private + */ +Dygraph.round_ = function(num, places) { + var shift = Math.pow(10, places); + return Math.round(num * shift)/shift; +}; + +/** + * Implementation of binary search over an array. + * Currently does not work when val is outside the range of arry's values. + * @param {number} val the value to search for + * @param {Array.} 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 || + high === null || high === undefined) { + low = 0; + high = arry.length - 1; + } + if (low > high) { + return -1; + } + if (abs === null || abs === undefined) { + abs = 0; + } + var validIndex = function(idx) { + return idx >= 0 && idx < arry.length; + }; + var mid = parseInt((low + high) / 2, 10); + var element = arry[mid]; + var idx; + if (element == val) { + return mid; + } else if (element > val) { + if (abs > 0) { + // Accept if element > val, but also if prior element < val. + idx = mid - 1; + if (validIndex(idx) && arry[idx] < val) { + return mid; + } + } + return Dygraph.binarySearch(val, arry, abs, low, mid - 1); + } else if (element < val) { + if (abs < 0) { + // Accept if element < val, but also if prior element > val. + idx = mid + 1; + if (validIndex(idx) && arry[idx] > val) { + return mid; + } + } + return Dygraph.binarySearch(val, arry, abs, mid + 1, high); + } + return -1; // can't actually happen, but makes closure compiler happy +}; + +/** + * 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} dateStr A date in a variety of possible string formats. + * @return {number} Milliseconds since epoch. + * @private + */ +Dygraph.dateParser = function(dateStr) { + var dateStrSlashed; + var d; + + // Let the system try the format first, with one caveat: + // YYYY-MM-DD[ HH:MM:SS] is interpreted as UTC by a variety of browsers. + // dygraphs displays dates in local time, so this will result in surprising + // inconsistencies. But if you specify "T" or "Z" (i.e. YYYY-MM-DDTHH:MM:SS), + // then you probably know what you're doing, so we'll let you go ahead. + // Issue: http://code.google.com/p/dygraphs/issues/detail?id=255 + if (dateStr.search("-") == -1 || + dateStr.search("T") != -1 || dateStr.search("Z") != -1) { + d = Dygraph.dateStrToMillis(dateStr); + if (d && !isNaN(d)) return d; + } + + if (dateStr.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12' + dateStrSlashed = dateStr.replace("-", "/", "g"); + while (dateStrSlashed.search("-") != -1) { + dateStrSlashed = dateStrSlashed.replace("-", "/"); + } + d = Dygraph.dateStrToMillis(dateStrSlashed); + } else if (dateStr.length == 8) { // e.g. '20090712' + // TODO(danvk): remove support for this format. It's confusing. + dateStrSlashed = dateStr.substr(0,4) + "/" + dateStr.substr(4,2) + "/" + + dateStr.substr(6,2); + d = Dygraph.dateStrToMillis(dateStrSlashed); + } else { + // Any format that Date.parse will accept, e.g. "2009/07/12" or + // "2009/07/12 12:34:56" + d = Dygraph.dateStrToMillis(dateStr); + } + + if (!d || isNaN(d)) { + console.error("Couldn't parse " + dateStr + " as a date"); + } + return d; +}; + +/** + * 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 {number} millis since epoch + * @private + */ +Dygraph.dateStrToMillis = function(str) { + return new Date(str).getTime(); +}; + +// These functions are all based on MochiKit. +/** + * Copies all the properties from o to self. + * + * @param {!Object} self + * @param {!Object} o + * @return {!Object} + */ +Dygraph.update = function(self, o) { + if (typeof(o) != 'undefined' && o !== null) { + for (var k in o) { + if (o.hasOwnProperty(k)) { + self[k] = o[k]; + } + } + } + return self; +}; + +/** + * Copies all the properties from o to self. + * + * @param {!Object} self + * @param {!Object} o + * @return {!Object} + * @private + */ +Dygraph.updateDeep = function (self, o) { + // Taken from http://stackoverflow.com/questions/384286/javascript-isdom-how-do-you-check-if-a-javascript-object-is-a-dom-object + function isNode(o) { + return ( + typeof Node === "object" ? o instanceof Node : + typeof o === "object" && typeof o.nodeType === "number" && typeof o.nodeName==="string" + ); + } + + if (typeof(o) != 'undefined' && o !== null) { + for (var k in o) { + if (o.hasOwnProperty(k)) { + if (o[k] === null) { + self[k] = null; + } else if (Dygraph.isArrayLike(o[k])) { + self[k] = o[k].slice(); + } else if (isNode(o[k])) { + // DOM objects are shallowly-copied. + self[k] = o[k]; + } else if (typeof(o[k]) == 'object') { + if (typeof(self[k]) != 'object' || self[k] === null) { + self[k] = {}; + } + Dygraph.updateDeep(self[k], o[k]); + } else { + self[k] = o[k]; + } + } + } + } + return self; +}; + +/** + * @param {*} o + * @return {boolean} + * @private + */ +Dygraph.isArrayLike = function(o) { + var typ = typeof(o); + if ( + (typ != 'object' && !(typ == 'function' && + typeof(o.item) == 'function')) || + o === null || + typeof(o.length) != 'number' || + o.nodeType === 3 + ) { + return false; + } + return true; +}; + +/** + * @param {Object} o + * @return {boolean} + * @private + */ +Dygraph.isDateLike = function (o) { + if (typeof(o) != "object" || o === null || + typeof(o.getTime) != 'function') { + return false; + } + return true; +}; + +/** + * Note: this only seems to work for arrays. + * @param {!Array} o + * @return {!Array} + * @private + */ +Dygraph.clone = function(o) { + // TODO(danvk): figure out how MochiKit's version works + var r = []; + for (var i = 0; i < o.length; i++) { + if (Dygraph.isArrayLike(o[i])) { + r.push(Dygraph.clone(o[i])); + } else { + r.push(o[i]); + } + } + return r; +}; + +/** + * 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( + /**@type{!HTMLCanvasElement}*/(canvas)); + } + + return canvas; +}; + +/** + * Returns the context's pixel ratio, which is the ratio between the device + * pixel ratio and the backing store ratio. Typically this is 1 for conventional + * displays, and > 1 for HiDPI displays (such as the Retina MBP). + * See http://www.html5rocks.com/en/tutorials/canvas/hidpi/ for more details. + * + * @param {!CanvasRenderingContext2D} context The canvas's 2d context. + * @return {number} The ratio of the device pixel ratio and the backing store + * ratio for the specified context. + */ +Dygraph.getContextPixelRatio = function(context) { + try { + var devicePixelRatio = window.devicePixelRatio; + var backingStoreRatio = context.webkitBackingStorePixelRatio || + context.mozBackingStorePixelRatio || + context.msBackingStorePixelRatio || + context.oBackingStorePixelRatio || + context.backingStorePixelRatio || 1; + if (devicePixelRatio !== undefined) { + return devicePixelRatio / backingStoreRatio; + } else { + // At least devicePixelRatio must be defined for this ratio to make sense. + // We default backingStoreRatio to 1: this does not exist on some browsers + // (i.e. desktop Chrome). + return 1; + } + } catch (e) { + return 1; + } +}; + +/** + * Checks whether the user is on an Android browser. + * Android does not fully support the 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; + this.hasNext = true; // Use to identify if there's another element. + this.peek = null; // Use for look-ahead + this.start_ = start; + this.array_ = array; + this.predicate_ = predicate; + this.end_ = Math.min(array.length, start + length); + this.nextIdx_ = start - 1; // use -1 so initial advance works. + this.next(); // ignoring result. +}; + +/** + * @return {Object} + */ +Dygraph.Iterator.prototype.next = function() { + if (!this.hasNext) { + return null; + } + var obj = this.peek; + + var nextIdx = this.nextIdx_ + 1; + var found = false; + while (nextIdx < this.end_) { + if (!this.predicate_ || this.predicate_(this.array_, nextIdx)) { + this.peek = this.array_[nextIdx]; + found = true; + break; + } + nextIdx++; + } + this.nextIdx_ = nextIdx; + if (!found) { + this.hasNext = false; + this.peek = null; + } + return obj; +}; + +/** + * Returns a new iterator over array, between indexes start and + * start + length, and only returns entries that pass the accept function + * + * @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, opt_predicate) { + return new Dygraph.Iterator(array, start, length, opt_predicate); +}; + +// Shim layer with setTimeout fallback. +// From: http://paulirish.com/2011/requestanimationframe-for-smart-animating/ +// Should be called with the window context: +// Dygraph.requestAnimFrame.call(window, function() {}) +Dygraph.requestAnimFrame = (function() { + return window.requestAnimationFrame || + window.webkitRequestAnimationFrame || + window.mozRequestAnimationFrame || + window.oRequestAnimationFrame || + window.msRequestAnimationFrame || + function (callback) { + window.setTimeout(callback, 1000 / 60); + }; +})(); + +/** + * Call a function at most maxFrames times at an attempted interval of + * framePeriodInMillis, then call a cleanup function once. repeatFn is called + * once immediately, then at most (maxFrames - 1) times asynchronously. If + * maxFrames==1, then cleanup_fn() is also called synchronously. This function + * is used to sequence animation. + * @param {function(number)} repeatFn Called repeatedly -- takes the frame + * number (from 0 to maxFrames-1) as an argument. + * @param {number} maxFrames The max number of times to call repeatFn + * @param {number} framePeriodInMillis Max requested time between frames. + * @param {function()} cleanupFn A function to call after all repeatFn calls. + * @private + */ +Dygraph.repeatAndCleanup = function(repeatFn, maxFrames, framePeriodInMillis, + cleanupFn) { + var frameNumber = 0; + var previousFrameNumber; + var startTime = new Date().getTime(); + repeatFn(frameNumber); + if (maxFrames == 1) { + cleanupFn(); + return; + } + var maxFrameArg = maxFrames - 1; + + (function loop() { + if (frameNumber >= maxFrames) return; + Dygraph.requestAnimFrame.call(window, function() { + // Determine which frame to draw based on the delay so far. Will skip + // frames if necessary. + var currentTime = new Date().getTime(); + var delayInMillis = currentTime - startTime; + previousFrameNumber = frameNumber; + frameNumber = Math.floor(delayInMillis / framePeriodInMillis); + var frameDelta = frameNumber - previousFrameNumber; + // If we predict that the subsequent repeatFn call will overshoot our + // total frame target, so our last call will cause a stutter, then jump to + // the last call immediately. If we're going to cause a stutter, better + // to do it faster than slower. + var predictOvershootStutter = (frameNumber + frameDelta) > maxFrameArg; + if (predictOvershootStutter || (frameNumber >= maxFrameArg)) { + repeatFn(maxFrameArg); // Ensure final call with maxFrameArg. + cleanupFn(); + } else { + if (frameDelta !== 0) { // Don't call repeatFn with duplicate frames. + repeatFn(frameNumber); + } + loop(); + } + }); + })(); +}; + +// A whitelist of options that do not change pixel positions. +var pixelSafeOptions = { + 'annotationClickHandler': true, + 'annotationDblClickHandler': true, + 'annotationMouseOutHandler': true, + 'annotationMouseOverHandler': true, + 'axisLabelColor': true, + 'axisLineColor': true, + 'axisLineWidth': true, + 'clickCallback': true, + 'drawCallback': true, + 'drawHighlightPointCallback': true, + 'drawPoints': true, + 'drawPointCallback': true, + 'drawXGrid': true, + 'drawYGrid': true, + 'fillAlpha': true, + 'gridLineColor': true, + 'gridLineWidth': true, + 'hideOverlayOnMouseOut': true, + 'highlightCallback': true, + 'highlightCircleSize': true, + 'interactionModel': true, + 'isZoomedIgnoreProgrammaticZoom': true, + 'labelsDiv': true, + 'labelsDivStyles': true, + 'labelsDivWidth': true, + 'labelsKMB': true, + 'labelsKMG2': true, + 'labelsSeparateLines': true, + 'labelsShowZeroValues': true, + 'legend': true, + 'panEdgeFraction': true, + 'pixelsPerYLabel': true, + 'pointClickCallback': true, + 'pointSize': true, + 'rangeSelectorPlotFillColor': true, + 'rangeSelectorPlotStrokeColor': true, + 'showLabelsOnHighlight': true, + 'showRoller': true, + 'strokeWidth': true, + 'underlayCallback': true, + 'unhighlightCallback': true, + 'zoomCallback': true +}; + +/** + * This function will scan the option list and determine if they + * require us to recalculate the pixel positions of each point. + * TODO: move this into dygraph-options.js + * @param {!Array.} 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) { + // Assume that we do not require new points. + // This will change to true if we actually do need new points. + + // Create a dictionary of series names for faster lookup. + // If there are no labels, then the dictionary stays empty. + var seriesNamesDictionary = { }; + if (labels) { + for (var i = 1; i < labels.length; i++) { + seriesNamesDictionary[labels[i]] = true; + } + } + + // Scan through a flat (i.e. non-nested) object of options. + // Returns true/false depending on whether new points are needed. + var scanFlatOptions = function(options) { + for (var property in options) { + if (options.hasOwnProperty(property) && + !pixelSafeOptions[property]) { + return true; + } + } + return false; + }; + + // Iterate through the list of updated options. + for (var property in attrs) { + if (!attrs.hasOwnProperty(property)) continue; + + // Find out of this field is actually a series specific options list. + if (property == 'highlightSeriesOpts' || + (seriesNamesDictionary[property] && !attrs.series)) { + // This property value is a list of options for this series. + if (scanFlatOptions(attrs[property])) return true; + } else if (property == 'series' || property == 'axes') { + // This is twice-nested options list. + var perSeries = attrs[property]; + for (var series in perSeries) { + if (perSeries.hasOwnProperty(series) && + scanFlatOptions(perSeries[series])) { + return true; + } + } + } else { + // If this was not a series specific option list, check if it's a pixel + // changing property. + if (!pixelSafeOptions[property]) return true; + } + } + + return false; +}; + +Dygraph.Circles = { + DEFAULT : function(g, name, ctx, canvasx, canvasy, color, radius) { + ctx.beginPath(); + ctx.fillStyle = color; + ctx.arc(canvasx, canvasy, radius, 0, 2 * Math.PI, false); + ctx.fill(); + } + // For more shapes, include extras/shapes.js +}; + +/** + * To create a "drag" interaction, you typically register a mousedown event + * handler on the element where the drag begins. In that handler, you register a + * mouseup handler on the window to determine when the mouse is released, + * wherever that release happens. This works well, except when the user releases + * the mouse over an off-domain iframe. In that case, the mouseup event is + * handled by the iframe and never bubbles up to the window handler. + * + * To deal with this issue, we cover iframes with high z-index divs to make sure + * they don't capture mouseup. + * + * Usage: + * element.addEventListener('mousedown', function() { + * var tarper = new Dygraph.IFrameTarp(); + * tarper.cover(); + * var mouseUpHandler = function() { + * ... + * window.removeEventListener(mouseUpHandler); + * tarper.uncover(); + * }; + * window.addEventListener('mouseup', mouseUpHandler); + * }; + * + * @constructor + */ +Dygraph.IFrameTarp = function() { + /** @type {Array.} */ + this.tarps = []; +}; + +/** + * Find all the iframes in the document and cover them with high z-index + * transparent divs. + */ +Dygraph.IFrameTarp.prototype.cover = function() { + var iframes = document.getElementsByTagName("iframe"); + for (var i = 0; i < iframes.length; i++) { + var iframe = iframes[i]; + var pos = Dygraph.findPos(iframe), + x = pos.x, + y = pos.y, + width = iframe.offsetWidth, + height = iframe.offsetHeight; + + var div = document.createElement("div"); + div.style.position = "absolute"; + div.style.left = x + 'px'; + div.style.top = y + 'px'; + div.style.width = width + 'px'; + div.style.height = height + 'px'; + div.style.zIndex = 999; + document.body.appendChild(div); + this.tarps.push(div); + } +}; + +/** + * Remove all the iframe covers. You should call this in a mouseup handler. + */ +Dygraph.IFrameTarp.prototype.uncover = function() { + for (var i = 0; i < this.tarps.length; i++) { + this.tarps[i].parentNode.removeChild(this.tarps[i]); + } + this.tarps = []; +}; + +/** + * Determine whether |data| is delimited by CR, CRLF, LF, LFCR. + * @param {string} data + * @return {?string} the delimiter that was detected (or null on failure). + */ +Dygraph.detectLineDelimiter = function(data) { + for (var i = 0; i < data.length; i++) { + var code = data.charAt(i); + if (code === '\r') { + // Might actually be "\r\n". + if (((i + 1) < data.length) && (data.charAt(i + 1) === '\n')) { + return '\r\n'; + } + return code; + } + if (code === '\n') { + // Might actually be "\n\r". + if (((i + 1) < data.length) && (data.charAt(i + 1) === '\r')) { + return '\n\r'; + } + return code; + } + } + + return null; +}; + +/** + * Is one node contained by another? + * @param {Node} containee The contained node. + * @param {Node} container The container node. + * @return {boolean} Whether containee is inside (or equal to) container. + * @private + */ +Dygraph.isNodeContainedBy = function(containee, container) { + if (container === null || containee === null) { + return false; + } + var containeeNode = /** @type {Node} */ (containee); + while (containeeNode && containeeNode !== container) { + containeeNode = containeeNode.parentNode; + } + return (containeeNode === container); +}; + + +// 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} */ +Dygraph.pow = function(base, exp) { + if (exp < 0) { + return 1.0 / Math.pow(base, -exp); + } + return Math.pow(base, exp); +}; + +var RGBA_RE = /^rgba?\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})(?:,\s*([01](?:\.\d+)?))?\)$/; + +/** + * Helper for Dygraph.toRGB_ which parses strings of the form: + * rgb(123, 45, 67) + * rgba(123, 45, 67, 0.5) + * @return parsed {r,g,b,a?} tuple or null. + */ +function parseRGBA(rgbStr) { + var bits = RGBA_RE.exec(rgbStr); + if (!bits) return null; + var r = parseInt(bits[1], 10), + g = parseInt(bits[2], 10), + b = parseInt(bits[3], 10); + if (bits[4]) { + return {r: r, g: g, b: b, a: parseFloat(bits[4])}; + } else { + return {r: r, g: g, b: b}; + } +} + +/** + * Converts any valid CSS color (hex, rgb(), named color) to an RGB tuple. + * + * @param {!string} colorStr Any valid CSS color string. + * @return {{r:number,g:number,b:number,a:number?}} Parsed RGB tuple. + * @private + */ +Dygraph.toRGB_ = function(colorStr) { + // Strategy: First try to parse colorStr directly. This is fast & avoids DOM + // manipulation. If that fails (e.g. for named colors like 'red'), then + // create a hidden DOM element and parse its computed color. + var rgb = parseRGBA(colorStr); + if (rgb) return rgb; + + var div = document.createElement('div'); + div.style.backgroundColor = colorStr; + div.style.visibility = 'hidden'; + document.body.appendChild(div); + var rgbStr; + if (window.getComputedStyle) { + rgbStr = window.getComputedStyle(div, null).backgroundColor; + } else { + // IE8 + rgbStr = div.currentStyle.backgroundColor; + } + document.body.removeChild(div); + return parseRGBA(rgbStr); +}; + +/** + * Checks whether the browser supports the <canvas> tag. + * @param {HTMLCanvasElement=} opt_canvasElement Pass a canvas element as an + * optimization if you have one. + * @return {boolean} Whether the browser supports canvas. + */ +Dygraph.isCanvasSupported = function(opt_canvasElement) { + var canvas; + try { + canvas = opt_canvasElement || document.createElement("canvas"); + canvas.getContext("2d"); + } + catch (e) { + var ie = navigator.appVersion.match(/MSIE (\d\.\d)/); + var opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1); + if ((!ie) || (ie[1] < 6) || (opera)) + return false; + return true; + } + return true; +}; + +/** + * Parses the value as a floating point number. This is like the parseFloat() + * built-in, but with a few differences: + * - the empty string is parsed as null, rather than NaN. + * - if the string cannot be parsed at all, an error is logged. + * If the string can't be parsed, this method returns null. + * @param {string} x The string to be parsed + * @param {number=} opt_line_no The line number from which the string comes. + * @param {string=} opt_line The text of the line from which the string comes. + */ +Dygraph.parseFloat_ = function(x, opt_line_no, opt_line) { + var val = parseFloat(x); + if (!isNaN(val)) return val; + + // Try to figure out what happeend. + // If the value is the empty string, parse it as null. + if (/^ *$/.test(x)) return null; + + // If it was actually "NaN", return it as NaN. + if (/^ *nan *$/i.test(x)) return NaN; + + // Looks like a parsing error. + var msg = "Unable to parse '" + x + "' as a number"; + if (opt_line !== undefined && opt_line_no !== undefined) { + msg += " on line " + (1+(opt_line_no||0)) + " ('" + opt_line + "') of CSV."; + } + console.error(msg); + + return null; +}; + +})(); +/** + * @license + * Copyright 2011 Dan Vanderkam (danvdk@gmail.com) + * MIT-licensed (http://opensource.org/licenses/MIT) + */ + +/** + * @fileoverview A wrapper around the Dygraph class which implements the + * interface for a GViz (aka Google Visualization API) visualization. + * It is designed to be a drop-in replacement for Google's AnnotatedTimeline, + * so the documentation at + * http://code.google.com/apis/chart/interactive/docs/gallery/annotatedtimeline.html + * translates over directly. + * + * For a full demo, see: + * - http://dygraphs.com/tests/gviz.html + * - http://dygraphs.com/tests/annotation-gviz.html + */ + +(function() { +/*global Dygraph:false */ +"use strict"; + +/** + * A wrapper around Dygraph that implements the gviz API. + * @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 + // date_graph object? + this.container.innerHTML = ''; + if (typeof(this.date_graph) != 'undefined') { + this.date_graph.destroy(); + } + + this.date_graph = new Dygraph(this.container, data, options); +}; + +/** + * Google charts compatible setSelection + * Only row selection is supported, all points in the row will be highlighted + * @param {Array.<{row:number}>} selection_array array of the selected cells + * @public + */ +Dygraph.GVizChart.prototype.setSelection = function(selection_array) { + var row = false; + if (selection_array.length) { + row = selection_array[0].row; + } + this.date_graph.setSelection(row); +}; + +/** + * Google charts compatible getSelection implementation + * @return {Array.<{row:number,column:number}>} array of the selected cells + * @public + */ +Dygraph.GVizChart.prototype.getSelection = function() { + var selection = []; + + var row = this.date_graph.getSelection(); + + if (row < 0) return selection; + + var points = this.date_graph.layout_.points; + for (var setIdx = 0; setIdx < points.length; ++setIdx) { + selection.push({row: row, column: setIdx + 1}); + } + + return selection; +}; + +})(); +/** + * @license + * Copyright 2011 Robert Konigsberg (konigsberg@google.com) + * MIT-licensed (http://opensource.org/licenses/MIT) + */ + +/** + * @fileoverview The default interaction model for Dygraphs. This is kept out + * of dygraph.js for better navigability. + * @author Robert Konigsberg (konigsberg@google.com) + */ + +(function() { +/*global Dygraph:false */ +"use strict"; + +/** + * You can drag this many pixels past the edge of the chart and still have it + * be considered a zoom. This makes it easier to zoom to the exact edge of the + * chart, a fairly common operation. + */ +var DRAG_EDGE_MARGIN = 100; + +/** + * A collection of functions to facilitate build custom interaction models. + * @class + */ +Dygraph.Interaction = {}; + +/** + * Checks whether the beginning & ending of an event were close enough that it + * should be considered a click. If it should, dispatch appropriate events. + * Returns true if the event was treated as a click. + * + * @param {Event} event + * @param {Dygraph} g + * @param {Object} context + */ +Dygraph.Interaction.maybeTreatMouseOpAsClick = function(event, g, context) { + context.dragEndX = Dygraph.dragGetX_(event, context); + context.dragEndY = Dygraph.dragGetY_(event, context); + var regionWidth = Math.abs(context.dragEndX - context.dragStartX); + var regionHeight = Math.abs(context.dragEndY - context.dragStartY); + + if (regionWidth < 2 && regionHeight < 2 && + g.lastx_ !== undefined && g.lastx_ != -1) { + Dygraph.Interaction.treatMouseOpAsClick(g, event, context); + } + + context.regionWidth = regionWidth; + context.regionHeight = regionHeight; +}; + +/** + * Called in response to an interaction model operation that + * should start the default panning behavior. + * + * It's used in the default callback for "mousedown" operations. + * 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. + */ +Dygraph.Interaction.startPan = function(event, g, context) { + var i, axis; + context.isPanning = true; + var xRange = g.xAxisRange(); + + if (g.getOptionForAxis("logscale", "x")) { + context.initialLeftmostDate = Dygraph.log10(xRange[0]); + context.dateRange = Dygraph.log10(xRange[1]) - Dygraph.log10(xRange[0]); + } else { + context.initialLeftmostDate = xRange[0]; + context.dateRange = xRange[1] - xRange[0]; + } + context.xUnitsPerPixel = context.dateRange / (g.plotter_.area.w - 1); + + if (g.getNumericOption("panEdgeFraction")) { + var maxXPixelsToDraw = g.width_ * g.getNumericOption("panEdgeFraction"); + var xExtremes = g.xAxisExtremes(); // I REALLY WANT TO CALL THIS xTremes! + + var boundedLeftX = g.toDomXCoord(xExtremes[0]) - maxXPixelsToDraw; + var boundedRightX = g.toDomXCoord(xExtremes[1]) + maxXPixelsToDraw; + + var boundedLeftDate = g.toDataXCoord(boundedLeftX); + var boundedRightDate = g.toDataXCoord(boundedRightX); + context.boundedDates = [boundedLeftDate, boundedRightDate]; + + var boundedValues = []; + var maxYPixelsToDraw = g.height_ * g.getNumericOption("panEdgeFraction"); + + for (i = 0; i < g.axes_.length; i++) { + axis = g.axes_[i]; + var yExtremes = axis.extremeRange; + + var boundedTopY = g.toDomYCoord(yExtremes[0], i) + maxYPixelsToDraw; + var boundedBottomY = g.toDomYCoord(yExtremes[1], i) - maxYPixelsToDraw; + + var boundedTopValue = g.toDataYCoord(boundedTopY, i); + var boundedBottomValue = g.toDataYCoord(boundedBottomY, i); + + boundedValues[i] = [boundedTopValue, boundedBottomValue]; + } + context.boundedValues = boundedValues; + } + + // Record the range of each y-axis at the start of the drag. + // If any axis has a valueRange or valueWindow, then we want a 2D pan. + // We can't store data directly in g.axes_, because it does not belong to us + // and could change out from under us during a pan (say if there's a data + // update). + context.is2DPan = false; + context.axes = []; + for (i = 0; i < g.axes_.length; i++) { + axis = g.axes_[i]; + var axis_data = {}; + var yRange = g.yAxisRange(i); + // TODO(konigsberg): These values should be in |context|. + // In log scale, initialTopValue, dragValueRange and unitsPerPixel are log scale. + var logscale = g.attributes_.getForAxis("logscale", i); + if (logscale) { + axis_data.initialTopValue = Dygraph.log10(yRange[1]); + axis_data.dragValueRange = Dygraph.log10(yRange[1]) - Dygraph.log10(yRange[0]); + } else { + axis_data.initialTopValue = yRange[1]; + axis_data.dragValueRange = yRange[1] - yRange[0]; + } + axis_data.unitsPerPixel = axis_data.dragValueRange / (g.plotter_.area.h - 1); + context.axes.push(axis_data); + + // While calculating axes, set 2dpan. + if (axis.valueWindow || axis.valueRange) context.is2DPan = true; + } +}; + +/** + * Called in response to an interaction model operation that + * responds to an event that pans the view. + * + * It's used in the default callback for "mousemove" operations. + * 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. + */ +Dygraph.Interaction.movePan = function(event, g, context) { + context.dragEndX = Dygraph.dragGetX_(event, context); + context.dragEndY = Dygraph.dragGetY_(event, context); + + var minDate = context.initialLeftmostDate - + (context.dragEndX - context.dragStartX) * context.xUnitsPerPixel; + if (context.boundedDates) { + minDate = Math.max(minDate, context.boundedDates[0]); + } + var maxDate = minDate + context.dateRange; + if (context.boundedDates) { + if (maxDate > context.boundedDates[1]) { + // Adjust minDate, and recompute maxDate. + minDate = minDate - (maxDate - context.boundedDates[1]); + maxDate = minDate + context.dateRange; + } + } + + if (g.getOptionForAxis("logscale", "x")) { + g.dateWindow_ = [ Math.pow(Dygraph.LOG_SCALE, minDate), + Math.pow(Dygraph.LOG_SCALE, maxDate) ]; + } else { + g.dateWindow_ = [minDate, maxDate]; + } + + // y-axis scaling is automatic unless this is a full 2D pan. + if (context.is2DPan) { + + var pixelsDragged = context.dragEndY - context.dragStartY; + + // Adjust each axis appropriately. + for (var i = 0; i < g.axes_.length; i++) { + var axis = g.axes_[i]; + var axis_data = context.axes[i]; + var unitsDragged = pixelsDragged * axis_data.unitsPerPixel; + + var boundedValue = context.boundedValues ? context.boundedValues[i] : null; + + // In log scale, maxValue and minValue are the logs of those values. + var maxValue = axis_data.initialTopValue + unitsDragged; + if (boundedValue) { + maxValue = Math.min(maxValue, boundedValue[1]); + } + var minValue = maxValue - axis_data.dragValueRange; + if (boundedValue) { + if (minValue < boundedValue[0]) { + // Adjust maxValue, and recompute minValue. + maxValue = maxValue - (minValue - boundedValue[0]); + minValue = maxValue - axis_data.dragValueRange; + } + } + if (g.attributes_.getForAxis("logscale", i)) { + axis.valueWindow = [ Math.pow(Dygraph.LOG_SCALE, minValue), + Math.pow(Dygraph.LOG_SCALE, maxValue) ]; + } else { + axis.valueWindow = [ minValue, maxValue ]; + } + } + } + + g.drawGraph_(false); +}; + +/** + * Called in response to an interaction model operation that + * responds to an event that ends panning. + * + * It's used in the default callback for "mouseup" operations. + * 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. + */ +Dygraph.Interaction.endPan = Dygraph.Interaction.maybeTreatMouseOpAsClick; + +/** + * Called in response to an interaction model operation that + * responds to an event that starts zooming. + * + * It's used in the default callback for "mousedown" operations. + * 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. + */ +Dygraph.Interaction.startZoom = function(event, g, context) { + context.isZooming = true; + context.zoomMoved = false; +}; + +/** + * Called in response to an interaction model operation that + * responds to an event that defines zoom boundaries. + * + * It's used in the default callback for "mousemove" operations. + * 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. + */ +Dygraph.Interaction.moveZoom = function(event, g, context) { + context.zoomMoved = true; + context.dragEndX = Dygraph.dragGetX_(event, context); + context.dragEndY = Dygraph.dragGetY_(event, context); + + var xDelta = Math.abs(context.dragStartX - context.dragEndX); + var yDelta = Math.abs(context.dragStartY - context.dragEndY); + + // drag direction threshold for y axis is twice as large as x axis + context.dragDirection = (xDelta < yDelta / 2) ? Dygraph.VERTICAL : Dygraph.HORIZONTAL; + + g.drawZoomRect_( + context.dragDirection, + context.dragStartX, + context.dragEndX, + context.dragStartY, + context.dragEndY, + context.prevDragDirection, + context.prevEndX, + context.prevEndY); + + context.prevEndX = context.dragEndX; + context.prevEndY = context.dragEndY; + context.prevDragDirection = context.dragDirection; +}; + +/** + * TODO(danvk): move this logic into dygraph.js + * @param {Dygraph} g + * @param {Event} event + * @param {Object} context + */ +Dygraph.Interaction.treatMouseOpAsClick = function(g, event, context) { + var clickCallback = g.getFunctionOption('clickCallback'); + var pointClickCallback = g.getFunctionOption('pointClickCallback'); + + var selectedPoint = null; + + // Find out if the click occurs on a point. + var closestIdx = -1; + var closestDistance = Number.MAX_VALUE; + + // check if the click was on a particular point. + for (var i = 0; i < g.selPoints_.length; i++) { + var p = g.selPoints_[i]; + var distance = Math.pow(p.canvasx - context.dragEndX, 2) + + Math.pow(p.canvasy - context.dragEndY, 2); + if (!isNaN(distance) && + (closestIdx == -1 || distance < closestDistance)) { + closestDistance = distance; + closestIdx = i; + } + } + + // Allow any click within two pixels of the dot. + var radius = g.getNumericOption('highlightCircleSize') + 2; + if (closestDistance <= radius * radius) { + selectedPoint = g.selPoints_[closestIdx]; + } + + if (selectedPoint) { + var e = { + cancelable: true, + point: selectedPoint, + canvasx: context.dragEndX, + canvasy: context.dragEndY + }; + var defaultPrevented = g.cascadeEvents_('pointClick', e); + if (defaultPrevented) { + // Note: this also prevents click / clickCallback from firing. + return; + } + if (pointClickCallback) { + pointClickCallback.call(g, event, selectedPoint); + } + } + + var e = { + cancelable: true, + xval: g.lastx_, // closest point by x value + pts: g.selPoints_, + canvasx: context.dragEndX, + canvasy: context.dragEndY + }; + if (!g.cascadeEvents_('click', e)) { + if (clickCallback) { + // TODO(danvk): pass along more info about the points, e.g. 'x' + clickCallback.call(g, event, g.lastx_, g.selPoints_); + } + } +}; + +/** + * Called in response to an interaction model operation that + * responds to an event that performs a zoom based on previously defined + * bounds.. + * + * It's used in the default callback for "mouseup" operations. + * 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. + */ +Dygraph.Interaction.endZoom = function(event, g, context) { + g.clearZoomRect_(); + context.isZooming = false; + Dygraph.Interaction.maybeTreatMouseOpAsClick(event, g, context); + + // The zoom rectangle is visibly clipped to the plot area, so its behavior + // should be as well. + // See http://code.google.com/p/dygraphs/issues/detail?id=280 + var plotArea = g.getArea(); + if (context.regionWidth >= 10 && + context.dragDirection == Dygraph.HORIZONTAL) { + var left = Math.min(context.dragStartX, context.dragEndX), + right = Math.max(context.dragStartX, context.dragEndX); + left = Math.max(left, plotArea.x); + right = Math.min(right, plotArea.x + plotArea.w); + if (left < right) { + g.doZoomX_(left, right); + } + context.cancelNextDblclick = true; + } else if (context.regionHeight >= 10 && + context.dragDirection == Dygraph.VERTICAL) { + var top = Math.min(context.dragStartY, context.dragEndY), + bottom = Math.max(context.dragStartY, context.dragEndY); + top = Math.max(top, plotArea.y); + bottom = Math.min(bottom, plotArea.y + plotArea.h); + if (top < bottom) { + g.doZoomY_(top, bottom); + } + context.cancelNextDblclick = true; + } + context.dragStartX = null; + context.dragStartY = null; +}; + +/** + * @private + */ +Dygraph.Interaction.startTouch = function(event, g, context) { + event.preventDefault(); // touch browsers are all nice. + if (event.touches.length > 1) { + // If the user ever puts two fingers down, it's not a double tap. + context.startTimeForDoubleTapMs = null; + } + + var touches = []; + for (var i = 0; i < event.touches.length; i++) { + var t = event.touches[i]; + // we dispense with 'dragGetX_' because all touchBrowsers support pageX + touches.push({ + pageX: t.pageX, + pageY: t.pageY, + dataX: g.toDataXCoord(t.pageX), + dataY: g.toDataYCoord(t.pageY) + // identifier: t.identifier + }); + } + context.initialTouches = touches; + + if (touches.length == 1) { + // This is just a swipe. + context.initialPinchCenter = touches[0]; + context.touchDirections = { x: true, y: true }; + } else if (touches.length >= 2) { + // It's become a pinch! + // In case there are 3+ touches, we ignore all but the "first" two. + + // only screen coordinates can be averaged (data coords could be log scale). + context.initialPinchCenter = { + pageX: 0.5 * (touches[0].pageX + touches[1].pageX), + pageY: 0.5 * (touches[0].pageY + touches[1].pageY), + + // TODO(danvk): remove + dataX: 0.5 * (touches[0].dataX + touches[1].dataX), + dataY: 0.5 * (touches[0].dataY + touches[1].dataY) + }; + + // Make pinches in a 45-degree swath around either axis 1-dimensional zooms. + var initialAngle = 180 / Math.PI * Math.atan2( + context.initialPinchCenter.pageY - touches[0].pageY, + touches[0].pageX - context.initialPinchCenter.pageX); + + // use symmetry to get it into the first quadrant. + initialAngle = Math.abs(initialAngle); + if (initialAngle > 90) initialAngle = 90 - initialAngle; + + context.touchDirections = { + x: (initialAngle < (90 - 45/2)), + y: (initialAngle > 45/2) + }; + } + + // save the full x & y ranges. + context.initialRange = { + x: g.xAxisRange(), + y: g.yAxisRange() + }; +}; + +/** + * @private + */ +Dygraph.Interaction.moveTouch = function(event, g, context) { + // If the tap moves, then it's definitely not part of a double-tap. + context.startTimeForDoubleTapMs = null; + + var i, touches = []; + for (i = 0; i < event.touches.length; i++) { + var t = event.touches[i]; + touches.push({ + pageX: t.pageX, + pageY: t.pageY + }); + } + var initialTouches = context.initialTouches; + + var c_now; + + // old and new centers. + var c_init = context.initialPinchCenter; + if (touches.length == 1) { + c_now = touches[0]; + } else { + c_now = { + pageX: 0.5 * (touches[0].pageX + touches[1].pageX), + pageY: 0.5 * (touches[0].pageY + touches[1].pageY) + }; + } + + // this is the "swipe" component + // we toss it out for now, but could use it in the future. + var swipe = { + pageX: c_now.pageX - c_init.pageX, + pageY: c_now.pageY - c_init.pageY + }; + var dataWidth = context.initialRange.x[1] - context.initialRange.x[0]; + var dataHeight = context.initialRange.y[0] - context.initialRange.y[1]; + swipe.dataX = (swipe.pageX / g.plotter_.area.w) * dataWidth; + swipe.dataY = (swipe.pageY / g.plotter_.area.h) * dataHeight; + var xScale, yScale; + + // The residual bits are usually split into scale & rotate bits, but we split + // them into x-scale and y-scale bits. + if (touches.length == 1) { + xScale = 1.0; + yScale = 1.0; + } else if (touches.length >= 2) { + var initHalfWidth = (initialTouches[1].pageX - c_init.pageX); + xScale = (touches[1].pageX - c_now.pageX) / initHalfWidth; + + var initHalfHeight = (initialTouches[1].pageY - c_init.pageY); + yScale = (touches[1].pageY - c_now.pageY) / initHalfHeight; + } + + // Clip scaling to [1/8, 8] to prevent too much blowup. + xScale = Math.min(8, Math.max(0.125, xScale)); + yScale = Math.min(8, Math.max(0.125, yScale)); + + var didZoom = false; + if (context.touchDirections.x) { + g.dateWindow_ = [ + c_init.dataX - swipe.dataX + (context.initialRange.x[0] - c_init.dataX) / xScale, + c_init.dataX - swipe.dataX + (context.initialRange.x[1] - c_init.dataX) / xScale + ]; + didZoom = true; + } + + if (context.touchDirections.y) { + for (i = 0; i < 1 /*g.axes_.length*/; i++) { + var axis = g.axes_[i]; + var logscale = g.attributes_.getForAxis("logscale", i); + if (logscale) { + // TODO(danvk): implement + } else { + axis.valueWindow = [ + c_init.dataY - swipe.dataY + (context.initialRange.y[0] - c_init.dataY) / yScale, + c_init.dataY - swipe.dataY + (context.initialRange.y[1] - c_init.dataY) / yScale + ]; + didZoom = true; + } + } + } + + g.drawGraph_(false); + + // We only call zoomCallback on zooms, not pans, to mirror desktop behavior. + if (didZoom && touches.length > 1 && g.getFunctionOption('zoomCallback')) { + var viewWindow = g.xAxisRange(); + g.getFunctionOption("zoomCallback").call(g, viewWindow[0], viewWindow[1], g.yAxisRanges()); + } +}; + +/** + * @private + */ +Dygraph.Interaction.endTouch = function(event, g, context) { + if (event.touches.length !== 0) { + // this is effectively a "reset" + Dygraph.Interaction.startTouch(event, g, context); + } else if (event.changedTouches.length == 1) { + // Could be part of a "double tap" + // The heuristic here is that it's a double-tap if the two touchend events + // occur within 500ms and within a 50x50 pixel box. + var now = new Date().getTime(); + var t = event.changedTouches[0]; + if (context.startTimeForDoubleTapMs && + now - context.startTimeForDoubleTapMs < 500 && + context.doubleTapX && Math.abs(context.doubleTapX - t.screenX) < 50 && + context.doubleTapY && Math.abs(context.doubleTapY - t.screenY) < 50) { + g.resetZoom(); + } else { + context.startTimeForDoubleTapMs = now; + context.doubleTapX = t.screenX; + context.doubleTapY = t.screenY; + } + } +}; + +// Determine the distance from x to [left, right]. +var distanceFromInterval = function(x, left, right) { + if (x < left) { + return left - x; + } else if (x > right) { + return x - right; + } else { + return 0; + } +}; + +/** + * Returns the number of pixels by which the event happens from the nearest + * edge of the chart. For events in the interior of the chart, this returns zero. + */ +var distanceFromChart = function(event, g) { + var chartPos = Dygraph.findPos(g.canvas_); + var box = { + left: chartPos.x, + right: chartPos.x + g.canvas_.offsetWidth, + top: chartPos.y, + bottom: chartPos.y + g.canvas_.offsetHeight + }; + + var pt = { + x: Dygraph.pageX(event), + y: Dygraph.pageY(event) + }; + + var dx = distanceFromInterval(pt.x, box.left, box.right), + dy = distanceFromInterval(pt.y, box.top, box.bottom); + return Math.max(dx, dy); +}; + +/** + * Default interation model for dygraphs. You can refer to specific elements of + * this when constructing your own interaction model, e.g.: + * g.updateOptions( { + * interactionModel: { + * mousedown: Dygraph.defaultInteractionModel.mousedown + * } + * } ); + */ +Dygraph.Interaction.defaultModel = { + // Track the beginning of drag events + mousedown: function(event, g, context) { + // Right-click should not initiate a zoom. + if (event.button && event.button == 2) return; + + context.initializeMouseDown(event, g, context); + + if (event.altKey || event.shiftKey) { + Dygraph.startPan(event, g, context); + } else { + Dygraph.startZoom(event, g, context); + } + + // Note: we register mousemove/mouseup on document to allow some leeway for + // events to move outside of the chart. Interaction model events get + // registered on the canvas, which is too small to allow this. + var mousemove = function(event) { + if (context.isZooming) { + // When the mouse moves >200px from the chart edge, cancel the zoom. + var d = distanceFromChart(event, g); + if (d < DRAG_EDGE_MARGIN) { + Dygraph.moveZoom(event, g, context); + } else { + if (context.dragEndX !== null) { + context.dragEndX = null; + context.dragEndY = null; + g.clearZoomRect_(); + } + } + } else if (context.isPanning) { + Dygraph.movePan(event, g, context); + } + }; + var mouseup = function(event) { + if (context.isZooming) { + if (context.dragEndX !== null) { + Dygraph.endZoom(event, g, context); + } else { + Dygraph.Interaction.maybeTreatMouseOpAsClick(event, g, context); + } + } else if (context.isPanning) { + Dygraph.endPan(event, g, context); + } + + Dygraph.removeEvent(document, 'mousemove', mousemove); + Dygraph.removeEvent(document, 'mouseup', mouseup); + context.destroy(); + }; + + g.addAndTrackEvent(document, 'mousemove', mousemove); + g.addAndTrackEvent(document, 'mouseup', mouseup); + }, + willDestroyContextMyself: true, + + touchstart: function(event, g, context) { + Dygraph.Interaction.startTouch(event, g, context); + }, + touchmove: function(event, g, context) { + Dygraph.Interaction.moveTouch(event, g, context); + }, + touchend: function(event, g, context) { + Dygraph.Interaction.endTouch(event, g, context); + }, + + // Disable zooming out if panning. + dblclick: function(event, g, context) { + if (context.cancelNextDblclick) { + context.cancelNextDblclick = false; + return; + } + + // Give plugins a chance to grab this event. + var e = { + canvasx: context.dragEndX, + canvasy: context.dragEndY + }; + if (g.cascadeEvents_('dblclick', e)) { + return; + } + + if (event.altKey || event.shiftKey) { + return; + } + g.resetZoom(); + } +}; + +Dygraph.DEFAULT_ATTRS.interactionModel = Dygraph.Interaction.defaultModel; + +// old ways of accessing these methods/properties +Dygraph.defaultInteractionModel = Dygraph.Interaction.defaultModel; +Dygraph.endZoom = Dygraph.Interaction.endZoom; +Dygraph.moveZoom = Dygraph.Interaction.moveZoom; +Dygraph.startZoom = Dygraph.Interaction.startZoom; +Dygraph.endPan = Dygraph.Interaction.endPan; +Dygraph.movePan = Dygraph.Interaction.movePan; +Dygraph.startPan = Dygraph.Interaction.startPan; + +Dygraph.Interaction.nonInteractiveModel_ = { + mousedown: function(event, g, context) { + context.initializeMouseDown(event, g, context); + }, + mouseup: Dygraph.Interaction.maybeTreatMouseOpAsClick +}; + +// Default interaction model when using the range selector. +Dygraph.Interaction.dragIsPanInteractionModel = { + mousedown: function(event, g, context) { + context.initializeMouseDown(event, g, context); + Dygraph.startPan(event, g, context); + }, + mousemove: function(event, g, context) { + if (context.isPanning) { + Dygraph.movePan(event, g, context); + } + }, + mouseup: function(event, g, context) { + if (context.isPanning) { + Dygraph.endPan(event, g, context); + } + } +}; + +})(); +/** + * @license + * Copyright 2011 Dan Vanderkam (danvdk@gmail.com) + * MIT-licensed (http://opensource.org/licenses/MIT) + */ + +/** + * @fileoverview Description of this file. + * @author danvk@google.com (Dan Vanderkam) + * + * A ticker is a function with the following interface: + * + * function(a, b, pixels, options_view, dygraph, forced_values); + * -> [ { v: tick1_v, label: tick1_label[, label_v: label_v1] }, + * { v: tick2_v, label: tick2_label[, label_v: label_v2] }, + * ... + * ] + * + * The returned value is called a "tick list". + * + * Arguments + * --------- + * + * [a, b] is the range of the axis for which ticks are being generated. For a + * numeric axis, these will simply be numbers. For a date axis, these will be + * millis since epoch (convertable to Date objects using "new Date(a)" and "new + * Date(b)"). + * + * opts provides access to chart- and axis-specific options. It can be used to + * access number/date formatting code/options, check for a log scale, etc. + * + * pixels is the length of the axis in pixels. opts('pixelsPerLabel') is the + * minimum amount of space to be allotted to each label. For instance, if + * pixels=400 and opts('pixelsPerLabel')=40 then the ticker should return + * between zero and ten (400/40) ticks. + * + * dygraph is the Dygraph object for which an axis is being constructed. + * + * forced_values is used for secondary y-axes. The tick positions are typically + * set by the primary y-axis, so the secondary y-axis has no choice in where to + * put these. It simply has to generate labels for these data values. + * + * Tick lists + * ---------- + * Typically a tick will have both a grid/tick line and a label at one end of + * that line (at the bottom for an x-axis, at left or right for the y-axis). + * + * A tick may be missing one of these two components: + * - If "label_v" is specified instead of "v", then there will be no tick or + * gridline, just a label. + * - Similarly, if "label" is not specified, then there will be a gridline + * without a label. + * + * This flexibility is useful in a few situations: + * - For log scales, some of the tick lines may be too close to all have labels. + * - For date scales where years are being displayed, it is desirable to display + * tick marks at the beginnings of years but labels (e.g. "2006") in the + * middle of the years. + */ + +/*jshint sub:true */ +/*global Dygraph:false */ +(function() { +"use strict"; + +/** @typedef {Array.<{v:number, label:string, label_v:(string|undefined)}>} */ +Dygraph.TickList = undefined; // the ' = undefined' keeps jshint happy. + +/** @typedef {function( + * number, + * number, + * number, + * function(string):*, + * Dygraph=, + * Array.= + * ): Dygraph.TickList} + */ +Dygraph.Ticker = undefined; // the ' = undefined' keeps jshint happy. + +/** @type {Dygraph.Ticker} */ +Dygraph.numericLinearTicks = function(a, b, pixels, opts, dygraph, vals) { + var nonLogscaleOpts = function(opt) { + if (opt === 'logscale') return false; + return opts(opt); + }; + return Dygraph.numericTicks(a, b, pixels, nonLogscaleOpts, dygraph, vals); +}; + +/** @type {Dygraph.Ticker} */ +Dygraph.numericTicks = function(a, b, pixels, opts, dygraph, vals) { + var pixels_per_tick = /** @type{number} */(opts('pixelsPerLabel')); + var ticks = []; + var i, j, tickV, nTicks; + if (vals) { + for (i = 0; i < vals.length; i++) { + ticks.push({v: vals[i]}); + } + } else { + // TODO(danvk): factor this log-scale block out into a separate function. + if (opts("logscale")) { + nTicks = Math.floor(pixels / pixels_per_tick); + var minIdx = Dygraph.binarySearch(a, Dygraph.PREFERRED_LOG_TICK_VALUES, 1); + var maxIdx = Dygraph.binarySearch(b, Dygraph.PREFERRED_LOG_TICK_VALUES, -1); + if (minIdx == -1) { + minIdx = 0; + } + if (maxIdx == -1) { + maxIdx = Dygraph.PREFERRED_LOG_TICK_VALUES.length - 1; + } + // Count the number of tick values would appear, if we can get at least + // nTicks / 4 accept them. + var lastDisplayed = null; + if (maxIdx - minIdx >= nTicks / 4) { + for (var idx = maxIdx; idx >= minIdx; idx--) { + var tickValue = Dygraph.PREFERRED_LOG_TICK_VALUES[idx]; + var pixel_coord = Math.log(tickValue / a) / Math.log(b / a) * pixels; + var tick = { v: tickValue }; + if (lastDisplayed === null) { + lastDisplayed = { + tickValue : tickValue, + pixel_coord : pixel_coord + }; + } else { + if (Math.abs(pixel_coord - lastDisplayed.pixel_coord) >= pixels_per_tick) { + lastDisplayed = { + tickValue : tickValue, + pixel_coord : pixel_coord + }; + } else { + tick.label = ""; + } + } + ticks.push(tick); + } + // Since we went in backwards order. + ticks.reverse(); + } + } + + // ticks.length won't be 0 if the log scale function finds values to insert. + if (ticks.length === 0) { + // Basic idea: + // Try labels every 1, 2, 5, 10, 20, 50, 100, etc. + // Calculate the resulting tick spacing (i.e. this.height_ / nTicks). + // The first spacing greater than pixelsPerYLabel is what we use. + // TODO(danvk): version that works on a log scale. + var kmg2 = opts("labelsKMG2"); + var mults, base; + if (kmg2) { + mults = [1, 2, 4, 8, 16, 32, 64, 128, 256]; + base = 16; + } else { + mults = [1, 2, 5, 10, 20, 50, 100]; + base = 10; + } + + // Get the maximum number of permitted ticks based on the + // graph's pixel size and pixels_per_tick setting. + var max_ticks = Math.ceil(pixels / pixels_per_tick); + + // Now calculate the data unit equivalent of this tick spacing. + // Use abs() since graphs may have a reversed Y axis. + var units_per_tick = Math.abs(b - a) / max_ticks; + + // Based on this, get a starting scale which is the largest + // integer power of the chosen base (10 or 16) that still remains + // below the requested pixels_per_tick spacing. + var base_power = Math.floor(Math.log(units_per_tick) / Math.log(base)); + var base_scale = Math.pow(base, base_power); + + // Now try multiples of the starting scale until we find one + // that results in tick marks spaced sufficiently far apart. + // The "mults" array should cover the range 1 .. base^2 to + // adjust for rounding and edge effects. + var scale, low_val, high_val, spacing; + for (j = 0; j < mults.length; j++) { + scale = base_scale * mults[j]; + low_val = Math.floor(a / scale) * scale; + high_val = Math.ceil(b / scale) * scale; + nTicks = Math.abs(high_val - low_val) / scale; + spacing = pixels / nTicks; + if (spacing > pixels_per_tick) break; + } + + // Construct the set of ticks. + // Allow reverse y-axis if it's explicitly requested. + if (low_val > high_val) scale *= -1; + for (i = 0; i <= nTicks; i++) { + tickV = low_val + i * scale; + ticks.push( {v: tickV} ); + } + } + } + + var formatter = /**@type{AxisLabelFormatter}*/(opts('axisLabelFormatter')); + + // Add labels to the ticks. + for (i = 0; i < ticks.length; i++) { + if (ticks[i].label !== undefined) continue; // Use current label. + // TODO(danvk): set granularity to something appropriate here. + ticks[i].label = formatter.call(dygraph, ticks[i].v, 0, opts, dygraph); + } + + return ticks; +}; + + +/** @type {Dygraph.Ticker} */ +Dygraph.dateTicker = function(a, b, pixels, opts, dygraph, vals) { + var chosen = Dygraph.pickDateTickGranularity(a, b, pixels, opts); + + if (chosen >= 0) { + return Dygraph.getDateAxis(a, b, chosen, opts, dygraph); + } else { + // this can happen if self.width_ is zero. + return []; + } +}; + +// Time granularity enumeration +// TODO(danvk): make this an @enum +Dygraph.SECONDLY = 0; +Dygraph.TWO_SECONDLY = 1; +Dygraph.FIVE_SECONDLY = 2; +Dygraph.TEN_SECONDLY = 3; +Dygraph.THIRTY_SECONDLY = 4; +Dygraph.MINUTELY = 5; +Dygraph.TWO_MINUTELY = 6; +Dygraph.FIVE_MINUTELY = 7; +Dygraph.TEN_MINUTELY = 8; +Dygraph.THIRTY_MINUTELY = 9; +Dygraph.HOURLY = 10; +Dygraph.TWO_HOURLY = 11; +Dygraph.SIX_HOURLY = 12; +Dygraph.DAILY = 13; +Dygraph.TWO_DAILY = 14; +Dygraph.WEEKLY = 15; +Dygraph.MONTHLY = 16; +Dygraph.QUARTERLY = 17; +Dygraph.BIANNUAL = 18; +Dygraph.ANNUAL = 19; +Dygraph.DECADAL = 20; +Dygraph.CENTENNIAL = 21; +Dygraph.NUM_GRANULARITIES = 22; + +// Date components enumeration (in the order of the arguments in Date) +// TODO: make this an @enum +Dygraph.DATEFIELD_Y = 0; +Dygraph.DATEFIELD_M = 1; +Dygraph.DATEFIELD_D = 2; +Dygraph.DATEFIELD_HH = 3; +Dygraph.DATEFIELD_MM = 4; +Dygraph.DATEFIELD_SS = 5; +Dygraph.DATEFIELD_MS = 6; +Dygraph.NUM_DATEFIELDS = 7; + + +/** + * The value of datefield will start at an even multiple of "step", i.e. + * if datefield=SS and step=5 then the first tick will be on a multiple of 5s. + * + * For granularities <= HOURLY, ticks are generated every `spacing` ms. + * + * At coarser granularities, ticks are generated by incrementing `datefield` by + * `step`. In this case, the `spacing` value is only used to estimate the + * number of ticks. It should roughly correspond to the spacing between + * adjacent ticks. + * + * @type {Array.<{datefield:number, step:number, spacing:number}>} + */ +Dygraph.TICK_PLACEMENT = []; +Dygraph.TICK_PLACEMENT[Dygraph.SECONDLY] = {datefield: Dygraph.DATEFIELD_SS, step: 1, spacing: 1000 * 1}; +Dygraph.TICK_PLACEMENT[Dygraph.TWO_SECONDLY] = {datefield: Dygraph.DATEFIELD_SS, step: 2, spacing: 1000 * 2}; +Dygraph.TICK_PLACEMENT[Dygraph.FIVE_SECONDLY] = {datefield: Dygraph.DATEFIELD_SS, step: 5, spacing: 1000 * 5}; +Dygraph.TICK_PLACEMENT[Dygraph.TEN_SECONDLY] = {datefield: Dygraph.DATEFIELD_SS, step: 10, spacing: 1000 * 10}; +Dygraph.TICK_PLACEMENT[Dygraph.THIRTY_SECONDLY] = {datefield: Dygraph.DATEFIELD_SS, step: 30, spacing: 1000 * 30}; +Dygraph.TICK_PLACEMENT[Dygraph.MINUTELY] = {datefield: Dygraph.DATEFIELD_MM, step: 1, spacing: 1000 * 60}; +Dygraph.TICK_PLACEMENT[Dygraph.TWO_MINUTELY] = {datefield: Dygraph.DATEFIELD_MM, step: 2, spacing: 1000 * 60 * 2}; +Dygraph.TICK_PLACEMENT[Dygraph.FIVE_MINUTELY] = {datefield: Dygraph.DATEFIELD_MM, step: 5, spacing: 1000 * 60 * 5}; +Dygraph.TICK_PLACEMENT[Dygraph.TEN_MINUTELY] = {datefield: Dygraph.DATEFIELD_MM, step: 10, spacing: 1000 * 60 * 10}; +Dygraph.TICK_PLACEMENT[Dygraph.THIRTY_MINUTELY] = {datefield: Dygraph.DATEFIELD_MM, step: 30, spacing: 1000 * 60 * 30}; +Dygraph.TICK_PLACEMENT[Dygraph.HOURLY] = {datefield: Dygraph.DATEFIELD_HH, step: 1, spacing: 1000 * 3600}; +Dygraph.TICK_PLACEMENT[Dygraph.TWO_HOURLY] = {datefield: Dygraph.DATEFIELD_HH, step: 2, spacing: 1000 * 3600 * 2}; +Dygraph.TICK_PLACEMENT[Dygraph.SIX_HOURLY] = {datefield: Dygraph.DATEFIELD_HH, step: 6, spacing: 1000 * 3600 * 6}; +Dygraph.TICK_PLACEMENT[Dygraph.DAILY] = {datefield: Dygraph.DATEFIELD_D, step: 1, spacing: 1000 * 86400}; +Dygraph.TICK_PLACEMENT[Dygraph.TWO_DAILY] = {datefield: Dygraph.DATEFIELD_D, step: 2, spacing: 1000 * 86400 * 2}; +Dygraph.TICK_PLACEMENT[Dygraph.WEEKLY] = {datefield: Dygraph.DATEFIELD_D, step: 7, spacing: 1000 * 604800}; +Dygraph.TICK_PLACEMENT[Dygraph.MONTHLY] = {datefield: Dygraph.DATEFIELD_M, step: 1, spacing: 1000 * 7200 * 365.2524}; // 1e3 * 60 * 60 * 24 * 365.2524 / 12 +Dygraph.TICK_PLACEMENT[Dygraph.QUARTERLY] = {datefield: Dygraph.DATEFIELD_M, step: 3, spacing: 1000 * 21600 * 365.2524}; // 1e3 * 60 * 60 * 24 * 365.2524 / 4 +Dygraph.TICK_PLACEMENT[Dygraph.BIANNUAL] = {datefield: Dygraph.DATEFIELD_M, step: 6, spacing: 1000 * 43200 * 365.2524}; // 1e3 * 60 * 60 * 24 * 365.2524 / 2 +Dygraph.TICK_PLACEMENT[Dygraph.ANNUAL] = {datefield: Dygraph.DATEFIELD_Y, step: 1, spacing: 1000 * 86400 * 365.2524}; // 1e3 * 60 * 60 * 24 * 365.2524 * 1 +Dygraph.TICK_PLACEMENT[Dygraph.DECADAL] = {datefield: Dygraph.DATEFIELD_Y, step: 10, spacing: 1000 * 864000 * 365.2524}; // 1e3 * 60 * 60 * 24 * 365.2524 * 10 +Dygraph.TICK_PLACEMENT[Dygraph.CENTENNIAL] = {datefield: Dygraph.DATEFIELD_Y, step: 100, spacing: 1000 * 8640000 * 365.2524}; // 1e3 * 60 * 60 * 24 * 365.2524 * 100 + + +/** + * 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.} + */ +Dygraph.PREFERRED_LOG_TICK_VALUES = (function() { + var vals = []; + for (var power = -39; power <= 39; power++) { + var range = Math.pow(10, power); + for (var mult = 1; mult <= 9; mult++) { + var val = range * mult; + vals.push(val); + } + } + return vals; +})(); + +/** + * 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(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 = /** @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) { + return i; + } + } + return -1; +}; + +/** + * Compute the number of ticks on a date axis for a given granularity. + * @param {number} start_time + * @param {number} end_time + * @param {number} granularity (one of the granularities enumerated above) + * @return {number} (Approximate) number of ticks that would result. + */ +Dygraph.numDateTicks = function(start_time, end_time, granularity) { + var spacing = Dygraph.TICK_PLACEMENT[granularity].spacing; + return Math.round(1.0 * (end_time - start_time) / spacing); +}; + +/** + * Compute the positions and labels of ticks on a date axis for a given 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 -> value. + * @param {Dygraph=} dg + * @return {!Dygraph.TickList} + */ +Dygraph.getDateAxis = function(start_time, end_time, granularity, opts, dg) { + var formatter = /** @type{AxisLabelFormatter} */( + opts("axisLabelFormatter")); + var utc = opts("labelsUTC"); + var accessors = utc ? Dygraph.DateAccessorsUTC : Dygraph.DateAccessorsLocal; + + var datefield = Dygraph.TICK_PLACEMENT[granularity].datefield; + var step = Dygraph.TICK_PLACEMENT[granularity].step; + var spacing = Dygraph.TICK_PLACEMENT[granularity].spacing; + + // Choose a nice tick position before the initial instant. + // Currently, this code deals properly with the existent daily granularities: + // DAILY (with step of 1) and WEEKLY (with step of 7 but specially handled). + // Other daily granularities (say TWO_DAILY) should also be handled specially + // by setting the start_date_offset to 0. + var start_date = new Date(start_time); + var date_array = []; + date_array[Dygraph.DATEFIELD_Y] = accessors.getFullYear(start_date); + date_array[Dygraph.DATEFIELD_M] = accessors.getMonth(start_date); + date_array[Dygraph.DATEFIELD_D] = accessors.getDate(start_date); + date_array[Dygraph.DATEFIELD_HH] = accessors.getHours(start_date); + date_array[Dygraph.DATEFIELD_MM] = accessors.getMinutes(start_date); + date_array[Dygraph.DATEFIELD_SS] = accessors.getSeconds(start_date); + date_array[Dygraph.DATEFIELD_MS] = accessors.getMilliseconds(start_date); + + var start_date_offset = date_array[datefield] % step; + if (granularity == Dygraph.WEEKLY) { + // This will put the ticks on Sundays. + start_date_offset = accessors.getDay(start_date); + } + + date_array[datefield] -= start_date_offset; + for (var df = datefield + 1; df < Dygraph.NUM_DATEFIELDS; df++) { + // The minimum value is 1 for the day of month, and 0 for all other fields. + date_array[df] = (df === Dygraph.DATEFIELD_D) ? 1 : 0; + } + + // Generate the ticks. + // For granularities not coarser than HOURLY we use the fact that: + // the number of milliseconds between ticks is constant + // and equal to the defined spacing. + // Otherwise we rely on the 'roll over' property of the Date functions: + // when some date field is set to a value outside of its logical range, + // the excess 'rolls over' the next (more significant) field. + // However, when using local time with DST transitions, + // there are dates that do not represent any time value at all + // (those in the hour skipped at the 'spring forward'), + // and the JavaScript engines usually return an equivalent value. + // Hence we have to check that the date is properly increased at each step, + // returning a date at a nice tick position. + var ticks = []; + var tick_date = accessors.makeDate.apply(null, date_array); + var tick_time = tick_date.getTime(); + if (granularity <= Dygraph.HOURLY) { + if (tick_time < start_time) { + tick_time += spacing; + tick_date = new Date(tick_time); + } + while (tick_time <= end_time) { + ticks.push({ v: tick_time, + label: formatter.call(dg, tick_date, granularity, opts, dg) + }); + tick_time += spacing; + tick_date = new Date(tick_time); + } + } else { + if (tick_time < start_time) { + date_array[datefield] += step; + tick_date = accessors.makeDate.apply(null, date_array); + tick_time = tick_date.getTime(); + } + while (tick_time <= end_time) { + if (granularity >= Dygraph.DAILY || + accessors.getHours(tick_date) % step === 0) { + ticks.push({ v: tick_time, + label: formatter.call(dg, tick_date, granularity, opts, dg) + }); + } + date_array[datefield] += step; + tick_date = accessors.makeDate.apply(null, date_array); + tick_time = tick_date.getTime(); + } + } + return ticks; +}; + +// These are set here so that this file can be included after dygraph.js +// or independently. +if (Dygraph && + Dygraph.DEFAULT_ATTRS && + Dygraph.DEFAULT_ATTRS['axes'] && + Dygraph.DEFAULT_ATTRS['axes']['x'] && + Dygraph.DEFAULT_ATTRS['axes']['y'] && + Dygraph.DEFAULT_ATTRS['axes']['y2']) { + Dygraph.DEFAULT_ATTRS['axes']['x']['ticker'] = Dygraph.dateTicker; + Dygraph.DEFAULT_ATTRS['axes']['y']['ticker'] = Dygraph.numericTicks; + Dygraph.DEFAULT_ATTRS['axes']['y2']['ticker'] = Dygraph.numericTicks; +} + +})(); +/*global Dygraph:false */ + +// Namespace for plugins. Load this before plugins/*.js files. +Dygraph.Plugins = {}; +/** + * @license + * Copyright 2012 Dan Vanderkam (danvdk@gmail.com) + * MIT-licensed (http://opensource.org/licenses/MIT) + */ + +/*global Dygraph:false */ + +Dygraph.Plugins.Annotations = (function() { + +"use strict"; + +/** +Current bits of jankiness: +- Uses dygraph.layout_ to get the parsed annotations. +- Uses dygraph.plotter_.area + +It would be nice if the plugin didn't require so much special support inside +the core dygraphs classes, but annotations involve quite a bit of parsing and +layout. + +TODO(danvk): cache DOM elements. + +*/ + +var annotations = function() { + this.annotations_ = []; +}; + +annotations.prototype.toString = function() { + return "Annotations Plugin"; +}; + +annotations.prototype.activate = function(g) { + return { + clearChart: this.clearChart, + didDrawChart: this.didDrawChart + }; +}; + +annotations.prototype.detachLabels = function() { + for (var i = 0; i < this.annotations_.length; i++) { + var a = this.annotations_[i]; + if (a.parentNode) a.parentNode.removeChild(a); + this.annotations_[i] = null; + } + this.annotations_ = []; +}; + +annotations.prototype.clearChart = function(e) { + this.detachLabels(); +}; + +annotations.prototype.didDrawChart = function(e) { + var g = e.dygraph; + + // Early out in the (common) case of zero annotations. + var points = g.layout_.annotated_points; + if (!points || points.length === 0) return; + + var containerDiv = e.canvas.parentNode; + var annotationStyle = { + "position": "absolute", + "fontSize": g.getOption('axisLabelFontSize') + "px", + "zIndex": 10, + "overflow": "hidden" + }; + + var bindEvt = function(eventName, classEventName, pt) { + return function(annotation_event) { + var a = pt.annotation; + if (a.hasOwnProperty(eventName)) { + a[eventName](a, pt, g, annotation_event); + } else if (g.getOption(classEventName)) { + g.getOption(classEventName)(a, pt, g, annotation_event ); + } + }; + }; + + // Add the annotations one-by-one. + var area = e.dygraph.plotter_.area; + + // x-coord to sum of previous annotation's heights (used for stacking). + var xToUsedHeight = {}; + + for (var i = 0; i < points.length; i++) { + var p = points[i]; + if (p.canvasx < area.x || p.canvasx > area.x + area.w || + p.canvasy < area.y || p.canvasy > area.y + area.h) { + continue; + } + + var a = p.annotation; + var tick_height = 6; + if (a.hasOwnProperty("tickHeight")) { + tick_height = a.tickHeight; + } + + var div = document.createElement("div"); + for (var name in annotationStyle) { + if (annotationStyle.hasOwnProperty(name)) { + div.style[name] = annotationStyle[name]; + } + } + if (!a.hasOwnProperty('icon')) { + div.className = "dygraphDefaultAnnotation"; + } + if (a.hasOwnProperty('cssClass')) { + div.className += " " + a.cssClass; + } + + var width = a.hasOwnProperty('width') ? a.width : 16; + var height = a.hasOwnProperty('height') ? a.height : 16; + if (a.hasOwnProperty('icon')) { + var img = document.createElement("img"); + img.src = a.icon; + img.width = width; + img.height = height; + div.appendChild(img); + } else if (p.annotation.hasOwnProperty('shortText')) { + div.appendChild(document.createTextNode(p.annotation.shortText)); + } + var left = p.canvasx - width / 2; + div.style.left = left + "px"; + var divTop = 0; + if (a.attachAtBottom) { + var y = (area.y + area.h - height - tick_height); + if (xToUsedHeight[left]) { + y -= xToUsedHeight[left]; + } else { + xToUsedHeight[left] = 0; + } + xToUsedHeight[left] += (tick_height + height); + divTop = y; + } else { + divTop = p.canvasy - height - tick_height; + } + div.style.top = divTop + "px"; + div.style.width = width + "px"; + div.style.height = height + "px"; + div.title = p.annotation.text; + div.style.color = g.colorsMap_[p.name]; + div.style.borderColor = g.colorsMap_[p.name]; + a.div = div; + + g.addAndTrackEvent(div, 'click', + bindEvt('clickHandler', 'annotationClickHandler', p, this)); + g.addAndTrackEvent(div, 'mouseover', + bindEvt('mouseOverHandler', 'annotationMouseOverHandler', p, this)); + g.addAndTrackEvent(div, 'mouseout', + bindEvt('mouseOutHandler', 'annotationMouseOutHandler', p, this)); + g.addAndTrackEvent(div, 'dblclick', + bindEvt('dblClickHandler', 'annotationDblClickHandler', p, this)); + + containerDiv.appendChild(div); + this.annotations_.push(div); + + var ctx = e.drawingContext; + ctx.save(); + ctx.strokeStyle = g.colorsMap_[p.name]; + ctx.beginPath(); + if (!a.attachAtBottom) { + ctx.moveTo(p.canvasx, p.canvasy); + ctx.lineTo(p.canvasx, p.canvasy - 2 - tick_height); + } else { + var y = divTop + height; + ctx.moveTo(p.canvasx, y); + ctx.lineTo(p.canvasx, y + tick_height); + } + ctx.closePath(); + ctx.stroke(); + ctx.restore(); + } +}; + +annotations.prototype.destroy = function() { + this.detachLabels(); +}; + +return annotations; + +})(); +/** + * @license + * Copyright 2012 Dan Vanderkam (danvdk@gmail.com) + * MIT-licensed (http://opensource.org/licenses/MIT) + */ + +/*global Dygraph:false */ + +Dygraph.Plugins.Axes = (function() { + +'use strict'; + +/* +Bits of jankiness: +- Direct layout access +- Direct area access +- Should include calculation of ticks, not just the drawing. + +Options left to make axis-friendly. + ('drawAxesAtZero') + ('xAxisHeight') +*/ + +/** + * Draws the axes. This includes the labels on the x- and y-axes, as well + * as the tick marks on the axes. + * It does _not_ draw the grid lines which span the entire chart. + */ +var axes = function() { + this.xlabels_ = []; + this.ylabels_ = []; +}; + +axes.prototype.toString = function() { + return 'Axes Plugin'; +}; + +axes.prototype.activate = function(g) { + return { + layout: this.layout, + clearChart: this.clearChart, + willDrawChart: this.willDrawChart + }; +}; + +axes.prototype.layout = function(e) { + var g = e.dygraph; + + if (g.getOptionForAxis('drawAxis', 'y')) { + var w = g.getOptionForAxis('axisLabelWidth', 'y') + 2 * g.getOptionForAxis('axisTickSize', 'y'); + e.reserveSpaceLeft(w); + } + + if (g.getOptionForAxis('drawAxis', 'x')) { + var h; + // NOTE: I think this is probably broken now, since g.getOption() now + // hits the dictionary. (That is, g.getOption('xAxisHeight') now always + // has a value.) + if (g.getOption('xAxisHeight')) { + h = g.getOption('xAxisHeight'); + } else { + h = g.getOptionForAxis('axisLabelFontSize', 'x') + 2 * g.getOptionForAxis('axisTickSize', 'x'); + } + e.reserveSpaceBottom(h); + } + + if (g.numAxes() == 2) { + if (g.getOptionForAxis('drawAxis', 'y2')) { + var w = g.getOptionForAxis('axisLabelWidth', 'y2') + 2 * g.getOptionForAxis('axisTickSize', 'y2'); + e.reserveSpaceRight(w); + } + } else if (g.numAxes() > 2) { + g.error('Only two y-axes are supported at this time. (Trying ' + + 'to use ' + g.numAxes() + ')'); + } +}; + +axes.prototype.detachLabels = function() { + function removeArray(ary) { + for (var i = 0; i < ary.length; i++) { + var el = ary[i]; + if (el.parentNode) el.parentNode.removeChild(el); + } + } + + removeArray(this.xlabels_); + removeArray(this.ylabels_); + this.xlabels_ = []; + this.ylabels_ = []; +}; + +axes.prototype.clearChart = function(e) { + this.detachLabels(); +}; + +axes.prototype.willDrawChart = function(e) { + var g = e.dygraph; + + if (!g.getOptionForAxis('drawAxis', 'x') && + !g.getOptionForAxis('drawAxis', 'y') && + !g.getOptionForAxis('drawAxis', 'y2')) { + return; + } + + // Round pixels to half-integer boundaries for crisper drawing. + function halfUp(x) { return Math.round(x) + 0.5; } + function halfDown(y){ return Math.round(y) - 0.5; } + + var context = e.drawingContext; + var containerDiv = e.canvas.parentNode; + var canvasWidth = g.width_; // e.canvas.width is affected by pixel ratio. + var canvasHeight = g.height_; + + var label, x, y, tick, i; + + var makeLabelStyle = function(axis) { + return { + position: 'absolute', + fontSize: g.getOptionForAxis('axisLabelFontSize', axis) + 'px', + zIndex: 10, + color: g.getOptionForAxis('axisLabelColor', axis), + width: g.getOptionForAxis('axisLabelWidth', axis) + 'px', + // height: g.getOptionForAxis('axisLabelFontSize', 'x') + 2 + "px", + lineHeight: 'normal', // Something other than "normal" line-height screws up label positioning. + overflow: 'hidden' + }; + }; + + var labelStyles = { + x : makeLabelStyle('x'), + y : makeLabelStyle('y'), + y2 : makeLabelStyle('y2') + }; + + var makeDiv = function(txt, axis, prec_axis) { + /* + * This seems to be called with the following three sets of axis/prec_axis: + * x: undefined + * y: y1 + * y: y2 + */ + var div = document.createElement('div'); + var labelStyle = labelStyles[prec_axis == 'y2' ? 'y2' : axis]; + for (var name in labelStyle) { + if (labelStyle.hasOwnProperty(name)) { + div.style[name] = labelStyle[name]; + } + } + var inner_div = document.createElement('div'); + inner_div.className = 'dygraph-axis-label' + + ' dygraph-axis-label-' + axis + + (prec_axis ? ' dygraph-axis-label-' + prec_axis : ''); + inner_div.innerHTML = txt; + div.appendChild(inner_div); + return div; + }; + + // axis lines + context.save(); + + var layout = g.layout_; + var area = e.dygraph.plotter_.area; + + // Helper for repeated axis-option accesses. + var makeOptionGetter = function(axis) { + return function(option) { + return g.getOptionForAxis(option, axis); + }; + }; + + if (g.getOptionForAxis('drawAxis', 'y')) { + if (layout.yticks && layout.yticks.length > 0) { + var num_axes = g.numAxes(); + var getOptions = [makeOptionGetter('y'), makeOptionGetter('y2')]; + for (i = 0; i < layout.yticks.length; i++) { + tick = layout.yticks[i]; + if (typeof(tick) == 'function') return; // <-- when would this happen? + x = area.x; + var sgn = 1; + var prec_axis = 'y1'; + var getAxisOption = getOptions[0]; + if (tick[0] == 1) { // right-side y-axis + x = area.x + area.w; + sgn = -1; + prec_axis = 'y2'; + getAxisOption = getOptions[1]; + } + var fontSize = getAxisOption('axisLabelFontSize'); + y = area.y + tick[1] * area.h; + + /* Tick marks are currently clipped, so don't bother drawing them. + context.beginPath(); + context.moveTo(halfUp(x), halfDown(y)); + context.lineTo(halfUp(x - sgn * this.attr_('axisTickSize')), halfDown(y)); + context.closePath(); + context.stroke(); + */ + + label = makeDiv(tick[2], 'y', num_axes == 2 ? prec_axis : null); + var top = (y - fontSize / 2); + if (top < 0) top = 0; + + if (top + fontSize + 3 > canvasHeight) { + label.style.bottom = '0'; + } else { + label.style.top = top + 'px'; + } + if (tick[0] === 0) { + label.style.left = (area.x - getAxisOption('axisLabelWidth') - getAxisOption('axisTickSize')) + 'px'; + label.style.textAlign = 'right'; + } else if (tick[0] == 1) { + label.style.left = (area.x + area.w + + getAxisOption('axisTickSize')) + 'px'; + label.style.textAlign = 'left'; + } + label.style.width = getAxisOption('axisLabelWidth') + 'px'; + containerDiv.appendChild(label); + this.ylabels_.push(label); + } + + // The lowest tick on the y-axis often overlaps with the leftmost + // tick on the x-axis. Shift the bottom tick up a little bit to + // compensate if necessary. + var bottomTick = this.ylabels_[0]; + // Interested in the y2 axis also? + var fontSize = g.getOptionForAxis('axisLabelFontSize', 'y'); + var bottom = parseInt(bottomTick.style.top, 10) + fontSize; + if (bottom > canvasHeight - fontSize) { + bottomTick.style.top = (parseInt(bottomTick.style.top, 10) - + fontSize / 2) + 'px'; + } + } + + // draw a vertical line on the left to separate the chart from the labels. + var axisX; + if (g.getOption('drawAxesAtZero')) { + var r = g.toPercentXCoord(0); + if (r > 1 || r < 0 || isNaN(r)) r = 0; + axisX = halfUp(area.x + r * area.w); + } else { + axisX = halfUp(area.x); + } + + context.strokeStyle = g.getOptionForAxis('axisLineColor', 'y'); + context.lineWidth = g.getOptionForAxis('axisLineWidth', 'y'); + + context.beginPath(); + context.moveTo(axisX, halfDown(area.y)); + context.lineTo(axisX, halfDown(area.y + area.h)); + context.closePath(); + context.stroke(); + + // if there's a secondary y-axis, draw a vertical line for that, too. + if (g.numAxes() == 2) { + context.strokeStyle = g.getOptionForAxis('axisLineColor', 'y2'); + context.lineWidth = g.getOptionForAxis('axisLineWidth', 'y2'); + context.beginPath(); + context.moveTo(halfDown(area.x + area.w), halfDown(area.y)); + context.lineTo(halfDown(area.x + area.w), halfDown(area.y + area.h)); + context.closePath(); + context.stroke(); + } + } + + if (g.getOptionForAxis('drawAxis', 'x')) { + if (layout.xticks) { + var getAxisOption = makeOptionGetter('x'); + for (i = 0; i < layout.xticks.length; i++) { + tick = layout.xticks[i]; + x = area.x + tick[0] * area.w; + y = area.y + area.h; + + /* Tick marks are currently clipped, so don't bother drawing them. + context.beginPath(); + context.moveTo(halfUp(x), halfDown(y)); + context.lineTo(halfUp(x), halfDown(y + this.attr_('axisTickSize'))); + context.closePath(); + context.stroke(); + */ + + label = makeDiv(tick[1], 'x'); + label.style.textAlign = 'center'; + label.style.top = (y + getAxisOption('axisTickSize')) + 'px'; + + var left = (x - getAxisOption('axisLabelWidth')/2); + if (left + getAxisOption('axisLabelWidth') > canvasWidth) { + left = canvasWidth - getAxisOption('axisLabelWidth'); + label.style.textAlign = 'right'; + } + if (left < 0) { + left = 0; + label.style.textAlign = 'left'; + } + + label.style.left = left + 'px'; + label.style.width = getAxisOption('axisLabelWidth') + 'px'; + containerDiv.appendChild(label); + this.xlabels_.push(label); + } + } + + context.strokeStyle = g.getOptionForAxis('axisLineColor', 'x'); + context.lineWidth = g.getOptionForAxis('axisLineWidth', 'x'); + context.beginPath(); + var axisY; + if (g.getOption('drawAxesAtZero')) { + var r = g.toPercentYCoord(0, 0); + if (r > 1 || r < 0) r = 1; + axisY = halfDown(area.y + r * area.h); + } else { + axisY = halfDown(area.y + area.h); + } + context.moveTo(halfUp(area.x), axisY); + context.lineTo(halfUp(area.x + area.w), axisY); + context.closePath(); + context.stroke(); + } + + context.restore(); +}; + +return axes; +})(); +/** + * @license + * Copyright 2012 Dan Vanderkam (danvdk@gmail.com) + * MIT-licensed (http://opensource.org/licenses/MIT) + */ +/*global Dygraph:false */ + +Dygraph.Plugins.ChartLabels = (function() { + +"use strict"; + +// TODO(danvk): move chart label options out of dygraphs and into the plugin. +// TODO(danvk): only tear down & rebuild the DIVs when it's necessary. + +var chart_labels = function() { + this.title_div_ = null; + this.xlabel_div_ = null; + this.ylabel_div_ = null; + this.y2label_div_ = null; +}; + +chart_labels.prototype.toString = function() { + return "ChartLabels Plugin"; +}; + +chart_labels.prototype.activate = function(g) { + return { + layout: this.layout, + // clearChart: this.clearChart, + didDrawChart: this.didDrawChart + }; +}; + +// QUESTION: should there be a plugin-utils.js? +var createDivInRect = function(r) { + var div = document.createElement('div'); + div.style.position = 'absolute'; + div.style.left = r.x + 'px'; + div.style.top = r.y + 'px'; + div.style.width = r.w + 'px'; + div.style.height = r.h + 'px'; + return div; +}; + +// Detach and null out any existing nodes. +chart_labels.prototype.detachLabels_ = function() { + var els = [ this.title_div_, + this.xlabel_div_, + this.ylabel_div_, + this.y2label_div_ ]; + for (var i = 0; i < els.length; i++) { + var el = els[i]; + if (!el) continue; + if (el.parentNode) el.parentNode.removeChild(el); + } + + this.title_div_ = null; + this.xlabel_div_ = null; + this.ylabel_div_ = null; + this.y2label_div_ = null; +}; + +var createRotatedDiv = function(g, box, axis, classes, html) { + // TODO(danvk): is this outer div actually necessary? + var div = document.createElement("div"); + div.style.position = 'absolute'; + if (axis == 1) { + // NOTE: this is cheating. Should be positioned relative to the box. + div.style.left = '0px'; + } else { + div.style.left = box.x + 'px'; + } + div.style.top = box.y + 'px'; + div.style.width = box.w + 'px'; + div.style.height = box.h + 'px'; + div.style.fontSize = (g.getOption('yLabelWidth') - 2) + 'px'; + + var inner_div = document.createElement("div"); + inner_div.style.position = 'absolute'; + inner_div.style.width = box.h + 'px'; + inner_div.style.height = box.w + 'px'; + inner_div.style.top = (box.h / 2 - box.w / 2) + 'px'; + inner_div.style.left = (box.w / 2 - box.h / 2) + 'px'; + inner_div.style.textAlign = 'center'; + + // CSS rotation is an HTML5 feature which is not standardized. Hence every + // browser has its own name for the CSS style. + var val = 'rotate(' + (axis == 1 ? '-' : '') + '90deg)'; + inner_div.style.transform = val; // HTML5 + inner_div.style.WebkitTransform = val; // Safari/Chrome + inner_div.style.MozTransform = val; // Firefox + inner_div.style.OTransform = val; // Opera + inner_div.style.msTransform = val; // IE9 + + if (typeof(document.documentMode) !== 'undefined' && + document.documentMode < 9) { + // We're dealing w/ an old version of IE, so we have to rotate the text + // using a BasicImage transform. This uses a different origin of rotation + // than HTML5 rotation (top left of div vs. its center). + inner_div.style.filter = + 'progid:DXImageTransform.Microsoft.BasicImage(rotation=' + + (axis == 1 ? '3' : '1') + ')'; + inner_div.style.left = '0px'; + inner_div.style.top = '0px'; + } + + var class_div = document.createElement("div"); + class_div.className = classes; + class_div.innerHTML = html; + + inner_div.appendChild(class_div); + div.appendChild(inner_div); + return div; +}; + +chart_labels.prototype.layout = function(e) { + this.detachLabels_(); + + var g = e.dygraph; + var div = e.chart_div; + if (g.getOption('title')) { + // QUESTION: should this return an absolutely-positioned div instead? + var title_rect = e.reserveSpaceTop(g.getOption('titleHeight')); + this.title_div_ = createDivInRect(title_rect); + this.title_div_.style.textAlign = 'center'; + this.title_div_.style.fontSize = (g.getOption('titleHeight') - 8) + 'px'; + this.title_div_.style.fontWeight = 'bold'; + this.title_div_.style.zIndex = 10; + + var class_div = document.createElement("div"); + class_div.className = 'dygraph-label dygraph-title'; + class_div.innerHTML = g.getOption('title'); + this.title_div_.appendChild(class_div); + div.appendChild(this.title_div_); + } + + if (g.getOption('xlabel')) { + var x_rect = e.reserveSpaceBottom(g.getOption('xLabelHeight')); + this.xlabel_div_ = createDivInRect(x_rect); + this.xlabel_div_.style.textAlign = 'center'; + this.xlabel_div_.style.fontSize = (g.getOption('xLabelHeight') - 2) + 'px'; + + var class_div = document.createElement("div"); + class_div.className = 'dygraph-label dygraph-xlabel'; + class_div.innerHTML = g.getOption('xlabel'); + this.xlabel_div_.appendChild(class_div); + div.appendChild(this.xlabel_div_); + } + + if (g.getOption('ylabel')) { + // It would make sense to shift the chart here to make room for the y-axis + // label, but the default yAxisLabelWidth is large enough that this results + // in overly-padded charts. The y-axis label should fit fine. If it + // doesn't, the yAxisLabelWidth option can be increased. + var y_rect = e.reserveSpaceLeft(0); + + this.ylabel_div_ = createRotatedDiv( + g, y_rect, + 1, // primary (left) y-axis + 'dygraph-label dygraph-ylabel', + g.getOption('ylabel')); + div.appendChild(this.ylabel_div_); + } + + if (g.getOption('y2label') && g.numAxes() == 2) { + // same logic applies here as for ylabel. + var y2_rect = e.reserveSpaceRight(0); + this.y2label_div_ = createRotatedDiv( + g, y2_rect, + 2, // secondary (right) y-axis + 'dygraph-label dygraph-y2label', + g.getOption('y2label')); + div.appendChild(this.y2label_div_); + } +}; + +chart_labels.prototype.didDrawChart = function(e) { + var g = e.dygraph; + if (this.title_div_) { + this.title_div_.children[0].innerHTML = g.getOption('title'); + } + if (this.xlabel_div_) { + this.xlabel_div_.children[0].innerHTML = g.getOption('xlabel'); + } + if (this.ylabel_div_) { + this.ylabel_div_.children[0].children[0].innerHTML = g.getOption('ylabel'); + } + if (this.y2label_div_) { + this.y2label_div_.children[0].children[0].innerHTML = g.getOption('y2label'); + } +}; + +chart_labels.prototype.clearChart = function() { +}; + +chart_labels.prototype.destroy = function() { + this.detachLabels_(); +}; + + +return chart_labels; +})(); +/** + * @license + * Copyright 2012 Dan Vanderkam (danvdk@gmail.com) + * MIT-licensed (http://opensource.org/licenses/MIT) + */ +/*global Dygraph:false */ + +Dygraph.Plugins.Grid = (function() { + +/* + +Current bits of jankiness: +- Direct layout access +- Direct area access + +*/ + +"use strict"; + + +/** + * Draws the gridlines, i.e. the gray horizontal & vertical lines running the + * length of the chart. + * + * @constructor + */ +var grid = function() { +}; + +grid.prototype.toString = function() { + return "Gridline Plugin"; +}; + +grid.prototype.activate = function(g) { + return { + willDrawChart: this.willDrawChart + }; +}; + +grid.prototype.willDrawChart = function(e) { + // Draw the new X/Y grid. Lines appear crisper when pixels are rounded to + // half-integers. This prevents them from drawing in two rows/cols. + var g = e.dygraph; + var ctx = e.drawingContext; + var layout = g.layout_; + var area = e.dygraph.plotter_.area; + + function halfUp(x) { return Math.round(x) + 0.5; } + function halfDown(y){ return Math.round(y) - 0.5; } + + var x, y, i, ticks; + if (g.getOptionForAxis('drawGrid', 'y')) { + var axes = ["y", "y2"]; + var strokeStyles = [], lineWidths = [], drawGrid = [], stroking = [], strokePattern = []; + for (var i = 0; i < axes.length; i++) { + drawGrid[i] = g.getOptionForAxis('drawGrid', axes[i]); + if (drawGrid[i]) { + strokeStyles[i] = g.getOptionForAxis('gridLineColor', axes[i]); + lineWidths[i] = g.getOptionForAxis('gridLineWidth', axes[i]); + strokePattern[i] = g.getOptionForAxis('gridLinePattern', axes[i]); + stroking[i] = strokePattern[i] && (strokePattern[i].length >= 2); + } + } + ticks = layout.yticks; + ctx.save(); + // draw grids for the different y axes + for (i = 0; i < ticks.length; i++) { + var axis = ticks[i][0]; + if(drawGrid[axis]) { + if (stroking[axis]) { + ctx.installPattern(strokePattern[axis]); + } + ctx.strokeStyle = strokeStyles[axis]; + ctx.lineWidth = lineWidths[axis]; + + x = halfUp(area.x); + y = halfDown(area.y + ticks[i][1] * area.h); + ctx.beginPath(); + ctx.moveTo(x, y); + ctx.lineTo(x + area.w, y); + ctx.closePath(); + ctx.stroke(); + + if (stroking[axis]) { + ctx.uninstallPattern(); + } + } + } + ctx.restore(); + } + + // draw grid for x axis + if (g.getOptionForAxis('drawGrid', 'x')) { + ticks = layout.xticks; + ctx.save(); + var strokePattern = g.getOptionForAxis('gridLinePattern', 'x'); + var stroking = strokePattern && (strokePattern.length >= 2); + if (stroking) { + ctx.installPattern(strokePattern); + } + ctx.strokeStyle = g.getOptionForAxis('gridLineColor', 'x'); + ctx.lineWidth = g.getOptionForAxis('gridLineWidth', 'x'); + for (i = 0; i < ticks.length; i++) { + x = halfUp(area.x + ticks[i][0] * area.w); + y = halfDown(area.y + area.h); + ctx.beginPath(); + ctx.moveTo(x, y); + ctx.lineTo(x, area.y); + ctx.closePath(); + ctx.stroke(); + } + if (stroking) { + ctx.uninstallPattern(); + } + ctx.restore(); + } +}; + +grid.prototype.destroy = function() { +}; + +return grid; + +})(); +/** + * @license + * Copyright 2012 Dan Vanderkam (danvdk@gmail.com) + * MIT-licensed (http://opensource.org/licenses/MIT) + */ +/*global Dygraph:false */ + +Dygraph.Plugins.Legend = (function() { +/* +Current bits of jankiness: +- Uses two private APIs: + 1. Dygraph.optionsViewForAxis_ + 2. dygraph.plotter_.area +- Registers for a "predraw" event, which should be renamed. +- I call calculateEmWidthInDiv more often than needed. +*/ + +/*global Dygraph:false */ +"use strict"; + + +/** + * Creates the legend, which appears when the user hovers over the chart. + * The legend can be either a user-specified or generated div. + * + * @constructor + */ +var legend = function() { + this.legend_div_ = null; + this.is_generated_div_ = false; // do we own this div, or was it user-specified? +}; + +legend.prototype.toString = function() { + return "Legend Plugin"; +}; + +// (defined below) +var generateLegendDashHTML; + +/** + * This is called during the dygraph constructor, after options have been set + * but before the data is available. + * + * Proper tasks to do here include: + * - Reading your own options + * - DOM manipulation + * - Registering event listeners + * + * @param {Dygraph} g Graph instance. + * @return {object.} Mapping of event names to callbacks. + */ +legend.prototype.activate = function(g) { + var div; + var divWidth = g.getOption('labelsDivWidth'); + + var userLabelsDiv = g.getOption('labelsDiv'); + if (userLabelsDiv && null !== userLabelsDiv) { + if (typeof(userLabelsDiv) == "string" || userLabelsDiv instanceof String) { + div = document.getElementById(userLabelsDiv); + } else { + div = userLabelsDiv; + } + } else { + // Default legend styles. These can be overridden in CSS by adding + // "!important" after your rule, e.g. "left: 30px !important;" + var messagestyle = { + "position": "absolute", + "fontSize": "14px", + "zIndex": 10, + "width": divWidth + "px", + "top": "0px", + "left": (g.size().width - divWidth - 2) + "px", + "background": "white", + "lineHeight": "normal", + "textAlign": "left", + "overflow": "hidden"}; + + // TODO(danvk): get rid of labelsDivStyles? CSS is better. + Dygraph.update(messagestyle, g.getOption('labelsDivStyles')); + div = document.createElement("div"); + div.className = "dygraph-legend"; + for (var name in messagestyle) { + if (!messagestyle.hasOwnProperty(name)) continue; + + try { + div.style[name] = messagestyle[name]; + } catch (e) { + console.warn("You are using unsupported css properties for your " + + "browser in labelsDivStyles"); + } + } + + // TODO(danvk): come up with a cleaner way to expose this. + g.graphDiv.appendChild(div); + this.is_generated_div_ = true; + } + + this.legend_div_ = div; + this.one_em_width_ = 10; // just a guess, will be updated. + + return { + select: this.select, + deselect: this.deselect, + // TODO(danvk): rethink the name "predraw" before we commit to it in any API. + predraw: this.predraw, + didDrawChart: this.didDrawChart + }; +}; + +// Needed for dashed lines. +var calculateEmWidthInDiv = function(div) { + var sizeSpan = document.createElement('span'); + sizeSpan.setAttribute('style', 'margin: 0; padding: 0 0 0 1em; border: 0;'); + div.appendChild(sizeSpan); + var oneEmWidth=sizeSpan.offsetWidth; + div.removeChild(sizeSpan); + return oneEmWidth; +}; + +var escapeHTML = function(str) { + return str.replace(/&/g, "&").replace(/"/g, """).replace(//g, ">"); +}; + +legend.prototype.select = function(e) { + var xValue = e.selectedX; + var points = e.selectedPoints; + var row = e.selectedRow; + + var legendMode = e.dygraph.getOption('legend'); + if (legendMode === 'never') { + this.legend_div_.style.display = 'none'; + return; + } + + if (legendMode === 'follow') { + // create floating legend div + var area = e.dygraph.plotter_.area; + var labelsDivWidth = e.dygraph.getOption('labelsDivWidth'); + var yAxisLabelWidth = e.dygraph.getOptionForAxis('axisLabelWidth', 'y'); + // determine floating [left, top] coordinates of the legend div + // within the plotter_ area + // offset 20 px to the right and down from the first selection point + // 20 px is guess based on mouse cursor size + var leftLegend = points[0].x * area.w + 20; + var topLegend = points[0].y * area.h - 20; + + // if legend floats to end of the window area, it flips to the other + // side of the selection point + if ((leftLegend + labelsDivWidth + 1) > (window.scrollX + window.innerWidth)) { + leftLegend = leftLegend - 2 * 20 - labelsDivWidth - (yAxisLabelWidth - area.x); + } + + e.dygraph.graphDiv.appendChild(this.legend_div_); + this.legend_div_.style.left = yAxisLabelWidth + leftLegend + "px"; + this.legend_div_.style.top = topLegend + "px"; + } + + var html = legend.generateLegendHTML(e.dygraph, xValue, points, this.one_em_width_, row); + this.legend_div_.innerHTML = html; + this.legend_div_.style.display = ''; +}; + +legend.prototype.deselect = function(e) { + var legendMode = e.dygraph.getOption('legend'); + if (legendMode !== 'always') { + this.legend_div_.style.display = "none"; + } + + // Have to do this every time, since styles might have changed. + var oneEmWidth = calculateEmWidthInDiv(this.legend_div_); + this.one_em_width_ = oneEmWidth; + + var html = legend.generateLegendHTML(e.dygraph, undefined, undefined, oneEmWidth, null); + this.legend_div_.innerHTML = html; +}; + +legend.prototype.didDrawChart = function(e) { + this.deselect(e); +}; + +// Right edge should be flush with the right edge of the charting area (which +// may not be the same as the right edge of the div, if we have two y-axes. +// TODO(danvk): is any of this really necessary? Could just set "right" in "activate". +/** + * Position the labels div so that: + * - its right edge is flush with the right edge of the charting area + * - its top edge is flush with the top edge of the charting area + * @private + */ +legend.prototype.predraw = function(e) { + // Don't touch a user-specified labelsDiv. + if (!this.is_generated_div_) return; + + // TODO(danvk): only use real APIs for this. + e.dygraph.graphDiv.appendChild(this.legend_div_); + var area = e.dygraph.plotter_.area; + var labelsDivWidth = e.dygraph.getOption("labelsDivWidth"); + this.legend_div_.style.left = area.x + area.w - labelsDivWidth - 1 + "px"; + this.legend_div_.style.top = area.y + "px"; + this.legend_div_.style.width = labelsDivWidth + "px"; +}; + +/** + * Called when dygraph.destroy() is called. + * You should null out any references and detach any DOM elements. + */ +legend.prototype.destroy = function() { + this.legend_div_ = null; +}; + +/** + * @private + * Generates HTML for the legend which is displayed when hovering over the + * chart. If no selected points are specified, a default legend is returned + * (this may just be the empty string). + * @param {number} x The x-value of the selected points. + * @param {Object} sel_points List of selected points for the given + * x-value. Should have properties like 'name', 'yval' and 'canvasy'. + * @param {number} oneEmWidth The pixel width for 1em in the legend. Only + * relevant when displaying a legend with no selection (i.e. {legend: + * 'always'}) and with dashed lines. + * @param {number} row The selected row index. + */ +legend.generateLegendHTML = function(g, x, sel_points, oneEmWidth, row) { + // TODO(danvk): deprecate this option in place of {legend: 'never'} + if (g.getOption('showLabelsOnHighlight') !== true) return ''; + + // If no points are selected, we display a default legend. Traditionally, + // this has been blank. But a better default would be a conventional legend, + // which provides essential information for a non-interactive chart. + var html, sepLines, i, dash, strokePattern; + var labels = g.getLabels(); + + if (typeof(x) === 'undefined') { + if (g.getOption('legend') != 'always') { + return ''; + } + + sepLines = g.getOption('labelsSeparateLines'); + html = ''; + for (i = 1; i < labels.length; i++) { + var series = g.getPropertiesForSeries(labels[i]); + if (!series.visible) continue; + + if (html !== '') html += (sepLines ? '
' : ' '); + strokePattern = g.getOption("strokePattern", labels[i]); + dash = generateLegendDashHTML(strokePattern, series.color, oneEmWidth); + html += "" + + dash + " " + escapeHTML(labels[i]) + ""; + } + return html; + } + + // TODO(danvk): remove this use of a private API + var xOptView = g.optionsViewForAxis_('x'); + var xvf = xOptView('valueFormatter'); + html = xvf.call(g, x, xOptView, labels[0], g, row, 0); + if (html !== '') { + html += ':'; + } + + var yOptViews = []; + var num_axes = g.numAxes(); + for (i = 0; i < num_axes; i++) { + // TODO(danvk): remove this use of a private API + yOptViews[i] = g.optionsViewForAxis_('y' + (i ? 1 + i : '')); + } + var showZeros = g.getOption("labelsShowZeroValues"); + sepLines = g.getOption("labelsSeparateLines"); + var highlightSeries = g.getHighlightSeries(); + for (i = 0; i < sel_points.length; i++) { + var pt = sel_points[i]; + if (pt.yval === 0 && !showZeros) continue; + if (!Dygraph.isOK(pt.canvasy)) continue; + if (sepLines) html += "
"; + + var series = g.getPropertiesForSeries(pt.name); + var yOptView = yOptViews[series.axis - 1]; + var fmtFunc = yOptView('valueFormatter'); + var yval = fmtFunc.call(g, pt.yval, yOptView, pt.name, g, row, labels.indexOf(pt.name)); + + var cls = (pt.name == highlightSeries) ? " class='highlight'" : ""; + + // TODO(danvk): use a template string here and make it an attribute. + html += "" + " " + + escapeHTML(pt.name) + ": " + yval + ""; + } + return html; +}; + + +/** + * Generates html for the "dash" displayed on the legend when using "legend: always". + * In particular, this works for dashed lines with any stroke pattern. It will + * try to scale the pattern to fit in 1em width. Or if small enough repeat the + * pattern for 1em width. + * + * @param strokePattern The pattern + * @param color The color of the series. + * @param oneEmWidth The width in pixels of 1em in the legend. + * @private + */ +generateLegendDashHTML = function(strokePattern, color, oneEmWidth) { + // IE 7,8 fail at these divs, so they get boring legend, have not tested 9. + var isIE = (/MSIE/.test(navigator.userAgent) && !window.opera); + if (isIE) return "—"; + + // Easy, common case: a solid line + if (!strokePattern || strokePattern.length <= 1) { + return "
"; + } + + var i, j, paddingLeft, marginRight; + var strokePixelLength = 0, segmentLoop = 0; + var normalizedPattern = []; + var loop; + + // Compute the length of the pixels including the first segment twice, + // since we repeat it. + for (i = 0; i <= strokePattern.length; i++) { + strokePixelLength += strokePattern[i%strokePattern.length]; + } + + // See if we can loop the pattern by itself at least twice. + loop = Math.floor(oneEmWidth/(strokePixelLength-strokePattern[0])); + if (loop > 1) { + // This pattern fits at least two times, no scaling just convert to em; + for (i = 0; i < strokePattern.length; i++) { + normalizedPattern[i] = strokePattern[i]/oneEmWidth; + } + // Since we are repeating the pattern, we don't worry about repeating the + // first segment in one draw. + segmentLoop = normalizedPattern.length; + } else { + // If the pattern doesn't fit in the legend we scale it to fit. + loop = 1; + for (i = 0; i < strokePattern.length; i++) { + normalizedPattern[i] = strokePattern[i]/strokePixelLength; + } + // For the scaled patterns we do redraw the first segment. + segmentLoop = normalizedPattern.length+1; + } + + // Now make the pattern. + var dash = ""; + for (j = 0; j < loop; j++) { + for (i = 0; i < segmentLoop; i+=2) { + // The padding is the drawn segment. + paddingLeft = normalizedPattern[i%normalizedPattern.length]; + if (i < strokePattern.length) { + // The margin is the space segment. + marginRight = normalizedPattern[(i+1)%normalizedPattern.length]; + } else { + // The repeated first segment has no right margin. + marginRight = 0; + } + dash += "
"; + } + } + return dash; +}; + + +return legend; +})(); +/** + * @license + * Copyright 2011 Paul Felix (paul.eric.felix@gmail.com) + * MIT-licensed (http://opensource.org/licenses/MIT) + */ +/*global Dygraph:false,TouchEvent:false */ + +/** + * @fileoverview This file contains the RangeSelector plugin used to provide + * a timeline range selector widget for dygraphs. + */ + +Dygraph.Plugins.RangeSelector = (function() { + +/*global Dygraph:false */ +"use strict"; + +var rangeSelector = function() { + this.isIE_ = /MSIE/.test(navigator.userAgent) && !window.opera; + this.hasTouchInterface_ = typeof(TouchEvent) != 'undefined'; + this.isMobileDevice_ = /mobile|android/gi.test(navigator.appVersion); + this.interfaceCreated_ = false; +}; + +rangeSelector.prototype.toString = function() { + return "RangeSelector Plugin"; +}; + +rangeSelector.prototype.activate = function(dygraph) { + this.dygraph_ = dygraph; + this.isUsingExcanvas_ = dygraph.isUsingExcanvas_; + if (this.getOption_('showRangeSelector')) { + this.createInterface_(); + } + return { + layout: this.reserveSpace_, + predraw: this.renderStaticLayer_, + didDrawChart: this.renderInteractiveLayer_ + }; +}; + +rangeSelector.prototype.destroy = function() { + this.bgcanvas_ = null; + this.fgcanvas_ = null; + this.leftZoomHandle_ = null; + this.rightZoomHandle_ = null; + this.iePanOverlay_ = null; +}; + +//------------------------------------------------------------------ +// Private methods +//------------------------------------------------------------------ + +rangeSelector.prototype.getOption_ = function(name, opt_series) { + return this.dygraph_.getOption(name, opt_series); +}; + +rangeSelector.prototype.setDefaultOption_ = function(name, value) { + this.dygraph_.attrs_[name] = value; +}; + +/** + * @private + * Creates the range selector elements and adds them to the graph. + */ +rangeSelector.prototype.createInterface_ = function() { + this.createCanvases_(); + if (this.isUsingExcanvas_) { + this.createIEPanOverlay_(); + } + this.createZoomHandles_(); + this.initInteraction_(); + + // Range selector and animatedZooms have a bad interaction. See issue 359. + if (this.getOption_('animatedZooms')) { + console.warn('Animated zooms and range selector are not compatible; disabling animatedZooms.'); + this.dygraph_.updateOptions({animatedZooms: false}, true); + } + + this.interfaceCreated_ = true; + this.addToGraph_(); +}; + +/** + * @private + * Adds the range selector to the graph. + */ +rangeSelector.prototype.addToGraph_ = function() { + var graphDiv = this.graphDiv_ = this.dygraph_.graphDiv; + graphDiv.appendChild(this.bgcanvas_); + graphDiv.appendChild(this.fgcanvas_); + graphDiv.appendChild(this.leftZoomHandle_); + graphDiv.appendChild(this.rightZoomHandle_); +}; + +/** + * @private + * Removes the range selector from the graph. + */ +rangeSelector.prototype.removeFromGraph_ = function() { + var graphDiv = this.graphDiv_; + graphDiv.removeChild(this.bgcanvas_); + graphDiv.removeChild(this.fgcanvas_); + graphDiv.removeChild(this.leftZoomHandle_); + graphDiv.removeChild(this.rightZoomHandle_); + this.graphDiv_ = null; +}; + +/** + * @private + * Called by Layout to allow range selector to reserve its space. + */ +rangeSelector.prototype.reserveSpace_ = function(e) { + if (this.getOption_('showRangeSelector')) { + e.reserveSpaceBottom(this.getOption_('rangeSelectorHeight') + 4); + } +}; + +/** + * @private + * Renders the static portion of the range selector at the predraw stage. + */ +rangeSelector.prototype.renderStaticLayer_ = function() { + if (!this.updateVisibility_()) { + return; + } + this.resize_(); + this.drawStaticLayer_(); +}; + +/** + * @private + * Renders the interactive portion of the range selector after the chart has been drawn. + */ +rangeSelector.prototype.renderInteractiveLayer_ = function() { + if (!this.updateVisibility_() || this.isChangingRange_) { + return; + } + this.placeZoomHandles_(); + this.drawInteractiveLayer_(); +}; + +/** + * @private + * Check to see if the range selector is enabled/disabled and update visibility accordingly. + */ +rangeSelector.prototype.updateVisibility_ = function() { + var enabled = this.getOption_('showRangeSelector'); + if (enabled) { + if (!this.interfaceCreated_) { + this.createInterface_(); + } else if (!this.graphDiv_ || !this.graphDiv_.parentNode) { + this.addToGraph_(); + } + } else if (this.graphDiv_) { + this.removeFromGraph_(); + var dygraph = this.dygraph_; + setTimeout(function() { dygraph.width_ = 0; dygraph.resize(); }, 1); + } + return enabled; +}; + +/** + * @private + * Resizes the range selector. + */ +rangeSelector.prototype.resize_ = function() { + function setElementRect(canvas, context, rect) { + var canvasScale = Dygraph.getContextPixelRatio(context); + + canvas.style.top = rect.y + 'px'; + canvas.style.left = rect.x + 'px'; + canvas.width = rect.w * canvasScale; + canvas.height = rect.h * canvasScale; + canvas.style.width = rect.w + 'px'; + canvas.style.height = rect.h + 'px'; + + if(canvasScale != 1) { + context.scale(canvasScale, canvasScale); + } + } + + var plotArea = this.dygraph_.layout_.getPlotArea(); + + var xAxisLabelHeight = 0; + if (this.dygraph_.getOptionForAxis('drawAxis', 'x')) { + xAxisLabelHeight = this.getOption_('xAxisHeight') || (this.getOption_('axisLabelFontSize') + 2 * this.getOption_('axisTickSize')); + } + this.canvasRect_ = { + x: plotArea.x, + y: plotArea.y + plotArea.h + xAxisLabelHeight + 4, + w: plotArea.w, + h: this.getOption_('rangeSelectorHeight') + }; + + setElementRect(this.bgcanvas_, this.bgcanvas_ctx_, this.canvasRect_); + setElementRect(this.fgcanvas_, this.fgcanvas_ctx_, this.canvasRect_); +}; + +/** + * @private + * Creates the background and foreground canvases. + */ +rangeSelector.prototype.createCanvases_ = function() { + this.bgcanvas_ = Dygraph.createCanvas(); + this.bgcanvas_.className = 'dygraph-rangesel-bgcanvas'; + this.bgcanvas_.style.position = 'absolute'; + this.bgcanvas_.style.zIndex = 9; + this.bgcanvas_ctx_ = Dygraph.getContext(this.bgcanvas_); + + this.fgcanvas_ = Dygraph.createCanvas(); + this.fgcanvas_.className = 'dygraph-rangesel-fgcanvas'; + this.fgcanvas_.style.position = 'absolute'; + this.fgcanvas_.style.zIndex = 9; + this.fgcanvas_.style.cursor = 'default'; + this.fgcanvas_ctx_ = Dygraph.getContext(this.fgcanvas_); +}; + +/** + * @private + * Creates overlay divs for IE/Excanvas so that mouse events are handled properly. + */ +rangeSelector.prototype.createIEPanOverlay_ = function() { + this.iePanOverlay_ = document.createElement("div"); + this.iePanOverlay_.style.position = 'absolute'; + this.iePanOverlay_.style.backgroundColor = 'white'; + this.iePanOverlay_.style.filter = 'alpha(opacity=0)'; + this.iePanOverlay_.style.display = 'none'; + this.iePanOverlay_.style.cursor = 'move'; + this.fgcanvas_.appendChild(this.iePanOverlay_); +}; + +/** + * @private + * Creates the zoom handle elements. + */ +rangeSelector.prototype.createZoomHandles_ = function() { + var img = new Image(); + img.className = 'dygraph-rangesel-zoomhandle'; + img.style.position = 'absolute'; + img.style.zIndex = 10; + img.style.visibility = 'hidden'; // Initially hidden so they don't show up in the wrong place. + img.style.cursor = 'col-resize'; + + if (/MSIE 7/.test(navigator.userAgent)) { // IE7 doesn't support embedded src data. + img.width = 7; + img.height = 14; + img.style.backgroundColor = 'white'; + img.style.border = '1px solid #333333'; // Just show box in IE7. + } else { + img.width = 9; + img.height = 16; + img.src = 'data:image/png;base64,' + +'iVBORw0KGgoAAAANSUhEUgAAAAkAAAAQCAYAAADESFVDAAAAAXNSR0IArs4c6QAAAAZiS0dEANAA' + +'zwDP4Z7KegAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAAd0SU1FB9sHGw0cMqdt1UwAAAAZdEVYdENv' + +'bW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAaElEQVQoz+3SsRFAQBCF4Z9WJM8KCDVwownl' + +'6YXsTmCUsyKGkZzcl7zkz3YLkypgAnreFmDEpHkIwVOMfpdi9CEEN2nGpFdwD03yEqDtOgCaun7s' + +'qSTDH32I1pQA2Pb9sZecAxc5r3IAb21d6878xsAAAAAASUVORK5CYII='; + } + + if (this.isMobileDevice_) { + img.width *= 2; + img.height *= 2; + } + + this.leftZoomHandle_ = img; + this.rightZoomHandle_ = img.cloneNode(false); +}; + +/** + * @private + * Sets up the interaction for the range selector. + */ +rangeSelector.prototype.initInteraction_ = function() { + var self = this; + var topElem = document; + var clientXLast = 0; + var handle = null; + var isZooming = false; + var isPanning = false; + var dynamic = !this.isMobileDevice_ && !this.isUsingExcanvas_; + + // We cover iframes during mouse interactions. See comments in + // dygraph-utils.js for more info on why this is a good idea. + var tarp = new Dygraph.IFrameTarp(); + + // functions, defined below. Defining them this way (rather than with + // "function foo() {...}" makes JSHint happy. + var toXDataWindow, onZoomStart, onZoom, onZoomEnd, doZoom, isMouseInPanZone, + onPanStart, onPan, onPanEnd, doPan, onCanvasHover; + + // Touch event functions + var onZoomHandleTouchEvent, onCanvasTouchEvent, addTouchEvents; + + toXDataWindow = function(zoomHandleStatus) { + var xDataLimits = self.dygraph_.xAxisExtremes(); + var fact = (xDataLimits[1] - xDataLimits[0])/self.canvasRect_.w; + var xDataMin = xDataLimits[0] + (zoomHandleStatus.leftHandlePos - self.canvasRect_.x)*fact; + var xDataMax = xDataLimits[0] + (zoomHandleStatus.rightHandlePos - self.canvasRect_.x)*fact; + return [xDataMin, xDataMax]; + }; + + onZoomStart = function(e) { + Dygraph.cancelEvent(e); + isZooming = true; + clientXLast = e.clientX; + handle = e.target ? e.target : e.srcElement; + if (e.type === 'mousedown' || e.type === 'dragstart') { + // These events are removed manually. + Dygraph.addEvent(topElem, 'mousemove', onZoom); + Dygraph.addEvent(topElem, 'mouseup', onZoomEnd); + } + self.fgcanvas_.style.cursor = 'col-resize'; + tarp.cover(); + return true; + }; + + onZoom = function(e) { + if (!isZooming) { + return false; + } + Dygraph.cancelEvent(e); + + var delX = e.clientX - clientXLast; + if (Math.abs(delX) < 4) { + return true; + } + clientXLast = e.clientX; + + // Move handle. + var zoomHandleStatus = self.getZoomHandleStatus_(); + var newPos; + if (handle == self.leftZoomHandle_) { + newPos = zoomHandleStatus.leftHandlePos + delX; + newPos = Math.min(newPos, zoomHandleStatus.rightHandlePos - handle.width - 3); + newPos = Math.max(newPos, self.canvasRect_.x); + } else { + newPos = zoomHandleStatus.rightHandlePos + delX; + newPos = Math.min(newPos, self.canvasRect_.x + self.canvasRect_.w); + newPos = Math.max(newPos, zoomHandleStatus.leftHandlePos + handle.width + 3); + } + var halfHandleWidth = handle.width/2; + handle.style.left = (newPos - halfHandleWidth) + 'px'; + self.drawInteractiveLayer_(); + + // Zoom on the fly (if not using excanvas). + if (dynamic) { + doZoom(); + } + return true; + }; + + onZoomEnd = function(e) { + if (!isZooming) { + return false; + } + isZooming = false; + tarp.uncover(); + Dygraph.removeEvent(topElem, 'mousemove', onZoom); + Dygraph.removeEvent(topElem, 'mouseup', onZoomEnd); + self.fgcanvas_.style.cursor = 'default'; + + // If using excanvas, Zoom now. + if (!dynamic) { + doZoom(); + } + return true; + }; + + doZoom = function() { + try { + var zoomHandleStatus = self.getZoomHandleStatus_(); + self.isChangingRange_ = true; + if (!zoomHandleStatus.isZoomed) { + self.dygraph_.resetZoom(); + } else { + var xDataWindow = toXDataWindow(zoomHandleStatus); + self.dygraph_.doZoomXDates_(xDataWindow[0], xDataWindow[1]); + } + } finally { + self.isChangingRange_ = false; + } + }; + + isMouseInPanZone = function(e) { + if (self.isUsingExcanvas_) { + return e.srcElement == self.iePanOverlay_; + } else { + var rect = self.leftZoomHandle_.getBoundingClientRect(); + var leftHandleClientX = rect.left + rect.width/2; + rect = self.rightZoomHandle_.getBoundingClientRect(); + var rightHandleClientX = rect.left + rect.width/2; + return (e.clientX > leftHandleClientX && e.clientX < rightHandleClientX); + } + }; + + onPanStart = function(e) { + if (!isPanning && isMouseInPanZone(e) && self.getZoomHandleStatus_().isZoomed) { + Dygraph.cancelEvent(e); + isPanning = true; + clientXLast = e.clientX; + if (e.type === 'mousedown') { + // These events are removed manually. + Dygraph.addEvent(topElem, 'mousemove', onPan); + Dygraph.addEvent(topElem, 'mouseup', onPanEnd); + } + return true; + } + return false; + }; + + onPan = function(e) { + if (!isPanning) { + return false; + } + Dygraph.cancelEvent(e); + + var delX = e.clientX - clientXLast; + if (Math.abs(delX) < 4) { + return true; + } + clientXLast = e.clientX; + + // Move range view + var zoomHandleStatus = self.getZoomHandleStatus_(); + var leftHandlePos = zoomHandleStatus.leftHandlePos; + var rightHandlePos = zoomHandleStatus.rightHandlePos; + var rangeSize = rightHandlePos - leftHandlePos; + if (leftHandlePos + delX <= self.canvasRect_.x) { + leftHandlePos = self.canvasRect_.x; + rightHandlePos = leftHandlePos + rangeSize; + } else if (rightHandlePos + delX >= self.canvasRect_.x + self.canvasRect_.w) { + rightHandlePos = self.canvasRect_.x + self.canvasRect_.w; + leftHandlePos = rightHandlePos - rangeSize; + } else { + leftHandlePos += delX; + rightHandlePos += delX; + } + var halfHandleWidth = self.leftZoomHandle_.width/2; + self.leftZoomHandle_.style.left = (leftHandlePos - halfHandleWidth) + 'px'; + self.rightZoomHandle_.style.left = (rightHandlePos - halfHandleWidth) + 'px'; + self.drawInteractiveLayer_(); + + // Do pan on the fly (if not using excanvas). + if (dynamic) { + doPan(); + } + return true; + }; + + onPanEnd = function(e) { + if (!isPanning) { + return false; + } + isPanning = false; + Dygraph.removeEvent(topElem, 'mousemove', onPan); + Dygraph.removeEvent(topElem, 'mouseup', onPanEnd); + // If using excanvas, do pan now. + if (!dynamic) { + doPan(); + } + return true; + }; + + doPan = function() { + try { + self.isChangingRange_ = true; + self.dygraph_.dateWindow_ = toXDataWindow(self.getZoomHandleStatus_()); + self.dygraph_.drawGraph_(false); + } finally { + self.isChangingRange_ = false; + } + }; + + onCanvasHover = function(e) { + if (isZooming || isPanning) { + return; + } + var cursor = isMouseInPanZone(e) ? 'move' : 'default'; + if (cursor != self.fgcanvas_.style.cursor) { + self.fgcanvas_.style.cursor = cursor; + } + }; + + onZoomHandleTouchEvent = function(e) { + if (e.type == 'touchstart' && e.targetTouches.length == 1) { + if (onZoomStart(e.targetTouches[0])) { + Dygraph.cancelEvent(e); + } + } else if (e.type == 'touchmove' && e.targetTouches.length == 1) { + if (onZoom(e.targetTouches[0])) { + Dygraph.cancelEvent(e); + } + } else { + onZoomEnd(e); + } + }; + + onCanvasTouchEvent = function(e) { + if (e.type == 'touchstart' && e.targetTouches.length == 1) { + if (onPanStart(e.targetTouches[0])) { + Dygraph.cancelEvent(e); + } + } else if (e.type == 'touchmove' && e.targetTouches.length == 1) { + if (onPan(e.targetTouches[0])) { + Dygraph.cancelEvent(e); + } + } else { + onPanEnd(e); + } + }; + + addTouchEvents = function(elem, fn) { + var types = ['touchstart', 'touchend', 'touchmove', 'touchcancel']; + for (var i = 0; i < types.length; i++) { + self.dygraph_.addAndTrackEvent(elem, types[i], fn); + } + }; + + this.setDefaultOption_('interactionModel', Dygraph.Interaction.dragIsPanInteractionModel); + this.setDefaultOption_('panEdgeFraction', 0.0001); + + var dragStartEvent = window.opera ? 'mousedown' : 'dragstart'; + this.dygraph_.addAndTrackEvent(this.leftZoomHandle_, dragStartEvent, onZoomStart); + this.dygraph_.addAndTrackEvent(this.rightZoomHandle_, dragStartEvent, onZoomStart); + + if (this.isUsingExcanvas_) { + this.dygraph_.addAndTrackEvent(this.iePanOverlay_, 'mousedown', onPanStart); + } else { + this.dygraph_.addAndTrackEvent(this.fgcanvas_, 'mousedown', onPanStart); + this.dygraph_.addAndTrackEvent(this.fgcanvas_, 'mousemove', onCanvasHover); + } + + // Touch events + if (this.hasTouchInterface_) { + addTouchEvents(this.leftZoomHandle_, onZoomHandleTouchEvent); + addTouchEvents(this.rightZoomHandle_, onZoomHandleTouchEvent); + addTouchEvents(this.fgcanvas_, onCanvasTouchEvent); + } +}; + +/** + * @private + * Draws the static layer in the background canvas. + */ +rangeSelector.prototype.drawStaticLayer_ = function() { + var ctx = this.bgcanvas_ctx_; + ctx.clearRect(0, 0, this.canvasRect_.w, this.canvasRect_.h); + try { + this.drawMiniPlot_(); + } catch(ex) { + console.warn(ex); + } + + var margin = 0.5; + this.bgcanvas_ctx_.lineWidth = 1; + ctx.strokeStyle = 'gray'; + ctx.beginPath(); + ctx.moveTo(margin, margin); + ctx.lineTo(margin, this.canvasRect_.h-margin); + ctx.lineTo(this.canvasRect_.w-margin, this.canvasRect_.h-margin); + ctx.lineTo(this.canvasRect_.w-margin, margin); + ctx.stroke(); +}; + + +/** + * @private + * Draws the mini plot in the background canvas. + */ +rangeSelector.prototype.drawMiniPlot_ = function() { + var fillStyle = this.getOption_('rangeSelectorPlotFillColor'); + var strokeStyle = this.getOption_('rangeSelectorPlotStrokeColor'); + if (!fillStyle && !strokeStyle) { + return; + } + + var stepPlot = this.getOption_('stepPlot'); + + var combinedSeriesData = this.computeCombinedSeriesAndLimits_(); + var yRange = combinedSeriesData.yMax - combinedSeriesData.yMin; + + // Draw the mini plot. + var ctx = this.bgcanvas_ctx_; + var margin = 0.5; + + var xExtremes = this.dygraph_.xAxisExtremes(); + var xRange = Math.max(xExtremes[1] - xExtremes[0], 1.e-30); + var xFact = (this.canvasRect_.w - margin)/xRange; + var yFact = (this.canvasRect_.h - margin)/yRange; + 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] !== null) ? ((dataPoint[0] - xExtremes[0])*xFact) : NaN); + var y = ((dataPoint[1] !== null) ? (canvasHeight - (dataPoint[1] - combinedSeriesData.yMin)*yFact) : NaN); + + // Skip points that don't change the x-value. Overly fine-grained points + // can cause major slowdowns with the ctx.fill() call below. + if (!stepPlot && prevX !== null && Math.round(x) == Math.round(prevX)) { + continue; + } + + 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); + ctx.closePath(); + + if (fillStyle) { + var lingrad = this.bgcanvas_ctx_.createLinearGradient(0, 0, 0, canvasHeight); + lingrad.addColorStop(0, 'white'); + lingrad.addColorStop(1, fillStyle); + this.bgcanvas_ctx_.fillStyle = lingrad; + ctx.fill(); + } + + if (strokeStyle) { + this.bgcanvas_ctx_.strokeStyle = strokeStyle; + this.bgcanvas_ctx_.lineWidth = 1.5; + ctx.stroke(); + } +}; + +/** + * @private + * Computes and returns the combined series data along with min/max for the mini plot. + * The combined series consists of averaged values for all series. + * When series have error bars, the error bars are ignored. + * @return {Object} An object containing combined series array, ymin, ymax. + */ +rangeSelector.prototype.computeCombinedSeriesAndLimits_ = function() { + var g = this.dygraph_; + var logscale = this.getOption_('logscale'); + var i; + + // Select series to combine. By default, all series are combined. + var numColumns = g.numColumns(); + var labels = g.getLabels(); + var includeSeries = new Array(numColumns); + var anySet = false; + for (i = 1; i < numColumns; i++) { + var include = this.getOption_('showInRangeSelector', labels[i]); + includeSeries[i] = include; + if (include !== null) anySet = true; // it's set explicitly for this series + } + if (!anySet) { + for (i = 0; i < includeSeries.length; i++) includeSeries[i] = true; + } + + // Create a combined series (average of selected series values). + // TODO(danvk): short-circuit if there's only one series. + var rolledSeries = []; + var dataHandler = g.dataHandler_; + var options = g.attributes_; + for (i = 1; i < g.numColumns(); i++) { + if (!includeSeries[i]) continue; + var series = dataHandler.extractSeries(g.rawData_, i, options); + if (g.rollPeriod() > 1) { + series = dataHandler.rollingAverage(series, g.rollPeriod(), options); + } + + rolledSeries.push(series); + } + + var combinedSeries = []; + for (i = 0; i < rolledSeries[0].length; i++) { + var sum = 0; + var count = 0; + for (var j = 0; j < rolledSeries.length; j++) { + var y = rolledSeries[j][i][1]; + if (y === null || isNaN(y)) continue; + count++; + sum += y; + } + combinedSeries.push([rolledSeries[0][i][0], sum / count]); + } + + // Compute the y range. + var yMin = Number.MAX_VALUE; + var yMax = -Number.MAX_VALUE; + for (i = 0; i < combinedSeries.length; i++) { + var yVal = combinedSeries[i][1]; + if (yVal !== null && isFinite(yVal) && (!logscale || yVal > 0)) { + yMin = Math.min(yMin, yVal); + yMax = Math.max(yMax, yVal); + } + } + + // Convert Y data to log scale if needed. + // Also, expand the Y range to compress the mini plot a little. + var extraPercent = 0.25; + if (logscale) { + yMax = Dygraph.log10(yMax); + yMax += yMax*extraPercent; + yMin = Dygraph.log10(yMin); + for (i = 0; i < combinedSeries.length; i++) { + combinedSeries[i][1] = Dygraph.log10(combinedSeries[i][1]); + } + } else { + var yExtra; + var yRange = yMax - yMin; + if (yRange <= Number.MIN_VALUE) { + yExtra = yMax*extraPercent; + } else { + yExtra = yRange*extraPercent; + } + yMax += yExtra; + yMin -= yExtra; + } + + return {data: combinedSeries, yMin: yMin, yMax: yMax}; +}; + +/** + * @private + * Places the zoom handles in the proper position based on the current X data window. + */ +rangeSelector.prototype.placeZoomHandles_ = function() { + var xExtremes = this.dygraph_.xAxisExtremes(); + var xWindowLimits = this.dygraph_.xAxisRange(); + var xRange = xExtremes[1] - xExtremes[0]; + var leftPercent = Math.max(0, (xWindowLimits[0] - xExtremes[0])/xRange); + var rightPercent = Math.max(0, (xExtremes[1] - xWindowLimits[1])/xRange); + var leftCoord = this.canvasRect_.x + this.canvasRect_.w*leftPercent; + var rightCoord = this.canvasRect_.x + this.canvasRect_.w*(1 - rightPercent); + var handleTop = Math.max(this.canvasRect_.y, this.canvasRect_.y + (this.canvasRect_.h - this.leftZoomHandle_.height)/2); + var halfHandleWidth = this.leftZoomHandle_.width/2; + this.leftZoomHandle_.style.left = (leftCoord - halfHandleWidth) + 'px'; + this.leftZoomHandle_.style.top = handleTop + 'px'; + this.rightZoomHandle_.style.left = (rightCoord - halfHandleWidth) + 'px'; + this.rightZoomHandle_.style.top = this.leftZoomHandle_.style.top; + + this.leftZoomHandle_.style.visibility = 'visible'; + this.rightZoomHandle_.style.visibility = 'visible'; +}; + +/** + * @private + * Draws the interactive layer in the foreground canvas. + */ +rangeSelector.prototype.drawInteractiveLayer_ = function() { + var ctx = this.fgcanvas_ctx_; + ctx.clearRect(0, 0, this.canvasRect_.w, this.canvasRect_.h); + var margin = 1; + var width = this.canvasRect_.w - margin; + var height = this.canvasRect_.h - margin; + var zoomHandleStatus = this.getZoomHandleStatus_(); + + ctx.strokeStyle = 'black'; + if (!zoomHandleStatus.isZoomed) { + ctx.beginPath(); + ctx.moveTo(margin, margin); + ctx.lineTo(margin, height); + ctx.lineTo(width, height); + ctx.lineTo(width, margin); + ctx.stroke(); + if (this.iePanOverlay_) { + this.iePanOverlay_.style.display = 'none'; + } + } else { + var leftHandleCanvasPos = Math.max(margin, zoomHandleStatus.leftHandlePos - this.canvasRect_.x); + var rightHandleCanvasPos = Math.min(width, zoomHandleStatus.rightHandlePos - this.canvasRect_.x); + + ctx.fillStyle = 'rgba(240, 240, 240, 0.6)'; + ctx.fillRect(0, 0, leftHandleCanvasPos, this.canvasRect_.h); + ctx.fillRect(rightHandleCanvasPos, 0, this.canvasRect_.w - rightHandleCanvasPos, this.canvasRect_.h); + + ctx.beginPath(); + ctx.moveTo(margin, margin); + ctx.lineTo(leftHandleCanvasPos, margin); + ctx.lineTo(leftHandleCanvasPos, height); + ctx.lineTo(rightHandleCanvasPos, height); + ctx.lineTo(rightHandleCanvasPos, margin); + ctx.lineTo(width, margin); + ctx.stroke(); + + if (this.isUsingExcanvas_) { + this.iePanOverlay_.style.width = (rightHandleCanvasPos - leftHandleCanvasPos) + 'px'; + this.iePanOverlay_.style.left = leftHandleCanvasPos + 'px'; + this.iePanOverlay_.style.height = height + 'px'; + this.iePanOverlay_.style.display = 'inline'; + } + } +}; + +/** + * @private + * Returns the current zoom handle position information. + * @return {Object} The zoom handle status. + */ +rangeSelector.prototype.getZoomHandleStatus_ = function() { + var halfHandleWidth = this.leftZoomHandle_.width/2; + var leftHandlePos = parseFloat(this.leftZoomHandle_.style.left) + halfHandleWidth; + var rightHandlePos = parseFloat(this.rightZoomHandle_.style.left) + halfHandleWidth; + return { + leftHandlePos: leftHandlePos, + rightHandlePos: rightHandlePos, + isZoomed: (leftHandlePos - 1 > this.canvasRect_.x || rightHandlePos + 1 < this.canvasRect_.x+this.canvasRect_.w) + }; +}; + +return rangeSelector; + +})(); +/*global Dygraph:false */ + +// This file defines the ordering of the plugins. +// +// The ordering is from most-general to most-specific. +// This means that, in an event cascade, plugins which have registered for that +// event will be called in reverse order. +// +// This is most relevant for plugins which register a layout event, e.g. +// Axes, Legend and ChartLabels. + +Dygraph.PLUGINS.push( + Dygraph.Plugins.Legend, + Dygraph.Plugins.Axes, + Dygraph.Plugins.RangeSelector, // Has to be before ChartLabels so that its callbacks are called after ChartLabels' callbacks. + Dygraph.Plugins.ChartLabels, + Dygraph.Plugins.Annotations, + Dygraph.Plugins.Grid +); +/** + * @license + * Copyright 2011 Dan Vanderkam (danvdk@gmail.com) + * MIT-licensed (http://opensource.org/licenses/MIT) + */ + +// NOTE: in addition to parsing as JS, this snippet is expected to be valid +// JSON. This assumption cannot be checked in JS, but it will be checked when +// documentation is generated by the generate-documentation.py script. For the +// most part, this just means that you should always use double quotes. +Dygraph.OPTIONS_REFERENCE = // +{ + "xValueParser": { + "default": "parseFloat() or Date.parse()*", + "labels": ["CSV parsing"], + "type": "function(str) -> number", + "description": "A function which parses x-values (i.e. the dependent series). Must return a number, even when the values are dates. In this case, millis since epoch are used. This is used primarily for parsing CSV data. *=Dygraphs is slightly more accepting in the dates which it will parse. See code for details." + }, + "stackedGraph": { + "default": "false", + "labels": ["Data Line display"], + "type": "boolean", + "description": "If set, stack series on top of one another rather than drawing them independently. The first series specified in the input data will wind up on top of the chart and the last will be on bottom. NaN values are drawn as white areas without a line on top, see stackedGraphNaNFill for details." + }, + "stackedGraphNaNFill": { + "default": "all", + "labels": ["Data Line display"], + "type": "string", + "description": "Controls handling of NaN values inside a stacked graph. NaN values are interpolated/extended for stacking purposes, but the actual point value remains NaN in the legend display. Valid option values are \"all\" (interpolate internally, repeat leftmost and rightmost value as needed), \"inside\" (interpolate internally only, use zero outside leftmost and rightmost value), and \"none\" (treat NaN as zero everywhere)." + }, + "pointSize": { + "default": "1", + "labels": ["Data Line display"], + "type": "integer", + "description": "The size of the dot to draw on each point in pixels (see drawPoints). A dot is always drawn when a point is \"isolated\", i.e. there is a missing point on either side of it. This also controls the size of those dots." + }, + "labelsDivStyles": { + "default": "null", + "labels": ["Legend"], + "type": "{}", + "description": "Additional styles to apply to the currently-highlighted points div. For example, { 'fontWeight': 'bold' } will make the labels bold. In general, it is better to use CSS to style the .dygraph-legend class than to use this property." + }, + "drawPoints": { + "default": "false", + "labels": ["Data Line display"], + "type": "boolean", + "description": "Draw a small dot at each point, in addition to a line going through the point. This makes the individual data points easier to see, but can increase visual clutter in the chart. The small dot can be replaced with a custom rendering by supplying a drawPointCallback." + }, + "drawGapEdgePoints": { + "default": "false", + "labels": ["Data Line display"], + "type": "boolean", + "description": "Draw points at the edges of gaps in the data. This improves visibility of small data segments or other data irregularities." + }, + "drawPointCallback": { + "default": "null", + "labels": ["Data Line display"], + "type": "function(g, seriesName, canvasContext, cx, cy, color, pointSize)", + "parameters": [ + [ "g" , "the reference graph" ], + [ "seriesName" , "the name of the series" ], + [ "canvasContext" , "the canvas to draw on" ], + [ "cx" , "center x coordinate" ], + [ "cy" , "center y coordinate" ], + [ "color" , "series color" ], + [ "pointSize" , "the radius of the image." ], + [ "idx" , "the row-index of the point in the data."] + ], + "description": "Draw a custom item when drawPoints is enabled. Default is a small dot matching the series color. This method should constrain drawing to within pointSize pixels from (cx, cy). Also see drawHighlightPointCallback" + }, + "height": { + "default": "320", + "labels": ["Overall display"], + "type": "integer", + "description": "Height, in pixels, of the chart. If the container div has been explicitly sized, this will be ignored." + }, + "zoomCallback": { + "default": "null", + "labels": ["Callbacks"], + "type": "function(minDate, maxDate, yRanges)", + "parameters": [ + [ "minDate" , "milliseconds since epoch" ], + [ "maxDate" , "milliseconds since epoch." ], + [ "yRanges" , "is an array of [bottom, top] pairs, one for each y-axis." ] + ], + "description": "A function to call when the zoom window is changed (either by zooming in or out)." + }, + "pointClickCallback": { + "snippet": "function(e, point){
  alert(point);
}", + "default": "null", + "labels": ["Callbacks", "Interactive Elements"], + "type": "function(e, point)", + "parameters": [ + [ "e" , "the event object for the click" ], + [ "point" , "the point that was clicked See Point properties for details" ] + ], + "description": "A function to call when a data point is clicked. and the point that was clicked." + }, + "color": { + "default": "(see description)", + "labels": ["Data Series Colors"], + "type": "string", + "example": "red", + "description": "A per-series color definition. Used in conjunction with, and overrides, the colors option." + }, + "colors": { + "default": "(see description)", + "labels": ["Data Series Colors"], + "type": "array", + "example": "['red', '#00FF00']", + "description": "List of colors for the data series. These can be of the form \"#AABBCC\" or \"rgb(255,100,200)\" or \"yellow\", etc. If not specified, equally-spaced points around a color wheel are used. Overridden by the 'color' option." + }, + "connectSeparatedPoints": { + "default": "false", + "labels": ["Data Line display"], + "type": "boolean", + "description": "Usually, when Dygraphs encounters a missing value in a data series, it interprets this as a gap and draws it as such. If, instead, the missing values represents an x-value for which only a different series has data, then you'll want to connect the dots by setting this to true. To explicitly include a gap with this option set, use a value of NaN." + }, + "highlightCallback": { + "default": "null", + "labels": ["Callbacks"], + "type": "function(event, x, points, row, seriesName)", + "description": "When set, this callback gets called every time a new point is highlighted.", + "parameters": [ + ["event", "the JavaScript mousemove event"], + ["x", "the x-coordinate of the highlighted points"], + ["points", "an array of highlighted points: [ {name: 'series', yval: y-value}, … ]"], + ["row", "integer index of the highlighted row in the data table, starting from 0"], + ["seriesName", "name of the highlighted series, only present if highlightSeriesOpts is set."] + ] + }, + "drawHighlightPointCallback": { + "default": "null", + "labels": ["Data Line display"], + "type": "function(g, seriesName, canvasContext, cx, cy, color, pointSize)", + "parameters": [ + [ "g" , "the reference graph" ], + [ "seriesName" , "the name of the series" ], + [ "canvasContext" , "the canvas to draw on" ], + [ "cx" , "center x coordinate" ], + [ "cy" , "center y coordinate" ], + [ "color" , "series color" ], + [ "pointSize" , "the radius of the image." ], + [ "idx" , "the row-index of the point in the data."] + ], + "description": "Draw a custom item when a point is highlighted. Default is a small dot matching the series color. This method should constrain drawing to within pointSize pixels from (cx, cy) Also see drawPointCallback" + }, + "highlightSeriesOpts": { + "default": "null", + "labels": ["Interactive Elements"], + "type": "Object", + "description": "When set, the options from this object are applied to the timeseries closest to the mouse pointer for interactive highlighting. See also 'highlightCallback'. Example: highlightSeriesOpts: { strokeWidth: 3 }." + }, + "highlightSeriesBackgroundAlpha": { + "default": "0.5", + "labels": ["Interactive Elements"], + "type": "float", + "description": "Fade the background while highlighting series. 1=fully visible background (disable fading), 0=hiddden background (show highlighted series only)." + }, + "includeZero": { + "default": "false", + "labels": ["Axis display"], + "type": "boolean", + "description": "Usually, dygraphs will use the range of the data plus some padding to set the range of the y-axis. If this option is set, the y-axis will always include zero, typically as the lowest value. This can be used to avoid exaggerating the variance in the data" + }, + "rollPeriod": { + "default": "1", + "labels": ["Error Bars", "Rolling Averages"], + "type": "integer >= 1", + "description": "Number of days over which to average data. Discussed extensively above." + }, + "unhighlightCallback": { + "default": "null", + "labels": ["Callbacks"], + "type": "function(event)", + "parameters": [ + [ "event" , "the mouse event" ] + ], + "description": "When set, this callback gets called every time the user stops highlighting any point by mousing out of the graph." + }, + "axisTickSize": { + "default": "3.0", + "labels": ["Axis display"], + "type": "number", + "description": "The size of the line to display next to each tick mark on x- or y-axes." + }, + "labelsSeparateLines": { + "default": "false", + "labels": ["Legend"], + "type": "boolean", + "description": "Put <br/> between lines in the label string. Often used in conjunction with labelsDiv." + }, + "xValueFormatter": { + "default": "", + "labels": ["Deprecated"], + "type": "", + "description": "Prefer axes: { x: { valueFormatter } }" + }, + "valueFormatter": { + "default": "Depends on the type of your data.", + "labels": ["Legend", "Value display/formatting"], + "type": "function(num or millis, opts, seriesName, dygraph, row, col)", + "description": "Function to provide a custom display format for the values displayed on mouseover. This does not affect the values that appear on tick marks next to the axes. To format those, see axisLabelFormatter. This is usually set on a per-axis basis. .", + "parameters": [ + ["num_or_millis", "The value to be formatted. This is always a number. For date axes, it's millis since epoch. You can call new Date(millis) to get a Date object."], + ["opts", "This is a function you can call to access various options (e.g. opts('labelsKMB')). It returns per-axis values for the option when available."], + ["seriesName", "The name of the series from which the point came, e.g. 'X', 'Y', 'A', etc."], + ["dygraph", "The dygraph object for which the formatting is being done"], + ["row", "The row of the data from which this point comes. g.getValue(row, 0) will return the x-value for this point."], + ["col", "The column of the data from which this point comes. g.getValue(row, col) will return the original y-value for this point. This can be used to get the full confidence interval for the point, or access un-rolled values for the point."] + ] + }, + "pixelsPerYLabel": { + "default": "", + "labels": ["Deprecated"], + "type": "integer", + "description": "Prefer axes: { y: { pixelsPerLabel } }" + }, + "annotationMouseOverHandler": { + "default": "null", + "labels": ["Annotations"], + "type": "function(annotation, point, dygraph, event)", + "description": "If provided, this function is called whenever the user mouses over an annotation." + }, + "annotationMouseOutHandler": { + "default": "null", + "labels": ["Annotations"], + "type": "function(annotation, point, dygraph, event)", + "parameters": [ + [ "annotation" , "the annotation left" ], + [ "point" , "the point associated with the annotation" ], + [ "dygraph" , "the reference graph" ], + [ "event" , "the mouse event" ] + ], + "description": "If provided, this function is called whenever the user mouses out of an annotation." + }, + "annotationClickHandler": { + "default": "null", + "labels": ["Annotations"], + "type": "function(annotation, point, dygraph, event)", + "parameters": [ + [ "annotation" , "the annotation left" ], + [ "point" , "the point associated with the annotation" ], + [ "dygraph" , "the reference graph" ], + [ "event" , "the mouse event" ] + ], + "description": "If provided, this function is called whenever the user clicks on an annotation." + }, + "annotationDblClickHandler": { + "default": "null", + "labels": ["Annotations"], + "type": "function(annotation, point, dygraph, event)", + "parameters": [ + [ "annotation" , "the annotation left" ], + [ "point" , "the point associated with the annotation" ], + [ "dygraph" , "the reference graph" ], + [ "event" , "the mouse event" ] + ], + "description": "If provided, this function is called whenever the user double-clicks on an annotation." + }, + "drawCallback": { + "default": "null", + "labels": ["Callbacks"], + "type": "function(dygraph, is_initial)", + "parameters": [ + [ "dygraph" , "The graph being drawn" ], + [ "is_initial" , "True if this is the initial draw, false for subsequent draws." ] + ], + "description": "When set, this callback gets called every time the dygraph is drawn. This includes the initial draw, after zooming and repeatedly while panning." + }, + "labelsKMG2": { + "default": "false", + "labels": ["Value display/formatting"], + "type": "boolean", + "description": "Show k/M/G for kilo/Mega/Giga on y-axis. This is different than labelsKMB in that it uses base 2, not 10." + }, + "delimiter": { + "default": ",", + "labels": ["CSV parsing"], + "type": "string", + "description": "The delimiter to look for when separating fields of a CSV file. Setting this to a tab is not usually necessary, since tab-delimited data is auto-detected." + }, + "axisLabelFontSize": { + "default": "14", + "labels": ["Axis display"], + "type": "integer", + "description": "Size of the font (in pixels) to use in the axis labels, both x- and y-axis." + }, + "underlayCallback": { + "default": "null", + "labels": ["Callbacks"], + "type": "function(context, area, dygraph)", + "parameters": [ + [ "context" , "the canvas drawing context on which to draw" ], + [ "area" , "An object with {x,y,w,h} properties describing the drawing area." ], + [ "dygraph" , "the reference graph" ] + ], + "description": "When set, this callback gets called before the chart is drawn. It details on how to use this." + }, + "width": { + "default": "480", + "labels": ["Overall display"], + "type": "integer", + "description": "Width, in pixels, of the chart. If the container div has been explicitly sized, this will be ignored." + }, + "interactionModel": { + "default": "...", + "labels": ["Interactive Elements"], + "type": "Object", + "description": "TODO(konigsberg): document this" + }, + "ticker": { + "default": "Dygraph.dateTicker or Dygraph.numericTicks", + "labels": ["Axis display"], + "type": "function(min, max, pixels, opts, dygraph, vals) -> [{v: ..., label: ...}, ...]", + "parameters": [ + [ "min" , "" ], + [ "max" , "" ], + [ "pixels" , "" ], + [ "opts" , "" ], + [ "dygraph" , "the reference graph" ], + [ "vals" , "" ] + ], + "description": "This lets you specify an arbitrary function to generate tick marks on an axis. The tick marks are an array of (value, label) pairs. The built-in functions go to great lengths to choose good tick marks so, if you set this option, you'll most likely want to call one of them and modify the result. See dygraph-tickers.js for an extensive discussion. This is set on a per-axis basis." + }, + "xAxisLabelWidth": { + "default": "", + "labels": ["Deprecated"], + "type": "integer", + "description": "Prefer axes: { x: { axisLabelWidth } }" + }, + "xAxisHeight": { + "default": "(null)", + "labels": ["Axis display"], + "type": "integer", + "description": "Height, in pixels, of the x-axis. If not set explicitly, this is computed based on axisLabelFontSize and axisTickSize." + }, + "showLabelsOnHighlight": { + "default": "true", + "labels": ["Interactive Elements", "Legend"], + "type": "boolean", + "description": "Whether to show the legend upon mouseover." + }, + "axis": { + "default": "(none)", + "labels": ["Axis display"], + "type": "string", + "description": "Set to either 'y1' or 'y2' to assign a series to a y-axis (primary or secondary). Must be set per-series." + }, + "pixelsPerXLabel": { + "default": "", + "labels": ["Deprecated"], + "type": "integer", + "description": "Prefer axes { x: { pixelsPerLabel } }" + }, + "pixelsPerLabel": { + "default": "70 (x-axis) or 30 (y-axes)", + "labels": ["Axis display", "Grid"], + "type": "integer", + "description": "Number of pixels to require between each x- and y-label. Larger values will yield a sparser axis with fewer ticks. This is set on a per-axis basis." + }, + "labelsDiv": { + "default": "null", + "labels": ["Legend"], + "type": "DOM element or string", + "example": "document.getElementById('foo')or'foo'", + "description": "Show data labels in an external div, rather than on the graph. This value can either be a div element or a div id." + }, + "fractions": { + "default": "false", + "labels": ["CSV parsing", "Error Bars"], + "type": "boolean", + "description": "When set, attempt to parse each cell in the CSV file as \"a/b\", where a and b are integers. The ratio will be plotted. This allows computation of Wilson confidence intervals (see below)." + }, + "logscale": { + "default": "false", + "labels": ["Axis display"], + "type": "boolean", + "description": "When set for the y-axis or x-axis, the graph shows that axis in log scale. Any values less than or equal to zero are not displayed. Showing log scale with ranges that go below zero will result in an unviewable graph.\n\n Not compatible with showZero. connectSeparatedPoints is ignored. This is ignored for date-based x-axes." + }, + "strokeWidth": { + "default": "1.0", + "labels": ["Data Line display"], + "type": "float", + "example": "0.5, 2.0", + "description": "The width of the lines connecting data points. This can be used to increase the contrast or some graphs." + }, + "strokePattern": { + "default": "null", + "labels": ["Data Line display"], + "type": "array", + "example": "[10, 2, 5, 2]", + "description": "A custom pattern array where the even index is a draw and odd is a space in pixels. If null then it draws a solid line. The array should have a even length as any odd lengthed array could be expressed as a smaller even length array. This is used to create dashed lines." + }, + "strokeBorderWidth": { + "default": "null", + "labels": ["Data Line display"], + "type": "float", + "example": "1.0", + "description": "Draw a border around graph lines to make crossing lines more easily distinguishable. Useful for graphs with many lines." + }, + "strokeBorderColor": { + "default": "white", + "labels": ["Data Line display"], + "type": "string", + "example": "red, #ccffdd", + "description": "Color for the line border used if strokeBorderWidth is set." + }, + "wilsonInterval": { + "default": "true", + "labels": ["Error Bars"], + "type": "boolean", + "description": "Use in conjunction with the \"fractions\" option. Instead of plotting +/- N standard deviations, dygraphs will compute a Wilson confidence interval and plot that. This has more reasonable behavior for ratios close to 0 or 1." + }, + "fillGraph": { + "default": "false", + "labels": ["Data Line display"], + "type": "boolean", + "description": "Should the area underneath the graph be filled? This option is not compatible with error bars. This may be set on a per-series basis." + }, + "highlightCircleSize": { + "default": "3", + "labels": ["Interactive Elements"], + "type": "integer", + "description": "The size in pixels of the dot drawn over highlighted points." + }, + "gridLineColor": { + "default": "rgb(128,128,128)", + "labels": ["Grid"], + "type": "red, blue", + "description": "The color of the gridlines. This may be set on a per-axis basis to define each axis' grid separately." + }, + "gridLinePattern": { + "default": "null", + "labels": ["Grid"], + "type": "array", + "example": "[10, 2, 5, 2]", + "description": "A custom pattern array where the even index is a draw and odd is a space in pixels. If null then it draws a solid line. The array should have a even length as any odd lengthed array could be expressed as a smaller even length array. This is used to create dashed gridlines." + }, + "visibility": { + "default": "[true, true, ...]", + "labels": ["Data Line display"], + "type": "Array of booleans", + "description": "Which series should initially be visible? Once the Dygraph has been constructed, you can access and modify the visibility of each series using the visibility and setVisibility methods." + }, + "valueRange": { + "default": "Full range of the input is shown", + "labels": ["Axis display"], + "type": "Array of two numbers", + "example": "[10, 110]", + "description": "Explicitly set the vertical range of the graph to [low, high]. This may be set on a per-axis basis to define each y-axis separately. If either limit is unspecified, it will be calculated automatically (e.g. [null, 30] to automatically calculate just the lower bound)" + }, + "labelsDivWidth": { + "default": "250", + "labels": ["Legend"], + "type": "integer", + "description": "Width (in pixels) of the div which shows information on the currently-highlighted points." + }, + "colorSaturation": { + "default": "1.0", + "labels": ["Data Series Colors"], + "type": "float (0.0 - 1.0)", + "description": "If colors is not specified, saturation of the automatically-generated data series colors." + }, + "yAxisLabelWidth": { + "default": "", + "labels": ["Deprecated"], + "type": "integer", + "description": "Prefer axes { y: { axisLabelWidth } }" + }, + "hideOverlayOnMouseOut": { + "default": "true", + "labels": ["Interactive Elements", "Legend"], + "type": "boolean", + "description": "Whether to hide the legend when the mouse leaves the chart area." + }, + "yValueFormatter": { + "default": "", + "labels": ["Deprecated"], + "type": "", + "description": "Prefer axes: { y: { valueFormatter } }" + }, + "legend": { + "default": "onmouseover", + "labels": ["Legend"], + "type": "string", + "description": "When to display the legend. By default, it only appears when a user mouses over the chart. Set it to \"always\" to always display a legend of some sort. When set to \"follow\", legend follows highlighted points." + }, + "labelsShowZeroValues": { + "default": "true", + "labels": ["Legend"], + "type": "boolean", + "description": "Show zero value labels in the labelsDiv." + }, + "stepPlot": { + "default": "false", + "labels": ["Data Line display"], + "type": "boolean", + "description": "When set, display the graph as a step plot instead of a line plot. This option may either be set for the whole graph or for single series." + }, + "labelsUTC": { + "default": "false", + "labels": ["Value display/formatting", "Axis display"], + "type": "boolean", + "description": "Show date/time labels according to UTC (instead of local time)." + }, + "labelsKMB": { + "default": "false", + "labels": ["Value display/formatting"], + "type": "boolean", + "description": "Show K/M/B for thousands/millions/billions on y-axis." + }, + "rightGap": { + "default": "5", + "labels": ["Overall display"], + "type": "integer", + "description": "Number of pixels to leave blank at the right edge of the Dygraph. This makes it easier to highlight the right-most data point." + }, + "avoidMinZero": { + "default": "false", + "labels": ["Deprecated"], + "type": "boolean", + "description": "Deprecated, please use yRangePad instead. When set, the heuristic that fixes the Y axis at zero for a data set with the minimum Y value of zero is disabled. \nThis is particularly useful for data sets that contain many zero values, especially for step plots which may otherwise have lines not visible running along the bottom axis." + }, + "drawAxesAtZero": { + "default": "false", + "labels": ["Axis display"], + "type": "boolean", + "description": "When set, draw the X axis at the Y=0 position and the Y axis at the X=0 position if those positions are inside the graph's visible area. Otherwise, draw the axes at the bottom or left graph edge as usual." + }, + "xRangePad": { + "default": "0", + "labels": ["Axis display"], + "type": "float", + "description": "Add the specified amount of extra space (in pixels) around the X-axis value range to ensure points at the edges remain visible." + }, + "yRangePad": { + "default": "null", + "labels": ["Axis display"], + "type": "float", + "description": "If set, add the specified amount of extra space (in pixels) around the Y-axis value range to ensure points at the edges remain visible. If unset, use the traditional Y padding algorithm." + }, + "xAxisLabelFormatter": { + "default": "", + "labels": ["Deprecated"], + "type": "", + "description": "Prefer axes { x: { axisLabelFormatter } }" + }, + "axisLabelFormatter": { + "default": "Depends on the data type", + "labels": ["Axis display"], + "type": "function(number or Date, granularity, opts, dygraph)", + "parameters": [ + [ "number or date" , "Either a number (for a numeric axis) or a Date object (for a date axis)" ], + [ "granularity" , "specifies how fine-grained the axis is. For date axes, this is a reference to the time granularity enumeration, defined in dygraph-tickers.js, e.g. Dygraph.WEEKLY." ], + [ "opts" , "a function which provides access to various options on the dygraph, e.g. opts('labelsKMB')." ], + [ "dygraph" , "the referenced graph" ] + ], + "description": "Function to call to format the tick values that appear along an axis. This is usually set on a per-axis basis." + }, + "clickCallback": { + "snippet": "function(e, date_millis){
  alert(new Date(date_millis));
}", + "default": "null", + "labels": ["Callbacks"], + "type": "function(e, x, points)", + "parameters": [ + [ "e" , "The event object for the click" ], + [ "x" , "The x value that was clicked (for dates, this is milliseconds since epoch)" ], + [ "points" , "The closest points along that date. See Point properties for details." ] + ], + "description": "A function to call when the canvas is clicked." + }, + "yAxisLabelFormatter": { + "default": "", + "labels": ["Deprecated"], + "type": "", + "description": "Prefer axes: { y: { axisLabelFormatter } }" + }, + "labels": { + "default": "[\"X\", \"Y1\", \"Y2\", ...]*", + "labels": ["Legend"], + "type": "array", + "description": "A name for each data series, including the independent (X) series. For CSV files and DataTable objections, this is determined by context. For raw data, this must be specified. If it is not, default values are supplied and a warning is logged." + }, + "dateWindow": { + "default": "Full range of the input is shown", + "labels": ["Axis display"], + "type": "Array of two numbers", + "example": "[
  Date.parse('2006-01-01'),
  (new Date()).valueOf()
]", + "description": "Initially zoom in on a section of the graph. Is of the form [earliest, latest], where earliest/latest are milliseconds since epoch. If the data for the x-axis is numeric, the values in dateWindow must also be numbers." + }, + "showRoller": { + "default": "false", + "labels": ["Interactive Elements", "Rolling Averages"], + "type": "boolean", + "description": "If the rolling average period text box should be shown." + }, + "sigma": { + "default": "2.0", + "labels": ["Error Bars"], + "type": "float", + "description": "When errorBars is set, shade this many standard deviations above/below each point." + }, + "customBars": { + "default": "false", + "labels": ["CSV parsing", "Error Bars"], + "type": "boolean", + "description": "When set, parse each CSV cell as \"low;middle;high\". Error bars will be drawn for each point between low and high, with the series itself going through middle." + }, + "colorValue": { + "default": "1.0", + "labels": ["Data Series Colors"], + "type": "float (0.0 - 1.0)", + "description": "If colors is not specified, value of the data series colors, as in hue/saturation/value. (0.0-1.0, default 0.5)" + }, + "errorBars": { + "default": "false", + "labels": ["CSV parsing", "Error Bars"], + "type": "boolean", + "description": "Does the data contain standard deviations? Setting this to true alters the input format (see above)." + }, + "displayAnnotations": { + "default": "false", + "labels": ["Annotations"], + "type": "boolean", + "description": "Only applies when Dygraphs is used as a GViz chart. Causes string columns following a data series to be interpreted as annotations on points in that series. This is the same format used by Google's AnnotatedTimeLine chart." + }, + "panEdgeFraction": { + "default": "null", + "labels": ["Axis display", "Interactive Elements"], + "type": "float", + "description": "A value representing the farthest a graph may be panned, in percent of the display. For example, a value of 0.1 means that the graph can only be panned 10% pased the edges of the displayed values. null means no bounds." + }, + "title": { + "labels": ["Chart labels"], + "type": "string", + "default": "null", + "description": "Text to display above the chart. You can supply any HTML for this value, not just text. If you wish to style it using CSS, use the 'dygraph-label' or 'dygraph-title' classes." + }, + "titleHeight": { + "default": "18", + "labels": ["Chart labels"], + "type": "integer", + "description": "Height of the chart title, in pixels. This also controls the default font size of the title. If you style the title on your own, this controls how much space is set aside above the chart for the title's div." + }, + "xlabel": { + "labels": ["Chart labels"], + "type": "string", + "default": "null", + "description": "Text to display below the chart's x-axis. You can supply any HTML for this value, not just text. If you wish to style it using CSS, use the 'dygraph-label' or 'dygraph-xlabel' classes." + }, + "xLabelHeight": { + "labels": ["Chart labels"], + "type": "integer", + "default": "18", + "description": "Height of the x-axis label, in pixels. This also controls the default font size of the x-axis label. If you style the label on your own, this controls how much space is set aside below the chart for the x-axis label's div." + }, + "ylabel": { + "labels": ["Chart labels"], + "type": "string", + "default": "null", + "description": "Text to display to the left of the chart's y-axis. You can supply any HTML for this value, not just text. If you wish to style it using CSS, use the 'dygraph-label' or 'dygraph-ylabel' classes. The text will be rotated 90 degrees by default, so CSS rules may behave in unintuitive ways. No additional space is set aside for a y-axis label. If you need more space, increase the width of the y-axis tick labels using the yAxisLabelWidth option. If you need a wider div for the y-axis label, either style it that way with CSS (but remember that it's rotated, so width is controlled by the 'height' property) or set the yLabelWidth option." + }, + "y2label": { + "labels": ["Chart labels"], + "type": "string", + "default": "null", + "description": "Text to display to the right of the chart's secondary y-axis. This label is only displayed if a secondary y-axis is present. See this test for an example of how to do this. The comments for the 'ylabel' option generally apply here as well. This label gets a 'dygraph-y2label' instead of a 'dygraph-ylabel' class." + }, + "yLabelWidth": { + "labels": ["Chart labels"], + "type": "integer", + "default": "18", + "description": "Width of the div which contains the y-axis label. Since the y-axis label appears rotated 90 degrees, this actually affects the height of its div." + }, + "isZoomedIgnoreProgrammaticZoom" : { + "default": "false", + "labels": ["Zooming"], + "type": "boolean", + "description" : "When this option is passed to updateOptions() along with either the dateWindow or valueRange options, the zoom flags are not changed to reflect a zoomed state. This is primarily useful for when the display area of a chart is changed programmatically and also where manual zooming is allowed and use is made of the isZoomed method to determine this." + }, + "drawXGrid": { + "default": "true", + "labels": ["Grid","Deprecated"], + "type": "boolean", + "description" : "Use the per-axis option drawGrid instead. Whether to display vertical gridlines under the chart." + }, + "drawYGrid": { + "default": "true", + "labels": ["Grid","Deprecated"], + "type": "boolean", + "description" : "Use the per-axis option drawGrid instead. Whether to display horizontal gridlines under the chart." + }, + "drawGrid": { + "default": "true for x and y, false for y2", + "labels": ["Grid"], + "type": "boolean", + "description" : "Whether to display gridlines in the chart. This may be set on a per-axis basis to define the visibility of each axis' grid separately." + }, + "independentTicks": { + "default": "true for y, false for y2", + "labels": ["Axis display", "Grid"], + "type": "boolean", + "description" : "Only valid for y and y2, has no effect on x: This option defines whether the y axes should align their ticks or if they should be independent. Possible combinations: 1.) y=true, y2=false (default): y is the primary axis and the y2 ticks are aligned to the the ones of y. (only 1 grid) 2.) y=false, y2=true: y2 is the primary axis and the y ticks are aligned to the the ones of y2. (only 1 grid) 3.) y=true, y2=true: Both axis are independent and have their own ticks. (2 grids) 4.) y=false, y2=false: Invalid configuration causes an error." + }, + "drawXAxis": { + "default": "true", + "labels": ["Axis display"], + "type": "boolean", + "description" : "Deprecated. Use axes : { x : { drawAxis } }." + }, + "drawYAxis": { + "default": "true", + "labels": ["Axis display"], + "type": "boolean", + "description" : "Deprecated. Use axes : { y : { drawAxis } }." + }, + "drawAxis": { + "default": "true for x and y, false for y2", + "labels": ["Axis display"], + "type": "boolean", + "description" : "Whether to draw the specified axis. This may be set on a per-axis basis to define the visibility of each axis separately. Setting this to false also prevents axis ticks from being drawn and reclaims the space for the chart grid/lines." + }, + "gridLineWidth": { + "default": "0.3", + "labels": ["Grid"], + "type": "float", + "description" : "Thickness (in pixels) of the gridlines drawn under the chart. The vertical/horizontal gridlines can be turned off entirely by using the drawXGrid and drawYGrid options. This may be set on a per-axis basis to define each axis' grid separately." + }, + "axisLineWidth": { + "default": "0.3", + "labels": ["Axis display"], + "type": "float", + "description" : "Thickness (in pixels) of the x- and y-axis lines." + }, + "axisLineColor": { + "default": "black", + "labels": ["Axis display"], + "type": "string", + "description" : "Color of the x- and y-axis lines. Accepts any value which the HTML canvas strokeStyle attribute understands, e.g. 'black' or 'rgb(0, 100, 255)'." + }, + "fillAlpha": { + "default": "0.15", + "labels": ["Error Bars", "Data Series Colors"], + "type": "float (0.0 - 1.0)", + "description" : "Error bars (or custom bars) for each series are drawn in the same color as the series, but with partial transparency. This sets the transparency. A value of 0.0 means that the error bars will not be drawn, whereas a value of 1.0 means that the error bars will be as dark as the line for the series itself. This can be used to produce chart lines whose thickness varies at each point." + }, + "axisLabelColor": { + "default": "black", + "labels": ["Axis display"], + "type": "string", + "description" : "Color for x- and y-axis labels. This is a CSS color string." + }, + "axisLabelWidth": { + "default": "50 (y-axis), 60 (x-axis)", + "labels": ["Axis display", "Chart labels"], + "type": "integer", + "description" : "Width (in pixels) of the containing divs for x- and y-axis labels. For the y-axis, this also controls the width of the y-axis. Note that for the x-axis, this is independent from pixelsPerLabel, which controls the spacing between labels." + }, + "sigFigs" : { + "default": "null", + "labels": ["Value display/formatting"], + "type": "integer", + "description": "By default, dygraphs displays numbers with a fixed number of digits after the decimal point. If you'd prefer to have a fixed number of significant figures, set this option to that number of sig figs. A value of 2, for instance, would cause 1 to be display as 1.0 and 1234 to be displayed as 1.23e+3." + }, + "digitsAfterDecimal" : { + "default": "2", + "labels": ["Value display/formatting"], + "type": "integer", + "description": "Unless it's run in scientific mode (see the sigFigs option), dygraphs displays numbers with digitsAfterDecimal digits after the decimal point. Trailing zeros are not displayed, so with a value of 2 you'll get '0', '0.1', '0.12', '123.45' but not '123.456' (it will be rounded to '123.46'). Numbers with absolute value less than 0.1^digitsAfterDecimal (i.e. those which would show up as '0.00') will be displayed in scientific notation." + }, + "maxNumberWidth" : { + "default": "6", + "labels": ["Value display/formatting"], + "type": "integer", + "description": "When displaying numbers in normal (not scientific) mode, large numbers will be displayed with many trailing zeros (e.g. 100000000 instead of 1e9). This can lead to unwieldy y-axis labels. If there are more than maxNumberWidth digits to the left of the decimal in a number, dygraphs will switch to scientific notation, even when not operating in scientific mode. If you'd like to see all those digits, set this to something large, like 20 or 30." + }, + "file": { + "default": "(set when constructed)", + "labels": ["Data"], + "type": "string (URL of CSV or CSV), GViz DataTable or 2D Array", + "description": "Sets the data being displayed in the chart. This can only be set when calling updateOptions; it cannot be set from the constructor. For a full description of valid data formats, see the Data Formats page." + }, + "timingName": { + "default": "null", + "labels": [ "Debugging" ], + "type": "string", + "description": "Set this option to log timing information. The value of the option will be logged along with the timimg, so that you can distinguish multiple dygraphs on the same page." + }, + "showRangeSelector": { + "default": "false", + "labels": ["Interactive Elements"], + "type": "boolean", + "description": "Show or hide the range selector widget." + }, + "rangeSelectorHeight": { + "default": "40", + "labels": ["Interactive Elements"], + "type": "integer", + "description": "Height, in pixels, of the range selector widget. This option can only be specified at Dygraph creation time." + }, + "rangeSelectorPlotStrokeColor": { + "default": "#808FAB", + "labels": ["Interactive Elements"], + "type": "string", + "description": "The range selector mini plot stroke color. This can be of the form \"#AABBCC\" or \"rgb(255,100,200)\" or \"yellow\". You can also specify null or \"\" to turn off stroke." + }, + "rangeSelectorPlotFillColor": { + "default": "#A7B1C4", + "labels": ["Interactive Elements"], + "type": "string", + "description": "The range selector mini plot fill color. This can be of the form \"#AABBCC\" or \"rgb(255,100,200)\" or \"yellow\". You can also specify null or \"\" to turn off fill." + }, + "showInRangeSelector": { + "default": "null", + "labels": ["Interactive Elements"], + "type": "boolean", + "description": "Mark this series for inclusion in the range selector. The mini plot curve will be an average of all such series. If this is not specified for any series, the default behavior is to average all the series. Setting it for one series will result in that series being charted alone in the range selector." + }, + "animatedZooms": { + "default": "false", + "labels": ["Interactive Elements"], + "type": "boolean", + "description": "Set this option to animate the transition between zoom windows. Applies to programmatic and interactive zooms. Note that if you also set a drawCallback, it will be called several times on each zoom. If you set a zoomCallback, it will only be called after the animation is complete." + }, + "plotter": { + "default": "[DygraphCanvasRenderer.Plotters.fillPlotter, DygraphCanvasRenderer.Plotters.errorPlotter, DygraphCanvasRenderer.Plotters.linePlotter]", + "labels": ["Data Line display"], + "type": "array or function", + "description": "A function (or array of functions) which plot each data series on the chart. TODO(danvk): more details! May be set per-series." + }, + "axes": { + "default": "null", + "labels": ["Configuration"], + "type": "Object", + "description": "Defines per-axis options. Valid keys are 'x', 'y' and 'y2'. Only some options may be set on a per-axis basis. If an option may be set in this way, it will be noted on this page. See also documentation on per-series and per-axis options." + }, + "series": { + "default": "null", + "labels": ["Series"], + "type": "Object", + "description": "Defines per-series options. Its keys match the y-axis label names, and the values are dictionaries themselves that contain options specific to that series. When this option is missing, it falls back on the old-style of per-series options comingled with global options." + }, + "plugins": { + "default": "[]", + "labels": ["Configuration"], + "type": "Array", + "description": "Defines per-graph plugins. Useful for per-graph customization" + }, + "dataHandler": { + "default": "(depends on data)", + "labels": ["Data"], + "type": "Dygraph.DataHandler", + "description": "Custom DataHandler. This is an advanced customization. See http://bit.ly/151E7Aq." + } +} +; //
+// NOTE: in addition to parsing as JS, this snippet is expected to be valid +// JSON. This assumption cannot be checked in JS, but it will be checked when +// documentation is generated by the generate-documentation.py script. For the +// most part, this just means that you should always use double quotes. + +// Do a quick sanity check on the options reference. +(function() { + "use strict"; + var warn = function(msg) { if (window.console) window.console.warn(msg); }; + var flds = ['type', 'default', 'description']; + var valid_cats = [ + 'Annotations', + 'Axis display', + 'Chart labels', + 'CSV parsing', + 'Callbacks', + 'Data', + 'Data Line display', + 'Data Series Colors', + 'Error Bars', + 'Grid', + 'Interactive Elements', + 'Legend', + 'Overall display', + 'Rolling Averages', + 'Series', + 'Value display/formatting', + 'Zooming', + 'Debugging', + 'Configuration', + 'Deprecated' + ]; + var i; + var cats = {}; + for (i = 0; i < valid_cats.length; i++) cats[valid_cats[i]] = true; + + for (var k in Dygraph.OPTIONS_REFERENCE) { + if (!Dygraph.OPTIONS_REFERENCE.hasOwnProperty(k)) continue; + var op = Dygraph.OPTIONS_REFERENCE[k]; + for (i = 0; i < flds.length; i++) { + if (!op.hasOwnProperty(flds[i])) { + warn('Option ' + k + ' missing "' + flds[i] + '" property'); + } else if (typeof(op[flds[i]]) != 'string') { + warn(k + '.' + flds[i] + ' must be of type string'); + } + } + var labels = op.labels; + if (typeof(labels) !== 'object') { + warn('Option "' + k + '" is missing a "labels": [...] option'); + } else { + for (i = 0; i < labels.length; i++) { + if (!cats.hasOwnProperty(labels[i])) { + warn('Option "' + k + '" has label "' + labels[i] + + '", which is invalid.'); + } + } + } + } +})(); +/** + * @license + * Copyright 2013 David Eberlein (david.eberlein@ch.sauter-bc.com) + * MIT-licensed (http://opensource.org/licenses/MIT) + */ + +/** + * @fileoverview This file contains the managment of data handlers + * @author David Eberlein (david.eberlein@ch.sauter-bc.com) + * + * The idea is to define a common, generic data format that works for all data + * structures supported by dygraphs. To make this possible, the DataHandler + * interface is introduced. This makes it possible, that dygraph itself can work + * with the same logic for every data type independent of the actual format and + * the DataHandler takes care of the data format specific jobs. + * DataHandlers are implemented for all data types supported by Dygraphs and + * return Dygraphs compliant formats. + * By default the correct DataHandler is chosen based on the options set. + * Optionally the user may use his own DataHandler (similar to the plugin + * system). + * + * + * The unified data format returend by each handler is defined as so: + * series[n][point] = [x,y,(extras)] + * + * This format contains the common basis that is needed to draw a simple line + * series extended by optional extras for more complex graphing types. It + * contains a primitive x value as first array entry, a primitive y value as + * second array entry and an optional extras object for additional data needed. + * + * x must always be a number. + * y must always be a number, NaN of type number or null. + * extras is optional and must be interpreted by the DataHandler. It may be of + * any type. + * + * In practice this might look something like this: + * default: [x, yVal] + * errorBar / customBar: [x, yVal, [yTopVariance, yBottomVariance] ] + * + */ +/*global Dygraph:false */ +/*global DygraphLayout:false */ + +/** + * + * The data handler is responsible for all data specific operations. All of the + * series data it receives and returns is always in the unified data format. + * Initially the unified data is created by the extractSeries method + * @constructor + */ +Dygraph.DataHandler = function () { +}; + +/** + * A collection of functions to create and retrieve data handlers. + * @type {Object.} + */ +Dygraph.DataHandlers = {}; + +(function() { + +"use strict"; + +var handler = Dygraph.DataHandler; + +/** + * X-value array index constant for unified data samples. + * @const + * @type {number} + */ +handler.X = 0; + +/** + * Y-value array index constant for unified data samples. + * @const + * @type {number} + */ +handler.Y = 1; + +/** + * Extras-value array index constant for unified data samples. + * @const + * @type {number} + */ +handler.EXTRAS = 2; + +/** + * Extracts one series from the raw data (a 2D array) into an array of the + * unified data format. + * This is where undesirable points (i.e. negative values on log scales and + * missing values through which we wish to connect lines) are dropped. + * TODO(danvk): the "missing values" bit above doesn't seem right. + * + * @param {!Array.} rawData The raw data passed into dygraphs where + * rawData[i] = [x,ySeries1,...,ySeriesN]. + * @param {!number} seriesIndex Index of the series to extract. All other + * series should be ignored. + * @param {!DygraphOptions} options Dygraph options. + * @return {Array.<[!number,?number,?]>} The series in the unified data format + * where series[i] = [x,y,{extras}]. + */ +handler.prototype.extractSeries = function(rawData, seriesIndex, options) { +}; + +/** + * Converts a series to a Point array. The resulting point array must be + * returned in increasing order of idx property. + * + * @param {!Array.<[!number,?number,?]>} series The series in the unified + * data format where series[i] = [x,y,{extras}]. + * @param {!string} setName Name of the series. + * @param {!number} boundaryIdStart Index offset of the first point, equal to the + * number of skipped points left of the date window minimum (if any). + * @return {!Array.} List of points for this series. + */ +handler.prototype.seriesToPoints = function(series, setName, boundaryIdStart) { + // TODO(bhs): these loops are a hot-spot for high-point-count charts. In + // fact, + // on chrome+linux, they are 6 times more expensive than iterating through + // the + // points and drawing the lines. The brunt of the cost comes from allocating + // the |point| structures. + var points = []; + for ( var i = 0; i < series.length; ++i) { + var item = series[i]; + var yraw = item[1]; + var yval = yraw === null ? null : handler.parseFloat(yraw); + var point = { + x : NaN, + y : NaN, + xval : handler.parseFloat(item[0]), + yval : yval, + name : setName, // TODO(danvk): is this really necessary? + idx : i + boundaryIdStart + }; + points.push(point); + } + this.onPointsCreated_(series, points); + return points; +}; + +/** + * Callback called for each series after the series points have been generated + * which will later be used by the plotters to draw the graph. + * Here data may be added to the seriesPoints which is needed by the plotters. + * The indexes of series and points are in sync meaning the original data + * sample for series[i] is points[i]. + * + * @param {!Array.<[!number,?number,?]>} series The series in the unified + * data format where series[i] = [x,y,{extras}]. + * @param {!Array.} points The corresponding points passed + * to the plotter. + * @protected + */ +handler.prototype.onPointsCreated_ = function(series, points) { +}; + +/** + * Calculates the rolling average of a data set. + * + * @param {!Array.<[!number,?number,?]>} series The series in the unified + * data format where series[i] = [x,y,{extras}]. + * @param {!number} rollPeriod The number of points over which to average the data + * @param {!DygraphOptions} options The dygraph options. + * @return {!Array.<[!number,?number,?]>} the rolled series. + */ +handler.prototype.rollingAverage = function(series, rollPeriod, options) { +}; + +/** + * Computes the range of the data series (including confidence intervals). + * + * @param {!Array.<[!number,?number,?]>} series The series in the unified + * data format where series[i] = [x, y, {extras}]. + * @param {!Array.} dateWindow The x-value range to display with + * the format: [min, max]. + * @param {!DygraphOptions} options The dygraph options. + * @return {Array.} The low and high extremes of the series in the + * given window with the format: [low, high]. + */ +handler.prototype.getExtremeYValues = function(series, dateWindow, options) { +}; + +/** + * Callback called for each series after the layouting data has been + * calculated before the series is drawn. Here normalized positioning data + * should be calculated for the extras of each point. + * + * @param {!Array.} points The points passed to + * the plotter. + * @param {!Object} axis The axis on which the series will be plotted. + * @param {!boolean} logscale Weather or not to use a logscale. + */ +handler.prototype.onLineEvaluated = function(points, axis, logscale) { +}; + +/** + * Helper method that computes the y value of a line defined by the points p1 + * and p2 and a given x value. + * + * @param {!Array.} p1 left point ([x,y]). + * @param {!Array.} p2 right point ([x,y]). + * @param {!number} xValue The x value to compute the y-intersection for. + * @return {number} corresponding y value to x on the line defined by p1 and p2. + * @private + */ +handler.prototype.computeYInterpolation_ = function(p1, p2, xValue) { + var deltaY = p2[1] - p1[1]; + var deltaX = p2[0] - p1[0]; + var gradient = deltaY / deltaX; + var growth = (xValue - p1[0]) * gradient; + return p1[1] + growth; +}; + +/** + * Helper method that returns the first and the last index of the given series + * that lie inside the given dateWindow. + * + * @param {!Array.<[!number,?number,?]>} series The series in the unified + * data format where series[i] = [x,y,{extras}]. + * @param {!Array.} dateWindow The x-value range to display with + * the format: [min,max]. + * @return {!Array.<[!number,?number,?]>} The samples of the series that + * are in the given date window. + * @private + */ +handler.prototype.getIndexesInWindow_ = function(series, dateWindow) { + var firstIdx = 0, lastIdx = series.length - 1; + if (dateWindow) { + var idx = 0; + var low = dateWindow[0]; + var high = dateWindow[1]; + + // Start from each side of the array to minimize the performance + // needed. + while (idx < series.length - 1 && series[idx][0] < low) { + firstIdx++; + idx++; + } + idx = series.length - 1; + while (idx > 0 && series[idx][0] > high) { + lastIdx--; + idx--; + } + } + if (firstIdx <= lastIdx) { + return [ firstIdx, lastIdx ]; + } else { + return [ 0, series.length - 1 ]; + } +}; + +/** + * Optimized replacement for parseFloat, which was way too slow when almost + * all values were type number, with few edge cases, none of which were strings. + * @param {?number} val + * @return {number} + * @protected + */ +handler.parseFloat = function(val) { + // parseFloat(null) is NaN + if (val === null) { + return NaN; + } + + // Assume it's a number or NaN. If it's something else, I'll be shocked. + return val; +}; + +})(); +/** + * @license + * Copyright 2013 David Eberlein (david.eberlein@ch.sauter-bc.com) + * MIT-licensed (http://opensource.org/licenses/MIT) + */ + +/** + * @fileoverview DataHandler default implementation used for simple line charts. + * @author David Eberlein (david.eberlein@ch.sauter-bc.com) + */ + +(function() { + +/*global Dygraph:false */ +"use strict"; + +/** + * @constructor + * @extends Dygraph.DataHandler + */ +Dygraph.DataHandlers.DefaultHandler = function() { +}; + +var DefaultHandler = Dygraph.DataHandlers.DefaultHandler; +DefaultHandler.prototype = new Dygraph.DataHandler(); + +/** @inheritDoc */ +DefaultHandler.prototype.extractSeries = function(rawData, i, options) { + // TODO(danvk): pre-allocate series here. + var series = []; + var logScale = options.get('logscale'); + for ( var j = 0; j < rawData.length; j++) { + var x = rawData[j][0]; + var point = rawData[j][i]; + if (logScale) { + // On the log scale, points less than zero do not exist. + // This will create a gap in the chart. + if (point <= 0) { + point = null; + } + } + series.push([ x, point ]); + } + return series; +}; + +/** @inheritDoc */ +DefaultHandler.prototype.rollingAverage = function(originalData, rollPeriod, + options) { + rollPeriod = Math.min(rollPeriod, originalData.length); + var rollingData = []; + + var i, j, y, sum, num_ok; + // Calculate the rolling average for the first rollPeriod - 1 points + // where + // there is not enough data to roll over the full number of points + if (rollPeriod == 1) { + return originalData; + } + for (i = 0; i < originalData.length; i++) { + sum = 0; + num_ok = 0; + for (j = Math.max(0, i - rollPeriod + 1); j < i + 1; j++) { + y = originalData[j][1]; + if (y === null || isNaN(y)) + continue; + num_ok++; + sum += originalData[j][1]; + } + if (num_ok) { + rollingData[i] = [ originalData[i][0], sum / num_ok ]; + } else { + rollingData[i] = [ originalData[i][0], null ]; + } + } + + return rollingData; +}; + +/** @inheritDoc */ +DefaultHandler.prototype.getExtremeYValues = function(series, dateWindow, + options) { + var minY = null, maxY = null, y; + var firstIdx = 0, lastIdx = series.length - 1; + + for ( var j = firstIdx; j <= lastIdx; j++) { + y = series[j][1]; + if (y === null || isNaN(y)) + continue; + if (maxY === null || y > maxY) { + maxY = y; + } + if (minY === null || y < minY) { + minY = y; + } + } + return [ minY, maxY ]; +}; + +})(); +/** + * @license + * Copyright 2013 David Eberlein (david.eberlein@ch.sauter-bc.com) + * MIT-licensed (http://opensource.org/licenses/MIT) + */ + +/** + * @fileoverview DataHandler implementation for the fractions option. + * @author David Eberlein (david.eberlein@ch.sauter-bc.com) + */ + +(function() { + +/*global Dygraph:false */ +"use strict"; + +/** + * @extends Dygraph.DataHandlers.DefaultHandler + * @constructor + */ +Dygraph.DataHandlers.DefaultFractionHandler = function() { +}; + +var DefaultFractionHandler = Dygraph.DataHandlers.DefaultFractionHandler; +DefaultFractionHandler.prototype = new Dygraph.DataHandlers.DefaultHandler(); + +DefaultFractionHandler.prototype.extractSeries = function(rawData, i, options) { + // TODO(danvk): pre-allocate series here. + var series = []; + var x, y, point, num, den, value; + var mult = 100.0; + var logScale = options.get('logscale'); + for ( var j = 0; j < rawData.length; j++) { + x = rawData[j][0]; + point = rawData[j][i]; + if (logScale && point !== null) { + // On the log scale, points less than zero do not exist. + // This will create a gap in the chart. + if (point[0] <= 0 || point[1] <= 0) { + point = null; + } + } + // Extract to the unified data format. + if (point !== null) { + num = point[0]; + den = point[1]; + if (num !== null && !isNaN(num)) { + value = den ? num / den : 0.0; + y = mult * value; + // preserve original values in extras for further filtering + series.push([ x, y, [ num, den ] ]); + } else { + series.push([ x, num, [ num, den ] ]); + } + } else { + series.push([ x, null, [ null, null ] ]); + } + } + return series; +}; + +DefaultFractionHandler.prototype.rollingAverage = function(originalData, rollPeriod, + options) { + rollPeriod = Math.min(rollPeriod, originalData.length); + var rollingData = []; + + var i; + var num = 0; + var den = 0; // numerator/denominator + var mult = 100.0; + for (i = 0; i < originalData.length; i++) { + num += originalData[i][2][0]; + den += originalData[i][2][1]; + if (i - rollPeriod >= 0) { + num -= originalData[i - rollPeriod][2][0]; + den -= originalData[i - rollPeriod][2][1]; + } + + var date = originalData[i][0]; + var value = den ? num / den : 0.0; + rollingData[i] = [ date, mult * value ]; + } + + return rollingData; +}; + +})(); +/** + * @license + * Copyright 2013 David Eberlein (david.eberlein@ch.sauter-bc.com) + * MIT-licensed (http://opensource.org/licenses/MIT) + */ + +/** + * @fileoverview DataHandler base implementation for the "bar" + * data formats. This implementation must be extended and the + * extractSeries and rollingAverage must be implemented. + * @author David Eberlein (david.eberlein@ch.sauter-bc.com) + */ + +(function() { + +/*global Dygraph:false */ +/*global DygraphLayout:false */ +"use strict"; + +/** + * @constructor + * @extends {Dygraph.DataHandler} + */ +Dygraph.DataHandlers.BarsHandler = function() { + Dygraph.DataHandler.call(this); +}; +Dygraph.DataHandlers.BarsHandler.prototype = new Dygraph.DataHandler(); + +// alias for the rest of the implementation +var BarsHandler = Dygraph.DataHandlers.BarsHandler; + +// TODO(danvk): figure out why the jsdoc has to be copy/pasted from superclass. +// (I get closure compiler errors if this isn't here.) +/** + * @override + * @param {!Array.} rawData The raw data passed into dygraphs where + * rawData[i] = [x,ySeries1,...,ySeriesN]. + * @param {!number} seriesIndex Index of the series to extract. All other + * series should be ignored. + * @param {!DygraphOptions} options Dygraph options. + * @return {Array.<[!number,?number,?]>} The series in the unified data format + * where series[i] = [x,y,{extras}]. + */ +BarsHandler.prototype.extractSeries = function(rawData, seriesIndex, options) { + // Not implemented here must be extended +}; + +/** + * @override + * @param {!Array.<[!number,?number,?]>} series The series in the unified + * data format where series[i] = [x,y,{extras}]. + * @param {!number} rollPeriod The number of points over which to average the data + * @param {!DygraphOptions} options The dygraph options. + * TODO(danvk): be more specific than "Array" here. + * @return {!Array.<[!number,?number,?]>} the rolled series. + */ +BarsHandler.prototype.rollingAverage = + function(series, rollPeriod, options) { + // Not implemented here, must be extended. +}; + +/** @inheritDoc */ +BarsHandler.prototype.onPointsCreated_ = function(series, points) { + for (var i = 0; i < series.length; ++i) { + var item = series[i]; + var point = points[i]; + point.y_top = NaN; + point.y_bottom = NaN; + point.yval_minus = Dygraph.DataHandler.parseFloat(item[2][0]); + point.yval_plus = Dygraph.DataHandler.parseFloat(item[2][1]); + } +}; + +/** @inheritDoc */ +BarsHandler.prototype.getExtremeYValues = function(series, dateWindow, options) { + var minY = null, maxY = null, y; + + var firstIdx = 0; + var lastIdx = series.length - 1; + + for ( var j = firstIdx; j <= lastIdx; j++) { + y = series[j][1]; + if (y === null || isNaN(y)) continue; + + var low = series[j][2][0]; + var high = series[j][2][1]; + + if (low > y) low = y; // this can happen with custom bars, + if (high < y) high = y; // e.g. in tests/custom-bars.html + + if (maxY === null || high > maxY) maxY = high; + if (minY === null || low < minY) minY = low; + } + + return [ minY, maxY ]; +}; + +/** @inheritDoc */ +BarsHandler.prototype.onLineEvaluated = function(points, axis, logscale) { + var point; + for (var j = 0; j < points.length; j++) { + // Copy over the error terms + point = points[j]; + point.y_top = DygraphLayout.calcYNormal_(axis, point.yval_minus, logscale); + point.y_bottom = DygraphLayout.calcYNormal_(axis, point.yval_plus, logscale); + } +}; + +})(); +/** + * @license + * Copyright 2013 David Eberlein (david.eberlein@ch.sauter-bc.com) + * MIT-licensed (http://opensource.org/licenses/MIT) + */ + +/** + * @fileoverview DataHandler implementation for the custom bars option. + * @author David Eberlein (david.eberlein@ch.sauter-bc.com) + */ + +(function() { + +/*global Dygraph:false */ +"use strict"; + +/** + * @constructor + * @extends Dygraph.DataHandlers.BarsHandler + */ +Dygraph.DataHandlers.CustomBarsHandler = function() { +}; + +var CustomBarsHandler = Dygraph.DataHandlers.CustomBarsHandler; +CustomBarsHandler.prototype = new Dygraph.DataHandlers.BarsHandler(); + +/** @inheritDoc */ +CustomBarsHandler.prototype.extractSeries = function(rawData, i, options) { + // TODO(danvk): pre-allocate series here. + var series = []; + var x, y, point; + var logScale = options.get('logscale'); + for ( var j = 0; j < rawData.length; j++) { + x = rawData[j][0]; + point = rawData[j][i]; + if (logScale && point !== null) { + // On the log scale, points less than zero do not exist. + // This will create a gap in the chart. + if (point[0] <= 0 || point[1] <= 0 || point[2] <= 0) { + point = null; + } + } + // Extract to the unified data format. + if (point !== null) { + y = point[1]; + if (y !== null && !isNaN(y)) { + series.push([ x, y, [ point[0], point[2] ] ]); + } else { + series.push([ x, y, [ y, y ] ]); + } + } else { + series.push([ x, null, [ null, null ] ]); + } + } + return series; +}; + +/** @inheritDoc */ +CustomBarsHandler.prototype.rollingAverage = + function(originalData, rollPeriod, options) { + rollPeriod = Math.min(rollPeriod, originalData.length); + var rollingData = []; + var y, low, high, mid,count, i, extremes; + + low = 0; + mid = 0; + high = 0; + count = 0; + for (i = 0; i < originalData.length; i++) { + y = originalData[i][1]; + extremes = originalData[i][2]; + rollingData[i] = originalData[i]; + + if (y !== null && !isNaN(y)) { + low += extremes[0]; + mid += y; + high += extremes[1]; + count += 1; + } + if (i - rollPeriod >= 0) { + var prev = originalData[i - rollPeriod]; + if (prev[1] !== null && !isNaN(prev[1])) { + low -= prev[2][0]; + mid -= prev[1]; + high -= prev[2][1]; + count -= 1; + } + } + if (count) { + rollingData[i] = [ + originalData[i][0], + 1.0 * mid / count, + [ 1.0 * low / count, + 1.0 * high / count ] ]; + } else { + rollingData[i] = [ originalData[i][0], null, [ null, null ] ]; + } + } + + return rollingData; +}; + +})(); +/** + * @license + * Copyright 2013 David Eberlein (david.eberlein@ch.sauter-bc.com) + * MIT-licensed (http://opensource.org/licenses/MIT) + */ + +/** + * @fileoverview DataHandler implementation for the error bars option. + * @author David Eberlein (david.eberlein@ch.sauter-bc.com) + */ + +(function() { + +/*global Dygraph:false */ +"use strict"; + +/** + * @constructor + * @extends Dygraph.DataHandlers.BarsHandler + */ +Dygraph.DataHandlers.ErrorBarsHandler = function() { +}; + +var ErrorBarsHandler = Dygraph.DataHandlers.ErrorBarsHandler; +ErrorBarsHandler.prototype = new Dygraph.DataHandlers.BarsHandler(); + +/** @inheritDoc */ +ErrorBarsHandler.prototype.extractSeries = function(rawData, i, options) { + // TODO(danvk): pre-allocate series here. + var series = []; + var x, y, variance, point; + var sigma = options.get("sigma"); + var logScale = options.get('logscale'); + for ( var j = 0; j < rawData.length; j++) { + x = rawData[j][0]; + point = rawData[j][i]; + if (logScale && point !== null) { + // On the log scale, points less than zero do not exist. + // This will create a gap in the chart. + if (point[0] <= 0 || point[0] - sigma * point[1] <= 0) { + point = null; + } + } + // Extract to the unified data format. + if (point !== null) { + y = point[0]; + if (y !== null && !isNaN(y)) { + variance = sigma * point[1]; + // preserve original error value in extras for further + // filtering + series.push([ x, y, [ y - variance, y + variance, point[1] ] ]); + } else { + series.push([ x, y, [ y, y, y ] ]); + } + } else { + series.push([ x, null, [ null, null, null ] ]); + } + } + return series; +}; + +/** @inheritDoc */ +ErrorBarsHandler.prototype.rollingAverage = + function(originalData, rollPeriod, options) { + rollPeriod = Math.min(rollPeriod, originalData.length); + var rollingData = []; + var sigma = options.get("sigma"); + + var i, j, y, v, sum, num_ok, stddev, variance, value; + + // Calculate the rolling average for the first rollPeriod - 1 points + // where there is not enough data to roll over the full number of points + for (i = 0; i < originalData.length; i++) { + sum = 0; + variance = 0; + num_ok = 0; + for (j = Math.max(0, i - rollPeriod + 1); j < i + 1; j++) { + y = originalData[j][1]; + if (y === null || isNaN(y)) + continue; + num_ok++; + sum += y; + variance += Math.pow(originalData[j][2][2], 2); + } + if (num_ok) { + stddev = Math.sqrt(variance) / num_ok; + value = sum / num_ok; + rollingData[i] = [ originalData[i][0], value, + [value - sigma * stddev, value + sigma * stddev] ]; + } else { + // This explicitly preserves NaNs to aid with "independent + // series". + // See testRollingAveragePreservesNaNs. + v = (rollPeriod == 1) ? originalData[i][1] : null; + rollingData[i] = [ originalData[i][0], v, [ v, v ] ]; + } + } + + return rollingData; +}; + +})(); +/** + * @license + * Copyright 2013 David Eberlein (david.eberlein@ch.sauter-bc.com) + * MIT-licensed (http://opensource.org/licenses/MIT) + */ + +/** + * @fileoverview DataHandler implementation for the combination + * of error bars and fractions options. + * @author David Eberlein (david.eberlein@ch.sauter-bc.com) + */ + +(function() { + +/*global Dygraph:false */ +"use strict"; + +/** + * @constructor + * @extends Dygraph.DataHandlers.BarsHandler + */ +Dygraph.DataHandlers.FractionsBarsHandler = function() { +}; + +var FractionsBarsHandler = Dygraph.DataHandlers.FractionsBarsHandler; +FractionsBarsHandler.prototype = new Dygraph.DataHandlers.BarsHandler(); + +/** @inheritDoc */ +FractionsBarsHandler.prototype.extractSeries = function(rawData, i, options) { + // TODO(danvk): pre-allocate series here. + var series = []; + var x, y, point, num, den, value, stddev, variance; + var mult = 100.0; + var sigma = options.get("sigma"); + var logScale = options.get('logscale'); + for ( var j = 0; j < rawData.length; j++) { + x = rawData[j][0]; + point = rawData[j][i]; + if (logScale && point !== null) { + // On the log scale, points less than zero do not exist. + // This will create a gap in the chart. + if (point[0] <= 0 || point[1] <= 0) { + point = null; + } + } + // Extract to the unified data format. + if (point !== null) { + num = point[0]; + den = point[1]; + if (num !== null && !isNaN(num)) { + value = den ? num / den : 0.0; + stddev = den ? sigma * Math.sqrt(value * (1 - value) / den) : 1.0; + variance = mult * stddev; + y = mult * value; + // preserve original values in extras for further filtering + series.push([ x, y, [ y - variance, y + variance, num, den ] ]); + } else { + series.push([ x, num, [ num, num, num, den ] ]); + } + } else { + series.push([ x, null, [ null, null, null, null ] ]); + } + } + return series; +}; + +/** @inheritDoc */ +FractionsBarsHandler.prototype.rollingAverage = + function(originalData, rollPeriod, options) { + rollPeriod = Math.min(rollPeriod, originalData.length); + var rollingData = []; + var sigma = options.get("sigma"); + var wilsonInterval = options.get("wilsonInterval"); + + var low, high, i, stddev; + var num = 0; + var den = 0; // numerator/denominator + var mult = 100.0; + for (i = 0; i < originalData.length; i++) { + num += originalData[i][2][2]; + den += originalData[i][2][3]; + if (i - rollPeriod >= 0) { + num -= originalData[i - rollPeriod][2][2]; + den -= originalData[i - rollPeriod][2][3]; + } + + var date = originalData[i][0]; + var value = den ? num / den : 0.0; + if (wilsonInterval) { + // For more details on this confidence interval, see: + // http://en.wikipedia.org/wiki/Binomial_confidence_interval + if (den) { + var p = value < 0 ? 0 : value, n = den; + var pm = sigma * Math.sqrt(p * (1 - p) / n + sigma * sigma / (4 * n * n)); + var denom = 1 + sigma * sigma / den; + low = (p + sigma * sigma / (2 * den) - pm) / denom; + high = (p + sigma * sigma / (2 * den) + pm) / denom; + rollingData[i] = [ date, p * mult, + [ low * mult, high * mult ] ]; + } else { + rollingData[i] = [ date, 0, [ 0, 0 ] ]; + } + } else { + stddev = den ? sigma * Math.sqrt(value * (1 - value) / den) : 1.0; + rollingData[i] = [ date, mult * value, + [ mult * (value - stddev), mult * (value + stddev) ] ]; + } + } + + return rollingData; +}; + +})(); diff --git a/dygraph-combined.js b/dygraph-combined.js index e6380de..7d6121e 100644 --- a/dygraph-combined.js +++ b/dygraph-combined.js @@ -1,7 +1,6 @@ -This is not the file you are looking for. -A reasonably up-to-date version can be found at http://dygraphs.com/dygraph-combined.js - -dygraph-combined.js is a "packed" version of the larger dygraphs JS files. It is -smaller and loads more quickly, but is harder to debug. - -To generate this file, run "make" or generate-combined.sh. +/*! @license Copyright 2014 Dan Vanderkam (danvdk@gmail.com) MIT-licensed (http://opensource.org/licenses/MIT) */ +!function(t){"use strict";for(var e,a,i={},r=function(){},n="memory".split(","),o="assert,clear,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profiles,profileEnd,show,table,time,timeEnd,timeline,timelineEnd,timeStamp,trace,warn".split(",");e=n.pop();)t[e]=t[e]||i;for(;a=o.pop();)t[a]=t[a]||r}(this.console=this.console||{}),function(){"use strict";CanvasRenderingContext2D.prototype.installPattern=function(t){if("undefined"!=typeof this.isPatternInstalled)throw"Must un-install old line pattern before installing a new one.";this.isPatternInstalled=!0;var e=[0,0],a=[],i=this.beginPath,r=this.lineTo,n=this.moveTo,o=this.stroke;this.uninstallPattern=function(){this.beginPath=i,this.lineTo=r,this.moveTo=n,this.stroke=o,this.uninstallPattern=void 0,this.isPatternInstalled=void 0},this.beginPath=function(){a=[],i.call(this)},this.moveTo=function(t,e){a.push([[t,e]]),n.call(this,t,e)},this.lineTo=function(t,e){var i=a[a.length-1];i.push([t,e])},this.stroke=function(){if(0===a.length)return void o.call(this);for(var i=0;if;){var x=t[v];f+=e[1]?e[1]:x,f>y?(e=[v,f-y],f=y):e=[(v+1)%t.length,0],v%2===0?r.call(this,f,0):n.call(this,f,0),v=(v+1)%t.length}this.restore(),l=g,h=d}o.call(this),a=[]}},CanvasRenderingContext2D.prototype.uninstallPattern=function(){throw"Must install a line pattern before uninstalling it."}}();var DygraphOptions=function(){return function(){"use strict";var t=function(t){this.dygraph_=t,this.yAxes_=[],this.xAxis_={},this.series_={},this.global_=this.dygraph_.attrs_,this.user_=this.dygraph_.user_attrs_||{},this.labels_=[],this.highlightSeries_=this.get("highlightSeriesOpts")||{},this.reparseSeries()};t.AXIS_STRING_MAPPINGS_={y:0,Y:0,y1:0,Y1:0,y2:1,Y2:1},t.axisToIndex_=function(e){if("string"==typeof e){if(t.AXIS_STRING_MAPPINGS_.hasOwnProperty(e))return t.AXIS_STRING_MAPPINGS_[e];throw"Unknown axis : "+e}if("number"==typeof e){if(0===e||1===e)return e;throw"Dygraphs only supports two y-axes, indexed from 0-1."}if(e)throw"Unknown axis : "+e;return 0},t.prototype.reparseSeries=function(){var e=this.get("labels");if(e){this.labels_=e.slice(1),this.yAxes_=[{series:[],options:{}}],this.xAxis_={options:{}},this.series_={};var a=!this.user_.series;if(a){for(var i=0,r=0;r1&&Dygraph.update(this.yAxes_[1].options,h.y2||{}),Dygraph.update(this.xAxis_.options,h.x||{})}},t.prototype.get=function(t){var e=this.getGlobalUser_(t);return null!==e?e:this.getGlobalDefault_(t)},t.prototype.getGlobalUser_=function(t){return this.user_.hasOwnProperty(t)?this.user_[t]:null},t.prototype.getGlobalDefault_=function(t){return this.global_.hasOwnProperty(t)?this.global_[t]:Dygraph.DEFAULT_ATTRS.hasOwnProperty(t)?Dygraph.DEFAULT_ATTRS[t]:null},t.prototype.getForAxis=function(t,e){var a,i;if("number"==typeof e)a=e,i=0===a?"y":"y2";else{if("y1"==e&&(e="y"),"y"==e)a=0;else if("y2"==e)a=1;else{if("x"!=e)throw"Unknown axis "+e;a=-1}i=e}var r=-1==a?this.xAxis_:this.yAxes_[a];if(r){var n=r.options;if(n.hasOwnProperty(t))return n[t]}if("x"!==e||"logscale"!==t){var o=this.getGlobalUser_(t);if(null!==o)return o}var s=Dygraph.DEFAULT_ATTRS.axes[i];return s.hasOwnProperty(t)?s[t]:this.getGlobalDefault_(t)},t.prototype.getForSeries=function(t,e){if(e===this.dygraph_.getHighlightSeries()&&this.highlightSeries_.hasOwnProperty(t))return this.highlightSeries_[t];if(!this.series_.hasOwnProperty(e))throw"Unknown series: "+e;var a=this.series_[e],i=a.options;return i.hasOwnProperty(t)?i[t]:this.getForAxis(t,a.yAxis)},t.prototype.numAxes=function(){return this.yAxes_.length},t.prototype.axisForSeries=function(t){return this.series_[t].yAxis},t.prototype.axisOptions=function(t){return this.yAxes_[t].options},t.prototype.seriesForAxis=function(t){return this.yAxes_[t].series},t.prototype.seriesNames=function(){return this.labels_};return t}()}(),DygraphLayout=function(){"use strict";var t=function(t){this.dygraph_=t,this.points=[],this.setNames=[],this.annotations=[],this.yAxes_=null,this.xTicks_=null,this.yTicks_=null};return t.prototype.addDataset=function(t,e){this.points.push(e),this.setNames.push(t)},t.prototype.getPlotArea=function(){return this.area_},t.prototype.computePlotArea=function(){var t={x:0,y:0};t.w=this.dygraph_.width_-t.x-this.dygraph_.getOption("rightGap"),t.h=this.dygraph_.height_;var e={chart_div:this.dygraph_.graphDiv,reserveSpaceLeft:function(e){var a={x:t.x,y:t.y,w:e,h:t.h};return t.x+=e,t.w-=e,a},reserveSpaceRight:function(e){var a={x:t.x+t.w-e,y:t.y,w:e,h:t.h};return t.w-=e,a},reserveSpaceTop:function(e){var a={x:t.x,y:t.y,w:t.w,h:e};return t.y+=e,t.h-=e,a},reserveSpaceBottom:function(e){var a={x:t.x,y:t.y+t.h-e,w:t.w,h:e};return t.h-=e,a},chartRect:function(){return{x:t.x,y:t.y,w:t.w,h:t.h}}};this.dygraph_.cascadeEvents_("layout",e),this.area_=t},t.prototype.setAnnotations=function(t){this.annotations=[];for(var e=this.dygraph_.getOption("xValueParser")||function(t){return t},a=0;a=0&&1>i&&this.xticks.push([i,a]);for(this.yticks=[],t=0;t0&&1>=i&&this.yticks.push([t,i,a])},t.prototype._evaluateAnnotations=function(){var t,e={};for(t=0;t=0;i--)a.childNodes[i].className==e&&a.removeChild(a.childNodes[i]);for(var r=document.bgColor,n=this.dygraph_.graphDiv;n!=document;){var o=n.currentStyle.backgroundColor;if(o&&"transparent"!=o){r=o;break}n=n.parentNode}var s=this.area;t({x:0,y:0,w:s.x,h:this.height}),t({x:s.x,y:0,w:this.width-s.x,h:s.y}),t({x:s.x+s.w,y:0,w:this.width-s.x-s.w,h:this.height}),t({x:s.x,y:s.y+s.h,w:this.width-s.x,h:this.height-s.h-s.y})},t._getIteratorPredicate=function(e){return e?t._predicateThatSkipsEmptyPoints:null},t._predicateThatSkipsEmptyPoints=function(t,e){return null!==t[e].yval},t._drawStyledLine=function(e,a,i,r,n,o,s){var l=e.dygraph,h=l.getBooleanOption("stepPlot",e.setName);Dygraph.isArrayLike(r)||(r=null);var p=l.getBooleanOption("drawGapEdgePoints",e.setName),g=e.points,d=e.setName,u=Dygraph.createIterator(g,0,g.length,t._getIteratorPredicate(l.getBooleanOption("connectSeparatedPoints",d))),c=r&&r.length>=2,y=e.drawingContext;y.save(),c&&y.installPattern(r);var _=t._drawSeries(e,u,i,s,n,p,h,a);t._drawPointsOnLine(e,_,o,a,s),c&&y.uninstallPattern(),y.restore()},t._drawSeries=function(t,e,a,i,r,n,o,s){var l,h,p=null,g=null,d=null,u=[],c=!0,y=t.drawingContext;y.beginPath(),y.strokeStyle=s,y.lineWidth=a;for(var _=e.array_,v=e.end_,f=e.predicate_,x=e.start_;v>x;x++){if(h=_[x],f){for(;v>x&&!f(_,x);)x++;if(x==v)break;h=_[x]}if(null===h.canvasy||h.canvasy!=h.canvasy)o&&null!==p&&(y.moveTo(p,g),y.lineTo(h.canvasx,g)),p=g=null;else{if(l=!1,n||!p){e.nextIdx_=x,e.next(),d=e.hasNext?e.peek.canvasy:null;var m=null===d||d!=d;l=!p&&m,n&&(!c&&!p||e.hasNext&&m)&&(l=!0)}null!==p?a&&(o&&(y.moveTo(p,g),y.lineTo(h.canvasx,g)),y.lineTo(h.canvasx,h.canvasy)):y.moveTo(h.canvasx,h.canvasy),(r||l)&&u.push([h.canvasx,h.canvasy,h.idx]),p=h.canvasx,g=h.canvasy}c=!1}return y.stroke(),u},t._drawPointsOnLine=function(t,e,a,i,r){for(var n=t.drawingContext,o=0;o0;a--){var i=e[a];if(i[0]==n){var o=e[a-1];o[1]==i[1]&&o[2]==i[2]&&e.splice(a,1)}}for(var a=0;a2&&!t){var s=0;e[0][0]==n&&s++;for(var l=null,h=null,a=s;ae[h][2]&&(h=a)}}var g=e[l],d=e[h];e.splice(s,e.length-s),h>l?(e.push(g),e.push(d)):l>h?(e.push(d),e.push(g)):e.push(g)}}},l=function(a){s(a);for(var l=0,h=e.length;h>l;l++){var p=e[l];p[0]==r?t.lineTo(p[1],p[2]):p[0]==n&&t.moveTo(p[1],p[2])}e.length&&(i=e[e.length-1][1]),o+=e.length,e=[]},h=function(t,r,n){var o=Math.round(r);if(null===a||o!=a){var s=a-i>1,h=o-a>1,p=s||h;l(p),a=o}e.push([t,r,n])};return{moveTo:function(t,e){h(n,t,e)},lineTo:function(t,e){h(r,t,e)},stroke:function(){l(!0),t.stroke()},fill:function(){l(!0),t.fill()},beginPath:function(){l(!0),t.beginPath()},closePath:function(){l(!0),t.closePath()},_count:function(){return o}}},t._fillPlotter=function(e){if(!e.singleSeriesName&&0===e.seriesIndex){for(var a=e.dygraph,i=a.getLabels().slice(1),r=i.length;r>=0;r--)a.visibility()[r]||i.splice(r,1);var n=function(){for(var t=0;t=0;r--){var n=i[r];t.lineTo(n[0],n[1])}},_=p-1;_>=0;_--){var v=e.drawingContext,f=i[_];if(a.getBooleanOption("fillGraph",f)){var x=a.getBooleanOption("stepPlot",f),m=u[_],D=a.axisPropertiesForSeries(f),w=1+D.minyval*D.yscale;0>w?w=0:w>1&&(w=1),w=l.h*w+l.y;var A,b=h[_],T=Dygraph.createIterator(b,0,b.length,t._getIteratorPredicate(a.getBooleanOption("connectSeparatedPoints",f))),E=0/0,C=[-1,-1],L=Dygraph.toRGB_(m),P="rgba("+L.r+","+L.g+","+L.b+","+g+")";v.fillStyle=P,v.beginPath();var S,O=!0;(b.length>2*a.width_||Dygraph.FORCE_FAST_PROXY)&&(v=t._fastCanvasProxy(v));for(var M,R=[];T.hasNext;)if(M=T.next(),Dygraph.isOK(M.y)||x){if(d){if(!O&&S==M.xval)continue;O=!1,S=M.xval,o=c[M.canvasx];var F;F=void 0===o?w:s?o[0]:o,A=[M.canvasy,F],x?-1===C[0]?c[M.canvasx]=[M.canvasy,w]:c[M.canvasx]=[M.canvasy,C[0]]:c[M.canvasx]=M.canvasy}else A=isNaN(M.canvasy)&&x?[l.y+l.h,w]:[M.canvasy,w];isNaN(E)?(v.moveTo(M.canvasx,A[1]),v.lineTo(M.canvasx,A[0])):(x?(v.lineTo(M.canvasx,C[0]),v.lineTo(M.canvasx,A[0])):v.lineTo(M.canvasx,A[0]),d&&(R.push([E,C[1]]),R.push(s&&o?[M.canvasx,o[1]]:[M.canvasx,A[1]]))),C=A,E=M.canvasx}else y(v,E,C[1],R),R=[],E=0/0,null===M.y_stacked||isNaN(M.y_stacked)||(c[M.canvasx]=l.h*M.y_stacked+l.y);s=x,A&&M&&(y(v,M.canvasx,A[1],R),R=[]),v.fill()}}}},t}(),Dygraph=function(){"use strict";var t=function(t,e,a,i){this.is_initial_draw_=!0,this.readyFns_=[],void 0!==i?(console.warn("Using deprecated four-argument dygraph constructor"),this.__old_init__(t,e,a,i)):this.__init__(t,e,a)};return t.NAME="Dygraph",t.VERSION="1.1.1",t.__repr__=function(){return"["+t.NAME+" "+t.VERSION+"]"},t.toString=function(){return t.__repr__()},t.DEFAULT_ROLL_PERIOD=1,t.DEFAULT_WIDTH=480,t.DEFAULT_HEIGHT=320,t.ANIMATION_STEPS=12,t.ANIMATION_DURATION=200,t.KMB_LABELS=["K","M","B","T","Q"],t.KMG2_BIG_LABELS=["k","M","G","T","P","E","Z","Y"],t.KMG2_SMALL_LABELS=["m","u","n","p","f","a","z","y"],t.numberValueFormatter=function(e,a){var i=a("sigFigs");if(null!==i)return t.floatFormat(e,i);var r,n=a("digitsAfterDecimal"),o=a("maxNumberWidth"),s=a("labelsKMB"),l=a("labelsKMG2");if(r=0!==e&&(Math.abs(e)>=Math.pow(10,o)||Math.abs(e)=0;c--,u/=h)if(d>=u){r=t.round_(e/u,n)+p[c];break}if(l){var y=String(e.toExponential()).split("e-");2===y.length&&y[1]>=3&&y[1]<=24&&(r=y[1]%3>0?t.round_(y[0]/t.pow(10,y[1]%3),n):Number(y[0]).toFixed(2),r+=g[Math.floor(y[1]/3)-1])}}return r},t.numberAxisLabelFormatter=function(e,a,i){return t.numberValueFormatter.call(this,e,i)},t.SHORT_MONTH_NAMES_=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],t.dateAxisLabelFormatter=function(e,a,i){var r=i("labelsUTC"),n=r?t.DateAccessorsUTC:t.DateAccessorsLocal,o=n.getFullYear(e),s=n.getMonth(e),l=n.getDate(e),h=n.getHours(e),p=n.getMinutes(e),g=n.getSeconds(e),d=n.getSeconds(e);if(a>=t.DECADAL)return""+o;if(a>=t.MONTHLY)return t.SHORT_MONTH_NAMES_[s]+" "+o;var u=3600*h+60*p+g+.001*d;return 0===u||a>=t.DAILY?t.zeropad(l)+" "+t.SHORT_MONTH_NAMES_[s]:t.hmsString_(h,p,g)},t.dateAxisFormatter=t.dateAxisLabelFormatter,t.dateValueFormatter=function(e,a){return t.dateString_(e,a("labelsUTC"))},t.Plotters=DygraphCanvasRenderer._Plotters,t.DEFAULT_ATTRS={highlightCircleSize:3,highlightSeriesOpts:null,highlightSeriesBackgroundAlpha:.5,labelsDivWidth:250,labelsDivStyles:{},labelsSeparateLines:!1,labelsShowZeroValues:!0,labelsKMB:!1,labelsKMG2:!1,showLabelsOnHighlight:!0,digitsAfterDecimal:2,maxNumberWidth:6,sigFigs:null,strokeWidth:1,strokeBorderWidth:0,strokeBorderColor:"white",axisTickSize:3,axisLabelFontSize:14,rightGap:5,showRoller:!1,xValueParser:t.dateParser,delimiter:",",sigma:2,errorBars:!1,fractions:!1,wilsonInterval:!0,customBars:!1,fillGraph:!1,fillAlpha:.15,connectSeparatedPoints:!1,stackedGraph:!1,stackedGraphNaNFill:"all",hideOverlayOnMouseOut:!0,legend:"onmouseover",stepPlot:!1,avoidMinZero:!1,xRangePad:0,yRangePad:null,drawAxesAtZero:!1,titleHeight:28,xLabelHeight:18,yLabelWidth:18,drawXAxis:!0,drawYAxis:!0,axisLineColor:"black",axisLineWidth:.3,gridLineWidth:.3,axisLabelColor:"black",axisLabelWidth:50,drawYGrid:!0,drawXGrid:!0,gridLineColor:"rgb(128,128,128)",interactionModel:null,animatedZooms:!1,showRangeSelector:!1,rangeSelectorHeight:40,rangeSelectorPlotStrokeColor:"#808FAB",rangeSelectorPlotFillColor:"#A7B1C4",showInRangeSelector:null,plotter:[t.Plotters.fillPlotter,t.Plotters.errorPlotter,t.Plotters.linePlotter],plugins:[],axes:{x:{pixelsPerLabel:70,axisLabelWidth:60,axisLabelFormatter:t.dateAxisLabelFormatter,valueFormatter:t.dateValueFormatter,drawGrid:!0,drawAxis:!0,independentTicks:!0,ticker:null},y:{axisLabelWidth:50,pixelsPerLabel:30,valueFormatter:t.numberValueFormatter,axisLabelFormatter:t.numberAxisLabelFormatter,drawGrid:!0,drawAxis:!0,independentTicks:!0,ticker:null},y2:{axisLabelWidth:50,pixelsPerLabel:30,valueFormatter:t.numberValueFormatter,axisLabelFormatter:t.numberAxisLabelFormatter,drawAxis:!0,drawGrid:!1,independentTicks:!1,ticker:null}}},t.HORIZONTAL=1,t.VERTICAL=2,t.PLUGINS=[],t.addedAnnotationCSS=!1,t.prototype.__old_init__=function(e,a,i,r){if(null!==i){for(var n=["Date"],o=0;o=0;n--){var o=r[n][0],s=r[n][1];if(s.call(o,i),i.propagationStopped)break}return i.defaultPrevented},t.prototype.getPluginInstance_=function(t){for(var e=0;et||t>=this.axes_.length)return null;var e=this.axes_[t];return[e.computedValueRange[0],e.computedValueRange[1]]},t.prototype.yAxisRanges=function(){for(var t=[],e=0;et||t>this.rawData_.length?null:0>e||e>this.rawData_[t].length?null:this.rawData_[t][e]},t.prototype.createInterface_=function(){var e=this.maindiv_;this.graphDiv=document.createElement("div"),this.graphDiv.style.textAlign="left",this.graphDiv.style.position="relative",e.appendChild(this.graphDiv),this.canvas_=t.createCanvas(),this.canvas_.style.position="absolute",this.hidden_=this.createPlotKitCanvas_(this.canvas_),this.canvas_ctx_=t.getContext(this.canvas_),this.hidden_ctx_=t.getContext(this.hidden_),this.resizeElements_(),this.graphDiv.appendChild(this.hidden_),this.graphDiv.appendChild(this.canvas_),this.mouseEventElement_=this.createMouseEventElement_(),this.layout_=new DygraphLayout(this);var a=this;this.mouseMoveHandler_=function(t){a.mouseMove_(t)},this.mouseOutHandler_=function(e){var i=e.target||e.fromElement,r=e.relatedTarget||e.toElement;t.isNodeContainedBy(i,a.graphDiv)&&!t.isNodeContainedBy(r,a.graphDiv)&&a.mouseOut_(e)},this.addAndTrackEvent(window,"mouseout",this.mouseOutHandler_),this.addAndTrackEvent(this.mouseEventElement_,"mousemove",this.mouseMoveHandler_),this.resizeHandler_||(this.resizeHandler_=function(t){a.resize()},this.addAndTrackEvent(window,"resize",this.resizeHandler_))},t.prototype.resizeElements_=function(){this.graphDiv.style.width=this.width_+"px",this.graphDiv.style.height=this.height_+"px";var e=t.getContextPixelRatio(this.canvas_ctx_);this.canvas_.width=this.width_*e,this.canvas_.height=this.height_*e,this.canvas_.style.width=this.width_+"px",this.canvas_.style.height=this.height_+"px",1!==e&&this.canvas_ctx_.scale(e,e);var a=t.getContextPixelRatio(this.hidden_ctx_);this.hidden_.width=this.width_*a,this.hidden_.height=this.height_*a,this.hidden_.style.width=this.width_+"px",this.hidden_.style.height=this.height_+"px",1!==a&&this.hidden_ctx_.scale(a,a)},t.prototype.destroy=function(){this.canvas_ctx_.restore(),this.hidden_ctx_.restore();for(var e=this.plugins_.length-1;e>=0;e--){var a=this.plugins_.pop();a.plugin.destroy&&a.plugin.destroy()}var i=function(t){for(;t.hasChildNodes();)i(t.firstChild),t.removeChild(t.firstChild)};this.removeTrackedEvents_(),t.removeEvent(window,"mouseout",this.mouseOutHandler_),t.removeEvent(this.mouseEventElement_,"mousemove",this.mouseMoveHandler_),t.removeEvent(window,"resize",this.resizeHandler_),this.resizeHandler_=null,i(this.maindiv_);var r=function(t){for(var e in t)"object"==typeof t[e]&&(t[e]=null)};r(this.layout_),r(this.plotter_),r(this)},t.prototype.createPlotKitCanvas_=function(e){var a=t.createCanvas();return a.style.position="absolute",a.style.top=e.style.top,a.style.left=e.style.left,a.width=this.width_,a.height=this.height_,a.style.width=this.width_+"px",a.style.height=this.height_+"px",a},t.prototype.createMouseEventElement_=function(){if(this.isUsingExcanvas_){var t=document.createElement("div");return t.style.position="absolute",t.style.backgroundColor="white",t.style.filter="alpha(opacity=0)",t.style.width=this.width_+"px",t.style.height=this.height_+"px",this.graphDiv.appendChild(t),t}return this.canvas_},t.prototype.setColors_=function(){var e=this.getLabels(),a=e.length-1;this.colors_=[],this.colorsMap_={};for(var i=this.getNumericOption("colorSaturation")||1,r=this.getNumericOption("colorValue")||.5,n=Math.ceil(a/2),o=this.getOption("colors"),s=this.visibility(),l=0;a>l;l++)if(s[l]){ +var h=e[l+1],p=this.attributes_.getForSeries("color",h);if(!p)if(o)p=o[l%o.length];else{var g=l%2?n+(l+1)/2:Math.ceil((l+1)/2),d=1*g/(1+a);p=t.hsvToRGB(d,i,r)}this.colors_.push(p),this.colorsMap_[h]=p}},t.prototype.getColors=function(){return this.colors_},t.prototype.getPropertiesForSeries=function(t){for(var e=-1,a=this.getLabels(),i=1;i=o;o++)s=t.zoomAnimationFunction(o,l),h[o-1]=[e[0]*(1-s)+s*a[0],e[1]*(1-s)+s*a[1]];if(null!==i&&null!==r)for(o=1;l>=o;o++){s=t.zoomAnimationFunction(o,l);for(var g=[],d=0;dl;l++){var h=o[l];if(t.isValidPoint(h,!0)){var p=Math.abs(h.canvasx-e);a>p&&(a=p,i=h.idx)}}return i},t.prototype.findClosestPoint=function(e,a){for(var i,r,n,o,s,l,h,p=1/0,g=this.layout_.points.length-1;g>=0;--g)for(var d=this.layout_.points[g],u=0;ui&&(p=i,s=o,l=g,h=o.idx));var c=this.layout_.setNames[l];return{row:h,seriesName:c,point:s}},t.prototype.findStackedPoint=function(e,a){for(var i,r,n=this.findClosestRow(e),o=0;o=h.length)){var p=h[l];if(t.isValidPoint(p)){var g=p.canvasy;if(e>p.canvasx&&l+10){var c=(e-p.canvasx)/u;g+=c*(d.canvasy-p.canvasy)}}}else if(e0){var y=h[l-1];if(t.isValidPoint(y)){var u=p.canvasx-y.canvasx;if(u>0){var c=(p.canvasx-e)/u;g+=c*(y.canvasy-p.canvasy)}}}(0===o||a>g)&&(i=p,r=o)}}}var _=this.layout_.setNames[r];return{row:n,seriesName:_,point:i}},t.prototype.mouseMove_=function(t){var e=this.layout_.points;if(void 0!==e&&null!==e){var a=this.eventToDomCoords(t),i=a[0],r=a[1],n=this.getOption("highlightSeriesOpts"),o=!1;if(n&&!this.isSeriesLocked()){var s;s=this.getBooleanOption("stackedGraph")?this.findStackedPoint(i,r):this.findClosestPoint(i,r),o=this.setSelection(s.row,s.seriesName)}else{var l=this.findClosestRow(i);o=this.setSelection(l)}var h=this.getFunctionOption("highlightCallback");h&&o&&h.call(this,t,this.lastx_,this.selPoints_,this.lastRow_,this.highlightSet_)}},t.prototype.getLeftBoundary_=function(t){if(this.boundaryIds_[t])return this.boundaryIds_[t][0];for(var e=0;ee?r:a-r;if(0>=n)return void(this.fadeLevel&&this.updateSelection_(1));var o=++this.animateId,s=this;t.repeatAndCleanup(function(t){s.animateId==o&&(s.fadeLevel+=e,0===s.fadeLevel?s.clearSelection():s.updateSelection_(s.fadeLevel/a))},n,i,function(){})},t.prototype.updateSelection_=function(e){this.cascadeEvents_("select",{selectedRow:this.lastRow_,selectedX:this.lastx_,selectedPoints:this.selPoints_});var a,i=this.canvas_ctx_;if(this.getOption("highlightSeriesOpts")){i.clearRect(0,0,this.width_,this.height_);var r=1-this.getNumericOption("highlightSeriesBackgroundAlpha");if(r){var n=!0;if(n){if(void 0===e)return void this.animateSelection_(1);r*=e}i.fillStyle="rgba(255,255,255,"+r+")",i.fillRect(0,0,this.width_,this.height_)}this.plotter_._renderLineChart(this.highlightSet_,i)}else if(this.previousVerticalX_>=0){var o=0,s=this.attr_("labels");for(a=1;ao&&(o=l)}var h=this.previousVerticalX_;i.clearRect(h-o-1,0,2*o+2,this.height_)}if(this.isUsingExcanvas_&&this.currentZoomRectArgs_&&t.prototype.drawZoomRect_.apply(this,this.currentZoomRectArgs_),this.selPoints_.length>0){var p=this.selPoints_[0].canvasx;for(i.save(),a=0;a=0){t!=this.lastRow_&&(i=!0),this.lastRow_=t;for(var r=0;r=0&&(i=!0),this.lastRow_=-1;return this.selPoints_.length?this.lastx_=this.selPoints_[0].xval:this.lastx_=-1,void 0!==e&&(this.highlightSet_!==e&&(i=!0),this.highlightSet_=e),void 0!==a&&(this.lockedSet_=a),i&&this.updateSelection_(void 0),i},t.prototype.mouseOut_=function(t){this.getFunctionOption("unhighlightCallback")&&this.getFunctionOption("unhighlightCallback").call(this,t),this.getBooleanOption("hideOverlayOnMouseOut")&&!this.lockedSet_&&this.clearSelection()},t.prototype.clearSelection=function(){return this.cascadeEvents_("deselect",{}),this.lockedSet_=!1,this.fadeLevel?void this.animateSelection_(-1):(this.canvas_ctx_.clearRect(0,0,this.width_,this.height_),this.fadeLevel=0,this.selPoints_=[],this.lastx_=-1,this.lastRow_=-1,void(this.highlightSet_=null))},t.prototype.getSelection=function(){if(!this.selPoints_||this.selPoints_.length<1)return-1;for(var t=0;t1&&(a=this.dataHandler_.rollingAverage(a,this.rollPeriod_,this.attributes_)),this.rolledSeries_.push(a)}this.drawGraph_();var i=new Date;this.drawingTimeMs_=i-t},t.PointType=void 0,t.stackPoints_=function(t,e,a,i){for(var r=null,n=null,o=null,s=-1,l=function(e){if(!(s>=e))for(var a=e;aa[1]&&(a[1]=u),u=1;i--)if(this.visibility()[i-1]){if(a){l=e[i];var c=a[0],y=a[1];for(n=null,o=null,r=0;r=c&&null===n&&(n=r),l[r][0]<=y&&(o=r);null===n&&(n=0);for(var _=n,v=!0;v&&_>0;)_--,v=null===l[_][1];null===o&&(o=l.length-1);var f=o;for(v=!0;v&&f0&&(this.setIndexByName_[n[0]]=0);for(var o=0,s=1;s0;){var a=this.readyFns_.pop();a(this)}},t.prototype.computeYAxes_=function(){var e,a,i,r,n;if(void 0!==this.axes_&&this.user_attrs_.hasOwnProperty("valueRange")===!1)for(e=[],i=0;ii;i++)this.axes_[i].valueWindow=e[i]}for(a=0;al;l++){var h=this.axes_[l],p=this.attributes_.getForAxis("logscale",l),g=this.attributes_.getForAxis("includeZero",l),d=this.attributes_.getForAxis("independentTicks",l);if(i=this.attributes_.seriesForAxis(l),e=!0,r=.1,null!==this.getNumericOption("yRangePad")&&(e=!1,r=this.getNumericOption("yRangePad")/this.plotter_.area.h),0===i.length)h.extremeRange=[0,1];else{for(var u,c,y=1/0,_=-(1/0),v=0;v0&&(y=0),0>_&&(_=0)),y==1/0&&(y=0),_==-(1/0)&&(_=1),a=_-y,0===a&&(0!==_?a=Math.abs(_):(_=1,a=1));var f,x;if(p)if(e)f=_+r*a,x=y;else{var m=Math.exp(Math.log(a)*r);f=_*m,x=y/m}else f=_+r*a,x=y-r*a,e&&!this.getBooleanOption("avoidMinZero")&&(0>x&&y>=0&&(x=0),f>0&&0>=_&&(f=0));h.extremeRange=[x,f]}if(h.valueWindow)h.computedValueRange=[h.valueWindow[0],h.valueWindow[1]];else if(h.valueRange){var D=o(h.valueRange[0])?h.extremeRange[0]:h.valueRange[0],w=o(h.valueRange[1])?h.extremeRange[1]:h.valueRange[1];if(!e)if(h.logscale){var m=Math.exp(Math.log(a)*r);D*=m,w/=m}else a=w-D,D-=a*r,w+=a*r;h.computedValueRange=[D,w]}else h.computedValueRange=h.extremeRange;if(d){h.independentTicks=d;var A=this.optionsViewForAxis_("y"+(l?"2":"")),b=A("ticker");h.ticks=b(h.computedValueRange[0],h.computedValueRange[1],this.plotter_.area.h,A,this),n||(n=h)}}if(void 0===n)throw'Configuration Error: At least one axis has to have the "independentTicks" option activated.';for(var l=0;s>l;l++){var h=this.axes_[l];if(!h.independentTicks){for(var A=this.optionsViewForAxis_("y"+(l?"2":"")),b=A("ticker"),T=n.ticks,E=n.computedValueRange[1]-n.computedValueRange[0],C=h.computedValueRange[1]-h.computedValueRange[0],L=[],P=0;P0&&"e"!=t[a-1]&&"E"!=t[a-1]||t.indexOf("/")>=0||isNaN(parseFloat(t))?e=!0:8==t.length&&t>"19700101"&&"20371231">t&&(e=!0),this.setXAxisOptions_(e)},t.prototype.setXAxisOptions_=function(e){e?(this.attrs_.xValueParser=t.dateParser,this.attrs_.axes.x.valueFormatter=t.dateValueFormatter,this.attrs_.axes.x.ticker=t.dateTicker,this.attrs_.axes.x.axisLabelFormatter=t.dateAxisLabelFormatter):(this.attrs_.xValueParser=function(t){return parseFloat(t)},this.attrs_.axes.x.valueFormatter=function(t){return t},this.attrs_.axes.x.ticker=t.numericTicks,this.attrs_.axes.x.axisLabelFormatter=this.attrs_.axes.x.valueFormatter)},t.prototype.parseCSV_=function(e){var a,i,r=[],n=t.detectLineDelimiter(e),o=e.split(n||"\n"),s=this.getStringOption("delimiter");-1==o[0].indexOf(s)&&o[0].indexOf(" ")>=0&&(s=" ");var l=0;"labels"in this.user_attrs_||(l=1,this.attrs_.labels=o[0].split(s),this.attributes_.reparseSeries());for(var h,p=0,g=!1,d=this.attr_("labels").length,u=!1,c=l;c0&&v[0]0;)e=String.fromCharCode(65+(t-1)%26)+e.toLowerCase(),t=Math.floor((t-1)/26);return e},i=e.getNumberOfColumns(),r=e.getNumberOfRows(),n=e.getColumnType(0);if("date"==n||"datetime"==n)this.attrs_.xValueParser=t.dateParser,this.attrs_.axes.x.valueFormatter=t.dateValueFormatter,this.attrs_.axes.x.ticker=t.dateTicker,this.attrs_.axes.x.axisLabelFormatter=t.dateAxisLabelFormatter;else{if("number"!=n)return console.error("only 'date', 'datetime' and 'number' types are supported for column 1 of DataTable input (Got '"+n+"')"),null;this.attrs_.xValueParser=function(t){return parseFloat(t)},this.attrs_.axes.x.valueFormatter=function(t){return t},this.attrs_.axes.x.ticker=t.numericTicks,this.attrs_.axes.x.axisLabelFormatter=this.attrs_.axes.x.valueFormatter}var o,s,l=[],h={},p=!1;for(o=1;i>o;o++){var g=e.getColumnType(o);if("number"==g)l.push(o);else if("string"==g&&this.getBooleanOption("displayAnnotations")){var d=l[l.length-1];h.hasOwnProperty(d)?h[d].push(o):h[d]=[o],p=!0}else console.error("Only 'number' is supported as a dependent type with Gviz. 'string' is only supported if displayAnnotations is true")}var u=[e.getColumnLabel(0)];for(o=0;oo;o++){var v=[];if("undefined"!=typeof e.getValue(o,0)&&null!==e.getValue(o,0)){if(v.push("date"==n||"datetime"==n?e.getValue(o,0).getTime():e.getValue(o,0)),this.getBooleanOption("errorBars"))for(s=0;i-1>s;s++)v.push([e.getValue(o,1+2*s),e.getValue(o,2+2*s)]);else{for(s=0;s0&&v[0]0&&this.setAnnotations(_,!0),this.attributes_.reparseSeries()},t.prototype.cascadeDataDidUpdateEvent_=function(){this.cascadeEvents_("dataDidUpdate",{})},t.prototype.start_=function(){var e=this.file_;if("function"==typeof e&&(e=e()),t.isArrayLike(e))this.rawData_=this.parseArray_(e),this.cascadeDataDidUpdateEvent_(),this.predraw_();else if("object"==typeof e&&"function"==typeof e.getColumnRange)this.parseDataTable_(e),this.cascadeDataDidUpdateEvent_(),this.predraw_();else if("string"==typeof e){var a=t.detectLineDelimiter(e);if(a)this.loadedEvent_(e);else{var i;i=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP");var r=this;i.onreadystatechange=function(){4==i.readyState&&(200===i.status||0===i.status)&&r.loadedEvent_(i.responseText)},i.open("GET",e,!0),i.send(null)}}else console.error("Unknown data format: "+typeof e)},t.prototype.updateOptions=function(e,a){"undefined"==typeof a&&(a=!1);var i=e.file,r=t.mapLegacyOptions_(e);"rollPeriod"in r&&(this.rollPeriod_=r.rollPeriod),"dateWindow"in r&&(this.dateWindow_=r.dateWindow,"isZoomedIgnoreProgrammaticZoom"in r||(this.zoomed_x_=null!==r.dateWindow)),"valueRange"in r&&!("isZoomedIgnoreProgrammaticZoom"in r)&&(this.zoomed_y_=null!==r.valueRange);var n=t.isPixelChangingOptionList(this.attr_("labels"),r);t.updateDeep(this.user_attrs_,r),this.attributes_.reparseSeries(),i?(this.cascadeEvents_("dataWillUpdate",{}),this.file_=i,a||this.start_()):a||(n?this.predraw_():this.renderGraph_(!1))},t.mapLegacyOptions_=function(t){var e={};for(var a in t)t.hasOwnProperty(a)&&"file"!=a&&t.hasOwnProperty(a)&&(e[a]=t[a]);var i=function(t,a,i){e.axes||(e.axes={}),e.axes[t]||(e.axes[t]={}),e.axes[t][a]=i},r=function(a,r,n){"undefined"!=typeof t[a]&&(console.warn("Option "+a+" is deprecated. Use the "+n+" option for the "+r+" axis instead. (e.g. { axes : { "+r+" : { "+n+" : ... } } } (see http://dygraphs.com/per-axis.html for more information."),i(r,n,t[a]),delete e[a])};return r("xValueFormatter","x","valueFormatter"),r("pixelsPerXLabel","x","pixelsPerLabel"),r("xAxisLabelFormatter","x","axisLabelFormatter"),r("xTicker","x","ticker"),r("yValueFormatter","y","valueFormatter"),r("pixelsPerYLabel","y","pixelsPerLabel"),r("yAxisLabelFormatter","y","axisLabelFormatter"),r("yTicker","y","ticker"),r("drawXGrid","x","drawGrid"),r("drawXAxis","x","drawAxis"),r("drawYGrid","y","drawGrid"),r("drawYAxis","y","drawAxis"),r("xAxisLabelWidth","x","axisLabelWidth"),r("yAxisLabelWidth","y","axisLabelWidth"),e},t.prototype.resize=function(t,e){if(!this.resize_lock){this.resize_lock=!0,null===t!=(null===e)&&(console.warn("Dygraph.resize() should be called with zero parameters or two non-NULL parameters. Pretending it was zero."),t=e=null);var a=this.width_,i=this.height_;t?(this.maindiv_.style.width=t+"px",this.maindiv_.style.height=e+"px",this.width_=t,this.height_=e):(this.width_=this.maindiv_.clientWidth,this.height_=this.maindiv_.clientHeight),(a!=this.width_||i!=this.height_)&&(this.resizeElements_(),this.predraw_()),this.resize_lock=!1}},t.prototype.adjustRoll=function(t){this.rollPeriod_=t,this.predraw_()},t.prototype.visibility=function(){for(this.getOption("visibility")||(this.attrs_.visibility=[]);this.getOption("visibility").lengtht||t>=a.length?console.warn("invalid series number in setVisibility: "+t):(a[t]=e,this.predraw_())},t.prototype.size=function(){return{width:this.width_,height:this.height_}},t.prototype.setAnnotations=function(e,a){return t.addAnnotationRule(),this.annotations_=e,this.layout_?(this.layout_.setAnnotations(this.annotations_),void(a||this.predraw_())):void console.warn("Tried to setAnnotations before dygraph was ready. Try setting them in a ready() block. See dygraphs.com/tests/annotation.html")},t.prototype.annotations=function(){return this.annotations_},t.prototype.getLabels=function(){var t=this.attr_("labels");return t?t.slice():null},t.prototype.indexFromSetName=function(t){return this.setIndexByName_[t]},t.prototype.ready=function(t){this.is_initial_draw_?this.readyFns_.push(t):t.call(this,this)},t.addAnnotationRule=function(){if(!t.addedAnnotationCSS){var e="border: 1px solid black; background-color: white; text-align: center;",a=document.createElement("style");a.type="text/css",document.getElementsByTagName("head")[0].appendChild(a);for(var i=0;it?"0"+t:""+t},Dygraph.DateAccessorsLocal={getFullYear:function(t){return t.getFullYear()},getMonth:function(t){return t.getMonth()},getDate:function(t){return t.getDate()},getHours:function(t){return t.getHours()},getMinutes:function(t){return t.getMinutes()},getSeconds:function(t){return t.getSeconds()},getMilliseconds:function(t){return t.getMilliseconds()},getDay:function(t){return t.getDay()},makeDate:function(t,e,a,i,r,n,o){return new Date(t,e,a,i,r,n,o)}},Dygraph.DateAccessorsUTC={getFullYear:function(t){return t.getUTCFullYear()},getMonth:function(t){return t.getUTCMonth()},getDate:function(t){return t.getUTCDate()},getHours:function(t){return t.getUTCHours()},getMinutes:function(t){return t.getUTCMinutes()},getSeconds:function(t){return t.getUTCSeconds()},getMilliseconds:function(t){return t.getUTCMilliseconds()},getDay:function(t){return t.getUTCDay()},makeDate:function(t,e,a,i,r,n,o){return new Date(Date.UTC(t,e,a,i,r,n,o))}},Dygraph.hmsString_=function(t,e,a){var i=Dygraph.zeropad,r=i(t)+":"+i(e);return a&&(r+=":"+i(a)),r},Dygraph.dateString_=function(t,e){var a=Dygraph.zeropad,i=e?Dygraph.DateAccessorsUTC:Dygraph.DateAccessorsLocal,r=new Date(t),n=i.getFullYear(r),o=i.getMonth(r),s=i.getDate(r),l=i.getHours(r),h=i.getMinutes(r),p=i.getSeconds(r),g=""+n,d=a(o+1),u=a(s),c=3600*l+60*h+p,y=g+"/"+d+"/"+u;return c&&(y+=" "+Dygraph.hmsString_(l,h,p)),y},Dygraph.round_=function(t,e){var a=Math.pow(10,e);return Math.round(t*a)/a},Dygraph.binarySearch=function(t,e,a,i,r){if((null===i||void 0===i||null===r||void 0===r)&&(i=0,r=e.length-1),i>r)return-1;(null===a||void 0===a)&&(a=0);var n,o=function(t){return t>=0&&tt?a>0&&(n=s-1,o(n)&&e[n]l?0>a&&(n=s+1,o(n)&&e[n]>t)?s:Dygraph.binarySearch(t,e,a,s+1,r):-1},Dygraph.dateParser=function(t){var e,a;if((-1==t.search("-")||-1!=t.search("T")||-1!=t.search("Z"))&&(a=Dygraph.dateStrToMillis(t),a&&!isNaN(a)))return a;if(-1!=t.search("-")){for(e=t.replace("-","/","g");-1!=e.search("-");)e=e.replace("-","/");a=Dygraph.dateStrToMillis(e)}else 8==t.length?(e=t.substr(0,4)+"/"+t.substr(4,2)+"/"+t.substr(6,2),a=Dygraph.dateStrToMillis(e)):a=Dygraph.dateStrToMillis(t);return(!a||isNaN(a))&&console.error("Couldn't parse "+t+" as a date"),a},Dygraph.dateStrToMillis=function(t){return new Date(t).getTime()},Dygraph.update=function(t,e){if("undefined"!=typeof e&&null!==e)for(var a in e)e.hasOwnProperty(a)&&(t[a]=e[a]);return t},Dygraph.updateDeep=function(t,e){function a(t){return"object"==typeof Node?t instanceof Node:"object"==typeof t&&"number"==typeof t.nodeType&&"string"==typeof t.nodeName}if("undefined"!=typeof e&&null!==e)for(var i in e)e.hasOwnProperty(i)&&(null===e[i]?t[i]=null:Dygraph.isArrayLike(e[i])?t[i]=e[i].slice():a(e[i])?t[i]=e[i]:"object"==typeof e[i]?(("object"!=typeof t[i]||null===t[i])&&(t[i]={}),Dygraph.updateDeep(t[i],e[i])):t[i]=e[i]);return t},Dygraph.isArrayLike=function(t){var e=typeof t;return"object"!=e&&("function"!=e||"function"!=typeof t.item)||null===t||"number"!=typeof t.length||3===t.nodeType?!1:!0},Dygraph.isDateLike=function(t){return"object"!=typeof t||null===t||"function"!=typeof t.getTime?!1:!0},Dygraph.clone=function(t){for(var e=[],a=0;a=e||Dygraph.requestAnimFrame.call(window,function(){var e=(new Date).getTime(),h=e-o;r=n,n=Math.floor(h/a);var p=n-r,g=n+p>s;g||n>=s?(t(s),i()):(0!==p&&t(n),l())})}()};var e={annotationClickHandler:!0,annotationDblClickHandler:!0,annotationMouseOutHandler:!0,annotationMouseOverHandler:!0,axisLabelColor:!0,axisLineColor:!0,axisLineWidth:!0,clickCallback:!0,drawCallback:!0,drawHighlightPointCallback:!0,drawPoints:!0,drawPointCallback:!0,drawXGrid:!0,drawYGrid:!0,fillAlpha:!0,gridLineColor:!0,gridLineWidth:!0,hideOverlayOnMouseOut:!0,highlightCallback:!0,highlightCircleSize:!0,interactionModel:!0,isZoomedIgnoreProgrammaticZoom:!0,labelsDiv:!0,labelsDivStyles:!0,labelsDivWidth:!0,labelsKMB:!0,labelsKMG2:!0,labelsSeparateLines:!0,labelsShowZeroValues:!0,legend:!0,panEdgeFraction:!0,pixelsPerYLabel:!0,pointClickCallback:!0,pointSize:!0,rangeSelectorPlotFillColor:!0,rangeSelectorPlotStrokeColor:!0,showLabelsOnHighlight:!0,showRoller:!0,strokeWidth:!0,underlayCallback:!0,unhighlightCallback:!0,zoomCallback:!0};Dygraph.isPixelChangingOptionList=function(t,a){var i={};if(t)for(var r=1;re?1/Math.pow(t,-e):Math.pow(t,e)};var a=/^rgba?\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})(?:,\s*([01](?:\.\d+)?))?\)$/;Dygraph.toRGB_=function(e){var a=t(e);if(a)return a;var i=document.createElement("div");i.style.backgroundColor=e,i.style.visibility="hidden",document.body.appendChild(i);var r;return r=window.getComputedStyle?window.getComputedStyle(i,null).backgroundColor:i.currentStyle.backgroundColor,document.body.removeChild(i),t(r)},Dygraph.isCanvasSupported=function(t){var e;try{e=t||document.createElement("canvas"),e.getContext("2d")}catch(a){var i=navigator.appVersion.match(/MSIE (\d\.\d)/),r=-1!=navigator.userAgent.toLowerCase().indexOf("opera");return!i||i[1]<6||r?!1:!0}return!0},Dygraph.parseFloat_=function(t,e,a){var i=parseFloat(t);if(!isNaN(i))return i;if(/^ *$/.test(t))return null;if(/^ *nan *$/i.test(t))return 0/0;var r="Unable to parse '"+t+"' as a number";return void 0!==a&&void 0!==e&&(r+=" on line "+(1+(e||0))+" ('"+a+"') of CSV."),console.error(r),null}}(),function(){"use strict";Dygraph.GVizChart=function(t){this.container=t},Dygraph.GVizChart.prototype.draw=function(t,e){this.container.innerHTML="","undefined"!=typeof this.date_graph&&this.date_graph.destroy(),this.date_graph=new Dygraph(this.container,t,e)},Dygraph.GVizChart.prototype.setSelection=function(t){var e=!1;t.length&&(e=t[0].row),this.date_graph.setSelection(e)},Dygraph.GVizChart.prototype.getSelection=function(){var t=[],e=this.date_graph.getSelection();if(0>e)return t;for(var a=this.date_graph.layout_.points,i=0;ii&&2>r&&void 0!==e.lastx_&&-1!=e.lastx_&&Dygraph.Interaction.treatMouseOpAsClick(e,t,a),a.regionWidth=i,a.regionHeight=r},Dygraph.Interaction.startPan=function(t,e,a){var i,r;a.isPanning=!0;var n=e.xAxisRange();if(e.getOptionForAxis("logscale","x")?(a.initialLeftmostDate=Dygraph.log10(n[0]),a.dateRange=Dygraph.log10(n[1])-Dygraph.log10(n[0])):(a.initialLeftmostDate=n[0],a.dateRange=n[1]-n[0]),a.xUnitsPerPixel=a.dateRange/(e.plotter_.area.w-1),e.getNumericOption("panEdgeFraction")){var o=e.width_*e.getNumericOption("panEdgeFraction"),s=e.xAxisExtremes(),l=e.toDomXCoord(s[0])-o,h=e.toDomXCoord(s[1])+o,p=e.toDataXCoord(l),g=e.toDataXCoord(h);a.boundedDates=[p,g];var d=[],u=e.height_*e.getNumericOption("panEdgeFraction");for(i=0;ia.boundedDates[1]&&(i-=r-a.boundedDates[1],r=i+a.dateRange),e.getOptionForAxis("logscale","x")?e.dateWindow_=[Math.pow(Dygraph.LOG_SCALE,i),Math.pow(Dygraph.LOG_SCALE,r)]:e.dateWindow_=[i,r],a.is2DPan)for(var n=a.dragEndY-a.dragStartY,o=0;oi?Dygraph.VERTICAL:Dygraph.HORIZONTAL,e.drawZoomRect_(a.dragDirection,a.dragStartX,a.dragEndX,a.dragStartY,a.dragEndY,a.prevDragDirection,a.prevEndX,a.prevEndY),a.prevEndX=a.dragEndX,a.prevEndY=a.dragEndY,a.prevDragDirection=a.dragDirection},Dygraph.Interaction.treatMouseOpAsClick=function(t,e,a){for(var i=t.getFunctionOption("clickCallback"),r=t.getFunctionOption("pointClickCallback"),n=null,o=-1,s=Number.MAX_VALUE,l=0;lp)&&(s=p,o=l)}var g=t.getNumericOption("highlightCircleSize")+2;if(g*g>=s&&(n=t.selPoints_[o]),n){var d={cancelable:!0,point:n,canvasx:a.dragEndX,canvasy:a.dragEndY},u=t.cascadeEvents_("pointClick",d);if(u)return;r&&r.call(t,e,n)}var d={cancelable:!0,xval:t.lastx_,pts:t.selPoints_,canvasx:a.dragEndX,canvasy:a.dragEndY};t.cascadeEvents_("click",d)||i&&i.call(t,e,t.lastx_,t.selPoints_)},Dygraph.Interaction.endZoom=function(t,e,a){e.clearZoomRect_(),a.isZooming=!1,Dygraph.Interaction.maybeTreatMouseOpAsClick(t,e,a);var i=e.getArea();if(a.regionWidth>=10&&a.dragDirection==Dygraph.HORIZONTAL){var r=Math.min(a.dragStartX,a.dragEndX),n=Math.max(a.dragStartX,a.dragEndX);r=Math.max(r,i.x),n=Math.min(n,i.x+i.w),n>r&&e.doZoomX_(r,n),a.cancelNextDblclick=!0}else if(a.regionHeight>=10&&a.dragDirection==Dygraph.VERTICAL){var o=Math.min(a.dragStartY,a.dragEndY),s=Math.max(a.dragStartY,a.dragEndY);o=Math.max(o,i.y),s=Math.min(s,i.y+i.h),s>o&&e.doZoomY_(o,s),a.cancelNextDblclick=!0}a.dragStartX=null,a.dragStartY=null},Dygraph.Interaction.startTouch=function(t,e,a){t.preventDefault(),t.touches.length>1&&(a.startTimeForDoubleTapMs=null);for(var i=[],r=0;r=2){a.initialPinchCenter={pageX:.5*(i[0].pageX+i[1].pageX),pageY:.5*(i[0].pageY+i[1].pageY),dataX:.5*(i[0].dataX+i[1].dataX),dataY:.5*(i[0].dataY+i[1].dataY)};var o=180/Math.PI*Math.atan2(a.initialPinchCenter.pageY-i[0].pageY,i[0].pageX-a.initialPinchCenter.pageX);o=Math.abs(o),o>90&&(o=90-o),a.touchDirections={x:67.5>o,y:o>22.5}}a.initialRange={x:e.xAxisRange(),y:e.yAxisRange()}},Dygraph.Interaction.moveTouch=function(t,e,a){a.startTimeForDoubleTapMs=null;var i,r=[];for(i=0;i=2){var c=s[1].pageX-l.pageX;d=(r[1].pageX-o.pageX)/c;var y=s[1].pageY-l.pageY;u=(r[1].pageY-o.pageY)/y}d=Math.min(8,Math.max(.125,d)),u=Math.min(8,Math.max(.125,u));var _=!1;if(a.touchDirections.x&&(e.dateWindow_=[l.dataX-h.dataX+(a.initialRange.x[0]-l.dataX)/d,l.dataX-h.dataX+(a.initialRange.x[1]-l.dataX)/d],_=!0),a.touchDirections.y)for(i=0;1>i;i++){var v=e.axes_[i],f=e.attributes_.getForAxis("logscale",i);f||(v.valueWindow=[l.dataY-h.dataY+(a.initialRange.y[0]-l.dataY)/u,l.dataY-h.dataY+(a.initialRange.y[1]-l.dataY)/u],_=!0)}if(e.drawGraph_(!1),_&&r.length>1&&e.getFunctionOption("zoomCallback")){var x=e.xAxisRange();e.getFunctionOption("zoomCallback").call(e,x[0],x[1],e.yAxisRanges())}},Dygraph.Interaction.endTouch=function(t,e,a){if(0!==t.touches.length)Dygraph.Interaction.startTouch(t,e,a);else if(1==t.changedTouches.length){var i=(new Date).getTime(),r=t.changedTouches[0];a.startTimeForDoubleTapMs&&i-a.startTimeForDoubleTapMs<500&&a.doubleTapX&&Math.abs(a.doubleTapX-r.screenX)<50&&a.doubleTapY&&Math.abs(a.doubleTapY-r.screenY)<50?e.resetZoom():(a.startTimeForDoubleTapMs=i,a.doubleTapX=r.screenX,a.doubleTapY=r.screenY)}};var e=function(t,e,a){return e>t?e-t:t>a?t-a:0},a=function(t,a){var i=Dygraph.findPos(a.canvas_),r={left:i.x,right:i.x+a.canvas_.offsetWidth,top:i.y,bottom:i.y+a.canvas_.offsetHeight},n={x:Dygraph.pageX(t),y:Dygraph.pageY(t)},o=e(n.x,r.left,r.right),s=e(n.y,r.top,r.bottom);return Math.max(o,s)};Dygraph.Interaction.defaultModel={mousedown:function(e,i,r){if(!e.button||2!=e.button){r.initializeMouseDown(e,i,r),e.altKey||e.shiftKey?Dygraph.startPan(e,i,r):Dygraph.startZoom(e,i,r);var n=function(e){if(r.isZooming){var n=a(e,i);t>n?Dygraph.moveZoom(e,i,r):null!==r.dragEndX&&(r.dragEndX=null,r.dragEndY=null,i.clearZoomRect_())}else r.isPanning&&Dygraph.movePan(e,i,r)},o=function(t){r.isZooming?null!==r.dragEndX?Dygraph.endZoom(t,i,r):Dygraph.Interaction.maybeTreatMouseOpAsClick(t,i,r):r.isPanning&&Dygraph.endPan(t,i,r),Dygraph.removeEvent(document,"mousemove",n),Dygraph.removeEvent(document,"mouseup",o),r.destroy()};i.addAndTrackEvent(document,"mousemove",n),i.addAndTrackEvent(document,"mouseup",o)}},willDestroyContextMyself:!0,touchstart:function(t,e,a){Dygraph.Interaction.startTouch(t,e,a)},touchmove:function(t,e,a){Dygraph.Interaction.moveTouch(t,e,a)},touchend:function(t,e,a){Dygraph.Interaction.endTouch(t,e,a)},dblclick:function(t,e,a){if(a.cancelNextDblclick)return void(a.cancelNextDblclick=!1);var i={canvasx:a.dragEndX,canvasy:a.dragEndY};e.cascadeEvents_("dblclick",i)||t.altKey||t.shiftKey||e.resetZoom()}},Dygraph.DEFAULT_ATTRS.interactionModel=Dygraph.Interaction.defaultModel,Dygraph.defaultInteractionModel=Dygraph.Interaction.defaultModel,Dygraph.endZoom=Dygraph.Interaction.endZoom,Dygraph.moveZoom=Dygraph.Interaction.moveZoom,Dygraph.startZoom=Dygraph.Interaction.startZoom,Dygraph.endPan=Dygraph.Interaction.endPan,Dygraph.movePan=Dygraph.Interaction.movePan,Dygraph.startPan=Dygraph.Interaction.startPan,Dygraph.Interaction.nonInteractiveModel_={mousedown:function(t,e,a){a.initializeMouseDown(t,e,a)},mouseup:Dygraph.Interaction.maybeTreatMouseOpAsClick},Dygraph.Interaction.dragIsPanInteractionModel={mousedown:function(t,e,a){a.initializeMouseDown(t,e,a),Dygraph.startPan(t,e,a)},mousemove:function(t,e,a){a.isPanning&&Dygraph.movePan(t,e,a)},mouseup:function(t,e,a){a.isPanning&&Dygraph.endPan(t,e,a)}}}(),function(){"use strict";Dygraph.TickList=void 0,Dygraph.Ticker=void 0,Dygraph.numericLinearTicks=function(t,e,a,i,r,n){var o=function(t){return"logscale"===t?!1:i(t)};return Dygraph.numericTicks(t,e,a,o,r,n)},Dygraph.numericTicks=function(t,e,a,i,r,n){var o,s,l,h,p=i("pixelsPerLabel"),g=[];if(n)for(o=0;o=h/4){for(var y=u;y>=d;y--){var _=Dygraph.PREFERRED_LOG_TICK_VALUES[y],v=Math.log(_/t)/Math.log(e/t)*a,f={v:_};null===c?c={tickValue:_,pixel_coord:v}:Math.abs(v-c.pixel_coord)>=p?c={tickValue:_,pixel_coord:v}:f.label="",g.push(f)}g.reverse()}}if(0===g.length){var x,m,D=i("labelsKMG2");D?(x=[1,2,4,8,16,32,64,128,256],m=16):(x=[1,2,5,10,20,50,100],m=10);var w,A,b,T,E=Math.ceil(a/p),C=Math.abs(e-t)/E,L=Math.floor(Math.log(C)/Math.log(m)),P=Math.pow(m,L);for(s=0;sp));s++);for(A>b&&(w*=-1),o=0;h>=o;o++)l=A+o*w,g.push({v:l})}}var S=i("axisLabelFormatter");for(o=0;o=0?Dygraph.getDateAxis(t,e,o,i,r):[]},Dygraph.SECONDLY=0,Dygraph.TWO_SECONDLY=1,Dygraph.FIVE_SECONDLY=2,Dygraph.TEN_SECONDLY=3,Dygraph.THIRTY_SECONDLY=4,Dygraph.MINUTELY=5,Dygraph.TWO_MINUTELY=6,Dygraph.FIVE_MINUTELY=7,Dygraph.TEN_MINUTELY=8,Dygraph.THIRTY_MINUTELY=9,Dygraph.HOURLY=10,Dygraph.TWO_HOURLY=11,Dygraph.SIX_HOURLY=12,Dygraph.DAILY=13,Dygraph.TWO_DAILY=14,Dygraph.WEEKLY=15,Dygraph.MONTHLY=16,Dygraph.QUARTERLY=17,Dygraph.BIANNUAL=18,Dygraph.ANNUAL=19,Dygraph.DECADAL=20,Dygraph.CENTENNIAL=21,Dygraph.NUM_GRANULARITIES=22,Dygraph.DATEFIELD_Y=0,Dygraph.DATEFIELD_M=1,Dygraph.DATEFIELD_D=2,Dygraph.DATEFIELD_HH=3,Dygraph.DATEFIELD_MM=4,Dygraph.DATEFIELD_SS=5,Dygraph.DATEFIELD_MS=6,Dygraph.NUM_DATEFIELDS=7,Dygraph.TICK_PLACEMENT=[],Dygraph.TICK_PLACEMENT[Dygraph.SECONDLY]={datefield:Dygraph.DATEFIELD_SS,step:1,spacing:1e3},Dygraph.TICK_PLACEMENT[Dygraph.TWO_SECONDLY]={datefield:Dygraph.DATEFIELD_SS,step:2,spacing:2e3},Dygraph.TICK_PLACEMENT[Dygraph.FIVE_SECONDLY]={datefield:Dygraph.DATEFIELD_SS,step:5,spacing:5e3},Dygraph.TICK_PLACEMENT[Dygraph.TEN_SECONDLY]={datefield:Dygraph.DATEFIELD_SS,step:10,spacing:1e4},Dygraph.TICK_PLACEMENT[Dygraph.THIRTY_SECONDLY]={datefield:Dygraph.DATEFIELD_SS,step:30,spacing:3e4},Dygraph.TICK_PLACEMENT[Dygraph.MINUTELY]={datefield:Dygraph.DATEFIELD_MM,step:1,spacing:6e4},Dygraph.TICK_PLACEMENT[Dygraph.TWO_MINUTELY]={datefield:Dygraph.DATEFIELD_MM,step:2,spacing:12e4},Dygraph.TICK_PLACEMENT[Dygraph.FIVE_MINUTELY]={datefield:Dygraph.DATEFIELD_MM,step:5,spacing:3e5},Dygraph.TICK_PLACEMENT[Dygraph.TEN_MINUTELY]={datefield:Dygraph.DATEFIELD_MM,step:10,spacing:6e5},Dygraph.TICK_PLACEMENT[Dygraph.THIRTY_MINUTELY]={datefield:Dygraph.DATEFIELD_MM,step:30,spacing:18e5},Dygraph.TICK_PLACEMENT[Dygraph.HOURLY]={datefield:Dygraph.DATEFIELD_HH,step:1,spacing:36e5},Dygraph.TICK_PLACEMENT[Dygraph.TWO_HOURLY]={datefield:Dygraph.DATEFIELD_HH,step:2,spacing:72e5},Dygraph.TICK_PLACEMENT[Dygraph.SIX_HOURLY]={datefield:Dygraph.DATEFIELD_HH,step:6,spacing:216e5},Dygraph.TICK_PLACEMENT[Dygraph.DAILY]={datefield:Dygraph.DATEFIELD_D,step:1,spacing:864e5},Dygraph.TICK_PLACEMENT[Dygraph.TWO_DAILY]={datefield:Dygraph.DATEFIELD_D,step:2,spacing:1728e5},Dygraph.TICK_PLACEMENT[Dygraph.WEEKLY]={datefield:Dygraph.DATEFIELD_D,step:7,spacing:6048e5},Dygraph.TICK_PLACEMENT[Dygraph.MONTHLY]={datefield:Dygraph.DATEFIELD_M,step:1,spacing:2629817280},Dygraph.TICK_PLACEMENT[Dygraph.QUARTERLY]={datefield:Dygraph.DATEFIELD_M,step:3,spacing:216e5*365.2524},Dygraph.TICK_PLACEMENT[Dygraph.BIANNUAL]={datefield:Dygraph.DATEFIELD_M,step:6,spacing:432e5*365.2524},Dygraph.TICK_PLACEMENT[Dygraph.ANNUAL]={datefield:Dygraph.DATEFIELD_Y,step:1,spacing:864e5*365.2524},Dygraph.TICK_PLACEMENT[Dygraph.DECADAL]={datefield:Dygraph.DATEFIELD_Y,step:10,spacing:315578073600},Dygraph.TICK_PLACEMENT[Dygraph.CENTENNIAL]={datefield:Dygraph.DATEFIELD_Y,step:100,spacing:3155780736e3},Dygraph.PREFERRED_LOG_TICK_VALUES=function(){for(var t=[],e=-39;39>=e;e++)for(var a=Math.pow(10,e),i=1;9>=i;i++){var r=a*i;t.push(r)}return t}(),Dygraph.pickDateTickGranularity=function(t,e,a,i){for(var r=i("pixelsPerLabel"),n=0;n=r)return n}return-1},Dygraph.numDateTicks=function(t,e,a){var i=Dygraph.TICK_PLACEMENT[a].spacing;return Math.round(1*(e-t)/i)},Dygraph.getDateAxis=function(t,e,a,i,r){var n=i("axisLabelFormatter"),o=i("labelsUTC"),s=o?Dygraph.DateAccessorsUTC:Dygraph.DateAccessorsLocal,l=Dygraph.TICK_PLACEMENT[a].datefield,h=Dygraph.TICK_PLACEMENT[a].step,p=Dygraph.TICK_PLACEMENT[a].spacing,g=new Date(t),d=[];d[Dygraph.DATEFIELD_Y]=s.getFullYear(g),d[Dygraph.DATEFIELD_M]=s.getMonth(g),d[Dygraph.DATEFIELD_D]=s.getDate(g),d[Dygraph.DATEFIELD_HH]=s.getHours(g),d[Dygraph.DATEFIELD_MM]=s.getMinutes(g),d[Dygraph.DATEFIELD_SS]=s.getSeconds(g),d[Dygraph.DATEFIELD_MS]=s.getMilliseconds(g);var u=d[l]%h;a==Dygraph.WEEKLY&&(u=s.getDay(g)),d[l]-=u;for(var c=l+1;cv&&(v+=p,_=new Date(v));e>=v;)y.push({v:v,label:n.call(r,_,a,i,r)}),v+=p,_=new Date(v);else for(t>v&&(d[l]+=h,_=s.makeDate.apply(null,d),v=_.getTime());e>=v;)(a>=Dygraph.DAILY||s.getHours(_)%h===0)&&y.push({v:v,label:n.call(r,_,a,i,r)}),d[l]+=h,_=s.makeDate.apply(null,d),v=_.getTime();return y},Dygraph&&Dygraph.DEFAULT_ATTRS&&Dygraph.DEFAULT_ATTRS.axes&&Dygraph.DEFAULT_ATTRS.axes.x&&Dygraph.DEFAULT_ATTRS.axes.y&&Dygraph.DEFAULT_ATTRS.axes.y2&&(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.Plugins={},Dygraph.Plugins.Annotations=function(){"use strict";var t=function(){this.annotations_=[]};return t.prototype.toString=function(){return"Annotations Plugin"},t.prototype.activate=function(t){return{clearChart:this.clearChart,didDrawChart:this.didDrawChart}},t.prototype.detachLabels=function(){for(var t=0;to.x+o.w||h.canvasyo.y+o.h)){var p=h.annotation,g=6;p.hasOwnProperty("tickHeight")&&(g=p.tickHeight);var d=document.createElement("div");for(var u in r)r.hasOwnProperty(u)&&(d.style[u]=r[u]);p.hasOwnProperty("icon")||(d.className="dygraphDefaultAnnotation"),p.hasOwnProperty("cssClass")&&(d.className+=" "+p.cssClass);var c=p.hasOwnProperty("width")?p.width:16,y=p.hasOwnProperty("height")?p.height:16;if(p.hasOwnProperty("icon")){var _=document.createElement("img");_.src=p.icon,_.width=c,_.height=y,d.appendChild(_)}else h.annotation.hasOwnProperty("shortText")&&d.appendChild(document.createTextNode(h.annotation.shortText));var v=h.canvasx-c/2;d.style.left=v+"px";var f=0;if(p.attachAtBottom){var x=o.y+o.h-y-g;s[v]?x-=s[v]:s[v]=0,s[v]+=g+y,f=x}else f=h.canvasy-y-g;d.style.top=f+"px",d.style.width=c+"px",d.style.height=y+"px",d.title=h.annotation.text,d.style.color=e.colorsMap_[h.name],d.style.borderColor=e.colorsMap_[h.name],p.div=d,e.addAndTrackEvent(d,"click",n("clickHandler","annotationClickHandler",h,this)),e.addAndTrackEvent(d,"mouseover",n("mouseOverHandler","annotationMouseOverHandler",h,this)),e.addAndTrackEvent(d,"mouseout",n("mouseOutHandler","annotationMouseOutHandler",h,this)),e.addAndTrackEvent(d,"dblclick",n("dblClickHandler","annotationDblClickHandler",h,this)),i.appendChild(d),this.annotations_.push(d);var m=t.drawingContext;if(m.save(),m.strokeStyle=e.colorsMap_[h.name],m.beginPath(),p.attachAtBottom){var x=f+y;m.moveTo(h.canvasx,x),m.lineTo(h.canvasx,x+g)}else m.moveTo(h.canvasx,h.canvasy),m.lineTo(h.canvasx,h.canvasy-2-g);m.closePath(),m.stroke(),m.restore()}}},t.prototype.destroy=function(){this.detachLabels()},t}(),Dygraph.Plugins.Axes=function(){"use strict";var t=function(){this.xlabels_=[],this.ylabels_=[]};return t.prototype.toString=function(){return"Axes Plugin"},t.prototype.activate=function(t){return{layout:this.layout,clearChart:this.clearChart,willDrawChart:this.willDrawChart}},t.prototype.layout=function(t){var e=t.dygraph;if(e.getOptionForAxis("drawAxis","y")){var a=e.getOptionForAxis("axisLabelWidth","y")+2*e.getOptionForAxis("axisTickSize","y");t.reserveSpaceLeft(a)}if(e.getOptionForAxis("drawAxis","x")){var i;i=e.getOption("xAxisHeight")?e.getOption("xAxisHeight"):e.getOptionForAxis("axisLabelFontSize","x")+2*e.getOptionForAxis("axisTickSize","x"),t.reserveSpaceBottom(i)}if(2==e.numAxes()){if(e.getOptionForAxis("drawAxis","y2")){var a=e.getOptionForAxis("axisLabelWidth","y2")+2*e.getOptionForAxis("axisTickSize","y2");t.reserveSpaceRight(a)}}else e.numAxes()>2&&e.error("Only two y-axes are supported at this time. (Trying to use "+e.numAxes()+")")},t.prototype.detachLabels=function(){function t(t){for(var e=0;e0){var x=i.numAxes(),m=[f("y"),f("y2")];for(l=0;l<_.yticks.length;l++){if(s=_.yticks[l],"function"==typeof s)return;n=v.x;var D=1,w="y1",A=m[0];1==s[0]&&(n=v.x+v.w,D=-1,w="y2",A=m[1]);var b=A("axisLabelFontSize");o=v.y+s[1]*v.h,r=y(s[2],"y",2==x?w:null);var T=o-b/2;0>T&&(T=0),T+b+3>d?r.style.bottom="0":r.style.top=T+"px",0===s[0]?(r.style.left=v.x-A("axisLabelWidth")-A("axisTickSize")+"px",r.style.textAlign="right"):1==s[0]&&(r.style.left=v.x+v.w+A("axisTickSize")+"px",r.style.textAlign="left"),r.style.width=A("axisLabelWidth")+"px",p.appendChild(r),this.ylabels_.push(r)}var E=this.ylabels_[0],b=i.getOptionForAxis("axisLabelFontSize","y"),C=parseInt(E.style.top,10)+b;C>d-b&&(E.style.top=parseInt(E.style.top,10)-b/2+"px")}var L;if(i.getOption("drawAxesAtZero")){var P=i.toPercentXCoord(0);(P>1||0>P||isNaN(P))&&(P=0),L=e(v.x+P*v.w)}else L=e(v.x);h.strokeStyle=i.getOptionForAxis("axisLineColor","y"),h.lineWidth=i.getOptionForAxis("axisLineWidth","y"),h.beginPath(),h.moveTo(L,a(v.y)),h.lineTo(L,a(v.y+v.h)),h.closePath(),h.stroke(),2==i.numAxes()&&(h.strokeStyle=i.getOptionForAxis("axisLineColor","y2"),h.lineWidth=i.getOptionForAxis("axisLineWidth","y2"),h.beginPath(),h.moveTo(a(v.x+v.w),a(v.y)),h.lineTo(a(v.x+v.w),a(v.y+v.h)),h.closePath(),h.stroke())}if(i.getOptionForAxis("drawAxis","x")){if(_.xticks){var A=f("x");for(l=0;l<_.xticks.length;l++){s=_.xticks[l],n=v.x+s[0]*v.w,o=v.y+v.h,r=y(s[1],"x"),r.style.textAlign="center",r.style.top=o+A("axisTickSize")+"px";var S=n-A("axisLabelWidth")/2;S+A("axisLabelWidth")>g&&(S=g-A("axisLabelWidth"),r.style.textAlign="right"),0>S&&(S=0,r.style.textAlign="left"),r.style.left=S+"px",r.style.width=A("axisLabelWidth")+"px", +p.appendChild(r),this.xlabels_.push(r)}}h.strokeStyle=i.getOptionForAxis("axisLineColor","x"),h.lineWidth=i.getOptionForAxis("axisLineWidth","x"),h.beginPath();var O;if(i.getOption("drawAxesAtZero")){var P=i.toPercentYCoord(0,0);(P>1||0>P)&&(P=1),O=a(v.y+P*v.h)}else O=a(v.y+v.h);h.moveTo(e(v.x),O),h.lineTo(e(v.x+v.w),O),h.closePath(),h.stroke()}h.restore()}},t}(),Dygraph.Plugins.ChartLabels=function(){"use strict";var t=function(){this.title_div_=null,this.xlabel_div_=null,this.ylabel_div_=null,this.y2label_div_=null};t.prototype.toString=function(){return"ChartLabels Plugin"},t.prototype.activate=function(t){return{layout:this.layout,didDrawChart:this.didDrawChart}};var e=function(t){var e=document.createElement("div");return e.style.position="absolute",e.style.left=t.x+"px",e.style.top=t.y+"px",e.style.width=t.w+"px",e.style.height=t.h+"px",e};t.prototype.detachLabels_=function(){for(var t=[this.title_div_,this.xlabel_div_,this.ylabel_div_,this.y2label_div_],e=0;e=2);for(o=h.yticks,l.save(),n=0;n=2;for(y&&l.installPattern(_),l.strokeStyle=s.getOptionForAxis("gridLineColor","x"),l.lineWidth=s.getOptionForAxis("gridLineWidth","x"),n=0;n/g,">")};return t.prototype.select=function(e){var a=e.selectedX,i=e.selectedPoints,r=e.selectedRow,n=e.dygraph.getOption("legend");if("never"===n)return void(this.legend_div_.style.display="none");if("follow"===n){var o=e.dygraph.plotter_.area,s=e.dygraph.getOption("labelsDivWidth"),l=e.dygraph.getOptionForAxis("axisLabelWidth","y"),h=i[0].x*o.w+20,p=i[0].y*o.h-20;h+s+1>window.scrollX+window.innerWidth&&(h=h-40-s-(l-o.x)),e.dygraph.graphDiv.appendChild(this.legend_div_),this.legend_div_.style.left=l+h+"px",this.legend_div_.style.top=p+"px"}var g=t.generateLegendHTML(e.dygraph,a,i,this.one_em_width_,r);this.legend_div_.innerHTML=g,this.legend_div_.style.display=""},t.prototype.deselect=function(e){var i=e.dygraph.getOption("legend");"always"!==i&&(this.legend_div_.style.display="none");var r=a(this.legend_div_);this.one_em_width_=r;var n=t.generateLegendHTML(e.dygraph,void 0,void 0,r,null);this.legend_div_.innerHTML=n},t.prototype.didDrawChart=function(t){this.deselect(t)},t.prototype.predraw=function(t){if(this.is_generated_div_){t.dygraph.graphDiv.appendChild(this.legend_div_);var e=t.dygraph.plotter_.area,a=t.dygraph.getOption("labelsDivWidth");this.legend_div_.style.left=e.x+e.w-a-1+"px",this.legend_div_.style.top=e.y+"px",this.legend_div_.style.width=a+"px"}},t.prototype.destroy=function(){this.legend_div_=null},t.generateLegendHTML=function(t,a,r,n,o){if(t.getOption("showLabelsOnHighlight")!==!0)return"";var s,l,h,p,g,d=t.getLabels();if("undefined"==typeof a){if("always"!=t.getOption("legend"))return"";for(l=t.getOption("labelsSeparateLines"),s="",h=1;h":" "),g=t.getOption("strokePattern",d[h]),p=e(g,u.color,n),s+=""+p+" "+i(d[h])+"")}return s}var c=t.optionsViewForAxis_("x"),y=c("valueFormatter");s=y.call(t,a,c,d[0],t,o,0),""!==s&&(s+=":");var _=[],v=t.numAxes();for(h=0;v>h;h++)_[h]=t.optionsViewForAxis_("y"+(h?1+h:""));var f=t.getOption("labelsShowZeroValues");l=t.getOption("labelsSeparateLines");var x=t.getHighlightSeries();for(h=0;h");var u=t.getPropertiesForSeries(m.name),D=_[u.axis-1],w=D("valueFormatter"),A=w.call(t,m.yval,D,m.name,t,o,d.indexOf(m.name)),b=m.name==x?" class='highlight'":"";s+=" "+i(m.name)+": "+A+""}}return s},e=function(t,e,a){var i=/MSIE/.test(navigator.userAgent)&&!window.opera;if(i)return"—";if(!t||t.length<=1)return'
';var r,n,o,s,l,h=0,p=0,g=[];for(r=0;r<=t.length;r++)h+=t[r%t.length];if(l=Math.floor(a/(h-t[0])),l>1){for(r=0;rn;n++)for(r=0;p>r;r+=2)o=g[r%g.length],s=r';return d},t}(),Dygraph.Plugins.RangeSelector=function(){"use strict";var t=function(){this.isIE_=/MSIE/.test(navigator.userAgent)&&!window.opera,this.hasTouchInterface_="undefined"!=typeof TouchEvent,this.isMobileDevice_=/mobile|android/gi.test(navigator.appVersion),this.interfaceCreated_=!1};return t.prototype.toString=function(){return"RangeSelector Plugin"},t.prototype.activate=function(t){return this.dygraph_=t,this.isUsingExcanvas_=t.isUsingExcanvas_,this.getOption_("showRangeSelector")&&this.createInterface_(),{layout:this.reserveSpace_,predraw:this.renderStaticLayer_,didDrawChart:this.renderInteractiveLayer_}},t.prototype.destroy=function(){this.bgcanvas_=null,this.fgcanvas_=null,this.leftZoomHandle_=null,this.rightZoomHandle_=null,this.iePanOverlay_=null},t.prototype.getOption_=function(t,e){return this.dygraph_.getOption(t,e)},t.prototype.setDefaultOption_=function(t,e){this.dygraph_.attrs_[t]=e},t.prototype.createInterface_=function(){this.createCanvases_(),this.isUsingExcanvas_&&this.createIEPanOverlay_(),this.createZoomHandles_(),this.initInteraction_(),this.getOption_("animatedZooms")&&(console.warn("Animated zooms and range selector are not compatible; disabling animatedZooms."),this.dygraph_.updateOptions({animatedZooms:!1},!0)),this.interfaceCreated_=!0,this.addToGraph_()},t.prototype.addToGraph_=function(){var t=this.graphDiv_=this.dygraph_.graphDiv;t.appendChild(this.bgcanvas_),t.appendChild(this.fgcanvas_),t.appendChild(this.leftZoomHandle_),t.appendChild(this.rightZoomHandle_)},t.prototype.removeFromGraph_=function(){var t=this.graphDiv_;t.removeChild(this.bgcanvas_),t.removeChild(this.fgcanvas_),t.removeChild(this.leftZoomHandle_),t.removeChild(this.rightZoomHandle_),this.graphDiv_=null},t.prototype.reserveSpace_=function(t){this.getOption_("showRangeSelector")&&t.reserveSpaceBottom(this.getOption_("rangeSelectorHeight")+4)},t.prototype.renderStaticLayer_=function(){this.updateVisibility_()&&(this.resize_(),this.drawStaticLayer_())},t.prototype.renderInteractiveLayer_=function(){this.updateVisibility_()&&!this.isChangingRange_&&(this.placeZoomHandles_(),this.drawInteractiveLayer_())},t.prototype.updateVisibility_=function(){var t=this.getOption_("showRangeSelector");if(t)this.interfaceCreated_?this.graphDiv_&&this.graphDiv_.parentNode||this.addToGraph_():this.createInterface_();else if(this.graphDiv_){this.removeFromGraph_();var e=this.dygraph_;setTimeout(function(){e.width_=0,e.resize()},1)}return t},t.prototype.resize_=function(){function t(t,e,a){var i=Dygraph.getContextPixelRatio(e);t.style.top=a.y+"px",t.style.left=a.x+"px",t.width=a.w*i,t.height=a.h*i,t.style.width=a.w+"px",t.style.height=a.h+"px",1!=i&&e.scale(i,i)}var e=this.dygraph_.layout_.getPlotArea(),a=0;this.dygraph_.getOptionForAxis("drawAxis","x")&&(a=this.getOption_("xAxisHeight")||this.getOption_("axisLabelFontSize")+2*this.getOption_("axisTickSize")),this.canvasRect_={x:e.x,y:e.y+e.h+a+4,w:e.w,h:this.getOption_("rangeSelectorHeight")},t(this.bgcanvas_,this.bgcanvas_ctx_,this.canvasRect_),t(this.fgcanvas_,this.fgcanvas_ctx_,this.canvasRect_)},t.prototype.createCanvases_=function(){this.bgcanvas_=Dygraph.createCanvas(),this.bgcanvas_.className="dygraph-rangesel-bgcanvas",this.bgcanvas_.style.position="absolute",this.bgcanvas_.style.zIndex=9,this.bgcanvas_ctx_=Dygraph.getContext(this.bgcanvas_),this.fgcanvas_=Dygraph.createCanvas(),this.fgcanvas_.className="dygraph-rangesel-fgcanvas",this.fgcanvas_.style.position="absolute",this.fgcanvas_.style.zIndex=9,this.fgcanvas_.style.cursor="default",this.fgcanvas_ctx_=Dygraph.getContext(this.fgcanvas_)},t.prototype.createIEPanOverlay_=function(){this.iePanOverlay_=document.createElement("div"),this.iePanOverlay_.style.position="absolute",this.iePanOverlay_.style.backgroundColor="white",this.iePanOverlay_.style.filter="alpha(opacity=0)",this.iePanOverlay_.style.display="none",this.iePanOverlay_.style.cursor="move",this.fgcanvas_.appendChild(this.iePanOverlay_)},t.prototype.createZoomHandles_=function(){var t=new Image;t.className="dygraph-rangesel-zoomhandle",t.style.position="absolute",t.style.zIndex=10,t.style.visibility="hidden",t.style.cursor="col-resize",/MSIE 7/.test(navigator.userAgent)?(t.width=7,t.height=14,t.style.backgroundColor="white",t.style.border="1px solid #333333"):(t.width=9,t.height=16,t.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAQCAYAAADESFVDAAAAAXNSR0IArs4c6QAAAAZiS0dEANAAzwDP4Z7KegAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAAd0SU1FB9sHGw0cMqdt1UwAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAaElEQVQoz+3SsRFAQBCF4Z9WJM8KCDVwownl6YXsTmCUsyKGkZzcl7zkz3YLkypgAnreFmDEpHkIwVOMfpdi9CEEN2nGpFdwD03yEqDtOgCaun7sqSTDH32I1pQA2Pb9sZecAxc5r3IAb21d6878xsAAAAAASUVORK5CYII="),this.isMobileDevice_&&(t.width*=2,t.height*=2),this.leftZoomHandle_=t,this.rightZoomHandle_=t.cloneNode(!1)},t.prototype.initInteraction_=function(){var t,e,a,i,r,n,o,s,l,h,p,g,d,u,c=this,y=document,_=0,v=null,f=!1,x=!1,m=!this.isMobileDevice_&&!this.isUsingExcanvas_,D=new Dygraph.IFrameTarp;t=function(t){var e=c.dygraph_.xAxisExtremes(),a=(e[1]-e[0])/c.canvasRect_.w,i=e[0]+(t.leftHandlePos-c.canvasRect_.x)*a,r=e[0]+(t.rightHandlePos-c.canvasRect_.x)*a;return[i,r]},e=function(t){return Dygraph.cancelEvent(t),f=!0,_=t.clientX,v=t.target?t.target:t.srcElement,("mousedown"===t.type||"dragstart"===t.type)&&(Dygraph.addEvent(y,"mousemove",a),Dygraph.addEvent(y,"mouseup",i)),c.fgcanvas_.style.cursor="col-resize",D.cover(),!0},a=function(t){if(!f)return!1;Dygraph.cancelEvent(t);var e=t.clientX-_;if(Math.abs(e)<4)return!0;_=t.clientX;var a,i=c.getZoomHandleStatus_();v==c.leftZoomHandle_?(a=i.leftHandlePos+e,a=Math.min(a,i.rightHandlePos-v.width-3),a=Math.max(a,c.canvasRect_.x)):(a=i.rightHandlePos+e,a=Math.min(a,c.canvasRect_.x+c.canvasRect_.w),a=Math.max(a,i.leftHandlePos+v.width+3));var n=v.width/2;return v.style.left=a-n+"px",c.drawInteractiveLayer_(),m&&r(),!0},i=function(t){return f?(f=!1,D.uncover(),Dygraph.removeEvent(y,"mousemove",a),Dygraph.removeEvent(y,"mouseup",i),c.fgcanvas_.style.cursor="default",m||r(),!0):!1},r=function(){try{var e=c.getZoomHandleStatus_();if(c.isChangingRange_=!0,e.isZoomed){var a=t(e);c.dygraph_.doZoomXDates_(a[0],a[1])}else c.dygraph_.resetZoom()}finally{c.isChangingRange_=!1}},n=function(t){if(c.isUsingExcanvas_)return t.srcElement==c.iePanOverlay_;var e=c.leftZoomHandle_.getBoundingClientRect(),a=e.left+e.width/2;e=c.rightZoomHandle_.getBoundingClientRect();var i=e.left+e.width/2;return t.clientX>a&&t.clientX=c.canvasRect_.x+c.canvasRect_.w?(r=c.canvasRect_.x+c.canvasRect_.w,i=r-n):(i+=e,r+=e);var o=c.leftZoomHandle_.width/2;return c.leftZoomHandle_.style.left=i-o+"px",c.rightZoomHandle_.style.left=r-o+"px",c.drawInteractiveLayer_(),m&&h(),!0},l=function(t){return x?(x=!1,Dygraph.removeEvent(y,"mousemove",s),Dygraph.removeEvent(y,"mouseup",l),m||h(),!0):!1},h=function(){try{c.isChangingRange_=!0,c.dygraph_.dateWindow_=t(c.getZoomHandleStatus_()),c.dygraph_.drawGraph_(!1)}finally{c.isChangingRange_=!1}},p=function(t){if(!f&&!x){var e=n(t)?"move":"default";e!=c.fgcanvas_.style.cursor&&(c.fgcanvas_.style.cursor=e)}},g=function(t){"touchstart"==t.type&&1==t.targetTouches.length?e(t.targetTouches[0])&&Dygraph.cancelEvent(t):"touchmove"==t.type&&1==t.targetTouches.length?a(t.targetTouches[0])&&Dygraph.cancelEvent(t):i(t)},d=function(t){"touchstart"==t.type&&1==t.targetTouches.length?o(t.targetTouches[0])&&Dygraph.cancelEvent(t):"touchmove"==t.type&&1==t.targetTouches.length?s(t.targetTouches[0])&&Dygraph.cancelEvent(t):l(t)},u=function(t,e){for(var a=["touchstart","touchend","touchmove","touchcancel"],i=0;it;t++){var s=this.getOption_("showInRangeSelector",r[t]);n[t]=s,null!==s&&(o=!0)}if(!o)for(t=0;t1&&(g=h.rollingAverage(g,e.rollPeriod(),p)),l.push(g)}var d=[];for(t=0;t0)&&(v=Math.min(v,x),f=Math.max(f,x))}var m=.25;if(a)for(f=Dygraph.log10(f),f+=f*m,v=Dygraph.log10(v),t=0;tthis.canvasRect_.x||a+10&&t[r][0]>o;)i--,r--}return i>=a?[a,i]:[0,t.length-1]},t.parseFloat=function(t){return null===t?0/0:t}}(),function(){"use strict";Dygraph.DataHandlers.DefaultHandler=function(){};var t=Dygraph.DataHandlers.DefaultHandler;t.prototype=new Dygraph.DataHandler,t.prototype.extractSeries=function(t,e,a){for(var i=[],r=a.get("logscale"),n=0;n=s&&(s=null),i.push([o,s])}return i},t.prototype.rollingAverage=function(t,e,a){e=Math.min(e,t.length);var i,r,n,o,s,l=[];if(1==e)return t;for(i=0;ir;r++)n=t[r][1],null===n||isNaN(n)||(s++,o+=t[r][1]);s?l[i]=[t[i][0],o/s]:l[i]=[t[i][0],null]}return l},t.prototype.getExtremeYValues=function(t,e,a){for(var i,r=null,n=null,o=0,s=t.length-1,l=o;s>=l;l++)i=t[l][1],null===i||isNaN(i)||((null===n||i>n)&&(n=i),(null===r||r>i)&&(r=i));return[r,n]}}(),function(){"use strict";Dygraph.DataHandlers.DefaultFractionHandler=function(){};var t=Dygraph.DataHandlers.DefaultFractionHandler;t.prototype=new Dygraph.DataHandlers.DefaultHandler,t.prototype.extractSeries=function(t,e,a){for(var i,r,n,o,s,l,h=[],p=100,g=a.get("logscale"),d=0;d=0&&(n-=t[i-e][2][0],o-=t[i-e][2][1]);var l=t[i][0],h=o?n/o:0;r[i]=[l,s*h]}return r}}(),function(){"use strict";Dygraph.DataHandlers.BarsHandler=function(){Dygraph.DataHandler.call(this)},Dygraph.DataHandlers.BarsHandler.prototype=new Dygraph.DataHandler;var t=Dygraph.DataHandlers.BarsHandler;t.prototype.extractSeries=function(t,e,a){},t.prototype.rollingAverage=function(t,e,a){},t.prototype.onPointsCreated_=function(t,e){for(var a=0;a=l;l++)if(i=t[l][1],null!==i&&!isNaN(i)){var h=t[l][2][0],p=t[l][2][1];h>i&&(h=i),i>p&&(p=i),(null===n||p>n)&&(n=p),(null===r||r>h)&&(r=h)}return[r,n]},t.prototype.onLineEvaluated=function(t,e,a){for(var i,r=0;r=0){var g=t[l-e];null===g[1]||isNaN(g[1])||(r-=g[2][0],o-=g[1],n-=g[2][1],s-=1)}s?p[l]=[t[l][0],1*o/s,[1*r/s,1*n/s]]:p[l]=[t[l][0],null,[null,null]]}return p}}(),function(){"use strict";Dygraph.DataHandlers.ErrorBarsHandler=function(){};var t=Dygraph.DataHandlers.ErrorBarsHandler;t.prototype=new Dygraph.DataHandlers.BarsHandler,t.prototype.extractSeries=function(t,e,a){for(var i,r,n,o,s=[],l=a.get("sigma"),h=a.get("logscale"),p=0;pr;r++)n=t[r][1],null===n||isNaN(n)||(l++,s+=n,p+=Math.pow(t[r][2][2],2));l?(h=Math.sqrt(p)/l,g=s/l,d[i]=[t[i][0],g,[g-u*h,g+u*h]]):(o=1==e?t[i][1]:null,d[i]=[t[i][0],o,[o,o]])}return d}}(),function(){"use strict";Dygraph.DataHandlers.FractionsBarsHandler=function(){};var t=Dygraph.DataHandlers.FractionsBarsHandler;t.prototype=new Dygraph.DataHandlers.BarsHandler,t.prototype.extractSeries=function(t,e,a){for(var i,r,n,o,s,l,h,p,g=[],d=100,u=a.get("sigma"),c=a.get("logscale"),y=0;y=0&&(p-=t[n-e][2][2],g-=t[n-e][2][3]);var u=t[n][0],c=g?p/g:0;if(h)if(g){var y=0>c?0:c,_=g,v=l*Math.sqrt(y*(1-y)/_+l*l/(4*_*_)),f=1+l*l/g;i=(y+l*l/(2*g)-v)/f,r=(y+l*l/(2*g)+v)/f,s[n]=[u,y*d,[i*d,r*d]]}else s[n]=[u,0,[0,0]];else o=g?l*Math.sqrt(c*(1-c)/g):1,s[n]=[u,d*c,[d*(c-o),d*(c+o)]]}return s}}(); +//# sourceMappingURL=dygraph-combined.js.map \ No newline at end of file diff --git a/dygraph-combined.js.map b/dygraph-combined.js.map new file mode 100644 index 0000000..28603b1 --- /dev/null +++ b/dygraph-combined.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["polyfills/console.js","dashed-canvas.js","dygraph-options.js","dygraph-layout.js","dygraph-canvas.js","dygraph.js","dygraph-utils.js","dygraph-gviz.js","dygraph-interaction-model.js","dygraph-tickers.js","dygraph-plugin-base.js","plugins/annotations.js","plugins/axes.js","plugins/chart-labels.js","plugins/grid.js","plugins/legend.js","plugins/range-selector.js","dygraph-plugin-install.js","datahandler/datahandler.js","datahandler/default.js","datahandler/default-fractions.js","datahandler/bars.js","datahandler/bars-custom.js","datahandler/bars-error.js","datahandler/bars-fractions.js"],"names":["con","prop","method","empty","dummy","properties","split","methods","pop","this","console","CanvasRenderingContext2D","prototype","installPattern","pattern","isPatternInstalled","dashedLineToHistory","segments","realBeginPath","beginPath","realLineTo","lineTo","realMoveTo","moveTo","realStroke","stroke","uninstallPattern","undefined","call","x","y","push","last","length","i","seg","x1","y1","j","x2","y2","save","dx","dy","len","Math","sqrt","rot","atan2","translate","rotate","patternIndex","segment","restore","DygraphOptions","dygraph","dygraph_","yAxes_","xAxis_","series_","global_","attrs_","user_","user_attrs_","labels_","highlightSeries_","get","reparseSeries","AXIS_STRING_MAPPINGS_","Y","Y1","Y2","axisToIndex_","axis","hasOwnProperty","labels","slice","series","options","oldStyleSeries","axisId","idx","seriesName","optionsForSeries","yAxis","error","axis_opts","Dygraph","update","name","result","getGlobalUser_","getGlobalDefault_","DEFAULT_ATTRS","getForAxis","axisIdx","axisString","userAxis","axisOptions","defaultAxisOptions","axes","getForSeries","getHighlightSeries","seriesObj","seriesOptions","numAxes","axisForSeries","seriesForAxis","seriesNames","DygraphLayout","points","setNames","annotations","xTicks_","yTicks_","addDataset","setname","set_xy","getPlotArea","area_","computePlotArea","area","w","width_","getOption","h","height_","e","chart_div","graphDiv","reserveSpaceLeft","px","r","reserveSpaceRight","reserveSpaceTop","reserveSpaceBottom","chartRect","cascadeEvents_","setAnnotations","ann","parse","a","xval","icon","setXTicks","xTicks","setYAxes","yAxes","evaluate","_xAxis","_evaluateLimits","_evaluateLineCharts","_evaluateLineTicks","_evaluateAnnotations","xlimits","xAxisRange","minval","maxval","xrange","scale","getOptionForAxis","xlogrange","log10","xlogscale","minyval","computedValueRange","maxyval","yrange","yscale","ylogrange","ylogscale","isFinite","isNaN","g","calcXNormal_","value","xAxis","logscale","calcYNormal_","NaN","isStacked","isLogscaleForX","setIdx","setName","connectSeparated","axisPropertiesForSeries","attributes_","point","yval","y_stacked","yval_stacked","dataHandler_","onLineEvaluated","tick","label","pos","xticks","toPercentXCoord","v","yticks","ticks","toPercentYCoord","annotated_points","p","k","annotation","removeAllDatasets","setPointsLengths","setPointsOffsets","DygraphCanvasRenderer","element","elementContext","layout","height","width","isIE","isCanvasSupported","isUsingExcanvas_","_createIEClipArea","isAndroid","ctx","canvas_ctx_","rect","clip","hidden_ctx_","clear","context","clearDelay","cancel","clearRect","render","_updatePoints","_renderLineChart","createClipDiv","elem","document","createElement","className","style","backgroundColor","position","left","top","appendChild","childNodes","removeChild","bgColor","bgcolor","currentStyle","parentNode","plotArea","_getIteratorPredicate","connectSeparatedPoints","_predicateThatSkipsEmptyPoints","array","_drawStyledLine","color","strokeWidth","strokePattern","drawPoints","drawPointCallback","pointSize","stepPlot","getBooleanOption","isArrayLike","drawGapPoints","iter","createIterator","stroking","drawingContext","pointsOnLine","_drawSeries","_drawPointsOnLine","isIsolated","prevCanvasX","prevCanvasY","nextCanvasY","first","strokeStyle","lineWidth","arr","array_","limit","end_","predicate","predicate_","start_","canvasy","canvasx","nextIdx_","next","hasNext","peek","isNextCanvasYNullOrNaN","cb","sets","opt_seriesName","opt_ctx","colors","colorsMap_","plotter_attr","plotters","setPlotters","setPlotter","plotter","is_last","seriesIndex","seriesCount","singleSeriesName","allSeriesPoints","_Plotters","linePlotter","_linePlotter","fillPlotter","_fillPlotter","errorPlotter","_errorPlotter","borderWidth","getNumericOption","Circles","DEFAULT","errorBars","fillGraph","warn","newYs","fillAlpha","prevX","prevY","prevYs","rgb","toRGB_","err_color","b","fillStyle","isNullUndefinedOrNaN","y_bottom","y_top","closePath","fill","_fastCanvasProxy","pendingActions","lastRoundedX","lastFlushedX","LINE_TO","MOVE_TO","actionCount","compressActions","opt_losslessOnly","action","prevAction","splice","startIdx","minIdx","maxIdx","minAction","maxAction","flushActions","opt_noLossyCompression","addAction","rx","round","hasGapOnLeft","hasGapOnRight","hasGap","_count","getLabels","visibility","anySeriesFilled","currBaseline","prevStepPlot","setCount","stackedGraph","getColors","baseline","traceBackPath","baselineX","baselineY","pathBack","pt","axisY","last_x","is_first","FORCE_FAST_PROXY","isOK","lastY","div","data","opts","opt_fourth_param","is_initial_draw_","readyFns_","__old_init__","__init__","NAME","VERSION","__repr__","toString","DEFAULT_ROLL_PERIOD","DEFAULT_WIDTH","DEFAULT_HEIGHT","ANIMATION_STEPS","ANIMATION_DURATION","KMB_LABELS","KMG2_BIG_LABELS","KMG2_SMALL_LABELS","numberValueFormatter","sigFigs","floatFormat","digits","maxNumberWidth","kmb","kmg2","abs","pow","toExponential","round_","k_labels","m_labels","absx","n","x_parts","String","Number","toFixed","floor","numberAxisLabelFormatter","granularity","SHORT_MONTH_NAMES_","dateAxisLabelFormatter","date","utc","accessors","DateAccessorsUTC","DateAccessorsLocal","year","getFullYear","month","getMonth","day","getDate","hours","getHours","mins","getMinutes","secs","getSeconds","millis","DECADAL","MONTHLY","frac","DAILY","zeropad","hmsString_","dateAxisFormatter","dateValueFormatter","d","dateString_","Plotters","highlightCircleSize","highlightSeriesOpts","highlightSeriesBackgroundAlpha","labelsDivWidth","labelsDivStyles","labelsSeparateLines","labelsShowZeroValues","labelsKMB","labelsKMG2","showLabelsOnHighlight","digitsAfterDecimal","strokeBorderWidth","strokeBorderColor","axisTickSize","axisLabelFontSize","rightGap","showRoller","xValueParser","dateParser","delimiter","sigma","fractions","wilsonInterval","customBars","stackedGraphNaNFill","hideOverlayOnMouseOut","legend","avoidMinZero","xRangePad","yRangePad","drawAxesAtZero","titleHeight","xLabelHeight","yLabelWidth","drawXAxis","drawYAxis","axisLineColor","axisLineWidth","gridLineWidth","axisLabelColor","axisLabelWidth","drawYGrid","drawXGrid","gridLineColor","interactionModel","animatedZooms","showRangeSelector","rangeSelectorHeight","rangeSelectorPlotStrokeColor","rangeSelectorPlotFillColor","showInRangeSelector","plugins","pixelsPerLabel","axisLabelFormatter","valueFormatter","drawGrid","drawAxis","independentTicks","ticker","HORIZONTAL","VERTICAL","PLUGINS","addedAnnotationCSS","file","attrs","new_labels","test","navigator","userAgent","window","opera","readyState","self","setTimeout","mapLegacyOptions_","getElementById","maindiv_","file_","rollPeriod_","rollPeriod","previousVerticalX_","fractions_","dateWindow_","dateWindow","annotations_","zoomed_x_","zoomed_y_","innerHTML","clientHeight","clientWidth","updateDeep","boundaryIds_","setIndexByName_","datasetIndex_","registeredEvents_","eventListeners_","createInterface_","plugins_","concat","pluginInstance","Plugin","pluginDict","plugin","events","pluginOptions","handlers","activate","eventName","plugin_dict","callback","pair","createDragInterface_","extra_props","cancelable","defaultPrevented","preventDefault","propagationStopped","stopPropagation","callback_plugin_pairs","getPluginInstance_","type","isZoomed","maindiv","id","attr_","getStringOption","getFunctionOption","optionsViewForAxis_","opt","axes_","xAxisExtremes","pad","plotter_","numRows","rawData_","right","range","yAxisRange","yAxisRanges","ret","toDomCoords","toDomXCoord","toDomYCoord","xRange","pct","toDataCoords","toDataXCoord","toDataYCoord","logr0","logr1","exponent","LOG_SCALE","yRange","numColumns","getValue","row","col","enclosing","textAlign","canvas_","createCanvas","hidden_","createPlotKitCanvas_","getContext","resizeElements_","mouseEventElement_","createMouseEventElement_","layout_","mouseMoveHandler_","mouseMove_","mouseOutHandler_","target","fromElement","relatedTarget","toElement","isNodeContainedBy","mouseOut_","addAndTrackEvent","resizeHandler_","resize","canvasScale","getContextPixelRatio","hiddenScale","destroy","removeRecursive","node","hasChildNodes","firstChild","removeTrackedEvents_","removeEvent","nullOut","obj","canvas","filter","setColors_","num","colors_","sat","val","half","ceil","colorStr","hue","hsvToRGB","getPropertiesForSeries","series_name","column","visible","createRollInterface_","roller_","display","textAttr","zIndex","size","onchange","adjustRoll","isZooming","isPanning","is2DPan","dragStartX","dragStartY","dragEndX","dragEndY","dragDirection","prevEndX","prevEndY","prevDragDirection","cancelNextDblclick","initialLeftmostDate","xUnitsPerPixel","dateRange","py","boundedDates","boundedValues","tarp","IFrameTarp","initializeMouseDown","event","contextB","returnValue","cancelBubble","canvasPos","findPos","dragGetX_","dragGetY_","cover","draggingDate","draggingValue","dragValueRange","uncover","bindHandler","handler","willDestroyContextMyself","mouseUpHandler","drawZoomRect_","direction","startX","endX","startY","endY","prevDirection","min","fillRect","currentZoomRectArgs_","clearZoomRect_","doZoomX_","lowX","highX","minDate","maxDate","doZoomXDates_","old_window","new_window","that","doAnimatedZoom","doZoomY_","lowY","highY","oldValueRanges","newValueRanges","hi","low","zoomAnimationFunction","frame","numFrames","resetZoom","dirty","dirtyX","dirtyY","valueWindow","clearSelection","drawGraph_","oldWindow","newWindow","packed","gatherDatasets_","rolledSeries_","extremes","computeYAxisRanges_","valueRange","extremeRange","oldXRange","newXRange","oldYRanges","newYRanges","step","steps","windows","valueRanges","thisRange","repeatAndCleanup","getArea","eventToDomCoords","offsetX","offsetY","eventElementPos","pageX","pageY","findClosestRow","domX","minDistX","Infinity","closestRow","isValidPoint","dist","findClosestPoint","domY","closestPoint","closestSeries","minDist","findStackedPoint","boundary","getLeftBoundary_","rowIdx","p1","p2","p0","canvasCoords","selectionChanged","isSeriesLocked","closest","setSelection","lastx_","selPoints_","lastRow_","highlightSet_","animateSelection_","totalSteps","fadeLevel","animateId","start","updateSelection_","thisId","opt_animFraction","selectedRow","selectedX","selectedPoints","alpha","animateBackgroundFade","maxCircleSize","apply","circleSize","opt_locked","changed","setRow","pointIdx","lockedSet_","getSelection","loadedEvent_","parseCSV_","cascadeDataDidUpdateEvent_","predraw_","addXTicks_","xAxisOptionsView","getHandlerClass_","handlerClass","DataHandlers","FractionsBarsHandler","DefaultFractionHandler","CustomBarsHandler","ErrorBarsHandler","DefaultHandler","Date","computeYAxes_","extractSeries","rollingAverage","end","drawingTimeMs_","PointType","stackPoints_","cumulativeYval","seriesExtremes","fillMethod","lastXval","prevPoint","nextPoint","nextPointIdx","updateNextPoint","actualYval","stackedYval","rolledSeries","seriesIdx","sampleIdx","firstIdx","lastIdx","boundaryIds","num_series","high","correctedFirstIdx","isInvalidValue","correctedLastIdx","getExtremeYValues","seriesPoints","seriesToPoints","is_initial_draw","dataIdx","tmp_zoomed_x","renderGraph_","log","readyFired_","fn","valueWindows","index","idxCount","ypadCompat","span","ypad","p_axis","parseFloat","includeZero","extremeMinY","extremeMaxY","minY","maxY","max","maxAxisY","minAxisY","logpad","exp","y0","p_ticks","p_scale","tick_values","y_frac","y_val","detectTypeFromString_","str","isDate","dashPos","indexOf","setXAxisOptions_","dateTicker","numericTicks","vals","line_delimiter","detectLineDelimiter","lines","delim","xParser","line_no","defaultParserSet","expectedCols","outOfOrder","line","inFields","fields","parseFloat_","all_null","sort","parseArray_","num_labels","isDateLike","parsedData","clone","getTime","parseDataTable_","shortTextForAnnotationNum","shortText","fromCharCode","toLowerCase","cols","getNumberOfColumns","rows","getNumberOfRows","indepType","getColumnType","colIdx","annotationCols","hasAnnotations","getColumnLabel","text","getColumnRange","req","XMLHttpRequest","ActiveXObject","caller","onreadystatechange","status","responseText","open","send","updateOptions","input_attrs","block_redraw","requiresNewPoints","isPixelChangingOptionList","my_attrs","set","map","new_opt","resize_lock","old_width","old_height","setVisibility","suppressDraw","addAnnotationRule","indexFromSetName","ready","rule","styleSheetElement","getElementsByTagName","styleSheets","disabled","mysheet","insertRule","cssRules","addRule","err","exports","module","parseRGBA","rgbStr","bits","RGBA_RE","exec","parseInt","LN_TEN","DOTTED_LINE","DASHED_LINE","DOT_DASH_LINE","addEvent","addEventListener","attachEvent","removeEventListener","detachEvent","reg","cancelEvent","saturation","red","green","blue","f","q","t","curleft","curtop","offsetParent","copyObj","borderLeft","borderTop","getComputedStyle","computedStyle","offsetLeft","offsetTop","body","scrollLeft","scrollTop","de","documentElement","clientX","clientLeft","clientY","clientTop","opt_allowNaNY","opt_precision","toPrecision","getMilliseconds","getDay","makeDate","m","hh","mm","ss","ms","getUTCFullYear","getUTCMonth","getUTCDate","getUTCHours","getUTCMinutes","getUTCSeconds","getUTCMilliseconds","getUTCDay","UTC","time","places","shift","binarySearch","arry","validIndex","mid","dateStr","dateStrSlashed","search","dateStrToMillis","replace","substr","o","isNode","Node","nodeType","nodeName","typ","G_vmlCanvasManager","initElement","devicePixelRatio","backingStoreRatio","webkitBackingStorePixelRatio","mozBackingStorePixelRatio","msBackingStorePixelRatio","oBackingStorePixelRatio","backingStorePixelRatio","Iterator","nextIdx","found","opt_predicate","requestAnimFrame","requestAnimationFrame","webkitRequestAnimationFrame","mozRequestAnimationFrame","oRequestAnimationFrame","msRequestAnimationFrame","repeatFn","maxFrames","framePeriodInMillis","cleanupFn","previousFrameNumber","frameNumber","startTime","maxFrameArg","loop","currentTime","delayInMillis","frameDelta","predictOvershootStutter","pixelSafeOptions","annotationClickHandler","annotationDblClickHandler","annotationMouseOutHandler","annotationMouseOverHandler","clickCallback","drawCallback","drawHighlightPointCallback","highlightCallback","isZoomedIgnoreProgrammaticZoom","labelsDiv","panEdgeFraction","pixelsPerYLabel","pointClickCallback","underlayCallback","unhighlightCallback","zoomCallback","seriesNamesDictionary","scanFlatOptions","property","perSeries","radius","arc","PI","tarps","iframes","iframe","offsetWidth","offsetHeight","code","charAt","containee","container","containeeNode","base","opt_canvasElement","ie","appVersion","match","opt_line_no","opt_line","msg","GVizChart","draw","date_graph","selection_array","selection","DRAG_EDGE_MARGIN","Interaction","maybeTreatMouseOpAsClick","regionWidth","regionHeight","treatMouseOpAsClick","startPan","maxXPixelsToDraw","xExtremes","boundedLeftX","boundedRightX","boundedLeftDate","boundedRightDate","maxYPixelsToDraw","yExtremes","boundedTopY","boundedBottomY","boundedTopValue","boundedBottomValue","axis_data","initialTopValue","unitsPerPixel","movePan","pixelsDragged","unitsDragged","boundedValue","maxValue","minValue","endPan","startZoom","zoomMoved","moveZoom","xDelta","yDelta","selectedPoint","closestIdx","closestDistance","MAX_VALUE","distance","pts","endZoom","bottom","startTouch","touches","startTimeForDoubleTapMs","dataX","dataY","initialTouches","initialPinchCenter","touchDirections","initialAngle","initialRange","moveTouch","c_now","c_init","swipe","dataWidth","dataHeight","xScale","yScale","initHalfWidth","initHalfHeight","didZoom","viewWindow","endTouch","changedTouches","now","doubleTapX","screenX","doubleTapY","screenY","distanceFromInterval","distanceFromChart","chartPos","box","defaultModel","mousedown","button","altKey","shiftKey","mousemove","mouseup","touchstart","touchmove","touchend","dblclick","defaultInteractionModel","nonInteractiveModel_","dragIsPanInteractionModel","TickList","Ticker","numericLinearTicks","pixels","nonLogscaleOpts","tickV","nTicks","pixels_per_tick","PREFERRED_LOG_TICK_VALUES","lastDisplayed","tickValue","pixel_coord","reverse","mults","low_val","high_val","spacing","max_ticks","units_per_tick","base_power","base_scale","formatter","chosen","pickDateTickGranularity","getDateAxis","SECONDLY","TWO_SECONDLY","FIVE_SECONDLY","TEN_SECONDLY","THIRTY_SECONDLY","MINUTELY","TWO_MINUTELY","FIVE_MINUTELY","TEN_MINUTELY","THIRTY_MINUTELY","HOURLY","TWO_HOURLY","SIX_HOURLY","TWO_DAILY","WEEKLY","QUARTERLY","BIANNUAL","ANNUAL","CENTENNIAL","NUM_GRANULARITIES","DATEFIELD_Y","DATEFIELD_M","DATEFIELD_D","DATEFIELD_HH","DATEFIELD_MM","DATEFIELD_SS","DATEFIELD_MS","NUM_DATEFIELDS","TICK_PLACEMENT","datefield","power","mult","num_ticks","numDateTicks","start_time","end_time","dg","start_date","date_array","start_date_offset","df","tick_date","tick_time","Plugins","Annotations","clearChart","didDrawChart","detachLabels","containerDiv","annotationStyle","fontSize","overflow","bindEvt","classEventName","annotation_event","xToUsedHeight","tick_height","tickHeight","cssClass","img","src","createTextNode","divTop","attachAtBottom","title","borderColor","Axes","xlabels_","ylabels_","willDrawChart","removeArray","ary","el","halfUp","halfDown","canvasWidth","canvasHeight","makeLabelStyle","lineHeight","labelStyles","makeDiv","txt","prec_axis","labelStyle","inner_div","makeOptionGetter","option","num_axes","getOptions","sgn","getAxisOption","bottomTick","axisX","ChartLabels","chart_labels","title_div_","xlabel_div_","ylabel_div_","y2label_div_","createDivInRect","detachLabels_","els","createRotatedDiv","classes","html","transform","WebkitTransform","MozTransform","OTransform","msTransform","documentMode","class_div","title_rect","fontWeight","x_rect","y_rect","y2_rect","children","Grid","grid","strokeStyles","lineWidths","Legend","legend_div_","is_generated_div_","generateLegendDashHTML","divWidth","userLabelsDiv","messagestyle","background","one_em_width_","select","deselect","predraw","calculateEmWidthInDiv","sizeSpan","setAttribute","oneEmWidth","escapeHTML","xValue","legendMode","yAxisLabelWidth","leftLegend","topLegend","scrollX","innerWidth","generateLegendHTML","sel_points","sepLines","dash","xOptView","xvf","yOptViews","showZeros","highlightSeries","yOptView","fmtFunc","cls","paddingLeft","marginRight","strokePixelLength","segmentLoop","normalizedPattern","RangeSelector","rangeSelector","isIE_","hasTouchInterface_","isMobileDevice_","interfaceCreated_","getOption_","reserveSpace_","renderStaticLayer_","renderInteractiveLayer_","bgcanvas_","fgcanvas_","leftZoomHandle_","rightZoomHandle_","iePanOverlay_","opt_series","setDefaultOption_","createCanvases_","createIEPanOverlay_","createZoomHandles_","initInteraction_","addToGraph_","graphDiv_","removeFromGraph_","updateVisibility_","resize_","drawStaticLayer_","isChangingRange_","placeZoomHandles_","drawInteractiveLayer_","enabled","setElementRect","xAxisLabelHeight","canvasRect_","bgcanvas_ctx_","fgcanvas_ctx_","cursor","Image","border","cloneNode","toXDataWindow","onZoomStart","onZoom","onZoomEnd","doZoom","isMouseInPanZone","onPanStart","onPan","onPanEnd","doPan","onCanvasHover","onZoomHandleTouchEvent","onCanvasTouchEvent","addTouchEvents","topElem","clientXLast","handle","dynamic","zoomHandleStatus","xDataLimits","fact","xDataMin","leftHandlePos","xDataMax","rightHandlePos","srcElement","delX","newPos","getZoomHandleStatus_","halfHandleWidth","xDataWindow","getBoundingClientRect","leftHandleClientX","rightHandleClientX","rangeSize","targetTouches","types","dragStartEvent","drawMiniPlot_","ex","margin","combinedSeriesData","computeCombinedSeriesAndLimits_","yMax","yMin","xFact","yFact","dataPoint","lingrad","createLinearGradient","addColorStop","includeSeries","Array","anySet","include","dataHandler","combinedSeries","sum","count","yVal","extraPercent","yExtra","MIN_VALUE","xWindowLimits","leftPercent","rightPercent","leftCoord","rightCoord","handleTop","leftHandleCanvasPos","rightHandleCanvasPos","DataHandler","X","EXTRAS","rawData","boundaryIdStart","item","yraw","onPointsCreated_","computeYInterpolation_","deltaY","deltaX","gradient","growth","getIndexesInWindow_","logScale","originalData","num_ok","rollingData","den","BarsHandler","yval_minus","yval_plus","prev","variance","stddev","pm","denom"],"mappings":";CAGA,SAAUA,GACR,YAQA,KAPA,GAAIC,GAAMC,EACNC,KACAC,EAAQ,aACRC,EAAa,SAASC,MAAM,KAC5BC,EAAU,wMAE0DD,MAAM,KACvEL,EAAOI,EAAWG,OAAOR,EAAIC,GAAQD,EAAIC,IAASE,CACzD,MAAOD,EAASK,EAAQC,OAAOR,EAAIE,GAAUF,EAAIE,IAAWE,GAC3DK,KAAKC,QAAUD,KAAKC,aCRvB,WACA,YA2CAC,0BAAyBC,UAAUC,eAAiB,SAASC,GAC3D,GAAwC,mBAA7BL,MAAuB,mBAChC,KAAM,+DAERA,MAAKM,oBAAqB,CAE1B,IAAIC,IAAuB,EAAG,GAI1BC,KAGAC,EAAgBT,KAAKU,UACrBC,EAAaX,KAAKY,OAClBC,EAAab,KAAKc,OAClBC,EAAaf,KAAKgB,MAGtBhB,MAAKiB,iBAAmB,WACtBjB,KAAKU,UAAYD,EACjBT,KAAKY,OAASD,EACdX,KAAKc,OAASD,EACdb,KAAKgB,OAASD,EACdf,KAAKiB,iBAAmBC,OACxBlB,KAAKM,mBAAqBY,QAI5BlB,KAAKU,UAAY,WACfF,KACAC,EAAcU,KAAKnB,OAErBA,KAAKc,OAAS,SAASM,EAAGC,GACxBb,EAASc,OAAOF,EAAGC,KACnBR,EAAWM,KAAKnB,KAAMoB,EAAGC,IAE3BrB,KAAKY,OAAS,SAASQ,EAAGC,GACxB,GAAIE,GAAOf,EAASA,EAASgB,OAAS,EACtCD,GAAKD,MAAMF,EAAGC,KAGhBrB,KAAKgB,OAAS,WACZ,GAAwB,IAApBR,EAASgB,OAIX,WADAT,GAAWI,KAAKnB,KAIlB,KAAK,GAAIyB,GAAI,EAAGA,EAAIjB,EAASgB,OAAQC,IAGnC,IAAK,GAFDC,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