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 | |
c0f54d4f DV |
14 | "use strict"; |
15 | ||
dedb4f5f DV |
16 | Dygraph.LOG_SCALE = 10; |
17 | Dygraph.LN_TEN = Math.log(Dygraph.LOG_SCALE); | |
18 | ||
19 | /** @private */ | |
20 | Dygraph.log10 = function(x) { | |
21 | return Math.log(x) / Dygraph.LN_TEN; | |
22 | } | |
23 | ||
24 | // Various logging levels. | |
25 | Dygraph.DEBUG = 1; | |
26 | Dygraph.INFO = 2; | |
27 | Dygraph.WARNING = 3; | |
28 | Dygraph.ERROR = 3; | |
29 | ||
00639fab DV |
30 | // Set this to log stack traces on warnings, etc. |
31 | // This requires stacktrace.js, which is up to you to provide. | |
32 | // A copy can be found in the dygraphs repo, or at | |
33 | // https://github.com/eriwen/javascript-stacktrace | |
34 | Dygraph.LOG_STACK_TRACES = false; | |
35 | ||
dedb4f5f DV |
36 | /** |
37 | * @private | |
38 | * Log an error on the JS console at the given severity. | |
39 | * @param { Integer } severity One of Dygraph.{DEBUG,INFO,WARNING,ERROR} | |
40 | * @param { String } The message to log. | |
41 | */ | |
42 | Dygraph.log = function(severity, message) { | |
00639fab DV |
43 | var st; |
44 | if (typeof(printStackTrace) != 'undefined') { | |
45 | // Remove uninteresting bits: logging functions and paths. | |
46 | var st = printStackTrace({guess:false}); | |
47 | while (st[0].indexOf("Function.log") != 0) { | |
48 | st.splice(0, 1); | |
49 | } | |
50 | st.splice(0, 2); | |
51 | for (var i = 0; i < st.length; i++) { | |
52 | st[i] = st[i].replace(/\([^)]*\/(.*)\)/, '($1)') | |
53 | .replace(/\@.*\/([^\/]*)/, '@$1') | |
54 | .replace('[object Object].', ''); | |
55 | } | |
56 | message += ' (' + st.splice(0, 1) + ')'; | |
57 | } | |
58 | ||
dedb4f5f DV |
59 | if (typeof(console) != 'undefined') { |
60 | switch (severity) { | |
61 | case Dygraph.DEBUG: | |
62 | console.debug('dygraphs: ' + message); | |
63 | break; | |
64 | case Dygraph.INFO: | |
65 | console.info('dygraphs: ' + message); | |
66 | break; | |
67 | case Dygraph.WARNING: | |
68 | console.warn('dygraphs: ' + message); | |
69 | break; | |
70 | case Dygraph.ERROR: | |
71 | console.error('dygraphs: ' + message); | |
72 | break; | |
73 | } | |
74 | } | |
00639fab DV |
75 | |
76 | if (Dygraph.LOG_STACK_TRACES) { | |
77 | console.log(st.join('\n')); | |
78 | } | |
dedb4f5f DV |
79 | }; |
80 | ||
81 | /** @private */ | |
82 | Dygraph.info = function(message) { | |
83 | Dygraph.log(Dygraph.INFO, message); | |
84 | }; | |
85 | /** @private */ | |
86 | Dygraph.prototype.info = Dygraph.info; | |
87 | ||
88 | /** @private */ | |
89 | Dygraph.warn = function(message) { | |
90 | Dygraph.log(Dygraph.WARNING, message); | |
91 | }; | |
92 | /** @private */ | |
93 | Dygraph.prototype.warn = Dygraph.warn; | |
94 | ||
95 | /** @private */ | |
96 | Dygraph.error = function(message) { | |
97 | Dygraph.log(Dygraph.ERROR, message); | |
98 | }; | |
99 | /** @private */ | |
100 | Dygraph.prototype.error = Dygraph.error; | |
101 | ||
102 | /** | |
103 | * @private | |
104 | * Return the 2d context for a dygraph canvas. | |
105 | * | |
106 | * This method is only exposed for the sake of replacing the function in | |
107 | * automated tests, e.g. | |
108 | * | |
109 | * var oldFunc = Dygraph.getContext(); | |
110 | * Dygraph.getContext = function(canvas) { | |
111 | * var realContext = oldFunc(canvas); | |
112 | * return new Proxy(realContext); | |
113 | * }; | |
114 | */ | |
115 | Dygraph.getContext = function(canvas) { | |
116 | return canvas.getContext("2d"); | |
117 | }; | |
118 | ||
119 | /** | |
120 | * @private | |
121 | * Add an event handler. This smooths a difference between IE and the rest of | |
122 | * the world. | |
ccd9d7c2 PF |
123 | * @param { DOM element } elem The element to add the event to. |
124 | * @param { String } type The type of the event, e.g. 'click' or 'mousemove'. | |
dedb4f5f DV |
125 | * @param { Function } fn The function to call on the event. The function takes |
126 | * one parameter: the event object. | |
127 | */ | |
ccd9d7c2 PF |
128 | Dygraph.addEvent = function addEvent(elem, type, fn) { |
129 | if (elem.addEventListener) { | |
130 | elem.addEventListener(type, fn, false); | |
131 | } else { | |
132 | elem[type+fn] = function(){fn(window.event);}; | |
133 | elem.attachEvent('on'+type, elem[type+fn]); | |
134 | } | |
135 | }; | |
136 | ||
137 | /** | |
138 | * @private | |
139 | * Remove an event handler. This smooths a difference between IE and the rest of | |
140 | * the world. | |
141 | * @param { DOM element } elem The element to add the event to. | |
142 | * @param { String } type The type of the event, e.g. 'click' or 'mousemove'. | |
143 | * @param { Function } fn The function to call on the event. The function takes | |
144 | * one parameter: the event object. | |
145 | */ | |
146 | Dygraph.removeEvent = function addEvent(elem, type, fn) { | |
147 | if (elem.removeEventListener) { | |
148 | elem.removeEventListener(type, fn, false); | |
149 | } else { | |
150 | elem.detachEvent('on'+type, elem[type+fn]); | |
151 | elem[type+fn] = null; | |
dedb4f5f DV |
152 | } |
153 | }; | |
154 | ||
155 | /** | |
156 | * @private | |
157 | * Cancels further processing of an event. This is useful to prevent default | |
158 | * browser actions, e.g. highlighting text on a double-click. | |
159 | * Based on the article at | |
160 | * http://www.switchonthecode.com/tutorials/javascript-tutorial-the-scroll-wheel | |
161 | * @param { Event } e The event whose normal behavior should be canceled. | |
162 | */ | |
163 | Dygraph.cancelEvent = function(e) { | |
164 | e = e ? e : window.event; | |
165 | if (e.stopPropagation) { | |
166 | e.stopPropagation(); | |
167 | } | |
168 | if (e.preventDefault) { | |
169 | e.preventDefault(); | |
170 | } | |
171 | e.cancelBubble = true; | |
172 | e.cancel = true; | |
173 | e.returnValue = false; | |
174 | return false; | |
175 | }; | |
176 | ||
177 | /** | |
178 | * Convert hsv values to an rgb(r,g,b) string. Taken from MochiKit.Color. This | |
179 | * is used to generate default series colors which are evenly spaced on the | |
180 | * color wheel. | |
181 | * @param { Number } hue Range is 0.0-1.0. | |
182 | * @param { Number } saturation Range is 0.0-1.0. | |
183 | * @param { Number } value Range is 0.0-1.0. | |
184 | * @return { String } "rgb(r,g,b)" where r, g and b range from 0-255. | |
185 | * @private | |
186 | */ | |
187 | Dygraph.hsvToRGB = function (hue, saturation, value) { | |
188 | var red; | |
189 | var green; | |
190 | var blue; | |
191 | if (saturation === 0) { | |
192 | red = value; | |
193 | green = value; | |
194 | blue = value; | |
195 | } else { | |
196 | var i = Math.floor(hue * 6); | |
197 | var f = (hue * 6) - i; | |
198 | var p = value * (1 - saturation); | |
199 | var q = value * (1 - (saturation * f)); | |
200 | var t = value * (1 - (saturation * (1 - f))); | |
201 | switch (i) { | |
202 | case 1: red = q; green = value; blue = p; break; | |
203 | case 2: red = p; green = value; blue = t; break; | |
204 | case 3: red = p; green = q; blue = value; break; | |
205 | case 4: red = t; green = p; blue = value; break; | |
206 | case 5: red = value; green = p; blue = q; break; | |
207 | case 6: // fall through | |
208 | case 0: red = value; green = t; blue = p; break; | |
209 | } | |
210 | } | |
211 | red = Math.floor(255 * red + 0.5); | |
212 | green = Math.floor(255 * green + 0.5); | |
213 | blue = Math.floor(255 * blue + 0.5); | |
214 | return 'rgb(' + red + ',' + green + ',' + blue + ')'; | |
215 | }; | |
216 | ||
217 | // The following functions are from quirksmode.org with a modification for Safari from | |
218 | // http://blog.firetree.net/2005/07/04/javascript-find-position/ | |
219 | // http://www.quirksmode.org/js/findpos.html | |
1bc38cbc | 220 | // ... and modifications to support scrolling divs. |
dedb4f5f | 221 | |
8442269f RK |
222 | /** |
223 | * Find the x-coordinate of the supplied object relative to the left side | |
224 | * of the page. | |
225 | * @private | |
226 | */ | |
dedb4f5f DV |
227 | Dygraph.findPosX = function(obj) { |
228 | var curleft = 0; | |
8442269f RK |
229 | if(obj.offsetParent) { |
230 | var copyObj = obj; | |
231 | while(1) { | |
232 | curleft += copyObj.offsetLeft; | |
233 | if(!copyObj.offsetParent) { | |
dedb4f5f | 234 | break; |
8442269f RK |
235 | } |
236 | copyObj = copyObj.offsetParent; | |
dedb4f5f | 237 | } |
8442269f | 238 | } else if(obj.x) { |
dedb4f5f | 239 | curleft += obj.x; |
8442269f RK |
240 | } |
241 | // This handles the case where the object is inside a scrolled div. | |
242 | while(obj && obj != document.body) { | |
243 | curleft -= obj.scrollLeft; | |
244 | obj = obj.parentNode; | |
245 | } | |
dedb4f5f DV |
246 | return curleft; |
247 | }; | |
248 | ||
8442269f RK |
249 | /** |
250 | * Find the y-coordinate of the supplied object relative to the top of the | |
251 | * page. | |
252 | * @private | |
253 | */ | |
dedb4f5f DV |
254 | Dygraph.findPosY = function(obj) { |
255 | var curtop = 0; | |
8442269f RK |
256 | if(obj.offsetParent) { |
257 | var copyObj = obj; | |
258 | while(1) { | |
259 | curtop += copyObj.offsetTop; | |
260 | if(!copyObj.offsetParent) { | |
dedb4f5f | 261 | break; |
8442269f RK |
262 | } |
263 | copyObj = copyObj.offsetParent; | |
dedb4f5f | 264 | } |
8442269f | 265 | } else if(obj.y) { |
dedb4f5f | 266 | curtop += obj.y; |
8442269f RK |
267 | } |
268 | // This handles the case where the object is inside a scrolled div. | |
269 | while(obj && obj != document.body) { | |
270 | curtop -= obj.scrollTop; | |
271 | obj = obj.parentNode; | |
272 | } | |
dedb4f5f DV |
273 | return curtop; |
274 | }; | |
275 | ||
276 | /** | |
277 | * @private | |
278 | * Returns the x-coordinate of the event in a coordinate system where the | |
279 | * top-left corner of the page (not the window) is (0,0). | |
280 | * Taken from MochiKit.Signal | |
281 | */ | |
282 | Dygraph.pageX = function(e) { | |
283 | if (e.pageX) { | |
284 | return (!e.pageX || e.pageX < 0) ? 0 : e.pageX; | |
285 | } else { | |
286 | var de = document; | |
287 | var b = document.body; | |
288 | return e.clientX + | |
289 | (de.scrollLeft || b.scrollLeft) - | |
290 | (de.clientLeft || 0); | |
291 | } | |
292 | }; | |
293 | ||
294 | /** | |
295 | * @private | |
296 | * Returns the y-coordinate of the event in a coordinate system where the | |
297 | * top-left corner of the page (not the window) is (0,0). | |
298 | * Taken from MochiKit.Signal | |
299 | */ | |
300 | Dygraph.pageY = function(e) { | |
301 | if (e.pageY) { | |
302 | return (!e.pageY || e.pageY < 0) ? 0 : e.pageY; | |
303 | } else { | |
304 | var de = document; | |
305 | var b = document.body; | |
306 | return e.clientY + | |
307 | (de.scrollTop || b.scrollTop) - | |
308 | (de.clientTop || 0); | |
309 | } | |
310 | }; | |
311 | ||
312 | /** | |
313 | * @private | |
314 | * @param { Number } x The number to consider. | |
315 | * @return { Boolean } Whether the number is zero or NaN. | |
316 | */ | |
317 | // TODO(danvk): rename this function to something like 'isNonZeroNan'. | |
318 | Dygraph.isOK = function(x) { | |
319 | return x && !isNaN(x); | |
320 | }; | |
321 | ||
322 | /** | |
323 | * Number formatting function which mimicks the behavior of %g in printf, i.e. | |
324 | * either exponential or fixed format (without trailing 0s) is used depending on | |
325 | * the length of the generated string. The advantage of this format is that | |
326 | * there is a predictable upper bound on the resulting string length, | |
327 | * significant figures are not dropped, and normal numbers are not displayed in | |
328 | * exponential notation. | |
329 | * | |
330 | * NOTE: JavaScript's native toPrecision() is NOT a drop-in replacement for %g. | |
331 | * It creates strings which are too long for absolute values between 10^-4 and | |
332 | * 10^-6, e.g. '0.00001' instead of '1e-5'. See tests/number-format.html for | |
333 | * output examples. | |
334 | * | |
335 | * @param {Number} x The number to format | |
336 | * @param {Number} opt_precision The precision to use, default 2. | |
337 | * @return {String} A string formatted like %g in printf. The max generated | |
338 | * string length should be precision + 6 (e.g 1.123e+300). | |
339 | */ | |
340 | Dygraph.floatFormat = function(x, opt_precision) { | |
341 | // Avoid invalid precision values; [1, 21] is the valid range. | |
342 | var p = Math.min(Math.max(1, opt_precision || 2), 21); | |
343 | ||
344 | // This is deceptively simple. The actual algorithm comes from: | |
345 | // | |
346 | // Max allowed length = p + 4 | |
347 | // where 4 comes from 'e+n' and '.'. | |
348 | // | |
349 | // Length of fixed format = 2 + y + p | |
350 | // where 2 comes from '0.' and y = # of leading zeroes. | |
351 | // | |
352 | // Equating the two and solving for y yields y = 2, or 0.00xxxx which is | |
353 | // 1.0e-3. | |
354 | // | |
355 | // Since the behavior of toPrecision() is identical for larger numbers, we | |
356 | // don't have to worry about the other bound. | |
357 | // | |
358 | // Finally, the argument for toExponential() is the number of trailing digits, | |
359 | // so we take off 1 for the value before the '.'. | |
360 | return (Math.abs(x) < 1.0e-3 && x != 0.0) ? | |
361 | x.toExponential(p - 1) : x.toPrecision(p); | |
362 | }; | |
363 | ||
364 | /** | |
365 | * @private | |
366 | * Converts '9' to '09' (useful for dates) | |
367 | */ | |
368 | Dygraph.zeropad = function(x) { | |
369 | if (x < 10) return "0" + x; else return "" + x; | |
370 | }; | |
371 | ||
372 | /** | |
373 | * Return a string version of the hours, minutes and seconds portion of a date. | |
374 | * @param {Number} date The JavaScript date (ms since epoch) | |
375 | * @return {String} A time of the form "HH:MM:SS" | |
376 | * @private | |
377 | */ | |
378 | Dygraph.hmsString_ = function(date) { | |
379 | var zeropad = Dygraph.zeropad; | |
380 | var d = new Date(date); | |
381 | if (d.getSeconds()) { | |
382 | return zeropad(d.getHours()) + ":" + | |
383 | zeropad(d.getMinutes()) + ":" + | |
384 | zeropad(d.getSeconds()); | |
385 | } else { | |
386 | return zeropad(d.getHours()) + ":" + zeropad(d.getMinutes()); | |
387 | } | |
388 | }; | |
389 | ||
390 | /** | |
dedb4f5f DV |
391 | * Round a number to the specified number of digits past the decimal point. |
392 | * @param {Number} num The number to round | |
393 | * @param {Number} places The number of decimals to which to round | |
394 | * @return {Number} The rounded number | |
395 | * @private | |
396 | */ | |
397 | Dygraph.round_ = function(num, places) { | |
398 | var shift = Math.pow(10, places); | |
399 | return Math.round(num * shift)/shift; | |
400 | }; | |
401 | ||
402 | /** | |
403 | * @private | |
404 | * Implementation of binary search over an array. | |
405 | * Currently does not work when val is outside the range of arry's values. | |
406 | * @param { Integer } val the value to search for | |
407 | * @param { Integer[] } arry is the value over which to search | |
408 | * @param { Integer } abs If abs > 0, find the lowest entry greater than val | |
409 | * If abs < 0, find the highest entry less than val. | |
410 | * if abs == 0, find the entry that equals val. | |
411 | * @param { Integer } [low] The first index in arry to consider (optional) | |
412 | * @param { Integer } [high] The last index in arry to consider (optional) | |
413 | */ | |
414 | Dygraph.binarySearch = function(val, arry, abs, low, high) { | |
415 | if (low == null || high == null) { | |
416 | low = 0; | |
417 | high = arry.length - 1; | |
418 | } | |
419 | if (low > high) { | |
420 | return -1; | |
421 | } | |
422 | if (abs == null) { | |
423 | abs = 0; | |
424 | } | |
425 | var validIndex = function(idx) { | |
426 | return idx >= 0 && idx < arry.length; | |
427 | } | |
428 | var mid = parseInt((low + high) / 2); | |
429 | var element = arry[mid]; | |
430 | if (element == val) { | |
431 | return mid; | |
432 | } | |
433 | if (element > val) { | |
434 | if (abs > 0) { | |
435 | // Accept if element > val, but also if prior element < val. | |
436 | var idx = mid - 1; | |
437 | if (validIndex(idx) && arry[idx] < val) { | |
438 | return mid; | |
439 | } | |
440 | } | |
441 | return Dygraph.binarySearch(val, arry, abs, low, mid - 1); | |
442 | } | |
443 | if (element < val) { | |
444 | if (abs < 0) { | |
445 | // Accept if element < val, but also if prior element > val. | |
446 | var idx = mid + 1; | |
447 | if (validIndex(idx) && arry[idx] > val) { | |
448 | return mid; | |
449 | } | |
450 | } | |
451 | return Dygraph.binarySearch(val, arry, abs, mid + 1, high); | |
452 | } | |
453 | }; | |
454 | ||
455 | /** | |
456 | * @private | |
457 | * Parses a date, returning the number of milliseconds since epoch. This can be | |
458 | * passed in as an xValueParser in the Dygraph constructor. | |
459 | * TODO(danvk): enumerate formats that this understands. | |
460 | * @param {String} A date in YYYYMMDD format. | |
461 | * @return {Number} Milliseconds since epoch. | |
462 | */ | |
463 | Dygraph.dateParser = function(dateStr) { | |
464 | var dateStrSlashed; | |
465 | var d; | |
466 | if (dateStr.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12' | |
467 | dateStrSlashed = dateStr.replace("-", "/", "g"); | |
468 | while (dateStrSlashed.search("-") != -1) { | |
469 | dateStrSlashed = dateStrSlashed.replace("-", "/"); | |
470 | } | |
471 | d = Dygraph.dateStrToMillis(dateStrSlashed); | |
472 | } else if (dateStr.length == 8) { // e.g. '20090712' | |
473 | // TODO(danvk): remove support for this format. It's confusing. | |
474 | dateStrSlashed = dateStr.substr(0,4) + "/" + dateStr.substr(4,2) | |
475 | + "/" + dateStr.substr(6,2); | |
476 | d = Dygraph.dateStrToMillis(dateStrSlashed); | |
477 | } else { | |
478 | // Any format that Date.parse will accept, e.g. "2009/07/12" or | |
479 | // "2009/07/12 12:34:56" | |
480 | d = Dygraph.dateStrToMillis(dateStr); | |
481 | } | |
482 | ||
483 | if (!d || isNaN(d)) { | |
484 | Dygraph.error("Couldn't parse " + dateStr + " as a date"); | |
485 | } | |
486 | return d; | |
487 | }; | |
488 | ||
489 | /** | |
490 | * @private | |
491 | * This is identical to JavaScript's built-in Date.parse() method, except that | |
492 | * it doesn't get replaced with an incompatible method by aggressive JS | |
493 | * libraries like MooTools or Joomla. | |
494 | * @param { String } str The date string, e.g. "2011/05/06" | |
495 | * @return { Integer } millis since epoch | |
496 | */ | |
497 | Dygraph.dateStrToMillis = function(str) { | |
498 | return new Date(str).getTime(); | |
499 | }; | |
500 | ||
501 | // These functions are all based on MochiKit. | |
502 | /** | |
503 | * Copies all the properties from o to self. | |
504 | * | |
505 | * @private | |
506 | */ | |
507 | Dygraph.update = function (self, o) { | |
508 | if (typeof(o) != 'undefined' && o !== null) { | |
509 | for (var k in o) { | |
510 | if (o.hasOwnProperty(k)) { | |
511 | self[k] = o[k]; | |
512 | } | |
513 | } | |
514 | } | |
515 | return self; | |
516 | }; | |
517 | ||
518 | /** | |
48e614ac DV |
519 | * Copies all the properties from o to self. |
520 | * | |
521 | * @private | |
522 | */ | |
523 | Dygraph.updateDeep = function (self, o) { | |
920208fb PF |
524 | // Taken from http://stackoverflow.com/questions/384286/javascript-isdom-how-do-you-check-if-a-javascript-object-is-a-dom-object |
525 | function isNode(o) { | |
526 | return ( | |
527 | typeof Node === "object" ? o instanceof Node : | |
528 | typeof o === "object" && typeof o.nodeType === "number" && typeof o.nodeName==="string" | |
529 | ); | |
530 | } | |
531 | ||
48e614ac DV |
532 | if (typeof(o) != 'undefined' && o !== null) { |
533 | for (var k in o) { | |
534 | if (o.hasOwnProperty(k)) { | |
535 | if (o[k] == null) { | |
536 | self[k] = null; | |
537 | } else if (Dygraph.isArrayLike(o[k])) { | |
538 | self[k] = o[k].slice(); | |
920208fb | 539 | } else if (isNode(o[k])) { |
66ad3609 RK |
540 | // DOM objects are shallowly-copied. |
541 | self[k] = o[k]; | |
48e614ac DV |
542 | } else if (typeof(o[k]) == 'object') { |
543 | if (typeof(self[k]) != 'object') { | |
544 | self[k] = {}; | |
545 | } | |
546 | Dygraph.updateDeep(self[k], o[k]); | |
547 | } else { | |
548 | self[k] = o[k]; | |
549 | } | |
550 | } | |
551 | } | |
552 | } | |
553 | return self; | |
554 | }; | |
555 | ||
556 | /** | |
dedb4f5f DV |
557 | * @private |
558 | */ | |
559 | Dygraph.isArrayLike = function (o) { | |
560 | var typ = typeof(o); | |
561 | if ( | |
562 | (typ != 'object' && !(typ == 'function' && | |
563 | typeof(o.item) == 'function')) || | |
564 | o === null || | |
565 | typeof(o.length) != 'number' || | |
566 | o.nodeType === 3 | |
567 | ) { | |
568 | return false; | |
569 | } | |
570 | return true; | |
571 | }; | |
572 | ||
573 | /** | |
574 | * @private | |
575 | */ | |
576 | Dygraph.isDateLike = function (o) { | |
577 | if (typeof(o) != "object" || o === null || | |
578 | typeof(o.getTime) != 'function') { | |
579 | return false; | |
580 | } | |
581 | return true; | |
582 | }; | |
583 | ||
584 | /** | |
48e614ac | 585 | * Note: this only seems to work for arrays. |
dedb4f5f DV |
586 | * @private |
587 | */ | |
588 | Dygraph.clone = function(o) { | |
589 | // TODO(danvk): figure out how MochiKit's version works | |
590 | var r = []; | |
591 | for (var i = 0; i < o.length; i++) { | |
592 | if (Dygraph.isArrayLike(o[i])) { | |
593 | r.push(Dygraph.clone(o[i])); | |
594 | } else { | |
595 | r.push(o[i]); | |
596 | } | |
597 | } | |
598 | return r; | |
599 | }; | |
600 | ||
601 | /** | |
602 | * @private | |
603 | * Create a new canvas element. This is more complex than a simple | |
604 | * document.createElement("canvas") because of IE and excanvas. | |
605 | */ | |
606 | Dygraph.createCanvas = function() { | |
607 | var canvas = document.createElement("canvas"); | |
608 | ||
c0f54d4f | 609 | var isIE = (/MSIE/.test(navigator.userAgent) && !window.opera); |
dedb4f5f DV |
610 | if (isIE && (typeof(G_vmlCanvasManager) != 'undefined')) { |
611 | canvas = G_vmlCanvasManager.initElement(canvas); | |
612 | } | |
613 | ||
614 | return canvas; | |
615 | }; | |
9ca829f2 DV |
616 | |
617 | /** | |
618 | * @private | |
b1a3b195 DV |
619 | * Call a function N times at a given interval, then call a cleanup function |
620 | * once. repeat_fn is called once immediately, then (times - 1) times | |
621 | * asynchronously. If times=1, then cleanup_fn() is also called synchronously. | |
622 | * @param repeat_fn {Function} Called repeatedly -- takes the number of calls | |
623 | * (from 0 to times-1) as an argument. | |
624 | * @param times {number} The number of times to call repeat_fn | |
625 | * @param every_ms {number} Milliseconds between calls | |
626 | * @param cleanup_fn {Function} A function to call after all repeat_fn calls. | |
627 | * @private | |
628 | */ | |
629 | Dygraph.repeatAndCleanup = function(repeat_fn, times, every_ms, cleanup_fn) { | |
630 | var count = 0; | |
631 | var start_time = new Date().getTime(); | |
632 | repeat_fn(count); | |
633 | if (times == 1) { | |
634 | cleanup_fn(); | |
635 | return; | |
636 | } | |
637 | ||
638 | (function loop() { | |
639 | if (count >= times) return; | |
640 | var target_time = start_time + (1 + count) * every_ms; | |
641 | setTimeout(function() { | |
642 | count++; | |
643 | repeat_fn(count) | |
644 | if (count >= times - 1) { | |
645 | cleanup_fn(); | |
646 | } else { | |
647 | loop(); | |
648 | } | |
649 | }, target_time - new Date().getTime()); | |
650 | // TODO(danvk): adjust every_ms to produce evenly-timed function calls. | |
651 | })(); | |
652 | }; | |
653 | ||
654 | /** | |
655 | * @private | |
9ca829f2 DV |
656 | * This function will scan the option list and determine if they |
657 | * require us to recalculate the pixel positions of each point. | |
658 | * @param { List } a list of options to check. | |
659 | * @return { Boolean } true if the graph needs new points else false. | |
660 | */ | |
661 | Dygraph.isPixelChangingOptionList = function(labels, attrs) { | |
662 | // A whitelist of options that do not change pixel positions. | |
663 | var pixelSafeOptions = { | |
664 | 'annotationClickHandler': true, | |
665 | 'annotationDblClickHandler': true, | |
666 | 'annotationMouseOutHandler': true, | |
667 | 'annotationMouseOverHandler': true, | |
668 | 'axisLabelColor': true, | |
669 | 'axisLineColor': true, | |
670 | 'axisLineWidth': true, | |
671 | 'clickCallback': true, | |
9ca829f2 DV |
672 | 'digitsAfterDecimal': true, |
673 | 'drawCallback': true, | |
674 | 'drawPoints': true, | |
675 | 'drawXGrid': true, | |
676 | 'drawYGrid': true, | |
677 | 'fillAlpha': true, | |
678 | 'gridLineColor': true, | |
679 | 'gridLineWidth': true, | |
680 | 'hideOverlayOnMouseOut': true, | |
681 | 'highlightCallback': true, | |
682 | 'highlightCircleSize': true, | |
683 | 'interactionModel': true, | |
684 | 'isZoomedIgnoreProgrammaticZoom': true, | |
685 | 'labelsDiv': true, | |
686 | 'labelsDivStyles': true, | |
687 | 'labelsDivWidth': true, | |
688 | 'labelsKMB': true, | |
689 | 'labelsKMG2': true, | |
690 | 'labelsSeparateLines': true, | |
691 | 'labelsShowZeroValues': true, | |
692 | 'legend': true, | |
693 | 'maxNumberWidth': true, | |
694 | 'panEdgeFraction': true, | |
695 | 'pixelsPerYLabel': true, | |
696 | 'pointClickCallback': true, | |
697 | 'pointSize': true, | |
ccd9d7c2 PF |
698 | 'rangeSelectorPlotFillColor': true, |
699 | 'rangeSelectorPlotStrokeColor': true, | |
9ca829f2 DV |
700 | 'showLabelsOnHighlight': true, |
701 | 'showRoller': true, | |
702 | 'sigFigs': true, | |
703 | 'strokeWidth': true, | |
704 | 'underlayCallback': true, | |
705 | 'unhighlightCallback': true, | |
706 | 'xAxisLabelFormatter': true, | |
707 | 'xTicker': true, | |
708 | 'xValueFormatter': true, | |
709 | 'yAxisLabelFormatter': true, | |
710 | 'yValueFormatter': true, | |
711 | 'zoomCallback': true | |
ccd9d7c2 | 712 | }; |
9ca829f2 DV |
713 | |
714 | // Assume that we do not require new points. | |
715 | // This will change to true if we actually do need new points. | |
716 | var requiresNewPoints = false; | |
717 | ||
718 | // Create a dictionary of series names for faster lookup. | |
719 | // If there are no labels, then the dictionary stays empty. | |
720 | var seriesNamesDictionary = { }; | |
721 | if (labels) { | |
722 | for (var i = 1; i < labels.length; i++) { | |
723 | seriesNamesDictionary[labels[i]] = true; | |
724 | } | |
725 | } | |
726 | ||
727 | // Iterate through the list of updated options. | |
5061b42f | 728 | for (var property in attrs) { |
9ca829f2 DV |
729 | // Break early if we already know we need new points from a previous option. |
730 | if (requiresNewPoints) { | |
731 | break; | |
732 | } | |
733 | if (attrs.hasOwnProperty(property)) { | |
734 | // Find out of this field is actually a series specific options list. | |
735 | if (seriesNamesDictionary[property]) { | |
736 | // This property value is a list of options for this series. | |
737 | // If any of these sub properties are not pixel safe, set the flag. | |
5061b42f | 738 | for (var subProperty in attrs[property]) { |
9ca829f2 DV |
739 | // Break early if we already know we need new points from a previous option. |
740 | if (requiresNewPoints) { | |
741 | break; | |
742 | } | |
743 | if (attrs[property].hasOwnProperty(subProperty) && !pixelSafeOptions[subProperty]) { | |
744 | requiresNewPoints = true; | |
745 | } | |
746 | } | |
747 | // If this was not a series specific option list, check if its a pixel changing property. | |
748 | } else if (!pixelSafeOptions[property]) { | |
749 | requiresNewPoints = true; | |
ccd9d7c2 | 750 | } |
9ca829f2 DV |
751 | } |
752 | } | |
753 | ||
754 | return requiresNewPoints; | |
755 | }; |