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