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