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