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