Fix comment and revert changes in DST transition test as requested.
[dygraphs.git] / dygraph-utils.js
CommitLineData
88e95c46
DV
1/**
2 * @license
3 * Copyright 2011 Dan Vanderkam (danvdk@gmail.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
5 */
dedb4f5f 6
004b5c90
DV
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 */
dedb4f5f 13
758a629f
DV
14/*jshint globalstrict: true */
15/*global Dygraph:false, G_vmlCanvasManager:false, Node:false, printStackTrace: false */
c0f54d4f
DV
16"use strict";
17
dedb4f5f
DV
18Dygraph.LOG_SCALE = 10;
19Dygraph.LN_TEN = Math.log(Dygraph.LOG_SCALE);
20
f11283de
DV
21/**
22 * @private
23 * @param {number} x
24 * @return {number}
25 */
dedb4f5f
DV
26Dygraph.log10 = function(x) {
27 return Math.log(x) / Dygraph.LN_TEN;
758a629f 28};
dedb4f5f
DV
29
30// Various logging levels.
31Dygraph.DEBUG = 1;
32Dygraph.INFO = 2;
33Dygraph.WARNING = 3;
34Dygraph.ERROR = 3;
35
464b5f50 36// <REMOVE_FOR_COMBINED>
00639fab
DV
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
41Dygraph.LOG_STACK_TRACES = false;
464b5f50 42// </REMOVE_FOR_COMBINED>
00639fab 43
79253bd0 44/** A dotted line stroke pattern. */
45Dygraph.DOTTED_LINE = [2, 2];
46/** A dashed line stroke pattern. */
47Dygraph.DASHED_LINE = [7, 3];
48/** A dot dash stroke pattern. */
49Dygraph.DOT_DASH_LINE = [7, 2, 2, 2];
50
dedb4f5f 51/**
dedb4f5f 52 * Log an error on the JS console at the given severity.
f11283de
DV
53 * @param {number} severity One of Dygraph.{DEBUG,INFO,WARNING,ERROR}
54 * @param {string} message The message to log.
55 * @private
dedb4f5f
DV
56 */
57Dygraph.log = function(severity, message) {
464b5f50 58 // <REMOVE_FOR_COMBINED>
00639fab
DV
59 var st;
60 if (typeof(printStackTrace) != 'undefined') {
df21c270
DV
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 }
0d319fa5 67
df21c270
DV
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!
00639fab 78 }
00639fab 79 }
464b5f50 80 // </REMOVE_FOR_COMBINED>
00639fab 81
f11283de 82 if (typeof(window.console) != 'undefined') {
33e96f11
DV
83 // In older versions of Firefox, only console.log is defined.
84 var console = window.console;
85 var log = function(console, method, msg) {
94ee0648 86 if (method && typeof(method) == 'function') {
33e96f11
DV
87 method.call(console, msg);
88 } else {
89 console.log(msg);
90 }
91 };
92
dedb4f5f
DV
93 switch (severity) {
94 case Dygraph.DEBUG:
33e96f11 95 log(console, console.debug, 'dygraphs: ' + message);
dedb4f5f
DV
96 break;
97 case Dygraph.INFO:
33e96f11 98 log(console, console.info, 'dygraphs: ' + message);
dedb4f5f
DV
99 break;
100 case Dygraph.WARNING:
33e96f11 101 log(console, console.warn, 'dygraphs: ' + message);
dedb4f5f
DV
102 break;
103 case Dygraph.ERROR:
33e96f11 104 log(console, console.error, 'dygraphs: ' + message);
dedb4f5f
DV
105 break;
106 }
107 }
00639fab 108
464b5f50 109 // <REMOVE_FOR_COMBINED>
00639fab 110 if (Dygraph.LOG_STACK_TRACES) {
f11283de 111 window.console.log(st.join('\n'));
00639fab 112 }
464b5f50 113 // </REMOVE_FOR_COMBINED>
dedb4f5f
DV
114};
115
f11283de
DV
116/**
117 * @param {string} message
118 * @private
119 */
dedb4f5f
DV
120Dygraph.info = function(message) {
121 Dygraph.log(Dygraph.INFO, message);
122};
dedb4f5f 123
f11283de
DV
124/**
125 * @param {string} message
126 * @private
127 */
dedb4f5f
DV
128Dygraph.warn = function(message) {
129 Dygraph.log(Dygraph.WARNING, message);
130};
dedb4f5f 131
f11283de
DV
132/**
133 * @param {string} message
f11283de 134 */
dedb4f5f
DV
135Dygraph.error = function(message) {
136 Dygraph.log(Dygraph.ERROR, message);
137};
dedb4f5f
DV
138
139/**
dedb4f5f
DV
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 * };
f11283de
DV
150 * @param {!HTMLCanvasElement} canvas
151 * @return {!CanvasRenderingContext2D}
152 * @private
dedb4f5f
DV
153 */
154Dygraph.getContext = function(canvas) {
f11283de 155 return /** @type{!CanvasRenderingContext2D}*/(canvas.getContext("2d"));
dedb4f5f
DV
156};
157
158/**
dedb4f5f
DV
159 * Add an event handler. This smooths a difference between IE and the rest of
160 * the world.
39b33f9f
DV
161 * @param {!Node} 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
f11283de
DV
164 * on the event. The function takes one parameter: the event object.
165 * @private
dedb4f5f 166 */
1cc3540b 167Dygraph.addEvent = function addEvent(elem, type, fn) {
ccd9d7c2
PF
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 }
1cc3540b
RK
174};
175
176/**
1cc3540b
RK
177 * Add an event handler. This event handler is kept until the graph is
178 * destroyed with a call to graph.destroy().
179 *
39b33f9f
DV
180 * @param {!Node} 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
f11283de
DV
183 * on the event. The function takes one parameter: the event object.
184 * @private
1cc3540b 185 */
aeca29ac 186Dygraph.prototype.addAndTrackEvent = function(elem, type, fn) {
1cc3540b 187 Dygraph.addEvent(elem, type, fn);
6a4587ac 188 this.registeredEvents_.push({ elem : elem, type : type, fn : fn });
ccd9d7c2
PF
189};
190
191/**
f11283de
DV
192 * Remove an event handler. This smooths a difference between IE and the rest
193 * of the world.
39b33f9f 194 * @param {!Node} elem The element to remove the event from.
f11283de
DV
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.
ccd9d7c2 198 * @private
ccd9d7c2 199 */
a537fd67 200Dygraph.removeEvent = function(elem, type, fn) {
ccd9d7c2
PF
201 if (elem.removeEventListener) {
202 elem.removeEventListener(type, fn, false);
203 } else {
e2769469
DV
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 }
ccd9d7c2 210 elem[type+fn] = null;
dedb4f5f
DV
211 }
212};
213
aeca29ac
RK
214Dygraph.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_ = [];
f914bed1 223};
aeca29ac 224
dedb4f5f 225/**
dedb4f5f
DV
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
39b33f9f 230 * @param {!Event} e The event whose normal behavior should be canceled.
f11283de 231 * @private
dedb4f5f
DV
232 */
233Dygraph.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.
f11283de
DV
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.
dedb4f5f
DV
255 * @private
256 */
257Dygraph.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
1bc38cbc 290// ... and modifications to support scrolling divs.
dedb4f5f 291
8442269f 292/**
464b5f50
DV
293 * Find the coordinates of an object relative to the top left of the page.
294 *
f11283de
DV
295 * TODO(danvk): change obj type from Node -&gt; !Node
296 * @param {Node} obj
464b5f50 297 * @return {{x:number,y:number}}
8442269f
RK
298 * @private
299 */
464b5f50
DV
300Dygraph.findPos = function(obj) {
301 var curleft = 0, curtop = 0;
302 if (obj.offsetParent) {
8442269f 303 var copyObj = obj;
464b5f50 304 while (1) {
ecdb6dff 305 // NOTE: the if statement here is for IE8.
464b5f50 306 var borderLeft = "0", borderTop = "0";
4ff8c62e 307 if (window.getComputedStyle) {
464b5f50
DV
308 var computedStyle = window.getComputedStyle(copyObj, null);
309 borderLeft = computedStyle.borderLeft || "0";
310 borderTop = computedStyle.borderTop || "0";
4ff8c62e 311 }
abc8c570 312 curleft += parseInt(borderLeft, 10) ;
abc8c570 313 curtop += parseInt(borderTop, 10) ;
464b5f50 314 curleft += copyObj.offsetLeft;
8442269f 315 curtop += copyObj.offsetTop;
464b5f50 316 if (!copyObj.offsetParent) {
dedb4f5f 317 break;
8442269f
RK
318 }
319 copyObj = copyObj.offsetParent;
dedb4f5f 320 }
464b5f50
DV
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;
8442269f 325 }
464b5f50 326
8442269f 327 // This handles the case where the object is inside a scrolled div.
464b5f50
DV
328 while (obj && obj != document.body) {
329 curleft -= obj.scrollLeft;
8442269f
RK
330 curtop -= obj.scrollTop;
331 obj = obj.parentNode;
332 }
464b5f50 333 return {x: curleft, y: curtop};
dedb4f5f
DV
334};
335
336/**
dedb4f5f
DV
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
f11283de
DV
340 * @param {!Event} e
341 * @return {number}
342 * @private
dedb4f5f
DV
343 */
344Dygraph.pageX = function(e) {
345 if (e.pageX) {
346 return (!e.pageX || e.pageX < 0) ? 0 : e.pageX;
347 } else {
f11283de 348 var de = document.documentElement;
dedb4f5f
DV
349 var b = document.body;
350 return e.clientX +
351 (de.scrollLeft || b.scrollLeft) -
352 (de.clientLeft || 0);
353 }
354};
355
356/**
dedb4f5f
DV
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
f11283de
DV
360 * @param {!Event} e
361 * @return {number}
362 * @private
dedb4f5f
DV
363 */
364Dygraph.pageY = function(e) {
365 if (e.pageY) {
366 return (!e.pageY || e.pageY < 0) ? 0 : e.pageY;
367 } else {
f11283de 368 var de = document.documentElement;
dedb4f5f
DV
369 var b = document.body;
370 return e.clientY +
371 (de.scrollTop || b.scrollTop) -
372 (de.clientTop || 0);
373 }
374};
375
376/**
806f92c1
DV
377 * Converts page the x-coordinate of the event to pixel x-coordinates on the
378 * canvas (i.e. DOM Coords).
379 * @param {!Event} e Drag event.
380 * @param {!DygraphInteractionContext} context Interaction context object.
381 * @return {number} The amount by which the drag has moved to the right.
382 */
383Dygraph.dragGetX_ = function(e, context) {
384 return Dygraph.pageX(e) - context.px;
385};
386
387/**
388 * Converts page the y-coordinate of the event to pixel y-coordinates on the
389 * canvas (i.e. DOM Coords).
390 * @param {!Event} e Drag event.
391 * @param {!DygraphInteractionContext} context Interaction context object.
392 * @return {number} The amount by which the drag has moved down.
393 */
394Dygraph.dragGetY_ = function(e, context) {
395 return Dygraph.pageY(e) - context.py;
396};
397
398/**
f11283de
DV
399 * This returns true unless the parameter is 0, null, undefined or NaN.
400 * TODO(danvk): rename this function to something like 'isNonZeroNan'.
401 *
402 * @param {number} x The number to consider.
403 * @return {boolean} Whether the number is zero or NaN.
dedb4f5f 404 * @private
dedb4f5f 405 */
dedb4f5f 406Dygraph.isOK = function(x) {
f11283de 407 return !!x && !isNaN(x);
dedb4f5f
DV
408};
409
410/**
55deb02f 411 * @param {{x:?number,y:?number,yval:?number}} p The point to consider, valid
f11283de 412 * points are {x, y} objects
55deb02f
DV
413 * @param {boolean=} opt_allowNaNY Treat point with y=NaN as valid
414 * @return {boolean} Whether the point has numeric x and y.
62c3d2fd 415 * @private
62c3d2fd 416 */
55deb02f 417Dygraph.isValidPoint = function(p, opt_allowNaNY) {
f11283de
DV
418 if (!p) return false; // null or undefined object
419 if (p.yval === null) return false; // missing point
04c104d7
KW
420 if (p.x === null || p.x === undefined) return false;
421 if (p.y === null || p.y === undefined) return false;
55deb02f 422 if (isNaN(p.x) || (!opt_allowNaNY && isNaN(p.y))) return false;
62c3d2fd
KW
423 return true;
424};
425
426/**
dedb4f5f
DV
427 * Number formatting function which mimicks the behavior of %g in printf, i.e.
428 * either exponential or fixed format (without trailing 0s) is used depending on
429 * the length of the generated string. The advantage of this format is that
430 * there is a predictable upper bound on the resulting string length,
431 * significant figures are not dropped, and normal numbers are not displayed in
432 * exponential notation.
433 *
434 * NOTE: JavaScript's native toPrecision() is NOT a drop-in replacement for %g.
435 * It creates strings which are too long for absolute values between 10^-4 and
436 * 10^-6, e.g. '0.00001' instead of '1e-5'. See tests/number-format.html for
437 * output examples.
438 *
f11283de
DV
439 * @param {number} x The number to format
440 * @param {number=} opt_precision The precision to use, default 2.
441 * @return {string} A string formatted like %g in printf. The max generated
dedb4f5f
DV
442 * string length should be precision + 6 (e.g 1.123e+300).
443 */
444Dygraph.floatFormat = function(x, opt_precision) {
445 // Avoid invalid precision values; [1, 21] is the valid range.
446 var p = Math.min(Math.max(1, opt_precision || 2), 21);
447
448 // This is deceptively simple. The actual algorithm comes from:
449 //
450 // Max allowed length = p + 4
451 // where 4 comes from 'e+n' and '.'.
452 //
453 // Length of fixed format = 2 + y + p
454 // where 2 comes from '0.' and y = # of leading zeroes.
455 //
456 // Equating the two and solving for y yields y = 2, or 0.00xxxx which is
457 // 1.0e-3.
458 //
459 // Since the behavior of toPrecision() is identical for larger numbers, we
460 // don't have to worry about the other bound.
461 //
462 // Finally, the argument for toExponential() is the number of trailing digits,
463 // so we take off 1 for the value before the '.'.
758a629f 464 return (Math.abs(x) < 1.0e-3 && x !== 0.0) ?
dedb4f5f
DV
465 x.toExponential(p - 1) : x.toPrecision(p);
466};
467
468/**
dedb4f5f 469 * Converts '9' to '09' (useful for dates)
f11283de
DV
470 * @param {number} x
471 * @return {string}
472 * @private
dedb4f5f
DV
473 */
474Dygraph.zeropad = function(x) {
475 if (x < 10) return "0" + x; else return "" + x;
476};
477
478/**
479 * Return a string version of the hours, minutes and seconds portion of a date.
872a6a00
DV
480 * @param {number} hh The hours (from 0-23)
481 * @param {number} mm The minutes (from 0-59)
482 * @param {number} ss The seconds (from 0-59)
483 * @return {string} A time of the form "HH:MM" or "HH:MM:SS"
dedb4f5f
DV
484 * @private
485 */
872a6a00 486Dygraph.hmsString_ = function(hh, mm, ss) {
dedb4f5f 487 var zeropad = Dygraph.zeropad;
872a6a00
DV
488 var ret = zeropad(hh) + ":" + zeropad(mm);
489 if (ss) {
490 ret += ":" + zeropad(ss);
dedb4f5f 491 }
872a6a00 492 return ret;
dedb4f5f
DV
493};
494
495/**
872a6a00 496 * Convert a JS date (millis since epoch) to a formatted string.
464b5f50 497 * @param {number} date The JavaScript date (ms since epoch)
872a6a00
DV
498 * @param {boolean} utc Wether output UTC or local time
499 * @return {string} A date of one of these forms:
500 * "YYYY/MM/DD", "YYYY/MM/DD HH:MM" or "YYYY/MM/DD HH:MM:SS"
464b5f50
DV
501 * @private
502 */
872a6a00 503Dygraph.dateString_ = function(date, utc) {
464b5f50 504 var zeropad = Dygraph.zeropad;
872a6a00
DV
505 var dt = new Date(date);
506 var y, m, d, hh, mm, ss;
507 if (utc) {
508 y = dt.getUTCFullYear();
509 m = dt.getUTCMonth();
510 d = dt.getUTCDate();
511 hh = dt.getUTCHours();
512 mm = dt.getUTCMinutes();
513 ss = dt.getUTCSeconds();
514 } else {
515 y = dt.getFullYear();
516 m = dt.getMonth();
517 d = dt.getDate();
518 hh = dt.getHours();
519 mm = dt.getMinutes();
520 ss = dt.getSeconds();
521 }
522 // Get a year string:
523 var year = "" + y;
464b5f50 524 // Get a 0 padded month string
872a6a00 525 var month = zeropad(m + 1); //months are 0-offset, sigh
464b5f50 526 // Get a 0 padded day string
872a6a00
DV
527 var day = zeropad(d);
528 var frac = hh * 3600 + mm * 60 + ss;
529 var ret = year + "/" + month + "/" + day;
530 if (frac) {
531 ret += " " + Dygraph.hmsString_(hh,mm,ss);
532 }
533 return ret;
464b5f50
DV
534};
535
536/**
dedb4f5f 537 * Round a number to the specified number of digits past the decimal point.
f11283de
DV
538 * @param {number} num The number to round
539 * @param {number} places The number of decimals to which to round
540 * @return {number} The rounded number
dedb4f5f
DV
541 * @private
542 */
543Dygraph.round_ = function(num, places) {
544 var shift = Math.pow(10, places);
545 return Math.round(num * shift)/shift;
546};
547
548/**
dedb4f5f
DV
549 * Implementation of binary search over an array.
550 * Currently does not work when val is outside the range of arry's values.
f11283de
DV
551 * @param {number} val the value to search for
552 * @param {Array.<number>} arry is the value over which to search
553 * @param {number} abs If abs > 0, find the lowest entry greater than val
554 * If abs < 0, find the highest entry less than val.
555 * If abs == 0, find the entry that equals val.
556 * @param {number=} low The first index in arry to consider (optional)
557 * @param {number=} high The last index in arry to consider (optional)
558 * @return {number} Index of the element, or -1 if it isn't found.
559 * @private
dedb4f5f
DV
560 */
561Dygraph.binarySearch = function(val, arry, abs, low, high) {
758a629f
DV
562 if (low === null || low === undefined ||
563 high === null || high === undefined) {
dedb4f5f
DV
564 low = 0;
565 high = arry.length - 1;
566 }
567 if (low > high) {
568 return -1;
569 }
758a629f 570 if (abs === null || abs === undefined) {
dedb4f5f
DV
571 abs = 0;
572 }
573 var validIndex = function(idx) {
574 return idx >= 0 && idx < arry.length;
758a629f
DV
575 };
576 var mid = parseInt((low + high) / 2, 10);
dedb4f5f 577 var element = arry[mid];
f11283de 578 var idx;
dedb4f5f
DV
579 if (element == val) {
580 return mid;
f11283de 581 } else if (element > val) {
dedb4f5f
DV
582 if (abs > 0) {
583 // Accept if element > val, but also if prior element < val.
758a629f 584 idx = mid - 1;
dedb4f5f
DV
585 if (validIndex(idx) && arry[idx] < val) {
586 return mid;
587 }
588 }
589 return Dygraph.binarySearch(val, arry, abs, low, mid - 1);
f11283de 590 } else if (element < val) {
dedb4f5f
DV
591 if (abs < 0) {
592 // Accept if element < val, but also if prior element > val.
758a629f 593 idx = mid + 1;
dedb4f5f
DV
594 if (validIndex(idx) && arry[idx] > val) {
595 return mid;
596 }
597 }
598 return Dygraph.binarySearch(val, arry, abs, mid + 1, high);
599 }
f11283de 600 return -1; // can't actually happen, but makes closure compiler happy
dedb4f5f
DV
601};
602
603/**
dedb4f5f
DV
604 * Parses a date, returning the number of milliseconds since epoch. This can be
605 * passed in as an xValueParser in the Dygraph constructor.
606 * TODO(danvk): enumerate formats that this understands.
f11283de
DV
607 *
608 * @param {string} dateStr A date in a variety of possible string formats.
609 * @return {number} Milliseconds since epoch.
610 * @private
dedb4f5f
DV
611 */
612Dygraph.dateParser = function(dateStr) {
613 var dateStrSlashed;
614 var d;
769e8bc7 615
3f675fe5
DV
616 // Let the system try the format first, with one caveat:
617 // YYYY-MM-DD[ HH:MM:SS] is interpreted as UTC by a variety of browsers.
618 // dygraphs displays dates in local time, so this will result in surprising
619 // inconsistencies. But if you specify "T" or "Z" (i.e. YYYY-MM-DDTHH:MM:SS),
620 // then you probably know what you're doing, so we'll let you go ahead.
621 // Issue: http://code.google.com/p/dygraphs/issues/detail?id=255
622 if (dateStr.search("-") == -1 ||
623 dateStr.search("T") != -1 || dateStr.search("Z") != -1) {
624 d = Dygraph.dateStrToMillis(dateStr);
625 if (d && !isNaN(d)) return d;
626 }
769e8bc7 627
dedb4f5f
DV
628 if (dateStr.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12'
629 dateStrSlashed = dateStr.replace("-", "/", "g");
630 while (dateStrSlashed.search("-") != -1) {
631 dateStrSlashed = dateStrSlashed.replace("-", "/");
632 }
633 d = Dygraph.dateStrToMillis(dateStrSlashed);
634 } else if (dateStr.length == 8) { // e.g. '20090712'
635 // TODO(danvk): remove support for this format. It's confusing.
758a629f
DV
636 dateStrSlashed = dateStr.substr(0,4) + "/" + dateStr.substr(4,2) + "/" +
637 dateStr.substr(6,2);
dedb4f5f
DV
638 d = Dygraph.dateStrToMillis(dateStrSlashed);
639 } else {
640 // Any format that Date.parse will accept, e.g. "2009/07/12" or
641 // "2009/07/12 12:34:56"
642 d = Dygraph.dateStrToMillis(dateStr);
643 }
644
645 if (!d || isNaN(d)) {
646 Dygraph.error("Couldn't parse " + dateStr + " as a date");
647 }
648 return d;
649};
650
651/**
dedb4f5f
DV
652 * This is identical to JavaScript's built-in Date.parse() method, except that
653 * it doesn't get replaced with an incompatible method by aggressive JS
654 * libraries like MooTools or Joomla.
f11283de
DV
655 * @param {string} str The date string, e.g. "2011/05/06"
656 * @return {number} millis since epoch
657 * @private
dedb4f5f
DV
658 */
659Dygraph.dateStrToMillis = function(str) {
660 return new Date(str).getTime();
661};
662
663// These functions are all based on MochiKit.
664/**
665 * Copies all the properties from o to self.
666 *
f11283de
DV
667 * @param {!Object} self
668 * @param {!Object} o
669 * @return {!Object}
dedb4f5f 670 */
f11283de 671Dygraph.update = function(self, o) {
dedb4f5f
DV
672 if (typeof(o) != 'undefined' && o !== null) {
673 for (var k in o) {
674 if (o.hasOwnProperty(k)) {
675 self[k] = o[k];
676 }
677 }
678 }
679 return self;
680};
681
682/**
48e614ac
DV
683 * Copies all the properties from o to self.
684 *
f11283de
DV
685 * @param {!Object} self
686 * @param {!Object} o
687 * @return {!Object}
48e614ac
DV
688 * @private
689 */
690Dygraph.updateDeep = function (self, o) {
920208fb
PF
691 // Taken from http://stackoverflow.com/questions/384286/javascript-isdom-how-do-you-check-if-a-javascript-object-is-a-dom-object
692 function isNode(o) {
693 return (
694 typeof Node === "object" ? o instanceof Node :
695 typeof o === "object" && typeof o.nodeType === "number" && typeof o.nodeName==="string"
696 );
697 }
698
48e614ac
DV
699 if (typeof(o) != 'undefined' && o !== null) {
700 for (var k in o) {
701 if (o.hasOwnProperty(k)) {
758a629f 702 if (o[k] === null) {
48e614ac
DV
703 self[k] = null;
704 } else if (Dygraph.isArrayLike(o[k])) {
705 self[k] = o[k].slice();
920208fb 706 } else if (isNode(o[k])) {
66ad3609
RK
707 // DOM objects are shallowly-copied.
708 self[k] = o[k];
48e614ac 709 } else if (typeof(o[k]) == 'object') {
c1c5dfeb 710 if (typeof(self[k]) != 'object' || self[k] === null) {
48e614ac
DV
711 self[k] = {};
712 }
713 Dygraph.updateDeep(self[k], o[k]);
714 } else {
715 self[k] = o[k];
716 }
717 }
718 }
719 }
720 return self;
721};
722
723/**
55deb02f 724 * @param {*} o
f11283de 725 * @return {boolean}
dedb4f5f
DV
726 * @private
727 */
f11283de 728Dygraph.isArrayLike = function(o) {
dedb4f5f
DV
729 var typ = typeof(o);
730 if (
731 (typ != 'object' && !(typ == 'function' &&
732 typeof(o.item) == 'function')) ||
733 o === null ||
734 typeof(o.length) != 'number' ||
735 o.nodeType === 3
736 ) {
737 return false;
738 }
739 return true;
740};
741
742/**
f11283de
DV
743 * @param {Object} o
744 * @return {boolean}
dedb4f5f
DV
745 * @private
746 */
747Dygraph.isDateLike = function (o) {
748 if (typeof(o) != "object" || o === null ||
749 typeof(o.getTime) != 'function') {
750 return false;
751 }
752 return true;
753};
754
755/**
48e614ac 756 * Note: this only seems to work for arrays.
f11283de
DV
757 * @param {!Array} o
758 * @return {!Array}
dedb4f5f
DV
759 * @private
760 */
761Dygraph.clone = function(o) {
762 // TODO(danvk): figure out how MochiKit's version works
763 var r = [];
764 for (var i = 0; i < o.length; i++) {
765 if (Dygraph.isArrayLike(o[i])) {
766 r.push(Dygraph.clone(o[i]));
767 } else {
768 r.push(o[i]);
769 }
770 }
771 return r;
772};
773
774/**
dedb4f5f
DV
775 * Create a new canvas element. This is more complex than a simple
776 * document.createElement("canvas") because of IE and excanvas.
f11283de
DV
777 *
778 * @return {!HTMLCanvasElement}
779 * @private
dedb4f5f
DV
780 */
781Dygraph.createCanvas = function() {
782 var canvas = document.createElement("canvas");
783
c0f54d4f 784 var isIE = (/MSIE/.test(navigator.userAgent) && !window.opera);
dedb4f5f 785 if (isIE && (typeof(G_vmlCanvasManager) != 'undefined')) {
f11283de
DV
786 canvas = G_vmlCanvasManager.initElement(
787 /**@type{!HTMLCanvasElement}*/(canvas));
dedb4f5f
DV
788 }
789
790 return canvas;
791};
9ca829f2
DV
792
793/**
37819481
PH
794 * Returns the context's pixel ratio, which is the ratio between the device
795 * pixel ratio and the backing store ratio. Typically this is 1 for conventional
796 * displays, and > 1 for HiDPI displays (such as the Retina MBP).
797 * See http://www.html5rocks.com/en/tutorials/canvas/hidpi/ for more details.
798 *
799 * @param {!CanvasRenderingContext2D} context The canvas's 2d context.
800 * @return {number} The ratio of the device pixel ratio and the backing store
801 * ratio for the specified context.
802 */
803Dygraph.getContextPixelRatio = function(context) {
804 try {
805 var devicePixelRatio = window.devicePixelRatio || 1,
806 backingStoreRatio = context.webkitBackingStorePixelRatio ||
807 context.mozBackingStorePixelRatio ||
808 context.msBackingStorePixelRatio ||
809 context.oBackingStorePixelRatio ||
810 context.backingStorePixelRatio || 1;
811 return devicePixelRatio / backingStoreRatio;
812 } catch (e) {
813 return 1;
814 }
815};
816
817/**
971870e5
DV
818 * Checks whether the user is on an Android browser.
819 * Android does not fully support the <canvas> tag, e.g. w/r/t/ clipping.
f11283de
DV
820 * @return {boolean}
821 * @private
971870e5
DV
822 */
823Dygraph.isAndroid = function() {
758a629f 824 return (/Android/).test(navigator.userAgent);
971870e5
DV
825};
826
f11283de
DV
827
828/**
829 * TODO(danvk): use @template here when it's better supported for classes.
830 * @param {!Array} array
831 * @param {number} start
832 * @param {number} length
45a8c16f 833 * @param {function(!Array,?):boolean=} predicate
f11283de
DV
834 * @constructor
835 */
a26206cf
RK
836Dygraph.Iterator = function(array, start, length, predicate) {
837 start = start || 0;
838 length = length || array.length;
ff1074cd
RK
839 this.hasNext = true; // Use to identify if there's another element.
840 this.peek = null; // Use for look-ahead
0f20de1c 841 this.start_ = start;
a26206cf
RK
842 this.array_ = array;
843 this.predicate_ = predicate;
844 this.end_ = Math.min(array.length, start + length);
ff1074cd
RK
845 this.nextIdx_ = start - 1; // use -1 so initial advance works.
846 this.next(); // ignoring result.
42a9ebb8 847};
a26206cf 848
f11283de
DV
849/**
850 * @return {Object}
851 */
a26206cf 852Dygraph.Iterator.prototype.next = function() {
ff1074cd
RK
853 if (!this.hasNext) {
854 return null;
a26206cf 855 }
ff1074cd 856 var obj = this.peek;
a26206cf 857
ff1074cd
RK
858 var nextIdx = this.nextIdx_ + 1;
859 var found = false;
860 while (nextIdx < this.end_) {
a26206cf 861 if (!this.predicate_ || this.predicate_(this.array_, nextIdx)) {
ff1074cd
RK
862 this.peek = this.array_[nextIdx];
863 found = true;
864 break;
a26206cf
RK
865 }
866 nextIdx++;
867 }
868 this.nextIdx_ = nextIdx;
ff1074cd
RK
869 if (!found) {
870 this.hasNext = false;
871 this.peek = null;
872 }
873 return obj;
42a9ebb8 874};
a26206cf 875
971870e5 876/**
222d67c9 877 * Returns a new iterator over array, between indexes start and
7d1afbb9
RK
878 * start + length, and only returns entries that pass the accept function
879 *
f11283de
DV
880 * @param {!Array} array the array to iterate over.
881 * @param {number} start the first index to iterate over, 0 if absent.
882 * @param {number} length the number of elements in the array to iterate over.
883 * This, along with start, defines a slice of the array, and so length
884 * doesn't imply the number of elements in the iterator when accept doesn't
885 * always accept all values. array.length when absent.
45a8c16f 886 * @param {function(?):boolean=} opt_predicate a function that takes
f11283de
DV
887 * parameters array and idx, which returns true when the element should be
888 * returned. If omitted, all elements are accepted.
889 * @private
7d1afbb9 890 */
f11283de
DV
891Dygraph.createIterator = function(array, start, length, opt_predicate) {
892 return new Dygraph.Iterator(array, start, length, opt_predicate);
7d1afbb9
RK
893};
894
a96b8ba3
A
895// Shim layer with setTimeout fallback.
896// From: http://paulirish.com/2011/requestanimationframe-for-smart-animating/
e9a32469
A
897// Should be called with the window context:
898// Dygraph.requestAnimFrame.call(window, function() {})
bec100ae 899Dygraph.requestAnimFrame = (function() {
a96b8ba3
A
900 return window.requestAnimationFrame ||
901 window.webkitRequestAnimationFrame ||
902 window.mozRequestAnimationFrame ||
903 window.oRequestAnimationFrame ||
904 window.msRequestAnimationFrame ||
905 function (callback) {
906 window.setTimeout(callback, 1000 / 60);
907 };
908})();
909
910/**
d91ba598
A
911 * Call a function at most maxFrames times at an attempted interval of
912 * framePeriodInMillis, then call a cleanup function once. repeatFn is called
913 * once immediately, then at most (maxFrames - 1) times asynchronously. If
914 * maxFrames==1, then cleanup_fn() is also called synchronously. This function
915 * is used to sequence animation.
916 * @param {function(number)} repeatFn Called repeatedly -- takes the frame
917 * number (from 0 to maxFrames-1) as an argument.
918 * @param {number} maxFrames The max number of times to call repeatFn
919 * @param {number} framePeriodInMillis Max requested time between frames.
920 * @param {function()} cleanupFn A function to call after all repeatFn calls.
921 * @private
922 */
923Dygraph.repeatAndCleanup = function(repeatFn, maxFrames, framePeriodInMillis,
bec100ae 924 cleanupFn) {
d91ba598
A
925 var frameNumber = 0;
926 var previousFrameNumber;
927 var startTime = new Date().getTime();
928 repeatFn(frameNumber);
929 if (maxFrames == 1) {
930 cleanupFn();
b1a3b195
DV
931 return;
932 }
d91ba598 933 var maxFrameArg = maxFrames - 1;
b1a3b195
DV
934
935 (function loop() {
d91ba598 936 if (frameNumber >= maxFrames) return;
e9a32469 937 Dygraph.requestAnimFrame.call(window, function() {
d91ba598
A
938 // Determine which frame to draw based on the delay so far. Will skip
939 // frames if necessary.
940 var currentTime = new Date().getTime();
941 var delayInMillis = currentTime - startTime;
942 previousFrameNumber = frameNumber;
943 frameNumber = Math.floor(delayInMillis / framePeriodInMillis);
944 var frameDelta = frameNumber - previousFrameNumber;
945 // If we predict that the subsequent repeatFn call will overshoot our
946 // total frame target, so our last call will cause a stutter, then jump to
947 // the last call immediately. If we're going to cause a stutter, better
948 // to do it faster than slower.
949 var predictOvershootStutter = (frameNumber + frameDelta) > maxFrameArg;
950 if (predictOvershootStutter || (frameNumber >= maxFrameArg)) {
951 repeatFn(maxFrameArg); // Ensure final call with maxFrameArg.
952 cleanupFn();
b1a3b195 953 } else {
83b0c192 954 if (frameDelta !== 0) { // Don't call repeatFn with duplicate frames.
d91ba598
A
955 repeatFn(frameNumber);
956 }
b1a3b195
DV
957 loop();
958 }
a96b8ba3 959 });
b1a3b195
DV
960 })();
961};
962
963/**
9ca829f2
DV
964 * This function will scan the option list and determine if they
965 * require us to recalculate the pixel positions of each point.
f11283de 966 * @param {!Array.<string>} labels a list of options to check.
222d67c9 967 * @param {!Object} attrs
f11283de
DV
968 * @return {boolean} true if the graph needs new points else false.
969 * @private
9ca829f2
DV
970 */
971Dygraph.isPixelChangingOptionList = function(labels, attrs) {
972 // A whitelist of options that do not change pixel positions.
973 var pixelSafeOptions = {
974 'annotationClickHandler': true,
975 'annotationDblClickHandler': true,
976 'annotationMouseOutHandler': true,
977 'annotationMouseOverHandler': true,
978 'axisLabelColor': true,
979 'axisLineColor': true,
980 'axisLineWidth': true,
981 'clickCallback': true,
9ca829f2
DV
982 'digitsAfterDecimal': true,
983 'drawCallback': true,
5879307d 984 'drawHighlightPointCallback': true,
9ca829f2 985 'drawPoints': true,
78e58af4 986 'drawPointCallback': true,
9ca829f2
DV
987 'drawXGrid': true,
988 'drawYGrid': true,
989 'fillAlpha': true,
990 'gridLineColor': true,
991 'gridLineWidth': true,
992 'hideOverlayOnMouseOut': true,
993 'highlightCallback': true,
994 'highlightCircleSize': true,
995 'interactionModel': true,
996 'isZoomedIgnoreProgrammaticZoom': true,
997 'labelsDiv': true,
998 'labelsDivStyles': true,
999 'labelsDivWidth': true,
1000 'labelsKMB': true,
1001 'labelsKMG2': true,
1002 'labelsSeparateLines': true,
1003 'labelsShowZeroValues': true,
1004 'legend': true,
1005 'maxNumberWidth': true,
1006 'panEdgeFraction': true,
1007 'pixelsPerYLabel': true,
1008 'pointClickCallback': true,
1009 'pointSize': true,
ccd9d7c2
PF
1010 'rangeSelectorPlotFillColor': true,
1011 'rangeSelectorPlotStrokeColor': true,
9ca829f2
DV
1012 'showLabelsOnHighlight': true,
1013 'showRoller': true,
1014 'sigFigs': true,
1015 'strokeWidth': true,
1016 'underlayCallback': true,
1017 'unhighlightCallback': true,
1018 'xAxisLabelFormatter': true,
1019 'xTicker': true,
1020 'xValueFormatter': true,
1021 'yAxisLabelFormatter': true,
1022 'yValueFormatter': true,
1023 'zoomCallback': true
ccd9d7c2 1024 };
9ca829f2
DV
1025
1026 // Assume that we do not require new points.
1027 // This will change to true if we actually do need new points.
1028 var requiresNewPoints = false;
1029
1030 // Create a dictionary of series names for faster lookup.
1031 // If there are no labels, then the dictionary stays empty.
1032 var seriesNamesDictionary = { };
1033 if (labels) {
1034 for (var i = 1; i < labels.length; i++) {
1035 seriesNamesDictionary[labels[i]] = true;
1036 }
1037 }
1038
1039 // Iterate through the list of updated options.
5061b42f 1040 for (var property in attrs) {
9ca829f2
DV
1041 // Break early if we already know we need new points from a previous option.
1042 if (requiresNewPoints) {
1043 break;
1044 }
1045 if (attrs.hasOwnProperty(property)) {
1046 // Find out of this field is actually a series specific options list.
1047 if (seriesNamesDictionary[property]) {
1048 // This property value is a list of options for this series.
1049 // If any of these sub properties are not pixel safe, set the flag.
5061b42f 1050 for (var subProperty in attrs[property]) {
9ca829f2
DV
1051 // Break early if we already know we need new points from a previous option.
1052 if (requiresNewPoints) {
1053 break;
1054 }
1055 if (attrs[property].hasOwnProperty(subProperty) && !pixelSafeOptions[subProperty]) {
1056 requiresNewPoints = true;
1057 }
1058 }
1059 // If this was not a series specific option list, check if its a pixel changing property.
1060 } else if (!pixelSafeOptions[property]) {
1061 requiresNewPoints = true;
ccd9d7c2 1062 }
9ca829f2
DV
1063 }
1064 }
1065
1066 return requiresNewPoints;
1067};
78e58af4 1068
78e58af4
RK
1069Dygraph.Circles = {
1070 DEFAULT : function(g, name, ctx, canvasx, canvasy, color, radius) {
1071 ctx.beginPath();
1072 ctx.fillStyle = color;
1073 ctx.arc(canvasx, canvasy, radius, 0, 2 * Math.PI, false);
1074 ctx.fill();
78e58af4 1075 }
b7a1dc22 1076 // For more shapes, include extras/shapes.js
78e58af4 1077};
2bad4d92
DV
1078
1079/**
1080 * To create a "drag" interaction, you typically register a mousedown event
1081 * handler on the element where the drag begins. In that handler, you register a
1082 * mouseup handler on the window to determine when the mouse is released,
1083 * wherever that release happens. This works well, except when the user releases
1084 * the mouse over an off-domain iframe. In that case, the mouseup event is
1085 * handled by the iframe and never bubbles up to the window handler.
1086 *
1087 * To deal with this issue, we cover iframes with high z-index divs to make sure
1088 * they don't capture mouseup.
1089 *
1090 * Usage:
1091 * element.addEventListener('mousedown', function() {
1092 * var tarper = new Dygraph.IFrameTarp();
1093 * tarper.cover();
1094 * var mouseUpHandler = function() {
1095 * ...
1096 * window.removeEventListener(mouseUpHandler);
1097 * tarper.uncover();
1098 * };
1099 * window.addEventListener('mouseup', mouseUpHandler);
1100 * };
222d67c9 1101 *
2bad4d92
DV
1102 * @constructor
1103 */
1104Dygraph.IFrameTarp = function() {
f11283de 1105 /** @type {Array.<!HTMLDivElement>} */
2bad4d92
DV
1106 this.tarps = [];
1107};
1108
1109/**
1110 * Find all the iframes in the document and cover them with high z-index
1111 * transparent divs.
1112 */
1113Dygraph.IFrameTarp.prototype.cover = function() {
1114 var iframes = document.getElementsByTagName("iframe");
1115 for (var i = 0; i < iframes.length; i++) {
1116 var iframe = iframes[i];
1bc88216
DV
1117 var pos = Dygraph.findPos(iframe),
1118 x = pos.x,
1119 y = pos.y,
2bad4d92
DV
1120 width = iframe.offsetWidth,
1121 height = iframe.offsetHeight;
1122
1123 var div = document.createElement("div");
1124 div.style.position = "absolute";
1125 div.style.left = x + 'px';
1126 div.style.top = y + 'px';
1127 div.style.width = width + 'px';
1128 div.style.height = height + 'px';
1129 div.style.zIndex = 999;
1130 document.body.appendChild(div);
1131 this.tarps.push(div);
1132 }
1133};
1134
1135/**
1136 * Remove all the iframe covers. You should call this in a mouseup handler.
1137 */
1138Dygraph.IFrameTarp.prototype.uncover = function() {
1139 for (var i = 0; i < this.tarps.length; i++) {
1140 this.tarps[i].parentNode.removeChild(this.tarps[i]);
1141 }
1142 this.tarps = [];
1143};
e5763589
DV
1144
1145/**
df268bcc 1146 * Determine whether |data| is delimited by CR, CRLF, LF, LFCR.
e5763589 1147 * @param {string} data
f11283de 1148 * @return {?string} the delimiter that was detected (or null on failure).
e5763589
DV
1149 */
1150Dygraph.detectLineDelimiter = function(data) {
1151 for (var i = 0; i < data.length; i++) {
df268bcc
JH
1152 var code = data.charAt(i);
1153 if (code === '\r') {
1154 // Might actually be "\r\n".
1155 if (((i + 1) < data.length) && (data.charAt(i + 1) === '\n')) {
1156 return '\r\n';
1157 }
1158 return code;
1159 }
1160 if (code === '\n') {
e5763589 1161 // Might actually be "\n\r".
df268bcc
JH
1162 if (((i + 1) < data.length) && (data.charAt(i + 1) === '\r')) {
1163 return '\n\r';
1164 }
e5763589
DV
1165 return code;
1166 }
1167 }
1168
1169 return null;
1170};
def24194
DV
1171
1172/**
bcb545f4
LB
1173 * Is one node contained by another?
1174 * @param {Node} containee The contained node.
1175 * @param {Node} container The container node.
def24194
DV
1176 * @return {boolean} Whether containee is inside (or equal to) container.
1177 * @private
1178 */
bcb545f4 1179Dygraph.isNodeContainedBy = function(containee, container) {
def24194
DV
1180 if (container === null || containee === null) {
1181 return false;
1182 }
db775859
RK
1183 var containeeNode = /** @type {Node} */ (containee);
1184 while (containeeNode && containeeNode !== container) {
1185 containeeNode = containeeNode.parentNode;
def24194 1186 }
db775859 1187 return (containeeNode === container);
def24194 1188};
2fd143d3
DV
1189
1190
1191// This masks some numeric issues in older versions of Firefox,
1192// where 1.0/Math.pow(10,2) != Math.pow(10,-2).
1193/** @type {function(number,number):number} */
1194Dygraph.pow = function(base, exp) {
1195 if (exp < 0) {
1196 return 1.0 / Math.pow(base, -exp);
1197 }
1198 return Math.pow(base, exp);
1199};
1200
464b5f50
DV
1201/**
1202 * Converts any valid CSS color (hex, rgb(), named color) to an RGB tuple.
1203 *
b7a1dc22 1204 * @param {!string} colorStr Any valid CSS color string.
464b5f50
DV
1205 * @return {{r:number,g:number,b:number}} Parsed RGB tuple.
1206 * @private
1207 */
b7a1dc22 1208Dygraph.toRGB_ = function(colorStr) {
464b5f50
DV
1209 // TODO(danvk): cache color parses to avoid repeated DOM manipulation.
1210 var div = document.createElement('div');
b7a1dc22 1211 div.style.backgroundColor = colorStr;
464b5f50
DV
1212 div.style.visibility = 'hidden';
1213 document.body.appendChild(div);
1bc88216 1214 var rgbStr = window.getComputedStyle(div, null).backgroundColor;
464b5f50 1215 document.body.removeChild(div);
b7a1dc22 1216 var bits = /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/.exec(rgbStr);
464b5f50
DV
1217 return {
1218 r: parseInt(bits[1], 10),
1219 g: parseInt(bits[2], 10),
1220 b: parseInt(bits[3], 10)
1221 };
1222};
55deb02f
DV
1223
1224/**
1225 * Checks whether the browser supports the &lt;canvas&gt; tag.
1226 * @param {HTMLCanvasElement=} opt_canvasElement Pass a canvas element as an
1227 * optimization if you have one.
1228 * @return {boolean} Whether the browser supports canvas.
1229 */
1230Dygraph.isCanvasSupported = function(opt_canvasElement) {
1231 var canvas;
1232 try {
1233 canvas = opt_canvasElement || document.createElement("canvas");
1234 canvas.getContext("2d");
1235 }
1236 catch (e) {
1237 var ie = navigator.appVersion.match(/MSIE (\d\.\d)/);
1238 var opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
1239 if ((!ie) || (ie[1] < 6) || (opera))
1240 return false;
1241 return true;
1242 }
1243 return true;
1244};
1245
1246/**
1247 * Parses the value as a floating point number. This is like the parseFloat()
1248 * built-in, but with a few differences:
1249 * - the empty string is parsed as null, rather than NaN.
1250 * - if the string cannot be parsed at all, an error is logged.
1251 * If the string can't be parsed, this method returns null.
1252 * @param {string} x The string to be parsed
1253 * @param {number=} opt_line_no The line number from which the string comes.
1254 * @param {string=} opt_line The text of the line from which the string comes.
1255 */
1256Dygraph.parseFloat_ = function(x, opt_line_no, opt_line) {
1257 var val = parseFloat(x);
1258 if (!isNaN(val)) return val;
1259
1260 // Try to figure out what happeend.
1261 // If the value is the empty string, parse it as null.
1262 if (/^ *$/.test(x)) return null;
1263
1264 // If it was actually "NaN", return it as NaN.
1265 if (/^ *nan *$/i.test(x)) return NaN;
1266
1267 // Looks like a parsing error.
1268 var msg = "Unable to parse '" + x + "' as a number";
1269 if (opt_line !== undefined && opt_line_no !== undefined) {
1270 msg += " on line " + (1+(opt_line_no||0)) + " ('" + opt_line + "') of CSV.";
1271 }
1272 Dygraph.error(msg);
1273
1274 return null;
1275};