3 * Copyright 2011 Dan Vanderkam (danvdk@gmail.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
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.
14 /*jshint globalstrict: true */
15 /*global Dygraph:false, G_vmlCanvasManager:false, Node:false, printStackTrace: false */
18 Dygraph
.LOG_SCALE
= 10;
19 Dygraph
.LN_TEN
= Math
.log(Dygraph
.LOG_SCALE
);
26 Dygraph
.log10
= function(x
) {
27 return Math
.log(x
) / Dygraph
.LN_TEN
;
30 // Various logging levels.
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;
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];
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.
55 Dygraph
.log
= function(severity
, message
) {
57 if (typeof(printStackTrace
) != 'undefined') {
59 // Remove uninteresting bits: logging functions and paths.
60 st
= printStackTrace({guess
:false});
61 while (st
[0].indexOf("stacktrace") != -1) {
66 for (var i
= 0; i
< st
.length
; i
++) {
67 st
[i
] = st
[i
].replace(/\([^)]*\/(.*)\)/, '@$1')
68 .replace(/\@.*\/([^\/]*)/, '@$1')
69 .replace('[object Object].', '');
71 var top_msg
= st
.splice(0, 1)[0];
72 message
+= ' (' + top_msg
.replace(/^.*@ ?/, '') + ')';
74 // Oh well, it was worth a shot!
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
);
91 log(console
, console
.debug
, 'dygraphs: ' + message
);
94 log(console
, console
.info
, 'dygraphs: ' + message
);
97 log(console
, console
.warn
, 'dygraphs: ' + message
);
100 log(console
, console
.error
, 'dygraphs: ' + message
);
105 if (Dygraph
.LOG_STACK_TRACES
) {
106 window
.console
.log(st
.join('\n'));
111 * @param {string} message
114 Dygraph
.info
= function(message
) {
115 Dygraph
.log(Dygraph
.INFO
, message
);
118 * @param {string} message
121 Dygraph
.prototype.info
= Dygraph
.info
;
124 * @param {string} message
127 Dygraph
.warn
= function(message
) {
128 Dygraph
.log(Dygraph
.WARNING
, message
);
131 * @param {string} message
134 Dygraph
.prototype.warn
= Dygraph
.warn
;
137 * @param {string} message
139 Dygraph
.error
= function(message
) {
140 Dygraph
.log(Dygraph
.ERROR
, message
);
143 * @param {string} message
146 Dygraph
.prototype.error
= Dygraph
.error
;
149 * Return the 2d context for a dygraph canvas.
151 * This method is only exposed for the sake of replacing the function in
152 * automated tests, e.g.
154 * var oldFunc = Dygraph.getContext();
155 * Dygraph.getContext = function(canvas) {
156 * var realContext = oldFunc(canvas);
157 * return new Proxy(realContext);
159 * @param {!HTMLCanvasElement} canvas
160 * @return {!CanvasRenderingContext2D}
163 Dygraph
.getContext
= function(canvas
) {
164 return /** @type{!CanvasRenderingContext2D}*/(canvas
.getContext("2d"));
168 * Add an event handler. This smooths a difference between IE and the rest of
170 * @param { !Element } elem The element to add the event to.
171 * @param { string } type The type of the event, e.g. 'click' or 'mousemove'.
172 * @param { function(Event):(boolean|undefined) } fn The function to call
173 * on the event. The function takes one parameter: the event object.
176 Dygraph
.addEvent
= function addEvent(elem
, type
, fn
) {
177 if (elem
.addEventListener
) {
178 elem
.addEventListener(type
, fn
, false);
180 elem
[type
+fn
] = function(){fn(window
.event
);};
181 elem
.attachEvent('on'+type
, elem
[type
+fn
]);
186 * Add an event handler. This event handler is kept until the graph is
187 * destroyed with a call to graph.destroy().
189 * @param { !Element } elem The element to add the event to.
190 * @param { string } type The type of the event, e.g. 'click' or 'mousemove'.
191 * @param { function(Event):(boolean|undefined) } fn The function to call
192 * on the event. The function takes one parameter: the event object.
195 Dygraph
.prototype.addEvent
= function(elem
, type
, fn
) {
196 Dygraph
.addEvent(elem
, type
, fn
);
197 this.registeredEvents_
.push({ elem
: elem
, type
: type
, fn
: fn
});
201 * Remove an event handler. This smooths a difference between IE and the rest
203 * @param {!Element} elem The element to add the event to.
204 * @param {string} type The type of the event, e.g. 'click' or 'mousemove'.
205 * @param {function(Event):(boolean|undefined)} fn The function to call
206 * on the event. The function takes one parameter: the event object.
209 Dygraph
.removeEvent
= function(elem
, type
, fn
) {
210 if (elem
.removeEventListener
) {
211 elem
.removeEventListener(type
, fn
, false);
214 elem
.detachEvent('on'+type
, elem
[type
+fn
]);
216 // We only detach event listeners on a "best effort" basis in IE. See:
217 // http://stackoverflow.com/questions
/2553632/detachevent-not
-working
-with-named
-inline
-functions
219 elem
[type
+fn
] = null;
224 * Cancels further processing of an event. This is useful to prevent default
225 * browser actions, e.g. highlighting text on a double-click.
226 * Based on the article at
227 * http://www.switchonthecode.com/tutorials/javascript-tutorial-the-scroll-wheel
228 * @param { !Event } e The event whose normal behavior should be canceled.
231 Dygraph
.cancelEvent
= function(e
) {
232 e
= e
? e
: window
.event
;
233 if (e
.stopPropagation
) {
236 if (e
.preventDefault
) {
239 e
.cancelBubble
= true;
241 e
.returnValue
= false;
246 * Convert hsv values to an rgb(r,g,b) string. Taken from MochiKit.Color. This
247 * is used to generate default series colors which are evenly spaced on the
249 * @param { number } hue Range is 0.0-1.0.
250 * @param { number } saturation Range is 0.0-1.0.
251 * @param { number } value Range is 0.0-1.0.
252 * @return { string } "rgb(r,g,b)" where r, g and b range from 0-255.
255 Dygraph
.hsvToRGB
= function (hue
, saturation
, value
) {
259 if (saturation
=== 0) {
264 var i
= Math
.floor(hue
* 6);
265 var f
= (hue
* 6) - i
;
266 var p
= value
* (1 - saturation
);
267 var q
= value
* (1 - (saturation
* f
));
268 var t
= value
* (1 - (saturation
* (1 - f
)));
270 case 1: red
= q
; green
= value
; blue
= p
; break;
271 case 2: red
= p
; green
= value
; blue
= t
; break;
272 case 3: red
= p
; green
= q
; blue
= value
; break;
273 case 4: red
= t
; green
= p
; blue
= value
; break;
274 case 5: red
= value
; green
= p
; blue
= q
; break;
275 case 6: // fall through
276 case 0: red
= value
; green
= t
; blue
= p
; break;
279 red
= Math
.floor(255 * red
+ 0.5);
280 green
= Math
.floor(255 * green
+ 0.5);
281 blue
= Math
.floor(255 * blue
+ 0.5);
282 return 'rgb(' + red
+ ',' + green
+ ',' + blue
+ ')';
285 // The following functions are from quirksmode.org with a modification for Safari from
286 // http://blog.firetree.net/2005/07/04/javascript-find-position/
287 // http://www.quirksmode.org/js
/findpos
.html
288 // ... and modifications to support scrolling divs.
291 * Find the x-coordinate of the supplied object relative to the left side
293 * TODO(danvk): change obj type from Node -> !Node
298 Dygraph
.findPosX
= function(obj
) {
300 if(obj
.offsetParent
) {
303 // NOTE: the if statement here is for IE8.
304 var borderLeft
= "0";
305 if (window
.getComputedStyle
) {
306 borderLeft
= window
.getComputedStyle(copyObj
, null).borderLeft
|| "0";
308 curleft
+= parseInt(borderLeft
, 10) ;
309 curleft
+= copyObj
.offsetLeft
;
310 if(!copyObj
.offsetParent
) {
313 copyObj
= copyObj
.offsetParent
;
318 // This handles the case where the object is inside a scrolled div.
319 while(obj
&& obj
!= document
.body
) {
320 curleft
-= obj
.scrollLeft
;
321 obj
= obj
.parentNode
;
327 * Find the y-coordinate of the supplied object relative to the top of the
329 * TODO(danvk): change obj type from Node -> !Node
330 * TODO(danvk): consolidate with findPosX and return an {x, y} object.
335 Dygraph
.findPosY
= function(obj
) {
337 if(obj
.offsetParent
) {
340 // NOTE: the if statement here is for IE8.
342 if (window
.getComputedStyle
) {
343 borderTop
= window
.getComputedStyle(copyObj
, null).borderTop
|| "0";
345 curtop
+= parseInt(borderTop
, 10) ;
346 curtop
+= copyObj
.offsetTop
;
347 if(!copyObj
.offsetParent
) {
350 copyObj
= copyObj
.offsetParent
;
355 // This handles the case where the object is inside a scrolled div.
356 while(obj
&& obj
!= document
.body
) {
357 curtop
-= obj
.scrollTop
;
358 obj
= obj
.parentNode
;
364 * Returns the x-coordinate of the event in a coordinate system where the
365 * top-left corner of the page (not the window) is (0,0).
366 * Taken from MochiKit.Signal
371 Dygraph
.pageX
= function(e
) {
373 return (!e
.pageX
|| e
.pageX
< 0) ? 0 : e
.pageX
;
375 var de
= document
.documentElement
;
376 var b
= document
.body
;
378 (de
.scrollLeft
|| b
.scrollLeft
) -
379 (de
.clientLeft
|| 0);
384 * Returns the y-coordinate of the event in a coordinate system where the
385 * top-left corner of the page (not the window) is (0,0).
386 * Taken from MochiKit.Signal
391 Dygraph
.pageY
= function(e
) {
393 return (!e
.pageY
|| e
.pageY
< 0) ? 0 : e
.pageY
;
395 var de
= document
.documentElement
;
396 var b
= document
.body
;
398 (de
.scrollTop
|| b
.scrollTop
) -
404 * This returns true unless the parameter is 0, null, undefined or NaN.
405 * TODO(danvk): rename this function to something like 'isNonZeroNan'.
407 * @param {number} x The number to consider.
408 * @return {boolean} Whether the number is zero or NaN.
411 Dygraph
.isOK
= function(x
) {
412 return !!x
&& !isNaN(x
);
416 * @param { {x:?number,y:?number,yval:?number} } p The point to consider, valid
417 * points are {x, y} objects
418 * @param { boolean } allowNaNY Treat point with y=NaN as valid
419 * @return { boolean } Whether the point has numeric x and y.
422 Dygraph
.isValidPoint
= function(p
, allowNaNY
) {
423 if (!p
) return false; // null or undefined object
424 if (p
.yval
=== null) return false; // missing point
425 if (p
.x
=== null || p
.x
=== undefined
) return false;
426 if (p
.y
=== null || p
.y
=== undefined
) return false;
427 if (isNaN(p
.x
) || (!allowNaNY
&& isNaN(p
.y
))) return false;
432 * Number formatting function which mimicks the behavior of %g in printf, i.e.
433 * either exponential or fixed format (without trailing 0s) is used depending on
434 * the length of the generated string. The advantage of this format is that
435 * there is a predictable upper bound on the resulting string length,
436 * significant figures are not dropped, and normal numbers are not displayed in
437 * exponential notation.
439 * NOTE: JavaScript's native toPrecision() is NOT a drop-in replacement for %g.
440 * It creates strings which are too long for absolute values between 10^-4 and
441 * 10^-6, e.g. '0.00001' instead of '1e-5'. See tests/number-format.html for
444 * @param {number} x The number to format
445 * @param {number=} opt_precision The precision to use, default 2.
446 * @return {string} A string formatted like %g in printf. The max generated
447 * string length should be precision + 6 (e.g 1.123e+300).
449 Dygraph
.floatFormat
= function(x
, opt_precision
) {
450 // Avoid invalid precision values; [1, 21] is the valid range.
451 var p
= Math
.min(Math
.max(1, opt_precision
|| 2), 21);
453 // This is deceptively simple. The actual algorithm comes from:
455 // Max allowed length = p + 4
456 // where 4 comes from 'e+n' and '.'.
458 // Length of fixed format = 2 + y + p
459 // where 2 comes from '0.' and y = # of leading zeroes.
461 // Equating the two and solving for y yields y = 2, or 0.00xxxx which is
464 // Since the behavior of toPrecision() is identical for larger numbers, we
465 // don't have to worry about the other bound.
467 // Finally, the argument for toExponential() is the number of trailing digits,
468 // so we take off 1 for the value before the '.'.
469 return (Math
.abs(x
) < 1.0e-3 && x
!== 0.0) ?
470 x
.toExponential(p
- 1) : x
.toPrecision(p
);
474 * Converts '9' to '09' (useful for dates)
479 Dygraph
.zeropad
= function(x
) {
480 if (x
< 10) return "0" + x
; else return "" + x
;
484 * Return a string version of the hours, minutes and seconds portion of a date.
486 * @param {number} date The JavaScript date (ms since epoch)
487 * @return {string} A time of the form "HH:MM:SS"
490 Dygraph
.hmsString_
= function(date
) {
491 var zeropad
= Dygraph
.zeropad
;
492 var d
= new Date(date
);
493 if (d
.getSeconds()) {
494 return zeropad(d
.getHours()) + ":" +
495 zeropad(d
.getMinutes()) + ":" +
496 zeropad(d
.getSeconds());
498 return zeropad(d
.getHours()) + ":" + zeropad(d
.getMinutes());
503 * Round a number to the specified number of digits past the decimal point.
504 * @param {number} num The number to round
505 * @param {number} places The number of decimals to which to round
506 * @return {number} The rounded number
509 Dygraph
.round_
= function(num
, places
) {
510 var shift
= Math
.pow(10, places
);
511 return Math
.round(num
* shift
)/shift
;
515 * Implementation of binary search over an array.
516 * Currently does not work when val is outside the range of arry's values.
517 * @param {number} val the value to search for
518 * @param {Array.<number>} arry is the value over which to search
519 * @param {number} abs If abs > 0, find the lowest entry greater than val
520 * If abs < 0, find the highest entry less than val.
521 * If abs == 0, find the entry that equals val.
522 * @param {number=} low The first index in arry to consider (optional)
523 * @param {number=} high The last index in arry to consider (optional)
524 * @return {number} Index of the element, or -1 if it isn't found.
527 Dygraph
.binarySearch
= function(val
, arry
, abs
, low
, high
) {
528 if (low
=== null || low
=== undefined
||
529 high
=== null || high
=== undefined
) {
531 high
= arry
.length
- 1;
536 if (abs
=== null || abs
=== undefined
) {
539 var validIndex
= function(idx
) {
540 return idx
>= 0 && idx
< arry
.length
;
542 var mid
= parseInt((low
+ high
) / 2, 10);
543 var element
= arry
[mid
];
545 if (element
== val
) {
547 } else if (element
> val
) {
549 // Accept if element > val, but also if prior element < val.
551 if (validIndex(idx
) && arry
[idx
] < val
) {
555 return Dygraph
.binarySearch(val
, arry
, abs
, low
, mid
- 1);
556 } else if (element
< val
) {
558 // Accept if element < val, but also if prior element > val.
560 if (validIndex(idx
) && arry
[idx
] > val
) {
564 return Dygraph
.binarySearch(val
, arry
, abs
, mid
+ 1, high
);
566 return -1; // can't actually happen, but makes closure compiler happy
570 * Parses a date, returning the number of milliseconds since epoch. This can be
571 * passed in as an xValueParser in the Dygraph constructor.
572 * TODO(danvk): enumerate formats that this understands.
574 * @param {string} dateStr A date in a variety of possible string formats.
575 * @return {number} Milliseconds since epoch.
578 Dygraph
.dateParser
= function(dateStr
) {
582 // Let the system try the format first, with one caveat:
583 // YYYY-MM-DD[ HH:MM:SS] is interpreted as UTC by a variety of browsers.
584 // dygraphs displays dates in local time, so this will result in surprising
585 // inconsistencies. But if you specify "T" or "Z" (i.e. YYYY-MM-DDTHH:MM:SS),
586 // then you probably know what you're doing, so we'll let you go ahead.
587 // Issue: http://code.google.com/p/dygraphs/issues/detail
?id
=255
588 if (dateStr
.search("-") == -1 ||
589 dateStr
.search("T") != -1 || dateStr
.search("Z") != -1) {
590 d
= Dygraph
.dateStrToMillis(dateStr
);
591 if (d
&& !isNaN(d
)) return d
;
594 if (dateStr
.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12'
595 dateStrSlashed
= dateStr
.replace("-", "/", "g");
596 while (dateStrSlashed
.search("-") != -1) {
597 dateStrSlashed
= dateStrSlashed
.replace("-", "/");
599 d
= Dygraph
.dateStrToMillis(dateStrSlashed
);
600 } else if (dateStr
.length
== 8) { // e.g. '20090712'
601 // TODO(danvk): remove support for this format. It's confusing.
602 dateStrSlashed
= dateStr
.substr(0,4) + "/" + dateStr.substr(4,2) + "/" +
604 d
= Dygraph
.dateStrToMillis(dateStrSlashed
);
606 // Any format that Date.parse will accept, e.g. "2009/07/12" or
607 // "2009/07/12 12:34:56"
608 d
= Dygraph
.dateStrToMillis(dateStr
);
611 if (!d
|| isNaN(d
)) {
612 Dygraph
.error("Couldn't parse " + dateStr
+ " as a date");
618 * This is identical to JavaScript's built-in Date.parse() method, except that
619 * it doesn't get replaced with an incompatible method by aggressive JS
620 * libraries like MooTools or Joomla.
621 * @param {string} str The date string, e.g. "2011/05/06"
622 * @return {number} millis since epoch
625 Dygraph
.dateStrToMillis
= function(str
) {
626 return new Date(str
).getTime();
629 // These functions are all based on MochiKit.
631 * Copies all the properties from o to self.
633 * @param {!Object} self
637 Dygraph
.update
= function(self
, o
) {
638 if (typeof(o
) != 'undefined' && o
!== null) {
640 if (o
.hasOwnProperty(k
)) {
649 * Copies all the properties from o to self.
651 * @param {!Object} self
656 Dygraph
.updateDeep
= function (self
, o
) {
657 // Taken from http://stackoverflow.com/questions
/384286/javascript
-isdom
-how
-do-you
-check
-if-a
-javascript
-object
-is
-a
-dom
-object
660 typeof Node
=== "object" ? o
instanceof Node
:
661 typeof o
=== "object" && typeof o
.nodeType
=== "number" && typeof o
.nodeName
==="string"
665 if (typeof(o
) != 'undefined' && o
!== null) {
667 if (o
.hasOwnProperty(k
)) {
670 } else if (Dygraph
.isArrayLike(o
[k
])) {
671 self
[k
] = o
[k
].slice();
672 } else if (isNode(o
[k
])) {
673 // DOM objects are shallowly-copied.
675 } else if (typeof(o
[k
]) == 'object') {
676 if (typeof(self
[k
]) != 'object' || self
[k
] === null) {
679 Dygraph
.updateDeep(self
[k
], o
[k
]);
694 Dygraph
.isArrayLike
= function(o
) {
697 (typ
!= 'object' && !(typ
== 'function' &&
698 typeof(o
.item
) == 'function')) ||
700 typeof(o
.length
) != 'number' ||
713 Dygraph
.isDateLike
= function (o
) {
714 if (typeof(o
) != "object" || o
=== null ||
715 typeof(o
.getTime
) != 'function') {
722 * Note: this only seems to work for arrays.
727 Dygraph
.clone
= function(o
) {
728 // TODO(danvk): figure out how MochiKit's version works
730 for (var i
= 0; i
< o
.length
; i
++) {
731 if (Dygraph
.isArrayLike(o
[i
])) {
732 r
.push(Dygraph
.clone(o
[i
]));
741 * Create a new canvas element. This is more complex than a simple
742 * document.createElement("canvas") because of IE and excanvas.
744 * @return {!HTMLCanvasElement}
747 Dygraph
.createCanvas
= function() {
748 var canvas
= document
.createElement("canvas");
750 var isIE
= (/MSIE/.test(navigator
.userAgent
) && !window
.opera
);
751 if (isIE
&& (typeof(G_vmlCanvasManager
) != 'undefined')) {
752 canvas
= G_vmlCanvasManager
.initElement(
753 /**@type{!HTMLCanvasElement}*/(canvas
));
760 * Checks whether the user is on an Android browser.
761 * Android does not fully support the <canvas> tag, e.g. w/r/t/ clipping.
765 Dygraph
.isAndroid
= function() {
766 return (/Android/).test(navigator
.userAgent
);
771 * TODO(danvk): use @template here when it's better supported for classes.
772 * @param {!Array} array
773 * @param {number} start
774 * @param {number} length
775 * @param {function(!Array,?):boolean=} predicate
778 Dygraph
.Iterator
= function(array
, start
, length
, predicate
) {
780 length
= length
|| array
.length
;
781 this.hasNext
= true; // Use to identify if there's another element.
782 this.peek
= null; // Use for look-ahead
785 this.predicate_
= predicate
;
786 this.end_
= Math
.min(array
.length
, start
+ length
);
787 this.nextIdx_
= start
- 1; // use -1 so initial advance works.
788 this.next(); // ignoring result.
794 Dygraph
.Iterator
.prototype.next
= function() {
800 var nextIdx
= this.nextIdx_
+ 1;
802 while (nextIdx
< this.end_
) {
803 if (!this.predicate_
|| this.predicate_(this.array_
, nextIdx
)) {
804 this.peek
= this.array_
[nextIdx
];
810 this.nextIdx_
= nextIdx
;
812 this.hasNext
= false;
819 * Returns a new iterator over array, between indexes start and
820 * start + length, and only returns entries that pass the accept function
822 * @param {!Array} array the array to iterate over.
823 * @param {number} start the first index to iterate over, 0 if absent.
824 * @param {number} length the number of elements in the array to iterate over.
825 * This, along with start, defines a slice of the array, and so length
826 * doesn't imply the number of elements in the iterator when accept doesn't
827 * always accept all values. array.length when absent.
828 * @param {function(?):boolean=} opt_predicate a function that takes
829 * parameters array and idx, which returns true when the element should be
830 * returned. If omitted, all elements are accepted.
833 Dygraph
.createIterator
= function(array
, start
, length
, opt_predicate
) {
834 return new Dygraph
.Iterator(array
, start
, length
, opt_predicate
);
837 // Shim layer with setTimeout fallback.
838 // From: http://paulirish.com/2011/requestanimationframe-for-smart-animating/
839 // Should be called with the window context:
840 // Dygraph.requestAnimFrame.call(window, function() {})
841 Dygraph
.requestAnimFrame
= (function() {
842 return window
.requestAnimationFrame
||
843 window
.webkitRequestAnimationFrame
||
844 window
.mozRequestAnimationFrame
||
845 window
.oRequestAnimationFrame
||
846 window
.msRequestAnimationFrame
||
847 function (callback
) {
848 window
.setTimeout(callback
, 1000 / 60);
853 * Call a function at most maxFrames times at an attempted interval of
854 * framePeriodInMillis, then call a cleanup function once. repeatFn is called
855 * once immediately, then at most (maxFrames - 1) times asynchronously. If
856 * maxFrames==1, then cleanup_fn() is also called synchronously. This function
857 * is used to sequence animation.
858 * @param {function(number)} repeatFn Called repeatedly -- takes the frame
859 * number (from 0 to maxFrames-1) as an argument.
860 * @param {number} maxFrames The max number of times to call repeatFn
861 * @param {number} framePeriodInMillis Max requested time between frames.
862 * @param {function()} cleanupFn A function to call after all repeatFn calls.
865 Dygraph
.repeatAndCleanup
= function(repeatFn
, maxFrames
, framePeriodInMillis
,
868 var previousFrameNumber
;
869 var startTime
= new Date().getTime();
870 repeatFn(frameNumber
);
871 if (maxFrames
== 1) {
875 var maxFrameArg
= maxFrames
- 1;
878 if (frameNumber
>= maxFrames
) return;
879 Dygraph
.requestAnimFrame
.call(window
, function() {
880 // Determine which frame to draw based on the delay so far. Will skip
881 // frames if necessary.
882 var currentTime
= new Date().getTime();
883 var delayInMillis
= currentTime
- startTime
;
884 previousFrameNumber
= frameNumber
;
885 frameNumber
= Math
.floor(delayInMillis
/ framePeriodInMillis
);
886 var frameDelta
= frameNumber
- previousFrameNumber
;
887 // If we predict that the subsequent repeatFn call will overshoot our
888 // total frame target, so our last call will cause a stutter, then jump to
889 // the last call immediately. If we're going to cause a stutter, better
890 // to do it faster than slower.
891 var predictOvershootStutter
= (frameNumber
+ frameDelta
) > maxFrameArg
;
892 if (predictOvershootStutter
|| (frameNumber
>= maxFrameArg
)) {
893 repeatFn(maxFrameArg
); // Ensure final call with maxFrameArg.
896 if (frameDelta
!== 0) { // Don't call repeatFn with duplicate frames.
897 repeatFn(frameNumber
);
906 * This function will scan the option list and determine if they
907 * require us to recalculate the pixel positions of each point.
908 * @param {!Array.<string>} labels a list of options to check.
909 * @param {!Object} attrs
910 * @return {boolean} true if the graph needs new points else false.
913 Dygraph
.isPixelChangingOptionList
= function(labels
, attrs
) {
914 // A whitelist of options that do not change pixel positions.
915 var pixelSafeOptions
= {
916 'annotationClickHandler': true,
917 'annotationDblClickHandler': true,
918 'annotationMouseOutHandler': true,
919 'annotationMouseOverHandler': true,
920 'axisLabelColor': true,
921 'axisLineColor': true,
922 'axisLineWidth': true,
923 'clickCallback': true,
924 'digitsAfterDecimal': true,
925 'drawCallback': true,
926 'drawHighlightPointCallback': true,
928 'drawPointCallback': true,
932 'gridLineColor': true,
933 'gridLineWidth': true,
934 'hideOverlayOnMouseOut': true,
935 'highlightCallback': true,
936 'highlightCircleSize': true,
937 'interactionModel': true,
938 'isZoomedIgnoreProgrammaticZoom': true,
940 'labelsDivStyles': true,
941 'labelsDivWidth': true,
944 'labelsSeparateLines': true,
945 'labelsShowZeroValues': true,
947 'maxNumberWidth': true,
948 'panEdgeFraction': true,
949 'pixelsPerYLabel': true,
950 'pointClickCallback': true,
952 'rangeSelectorPlotFillColor': true,
953 'rangeSelectorPlotStrokeColor': true,
954 'showLabelsOnHighlight': true,
958 'underlayCallback': true,
959 'unhighlightCallback': true,
960 'xAxisLabelFormatter': true,
962 'xValueFormatter': true,
963 'yAxisLabelFormatter': true,
964 'yValueFormatter': true,
968 // Assume that we do not require new points.
969 // This will change to true if we actually do need new points.
970 var requiresNewPoints
= false;
972 // Create a dictionary of series names for faster lookup.
973 // If there are no labels, then the dictionary stays empty.
974 var seriesNamesDictionary
= { };
976 for (var i
= 1; i
< labels
.length
; i
++) {
977 seriesNamesDictionary
[labels
[i
]] = true;
981 // Iterate through the list of updated options.
982 for (var property
in attrs
) {
983 // Break early if we already know we need new points from a previous option.
984 if (requiresNewPoints
) {
987 if (attrs
.hasOwnProperty(property
)) {
988 // Find out of this field is actually a series specific options list.
989 if (seriesNamesDictionary
[property
]) {
990 // This property value is a list of options for this series.
991 // If any of these sub properties are not pixel safe, set the flag.
992 for (var subProperty
in attrs
[property
]) {
993 // Break early if we already know we need new points from a previous option.
994 if (requiresNewPoints
) {
997 if (attrs
[property
].hasOwnProperty(subProperty
) && !pixelSafeOptions
[subProperty
]) {
998 requiresNewPoints
= true;
1001 // If this was not a series specific option list, check if its a pixel changing property.
1002 } else if (!pixelSafeOptions
[property
]) {
1003 requiresNewPoints
= true;
1008 return requiresNewPoints
;
1012 * Compares two arrays to see if they are equal. If either parameter is not an
1013 * array it will return false. Does a shallow compare
1014 * Dygraph.compareArrays([[1,2], [3, 4]], [[1,2], [3,4]]) === false.
1015 * @param {!Array.<T>} array1 first array
1016 * @param {!Array.<T>} array2 second array
1017 * @return {boolean} True if both parameters are arrays, and contents are equal.
1020 Dygraph
.compareArrays
= function(array1
, array2
) {
1021 if (!Dygraph
.isArrayLike(array1
) || !Dygraph
.isArrayLike(array2
)) {
1024 if (array1
.length
!== array2
.length
) {
1027 for (var i
= 0; i
< array1
.length
; i
++) {
1028 if (array1
[i
] !== array2
[i
]) {
1036 * @param {!CanvasRenderingContext2D} ctx the canvas context
1037 * @param {number} sides the number of sides in the shape.
1038 * @param {number} radius the radius of the image.
1039 * @param {number} cx center x coordate
1040 * @param {number} cy center y coordinate
1041 * @param {number=} rotationRadians the shift of the initial angle, in radians.
1042 * @param {number=} delta the angle shift for each line. If missing, creates a
1046 Dygraph
.regularShape_
= function(
1047 ctx
, sides
, radius
, cx
, cy
, rotationRadians
, delta
) {
1048 rotationRadians
= rotationRadians
|| 0;
1049 delta
= delta
|| Math
.PI
* 2 / sides
;
1052 var initialAngle
= rotationRadians
;
1053 var angle
= initialAngle
;
1055 var computeCoordinates
= function() {
1056 var x
= cx
+ (Math
.sin(angle
) * radius
);
1057 var y
= cy
+ (-Math
.cos(angle
) * radius
);
1061 var initialCoordinates
= computeCoordinates();
1062 var x
= initialCoordinates
[0];
1063 var y
= initialCoordinates
[1];
1066 for (var idx
= 0; idx
< sides
; idx
++) {
1067 angle
= (idx
== sides
- 1) ? initialAngle
: (angle
+ delta
);
1068 var coords
= computeCoordinates();
1069 ctx
.lineTo(coords
[0], coords
[1]);
1076 * TODO(danvk): be more specific on the return type.
1077 * @param {number} sides
1078 * @param {number=} rotationRadians
1079 * @param {number=} delta
1080 * @return {Function}
1083 Dygraph
.shapeFunction_
= function(sides
, rotationRadians
, delta
) {
1084 return function(g
, name
, ctx
, cx
, cy
, color
, radius
) {
1085 ctx
.strokeStyle
= color
;
1086 ctx
.fillStyle
= "white";
1087 Dygraph
.regularShape_(ctx
, sides
, radius
, cx
, cy
, rotationRadians
, delta
);
1092 DEFAULT
: function(g
, name
, ctx
, canvasx
, canvasy
, color
, radius
) {
1094 ctx
.fillStyle
= color
;
1095 ctx
.arc(canvasx
, canvasy
, radius
, 0, 2 * Math
.PI
, false);
1098 TRIANGLE
: Dygraph
.shapeFunction_(3),
1099 SQUARE
: Dygraph
.shapeFunction_(4, Math
.PI
/ 4),
1100 DIAMOND
: Dygraph
.shapeFunction_(4),
1101 PENTAGON
: Dygraph
.shapeFunction_(5),
1102 HEXAGON
: Dygraph
.shapeFunction_(6),
1103 CIRCLE
: function(g
, name
, ctx
, cx
, cy
, color
, radius
) {
1105 ctx
.strokeStyle
= color
;
1106 ctx
.fillStyle
= "white";
1107 ctx
.arc(cx
, cy
, radius
, 0, 2 * Math
.PI
, false);
1111 STAR
: Dygraph
.shapeFunction_(5, 0, 4 * Math
.PI
/ 5),
1112 PLUS
: function(g
, name
, ctx
, cx
, cy
, color
, radius
) {
1113 ctx
.strokeStyle
= color
;
1116 ctx
.moveTo(cx
+ radius
, cy
);
1117 ctx
.lineTo(cx
- radius
, cy
);
1122 ctx
.moveTo(cx
, cy
+ radius
);
1123 ctx
.lineTo(cx
, cy
- radius
);
1127 EX
: function(g
, name
, ctx
, cx
, cy
, color
, radius
) {
1128 ctx
.strokeStyle
= color
;
1131 ctx
.moveTo(cx
+ radius
, cy
+ radius
);
1132 ctx
.lineTo(cx
- radius
, cy
- radius
);
1137 ctx
.moveTo(cx
+ radius
, cy
- radius
);
1138 ctx
.lineTo(cx
- radius
, cy
+ radius
);
1145 * To create a "drag" interaction, you typically register a mousedown event
1146 * handler on the element where the drag begins. In that handler, you register a
1147 * mouseup handler on the window to determine when the mouse is released,
1148 * wherever that release happens. This works well, except when the user releases
1149 * the mouse over an off-domain iframe. In that case, the mouseup event is
1150 * handled by the iframe and never bubbles up to the window handler.
1152 * To deal with this issue, we cover iframes with high z-index divs to make sure
1153 * they don't capture mouseup.
1156 * element.addEventListener('mousedown', function() {
1157 * var tarper = new Dygraph.IFrameTarp();
1159 * var mouseUpHandler = function() {
1161 * window.removeEventListener(mouseUpHandler);
1164 * window.addEventListener('mouseup', mouseUpHandler);
1169 Dygraph
.IFrameTarp
= function() {
1170 /** @type {Array.<!HTMLDivElement>} */
1175 * Find all the iframes in the document and cover them with high z-index
1178 Dygraph
.IFrameTarp
.prototype.cover
= function() {
1179 var iframes
= document
.getElementsByTagName("iframe");
1180 for (var i
= 0; i
< iframes
.length
; i
++) {
1181 var iframe
= iframes
[i
];
1182 var x
= Dygraph
.findPosX(iframe
),
1183 y
= Dygraph
.findPosY(iframe
),
1184 width
= iframe
.offsetWidth
,
1185 height
= iframe
.offsetHeight
;
1187 var div
= document
.createElement("div");
1188 div
.style
.position
= "absolute";
1189 div
.style
.left
= x
+ 'px';
1190 div
.style
.top
= y
+ 'px';
1191 div
.style
.width
= width
+ 'px';
1192 div
.style
.height
= height
+ 'px';
1193 div
.style
.zIndex
= 999;
1194 document
.body
.appendChild(div
);
1195 this.tarps
.push(div
);
1200 * Remove all the iframe covers. You should call this in a mouseup handler.
1202 Dygraph
.IFrameTarp
.prototype.uncover
= function() {
1203 for (var i
= 0; i
< this.tarps
.length
; i
++) {
1204 this.tarps
[i
].parentNode
.removeChild(this.tarps
[i
]);
1210 * Determine whether |data| is delimited by CR, CRLF, LF, LFCR.
1211 * @param {string} data
1212 * @return {?string} the delimiter that was detected (or null on failure).
1214 Dygraph
.detectLineDelimiter
= function(data
) {
1215 for (var i
= 0; i
< data
.length
; i
++) {
1216 var code
= data
.charAt(i
);
1217 if (code
=== '\r') {
1218 // Might actually be "\r\n".
1219 if (((i
+ 1) < data
.length
) && (data
.charAt(i
+ 1) === '\n')) {
1224 if (code
=== '\n') {
1225 // Might actually be "\n\r".
1226 if (((i
+ 1) < data
.length
) && (data
.charAt(i
+ 1) === '\r')) {
1237 * Is one node contained by another?
1238 * @param {Node} containee The contained node.
1239 * @param {Node} container The container node.
1240 * @return {boolean} Whether containee is inside (or equal to) container.
1243 Dygraph
.isNodeContainedBy
= function(containee
, container
) {
1244 if (container
=== null || containee
=== null) {
1247 var containeeNode
= /** @type {Node} */ (containee
);
1248 while (containeeNode
&& containeeNode
!== container
) {
1249 containeeNode
= containeeNode
.parentNode
;
1251 return (containeeNode
=== container
);
1255 // This masks some numeric issues in older versions of Firefox,
1256 // where 1.0/Math
.pow(10,2) != Math
.pow(10,-2).
1257 /** @type {function(number,number):number} */
1258 Dygraph
.pow
= function(base
, exp
) {
1260 return 1.0 / Math
.pow(base
, -exp
);
1262 return Math
.pow(base
, exp
);
1265 // For Dygraph.setDateSameTZ, below.
1266 Dygraph
.dateSetters
= {
1267 ms
: Date
.prototype.setMilliseconds
,
1268 s
: Date
.prototype.setSeconds
,
1269 m
: Date
.prototype.setMinutes
,
1270 h
: Date
.prototype.setHours
1274 * This is like calling d.setSeconds(), d.setMinutes(), etc, except that it
1275 * adjusts for time zone changes to keep the date/time parts consistent.
1277 * For example, d.getSeconds(), d.getMinutes() and d.getHours() will all be
1278 * the same before/after you call setDateSameTZ(d, {ms: 0}). The same is not
1279 * true if you call d.setMilliseconds(0).
1281 * @type {function(!Date, Object.<number>)}
1283 Dygraph
.setDateSameTZ
= function(d
, parts
) {
1284 var tz
= d
.getTimezoneOffset();
1285 for (var k
in parts
) {
1286 if (!parts
.hasOwnProperty(k
)) continue;
1287 var setter
= Dygraph
.dateSetters
[k
];
1288 if (!setter
) throw "Invalid setter: " + k
;
1289 setter
.call(d
, parts
[k
]);
1290 if (d
.getTimezoneOffset() != tz
) {
1291 d
.setTime(d
.getTime() + (tz
- d
.getTimezoneOffset()) * 60 * 1000);