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