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