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