Export a few more symbols
[dygraphs.git] / src / dygraph.js
CommitLineData
88e95c46
DV
1/**
2 * @license
3 * Copyright 2006 Dan Vanderkam (danvdk@gmail.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
5 */
6a1aa64f
DV
6
7/**
8 * @fileoverview Creates an interactive, zoomable graph based on a CSV file or
285a6bda
DV
9 * string. Dygraph can handle multiple series with or without error bars. The
10 * date/value ranges will be automatically set. Dygraph uses the
6a1aa64f
DV
11 * <canvas> tag, so it only works in FF1.5+.
12 * @author danvdk@gmail.com (Dan Vanderkam)
13
14 Usage:
15 <div id="graphdiv" style="width:800px; height:500px;"></div>
16 <script type="text/javascript">
285a6bda
DV
17 new Dygraph(document.getElementById("graphdiv"),
18 "datafile.csv", // CSV file with headers
19 { }); // options
6a1aa64f
DV
20 </script>
21
22 The CSV file is of the form
23
285a6bda 24 Date,SeriesA,SeriesB,SeriesC
6a1aa64f
DV
25 YYYYMMDD,A1,B1,C1
26 YYYYMMDD,A2,B2,C2
27
6a1aa64f
DV
28 If the 'errorBars' option is set in the constructor, the input should be of
29 the form
285a6bda 30 Date,SeriesA,SeriesB,...
6a1aa64f
DV
31 YYYYMMDD,A1,sigmaA1,B1,sigmaB1,...
32 YYYYMMDD,A2,sigmaA2,B2,sigmaB2,...
33
34 If the 'fractions' option is set, the input should be of the form:
35
285a6bda 36 Date,SeriesA,SeriesB,...
6a1aa64f
DV
37 YYYYMMDD,A1/B1,A2/B2,...
38 YYYYMMDD,A1/B1,A2/B2,...
39
40 And error bars will be calculated automatically using a binomial distribution.
41
727439b4 42 For further documentation and examples, see http://dygraphs.com/
6a1aa64f
DV
43
44 */
45
6ecc0739
DV
46import DygraphLayout from './dygraph-layout';
47import DygraphCanvasRenderer from './dygraph-canvas';
48import DygraphOptions from './dygraph-options';
49import DygraphInteraction from './dygraph-interaction-model';
50import * as DygraphTickers from './dygraph-tickers';
51import * as utils from './dygraph-utils';
52import DEFAULT_ATTRS from './dygraph-default-attrs';
7fea22be 53import OPTIONS_REFERENCE from './dygraph-options-reference';
e8c70e4e 54
6ecc0739 55import DefaultHandler from './datahandler/default';
e8c70e4e
DV
56import ErrorBarsHandler from './datahandler/bars-error';
57import CustomBarsHandler from './datahandler/bars-custom';
58import DefaultFractionHandler from './datahandler/default-fractions';
59import FractionsBarsHandler from './datahandler/bars-fractions';
c4c10db6 60import BarsHandler from './datahandler/bars';
6ecc0739
DV
61
62import AnnotationsPlugin from './plugins/annotations';
63import AxesPlugin from './plugins/axes';
64import ChartLabelsPlugin from './plugins/chart-labels';
65import GridPlugin from './plugins/grid';
66import LegendPlugin from './plugins/legend';
67import RangeSelectorPlugin from './plugins/range-selector';
103fd879 68
e8c70e4e
DV
69import GVizChart from './dygraph-gviz';
70
c0f54d4f
DV
71"use strict";
72
6a1aa64f 73/**
629a09ae
DV
74 * Creates an interactive, zoomable chart.
75 *
76 * @constructor
77 * @param {div | String} div A div or the id of a div into which to construct
78 * the chart.
79 * @param {String | Function} file A file containing CSV data or a function
80 * that returns this data. The most basic expected format for each line is
81 * "YYYY/MM/DD,val1,val2,...". For more information, see
82 * http://dygraphs.com/data.html.
6a1aa64f 83 * @param {Object} attrs Various other attributes, e.g. errorBars determines
629a09ae
DV
84 * whether the input data contains error ranges. For a complete list of
85 * options, see http://dygraphs.com/options.html.
6a1aa64f 86 */
ba880736 87var Dygraph = function(div, data, opts) {
ba880736 88 this.__init__(div, data, opts);
6a1aa64f
DV
89};
90
285a6bda 91Dygraph.NAME = "Dygraph";
5efbb60b 92Dygraph.VERSION = "1.1.0";
6a1aa64f
DV
93
94// Various default values
285a6bda
DV
95Dygraph.DEFAULT_ROLL_PERIOD = 1;
96Dygraph.DEFAULT_WIDTH = 480;
97Dygraph.DEFAULT_HEIGHT = 320;
6a1aa64f 98
a96b8ba3
A
99// For max 60 Hz. animation:
100Dygraph.ANIMATION_STEPS = 12;
b1a3b195
DV
101Dygraph.ANIMATION_DURATION = 200;
102
38e3d209
DV
103/**
104 * Standard plotters. These may be used by clients.
105 * Available plotters are:
106 * - Dygraph.Plotters.linePlotter: draws central lines (most common)
107 * - Dygraph.Plotters.errorPlotter: draws error bars
108 * - Dygraph.Plotters.fillPlotter: draws fills under lines (used with fillGraph)
109 *
110 * By default, the plotter is [fillPlotter, errorPlotter, linePlotter].
111 * This causes all the lines to be drawn over all the fills/error bars.
112 */
113Dygraph.Plotters = DygraphCanvasRenderer._Plotters;
114
48e614ac 115
5c528fa2
DV
116// Used for initializing annotation CSS rules only once.
117Dygraph.addedAnnotationCSS = false;
118
6a1aa64f 119/**
285a6bda 120 * Initializes the Dygraph. This creates a new DIV and constructs the PlotKit
7aedf6fe 121 * and context &lt;canvas&gt; inside of it. See the constructor for details.
6a1aa64f 122 * on the parameters.
12e4c741 123 * @param {Element} div the Element to render the graph into.
1bc88216 124 * @param {string | Function} file Source data
6a1aa64f
DV
125 * @param {Object} attrs Miscellaneous other options
126 * @private
127 */
285a6bda 128Dygraph.prototype.__init__ = function(div, file, attrs) {
79ea4032
DV
129 this.is_initial_draw_ = true;
130 this.readyFns_ = [];
131
285a6bda 132 // Support two-argument constructor
758a629f 133 if (attrs === null || attrs === undefined) { attrs = {}; }
285a6bda 134
bfb3e0a4 135 attrs = Dygraph.copyUserAttrs_(attrs);
48e614ac 136
8a870376
RK
137 if (typeof(div) == 'string') {
138 div = document.getElementById(div);
139 }
140
48e614ac 141 if (!div) {
5db9ad5d 142 throw new Error('Constructing dygraph with a non-existent div!');
48e614ac
DV
143 }
144
6a1aa64f 145 // Copy the important bits into the object
32988383 146 // TODO(danvk): most of these should just stay in the attrs_ dictionary.
6a1aa64f 147 this.maindiv_ = div;
6a1aa64f 148 this.file_ = file;
285a6bda 149 this.rollPeriod_ = attrs.rollPeriod || Dygraph.DEFAULT_ROLL_PERIOD;
6a1aa64f 150 this.previousVerticalX_ = -1;
6a1aa64f 151 this.fractions_ = attrs.fractions || false;
6a1aa64f 152 this.dateWindow_ = attrs.dateWindow || null;
8b83c6cc 153
5c528fa2 154 this.annotations_ = [];
7aedf6fe 155
45f2c689 156 // Zoomed indicators - These indicate when the graph has been zoomed and on what axis.
57baab03
NN
157 this.zoomed_x_ = false;
158 this.zoomed_y_ = false;
45f2c689 159
f7d6278e
DV
160 // Clear the div. This ensure that, if multiple dygraphs are passed the same
161 // div, then only one will be drawn.
162 div.innerHTML = "";
163
0cb9bd91
DV
164 // For historical reasons, the 'width' and 'height' options trump all CSS
165 // rules _except_ for an explicit 'width' or 'height' on the div.
166 // As an added convenience, if the div has zero height (like <div></div> does
167 // without any styles), then we use a default height/width.
758a629f 168 if (div.style.width === '' && attrs.width) {
0cb9bd91 169 div.style.width = attrs.width + "px";
285a6bda 170 }
758a629f 171 if (div.style.height === '' && attrs.height) {
0cb9bd91 172 div.style.height = attrs.height + "px";
32988383 173 }
758a629f 174 if (div.style.height === '' && div.clientHeight === 0) {
0cb9bd91 175 div.style.height = Dygraph.DEFAULT_HEIGHT + "px";
758a629f 176 if (div.style.width === '') {
0cb9bd91
DV
177 div.style.width = Dygraph.DEFAULT_WIDTH + "px";
178 }
c21d2c2d 179 }
c28088bc
KW
180 // These will be zero if the dygraph's div is hidden. In that case,
181 // use the user-specified attributes if present. If not, use zero
182 // and assume the user will call resize to fix things later.
183 this.width_ = div.clientWidth || attrs.width || 0;
184 this.height_ = div.clientHeight || attrs.height || 0;
32988383 185
344ba8c0 186 // TODO(danvk): set fillGraph to be part of attrs_ here, not user_attrs_.
758a629f
DV
187 if (attrs.stackedGraph) {
188 attrs.fillGraph = true;
43af96e7
NK
189 // TODO(nikhilk): Add any other stackedGraph checks here.
190 }
191
a9172eb1
RK
192 // DEPRECATION WARNING: All option processing should be moved from
193 // attrs_ and user_attrs_ to options_, which holds all this information.
194 //
285a6bda
DV
195 // Dygraphs has many options, some of which interact with one another.
196 // To keep track of everything, we maintain two sets of options:
197 //
c21d2c2d 198 // this.user_attrs_ only options explicitly set by the user.
285a6bda
DV
199 // this.attrs_ defaults, options derived from user_attrs_, data.
200 //
201 // Options are then accessed this.attr_('attr'), which first looks at
202 // user_attrs_ and then computed attrs_. This way Dygraphs can set intelligent
203 // defaults without overriding behavior that the user specifically asks for.
204 this.user_attrs_ = {};
6ecc0739 205 utils.update(this.user_attrs_, attrs);
6a1aa64f 206
48e614ac 207 // This sequence ensures that Dygraph.DEFAULT_ATTRS is never modified.
285a6bda 208 this.attrs_ = {};
6ecc0739 209 utils.updateDeep(this.attrs_, DEFAULT_ATTRS);
6a1aa64f 210
16269f6e 211 this.boundaryIds_ = [];
82c6fe4d 212 this.setIndexByName_ = {};
857a6931 213 this.datasetIndex_ = [];
6a1aa64f 214
6a4587ac 215 this.registeredEvents_ = [];
de8f284f 216 this.eventListeners_ = {};
6a4587ac 217
c1780ad0
RK
218 this.attributes_ = new DygraphOptions(this);
219
6a1aa64f
DV
220 // Create the containing DIV and other interactive elements
221 this.createInterface_();
222
e2c21500
DV
223 // Activate plugins.
224 this.plugins_ = [];
d9fbba56
RK
225 var plugins = Dygraph.PLUGINS.concat(this.getOption('plugins'));
226 for (var i = 0; i < plugins.length; i++) {
6f5f0b2b 227 // the plugins option may contain either plugin classes or instances.
835351fd
DV
228 // Plugin instances contain an activate method.
229 var Plugin = plugins[i]; // either a constructor or an instance.
6f5f0b2b
DV
230 var pluginInstance;
231 if (typeof(Plugin.activate) !== 'undefined') {
232 pluginInstance = Plugin;
233 } else {
234 pluginInstance = new Plugin();
235 }
236
e2c21500
DV
237 var pluginDict = {
238 plugin: pluginInstance,
239 events: {},
240 options: {},
241 pluginOptions: {}
242 };
243
6a4457b4
KW
244 var handlers = pluginInstance.activate(this);
245 for (var eventName in handlers) {
3ce712e6 246 if (!handlers.hasOwnProperty(eventName)) continue;
28aa77ac 247 // TODO(danvk): validate eventName.
6a4457b4
KW
248 pluginDict.events[eventName] = handlers[eventName];
249 }
e2c21500
DV
250
251 this.plugins_.push(pluginDict);
252 }
253
254 // At this point, plugins can no longer register event handlers.
255 // Construct a map from event -> ordered list of [callback, plugin].
e2c21500
DV
256 for (var i = 0; i < this.plugins_.length; i++) {
257 var plugin_dict = this.plugins_[i];
258 for (var eventName in plugin_dict.events) {
259 if (!plugin_dict.events.hasOwnProperty(eventName)) continue;
260 var callback = plugin_dict.events[eventName];
261
262 var pair = [plugin_dict.plugin, callback];
263 if (!(eventName in this.eventListeners_)) {
264 this.eventListeners_[eventName] = [pair];
265 } else {
266 this.eventListeners_[eventName].push(pair);
267 }
268 }
269 }
270
487f5523
PF
271 this.createDragInterface_();
272
738fc797 273 this.start_();
6a1aa64f
DV
274};
275
dcb25130 276/**
e2c21500 277 * Triggers a cascade of events to the various plugins which are interested in them.
6f5f0b2b
DV
278 * Returns true if the "default behavior" should be prevented, i.e. if one
279 * of the event listeners called event.preventDefault().
e2c21500
DV
280 * @private
281 */
282Dygraph.prototype.cascadeEvents_ = function(name, extra_props) {
6f5f0b2b 283 if (!(name in this.eventListeners_)) return false;
e2c21500
DV
284
285 // QUESTION: can we use objects & prototypes to speed this up?
286 var e = {
287 dygraph: this,
288 cancelable: false,
289 defaultPrevented: false,
290 preventDefault: function() {
291 if (!e.cancelable) throw "Cannot call preventDefault on non-cancelable event.";
292 e.defaultPrevented = true;
293 },
294 propagationStopped: false,
295 stopPropagation: function() {
5bd29cf4 296 e.propagationStopped = true;
e2c21500
DV
297 }
298 };
6ecc0739 299 utils.update(e, extra_props);
e2c21500
DV
300
301 var callback_plugin_pairs = this.eventListeners_[name];
da1c187b
KW
302 if (callback_plugin_pairs) {
303 for (var i = callback_plugin_pairs.length - 1; i >= 0; i--) {
304 var plugin = callback_plugin_pairs[i][0];
305 var callback = callback_plugin_pairs[i][1];
306 callback.call(plugin, e);
307 if (e.propagationStopped) break;
308 }
e2c21500
DV
309 }
310 return e.defaultPrevented;
311};
312
313/**
b1a96215
DV
314 * Fetch a plugin instance of a particular class. Only for testing.
315 * @private
316 * @param {!Class} type The type of the plugin.
317 * @return {Object} Instance of the plugin, or null if there is none.
318 */
319Dygraph.prototype.getPluginInstance_ = function(type) {
320 for (var i = 0; i < this.plugins_.length; i++) {
321 var p = this.plugins_[i];
322 if (p.plugin instanceof type) {
323 return p.plugin;
324 }
325 }
326 return null;
327};
328
329/**
dcb25130
NN
330 * Returns the zoomed status of the chart for one or both axes.
331 *
332 * Axis is an optional parameter. Can be set to 'x' or 'y'.
333 *
334 * The zoomed status for an axis is set whenever a user zooms using the mouse
42a9ebb8
DV
335 * or when the dateWindow or valueRange are updated (unless the
336 * isZoomedIgnoreProgrammaticZoom option is also specified).
dcb25130 337 */
57baab03 338Dygraph.prototype.isZoomed = function(axis) {
42a9ebb8
DV
339 if (axis === null || axis === undefined) {
340 return this.zoomed_x_ || this.zoomed_y_;
341 }
758a629f
DV
342 if (axis === 'x') return this.zoomed_x_;
343 if (axis === 'y') return this.zoomed_y_;
94ea5744 344 throw "axis parameter is [" + axis + "] must be null, 'x' or 'y'.";
57baab03
NN
345};
346
629a09ae
DV
347/**
348 * Returns information about the Dygraph object, including its containing ID.
349 */
22bd1dfb
RK
350Dygraph.prototype.toString = function() {
351 var maindiv = this.maindiv_;
758a629f 352 var id = (maindiv && maindiv.id) ? maindiv.id : maindiv;
22bd1dfb 353 return "[Dygraph " + id + "]";
758a629f 354};
22bd1dfb 355
629a09ae
DV
356/**
357 * @private
358 * Returns the value of an option. This may be set by the user (either in the
359 * constructor or by calling updateOptions) or by dygraphs, and may be set to a
360 * per-series value.
1bc88216
DV
361 * @param {string} name The name of the option, e.g. 'rollPeriod'.
362 * @param {string} [seriesName] The name of the series to which the option
629a09ae
DV
363 * will be applied. If no per-series value of this option is available, then
364 * the global value is returned. This is optional.
365 * @return { ... } The value of the option.
366 */
227b93cc 367Dygraph.prototype.attr_ = function(name, seriesName) {
7fea22be
DV
368 // For "production" code, this gets removed by uglifyjs.
369 if (process.env.NODE_ENV != 'production') {
370 if (typeof(OPTIONS_REFERENCE) === 'undefined') {
371 console.error('Must include options reference JS for testing');
372 } else if (!OPTIONS_REFERENCE.hasOwnProperty(name)) {
373 console.error('Dygraphs is using property ' + name + ', which has no ' +
374 'entry in the Dygraphs.OPTIONS_REFERENCE listing.');
375 // Only log this error once.
376 OPTIONS_REFERENCE[name] = true;
377 }
378 }
5daa462d 379 return seriesName ? this.attributes_.getForSeries(name, seriesName) : this.attributes_.get(name);
285a6bda
DV
380};
381
6a1aa64f 382/**
e2c21500
DV
383 * Returns the current value for an option, as set in the constructor or via
384 * updateOptions. You may pass in an (optional) series name to get per-series
385 * values for the option.
386 *
387 * All values returned by this method should be considered immutable. If you
388 * modify them, there is no guarantee that the changes will be honored or that
389 * dygraphs will remain in a consistent state. If you want to modify an option,
390 * use updateOptions() instead.
391 *
1bc88216
DV
392 * @param {string} name The name of the option (e.g. 'strokeWidth')
393 * @param {string=} opt_seriesName Series name to get per-series values.
394 * @return {*} The value of the option.
e2c21500
DV
395 */
396Dygraph.prototype.getOption = function(name, opt_seriesName) {
397 return this.attr_(name, opt_seriesName);
398};
399
5266fc00 400/**
1c420f2f 401 * Like getOption(), but specifically returns a number.
5266fc00
DV
402 * This is a convenience function for working with the Closure Compiler.
403 * @param {string} name The name of the option (e.g. 'strokeWidth')
404 * @param {string=} opt_seriesName Series name to get per-series values.
405 * @return {number} The value of the option.
406 * @private
407 */
408Dygraph.prototype.getNumericOption = function(name, opt_seriesName) {
409 return /** @type{number} */(this.getOption(name, opt_seriesName));
410};
411
412/**
1c420f2f 413 * Like getOption(), but specifically returns a string.
5266fc00
DV
414 * This is a convenience function for working with the Closure Compiler.
415 * @param {string} name The name of the option (e.g. 'strokeWidth')
416 * @param {string=} opt_seriesName Series name to get per-series values.
417 * @return {string} The value of the option.
418 * @private
419 */
420Dygraph.prototype.getStringOption = function(name, opt_seriesName) {
421 return /** @type{string} */(this.getOption(name, opt_seriesName));
422};
423
424/**
1c420f2f 425 * Like getOption(), but specifically returns a boolean.
5266fc00
DV
426 * This is a convenience function for working with the Closure Compiler.
427 * @param {string} name The name of the option (e.g. 'strokeWidth')
428 * @param {string=} opt_seriesName Series name to get per-series values.
429 * @return {boolean} The value of the option.
430 * @private
431 */
432Dygraph.prototype.getBooleanOption = function(name, opt_seriesName) {
433 return /** @type{boolean} */(this.getOption(name, opt_seriesName));
434};
435
436/**
1c420f2f 437 * Like getOption(), but specifically returns a function.
5266fc00
DV
438 * This is a convenience function for working with the Closure Compiler.
439 * @param {string} name The name of the option (e.g. 'strokeWidth')
440 * @param {string=} opt_seriesName Series name to get per-series values.
441 * @return {function(...)} The value of the option.
442 * @private
443 */
444Dygraph.prototype.getFunctionOption = function(name, opt_seriesName) {
445 return /** @type{function(...)} */(this.getOption(name, opt_seriesName));
446};
447
48dc3815
RK
448Dygraph.prototype.getOptionForAxis = function(name, axis) {
449 return this.attributes_.getForAxis(name, axis);
83b0c192
DV
450};
451
e2c21500 452/**
48e614ac 453 * @private
5266fc00 454 * @param {string} axis The name of the axis (i.e. 'x', 'y' or 'y2')
48e614ac
DV
455 * @return { ... } A function mapping string -> option value
456 */
457Dygraph.prototype.optionsViewForAxis_ = function(axis) {
458 var self = this;
459 return function(opt) {
758a629f 460 var axis_opts = self.user_attrs_.axes;
2fd143d3 461 if (axis_opts && axis_opts[axis] && axis_opts[axis].hasOwnProperty(opt)) {
48e614ac
DV
462 return axis_opts[axis][opt];
463 }
5b9b2142
RK
464
465 // I don't like that this is in a second spot.
466 if (axis === 'x' && opt === 'logscale') {
467 // return the default value.
468 // TODO(konigsberg): pull the default from a global default.
469 return false;
470 }
471
48e614ac
DV
472 // user-specified attributes always trump defaults, even if they're less
473 // specific.
474 if (typeof(self.user_attrs_[opt]) != 'undefined') {
475 return self.user_attrs_[opt];
476 }
477
758a629f 478 axis_opts = self.attrs_.axes;
2fd143d3 479 if (axis_opts && axis_opts[axis] && axis_opts[axis].hasOwnProperty(opt)) {
48e614ac
DV
480 return axis_opts[axis][opt];
481 }
482 // check old-style axis options
483 // TODO(danvk): add a deprecation warning if either of these match.
484 if (axis == 'y' && self.axes_[0].hasOwnProperty(opt)) {
485 return self.axes_[0][opt];
486 } else if (axis == 'y2' && self.axes_[1].hasOwnProperty(opt)) {
487 return self.axes_[1][opt];
488 }
489 return self.attr_(opt);
490 };
491};
492
493/**
6a1aa64f 494 * Returns the current rolling period, as set by the user or an option.
1bc88216 495 * @return {number} The number of points in the rolling window
6a1aa64f 496 */
285a6bda 497Dygraph.prototype.rollPeriod = function() {
6a1aa64f 498 return this.rollPeriod_;
76171648
DV
499};
500
599fb4ad
DV
501/**
502 * Returns the currently-visible x-range. This can be affected by zooming,
503 * panning or a call to updateOptions.
504 * Returns a two-element array: [left, right].
505 * If the Dygraph has dates on the x-axis, these will be millis since epoch.
506 */
507Dygraph.prototype.xAxisRange = function() {
4cac8c7a
RK
508 return this.dateWindow_ ? this.dateWindow_ : this.xAxisExtremes();
509};
599fb4ad 510
4cac8c7a
RK
511/**
512 * Returns the lower- and upper-bound x-axis values of the
513 * data set.
514 */
515Dygraph.prototype.xAxisExtremes = function() {
b0963cdb 516 var pad = this.getNumericOption('xRangePad') / this.plotter_.area.w;
4bac38d8 517 if (this.numRows() === 0) {
fa460473
KW
518 return [0 - pad, 1 + pad];
519 }
599fb4ad
DV
520 var left = this.rawData_[0][0];
521 var right = this.rawData_[this.rawData_.length - 1][0];
fa460473
KW
522 if (pad) {
523 // Must keep this in sync with dygraph-layout _evaluateLimits()
524 var range = right - left;
525 left -= range * pad;
526 right += range * pad;
527 }
599fb4ad
DV
528 return [left, right];
529};
530
3230c662 531/**
d58ae307
DV
532 * Returns the currently-visible y-range for an axis. This can be affected by
533 * zooming, panning or a call to updateOptions. Axis indices are zero-based. If
534 * called with no arguments, returns the range of the first axis.
3230c662
DV
535 * Returns a two-element array: [bottom, top].
536 */
d58ae307 537Dygraph.prototype.yAxisRange = function(idx) {
d63e6799 538 if (typeof(idx) == "undefined") idx = 0;
d64b8fea
RK
539 if (idx < 0 || idx >= this.axes_.length) {
540 return null;
541 }
542 var axis = this.axes_[idx];
543 return [ axis.computedValueRange[0], axis.computedValueRange[1] ];
d58ae307
DV
544};
545
546/**
547 * Returns the currently-visible y-ranges for each axis. This can be affected by
548 * zooming, panning, calls to updateOptions, etc.
549 * Returns an array of [bottom, top] pairs, one for each y-axis.
550 */
551Dygraph.prototype.yAxisRanges = function() {
552 var ret = [];
553 for (var i = 0; i < this.axes_.length; i++) {
554 ret.push(this.yAxisRange(i));
555 }
556 return ret;
3230c662
DV
557};
558
d58ae307 559// TODO(danvk): use these functions throughout dygraphs.
3230c662
DV
560/**
561 * Convert from data coordinates to canvas/div X/Y coordinates.
d58ae307
DV
562 * If specified, do this conversion for the coordinate system of a particular
563 * axis. Uses the first axis by default.
3230c662 564 * Returns a two-element array: [X, Y]
ff022deb 565 *
0747928a 566 * Note: use toDomXCoord instead of toDomCoords(x, null) and use toDomYCoord
ff022deb 567 * instead of toDomCoords(null, y, axis).
3230c662 568 */
d58ae307 569Dygraph.prototype.toDomCoords = function(x, y, axis) {
ff022deb
RK
570 return [ this.toDomXCoord(x), this.toDomYCoord(y, axis) ];
571};
572
573/**
574 * Convert from data x coordinates to canvas/div X coordinate.
575 * If specified, do this conversion for the coordinate system of a particular
0037b2a4
RK
576 * axis.
577 * Returns a single value or null if x is null.
ff022deb
RK
578 */
579Dygraph.prototype.toDomXCoord = function(x) {
758a629f 580 if (x === null) {
ff022deb 581 return null;
758a629f 582 }
ff022deb 583
3230c662 584 var area = this.plotter_.area;
ff022deb
RK
585 var xRange = this.xAxisRange();
586 return area.x + (x - xRange[0]) / (xRange[1] - xRange[0]) * area.w;
758a629f 587};
3230c662 588
ff022deb
RK
589/**
590 * Convert from data x coordinates to canvas/div Y coordinate and optional
591 * axis. Uses the first axis by default.
592 *
593 * returns a single value or null if y is null.
594 */
595Dygraph.prototype.toDomYCoord = function(y, axis) {
0747928a 596 var pct = this.toPercentYCoord(y, axis);
3230c662 597
758a629f 598 if (pct === null) {
ff022deb
RK
599 return null;
600 }
e4416fb9 601 var area = this.plotter_.area;
ff022deb 602 return area.y + pct * area.h;
758a629f 603};
3230c662
DV
604
605/**
606 * Convert from canvas/div coords to data coordinates.
d58ae307
DV
607 * If specified, do this conversion for the coordinate system of a particular
608 * axis. Uses the first axis by default.
ff022deb
RK
609 * Returns a two-element array: [X, Y].
610 *
0747928a 611 * Note: use toDataXCoord instead of toDataCoords(x, null) and use toDataYCoord
ff022deb 612 * instead of toDataCoords(null, y, axis).
3230c662 613 */
d58ae307 614Dygraph.prototype.toDataCoords = function(x, y, axis) {
ff022deb
RK
615 return [ this.toDataXCoord(x), this.toDataYCoord(y, axis) ];
616};
617
618/**
619 * Convert from canvas/div x coordinate to data coordinate.
620 *
621 * If x is null, this returns null.
622 */
623Dygraph.prototype.toDataXCoord = function(x) {
758a629f 624 if (x === null) {
ff022deb 625 return null;
3230c662
DV
626 }
627
ff022deb
RK
628 var area = this.plotter_.area;
629 var xRange = this.xAxisRange();
5b9b2142
RK
630
631 if (!this.attributes_.getForAxis("logscale", 'x')) {
632 return xRange[0] + (x - area.x) / area.w * (xRange[1] - xRange[0]);
633 } else {
634 // TODO: remove duplicate code?
635 // Computing the inverse of toDomCoord.
636 var pct = (x - area.x) / area.w;
637
638 // Computing the inverse of toPercentXCoord. The function was arrived at with
639 // the following steps:
640 //
641 // Original calcuation:
642 // pct = (log(x) - log(xRange[0])) / (log(xRange[1]) - log(xRange[0])));
643 //
644 // Multiply both sides by the right-side demoninator.
645 // pct * (log(xRange[1] - log(xRange[0]))) = log(x) - log(xRange[0])
646 //
647 // add log(xRange[0]) to both sides
648 // log(xRange[0]) + (pct * (log(xRange[1]) - log(xRange[0])) = log(x);
649 //
650 // Swap both sides of the equation,
651 // log(x) = log(xRange[0]) + (pct * (log(xRange[1]) - log(xRange[0]))
652 //
653 // Use both sides as the exponent in 10^exp and we're done.
654 // x = 10 ^ (log(xRange[0]) + (pct * (log(xRange[1]) - log(xRange[0])))
e8c70e4e
DV
655 var logr0 = utils.log10(xRange[0]);
656 var logr1 = utils.log10(xRange[1]);
5b9b2142 657 var exponent = logr0 + (pct * (logr1 - logr0));
e8c70e4e 658 var value = Math.pow(utils.LOG_SCALE, exponent);
5b9b2142
RK
659 return value;
660 }
ff022deb
RK
661};
662
663/**
664 * Convert from canvas/div y coord to value.
665 *
666 * If y is null, this returns null.
667 * if axis is null, this uses the first axis.
668 */
669Dygraph.prototype.toDataYCoord = function(y, axis) {
758a629f 670 if (y === null) {
ff022deb 671 return null;
3230c662
DV
672 }
673
ff022deb
RK
674 var area = this.plotter_.area;
675 var yRange = this.yAxisRange(axis);
676
b70247dc 677 if (typeof(axis) == "undefined") axis = 0;
1f8c95d8 678 if (!this.attributes_.getForAxis("logscale", axis)) {
d9816e62 679 return yRange[0] + (area.y + area.h - y) / area.h * (yRange[1] - yRange[0]);
ff022deb
RK
680 } else {
681 // Computing the inverse of toDomCoord.
758a629f 682 var pct = (y - area.y) / area.h;
ff022deb
RK
683
684 // Computing the inverse of toPercentYCoord. The function was arrived at with
685 // the following steps:
686 //
687 // Original calcuation:
5b9b2142 688 // pct = (log(yRange[1]) - log(y)) / (log(yRange[1]) - log(yRange[0]));
ff022deb 689 //
5b9b2142
RK
690 // Multiply both sides by the right-side demoninator.
691 // pct * (log(yRange[1]) - log(yRange[0])) = log(yRange[1]) - log(y);
ff022deb 692 //
5b9b2142
RK
693 // subtract log(yRange[1]) from both sides.
694 // (pct * (log(yRange[1]) - log(yRange[0]))) - log(yRange[1]) = -log(y);
ff022deb 695 //
5b9b2142
RK
696 // and multiply both sides by -1.
697 // log(yRange[1]) - (pct * (logr1 - log(yRange[0])) = log(y);
698 //
699 // Swap both sides of the equation,
700 // log(y) = log(yRange[1]) - (pct * (log(yRange[1]) - log(yRange[0])));
701 //
702 // Use both sides as the exponent in 10^exp and we're done.
703 // y = 10 ^ (log(yRange[1]) - (pct * (log(yRange[1]) - log(yRange[0]))));
e8c70e4e
DV
704 var logr0 = utils.log10(yRange[0]);
705 var logr1 = utils.log10(yRange[1]);
5b9b2142 706 var exponent = logr1 - (pct * (logr1 - logr0));
e8c70e4e 707 var value = Math.pow(utils.LOG_SCALE, exponent);
ff022deb
RK
708 return value;
709 }
3230c662
DV
710};
711
e99fde05 712/**
ff022deb 713 * Converts a y for an axis to a percentage from the top to the
4cac8c7a 714 * bottom of the drawing area.
ff022deb
RK
715 *
716 * If the coordinate represents a value visible on the canvas, then
717 * the value will be between 0 and 1, where 0 is the top of the canvas.
718 * However, this method will return values outside the range, as
719 * values can fall outside the canvas.
720 *
721 * If y is null, this returns null.
722 * if axis is null, this uses the first axis.
629a09ae 723 *
1bc88216
DV
724 * @param {number} y The data y-coordinate.
725 * @param {number} [axis] The axis number on which the data coordinate lives.
726 * @return {number} A fraction in [0, 1] where 0 = the top edge.
ff022deb
RK
727 */
728Dygraph.prototype.toPercentYCoord = function(y, axis) {
758a629f 729 if (y === null) {
ff022deb
RK
730 return null;
731 }
7d0e7a0d 732 if (typeof(axis) == "undefined") axis = 0;
ff022deb 733
ff022deb
RK
734 var yRange = this.yAxisRange(axis);
735
736 var pct;
1761e6ed 737 var logscale = this.attributes_.getForAxis("logscale", axis);
5b9b2142 738 if (logscale) {
e8c70e4e
DV
739 var logr0 = utils.log10(yRange[0]);
740 var logr1 = utils.log10(yRange[1]);
741 pct = (logr1 - utils.log10(y)) / (logr1 - logr0);
5b9b2142 742 } else {
4cac8c7a
RK
743 // yRange[1] - y is unit distance from the bottom.
744 // yRange[1] - yRange[0] is the scale of the range.
ff022deb
RK
745 // (yRange[1] - y) / (yRange[1] - yRange[0]) is the % from the bottom.
746 pct = (yRange[1] - y) / (yRange[1] - yRange[0]);
ff022deb
RK
747 }
748 return pct;
758a629f 749};
ff022deb
RK
750
751/**
4cac8c7a
RK
752 * Converts an x value to a percentage from the left to the right of
753 * the drawing area.
754 *
755 * If the coordinate represents a value visible on the canvas, then
756 * the value will be between 0 and 1, where 0 is the left of the canvas.
757 * However, this method will return values outside the range, as
758 * values can fall outside the canvas.
759 *
760 * If x is null, this returns null.
1bc88216
DV
761 * @param {number} x The data x-coordinate.
762 * @return {number} A fraction in [0, 1] where 0 = the left edge.
4cac8c7a
RK
763 */
764Dygraph.prototype.toPercentXCoord = function(x) {
758a629f 765 if (x === null) {
4cac8c7a
RK
766 return null;
767 }
768
4cac8c7a 769 var xRange = this.xAxisRange();
5b9b2142
RK
770 var pct;
771 var logscale = this.attributes_.getForAxis("logscale", 'x') ;
46fd9089 772 if (logscale === true) { // logscale can be null so we test for true explicitly.
e8c70e4e
DV
773 var logr0 = utils.log10(xRange[0]);
774 var logr1 = utils.log10(xRange[1]);
775 pct = (utils.log10(x) - logr0) / (logr1 - logr0);
5b9b2142
RK
776 } else {
777 // x - xRange[0] is unit distance from the left.
778 // xRange[1] - xRange[0] is the scale of the range.
779 // The full expression below is the % from the left.
780 pct = (x - xRange[0]) / (xRange[1] - xRange[0]);
781 }
782 return pct;
629a09ae 783};
4cac8c7a
RK
784
785/**
e99fde05 786 * Returns the number of columns (including the independent variable).
1bc88216 787 * @return {number} The number of columns.
e99fde05
DV
788 */
789Dygraph.prototype.numColumns = function() {
fa460473 790 if (!this.rawData_) return 0;
395e98a3 791 return this.rawData_[0] ? this.rawData_[0].length : this.attr_("labels").length;
e99fde05
DV
792};
793
794/**
795 * Returns the number of rows (excluding any header/label row).
1bc88216 796 * @return {number} The number of rows, less any header.
e99fde05
DV
797 */
798Dygraph.prototype.numRows = function() {
fa460473 799 if (!this.rawData_) return 0;
e99fde05
DV
800 return this.rawData_.length;
801};
802
803/**
804 * Returns the value in the given row and column. If the row and column exceed
805 * the bounds on the data, returns null. Also returns null if the value is
806 * missing.
1bc88216
DV
807 * @param {number} row The row number of the data (0-based). Row 0 is the
808 * first row of data, not a header row.
809 * @param {number} col The column number of the data (0-based)
810 * @return {number} The value in the specified cell or null if the row/col
811 * were out of range.
e99fde05
DV
812 */
813Dygraph.prototype.getValue = function(row, col) {
814 if (row < 0 || row > this.rawData_.length) return null;
815 if (col < 0 || col > this.rawData_[row].length) return null;
816
817 return this.rawData_[row][col];
818};
819
629a09ae 820/**
285a6bda 821 * Generates interface elements for the Dygraph: a containing div, a div to
6a1aa64f 822 * display the current point, and a textbox to adjust the rolling average
697e70b2 823 * period. Also creates the Renderer/Layout elements.
6a1aa64f
DV
824 * @private
825 */
285a6bda 826Dygraph.prototype.createInterface_ = function() {
6a1aa64f
DV
827 // Create the all-enclosing graph div
828 var enclosing = this.maindiv_;
829
b0c3b730 830 this.graphDiv = document.createElement("div");
aeca29ac 831
e0629007
DV
832 // TODO(danvk): any other styles that are useful to set here?
833 this.graphDiv.style.textAlign = 'left'; // This is a CSS "reset"
cb8bb6a6 834 this.graphDiv.style.position = 'relative';
b0c3b730
DV
835 enclosing.appendChild(this.graphDiv);
836
837 // Create the canvas for interactive parts of the chart.
6ecc0739 838 this.canvas_ = utils.createCanvas();
b0c3b730 839 this.canvas_.style.position = "absolute";
aeca29ac 840
c28088bc
KW
841 // ... and for static parts of the chart.
842 this.hidden_ = this.createPlotKitCanvas_(this.canvas_);
843
6ecc0739
DV
844 this.canvas_ctx_ = utils.getContext(this.canvas_);
845 this.hidden_ctx_ = utils.getContext(this.hidden_);
76171648 846
37819481
PH
847 this.resizeElements_();
848
eb7bf005
EC
849 // The interactive parts of the graph are drawn on top of the chart.
850 this.graphDiv.appendChild(this.hidden_);
851 this.graphDiv.appendChild(this.canvas_);
920208fb
PF
852 this.mouseEventElement_ = this.createMouseEventElement_();
853
854 // Create the grapher
855 this.layout_ = new DygraphLayout(this);
856
76171648 857 var dygraph = this;
de8f284f 858
9fd9bbbb 859 this.mouseMoveHandler_ = function(e) {
860 dygraph.mouseMove_(e);
861 };
de8f284f 862
9fd9bbbb 863 this.mouseOutHandler_ = function(e) {
def24194
DV
864 // The mouse has left the chart if:
865 // 1. e.target is inside the chart
866 // 2. e.relatedTarget is outside the chart
867 var target = e.target || e.fromElement;
868 var relatedTarget = e.relatedTarget || e.toElement;
6ecc0739
DV
869 if (utils.isNodeContainedBy(target, dygraph.graphDiv) &&
870 !utils.isNodeContainedBy(relatedTarget, dygraph.graphDiv)) {
def24194
DV
871 dygraph.mouseOut_(e);
872 }
9fd9bbbb 873 };
874
aeca29ac
RK
875 this.addAndTrackEvent(window, 'mouseout', this.mouseOutHandler_);
876 this.addAndTrackEvent(this.mouseEventElement_, 'mousemove', this.mouseMoveHandler_);
697e70b2 877
9fd9bbbb 878 // Don't recreate and register the resize handler on subsequent calls.
879 // This happens when the graph is resized.
880 if (!this.resizeHandler_) {
e0b3afad
RK
881 this.resizeHandler_ = function(e) {
882 dygraph.resize();
883 };
1c6b239c 884
e0b3afad
RK
885 // Update when the window is resized.
886 // TODO(danvk): drop frames depending on complexity of the chart.
aeca29ac 887 this.addAndTrackEvent(window, 'resize', this.resizeHandler_);
e0b3afad 888 }
4cfcc38c
DV
889};
890
aeca29ac
RK
891Dygraph.prototype.resizeElements_ = function() {
892 this.graphDiv.style.width = this.width_ + "px";
893 this.graphDiv.style.height = this.height_ + "px";
37819481 894
6ecc0739 895 var canvasScale = utils.getContextPixelRatio(this.canvas_ctx_);
37819481
PH
896 this.canvas_.width = this.width_ * canvasScale;
897 this.canvas_.height = this.height_ * canvasScale;
aeca29ac
RK
898 this.canvas_.style.width = this.width_ + "px"; // for IE
899 this.canvas_.style.height = this.height_ + "px"; // for IE
37819481
PH
900 if (canvasScale !== 1) {
901 this.canvas_ctx_.scale(canvasScale, canvasScale);
902 }
903
6ecc0739 904 var hiddenScale = utils.getContextPixelRatio(this.hidden_ctx_);
37819481
PH
905 this.hidden_.width = this.width_ * hiddenScale;
906 this.hidden_.height = this.height_ * hiddenScale;
c28088bc
KW
907 this.hidden_.style.width = this.width_ + "px"; // for IE
908 this.hidden_.style.height = this.height_ + "px"; // for IE
37819481
PH
909 if (hiddenScale !== 1) {
910 this.hidden_ctx_.scale(hiddenScale, hiddenScale);
911 }
f914bed1 912};
aeca29ac 913
4cfcc38c
DV
914/**
915 * Detach DOM elements in the dygraph and null out all data references.
916 * Calling this when you're done with a dygraph can dramatically reduce memory
917 * usage. See, e.g., the tests/perf.html example.
918 */
919Dygraph.prototype.destroy = function() {
aeca29ac
RK
920 this.canvas_ctx_.restore();
921 this.hidden_ctx_.restore();
922
92c5f414
DV
923 // Destroy any plugins, in the reverse order that they were registered.
924 for (var i = this.plugins_.length - 1; i >= 0; i--) {
925 var p = this.plugins_.pop();
926 if (p.plugin.destroy) p.plugin.destroy();
927 }
928
4cfcc38c
DV
929 var removeRecursive = function(node) {
930 while (node.hasChildNodes()) {
931 removeRecursive(node.firstChild);
932 node.removeChild(node.firstChild);
933 }
934 };
de8f284f 935
aeca29ac 936 this.removeTrackedEvents_();
6a4587ac
RK
937
938 // remove mouse event handlers (This may not be necessary anymore)
e8c70e4e
DV
939 utils.removeEvent(window, 'mouseout', this.mouseOutHandler_);
940 utils.removeEvent(this.mouseEventElement_, 'mousemove', this.mouseMoveHandler_);
7d6df48d
RK
941
942 // remove window handlers
e8c70e4e 943 utils.removeEvent(window,'resize', this.resizeHandler_);
7d6df48d
RK
944 this.resizeHandler_ = null;
945
4cfcc38c
DV
946 removeRecursive(this.maindiv_);
947
948 var nullOut = function(obj) {
949 for (var n in obj) {
950 if (typeof(obj[n]) === 'object') {
951 obj[n] = null;
952 }
953 }
954 };
4cfcc38c
DV
955 // These may not all be necessary, but it can't hurt...
956 nullOut(this.layout_);
957 nullOut(this.plotter_);
958 nullOut(this);
959};
6a1aa64f
DV
960
961/**
629a09ae
DV
962 * Creates the canvas on which the chart will be drawn. Only the Renderer ever
963 * draws on this particular canvas. All Dygraph work (i.e. drawing hover dots
964 * or the zoom rectangles) is done on this.canvas_.
8846615a 965 * @param {Object} canvas The Dygraph canvas over which to overlay the plot
6a1aa64f
DV
966 * @return {Object} The newly-created canvas
967 * @private
968 */
285a6bda 969Dygraph.prototype.createPlotKitCanvas_ = function(canvas) {
6ecc0739 970 var h = utils.createCanvas();
6a1aa64f 971 h.style.position = "absolute";
9ac5e4ae
DV
972 // TODO(danvk): h should be offset from canvas. canvas needs to include
973 // some extra area to make it easier to zoom in on the far left and far
974 // right. h needs to be precisely the plot area, so that clipping occurs.
6a1aa64f
DV
975 h.style.top = canvas.style.top;
976 h.style.left = canvas.style.left;
977 h.width = this.width_;
978 h.height = this.height_;
f8cfec73
DV
979 h.style.width = this.width_ + "px"; // for IE
980 h.style.height = this.height_ + "px"; // for IE
6a1aa64f
DV
981 return h;
982};
983
629a09ae 984/**
920208fb
PF
985 * Creates an overlay element used to handle mouse events.
986 * @return {Object} The mouse event element.
987 * @private
988 */
989Dygraph.prototype.createMouseEventElement_ = function() {
9901b0c1 990 return this.canvas_;
920208fb
PF
991};
992
993/**
6a1aa64f
DV
994 * Generate a set of distinct colors for the data series. This is done with a
995 * color wheel. Saturation/Value are customizable, and the hue is
996 * equally-spaced around the color wheel. If a custom set of colors is
997 * specified, that is used instead.
6a1aa64f
DV
998 * @private
999 */
285a6bda 1000Dygraph.prototype.setColors_ = function() {
ee53deb9
DV
1001 var labels = this.getLabels();
1002 var num = labels.length - 1;
6a1aa64f 1003 this.colors_ = [];
ee53deb9 1004 this.colorsMap_ = {};
48423521
RK
1005
1006 // These are used for when no custom colors are specified.
b0963cdb
DV
1007 var sat = this.getNumericOption('colorSaturation') || 1.0;
1008 var val = this.getNumericOption('colorValue') || 0.5;
48423521
RK
1009 var half = Math.ceil(num / 2);
1010
b0963cdb 1011 var colors = this.getOption('colors');
48423521
RK
1012 var visibility = this.visibility();
1013 for (var i = 0; i < num; i++) {
1014 if (!visibility[i]) {
1015 continue;
1016 }
1017 var label = labels[i + 1];
1018 var colorStr = this.attributes_.getForSeries('color', label);
1019 if (!colorStr) {
1020 if (colors) {
1021 colorStr = colors[i % colors.length];
1022 } else {
1023 // alternate colors for high contrast.
1024 var idx = i % 2 ? (half + (i + 1)/ 2) : Math.ceil((i + 1) / 2);
1025 var hue = (1.0 * idx / (1 + num));
e8c70e4e 1026 colorStr = utils.hsvToRGB(hue, sat, val);
48423521
RK
1027 }
1028 }
1029 this.colors_.push(colorStr);
1030 this.colorsMap_[label] = colorStr;
1031 }
629a09ae 1032};
6a1aa64f 1033
43af96e7
NK
1034/**
1035 * Return the list of colors. This is either the list of colors passed in the
629a09ae 1036 * attributes or the autogenerated list of rgb(r,g,b) strings.
e2c21500 1037 * This does not return colors for invisible series.
8ef9d44d 1038 * @return {Array.<string>} The list of colors.
43af96e7
NK
1039 */
1040Dygraph.prototype.getColors = function() {
1041 return this.colors_;
1042};
1043
6a1aa64f 1044/**
e2c21500
DV
1045 * Returns a few attributes of a series, i.e. its color, its visibility, which
1046 * axis it's assigned to, and its column in the original data.
1047 * Returns null if the series does not exist.
1048 * Otherwise, returns an object with column, visibility, color and axis properties.
1049 * The "axis" property will be set to 1 for y1 and 2 for y2.
1050 * The "column" property can be fed back into getValue(row, column) to get
1051 * values for this series.
6a1aa64f 1052 */
e2c21500
DV
1053Dygraph.prototype.getPropertiesForSeries = function(series_name) {
1054 var idx = -1;
1055 var labels = this.getLabels();
1056 for (var i = 1; i < labels.length; i++) {
1057 if (labels[i] == series_name) {
1058 idx = i;
1059 break;
b0c3b730 1060 }
6a1aa64f 1061 }
e2c21500 1062 if (idx == -1) return null;
0abfbd7e 1063
e2c21500
DV
1064 return {
1065 name: series_name,
1066 column: idx,
1067 visible: this.visibility()[idx - 1],
189f8030 1068 color: this.colorsMap_[series_name],
16f00742 1069 axis: 1 + this.attributes_.axisForSeries(series_name)
e2c21500 1070 };
0abfbd7e
DV
1071};
1072
1073/**
6a1aa64f 1074 * Create the text box to adjust the averaging period
6a1aa64f
DV
1075 * @private
1076 */
285a6bda 1077Dygraph.prototype.createRollInterface_ = function() {
8c69de65
DV
1078 // Create a roller if one doesn't exist already.
1079 if (!this.roller_) {
1080 this.roller_ = document.createElement("input");
1081 this.roller_.type = "text";
1082 this.roller_.style.display = "none";
1083 this.graphDiv.appendChild(this.roller_);
1084 }
1085
b0963cdb 1086 var display = this.getBooleanOption('showRoller') ? 'block' : 'none';
26ca7938 1087
0c38f187 1088 var area = this.plotter_.area;
b0c3b730
DV
1089 var textAttr = { "position": "absolute",
1090 "zIndex": 10,
0c38f187
DV
1091 "top": (area.y + area.h - 25) + "px",
1092 "left": (area.x + 1) + "px",
b0c3b730 1093 "display": display
6a1aa64f 1094 };
8c69de65
DV
1095 this.roller_.size = "2";
1096 this.roller_.value = this.rollPeriod_;
b0c3b730 1097 for (var name in textAttr) {
85b99f0b 1098 if (textAttr.hasOwnProperty(name)) {
8c69de65 1099 this.roller_.style[name] = textAttr[name];
85b99f0b 1100 }
b0c3b730
DV
1101 }
1102
76171648 1103 var dygraph = this;
8c69de65 1104 this.roller_.onchange = function() { dygraph.adjustRoll(dygraph.roller_.value); };
76171648
DV
1105};
1106
629a09ae 1107/**
062ef401
JB
1108 * Set up all the mouse handlers needed to capture dragging behavior for zoom
1109 * events.
1110 * @private
1111 */
1112Dygraph.prototype.createDragInterface_ = function() {
1113 var context = {
1114 // Tracks whether the mouse is down right now
1115 isZooming: false,
1116 isPanning: false, // is this drag part of a pan?
1117 is2DPan: false, // if so, is that pan 1- or 2-dimensional?
8442269f
RK
1118 dragStartX: null, // pixel coordinates
1119 dragStartY: null, // pixel coordinates
1120 dragEndX: null, // pixel coordinates
1121 dragEndY: null, // pixel coordinates
062ef401 1122 dragDirection: null,
8442269f
RK
1123 prevEndX: null, // pixel coordinates
1124 prevEndY: null, // pixel coordinates
062ef401 1125 prevDragDirection: null,
421f1773 1126 cancelNextDblclick: false, // see comment in dygraph-interaction-model.js
062ef401 1127
ec291cbe
RK
1128 // The value on the left side of the graph when a pan operation starts.
1129 initialLeftmostDate: null,
1130
1131 // The number of units each pixel spans. (This won't be valid for log
1132 // scales)
1133 xUnitsPerPixel: null,
062ef401
JB
1134
1135 // TODO(danvk): update this comment
1136 // The range in second/value units that the viewport encompasses during a
1137 // panning operation.
1138 dateRange: null,
1139
8442269f
RK
1140 // Top-left corner of the canvas, in DOM coords
1141 // TODO(konigsberg): Rename topLeftCanvasX, topLeftCanvasY.
062ef401
JB
1142 px: 0,
1143 py: 0,
1144
965a030e 1145 // Values for use with panEdgeFraction, which limit how far outside the
4cac8c7a
RK
1146 // graph's data boundaries it can be panned.
1147 boundedDates: null, // [minDate, maxDate]
1148 boundedValues: null, // [[minValue, maxValue] ...]
1149
2bad4d92
DV
1150 // We cover iframes during mouse interactions. See comments in
1151 // dygraph-utils.js for more info on why this is a good idea.
6ecc0739 1152 tarp: new utils.IFrameTarp(),
2bad4d92 1153
6a4587ac
RK
1154 // contextB is the same thing as this context object but renamed.
1155 initializeMouseDown: function(event, g, contextB) {
062ef401
JB
1156 // prevents mouse drags from selecting page text.
1157 if (event.preventDefault) {
1158 event.preventDefault(); // Firefox, Chrome, etc.
6a1aa64f 1159 } else {
062ef401
JB
1160 event.returnValue = false; // IE
1161 event.cancelBubble = true;
6a1aa64f
DV
1162 }
1163
6ecc0739 1164 var canvasPos = utils.findPos(g.canvas_);
464b5f50
DV
1165 contextB.px = canvasPos.x;
1166 contextB.py = canvasPos.y;
6ecc0739
DV
1167 contextB.dragStartX = utils.dragGetX_(event, contextB);
1168 contextB.dragStartY = utils.dragGetY_(event, contextB);
6a4587ac 1169 contextB.cancelNextDblclick = false;
2bad4d92 1170 contextB.tarp.cover();
3f50dabb
DV
1171 },
1172 destroy: function() {
1173 var context = this;
1174 if (context.isZooming || context.isPanning) {
1175 context.isZooming = false;
1176 context.dragStartX = null;
1177 context.dragStartY = null;
1178 }
1179
1180 if (context.isPanning) {
1181 context.isPanning = false;
1182 context.draggingDate = null;
1183 context.dateRange = null;
1184 for (var i = 0; i < self.axes_.length; i++) {
1185 delete self.axes_[i].draggingValue;
1186 delete self.axes_[i].dragValueRange;
1187 }
1188 }
1189
1190 context.tarp.uncover();
6a1aa64f 1191 }
062ef401 1192 };
2b188b3d 1193
b0963cdb 1194 var interactionModel = this.getOption("interactionModel");
8b83c6cc 1195
062ef401
JB
1196 // Self is the graph.
1197 var self = this;
6faebb69 1198
062ef401
JB
1199 // Function that binds the graph and context to the handler.
1200 var bindHandler = function(handler) {
1201 return function(event) {
1202 handler(event, self, context);
1203 };
1204 };
1205
1206 for (var eventName in interactionModel) {
1207 if (!interactionModel.hasOwnProperty(eventName)) continue;
aeca29ac 1208 this.addAndTrackEvent(this.mouseEventElement_, eventName,
062ef401
JB
1209 bindHandler(interactionModel[eventName]));
1210 }
1211
1212 // If the user releases the mouse button during a drag, but not over the
1213 // canvas, then it doesn't count as a zooming action.
3f50dabb
DV
1214 if (!interactionModel.willDestroyContextMyself) {
1215 var mouseUpHandler = function(event) {
1216 context.destroy();
1217 };
cb1261cb 1218
3f50dabb
DV
1219 this.addAndTrackEvent(document, 'mouseup', mouseUpHandler);
1220 }
6a1aa64f
DV
1221};
1222
1223/**
1224 * Draw a gray zoom rectangle over the desired area of the canvas. Also clears
1225 * up any previous zoom rectangles that were drawn. This could be optimized to
1226 * avoid extra redrawing, but it's tricky to avoid interactions with the status
1227 * dots.
ccd9d7c2 1228 *
1bc88216 1229 * @param {number} direction the direction of the zoom rectangle. Acceptable
6ecc0739 1230 * values are utils.HORIZONTAL and utils.VERTICAL.
1bc88216
DV
1231 * @param {number} startX The X position where the drag started, in canvas
1232 * coordinates.
1233 * @param {number} endX The current X position of the drag, in canvas coords.
1234 * @param {number} startY The Y position where the drag started, in canvas
1235 * coordinates.
1236 * @param {number} endY The current Y position of the drag, in canvas coords.
1237 * @param {number} prevDirection the value of direction on the previous call to
1238 * this function. Used to avoid excess redrawing
1239 * @param {number} prevEndX The value of endX on the previous call to this
1240 * function. Used to avoid excess redrawing
1241 * @param {number} prevEndY The value of endY on the previous call to this
1242 * function. Used to avoid excess redrawing
6a1aa64f
DV
1243 * @private
1244 */
7201b11e
JB
1245Dygraph.prototype.drawZoomRect_ = function(direction, startX, endX, startY,
1246 endY, prevDirection, prevEndX,
1247 prevEndY) {
2cf95fff 1248 var ctx = this.canvas_ctx_;
6a1aa64f
DV
1249
1250 // Clean up from the previous rect if necessary
6ecc0739 1251 if (prevDirection == utils.HORIZONTAL) {
fa54c193
FXB
1252 ctx.clearRect(Math.min(startX, prevEndX), this.layout_.getPlotArea().y,
1253 Math.abs(startX - prevEndX), this.layout_.getPlotArea().h);
6ecc0739 1254 } else if (prevDirection == utils.VERTICAL) {
fa54c193
FXB
1255 ctx.clearRect(this.layout_.getPlotArea().x, Math.min(startY, prevEndY),
1256 this.layout_.getPlotArea().w, Math.abs(startY - prevEndY));
6a1aa64f
DV
1257 }
1258
1259 // Draw a light-grey rectangle to show the new viewing area
6ecc0739 1260 if (direction == utils.HORIZONTAL) {
8b83c6cc
RK
1261 if (endX && startX) {
1262 ctx.fillStyle = "rgba(128,128,128,0.33)";
fa54c193
FXB
1263 ctx.fillRect(Math.min(startX, endX), this.layout_.getPlotArea().y,
1264 Math.abs(endX - startX), this.layout_.getPlotArea().h);
8b83c6cc 1265 }
6ecc0739 1266 } else if (direction == utils.VERTICAL) {
8b83c6cc
RK
1267 if (endY && startY) {
1268 ctx.fillStyle = "rgba(128,128,128,0.33)";
fa54c193
FXB
1269 ctx.fillRect(this.layout_.getPlotArea().x, Math.min(startY, endY),
1270 this.layout_.getPlotArea().w, Math.abs(endY - startY));
8b83c6cc 1271 }
6a1aa64f 1272 }
920208fb
PF
1273};
1274
1275/**
1276 * Clear the zoom rectangle (and perform no zoom).
1277 * @private
1278 */
1279Dygraph.prototype.clearZoomRect_ = function() {
1280 this.currentZoomRectArgs_ = null;
7c39bb3a 1281 this.canvas_ctx_.clearRect(0, 0, this.width_, this.height_);
6a1aa64f
DV
1282};
1283
1284/**
8b83c6cc
RK
1285 * Zoom to something containing [lowX, highX]. These are pixel coordinates in
1286 * the canvas. The exact zoom window may be slightly larger if there are no data
1287 * points near lowX or highX. Don't confuse this function with doZoomXDates,
1288 * which accepts dates that match the raw data. This function redraws the graph.
d58ae307 1289 *
1bc88216
DV
1290 * @param {number} lowX The leftmost pixel value that should be visible.
1291 * @param {number} highX The rightmost pixel value that should be visible.
6a1aa64f
DV
1292 * @private
1293 */
8b83c6cc 1294Dygraph.prototype.doZoomX_ = function(lowX, highX) {
920208fb 1295 this.currentZoomRectArgs_ = null;
6a1aa64f 1296 // Find the earliest and latest dates contained in this canvasx range.
8b83c6cc 1297 // Convert the call to date ranges of the raw data.
ff022deb
RK
1298 var minDate = this.toDataXCoord(lowX);
1299 var maxDate = this.toDataXCoord(highX);
8b83c6cc
RK
1300 this.doZoomXDates_(minDate, maxDate);
1301};
6a1aa64f 1302
8b83c6cc
RK
1303/**
1304 * Zoom to something containing [minDate, maxDate] values. Don't confuse this
1305 * method with doZoomX which accepts pixel coordinates. This function redraws
1306 * the graph.
d58ae307 1307 *
1bc88216
DV
1308 * @param {number} minDate The minimum date that should be visible.
1309 * @param {number} maxDate The maximum date that should be visible.
8b83c6cc
RK
1310 * @private
1311 */
1312Dygraph.prototype.doZoomXDates_ = function(minDate, maxDate) {
5b9b2142
RK
1313 // TODO(danvk): when xAxisRange is null (i.e. "fit to data", the animation
1314 // can produce strange effects. Rather than the x-axis transitioning slowly
b1a3b195
DV
1315 // between values, it can jerk around.)
1316 var old_window = this.xAxisRange();
1317 var new_window = [minDate, maxDate];
57baab03 1318 this.zoomed_x_ = true;
b1a3b195
DV
1319 var that = this;
1320 this.doAnimatedZoom(old_window, new_window, null, null, function() {
b0963cdb 1321 if (that.getFunctionOption("zoomCallback")) {
4ee251cb 1322 that.getFunctionOption("zoomCallback").call(that,
b0963cdb 1323 minDate, maxDate, that.yAxisRanges());
b1a3b195
DV
1324 }
1325 });
8b83c6cc
RK
1326};
1327
1328/**
1329 * Zoom to something containing [lowY, highY]. These are pixel coordinates in
d58ae307
DV
1330 * the canvas. This function redraws the graph.
1331 *
1bc88216
DV
1332 * @param {number} lowY The topmost pixel value that should be visible.
1333 * @param {number} highY The lowest pixel value that should be visible.
8b83c6cc
RK
1334 * @private
1335 */
1336Dygraph.prototype.doZoomY_ = function(lowY, highY) {
920208fb 1337 this.currentZoomRectArgs_ = null;
d58ae307
DV
1338 // Find the highest and lowest values in pixel range for each axis.
1339 // Note that lowY (in pixels) corresponds to the max Value (in data coords).
1340 // This is because pixels increase as you go down on the screen, whereas data
1341 // coordinates increase as you go up the screen.
b1a3b195
DV
1342 var oldValueRanges = this.yAxisRanges();
1343 var newValueRanges = [];
d58ae307 1344 for (var i = 0; i < this.axes_.length; i++) {
ff022deb
RK
1345 var hi = this.toDataYCoord(lowY, i);
1346 var low = this.toDataYCoord(highY, i);
b1a3b195 1347 newValueRanges.push([low, hi]);
d58ae307 1348 }
8b83c6cc 1349
57baab03 1350 this.zoomed_y_ = true;
b1a3b195
DV
1351 var that = this;
1352 this.doAnimatedZoom(null, null, oldValueRanges, newValueRanges, function() {
b0963cdb 1353 if (that.getFunctionOption("zoomCallback")) {
b1a3b195 1354 var xRange = that.xAxisRange();
4ee251cb 1355 that.getFunctionOption("zoomCallback").call(that,
b0963cdb 1356 xRange[0], xRange[1], that.yAxisRanges());
b1a3b195
DV
1357 }
1358 });
8b83c6cc
RK
1359};
1360
1361/**
5b9b2142
RK
1362 * Transition function to use in animations. Returns values between 0.0
1363 * (totally old values) and 1.0 (totally new values) for each frame.
1364 * @private
1365 */
1366Dygraph.zoomAnimationFunction = function(frame, numFrames) {
1367 var k = 1.5;
1368 return (1.0 - Math.pow(k, -frame)) / (1.0 - Math.pow(k, -numFrames));
1369};
1370
1371/**
8b83c6cc
RK
1372 * Reset the zoom to the original view coordinates. This is the same as
1373 * double-clicking on the graph.
8b83c6cc 1374 */
e4f6e11a 1375Dygraph.prototype.resetZoom = function() {
b1a3b195 1376 var dirty = false, dirtyX = false, dirtyY = false;
758a629f 1377 if (this.dateWindow_ !== null) {
d58ae307 1378 dirty = true;
b1a3b195 1379 dirtyX = true;
8b83c6cc 1380 }
d58ae307
DV
1381
1382 for (var i = 0; i < this.axes_.length; i++) {
1f6a6254 1383 if (typeof(this.axes_[i].valueWindow) !== 'undefined' && this.axes_[i].valueWindow !== null) {
d58ae307 1384 dirty = true;
b1a3b195 1385 dirtyY = true;
d58ae307 1386 }
8b83c6cc
RK
1387 }
1388
da1369a5
DV
1389 // Clear any selection, since it's likely to be drawn in the wrong place.
1390 this.clearSelection();
1391
8b83c6cc 1392 if (dirty) {
57baab03
NN
1393 this.zoomed_x_ = false;
1394 this.zoomed_y_ = false;
b1a3b195 1395
1d2021b5
K
1396 //calculate extremes to avoid lack of padding on reset.
1397 var extremes = this.xAxisExtremes();
1398 var minDate = extremes[0],
1399 maxDate = extremes[1];
b1a3b195 1400
b1a3b195 1401 // TODO(danvk): merge this block w/ the code below.
b0963cdb 1402 if (!this.getBooleanOption("animatedZooms")) {
b1a3b195 1403 this.dateWindow_ = null;
758a629f
DV
1404 for (i = 0; i < this.axes_.length; i++) {
1405 if (this.axes_[i].valueWindow !== null) {
b1a3b195
DV
1406 delete this.axes_[i].valueWindow;
1407 }
1408 }
1409 this.drawGraph_();
b0963cdb 1410 if (this.getFunctionOption("zoomCallback")) {
4ee251cb 1411 this.getFunctionOption("zoomCallback").call(this,
b0963cdb 1412 minDate, maxDate, this.yAxisRanges());
b1a3b195
DV
1413 }
1414 return;
1415 }
1416
1417 var oldWindow=null, newWindow=null, oldValueRanges=null, newValueRanges=null;
1418 if (dirtyX) {
1419 oldWindow = this.xAxisRange();
1420 newWindow = [minDate, maxDate];
1421 }
1422
1423 if (dirtyY) {
1424 oldValueRanges = this.yAxisRanges();
1425 // TODO(danvk): this is pretty inefficient
1426 var packed = this.gatherDatasets_(this.rolledSeries_, null);
30a5cfc6 1427 var extremes = packed.extremes;
b1a3b195
DV
1428
1429 // this has the side-effect of modifying this.axes_.
1430 // this doesn't make much sense in this context, but it's convenient (we
1431 // need this.axes_[*].extremeValues) and not harmful since we'll be
1432 // calling drawGraph_ shortly, which clobbers these values.
1433 this.computeYAxisRanges_(extremes);
1434
1435 newValueRanges = [];
758a629f 1436 for (i = 0; i < this.axes_.length; i++) {
1f6a6254 1437 var axis = this.axes_[i];
681a215e
DV
1438 newValueRanges.push((axis.valueRange !== null &&
1439 axis.valueRange !== undefined) ?
42a9ebb8 1440 axis.valueRange : axis.extremeRange);
b1a3b195
DV
1441 }
1442 }
1443
1444 var that = this;
1445 this.doAnimatedZoom(oldWindow, newWindow, oldValueRanges, newValueRanges,
1446 function() {
1447 that.dateWindow_ = null;
1448 for (var i = 0; i < that.axes_.length; i++) {
758a629f 1449 if (that.axes_[i].valueWindow !== null) {
b1a3b195
DV
1450 delete that.axes_[i].valueWindow;
1451 }
1452 }
b0963cdb 1453 if (that.getFunctionOption("zoomCallback")) {
4ee251cb 1454 that.getFunctionOption("zoomCallback").call(that,
b0963cdb 1455 minDate, maxDate, that.yAxisRanges());
b1a3b195
DV
1456 }
1457 });
1458 }
1459};
1460
1461/**
1462 * Combined animation logic for all zoom functions.
1463 * either the x parameters or y parameters may be null.
1464 * @private
1465 */
1466Dygraph.prototype.doAnimatedZoom = function(oldXRange, newXRange, oldYRanges, newYRanges, callback) {
b0963cdb
DV
1467 var steps = this.getBooleanOption("animatedZooms") ?
1468 Dygraph.ANIMATION_STEPS : 1;
b1a3b195
DV
1469
1470 var windows = [];
1471 var valueRanges = [];
758a629f 1472 var step, frac;
b1a3b195 1473
758a629f
DV
1474 if (oldXRange !== null && newXRange !== null) {
1475 for (step = 1; step <= steps; step++) {
1476 frac = Dygraph.zoomAnimationFunction(step, steps);
b1a3b195
DV
1477 windows[step-1] = [oldXRange[0]*(1-frac) + frac*newXRange[0],
1478 oldXRange[1]*(1-frac) + frac*newXRange[1]];
8b83c6cc 1479 }
67e650dc 1480 }
b1a3b195 1481
758a629f
DV
1482 if (oldYRanges !== null && newYRanges !== null) {
1483 for (step = 1; step <= steps; step++) {
1484 frac = Dygraph.zoomAnimationFunction(step, steps);
b1a3b195
DV
1485 var thisRange = [];
1486 for (var j = 0; j < this.axes_.length; j++) {
1487 thisRange.push([oldYRanges[j][0]*(1-frac) + frac*newYRanges[j][0],
1488 oldYRanges[j][1]*(1-frac) + frac*newYRanges[j][1]]);
1489 }
1490 valueRanges[step-1] = thisRange;
1491 }
1492 }
1493
1494 var that = this;
6ecc0739 1495 utils.repeatAndCleanup(function(step) {
b1a3b195
DV
1496 if (valueRanges.length) {
1497 for (var i = 0; i < that.axes_.length; i++) {
1498 var w = valueRanges[step][i];
1499 that.axes_[i].valueWindow = [w[0], w[1]];
1500 }
1501 }
1502 if (windows.length) {
1503 that.dateWindow_ = windows[step];
1504 }
1505 that.drawGraph_();
1506 }, steps, Dygraph.ANIMATION_DURATION / steps, callback);
6a1aa64f
DV
1507};
1508
1509/**
857a6931
KW
1510 * Get the current graph's area object.
1511 *
1512 * Returns: {x, y, w, h}
6a1aa64f 1513 */
857a6931
KW
1514Dygraph.prototype.getArea = function() {
1515 return this.plotter_.area;
1516};
e863a17d 1517
857a6931
KW
1518/**
1519 * Convert a mouse event to DOM coordinates relative to the graph origin.
1520 *
1521 * Returns a two-element array: [X, Y].
1522 */
1523Dygraph.prototype.eventToDomCoords = function(event) {
abc8c570
RK
1524 if (event.offsetX && event.offsetY) {
1525 return [ event.offsetX, event.offsetY ];
1526 } else {
6ecc0739
DV
1527 var eventElementPos = utils.findPos(this.mouseEventElement_);
1528 var canvasx = utils.pageX(event) - eventElementPos.x;
1529 var canvasy = utils.pageY(event) - eventElementPos.y;
abc8c570
RK
1530 return [canvasx, canvasy];
1531 }
857a6931 1532};
4cac8c7a 1533
857a6931
KW
1534/**
1535 * Given a canvas X coordinate, find the closest row.
1bc88216
DV
1536 * @param {number} domX graph-relative DOM X coordinate
1537 * Returns {number} row number.
857a6931
KW
1538 * @private
1539 */
1540Dygraph.prototype.findClosestRow = function(domX) {
81cb07d6 1541 var minDistX = Infinity;
a703cbdf 1542 var closestRow = -1;
a12a78ae
DV
1543 var sets = this.layout_.points;
1544 for (var i = 0; i < sets.length; i++) {
1545 var points = sets[i];
1546 var len = points.length;
1547 for (var j = 0; j < len; j++) {
1548 var point = points[j];
6ecc0739 1549 if (!utils.isValidPoint(point, true)) continue;
a12a78ae
DV
1550 var dist = Math.abs(point.canvasx - domX);
1551 if (dist < minDistX) {
1552 minDistX = dist;
a703cbdf 1553 closestRow = point.idx;
a12a78ae 1554 }
a937d031 1555 }
6a1aa64f 1556 }
a12a78ae 1557
a703cbdf 1558 return closestRow;
857a6931 1559};
6a1aa64f 1560
857a6931 1561/**
2a02e5dd
KW
1562 * Given canvas X,Y coordinates, find the closest point.
1563 *
1564 * This finds the individual data point across all visible series
1565 * that's closest to the supplied DOM coordinates using the standard
1566 * Euclidean X,Y distance.
1567 *
1bc88216
DV
1568 * @param {number} domX graph-relative DOM X coordinate
1569 * @param {number} domY graph-relative DOM Y coordinate
857a6931
KW
1570 * Returns: {row, seriesName, point}
1571 * @private
1572 */
1573Dygraph.prototype.findClosestPoint = function(domX, domY) {
81cb07d6 1574 var minDist = Infinity;
55231c07 1575 var dist, dx, dy, point, closestPoint, closestSeries, closestRow;
30a5cfc6 1576 for ( var setIdx = this.layout_.points.length - 1 ; setIdx >= 0 ; --setIdx ) {
a12a78ae
DV
1577 var points = this.layout_.points[setIdx];
1578 for (var i = 0; i < points.length; ++i) {
55231c07 1579 point = points[i];
e8c70e4e 1580 if (!utils.isValidPoint(point)) continue;
857a6931
KW
1581 dx = point.canvasx - domX;
1582 dy = point.canvasy - domY;
1583 dist = dx * dx + dy * dy;
81cb07d6 1584 if (dist < minDist) {
62c3d2fd 1585 minDist = dist;
a937d031
KW
1586 closestPoint = point;
1587 closestSeries = setIdx;
55231c07 1588 closestRow = point.idx;
a937d031 1589 }
857a6931
KW
1590 }
1591 }
1592 var name = this.layout_.setNames[closestSeries];
1593 return {
55231c07 1594 row: closestRow,
857a6931
KW
1595 seriesName: name,
1596 point: closestPoint
1597 };
1598};
1599
1600/**
1601 * Given canvas X,Y coordinates, find the touched area in a stacked graph.
2a02e5dd
KW
1602 *
1603 * This first finds the X data point closest to the supplied DOM X coordinate,
1604 * then finds the series which puts the Y coordinate on top of its filled area,
1605 * using linear interpolation between adjacent point pairs.
1606 *
1bc88216
DV
1607 * @param {number} domX graph-relative DOM X coordinate
1608 * @param {number} domY graph-relative DOM Y coordinate
857a6931
KW
1609 * Returns: {row, seriesName, point}
1610 * @private
1611 */
1612Dygraph.prototype.findStackedPoint = function(domX, domY) {
1613 var row = this.findClosestRow(domX);
857a6931 1614 var closestPoint, closestSeries;
30a5cfc6 1615 for (var setIdx = 0; setIdx < this.layout_.points.length; ++setIdx) {
55231c07
DE
1616 var boundary = this.getLeftBoundary_(setIdx);
1617 var rowIdx = row - boundary;
a12a78ae
DV
1618 var points = this.layout_.points[setIdx];
1619 if (rowIdx >= points.length) continue;
1620 var p1 = points[rowIdx];
e8c70e4e 1621 if (!utils.isValidPoint(p1)) continue;
857a6931 1622 var py = p1.canvasy;
a12a78ae 1623 if (domX > p1.canvasx && rowIdx + 1 < points.length) {
857a6931 1624 // interpolate series Y value using next point
a12a78ae 1625 var p2 = points[rowIdx + 1];
e8c70e4e 1626 if (utils.isValidPoint(p2)) {
62c3d2fd
KW
1627 var dx = p2.canvasx - p1.canvasx;
1628 if (dx > 0) {
1629 var r = (domX - p1.canvasx) / dx;
1630 py += r * (p2.canvasy - p1.canvasy);
1631 }
416b05ad 1632 }
81cb07d6 1633 } else if (domX < p1.canvasx && rowIdx > 0) {
857a6931 1634 // interpolate series Y value using previous point
a12a78ae 1635 var p0 = points[rowIdx - 1];
e8c70e4e 1636 if (utils.isValidPoint(p0)) {
62c3d2fd
KW
1637 var dx = p1.canvasx - p0.canvasx;
1638 if (dx > 0) {
1639 var r = (p1.canvasx - domX) / dx;
1640 py += r * (p0.canvasy - p1.canvasy);
1641 }
12e4c741 1642 }
6a1aa64f 1643 }
857a6931 1644 // Stop if the point (domX, py) is above this series' upper edge
42a9ebb8 1645 if (setIdx === 0 || py < domY) {
a937d031
KW
1646 closestPoint = p1;
1647 closestSeries = setIdx;
1648 }
6a1aa64f 1649 }
857a6931
KW
1650 var name = this.layout_.setNames[closestSeries];
1651 return {
1652 row: row,
1653 seriesName: name,
1654 point: closestPoint
1655 };
1656};
6a1aa64f 1657
857a6931 1658/**
6a1aa64f
DV
1659 * When the mouse moves in the canvas, display information about a nearby data
1660 * point and draw dots over those points in the data series. This function
1661 * takes care of cleanup of previously-drawn dots.
1662 * @param {Object} event The mousemove event from the browser.
1663 * @private
1664 */
285a6bda 1665Dygraph.prototype.mouseMove_ = function(event) {
e863a17d 1666 // This prevents JS errors when mousing over the canvas before data loads.
4cac8c7a 1667 var points = this.layout_.points;
a12a78ae 1668 if (points === undefined || points === null) return;
e863a17d 1669
857a6931
KW
1670 var canvasCoords = this.eventToDomCoords(event);
1671 var canvasx = canvasCoords[0];
1672 var canvasy = canvasCoords[1];
6a1aa64f 1673
b0963cdb 1674 var highlightSeriesOpts = this.getOption("highlightSeriesOpts");
857a6931 1675 var selectionChanged = false;
3f55b813 1676 if (highlightSeriesOpts && !this.isSeriesLocked()) {
857a6931 1677 var closest;
b0963cdb 1678 if (this.getBooleanOption("stackedGraph")) {
857a6931
KW
1679 closest = this.findStackedPoint(canvasx, canvasy);
1680 } else {
1681 closest = this.findClosestPoint(canvasx, canvasy);
43af96e7 1682 }
857a6931 1683 selectionChanged = this.setSelection(closest.row, closest.seriesName);
416b05ad 1684 } else {
857a6931
KW
1685 var idx = this.findClosestRow(canvasx);
1686 selectionChanged = this.setSelection(idx);
12e4c741 1687 }
43af96e7 1688
b0963cdb 1689 var callback = this.getFunctionOption("highlightCallback");
857a6931 1690 if (callback && selectionChanged) {
4ee251cb 1691 callback.call(this, event,
870a309c
DV
1692 this.lastx_,
1693 this.selPoints_,
55231c07 1694 this.lastRow_,
870a309c 1695 this.highlightSet_);
12e4c741 1696 }
239c712d 1697};
b258a3da 1698
239c712d 1699/**
b77d7a56 1700 * Fetch left offset from the specified set index or if not passed, the
55231c07 1701 * first defined boundaryIds record (see bug #236).
e2c21500 1702 * @private
81cb07d6 1703 */
55231c07 1704Dygraph.prototype.getLeftBoundary_ = function(setIdx) {
383d8473 1705 if (this.boundaryIds_[setIdx]) {
a703cbdf 1706 return this.boundaryIds_[setIdx][0];
55231c07
DE
1707 } else {
1708 for (var i = 0; i < this.boundaryIds_.length; i++) {
1709 if (this.boundaryIds_[i] !== undefined) {
1710 return this.boundaryIds_[i][0];
1711 }
81cb07d6 1712 }
55231c07 1713 return 0;
81cb07d6 1714 }
81cb07d6
KW
1715};
1716
857a6931
KW
1717Dygraph.prototype.animateSelection_ = function(direction) {
1718 var totalSteps = 10;
1719 var millis = 30;
1d44ee5e
KW
1720 if (this.fadeLevel === undefined) this.fadeLevel = 0;
1721 if (this.animateId === undefined) this.animateId = 0;
857a6931
KW
1722 var start = this.fadeLevel;
1723 var steps = direction < 0 ? start : totalSteps - start;
1724 if (steps <= 0) {
1725 if (this.fadeLevel) {
1726 this.updateSelection_(1.0);
1727 }
1728 return;
1729 }
1730
1731 var thisId = ++this.animateId;
1732 var that = this;
fb2b89c8
MB
1733 var cleanupIfClearing = function() {
1734 // if we haven't reached fadeLevel 0 in the max frame time,
1735 // ensure that the clear happens and just go to 0
1736 if (that.fadeLevel !== 0 && direction < 0) {
1737 that.fadeLevel = 0;
1738 that.clearSelection();
1739 }
1740 };
6ecc0739 1741 utils.repeatAndCleanup(
475f7420
KW
1742 function(n) {
1743 // ignore simultaneous animations
1744 if (that.animateId != thisId) return;
1745
1746 that.fadeLevel += direction;
1747 if (that.fadeLevel === 0) {
1748 that.clearSelection();
1749 } else {
1750 that.updateSelection_(that.fadeLevel / totalSteps);
1751 }
1752 },
fb2b89c8 1753 steps, millis, cleanupIfClearing);
857a6931
KW
1754};
1755
2ddb1197 1756/**
239c712d
NAG
1757 * Draw dots over the selectied points in the data series. This function
1758 * takes care of cleanup of previously-drawn dots.
1759 * @private
1760 */
857a6931 1761Dygraph.prototype.updateSelection_ = function(opt_animFraction) {
0cd1ad15
DV
1762 /*var defaultPrevented = */
1763 this.cascadeEvents_('select', {
54f4c379 1764 selectedRow: this.lastRow_,
e2c21500
DV
1765 selectedX: this.lastx_,
1766 selectedPoints: this.selPoints_
1767 });
1768 // TODO(danvk): use defaultPrevented here?
1769
6a1aa64f 1770 // Clear the previously drawn vertical, if there is one
758a629f 1771 var i;
2cf95fff 1772 var ctx = this.canvas_ctx_;
b0963cdb 1773 if (this.getOption('highlightSeriesOpts')) {
857a6931 1774 ctx.clearRect(0, 0, this.width_, this.height_);
b0963cdb 1775 var alpha = 1.0 - this.getNumericOption('highlightSeriesBackgroundAlpha');
857a6931 1776 if (alpha) {
2a02e5dd
KW
1777 // Activating background fade includes an animation effect for a gradual
1778 // fade. TODO(klausw): make this independently configurable if it causes
1779 // issues? Use a shared preference to control animations?
1780 var animateBackgroundFade = true;
1781 if (animateBackgroundFade) {
857a6931
KW
1782 if (opt_animFraction === undefined) {
1783 // start a new animation
1784 this.animateSelection_(1);
1785 return;
1786 }
1787 alpha *= opt_animFraction;
1788 }
1789 ctx.fillStyle = 'rgba(255,255,255,' + alpha + ')';
1790 ctx.fillRect(0, 0, this.width_, this.height_);
1791 }
38e3d209
DV
1792
1793 // Redraw only the highlighted series in the interactive canvas (not the
1794 // static plot canvas, which is where series are usually drawn).
1795 this.plotter_._renderLineChart(this.highlightSet_, ctx);
857a6931 1796 } else if (this.previousVerticalX_ >= 0) {
46dde5f9
DV
1797 // Determine the maximum highlight circle size.
1798 var maxCircleSize = 0;
227b93cc 1799 var labels = this.attr_('labels');
758a629f 1800 for (i = 1; i < labels.length; i++) {
b0963cdb 1801 var r = this.getNumericOption('highlightCircleSize', labels[i]);
46dde5f9
DV
1802 if (r > maxCircleSize) maxCircleSize = r;
1803 }
6a1aa64f 1804 var px = this.previousVerticalX_;
46dde5f9
DV
1805 ctx.clearRect(px - maxCircleSize - 1, 0,
1806 2 * maxCircleSize + 2, this.height_);
6a1aa64f
DV
1807 }
1808
d160cc3b 1809 if (this.selPoints_.length > 0) {
6a1aa64f 1810 // Draw colored circles over the center of each selected point
e9fe4a2f 1811 var canvasx = this.selPoints_[0].canvasx;
43af96e7 1812 ctx.save();
758a629f 1813 for (i = 0; i < this.selPoints_.length; i++) {
e9fe4a2f 1814 var pt = this.selPoints_[i];
6ecc0739 1815 if (!utils.isOK(pt.canvasy)) continue;
e9fe4a2f 1816
b0963cdb
DV
1817 var circleSize = this.getNumericOption('highlightCircleSize', pt.name);
1818 var callback = this.getFunctionOption("drawHighlightPointCallback", pt.name);
a8ef67a8 1819 var color = this.plotter_.colors[pt.name];
78e58af4 1820 if (!callback) {
6ecc0739 1821 callback = utils.Circles.DEFAULT;
78e58af4 1822 }
b0963cdb 1823 ctx.lineWidth = this.getNumericOption('strokeWidth', pt.name);
a8ef67a8
KW
1824 ctx.strokeStyle = color;
1825 ctx.fillStyle = color;
4ee251cb 1826 callback.call(this, this, pt.name, ctx, canvasx, pt.canvasy,
ba697462 1827 color, circleSize, pt.idx);
6a1aa64f
DV
1828 }
1829 ctx.restore();
1830
1831 this.previousVerticalX_ = canvasx;
1832 }
1833};
1834
1835/**
629a09ae
DV
1836 * Manually set the selected points and display information about them in the
1837 * legend. The selection can be cleared using clearSelection() and queried
1838 * using getSelection().
1bc88216 1839 * @param {number} row Row number that should be highlighted (i.e. appear with
8cadc6c9 1840 * hover dots on the chart).
1bc88216 1841 * @param {seriesName} optional series name to highlight that series with the
857a6931 1842 * the highlightSeriesOpts setting.
b9a3ece4
KW
1843 * @param { locked } optional If true, keep seriesName selected when mousing
1844 * over the graph, disabling closest-series highlighting. Call clearSelection()
1845 * to unlock it.
239c712d 1846 */
b9a3ece4 1847Dygraph.prototype.setSelection = function(row, opt_seriesName, opt_locked) {
239c712d
NAG
1848 // Extract the points we've selected
1849 this.selPoints_ = [];
50360fd0 1850
857a6931 1851 var changed = false;
16269f6e 1852 if (row !== false && row >= 0) {
857a6931
KW
1853 if (row != this.lastRow_) changed = true;
1854 this.lastRow_ = row;
30a5cfc6
KW
1855 for (var setIdx = 0; setIdx < this.layout_.points.length; ++setIdx) {
1856 var points = this.layout_.points[setIdx];
8b7f7651
AV
1857 // Check if the point at the appropriate index is the point we're looking
1858 // for. If it is, just use it, otherwise search the array for a point
1859 // in the proper place.
1860 var setRow = row - this.getLeftBoundary_(setIdx);
1861 if (setRow < points.length && points[setRow].idx == row) {
1862 var point = points[setRow];
1863 if (point.yval !== null) this.selPoints_.push(point);
1864 } else {
1865 for (var pointIdx = 0; pointIdx < points.length; ++pointIdx) {
1866 var point = points[pointIdx];
1867 if (point.idx == row) {
1868 if (point.yval !== null) {
1869 this.selPoints_.push(point);
1870 }
1871 break;
ad7785b8 1872 }
ad7785b8 1873 }
16269f6e 1874 }
239c712d 1875 }
857a6931
KW
1876 } else {
1877 if (this.lastRow_ >= 0) changed = true;
1878 this.lastRow_ = -1;
16269f6e 1879 }
50360fd0 1880
16269f6e 1881 if (this.selPoints_.length) {
239c712d 1882 this.lastx_ = this.selPoints_[0].xval;
239c712d 1883 } else {
857a6931 1884 this.lastx_ = -1;
239c712d
NAG
1885 }
1886
857a6931
KW
1887 if (opt_seriesName !== undefined) {
1888 if (this.highlightSet_ !== opt_seriesName) changed = true;
1889 this.highlightSet_ = opt_seriesName;
239c712d
NAG
1890 }
1891
b9a3ece4
KW
1892 if (opt_locked !== undefined) {
1893 this.lockedSet_ = opt_locked;
1894 }
1895
857a6931
KW
1896 if (changed) {
1897 this.updateSelection_(undefined);
1898 }
1899 return changed;
239c712d
NAG
1900};
1901
1902/**
6a1aa64f
DV
1903 * The mouse has left the canvas. Clear out whatever artifacts remain
1904 * @param {Object} event the mouseout event from the browser.
1905 * @private
1906 */
285a6bda 1907Dygraph.prototype.mouseOut_ = function(event) {
b0963cdb 1908 if (this.getFunctionOption("unhighlightCallback")) {
4ee251cb 1909 this.getFunctionOption("unhighlightCallback").call(this, event);
a4c6a67c
AV
1910 }
1911
4ee251cb 1912 if (this.getBooleanOption("hideOverlayOnMouseOut") && !this.lockedSet_) {
239c712d 1913 this.clearSelection();
43af96e7 1914 }
6a1aa64f
DV
1915};
1916
239c712d 1917/**
629a09ae
DV
1918 * Clears the current selection (i.e. points that were highlighted by moving
1919 * the mouse over the chart).
239c712d
NAG
1920 */
1921Dygraph.prototype.clearSelection = function() {
e2c21500
DV
1922 this.cascadeEvents_('deselect', {});
1923
b9a3ece4 1924 this.lockedSet_ = false;
239c712d 1925 // Get rid of the overlay data
857a6931
KW
1926 if (this.fadeLevel) {
1927 this.animateSelection_(-1);
1928 return;
1929 }
2cf95fff 1930 this.canvas_ctx_.clearRect(0, 0, this.width_, this.height_);
857a6931 1931 this.fadeLevel = 0;
239c712d
NAG
1932 this.selPoints_ = [];
1933 this.lastx_ = -1;
857a6931
KW
1934 this.lastRow_ = -1;
1935 this.highlightSet_ = null;
758a629f 1936};
239c712d 1937
103b7292 1938/**
629a09ae
DV
1939 * Returns the number of the currently selected row. To get data for this row,
1940 * you can use the getValue method.
1bc88216 1941 * @return {number} row number, or -1 if nothing is selected
103b7292
NAG
1942 */
1943Dygraph.prototype.getSelection = function() {
1944 if (!this.selPoints_ || this.selPoints_.length < 1) {
1945 return -1;
1946 }
50360fd0 1947
a12a78ae
DV
1948 for (var setIdx = 0; setIdx < this.layout_.points.length; setIdx++) {
1949 var points = this.layout_.points[setIdx];
1950 for (var row = 0; row < points.length; row++) {
1951 if (points[row].x == this.selPoints_[0].x) {
55231c07 1952 return points[row].idx;
a12a78ae 1953 }
103b7292
NAG
1954 }
1955 }
1956 return -1;
2e1fcf1a 1957};
103b7292 1958
e2c21500
DV
1959/**
1960 * Returns the name of the currently-highlighted series.
1961 * Only available when the highlightSeriesOpts option is in use.
1962 */
857a6931
KW
1963Dygraph.prototype.getHighlightSeries = function() {
1964 return this.highlightSet_;
1965};
1966
19589a3e 1967/**
3f55b813
KW
1968 * Returns true if the currently-highlighted series was locked
1969 * via setSelection(..., seriesName, true).
1970 */
1971Dygraph.prototype.isSeriesLocked = function() {
1972 return this.lockedSet_;
1973};
1974
1975/**
6a1aa64f 1976 * Fires when there's data available to be graphed.
1bc88216 1977 * @param {string} data Raw CSV data to be plotted
6a1aa64f
DV
1978 * @private
1979 */
285a6bda 1980Dygraph.prototype.loadedEvent_ = function(data) {
6a1aa64f 1981 this.rawData_ = this.parseCSV_(data);
6f5f0b2b 1982 this.cascadeDataDidUpdateEvent_();
26ca7938 1983 this.predraw_();
6a1aa64f
DV
1984};
1985
6a1aa64f
DV
1986/**
1987 * Add ticks on the x-axis representing years, months, quarters, weeks, or days
1988 * @private
1989 */
285a6bda 1990Dygraph.prototype.addXTicks_ = function() {
6a1aa64f 1991 // Determine the correct ticks scale on the x-axis: quarterly, monthly, ...
7201b11e 1992 var range;
6a1aa64f 1993 if (this.dateWindow_) {
7201b11e 1994 range = [this.dateWindow_[0], this.dateWindow_[1]];
6a1aa64f 1995 } else {
ccecde93 1996 range = this.xAxisExtremes();
7201b11e
JB
1997 }
1998
48e614ac
DV
1999 var xAxisOptionsView = this.optionsViewForAxis_('x');
2000 var xTicks = xAxisOptionsView('ticker')(
2001 range[0],
2002 range[1],
b504bdd2 2003 this.plotter_.area.w, // TODO(danvk): should be area.width
48e614ac
DV
2004 xAxisOptionsView,
2005 this);
2006 // var msg = 'ticker(' + range[0] + ', ' + range[1] + ', ' + this.width_ + ', ' + this.attr_('pixelsPerXLabel') + ') -> ' + JSON.stringify(xTicks);
2007 // console.log(msg);
b2c9222a 2008 this.layout_.setXTicks(xTicks);
32988383
DV
2009};
2010
629a09ae 2011/**
3ea41d86 2012 * Returns the correct handler class for the currently set options.
629a09ae 2013 * @private
3ea41d86
DV
2014 */
2015Dygraph.prototype.getHandlerClass_ = function() {
2016 var handlerClass;
2017 if (this.attr_('dataHandler')) {
2018 handlerClass = this.attr_('dataHandler');
2019 } else if (this.fractions_) {
b0963cdb 2020 if (this.getBooleanOption('errorBars')) {
e8c70e4e 2021 handlerClass = FractionsBarsHandler;
a49c164a 2022 } else {
e8c70e4e 2023 handlerClass = DefaultFractionHandler;
5011e7a1 2024 }
b0963cdb 2025 } else if (this.getBooleanOption('customBars')) {
e8c70e4e 2026 handlerClass = CustomBarsHandler;
b0963cdb 2027 } else if (this.getBooleanOption('errorBars')) {
e8c70e4e 2028 handlerClass = ErrorBarsHandler;
5011e7a1 2029 } else {
6ecc0739 2030 handlerClass = DefaultHandler;
5011e7a1 2031 }
3ea41d86 2032 return handlerClass;
5011e7a1
DV
2033};
2034
6a1aa64f 2035/**
629a09ae 2036 * @private
26ca7938
DV
2037 * This function is called once when the chart's data is changed or the options
2038 * dictionary is updated. It is _not_ called when the user pans or zooms. The
2039 * idea is that values derived from the chart's data can be computed here,
2040 * rather than every time the chart is drawn. This includes things like the
2041 * number of axes, rolling averages, etc.
2042 */
2043Dygraph.prototype.predraw_ = function() {
7153e001 2044 var start = new Date();
b77d7a56 2045
a49c164a 2046 // Create the correct dataHandler
3ea41d86 2047 this.dataHandler_ = new (this.getHandlerClass_())();
7153e001 2048
0d216a60
PF
2049 this.layout_.computePlotArea();
2050
26ca7938
DV
2051 // TODO(danvk): move more computations out of drawGraph_ and into here.
2052 this.computeYAxes_();
2053
383d8473 2054 if (!this.is_initial_draw_) {
aeca29ac
RK
2055 this.canvas_ctx_.restore();
2056 this.hidden_ctx_.restore();
2057 }
2058
2059 this.canvas_ctx_.save();
2060 this.hidden_ctx_.save();
2061
c04c8044 2062 // Create a new plotter.
26ca7938 2063 this.plotter_ = new DygraphCanvasRenderer(this,
2cf95fff
RK
2064 this.hidden_,
2065 this.hidden_ctx_,
0e23cfc6 2066 this.layout_);
26ca7938 2067
0abfbd7e
DV
2068 // The roller sits in the bottom left corner of the chart. We don't know where
2069 // this will be until the options are available, so it's positioned here.
8c69de65 2070 this.createRollInterface_();
26ca7938 2071
e2c21500 2072 this.cascadeEvents_('predraw');
0abfbd7e 2073
b1a3b195
DV
2074 // Convert the raw data (a 2D array) into the internal format and compute
2075 // rolling averages.
2076 this.rolledSeries_ = [null]; // x-axis is the first series and it's special
395e98a3 2077 for (var i = 1; i < this.numColumns(); i++) {
c1780ad0 2078 // var logScale = this.attr_('logscale', i); // TODO(klausw): this looks wrong // konigsberg thinks so too.
a49c164a
DE
2079 var series = this.dataHandler_.extractSeries(this.rawData_, i, this.attributes_);
2080 if (this.rollPeriod_ > 1) {
2081 series = this.dataHandler_.rollingAverage(series, this.rollPeriod_, this.attributes_);
2082 }
b77d7a56 2083
b1a3b195
DV
2084 this.rolledSeries_.push(series);
2085 }
2086
26ca7938
DV
2087 // If the data or options have changed, then we'd better redraw.
2088 this.drawGraph_();
4b4d1a63
DV
2089
2090 // This is used to determine whether to do various animations.
2091 var end = new Date();
2092 this.drawingTimeMs_ = (end - start);
26ca7938
DV
2093};
2094
2095/**
30a5cfc6
KW
2096 * Point structure.
2097 *
2098 * xval_* and yval_* are the original unscaled data values,
2099 * while x_* and y_* are scaled to the range (0.0-1.0) for plotting.
2100 * yval_stacked is the cumulative Y value used for stacking graphs,
2101 * and bottom/top/minus/plus are used for error bar graphs.
2102 *
2103 * @typedef {{
2104 * idx: number,
2105 * name: string,
2106 * x: ?number,
2107 * xval: ?number,
2108 * y_bottom: ?number,
2109 * y: ?number,
2110 * y_stacked: ?number,
2111 * y_top: ?number,
2112 * yval_minus: ?number,
2113 * yval: ?number,
2114 * yval_plus: ?number,
2115 * yval_stacked
2116 * }}
2117 */
bcc53a77 2118Dygraph.PointType = undefined;
30a5cfc6 2119
30a5cfc6
KW
2120/**
2121 * Calculates point stacking for stackedGraph=true.
2122 *
2123 * For stacking purposes, interpolate or extend neighboring data across
2124 * NaN values based on stackedGraphNaNFill settings. This is for display
2125 * only, the underlying data value as shown in the legend remains NaN.
2126 *
2127 * @param {Array.<Dygraph.PointType>} points Point array for a single series.
2128 * Updates each Point's yval_stacked property.
2129 * @param {Array.<number>} cumulativeYval Accumulated top-of-graph stacked Y
2130 * values for the series seen so far. Index is the row number. Updated
2131 * based on the current series's values.
2132 * @param {Array.<number>} seriesExtremes Min and max values, updated
2133 * to reflect the stacked values.
2134 * @param {string} fillMethod Interpolation method, one of 'all', 'inside', or
2135 * 'none'.
24f2a74f 2136 * @private
30a5cfc6
KW
2137 */
2138Dygraph.stackPoints_ = function(
2139 points, cumulativeYval, seriesExtremes, fillMethod) {
2140 var lastXval = null;
2141 var prevPoint = null;
2142 var nextPoint = null;
2143 var nextPointIdx = -1;
2144
2145 // Find the next stackable point starting from the given index.
bcc53a77 2146 var updateNextPoint = function(idx) {
30a5cfc6
KW
2147 // If we've previously found a non-NaN point and haven't gone past it yet,
2148 // just use that.
2149 if (nextPointIdx >= idx) return;
2150
2151 // We haven't found a non-NaN point yet or have moved past it,
2152 // look towards the right to find a non-NaN point.
2153 for (var j = idx; j < points.length; ++j) {
2154 // Clear out a previously-found point (if any) since it's no longer
2155 // valid, we shouldn't use it for interpolation anymore.
2156 nextPoint = null;
2157 if (!isNaN(points[j].yval) && points[j].yval !== null) {
2158 nextPointIdx = j;
2159 nextPoint = points[j];
2160 break;
2161 }
2162 }
2163 };
2164
2165 for (var i = 0; i < points.length; ++i) {
2166 var point = points[i];
2167 var xval = point.xval;
2168 if (cumulativeYval[xval] === undefined) {
2169 cumulativeYval[xval] = 0;
2170 }
2171
2172 var actualYval = point.yval;
2173 if (isNaN(actualYval) || actualYval === null) {
06c0e1ee 2174 if(fillMethod == 'none') {
30a5cfc6 2175 actualYval = 0;
d68137fd 2176 } else {
06c0e1ee
S
2177 // Interpolate/extend for stacking purposes if possible.
2178 updateNextPoint(i);
2179 if (prevPoint && nextPoint && fillMethod != 'none') {
2180 // Use linear interpolation between prevPoint and nextPoint.
2181 actualYval = prevPoint.yval + (nextPoint.yval - prevPoint.yval) *
2182 ((xval - prevPoint.xval) / (nextPoint.xval - prevPoint.xval));
2183 } else if (prevPoint && fillMethod == 'all') {
2184 actualYval = prevPoint.yval;
2185 } else if (nextPoint && fillMethod == 'all') {
2186 actualYval = nextPoint.yval;
2187 } else {
2188 actualYval = 0;
2189 }
30a5cfc6
KW
2190 }
2191 } else {
2192 prevPoint = point;
2193 }
2194
2195 var stackedYval = cumulativeYval[xval];
2196 if (lastXval != xval) {
2197 // If an x-value is repeated, we ignore the duplicates.
2198 stackedYval += actualYval;
2199 cumulativeYval[xval] = stackedYval;
2200 }
2201 lastXval = xval;
2202
2203 point.yval_stacked = stackedYval;
2204
2205 if (stackedYval > seriesExtremes[1]) {
2206 seriesExtremes[1] = stackedYval;
2207 }
2208 if (stackedYval < seriesExtremes[0]) {
2209 seriesExtremes[0] = stackedYval;
2210 }
2211 }
2212};
2213
2214
2215/**
b1a3b195
DV
2216 * Loop over all fields and create datasets, calculating extreme y-values for
2217 * each series and extreme x-indices as we go.
fc4e84fa 2218 *
b1a3b195
DV
2219 * dateWindow is passed in as an explicit parameter so that we can compute
2220 * extreme values "speculatively", i.e. without actually setting state on the
2221 * dygraph.
fc4e84fa 2222 *
30a5cfc6
KW
2223 * @param {Array.<Array.<Array.<(number|Array<number>)>>} rolledSeries, where
2224 * rolledSeries[seriesIndex][row] = raw point, where
2225 * seriesIndex is the column number starting with 1, and
2226 * rawPoint is [x,y] or [x, [y, err]] or [x, [y, yminus, yplus]].
2227 * @param {?Array.<number>} dateWindow [xmin, xmax] pair, or null.
2228 * @return {{
2229 * points: Array.<Array.<Dygraph.PointType>>,
2230 * seriesExtremes: Array.<Array.<number>>,
2231 * boundaryIds: Array.<number>}}
6a1aa64f
DV
2232 * @private
2233 */
b1a3b195
DV
2234Dygraph.prototype.gatherDatasets_ = function(rolledSeries, dateWindow) {
2235 var boundaryIds = [];
30a5cfc6
KW
2236 var points = [];
2237 var cumulativeYval = []; // For stacked series.
f09fc545 2238 var extremes = {}; // series name -> [low, high]
a49c164a
DE
2239 var seriesIdx, sampleIdx;
2240 var firstIdx, lastIdx;
8b5f1691 2241 var axisIdx;
b77d7a56 2242
b1a3b195
DV
2243 // Loop over the fields (series). Go from the last to the first,
2244 // because if they're stacked that's how we accumulate the values.
2245 var num_series = rolledSeries.length - 1;
bcc53a77 2246 var series;
a49c164a
DE
2247 for (seriesIdx = num_series; seriesIdx >= 1; seriesIdx--) {
2248 if (!this.visibility()[seriesIdx - 1]) continue;
1cf11047 2249
6a1aa64f 2250 // Prune down to the desired range, if necessary (for zooming)
1a26f3fb
DV
2251 // Because there can be lines going to points outside of the visible area,
2252 // we actually prune to visible points, plus one on either side.
b1a3b195 2253 if (dateWindow) {
a49c164a 2254 series = rolledSeries[seriesIdx];
b1a3b195
DV
2255 var low = dateWindow[0];
2256 var high = dateWindow[1];
4e59e63e 2257
1a26f3fb
DV
2258 // TODO(danvk): do binary search instead of linear search.
2259 // TODO(danvk): pass firstIdx and lastIdx directly to the renderer.
b77d7a56 2260 firstIdx = null;
a49c164a
DE
2261 lastIdx = null;
2262 for (sampleIdx = 0; sampleIdx < series.length; sampleIdx++) {
2263 if (series[sampleIdx][0] >= low && firstIdx === null) {
2264 firstIdx = sampleIdx;
1a26f3fb 2265 }
a49c164a
DE
2266 if (series[sampleIdx][0] <= high) {
2267 lastIdx = sampleIdx;
6a1aa64f
DV
2268 }
2269 }
4e59e63e 2270
1a26f3fb 2271 if (firstIdx === null) firstIdx = 0;
14ac984e 2272 var correctedFirstIdx = firstIdx;
b0375a28 2273 var isInvalidValue = true;
4e59e63e 2274 while (isInvalidValue && correctedFirstIdx > 0) {
14ac984e 2275 correctedFirstIdx--;
a49c164a
DE
2276 // check if the y value is null.
2277 isInvalidValue = series[correctedFirstIdx][1] === null;
14ac984e 2278 }
4e59e63e 2279
1a26f3fb 2280 if (lastIdx === null) lastIdx = series.length - 1;
14ac984e 2281 var correctedLastIdx = lastIdx;
b0375a28 2282 isInvalidValue = true;
4e59e63e 2283 while (isInvalidValue && correctedLastIdx < series.length - 1) {
14ac984e 2284 correctedLastIdx++;
a49c164a 2285 isInvalidValue = series[correctedLastIdx][1] === null;
14ac984e 2286 }
4e59e63e 2287
4e59e63e 2288 if (correctedFirstIdx!==firstIdx) {
30a5cfc6 2289 firstIdx = correctedFirstIdx;
6a1aa64f 2290 }
4e59e63e 2291 if (correctedLastIdx !== lastIdx) {
30a5cfc6 2292 lastIdx = correctedLastIdx;
4e59e63e 2293 }
b77d7a56 2294
a49c164a 2295 boundaryIds[seriesIdx-1] = [firstIdx, lastIdx];
b77d7a56 2296
30a5cfc6
KW
2297 // .slice's end is exclusive, we want to include lastIdx.
2298 series = series.slice(firstIdx, lastIdx + 1);
16269f6e 2299 } else {
a49c164a
DE
2300 series = rolledSeries[seriesIdx];
2301 boundaryIds[seriesIdx-1] = [0, series.length-1];
6a1aa64f
DV
2302 }
2303
a49c164a 2304 var seriesName = this.attr_("labels")[seriesIdx];
b77d7a56 2305 var seriesExtremes = this.dataHandler_.getExtremeYValues(series,
b0963cdb 2306 dateWindow, this.getBooleanOption("stepPlot",seriesName));
5011e7a1 2307
b77d7a56 2308 var seriesPoints = this.dataHandler_.seriesToPoints(series,
a49c164a 2309 seriesName, boundaryIds[seriesIdx-1][0]);
43af96e7 2310
b0963cdb 2311 if (this.getBooleanOption("stackedGraph")) {
8b5f1691
JJS
2312 axisIdx = this.attributes_.axisForSeries(seriesName);
2313 if (cumulativeYval[axisIdx] === undefined) {
2314 cumulativeYval[axisIdx] = [];
2315 }
2316 Dygraph.stackPoints_(seriesPoints, cumulativeYval[axisIdx], seriesExtremes,
b0963cdb 2317 this.getBooleanOption("stackedGraphNaNFill"));
6a1aa64f 2318 }
354e15ab 2319
b1a3b195 2320 extremes[seriesName] = seriesExtremes;
a49c164a 2321 points[seriesIdx] = seriesPoints;
7d463f49
KW
2322 }
2323
30a5cfc6 2324 return { points: points, extremes: extremes, boundaryIds: boundaryIds };
b1a3b195
DV
2325};
2326
2327/**
2328 * Update the graph with new data. This method is called when the viewing area
2329 * has changed. If the underlying data or options have changed, predraw_ will
2330 * be called before drawGraph_ is called.
2331 *
b1a3b195
DV
2332 * @private
2333 */
e2c21500 2334Dygraph.prototype.drawGraph_ = function() {
b1a3b195
DV
2335 var start = new Date();
2336
b1a3b195
DV
2337 // This is used to set the second parameter to drawCallback, below.
2338 var is_initial_draw = this.is_initial_draw_;
2339 this.is_initial_draw_ = false;
2340
b1a3b195
DV
2341 this.layout_.removeAllDatasets();
2342 this.setColors_();
b0963cdb 2343 this.attrs_.pointSize = 0.5 * this.getNumericOption('highlightCircleSize');
b1a3b195
DV
2344
2345 var packed = this.gatherDatasets_(this.rolledSeries_, this.dateWindow_);
30a5cfc6
KW
2346 var points = packed.points;
2347 var extremes = packed.extremes;
2348 this.boundaryIds_ = packed.boundaryIds;
b1a3b195 2349
82c6fe4d
KW
2350 this.setIndexByName_ = {};
2351 var labels = this.attr_("labels");
2352 if (labels.length > 0) {
2353 this.setIndexByName_[labels[0]] = 0;
2354 }
857a6931 2355 var dataIdx = 0;
30a5cfc6 2356 for (var i = 1; i < points.length; i++) {
82c6fe4d 2357 this.setIndexByName_[labels[i]] = i;
4523c1f6 2358 if (!this.visibility()[i - 1]) continue;
30a5cfc6 2359 this.layout_.addDataset(labels[i], points[i]);
857a6931 2360 this.datasetIndex_[i] = dataIdx++;
43af96e7
NK
2361 }
2362
6faebb69 2363 this.computeYAxisRanges_(extremes);
b2c9222a
DV
2364 this.layout_.setYAxes(this.axes_);
2365
6a1aa64f
DV
2366 this.addXTicks_();
2367
b2c9222a 2368 // Save the X axis zoomed status as the updateOptions call will tend to set it erroneously
81856f70 2369 var tmp_zoomed_x = this.zoomed_x_;
6a1aa64f 2370 // Tell PlotKit to use this new data and render itself
81856f70 2371 this.zoomed_x_ = tmp_zoomed_x;
30a5cfc6 2372 this.layout_.evaluate();
e2c21500 2373 this.renderGraph_(is_initial_draw);
9ca829f2 2374
b0963cdb 2375 if (this.getStringOption("timingName")) {
9ca829f2 2376 var end = new Date();
8a68db7d 2377 console.log(this.getStringOption("timingName") + " - drawGraph: " + (end - start) + "ms");
9ca829f2
DV
2378 }
2379};
2380
e2c21500
DV
2381/**
2382 * This does the work of drawing the chart. It assumes that the layout and axis
2383 * scales have already been set (e.g. by predraw_).
2384 *
2385 * @private
2386 */
2387Dygraph.prototype.renderGraph_ = function(is_initial_draw) {
1748a51c 2388 this.cascadeEvents_('clearChart');
6a1aa64f 2389 this.plotter_.clear();
f417e3d3 2390
b0963cdb 2391 if (this.getFunctionOption('underlayCallback')) {
98eb4713
DV
2392 // NOTE: we pass the dygraph object to this callback twice to avoid breaking
2393 // users who expect a deprecated form of this callback.
4ee251cb 2394 this.getFunctionOption('underlayCallback').call(this,
98eb4713
DV
2395 this.hidden_ctx_, this.layout_.getPlotArea(), this, this);
2396 }
2397
2398 var e = {
189f8030 2399 canvas: this.hidden_,
2de7166c 2400 drawingContext: this.hidden_ctx_
98eb4713
DV
2401 };
2402 this.cascadeEvents_('willDrawChart', e);
6a1aa64f 2403 this.plotter_.render();
98eb4713 2404 this.cascadeEvents_('didDrawChart', e);
fa11f4e4 2405 this.lastRow_ = -1; // because plugins/legend.js clears the legend
8cfe592f
DV
2406
2407 // TODO(danvk): is this a performance bottleneck when panning?
2408 // The interaction canvas should already be empty in that situation.
7c39bb3a 2409 this.canvas_.getContext('2d').clearRect(0, 0, this.width_, this.height_);
599fb4ad 2410
b0963cdb 2411 if (this.getFunctionOption("drawCallback") !== null) {
b617ba25 2412 this.getFunctionOption("drawCallback").call(this, this, is_initial_draw);
599fb4ad 2413 }
5bcc58b4
DV
2414 if (is_initial_draw) {
2415 this.readyFired_ = true;
2416 while (this.readyFns_.length > 0) {
2417 var fn = this.readyFns_.pop();
2418 fn(this);
2419 }
2420 }
6a1aa64f
DV
2421};
2422
2423/**
629a09ae 2424 * @private
26ca7938
DV
2425 * Determine properties of the y-axes which are independent of the data
2426 * currently being displayed. This includes things like the number of axes and
2427 * the style of the axes. It does not include the range of each axis and its
2428 * tick marks.
16f00742 2429 * This fills in this.axes_.
26ca7938 2430 * axes_ = [ { options } ]
26ca7938 2431 * indices are into the axes_ array.
f09fc545 2432 */
26ca7938 2433Dygraph.prototype.computeYAxes_ = function() {
d64b8fea
RK
2434 // Preserve valueWindow settings if they exist, and if the user hasn't
2435 // specified a new valueRange.
0cd1ad15 2436 var valueWindows, axis, index, opts, v;
758a629f 2437 if (this.axes_ !== undefined && this.user_attrs_.hasOwnProperty("valueRange") === false) {
d64b8fea 2438 valueWindows = [];
758a629f 2439 for (index = 0; index < this.axes_.length; index++) {
d64b8fea
RK
2440 valueWindows.push(this.axes_[index].valueWindow);
2441 }
2442 }
2443
6ad8b6a4
RK
2444 // this.axes_ doesn't match this.attributes_.axes_.options. It's used for
2445 // data computation as well as options storage.
f09fc545 2446 // Go through once and add all the axes.
02c93ff5 2447 this.axes_ = [];
0d216a60 2448
02c93ff5 2449 for (axis = 0; axis < this.attributes_.numAxes(); axis++) {
6ad8b6a4 2450 // Add a new axis, making a copy of its per-axis options.
02c93ff5 2451 opts = { g : this };
6ecc0739 2452 utils.update(opts, this.attributes_.axisOptions(axis));
6ad8b6a4 2453 this.axes_[axis] = opts;
f09fc545 2454 }
1c77a3a1 2455
7740dd00
RK
2456
2457 // Copy global valueRange option over to the first axis.
2458 // NOTE(konigsberg): Are these two statements necessary?
2459 // I tried removing it. The automated tests pass, and manually
2460 // messing with tests/zoom.html showed no trouble.
2461 v = this.attr_('valueRange');
2462 if (v) this.axes_[0].valueRange = v;
478b866b 2463
758a629f 2464 if (valueWindows !== undefined) {
d64b8fea 2465 // Restore valueWindow settings.
4ecb55b5
RK
2466
2467 // When going from two axes back to one, we only restore
2468 // one axis.
2469 var idxCount = Math.min(valueWindows.length, this.axes_.length);
2470
2471 for (index = 0; index < idxCount; index++) {
d64b8fea
RK
2472 this.axes_[index].valueWindow = valueWindows[index];
2473 }
2474 }
4dd0ac55 2475
4dd0ac55
RV
2476 for (axis = 0; axis < this.axes_.length; axis++) {
2477 if (axis === 0) {
2478 opts = this.optionsViewForAxis_('y' + (axis ? '2' : ''));
2479 v = opts("valueRange");
2480 if (v) this.axes_[axis].valueRange = v;
2481 } else { // To keep old behavior
2482 var axes = this.user_attrs_.axes;
2483 if (axes && axes.y2) {
2484 v = axes.y2.valueRange;
2485 if (v) this.axes_[axis].valueRange = v;
2486 }
2487 }
2488 }
26ca7938
DV
2489};
2490
2491/**
2492 * Returns the number of y-axes on the chart.
1bc88216 2493 * @return {number} the number of axes.
26ca7938
DV
2494 */
2495Dygraph.prototype.numAxes = function() {
16f00742 2496 return this.attributes_.numAxes();
26ca7938
DV
2497};
2498
2499/**
629a09ae 2500 * @private
b2c9222a 2501 * Returns axis properties for the given series.
1bc88216 2502 * @param {string} setName The name of the series for which to get axis
b2c9222a 2503 * properties, e.g. 'Y1'.
1bc88216 2504 * @return {Object} The axis properties.
b2c9222a
DV
2505 */
2506Dygraph.prototype.axisPropertiesForSeries = function(series) {
2507 // TODO(danvk): handle errors.
16f00742 2508 return this.axes_[this.attributes_.axisForSeries(series)];
b2c9222a
DV
2509};
2510
2511/**
2512 * @private
26ca7938
DV
2513 * Determine the value range and tick marks for each axis.
2514 * @param {Object} extremes A mapping from seriesName -> [low, high]
2515 * This fills in the valueRange and ticks fields in each entry of this.axes_.
2516 */
2517Dygraph.prototype.computeYAxisRanges_ = function(extremes) {
9adc2c33 2518 var isNullUndefinedOrNaN = function(num) {
126bf1e3 2519 return isNaN(parseFloat(num));
6b05851c 2520 };
16f00742 2521 var numAxes = this.attributes_.numAxes();
4bac38d8 2522 var ypadCompat, span, series, ypad;
b77d7a56 2523
9e906ae6 2524 var p_axis;
f09fc545
DV
2525
2526 // Compute extreme values, a span and tick marks for each axis.
16f00742 2527 for (var i = 0; i < numAxes; i++) {
26ca7938 2528 var axis = this.axes_[i];
ec40f67c
RK
2529 var logscale = this.attributes_.getForAxis("logscale", i);
2530 var includeZero = this.attributes_.getForAxis("includeZero", i);
9e906ae6 2531 var independentTicks = this.attributes_.getForAxis("independentTicks", i);
6ad8b6a4
RK
2532 series = this.attributes_.seriesForAxis(i);
2533
31a8d0cd 2534 // Add some padding. This supports two Y padding operation modes:
2535 //
2536 // - backwards compatible (yRangePad not set):
2537 // 10% padding for automatic Y ranges, but not for user-supplied
2538 // ranges, and move a close-to-zero edge to zero except if
2539 // avoidMinZero is set, since drawing at the edge results in
2540 // invisible lines. Unfortunately lines drawn at the edge of a
2541 // user-supplied range will still be invisible. If logscale is
2542 // set, add a variable amount of padding at the top but
2543 // none at the bottom.
2544 //
2545 // - new-style (yRangePad set by the user):
2546 // always add the specified Y padding.
2547 //
2548 ypadCompat = true;
2549 ypad = 0.1; // add 10%
b0963cdb 2550 if (this.getNumericOption('yRangePad') !== null) {
31a8d0cd 2551 ypadCompat = false;
2552 // Convert pixel padding to ratio
b0963cdb 2553 ypad = this.getNumericOption('yRangePad') / this.plotter_.area.h;
31a8d0cd 2554 }
2555
83b0c192 2556 if (series.length === 0) {
06fc69b6
AV
2557 // If no series are defined or visible then use a reasonable default
2558 axis.extremeRange = [0, 1];
2559 } else {
1c77a3a1 2560 // Calculate the extremes of extremes.
f09fc545
DV
2561 var minY = Infinity; // extremes[series[0]][0];
2562 var maxY = -Infinity; // extremes[series[0]][1];
ba049b89 2563 var extremeMinY, extremeMaxY;
a2da3777 2564
f09fc545 2565 for (var j = 0; j < series.length; j++) {
a2da3777
DV
2566 // this skips invisible series
2567 if (!extremes.hasOwnProperty(series[j])) continue;
2568
ba049b89
NN
2569 // Only use valid extremes to stop null data series' from corrupting the scale.
2570 extremeMinY = extremes[series[j]][0];
758a629f 2571 if (extremeMinY !== null) {
36dfa958 2572 minY = Math.min(extremeMinY, minY);
ba049b89
NN
2573 }
2574 extremeMaxY = extremes[series[j]][1];
758a629f 2575 if (extremeMaxY !== null) {
36dfa958 2576 maxY = Math.max(extremeMaxY, maxY);
ba049b89 2577 }
f09fc545 2578 }
fa460473
KW
2579
2580 // Include zero if requested by the user.
2581 if (includeZero && !logscale) {
2582 if (minY > 0) minY = 0;
2583 if (maxY < 0) maxY = 0;
2584 }
f09fc545 2585
a2da3777 2586 // Ensure we have a valid scale, otherwise default to [0, 1] for safety.
36dfa958 2587 if (minY == Infinity) minY = 0;
a2da3777 2588 if (maxY == -Infinity) maxY = 1;
ba049b89 2589
4bac38d8 2590 span = maxY - minY;
fa460473
KW
2591 // special case: if we have no sense of scale, center on the sole value.
2592 if (span === 0) {
2593 if (maxY !== 0) {
2594 span = Math.abs(maxY);
2595 } else {
2596 // ... and if the sole value is zero, use range 0-1.
2597 maxY = 1;
2598 span = 1;
2599 }
2600 }
2601
758a629f 2602 var maxAxisY, minAxisY;
ec40f67c 2603 if (logscale) {
fa460473
KW
2604 if (ypadCompat) {
2605 maxAxisY = maxY + ypad * span;
2606 minAxisY = minY;
2607 } else {
2608 var logpad = Math.exp(Math.log(span) * ypad);
2609 maxAxisY = maxY * logpad;
2610 minAxisY = minY / logpad;
2611 }
ff022deb 2612 } else {
fa460473
KW
2613 maxAxisY = maxY + ypad * span;
2614 minAxisY = minY - ypad * span;
f09fc545 2615
fa460473
KW
2616 // Backwards-compatible behavior: Move the span to start or end at zero if it's
2617 // close to zero, but not if avoidMinZero is set.
b0963cdb 2618 if (ypadCompat && !this.getBooleanOption("avoidMinZero")) {
ff022deb
RK
2619 if (minAxisY < 0 && minY >= 0) minAxisY = 0;
2620 if (maxAxisY > 0 && maxY <= 0) maxAxisY = 0;
2621 }
f09fc545 2622 }
4cac8c7a
RK
2623 axis.extremeRange = [minAxisY, maxAxisY];
2624 }
2625 if (axis.valueWindow) {
2626 // This is only set if the user has zoomed on the y-axis. It is never set
2627 // by a user. It takes precedence over axis.valueRange because, if you set
2628 // valueRange, you'd still expect to be able to pan.
2629 axis.computedValueRange = [axis.valueWindow[0], axis.valueWindow[1]];
2630 } else if (axis.valueRange) {
2631 // This is a user-set value range for this axis.
fa460473
KW
2632 var y0 = isNullUndefinedOrNaN(axis.valueRange[0]) ? axis.extremeRange[0] : axis.valueRange[0];
2633 var y1 = isNullUndefinedOrNaN(axis.valueRange[1]) ? axis.extremeRange[1] : axis.valueRange[1];
2634 if (!ypadCompat) {
2635 if (axis.logscale) {
2636 var logpad = Math.exp(Math.log(span) * ypad);
2637 y0 *= logpad;
2638 y1 /= logpad;
2639 } else {
4bac38d8 2640 span = y1 - y0;
fa460473
KW
2641 y0 -= span * ypad;
2642 y1 += span * ypad;
2643 }
2644 }
2645 axis.computedValueRange = [y0, y1];
4cac8c7a
RK
2646 } else {
2647 axis.computedValueRange = axis.extremeRange;
f09fc545 2648 }
b77d7a56 2649
2650
383d8473 2651 if (independentTicks) {
9e906ae6
DE
2652 axis.independentTicks = independentTicks;
2653 var opts = this.optionsViewForAxis_('y' + (i ? '2' : ''));
2654 var ticker = opts('ticker');
48e614ac 2655 axis.ticks = ticker(axis.computedValueRange[0],
9e906ae6 2656 axis.computedValueRange[1],
b504bdd2 2657 this.plotter_.area.h,
9e906ae6
DE
2658 opts,
2659 this);
6c5f8774 2660 // Define the first independent axis as primary axis.
e8b3c7b4 2661 if (!p_axis) p_axis = axis;
9e906ae6
DE
2662 }
2663 }
e8b3c7b4 2664 if (p_axis === undefined) {
eba6dd23 2665 throw ("Configuration Error: At least one axis has to have the \"independentTicks\" option activated.");
e8b3c7b4 2666 }
9e906ae6
DE
2667 // Add ticks. By default, all axes inherit the tick positions of the
2668 // primary axis. However, if an axis is specifically marked as having
2669 // independent ticks, then that is permissible as well.
2670 for (var i = 0; i < numAxes; i++) {
2671 var axis = this.axes_[i];
b77d7a56 2672
9e906ae6
DE
2673 if (!axis.independentTicks) {
2674 var opts = this.optionsViewForAxis_('y' + (i ? '2' : ''));
2675 var ticker = opts('ticker');
0d64e596
DV
2676 var p_ticks = p_axis.ticks;
2677 var p_scale = p_axis.computedValueRange[1] - p_axis.computedValueRange[0];
2678 var scale = axis.computedValueRange[1] - axis.computedValueRange[0];
2679 var tick_values = [];
25f76ae3
DV
2680 for (var k = 0; k < p_ticks.length; k++) {
2681 var y_frac = (p_ticks[k].v - p_axis.computedValueRange[0]) / p_scale;
0d64e596
DV
2682 var y_val = axis.computedValueRange[0] + y_frac * scale;
2683 tick_values.push(y_val);
2684 }
2685
48e614ac
DV
2686 axis.ticks = ticker(axis.computedValueRange[0],
2687 axis.computedValueRange[1],
b504bdd2 2688 this.plotter_.area.h,
48e614ac
DV
2689 opts,
2690 this,
2691 tick_values);
0d64e596 2692 }
34fc91d4 2693 }
f09fc545 2694};
25f76ae3 2695
f09fc545 2696/**
285a6bda
DV
2697 * Detects the type of the str (date or numeric) and sets the various
2698 * formatting attributes in this.attrs_ based on this type.
1bc88216 2699 * @param {string} str An x value.
285a6bda
DV
2700 * @private
2701 */
2702Dygraph.prototype.detectTypeFromString_ = function(str) {
2703 var isDate = false;
0842b24b
DV
2704 var dashPos = str.indexOf('-'); // could be 2006-01-01 _or_ 1.0e-2
2705 if ((dashPos > 0 && (str[dashPos-1] != 'e' && str[dashPos-1] != 'E')) ||
285a6bda
DV
2706 str.indexOf('/') >= 0 ||
2707 isNaN(parseFloat(str))) {
2708 isDate = true;
2709 } else if (str.length == 8 && str > '19700101' && str < '20371231') {
2710 // TODO(danvk): remove support for this format.
2711 isDate = true;
2712 }
2713
a716aff2
RK
2714 this.setXAxisOptions_(isDate);
2715};
2716
2717Dygraph.prototype.setXAxisOptions_ = function(isDate) {
285a6bda 2718 if (isDate) {
6ecc0739
DV
2719 this.attrs_.xValueParser = utils.dateParser;
2720 this.attrs_.axes.x.valueFormatter = utils.dateValueFormatter;
2721 this.attrs_.axes.x.ticker = DygraphTickers.dateTicker;
2722 this.attrs_.axes.x.axisLabelFormatter = utils.dateAxisLabelFormatter;
285a6bda 2723 } else {
c39e1d93 2724 /** @private (shut up, jsdoc!) */
285a6bda 2725 this.attrs_.xValueParser = function(x) { return parseFloat(x); };
48e614ac
DV
2726 // TODO(danvk): use Dygraph.numberValueFormatter here?
2727 /** @private (shut up, jsdoc!) */
2728 this.attrs_.axes.x.valueFormatter = function(x) { return x; };
6ecc0739 2729 this.attrs_.axes.x.ticker = DygraphTickers.numericTicks;
48e614ac 2730 this.attrs_.axes.x.axisLabelFormatter = this.attrs_.axes.x.valueFormatter;
6a1aa64f 2731 }
83b0c192 2732};
6a1aa64f
DV
2733
2734/**
629a09ae 2735 * @private
6a1aa64f
DV
2736 * Parses a string in a special csv format. We expect a csv file where each
2737 * line is a date point, and the first field in each line is the date string.
2738 * We also expect that all remaining fields represent series.
285a6bda 2739 * if the errorBars attribute is set, then interpret the fields as:
6a1aa64f 2740 * date, series1, stddev1, series2, stddev2, ...
629a09ae 2741 * @param {[Object]} data See above.
285a6bda 2742 *
629a09ae 2743 * @return [Object] An array with one entry for each row. These entries
285a6bda
DV
2744 * are an array of cells in that row. The first entry is the parsed x-value for
2745 * the row. The second, third, etc. are the y-values. These can take on one of
2746 * three forms, depending on the CSV and constructor parameters:
2747 * 1. numeric value
2748 * 2. [ value, stddev ]
2749 * 3. [ low value, center value, high value ]
6a1aa64f 2750 */
285a6bda 2751Dygraph.prototype.parseCSV_ = function(data) {
6a1aa64f 2752 var ret = [];
6ecc0739 2753 var line_delimiter = utils.detectLineDelimiter(data);
e5763589 2754 var lines = data.split(line_delimiter || "\n");
758a629f 2755 var vals, j;
3d67f03b
DV
2756
2757 // Use the default delimiter or fall back to a tab if that makes sense.
b0963cdb 2758 var delim = this.getStringOption('delimiter');
3d67f03b
DV
2759 if (lines[0].indexOf(delim) == -1 && lines[0].indexOf('\t') >= 0) {
2760 delim = '\t';
2761 }
2762
285a6bda 2763 var start = 0;
d7beab6b
DV
2764 if (!('labels' in this.user_attrs_)) {
2765 // User hasn't explicitly set labels, so they're (presumably) in the CSV.
285a6bda 2766 start = 1;
d7beab6b 2767 this.attrs_.labels = lines[0].split(delim); // NOTE: _not_ user_attrs_.
34825ef5 2768 this.attributes_.reparseSeries();
6a1aa64f 2769 }
5cd7ac68 2770 var line_no = 0;
03b522a4 2771
285a6bda
DV
2772 var xParser;
2773 var defaultParserSet = false; // attempt to auto-detect x value type
2774 var expectedCols = this.attr_("labels").length;
987840a2 2775 var outOfOrder = false;
6a1aa64f
DV
2776 for (var i = start; i < lines.length; i++) {
2777 var line = lines[i];
5cd7ac68 2778 line_no = i;
758a629f 2779 if (line.length === 0) continue; // skip blank lines
3d67f03b
DV
2780 if (line[0] == '#') continue; // skip comment lines
2781 var inFields = line.split(delim);
285a6bda 2782 if (inFields.length < 2) continue;
6a1aa64f
DV
2783
2784 var fields = [];
285a6bda
DV
2785 if (!defaultParserSet) {
2786 this.detectTypeFromString_(inFields[0]);
b0963cdb 2787 xParser = this.getFunctionOption("xValueParser");
285a6bda
DV
2788 defaultParserSet = true;
2789 }
2790 fields[0] = xParser(inFields[0], this);
6a1aa64f
DV
2791
2792 // If fractions are expected, parse the numbers as "A/B"
2793 if (this.fractions_) {
758a629f 2794 for (j = 1; j < inFields.length; j++) {
6a1aa64f 2795 // TODO(danvk): figure out an appropriate way to flag parse errors.
758a629f 2796 vals = inFields[j].split("/");
7219edb3 2797 if (vals.length != 2) {
8a68db7d 2798 console.error('Expected fractional "num/den" values in CSV data ' +
464b5f50
DV
2799 "but found a value '" + inFields[j] + "' on line " +
2800 (1 + i) + " ('" + line + "') which is not of this form.");
7219edb3
DV
2801 fields[j] = [0, 0];
2802 } else {
6ecc0739
DV
2803 fields[j] = [utils.parseFloat_(vals[0], i, line),
2804 utils.parseFloat_(vals[1], i, line)];
7219edb3 2805 }
6a1aa64f 2806 }
b0963cdb 2807 } else if (this.getBooleanOption("errorBars")) {
6a1aa64f 2808 // If there are error bars, values are (value, stddev) pairs
7219edb3 2809 if (inFields.length % 2 != 1) {
8a68db7d 2810 console.error('Expected alternating (value, stdev.) pairs in CSV data ' +
464b5f50
DV
2811 'but line ' + (1 + i) + ' has an odd number of values (' +
2812 (inFields.length - 1) + "): '" + line + "'");
7219edb3 2813 }
758a629f 2814 for (j = 1; j < inFields.length; j += 2) {
6ecc0739
DV
2815 fields[(j + 1) / 2] = [utils.parseFloat_(inFields[j], i, line),
2816 utils.parseFloat_(inFields[j + 1], i, line)];
7219edb3 2817 }
b0963cdb 2818 } else if (this.getBooleanOption("customBars")) {
6a1aa64f 2819 // Bars are a low;center;high tuple
758a629f 2820 for (j = 1; j < inFields.length; j++) {
327a9279
DV
2821 var val = inFields[j];
2822 if (/^ *$/.test(val)) {
2823 fields[j] = [null, null, null];
2824 } else {
758a629f 2825 vals = val.split(";");
327a9279 2826 if (vals.length == 3) {
6ecc0739
DV
2827 fields[j] = [ utils.parseFloat_(vals[0], i, line),
2828 utils.parseFloat_(vals[1], i, line),
2829 utils.parseFloat_(vals[2], i, line) ];
327a9279 2830 } else {
8a68db7d 2831 console.warn('When using customBars, values must be either blank ' +
464b5f50
DV
2832 'or "low;center;high" tuples (got "' + val +
2833 '" on line ' + (1+i));
327a9279
DV
2834 }
2835 }
6a1aa64f
DV
2836 }
2837 } else {
2838 // Values are just numbers
758a629f 2839 for (j = 1; j < inFields.length; j++) {
6ecc0739 2840 fields[j] = utils.parseFloat_(inFields[j], i, line);
285a6bda 2841 }
6a1aa64f 2842 }
987840a2
DV
2843 if (ret.length > 0 && fields[0] < ret[ret.length - 1][0]) {
2844 outOfOrder = true;
2845 }
285a6bda
DV
2846
2847 if (fields.length != expectedCols) {
8a68db7d 2848 console.error("Number of columns in line " + i + " (" + fields.length +
464b5f50
DV
2849 ") does not agree with number of labels (" + expectedCols +
2850 ") " + line);
285a6bda 2851 }
6d0aaa09
DV
2852
2853 // If the user specified the 'labels' option and none of the cells of the
2854 // first row parsed correctly, then they probably double-specified the
2855 // labels. We go with the values set in the option, discard this row and
2856 // log a warning to the JS console.
758a629f 2857 if (i === 0 && this.attr_('labels')) {
6d0aaa09 2858 var all_null = true;
758a629f 2859 for (j = 0; all_null && j < fields.length; j++) {
6d0aaa09
DV
2860 if (fields[j]) all_null = false;
2861 }
2862 if (all_null) {
8a68db7d 2863 console.warn("The dygraphs 'labels' option is set, but the first row " +
464b5f50
DV
2864 "of CSV data ('" + line + "') appears to also contain " +
2865 "labels. Will drop the CSV labels and use the option " +
2866 "labels.");
6d0aaa09
DV
2867 continue;
2868 }
2869 }
2870 ret.push(fields);
6a1aa64f 2871 }
987840a2
DV
2872
2873 if (outOfOrder) {
8a68db7d 2874 console.warn("CSV is out of order; order it correctly to speed loading.");
758a629f 2875 ret.sort(function(a,b) { return a[0] - b[0]; });
987840a2
DV
2876 }
2877
6a1aa64f
DV
2878 return ret;
2879};
2880
2881/**
285a6bda
DV
2882 * The user has provided their data as a pre-packaged JS array. If the x values
2883 * are numeric, this is the same as dygraphs' internal format. If the x values
2884 * are dates, we need to convert them from Date objects to ms since epoch.
8ef9d44d
DV
2885 * @param {!Array} data
2886 * @return {Object} data with numeric x values.
2887 * @private
285a6bda
DV
2888 */
2889Dygraph.prototype.parseArray_ = function(data) {
2890 // Peek at the first x value to see if it's numeric.
758a629f 2891 if (data.length === 0) {
8a68db7d 2892 console.error("Can't plot empty data set");
285a6bda
DV
2893 return null;
2894 }
758a629f 2895 if (data[0].length === 0) {
8a68db7d 2896 console.error("Data set cannot contain an empty row");
285a6bda
DV
2897 return null;
2898 }
2899
758a629f
DV
2900 var i;
2901 if (this.attr_("labels") === null) {
8a68db7d 2902 console.warn("Using default labels. Set labels explicitly via 'labels' " +
464b5f50 2903 "in the options parameter");
285a6bda 2904 this.attrs_.labels = [ "X" ];
758a629f 2905 for (i = 1; i < data[0].length; i++) {
77812e0e 2906 this.attrs_.labels.push("Y" + i); // Not user_attrs_.
285a6bda 2907 }
77812e0e 2908 this.attributes_.reparseSeries();
debdb88d
DV
2909 } else {
2910 var num_labels = this.attr_("labels");
2911 if (num_labels.length != data[0].length) {
8a68db7d 2912 console.error("Mismatch between number of labels (" + num_labels + ")" +
464b5f50 2913 " and number of columns in array (" + data[0].length + ")");
debdb88d
DV
2914 return null;
2915 }
285a6bda
DV
2916 }
2917
6ecc0739 2918 if (utils.isDateLike(data[0][0])) {
285a6bda 2919 // Some intelligent defaults for a date x-axis.
6ecc0739
DV
2920 this.attrs_.axes.x.valueFormatter = utils.dateValueFormatter;
2921 this.attrs_.axes.x.ticker = DygraphTickers.dateTicker;
2922 this.attrs_.axes.x.axisLabelFormatter = utils.dateAxisLabelFormatter;
285a6bda
DV
2923
2924 // Assume they're all dates.
6ecc0739 2925 var parsedData = utils.clone(data);
758a629f
DV
2926 for (i = 0; i < data.length; i++) {
2927 if (parsedData[i].length === 0) {
8a68db7d 2928 console.error("Row " + (1 + i) + " of data is empty");
285a6bda
DV
2929 return null;
2930 }
758a629f
DV
2931 if (parsedData[i][0] === null ||
2932 typeof(parsedData[i][0].getTime) != 'function' ||
2933 isNaN(parsedData[i][0].getTime())) {
8a68db7d 2934 console.error("x value in row " + (1 + i) + " is not a Date");
285a6bda
DV
2935 return null;
2936 }
2937 parsedData[i][0] = parsedData[i][0].getTime();
2938 }
2939 return parsedData;
2940 } else {
2941 // Some intelligent defaults for a numeric x-axis.
c39e1d93 2942 /** @private (shut up, jsdoc!) */
48e614ac 2943 this.attrs_.axes.x.valueFormatter = function(x) { return x; };
6ecc0739
DV
2944 this.attrs_.axes.x.ticker = DygraphTickers.numericTicks;
2945 this.attrs_.axes.x.axisLabelFormatter = utils.numberAxisLabelFormatter;
285a6bda
DV
2946 return data;
2947 }
2948};
2949
2950/**
79420a1e
DV
2951 * Parses a DataTable object from gviz.
2952 * The data is expected to have a first column that is either a date or a
2953 * number. All subsequent columns must be numbers. If there is a clear mismatch
2954 * between this.xValueParser_ and the type of the first column, it will be
a685723c 2955 * fixed. Fills out rawData_.
1bc88216 2956 * @param {!google.visualization.DataTable} data See above.
79420a1e
DV
2957 * @private
2958 */
285a6bda 2959Dygraph.prototype.parseDataTable_ = function(data) {
5829af3d 2960 var shortTextForAnnotationNum = function(num) {
2961 // converts [0-9]+ [A-Z][a-z]*
2962 // example: 0=A, 1=B, 25=Z, 26=Aa, 27=Ab
2963 // and continues like.. Ba Bb .. Za .. Zz..Aaa...Zzz Aaaa Zzzz
2964 var shortText = String.fromCharCode(65 /* A */ + num % 26);
2965 num = Math.floor(num / 26);
2966 while ( num > 0 ) {
2967 shortText = String.fromCharCode(65 /* A */ + (num - 1) % 26 ) + shortText.toLowerCase();
2968 num = Math.floor((num - 1) / 26);
2969 }
2970 return shortText;
42a9ebb8 2971 };
5829af3d 2972
79420a1e
DV
2973 var cols = data.getNumberOfColumns();
2974 var rows = data.getNumberOfRows();
2975
d955e223 2976 var indepType = data.getColumnType(0);
4440f6c8 2977 if (indepType == 'date' || indepType == 'datetime') {
6ecc0739
DV
2978 this.attrs_.xValueParser = utils.dateParser;
2979 this.attrs_.axes.x.valueFormatter = utils.dateValueFormatter;
2980 this.attrs_.axes.x.ticker = DygraphTickers.dateTicker;
2981 this.attrs_.axes.x.axisLabelFormatter = utils.dateAxisLabelFormatter;
33127159 2982 } else if (indepType == 'number') {
285a6bda 2983 this.attrs_.xValueParser = function(x) { return parseFloat(x); };
48e614ac 2984 this.attrs_.axes.x.valueFormatter = function(x) { return x; };
6ecc0739 2985 this.attrs_.axes.x.ticker = DygraphTickers.numericTicks;
48e614ac 2986 this.attrs_.axes.x.axisLabelFormatter = this.attrs_.axes.x.valueFormatter;
285a6bda 2987 } else {
23b6c2e2
DV
2988 throw new Error(
2989 "only 'date', 'datetime' and 'number' types are supported " +
2990 "for column 1 of DataTable input (Got '" + indepType + "')");
79420a1e
DV
2991 }
2992
a685723c
DV
2993 // Array of the column indices which contain data (and not annotations).
2994 var colIdx = [];
2995 var annotationCols = {}; // data index -> [annotation cols]
2996 var hasAnnotations = false;
758a629f
DV
2997 var i, j;
2998 for (i = 1; i < cols; i++) {
a685723c
DV
2999 var type = data.getColumnType(i);
3000 if (type == 'number') {
3001 colIdx.push(i);
b0963cdb 3002 } else if (type == 'string' && this.getBooleanOption('displayAnnotations')) {
a685723c
DV
3003 // This is OK -- it's an annotation column.
3004 var dataIdx = colIdx[colIdx.length - 1];
3005 if (!annotationCols.hasOwnProperty(dataIdx)) {
3006 annotationCols[dataIdx] = [i];
3007 } else {
3008 annotationCols[dataIdx].push(i);
3009 }
3010 hasAnnotations = true;
3011 } else {
23b6c2e2
DV
3012 throw new Error(
3013 "Only 'number' is supported as a dependent type with Gviz." +
3014 " 'string' is only supported if displayAnnotations is true");
a685723c
DV
3015 }
3016 }
3017
3018 // Read column labels
3019 // TODO(danvk): add support back for errorBars
3020 var labels = [data.getColumnLabel(0)];
758a629f 3021 for (i = 0; i < colIdx.length; i++) {
a685723c 3022 labels.push(data.getColumnLabel(colIdx[i]));
b0963cdb 3023 if (this.getBooleanOption("errorBars")) i += 1;
a685723c
DV
3024 }
3025 this.attrs_.labels = labels;
3026 cols = labels.length;
3027
79420a1e 3028 var ret = [];
987840a2 3029 var outOfOrder = false;
a685723c 3030 var annotations = [];
758a629f 3031 for (i = 0; i < rows; i++) {
79420a1e 3032 var row = [];
debe4434
DV
3033 if (typeof(data.getValue(i, 0)) === 'undefined' ||
3034 data.getValue(i, 0) === null) {
8a68db7d 3035 console.warn("Ignoring row " + i +
464b5f50 3036 " of DataTable because of undefined or null first column.");
debe4434
DV
3037 continue;
3038 }
3039
c21d2c2d 3040 if (indepType == 'date' || indepType == 'datetime') {
d955e223
DV
3041 row.push(data.getValue(i, 0).getTime());
3042 } else {
3043 row.push(data.getValue(i, 0));
3044 }
b0963cdb 3045 if (!this.getBooleanOption("errorBars")) {
758a629f 3046 for (j = 0; j < colIdx.length; j++) {
a685723c
DV
3047 var col = colIdx[j];
3048 row.push(data.getValue(i, col));
3049 if (hasAnnotations &&
3050 annotationCols.hasOwnProperty(col) &&
758a629f 3051 data.getValue(i, annotationCols[col][0]) !== null) {
a685723c
DV
3052 var ann = {};
3053 ann.series = data.getColumnLabel(col);
3054 ann.xval = row[0];
5829af3d 3055 ann.shortText = shortTextForAnnotationNum(annotations.length);
a685723c
DV
3056 ann.text = '';
3057 for (var k = 0; k < annotationCols[col].length; k++) {
3058 if (k) ann.text += "\n";
3059 ann.text += data.getValue(i, annotationCols[col][k]);
3060 }
3061 annotations.push(ann);
3062 }
3e3f84e4 3063 }
92fd68d8
DV
3064
3065 // Strip out infinities, which give dygraphs problems later on.
758a629f 3066 for (j = 0; j < row.length; j++) {
92fd68d8
DV
3067 if (!isFinite(row[j])) row[j] = null;
3068 }
3e3f84e4 3069 } else {
758a629f 3070 for (j = 0; j < cols - 1; j++) {
3e3f84e4
DV
3071 row.push([ data.getValue(i, 1 + 2 * j), data.getValue(i, 2 + 2 * j) ]);
3072 }
79420a1e 3073 }
987840a2
DV
3074 if (ret.length > 0 && row[0] < ret[ret.length - 1][0]) {
3075 outOfOrder = true;
3076 }
243d96e8 3077 ret.push(row);
79420a1e 3078 }
987840a2
DV
3079
3080 if (outOfOrder) {
8a68db7d 3081 console.warn("DataTable is out of order; order it correctly to speed loading.");
758a629f 3082 ret.sort(function(a,b) { return a[0] - b[0]; });
987840a2 3083 }
a685723c
DV
3084 this.rawData_ = ret;
3085
3086 if (annotations.length > 0) {
3087 this.setAnnotations(annotations, true);
3088 }
0fa724fd 3089 this.attributes_.reparseSeries();
758a629f 3090};
79420a1e 3091
629a09ae 3092/**
6f5f0b2b
DV
3093 * Signals to plugins that the chart data has updated.
3094 * This happens after the data has updated but before the chart has redrawn.
3095 */
3096Dygraph.prototype.cascadeDataDidUpdateEvent_ = function() {
3097 // TODO(danvk): there are some issues checking xAxisRange() and using
3098 // toDomCoords from handlers of this event. The visible range should be set
3099 // when the chart is drawn, not derived from the data.
3100 this.cascadeEvents_('dataDidUpdate', {});
3101};
3102
3103/**
6a1aa64f
DV
3104 * Get the CSV data. If it's in a function, call that function. If it's in a
3105 * file, do an XMLHttpRequest to get it.
3106 * @private
3107 */
285a6bda 3108Dygraph.prototype.start_ = function() {
36d4fabf
RK
3109 var data = this.file_;
3110
3111 // Functions can return references of all other types.
3112 if (typeof data == 'function') {
3113 data = data();
3114 }
3115
6ecc0739 3116 if (utils.isArrayLike(data)) {
36d4fabf 3117 this.rawData_ = this.parseArray_(data);
6f5f0b2b 3118 this.cascadeDataDidUpdateEvent_();
26ca7938 3119 this.predraw_();
36d4fabf
RK
3120 } else if (typeof data == 'object' &&
3121 typeof data.getColumnRange == 'function') {
79420a1e 3122 // must be a DataTable from gviz.
36d4fabf 3123 this.parseDataTable_(data);
6f5f0b2b 3124 this.cascadeDataDidUpdateEvent_();
26ca7938 3125 this.predraw_();
36d4fabf 3126 } else if (typeof data == 'string') {
285a6bda 3127 // Heuristic: a newline means it's CSV data. Otherwise it's an URL.
6ecc0739 3128 var line_delimiter = utils.detectLineDelimiter(data);
e5763589 3129 if (line_delimiter) {
36d4fabf 3130 this.loadedEvent_(data);
285a6bda 3131 } else {
efc5160f
DV
3132 // REMOVE_FOR_IE
3133 var req;
3134 if (window.XMLHttpRequest) {
3135 // Firefox, Opera, IE7, and other browsers will use the native object
3136 req = new XMLHttpRequest();
3137 } else {
3138 // IE 5 and 6 will use the ActiveX control
3139 req = new ActiveXObject("Microsoft.XMLHTTP");
3140 }
3141
285a6bda
DV
3142 var caller = this;
3143 req.onreadystatechange = function () {
3144 if (req.readyState == 4) {
758a629f
DV
3145 if (req.status === 200 || // Normal http
3146 req.status === 0) { // Chrome w/ --allow-file-access-from-files
285a6bda
DV
3147 caller.loadedEvent_(req.responseText);
3148 }
6a1aa64f 3149 }
285a6bda 3150 };
6a1aa64f 3151
36d4fabf 3152 req.open("GET", data, true);
285a6bda
DV
3153 req.send(null);
3154 }
3155 } else {
8a68db7d 3156 console.error("Unknown data format: " + (typeof data));
6a1aa64f
DV
3157 }
3158};
3159
3160/**
3161 * Changes various properties of the graph. These can include:
3162 * <ul>
3163 * <li>file: changes the source data for the graph</li>
3164 * <li>errorBars: changes whether the data contains stddev</li>
3165 * </ul>
dcb25130 3166 *
ccfcc169
DV
3167 * There's a huge variety of options that can be passed to this method. For a
3168 * full list, see http://dygraphs.com/options.html.
3169 *
8ef9d44d
DV
3170 * @param {Object} input_attrs The new properties and values
3171 * @param {boolean} block_redraw Usually the chart is redrawn after every
3172 * call to updateOptions(). If you know better, you can pass true to
3173 * explicitly block the redraw. This can be useful for chaining
3174 * updateOptions() calls, avoiding the occasional infinite loop and
3175 * preventing redraws when it's not necessary (e.g. when updating a
3176 * callback).
6a1aa64f 3177 */
48e614ac 3178Dygraph.prototype.updateOptions = function(input_attrs, block_redraw) {
ccfcc169
DV
3179 if (typeof(block_redraw) == 'undefined') block_redraw = false;
3180
bfb3e0a4 3181 // copyUserAttrs_ drops the "file" parameter as a convenience to us.
758a629f 3182 var file = input_attrs.file;
bfb3e0a4 3183 var attrs = Dygraph.copyUserAttrs_(input_attrs);
48e614ac 3184
ccfcc169 3185 // TODO(danvk): this is a mess. Move these options into attr_.
c65f2303 3186 if ('rollPeriod' in attrs) {
6a1aa64f
DV
3187 this.rollPeriod_ = attrs.rollPeriod;
3188 }
c65f2303 3189 if ('dateWindow' in attrs) {
6a1aa64f 3190 this.dateWindow_ = attrs.dateWindow;
e5152598 3191 if (!('isZoomedIgnoreProgrammaticZoom' in attrs)) {
758a629f 3192 this.zoomed_x_ = (attrs.dateWindow !== null);
81856f70 3193 }
b7e5862d 3194 }
e5152598 3195 if ('valueRange' in attrs && !('isZoomedIgnoreProgrammaticZoom' in attrs)) {
758a629f 3196 this.zoomed_y_ = (attrs.valueRange !== null);
6a1aa64f 3197 }
450fe64b
DV
3198
3199 // TODO(danvk): validate per-series options.
46dde5f9
DV
3200 // Supported:
3201 // strokeWidth
3202 // pointSize
3203 // drawPoints
3204 // highlightCircleSize
450fe64b 3205
9ca829f2 3206 // Check if this set options will require new points.
6ecc0739 3207 var requiresNewPoints = utils.isPixelChangingOptionList(this.attr_("labels"), attrs);
9ca829f2 3208
6ecc0739 3209 utils.updateDeep(this.user_attrs_, attrs);
285a6bda 3210
b635457c
RK
3211 this.attributes_.reparseSeries();
3212
48e614ac 3213 if (file) {
6f5f0b2b
DV
3214 // This event indicates that the data is about to change, but hasn't yet.
3215 // TODO(danvk): support cancelation of the update via this event.
3216 this.cascadeEvents_('dataWillUpdate', {});
3217
48e614ac 3218 this.file_ = file;
ccfcc169 3219 if (!block_redraw) this.start_();
6a1aa64f 3220 } else {
9ca829f2
DV
3221 if (!block_redraw) {
3222 if (requiresNewPoints) {
48e614ac 3223 this.predraw_();
9ca829f2 3224 } else {
e2c21500 3225 this.renderGraph_(false);
9ca829f2
DV
3226 }
3227 }
6a1aa64f
DV
3228 }
3229};
3230
3231/**
bfb3e0a4 3232 * Make a copy of input attributes, removing file as a convenience.
48e614ac 3233 */
bfb3e0a4 3234Dygraph.copyUserAttrs_ = function(attrs) {
48e614ac
DV
3235 var my_attrs = {};
3236 for (var k in attrs) {
3ce712e6 3237 if (!attrs.hasOwnProperty(k)) continue;
48e614ac
DV
3238 if (k == 'file') continue;
3239 if (attrs.hasOwnProperty(k)) my_attrs[k] = attrs[k];
3240 }
48e614ac
DV
3241 return my_attrs;
3242};
3243
3244/**
697e70b2
DV
3245 * Resizes the dygraph. If no parameters are specified, resizes to fill the
3246 * containing div (which has presumably changed size since the dygraph was
3247 * instantiated. If the width/height are specified, the div will be resized.
964f30c6
DV
3248 *
3249 * This is far more efficient than destroying and re-instantiating a
3250 * Dygraph, since it doesn't have to reparse the underlying data.
3251 *
1bc88216
DV
3252 * @param {number} width Width (in pixels)
3253 * @param {number} height Height (in pixels)
697e70b2
DV
3254 */
3255Dygraph.prototype.resize = function(width, height) {
e8c7ef86
DV
3256 if (this.resize_lock) {
3257 return;
3258 }
3259 this.resize_lock = true;
3260
697e70b2 3261 if ((width === null) != (height === null)) {
8a68db7d 3262 console.warn("Dygraph.resize() should be called with zero parameters or " +
464b5f50 3263 "two non-NULL parameters. Pretending it was zero.");
697e70b2
DV
3264 width = height = null;
3265 }
3266
4b4d1a63
DV
3267 var old_width = this.width_;
3268 var old_height = this.height_;
b16e6369 3269
697e70b2
DV
3270 if (width) {
3271 this.maindiv_.style.width = width + "px";
3272 this.maindiv_.style.height = height + "px";
3273 this.width_ = width;
3274 this.height_ = height;
3275 } else {
ccd9d7c2
PF
3276 this.width_ = this.maindiv_.clientWidth;
3277 this.height_ = this.maindiv_.clientHeight;
697e70b2
DV
3278 }
3279
4b4d1a63 3280 if (old_width != this.width_ || old_height != this.height_) {
d82a3164
KW
3281 // Resizing a canvas erases it, even when the size doesn't change, so
3282 // any resize needs to be followed by a redraw.
3283 this.resizeElements_();
4b4d1a63
DV
3284 this.predraw_();
3285 }
e8c7ef86
DV
3286
3287 this.resize_lock = false;
697e70b2
DV
3288};
3289
3290/**
6faebb69 3291 * Adjusts the number of points in the rolling average. Updates the graph to
6a1aa64f 3292 * reflect the new averaging period.
1bc88216 3293 * @param {number} length Number of points over which to average the data.
6a1aa64f 3294 */
285a6bda 3295Dygraph.prototype.adjustRoll = function(length) {
6a1aa64f 3296 this.rollPeriod_ = length;
26ca7938 3297 this.predraw_();
6a1aa64f 3298};
540d00f1 3299
f8cfec73 3300/**
1cf11047
DV
3301 * Returns a boolean array of visibility statuses.
3302 */
3303Dygraph.prototype.visibility = function() {
3304 // Do lazy-initialization, so that this happens after we know the number of
3305 // data series.
b0963cdb 3306 if (!this.getOption("visibility")) {
758a629f 3307 this.attrs_.visibility = [];
1cf11047 3308 }
758a629f 3309 // TODO(danvk): it looks like this could go into an infinite loop w/ user_attrs.
b0963cdb 3310 while (this.getOption("visibility").length < this.numColumns() - 1) {
758a629f 3311 this.attrs_.visibility.push(true);
1cf11047 3312 }
b0963cdb 3313 return this.getOption("visibility");
1cf11047
DV
3314};
3315
3316/**
1f0f434a 3317 * Changes the visibility of one or more series.
2aed8ad8 3318 *
20aaadda
DR
3319 * @param {number|number[]|object} num the series index or an array of series indices
3320 * or a boolean array of visibility states by index
3321 * or an object mapping series numbers, as keys, to
3322 * visibility state (boolean values)
e5cc0a4c 3323 * @param {boolean} value the visibility state expressed as a boolean
1cf11047
DV
3324 */
3325Dygraph.prototype.setVisibility = function(num, value) {
3326 var x = this.visibility();
e5cc0a4c 3327 var numIsObject = false;
1f0f434a 3328
e5cc0a4c
DR
3329 if (!Array.isArray(num)) {
3330 if (num !== null && typeof num === 'object') {
3331 numIsObject = true;
3332 } else {
3333 num = [num];
94fff6f2
DR
3334 }
3335 }
1f0f434a 3336
e5cc0a4c
DR
3337 if (numIsObject) {
3338 for (var i in num) {
3339 if (num.hasOwnProperty(i)) {
3340 if (i < 0 || i >= x.length) {
3341 console.warn("Invalid series number in setVisibility: " + i);
3342 } else {
3343 x[i] = num[i];
3344 }
3345 }
3346 }
3347 } else {
3348 for (var i = 0; i < num.length; i++) {
20aaadda
DR
3349 if (typeof num[i] === 'boolean') {
3350 if (i >= x.length) {
3351 console.warn("Invalid series number in setVisibility: " + i);
3352 } else {
3353 x[i] = num[i];
3354 }
e5cc0a4c 3355 } else {
20aaadda
DR
3356 if (num[i] < 0 || num[i] >= x.length) {
3357 console.warn("Invalid series number in setVisibility: " + num[i]);
3358 } else {
3359 x[num[i]] = value;
3360 }
e5cc0a4c 3361 }
1f0f434a 3362 }
1cf11047 3363 }
1f0f434a
SS
3364
3365 this.predraw_();
1cf11047
DV
3366};
3367
3368/**
0cb9bd91
DV
3369 * How large of an area will the dygraph render itself in?
3370 * This is used for testing.
3371 * @return A {width: w, height: h} object.
3372 * @private
3373 */
3374Dygraph.prototype.size = function() {
3375 return { width: this.width_, height: this.height_ };
3376};
3377
3378/**
5c528fa2 3379 * Update the list of annotations and redraw the chart.
41ee764f
DV
3380 * See dygraphs.com/annotations.html for more info on how to use annotations.
3381 * @param ann {Array} An array of annotation objects.
3382 * @param suppressDraw {Boolean} Set to "true" to block chart redraw (optional).
5c528fa2 3383 */
a685723c 3384Dygraph.prototype.setAnnotations = function(ann, suppressDraw) {
3c51ab74
DV
3385 // Only add the annotation CSS rule once we know it will be used.
3386 Dygraph.addAnnotationRule();
5c528fa2 3387 this.annotations_ = ann;
af6e4ad5 3388 if (!this.layout_) {
8a68db7d 3389 console.warn("Tried to setAnnotations before dygraph was ready. " +
464b5f50
DV
3390 "Try setting them in a ready() block. See " +
3391 "dygraphs.com/tests/annotation.html");
af6e4ad5
DV
3392 return;
3393 }
3394
5c528fa2 3395 this.layout_.setAnnotations(this.annotations_);
a685723c 3396 if (!suppressDraw) {
26ca7938 3397 this.predraw_();
a685723c 3398 }
5c528fa2
DV
3399};
3400
3401/**
3402 * Return the list of annotations.
3403 */
3404Dygraph.prototype.annotations = function() {
3405 return this.annotations_;
3406};
3407
46dde5f9 3408/**
82c6fe4d
KW
3409 * Get the list of label names for this graph. The first column is the
3410 * x-axis, so the data series names start at index 1.
4c10c8d2
RK
3411 *
3412 * Returns null when labels have not yet been defined.
82c6fe4d 3413 */
e2c21500 3414Dygraph.prototype.getLabels = function() {
4c10c8d2
RK
3415 var labels = this.attr_("labels");
3416 return labels ? labels.slice() : null;
82c6fe4d
KW
3417};
3418
3419/**
46dde5f9
DV
3420 * Get the index of a series (column) given its name. The first column is the
3421 * x-axis, so the data series start with index 1.
3422 */
3423Dygraph.prototype.indexFromSetName = function(name) {
82c6fe4d 3424 return this.setIndexByName_[name];
46dde5f9
DV
3425};
3426
629a09ae 3427/**
fcf37b29
DV
3428 * Find the row number corresponding to the given x-value.
3429 * Returns null if there is no such x-value in the data.
3430 * If there are multiple rows with the same x-value, this will return the
3431 * first one.
3432 * @param {number} xVal The x-value to look for (e.g. millis since epoch).
3433 * @return {?number} The row number, which you can pass to getValue(), or null.
3434 */
3435Dygraph.prototype.getRowForX = function(xVal) {
3436 var low = 0,
3437 high = this.numRows() - 1;
3438
3439 while (low <= high) {
3440 var idx = (high + low) >> 1;
3441 var x = this.getValue(idx, 0);
3442 if (x < xVal) {
3443 low = idx + 1;
3444 } else if (x > xVal) {
3445 high = idx - 1;
3446 } else if (low != idx) { // equal, but there may be an earlier match.
3447 high = idx;
3448 } else {
3449 return idx;
3450 }
3451 }
3452
3453 return null;
3454};
3455
3456/**
5bcc58b4
DV
3457 * Trigger a callback when the dygraph has drawn itself and is ready to be
3458 * manipulated. This is primarily useful when dygraphs has to do an XHR for the
3459 * data (i.e. a URL is passed as the data source) and the chart is drawn
3460 * asynchronously. If the chart has already drawn, the callback will fire
3461 * immediately.
3462 *
3463 * This is a good place to call setAnnotation().
3464 *
3465 * @param {function(!Dygraph)} callback The callback to trigger when the chart
3466 * is ready.
3467 */
3468Dygraph.prototype.ready = function(callback) {
3469 if (this.is_initial_draw_) {
3470 this.readyFns_.push(callback);
3471 } else {
4ee251cb 3472 callback.call(this, this);
5bcc58b4
DV
3473 }
3474};
3475
3476/**
629a09ae
DV
3477 * @private
3478 * Adds a default style for the annotation CSS classes to the document. This is
3479 * only executed when annotations are actually used. It is designed to only be
3480 * called once -- all calls after the first will return immediately.
3481 */
5c528fa2 3482Dygraph.addAnnotationRule = function() {
d38c6191 3483 // TODO(danvk): move this function into plugins/annotations.js?
5c528fa2
DV
3484 if (Dygraph.addedAnnotationCSS) return;
3485
5c528fa2
DV
3486 var rule = "border: 1px solid black; " +
3487 "background-color: white; " +
3488 "text-align: center;";
22186871
DV
3489
3490 var styleSheetElement = document.createElement("style");
3491 styleSheetElement.type = "text/css";
3492 document.getElementsByTagName("head")[0].appendChild(styleSheetElement);
3493
3494 // Find the first style sheet that we can access.
3495 // We may not add a rule to a style sheet from another domain for security
3496 // reasons. This sometimes comes up when using gviz, since the Google gviz JS
3497 // adds its own style sheets from google.com.
3498 for (var i = 0; i < document.styleSheets.length; i++) {
3499 if (document.styleSheets[i].disabled) continue;
3500 var mysheet = document.styleSheets[i];
3501 try {
3502 if (mysheet.insertRule) { // Firefox
3503 var idx = mysheet.cssRules ? mysheet.cssRules.length : 0;
3504 mysheet.insertRule(".dygraphDefaultAnnotation { " + rule + " }", idx);
3505 } else if (mysheet.addRule) { // IE
3506 mysheet.addRule(".dygraphDefaultAnnotation", rule);
3507 }
3508 Dygraph.addedAnnotationCSS = true;
3509 return;
3510 } catch(err) {
3511 // Was likely a security exception.
3512 }
5c528fa2
DV
3513 }
3514
8a68db7d 3515 console.warn("Unable to add default annotation CSS rule; display may be off.");
758a629f 3516};
8887663f 3517
6ecc0739
DV
3518/**
3519 * Add an event handler. This event handler is kept until the graph is
3520 * destroyed with a call to graph.destroy().
3521 *
3522 * @param {!Node} elem The element to add the event to.
3523 * @param {string} type The type of the event, e.g. 'click' or 'mousemove'.
3524 * @param {function(Event):(boolean|undefined)} fn The function to call
3525 * on the event. The function takes one parameter: the event object.
3526 * @private
3527 */
3528Dygraph.prototype.addAndTrackEvent = function(elem, type, fn) {
3529 utils.addEvent(elem, type, fn);
3530 this.registeredEvents_.push({elem, type, fn});
3531};
0294d285 3532
6ecc0739
DV
3533Dygraph.prototype.removeTrackedEvents_ = function() {
3534 if (this.registeredEvents_) {
3535 for (var idx = 0; idx < this.registeredEvents_.length; idx++) {
3536 var reg = this.registeredEvents_[idx];
3537 utils.removeEvent(reg.elem, reg.type, reg.fn);
3538 }
3539 }
3540
3541 this.registeredEvents_ = [];
3542};
3543
3544
3545// Installed plugins, in order of precedence (most-general to most-specific).
3546Dygraph.PLUGINS = [
3547 LegendPlugin,
3548 AxesPlugin,
3549 RangeSelectorPlugin, // Has to be before ChartLabels so that its callbacks are called after ChartLabels' callbacks.
3550 ChartLabelsPlugin,
3551 AnnotationsPlugin,
3552 GridPlugin
3553];
8887663f 3554
178b1e0a
DV
3555// There are many symbols which have historically been available through the
3556// Dygraph class. These are exported here for backwards compatibility.
e8c70e4e 3557Dygraph.GVizChart = GVizChart;
178b1e0a
DV
3558Dygraph.DASHED_LINE = utils.DASHED_LINE;
3559Dygraph.DOT_DASH_LINE = utils.DOT_DASH_LINE;
3560Dygraph.dateAxisLabelFormatter = utils.dateAxisLabelFormatter;
3561Dygraph.toRGB_ = utils.toRGB_;
3562Dygraph.findPos = utils.findPos;
3563Dygraph.pageX = utils.pageX;
3564Dygraph.pageY = utils.pageY;
3565Dygraph.dateString_ = utils.dateString_;
3566Dygraph.defaultInteractionModel = DygraphInteraction.defaultModel;
3567Dygraph.nonInteractiveModel = Dygraph.nonInteractiveModel_ = DygraphInteraction.nonInteractiveModel_;
3568Dygraph.Circles = utils.Circles;
3569
3570Dygraph.Plugins = {
3571 Legend: LegendPlugin,
3572 Axes: AxesPlugin,
c4c10db6
DV
3573 Annotations: AnnotationsPlugin,
3574 ChartLabels: ChartLabelsPlugin,
3575 Grid: GridPlugin,
3576 RangeSelector: RangeSelectorPlugin
178b1e0a 3577};
c4c10db6 3578
178b1e0a 3579Dygraph.DataHandlers = {
c4c10db6
DV
3580 DefaultHandler,
3581 BarsHandler,
3582 CustomBarsHandler,
3583 DefaultFractionHandler,
3584 ErrorBarsHandler,
3585 FractionsBarsHandler
178b1e0a
DV
3586};
3587
3588Dygraph.startPan = DygraphInteraction.startPan;
3589Dygraph.startZoom = DygraphInteraction.startZoom;
3590Dygraph.movePan = DygraphInteraction.movePan;
3591Dygraph.moveZoom = DygraphInteraction.moveZoom;
3592Dygraph.endPan = DygraphInteraction.endPan;
3593Dygraph.endZoom = DygraphInteraction.endZoom;
e8c70e4e 3594
2b66af4f
DV
3595Dygraph.numericLinearTicks = DygraphTickers.numericLinearTicks;
3596Dygraph.numericTicks = DygraphTickers.numericTicks;
3597Dygraph.dateTicker = DygraphTickers.dateTicker;
3598Dygraph.Granularity = DygraphTickers.Granularity;
3599Dygraph.getDateAxis = DygraphTickers.getDateAxis;
3600Dygraph.floatFormat = utils.floatFormat;
3601
6ecc0739 3602export default Dygraph;