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