| 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 | /** |
| 22 | * @private |
| 23 | * @param {number} x |
| 24 | * @return {number} |
| 25 | */ |
| 26 | Dygraph.log10 = function(x) { |
| 27 | return Math.log(x) / Dygraph.LN_TEN; |
| 28 | }; |
| 29 | |
| 30 | // Various logging levels. |
| 31 | Dygraph.DEBUG = 1; |
| 32 | Dygraph.INFO = 2; |
| 33 | Dygraph.WARNING = 3; |
| 34 | Dygraph.ERROR = 3; |
| 35 | |
| 36 | // <REMOVE_FOR_COMBINED> |
| 37 | // Set this to log stack traces on warnings, etc. |
| 38 | // This requires stacktrace.js, which is up to you to provide. |
| 39 | // A copy can be found in the dygraphs repo, or at |
| 40 | // https://github.com/eriwen/javascript-stacktrace |
| 41 | Dygraph.LOG_STACK_TRACES = false; |
| 42 | // </REMOVE_FOR_COMBINED> |
| 43 | |
| 44 | /** A dotted line stroke pattern. */ |
| 45 | Dygraph.DOTTED_LINE = [2, 2]; |
| 46 | /** A dashed line stroke pattern. */ |
| 47 | Dygraph.DASHED_LINE = [7, 3]; |
| 48 | /** A dot dash stroke pattern. */ |
| 49 | Dygraph.DOT_DASH_LINE = [7, 2, 2, 2]; |
| 50 | |
| 51 | /** |
| 52 | * Log an error on the JS console at the given severity. |
| 53 | * @param {number} severity One of Dygraph.{DEBUG,INFO,WARNING,ERROR} |
| 54 | * @param {string} message The message to log. |
| 55 | * @private |
| 56 | */ |
| 57 | Dygraph.log = function(severity, message) { |
| 58 | // <REMOVE_FOR_COMBINED> |
| 59 | var st; |
| 60 | if (typeof(printStackTrace) != 'undefined') { |
| 61 | try { |
| 62 | // Remove uninteresting bits: logging functions and paths. |
| 63 | st = printStackTrace({guess:false}); |
| 64 | while (st[0].indexOf("stacktrace") != -1) { |
| 65 | st.splice(0, 1); |
| 66 | } |
| 67 | |
| 68 | st.splice(0, 2); |
| 69 | for (var i = 0; i < st.length; i++) { |
| 70 | st[i] = st[i].replace(/\([^)]*\/(.*)\)/, '@$1') |
| 71 | .replace(/\@.*\/([^\/]*)/, '@$1') |
| 72 | .replace('[object Object].', ''); |
| 73 | } |
| 74 | var top_msg = st.splice(0, 1)[0]; |
| 75 | message += ' (' + top_msg.replace(/^.*@ ?/, '') + ')'; |
| 76 | } catch(e) { |
| 77 | // Oh well, it was worth a shot! |
| 78 | } |
| 79 | } |
| 80 | // </REMOVE_FOR_COMBINED> |
| 81 | |
| 82 | if (typeof(window.console) != 'undefined') { |
| 83 | // In older versions of Firefox, only console.log is defined. |
| 84 | var console = window.console; |
| 85 | var log = function(console, method, msg) { |
| 86 | if (method && typeof(method) == 'function') { |
| 87 | method.call(console, msg); |
| 88 | } else { |
| 89 | console.log(msg); |
| 90 | } |
| 91 | }; |
| 92 | |
| 93 | switch (severity) { |
| 94 | case Dygraph.DEBUG: |
| 95 | log(console, console.debug, 'dygraphs: ' + message); |
| 96 | break; |
| 97 | case Dygraph.INFO: |
| 98 | log(console, console.info, 'dygraphs: ' + message); |
| 99 | break; |
| 100 | case Dygraph.WARNING: |
| 101 | log(console, console.warn, 'dygraphs: ' + message); |
| 102 | break; |
| 103 | case Dygraph.ERROR: |
| 104 | log(console, console.error, 'dygraphs: ' + message); |
| 105 | break; |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | // <REMOVE_FOR_COMBINED> |
| 110 | if (Dygraph.LOG_STACK_TRACES) { |
| 111 | window.console.log(st.join('\n')); |
| 112 | } |
| 113 | // </REMOVE_FOR_COMBINED> |
| 114 | }; |
| 115 | |
| 116 | /** |
| 117 | * @param {string} message |
| 118 | * @private |
| 119 | */ |
| 120 | Dygraph.info = function(message) { |
| 121 | Dygraph.log(Dygraph.INFO, message); |
| 122 | }; |
| 123 | |
| 124 | /** |
| 125 | * @param {string} message |
| 126 | * @private |
| 127 | */ |
| 128 | Dygraph.warn = function(message) { |
| 129 | Dygraph.log(Dygraph.WARNING, message); |
| 130 | }; |
| 131 | |
| 132 | /** |
| 133 | * @param {string} message |
| 134 | */ |
| 135 | Dygraph.error = function(message) { |
| 136 | Dygraph.log(Dygraph.ERROR, message); |
| 137 | }; |
| 138 | |
| 139 | /** |
| 140 | * Return the 2d context for a dygraph canvas. |
| 141 | * |
| 142 | * This method is only exposed for the sake of replacing the function in |
| 143 | * automated tests, e.g. |
| 144 | * |
| 145 | * var oldFunc = Dygraph.getContext(); |
| 146 | * Dygraph.getContext = function(canvas) { |
| 147 | * var realContext = oldFunc(canvas); |
| 148 | * return new Proxy(realContext); |
| 149 | * }; |
| 150 | * @param {!HTMLCanvasElement} canvas |
| 151 | * @return {!CanvasRenderingContext2D} |
| 152 | * @private |
| 153 | */ |
| 154 | Dygraph.getContext = function(canvas) { |
| 155 | return /** @type{!CanvasRenderingContext2D}*/(canvas.getContext("2d")); |
| 156 | }; |
| 157 | |
| 158 | /** |
| 159 | * Add an event handler. This smooths a difference between IE and the rest of |
| 160 | * the world. |
| 161 | * @param { !Element } elem The element to add the event to. |
| 162 | * @param { string } type The type of the event, e.g. 'click' or 'mousemove'. |
| 163 | * @param { function(Event):(boolean|undefined) } fn The function to call |
| 164 | * on the event. The function takes one parameter: the event object. |
| 165 | * @private |
| 166 | */ |
| 167 | Dygraph.addEvent = function addEvent(elem, type, fn) { |
| 168 | if (elem.addEventListener) { |
| 169 | elem.addEventListener(type, fn, false); |
| 170 | } else { |
| 171 | elem[type+fn] = function(){fn(window.event);}; |
| 172 | elem.attachEvent('on'+type, elem[type+fn]); |
| 173 | } |
| 174 | }; |
| 175 | |
| 176 | /** |
| 177 | * Add an event handler. This event handler is kept until the graph is |
| 178 | * destroyed with a call to graph.destroy(). |
| 179 | * |
| 180 | * @param { !Element } elem The element to add the event to. |
| 181 | * @param { string } type The type of the event, e.g. 'click' or 'mousemove'. |
| 182 | * @param { function(Event):(boolean|undefined) } fn The function to call |
| 183 | * on the event. The function takes one parameter: the event object. |
| 184 | * @private |
| 185 | */ |
| 186 | Dygraph.prototype.addAndTrackEvent = function(elem, type, fn) { |
| 187 | Dygraph.addEvent(elem, type, fn); |
| 188 | this.registeredEvents_.push({ elem : elem, type : type, fn : fn }); |
| 189 | }; |
| 190 | |
| 191 | /** |
| 192 | * Remove an event handler. This smooths a difference between IE and the rest |
| 193 | * of the world. |
| 194 | * @param {!Element} elem The element to add the event to. |
| 195 | * @param {string} type The type of the event, e.g. 'click' or 'mousemove'. |
| 196 | * @param {function(Event):(boolean|undefined)} fn The function to call |
| 197 | * on the event. The function takes one parameter: the event object. |
| 198 | * @private |
| 199 | */ |
| 200 | Dygraph.removeEvent = function(elem, type, fn) { |
| 201 | if (elem.removeEventListener) { |
| 202 | elem.removeEventListener(type, fn, false); |
| 203 | } else { |
| 204 | try { |
| 205 | elem.detachEvent('on'+type, elem[type+fn]); |
| 206 | } catch(e) { |
| 207 | // We only detach event listeners on a "best effort" basis in IE. See: |
| 208 | // http://stackoverflow.com/questions/2553632/detachevent-not-working-with-named-inline-functions |
| 209 | } |
| 210 | elem[type+fn] = null; |
| 211 | } |
| 212 | }; |
| 213 | |
| 214 | Dygraph.prototype.removeTrackedEvents_ = function() { |
| 215 | if (this.registeredEvents_) { |
| 216 | for (var idx = 0; idx < this.registeredEvents_.length; idx++) { |
| 217 | var reg = this.registeredEvents_[idx]; |
| 218 | Dygraph.removeEvent(reg.elem, reg.type, reg.fn); |
| 219 | } |
| 220 | } |
| 221 | |
| 222 | this.registeredEvents_ = []; |
| 223 | }; |
| 224 | |
| 225 | /** |
| 226 | * Cancels further processing of an event. This is useful to prevent default |
| 227 | * browser actions, e.g. highlighting text on a double-click. |
| 228 | * Based on the article at |
| 229 | * http://www.switchonthecode.com/tutorials/javascript-tutorial-the-scroll-wheel |
| 230 | * @param { !Event } e The event whose normal behavior should be canceled. |
| 231 | * @private |
| 232 | */ |
| 233 | Dygraph.cancelEvent = function(e) { |
| 234 | e = e ? e : window.event; |
| 235 | if (e.stopPropagation) { |
| 236 | e.stopPropagation(); |
| 237 | } |
| 238 | if (e.preventDefault) { |
| 239 | e.preventDefault(); |
| 240 | } |
| 241 | e.cancelBubble = true; |
| 242 | e.cancel = true; |
| 243 | e.returnValue = false; |
| 244 | return false; |
| 245 | }; |
| 246 | |
| 247 | /** |
| 248 | * Convert hsv values to an rgb(r,g,b) string. Taken from MochiKit.Color. This |
| 249 | * is used to generate default series colors which are evenly spaced on the |
| 250 | * color wheel. |
| 251 | * @param { number } hue Range is 0.0-1.0. |
| 252 | * @param { number } saturation Range is 0.0-1.0. |
| 253 | * @param { number } value Range is 0.0-1.0. |
| 254 | * @return { string } "rgb(r,g,b)" where r, g and b range from 0-255. |
| 255 | * @private |
| 256 | */ |
| 257 | Dygraph.hsvToRGB = function (hue, saturation, value) { |
| 258 | var red; |
| 259 | var green; |
| 260 | var blue; |
| 261 | if (saturation === 0) { |
| 262 | red = value; |
| 263 | green = value; |
| 264 | blue = value; |
| 265 | } else { |
| 266 | var i = Math.floor(hue * 6); |
| 267 | var f = (hue * 6) - i; |
| 268 | var p = value * (1 - saturation); |
| 269 | var q = value * (1 - (saturation * f)); |
| 270 | var t = value * (1 - (saturation * (1 - f))); |
| 271 | switch (i) { |
| 272 | case 1: red = q; green = value; blue = p; break; |
| 273 | case 2: red = p; green = value; blue = t; break; |
| 274 | case 3: red = p; green = q; blue = value; break; |
| 275 | case 4: red = t; green = p; blue = value; break; |
| 276 | case 5: red = value; green = p; blue = q; break; |
| 277 | case 6: // fall through |
| 278 | case 0: red = value; green = t; blue = p; break; |
| 279 | } |
| 280 | } |
| 281 | red = Math.floor(255 * red + 0.5); |
| 282 | green = Math.floor(255 * green + 0.5); |
| 283 | blue = Math.floor(255 * blue + 0.5); |
| 284 | return 'rgb(' + red + ',' + green + ',' + blue + ')'; |
| 285 | }; |
| 286 | |
| 287 | // The following functions are from quirksmode.org with a modification for Safari from |
| 288 | // http://blog.firetree.net/2005/07/04/javascript-find-position/ |
| 289 | // http://www.quirksmode.org/js/findpos.html |
| 290 | // ... and modifications to support scrolling divs. |
| 291 | |
| 292 | /** |
| 293 | * Find the coordinates of an object relative to the top left of the page. |
| 294 | * |
| 295 | * TODO(danvk): change obj type from Node -> !Node |
| 296 | * @param {Node} obj |
| 297 | * @return {{x:number,y:number}} |
| 298 | * @private |
| 299 | */ |
| 300 | Dygraph.findPos = function(obj) { |
| 301 | var curleft = 0, curtop = 0; |
| 302 | if (obj.offsetParent) { |
| 303 | var copyObj = obj; |
| 304 | while (1) { |
| 305 | // NOTE: the if statement here is for IE8. |
| 306 | var borderLeft = "0", borderTop = "0"; |
| 307 | if (window.getComputedStyle) { |
| 308 | var computedStyle = window.getComputedStyle(copyObj, null); |
| 309 | borderLeft = computedStyle.borderLeft || "0"; |
| 310 | borderTop = computedStyle.borderTop || "0"; |
| 311 | } |
| 312 | curleft += parseInt(borderLeft, 10) ; |
| 313 | curtop += parseInt(borderTop, 10) ; |
| 314 | curleft += copyObj.offsetLeft; |
| 315 | curtop += copyObj.offsetTop; |
| 316 | if (!copyObj.offsetParent) { |
| 317 | break; |
| 318 | } |
| 319 | copyObj = copyObj.offsetParent; |
| 320 | } |
| 321 | } else { |
| 322 | // TODO(danvk): why would obj ever have these properties? |
| 323 | if (obj.x) curleft += obj.x; |
| 324 | if (obj.y) curtop += obj.y; |
| 325 | } |
| 326 | |
| 327 | // This handles the case where the object is inside a scrolled div. |
| 328 | while (obj && obj != document.body) { |
| 329 | curleft -= obj.scrollLeft; |
| 330 | curtop -= obj.scrollTop; |
| 331 | obj = obj.parentNode; |
| 332 | } |
| 333 | return {x: curleft, y: curtop}; |
| 334 | }; |
| 335 | |
| 336 | /** |
| 337 | * Returns the x-coordinate of the event in a coordinate system where the |
| 338 | * top-left corner of the page (not the window) is (0,0). |
| 339 | * Taken from MochiKit.Signal |
| 340 | * @param {!Event} e |
| 341 | * @return {number} |
| 342 | * @private |
| 343 | */ |
| 344 | Dygraph.pageX = function(e) { |
| 345 | if (e.pageX) { |
| 346 | return (!e.pageX || e.pageX < 0) ? 0 : e.pageX; |
| 347 | } else { |
| 348 | var de = document.documentElement; |
| 349 | var b = document.body; |
| 350 | return e.clientX + |
| 351 | (de.scrollLeft || b.scrollLeft) - |
| 352 | (de.clientLeft || 0); |
| 353 | } |
| 354 | }; |
| 355 | |
| 356 | /** |
| 357 | * Returns the y-coordinate of the event in a coordinate system where the |
| 358 | * top-left corner of the page (not the window) is (0,0). |
| 359 | * Taken from MochiKit.Signal |
| 360 | * @param {!Event} e |
| 361 | * @return {number} |
| 362 | * @private |
| 363 | */ |
| 364 | Dygraph.pageY = function(e) { |
| 365 | if (e.pageY) { |
| 366 | return (!e.pageY || e.pageY < 0) ? 0 : e.pageY; |
| 367 | } else { |
| 368 | var de = document.documentElement; |
| 369 | var b = document.body; |
| 370 | return e.clientY + |
| 371 | (de.scrollTop || b.scrollTop) - |
| 372 | (de.clientTop || 0); |
| 373 | } |
| 374 | }; |
| 375 | |
| 376 | /** |
| 377 | * This returns true unless the parameter is 0, null, undefined or NaN. |
| 378 | * TODO(danvk): rename this function to something like 'isNonZeroNan'. |
| 379 | * |
| 380 | * @param {number} x The number to consider. |
| 381 | * @return {boolean} Whether the number is zero or NaN. |
| 382 | * @private |
| 383 | */ |
| 384 | Dygraph.isOK = function(x) { |
| 385 | return !!x && !isNaN(x); |
| 386 | }; |
| 387 | |
| 388 | /** |
| 389 | * @param { {x:?number,y:?number,yval:?number} } p The point to consider, valid |
| 390 | * points are {x, y} objects |
| 391 | * @param { boolean } allowNaNY Treat point with y=NaN as valid |
| 392 | * @return { boolean } Whether the point has numeric x and y. |
| 393 | * @private |
| 394 | */ |
| 395 | Dygraph.isValidPoint = function(p, allowNaNY) { |
| 396 | if (!p) return false; // null or undefined object |
| 397 | if (p.yval === null) return false; // missing point |
| 398 | if (p.x === null || p.x === undefined) return false; |
| 399 | if (p.y === null || p.y === undefined) return false; |
| 400 | if (isNaN(p.x) || (!allowNaNY && isNaN(p.y))) return false; |
| 401 | return true; |
| 402 | }; |
| 403 | |
| 404 | /** |
| 405 | * Number formatting function which mimicks the behavior of %g in printf, i.e. |
| 406 | * either exponential or fixed format (without trailing 0s) is used depending on |
| 407 | * the length of the generated string. The advantage of this format is that |
| 408 | * there is a predictable upper bound on the resulting string length, |
| 409 | * significant figures are not dropped, and normal numbers are not displayed in |
| 410 | * exponential notation. |
| 411 | * |
| 412 | * NOTE: JavaScript's native toPrecision() is NOT a drop-in replacement for %g. |
| 413 | * It creates strings which are too long for absolute values between 10^-4 and |
| 414 | * 10^-6, e.g. '0.00001' instead of '1e-5'. See tests/number-format.html for |
| 415 | * output examples. |
| 416 | * |
| 417 | * @param {number} x The number to format |
| 418 | * @param {number=} opt_precision The precision to use, default 2. |
| 419 | * @return {string} A string formatted like %g in printf. The max generated |
| 420 | * string length should be precision + 6 (e.g 1.123e+300). |
| 421 | */ |
| 422 | Dygraph.floatFormat = function(x, opt_precision) { |
| 423 | // Avoid invalid precision values; [1, 21] is the valid range. |
| 424 | var p = Math.min(Math.max(1, opt_precision || 2), 21); |
| 425 | |
| 426 | // This is deceptively simple. The actual algorithm comes from: |
| 427 | // |
| 428 | // Max allowed length = p + 4 |
| 429 | // where 4 comes from 'e+n' and '.'. |
| 430 | // |
| 431 | // Length of fixed format = 2 + y + p |
| 432 | // where 2 comes from '0.' and y = # of leading zeroes. |
| 433 | // |
| 434 | // Equating the two and solving for y yields y = 2, or 0.00xxxx which is |
| 435 | // 1.0e-3. |
| 436 | // |
| 437 | // Since the behavior of toPrecision() is identical for larger numbers, we |
| 438 | // don't have to worry about the other bound. |
| 439 | // |
| 440 | // Finally, the argument for toExponential() is the number of trailing digits, |
| 441 | // so we take off 1 for the value before the '.'. |
| 442 | return (Math.abs(x) < 1.0e-3 && x !== 0.0) ? |
| 443 | x.toExponential(p - 1) : x.toPrecision(p); |
| 444 | }; |
| 445 | |
| 446 | /** |
| 447 | * Converts '9' to '09' (useful for dates) |
| 448 | * @param {number} x |
| 449 | * @return {string} |
| 450 | * @private |
| 451 | */ |
| 452 | Dygraph.zeropad = function(x) { |
| 453 | if (x < 10) return "0" + x; else return "" + x; |
| 454 | }; |
| 455 | |
| 456 | /** |
| 457 | * Return a string version of the hours, minutes and seconds portion of a date. |
| 458 | * |
| 459 | * @param {number} date The JavaScript date (ms since epoch) |
| 460 | * @return {string} A time of the form "HH:MM:SS" |
| 461 | * @private |
| 462 | */ |
| 463 | Dygraph.hmsString_ = function(date) { |
| 464 | var zeropad = Dygraph.zeropad; |
| 465 | var d = new Date(date); |
| 466 | if (d.getSeconds()) { |
| 467 | return zeropad(d.getHours()) + ":" + |
| 468 | zeropad(d.getMinutes()) + ":" + |
| 469 | zeropad(d.getSeconds()); |
| 470 | } else { |
| 471 | return zeropad(d.getHours()) + ":" + zeropad(d.getMinutes()); |
| 472 | } |
| 473 | }; |
| 474 | |
| 475 | /** |
| 476 | * Convert a JS date (millis since epoch) to YYYY/MM/DD |
| 477 | * @param {number} date The JavaScript date (ms since epoch) |
| 478 | * @return {string} A date of the form "YYYY/MM/DD" |
| 479 | * @private |
| 480 | */ |
| 481 | Dygraph.dateString_ = function(date) { |
| 482 | var zeropad = Dygraph.zeropad; |
| 483 | var d = new Date(date); |
| 484 | |
| 485 | // Get the year: |
| 486 | var year = "" + d.getFullYear(); |
| 487 | // Get a 0 padded month string |
| 488 | var month = zeropad(d.getMonth() + 1); //months are 0-offset, sigh |
| 489 | // Get a 0 padded day string |
| 490 | var day = zeropad(d.getDate()); |
| 491 | |
| 492 | var ret = ""; |
| 493 | var frac = d.getHours() * 3600 + d.getMinutes() * 60 + d.getSeconds(); |
| 494 | if (frac) ret = " " + Dygraph.hmsString_(date); |
| 495 | |
| 496 | return year + "/" + month + "/" + day + ret; |
| 497 | }; |
| 498 | |
| 499 | /** |
| 500 | * Round a number to the specified number of digits past the decimal point. |
| 501 | * @param {number} num The number to round |
| 502 | * @param {number} places The number of decimals to which to round |
| 503 | * @return {number} The rounded number |
| 504 | * @private |
| 505 | */ |
| 506 | Dygraph.round_ = function(num, places) { |
| 507 | var shift = Math.pow(10, places); |
| 508 | return Math.round(num * shift)/shift; |
| 509 | }; |
| 510 | |
| 511 | /** |
| 512 | * Implementation of binary search over an array. |
| 513 | * Currently does not work when val is outside the range of arry's values. |
| 514 | * @param {number} val the value to search for |
| 515 | * @param {Array.<number>} arry is the value over which to search |
| 516 | * @param {number} abs If abs > 0, find the lowest entry greater than val |
| 517 | * If abs < 0, find the highest entry less than val. |
| 518 | * If abs == 0, find the entry that equals val. |
| 519 | * @param {number=} low The first index in arry to consider (optional) |
| 520 | * @param {number=} high The last index in arry to consider (optional) |
| 521 | * @return {number} Index of the element, or -1 if it isn't found. |
| 522 | * @private |
| 523 | */ |
| 524 | Dygraph.binarySearch = function(val, arry, abs, low, high) { |
| 525 | if (low === null || low === undefined || |
| 526 | high === null || high === undefined) { |
| 527 | low = 0; |
| 528 | high = arry.length - 1; |
| 529 | } |
| 530 | if (low > high) { |
| 531 | return -1; |
| 532 | } |
| 533 | if (abs === null || abs === undefined) { |
| 534 | abs = 0; |
| 535 | } |
| 536 | var validIndex = function(idx) { |
| 537 | return idx >= 0 && idx < arry.length; |
| 538 | }; |
| 539 | var mid = parseInt((low + high) / 2, 10); |
| 540 | var element = arry[mid]; |
| 541 | var idx; |
| 542 | if (element == val) { |
| 543 | return mid; |
| 544 | } else if (element > val) { |
| 545 | if (abs > 0) { |
| 546 | // Accept if element > val, but also if prior element < val. |
| 547 | idx = mid - 1; |
| 548 | if (validIndex(idx) && arry[idx] < val) { |
| 549 | return mid; |
| 550 | } |
| 551 | } |
| 552 | return Dygraph.binarySearch(val, arry, abs, low, mid - 1); |
| 553 | } else if (element < val) { |
| 554 | if (abs < 0) { |
| 555 | // Accept if element < val, but also if prior element > val. |
| 556 | idx = mid + 1; |
| 557 | if (validIndex(idx) && arry[idx] > val) { |
| 558 | return mid; |
| 559 | } |
| 560 | } |
| 561 | return Dygraph.binarySearch(val, arry, abs, mid + 1, high); |
| 562 | } |
| 563 | return -1; // can't actually happen, but makes closure compiler happy |
| 564 | }; |
| 565 | |
| 566 | /** |
| 567 | * Parses a date, returning the number of milliseconds since epoch. This can be |
| 568 | * passed in as an xValueParser in the Dygraph constructor. |
| 569 | * TODO(danvk): enumerate formats that this understands. |
| 570 | * |
| 571 | * @param {string} dateStr A date in a variety of possible string formats. |
| 572 | * @return {number} Milliseconds since epoch. |
| 573 | * @private |
| 574 | */ |
| 575 | Dygraph.dateParser = function(dateStr) { |
| 576 | var dateStrSlashed; |
| 577 | var d; |
| 578 | |
| 579 | // Let the system try the format first, with one caveat: |
| 580 | // YYYY-MM-DD[ HH:MM:SS] is interpreted as UTC by a variety of browsers. |
| 581 | // dygraphs displays dates in local time, so this will result in surprising |
| 582 | // inconsistencies. But if you specify "T" or "Z" (i.e. YYYY-MM-DDTHH:MM:SS), |
| 583 | // then you probably know what you're doing, so we'll let you go ahead. |
| 584 | // Issue: http://code.google.com/p/dygraphs/issues/detail?id=255 |
| 585 | if (dateStr.search("-") == -1 || |
| 586 | dateStr.search("T") != -1 || dateStr.search("Z") != -1) { |
| 587 | d = Dygraph.dateStrToMillis(dateStr); |
| 588 | if (d && !isNaN(d)) return d; |
| 589 | } |
| 590 | |
| 591 | if (dateStr.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12' |
| 592 | dateStrSlashed = dateStr.replace("-", "/", "g"); |
| 593 | while (dateStrSlashed.search("-") != -1) { |
| 594 | dateStrSlashed = dateStrSlashed.replace("-", "/"); |
| 595 | } |
| 596 | d = Dygraph.dateStrToMillis(dateStrSlashed); |
| 597 | } else if (dateStr.length == 8) { // e.g. '20090712' |
| 598 | // TODO(danvk): remove support for this format. It's confusing. |
| 599 | dateStrSlashed = dateStr.substr(0,4) + "/" + dateStr.substr(4,2) + "/" + |
| 600 | dateStr.substr(6,2); |
| 601 | d = Dygraph.dateStrToMillis(dateStrSlashed); |
| 602 | } else { |
| 603 | // Any format that Date.parse will accept, e.g. "2009/07/12" or |
| 604 | // "2009/07/12 12:34:56" |
| 605 | d = Dygraph.dateStrToMillis(dateStr); |
| 606 | } |
| 607 | |
| 608 | if (!d || isNaN(d)) { |
| 609 | Dygraph.error("Couldn't parse " + dateStr + " as a date"); |
| 610 | } |
| 611 | return d; |
| 612 | }; |
| 613 | |
| 614 | /** |
| 615 | * This is identical to JavaScript's built-in Date.parse() method, except that |
| 616 | * it doesn't get replaced with an incompatible method by aggressive JS |
| 617 | * libraries like MooTools or Joomla. |
| 618 | * @param {string} str The date string, e.g. "2011/05/06" |
| 619 | * @return {number} millis since epoch |
| 620 | * @private |
| 621 | */ |
| 622 | Dygraph.dateStrToMillis = function(str) { |
| 623 | return new Date(str).getTime(); |
| 624 | }; |
| 625 | |
| 626 | // These functions are all based on MochiKit. |
| 627 | /** |
| 628 | * Copies all the properties from o to self. |
| 629 | * |
| 630 | * @param {!Object} self |
| 631 | * @param {!Object} o |
| 632 | * @return {!Object} |
| 633 | */ |
| 634 | Dygraph.update = function(self, o) { |
| 635 | if (typeof(o) != 'undefined' && o !== null) { |
| 636 | for (var k in o) { |
| 637 | if (o.hasOwnProperty(k)) { |
| 638 | self[k] = o[k]; |
| 639 | } |
| 640 | } |
| 641 | } |
| 642 | return self; |
| 643 | }; |
| 644 | |
| 645 | /** |
| 646 | * Copies all the properties from o to self. |
| 647 | * |
| 648 | * @param {!Object} self |
| 649 | * @param {!Object} o |
| 650 | * @return {!Object} |
| 651 | * @private |
| 652 | */ |
| 653 | Dygraph.updateDeep = function (self, o) { |
| 654 | // Taken from http://stackoverflow.com/questions/384286/javascript-isdom-how-do-you-check-if-a-javascript-object-is-a-dom-object |
| 655 | function isNode(o) { |
| 656 | return ( |
| 657 | typeof Node === "object" ? o instanceof Node : |
| 658 | typeof o === "object" && typeof o.nodeType === "number" && typeof o.nodeName==="string" |
| 659 | ); |
| 660 | } |
| 661 | |
| 662 | if (typeof(o) != 'undefined' && o !== null) { |
| 663 | for (var k in o) { |
| 664 | if (o.hasOwnProperty(k)) { |
| 665 | if (o[k] === null) { |
| 666 | self[k] = null; |
| 667 | } else if (Dygraph.isArrayLike(o[k])) { |
| 668 | self[k] = o[k].slice(); |
| 669 | } else if (isNode(o[k])) { |
| 670 | // DOM objects are shallowly-copied. |
| 671 | self[k] = o[k]; |
| 672 | } else if (typeof(o[k]) == 'object') { |
| 673 | if (typeof(self[k]) != 'object' || self[k] === null) { |
| 674 | self[k] = {}; |
| 675 | } |
| 676 | Dygraph.updateDeep(self[k], o[k]); |
| 677 | } else { |
| 678 | self[k] = o[k]; |
| 679 | } |
| 680 | } |
| 681 | } |
| 682 | } |
| 683 | return self; |
| 684 | }; |
| 685 | |
| 686 | /** |
| 687 | * @param {Object} o |
| 688 | * @return {boolean} |
| 689 | * @private |
| 690 | */ |
| 691 | Dygraph.isArrayLike = function(o) { |
| 692 | var typ = typeof(o); |
| 693 | if ( |
| 694 | (typ != 'object' && !(typ == 'function' && |
| 695 | typeof(o.item) == 'function')) || |
| 696 | o === null || |
| 697 | typeof(o.length) != 'number' || |
| 698 | o.nodeType === 3 |
| 699 | ) { |
| 700 | return false; |
| 701 | } |
| 702 | return true; |
| 703 | }; |
| 704 | |
| 705 | /** |
| 706 | * @param {Object} o |
| 707 | * @return {boolean} |
| 708 | * @private |
| 709 | */ |
| 710 | Dygraph.isDateLike = function (o) { |
| 711 | if (typeof(o) != "object" || o === null || |
| 712 | typeof(o.getTime) != 'function') { |
| 713 | return false; |
| 714 | } |
| 715 | return true; |
| 716 | }; |
| 717 | |
| 718 | /** |
| 719 | * Note: this only seems to work for arrays. |
| 720 | * @param {!Array} o |
| 721 | * @return {!Array} |
| 722 | * @private |
| 723 | */ |
| 724 | Dygraph.clone = function(o) { |
| 725 | // TODO(danvk): figure out how MochiKit's version works |
| 726 | var r = []; |
| 727 | for (var i = 0; i < o.length; i++) { |
| 728 | if (Dygraph.isArrayLike(o[i])) { |
| 729 | r.push(Dygraph.clone(o[i])); |
| 730 | } else { |
| 731 | r.push(o[i]); |
| 732 | } |
| 733 | } |
| 734 | return r; |
| 735 | }; |
| 736 | |
| 737 | /** |
| 738 | * Create a new canvas element. This is more complex than a simple |
| 739 | * document.createElement("canvas") because of IE and excanvas. |
| 740 | * |
| 741 | * @return {!HTMLCanvasElement} |
| 742 | * @private |
| 743 | */ |
| 744 | Dygraph.createCanvas = function() { |
| 745 | var canvas = document.createElement("canvas"); |
| 746 | |
| 747 | var isIE = (/MSIE/.test(navigator.userAgent) && !window.opera); |
| 748 | if (isIE && (typeof(G_vmlCanvasManager) != 'undefined')) { |
| 749 | canvas = G_vmlCanvasManager.initElement( |
| 750 | /**@type{!HTMLCanvasElement}*/(canvas)); |
| 751 | } |
| 752 | |
| 753 | return canvas; |
| 754 | }; |
| 755 | |
| 756 | /** |
| 757 | * Checks whether the user is on an Android browser. |
| 758 | * Android does not fully support the <canvas> tag, e.g. w/r/t/ clipping. |
| 759 | * @return {boolean} |
| 760 | * @private |
| 761 | */ |
| 762 | Dygraph.isAndroid = function() { |
| 763 | return (/Android/).test(navigator.userAgent); |
| 764 | }; |
| 765 | |
| 766 | |
| 767 | /** |
| 768 | * TODO(danvk): use @template here when it's better supported for classes. |
| 769 | * @param {!Array} array |
| 770 | * @param {number} start |
| 771 | * @param {number} length |
| 772 | * @param {function(!Array,?):boolean=} predicate |
| 773 | * @constructor |
| 774 | */ |
| 775 | Dygraph.Iterator = function(array, start, length, predicate) { |
| 776 | start = start || 0; |
| 777 | length = length || array.length; |
| 778 | this.hasNext = true; // Use to identify if there's another element. |
| 779 | this.peek = null; // Use for look-ahead |
| 780 | this.start_ = start; |
| 781 | this.array_ = array; |
| 782 | this.predicate_ = predicate; |
| 783 | this.end_ = Math.min(array.length, start + length); |
| 784 | this.nextIdx_ = start - 1; // use -1 so initial advance works. |
| 785 | this.next(); // ignoring result. |
| 786 | }; |
| 787 | |
| 788 | /** |
| 789 | * @return {Object} |
| 790 | */ |
| 791 | Dygraph.Iterator.prototype.next = function() { |
| 792 | if (!this.hasNext) { |
| 793 | return null; |
| 794 | } |
| 795 | var obj = this.peek; |
| 796 | |
| 797 | var nextIdx = this.nextIdx_ + 1; |
| 798 | var found = false; |
| 799 | while (nextIdx < this.end_) { |
| 800 | if (!this.predicate_ || this.predicate_(this.array_, nextIdx)) { |
| 801 | this.peek = this.array_[nextIdx]; |
| 802 | found = true; |
| 803 | break; |
| 804 | } |
| 805 | nextIdx++; |
| 806 | } |
| 807 | this.nextIdx_ = nextIdx; |
| 808 | if (!found) { |
| 809 | this.hasNext = false; |
| 810 | this.peek = null; |
| 811 | } |
| 812 | return obj; |
| 813 | }; |
| 814 | |
| 815 | /** |
| 816 | * Returns a new iterator over array, between indexes start and |
| 817 | * start + length, and only returns entries that pass the accept function |
| 818 | * |
| 819 | * @param {!Array} array the array to iterate over. |
| 820 | * @param {number} start the first index to iterate over, 0 if absent. |
| 821 | * @param {number} length the number of elements in the array to iterate over. |
| 822 | * This, along with start, defines a slice of the array, and so length |
| 823 | * doesn't imply the number of elements in the iterator when accept doesn't |
| 824 | * always accept all values. array.length when absent. |
| 825 | * @param {function(?):boolean=} opt_predicate a function that takes |
| 826 | * parameters array and idx, which returns true when the element should be |
| 827 | * returned. If omitted, all elements are accepted. |
| 828 | * @private |
| 829 | */ |
| 830 | Dygraph.createIterator = function(array, start, length, opt_predicate) { |
| 831 | return new Dygraph.Iterator(array, start, length, opt_predicate); |
| 832 | }; |
| 833 | |
| 834 | // Shim layer with setTimeout fallback. |
| 835 | // From: http://paulirish.com/2011/requestanimationframe-for-smart-animating/ |
| 836 | // Should be called with the window context: |
| 837 | // Dygraph.requestAnimFrame.call(window, function() {}) |
| 838 | Dygraph.requestAnimFrame = (function() { |
| 839 | return window.requestAnimationFrame || |
| 840 | window.webkitRequestAnimationFrame || |
| 841 | window.mozRequestAnimationFrame || |
| 842 | window.oRequestAnimationFrame || |
| 843 | window.msRequestAnimationFrame || |
| 844 | function (callback) { |
| 845 | window.setTimeout(callback, 1000 / 60); |
| 846 | }; |
| 847 | })(); |
| 848 | |
| 849 | /** |
| 850 | * Call a function at most maxFrames times at an attempted interval of |
| 851 | * framePeriodInMillis, then call a cleanup function once. repeatFn is called |
| 852 | * once immediately, then at most (maxFrames - 1) times asynchronously. If |
| 853 | * maxFrames==1, then cleanup_fn() is also called synchronously. This function |
| 854 | * is used to sequence animation. |
| 855 | * @param {function(number)} repeatFn Called repeatedly -- takes the frame |
| 856 | * number (from 0 to maxFrames-1) as an argument. |
| 857 | * @param {number} maxFrames The max number of times to call repeatFn |
| 858 | * @param {number} framePeriodInMillis Max requested time between frames. |
| 859 | * @param {function()} cleanupFn A function to call after all repeatFn calls. |
| 860 | * @private |
| 861 | */ |
| 862 | Dygraph.repeatAndCleanup = function(repeatFn, maxFrames, framePeriodInMillis, |
| 863 | cleanupFn) { |
| 864 | var frameNumber = 0; |
| 865 | var previousFrameNumber; |
| 866 | var startTime = new Date().getTime(); |
| 867 | repeatFn(frameNumber); |
| 868 | if (maxFrames == 1) { |
| 869 | cleanupFn(); |
| 870 | return; |
| 871 | } |
| 872 | var maxFrameArg = maxFrames - 1; |
| 873 | |
| 874 | (function loop() { |
| 875 | if (frameNumber >= maxFrames) return; |
| 876 | Dygraph.requestAnimFrame.call(window, function() { |
| 877 | // Determine which frame to draw based on the delay so far. Will skip |
| 878 | // frames if necessary. |
| 879 | var currentTime = new Date().getTime(); |
| 880 | var delayInMillis = currentTime - startTime; |
| 881 | previousFrameNumber = frameNumber; |
| 882 | frameNumber = Math.floor(delayInMillis / framePeriodInMillis); |
| 883 | var frameDelta = frameNumber - previousFrameNumber; |
| 884 | // If we predict that the subsequent repeatFn call will overshoot our |
| 885 | // total frame target, so our last call will cause a stutter, then jump to |
| 886 | // the last call immediately. If we're going to cause a stutter, better |
| 887 | // to do it faster than slower. |
| 888 | var predictOvershootStutter = (frameNumber + frameDelta) > maxFrameArg; |
| 889 | if (predictOvershootStutter || (frameNumber >= maxFrameArg)) { |
| 890 | repeatFn(maxFrameArg); // Ensure final call with maxFrameArg. |
| 891 | cleanupFn(); |
| 892 | } else { |
| 893 | if (frameDelta !== 0) { // Don't call repeatFn with duplicate frames. |
| 894 | repeatFn(frameNumber); |
| 895 | } |
| 896 | loop(); |
| 897 | } |
| 898 | }); |
| 899 | })(); |
| 900 | }; |
| 901 | |
| 902 | /** |
| 903 | * This function will scan the option list and determine if they |
| 904 | * require us to recalculate the pixel positions of each point. |
| 905 | * @param {!Array.<string>} labels a list of options to check. |
| 906 | * @param {!Object} attrs |
| 907 | * @return {boolean} true if the graph needs new points else false. |
| 908 | * @private |
| 909 | */ |
| 910 | Dygraph.isPixelChangingOptionList = function(labels, attrs) { |
| 911 | // A whitelist of options that do not change pixel positions. |
| 912 | var pixelSafeOptions = { |
| 913 | 'annotationClickHandler': true, |
| 914 | 'annotationDblClickHandler': true, |
| 915 | 'annotationMouseOutHandler': true, |
| 916 | 'annotationMouseOverHandler': true, |
| 917 | 'axisLabelColor': true, |
| 918 | 'axisLineColor': true, |
| 919 | 'axisLineWidth': true, |
| 920 | 'clickCallback': true, |
| 921 | 'digitsAfterDecimal': true, |
| 922 | 'drawCallback': true, |
| 923 | 'drawHighlightPointCallback': true, |
| 924 | 'drawPoints': true, |
| 925 | 'drawPointCallback': true, |
| 926 | 'drawXGrid': true, |
| 927 | 'drawYGrid': true, |
| 928 | 'fillAlpha': true, |
| 929 | 'gridLineColor': true, |
| 930 | 'gridLineWidth': true, |
| 931 | 'hideOverlayOnMouseOut': true, |
| 932 | 'highlightCallback': true, |
| 933 | 'highlightCircleSize': true, |
| 934 | 'interactionModel': true, |
| 935 | 'isZoomedIgnoreProgrammaticZoom': true, |
| 936 | 'labelsDiv': true, |
| 937 | 'labelsDivStyles': true, |
| 938 | 'labelsDivWidth': true, |
| 939 | 'labelsKMB': true, |
| 940 | 'labelsKMG2': true, |
| 941 | 'labelsSeparateLines': true, |
| 942 | 'labelsShowZeroValues': true, |
| 943 | 'legend': true, |
| 944 | 'maxNumberWidth': true, |
| 945 | 'panEdgeFraction': true, |
| 946 | 'pixelsPerYLabel': true, |
| 947 | 'pointClickCallback': true, |
| 948 | 'pointSize': true, |
| 949 | 'rangeSelectorPlotFillColor': true, |
| 950 | 'rangeSelectorPlotStrokeColor': true, |
| 951 | 'showLabelsOnHighlight': true, |
| 952 | 'showRoller': true, |
| 953 | 'sigFigs': true, |
| 954 | 'strokeWidth': true, |
| 955 | 'underlayCallback': true, |
| 956 | 'unhighlightCallback': true, |
| 957 | 'xAxisLabelFormatter': true, |
| 958 | 'xTicker': true, |
| 959 | 'xValueFormatter': true, |
| 960 | 'yAxisLabelFormatter': true, |
| 961 | 'yValueFormatter': true, |
| 962 | 'zoomCallback': true |
| 963 | }; |
| 964 | |
| 965 | // Assume that we do not require new points. |
| 966 | // This will change to true if we actually do need new points. |
| 967 | var requiresNewPoints = false; |
| 968 | |
| 969 | // Create a dictionary of series names for faster lookup. |
| 970 | // If there are no labels, then the dictionary stays empty. |
| 971 | var seriesNamesDictionary = { }; |
| 972 | if (labels) { |
| 973 | for (var i = 1; i < labels.length; i++) { |
| 974 | seriesNamesDictionary[labels[i]] = true; |
| 975 | } |
| 976 | } |
| 977 | |
| 978 | // Iterate through the list of updated options. |
| 979 | for (var property in attrs) { |
| 980 | // Break early if we already know we need new points from a previous option. |
| 981 | if (requiresNewPoints) { |
| 982 | break; |
| 983 | } |
| 984 | if (attrs.hasOwnProperty(property)) { |
| 985 | // Find out of this field is actually a series specific options list. |
| 986 | if (seriesNamesDictionary[property]) { |
| 987 | // This property value is a list of options for this series. |
| 988 | // If any of these sub properties are not pixel safe, set the flag. |
| 989 | for (var subProperty in attrs[property]) { |
| 990 | // Break early if we already know we need new points from a previous option. |
| 991 | if (requiresNewPoints) { |
| 992 | break; |
| 993 | } |
| 994 | if (attrs[property].hasOwnProperty(subProperty) && !pixelSafeOptions[subProperty]) { |
| 995 | requiresNewPoints = true; |
| 996 | } |
| 997 | } |
| 998 | // If this was not a series specific option list, check if its a pixel changing property. |
| 999 | } else if (!pixelSafeOptions[property]) { |
| 1000 | requiresNewPoints = true; |
| 1001 | } |
| 1002 | } |
| 1003 | } |
| 1004 | |
| 1005 | return requiresNewPoints; |
| 1006 | }; |
| 1007 | |
| 1008 | Dygraph.Circles = { |
| 1009 | DEFAULT : function(g, name, ctx, canvasx, canvasy, color, radius) { |
| 1010 | ctx.beginPath(); |
| 1011 | ctx.fillStyle = color; |
| 1012 | ctx.arc(canvasx, canvasy, radius, 0, 2 * Math.PI, false); |
| 1013 | ctx.fill(); |
| 1014 | } |
| 1015 | // For more shapes, include extras/stars.js |
| 1016 | }; |
| 1017 | |
| 1018 | /** |
| 1019 | * To create a "drag" interaction, you typically register a mousedown event |
| 1020 | * handler on the element where the drag begins. In that handler, you register a |
| 1021 | * mouseup handler on the window to determine when the mouse is released, |
| 1022 | * wherever that release happens. This works well, except when the user releases |
| 1023 | * the mouse over an off-domain iframe. In that case, the mouseup event is |
| 1024 | * handled by the iframe and never bubbles up to the window handler. |
| 1025 | * |
| 1026 | * To deal with this issue, we cover iframes with high z-index divs to make sure |
| 1027 | * they don't capture mouseup. |
| 1028 | * |
| 1029 | * Usage: |
| 1030 | * element.addEventListener('mousedown', function() { |
| 1031 | * var tarper = new Dygraph.IFrameTarp(); |
| 1032 | * tarper.cover(); |
| 1033 | * var mouseUpHandler = function() { |
| 1034 | * ... |
| 1035 | * window.removeEventListener(mouseUpHandler); |
| 1036 | * tarper.uncover(); |
| 1037 | * }; |
| 1038 | * window.addEventListener('mouseup', mouseUpHandler); |
| 1039 | * }; |
| 1040 | * |
| 1041 | * @constructor |
| 1042 | */ |
| 1043 | Dygraph.IFrameTarp = function() { |
| 1044 | /** @type {Array.<!HTMLDivElement>} */ |
| 1045 | this.tarps = []; |
| 1046 | }; |
| 1047 | |
| 1048 | /** |
| 1049 | * Find all the iframes in the document and cover them with high z-index |
| 1050 | * transparent divs. |
| 1051 | */ |
| 1052 | Dygraph.IFrameTarp.prototype.cover = function() { |
| 1053 | var iframes = document.getElementsByTagName("iframe"); |
| 1054 | for (var i = 0; i < iframes.length; i++) { |
| 1055 | var iframe = iframes[i]; |
| 1056 | var x = Dygraph.findPosX(iframe), |
| 1057 | y = Dygraph.findPosY(iframe), |
| 1058 | width = iframe.offsetWidth, |
| 1059 | height = iframe.offsetHeight; |
| 1060 | |
| 1061 | var div = document.createElement("div"); |
| 1062 | div.style.position = "absolute"; |
| 1063 | div.style.left = x + 'px'; |
| 1064 | div.style.top = y + 'px'; |
| 1065 | div.style.width = width + 'px'; |
| 1066 | div.style.height = height + 'px'; |
| 1067 | div.style.zIndex = 999; |
| 1068 | document.body.appendChild(div); |
| 1069 | this.tarps.push(div); |
| 1070 | } |
| 1071 | }; |
| 1072 | |
| 1073 | /** |
| 1074 | * Remove all the iframe covers. You should call this in a mouseup handler. |
| 1075 | */ |
| 1076 | Dygraph.IFrameTarp.prototype.uncover = function() { |
| 1077 | for (var i = 0; i < this.tarps.length; i++) { |
| 1078 | this.tarps[i].parentNode.removeChild(this.tarps[i]); |
| 1079 | } |
| 1080 | this.tarps = []; |
| 1081 | }; |
| 1082 | |
| 1083 | /** |
| 1084 | * Determine whether |data| is delimited by CR, CRLF, LF, LFCR. |
| 1085 | * @param {string} data |
| 1086 | * @return {?string} the delimiter that was detected (or null on failure). |
| 1087 | */ |
| 1088 | Dygraph.detectLineDelimiter = function(data) { |
| 1089 | for (var i = 0; i < data.length; i++) { |
| 1090 | var code = data.charAt(i); |
| 1091 | if (code === '\r') { |
| 1092 | // Might actually be "\r\n". |
| 1093 | if (((i + 1) < data.length) && (data.charAt(i + 1) === '\n')) { |
| 1094 | return '\r\n'; |
| 1095 | } |
| 1096 | return code; |
| 1097 | } |
| 1098 | if (code === '\n') { |
| 1099 | // Might actually be "\n\r". |
| 1100 | if (((i + 1) < data.length) && (data.charAt(i + 1) === '\r')) { |
| 1101 | return '\n\r'; |
| 1102 | } |
| 1103 | return code; |
| 1104 | } |
| 1105 | } |
| 1106 | |
| 1107 | return null; |
| 1108 | }; |
| 1109 | |
| 1110 | /** |
| 1111 | * Is one node contained by another? |
| 1112 | * @param {Node} containee The contained node. |
| 1113 | * @param {Node} container The container node. |
| 1114 | * @return {boolean} Whether containee is inside (or equal to) container. |
| 1115 | * @private |
| 1116 | */ |
| 1117 | Dygraph.isNodeContainedBy = function(containee, container) { |
| 1118 | if (container === null || containee === null) { |
| 1119 | return false; |
| 1120 | } |
| 1121 | var containeeNode = /** @type {Node} */ (containee); |
| 1122 | while (containeeNode && containeeNode !== container) { |
| 1123 | containeeNode = containeeNode.parentNode; |
| 1124 | } |
| 1125 | return (containeeNode === container); |
| 1126 | }; |
| 1127 | |
| 1128 | |
| 1129 | // This masks some numeric issues in older versions of Firefox, |
| 1130 | // where 1.0/Math.pow(10,2) != Math.pow(10,-2). |
| 1131 | /** @type {function(number,number):number} */ |
| 1132 | Dygraph.pow = function(base, exp) { |
| 1133 | if (exp < 0) { |
| 1134 | return 1.0 / Math.pow(base, -exp); |
| 1135 | } |
| 1136 | return Math.pow(base, exp); |
| 1137 | }; |
| 1138 | |
| 1139 | // For Dygraph.setDateSameTZ, below. |
| 1140 | Dygraph.dateSetters = { |
| 1141 | ms: Date.prototype.setMilliseconds, |
| 1142 | s: Date.prototype.setSeconds, |
| 1143 | m: Date.prototype.setMinutes, |
| 1144 | h: Date.prototype.setHours |
| 1145 | }; |
| 1146 | |
| 1147 | /** |
| 1148 | * This is like calling d.setSeconds(), d.setMinutes(), etc, except that it |
| 1149 | * adjusts for time zone changes to keep the date/time parts consistent. |
| 1150 | * |
| 1151 | * For example, d.getSeconds(), d.getMinutes() and d.getHours() will all be |
| 1152 | * the same before/after you call setDateSameTZ(d, {ms: 0}). The same is not |
| 1153 | * true if you call d.setMilliseconds(0). |
| 1154 | * |
| 1155 | * @type {function(!Date, Object.<number>)} |
| 1156 | */ |
| 1157 | Dygraph.setDateSameTZ = function(d, parts) { |
| 1158 | var tz = d.getTimezoneOffset(); |
| 1159 | for (var k in parts) { |
| 1160 | if (!parts.hasOwnProperty(k)) continue; |
| 1161 | var setter = Dygraph.dateSetters[k]; |
| 1162 | if (!setter) throw "Invalid setter: " + k; |
| 1163 | setter.call(d, parts[k]); |
| 1164 | if (d.getTimezoneOffset() != tz) { |
| 1165 | d.setTime(d.getTime() + (tz - d.getTimezoneOffset()) * 60 * 1000); |
| 1166 | } |
| 1167 | } |
| 1168 | }; |
| 1169 | |
| 1170 | /** |
| 1171 | * Converts any valid CSS color (hex, rgb(), named color) to an RGB tuple. |
| 1172 | * |
| 1173 | * @param {!string} color_str Any valid CSS color string. |
| 1174 | * @return {{r:number,g:number,b:number}} Parsed RGB tuple. |
| 1175 | * @private |
| 1176 | */ |
| 1177 | Dygraph.toRGB_ = function(color_str) { |
| 1178 | // TODO(danvk): cache color parses to avoid repeated DOM manipulation. |
| 1179 | var div = document.createElement('div'); |
| 1180 | div.style.backgroundColor = color_str; |
| 1181 | div.style.visibility = 'hidden'; |
| 1182 | document.body.appendChild(div); |
| 1183 | var rgb_str = window.getComputedStyle(div).backgroundColor; |
| 1184 | document.body.removeChild(div); |
| 1185 | var bits = /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/.exec(rgb_str); |
| 1186 | return { |
| 1187 | r: parseInt(bits[1], 10), |
| 1188 | g: parseInt(bits[2], 10), |
| 1189 | b: parseInt(bits[3], 10) |
| 1190 | }; |
| 1191 | }; |