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