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