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