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