Commit | Line | Data |
---|---|---|
88e95c46 DV |
1 | /** |
2 | * @license | |
3 | * Copyright 2011 Dan Vanderkam (danvdk@gmail.com) | |
4 | * MIT-licensed (http://opensource.org/licenses/MIT) | |
5 | */ | |
dedb4f5f | 6 | |
004b5c90 DV |
7 | /** |
8 | * @fileoverview This file contains utility functions used by dygraphs. These | |
9 | * are typically static (i.e. not related to any particular dygraph). Examples | |
10 | * include date/time formatting functions, basic algorithms (e.g. binary | |
11 | * search) and generic DOM-manipulation functions. | |
12 | */ | |
dedb4f5f | 13 | |
8887663f DV |
14 | (function() { |
15 | ||
9901b0c1 | 16 | /*global Dygraph:false, Node:false */ |
c0f54d4f DV |
17 | "use strict"; |
18 | ||
dedb4f5f DV |
19 | Dygraph.LOG_SCALE = 10; |
20 | Dygraph.LN_TEN = Math.log(Dygraph.LOG_SCALE); | |
21 | ||
f11283de DV |
22 | /** |
23 | * @private | |
24 | * @param {number} x | |
25 | * @return {number} | |
26 | */ | |
dedb4f5f DV |
27 | Dygraph.log10 = function(x) { |
28 | return Math.log(x) / Dygraph.LN_TEN; | |
758a629f | 29 | }; |
dedb4f5f | 30 | |
79253bd0 | 31 | /** A dotted line stroke pattern. */ |
32 | Dygraph.DOTTED_LINE = [2, 2]; | |
33 | /** A dashed line stroke pattern. */ | |
34 | Dygraph.DASHED_LINE = [7, 3]; | |
35 | /** A dot dash stroke pattern. */ | |
36 | Dygraph.DOT_DASH_LINE = [7, 2, 2, 2]; | |
37 | ||
dedb4f5f | 38 | /** |
dedb4f5f DV |
39 | * Return the 2d context for a dygraph canvas. |
40 | * | |
41 | * This method is only exposed for the sake of replacing the function in | |
42 | * automated tests, e.g. | |
43 | * | |
44 | * var oldFunc = Dygraph.getContext(); | |
45 | * Dygraph.getContext = function(canvas) { | |
46 | * var realContext = oldFunc(canvas); | |
47 | * return new Proxy(realContext); | |
48 | * }; | |
f11283de DV |
49 | * @param {!HTMLCanvasElement} canvas |
50 | * @return {!CanvasRenderingContext2D} | |
51 | * @private | |
dedb4f5f DV |
52 | */ |
53 | Dygraph.getContext = function(canvas) { | |
f11283de | 54 | return /** @type{!CanvasRenderingContext2D}*/(canvas.getContext("2d")); |
dedb4f5f DV |
55 | }; |
56 | ||
57 | /** | |
9901b0c1 | 58 | * Add an event handler. |
39b33f9f DV |
59 | * @param {!Node} elem The element to add the event to. |
60 | * @param {string} type The type of the event, e.g. 'click' or 'mousemove'. | |
61 | * @param {function(Event):(boolean|undefined)} fn The function to call | |
f11283de DV |
62 | * on the event. The function takes one parameter: the event object. |
63 | * @private | |
dedb4f5f | 64 | */ |
1cc3540b | 65 | Dygraph.addEvent = function addEvent(elem, type, fn) { |
9901b0c1 | 66 | elem.addEventListener(type, fn, false); |
1cc3540b RK |
67 | }; |
68 | ||
69 | /** | |
1cc3540b RK |
70 | * Add an event handler. This event handler is kept until the graph is |
71 | * destroyed with a call to graph.destroy(). | |
72 | * | |
39b33f9f DV |
73 | * @param {!Node} elem The element to add the event to. |
74 | * @param {string} type The type of the event, e.g. 'click' or 'mousemove'. | |
75 | * @param {function(Event):(boolean|undefined)} fn The function to call | |
f11283de DV |
76 | * on the event. The function takes one parameter: the event object. |
77 | * @private | |
1cc3540b | 78 | */ |
aeca29ac | 79 | Dygraph.prototype.addAndTrackEvent = function(elem, type, fn) { |
1cc3540b | 80 | Dygraph.addEvent(elem, type, fn); |
6a4587ac | 81 | this.registeredEvents_.push({ elem : elem, type : type, fn : fn }); |
ccd9d7c2 PF |
82 | }; |
83 | ||
84 | /** | |
9901b0c1 | 85 | * Remove an event handler. |
39b33f9f | 86 | * @param {!Node} elem The element to remove the event from. |
f11283de DV |
87 | * @param {string} type The type of the event, e.g. 'click' or 'mousemove'. |
88 | * @param {function(Event):(boolean|undefined)} fn The function to call | |
89 | * on the event. The function takes one parameter: the event object. | |
ccd9d7c2 | 90 | * @private |
ccd9d7c2 | 91 | */ |
a537fd67 | 92 | Dygraph.removeEvent = function(elem, type, fn) { |
9901b0c1 | 93 | elem.removeEventListener(type, fn, false); |
dedb4f5f DV |
94 | }; |
95 | ||
aeca29ac RK |
96 | Dygraph.prototype.removeTrackedEvents_ = function() { |
97 | if (this.registeredEvents_) { | |
98 | for (var idx = 0; idx < this.registeredEvents_.length; idx++) { | |
99 | var reg = this.registeredEvents_[idx]; | |
100 | Dygraph.removeEvent(reg.elem, reg.type, reg.fn); | |
101 | } | |
102 | } | |
103 | ||
104 | this.registeredEvents_ = []; | |
f914bed1 | 105 | }; |
aeca29ac | 106 | |
dedb4f5f | 107 | /** |
dedb4f5f DV |
108 | * Cancels further processing of an event. This is useful to prevent default |
109 | * browser actions, e.g. highlighting text on a double-click. | |
110 | * Based on the article at | |
111 | * http://www.switchonthecode.com/tutorials/javascript-tutorial-the-scroll-wheel | |
39b33f9f | 112 | * @param {!Event} e The event whose normal behavior should be canceled. |
f11283de | 113 | * @private |
dedb4f5f DV |
114 | */ |
115 | Dygraph.cancelEvent = function(e) { | |
116 | e = e ? e : window.event; | |
117 | if (e.stopPropagation) { | |
118 | e.stopPropagation(); | |
119 | } | |
120 | if (e.preventDefault) { | |
121 | e.preventDefault(); | |
122 | } | |
123 | e.cancelBubble = true; | |
124 | e.cancel = true; | |
125 | e.returnValue = false; | |
126 | return false; | |
127 | }; | |
128 | ||
129 | /** | |
130 | * Convert hsv values to an rgb(r,g,b) string. Taken from MochiKit.Color. This | |
131 | * is used to generate default series colors which are evenly spaced on the | |
132 | * color wheel. | |
f11283de DV |
133 | * @param { number } hue Range is 0.0-1.0. |
134 | * @param { number } saturation Range is 0.0-1.0. | |
135 | * @param { number } value Range is 0.0-1.0. | |
136 | * @return { string } "rgb(r,g,b)" where r, g and b range from 0-255. | |
dedb4f5f DV |
137 | * @private |
138 | */ | |
139 | Dygraph.hsvToRGB = function (hue, saturation, value) { | |
140 | var red; | |
141 | var green; | |
142 | var blue; | |
143 | if (saturation === 0) { | |
144 | red = value; | |
145 | green = value; | |
146 | blue = value; | |
147 | } else { | |
148 | var i = Math.floor(hue * 6); | |
149 | var f = (hue * 6) - i; | |
150 | var p = value * (1 - saturation); | |
151 | var q = value * (1 - (saturation * f)); | |
152 | var t = value * (1 - (saturation * (1 - f))); | |
153 | switch (i) { | |
154 | case 1: red = q; green = value; blue = p; break; | |
155 | case 2: red = p; green = value; blue = t; break; | |
156 | case 3: red = p; green = q; blue = value; break; | |
157 | case 4: red = t; green = p; blue = value; break; | |
158 | case 5: red = value; green = p; blue = q; break; | |
159 | case 6: // fall through | |
160 | case 0: red = value; green = t; blue = p; break; | |
161 | } | |
162 | } | |
163 | red = Math.floor(255 * red + 0.5); | |
164 | green = Math.floor(255 * green + 0.5); | |
165 | blue = Math.floor(255 * blue + 0.5); | |
166 | return 'rgb(' + red + ',' + green + ',' + blue + ')'; | |
167 | }; | |
168 | ||
8442269f | 169 | /** |
464b5f50 DV |
170 | * Find the coordinates of an object relative to the top left of the page. |
171 | * | |
f11283de | 172 | * @param {Node} obj |
464b5f50 | 173 | * @return {{x:number,y:number}} |
8442269f RK |
174 | * @private |
175 | */ | |
464b5f50 | 176 | Dygraph.findPos = function(obj) { |
4debe18e MJ |
177 | var p = obj.getBoundingClientRect(), |
178 | w = window, | |
179 | d = document.documentElement; | |
464b5f50 | 180 | |
4debe18e | 181 | return { |
9013cfe5 MJ |
182 | x: p.left + (w.pageXOffset || d.scrollLeft), |
183 | y: p.top + (w.pageYOffset || d.scrollTop) | |
8442269f | 184 | } |
dedb4f5f DV |
185 | }; |
186 | ||
187 | /** | |
dedb4f5f DV |
188 | * Returns the x-coordinate of the event in a coordinate system where the |
189 | * top-left corner of the page (not the window) is (0,0). | |
190 | * Taken from MochiKit.Signal | |
f11283de DV |
191 | * @param {!Event} e |
192 | * @return {number} | |
193 | * @private | |
dedb4f5f DV |
194 | */ |
195 | Dygraph.pageX = function(e) { | |
920e93f2 | 196 | return (!e.pageX || e.pageX < 0) ? 0 : e.pageX; |
dedb4f5f DV |
197 | }; |
198 | ||
199 | /** | |
dedb4f5f DV |
200 | * Returns the y-coordinate of the event in a coordinate system where the |
201 | * top-left corner of the page (not the window) is (0,0). | |
202 | * Taken from MochiKit.Signal | |
f11283de DV |
203 | * @param {!Event} e |
204 | * @return {number} | |
205 | * @private | |
dedb4f5f DV |
206 | */ |
207 | Dygraph.pageY = function(e) { | |
920e93f2 | 208 | return (!e.pageY || e.pageY < 0) ? 0 : e.pageY; |
dedb4f5f DV |
209 | }; |
210 | ||
211 | /** | |
806f92c1 DV |
212 | * Converts page the x-coordinate of the event to pixel x-coordinates on the |
213 | * canvas (i.e. DOM Coords). | |
214 | * @param {!Event} e Drag event. | |
215 | * @param {!DygraphInteractionContext} context Interaction context object. | |
216 | * @return {number} The amount by which the drag has moved to the right. | |
217 | */ | |
218 | Dygraph.dragGetX_ = function(e, context) { | |
219 | return Dygraph.pageX(e) - context.px; | |
220 | }; | |
221 | ||
222 | /** | |
223 | * Converts page the y-coordinate of the event to pixel y-coordinates on the | |
224 | * canvas (i.e. DOM Coords). | |
225 | * @param {!Event} e Drag event. | |
226 | * @param {!DygraphInteractionContext} context Interaction context object. | |
227 | * @return {number} The amount by which the drag has moved down. | |
228 | */ | |
229 | Dygraph.dragGetY_ = function(e, context) { | |
230 | return Dygraph.pageY(e) - context.py; | |
231 | }; | |
232 | ||
233 | /** | |
f11283de DV |
234 | * This returns true unless the parameter is 0, null, undefined or NaN. |
235 | * TODO(danvk): rename this function to something like 'isNonZeroNan'. | |
236 | * | |
237 | * @param {number} x The number to consider. | |
238 | * @return {boolean} Whether the number is zero or NaN. | |
dedb4f5f | 239 | * @private |
dedb4f5f | 240 | */ |
dedb4f5f | 241 | Dygraph.isOK = function(x) { |
f11283de | 242 | return !!x && !isNaN(x); |
dedb4f5f DV |
243 | }; |
244 | ||
245 | /** | |
55deb02f | 246 | * @param {{x:?number,y:?number,yval:?number}} p The point to consider, valid |
f11283de | 247 | * points are {x, y} objects |
55deb02f DV |
248 | * @param {boolean=} opt_allowNaNY Treat point with y=NaN as valid |
249 | * @return {boolean} Whether the point has numeric x and y. | |
62c3d2fd | 250 | * @private |
62c3d2fd | 251 | */ |
55deb02f | 252 | Dygraph.isValidPoint = function(p, opt_allowNaNY) { |
f11283de DV |
253 | if (!p) return false; // null or undefined object |
254 | if (p.yval === null) return false; // missing point | |
04c104d7 KW |
255 | if (p.x === null || p.x === undefined) return false; |
256 | if (p.y === null || p.y === undefined) return false; | |
55deb02f | 257 | if (isNaN(p.x) || (!opt_allowNaNY && isNaN(p.y))) return false; |
62c3d2fd KW |
258 | return true; |
259 | }; | |
260 | ||
261 | /** | |
dedb4f5f DV |
262 | * Number formatting function which mimicks the behavior of %g in printf, i.e. |
263 | * either exponential or fixed format (without trailing 0s) is used depending on | |
264 | * the length of the generated string. The advantage of this format is that | |
265 | * there is a predictable upper bound on the resulting string length, | |
266 | * significant figures are not dropped, and normal numbers are not displayed in | |
267 | * exponential notation. | |
268 | * | |
269 | * NOTE: JavaScript's native toPrecision() is NOT a drop-in replacement for %g. | |
270 | * It creates strings which are too long for absolute values between 10^-4 and | |
271 | * 10^-6, e.g. '0.00001' instead of '1e-5'. See tests/number-format.html for | |
272 | * output examples. | |
273 | * | |
f11283de DV |
274 | * @param {number} x The number to format |
275 | * @param {number=} opt_precision The precision to use, default 2. | |
276 | * @return {string} A string formatted like %g in printf. The max generated | |
dedb4f5f DV |
277 | * string length should be precision + 6 (e.g 1.123e+300). |
278 | */ | |
279 | Dygraph.floatFormat = function(x, opt_precision) { | |
280 | // Avoid invalid precision values; [1, 21] is the valid range. | |
281 | var p = Math.min(Math.max(1, opt_precision || 2), 21); | |
282 | ||
283 | // This is deceptively simple. The actual algorithm comes from: | |
284 | // | |
285 | // Max allowed length = p + 4 | |
286 | // where 4 comes from 'e+n' and '.'. | |
287 | // | |
288 | // Length of fixed format = 2 + y + p | |
289 | // where 2 comes from '0.' and y = # of leading zeroes. | |
290 | // | |
291 | // Equating the two and solving for y yields y = 2, or 0.00xxxx which is | |
292 | // 1.0e-3. | |
293 | // | |
294 | // Since the behavior of toPrecision() is identical for larger numbers, we | |
295 | // don't have to worry about the other bound. | |
296 | // | |
297 | // Finally, the argument for toExponential() is the number of trailing digits, | |
298 | // so we take off 1 for the value before the '.'. | |
758a629f | 299 | return (Math.abs(x) < 1.0e-3 && x !== 0.0) ? |
dedb4f5f DV |
300 | x.toExponential(p - 1) : x.toPrecision(p); |
301 | }; | |
302 | ||
303 | /** | |
dedb4f5f | 304 | * Converts '9' to '09' (useful for dates) |
f11283de DV |
305 | * @param {number} x |
306 | * @return {string} | |
307 | * @private | |
dedb4f5f DV |
308 | */ |
309 | Dygraph.zeropad = function(x) { | |
310 | if (x < 10) return "0" + x; else return "" + x; | |
311 | }; | |
312 | ||
313 | /** | |
b77d7a56 | 314 | * Date accessors to get the parts of a calendar date (year, month, |
1e7f8af0 JPB |
315 | * day, hour, minute, second and millisecond) according to local time, |
316 | * and factory method to call the Date constructor with an array of arguments. | |
317 | */ | |
318 | Dygraph.DateAccessorsLocal = { | |
319 | getFullYear: function(d) {return d.getFullYear();}, | |
320 | getMonth: function(d) {return d.getMonth();}, | |
321 | getDate: function(d) {return d.getDate();}, | |
322 | getHours: function(d) {return d.getHours();}, | |
323 | getMinutes: function(d) {return d.getMinutes();}, | |
324 | getSeconds: function(d) {return d.getSeconds();}, | |
325 | getMilliseconds: function(d) {return d.getMilliseconds();}, | |
326 | getDay: function(d) {return d.getDay();}, | |
327 | makeDate: function(y, m, d, hh, mm, ss, ms) { | |
328 | return new Date(y, m, d, hh, mm, ss, ms); | |
329 | } | |
330 | }; | |
331 | ||
332 | /** | |
b77d7a56 | 333 | * Date accessors to get the parts of a calendar date (year, month, |
1e7f8af0 JPB |
334 | * day of month, hour, minute, second and millisecond) according to UTC time, |
335 | * and factory method to call the Date constructor with an array of arguments. | |
336 | */ | |
337 | Dygraph.DateAccessorsUTC = { | |
338 | getFullYear: function(d) {return d.getUTCFullYear();}, | |
339 | getMonth: function(d) {return d.getUTCMonth();}, | |
340 | getDate: function(d) {return d.getUTCDate();}, | |
341 | getHours: function(d) {return d.getUTCHours();}, | |
342 | getMinutes: function(d) {return d.getUTCMinutes();}, | |
343 | getSeconds: function(d) {return d.getUTCSeconds();}, | |
344 | getMilliseconds: function(d) {return d.getUTCMilliseconds();}, | |
345 | getDay: function(d) {return d.getUTCDay();}, | |
346 | makeDate: function(y, m, d, hh, mm, ss, ms) { | |
347 | return new Date(Date.UTC(y, m, d, hh, mm, ss, ms)); | |
348 | } | |
349 | }; | |
350 | ||
351 | /** | |
dedb4f5f | 352 | * Return a string version of the hours, minutes and seconds portion of a date. |
872a6a00 DV |
353 | * @param {number} hh The hours (from 0-23) |
354 | * @param {number} mm The minutes (from 0-59) | |
355 | * @param {number} ss The seconds (from 0-59) | |
356 | * @return {string} A time of the form "HH:MM" or "HH:MM:SS" | |
dedb4f5f DV |
357 | * @private |
358 | */ | |
872a6a00 | 359 | Dygraph.hmsString_ = function(hh, mm, ss) { |
dedb4f5f | 360 | var zeropad = Dygraph.zeropad; |
872a6a00 DV |
361 | var ret = zeropad(hh) + ":" + zeropad(mm); |
362 | if (ss) { | |
363 | ret += ":" + zeropad(ss); | |
dedb4f5f | 364 | } |
872a6a00 | 365 | return ret; |
dedb4f5f DV |
366 | }; |
367 | ||
368 | /** | |
872a6a00 | 369 | * Convert a JS date (millis since epoch) to a formatted string. |
1e7f8af0 | 370 | * @param {number} time The JavaScript time value (ms since epoch) |
872a6a00 DV |
371 | * @param {boolean} utc Wether output UTC or local time |
372 | * @return {string} A date of one of these forms: | |
373 | * "YYYY/MM/DD", "YYYY/MM/DD HH:MM" or "YYYY/MM/DD HH:MM:SS" | |
464b5f50 DV |
374 | * @private |
375 | */ | |
1e7f8af0 | 376 | Dygraph.dateString_ = function(time, utc) { |
464b5f50 | 377 | var zeropad = Dygraph.zeropad; |
1e7f8af0 JPB |
378 | var accessors = utc ? Dygraph.DateAccessorsUTC : Dygraph.DateAccessorsLocal; |
379 | var date = new Date(time); | |
380 | var y = accessors.getFullYear(date); | |
381 | var m = accessors.getMonth(date); | |
382 | var d = accessors.getDate(date); | |
383 | var hh = accessors.getHours(date); | |
384 | var mm = accessors.getMinutes(date); | |
385 | var ss = accessors.getSeconds(date); | |
872a6a00 DV |
386 | // Get a year string: |
387 | var year = "" + y; | |
464b5f50 | 388 | // Get a 0 padded month string |
872a6a00 | 389 | var month = zeropad(m + 1); //months are 0-offset, sigh |
464b5f50 | 390 | // Get a 0 padded day string |
872a6a00 DV |
391 | var day = zeropad(d); |
392 | var frac = hh * 3600 + mm * 60 + ss; | |
393 | var ret = year + "/" + month + "/" + day; | |
394 | if (frac) { | |
1e7f8af0 | 395 | ret += " " + Dygraph.hmsString_(hh, mm, ss); |
872a6a00 DV |
396 | } |
397 | return ret; | |
464b5f50 DV |
398 | }; |
399 | ||
400 | /** | |
dedb4f5f | 401 | * Round a number to the specified number of digits past the decimal point. |
f11283de DV |
402 | * @param {number} num The number to round |
403 | * @param {number} places The number of decimals to which to round | |
404 | * @return {number} The rounded number | |
dedb4f5f DV |
405 | * @private |
406 | */ | |
407 | Dygraph.round_ = function(num, places) { | |
408 | var shift = Math.pow(10, places); | |
409 | return Math.round(num * shift)/shift; | |
410 | }; | |
411 | ||
412 | /** | |
dedb4f5f DV |
413 | * Implementation of binary search over an array. |
414 | * Currently does not work when val is outside the range of arry's values. | |
f11283de DV |
415 | * @param {number} val the value to search for |
416 | * @param {Array.<number>} arry is the value over which to search | |
417 | * @param {number} abs If abs > 0, find the lowest entry greater than val | |
418 | * If abs < 0, find the highest entry less than val. | |
419 | * If abs == 0, find the entry that equals val. | |
420 | * @param {number=} low The first index in arry to consider (optional) | |
421 | * @param {number=} high The last index in arry to consider (optional) | |
422 | * @return {number} Index of the element, or -1 if it isn't found. | |
423 | * @private | |
dedb4f5f DV |
424 | */ |
425 | Dygraph.binarySearch = function(val, arry, abs, low, high) { | |
758a629f DV |
426 | if (low === null || low === undefined || |
427 | high === null || high === undefined) { | |
dedb4f5f DV |
428 | low = 0; |
429 | high = arry.length - 1; | |
430 | } | |
431 | if (low > high) { | |
432 | return -1; | |
433 | } | |
758a629f | 434 | if (abs === null || abs === undefined) { |
dedb4f5f DV |
435 | abs = 0; |
436 | } | |
437 | var validIndex = function(idx) { | |
438 | return idx >= 0 && idx < arry.length; | |
758a629f DV |
439 | }; |
440 | var mid = parseInt((low + high) / 2, 10); | |
dedb4f5f | 441 | var element = arry[mid]; |
f11283de | 442 | var idx; |
dedb4f5f DV |
443 | if (element == val) { |
444 | return mid; | |
f11283de | 445 | } else if (element > val) { |
dedb4f5f DV |
446 | if (abs > 0) { |
447 | // Accept if element > val, but also if prior element < val. | |
758a629f | 448 | idx = mid - 1; |
dedb4f5f DV |
449 | if (validIndex(idx) && arry[idx] < val) { |
450 | return mid; | |
451 | } | |
452 | } | |
453 | return Dygraph.binarySearch(val, arry, abs, low, mid - 1); | |
f11283de | 454 | } else if (element < val) { |
dedb4f5f DV |
455 | if (abs < 0) { |
456 | // Accept if element < val, but also if prior element > val. | |
758a629f | 457 | idx = mid + 1; |
dedb4f5f DV |
458 | if (validIndex(idx) && arry[idx] > val) { |
459 | return mid; | |
460 | } | |
461 | } | |
462 | return Dygraph.binarySearch(val, arry, abs, mid + 1, high); | |
463 | } | |
f11283de | 464 | return -1; // can't actually happen, but makes closure compiler happy |
dedb4f5f DV |
465 | }; |
466 | ||
467 | /** | |
dedb4f5f DV |
468 | * Parses a date, returning the number of milliseconds since epoch. This can be |
469 | * passed in as an xValueParser in the Dygraph constructor. | |
470 | * TODO(danvk): enumerate formats that this understands. | |
f11283de DV |
471 | * |
472 | * @param {string} dateStr A date in a variety of possible string formats. | |
473 | * @return {number} Milliseconds since epoch. | |
474 | * @private | |
dedb4f5f DV |
475 | */ |
476 | Dygraph.dateParser = function(dateStr) { | |
477 | var dateStrSlashed; | |
478 | var d; | |
769e8bc7 | 479 | |
3f675fe5 DV |
480 | // Let the system try the format first, with one caveat: |
481 | // YYYY-MM-DD[ HH:MM:SS] is interpreted as UTC by a variety of browsers. | |
482 | // dygraphs displays dates in local time, so this will result in surprising | |
483 | // inconsistencies. But if you specify "T" or "Z" (i.e. YYYY-MM-DDTHH:MM:SS), | |
484 | // then you probably know what you're doing, so we'll let you go ahead. | |
485 | // Issue: http://code.google.com/p/dygraphs/issues/detail?id=255 | |
486 | if (dateStr.search("-") == -1 || | |
487 | dateStr.search("T") != -1 || dateStr.search("Z") != -1) { | |
488 | d = Dygraph.dateStrToMillis(dateStr); | |
489 | if (d && !isNaN(d)) return d; | |
490 | } | |
769e8bc7 | 491 | |
dedb4f5f DV |
492 | if (dateStr.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12' |
493 | dateStrSlashed = dateStr.replace("-", "/", "g"); | |
494 | while (dateStrSlashed.search("-") != -1) { | |
495 | dateStrSlashed = dateStrSlashed.replace("-", "/"); | |
496 | } | |
497 | d = Dygraph.dateStrToMillis(dateStrSlashed); | |
498 | } else if (dateStr.length == 8) { // e.g. '20090712' | |
499 | // TODO(danvk): remove support for this format. It's confusing. | |
758a629f DV |
500 | dateStrSlashed = dateStr.substr(0,4) + "/" + dateStr.substr(4,2) + "/" + |
501 | dateStr.substr(6,2); | |
dedb4f5f DV |
502 | d = Dygraph.dateStrToMillis(dateStrSlashed); |
503 | } else { | |
504 | // Any format that Date.parse will accept, e.g. "2009/07/12" or | |
505 | // "2009/07/12 12:34:56" | |
506 | d = Dygraph.dateStrToMillis(dateStr); | |
507 | } | |
508 | ||
509 | if (!d || isNaN(d)) { | |
8a68db7d | 510 | console.error("Couldn't parse " + dateStr + " as a date"); |
dedb4f5f DV |
511 | } |
512 | return d; | |
513 | }; | |
514 | ||
515 | /** | |
dedb4f5f DV |
516 | * This is identical to JavaScript's built-in Date.parse() method, except that |
517 | * it doesn't get replaced with an incompatible method by aggressive JS | |
518 | * libraries like MooTools or Joomla. | |
f11283de DV |
519 | * @param {string} str The date string, e.g. "2011/05/06" |
520 | * @return {number} millis since epoch | |
521 | * @private | |
dedb4f5f DV |
522 | */ |
523 | Dygraph.dateStrToMillis = function(str) { | |
524 | return new Date(str).getTime(); | |
525 | }; | |
526 | ||
527 | // These functions are all based on MochiKit. | |
528 | /** | |
529 | * Copies all the properties from o to self. | |
530 | * | |
f11283de DV |
531 | * @param {!Object} self |
532 | * @param {!Object} o | |
533 | * @return {!Object} | |
dedb4f5f | 534 | */ |
f11283de | 535 | Dygraph.update = function(self, o) { |
dedb4f5f DV |
536 | if (typeof(o) != 'undefined' && o !== null) { |
537 | for (var k in o) { | |
538 | if (o.hasOwnProperty(k)) { | |
539 | self[k] = o[k]; | |
540 | } | |
541 | } | |
542 | } | |
543 | return self; | |
544 | }; | |
545 | ||
546 | /** | |
48e614ac DV |
547 | * Copies all the properties from o to self. |
548 | * | |
f11283de DV |
549 | * @param {!Object} self |
550 | * @param {!Object} o | |
551 | * @return {!Object} | |
48e614ac DV |
552 | * @private |
553 | */ | |
554 | Dygraph.updateDeep = function (self, o) { | |
920208fb PF |
555 | // Taken from http://stackoverflow.com/questions/384286/javascript-isdom-how-do-you-check-if-a-javascript-object-is-a-dom-object |
556 | function isNode(o) { | |
557 | return ( | |
558 | typeof Node === "object" ? o instanceof Node : | |
559 | typeof o === "object" && typeof o.nodeType === "number" && typeof o.nodeName==="string" | |
560 | ); | |
561 | } | |
562 | ||
48e614ac DV |
563 | if (typeof(o) != 'undefined' && o !== null) { |
564 | for (var k in o) { | |
565 | if (o.hasOwnProperty(k)) { | |
758a629f | 566 | if (o[k] === null) { |
48e614ac DV |
567 | self[k] = null; |
568 | } else if (Dygraph.isArrayLike(o[k])) { | |
569 | self[k] = o[k].slice(); | |
920208fb | 570 | } else if (isNode(o[k])) { |
66ad3609 RK |
571 | // DOM objects are shallowly-copied. |
572 | self[k] = o[k]; | |
48e614ac | 573 | } else if (typeof(o[k]) == 'object') { |
c1c5dfeb | 574 | if (typeof(self[k]) != 'object' || self[k] === null) { |
48e614ac DV |
575 | self[k] = {}; |
576 | } | |
577 | Dygraph.updateDeep(self[k], o[k]); | |
578 | } else { | |
579 | self[k] = o[k]; | |
580 | } | |
581 | } | |
582 | } | |
583 | } | |
584 | return self; | |
585 | }; | |
586 | ||
587 | /** | |
55deb02f | 588 | * @param {*} o |
f11283de | 589 | * @return {boolean} |
dedb4f5f DV |
590 | * @private |
591 | */ | |
f11283de | 592 | Dygraph.isArrayLike = function(o) { |
dedb4f5f DV |
593 | var typ = typeof(o); |
594 | if ( | |
595 | (typ != 'object' && !(typ == 'function' && | |
596 | typeof(o.item) == 'function')) || | |
597 | o === null || | |
598 | typeof(o.length) != 'number' || | |
599 | o.nodeType === 3 | |
600 | ) { | |
601 | return false; | |
602 | } | |
603 | return true; | |
604 | }; | |
605 | ||
606 | /** | |
f11283de DV |
607 | * @param {Object} o |
608 | * @return {boolean} | |
dedb4f5f DV |
609 | * @private |
610 | */ | |
611 | Dygraph.isDateLike = function (o) { | |
612 | if (typeof(o) != "object" || o === null || | |
613 | typeof(o.getTime) != 'function') { | |
614 | return false; | |
615 | } | |
616 | return true; | |
617 | }; | |
618 | ||
619 | /** | |
48e614ac | 620 | * Note: this only seems to work for arrays. |
f11283de DV |
621 | * @param {!Array} o |
622 | * @return {!Array} | |
dedb4f5f DV |
623 | * @private |
624 | */ | |
625 | Dygraph.clone = function(o) { | |
626 | // TODO(danvk): figure out how MochiKit's version works | |
627 | var r = []; | |
628 | for (var i = 0; i < o.length; i++) { | |
629 | if (Dygraph.isArrayLike(o[i])) { | |
630 | r.push(Dygraph.clone(o[i])); | |
631 | } else { | |
632 | r.push(o[i]); | |
633 | } | |
634 | } | |
635 | return r; | |
636 | }; | |
637 | ||
638 | /** | |
9901b0c1 | 639 | * Create a new canvas element. |
f11283de DV |
640 | * |
641 | * @return {!HTMLCanvasElement} | |
642 | * @private | |
dedb4f5f DV |
643 | */ |
644 | Dygraph.createCanvas = function() { | |
9901b0c1 | 645 | return document.createElement('canvas'); |
dedb4f5f | 646 | }; |
9ca829f2 DV |
647 | |
648 | /** | |
37819481 PH |
649 | * Returns the context's pixel ratio, which is the ratio between the device |
650 | * pixel ratio and the backing store ratio. Typically this is 1 for conventional | |
651 | * displays, and > 1 for HiDPI displays (such as the Retina MBP). | |
652 | * See http://www.html5rocks.com/en/tutorials/canvas/hidpi/ for more details. | |
653 | * | |
654 | * @param {!CanvasRenderingContext2D} context The canvas's 2d context. | |
655 | * @return {number} The ratio of the device pixel ratio and the backing store | |
656 | * ratio for the specified context. | |
657 | */ | |
658 | Dygraph.getContextPixelRatio = function(context) { | |
659 | try { | |
8241944b GJ |
660 | var devicePixelRatio = window.devicePixelRatio; |
661 | var backingStoreRatio = context.webkitBackingStorePixelRatio || | |
37819481 PH |
662 | context.mozBackingStorePixelRatio || |
663 | context.msBackingStorePixelRatio || | |
664 | context.oBackingStorePixelRatio || | |
3a0e53a4 AK |
665 | context.backingStorePixelRatio || 1; |
666 | if (devicePixelRatio !== undefined) { | |
8241944b GJ |
667 | return devicePixelRatio / backingStoreRatio; |
668 | } else { | |
3a0e53a4 AK |
669 | // At least devicePixelRatio must be defined for this ratio to make sense. |
670 | // We default backingStoreRatio to 1: this does not exist on some browsers | |
671 | // (i.e. desktop Chrome). | |
8241944b GJ |
672 | return 1; |
673 | } | |
37819481 PH |
674 | } catch (e) { |
675 | return 1; | |
676 | } | |
677 | }; | |
678 | ||
679 | /** | |
971870e5 DV |
680 | * Checks whether the user is on an Android browser. |
681 | * Android does not fully support the <canvas> tag, e.g. w/r/t/ clipping. | |
f11283de DV |
682 | * @return {boolean} |
683 | * @private | |
971870e5 DV |
684 | */ |
685 | Dygraph.isAndroid = function() { | |
758a629f | 686 | return (/Android/).test(navigator.userAgent); |
971870e5 DV |
687 | }; |
688 | ||
f11283de DV |
689 | |
690 | /** | |
691 | * TODO(danvk): use @template here when it's better supported for classes. | |
692 | * @param {!Array} array | |
693 | * @param {number} start | |
694 | * @param {number} length | |
45a8c16f | 695 | * @param {function(!Array,?):boolean=} predicate |
f11283de DV |
696 | * @constructor |
697 | */ | |
a26206cf RK |
698 | Dygraph.Iterator = function(array, start, length, predicate) { |
699 | start = start || 0; | |
700 | length = length || array.length; | |
ff1074cd RK |
701 | this.hasNext = true; // Use to identify if there's another element. |
702 | this.peek = null; // Use for look-ahead | |
0f20de1c | 703 | this.start_ = start; |
a26206cf RK |
704 | this.array_ = array; |
705 | this.predicate_ = predicate; | |
706 | this.end_ = Math.min(array.length, start + length); | |
ff1074cd RK |
707 | this.nextIdx_ = start - 1; // use -1 so initial advance works. |
708 | this.next(); // ignoring result. | |
42a9ebb8 | 709 | }; |
a26206cf | 710 | |
f11283de DV |
711 | /** |
712 | * @return {Object} | |
713 | */ | |
a26206cf | 714 | Dygraph.Iterator.prototype.next = function() { |
ff1074cd RK |
715 | if (!this.hasNext) { |
716 | return null; | |
a26206cf | 717 | } |
ff1074cd | 718 | var obj = this.peek; |
a26206cf | 719 | |
ff1074cd RK |
720 | var nextIdx = this.nextIdx_ + 1; |
721 | var found = false; | |
722 | while (nextIdx < this.end_) { | |
a26206cf | 723 | if (!this.predicate_ || this.predicate_(this.array_, nextIdx)) { |
ff1074cd RK |
724 | this.peek = this.array_[nextIdx]; |
725 | found = true; | |
726 | break; | |
a26206cf RK |
727 | } |
728 | nextIdx++; | |
729 | } | |
730 | this.nextIdx_ = nextIdx; | |
ff1074cd RK |
731 | if (!found) { |
732 | this.hasNext = false; | |
733 | this.peek = null; | |
734 | } | |
735 | return obj; | |
42a9ebb8 | 736 | }; |
a26206cf | 737 | |
971870e5 | 738 | /** |
222d67c9 | 739 | * Returns a new iterator over array, between indexes start and |
7d1afbb9 RK |
740 | * start + length, and only returns entries that pass the accept function |
741 | * | |
f11283de DV |
742 | * @param {!Array} array the array to iterate over. |
743 | * @param {number} start the first index to iterate over, 0 if absent. | |
744 | * @param {number} length the number of elements in the array to iterate over. | |
745 | * This, along with start, defines a slice of the array, and so length | |
746 | * doesn't imply the number of elements in the iterator when accept doesn't | |
747 | * always accept all values. array.length when absent. | |
45a8c16f | 748 | * @param {function(?):boolean=} opt_predicate a function that takes |
f11283de DV |
749 | * parameters array and idx, which returns true when the element should be |
750 | * returned. If omitted, all elements are accepted. | |
751 | * @private | |
7d1afbb9 | 752 | */ |
f11283de DV |
753 | Dygraph.createIterator = function(array, start, length, opt_predicate) { |
754 | return new Dygraph.Iterator(array, start, length, opt_predicate); | |
7d1afbb9 RK |
755 | }; |
756 | ||
a96b8ba3 A |
757 | // Shim layer with setTimeout fallback. |
758 | // From: http://paulirish.com/2011/requestanimationframe-for-smart-animating/ | |
e9a32469 A |
759 | // Should be called with the window context: |
760 | // Dygraph.requestAnimFrame.call(window, function() {}) | |
bec100ae | 761 | Dygraph.requestAnimFrame = (function() { |
a96b8ba3 A |
762 | return window.requestAnimationFrame || |
763 | window.webkitRequestAnimationFrame || | |
764 | window.mozRequestAnimationFrame || | |
765 | window.oRequestAnimationFrame || | |
766 | window.msRequestAnimationFrame || | |
767 | function (callback) { | |
768 | window.setTimeout(callback, 1000 / 60); | |
769 | }; | |
770 | })(); | |
771 | ||
772 | /** | |
d91ba598 A |
773 | * Call a function at most maxFrames times at an attempted interval of |
774 | * framePeriodInMillis, then call a cleanup function once. repeatFn is called | |
775 | * once immediately, then at most (maxFrames - 1) times asynchronously. If | |
776 | * maxFrames==1, then cleanup_fn() is also called synchronously. This function | |
777 | * is used to sequence animation. | |
778 | * @param {function(number)} repeatFn Called repeatedly -- takes the frame | |
779 | * number (from 0 to maxFrames-1) as an argument. | |
780 | * @param {number} maxFrames The max number of times to call repeatFn | |
781 | * @param {number} framePeriodInMillis Max requested time between frames. | |
782 | * @param {function()} cleanupFn A function to call after all repeatFn calls. | |
783 | * @private | |
784 | */ | |
785 | Dygraph.repeatAndCleanup = function(repeatFn, maxFrames, framePeriodInMillis, | |
bec100ae | 786 | cleanupFn) { |
d91ba598 A |
787 | var frameNumber = 0; |
788 | var previousFrameNumber; | |
789 | var startTime = new Date().getTime(); | |
790 | repeatFn(frameNumber); | |
791 | if (maxFrames == 1) { | |
792 | cleanupFn(); | |
b1a3b195 DV |
793 | return; |
794 | } | |
d91ba598 | 795 | var maxFrameArg = maxFrames - 1; |
b1a3b195 DV |
796 | |
797 | (function loop() { | |
d91ba598 | 798 | if (frameNumber >= maxFrames) return; |
e9a32469 | 799 | Dygraph.requestAnimFrame.call(window, function() { |
d91ba598 A |
800 | // Determine which frame to draw based on the delay so far. Will skip |
801 | // frames if necessary. | |
802 | var currentTime = new Date().getTime(); | |
803 | var delayInMillis = currentTime - startTime; | |
804 | previousFrameNumber = frameNumber; | |
805 | frameNumber = Math.floor(delayInMillis / framePeriodInMillis); | |
806 | var frameDelta = frameNumber - previousFrameNumber; | |
807 | // If we predict that the subsequent repeatFn call will overshoot our | |
808 | // total frame target, so our last call will cause a stutter, then jump to | |
809 | // the last call immediately. If we're going to cause a stutter, better | |
810 | // to do it faster than slower. | |
811 | var predictOvershootStutter = (frameNumber + frameDelta) > maxFrameArg; | |
812 | if (predictOvershootStutter || (frameNumber >= maxFrameArg)) { | |
813 | repeatFn(maxFrameArg); // Ensure final call with maxFrameArg. | |
814 | cleanupFn(); | |
b1a3b195 | 815 | } else { |
83b0c192 | 816 | if (frameDelta !== 0) { // Don't call repeatFn with duplicate frames. |
d91ba598 A |
817 | repeatFn(frameNumber); |
818 | } | |
b1a3b195 DV |
819 | loop(); |
820 | } | |
a96b8ba3 | 821 | }); |
b1a3b195 DV |
822 | })(); |
823 | }; | |
824 | ||
8887663f DV |
825 | // A whitelist of options that do not change pixel positions. |
826 | var pixelSafeOptions = { | |
827 | 'annotationClickHandler': true, | |
828 | 'annotationDblClickHandler': true, | |
829 | 'annotationMouseOutHandler': true, | |
830 | 'annotationMouseOverHandler': true, | |
831 | 'axisLabelColor': true, | |
832 | 'axisLineColor': true, | |
833 | 'axisLineWidth': true, | |
834 | 'clickCallback': true, | |
835 | 'drawCallback': true, | |
836 | 'drawHighlightPointCallback': true, | |
837 | 'drawPoints': true, | |
838 | 'drawPointCallback': true, | |
bfb3e0a4 | 839 | 'drawGrid': true, |
8887663f DV |
840 | 'fillAlpha': true, |
841 | 'gridLineColor': true, | |
842 | 'gridLineWidth': true, | |
843 | 'hideOverlayOnMouseOut': true, | |
844 | 'highlightCallback': true, | |
845 | 'highlightCircleSize': true, | |
846 | 'interactionModel': true, | |
847 | 'isZoomedIgnoreProgrammaticZoom': true, | |
848 | 'labelsDiv': true, | |
849 | 'labelsDivStyles': true, | |
850 | 'labelsDivWidth': true, | |
851 | 'labelsKMB': true, | |
852 | 'labelsKMG2': true, | |
853 | 'labelsSeparateLines': true, | |
854 | 'labelsShowZeroValues': true, | |
855 | 'legend': true, | |
856 | 'panEdgeFraction': true, | |
857 | 'pixelsPerYLabel': true, | |
858 | 'pointClickCallback': true, | |
859 | 'pointSize': true, | |
860 | 'rangeSelectorPlotFillColor': true, | |
79cb28dd | 861 | 'rangeSelectorPlotFillGradientColor': true, |
8887663f | 862 | 'rangeSelectorPlotStrokeColor': true, |
fb24d32c | 863 | 'rangeSelectorBackgroundStrokeColor': true, |
864 | 'rangeSelectorBackgroundLineWidth': true, | |
b77d7a56 | 865 | 'rangeSelectorPlotLineWidth': true, |
fb24d32c | 866 | 'rangeSelectorForegroundStrokeColor': true, |
867 | 'rangeSelectorForegroundLineWidth': true, | |
b77d7a56 | 868 | 'rangeSelectorAlpha': true, |
8887663f DV |
869 | 'showLabelsOnHighlight': true, |
870 | 'showRoller': true, | |
871 | 'strokeWidth': true, | |
872 | 'underlayCallback': true, | |
873 | 'unhighlightCallback': true, | |
874 | 'zoomCallback': true | |
875 | }; | |
876 | ||
b1a3b195 | 877 | /** |
9ca829f2 DV |
878 | * This function will scan the option list and determine if they |
879 | * require us to recalculate the pixel positions of each point. | |
8887663f | 880 | * TODO: move this into dygraph-options.js |
f11283de | 881 | * @param {!Array.<string>} labels a list of options to check. |
222d67c9 | 882 | * @param {!Object} attrs |
f11283de DV |
883 | * @return {boolean} true if the graph needs new points else false. |
884 | * @private | |
9ca829f2 DV |
885 | */ |
886 | Dygraph.isPixelChangingOptionList = function(labels, attrs) { | |
9ca829f2 DV |
887 | // Assume that we do not require new points. |
888 | // This will change to true if we actually do need new points. | |
9ca829f2 DV |
889 | |
890 | // Create a dictionary of series names for faster lookup. | |
891 | // If there are no labels, then the dictionary stays empty. | |
892 | var seriesNamesDictionary = { }; | |
893 | if (labels) { | |
894 | for (var i = 1; i < labels.length; i++) { | |
895 | seriesNamesDictionary[labels[i]] = true; | |
896 | } | |
897 | } | |
898 | ||
8887663f DV |
899 | // Scan through a flat (i.e. non-nested) object of options. |
900 | // Returns true/false depending on whether new points are needed. | |
901 | var scanFlatOptions = function(options) { | |
902 | for (var property in options) { | |
903 | if (options.hasOwnProperty(property) && | |
904 | !pixelSafeOptions[property]) { | |
905 | return true; | |
906 | } | |
907 | } | |
908 | return false; | |
909 | }; | |
910 | ||
9ca829f2 | 911 | // Iterate through the list of updated options. |
5061b42f | 912 | for (var property in attrs) { |
8887663f DV |
913 | if (!attrs.hasOwnProperty(property)) continue; |
914 | ||
915 | // Find out of this field is actually a series specific options list. | |
916 | if (property == 'highlightSeriesOpts' || | |
917 | (seriesNamesDictionary[property] && !attrs.series)) { | |
918 | // This property value is a list of options for this series. | |
919 | if (scanFlatOptions(attrs[property])) return true; | |
920 | } else if (property == 'series' || property == 'axes') { | |
921 | // This is twice-nested options list. | |
922 | var perSeries = attrs[property]; | |
923 | for (var series in perSeries) { | |
924 | if (perSeries.hasOwnProperty(series) && | |
925 | scanFlatOptions(perSeries[series])) { | |
926 | return true; | |
9ca829f2 | 927 | } |
ccd9d7c2 | 928 | } |
8887663f DV |
929 | } else { |
930 | // If this was not a series specific option list, check if it's a pixel | |
931 | // changing property. | |
932 | if (!pixelSafeOptions[property]) return true; | |
9ca829f2 DV |
933 | } |
934 | } | |
935 | ||
8887663f | 936 | return false; |
9ca829f2 | 937 | }; |
78e58af4 | 938 | |
78e58af4 RK |
939 | Dygraph.Circles = { |
940 | DEFAULT : function(g, name, ctx, canvasx, canvasy, color, radius) { | |
941 | ctx.beginPath(); | |
942 | ctx.fillStyle = color; | |
943 | ctx.arc(canvasx, canvasy, radius, 0, 2 * Math.PI, false); | |
944 | ctx.fill(); | |
78e58af4 | 945 | } |
b7a1dc22 | 946 | // For more shapes, include extras/shapes.js |
78e58af4 | 947 | }; |
2bad4d92 DV |
948 | |
949 | /** | |
950 | * To create a "drag" interaction, you typically register a mousedown event | |
951 | * handler on the element where the drag begins. In that handler, you register a | |
952 | * mouseup handler on the window to determine when the mouse is released, | |
953 | * wherever that release happens. This works well, except when the user releases | |
954 | * the mouse over an off-domain iframe. In that case, the mouseup event is | |
955 | * handled by the iframe and never bubbles up to the window handler. | |
956 | * | |
957 | * To deal with this issue, we cover iframes with high z-index divs to make sure | |
958 | * they don't capture mouseup. | |
959 | * | |
960 | * Usage: | |
961 | * element.addEventListener('mousedown', function() { | |
962 | * var tarper = new Dygraph.IFrameTarp(); | |
963 | * tarper.cover(); | |
964 | * var mouseUpHandler = function() { | |
965 | * ... | |
966 | * window.removeEventListener(mouseUpHandler); | |
967 | * tarper.uncover(); | |
968 | * }; | |
969 | * window.addEventListener('mouseup', mouseUpHandler); | |
970 | * }; | |
222d67c9 | 971 | * |
2bad4d92 DV |
972 | * @constructor |
973 | */ | |
974 | Dygraph.IFrameTarp = function() { | |
f11283de | 975 | /** @type {Array.<!HTMLDivElement>} */ |
2bad4d92 DV |
976 | this.tarps = []; |
977 | }; | |
978 | ||
979 | /** | |
980 | * Find all the iframes in the document and cover them with high z-index | |
981 | * transparent divs. | |
982 | */ | |
983 | Dygraph.IFrameTarp.prototype.cover = function() { | |
984 | var iframes = document.getElementsByTagName("iframe"); | |
985 | for (var i = 0; i < iframes.length; i++) { | |
986 | var iframe = iframes[i]; | |
1bc88216 DV |
987 | var pos = Dygraph.findPos(iframe), |
988 | x = pos.x, | |
989 | y = pos.y, | |
2bad4d92 DV |
990 | width = iframe.offsetWidth, |
991 | height = iframe.offsetHeight; | |
992 | ||
993 | var div = document.createElement("div"); | |
994 | div.style.position = "absolute"; | |
995 | div.style.left = x + 'px'; | |
996 | div.style.top = y + 'px'; | |
997 | div.style.width = width + 'px'; | |
998 | div.style.height = height + 'px'; | |
999 | div.style.zIndex = 999; | |
1000 | document.body.appendChild(div); | |
1001 | this.tarps.push(div); | |
1002 | } | |
1003 | }; | |
1004 | ||
1005 | /** | |
1006 | * Remove all the iframe covers. You should call this in a mouseup handler. | |
1007 | */ | |
1008 | Dygraph.IFrameTarp.prototype.uncover = function() { | |
1009 | for (var i = 0; i < this.tarps.length; i++) { | |
1010 | this.tarps[i].parentNode.removeChild(this.tarps[i]); | |
1011 | } | |
1012 | this.tarps = []; | |
1013 | }; | |
e5763589 DV |
1014 | |
1015 | /** | |
df268bcc | 1016 | * Determine whether |data| is delimited by CR, CRLF, LF, LFCR. |
e5763589 | 1017 | * @param {string} data |
f11283de | 1018 | * @return {?string} the delimiter that was detected (or null on failure). |
e5763589 DV |
1019 | */ |
1020 | Dygraph.detectLineDelimiter = function(data) { | |
1021 | for (var i = 0; i < data.length; i++) { | |
df268bcc JH |
1022 | var code = data.charAt(i); |
1023 | if (code === '\r') { | |
1024 | // Might actually be "\r\n". | |
1025 | if (((i + 1) < data.length) && (data.charAt(i + 1) === '\n')) { | |
1026 | return '\r\n'; | |
1027 | } | |
1028 | return code; | |
1029 | } | |
1030 | if (code === '\n') { | |
e5763589 | 1031 | // Might actually be "\n\r". |
df268bcc JH |
1032 | if (((i + 1) < data.length) && (data.charAt(i + 1) === '\r')) { |
1033 | return '\n\r'; | |
1034 | } | |
e5763589 DV |
1035 | return code; |
1036 | } | |
1037 | } | |
1038 | ||
1039 | return null; | |
1040 | }; | |
def24194 DV |
1041 | |
1042 | /** | |
bcb545f4 LB |
1043 | * Is one node contained by another? |
1044 | * @param {Node} containee The contained node. | |
1045 | * @param {Node} container The container node. | |
def24194 DV |
1046 | * @return {boolean} Whether containee is inside (or equal to) container. |
1047 | * @private | |
1048 | */ | |
bcb545f4 | 1049 | Dygraph.isNodeContainedBy = function(containee, container) { |
def24194 DV |
1050 | if (container === null || containee === null) { |
1051 | return false; | |
1052 | } | |
db775859 RK |
1053 | var containeeNode = /** @type {Node} */ (containee); |
1054 | while (containeeNode && containeeNode !== container) { | |
1055 | containeeNode = containeeNode.parentNode; | |
def24194 | 1056 | } |
db775859 | 1057 | return (containeeNode === container); |
def24194 | 1058 | }; |
2fd143d3 DV |
1059 | |
1060 | ||
1061 | // This masks some numeric issues in older versions of Firefox, | |
1062 | // where 1.0/Math.pow(10,2) != Math.pow(10,-2). | |
1063 | /** @type {function(number,number):number} */ | |
1064 | Dygraph.pow = function(base, exp) { | |
1065 | if (exp < 0) { | |
1066 | return 1.0 / Math.pow(base, -exp); | |
1067 | } | |
1068 | return Math.pow(base, exp); | |
1069 | }; | |
1070 | ||
337a79bc DV |
1071 | var RGBA_RE = /^rgba?\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})(?:,\s*([01](?:\.\d+)?))?\)$/; |
1072 | ||
1073 | /** | |
1074 | * Helper for Dygraph.toRGB_ which parses strings of the form: | |
1075 | * rgb(123, 45, 67) | |
1076 | * rgba(123, 45, 67, 0.5) | |
1077 | * @return parsed {r,g,b,a?} tuple or null. | |
1078 | */ | |
1079 | function parseRGBA(rgbStr) { | |
1080 | var bits = RGBA_RE.exec(rgbStr); | |
1081 | if (!bits) return null; | |
1082 | var r = parseInt(bits[1], 10), | |
1083 | g = parseInt(bits[2], 10), | |
1084 | b = parseInt(bits[3], 10); | |
1085 | if (bits[4]) { | |
1086 | return {r: r, g: g, b: b, a: parseFloat(bits[4])}; | |
1087 | } else { | |
1088 | return {r: r, g: g, b: b}; | |
1089 | } | |
1090 | } | |
1091 | ||
464b5f50 DV |
1092 | /** |
1093 | * Converts any valid CSS color (hex, rgb(), named color) to an RGB tuple. | |
1094 | * | |
b7a1dc22 | 1095 | * @param {!string} colorStr Any valid CSS color string. |
337a79bc | 1096 | * @return {{r:number,g:number,b:number,a:number?}} Parsed RGB tuple. |
464b5f50 DV |
1097 | * @private |
1098 | */ | |
b7a1dc22 | 1099 | Dygraph.toRGB_ = function(colorStr) { |
337a79bc DV |
1100 | // Strategy: First try to parse colorStr directly. This is fast & avoids DOM |
1101 | // manipulation. If that fails (e.g. for named colors like 'red'), then | |
1102 | // create a hidden DOM element and parse its computed color. | |
1103 | var rgb = parseRGBA(colorStr); | |
1104 | if (rgb) return rgb; | |
1105 | ||
464b5f50 | 1106 | var div = document.createElement('div'); |
b7a1dc22 | 1107 | div.style.backgroundColor = colorStr; |
464b5f50 DV |
1108 | div.style.visibility = 'hidden'; |
1109 | document.body.appendChild(div); | |
9901b0c1 | 1110 | var rgbStr = window.getComputedStyle(div, null).backgroundColor; |
464b5f50 | 1111 | document.body.removeChild(div); |
337a79bc | 1112 | return parseRGBA(rgbStr); |
464b5f50 | 1113 | }; |
55deb02f DV |
1114 | |
1115 | /** | |
1116 | * Checks whether the browser supports the <canvas> tag. | |
1117 | * @param {HTMLCanvasElement=} opt_canvasElement Pass a canvas element as an | |
1118 | * optimization if you have one. | |
1119 | * @return {boolean} Whether the browser supports canvas. | |
1120 | */ | |
1121 | Dygraph.isCanvasSupported = function(opt_canvasElement) { | |
55deb02f | 1122 | try { |
9901b0c1 | 1123 | var canvas = opt_canvasElement || document.createElement("canvas"); |
55deb02f | 1124 | canvas.getContext("2d"); |
9901b0c1 DV |
1125 | } catch (e) { |
1126 | return false; | |
55deb02f DV |
1127 | } |
1128 | return true; | |
1129 | }; | |
1130 | ||
1131 | /** | |
1132 | * Parses the value as a floating point number. This is like the parseFloat() | |
1133 | * built-in, but with a few differences: | |
1134 | * - the empty string is parsed as null, rather than NaN. | |
1135 | * - if the string cannot be parsed at all, an error is logged. | |
1136 | * If the string can't be parsed, this method returns null. | |
1137 | * @param {string} x The string to be parsed | |
1138 | * @param {number=} opt_line_no The line number from which the string comes. | |
1139 | * @param {string=} opt_line The text of the line from which the string comes. | |
1140 | */ | |
1141 | Dygraph.parseFloat_ = function(x, opt_line_no, opt_line) { | |
1142 | var val = parseFloat(x); | |
1143 | if (!isNaN(val)) return val; | |
1144 | ||
1145 | // Try to figure out what happeend. | |
1146 | // If the value is the empty string, parse it as null. | |
1147 | if (/^ *$/.test(x)) return null; | |
1148 | ||
1149 | // If it was actually "NaN", return it as NaN. | |
1150 | if (/^ *nan *$/i.test(x)) return NaN; | |
1151 | ||
1152 | // Looks like a parsing error. | |
1153 | var msg = "Unable to parse '" + x + "' as a number"; | |
1154 | if (opt_line !== undefined && opt_line_no !== undefined) { | |
1155 | msg += " on line " + (1+(opt_line_no||0)) + " ('" + opt_line + "') of CSV."; | |
1156 | } | |
8a68db7d | 1157 | console.error(msg); |
55deb02f DV |
1158 | |
1159 | return null; | |
1160 | }; | |
8887663f DV |
1161 | |
1162 | })(); |