| 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 | * Number formatting function which mimicks the behavior of %g in printf, i.e. |
| 336 | * either exponential or fixed format (without trailing 0s) is used depending on |
| 337 | * the length of the generated string. The advantage of this format is that |
| 338 | * there is a predictable upper bound on the resulting string length, |
| 339 | * significant figures are not dropped, and normal numbers are not displayed in |
| 340 | * exponential notation. |
| 341 | * |
| 342 | * NOTE: JavaScript's native toPrecision() is NOT a drop-in replacement for %g. |
| 343 | * It creates strings which are too long for absolute values between 10^-4 and |
| 344 | * 10^-6, e.g. '0.00001' instead of '1e-5'. See tests/number-format.html for |
| 345 | * output examples. |
| 346 | * |
| 347 | * @param {Number} x The number to format |
| 348 | * @param {Number} opt_precision The precision to use, default 2. |
| 349 | * @return {String} A string formatted like %g in printf. The max generated |
| 350 | * string length should be precision + 6 (e.g 1.123e+300). |
| 351 | */ |
| 352 | Dygraph.floatFormat = function(x, opt_precision) { |
| 353 | // Avoid invalid precision values; [1, 21] is the valid range. |
| 354 | var p = Math.min(Math.max(1, opt_precision || 2), 21); |
| 355 | |
| 356 | // This is deceptively simple. The actual algorithm comes from: |
| 357 | // |
| 358 | // Max allowed length = p + 4 |
| 359 | // where 4 comes from 'e+n' and '.'. |
| 360 | // |
| 361 | // Length of fixed format = 2 + y + p |
| 362 | // where 2 comes from '0.' and y = # of leading zeroes. |
| 363 | // |
| 364 | // Equating the two and solving for y yields y = 2, or 0.00xxxx which is |
| 365 | // 1.0e-3. |
| 366 | // |
| 367 | // Since the behavior of toPrecision() is identical for larger numbers, we |
| 368 | // don't have to worry about the other bound. |
| 369 | // |
| 370 | // Finally, the argument for toExponential() is the number of trailing digits, |
| 371 | // so we take off 1 for the value before the '.'. |
| 372 | return (Math.abs(x) < 1.0e-3 && x !== 0.0) ? |
| 373 | x.toExponential(p - 1) : x.toPrecision(p); |
| 374 | }; |
| 375 | |
| 376 | /** |
| 377 | * @private |
| 378 | * Converts '9' to '09' (useful for dates) |
| 379 | */ |
| 380 | Dygraph.zeropad = function(x) { |
| 381 | if (x < 10) return "0" + x; else return "" + x; |
| 382 | }; |
| 383 | |
| 384 | /** |
| 385 | * Return a string version of the hours, minutes and seconds portion of a date. |
| 386 | * @param {Number} date The JavaScript date (ms since epoch) |
| 387 | * @return {String} A time of the form "HH:MM:SS" |
| 388 | * @private |
| 389 | */ |
| 390 | Dygraph.hmsString_ = function(date) { |
| 391 | var zeropad = Dygraph.zeropad; |
| 392 | var d = new Date(date); |
| 393 | if (d.getSeconds()) { |
| 394 | return zeropad(d.getHours()) + ":" + |
| 395 | zeropad(d.getMinutes()) + ":" + |
| 396 | zeropad(d.getSeconds()); |
| 397 | } else { |
| 398 | return zeropad(d.getHours()) + ":" + zeropad(d.getMinutes()); |
| 399 | } |
| 400 | }; |
| 401 | |
| 402 | /** |
| 403 | * Round a number to the specified number of digits past the decimal point. |
| 404 | * @param {Number} num The number to round |
| 405 | * @param {Number} places The number of decimals to which to round |
| 406 | * @return {Number} The rounded number |
| 407 | * @private |
| 408 | */ |
| 409 | Dygraph.round_ = function(num, places) { |
| 410 | var shift = Math.pow(10, places); |
| 411 | return Math.round(num * shift)/shift; |
| 412 | }; |
| 413 | |
| 414 | /** |
| 415 | * @private |
| 416 | * Implementation of binary search over an array. |
| 417 | * Currently does not work when val is outside the range of arry's values. |
| 418 | * @param { Integer } val the value to search for |
| 419 | * @param { Integer[] } arry is the value over which to search |
| 420 | * @param { Integer } abs If abs > 0, find the lowest entry greater than val |
| 421 | * If abs < 0, find the highest entry less than val. |
| 422 | * if abs == 0, find the entry that equals val. |
| 423 | * @param { Integer } [low] The first index in arry to consider (optional) |
| 424 | * @param { Integer } [high] The last index in arry to consider (optional) |
| 425 | */ |
| 426 | Dygraph.binarySearch = function(val, arry, abs, low, high) { |
| 427 | if (low === null || low === undefined || |
| 428 | high === null || high === undefined) { |
| 429 | low = 0; |
| 430 | high = arry.length - 1; |
| 431 | } |
| 432 | if (low > high) { |
| 433 | return -1; |
| 434 | } |
| 435 | if (abs === null || abs === undefined) { |
| 436 | abs = 0; |
| 437 | } |
| 438 | var validIndex = function(idx) { |
| 439 | return idx >= 0 && idx < arry.length; |
| 440 | }; |
| 441 | var mid = parseInt((low + high) / 2, 10); |
| 442 | var element = arry[mid]; |
| 443 | if (element == val) { |
| 444 | return mid; |
| 445 | } |
| 446 | |
| 447 | var idx; |
| 448 | if (element > val) { |
| 449 | if (abs > 0) { |
| 450 | // Accept if element > val, but also if prior element < val. |
| 451 | idx = mid - 1; |
| 452 | if (validIndex(idx) && arry[idx] < val) { |
| 453 | return mid; |
| 454 | } |
| 455 | } |
| 456 | return Dygraph.binarySearch(val, arry, abs, low, mid - 1); |
| 457 | } |
| 458 | if (element < val) { |
| 459 | if (abs < 0) { |
| 460 | // Accept if element < val, but also if prior element > val. |
| 461 | idx = mid + 1; |
| 462 | if (validIndex(idx) && arry[idx] > val) { |
| 463 | return mid; |
| 464 | } |
| 465 | } |
| 466 | return Dygraph.binarySearch(val, arry, abs, mid + 1, high); |
| 467 | } |
| 468 | }; |
| 469 | |
| 470 | /** |
| 471 | * @private |
| 472 | * Parses a date, returning the number of milliseconds since epoch. This can be |
| 473 | * passed in as an xValueParser in the Dygraph constructor. |
| 474 | * TODO(danvk): enumerate formats that this understands. |
| 475 | * @param {String} A date in YYYYMMDD format. |
| 476 | * @return {Number} Milliseconds since epoch. |
| 477 | */ |
| 478 | Dygraph.dateParser = function(dateStr) { |
| 479 | var dateStrSlashed; |
| 480 | var d; |
| 481 | |
| 482 | // Let the system try the format first. |
| 483 | d = Dygraph.dateStrToMillis(dateStr); |
| 484 | if (d && !isNaN(d)) return d; |
| 485 | |
| 486 | if (dateStr.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12' |
| 487 | dateStrSlashed = dateStr.replace("-", "/", "g"); |
| 488 | while (dateStrSlashed.search("-") != -1) { |
| 489 | dateStrSlashed = dateStrSlashed.replace("-", "/"); |
| 490 | } |
| 491 | d = Dygraph.dateStrToMillis(dateStrSlashed); |
| 492 | } else if (dateStr.length == 8) { // e.g. '20090712' |
| 493 | // TODO(danvk): remove support for this format. It's confusing. |
| 494 | dateStrSlashed = dateStr.substr(0,4) + "/" + dateStr.substr(4,2) + "/" + |
| 495 | dateStr.substr(6,2); |
| 496 | d = Dygraph.dateStrToMillis(dateStrSlashed); |
| 497 | } else { |
| 498 | // Any format that Date.parse will accept, e.g. "2009/07/12" or |
| 499 | // "2009/07/12 12:34:56" |
| 500 | d = Dygraph.dateStrToMillis(dateStr); |
| 501 | } |
| 502 | |
| 503 | if (!d || isNaN(d)) { |
| 504 | Dygraph.error("Couldn't parse " + dateStr + " as a date"); |
| 505 | } |
| 506 | return d; |
| 507 | }; |
| 508 | |
| 509 | /** |
| 510 | * @private |
| 511 | * This is identical to JavaScript's built-in Date.parse() method, except that |
| 512 | * it doesn't get replaced with an incompatible method by aggressive JS |
| 513 | * libraries like MooTools or Joomla. |
| 514 | * @param { String } str The date string, e.g. "2011/05/06" |
| 515 | * @return { Integer } millis since epoch |
| 516 | */ |
| 517 | Dygraph.dateStrToMillis = function(str) { |
| 518 | return new Date(str).getTime(); |
| 519 | }; |
| 520 | |
| 521 | // These functions are all based on MochiKit. |
| 522 | /** |
| 523 | * Copies all the properties from o to self. |
| 524 | * |
| 525 | * @private |
| 526 | */ |
| 527 | Dygraph.update = function (self, o) { |
| 528 | if (typeof(o) != 'undefined' && o !== null) { |
| 529 | for (var k in o) { |
| 530 | if (o.hasOwnProperty(k)) { |
| 531 | self[k] = o[k]; |
| 532 | } |
| 533 | } |
| 534 | } |
| 535 | return self; |
| 536 | }; |
| 537 | |
| 538 | /** |
| 539 | * Copies all the properties from o to self. |
| 540 | * |
| 541 | * @private |
| 542 | */ |
| 543 | Dygraph.updateDeep = function (self, o) { |
| 544 | // Taken from http://stackoverflow.com/questions/384286/javascript-isdom-how-do-you-check-if-a-javascript-object-is-a-dom-object |
| 545 | function isNode(o) { |
| 546 | return ( |
| 547 | typeof Node === "object" ? o instanceof Node : |
| 548 | typeof o === "object" && typeof o.nodeType === "number" && typeof o.nodeName==="string" |
| 549 | ); |
| 550 | } |
| 551 | |
| 552 | if (typeof(o) != 'undefined' && o !== null) { |
| 553 | for (var k in o) { |
| 554 | if (o.hasOwnProperty(k)) { |
| 555 | if (o[k] === null) { |
| 556 | self[k] = null; |
| 557 | } else if (Dygraph.isArrayLike(o[k])) { |
| 558 | self[k] = o[k].slice(); |
| 559 | } else if (isNode(o[k])) { |
| 560 | // DOM objects are shallowly-copied. |
| 561 | self[k] = o[k]; |
| 562 | } else if (typeof(o[k]) == 'object') { |
| 563 | if (typeof(self[k]) != 'object') { |
| 564 | self[k] = {}; |
| 565 | } |
| 566 | Dygraph.updateDeep(self[k], o[k]); |
| 567 | } else { |
| 568 | self[k] = o[k]; |
| 569 | } |
| 570 | } |
| 571 | } |
| 572 | } |
| 573 | return self; |
| 574 | }; |
| 575 | |
| 576 | /** |
| 577 | * @private |
| 578 | */ |
| 579 | Dygraph.isArrayLike = function (o) { |
| 580 | var typ = typeof(o); |
| 581 | if ( |
| 582 | (typ != 'object' && !(typ == 'function' && |
| 583 | typeof(o.item) == 'function')) || |
| 584 | o === null || |
| 585 | typeof(o.length) != 'number' || |
| 586 | o.nodeType === 3 |
| 587 | ) { |
| 588 | return false; |
| 589 | } |
| 590 | return true; |
| 591 | }; |
| 592 | |
| 593 | /** |
| 594 | * @private |
| 595 | */ |
| 596 | Dygraph.isDateLike = function (o) { |
| 597 | if (typeof(o) != "object" || o === null || |
| 598 | typeof(o.getTime) != 'function') { |
| 599 | return false; |
| 600 | } |
| 601 | return true; |
| 602 | }; |
| 603 | |
| 604 | /** |
| 605 | * Note: this only seems to work for arrays. |
| 606 | * @private |
| 607 | */ |
| 608 | Dygraph.clone = function(o) { |
| 609 | // TODO(danvk): figure out how MochiKit's version works |
| 610 | var r = []; |
| 611 | for (var i = 0; i < o.length; i++) { |
| 612 | if (Dygraph.isArrayLike(o[i])) { |
| 613 | r.push(Dygraph.clone(o[i])); |
| 614 | } else { |
| 615 | r.push(o[i]); |
| 616 | } |
| 617 | } |
| 618 | return r; |
| 619 | }; |
| 620 | |
| 621 | /** |
| 622 | * @private |
| 623 | * Create a new canvas element. This is more complex than a simple |
| 624 | * document.createElement("canvas") because of IE and excanvas. |
| 625 | */ |
| 626 | Dygraph.createCanvas = function() { |
| 627 | var canvas = document.createElement("canvas"); |
| 628 | |
| 629 | var isIE = (/MSIE/.test(navigator.userAgent) && !window.opera); |
| 630 | if (isIE && (typeof(G_vmlCanvasManager) != 'undefined')) { |
| 631 | canvas = G_vmlCanvasManager.initElement(canvas); |
| 632 | } |
| 633 | |
| 634 | return canvas; |
| 635 | }; |
| 636 | |
| 637 | /** |
| 638 | * @private |
| 639 | * Checks whether the user is on an Android browser. |
| 640 | * Android does not fully support the <canvas> tag, e.g. w/r/t/ clipping. |
| 641 | */ |
| 642 | Dygraph.isAndroid = function() { |
| 643 | return (/Android/).test(navigator.userAgent); |
| 644 | }; |
| 645 | |
| 646 | /** |
| 647 | * @private |
| 648 | * Call a function N times at a given interval, then call a cleanup function |
| 649 | * once. repeat_fn is called once immediately, then (times - 1) times |
| 650 | * asynchronously. If times=1, then cleanup_fn() is also called synchronously. |
| 651 | * @param repeat_fn {Function} Called repeatedly -- takes the number of calls |
| 652 | * (from 0 to times-1) as an argument. |
| 653 | * @param times {number} The number of times to call repeat_fn |
| 654 | * @param every_ms {number} Milliseconds between calls |
| 655 | * @param cleanup_fn {Function} A function to call after all repeat_fn calls. |
| 656 | * @private |
| 657 | */ |
| 658 | Dygraph.repeatAndCleanup = function(repeat_fn, times, every_ms, cleanup_fn) { |
| 659 | var count = 0; |
| 660 | var start_time = new Date().getTime(); |
| 661 | repeat_fn(count); |
| 662 | if (times == 1) { |
| 663 | cleanup_fn(); |
| 664 | return; |
| 665 | } |
| 666 | |
| 667 | (function loop() { |
| 668 | if (count >= times) return; |
| 669 | var target_time = start_time + (1 + count) * every_ms; |
| 670 | setTimeout(function() { |
| 671 | count++; |
| 672 | repeat_fn(count); |
| 673 | if (count >= times - 1) { |
| 674 | cleanup_fn(); |
| 675 | } else { |
| 676 | loop(); |
| 677 | } |
| 678 | }, target_time - new Date().getTime()); |
| 679 | // TODO(danvk): adjust every_ms to produce evenly-timed function calls. |
| 680 | })(); |
| 681 | }; |
| 682 | |
| 683 | /** |
| 684 | * @private |
| 685 | * This function will scan the option list and determine if they |
| 686 | * require us to recalculate the pixel positions of each point. |
| 687 | * @param { List } a list of options to check. |
| 688 | * @return { Boolean } true if the graph needs new points else false. |
| 689 | */ |
| 690 | Dygraph.isPixelChangingOptionList = function(labels, attrs) { |
| 691 | // A whitelist of options that do not change pixel positions. |
| 692 | var pixelSafeOptions = { |
| 693 | 'annotationClickHandler': true, |
| 694 | 'annotationDblClickHandler': true, |
| 695 | 'annotationMouseOutHandler': true, |
| 696 | 'annotationMouseOverHandler': true, |
| 697 | 'axisLabelColor': true, |
| 698 | 'axisLineColor': true, |
| 699 | 'axisLineWidth': true, |
| 700 | 'clickCallback': true, |
| 701 | 'digitsAfterDecimal': true, |
| 702 | 'drawCallback': true, |
| 703 | 'drawHighlightPointCallback': true, |
| 704 | 'drawPoints': true, |
| 705 | 'drawPointCallback': true, |
| 706 | 'drawXGrid': true, |
| 707 | 'drawYGrid': true, |
| 708 | 'fillAlpha': true, |
| 709 | 'gridLineColor': true, |
| 710 | 'gridLineWidth': true, |
| 711 | 'hideOverlayOnMouseOut': true, |
| 712 | 'highlightCallback': true, |
| 713 | 'highlightCircleSize': true, |
| 714 | 'interactionModel': true, |
| 715 | 'isZoomedIgnoreProgrammaticZoom': true, |
| 716 | 'labelsDiv': true, |
| 717 | 'labelsDivStyles': true, |
| 718 | 'labelsDivWidth': true, |
| 719 | 'labelsKMB': true, |
| 720 | 'labelsKMG2': true, |
| 721 | 'labelsSeparateLines': true, |
| 722 | 'labelsShowZeroValues': true, |
| 723 | 'legend': true, |
| 724 | 'maxNumberWidth': true, |
| 725 | 'panEdgeFraction': true, |
| 726 | 'pixelsPerYLabel': true, |
| 727 | 'pointClickCallback': true, |
| 728 | 'pointSize': true, |
| 729 | 'rangeSelectorPlotFillColor': true, |
| 730 | 'rangeSelectorPlotStrokeColor': true, |
| 731 | 'showLabelsOnHighlight': true, |
| 732 | 'showRoller': true, |
| 733 | 'sigFigs': true, |
| 734 | 'strokeWidth': true, |
| 735 | 'underlayCallback': true, |
| 736 | 'unhighlightCallback': true, |
| 737 | 'xAxisLabelFormatter': true, |
| 738 | 'xTicker': true, |
| 739 | 'xValueFormatter': true, |
| 740 | 'yAxisLabelFormatter': true, |
| 741 | 'yValueFormatter': true, |
| 742 | 'zoomCallback': true |
| 743 | }; |
| 744 | |
| 745 | // Assume that we do not require new points. |
| 746 | // This will change to true if we actually do need new points. |
| 747 | var requiresNewPoints = false; |
| 748 | |
| 749 | // Create a dictionary of series names for faster lookup. |
| 750 | // If there are no labels, then the dictionary stays empty. |
| 751 | var seriesNamesDictionary = { }; |
| 752 | if (labels) { |
| 753 | for (var i = 1; i < labels.length; i++) { |
| 754 | seriesNamesDictionary[labels[i]] = true; |
| 755 | } |
| 756 | } |
| 757 | |
| 758 | // Iterate through the list of updated options. |
| 759 | for (var property in attrs) { |
| 760 | // Break early if we already know we need new points from a previous option. |
| 761 | if (requiresNewPoints) { |
| 762 | break; |
| 763 | } |
| 764 | if (attrs.hasOwnProperty(property)) { |
| 765 | // Find out of this field is actually a series specific options list. |
| 766 | if (seriesNamesDictionary[property]) { |
| 767 | // This property value is a list of options for this series. |
| 768 | // If any of these sub properties are not pixel safe, set the flag. |
| 769 | for (var subProperty in attrs[property]) { |
| 770 | // Break early if we already know we need new points from a previous option. |
| 771 | if (requiresNewPoints) { |
| 772 | break; |
| 773 | } |
| 774 | if (attrs[property].hasOwnProperty(subProperty) && !pixelSafeOptions[subProperty]) { |
| 775 | requiresNewPoints = true; |
| 776 | } |
| 777 | } |
| 778 | // If this was not a series specific option list, check if its a pixel changing property. |
| 779 | } else if (!pixelSafeOptions[property]) { |
| 780 | requiresNewPoints = true; |
| 781 | } |
| 782 | } |
| 783 | } |
| 784 | |
| 785 | return requiresNewPoints; |
| 786 | }; |
| 787 | |
| 788 | /** |
| 789 | * Compares two arrays to see if they are equal. If either parameter is not an |
| 790 | * array it will return false. Does a shallow compare |
| 791 | * Dygraph.compareArrays([[1,2], [3, 4]], [[1,2], [3,4]]) === false. |
| 792 | * @param array1 first array |
| 793 | * @param array2 second array |
| 794 | * @return True if both parameters are arrays, and contents are equal. |
| 795 | */ |
| 796 | Dygraph.compareArrays = function(array1, array2) { |
| 797 | if (!Dygraph.isArrayLike(array1) || !Dygraph.isArrayLike(array2)) { |
| 798 | return false; |
| 799 | } |
| 800 | if (array1.length !== array2.length) { |
| 801 | return false; |
| 802 | } |
| 803 | for (var i = 0; i < array1.length; i++) { |
| 804 | if (array1[i] !== array2[i]) { |
| 805 | return false; |
| 806 | } |
| 807 | } |
| 808 | return true; |
| 809 | }; |
| 810 | |
| 811 | /** |
| 812 | * ctx: the canvas context |
| 813 | * sides: the number of sides in the shape. |
| 814 | * radius: the radius of the image. |
| 815 | * cx: center x coordate |
| 816 | * cy: center y coordinate |
| 817 | * rotationRadians: the shift of the initial angle, in radians. |
| 818 | * delta: the angle shift for each line. If missing, creates a regular |
| 819 | * polygon. |
| 820 | */ |
| 821 | Dygraph.regularShape_ = function( |
| 822 | ctx, sides, radius, cx, cy, rotationRadians, delta) { |
| 823 | rotationRadians = rotationRadians ? rotationRadians : 0; |
| 824 | delta = delta ? delta : Math.PI * 2 / sides; |
| 825 | |
| 826 | ctx.beginPath(); |
| 827 | var first = true; |
| 828 | var initialAngle = rotationRadians; |
| 829 | var angle = initialAngle; |
| 830 | |
| 831 | var computeCoordinates = function() { |
| 832 | var x = cx + (Math.sin(angle) * radius); |
| 833 | var y = cy + (-Math.cos(angle) * radius); |
| 834 | return [x, y]; |
| 835 | }; |
| 836 | |
| 837 | var initialCoordinates = computeCoordinates(); |
| 838 | var x = initialCoordinates[0]; |
| 839 | var y = initialCoordinates[1]; |
| 840 | ctx.moveTo(x, y); |
| 841 | |
| 842 | for (var idx = 0; idx < sides; idx++) { |
| 843 | angle = (idx == sides - 1) ? initialAngle : (angle + delta); |
| 844 | var coords = computeCoordinates(); |
| 845 | ctx.lineTo(coords[0], coords[1]); |
| 846 | } |
| 847 | ctx.stroke(); |
| 848 | ctx.closePath(); |
| 849 | } |
| 850 | |
| 851 | Dygraph.shapeFunction_ = function(sides, rotationRadians, delta) { |
| 852 | return function(g, name, ctx, cx, cy, color, radius) { |
| 853 | ctx.lineWidth = 1; |
| 854 | ctx.strokeStyle = color; |
| 855 | Dygraph.regularShape_(ctx, sides, radius, cx, cy, rotationRadians, delta); |
| 856 | }; |
| 857 | }; |
| 858 | |
| 859 | Dygraph.DrawPolygon_ = function(sides, rotationRadians, ctx, cx, cy, color, radius, delta) { |
| 860 | new Dygraph.RegularShape_(sides, rotationRadians, delta).draw(ctx, cx, cy, radius); |
| 861 | } |
| 862 | |
| 863 | Dygraph.Circles = { |
| 864 | DEFAULT : function(g, name, ctx, canvasx, canvasy, color, radius) { |
| 865 | ctx.beginPath(); |
| 866 | ctx.fillStyle = color; |
| 867 | ctx.arc(canvasx, canvasy, radius, 0, 2 * Math.PI, false); |
| 868 | ctx.fill(); |
| 869 | }, |
| 870 | TRIANGLE : Dygraph.shapeFunction_(3), |
| 871 | SQUARE : Dygraph.shapeFunction_(4, Math.PI / 4), |
| 872 | DIAMOND : Dygraph.shapeFunction_(4), |
| 873 | PENTAGON : Dygraph.shapeFunction_(5), |
| 874 | HEXAGON : Dygraph.shapeFunction_(6), |
| 875 | CIRCLE : function(g, name, ctx, cx, cy, color, radius) { |
| 876 | ctx.beginPath(); |
| 877 | ctx.strokeStyle = color; |
| 878 | ctx.arc(cx, cy, radius, 0, 2 * Math.PI, false); |
| 879 | ctx.stroke(); |
| 880 | }, |
| 881 | STAR : Dygraph.shapeFunction_(5, 0, 4 * Math.PI / 5), |
| 882 | PLUS : function(g, name, ctx, cx, cy, color, radius) { |
| 883 | ctx.lineWidth = 1; |
| 884 | ctx.strokeStyle = color; |
| 885 | |
| 886 | ctx.beginPath(); |
| 887 | ctx.moveTo(cx + radius, cy); |
| 888 | ctx.lineTo(cx - radius, cy); |
| 889 | ctx.closePath(); |
| 890 | ctx.stroke(); |
| 891 | |
| 892 | ctx.beginPath(); |
| 893 | ctx.moveTo(cx, cy + radius); |
| 894 | ctx.lineTo(cx, cy - radius); |
| 895 | ctx.closePath(); |
| 896 | |
| 897 | ctx.stroke(); |
| 898 | }, |
| 899 | EX : function(g, name, ctx, cx, cy, color, radius) { |
| 900 | ctx.lineWidth = 1; |
| 901 | ctx.strokeStyle = "black"; |
| 902 | |
| 903 | ctx.beginPath(); |
| 904 | ctx.moveTo(cx + radius, cy + radius); |
| 905 | ctx.lineTo(cx - radius, cy - radius); |
| 906 | ctx.closePath(); |
| 907 | ctx.stroke(); |
| 908 | |
| 909 | ctx.beginPath(); |
| 910 | ctx.moveTo(cx + radius, cy - radius); |
| 911 | ctx.lineTo(cx - radius, cy + radius); |
| 912 | ctx.closePath(); |
| 913 | |
| 914 | ctx.stroke(); |
| 915 | } |
| 916 | }; |