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