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