Merge pull request #465 from danvk/callback-this
[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 */
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 /** A dotted line stroke pattern. */
31 Dygraph.DOTTED_LINE = [2, 2];
32 /** A dashed line stroke pattern. */
33 Dygraph.DASHED_LINE = [7, 3];
34 /** A dot dash stroke pattern. */
35 Dygraph.DOT_DASH_LINE = [7, 2, 2, 2];
36
37 /**
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 * };
48 * @param {!HTMLCanvasElement} canvas
49 * @return {!CanvasRenderingContext2D}
50 * @private
51 */
52 Dygraph.getContext = function(canvas) {
53 return /** @type{!CanvasRenderingContext2D}*/(canvas.getContext("2d"));
54 };
55
56 /**
57 * Add an event handler. This smooths a difference between IE and the rest of
58 * the world.
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
62 * on the event. The function takes one parameter: the event object.
63 * @private
64 */
65 Dygraph.addEvent = function addEvent(elem, type, fn) {
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 }
72 };
73
74 /**
75 * Add an event handler. This event handler is kept until the graph is
76 * destroyed with a call to graph.destroy().
77 *
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
81 * on the event. The function takes one parameter: the event object.
82 * @private
83 */
84 Dygraph.prototype.addAndTrackEvent = function(elem, type, fn) {
85 Dygraph.addEvent(elem, type, fn);
86 this.registeredEvents_.push({ elem : elem, type : type, fn : fn });
87 };
88
89 /**
90 * Remove an event handler. This smooths a difference between IE and the rest
91 * of the world.
92 * @param {!Node} elem The element to remove the event from.
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.
96 * @private
97 */
98 Dygraph.removeEvent = function(elem, type, fn) {
99 if (elem.removeEventListener) {
100 elem.removeEventListener(type, fn, false);
101 } else {
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 }
108 elem[type+fn] = null;
109 }
110 };
111
112 Dygraph.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_ = [];
121 };
122
123 /**
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
128 * @param {!Event} e The event whose normal behavior should be canceled.
129 * @private
130 */
131 Dygraph.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.
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.
153 * @private
154 */
155 Dygraph.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
188 // ... and modifications to support scrolling divs.
189
190 /**
191 * Find the coordinates of an object relative to the top left of the page.
192 *
193 * TODO(danvk): change obj type from Node -&gt; !Node
194 * @param {Node} obj
195 * @return {{x:number,y:number}}
196 * @private
197 */
198 Dygraph.findPos = function(obj) {
199 var curleft = 0, curtop = 0;
200 if (obj.offsetParent) {
201 var copyObj = obj;
202 while (1) {
203 // NOTE: the if statement here is for IE8.
204 var borderLeft = "0", borderTop = "0";
205 if (window.getComputedStyle) {
206 var computedStyle = window.getComputedStyle(copyObj, null);
207 borderLeft = computedStyle.borderLeft || "0";
208 borderTop = computedStyle.borderTop || "0";
209 }
210 curleft += parseInt(borderLeft, 10) ;
211 curtop += parseInt(borderTop, 10) ;
212 curleft += copyObj.offsetLeft;
213 curtop += copyObj.offsetTop;
214 if (!copyObj.offsetParent) {
215 break;
216 }
217 copyObj = copyObj.offsetParent;
218 }
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;
223 }
224
225 // This handles the case where the object is inside a scrolled div.
226 while (obj && obj != document.body) {
227 curleft -= obj.scrollLeft;
228 curtop -= obj.scrollTop;
229 obj = obj.parentNode;
230 }
231 return {x: curleft, y: curtop};
232 };
233
234 /**
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
238 * @param {!Event} e
239 * @return {number}
240 * @private
241 */
242 Dygraph.pageX = function(e) {
243 if (e.pageX) {
244 return (!e.pageX || e.pageX < 0) ? 0 : e.pageX;
245 } else {
246 var de = document.documentElement;
247 var b = document.body;
248 return e.clientX +
249 (de.scrollLeft || b.scrollLeft) -
250 (de.clientLeft || 0);
251 }
252 };
253
254 /**
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
258 * @param {!Event} e
259 * @return {number}
260 * @private
261 */
262 Dygraph.pageY = function(e) {
263 if (e.pageY) {
264 return (!e.pageY || e.pageY < 0) ? 0 : e.pageY;
265 } else {
266 var de = document.documentElement;
267 var b = document.body;
268 return e.clientY +
269 (de.scrollTop || b.scrollTop) -
270 (de.clientTop || 0);
271 }
272 };
273
274 /**
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 */
281 Dygraph.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 */
292 Dygraph.dragGetY_ = function(e, context) {
293 return Dygraph.pageY(e) - context.py;
294 };
295
296 /**
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.
302 * @private
303 */
304 Dygraph.isOK = function(x) {
305 return !!x && !isNaN(x);
306 };
307
308 /**
309 * @param {{x:?number,y:?number,yval:?number}} p The point to consider, valid
310 * points are {x, y} objects
311 * @param {boolean=} opt_allowNaNY Treat point with y=NaN as valid
312 * @return {boolean} Whether the point has numeric x and y.
313 * @private
314 */
315 Dygraph.isValidPoint = function(p, opt_allowNaNY) {
316 if (!p) return false; // null or undefined object
317 if (p.yval === null) return false; // missing point
318 if (p.x === null || p.x === undefined) return false;
319 if (p.y === null || p.y === undefined) return false;
320 if (isNaN(p.x) || (!opt_allowNaNY && isNaN(p.y))) return false;
321 return true;
322 };
323
324 /**
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 *
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
340 * string length should be precision + 6 (e.g 1.123e+300).
341 */
342 Dygraph.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 '.'.
362 return (Math.abs(x) < 1.0e-3 && x !== 0.0) ?
363 x.toExponential(p - 1) : x.toPrecision(p);
364 };
365
366 /**
367 * Converts '9' to '09' (useful for dates)
368 * @param {number} x
369 * @return {string}
370 * @private
371 */
372 Dygraph.zeropad = function(x) {
373 if (x < 10) return "0" + x; else return "" + x;
374 };
375
376 /**
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 */
381 Dygraph.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 */
400 Dygraph.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 /**
415 * Return a string version of the hours, minutes and seconds portion of a date.
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"
420 * @private
421 */
422 Dygraph.hmsString_ = function(hh, mm, ss) {
423 var zeropad = Dygraph.zeropad;
424 var ret = zeropad(hh) + ":" + zeropad(mm);
425 if (ss) {
426 ret += ":" + zeropad(ss);
427 }
428 return ret;
429 };
430
431 /**
432 * Convert a JS date (millis since epoch) to a formatted string.
433 * @param {number} time The JavaScript time value (ms since epoch)
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"
437 * @private
438 */
439 Dygraph.dateString_ = function(time, utc) {
440 var zeropad = Dygraph.zeropad;
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);
449 // Get a year string:
450 var year = "" + y;
451 // Get a 0 padded month string
452 var month = zeropad(m + 1); //months are 0-offset, sigh
453 // Get a 0 padded day string
454 var day = zeropad(d);
455 var frac = hh * 3600 + mm * 60 + ss;
456 var ret = year + "/" + month + "/" + day;
457 if (frac) {
458 ret += " " + Dygraph.hmsString_(hh, mm, ss);
459 }
460 return ret;
461 };
462
463 /**
464 * Round a number to the specified number of digits past the decimal point.
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
468 * @private
469 */
470 Dygraph.round_ = function(num, places) {
471 var shift = Math.pow(10, places);
472 return Math.round(num * shift)/shift;
473 };
474
475 /**
476 * Implementation of binary search over an array.
477 * Currently does not work when val is outside the range of arry's values.
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
487 */
488 Dygraph.binarySearch = function(val, arry, abs, low, high) {
489 if (low === null || low === undefined ||
490 high === null || high === undefined) {
491 low = 0;
492 high = arry.length - 1;
493 }
494 if (low > high) {
495 return -1;
496 }
497 if (abs === null || abs === undefined) {
498 abs = 0;
499 }
500 var validIndex = function(idx) {
501 return idx >= 0 && idx < arry.length;
502 };
503 var mid = parseInt((low + high) / 2, 10);
504 var element = arry[mid];
505 var idx;
506 if (element == val) {
507 return mid;
508 } else if (element > val) {
509 if (abs > 0) {
510 // Accept if element > val, but also if prior element < val.
511 idx = mid - 1;
512 if (validIndex(idx) && arry[idx] < val) {
513 return mid;
514 }
515 }
516 return Dygraph.binarySearch(val, arry, abs, low, mid - 1);
517 } else if (element < val) {
518 if (abs < 0) {
519 // Accept if element < val, but also if prior element > val.
520 idx = mid + 1;
521 if (validIndex(idx) && arry[idx] > val) {
522 return mid;
523 }
524 }
525 return Dygraph.binarySearch(val, arry, abs, mid + 1, high);
526 }
527 return -1; // can't actually happen, but makes closure compiler happy
528 };
529
530 /**
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.
534 *
535 * @param {string} dateStr A date in a variety of possible string formats.
536 * @return {number} Milliseconds since epoch.
537 * @private
538 */
539 Dygraph.dateParser = function(dateStr) {
540 var dateStrSlashed;
541 var d;
542
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 }
554
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.
563 dateStrSlashed = dateStr.substr(0,4) + "/" + dateStr.substr(4,2) + "/" +
564 dateStr.substr(6,2);
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)) {
573 console.error("Couldn't parse " + dateStr + " as a date");
574 }
575 return d;
576 };
577
578 /**
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.
582 * @param {string} str The date string, e.g. "2011/05/06"
583 * @return {number} millis since epoch
584 * @private
585 */
586 Dygraph.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 *
594 * @param {!Object} self
595 * @param {!Object} o
596 * @return {!Object}
597 */
598 Dygraph.update = function(self, o) {
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 /**
610 * Copies all the properties from o to self.
611 *
612 * @param {!Object} self
613 * @param {!Object} o
614 * @return {!Object}
615 * @private
616 */
617 Dygraph.updateDeep = function (self, o) {
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
626 if (typeof(o) != 'undefined' && o !== null) {
627 for (var k in o) {
628 if (o.hasOwnProperty(k)) {
629 if (o[k] === null) {
630 self[k] = null;
631 } else if (Dygraph.isArrayLike(o[k])) {
632 self[k] = o[k].slice();
633 } else if (isNode(o[k])) {
634 // DOM objects are shallowly-copied.
635 self[k] = o[k];
636 } else if (typeof(o[k]) == 'object') {
637 if (typeof(self[k]) != 'object' || self[k] === null) {
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 /**
651 * @param {*} o
652 * @return {boolean}
653 * @private
654 */
655 Dygraph.isArrayLike = function(o) {
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 /**
670 * @param {Object} o
671 * @return {boolean}
672 * @private
673 */
674 Dygraph.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 /**
683 * Note: this only seems to work for arrays.
684 * @param {!Array} o
685 * @return {!Array}
686 * @private
687 */
688 Dygraph.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 /**
702 * Create a new canvas element. This is more complex than a simple
703 * document.createElement("canvas") because of IE and excanvas.
704 *
705 * @return {!HTMLCanvasElement}
706 * @private
707 */
708 Dygraph.createCanvas = function() {
709 var canvas = document.createElement("canvas");
710
711 var isIE = (/MSIE/.test(navigator.userAgent) && !window.opera);
712 if (isIE && (typeof(G_vmlCanvasManager) != 'undefined')) {
713 canvas = G_vmlCanvasManager.initElement(
714 /**@type{!HTMLCanvasElement}*/(canvas));
715 }
716
717 return canvas;
718 };
719
720 /**
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 */
730 Dygraph.getContextPixelRatio = function(context) {
731 try {
732 var devicePixelRatio = window.devicePixelRatio;
733 var backingStoreRatio = context.webkitBackingStorePixelRatio ||
734 context.mozBackingStorePixelRatio ||
735 context.msBackingStorePixelRatio ||
736 context.oBackingStorePixelRatio ||
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 }
746 } catch (e) {
747 return 1;
748 }
749 };
750
751 /**
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.
754 * @return {boolean}
755 * @private
756 */
757 Dygraph.isAndroid = function() {
758 return (/Android/).test(navigator.userAgent);
759 };
760
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
767 * @param {function(!Array,?):boolean=} predicate
768 * @constructor
769 */
770 Dygraph.Iterator = function(array, start, length, predicate) {
771 start = start || 0;
772 length = length || array.length;
773 this.hasNext = true; // Use to identify if there's another element.
774 this.peek = null; // Use for look-ahead
775 this.start_ = start;
776 this.array_ = array;
777 this.predicate_ = predicate;
778 this.end_ = Math.min(array.length, start + length);
779 this.nextIdx_ = start - 1; // use -1 so initial advance works.
780 this.next(); // ignoring result.
781 };
782
783 /**
784 * @return {Object}
785 */
786 Dygraph.Iterator.prototype.next = function() {
787 if (!this.hasNext) {
788 return null;
789 }
790 var obj = this.peek;
791
792 var nextIdx = this.nextIdx_ + 1;
793 var found = false;
794 while (nextIdx < this.end_) {
795 if (!this.predicate_ || this.predicate_(this.array_, nextIdx)) {
796 this.peek = this.array_[nextIdx];
797 found = true;
798 break;
799 }
800 nextIdx++;
801 }
802 this.nextIdx_ = nextIdx;
803 if (!found) {
804 this.hasNext = false;
805 this.peek = null;
806 }
807 return obj;
808 };
809
810 /**
811 * Returns a new iterator over array, between indexes start and
812 * start + length, and only returns entries that pass the accept function
813 *
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.
820 * @param {function(?):boolean=} opt_predicate a function that takes
821 * parameters array and idx, which returns true when the element should be
822 * returned. If omitted, all elements are accepted.
823 * @private
824 */
825 Dygraph.createIterator = function(array, start, length, opt_predicate) {
826 return new Dygraph.Iterator(array, start, length, opt_predicate);
827 };
828
829 // Shim layer with setTimeout fallback.
830 // From: http://paulirish.com/2011/requestanimationframe-for-smart-animating/
831 // Should be called with the window context:
832 // Dygraph.requestAnimFrame.call(window, function() {})
833 Dygraph.requestAnimFrame = (function() {
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 /**
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 */
857 Dygraph.repeatAndCleanup = function(repeatFn, maxFrames, framePeriodInMillis,
858 cleanupFn) {
859 var frameNumber = 0;
860 var previousFrameNumber;
861 var startTime = new Date().getTime();
862 repeatFn(frameNumber);
863 if (maxFrames == 1) {
864 cleanupFn();
865 return;
866 }
867 var maxFrameArg = maxFrames - 1;
868
869 (function loop() {
870 if (frameNumber >= maxFrames) return;
871 Dygraph.requestAnimFrame.call(window, function() {
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();
887 } else {
888 if (frameDelta !== 0) { // Don't call repeatFn with duplicate frames.
889 repeatFn(frameNumber);
890 }
891 loop();
892 }
893 });
894 })();
895 };
896
897 /**
898 * This function will scan the option list and determine if they
899 * require us to recalculate the pixel positions of each point.
900 * @param {!Array.<string>} labels a list of options to check.
901 * @param {!Object} attrs
902 * @return {boolean} true if the graph needs new points else false.
903 * @private
904 */
905 Dygraph.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,
916 'digitsAfterDecimal': true,
917 'drawCallback': true,
918 'drawHighlightPointCallback': true,
919 'drawPoints': true,
920 'drawPointCallback': true,
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,
944 'rangeSelectorPlotFillColor': true,
945 'rangeSelectorPlotStrokeColor': true,
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
958 };
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.
974 for (var property in attrs) {
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.
984 for (var subProperty in attrs[property]) {
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;
996 }
997 }
998 }
999
1000 return requiresNewPoints;
1001 };
1002
1003 Dygraph.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();
1009 }
1010 // For more shapes, include extras/shapes.js
1011 };
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 * };
1035 *
1036 * @constructor
1037 */
1038 Dygraph.IFrameTarp = function() {
1039 /** @type {Array.<!HTMLDivElement>} */
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 */
1047 Dygraph.IFrameTarp.prototype.cover = function() {
1048 var iframes = document.getElementsByTagName("iframe");
1049 for (var i = 0; i < iframes.length; i++) {
1050 var iframe = iframes[i];
1051 var pos = Dygraph.findPos(iframe),
1052 x = pos.x,
1053 y = pos.y,
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 */
1072 Dygraph.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 };
1078
1079 /**
1080 * Determine whether |data| is delimited by CR, CRLF, LF, LFCR.
1081 * @param {string} data
1082 * @return {?string} the delimiter that was detected (or null on failure).
1083 */
1084 Dygraph.detectLineDelimiter = function(data) {
1085 for (var i = 0; i < data.length; i++) {
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') {
1095 // Might actually be "\n\r".
1096 if (((i + 1) < data.length) && (data.charAt(i + 1) === '\r')) {
1097 return '\n\r';
1098 }
1099 return code;
1100 }
1101 }
1102
1103 return null;
1104 };
1105
1106 /**
1107 * Is one node contained by another?
1108 * @param {Node} containee The contained node.
1109 * @param {Node} container The container node.
1110 * @return {boolean} Whether containee is inside (or equal to) container.
1111 * @private
1112 */
1113 Dygraph.isNodeContainedBy = function(containee, container) {
1114 if (container === null || containee === null) {
1115 return false;
1116 }
1117 var containeeNode = /** @type {Node} */ (containee);
1118 while (containeeNode && containeeNode !== container) {
1119 containeeNode = containeeNode.parentNode;
1120 }
1121 return (containeeNode === container);
1122 };
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} */
1128 Dygraph.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
1135 /**
1136 * Converts any valid CSS color (hex, rgb(), named color) to an RGB tuple.
1137 *
1138 * @param {!string} colorStr Any valid CSS color string.
1139 * @return {{r:number,g:number,b:number}} Parsed RGB tuple.
1140 * @private
1141 */
1142 Dygraph.toRGB_ = function(colorStr) {
1143 // TODO(danvk): cache color parses to avoid repeated DOM manipulation.
1144 var div = document.createElement('div');
1145 div.style.backgroundColor = colorStr;
1146 div.style.visibility = 'hidden';
1147 document.body.appendChild(div);
1148 var rgbStr = window.getComputedStyle(div, null).backgroundColor;
1149 document.body.removeChild(div);
1150 var bits = /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/.exec(rgbStr);
1151 return {
1152 r: parseInt(bits[1], 10),
1153 g: parseInt(bits[2], 10),
1154 b: parseInt(bits[3], 10)
1155 };
1156 };
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 */
1164 Dygraph.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 */
1190 Dygraph.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 }
1206 console.error(msg);
1207
1208 return null;
1209 };