Test labelsKMB{B,G2} with values < 1
[dygraphs.git] / src / dygraph.js
CommitLineData
88e95c46
DV
1/**
2 * @license
3 * Copyright 2006 Dan Vanderkam (danvdk@gmail.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
5 */
6a1aa64f
DV
6
7/**
8 * @fileoverview Creates an interactive, zoomable graph based on a CSV file or
285a6bda
DV
9 * string. Dygraph can handle multiple series with or without error bars. The
10 * date/value ranges will be automatically set. Dygraph uses the
6a1aa64f
DV
11 * &lt;canvas&gt; 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">
285a6bda
DV
17 new Dygraph(document.getElementById("graphdiv"),
18 "datafile.csv", // CSV file with headers
19 { }); // options
6a1aa64f
DV
20 </script>
21
22 The CSV file is of the form
23
285a6bda 24 Date,SeriesA,SeriesB,SeriesC
6a1aa64f
DV
25 YYYYMMDD,A1,B1,C1
26 YYYYMMDD,A2,B2,C2
27
6a1aa64f
DV
28 If the 'errorBars' option is set in the constructor, the input should be of
29 the form
285a6bda 30 Date,SeriesA,SeriesB,...
6a1aa64f
DV
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
285a6bda 36 Date,SeriesA,SeriesB,...
6a1aa64f
DV
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
727439b4 42 For further documentation and examples, see http://dygraphs.com/
6a1aa64f
DV
43
44 */
45
103fd879
DV
46// For "production" code, this gets set to false by uglifyjs.
47if (typeof(DEBUG) === 'undefined') DEBUG=true;
48
8887663f 49var Dygraph = (function() {
ac6a9c2b 50/*global DygraphLayout:false, DygraphCanvasRenderer:false, DygraphOptions:false, G_vmlCanvasManager:false,ActiveXObject:false */
c0f54d4f
DV
51"use strict";
52
6a1aa64f 53/**
629a09ae
DV
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.
6a1aa64f 63 * @param {Object} attrs Various other attributes, e.g. errorBars determines
629a09ae
DV
64 * whether the input data contains error ranges. For a complete list of
65 * options, see http://dygraphs.com/options.html.
6a1aa64f 66 */
86a3e64f 67var Dygraph = function(div, data, opts, opt_fourth_param) {
28eb1748
DV
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
86a3e64f
DV
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.
8a68db7d 78 console.warn("Using deprecated four-argument dygraph constructor");
86a3e64f
DV
79 this.__old_init__(div, data, opts, opt_fourth_param);
80 } else {
81 this.__init__(div, data, opts);
285a6bda 82 }
6a1aa64f
DV
83};
84
285a6bda 85Dygraph.NAME = "Dygraph";
5efbb60b 86Dygraph.VERSION = "1.1.0";
6a1aa64f
DV
87
88// Various default values
285a6bda
DV
89Dygraph.DEFAULT_ROLL_PERIOD = 1;
90Dygraph.DEFAULT_WIDTH = 480;
91Dygraph.DEFAULT_HEIGHT = 320;
6a1aa64f 92
a96b8ba3
A
93// For max 60 Hz. animation:
94Dygraph.ANIMATION_STEPS = 12;
b1a3b195
DV
95Dygraph.ANIMATION_DURATION = 200;
96
6108122b
DV
97// Label constants for the labelsKMB and labelsKMG2 options.
98// (i.e. '100000' -> '100K')
2fd143d3
DV
99Dygraph.KMB_LABELS = [ 'K', 'M', 'B', 'T', 'Q' ];
100Dygraph.KMG2_BIG_LABELS = [ 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y' ];
101Dygraph.KMG2_SMALL_LABELS = [ 'm', 'u', 'n', 'p', 'f', 'a', 'z', 'y' ];
102
48e614ac
DV
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.
1bc88216 108 * @param {number} x The number to be formatted
48e614ac 109 * @param {Dygraph} opts An options view
48e614ac 110 */
3ce712e6 111Dygraph.numberValueFormatter = function(x, opts) {
48e614ac
DV
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
2fd143d3
DV
122 var kmb = opts('labelsKMB');
123 var kmg2 = opts('labelsKMG2');
124
125 var label;
126
48e614ac
DV
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))) {
2fd143d3 131 label = x.toExponential(digits);
48e614ac 132 } else {
2fd143d3 133 label = '' + Dygraph.round_(x, digits);
48e614ac 134 }
2fd143d3
DV
135
136 if (kmb || kmg2) {
137 var k;
138 var k_labels = [];
139 var m_labels = [];
140 if (kmb) {
141 k = 1000;
6108122b 142 k_labels = Dygraph.KMB_LABELS;
2fd143d3
DV
143 }
144 if (kmg2) {
8a68db7d 145 if (kmb) console.warn("Setting both labelsKMB and labelsKMG2. Pick one!");
2fd143d3 146 k = 1024;
6108122b
DV
147 k_labels = Dygraph.KMG2_BIG_LABELS;
148 m_labels = Dygraph.KMG2_SMALL_LABELS;
2fd143d3
DV
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;
48e614ac
DV
176};
177
178/**
179 * variant for use as an axisLabelFormatter.
180 * @private
181 */
3ce712e6 182Dygraph.numberAxisLabelFormatter = function(x, granularity, opts) {
6addd5b7 183 return Dygraph.numberValueFormatter.call(this, x, opts);
48e614ac
DV
184};
185
186/**
7b2dfd06 187 * @type {!Array.<string>}
48e614ac 188 * @private
7b2dfd06 189 * @constant
48e614ac 190 */
7b2dfd06 191Dygraph.SHORT_MONTH_NAMES_ = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
48e614ac 192
48e614ac
DV
193
194/**
195 * Convert a JS date to a string appropriate to display on an axis that
b77d7a56 196 * is displaying values at the stated granularity. This respects the
8c0599e3 197 * labelsUTC option.
48e614ac 198 * @param {Date} date The date to format
1bc88216 199 * @param {number} granularity One of the Dygraph granularity constants
872a6a00
DV
200 * @param {Dygraph} opts An options view
201 * @return {string} The date formatted as local time
48e614ac
DV
202 * @private
203 */
872a6a00 204Dygraph.dateAxisLabelFormatter = function(date, granularity, opts) {
8c0599e3 205 var utc = opts('labelsUTC');
f1ec8cf5
DV
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
48e614ac 216 if (granularity >= Dygraph.DECADAL) {
872a6a00 217 return '' + year;
48e614ac 218 } else if (granularity >= Dygraph.MONTHLY) {
0b85865a 219 return Dygraph.SHORT_MONTH_NAMES_[month] + '&#160;' + year;
48e614ac 220 } else {
872a6a00 221 var frac = hours * 3600 + mins * 60 + secs + 1e-3 * millis;
758a629f 222 if (frac === 0 || granularity >= Dygraph.DAILY) {
e0269a3d 223 // e.g. '21 Jan' (%d%b)
0b85865a 224 return Dygraph.zeropad(day) + '&#160;' + Dygraph.SHORT_MONTH_NAMES_[month];
48e614ac 225 } else {
872a6a00 226 return Dygraph.hmsString_(hours, mins, secs);
48e614ac
DV
227 }
228 }
229};
ad9515f8
DV
230// alias in case anyone is referencing the old method.
231Dygraph.dateAxisFormatter = Dygraph.dateAxisLabelFormatter;
48e614ac 232
38e3d209 233/**
b77d7a56 234 * Return a string version of a JS date for a value label. This respects the
8c0599e3 235 * labelsUTC option.
872a6a00
DV
236 * @param {Date} date The date to be formatted
237 * @param {Dygraph} opts An options view
aaaf030e 238 * @private
872a6a00
DV
239 */
240Dygraph.dateValueFormatter = function(d, opts) {
8c0599e3 241 return Dygraph.dateString_(d, opts('labelsUTC'));
872a6a00 242};
48e614ac 243
38e3d209
DV
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 */
254Dygraph.Plotters = DygraphCanvasRenderer._Plotters;
255
48e614ac 256
8e4a6af3 257// Default attribute values.
285a6bda 258Dygraph.DEFAULT_ATTRS = {
a9fc39ab 259 highlightCircleSize: 3,
857a6931 260 highlightSeriesOpts: null,
afdb20d8 261 highlightSeriesBackgroundAlpha: 0.5,
285a6bda 262
8e4a6af3
DV
263 labelsDivWidth: 250,
264 labelsDivStyles: {
265 // TODO(danvk): move defaults from createStatusMessage_ here.
285a6bda
DV
266 },
267 labelsSeparateLines: false,
bcd3ebf0 268 labelsShowZeroValues: true,
285a6bda 269 labelsKMB: false,
afefbcdb 270 labelsKMG2: false,
d160cc3b 271 showLabelsOnHighlight: true,
12e4c741 272
2e1fcf1a
DV
273 digitsAfterDecimal: 2,
274 maxNumberWidth: 6,
19589a3e 275 sigFigs: null,
285a6bda
DV
276
277 strokeWidth: 1.0,
857a6931
KW
278 strokeBorderWidth: 0,
279 strokeBorderColor: "white",
8e4a6af3 280
8846615a
DV
281 axisTickSize: 3,
282 axisLabelFontSize: 14,
8846615a 283 rightGap: 5,
285a6bda
DV
284
285 showRoller: false,
285a6bda 286 xValueParser: Dygraph.dateParser,
285a6bda 287
3d67f03b
DV
288 delimiter: ',',
289
285a6bda
DV
290 sigma: 2.0,
291 errorBars: false,
292 fractions: false,
293 wilsonInterval: true, // only relevant if fractions is true
5954ef32 294 customBars: false,
43af96e7
NK
295 fillGraph: false,
296 fillAlpha: 0.15,
f032c51d 297 connectSeparatedPoints: false,
43af96e7
NK
298
299 stackedGraph: false,
30a5cfc6 300 stackedGraphNaNFill: 'all',
afdc483f
NN
301 hideOverlayOnMouseOut: true,
302
c08d4ce2 303 legend: 'onmouseover',
00c281d4 304 stepPlot: false,
062ef401 305 avoidMinZero: false,
fa460473
KW
306 xRangePad: 0,
307 yRangePad: null,
f4b87da2 308 drawAxesAtZero: false,
062ef401 309
ad1798c2 310 // Sizes of the various chart labels.
b4202b3d 311 titleHeight: 28,
86cce9e8
DV
312 xLabelHeight: 18,
313 yLabelWidth: 18,
ad1798c2 314
423f5ed3 315 axisLineColor: "black",
990d6a35
DV
316 axisLineWidth: 0.3,
317 gridLineWidth: 0.3,
318 axisLabelColor: "black",
990d6a35 319 axisLabelWidth: 50,
990d6a35 320 gridLineColor: "rgb(128,128,128)",
423f5ed3 321
48e614ac 322 interactionModel: null, // will be set to Dygraph.Interaction.defaultModel
b1a3b195 323 animatedZooms: false, // (for now)
48e614ac 324
ccd9d7c2
PF
325 // Range selector options
326 showRangeSelector: false,
327 rangeSelectorHeight: 40,
328 rangeSelectorPlotStrokeColor: "#808FAB",
79cb28dd 329 rangeSelectorPlotFillGradientColor: "white",
ccd9d7c2 330 rangeSelectorPlotFillColor: "#A7B1C4",
fb24d32c 331 rangeSelectorBackgroundStrokeColor: "gray",
332 rangeSelectorBackgroundLineWidth: 1,
b77d7a56 333 rangeSelectorPlotLineWidth:1.5,
fb24d32c 334 rangeSelectorForegroundStrokeColor: "black",
335 rangeSelectorForegroundLineWidth: 1,
b77d7a56 336 rangeSelectorAlpha: 0.6,
0a0885d1 337 showInRangeSelector: null,
ccd9d7c2 338
38e3d209
DV
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
eced46cf 347 plugins: [ ],
d9fbba56 348
48e614ac
DV
349 // per-axis options
350 axes: {
351 x: {
d7aa8aa5
DV
352 pixelsPerLabel: 70,
353 axisLabelWidth: 60,
872a6a00
DV
354 axisLabelFormatter: Dygraph.dateAxisLabelFormatter,
355 valueFormatter: Dygraph.dateValueFormatter,
9e906ae6 356 drawGrid: true,
7f6a7190 357 drawAxis: true,
9e906ae6 358 independentTicks: true,
48e614ac
DV
359 ticker: null // will be set in dygraph-tickers.js
360 },
361 y: {
e0269a3d 362 axisLabelWidth: 50,
48e614ac
DV
363 pixelsPerLabel: 30,
364 valueFormatter: Dygraph.numberValueFormatter,
365 axisLabelFormatter: Dygraph.numberAxisLabelFormatter,
9e906ae6 366 drawGrid: true,
7f6a7190 367 drawAxis: true,
9e906ae6 368 independentTicks: true,
48e614ac
DV
369 ticker: null // will be set in dygraph-tickers.js
370 },
371 y2: {
e0269a3d 372 axisLabelWidth: 50,
48e614ac
DV
373 pixelsPerLabel: 30,
374 valueFormatter: Dygraph.numberValueFormatter,
375 axisLabelFormatter: Dygraph.numberAxisLabelFormatter,
e0269a3d 376 drawAxis: true, // only applies when there are two axes of data.
9e906ae6
DE
377 drawGrid: false,
378 independentTicks: false,
48e614ac
DV
379 ticker: null // will be set in dygraph-tickers.js
380 }
381 }
285a6bda
DV
382};
383
39b0e098
RK
384// Directions for panning and zooming. Use bit operations when combined
385// values are possible.
386Dygraph.HORIZONTAL = 1;
387Dygraph.VERTICAL = 2;
388
e2c21500
DV
389// Installed plugins, in order of precedence (most-general to most-specific).
390// Plugins are installed after they are defined, in plugins/install.js.
391Dygraph.PLUGINS = [
392];
393
5c528fa2
DV
394// Used for initializing annotation CSS rules only once.
395Dygraph.addedAnnotationCSS = false;
396
285a6bda
DV
397Dygraph.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.
758a629f 401 if (labels !== null) {
285a6bda
DV
402 var new_labels = ["Date"];
403 for (var i = 0; i < labels.length; i++) new_labels.push(labels[i]);
fc80a396 404 Dygraph.update(attrs, { 'labels': new_labels });
285a6bda
DV
405 }
406 this.__init__(div, file, attrs);
8e4a6af3
DV
407};
408
6a1aa64f 409/**
285a6bda 410 * Initializes the Dygraph. This creates a new DIV and constructs the PlotKit
7aedf6fe 411 * and context &lt;canvas&gt; inside of it. See the constructor for details.
6a1aa64f 412 * on the parameters.
12e4c741 413 * @param {Element} div the Element to render the graph into.
1bc88216 414 * @param {string | Function} file Source data
6a1aa64f
DV
415 * @param {Object} attrs Miscellaneous other options
416 * @private
417 */
285a6bda
DV
418Dygraph.prototype.__init__ = function(div, file, attrs) {
419 // Support two-argument constructor
758a629f 420 if (attrs === null || attrs === undefined) { attrs = {}; }
285a6bda 421
bfb3e0a4 422 attrs = Dygraph.copyUserAttrs_(attrs);
48e614ac 423
8a870376
RK
424 if (typeof(div) == 'string') {
425 div = document.getElementById(div);
426 }
427
48e614ac 428 if (!div) {
8a68db7d 429 console.error("Constructing dygraph with a non-existent div!");
48e614ac
DV
430 return;
431 }
432
6a1aa64f 433 // Copy the important bits into the object
32988383 434 // TODO(danvk): most of these should just stay in the attrs_ dictionary.
6a1aa64f 435 this.maindiv_ = div;
6a1aa64f 436 this.file_ = file;
285a6bda 437 this.rollPeriod_ = attrs.rollPeriod || Dygraph.DEFAULT_ROLL_PERIOD;
6a1aa64f 438 this.previousVerticalX_ = -1;
6a1aa64f 439 this.fractions_ = attrs.fractions || false;
6a1aa64f 440 this.dateWindow_ = attrs.dateWindow || null;
8b83c6cc 441
5c528fa2 442 this.annotations_ = [];
7aedf6fe 443
45f2c689 444 // Zoomed indicators - These indicate when the graph has been zoomed and on what axis.
57baab03
NN
445 this.zoomed_x_ = false;
446 this.zoomed_y_ = false;
45f2c689 447
f7d6278e
DV
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
0cb9bd91
DV
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.
758a629f 456 if (div.style.width === '' && attrs.width) {
0cb9bd91 457 div.style.width = attrs.width + "px";
285a6bda 458 }
758a629f 459 if (div.style.height === '' && attrs.height) {
0cb9bd91 460 div.style.height = attrs.height + "px";
32988383 461 }
758a629f 462 if (div.style.height === '' && div.clientHeight === 0) {
0cb9bd91 463 div.style.height = Dygraph.DEFAULT_HEIGHT + "px";
758a629f 464 if (div.style.width === '') {
0cb9bd91
DV
465 div.style.width = Dygraph.DEFAULT_WIDTH + "px";
466 }
c21d2c2d 467 }
c28088bc
KW
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;
32988383 473
344ba8c0 474 // TODO(danvk): set fillGraph to be part of attrs_ here, not user_attrs_.
758a629f
DV
475 if (attrs.stackedGraph) {
476 attrs.fillGraph = true;
43af96e7
NK
477 // TODO(nikhilk): Add any other stackedGraph checks here.
478 }
479
a9172eb1
RK
480 // DEPRECATION WARNING: All option processing should be moved from
481 // attrs_ and user_attrs_ to options_, which holds all this information.
482 //
285a6bda
DV
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 //
c21d2c2d 486 // this.user_attrs_ only options explicitly set by the user.
285a6bda
DV
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_ = {};
fc80a396 493 Dygraph.update(this.user_attrs_, attrs);
6a1aa64f 494
48e614ac 495 // This sequence ensures that Dygraph.DEFAULT_ATTRS is never modified.
285a6bda 496 this.attrs_ = {};
48e614ac 497 Dygraph.updateDeep(this.attrs_, Dygraph.DEFAULT_ATTRS);
6a1aa64f 498
16269f6e 499 this.boundaryIds_ = [];
82c6fe4d 500 this.setIndexByName_ = {};
857a6931 501 this.datasetIndex_ = [];
6a1aa64f 502
6a4587ac 503 this.registeredEvents_ = [];
de8f284f 504 this.eventListeners_ = {};
6a4587ac 505
c1780ad0
RK
506 this.attributes_ = new DygraphOptions(this);
507
6a1aa64f
DV
508 // Create the containing DIV and other interactive elements
509 this.createInterface_();
510
e2c21500
DV
511 // Activate plugins.
512 this.plugins_ = [];
d9fbba56
RK
513 var plugins = Dygraph.PLUGINS.concat(this.getOption('plugins'));
514 for (var i = 0; i < plugins.length; i++) {
6f5f0b2b 515 // the plugins option may contain either plugin classes or instances.
835351fd
DV
516 // Plugin instances contain an activate method.
517 var Plugin = plugins[i]; // either a constructor or an instance.
6f5f0b2b
DV
518 var pluginInstance;
519 if (typeof(Plugin.activate) !== 'undefined') {
520 pluginInstance = Plugin;
521 } else {
522 pluginInstance = new Plugin();
523 }
524
e2c21500
DV
525 var pluginDict = {
526 plugin: pluginInstance,
527 events: {},
528 options: {},
529 pluginOptions: {}
530 };
531
6a4457b4
KW
532 var handlers = pluginInstance.activate(this);
533 for (var eventName in handlers) {
3ce712e6 534 if (!handlers.hasOwnProperty(eventName)) continue;
28aa77ac 535 // TODO(danvk): validate eventName.
6a4457b4
KW
536 pluginDict.events[eventName] = handlers[eventName];
537 }
e2c21500
DV
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].
e2c21500
DV
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
487f5523
PF
559 this.createDragInterface_();
560
738fc797 561 this.start_();
6a1aa64f
DV
562};
563
dcb25130 564/**
e2c21500 565 * Triggers a cascade of events to the various plugins which are interested in them.
6f5f0b2b
DV
566 * Returns true if the "default behavior" should be prevented, i.e. if one
567 * of the event listeners called event.preventDefault().
e2c21500
DV
568 * @private
569 */
570Dygraph.prototype.cascadeEvents_ = function(name, extra_props) {
6f5f0b2b 571 if (!(name in this.eventListeners_)) return false;
e2c21500
DV
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() {
5bd29cf4 584 e.propagationStopped = true;
e2c21500
DV
585 }
586 };
587 Dygraph.update(e, extra_props);
588
589 var callback_plugin_pairs = this.eventListeners_[name];
da1c187b
KW
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 }
e2c21500
DV
597 }
598 return e.defaultPrevented;
599};
600
601/**
b1a96215
DV
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 */
607Dygraph.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/**
dcb25130
NN
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
42a9ebb8
DV
623 * or when the dateWindow or valueRange are updated (unless the
624 * isZoomedIgnoreProgrammaticZoom option is also specified).
dcb25130 625 */
57baab03 626Dygraph.prototype.isZoomed = function(axis) {
42a9ebb8
DV
627 if (axis === null || axis === undefined) {
628 return this.zoomed_x_ || this.zoomed_y_;
629 }
758a629f
DV
630 if (axis === 'x') return this.zoomed_x_;
631 if (axis === 'y') return this.zoomed_y_;
94ea5744 632 throw "axis parameter is [" + axis + "] must be null, 'x' or 'y'.";
57baab03
NN
633};
634
629a09ae
DV
635/**
636 * Returns information about the Dygraph object, including its containing ID.
637 */
22bd1dfb
RK
638Dygraph.prototype.toString = function() {
639 var maindiv = this.maindiv_;
758a629f 640 var id = (maindiv && maindiv.id) ? maindiv.id : maindiv;
22bd1dfb 641 return "[Dygraph " + id + "]";
758a629f 642};
22bd1dfb 643
629a09ae
DV
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.
1bc88216
DV
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
629a09ae
DV
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 */
227b93cc 655Dygraph.prototype.attr_ = function(name, seriesName) {
103fd879
DV
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 }
028ddf8a 665 }
5daa462d 666 return seriesName ? this.attributes_.getForSeries(name, seriesName) : this.attributes_.get(name);
285a6bda
DV
667};
668
6a1aa64f 669/**
e2c21500
DV
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 *
1bc88216
DV
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.
e2c21500
DV
682 */
683Dygraph.prototype.getOption = function(name, opt_seriesName) {
684 return this.attr_(name, opt_seriesName);
685};
686
5266fc00 687/**
1c420f2f 688 * Like getOption(), but specifically returns a number.
5266fc00
DV
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 */
695Dygraph.prototype.getNumericOption = function(name, opt_seriesName) {
696 return /** @type{number} */(this.getOption(name, opt_seriesName));
697};
698
699/**
1c420f2f 700 * Like getOption(), but specifically returns a string.
5266fc00
DV
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 */
707Dygraph.prototype.getStringOption = function(name, opt_seriesName) {
708 return /** @type{string} */(this.getOption(name, opt_seriesName));
709};
710
711/**
1c420f2f 712 * Like getOption(), but specifically returns a boolean.
5266fc00
DV
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 */
719Dygraph.prototype.getBooleanOption = function(name, opt_seriesName) {
720 return /** @type{boolean} */(this.getOption(name, opt_seriesName));
721};
722
723/**
1c420f2f 724 * Like getOption(), but specifically returns a function.
5266fc00
DV
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 */
731Dygraph.prototype.getFunctionOption = function(name, opt_seriesName) {
732 return /** @type{function(...)} */(this.getOption(name, opt_seriesName));
733};
734
48dc3815
RK
735Dygraph.prototype.getOptionForAxis = function(name, axis) {
736 return this.attributes_.getForAxis(name, axis);
83b0c192
DV
737};
738
e2c21500 739/**
48e614ac 740 * @private
5266fc00 741 * @param {string} axis The name of the axis (i.e. 'x', 'y' or 'y2')
48e614ac
DV
742 * @return { ... } A function mapping string -> option value
743 */
744Dygraph.prototype.optionsViewForAxis_ = function(axis) {
745 var self = this;
746 return function(opt) {
758a629f 747 var axis_opts = self.user_attrs_.axes;
2fd143d3 748 if (axis_opts && axis_opts[axis] && axis_opts[axis].hasOwnProperty(opt)) {
48e614ac
DV
749 return axis_opts[axis][opt];
750 }
5b9b2142
RK
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
48e614ac
DV
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
758a629f 765 axis_opts = self.attrs_.axes;
2fd143d3 766 if (axis_opts && axis_opts[axis] && axis_opts[axis].hasOwnProperty(opt)) {
48e614ac
DV
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/**
6a1aa64f 781 * Returns the current rolling period, as set by the user or an option.
1bc88216 782 * @return {number} The number of points in the rolling window
6a1aa64f 783 */
285a6bda 784Dygraph.prototype.rollPeriod = function() {
6a1aa64f 785 return this.rollPeriod_;
76171648
DV
786};
787
599fb4ad
DV
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 */
794Dygraph.prototype.xAxisRange = function() {
4cac8c7a
RK
795 return this.dateWindow_ ? this.dateWindow_ : this.xAxisExtremes();
796};
599fb4ad 797
4cac8c7a
RK
798/**
799 * Returns the lower- and upper-bound x-axis values of the
800 * data set.
801 */
802Dygraph.prototype.xAxisExtremes = function() {
b0963cdb 803 var pad = this.getNumericOption('xRangePad') / this.plotter_.area.w;
4bac38d8 804 if (this.numRows() === 0) {
fa460473
KW
805 return [0 - pad, 1 + pad];
806 }
599fb4ad
DV
807 var left = this.rawData_[0][0];
808 var right = this.rawData_[this.rawData_.length - 1][0];
fa460473
KW
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 }
599fb4ad
DV
815 return [left, right];
816};
817
3230c662 818/**
d58ae307
DV
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.
3230c662
DV
822 * Returns a two-element array: [bottom, top].
823 */
d58ae307 824Dygraph.prototype.yAxisRange = function(idx) {
d63e6799 825 if (typeof(idx) == "undefined") idx = 0;
d64b8fea
RK
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] ];
d58ae307
DV
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 */
838Dygraph.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;
3230c662
DV
844};
845
d58ae307 846// TODO(danvk): use these functions throughout dygraphs.
3230c662
DV
847/**
848 * Convert from data coordinates to canvas/div X/Y coordinates.
d58ae307
DV
849 * If specified, do this conversion for the coordinate system of a particular
850 * axis. Uses the first axis by default.
3230c662 851 * Returns a two-element array: [X, Y]
ff022deb 852 *
0747928a 853 * Note: use toDomXCoord instead of toDomCoords(x, null) and use toDomYCoord
ff022deb 854 * instead of toDomCoords(null, y, axis).
3230c662 855 */
d58ae307 856Dygraph.prototype.toDomCoords = function(x, y, axis) {
ff022deb
RK
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
0037b2a4
RK
863 * axis.
864 * Returns a single value or null if x is null.
ff022deb
RK
865 */
866Dygraph.prototype.toDomXCoord = function(x) {
758a629f 867 if (x === null) {
ff022deb 868 return null;
758a629f 869 }
ff022deb 870
3230c662 871 var area = this.plotter_.area;
ff022deb
RK
872 var xRange = this.xAxisRange();
873 return area.x + (x - xRange[0]) / (xRange[1] - xRange[0]) * area.w;
758a629f 874};
3230c662 875
ff022deb
RK
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 */
882Dygraph.prototype.toDomYCoord = function(y, axis) {
0747928a 883 var pct = this.toPercentYCoord(y, axis);
3230c662 884
758a629f 885 if (pct === null) {
ff022deb
RK
886 return null;
887 }
e4416fb9 888 var area = this.plotter_.area;
ff022deb 889 return area.y + pct * area.h;
758a629f 890};
3230c662
DV
891
892/**
893 * Convert from canvas/div coords to data coordinates.
d58ae307
DV
894 * If specified, do this conversion for the coordinate system of a particular
895 * axis. Uses the first axis by default.
ff022deb
RK
896 * Returns a two-element array: [X, Y].
897 *
0747928a 898 * Note: use toDataXCoord instead of toDataCoords(x, null) and use toDataYCoord
ff022deb 899 * instead of toDataCoords(null, y, axis).
3230c662 900 */
d58ae307 901Dygraph.prototype.toDataCoords = function(x, y, axis) {
ff022deb
RK
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 */
910Dygraph.prototype.toDataXCoord = function(x) {
758a629f 911 if (x === null) {
ff022deb 912 return null;
3230c662
DV
913 }
914
ff022deb
RK
915 var area = this.plotter_.area;
916 var xRange = this.xAxisRange();
5b9b2142
RK
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 }
ff022deb
RK
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 */
956Dygraph.prototype.toDataYCoord = function(y, axis) {
758a629f 957 if (y === null) {
ff022deb 958 return null;
3230c662
DV
959 }
960
ff022deb
RK
961 var area = this.plotter_.area;
962 var yRange = this.yAxisRange(axis);
963
b70247dc 964 if (typeof(axis) == "undefined") axis = 0;
1f8c95d8 965 if (!this.attributes_.getForAxis("logscale", axis)) {
d9816e62 966 return yRange[0] + (area.y + area.h - y) / area.h * (yRange[1] - yRange[0]);
ff022deb
RK
967 } else {
968 // Computing the inverse of toDomCoord.
758a629f 969 var pct = (y - area.y) / area.h;
ff022deb
RK
970
971 // Computing the inverse of toPercentYCoord. The function was arrived at with
972 // the following steps:
973 //
974 // Original calcuation:
5b9b2142 975 // pct = (log(yRange[1]) - log(y)) / (log(yRange[1]) - log(yRange[0]));
ff022deb 976 //
5b9b2142
RK
977 // Multiply both sides by the right-side demoninator.
978 // pct * (log(yRange[1]) - log(yRange[0])) = log(yRange[1]) - log(y);
ff022deb 979 //
5b9b2142
RK
980 // subtract log(yRange[1]) from both sides.
981 // (pct * (log(yRange[1]) - log(yRange[0]))) - log(yRange[1]) = -log(y);
ff022deb 982 //
5b9b2142
RK
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]);
d59b6f34 992 var logr1 = Dygraph.log10(yRange[1]);
5b9b2142 993 var exponent = logr1 - (pct * (logr1 - logr0));
d59b6f34 994 var value = Math.pow(Dygraph.LOG_SCALE, exponent);
ff022deb
RK
995 return value;
996 }
3230c662
DV
997};
998
e99fde05 999/**
ff022deb 1000 * Converts a y for an axis to a percentage from the top to the
4cac8c7a 1001 * bottom of the drawing area.
ff022deb
RK
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.
629a09ae 1010 *
1bc88216
DV
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.
ff022deb
RK
1014 */
1015Dygraph.prototype.toPercentYCoord = function(y, axis) {
758a629f 1016 if (y === null) {
ff022deb
RK
1017 return null;
1018 }
7d0e7a0d 1019 if (typeof(axis) == "undefined") axis = 0;
ff022deb 1020
ff022deb
RK
1021 var yRange = this.yAxisRange(axis);
1022
1023 var pct;
1761e6ed 1024 var logscale = this.attributes_.getForAxis("logscale", axis);
5b9b2142
RK
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 {
4cac8c7a
RK
1030 // yRange[1] - y is unit distance from the bottom.
1031 // yRange[1] - yRange[0] is the scale of the range.
ff022deb
RK
1032 // (yRange[1] - y) / (yRange[1] - yRange[0]) is the % from the bottom.
1033 pct = (yRange[1] - y) / (yRange[1] - yRange[0]);
ff022deb
RK
1034 }
1035 return pct;
758a629f 1036};
ff022deb
RK
1037
1038/**
4cac8c7a
RK
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.
1bc88216
DV
1048 * @param {number} x The data x-coordinate.
1049 * @return {number} A fraction in [0, 1] where 0 = the left edge.
4cac8c7a
RK
1050 */
1051Dygraph.prototype.toPercentXCoord = function(x) {
758a629f 1052 if (x === null) {
4cac8c7a
RK
1053 return null;
1054 }
1055
4cac8c7a 1056 var xRange = this.xAxisRange();
5b9b2142
RK
1057 var pct;
1058 var logscale = this.attributes_.getForAxis("logscale", 'x') ;
46fd9089 1059 if (logscale === true) { // logscale can be null so we test for true explicitly.
5b9b2142
RK
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;
629a09ae 1070};
4cac8c7a
RK
1071
1072/**
e99fde05 1073 * Returns the number of columns (including the independent variable).
1bc88216 1074 * @return {number} The number of columns.
e99fde05
DV
1075 */
1076Dygraph.prototype.numColumns = function() {
fa460473 1077 if (!this.rawData_) return 0;
395e98a3 1078 return this.rawData_[0] ? this.rawData_[0].length : this.attr_("labels").length;
e99fde05
DV
1079};
1080
1081/**
1082 * Returns the number of rows (excluding any header/label row).
1bc88216 1083 * @return {number} The number of rows, less any header.
e99fde05
DV
1084 */
1085Dygraph.prototype.numRows = function() {
fa460473 1086 if (!this.rawData_) return 0;
e99fde05
DV
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.
1bc88216
DV
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.
e99fde05
DV
1099 */
1100Dygraph.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
629a09ae 1107/**
285a6bda 1108 * Generates interface elements for the Dygraph: a containing div, a div to
6a1aa64f 1109 * display the current point, and a textbox to adjust the rolling average
697e70b2 1110 * period. Also creates the Renderer/Layout elements.
6a1aa64f
DV
1111 * @private
1112 */
285a6bda 1113Dygraph.prototype.createInterface_ = function() {
6a1aa64f
DV
1114 // Create the all-enclosing graph div
1115 var enclosing = this.maindiv_;
1116
b0c3b730 1117 this.graphDiv = document.createElement("div");
aeca29ac 1118
e0629007
DV
1119 // TODO(danvk): any other styles that are useful to set here?
1120 this.graphDiv.style.textAlign = 'left'; // This is a CSS "reset"
cb8bb6a6 1121 this.graphDiv.style.position = 'relative';
b0c3b730
DV
1122 enclosing.appendChild(this.graphDiv);
1123
1124 // Create the canvas for interactive parts of the chart.
f8cfec73 1125 this.canvas_ = Dygraph.createCanvas();
b0c3b730 1126 this.canvas_.style.position = "absolute";
aeca29ac 1127
c28088bc
KW
1128 // ... and for static parts of the chart.
1129 this.hidden_ = this.createPlotKitCanvas_(this.canvas_);
1130
2cf95fff 1131 this.canvas_ctx_ = Dygraph.getContext(this.canvas_);
2cf95fff 1132 this.hidden_ctx_ = Dygraph.getContext(this.hidden_);
76171648 1133
37819481
PH
1134 this.resizeElements_();
1135
eb7bf005
EC
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_);
920208fb
PF
1139 this.mouseEventElement_ = this.createMouseEventElement_();
1140
1141 // Create the grapher
1142 this.layout_ = new DygraphLayout(this);
1143
76171648 1144 var dygraph = this;
de8f284f 1145
9fd9bbbb 1146 this.mouseMoveHandler_ = function(e) {
1147 dygraph.mouseMove_(e);
1148 };
de8f284f 1149
9fd9bbbb 1150 this.mouseOutHandler_ = function(e) {
def24194
DV
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;
bcb545f4
LB
1156 if (Dygraph.isNodeContainedBy(target, dygraph.graphDiv) &&
1157 !Dygraph.isNodeContainedBy(relatedTarget, dygraph.graphDiv)) {
def24194
DV
1158 dygraph.mouseOut_(e);
1159 }
9fd9bbbb 1160 };
1161
aeca29ac
RK
1162 this.addAndTrackEvent(window, 'mouseout', this.mouseOutHandler_);
1163 this.addAndTrackEvent(this.mouseEventElement_, 'mousemove', this.mouseMoveHandler_);
697e70b2 1164
9fd9bbbb 1165 // Don't recreate and register the resize handler on subsequent calls.
1166 // This happens when the graph is resized.
1167 if (!this.resizeHandler_) {
e0b3afad
RK
1168 this.resizeHandler_ = function(e) {
1169 dygraph.resize();
1170 };
1c6b239c 1171
e0b3afad
RK
1172 // Update when the window is resized.
1173 // TODO(danvk): drop frames depending on complexity of the chart.
aeca29ac 1174 this.addAndTrackEvent(window, 'resize', this.resizeHandler_);
e0b3afad 1175 }
4cfcc38c
DV
1176};
1177
aeca29ac
RK
1178Dygraph.prototype.resizeElements_ = function() {
1179 this.graphDiv.style.width = this.width_ + "px";
1180 this.graphDiv.style.height = this.height_ + "px";
37819481
PH
1181
1182 var canvasScale = Dygraph.getContextPixelRatio(this.canvas_ctx_);
1183 this.canvas_.width = this.width_ * canvasScale;
1184 this.canvas_.height = this.height_ * canvasScale;
aeca29ac
RK
1185 this.canvas_.style.width = this.width_ + "px"; // for IE
1186 this.canvas_.style.height = this.height_ + "px"; // for IE
37819481
PH
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;
c28088bc
KW
1194 this.hidden_.style.width = this.width_ + "px"; // for IE
1195 this.hidden_.style.height = this.height_ + "px"; // for IE
37819481
PH
1196 if (hiddenScale !== 1) {
1197 this.hidden_ctx_.scale(hiddenScale, hiddenScale);
1198 }
f914bed1 1199};
aeca29ac 1200
4cfcc38c
DV
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 */
1206Dygraph.prototype.destroy = function() {
aeca29ac
RK
1207 this.canvas_ctx_.restore();
1208 this.hidden_ctx_.restore();
1209
92c5f414
DV
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
4cfcc38c
DV
1216 var removeRecursive = function(node) {
1217 while (node.hasChildNodes()) {
1218 removeRecursive(node.firstChild);
1219 node.removeChild(node.firstChild);
1220 }
1221 };
de8f284f 1222
aeca29ac 1223 this.removeTrackedEvents_();
6a4587ac
RK
1224
1225 // remove mouse event handlers (This may not be necessary anymore)
def24194 1226 Dygraph.removeEvent(window, 'mouseout', this.mouseOutHandler_);
7d6df48d 1227 Dygraph.removeEvent(this.mouseEventElement_, 'mousemove', this.mouseMoveHandler_);
7d6df48d
RK
1228
1229 // remove window handlers
92c5f414 1230 Dygraph.removeEvent(window,'resize', this.resizeHandler_);
7d6df48d
RK
1231 this.resizeHandler_ = null;
1232
4cfcc38c
DV
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 };
4cfcc38c
DV
1242 // These may not all be necessary, but it can't hurt...
1243 nullOut(this.layout_);
1244 nullOut(this.plotter_);
1245 nullOut(this);
1246};
6a1aa64f
DV
1247
1248/**
629a09ae
DV
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_.
8846615a 1252 * @param {Object} canvas The Dygraph canvas over which to overlay the plot
6a1aa64f
DV
1253 * @return {Object} The newly-created canvas
1254 * @private
1255 */
285a6bda 1256Dygraph.prototype.createPlotKitCanvas_ = function(canvas) {
f8cfec73 1257 var h = Dygraph.createCanvas();
6a1aa64f 1258 h.style.position = "absolute";
9ac5e4ae
DV
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.
6a1aa64f
DV
1262 h.style.top = canvas.style.top;
1263 h.style.left = canvas.style.left;
1264 h.width = this.width_;
1265 h.height = this.height_;
f8cfec73
DV
1266 h.style.width = this.width_ + "px"; // for IE
1267 h.style.height = this.height_ + "px"; // for IE
6a1aa64f
DV
1268 return h;
1269};
1270
629a09ae 1271/**
920208fb
PF
1272 * Creates an overlay element used to handle mouse events.
1273 * @return {Object} The mouse event element.
1274 * @private
1275 */
1276Dygraph.prototype.createMouseEventElement_ = function() {
9901b0c1 1277 return this.canvas_;
920208fb
PF
1278};
1279
1280/**
6a1aa64f
DV
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.
6a1aa64f
DV
1285 * @private
1286 */
285a6bda 1287Dygraph.prototype.setColors_ = function() {
ee53deb9
DV
1288 var labels = this.getLabels();
1289 var num = labels.length - 1;
6a1aa64f 1290 this.colors_ = [];
ee53deb9 1291 this.colorsMap_ = {};
48423521
RK
1292
1293 // These are used for when no custom colors are specified.
b0963cdb
DV
1294 var sat = this.getNumericOption('colorSaturation') || 1.0;
1295 var val = this.getNumericOption('colorValue') || 0.5;
48423521
RK
1296 var half = Math.ceil(num / 2);
1297
b0963cdb 1298 var colors = this.getOption('colors');
48423521
RK
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 }
629a09ae 1319};
6a1aa64f 1320
43af96e7
NK
1321/**
1322 * Return the list of colors. This is either the list of colors passed in the
629a09ae 1323 * attributes or the autogenerated list of rgb(r,g,b) strings.
e2c21500 1324 * This does not return colors for invisible series.
8ef9d44d 1325 * @return {Array.<string>} The list of colors.
43af96e7
NK
1326 */
1327Dygraph.prototype.getColors = function() {
1328 return this.colors_;
1329};
1330
6a1aa64f 1331/**
e2c21500
DV
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.
6a1aa64f 1339 */
e2c21500
DV
1340Dygraph.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;
b0c3b730 1347 }
6a1aa64f 1348 }
e2c21500 1349 if (idx == -1) return null;
0abfbd7e 1350
e2c21500
DV
1351 return {
1352 name: series_name,
1353 column: idx,
1354 visible: this.visibility()[idx - 1],
189f8030 1355 color: this.colorsMap_[series_name],
16f00742 1356 axis: 1 + this.attributes_.axisForSeries(series_name)
e2c21500 1357 };
0abfbd7e
DV
1358};
1359
1360/**
6a1aa64f 1361 * Create the text box to adjust the averaging period
6a1aa64f
DV
1362 * @private
1363 */
285a6bda 1364Dygraph.prototype.createRollInterface_ = function() {
8c69de65
DV
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
b0963cdb 1373 var display = this.getBooleanOption('showRoller') ? 'block' : 'none';
26ca7938 1374
0c38f187 1375 var area = this.plotter_.area;
b0c3b730
DV
1376 var textAttr = { "position": "absolute",
1377 "zIndex": 10,
0c38f187
DV
1378 "top": (area.y + area.h - 25) + "px",
1379 "left": (area.x + 1) + "px",
b0c3b730 1380 "display": display
6a1aa64f 1381 };
8c69de65
DV
1382 this.roller_.size = "2";
1383 this.roller_.value = this.rollPeriod_;
b0c3b730 1384 for (var name in textAttr) {
85b99f0b 1385 if (textAttr.hasOwnProperty(name)) {
8c69de65 1386 this.roller_.style[name] = textAttr[name];
85b99f0b 1387 }
b0c3b730
DV
1388 }
1389
76171648 1390 var dygraph = this;
8c69de65 1391 this.roller_.onchange = function() { dygraph.adjustRoll(dygraph.roller_.value); };
76171648
DV
1392};
1393
629a09ae 1394/**
062ef401
JB
1395 * Set up all the mouse handlers needed to capture dragging behavior for zoom
1396 * events.
1397 * @private
1398 */
1399Dygraph.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?
8442269f
RK
1405 dragStartX: null, // pixel coordinates
1406 dragStartY: null, // pixel coordinates
1407 dragEndX: null, // pixel coordinates
1408 dragEndY: null, // pixel coordinates
062ef401 1409 dragDirection: null,
8442269f
RK
1410 prevEndX: null, // pixel coordinates
1411 prevEndY: null, // pixel coordinates
062ef401 1412 prevDragDirection: null,
421f1773 1413 cancelNextDblclick: false, // see comment in dygraph-interaction-model.js
062ef401 1414
ec291cbe
RK
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,
062ef401
JB
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
8442269f
RK
1427 // Top-left corner of the canvas, in DOM coords
1428 // TODO(konigsberg): Rename topLeftCanvasX, topLeftCanvasY.
062ef401
JB
1429 px: 0,
1430 py: 0,
1431
965a030e 1432 // Values for use with panEdgeFraction, which limit how far outside the
4cac8c7a
RK
1433 // graph's data boundaries it can be panned.
1434 boundedDates: null, // [minDate, maxDate]
1435 boundedValues: null, // [[minValue, maxValue] ...]
1436
2bad4d92
DV
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
6a4587ac
RK
1441 // contextB is the same thing as this context object but renamed.
1442 initializeMouseDown: function(event, g, contextB) {
062ef401
JB
1443 // prevents mouse drags from selecting page text.
1444 if (event.preventDefault) {
1445 event.preventDefault(); // Firefox, Chrome, etc.
6a1aa64f 1446 } else {
062ef401
JB
1447 event.returnValue = false; // IE
1448 event.cancelBubble = true;
6a1aa64f
DV
1449 }
1450
f381ac71 1451 var canvasPos = Dygraph.findPos(g.canvas_);
464b5f50
DV
1452 contextB.px = canvasPos.x;
1453 contextB.py = canvasPos.y;
806f92c1
DV
1454 contextB.dragStartX = Dygraph.dragGetX_(event, contextB);
1455 contextB.dragStartY = Dygraph.dragGetY_(event, contextB);
6a4587ac 1456 contextB.cancelNextDblclick = false;
2bad4d92 1457 contextB.tarp.cover();
3f50dabb
DV
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();
6a1aa64f 1478 }
062ef401 1479 };
2b188b3d 1480
b0963cdb 1481 var interactionModel = this.getOption("interactionModel");
8b83c6cc 1482
062ef401
JB
1483 // Self is the graph.
1484 var self = this;
6faebb69 1485
062ef401
JB
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;
aeca29ac 1495 this.addAndTrackEvent(this.mouseEventElement_, eventName,
062ef401
JB
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.
3f50dabb
DV
1501 if (!interactionModel.willDestroyContextMyself) {
1502 var mouseUpHandler = function(event) {
1503 context.destroy();
1504 };
cb1261cb 1505
3f50dabb
DV
1506 this.addAndTrackEvent(document, 'mouseup', mouseUpHandler);
1507 }
6a1aa64f
DV
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.
ccd9d7c2 1515 *
1bc88216
DV
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
6a1aa64f
DV
1530 * @private
1531 */
7201b11e
JB
1532Dygraph.prototype.drawZoomRect_ = function(direction, startX, endX, startY,
1533 endY, prevDirection, prevEndX,
1534 prevEndY) {
2cf95fff 1535 var ctx = this.canvas_ctx_;
6a1aa64f
DV
1536
1537 // Clean up from the previous rect if necessary
39b0e098 1538 if (prevDirection == Dygraph.HORIZONTAL) {
fa54c193
FXB
1539 ctx.clearRect(Math.min(startX, prevEndX), this.layout_.getPlotArea().y,
1540 Math.abs(startX - prevEndX), this.layout_.getPlotArea().h);
383d8473 1541 } else if (prevDirection == Dygraph.VERTICAL) {
fa54c193
FXB
1542 ctx.clearRect(this.layout_.getPlotArea().x, Math.min(startY, prevEndY),
1543 this.layout_.getPlotArea().w, Math.abs(startY - prevEndY));
6a1aa64f
DV
1544 }
1545
1546 // Draw a light-grey rectangle to show the new viewing area
39b0e098 1547 if (direction == Dygraph.HORIZONTAL) {
8b83c6cc
RK
1548 if (endX && startX) {
1549 ctx.fillStyle = "rgba(128,128,128,0.33)";
fa54c193
FXB
1550 ctx.fillRect(Math.min(startX, endX), this.layout_.getPlotArea().y,
1551 Math.abs(endX - startX), this.layout_.getPlotArea().h);
8b83c6cc 1552 }
920208fb 1553 } else if (direction == Dygraph.VERTICAL) {
8b83c6cc
RK
1554 if (endY && startY) {
1555 ctx.fillStyle = "rgba(128,128,128,0.33)";
fa54c193
FXB
1556 ctx.fillRect(this.layout_.getPlotArea().x, Math.min(startY, endY),
1557 this.layout_.getPlotArea().w, Math.abs(endY - startY));
8b83c6cc 1558 }
6a1aa64f 1559 }
920208fb
PF
1560};
1561
1562/**
1563 * Clear the zoom rectangle (and perform no zoom).
1564 * @private
1565 */
1566Dygraph.prototype.clearZoomRect_ = function() {
1567 this.currentZoomRectArgs_ = null;
7c39bb3a 1568 this.canvas_ctx_.clearRect(0, 0, this.width_, this.height_);
6a1aa64f
DV
1569};
1570
1571/**
8b83c6cc
RK
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.
d58ae307 1576 *
1bc88216
DV
1577 * @param {number} lowX The leftmost pixel value that should be visible.
1578 * @param {number} highX The rightmost pixel value that should be visible.
6a1aa64f
DV
1579 * @private
1580 */
8b83c6cc 1581Dygraph.prototype.doZoomX_ = function(lowX, highX) {
920208fb 1582 this.currentZoomRectArgs_ = null;
6a1aa64f 1583 // Find the earliest and latest dates contained in this canvasx range.
8b83c6cc 1584 // Convert the call to date ranges of the raw data.
ff022deb
RK
1585 var minDate = this.toDataXCoord(lowX);
1586 var maxDate = this.toDataXCoord(highX);
8b83c6cc
RK
1587 this.doZoomXDates_(minDate, maxDate);
1588};
6a1aa64f 1589
8b83c6cc
RK
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.
d58ae307 1594 *
1bc88216
DV
1595 * @param {number} minDate The minimum date that should be visible.
1596 * @param {number} maxDate The maximum date that should be visible.
8b83c6cc
RK
1597 * @private
1598 */
1599Dygraph.prototype.doZoomXDates_ = function(minDate, maxDate) {
5b9b2142
RK
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
b1a3b195
DV
1602 // between values, it can jerk around.)
1603 var old_window = this.xAxisRange();
1604 var new_window = [minDate, maxDate];
57baab03 1605 this.zoomed_x_ = true;
b1a3b195
DV
1606 var that = this;
1607 this.doAnimatedZoom(old_window, new_window, null, null, function() {
b0963cdb 1608 if (that.getFunctionOption("zoomCallback")) {
4ee251cb 1609 that.getFunctionOption("zoomCallback").call(that,
b0963cdb 1610 minDate, maxDate, that.yAxisRanges());
b1a3b195
DV
1611 }
1612 });
8b83c6cc
RK
1613};
1614
1615/**
1616 * Zoom to something containing [lowY, highY]. These are pixel coordinates in
d58ae307
DV
1617 * the canvas. This function redraws the graph.
1618 *
1bc88216
DV
1619 * @param {number} lowY The topmost pixel value that should be visible.
1620 * @param {number} highY The lowest pixel value that should be visible.
8b83c6cc
RK
1621 * @private
1622 */
1623Dygraph.prototype.doZoomY_ = function(lowY, highY) {
920208fb 1624 this.currentZoomRectArgs_ = null;
d58ae307
DV
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.
b1a3b195
DV
1629 var oldValueRanges = this.yAxisRanges();
1630 var newValueRanges = [];
d58ae307 1631 for (var i = 0; i < this.axes_.length; i++) {
ff022deb
RK
1632 var hi = this.toDataYCoord(lowY, i);
1633 var low = this.toDataYCoord(highY, i);
b1a3b195 1634 newValueRanges.push([low, hi]);
d58ae307 1635 }
8b83c6cc 1636
57baab03 1637 this.zoomed_y_ = true;
b1a3b195
DV
1638 var that = this;
1639 this.doAnimatedZoom(null, null, oldValueRanges, newValueRanges, function() {
b0963cdb 1640 if (that.getFunctionOption("zoomCallback")) {
b1a3b195 1641 var xRange = that.xAxisRange();
4ee251cb 1642 that.getFunctionOption("zoomCallback").call(that,
b0963cdb 1643 xRange[0], xRange[1], that.yAxisRanges());
b1a3b195
DV
1644 }
1645 });
8b83c6cc
RK
1646};
1647
1648/**
5b9b2142
RK
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 */
1653Dygraph.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/**
8b83c6cc
RK
1659 * Reset the zoom to the original view coordinates. This is the same as
1660 * double-clicking on the graph.
8b83c6cc 1661 */
e4f6e11a 1662Dygraph.prototype.resetZoom = function() {
b1a3b195 1663 var dirty = false, dirtyX = false, dirtyY = false;
758a629f 1664 if (this.dateWindow_ !== null) {
d58ae307 1665 dirty = true;
b1a3b195 1666 dirtyX = true;
8b83c6cc 1667 }
d58ae307
DV
1668
1669 for (var i = 0; i < this.axes_.length; i++) {
1f6a6254 1670 if (typeof(this.axes_[i].valueWindow) !== 'undefined' && this.axes_[i].valueWindow !== null) {
d58ae307 1671 dirty = true;
b1a3b195 1672 dirtyY = true;
d58ae307 1673 }
8b83c6cc
RK
1674 }
1675
da1369a5
DV
1676 // Clear any selection, since it's likely to be drawn in the wrong place.
1677 this.clearSelection();
1678
8b83c6cc 1679 if (dirty) {
57baab03
NN
1680 this.zoomed_x_ = false;
1681 this.zoomed_y_ = false;
b1a3b195
DV
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.
b0963cdb 1688 if (!this.getBooleanOption("animatedZooms")) {
b1a3b195 1689 this.dateWindow_ = null;
758a629f
DV
1690 for (i = 0; i < this.axes_.length; i++) {
1691 if (this.axes_[i].valueWindow !== null) {
b1a3b195
DV
1692 delete this.axes_[i].valueWindow;
1693 }
1694 }
1695 this.drawGraph_();
b0963cdb 1696 if (this.getFunctionOption("zoomCallback")) {
4ee251cb 1697 this.getFunctionOption("zoomCallback").call(this,
b0963cdb 1698 minDate, maxDate, this.yAxisRanges());
b1a3b195
DV
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);
30a5cfc6 1713 var extremes = packed.extremes;
b1a3b195
DV
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 = [];
758a629f 1722 for (i = 0; i < this.axes_.length; i++) {
1f6a6254 1723 var axis = this.axes_[i];
681a215e
DV
1724 newValueRanges.push((axis.valueRange !== null &&
1725 axis.valueRange !== undefined) ?
42a9ebb8 1726 axis.valueRange : axis.extremeRange);
b1a3b195
DV
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++) {
758a629f 1735 if (that.axes_[i].valueWindow !== null) {
b1a3b195
DV
1736 delete that.axes_[i].valueWindow;
1737 }
1738 }
b0963cdb 1739 if (that.getFunctionOption("zoomCallback")) {
4ee251cb 1740 that.getFunctionOption("zoomCallback").call(that,
b0963cdb 1741 minDate, maxDate, that.yAxisRanges());
b1a3b195
DV
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 */
1752Dygraph.prototype.doAnimatedZoom = function(oldXRange, newXRange, oldYRanges, newYRanges, callback) {
b0963cdb
DV
1753 var steps = this.getBooleanOption("animatedZooms") ?
1754 Dygraph.ANIMATION_STEPS : 1;
b1a3b195
DV
1755
1756 var windows = [];
1757 var valueRanges = [];
758a629f 1758 var step, frac;
b1a3b195 1759
758a629f
DV
1760 if (oldXRange !== null && newXRange !== null) {
1761 for (step = 1; step <= steps; step++) {
1762 frac = Dygraph.zoomAnimationFunction(step, steps);
b1a3b195
DV
1763 windows[step-1] = [oldXRange[0]*(1-frac) + frac*newXRange[0],
1764 oldXRange[1]*(1-frac) + frac*newXRange[1]];
8b83c6cc 1765 }
67e650dc 1766 }
b1a3b195 1767
758a629f
DV
1768 if (oldYRanges !== null && newYRanges !== null) {
1769 for (step = 1; step <= steps; step++) {
1770 frac = Dygraph.zoomAnimationFunction(step, steps);
b1a3b195
DV
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);
6a1aa64f
DV
1793};
1794
1795/**
857a6931
KW
1796 * Get the current graph's area object.
1797 *
1798 * Returns: {x, y, w, h}
6a1aa64f 1799 */
857a6931
KW
1800Dygraph.prototype.getArea = function() {
1801 return this.plotter_.area;
1802};
e863a17d 1803
857a6931
KW
1804/**
1805 * Convert a mouse event to DOM coordinates relative to the graph origin.
1806 *
1807 * Returns a two-element array: [X, Y].
1808 */
1809Dygraph.prototype.eventToDomCoords = function(event) {
abc8c570
RK
1810 if (event.offsetX && event.offsetY) {
1811 return [ event.offsetX, event.offsetY ];
1812 } else {
4d9f1cb9 1813 var eventElementPos = Dygraph.findPos(this.mouseEventElement_);
464b5f50
DV
1814 var canvasx = Dygraph.pageX(event) - eventElementPos.x;
1815 var canvasy = Dygraph.pageY(event) - eventElementPos.y;
abc8c570
RK
1816 return [canvasx, canvasy];
1817 }
857a6931 1818};
4cac8c7a 1819
857a6931
KW
1820/**
1821 * Given a canvas X coordinate, find the closest row.
1bc88216
DV
1822 * @param {number} domX graph-relative DOM X coordinate
1823 * Returns {number} row number.
857a6931
KW
1824 * @private
1825 */
1826Dygraph.prototype.findClosestRow = function(domX) {
81cb07d6 1827 var minDistX = Infinity;
a703cbdf 1828 var closestRow = -1;
a12a78ae
DV
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;
a703cbdf 1839 closestRow = point.idx;
a12a78ae 1840 }
a937d031 1841 }
6a1aa64f 1842 }
a12a78ae 1843
a703cbdf 1844 return closestRow;
857a6931 1845};
6a1aa64f 1846
857a6931 1847/**
2a02e5dd
KW
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 *
1bc88216
DV
1854 * @param {number} domX graph-relative DOM X coordinate
1855 * @param {number} domY graph-relative DOM Y coordinate
857a6931
KW
1856 * Returns: {row, seriesName, point}
1857 * @private
1858 */
1859Dygraph.prototype.findClosestPoint = function(domX, domY) {
81cb07d6 1860 var minDist = Infinity;
55231c07 1861 var dist, dx, dy, point, closestPoint, closestSeries, closestRow;
30a5cfc6 1862 for ( var setIdx = this.layout_.points.length - 1 ; setIdx >= 0 ; --setIdx ) {
a12a78ae
DV
1863 var points = this.layout_.points[setIdx];
1864 for (var i = 0; i < points.length; ++i) {
55231c07 1865 point = points[i];
62c3d2fd 1866 if (!Dygraph.isValidPoint(point)) continue;
857a6931
KW
1867 dx = point.canvasx - domX;
1868 dy = point.canvasy - domY;
1869 dist = dx * dx + dy * dy;
81cb07d6 1870 if (dist < minDist) {
62c3d2fd 1871 minDist = dist;
a937d031
KW
1872 closestPoint = point;
1873 closestSeries = setIdx;
55231c07 1874 closestRow = point.idx;
a937d031 1875 }
857a6931
KW
1876 }
1877 }
1878 var name = this.layout_.setNames[closestSeries];
1879 return {
55231c07 1880 row: closestRow,
857a6931
KW
1881 seriesName: name,
1882 point: closestPoint
1883 };
1884};
1885
1886/**
1887 * Given canvas X,Y coordinates, find the touched area in a stacked graph.
2a02e5dd
KW
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 *
1bc88216
DV
1893 * @param {number} domX graph-relative DOM X coordinate
1894 * @param {number} domY graph-relative DOM Y coordinate
857a6931
KW
1895 * Returns: {row, seriesName, point}
1896 * @private
1897 */
1898Dygraph.prototype.findStackedPoint = function(domX, domY) {
1899 var row = this.findClosestRow(domX);
857a6931 1900 var closestPoint, closestSeries;
30a5cfc6 1901 for (var setIdx = 0; setIdx < this.layout_.points.length; ++setIdx) {
55231c07
DE
1902 var boundary = this.getLeftBoundary_(setIdx);
1903 var rowIdx = row - boundary;
a12a78ae
DV
1904 var points = this.layout_.points[setIdx];
1905 if (rowIdx >= points.length) continue;
1906 var p1 = points[rowIdx];
62c3d2fd 1907 if (!Dygraph.isValidPoint(p1)) continue;
857a6931 1908 var py = p1.canvasy;
a12a78ae 1909 if (domX > p1.canvasx && rowIdx + 1 < points.length) {
857a6931 1910 // interpolate series Y value using next point
a12a78ae 1911 var p2 = points[rowIdx + 1];
62c3d2fd
KW
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 }
416b05ad 1918 }
81cb07d6 1919 } else if (domX < p1.canvasx && rowIdx > 0) {
857a6931 1920 // interpolate series Y value using previous point
a12a78ae 1921 var p0 = points[rowIdx - 1];
62c3d2fd
KW
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 }
12e4c741 1928 }
6a1aa64f 1929 }
857a6931 1930 // Stop if the point (domX, py) is above this series' upper edge
42a9ebb8 1931 if (setIdx === 0 || py < domY) {
a937d031
KW
1932 closestPoint = p1;
1933 closestSeries = setIdx;
1934 }
6a1aa64f 1935 }
857a6931
KW
1936 var name = this.layout_.setNames[closestSeries];
1937 return {
1938 row: row,
1939 seriesName: name,
1940 point: closestPoint
1941 };
1942};
6a1aa64f 1943
857a6931 1944/**
6a1aa64f
DV
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 */
285a6bda 1951Dygraph.prototype.mouseMove_ = function(event) {
e863a17d 1952 // This prevents JS errors when mousing over the canvas before data loads.
4cac8c7a 1953 var points = this.layout_.points;
a12a78ae 1954 if (points === undefined || points === null) return;
e863a17d 1955
857a6931
KW
1956 var canvasCoords = this.eventToDomCoords(event);
1957 var canvasx = canvasCoords[0];
1958 var canvasy = canvasCoords[1];
6a1aa64f 1959
b0963cdb 1960 var highlightSeriesOpts = this.getOption("highlightSeriesOpts");
857a6931 1961 var selectionChanged = false;
3f55b813 1962 if (highlightSeriesOpts && !this.isSeriesLocked()) {
857a6931 1963 var closest;
b0963cdb 1964 if (this.getBooleanOption("stackedGraph")) {
857a6931
KW
1965 closest = this.findStackedPoint(canvasx, canvasy);
1966 } else {
1967 closest = this.findClosestPoint(canvasx, canvasy);
43af96e7 1968 }
857a6931 1969 selectionChanged = this.setSelection(closest.row, closest.seriesName);
416b05ad 1970 } else {
857a6931
KW
1971 var idx = this.findClosestRow(canvasx);
1972 selectionChanged = this.setSelection(idx);
12e4c741 1973 }
43af96e7 1974
b0963cdb 1975 var callback = this.getFunctionOption("highlightCallback");
857a6931 1976 if (callback && selectionChanged) {
4ee251cb 1977 callback.call(this, event,
870a309c
DV
1978 this.lastx_,
1979 this.selPoints_,
55231c07 1980 this.lastRow_,
870a309c 1981 this.highlightSet_);
12e4c741 1982 }
239c712d 1983};
b258a3da 1984
239c712d 1985/**
b77d7a56 1986 * Fetch left offset from the specified set index or if not passed, the
55231c07 1987 * first defined boundaryIds record (see bug #236).
e2c21500 1988 * @private
81cb07d6 1989 */
55231c07 1990Dygraph.prototype.getLeftBoundary_ = function(setIdx) {
383d8473 1991 if (this.boundaryIds_[setIdx]) {
a703cbdf 1992 return this.boundaryIds_[setIdx][0];
55231c07
DE
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 }
81cb07d6 1998 }
55231c07 1999 return 0;
81cb07d6 2000 }
81cb07d6
KW
2001};
2002
857a6931
KW
2003Dygraph.prototype.animateSelection_ = function(direction) {
2004 var totalSteps = 10;
2005 var millis = 30;
1d44ee5e
KW
2006 if (this.fadeLevel === undefined) this.fadeLevel = 0;
2007 if (this.animateId === undefined) this.animateId = 0;
857a6931
KW
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;
fb2b89c8
MB
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 };
475f7420
KW
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 },
fb2b89c8 2039 steps, millis, cleanupIfClearing);
857a6931
KW
2040};
2041
2ddb1197 2042/**
239c712d
NAG
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 */
857a6931 2047Dygraph.prototype.updateSelection_ = function(opt_animFraction) {
0cd1ad15
DV
2048 /*var defaultPrevented = */
2049 this.cascadeEvents_('select', {
54f4c379 2050 selectedRow: this.lastRow_,
e2c21500
DV
2051 selectedX: this.lastx_,
2052 selectedPoints: this.selPoints_
2053 });
2054 // TODO(danvk): use defaultPrevented here?
2055
6a1aa64f 2056 // Clear the previously drawn vertical, if there is one
758a629f 2057 var i;
2cf95fff 2058 var ctx = this.canvas_ctx_;
b0963cdb 2059 if (this.getOption('highlightSeriesOpts')) {
857a6931 2060 ctx.clearRect(0, 0, this.width_, this.height_);
b0963cdb 2061 var alpha = 1.0 - this.getNumericOption('highlightSeriesBackgroundAlpha');
857a6931 2062 if (alpha) {
2a02e5dd
KW
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) {
857a6931
KW
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 }
38e3d209
DV
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);
857a6931 2082 } else if (this.previousVerticalX_ >= 0) {
46dde5f9
DV
2083 // Determine the maximum highlight circle size.
2084 var maxCircleSize = 0;
227b93cc 2085 var labels = this.attr_('labels');
758a629f 2086 for (i = 1; i < labels.length; i++) {
b0963cdb 2087 var r = this.getNumericOption('highlightCircleSize', labels[i]);
46dde5f9
DV
2088 if (r > maxCircleSize) maxCircleSize = r;
2089 }
6a1aa64f 2090 var px = this.previousVerticalX_;
46dde5f9
DV
2091 ctx.clearRect(px - maxCircleSize - 1, 0,
2092 2 * maxCircleSize + 2, this.height_);
6a1aa64f
DV
2093 }
2094
d160cc3b 2095 if (this.selPoints_.length > 0) {
6a1aa64f 2096 // Draw colored circles over the center of each selected point
e9fe4a2f 2097 var canvasx = this.selPoints_[0].canvasx;
43af96e7 2098 ctx.save();
758a629f 2099 for (i = 0; i < this.selPoints_.length; i++) {
e9fe4a2f
DV
2100 var pt = this.selPoints_[i];
2101 if (!Dygraph.isOK(pt.canvasy)) continue;
2102
b0963cdb
DV
2103 var circleSize = this.getNumericOption('highlightCircleSize', pt.name);
2104 var callback = this.getFunctionOption("drawHighlightPointCallback", pt.name);
a8ef67a8 2105 var color = this.plotter_.colors[pt.name];
78e58af4
RK
2106 if (!callback) {
2107 callback = Dygraph.Circles.DEFAULT;
2108 }
b0963cdb 2109 ctx.lineWidth = this.getNumericOption('strokeWidth', pt.name);
a8ef67a8
KW
2110 ctx.strokeStyle = color;
2111 ctx.fillStyle = color;
4ee251cb 2112 callback.call(this, this, pt.name, ctx, canvasx, pt.canvasy,
ba697462 2113 color, circleSize, pt.idx);
6a1aa64f
DV
2114 }
2115 ctx.restore();
2116
2117 this.previousVerticalX_ = canvasx;
2118 }
2119};
2120
2121/**
629a09ae
DV
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().
1bc88216 2125 * @param {number} row Row number that should be highlighted (i.e. appear with
8cadc6c9 2126 * hover dots on the chart).
1bc88216 2127 * @param {seriesName} optional series name to highlight that series with the
857a6931 2128 * the highlightSeriesOpts setting.
b9a3ece4
KW
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.
239c712d 2132 */
b9a3ece4 2133Dygraph.prototype.setSelection = function(row, opt_seriesName, opt_locked) {
239c712d
NAG
2134 // Extract the points we've selected
2135 this.selPoints_ = [];
50360fd0 2136
857a6931 2137 var changed = false;
16269f6e 2138 if (row !== false && row >= 0) {
857a6931
KW
2139 if (row != this.lastRow_) changed = true;
2140 this.lastRow_ = row;
30a5cfc6
KW
2141 for (var setIdx = 0; setIdx < this.layout_.points.length; ++setIdx) {
2142 var points = this.layout_.points[setIdx];
8b7f7651
AV
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;
ad7785b8 2158 }
ad7785b8 2159 }
16269f6e 2160 }
239c712d 2161 }
857a6931
KW
2162 } else {
2163 if (this.lastRow_ >= 0) changed = true;
2164 this.lastRow_ = -1;
16269f6e 2165 }
50360fd0 2166
16269f6e 2167 if (this.selPoints_.length) {
239c712d 2168 this.lastx_ = this.selPoints_[0].xval;
239c712d 2169 } else {
857a6931 2170 this.lastx_ = -1;
239c712d
NAG
2171 }
2172
857a6931
KW
2173 if (opt_seriesName !== undefined) {
2174 if (this.highlightSet_ !== opt_seriesName) changed = true;
2175 this.highlightSet_ = opt_seriesName;
239c712d
NAG
2176 }
2177
b9a3ece4
KW
2178 if (opt_locked !== undefined) {
2179 this.lockedSet_ = opt_locked;
2180 }
2181
857a6931
KW
2182 if (changed) {
2183 this.updateSelection_(undefined);
2184 }
2185 return changed;
239c712d
NAG
2186};
2187
2188/**
6a1aa64f
DV
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 */
285a6bda 2193Dygraph.prototype.mouseOut_ = function(event) {
b0963cdb 2194 if (this.getFunctionOption("unhighlightCallback")) {
4ee251cb 2195 this.getFunctionOption("unhighlightCallback").call(this, event);
a4c6a67c
AV
2196 }
2197
4ee251cb 2198 if (this.getBooleanOption("hideOverlayOnMouseOut") && !this.lockedSet_) {
239c712d 2199 this.clearSelection();
43af96e7 2200 }
6a1aa64f
DV
2201};
2202
239c712d 2203/**
629a09ae
DV
2204 * Clears the current selection (i.e. points that were highlighted by moving
2205 * the mouse over the chart).
239c712d
NAG
2206 */
2207Dygraph.prototype.clearSelection = function() {
e2c21500
DV
2208 this.cascadeEvents_('deselect', {});
2209
b9a3ece4 2210 this.lockedSet_ = false;
239c712d 2211 // Get rid of the overlay data
857a6931
KW
2212 if (this.fadeLevel) {
2213 this.animateSelection_(-1);
2214 return;
2215 }
2cf95fff 2216 this.canvas_ctx_.clearRect(0, 0, this.width_, this.height_);
857a6931 2217 this.fadeLevel = 0;
239c712d
NAG
2218 this.selPoints_ = [];
2219 this.lastx_ = -1;
857a6931
KW
2220 this.lastRow_ = -1;
2221 this.highlightSet_ = null;
758a629f 2222};
239c712d 2223
103b7292 2224/**
629a09ae
DV
2225 * Returns the number of the currently selected row. To get data for this row,
2226 * you can use the getValue method.
1bc88216 2227 * @return {number} row number, or -1 if nothing is selected
103b7292
NAG
2228 */
2229Dygraph.prototype.getSelection = function() {
2230 if (!this.selPoints_ || this.selPoints_.length < 1) {
2231 return -1;
2232 }
50360fd0 2233
a12a78ae
DV
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) {
55231c07 2238 return points[row].idx;
a12a78ae 2239 }
103b7292
NAG
2240 }
2241 }
2242 return -1;
2e1fcf1a 2243};
103b7292 2244
e2c21500
DV
2245/**
2246 * Returns the name of the currently-highlighted series.
2247 * Only available when the highlightSeriesOpts option is in use.
2248 */
857a6931
KW
2249Dygraph.prototype.getHighlightSeries = function() {
2250 return this.highlightSet_;
2251};
2252
19589a3e 2253/**
3f55b813
KW
2254 * Returns true if the currently-highlighted series was locked
2255 * via setSelection(..., seriesName, true).
2256 */
2257Dygraph.prototype.isSeriesLocked = function() {
2258 return this.lockedSet_;
2259};
2260
2261/**
6a1aa64f 2262 * Fires when there's data available to be graphed.
1bc88216 2263 * @param {string} data Raw CSV data to be plotted
6a1aa64f
DV
2264 * @private
2265 */
285a6bda 2266Dygraph.prototype.loadedEvent_ = function(data) {
6a1aa64f 2267 this.rawData_ = this.parseCSV_(data);
6f5f0b2b 2268 this.cascadeDataDidUpdateEvent_();
26ca7938 2269 this.predraw_();
6a1aa64f
DV
2270};
2271
6a1aa64f
DV
2272/**
2273 * Add ticks on the x-axis representing years, months, quarters, weeks, or days
2274 * @private
2275 */
285a6bda 2276Dygraph.prototype.addXTicks_ = function() {
6a1aa64f 2277 // Determine the correct ticks scale on the x-axis: quarterly, monthly, ...
7201b11e 2278 var range;
6a1aa64f 2279 if (this.dateWindow_) {
7201b11e 2280 range = [this.dateWindow_[0], this.dateWindow_[1]];
6a1aa64f 2281 } else {
ccecde93 2282 range = this.xAxisExtremes();
7201b11e
JB
2283 }
2284
48e614ac
DV
2285 var xAxisOptionsView = this.optionsViewForAxis_('x');
2286 var xTicks = xAxisOptionsView('ticker')(
2287 range[0],
2288 range[1],
b504bdd2 2289 this.plotter_.area.w, // TODO(danvk): should be area.width
48e614ac
DV
2290 xAxisOptionsView,
2291 this);
2292 // var msg = 'ticker(' + range[0] + ', ' + range[1] + ', ' + this.width_ + ', ' + this.attr_('pixelsPerXLabel') + ') -> ' + JSON.stringify(xTicks);
2293 // console.log(msg);
b2c9222a 2294 this.layout_.setXTicks(xTicks);
32988383
DV
2295};
2296
629a09ae 2297/**
3ea41d86 2298 * Returns the correct handler class for the currently set options.
629a09ae 2299 * @private
3ea41d86
DV
2300 */
2301Dygraph.prototype.getHandlerClass_ = function() {
2302 var handlerClass;
2303 if (this.attr_('dataHandler')) {
2304 handlerClass = this.attr_('dataHandler');
2305 } else if (this.fractions_) {
b0963cdb 2306 if (this.getBooleanOption('errorBars')) {
3ea41d86 2307 handlerClass = Dygraph.DataHandlers.FractionsBarsHandler;
a49c164a 2308 } else {
3ea41d86 2309 handlerClass = Dygraph.DataHandlers.DefaultFractionHandler;
5011e7a1 2310 }
b0963cdb 2311 } else if (this.getBooleanOption('customBars')) {
3ea41d86 2312 handlerClass = Dygraph.DataHandlers.CustomBarsHandler;
b0963cdb 2313 } else if (this.getBooleanOption('errorBars')) {
3ea41d86 2314 handlerClass = Dygraph.DataHandlers.ErrorBarsHandler;
5011e7a1 2315 } else {
3ea41d86 2316 handlerClass = Dygraph.DataHandlers.DefaultHandler;
5011e7a1 2317 }
3ea41d86 2318 return handlerClass;
5011e7a1
DV
2319};
2320
6a1aa64f 2321/**
629a09ae 2322 * @private
26ca7938
DV
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 */
2329Dygraph.prototype.predraw_ = function() {
7153e001 2330 var start = new Date();
b77d7a56 2331
a49c164a 2332 // Create the correct dataHandler
3ea41d86 2333 this.dataHandler_ = new (this.getHandlerClass_())();
7153e001 2334
0d216a60
PF
2335 this.layout_.computePlotArea();
2336
26ca7938
DV
2337 // TODO(danvk): move more computations out of drawGraph_ and into here.
2338 this.computeYAxes_();
2339
383d8473 2340 if (!this.is_initial_draw_) {
aeca29ac
RK
2341 this.canvas_ctx_.restore();
2342 this.hidden_ctx_.restore();
2343 }
2344
2345 this.canvas_ctx_.save();
2346 this.hidden_ctx_.save();
2347
c04c8044 2348 // Create a new plotter.
26ca7938 2349 this.plotter_ = new DygraphCanvasRenderer(this,
2cf95fff
RK
2350 this.hidden_,
2351 this.hidden_ctx_,
0e23cfc6 2352 this.layout_);
26ca7938 2353
0abfbd7e
DV
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.
8c69de65 2356 this.createRollInterface_();
26ca7938 2357
e2c21500 2358 this.cascadeEvents_('predraw');
0abfbd7e 2359
b1a3b195
DV
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
395e98a3 2363 for (var i = 1; i < this.numColumns(); i++) {
c1780ad0 2364 // var logScale = this.attr_('logscale', i); // TODO(klausw): this looks wrong // konigsberg thinks so too.
a49c164a
DE
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 }
b77d7a56 2369
b1a3b195
DV
2370 this.rolledSeries_.push(series);
2371 }
2372
26ca7938
DV
2373 // If the data or options have changed, then we'd better redraw.
2374 this.drawGraph_();
4b4d1a63
DV
2375
2376 // This is used to determine whether to do various animations.
2377 var end = new Date();
2378 this.drawingTimeMs_ = (end - start);
26ca7938
DV
2379};
2380
2381/**
30a5cfc6
KW
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 */
bcc53a77 2404Dygraph.PointType = undefined;
30a5cfc6 2405
30a5cfc6
KW
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'.
24f2a74f 2422 * @private
30a5cfc6
KW
2423 */
2424Dygraph.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.
bcc53a77 2432 var updateNextPoint = function(idx) {
30a5cfc6
KW
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) {
06c0e1ee 2460 if(fillMethod == 'none') {
30a5cfc6 2461 actualYval = 0;
d68137fd 2462 } else {
06c0e1ee
S
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 }
30a5cfc6
KW
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/**
b1a3b195
DV
2502 * Loop over all fields and create datasets, calculating extreme y-values for
2503 * each series and extreme x-indices as we go.
fc4e84fa 2504 *
b1a3b195
DV
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.
fc4e84fa 2508 *
30a5cfc6
KW
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>}}
6a1aa64f
DV
2518 * @private
2519 */
b1a3b195
DV
2520Dygraph.prototype.gatherDatasets_ = function(rolledSeries, dateWindow) {
2521 var boundaryIds = [];
30a5cfc6
KW
2522 var points = [];
2523 var cumulativeYval = []; // For stacked series.
f09fc545 2524 var extremes = {}; // series name -> [low, high]
a49c164a
DE
2525 var seriesIdx, sampleIdx;
2526 var firstIdx, lastIdx;
8b5f1691 2527 var axisIdx;
b77d7a56 2528
b1a3b195
DV
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;
bcc53a77 2532 var series;
a49c164a
DE
2533 for (seriesIdx = num_series; seriesIdx >= 1; seriesIdx--) {
2534 if (!this.visibility()[seriesIdx - 1]) continue;
1cf11047 2535
6a1aa64f 2536 // Prune down to the desired range, if necessary (for zooming)
1a26f3fb
DV
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.
b1a3b195 2539 if (dateWindow) {
a49c164a 2540 series = rolledSeries[seriesIdx];
b1a3b195
DV
2541 var low = dateWindow[0];
2542 var high = dateWindow[1];
4e59e63e 2543
1a26f3fb
DV
2544 // TODO(danvk): do binary search instead of linear search.
2545 // TODO(danvk): pass firstIdx and lastIdx directly to the renderer.
b77d7a56 2546 firstIdx = null;
a49c164a
DE
2547 lastIdx = null;
2548 for (sampleIdx = 0; sampleIdx < series.length; sampleIdx++) {
2549 if (series[sampleIdx][0] >= low && firstIdx === null) {
2550 firstIdx = sampleIdx;
1a26f3fb 2551 }
a49c164a
DE
2552 if (series[sampleIdx][0] <= high) {
2553 lastIdx = sampleIdx;
6a1aa64f
DV
2554 }
2555 }
4e59e63e 2556
1a26f3fb 2557 if (firstIdx === null) firstIdx = 0;
14ac984e 2558 var correctedFirstIdx = firstIdx;
b0375a28 2559 var isInvalidValue = true;
4e59e63e 2560 while (isInvalidValue && correctedFirstIdx > 0) {
14ac984e 2561 correctedFirstIdx--;
a49c164a
DE
2562 // check if the y value is null.
2563 isInvalidValue = series[correctedFirstIdx][1] === null;
14ac984e 2564 }
4e59e63e 2565
1a26f3fb 2566 if (lastIdx === null) lastIdx = series.length - 1;
14ac984e 2567 var correctedLastIdx = lastIdx;
b0375a28 2568 isInvalidValue = true;
4e59e63e 2569 while (isInvalidValue && correctedLastIdx < series.length - 1) {
14ac984e 2570 correctedLastIdx++;
a49c164a 2571 isInvalidValue = series[correctedLastIdx][1] === null;
14ac984e 2572 }
4e59e63e 2573
4e59e63e 2574 if (correctedFirstIdx!==firstIdx) {
30a5cfc6 2575 firstIdx = correctedFirstIdx;
6a1aa64f 2576 }
4e59e63e 2577 if (correctedLastIdx !== lastIdx) {
30a5cfc6 2578 lastIdx = correctedLastIdx;
4e59e63e 2579 }
b77d7a56 2580
a49c164a 2581 boundaryIds[seriesIdx-1] = [firstIdx, lastIdx];
b77d7a56 2582
30a5cfc6
KW
2583 // .slice's end is exclusive, we want to include lastIdx.
2584 series = series.slice(firstIdx, lastIdx + 1);
16269f6e 2585 } else {
a49c164a
DE
2586 series = rolledSeries[seriesIdx];
2587 boundaryIds[seriesIdx-1] = [0, series.length-1];
6a1aa64f
DV
2588 }
2589
a49c164a 2590 var seriesName = this.attr_("labels")[seriesIdx];
b77d7a56 2591 var seriesExtremes = this.dataHandler_.getExtremeYValues(series,
b0963cdb 2592 dateWindow, this.getBooleanOption("stepPlot",seriesName));
5011e7a1 2593
b77d7a56 2594 var seriesPoints = this.dataHandler_.seriesToPoints(series,
a49c164a 2595 seriesName, boundaryIds[seriesIdx-1][0]);
43af96e7 2596
b0963cdb 2597 if (this.getBooleanOption("stackedGraph")) {
8b5f1691
JJS
2598 axisIdx = this.attributes_.axisForSeries(seriesName);
2599 if (cumulativeYval[axisIdx] === undefined) {
2600 cumulativeYval[axisIdx] = [];
2601 }
2602 Dygraph.stackPoints_(seriesPoints, cumulativeYval[axisIdx], seriesExtremes,
b0963cdb 2603 this.getBooleanOption("stackedGraphNaNFill"));
6a1aa64f 2604 }
354e15ab 2605
b1a3b195 2606 extremes[seriesName] = seriesExtremes;
a49c164a 2607 points[seriesIdx] = seriesPoints;
7d463f49
KW
2608 }
2609
30a5cfc6 2610 return { points: points, extremes: extremes, boundaryIds: boundaryIds };
b1a3b195
DV
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 *
b1a3b195
DV
2618 * @private
2619 */
e2c21500 2620Dygraph.prototype.drawGraph_ = function() {
b1a3b195
DV
2621 var start = new Date();
2622
b1a3b195
DV
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
b1a3b195
DV
2627 this.layout_.removeAllDatasets();
2628 this.setColors_();
b0963cdb 2629 this.attrs_.pointSize = 0.5 * this.getNumericOption('highlightCircleSize');
b1a3b195
DV
2630
2631 var packed = this.gatherDatasets_(this.rolledSeries_, this.dateWindow_);
30a5cfc6
KW
2632 var points = packed.points;
2633 var extremes = packed.extremes;
2634 this.boundaryIds_ = packed.boundaryIds;
b1a3b195 2635
82c6fe4d
KW
2636 this.setIndexByName_ = {};
2637 var labels = this.attr_("labels");
2638 if (labels.length > 0) {
2639 this.setIndexByName_[labels[0]] = 0;
2640 }
857a6931 2641 var dataIdx = 0;
30a5cfc6 2642 for (var i = 1; i < points.length; i++) {
82c6fe4d 2643 this.setIndexByName_[labels[i]] = i;
4523c1f6 2644 if (!this.visibility()[i - 1]) continue;
30a5cfc6 2645 this.layout_.addDataset(labels[i], points[i]);
857a6931 2646 this.datasetIndex_[i] = dataIdx++;
43af96e7
NK
2647 }
2648
6faebb69 2649 this.computeYAxisRanges_(extremes);
b2c9222a
DV
2650 this.layout_.setYAxes(this.axes_);
2651
6a1aa64f
DV
2652 this.addXTicks_();
2653
b2c9222a 2654 // Save the X axis zoomed status as the updateOptions call will tend to set it erroneously
81856f70 2655 var tmp_zoomed_x = this.zoomed_x_;
6a1aa64f 2656 // Tell PlotKit to use this new data and render itself
81856f70 2657 this.zoomed_x_ = tmp_zoomed_x;
30a5cfc6 2658 this.layout_.evaluate();
e2c21500 2659 this.renderGraph_(is_initial_draw);
9ca829f2 2660
b0963cdb 2661 if (this.getStringOption("timingName")) {
9ca829f2 2662 var end = new Date();
8a68db7d 2663 console.log(this.getStringOption("timingName") + " - drawGraph: " + (end - start) + "ms");
9ca829f2
DV
2664 }
2665};
2666
e2c21500
DV
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 */
2673Dygraph.prototype.renderGraph_ = function(is_initial_draw) {
1748a51c 2674 this.cascadeEvents_('clearChart');
6a1aa64f 2675 this.plotter_.clear();
f417e3d3 2676
b0963cdb 2677 if (this.getFunctionOption('underlayCallback')) {
98eb4713
DV
2678 // NOTE: we pass the dygraph object to this callback twice to avoid breaking
2679 // users who expect a deprecated form of this callback.
4ee251cb 2680 this.getFunctionOption('underlayCallback').call(this,
98eb4713
DV
2681 this.hidden_ctx_, this.layout_.getPlotArea(), this, this);
2682 }
2683
2684 var e = {
189f8030 2685 canvas: this.hidden_,
2de7166c 2686 drawingContext: this.hidden_ctx_
98eb4713
DV
2687 };
2688 this.cascadeEvents_('willDrawChart', e);
6a1aa64f 2689 this.plotter_.render();
98eb4713 2690 this.cascadeEvents_('didDrawChart', e);
fa11f4e4 2691 this.lastRow_ = -1; // because plugins/legend.js clears the legend
8cfe592f
DV
2692
2693 // TODO(danvk): is this a performance bottleneck when panning?
2694 // The interaction canvas should already be empty in that situation.
7c39bb3a 2695 this.canvas_.getContext('2d').clearRect(0, 0, this.width_, this.height_);
599fb4ad 2696
b0963cdb
DV
2697 if (this.getFunctionOption("drawCallback") !== null) {
2698 this.getFunctionOption("drawCallback")(this, is_initial_draw);
599fb4ad 2699 }
5bcc58b4
DV
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 }
6a1aa64f
DV
2707};
2708
2709/**
629a09ae 2710 * @private
26ca7938
DV
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.
16f00742 2715 * This fills in this.axes_.
26ca7938 2716 * axes_ = [ { options } ]
26ca7938 2717 * indices are into the axes_ array.
f09fc545 2718 */
26ca7938 2719Dygraph.prototype.computeYAxes_ = function() {
d64b8fea
RK
2720 // Preserve valueWindow settings if they exist, and if the user hasn't
2721 // specified a new valueRange.
0cd1ad15 2722 var valueWindows, axis, index, opts, v;
758a629f 2723 if (this.axes_ !== undefined && this.user_attrs_.hasOwnProperty("valueRange") === false) {
d64b8fea 2724 valueWindows = [];
758a629f 2725 for (index = 0; index < this.axes_.length; index++) {
d64b8fea
RK
2726 valueWindows.push(this.axes_[index].valueWindow);
2727 }
2728 }
2729
6ad8b6a4
RK
2730 // this.axes_ doesn't match this.attributes_.axes_.options. It's used for
2731 // data computation as well as options storage.
f09fc545 2732 // Go through once and add all the axes.
02c93ff5 2733 this.axes_ = [];
0d216a60 2734
02c93ff5 2735 for (axis = 0; axis < this.attributes_.numAxes(); axis++) {
6ad8b6a4 2736 // Add a new axis, making a copy of its per-axis options.
02c93ff5 2737 opts = { g : this };
6ad8b6a4
RK
2738 Dygraph.update(opts, this.attributes_.axisOptions(axis));
2739 this.axes_[axis] = opts;
f09fc545 2740 }
1c77a3a1 2741
7740dd00
RK
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;
478b866b 2749
758a629f 2750 if (valueWindows !== undefined) {
d64b8fea 2751 // Restore valueWindow settings.
4ecb55b5
RK
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++) {
d64b8fea
RK
2758 this.axes_[index].valueWindow = valueWindows[index];
2759 }
2760 }
4dd0ac55 2761
4dd0ac55
RV
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 }
26ca7938
DV
2775};
2776
2777/**
2778 * Returns the number of y-axes on the chart.
1bc88216 2779 * @return {number} the number of axes.
26ca7938
DV
2780 */
2781Dygraph.prototype.numAxes = function() {
16f00742 2782 return this.attributes_.numAxes();
26ca7938
DV
2783};
2784
2785/**
629a09ae 2786 * @private
b2c9222a 2787 * Returns axis properties for the given series.
1bc88216 2788 * @param {string} setName The name of the series for which to get axis
b2c9222a 2789 * properties, e.g. 'Y1'.
1bc88216 2790 * @return {Object} The axis properties.
b2c9222a
DV
2791 */
2792Dygraph.prototype.axisPropertiesForSeries = function(series) {
2793 // TODO(danvk): handle errors.
16f00742 2794 return this.axes_[this.attributes_.axisForSeries(series)];
b2c9222a
DV
2795};
2796
2797/**
2798 * @private
26ca7938
DV
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 */
2803Dygraph.prototype.computeYAxisRanges_ = function(extremes) {
9adc2c33 2804 var isNullUndefinedOrNaN = function(num) {
126bf1e3 2805 return isNaN(parseFloat(num));
6b05851c 2806 };
16f00742 2807 var numAxes = this.attributes_.numAxes();
4bac38d8 2808 var ypadCompat, span, series, ypad;
b77d7a56 2809
9e906ae6 2810 var p_axis;
f09fc545
DV
2811
2812 // Compute extreme values, a span and tick marks for each axis.
16f00742 2813 for (var i = 0; i < numAxes; i++) {
26ca7938 2814 var axis = this.axes_[i];
ec40f67c
RK
2815 var logscale = this.attributes_.getForAxis("logscale", i);
2816 var includeZero = this.attributes_.getForAxis("includeZero", i);
9e906ae6 2817 var independentTicks = this.attributes_.getForAxis("independentTicks", i);
6ad8b6a4
RK
2818 series = this.attributes_.seriesForAxis(i);
2819
31a8d0cd 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%
b0963cdb 2836 if (this.getNumericOption('yRangePad') !== null) {
31a8d0cd 2837 ypadCompat = false;
2838 // Convert pixel padding to ratio
b0963cdb 2839 ypad = this.getNumericOption('yRangePad') / this.plotter_.area.h;
31a8d0cd 2840 }
2841
83b0c192 2842 if (series.length === 0) {
06fc69b6
AV
2843 // If no series are defined or visible then use a reasonable default
2844 axis.extremeRange = [0, 1];
2845 } else {
1c77a3a1 2846 // Calculate the extremes of extremes.
f09fc545
DV
2847 var minY = Infinity; // extremes[series[0]][0];
2848 var maxY = -Infinity; // extremes[series[0]][1];
ba049b89 2849 var extremeMinY, extremeMaxY;
a2da3777 2850
f09fc545 2851 for (var j = 0; j < series.length; j++) {
a2da3777
DV
2852 // this skips invisible series
2853 if (!extremes.hasOwnProperty(series[j])) continue;
2854
ba049b89
NN
2855 // Only use valid extremes to stop null data series' from corrupting the scale.
2856 extremeMinY = extremes[series[j]][0];
758a629f 2857 if (extremeMinY !== null) {
36dfa958 2858 minY = Math.min(extremeMinY, minY);
ba049b89
NN
2859 }
2860 extremeMaxY = extremes[series[j]][1];
758a629f 2861 if (extremeMaxY !== null) {
36dfa958 2862 maxY = Math.max(extremeMaxY, maxY);
ba049b89 2863 }
f09fc545 2864 }
fa460473
KW
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 }
f09fc545 2871
a2da3777 2872 // Ensure we have a valid scale, otherwise default to [0, 1] for safety.
36dfa958 2873 if (minY == Infinity) minY = 0;
a2da3777 2874 if (maxY == -Infinity) maxY = 1;
ba049b89 2875
4bac38d8 2876 span = maxY - minY;
fa460473
KW
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
758a629f 2888 var maxAxisY, minAxisY;
ec40f67c 2889 if (logscale) {
fa460473
KW
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 }
ff022deb 2898 } else {
fa460473
KW
2899 maxAxisY = maxY + ypad * span;
2900 minAxisY = minY - ypad * span;
f09fc545 2901
fa460473
KW
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.
b0963cdb 2904 if (ypadCompat && !this.getBooleanOption("avoidMinZero")) {
ff022deb
RK
2905 if (minAxisY < 0 && minY >= 0) minAxisY = 0;
2906 if (maxAxisY > 0 && maxY <= 0) maxAxisY = 0;
2907 }
f09fc545 2908 }
4cac8c7a
RK
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.
fa460473
KW
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 {
4bac38d8 2926 span = y1 - y0;
fa460473
KW
2927 y0 -= span * ypad;
2928 y1 += span * ypad;
2929 }
2930 }
2931 axis.computedValueRange = [y0, y1];
4cac8c7a
RK
2932 } else {
2933 axis.computedValueRange = axis.extremeRange;
f09fc545 2934 }
b77d7a56 2935
2936
383d8473 2937 if (independentTicks) {
9e906ae6
DE
2938 axis.independentTicks = independentTicks;
2939 var opts = this.optionsViewForAxis_('y' + (i ? '2' : ''));
2940 var ticker = opts('ticker');
48e614ac 2941 axis.ticks = ticker(axis.computedValueRange[0],
9e906ae6 2942 axis.computedValueRange[1],
b504bdd2 2943 this.plotter_.area.h,
9e906ae6
DE
2944 opts,
2945 this);
6c5f8774 2946 // Define the first independent axis as primary axis.
e8b3c7b4 2947 if (!p_axis) p_axis = axis;
9e906ae6
DE
2948 }
2949 }
e8b3c7b4 2950 if (p_axis === undefined) {
eba6dd23 2951 throw ("Configuration Error: At least one axis has to have the \"independentTicks\" option activated.");
e8b3c7b4 2952 }
9e906ae6
DE
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];
b77d7a56 2958
9e906ae6
DE
2959 if (!axis.independentTicks) {
2960 var opts = this.optionsViewForAxis_('y' + (i ? '2' : ''));
2961 var ticker = opts('ticker');
0d64e596
DV
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 = [];
25f76ae3
DV
2966 for (var k = 0; k < p_ticks.length; k++) {
2967 var y_frac = (p_ticks[k].v - p_axis.computedValueRange[0]) / p_scale;
0d64e596
DV
2968 var y_val = axis.computedValueRange[0] + y_frac * scale;
2969 tick_values.push(y_val);
2970 }
2971
48e614ac
DV
2972 axis.ticks = ticker(axis.computedValueRange[0],
2973 axis.computedValueRange[1],
b504bdd2 2974 this.plotter_.area.h,
48e614ac
DV
2975 opts,
2976 this,
2977 tick_values);
0d64e596 2978 }
34fc91d4 2979 }
f09fc545 2980};
25f76ae3 2981
f09fc545 2982/**
285a6bda
DV
2983 * Detects the type of the str (date or numeric) and sets the various
2984 * formatting attributes in this.attrs_ based on this type.
1bc88216 2985 * @param {string} str An x value.
285a6bda
DV
2986 * @private
2987 */
2988Dygraph.prototype.detectTypeFromString_ = function(str) {
2989 var isDate = false;
0842b24b
DV
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')) ||
285a6bda
DV
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
a716aff2
RK
3000 this.setXAxisOptions_(isDate);
3001};
3002
3003Dygraph.prototype.setXAxisOptions_ = function(isDate) {
285a6bda 3004 if (isDate) {
285a6bda 3005 this.attrs_.xValueParser = Dygraph.dateParser;
872a6a00 3006 this.attrs_.axes.x.valueFormatter = Dygraph.dateValueFormatter;
48e614ac 3007 this.attrs_.axes.x.ticker = Dygraph.dateTicker;
872a6a00 3008 this.attrs_.axes.x.axisLabelFormatter = Dygraph.dateAxisLabelFormatter;
285a6bda 3009 } else {
c39e1d93 3010 /** @private (shut up, jsdoc!) */
285a6bda 3011 this.attrs_.xValueParser = function(x) { return parseFloat(x); };
48e614ac
DV
3012 // TODO(danvk): use Dygraph.numberValueFormatter here?
3013 /** @private (shut up, jsdoc!) */
3014 this.attrs_.axes.x.valueFormatter = function(x) { return x; };
5b9b2142 3015 this.attrs_.axes.x.ticker = Dygraph.numericTicks;
48e614ac 3016 this.attrs_.axes.x.axisLabelFormatter = this.attrs_.axes.x.valueFormatter;
6a1aa64f 3017 }
83b0c192 3018};
6a1aa64f
DV
3019
3020/**
629a09ae 3021 * @private
6a1aa64f
DV
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.
285a6bda 3025 * if the errorBars attribute is set, then interpret the fields as:
6a1aa64f 3026 * date, series1, stddev1, series2, stddev2, ...
629a09ae 3027 * @param {[Object]} data See above.
285a6bda 3028 *
629a09ae 3029 * @return [Object] An array with one entry for each row. These entries
285a6bda
DV
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 ]
6a1aa64f 3036 */
285a6bda 3037Dygraph.prototype.parseCSV_ = function(data) {
6a1aa64f 3038 var ret = [];
e5763589
DV
3039 var line_delimiter = Dygraph.detectLineDelimiter(data);
3040 var lines = data.split(line_delimiter || "\n");
758a629f 3041 var vals, j;
3d67f03b
DV
3042
3043 // Use the default delimiter or fall back to a tab if that makes sense.
b0963cdb 3044 var delim = this.getStringOption('delimiter');
3d67f03b
DV
3045 if (lines[0].indexOf(delim) == -1 && lines[0].indexOf('\t') >= 0) {
3046 delim = '\t';
3047 }
3048
285a6bda 3049 var start = 0;
d7beab6b
DV
3050 if (!('labels' in this.user_attrs_)) {
3051 // User hasn't explicitly set labels, so they're (presumably) in the CSV.
285a6bda 3052 start = 1;
d7beab6b 3053 this.attrs_.labels = lines[0].split(delim); // NOTE: _not_ user_attrs_.
34825ef5 3054 this.attributes_.reparseSeries();
6a1aa64f 3055 }
5cd7ac68 3056 var line_no = 0;
03b522a4 3057
285a6bda
DV
3058 var xParser;
3059 var defaultParserSet = false; // attempt to auto-detect x value type
3060 var expectedCols = this.attr_("labels").length;
987840a2 3061 var outOfOrder = false;
6a1aa64f
DV
3062 for (var i = start; i < lines.length; i++) {
3063 var line = lines[i];
5cd7ac68 3064 line_no = i;
758a629f 3065 if (line.length === 0) continue; // skip blank lines
3d67f03b
DV
3066 if (line[0] == '#') continue; // skip comment lines
3067 var inFields = line.split(delim);
285a6bda 3068 if (inFields.length < 2) continue;
6a1aa64f
DV
3069
3070 var fields = [];
285a6bda
DV
3071 if (!defaultParserSet) {
3072 this.detectTypeFromString_(inFields[0]);
b0963cdb 3073 xParser = this.getFunctionOption("xValueParser");
285a6bda
DV
3074 defaultParserSet = true;
3075 }
3076 fields[0] = xParser(inFields[0], this);
6a1aa64f
DV
3077
3078 // If fractions are expected, parse the numbers as "A/B"
3079 if (this.fractions_) {
758a629f 3080 for (j = 1; j < inFields.length; j++) {
6a1aa64f 3081 // TODO(danvk): figure out an appropriate way to flag parse errors.
758a629f 3082 vals = inFields[j].split("/");
7219edb3 3083 if (vals.length != 2) {
8a68db7d 3084 console.error('Expected fractional "num/den" values in CSV data ' +
464b5f50
DV
3085 "but found a value '" + inFields[j] + "' on line " +
3086 (1 + i) + " ('" + line + "') which is not of this form.");
7219edb3
DV
3087 fields[j] = [0, 0];
3088 } else {
55deb02f
DV
3089 fields[j] = [Dygraph.parseFloat_(vals[0], i, line),
3090 Dygraph.parseFloat_(vals[1], i, line)];
7219edb3 3091 }
6a1aa64f 3092 }
b0963cdb 3093 } else if (this.getBooleanOption("errorBars")) {
6a1aa64f 3094 // If there are error bars, values are (value, stddev) pairs
7219edb3 3095 if (inFields.length % 2 != 1) {
8a68db7d 3096 console.error('Expected alternating (value, stdev.) pairs in CSV data ' +
464b5f50
DV
3097 'but line ' + (1 + i) + ' has an odd number of values (' +
3098 (inFields.length - 1) + "): '" + line + "'");
7219edb3 3099 }
758a629f 3100 for (j = 1; j < inFields.length; j += 2) {
55deb02f
DV
3101 fields[(j + 1) / 2] = [Dygraph.parseFloat_(inFields[j], i, line),
3102 Dygraph.parseFloat_(inFields[j + 1], i, line)];
7219edb3 3103 }
b0963cdb 3104 } else if (this.getBooleanOption("customBars")) {
6a1aa64f 3105 // Bars are a low;center;high tuple
758a629f 3106 for (j = 1; j < inFields.length; j++) {
327a9279
DV
3107 var val = inFields[j];
3108 if (/^ *$/.test(val)) {
3109 fields[j] = [null, null, null];
3110 } else {
758a629f 3111 vals = val.split(";");
327a9279 3112 if (vals.length == 3) {
55deb02f
DV
3113 fields[j] = [ Dygraph.parseFloat_(vals[0], i, line),
3114 Dygraph.parseFloat_(vals[1], i, line),
3115 Dygraph.parseFloat_(vals[2], i, line) ];
327a9279 3116 } else {
8a68db7d 3117 console.warn('When using customBars, values must be either blank ' +
464b5f50
DV
3118 'or "low;center;high" tuples (got "' + val +
3119 '" on line ' + (1+i));
327a9279
DV
3120 }
3121 }
6a1aa64f
DV
3122 }
3123 } else {
3124 // Values are just numbers
758a629f 3125 for (j = 1; j < inFields.length; j++) {
55deb02f 3126 fields[j] = Dygraph.parseFloat_(inFields[j], i, line);
285a6bda 3127 }
6a1aa64f 3128 }
987840a2
DV
3129 if (ret.length > 0 && fields[0] < ret[ret.length - 1][0]) {
3130 outOfOrder = true;
3131 }
285a6bda
DV
3132
3133 if (fields.length != expectedCols) {
8a68db7d 3134 console.error("Number of columns in line " + i + " (" + fields.length +
464b5f50
DV
3135 ") does not agree with number of labels (" + expectedCols +
3136 ") " + line);
285a6bda 3137 }
6d0aaa09
DV
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.
758a629f 3143 if (i === 0 && this.attr_('labels')) {
6d0aaa09 3144 var all_null = true;
758a629f 3145 for (j = 0; all_null && j < fields.length; j++) {
6d0aaa09
DV
3146 if (fields[j]) all_null = false;
3147 }
3148 if (all_null) {
8a68db7d 3149 console.warn("The dygraphs 'labels' option is set, but the first row " +
464b5f50
DV
3150 "of CSV data ('" + line + "') appears to also contain " +
3151 "labels. Will drop the CSV labels and use the option " +
3152 "labels.");
6d0aaa09
DV
3153 continue;
3154 }
3155 }
3156 ret.push(fields);
6a1aa64f 3157 }
987840a2
DV
3158
3159 if (outOfOrder) {
8a68db7d 3160 console.warn("CSV is out of order; order it correctly to speed loading.");
758a629f 3161 ret.sort(function(a,b) { return a[0] - b[0]; });
987840a2
DV
3162 }
3163
6a1aa64f
DV
3164 return ret;
3165};
3166
3167/**
285a6bda
DV
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.
8ef9d44d
DV
3171 * @param {!Array} data
3172 * @return {Object} data with numeric x values.
3173 * @private
285a6bda
DV
3174 */
3175Dygraph.prototype.parseArray_ = function(data) {
3176 // Peek at the first x value to see if it's numeric.
758a629f 3177 if (data.length === 0) {
8a68db7d 3178 console.error("Can't plot empty data set");
285a6bda
DV
3179 return null;
3180 }
758a629f 3181 if (data[0].length === 0) {
8a68db7d 3182 console.error("Data set cannot contain an empty row");
285a6bda
DV
3183 return null;
3184 }
3185
758a629f
DV
3186 var i;
3187 if (this.attr_("labels") === null) {
8a68db7d 3188 console.warn("Using default labels. Set labels explicitly via 'labels' " +
464b5f50 3189 "in the options parameter");
285a6bda 3190 this.attrs_.labels = [ "X" ];
758a629f 3191 for (i = 1; i < data[0].length; i++) {
77812e0e 3192 this.attrs_.labels.push("Y" + i); // Not user_attrs_.
285a6bda 3193 }
77812e0e 3194 this.attributes_.reparseSeries();
debdb88d
DV
3195 } else {
3196 var num_labels = this.attr_("labels");
3197 if (num_labels.length != data[0].length) {
8a68db7d 3198 console.error("Mismatch between number of labels (" + num_labels + ")" +
464b5f50 3199 " and number of columns in array (" + data[0].length + ")");
debdb88d
DV
3200 return null;
3201 }
285a6bda
DV
3202 }
3203
2dda3850 3204 if (Dygraph.isDateLike(data[0][0])) {
285a6bda 3205 // Some intelligent defaults for a date x-axis.
872a6a00 3206 this.attrs_.axes.x.valueFormatter = Dygraph.dateValueFormatter;
48e614ac 3207 this.attrs_.axes.x.ticker = Dygraph.dateTicker;
872a6a00 3208 this.attrs_.axes.x.axisLabelFormatter = Dygraph.dateAxisLabelFormatter;
285a6bda
DV
3209
3210 // Assume they're all dates.
e3ab7b40 3211 var parsedData = Dygraph.clone(data);
758a629f
DV
3212 for (i = 0; i < data.length; i++) {
3213 if (parsedData[i].length === 0) {
8a68db7d 3214 console.error("Row " + (1 + i) + " of data is empty");
285a6bda
DV
3215 return null;
3216 }
758a629f
DV
3217 if (parsedData[i][0] === null ||
3218 typeof(parsedData[i][0].getTime) != 'function' ||
3219 isNaN(parsedData[i][0].getTime())) {
8a68db7d 3220 console.error("x value in row " + (1 + i) + " is not a Date");
285a6bda
DV
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.
c39e1d93 3228 /** @private (shut up, jsdoc!) */
48e614ac 3229 this.attrs_.axes.x.valueFormatter = function(x) { return x; };
5b9b2142 3230 this.attrs_.axes.x.ticker = Dygraph.numericTicks;
a716aff2 3231 this.attrs_.axes.x.axisLabelFormatter = Dygraph.numberAxisLabelFormatter;
285a6bda
DV
3232 return data;
3233 }
3234};
3235
3236/**
79420a1e
DV
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
a685723c 3241 * fixed. Fills out rawData_.
1bc88216 3242 * @param {!google.visualization.DataTable} data See above.
79420a1e
DV
3243 * @private
3244 */
285a6bda 3245Dygraph.prototype.parseDataTable_ = function(data) {
5829af3d 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;
42a9ebb8 3257 };
5829af3d 3258
79420a1e
DV
3259 var cols = data.getNumberOfColumns();
3260 var rows = data.getNumberOfRows();
3261
d955e223 3262 var indepType = data.getColumnType(0);
4440f6c8 3263 if (indepType == 'date' || indepType == 'datetime') {
285a6bda 3264 this.attrs_.xValueParser = Dygraph.dateParser;
872a6a00 3265 this.attrs_.axes.x.valueFormatter = Dygraph.dateValueFormatter;
48e614ac 3266 this.attrs_.axes.x.ticker = Dygraph.dateTicker;
872a6a00 3267 this.attrs_.axes.x.axisLabelFormatter = Dygraph.dateAxisLabelFormatter;
33127159 3268 } else if (indepType == 'number') {
285a6bda 3269 this.attrs_.xValueParser = function(x) { return parseFloat(x); };
48e614ac 3270 this.attrs_.axes.x.valueFormatter = function(x) { return x; };
5b9b2142 3271 this.attrs_.axes.x.ticker = Dygraph.numericTicks;
48e614ac 3272 this.attrs_.axes.x.axisLabelFormatter = this.attrs_.axes.x.valueFormatter;
285a6bda 3273 } else {
8a68db7d 3274 console.error("only 'date', 'datetime' and 'number' types are supported " +
464b5f50 3275 "for column 1 of DataTable input (Got '" + indepType + "')");
79420a1e
DV
3276 return null;
3277 }
3278
a685723c
DV
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;
758a629f
DV
3283 var i, j;
3284 for (i = 1; i < cols; i++) {
a685723c
DV
3285 var type = data.getColumnType(i);
3286 if (type == 'number') {
3287 colIdx.push(i);
b0963cdb 3288 } else if (type == 'string' && this.getBooleanOption('displayAnnotations')) {
a685723c
DV
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 {
8a68db7d 3298 console.error("Only 'number' is supported as a dependent type with Gviz." +
464b5f50 3299 " 'string' is only supported if displayAnnotations is true");
a685723c
DV
3300 }
3301 }
3302
3303 // Read column labels
3304 // TODO(danvk): add support back for errorBars
3305 var labels = [data.getColumnLabel(0)];
758a629f 3306 for (i = 0; i < colIdx.length; i++) {
a685723c 3307 labels.push(data.getColumnLabel(colIdx[i]));
b0963cdb 3308 if (this.getBooleanOption("errorBars")) i += 1;
a685723c
DV
3309 }
3310 this.attrs_.labels = labels;
3311 cols = labels.length;
3312
79420a1e 3313 var ret = [];
987840a2 3314 var outOfOrder = false;
a685723c 3315 var annotations = [];
758a629f 3316 for (i = 0; i < rows; i++) {
79420a1e 3317 var row = [];
debe4434
DV
3318 if (typeof(data.getValue(i, 0)) === 'undefined' ||
3319 data.getValue(i, 0) === null) {
8a68db7d 3320 console.warn("Ignoring row " + i +
464b5f50 3321 " of DataTable because of undefined or null first column.");
debe4434
DV
3322 continue;
3323 }
3324
c21d2c2d 3325 if (indepType == 'date' || indepType == 'datetime') {
d955e223
DV
3326 row.push(data.getValue(i, 0).getTime());
3327 } else {
3328 row.push(data.getValue(i, 0));
3329 }
b0963cdb 3330 if (!this.getBooleanOption("errorBars")) {
758a629f 3331 for (j = 0; j < colIdx.length; j++) {
a685723c
DV
3332 var col = colIdx[j];
3333 row.push(data.getValue(i, col));
3334 if (hasAnnotations &&
3335 annotationCols.hasOwnProperty(col) &&
758a629f 3336 data.getValue(i, annotationCols[col][0]) !== null) {
a685723c
DV
3337 var ann = {};
3338 ann.series = data.getColumnLabel(col);
3339 ann.xval = row[0];
5829af3d 3340 ann.shortText = shortTextForAnnotationNum(annotations.length);
a685723c
DV
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 }
3e3f84e4 3348 }
92fd68d8
DV
3349
3350 // Strip out infinities, which give dygraphs problems later on.
758a629f 3351 for (j = 0; j < row.length; j++) {
92fd68d8
DV
3352 if (!isFinite(row[j])) row[j] = null;
3353 }
3e3f84e4 3354 } else {
758a629f 3355 for (j = 0; j < cols - 1; j++) {
3e3f84e4
DV
3356 row.push([ data.getValue(i, 1 + 2 * j), data.getValue(i, 2 + 2 * j) ]);
3357 }
79420a1e 3358 }
987840a2
DV
3359 if (ret.length > 0 && row[0] < ret[ret.length - 1][0]) {
3360 outOfOrder = true;
3361 }
243d96e8 3362 ret.push(row);
79420a1e 3363 }
987840a2
DV
3364
3365 if (outOfOrder) {
8a68db7d 3366 console.warn("DataTable is out of order; order it correctly to speed loading.");
758a629f 3367 ret.sort(function(a,b) { return a[0] - b[0]; });
987840a2 3368 }
a685723c
DV
3369 this.rawData_ = ret;
3370
3371 if (annotations.length > 0) {
3372 this.setAnnotations(annotations, true);
3373 }
0fa724fd 3374 this.attributes_.reparseSeries();
758a629f 3375};
79420a1e 3376
629a09ae 3377/**
6f5f0b2b
DV
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 */
3381Dygraph.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/**
6a1aa64f
DV
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 */
285a6bda 3393Dygraph.prototype.start_ = function() {
36d4fabf
RK
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);
6f5f0b2b 3403 this.cascadeDataDidUpdateEvent_();
26ca7938 3404 this.predraw_();
36d4fabf
RK
3405 } else if (typeof data == 'object' &&
3406 typeof data.getColumnRange == 'function') {
79420a1e 3407 // must be a DataTable from gviz.
36d4fabf 3408 this.parseDataTable_(data);
6f5f0b2b 3409 this.cascadeDataDidUpdateEvent_();
26ca7938 3410 this.predraw_();
36d4fabf 3411 } else if (typeof data == 'string') {
285a6bda 3412 // Heuristic: a newline means it's CSV data. Otherwise it's an URL.
e5763589
DV
3413 var line_delimiter = Dygraph.detectLineDelimiter(data);
3414 if (line_delimiter) {
36d4fabf 3415 this.loadedEvent_(data);
285a6bda 3416 } else {
efc5160f
DV
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
285a6bda
DV
3427 var caller = this;
3428 req.onreadystatechange = function () {
3429 if (req.readyState == 4) {
758a629f
DV
3430 if (req.status === 200 || // Normal http
3431 req.status === 0) { // Chrome w/ --allow-file-access-from-files
285a6bda
DV
3432 caller.loadedEvent_(req.responseText);
3433 }
6a1aa64f 3434 }
285a6bda 3435 };
6a1aa64f 3436
36d4fabf 3437 req.open("GET", data, true);
285a6bda
DV
3438 req.send(null);
3439 }
3440 } else {
8a68db7d 3441 console.error("Unknown data format: " + (typeof data));
6a1aa64f
DV
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>
dcb25130 3451 *
ccfcc169
DV
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 *
8ef9d44d
DV
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).
6a1aa64f 3462 */
48e614ac 3463Dygraph.prototype.updateOptions = function(input_attrs, block_redraw) {
ccfcc169
DV
3464 if (typeof(block_redraw) == 'undefined') block_redraw = false;
3465
bfb3e0a4 3466 // copyUserAttrs_ drops the "file" parameter as a convenience to us.
758a629f 3467 var file = input_attrs.file;
bfb3e0a4 3468 var attrs = Dygraph.copyUserAttrs_(input_attrs);
48e614ac 3469
ccfcc169 3470 // TODO(danvk): this is a mess. Move these options into attr_.
c65f2303 3471 if ('rollPeriod' in attrs) {
6a1aa64f
DV
3472 this.rollPeriod_ = attrs.rollPeriod;
3473 }
c65f2303 3474 if ('dateWindow' in attrs) {
6a1aa64f 3475 this.dateWindow_ = attrs.dateWindow;
e5152598 3476 if (!('isZoomedIgnoreProgrammaticZoom' in attrs)) {
758a629f 3477 this.zoomed_x_ = (attrs.dateWindow !== null);
81856f70 3478 }
b7e5862d 3479 }
e5152598 3480 if ('valueRange' in attrs && !('isZoomedIgnoreProgrammaticZoom' in attrs)) {
758a629f 3481 this.zoomed_y_ = (attrs.valueRange !== null);
6a1aa64f 3482 }
450fe64b
DV
3483
3484 // TODO(danvk): validate per-series options.
46dde5f9
DV
3485 // Supported:
3486 // strokeWidth
3487 // pointSize
3488 // drawPoints
3489 // highlightCircleSize
450fe64b 3490
9ca829f2
DV
3491 // Check if this set options will require new points.
3492 var requiresNewPoints = Dygraph.isPixelChangingOptionList(this.attr_("labels"), attrs);
3493
48e614ac 3494 Dygraph.updateDeep(this.user_attrs_, attrs);
285a6bda 3495
b635457c
RK
3496 this.attributes_.reparseSeries();
3497
48e614ac 3498 if (file) {
6f5f0b2b
DV
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
48e614ac 3503 this.file_ = file;
ccfcc169 3504 if (!block_redraw) this.start_();
6a1aa64f 3505 } else {
9ca829f2
DV
3506 if (!block_redraw) {
3507 if (requiresNewPoints) {
48e614ac 3508 this.predraw_();
9ca829f2 3509 } else {
e2c21500 3510 this.renderGraph_(false);
9ca829f2
DV
3511 }
3512 }
6a1aa64f
DV
3513 }
3514};
3515
3516/**
bfb3e0a4 3517 * Make a copy of input attributes, removing file as a convenience.
48e614ac 3518 */
bfb3e0a4 3519Dygraph.copyUserAttrs_ = function(attrs) {
48e614ac
DV
3520 var my_attrs = {};
3521 for (var k in attrs) {
3ce712e6 3522 if (!attrs.hasOwnProperty(k)) continue;
48e614ac
DV
3523 if (k == 'file') continue;
3524 if (attrs.hasOwnProperty(k)) my_attrs[k] = attrs[k];
3525 }
48e614ac
DV
3526 return my_attrs;
3527};
3528
3529/**
697e70b2
DV
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.
964f30c6
DV
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 *
1bc88216
DV
3537 * @param {number} width Width (in pixels)
3538 * @param {number} height Height (in pixels)
697e70b2
DV
3539 */
3540Dygraph.prototype.resize = function(width, height) {
e8c7ef86
DV
3541 if (this.resize_lock) {
3542 return;
3543 }
3544 this.resize_lock = true;
3545
697e70b2 3546 if ((width === null) != (height === null)) {
8a68db7d 3547 console.warn("Dygraph.resize() should be called with zero parameters or " +
464b5f50 3548 "two non-NULL parameters. Pretending it was zero.");
697e70b2
DV
3549 width = height = null;
3550 }
3551
4b4d1a63
DV
3552 var old_width = this.width_;
3553 var old_height = this.height_;
b16e6369 3554
697e70b2
DV
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 {
ccd9d7c2
PF
3561 this.width_ = this.maindiv_.clientWidth;
3562 this.height_ = this.maindiv_.clientHeight;
697e70b2
DV
3563 }
3564
4b4d1a63 3565 if (old_width != this.width_ || old_height != this.height_) {
d82a3164
KW
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_();
4b4d1a63
DV
3569 this.predraw_();
3570 }
e8c7ef86
DV
3571
3572 this.resize_lock = false;
697e70b2
DV
3573};
3574
3575/**
6faebb69 3576 * Adjusts the number of points in the rolling average. Updates the graph to
6a1aa64f 3577 * reflect the new averaging period.
1bc88216 3578 * @param {number} length Number of points over which to average the data.
6a1aa64f 3579 */
285a6bda 3580Dygraph.prototype.adjustRoll = function(length) {
6a1aa64f 3581 this.rollPeriod_ = length;
26ca7938 3582 this.predraw_();
6a1aa64f 3583};
540d00f1 3584
f8cfec73 3585/**
1cf11047
DV
3586 * Returns a boolean array of visibility statuses.
3587 */
3588Dygraph.prototype.visibility = function() {
3589 // Do lazy-initialization, so that this happens after we know the number of
3590 // data series.
b0963cdb 3591 if (!this.getOption("visibility")) {
758a629f 3592 this.attrs_.visibility = [];
1cf11047 3593 }
758a629f 3594 // TODO(danvk): it looks like this could go into an infinite loop w/ user_attrs.
b0963cdb 3595 while (this.getOption("visibility").length < this.numColumns() - 1) {
758a629f 3596 this.attrs_.visibility.push(true);
1cf11047 3597 }
b0963cdb 3598 return this.getOption("visibility");
1cf11047
DV
3599};
3600
3601/**
1f0f434a 3602 * Changes the visibility of one or more series.
2aed8ad8 3603 *
1f0f434a 3604 * @param {number|number[]} num the series index or an array of series indices
7e64db42 3605 * @param {boolean} value true or false, identifying the visibility.
1cf11047
DV
3606 */
3607Dygraph.prototype.setVisibility = function(num, value) {
3608 var x = this.visibility();
1f0f434a
SS
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 }
1cf11047 3618 }
1f0f434a
SS
3619
3620 this.predraw_();
1cf11047
DV
3621};
3622
3623/**
0cb9bd91
DV
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 */
3629Dygraph.prototype.size = function() {
3630 return { width: this.width_, height: this.height_ };
3631};
3632
3633/**
5c528fa2 3634 * Update the list of annotations and redraw the chart.
41ee764f
DV
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).
5c528fa2 3638 */
a685723c 3639Dygraph.prototype.setAnnotations = function(ann, suppressDraw) {
3c51ab74
DV
3640 // Only add the annotation CSS rule once we know it will be used.
3641 Dygraph.addAnnotationRule();
5c528fa2 3642 this.annotations_ = ann;
af6e4ad5 3643 if (!this.layout_) {
8a68db7d 3644 console.warn("Tried to setAnnotations before dygraph was ready. " +
464b5f50
DV
3645 "Try setting them in a ready() block. See " +
3646 "dygraphs.com/tests/annotation.html");
af6e4ad5
DV
3647 return;
3648 }
3649
5c528fa2 3650 this.layout_.setAnnotations(this.annotations_);
a685723c 3651 if (!suppressDraw) {
26ca7938 3652 this.predraw_();
a685723c 3653 }
5c528fa2
DV
3654};
3655
3656/**
3657 * Return the list of annotations.
3658 */
3659Dygraph.prototype.annotations = function() {
3660 return this.annotations_;
3661};
3662
46dde5f9 3663/**
82c6fe4d
KW
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.
4c10c8d2
RK
3666 *
3667 * Returns null when labels have not yet been defined.
82c6fe4d 3668 */
e2c21500 3669Dygraph.prototype.getLabels = function() {
4c10c8d2
RK
3670 var labels = this.attr_("labels");
3671 return labels ? labels.slice() : null;
82c6fe4d
KW
3672};
3673
3674/**
46dde5f9
DV
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 */
3678Dygraph.prototype.indexFromSetName = function(name) {
82c6fe4d 3679 return this.setIndexByName_[name];
46dde5f9
DV
3680};
3681
629a09ae 3682/**
fcf37b29
DV
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 */
3690Dygraph.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/**
5bcc58b4
DV
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 */
3723Dygraph.prototype.ready = function(callback) {
3724 if (this.is_initial_draw_) {
3725 this.readyFns_.push(callback);
3726 } else {
4ee251cb 3727 callback.call(this, this);
5bcc58b4
DV
3728 }
3729};
3730
3731/**
629a09ae
DV
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 */
5c528fa2 3737Dygraph.addAnnotationRule = function() {
d38c6191 3738 // TODO(danvk): move this function into plugins/annotations.js?
5c528fa2
DV
3739 if (Dygraph.addedAnnotationCSS) return;
3740
5c528fa2
DV
3741 var rule = "border: 1px solid black; " +
3742 "background-color: white; " +
3743 "text-align: center;";
22186871
DV
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 }
5c528fa2
DV
3768 }
3769
8a68db7d 3770 console.warn("Unable to add default annotation CSS rule; display may be off.");
758a629f 3771};
8887663f
DV
3772
3773return Dygraph;
3774
3775})();