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