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 | |
758a629f DV |
14 | /*jshint globalstrict: true */ |
15 | /*global Dygraph:false, G_vmlCanvasManager:false, Node:false, printStackTrace: false */ | |
c0f54d4f DV |
16 | "use strict"; |
17 | ||
dedb4f5f DV |
18 | Dygraph.LOG_SCALE = 10; |
19 | Dygraph.LN_TEN = Math.log(Dygraph.LOG_SCALE); | |
20 | ||
f11283de DV |
21 | /** |
22 | * @private | |
23 | * @param {number} x | |
24 | * @return {number} | |
25 | */ | |
dedb4f5f DV |
26 | Dygraph.log10 = function(x) { |
27 | return Math.log(x) / Dygraph.LN_TEN; | |
758a629f | 28 | }; |
dedb4f5f DV |
29 | |
30 | // Various logging levels. | |
31 | Dygraph.DEBUG = 1; | |
32 | Dygraph.INFO = 2; | |
33 | Dygraph.WARNING = 3; | |
34 | Dygraph.ERROR = 3; | |
35 | ||
00639fab DV |
36 | // Set this to log stack traces on warnings, etc. |
37 | // This requires stacktrace.js, which is up to you to provide. | |
38 | // A copy can be found in the dygraphs repo, or at | |
39 | // https://github.com/eriwen/javascript-stacktrace | |
40 | Dygraph.LOG_STACK_TRACES = false; | |
41 | ||
79253bd0 | 42 | /** A dotted line stroke pattern. */ |
43 | Dygraph.DOTTED_LINE = [2, 2]; | |
44 | /** A dashed line stroke pattern. */ | |
45 | Dygraph.DASHED_LINE = [7, 3]; | |
46 | /** A dot dash stroke pattern. */ | |
47 | Dygraph.DOT_DASH_LINE = [7, 2, 2, 2]; | |
48 | ||
dedb4f5f | 49 | /** |
dedb4f5f | 50 | * Log an error on the JS console at the given severity. |
f11283de DV |
51 | * @param {number} severity One of Dygraph.{DEBUG,INFO,WARNING,ERROR} |
52 | * @param {string} message The message to log. | |
53 | * @private | |
dedb4f5f DV |
54 | */ |
55 | Dygraph.log = function(severity, message) { | |
00639fab DV |
56 | var st; |
57 | if (typeof(printStackTrace) != 'undefined') { | |
df21c270 DV |
58 | try { |
59 | // Remove uninteresting bits: logging functions and paths. | |
60 | st = printStackTrace({guess:false}); | |
61 | while (st[0].indexOf("stacktrace") != -1) { | |
62 | st.splice(0, 1); | |
63 | } | |
0d319fa5 | 64 | |
df21c270 DV |
65 | st.splice(0, 2); |
66 | for (var i = 0; i < st.length; i++) { | |
67 | st[i] = st[i].replace(/\([^)]*\/(.*)\)/, '@$1') | |
68 | .replace(/\@.*\/([^\/]*)/, '@$1') | |
69 | .replace('[object Object].', ''); | |
70 | } | |
71 | var top_msg = st.splice(0, 1)[0]; | |
72 | message += ' (' + top_msg.replace(/^.*@ ?/, '') + ')'; | |
73 | } catch(e) { | |
74 | // Oh well, it was worth a shot! | |
00639fab | 75 | } |
00639fab DV |
76 | } |
77 | ||
f11283de | 78 | if (typeof(window.console) != 'undefined') { |
33e96f11 DV |
79 | // In older versions of Firefox, only console.log is defined. |
80 | var console = window.console; | |
81 | var log = function(console, method, msg) { | |
94ee0648 | 82 | if (method && typeof(method) == 'function') { |
33e96f11 DV |
83 | method.call(console, msg); |
84 | } else { | |
85 | console.log(msg); | |
86 | } | |
87 | }; | |
88 | ||
dedb4f5f DV |
89 | switch (severity) { |
90 | case Dygraph.DEBUG: | |
33e96f11 | 91 | log(console, console.debug, 'dygraphs: ' + message); |
dedb4f5f DV |
92 | break; |
93 | case Dygraph.INFO: | |
33e96f11 | 94 | log(console, console.info, 'dygraphs: ' + message); |
dedb4f5f DV |
95 | break; |
96 | case Dygraph.WARNING: | |
33e96f11 | 97 | log(console, console.warn, 'dygraphs: ' + message); |
dedb4f5f DV |
98 | break; |
99 | case Dygraph.ERROR: | |
33e96f11 | 100 | log(console, console.error, 'dygraphs: ' + message); |
dedb4f5f DV |
101 | break; |
102 | } | |
103 | } | |
00639fab DV |
104 | |
105 | if (Dygraph.LOG_STACK_TRACES) { | |
f11283de | 106 | window.console.log(st.join('\n')); |
00639fab | 107 | } |
dedb4f5f DV |
108 | }; |
109 | ||
f11283de DV |
110 | /** |
111 | * @param {string} message | |
112 | * @private | |
113 | */ | |
dedb4f5f DV |
114 | Dygraph.info = function(message) { |
115 | Dygraph.log(Dygraph.INFO, message); | |
116 | }; | |
f11283de DV |
117 | /** |
118 | * @param {string} message | |
119 | * @private | |
120 | */ | |
dedb4f5f DV |
121 | Dygraph.prototype.info = Dygraph.info; |
122 | ||
f11283de DV |
123 | /** |
124 | * @param {string} message | |
125 | * @private | |
126 | */ | |
dedb4f5f DV |
127 | Dygraph.warn = function(message) { |
128 | Dygraph.log(Dygraph.WARNING, message); | |
129 | }; | |
f11283de DV |
130 | /** |
131 | * @param {string} message | |
132 | * @private | |
133 | */ | |
dedb4f5f DV |
134 | Dygraph.prototype.warn = Dygraph.warn; |
135 | ||
f11283de DV |
136 | /** |
137 | * @param {string} message | |
138 | * @private | |
139 | */ | |
dedb4f5f DV |
140 | Dygraph.error = function(message) { |
141 | Dygraph.log(Dygraph.ERROR, message); | |
142 | }; | |
f11283de DV |
143 | /** |
144 | * @param {string} message | |
145 | * @private | |
146 | */ | |
dedb4f5f DV |
147 | Dygraph.prototype.error = Dygraph.error; |
148 | ||
149 | /** | |
dedb4f5f DV |
150 | * Return the 2d context for a dygraph canvas. |
151 | * | |
152 | * This method is only exposed for the sake of replacing the function in | |
153 | * automated tests, e.g. | |
154 | * | |
155 | * var oldFunc = Dygraph.getContext(); | |
156 | * Dygraph.getContext = function(canvas) { | |
157 | * var realContext = oldFunc(canvas); | |
158 | * return new Proxy(realContext); | |
159 | * }; | |
f11283de DV |
160 | * @param {!HTMLCanvasElement} canvas |
161 | * @return {!CanvasRenderingContext2D} | |
162 | * @private | |
dedb4f5f DV |
163 | */ |
164 | Dygraph.getContext = function(canvas) { | |
f11283de | 165 | return /** @type{!CanvasRenderingContext2D}*/(canvas.getContext("2d")); |
dedb4f5f DV |
166 | }; |
167 | ||
168 | /** | |
dedb4f5f DV |
169 | * Add an event handler. This smooths a difference between IE and the rest of |
170 | * the world. | |
f11283de DV |
171 | * @param { !Element } elem The element to add the event to. |
172 | * @param { string } type The type of the event, e.g. 'click' or 'mousemove'. | |
173 | * @param { function(Event):(boolean|undefined) } fn The function to call | |
174 | * on the event. The function takes one parameter: the event object. | |
175 | * @private | |
dedb4f5f | 176 | */ |
1cc3540b | 177 | Dygraph.addEvent = function addEvent(elem, type, fn) { |
ccd9d7c2 PF |
178 | if (elem.addEventListener) { |
179 | elem.addEventListener(type, fn, false); | |
180 | } else { | |
181 | elem[type+fn] = function(){fn(window.event);}; | |
182 | elem.attachEvent('on'+type, elem[type+fn]); | |
183 | } | |
1cc3540b RK |
184 | }; |
185 | ||
186 | /** | |
1cc3540b RK |
187 | * Add an event handler. This event handler is kept until the graph is |
188 | * destroyed with a call to graph.destroy(). | |
189 | * | |
f11283de DV |
190 | * @param { !Element } elem The element to add the event to. |
191 | * @param { string } type The type of the event, e.g. 'click' or 'mousemove'. | |
192 | * @param { function(Event):(boolean|undefined) } fn The function to call | |
193 | * on the event. The function takes one parameter: the event object. | |
194 | * @private | |
1cc3540b | 195 | */ |
aeca29ac | 196 | Dygraph.prototype.addAndTrackEvent = function(elem, type, fn) { |
1cc3540b | 197 | Dygraph.addEvent(elem, type, fn); |
6a4587ac | 198 | this.registeredEvents_.push({ elem : elem, type : type, fn : fn }); |
ccd9d7c2 PF |
199 | }; |
200 | ||
201 | /** | |
f11283de DV |
202 | * Remove an event handler. This smooths a difference between IE and the rest |
203 | * of the world. | |
204 | * @param {!Element} elem The element to add the event to. | |
205 | * @param {string} type The type of the event, e.g. 'click' or 'mousemove'. | |
206 | * @param {function(Event):(boolean|undefined)} fn The function to call | |
207 | * on the event. The function takes one parameter: the event object. | |
ccd9d7c2 | 208 | * @private |
ccd9d7c2 | 209 | */ |
a537fd67 | 210 | Dygraph.removeEvent = function(elem, type, fn) { |
ccd9d7c2 PF |
211 | if (elem.removeEventListener) { |
212 | elem.removeEventListener(type, fn, false); | |
213 | } else { | |
e2769469 DV |
214 | try { |
215 | elem.detachEvent('on'+type, elem[type+fn]); | |
216 | } catch(e) { | |
217 | // We only detach event listeners on a "best effort" basis in IE. See: | |
218 | // http://stackoverflow.com/questions/2553632/detachevent-not-working-with-named-inline-functions | |
219 | } | |
ccd9d7c2 | 220 | elem[type+fn] = null; |
dedb4f5f DV |
221 | } |
222 | }; | |
223 | ||
aeca29ac RK |
224 | Dygraph.prototype.removeTrackedEvents_ = function() { |
225 | if (this.registeredEvents_) { | |
226 | for (var idx = 0; idx < this.registeredEvents_.length; idx++) { | |
227 | var reg = this.registeredEvents_[idx]; | |
228 | Dygraph.removeEvent(reg.elem, reg.type, reg.fn); | |
229 | } | |
230 | } | |
231 | ||
232 | this.registeredEvents_ = []; | |
233 | } | |
234 | ||
dedb4f5f | 235 | /** |
dedb4f5f DV |
236 | * Cancels further processing of an event. This is useful to prevent default |
237 | * browser actions, e.g. highlighting text on a double-click. | |
238 | * Based on the article at | |
239 | * http://www.switchonthecode.com/tutorials/javascript-tutorial-the-scroll-wheel | |
f11283de DV |
240 | * @param { !Event } e The event whose normal behavior should be canceled. |
241 | * @private | |
dedb4f5f DV |
242 | */ |
243 | Dygraph.cancelEvent = function(e) { | |
244 | e = e ? e : window.event; | |
245 | if (e.stopPropagation) { | |
246 | e.stopPropagation(); | |
247 | } | |
248 | if (e.preventDefault) { | |
249 | e.preventDefault(); | |
250 | } | |
251 | e.cancelBubble = true; | |
252 | e.cancel = true; | |
253 | e.returnValue = false; | |
254 | return false; | |
255 | }; | |
256 | ||
257 | /** | |
258 | * Convert hsv values to an rgb(r,g,b) string. Taken from MochiKit.Color. This | |
259 | * is used to generate default series colors which are evenly spaced on the | |
260 | * color wheel. | |
f11283de DV |
261 | * @param { number } hue Range is 0.0-1.0. |
262 | * @param { number } saturation Range is 0.0-1.0. | |
263 | * @param { number } value Range is 0.0-1.0. | |
264 | * @return { string } "rgb(r,g,b)" where r, g and b range from 0-255. | |
dedb4f5f DV |
265 | * @private |
266 | */ | |
267 | Dygraph.hsvToRGB = function (hue, saturation, value) { | |
268 | var red; | |
269 | var green; | |
270 | var blue; | |
271 | if (saturation === 0) { | |
272 | red = value; | |
273 | green = value; | |
274 | blue = value; | |
275 | } else { | |
276 | var i = Math.floor(hue * 6); | |
277 | var f = (hue * 6) - i; | |
278 | var p = value * (1 - saturation); | |
279 | var q = value * (1 - (saturation * f)); | |
280 | var t = value * (1 - (saturation * (1 - f))); | |
281 | switch (i) { | |
282 | case 1: red = q; green = value; blue = p; break; | |
283 | case 2: red = p; green = value; blue = t; break; | |
284 | case 3: red = p; green = q; blue = value; break; | |
285 | case 4: red = t; green = p; blue = value; break; | |
286 | case 5: red = value; green = p; blue = q; break; | |
287 | case 6: // fall through | |
288 | case 0: red = value; green = t; blue = p; break; | |
289 | } | |
290 | } | |
291 | red = Math.floor(255 * red + 0.5); | |
292 | green = Math.floor(255 * green + 0.5); | |
293 | blue = Math.floor(255 * blue + 0.5); | |
294 | return 'rgb(' + red + ',' + green + ',' + blue + ')'; | |
295 | }; | |
296 | ||
297 | // The following functions are from quirksmode.org with a modification for Safari from | |
298 | // http://blog.firetree.net/2005/07/04/javascript-find-position/ | |
299 | // http://www.quirksmode.org/js/findpos.html | |
1bc38cbc | 300 | // ... and modifications to support scrolling divs. |
dedb4f5f | 301 | |
8442269f RK |
302 | /** |
303 | * Find the x-coordinate of the supplied object relative to the left side | |
304 | * of the page. | |
f11283de DV |
305 | * TODO(danvk): change obj type from Node -> !Node |
306 | * @param {Node} obj | |
307 | * @return {number} | |
8442269f RK |
308 | * @private |
309 | */ | |
dedb4f5f DV |
310 | Dygraph.findPosX = function(obj) { |
311 | var curleft = 0; | |
8442269f RK |
312 | if(obj.offsetParent) { |
313 | var copyObj = obj; | |
314 | while(1) { | |
ecdb6dff | 315 | // NOTE: the if statement here is for IE8. |
4ff8c62e DV |
316 | var borderLeft = "0"; |
317 | if (window.getComputedStyle) { | |
318 | borderLeft = window.getComputedStyle(copyObj, null).borderLeft || "0"; | |
319 | } | |
abc8c570 | 320 | curleft += parseInt(borderLeft, 10) ; |
8442269f RK |
321 | curleft += copyObj.offsetLeft; |
322 | if(!copyObj.offsetParent) { | |
dedb4f5f | 323 | break; |
8442269f RK |
324 | } |
325 | copyObj = copyObj.offsetParent; | |
dedb4f5f | 326 | } |
8442269f | 327 | } else if(obj.x) { |
dedb4f5f | 328 | curleft += obj.x; |
8442269f RK |
329 | } |
330 | // This handles the case where the object is inside a scrolled div. | |
331 | while(obj && obj != document.body) { | |
332 | curleft -= obj.scrollLeft; | |
333 | obj = obj.parentNode; | |
334 | } | |
dedb4f5f DV |
335 | return curleft; |
336 | }; | |
337 | ||
8442269f RK |
338 | /** |
339 | * Find the y-coordinate of the supplied object relative to the top of the | |
340 | * page. | |
f11283de DV |
341 | * TODO(danvk): change obj type from Node -> !Node |
342 | * TODO(danvk): consolidate with findPosX and return an {x, y} object. | |
343 | * @param {Node} obj | |
344 | * @return {number} | |
8442269f RK |
345 | * @private |
346 | */ | |
dedb4f5f DV |
347 | Dygraph.findPosY = function(obj) { |
348 | var curtop = 0; | |
8442269f RK |
349 | if(obj.offsetParent) { |
350 | var copyObj = obj; | |
351 | while(1) { | |
ecdb6dff | 352 | // NOTE: the if statement here is for IE8. |
4ff8c62e DV |
353 | var borderTop = "0"; |
354 | if (window.getComputedStyle) { | |
355 | borderTop = window.getComputedStyle(copyObj, null).borderTop || "0"; | |
356 | } | |
abc8c570 | 357 | curtop += parseInt(borderTop, 10) ; |
8442269f RK |
358 | curtop += copyObj.offsetTop; |
359 | if(!copyObj.offsetParent) { | |
dedb4f5f | 360 | break; |
8442269f RK |
361 | } |
362 | copyObj = copyObj.offsetParent; | |
dedb4f5f | 363 | } |
8442269f | 364 | } else if(obj.y) { |
dedb4f5f | 365 | curtop += obj.y; |
8442269f RK |
366 | } |
367 | // This handles the case where the object is inside a scrolled div. | |
368 | while(obj && obj != document.body) { | |
369 | curtop -= obj.scrollTop; | |
370 | obj = obj.parentNode; | |
371 | } | |
dedb4f5f DV |
372 | return curtop; |
373 | }; | |
374 | ||
375 | /** | |
dedb4f5f DV |
376 | * Returns the x-coordinate of the event in a coordinate system where the |
377 | * top-left corner of the page (not the window) is (0,0). | |
378 | * Taken from MochiKit.Signal | |
f11283de DV |
379 | * @param {!Event} e |
380 | * @return {number} | |
381 | * @private | |
dedb4f5f DV |
382 | */ |
383 | Dygraph.pageX = function(e) { | |
384 | if (e.pageX) { | |
385 | return (!e.pageX || e.pageX < 0) ? 0 : e.pageX; | |
386 | } else { | |
f11283de | 387 | var de = document.documentElement; |
dedb4f5f DV |
388 | var b = document.body; |
389 | return e.clientX + | |
390 | (de.scrollLeft || b.scrollLeft) - | |
391 | (de.clientLeft || 0); | |
392 | } | |
393 | }; | |
394 | ||
395 | /** | |
dedb4f5f DV |
396 | * Returns the y-coordinate of the event in a coordinate system where the |
397 | * top-left corner of the page (not the window) is (0,0). | |
398 | * Taken from MochiKit.Signal | |
f11283de DV |
399 | * @param {!Event} e |
400 | * @return {number} | |
401 | * @private | |
dedb4f5f DV |
402 | */ |
403 | Dygraph.pageY = function(e) { | |
404 | if (e.pageY) { | |
405 | return (!e.pageY || e.pageY < 0) ? 0 : e.pageY; | |
406 | } else { | |
f11283de | 407 | var de = document.documentElement; |
dedb4f5f DV |
408 | var b = document.body; |
409 | return e.clientY + | |
410 | (de.scrollTop || b.scrollTop) - | |
411 | (de.clientTop || 0); | |
412 | } | |
413 | }; | |
414 | ||
415 | /** | |
f11283de DV |
416 | * This returns true unless the parameter is 0, null, undefined or NaN. |
417 | * TODO(danvk): rename this function to something like 'isNonZeroNan'. | |
418 | * | |
419 | * @param {number} x The number to consider. | |
420 | * @return {boolean} Whether the number is zero or NaN. | |
dedb4f5f | 421 | * @private |
dedb4f5f | 422 | */ |
dedb4f5f | 423 | Dygraph.isOK = function(x) { |
f11283de | 424 | return !!x && !isNaN(x); |
dedb4f5f DV |
425 | }; |
426 | ||
427 | /** | |
f11283de DV |
428 | * @param { {x:?number,y:?number,yval:?number} } p The point to consider, valid |
429 | * points are {x, y} objects | |
430 | * @param { boolean } allowNaNY Treat point with y=NaN as valid | |
431 | * @return { boolean } Whether the point has numeric x and y. | |
62c3d2fd | 432 | * @private |
62c3d2fd | 433 | */ |
04c104d7 | 434 | Dygraph.isValidPoint = function(p, allowNaNY) { |
f11283de DV |
435 | if (!p) return false; // null or undefined object |
436 | if (p.yval === null) return false; // missing point | |
04c104d7 KW |
437 | if (p.x === null || p.x === undefined) return false; |
438 | if (p.y === null || p.y === undefined) return false; | |
439 | if (isNaN(p.x) || (!allowNaNY && isNaN(p.y))) return false; | |
62c3d2fd KW |
440 | return true; |
441 | }; | |
442 | ||
443 | /** | |
dedb4f5f DV |
444 | * Number formatting function which mimicks the behavior of %g in printf, i.e. |
445 | * either exponential or fixed format (without trailing 0s) is used depending on | |
446 | * the length of the generated string. The advantage of this format is that | |
447 | * there is a predictable upper bound on the resulting string length, | |
448 | * significant figures are not dropped, and normal numbers are not displayed in | |
449 | * exponential notation. | |
450 | * | |
451 | * NOTE: JavaScript's native toPrecision() is NOT a drop-in replacement for %g. | |
452 | * It creates strings which are too long for absolute values between 10^-4 and | |
453 | * 10^-6, e.g. '0.00001' instead of '1e-5'. See tests/number-format.html for | |
454 | * output examples. | |
455 | * | |
f11283de DV |
456 | * @param {number} x The number to format |
457 | * @param {number=} opt_precision The precision to use, default 2. | |
458 | * @return {string} A string formatted like %g in printf. The max generated | |
dedb4f5f DV |
459 | * string length should be precision + 6 (e.g 1.123e+300). |
460 | */ | |
461 | Dygraph.floatFormat = function(x, opt_precision) { | |
462 | // Avoid invalid precision values; [1, 21] is the valid range. | |
463 | var p = Math.min(Math.max(1, opt_precision || 2), 21); | |
464 | ||
465 | // This is deceptively simple. The actual algorithm comes from: | |
466 | // | |
467 | // Max allowed length = p + 4 | |
468 | // where 4 comes from 'e+n' and '.'. | |
469 | // | |
470 | // Length of fixed format = 2 + y + p | |
471 | // where 2 comes from '0.' and y = # of leading zeroes. | |
472 | // | |
473 | // Equating the two and solving for y yields y = 2, or 0.00xxxx which is | |
474 | // 1.0e-3. | |
475 | // | |
476 | // Since the behavior of toPrecision() is identical for larger numbers, we | |
477 | // don't have to worry about the other bound. | |
478 | // | |
479 | // Finally, the argument for toExponential() is the number of trailing digits, | |
480 | // so we take off 1 for the value before the '.'. | |
758a629f | 481 | return (Math.abs(x) < 1.0e-3 && x !== 0.0) ? |
dedb4f5f DV |
482 | x.toExponential(p - 1) : x.toPrecision(p); |
483 | }; | |
484 | ||
485 | /** | |
dedb4f5f | 486 | * Converts '9' to '09' (useful for dates) |
f11283de DV |
487 | * @param {number} x |
488 | * @return {string} | |
489 | * @private | |
dedb4f5f DV |
490 | */ |
491 | Dygraph.zeropad = function(x) { | |
492 | if (x < 10) return "0" + x; else return "" + x; | |
493 | }; | |
494 | ||
495 | /** | |
496 | * Return a string version of the hours, minutes and seconds portion of a date. | |
f11283de DV |
497 | * |
498 | * @param {number} date The JavaScript date (ms since epoch) | |
499 | * @return {string} A time of the form "HH:MM:SS" | |
dedb4f5f DV |
500 | * @private |
501 | */ | |
502 | Dygraph.hmsString_ = function(date) { | |
503 | var zeropad = Dygraph.zeropad; | |
504 | var d = new Date(date); | |
505 | if (d.getSeconds()) { | |
506 | return zeropad(d.getHours()) + ":" + | |
507 | zeropad(d.getMinutes()) + ":" + | |
508 | zeropad(d.getSeconds()); | |
509 | } else { | |
510 | return zeropad(d.getHours()) + ":" + zeropad(d.getMinutes()); | |
511 | } | |
512 | }; | |
513 | ||
514 | /** | |
dedb4f5f | 515 | * Round a number to the specified number of digits past the decimal point. |
f11283de DV |
516 | * @param {number} num The number to round |
517 | * @param {number} places The number of decimals to which to round | |
518 | * @return {number} The rounded number | |
dedb4f5f DV |
519 | * @private |
520 | */ | |
521 | Dygraph.round_ = function(num, places) { | |
522 | var shift = Math.pow(10, places); | |
523 | return Math.round(num * shift)/shift; | |
524 | }; | |
525 | ||
526 | /** | |
dedb4f5f DV |
527 | * Implementation of binary search over an array. |
528 | * Currently does not work when val is outside the range of arry's values. | |
f11283de DV |
529 | * @param {number} val the value to search for |
530 | * @param {Array.<number>} arry is the value over which to search | |
531 | * @param {number} abs If abs > 0, find the lowest entry greater than val | |
532 | * If abs < 0, find the highest entry less than val. | |
533 | * If abs == 0, find the entry that equals val. | |
534 | * @param {number=} low The first index in arry to consider (optional) | |
535 | * @param {number=} high The last index in arry to consider (optional) | |
536 | * @return {number} Index of the element, or -1 if it isn't found. | |
537 | * @private | |
dedb4f5f DV |
538 | */ |
539 | Dygraph.binarySearch = function(val, arry, abs, low, high) { | |
758a629f DV |
540 | if (low === null || low === undefined || |
541 | high === null || high === undefined) { | |
dedb4f5f DV |
542 | low = 0; |
543 | high = arry.length - 1; | |
544 | } | |
545 | if (low > high) { | |
546 | return -1; | |
547 | } | |
758a629f | 548 | if (abs === null || abs === undefined) { |
dedb4f5f DV |
549 | abs = 0; |
550 | } | |
551 | var validIndex = function(idx) { | |
552 | return idx >= 0 && idx < arry.length; | |
758a629f DV |
553 | }; |
554 | var mid = parseInt((low + high) / 2, 10); | |
dedb4f5f | 555 | var element = arry[mid]; |
f11283de | 556 | var idx; |
dedb4f5f DV |
557 | if (element == val) { |
558 | return mid; | |
f11283de | 559 | } else if (element > val) { |
dedb4f5f DV |
560 | if (abs > 0) { |
561 | // Accept if element > val, but also if prior element < val. | |
758a629f | 562 | idx = mid - 1; |
dedb4f5f DV |
563 | if (validIndex(idx) && arry[idx] < val) { |
564 | return mid; | |
565 | } | |
566 | } | |
567 | return Dygraph.binarySearch(val, arry, abs, low, mid - 1); | |
f11283de | 568 | } else if (element < val) { |
dedb4f5f DV |
569 | if (abs < 0) { |
570 | // Accept if element < val, but also if prior element > val. | |
758a629f | 571 | idx = mid + 1; |
dedb4f5f DV |
572 | if (validIndex(idx) && arry[idx] > val) { |
573 | return mid; | |
574 | } | |
575 | } | |
576 | return Dygraph.binarySearch(val, arry, abs, mid + 1, high); | |
577 | } | |
f11283de | 578 | return -1; // can't actually happen, but makes closure compiler happy |
dedb4f5f DV |
579 | }; |
580 | ||
581 | /** | |
dedb4f5f DV |
582 | * Parses a date, returning the number of milliseconds since epoch. This can be |
583 | * passed in as an xValueParser in the Dygraph constructor. | |
584 | * TODO(danvk): enumerate formats that this understands. | |
f11283de DV |
585 | * |
586 | * @param {string} dateStr A date in a variety of possible string formats. | |
587 | * @return {number} Milliseconds since epoch. | |
588 | * @private | |
dedb4f5f DV |
589 | */ |
590 | Dygraph.dateParser = function(dateStr) { | |
591 | var dateStrSlashed; | |
592 | var d; | |
769e8bc7 | 593 | |
3f675fe5 DV |
594 | // Let the system try the format first, with one caveat: |
595 | // YYYY-MM-DD[ HH:MM:SS] is interpreted as UTC by a variety of browsers. | |
596 | // dygraphs displays dates in local time, so this will result in surprising | |
597 | // inconsistencies. But if you specify "T" or "Z" (i.e. YYYY-MM-DDTHH:MM:SS), | |
598 | // then you probably know what you're doing, so we'll let you go ahead. | |
599 | // Issue: http://code.google.com/p/dygraphs/issues/detail?id=255 | |
600 | if (dateStr.search("-") == -1 || | |
601 | dateStr.search("T") != -1 || dateStr.search("Z") != -1) { | |
602 | d = Dygraph.dateStrToMillis(dateStr); | |
603 | if (d && !isNaN(d)) return d; | |
604 | } | |
769e8bc7 | 605 | |
dedb4f5f DV |
606 | if (dateStr.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12' |
607 | dateStrSlashed = dateStr.replace("-", "/", "g"); | |
608 | while (dateStrSlashed.search("-") != -1) { | |
609 | dateStrSlashed = dateStrSlashed.replace("-", "/"); | |
610 | } | |
611 | d = Dygraph.dateStrToMillis(dateStrSlashed); | |
612 | } else if (dateStr.length == 8) { // e.g. '20090712' | |
613 | // TODO(danvk): remove support for this format. It's confusing. | |
758a629f DV |
614 | dateStrSlashed = dateStr.substr(0,4) + "/" + dateStr.substr(4,2) + "/" + |
615 | dateStr.substr(6,2); | |
dedb4f5f DV |
616 | d = Dygraph.dateStrToMillis(dateStrSlashed); |
617 | } else { | |
618 | // Any format that Date.parse will accept, e.g. "2009/07/12" or | |
619 | // "2009/07/12 12:34:56" | |
620 | d = Dygraph.dateStrToMillis(dateStr); | |
621 | } | |
622 | ||
623 | if (!d || isNaN(d)) { | |
624 | Dygraph.error("Couldn't parse " + dateStr + " as a date"); | |
625 | } | |
626 | return d; | |
627 | }; | |
628 | ||
629 | /** | |
dedb4f5f DV |
630 | * This is identical to JavaScript's built-in Date.parse() method, except that |
631 | * it doesn't get replaced with an incompatible method by aggressive JS | |
632 | * libraries like MooTools or Joomla. | |
f11283de DV |
633 | * @param {string} str The date string, e.g. "2011/05/06" |
634 | * @return {number} millis since epoch | |
635 | * @private | |
dedb4f5f DV |
636 | */ |
637 | Dygraph.dateStrToMillis = function(str) { | |
638 | return new Date(str).getTime(); | |
639 | }; | |
640 | ||
641 | // These functions are all based on MochiKit. | |
642 | /** | |
643 | * Copies all the properties from o to self. | |
644 | * | |
f11283de DV |
645 | * @param {!Object} self |
646 | * @param {!Object} o | |
647 | * @return {!Object} | |
dedb4f5f DV |
648 | * @private |
649 | */ | |
f11283de | 650 | Dygraph.update = function(self, o) { |
dedb4f5f DV |
651 | if (typeof(o) != 'undefined' && o !== null) { |
652 | for (var k in o) { | |
653 | if (o.hasOwnProperty(k)) { | |
654 | self[k] = o[k]; | |
655 | } | |
656 | } | |
657 | } | |
658 | return self; | |
659 | }; | |
660 | ||
661 | /** | |
48e614ac DV |
662 | * Copies all the properties from o to self. |
663 | * | |
f11283de DV |
664 | * @param {!Object} self |
665 | * @param {!Object} o | |
666 | * @return {!Object} | |
48e614ac DV |
667 | * @private |
668 | */ | |
669 | Dygraph.updateDeep = function (self, o) { | |
920208fb PF |
670 | // Taken from http://stackoverflow.com/questions/384286/javascript-isdom-how-do-you-check-if-a-javascript-object-is-a-dom-object |
671 | function isNode(o) { | |
672 | return ( | |
673 | typeof Node === "object" ? o instanceof Node : | |
674 | typeof o === "object" && typeof o.nodeType === "number" && typeof o.nodeName==="string" | |
675 | ); | |
676 | } | |
677 | ||
48e614ac DV |
678 | if (typeof(o) != 'undefined' && o !== null) { |
679 | for (var k in o) { | |
680 | if (o.hasOwnProperty(k)) { | |
758a629f | 681 | if (o[k] === null) { |
48e614ac DV |
682 | self[k] = null; |
683 | } else if (Dygraph.isArrayLike(o[k])) { | |
684 | self[k] = o[k].slice(); | |
920208fb | 685 | } else if (isNode(o[k])) { |
66ad3609 RK |
686 | // DOM objects are shallowly-copied. |
687 | self[k] = o[k]; | |
48e614ac | 688 | } else if (typeof(o[k]) == 'object') { |
c1c5dfeb | 689 | if (typeof(self[k]) != 'object' || self[k] === null) { |
48e614ac DV |
690 | self[k] = {}; |
691 | } | |
692 | Dygraph.updateDeep(self[k], o[k]); | |
693 | } else { | |
694 | self[k] = o[k]; | |
695 | } | |
696 | } | |
697 | } | |
698 | } | |
699 | return self; | |
700 | }; | |
701 | ||
702 | /** | |
f11283de DV |
703 | * @param {Object} o |
704 | * @return {boolean} | |
dedb4f5f DV |
705 | * @private |
706 | */ | |
f11283de | 707 | Dygraph.isArrayLike = function(o) { |
dedb4f5f DV |
708 | var typ = typeof(o); |
709 | if ( | |
710 | (typ != 'object' && !(typ == 'function' && | |
711 | typeof(o.item) == 'function')) || | |
712 | o === null || | |
713 | typeof(o.length) != 'number' || | |
714 | o.nodeType === 3 | |
715 | ) { | |
716 | return false; | |
717 | } | |
718 | return true; | |
719 | }; | |
720 | ||
721 | /** | |
f11283de DV |
722 | * @param {Object} o |
723 | * @return {boolean} | |
dedb4f5f DV |
724 | * @private |
725 | */ | |
726 | Dygraph.isDateLike = function (o) { | |
727 | if (typeof(o) != "object" || o === null || | |
728 | typeof(o.getTime) != 'function') { | |
729 | return false; | |
730 | } | |
731 | return true; | |
732 | }; | |
733 | ||
734 | /** | |
48e614ac | 735 | * Note: this only seems to work for arrays. |
f11283de DV |
736 | * @param {!Array} o |
737 | * @return {!Array} | |
dedb4f5f DV |
738 | * @private |
739 | */ | |
740 | Dygraph.clone = function(o) { | |
741 | // TODO(danvk): figure out how MochiKit's version works | |
742 | var r = []; | |
743 | for (var i = 0; i < o.length; i++) { | |
744 | if (Dygraph.isArrayLike(o[i])) { | |
745 | r.push(Dygraph.clone(o[i])); | |
746 | } else { | |
747 | r.push(o[i]); | |
748 | } | |
749 | } | |
750 | return r; | |
751 | }; | |
752 | ||
753 | /** | |
dedb4f5f DV |
754 | * Create a new canvas element. This is more complex than a simple |
755 | * document.createElement("canvas") because of IE and excanvas. | |
f11283de DV |
756 | * |
757 | * @return {!HTMLCanvasElement} | |
758 | * @private | |
dedb4f5f DV |
759 | */ |
760 | Dygraph.createCanvas = function() { | |
761 | var canvas = document.createElement("canvas"); | |
762 | ||
c0f54d4f | 763 | var isIE = (/MSIE/.test(navigator.userAgent) && !window.opera); |
dedb4f5f | 764 | if (isIE && (typeof(G_vmlCanvasManager) != 'undefined')) { |
f11283de DV |
765 | canvas = G_vmlCanvasManager.initElement( |
766 | /**@type{!HTMLCanvasElement}*/(canvas)); | |
dedb4f5f DV |
767 | } |
768 | ||
769 | return canvas; | |
770 | }; | |
9ca829f2 DV |
771 | |
772 | /** | |
971870e5 DV |
773 | * Checks whether the user is on an Android browser. |
774 | * Android does not fully support the <canvas> tag, e.g. w/r/t/ clipping. | |
f11283de DV |
775 | * @return {boolean} |
776 | * @private | |
971870e5 DV |
777 | */ |
778 | Dygraph.isAndroid = function() { | |
758a629f | 779 | return (/Android/).test(navigator.userAgent); |
971870e5 DV |
780 | }; |
781 | ||
f11283de DV |
782 | |
783 | /** | |
784 | * TODO(danvk): use @template here when it's better supported for classes. | |
785 | * @param {!Array} array | |
786 | * @param {number} start | |
787 | * @param {number} length | |
45a8c16f | 788 | * @param {function(!Array,?):boolean=} predicate |
f11283de DV |
789 | * @constructor |
790 | */ | |
a26206cf RK |
791 | Dygraph.Iterator = function(array, start, length, predicate) { |
792 | start = start || 0; | |
793 | length = length || array.length; | |
ff1074cd RK |
794 | this.hasNext = true; // Use to identify if there's another element. |
795 | this.peek = null; // Use for look-ahead | |
0f20de1c | 796 | this.start_ = start; |
a26206cf RK |
797 | this.array_ = array; |
798 | this.predicate_ = predicate; | |
799 | this.end_ = Math.min(array.length, start + length); | |
ff1074cd RK |
800 | this.nextIdx_ = start - 1; // use -1 so initial advance works. |
801 | this.next(); // ignoring result. | |
42a9ebb8 | 802 | }; |
a26206cf | 803 | |
f11283de DV |
804 | /** |
805 | * @return {Object} | |
806 | */ | |
a26206cf | 807 | Dygraph.Iterator.prototype.next = function() { |
ff1074cd RK |
808 | if (!this.hasNext) { |
809 | return null; | |
a26206cf | 810 | } |
ff1074cd | 811 | var obj = this.peek; |
a26206cf | 812 | |
ff1074cd RK |
813 | var nextIdx = this.nextIdx_ + 1; |
814 | var found = false; | |
815 | while (nextIdx < this.end_) { | |
a26206cf | 816 | if (!this.predicate_ || this.predicate_(this.array_, nextIdx)) { |
ff1074cd RK |
817 | this.peek = this.array_[nextIdx]; |
818 | found = true; | |
819 | break; | |
a26206cf RK |
820 | } |
821 | nextIdx++; | |
822 | } | |
823 | this.nextIdx_ = nextIdx; | |
ff1074cd RK |
824 | if (!found) { |
825 | this.hasNext = false; | |
826 | this.peek = null; | |
827 | } | |
828 | return obj; | |
42a9ebb8 | 829 | }; |
a26206cf | 830 | |
971870e5 | 831 | /** |
7d1afbb9 RK |
832 | * Returns a new iterator over array, between indexes start and |
833 | * start + length, and only returns entries that pass the accept function | |
834 | * | |
f11283de DV |
835 | * @param {!Array} array the array to iterate over. |
836 | * @param {number} start the first index to iterate over, 0 if absent. | |
837 | * @param {number} length the number of elements in the array to iterate over. | |
838 | * This, along with start, defines a slice of the array, and so length | |
839 | * doesn't imply the number of elements in the iterator when accept doesn't | |
840 | * always accept all values. array.length when absent. | |
45a8c16f | 841 | * @param {function(?):boolean=} opt_predicate a function that takes |
f11283de DV |
842 | * parameters array and idx, which returns true when the element should be |
843 | * returned. If omitted, all elements are accepted. | |
844 | * @private | |
7d1afbb9 | 845 | */ |
f11283de DV |
846 | Dygraph.createIterator = function(array, start, length, opt_predicate) { |
847 | return new Dygraph.Iterator(array, start, length, opt_predicate); | |
7d1afbb9 RK |
848 | }; |
849 | ||
a96b8ba3 A |
850 | // Shim layer with setTimeout fallback. |
851 | // From: http://paulirish.com/2011/requestanimationframe-for-smart-animating/ | |
e9a32469 A |
852 | // Should be called with the window context: |
853 | // Dygraph.requestAnimFrame.call(window, function() {}) | |
bec100ae | 854 | Dygraph.requestAnimFrame = (function() { |
a96b8ba3 A |
855 | return window.requestAnimationFrame || |
856 | window.webkitRequestAnimationFrame || | |
857 | window.mozRequestAnimationFrame || | |
858 | window.oRequestAnimationFrame || | |
859 | window.msRequestAnimationFrame || | |
860 | function (callback) { | |
861 | window.setTimeout(callback, 1000 / 60); | |
862 | }; | |
863 | })(); | |
864 | ||
865 | /** | |
d91ba598 A |
866 | * Call a function at most maxFrames times at an attempted interval of |
867 | * framePeriodInMillis, then call a cleanup function once. repeatFn is called | |
868 | * once immediately, then at most (maxFrames - 1) times asynchronously. If | |
869 | * maxFrames==1, then cleanup_fn() is also called synchronously. This function | |
870 | * is used to sequence animation. | |
871 | * @param {function(number)} repeatFn Called repeatedly -- takes the frame | |
872 | * number (from 0 to maxFrames-1) as an argument. | |
873 | * @param {number} maxFrames The max number of times to call repeatFn | |
874 | * @param {number} framePeriodInMillis Max requested time between frames. | |
875 | * @param {function()} cleanupFn A function to call after all repeatFn calls. | |
876 | * @private | |
877 | */ | |
878 | Dygraph.repeatAndCleanup = function(repeatFn, maxFrames, framePeriodInMillis, | |
bec100ae | 879 | cleanupFn) { |
d91ba598 A |
880 | var frameNumber = 0; |
881 | var previousFrameNumber; | |
882 | var startTime = new Date().getTime(); | |
883 | repeatFn(frameNumber); | |
884 | if (maxFrames == 1) { | |
885 | cleanupFn(); | |
b1a3b195 DV |
886 | return; |
887 | } | |
d91ba598 | 888 | var maxFrameArg = maxFrames - 1; |
b1a3b195 DV |
889 | |
890 | (function loop() { | |
d91ba598 | 891 | if (frameNumber >= maxFrames) return; |
e9a32469 | 892 | Dygraph.requestAnimFrame.call(window, function() { |
d91ba598 A |
893 | // Determine which frame to draw based on the delay so far. Will skip |
894 | // frames if necessary. | |
895 | var currentTime = new Date().getTime(); | |
896 | var delayInMillis = currentTime - startTime; | |
897 | previousFrameNumber = frameNumber; | |
898 | frameNumber = Math.floor(delayInMillis / framePeriodInMillis); | |
899 | var frameDelta = frameNumber - previousFrameNumber; | |
900 | // If we predict that the subsequent repeatFn call will overshoot our | |
901 | // total frame target, so our last call will cause a stutter, then jump to | |
902 | // the last call immediately. If we're going to cause a stutter, better | |
903 | // to do it faster than slower. | |
904 | var predictOvershootStutter = (frameNumber + frameDelta) > maxFrameArg; | |
905 | if (predictOvershootStutter || (frameNumber >= maxFrameArg)) { | |
906 | repeatFn(maxFrameArg); // Ensure final call with maxFrameArg. | |
907 | cleanupFn(); | |
b1a3b195 | 908 | } else { |
83b0c192 | 909 | if (frameDelta !== 0) { // Don't call repeatFn with duplicate frames. |
d91ba598 A |
910 | repeatFn(frameNumber); |
911 | } | |
b1a3b195 DV |
912 | loop(); |
913 | } | |
a96b8ba3 | 914 | }); |
b1a3b195 DV |
915 | })(); |
916 | }; | |
917 | ||
918 | /** | |
9ca829f2 DV |
919 | * This function will scan the option list and determine if they |
920 | * require us to recalculate the pixel positions of each point. | |
f11283de DV |
921 | * @param {!Array.<string>} labels a list of options to check. |
922 | * @param {!Object} attrs | |
923 | * @return {boolean} true if the graph needs new points else false. | |
924 | * @private | |
9ca829f2 DV |
925 | */ |
926 | Dygraph.isPixelChangingOptionList = function(labels, attrs) { | |
927 | // A whitelist of options that do not change pixel positions. | |
928 | var pixelSafeOptions = { | |
929 | 'annotationClickHandler': true, | |
930 | 'annotationDblClickHandler': true, | |
931 | 'annotationMouseOutHandler': true, | |
932 | 'annotationMouseOverHandler': true, | |
933 | 'axisLabelColor': true, | |
934 | 'axisLineColor': true, | |
935 | 'axisLineWidth': true, | |
936 | 'clickCallback': true, | |
9ca829f2 DV |
937 | 'digitsAfterDecimal': true, |
938 | 'drawCallback': true, | |
5879307d | 939 | 'drawHighlightPointCallback': true, |
9ca829f2 | 940 | 'drawPoints': true, |
78e58af4 | 941 | 'drawPointCallback': true, |
9ca829f2 DV |
942 | 'drawXGrid': true, |
943 | 'drawYGrid': true, | |
944 | 'fillAlpha': true, | |
945 | 'gridLineColor': true, | |
946 | 'gridLineWidth': true, | |
947 | 'hideOverlayOnMouseOut': true, | |
948 | 'highlightCallback': true, | |
949 | 'highlightCircleSize': true, | |
950 | 'interactionModel': true, | |
951 | 'isZoomedIgnoreProgrammaticZoom': true, | |
952 | 'labelsDiv': true, | |
953 | 'labelsDivStyles': true, | |
954 | 'labelsDivWidth': true, | |
955 | 'labelsKMB': true, | |
956 | 'labelsKMG2': true, | |
957 | 'labelsSeparateLines': true, | |
958 | 'labelsShowZeroValues': true, | |
959 | 'legend': true, | |
960 | 'maxNumberWidth': true, | |
961 | 'panEdgeFraction': true, | |
962 | 'pixelsPerYLabel': true, | |
963 | 'pointClickCallback': true, | |
964 | 'pointSize': true, | |
ccd9d7c2 PF |
965 | 'rangeSelectorPlotFillColor': true, |
966 | 'rangeSelectorPlotStrokeColor': true, | |
9ca829f2 DV |
967 | 'showLabelsOnHighlight': true, |
968 | 'showRoller': true, | |
969 | 'sigFigs': true, | |
970 | 'strokeWidth': true, | |
971 | 'underlayCallback': true, | |
972 | 'unhighlightCallback': true, | |
973 | 'xAxisLabelFormatter': true, | |
974 | 'xTicker': true, | |
975 | 'xValueFormatter': true, | |
976 | 'yAxisLabelFormatter': true, | |
977 | 'yValueFormatter': true, | |
978 | 'zoomCallback': true | |
ccd9d7c2 | 979 | }; |
9ca829f2 DV |
980 | |
981 | // Assume that we do not require new points. | |
982 | // This will change to true if we actually do need new points. | |
983 | var requiresNewPoints = false; | |
984 | ||
985 | // Create a dictionary of series names for faster lookup. | |
986 | // If there are no labels, then the dictionary stays empty. | |
987 | var seriesNamesDictionary = { }; | |
988 | if (labels) { | |
989 | for (var i = 1; i < labels.length; i++) { | |
990 | seriesNamesDictionary[labels[i]] = true; | |
991 | } | |
992 | } | |
993 | ||
994 | // Iterate through the list of updated options. | |
5061b42f | 995 | for (var property in attrs) { |
9ca829f2 DV |
996 | // Break early if we already know we need new points from a previous option. |
997 | if (requiresNewPoints) { | |
998 | break; | |
999 | } | |
1000 | if (attrs.hasOwnProperty(property)) { | |
1001 | // Find out of this field is actually a series specific options list. | |
1002 | if (seriesNamesDictionary[property]) { | |
1003 | // This property value is a list of options for this series. | |
1004 | // If any of these sub properties are not pixel safe, set the flag. | |
5061b42f | 1005 | for (var subProperty in attrs[property]) { |
9ca829f2 DV |
1006 | // Break early if we already know we need new points from a previous option. |
1007 | if (requiresNewPoints) { | |
1008 | break; | |
1009 | } | |
1010 | if (attrs[property].hasOwnProperty(subProperty) && !pixelSafeOptions[subProperty]) { | |
1011 | requiresNewPoints = true; | |
1012 | } | |
1013 | } | |
1014 | // If this was not a series specific option list, check if its a pixel changing property. | |
1015 | } else if (!pixelSafeOptions[property]) { | |
1016 | requiresNewPoints = true; | |
ccd9d7c2 | 1017 | } |
9ca829f2 DV |
1018 | } |
1019 | } | |
1020 | ||
1021 | return requiresNewPoints; | |
1022 | }; | |
78e58af4 | 1023 | |
79253bd0 | 1024 | /** |
1025 | * Compares two arrays to see if they are equal. If either parameter is not an | |
1026 | * array it will return false. Does a shallow compare | |
1027 | * Dygraph.compareArrays([[1,2], [3, 4]], [[1,2], [3,4]]) === false. | |
f11283de DV |
1028 | * @param {!Array.<T>} array1 first array |
1029 | * @param {!Array.<T>} array2 second array | |
1030 | * @return {boolean} True if both parameters are arrays, and contents are equal. | |
1031 | * @template T | |
79253bd0 | 1032 | */ |
1033 | Dygraph.compareArrays = function(array1, array2) { | |
1034 | if (!Dygraph.isArrayLike(array1) || !Dygraph.isArrayLike(array2)) { | |
1035 | return false; | |
1036 | } | |
1037 | if (array1.length !== array2.length) { | |
1038 | return false; | |
1039 | } | |
1040 | for (var i = 0; i < array1.length; i++) { | |
1041 | if (array1[i] !== array2[i]) { | |
1042 | return false; | |
1043 | } | |
1044 | } | |
1045 | return true; | |
1046 | }; | |
2996a18e | 1047 | |
240c0b11 | 1048 | /** |
f11283de DV |
1049 | * @param {!CanvasRenderingContext2D} ctx the canvas context |
1050 | * @param {number} sides the number of sides in the shape. | |
1051 | * @param {number} radius the radius of the image. | |
1052 | * @param {number} cx center x coordate | |
1053 | * @param {number} cy center y coordinate | |
45a8c16f DV |
1054 | * @param {number=} rotationRadians the shift of the initial angle, in radians. |
1055 | * @param {number=} delta the angle shift for each line. If missing, creates a | |
f11283de DV |
1056 | * regular polygon. |
1057 | * @private | |
240c0b11 | 1058 | */ |
5879307d RK |
1059 | Dygraph.regularShape_ = function( |
1060 | ctx, sides, radius, cx, cy, rotationRadians, delta) { | |
45a8c16f DV |
1061 | rotationRadians = rotationRadians || 0; |
1062 | delta = delta || Math.PI * 2 / sides; | |
78e58af4 | 1063 | |
240c0b11 | 1064 | ctx.beginPath(); |
5879307d | 1065 | var initialAngle = rotationRadians; |
240c0b11 RK |
1066 | var angle = initialAngle; |
1067 | ||
1068 | var computeCoordinates = function() { | |
1069 | var x = cx + (Math.sin(angle) * radius); | |
1070 | var y = cy + (-Math.cos(angle) * radius); | |
1071 | return [x, y]; | |
1072 | }; | |
1073 | ||
1074 | var initialCoordinates = computeCoordinates(); | |
1075 | var x = initialCoordinates[0]; | |
1076 | var y = initialCoordinates[1]; | |
1077 | ctx.moveTo(x, y); | |
1078 | ||
5879307d RK |
1079 | for (var idx = 0; idx < sides; idx++) { |
1080 | angle = (idx == sides - 1) ? initialAngle : (angle + delta); | |
240c0b11 RK |
1081 | var coords = computeCoordinates(); |
1082 | ctx.lineTo(coords[0], coords[1]); | |
1083 | } | |
a8ef67a8 | 1084 | ctx.fill(); |
85ff97a2 | 1085 | ctx.stroke(); |
42a9ebb8 | 1086 | }; |
78e58af4 | 1087 | |
f11283de DV |
1088 | /** |
1089 | * TODO(danvk): be more specific on the return type. | |
1090 | * @param {number} sides | |
45a8c16f DV |
1091 | * @param {number=} rotationRadians |
1092 | * @param {number=} delta | |
f11283de DV |
1093 | * @return {Function} |
1094 | * @private | |
1095 | */ | |
5879307d RK |
1096 | Dygraph.shapeFunction_ = function(sides, rotationRadians, delta) { |
1097 | return function(g, name, ctx, cx, cy, color, radius) { | |
5879307d | 1098 | ctx.strokeStyle = color; |
a8ef67a8 | 1099 | ctx.fillStyle = "white"; |
5879307d RK |
1100 | Dygraph.regularShape_(ctx, sides, radius, cx, cy, rotationRadians, delta); |
1101 | }; | |
1102 | }; | |
1103 | ||
78e58af4 RK |
1104 | Dygraph.Circles = { |
1105 | DEFAULT : function(g, name, ctx, canvasx, canvasy, color, radius) { | |
1106 | ctx.beginPath(); | |
1107 | ctx.fillStyle = color; | |
1108 | ctx.arc(canvasx, canvasy, radius, 0, 2 * Math.PI, false); | |
1109 | ctx.fill(); | |
1110 | }, | |
5879307d RK |
1111 | TRIANGLE : Dygraph.shapeFunction_(3), |
1112 | SQUARE : Dygraph.shapeFunction_(4, Math.PI / 4), | |
1113 | DIAMOND : Dygraph.shapeFunction_(4), | |
1114 | PENTAGON : Dygraph.shapeFunction_(5), | |
1115 | HEXAGON : Dygraph.shapeFunction_(6), | |
78e58af4 RK |
1116 | CIRCLE : function(g, name, ctx, cx, cy, color, radius) { |
1117 | ctx.beginPath(); | |
4ab51f75 | 1118 | ctx.strokeStyle = color; |
a8ef67a8 | 1119 | ctx.fillStyle = "white"; |
78e58af4 | 1120 | ctx.arc(cx, cy, radius, 0, 2 * Math.PI, false); |
a8ef67a8 | 1121 | ctx.fill(); |
85ff97a2 | 1122 | ctx.stroke(); |
78e58af4 | 1123 | }, |
5879307d | 1124 | STAR : Dygraph.shapeFunction_(5, 0, 4 * Math.PI / 5), |
240c0b11 | 1125 | PLUS : function(g, name, ctx, cx, cy, color, radius) { |
240c0b11 RK |
1126 | ctx.strokeStyle = color; |
1127 | ||
1128 | ctx.beginPath(); | |
1129 | ctx.moveTo(cx + radius, cy); | |
1130 | ctx.lineTo(cx - radius, cy); | |
a8ef67a8 | 1131 | ctx.closePath(); |
85ff97a2 | 1132 | ctx.stroke(); |
240c0b11 RK |
1133 | |
1134 | ctx.beginPath(); | |
1135 | ctx.moveTo(cx, cy + radius); | |
1136 | ctx.lineTo(cx, cy - radius); | |
a8ef67a8 | 1137 | ctx.closePath(); |
85ff97a2 | 1138 | ctx.stroke(); |
240c0b11 RK |
1139 | }, |
1140 | EX : function(g, name, ctx, cx, cy, color, radius) { | |
a8ef67a8 | 1141 | ctx.strokeStyle = color; |
240c0b11 RK |
1142 | |
1143 | ctx.beginPath(); | |
1144 | ctx.moveTo(cx + radius, cy + radius); | |
1145 | ctx.lineTo(cx - radius, cy - radius); | |
1146 | ctx.closePath(); | |
1147 | ctx.stroke(); | |
1148 | ||
1149 | ctx.beginPath(); | |
1150 | ctx.moveTo(cx + radius, cy - radius); | |
1151 | ctx.lineTo(cx - radius, cy + radius); | |
1152 | ctx.closePath(); | |
240c0b11 | 1153 | ctx.stroke(); |
78e58af4 | 1154 | } |
78e58af4 | 1155 | }; |
2bad4d92 DV |
1156 | |
1157 | /** | |
1158 | * To create a "drag" interaction, you typically register a mousedown event | |
1159 | * handler on the element where the drag begins. In that handler, you register a | |
1160 | * mouseup handler on the window to determine when the mouse is released, | |
1161 | * wherever that release happens. This works well, except when the user releases | |
1162 | * the mouse over an off-domain iframe. In that case, the mouseup event is | |
1163 | * handled by the iframe and never bubbles up to the window handler. | |
1164 | * | |
1165 | * To deal with this issue, we cover iframes with high z-index divs to make sure | |
1166 | * they don't capture mouseup. | |
1167 | * | |
1168 | * Usage: | |
1169 | * element.addEventListener('mousedown', function() { | |
1170 | * var tarper = new Dygraph.IFrameTarp(); | |
1171 | * tarper.cover(); | |
1172 | * var mouseUpHandler = function() { | |
1173 | * ... | |
1174 | * window.removeEventListener(mouseUpHandler); | |
1175 | * tarper.uncover(); | |
1176 | * }; | |
1177 | * window.addEventListener('mouseup', mouseUpHandler); | |
1178 | * }; | |
1179 | * | |
2bad4d92 DV |
1180 | * @constructor |
1181 | */ | |
1182 | Dygraph.IFrameTarp = function() { | |
f11283de | 1183 | /** @type {Array.<!HTMLDivElement>} */ |
2bad4d92 DV |
1184 | this.tarps = []; |
1185 | }; | |
1186 | ||
1187 | /** | |
1188 | * Find all the iframes in the document and cover them with high z-index | |
1189 | * transparent divs. | |
1190 | */ | |
1191 | Dygraph.IFrameTarp.prototype.cover = function() { | |
1192 | var iframes = document.getElementsByTagName("iframe"); | |
1193 | for (var i = 0; i < iframes.length; i++) { | |
1194 | var iframe = iframes[i]; | |
1195 | var x = Dygraph.findPosX(iframe), | |
1196 | y = Dygraph.findPosY(iframe), | |
1197 | width = iframe.offsetWidth, | |
1198 | height = iframe.offsetHeight; | |
1199 | ||
1200 | var div = document.createElement("div"); | |
1201 | div.style.position = "absolute"; | |
1202 | div.style.left = x + 'px'; | |
1203 | div.style.top = y + 'px'; | |
1204 | div.style.width = width + 'px'; | |
1205 | div.style.height = height + 'px'; | |
1206 | div.style.zIndex = 999; | |
1207 | document.body.appendChild(div); | |
1208 | this.tarps.push(div); | |
1209 | } | |
1210 | }; | |
1211 | ||
1212 | /** | |
1213 | * Remove all the iframe covers. You should call this in a mouseup handler. | |
1214 | */ | |
1215 | Dygraph.IFrameTarp.prototype.uncover = function() { | |
1216 | for (var i = 0; i < this.tarps.length; i++) { | |
1217 | this.tarps[i].parentNode.removeChild(this.tarps[i]); | |
1218 | } | |
1219 | this.tarps = []; | |
1220 | }; | |
e5763589 DV |
1221 | |
1222 | /** | |
df268bcc | 1223 | * Determine whether |data| is delimited by CR, CRLF, LF, LFCR. |
e5763589 | 1224 | * @param {string} data |
f11283de | 1225 | * @return {?string} the delimiter that was detected (or null on failure). |
e5763589 DV |
1226 | */ |
1227 | Dygraph.detectLineDelimiter = function(data) { | |
1228 | for (var i = 0; i < data.length; i++) { | |
df268bcc JH |
1229 | var code = data.charAt(i); |
1230 | if (code === '\r') { | |
1231 | // Might actually be "\r\n". | |
1232 | if (((i + 1) < data.length) && (data.charAt(i + 1) === '\n')) { | |
1233 | return '\r\n'; | |
1234 | } | |
1235 | return code; | |
1236 | } | |
1237 | if (code === '\n') { | |
e5763589 | 1238 | // Might actually be "\n\r". |
df268bcc JH |
1239 | if (((i + 1) < data.length) && (data.charAt(i + 1) === '\r')) { |
1240 | return '\n\r'; | |
1241 | } | |
e5763589 DV |
1242 | return code; |
1243 | } | |
1244 | } | |
1245 | ||
1246 | return null; | |
1247 | }; | |
def24194 DV |
1248 | |
1249 | /** | |
1250 | * Is one element contained by another? | |
1251 | * @param {Element} containee The contained element. | |
1252 | * @param {Element} container The container element. | |
1253 | * @return {boolean} Whether containee is inside (or equal to) container. | |
1254 | * @private | |
1255 | */ | |
1256 | Dygraph.isElementContainedBy = function(containee, container) { | |
1257 | if (container === null || containee === null) { | |
1258 | return false; | |
1259 | } | |
1260 | while (containee && containee !== container) { | |
1261 | containee = containee.parentNode; | |
1262 | } | |
1263 | return (containee === container); | |
1264 | }; | |
2fd143d3 DV |
1265 | |
1266 | ||
1267 | // This masks some numeric issues in older versions of Firefox, | |
1268 | // where 1.0/Math.pow(10,2) != Math.pow(10,-2). | |
1269 | /** @type {function(number,number):number} */ | |
1270 | Dygraph.pow = function(base, exp) { | |
1271 | if (exp < 0) { | |
1272 | return 1.0 / Math.pow(base, -exp); | |
1273 | } | |
1274 | return Math.pow(base, exp); | |
1275 | }; | |
1276 | ||
9a4fd029 DV |
1277 | // For Dygraph.setDateSameTZ, below. |
1278 | Dygraph.dateSetters = { | |
1279 | ms: Date.prototype.setMilliseconds, | |
1280 | s: Date.prototype.setSeconds, | |
1281 | m: Date.prototype.setMinutes, | |
1282 | h: Date.prototype.setHours | |
1283 | }; | |
1284 | ||
1285 | /** | |
1286 | * This is like calling d.setSeconds(), d.setMinutes(), etc, except that it | |
1287 | * adjusts for time zone changes to keep the date/time parts consistent. | |
1288 | * | |
1289 | * For example, d.getSeconds(), d.getMinutes() and d.getHours() will all be | |
1290 | * the same before/after you call setDateSameTZ(d, {ms: 0}). The same is not | |
1291 | * true if you call d.setMilliseconds(0). | |
1292 | * | |
1293 | * @type {function(!Date, Object.<number>)} | |
1294 | */ | |
1295 | Dygraph.setDateSameTZ = function(d, parts) { | |
1296 | var tz = d.getTimezoneOffset(); | |
1297 | for (var k in parts) { | |
1298 | if (!parts.hasOwnProperty(k)) continue; | |
1299 | var setter = Dygraph.dateSetters[k]; | |
1300 | if (!setter) throw "Invalid setter: " + k; | |
1301 | setter.call(d, parts[k]); | |
1302 | if (d.getTimezoneOffset() != tz) { | |
1303 | d.setTime(d.getTime() + (tz - d.getTimezoneOffset()) * 60 * 1000); | |
1304 | } | |
1305 | } | |
1306 | }; |