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