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