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