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