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 // <REMOVE_FOR_COMBINED>
37 // Set this to log stack traces on warnings, etc.
38 // This requires stacktrace.js, which is up to you to provide.
39 // A copy can be found in the dygraphs repo, or at
40 // https://github.com/eriwen
/javascript
-stacktrace
41 Dygraph
.LOG_STACK_TRACES
= false;
42 // </REMOVE_FOR_COMBINED
>
44 /** A dotted line stroke pattern. */
45 Dygraph
.DOTTED_LINE
= [2, 2];
46 /** A dashed line stroke pattern. */
47 Dygraph
.DASHED_LINE
= [7, 3];
48 /** A dot dash stroke pattern. */
49 Dygraph
.DOT_DASH_LINE
= [7, 2, 2, 2];
52 * Log an error on the JS console at the given severity.
53 * @param {number} severity One of Dygraph.{DEBUG,INFO,WARNING,ERROR}
54 * @param {string} message The message to log.
57 Dygraph
.log
= function(severity
, message
) {
58 // <REMOVE_FOR_COMBINED>
60 if (typeof(printStackTrace
) != 'undefined') {
62 // Remove uninteresting bits: logging functions and paths.
63 st
= printStackTrace({guess
:false});
64 while (st
[0].indexOf("stacktrace") != -1) {
69 for (var i
= 0; i
< st
.length
; i
++) {
70 st
[i
] = st
[i
].replace(/\([^)]*\/(.*)\)/, '@$1')
71 .replace(/\@.*\/([^\/]*)/, '@$1')
72 .replace('[object Object].', '');
74 var top_msg
= st
.splice(0, 1)[0];
75 message
+= ' (' + top_msg
.replace(/^.*@ ?/, '') + ')';
77 // Oh well, it was worth a shot!
80 // </REMOVE_FOR_COMBINED
>
82 if (typeof(window
.console
) != 'undefined') {
83 // In older versions of Firefox, only console.log is defined.
84 var console
= window
.console
;
85 var log
= function(console
, method
, msg
) {
86 if (method
&& typeof(method
) == 'function') {
87 method
.call(console
, msg
);
95 log(console
, console
.debug
, 'dygraphs: ' + message
);
98 log(console
, console
.info
, 'dygraphs: ' + message
);
100 case Dygraph
.WARNING
:
101 log(console
, console
.warn
, 'dygraphs: ' + message
);
104 log(console
, console
.error
, 'dygraphs: ' + message
);
109 // <REMOVE_FOR_COMBINED>
110 if (Dygraph
.LOG_STACK_TRACES
) {
111 window
.console
.log(st
.join('\n'));
113 // </REMOVE_FOR_COMBINED
>
117 * @param {string} message
120 Dygraph
.info
= function(message
) {
121 Dygraph
.log(Dygraph
.INFO
, message
);
125 * @param {string} message
128 Dygraph
.warn
= function(message
) {
129 Dygraph
.log(Dygraph
.WARNING
, message
);
133 * @param {string} message
135 Dygraph
.error
= function(message
) {
136 Dygraph
.log(Dygraph
.ERROR
, message
);
140 * Return the 2d context for a dygraph canvas.
142 * This method is only exposed for the sake of replacing the function in
143 * automated tests, e.g.
145 * var oldFunc = Dygraph.getContext();
146 * Dygraph.getContext = function(canvas) {
147 * var realContext = oldFunc(canvas);
148 * return new Proxy(realContext);
150 * @param {!HTMLCanvasElement} canvas
151 * @return {!CanvasRenderingContext2D}
154 Dygraph
.getContext
= function(canvas
) {
155 return /** @type{!CanvasRenderingContext2D}*/(canvas
.getContext("2d"));
159 * Add an event handler. This smooths a difference between IE and the rest of
161 * @param {!Node} elem The element to add the event to.
162 * @param {string} type The type of the event, e.g. 'click' or 'mousemove'.
163 * @param {function(Event):(boolean|undefined)} fn The function to call
164 * on the event. The function takes one parameter: the event object.
167 Dygraph
.addEvent
= function addEvent(elem
, type
, fn
) {
168 if (elem
.addEventListener
) {
169 elem
.addEventListener(type
, fn
, false);
171 elem
[type
+fn
] = function(){fn(window
.event
);};
172 elem
.attachEvent('on'+type
, elem
[type
+fn
]);
177 * Add an event handler. This event handler is kept until the graph is
178 * destroyed with a call to graph.destroy().
180 * @param {!Node} elem The element to add the event to.
181 * @param {string} type The type of the event, e.g. 'click' or 'mousemove'.
182 * @param {function(Event):(boolean|undefined)} fn The function to call
183 * on the event. The function takes one parameter: the event object.
186 Dygraph
.prototype.addAndTrackEvent
= function(elem
, type
, fn
) {
187 Dygraph
.addEvent(elem
, type
, fn
);
188 this.registeredEvents_
.push({ elem
: elem
, type
: type
, fn
: fn
});
192 * Remove an event handler. This smooths a difference between IE and the rest
194 * @param {!Node} elem The element to remove the event from.
195 * @param {string} type The type of the event, e.g. 'click' or 'mousemove'.
196 * @param {function(Event):(boolean|undefined)} fn The function to call
197 * on the event. The function takes one parameter: the event object.
200 Dygraph
.removeEvent
= function(elem
, type
, fn
) {
201 if (elem
.removeEventListener
) {
202 elem
.removeEventListener(type
, fn
, false);
205 elem
.detachEvent('on'+type
, elem
[type
+fn
]);
207 // We only detach event listeners on a "best effort" basis in IE. See:
208 // http://stackoverflow.com/questions
/2553632/detachevent-not
-working
-with-named
-inline
-functions
210 elem
[type
+fn
] = null;
214 Dygraph
.prototype.removeTrackedEvents_
= function() {
215 if (this.registeredEvents_
) {
216 for (var idx
= 0; idx
< this.registeredEvents_
.length
; idx
++) {
217 var reg
= this.registeredEvents_
[idx
];
218 Dygraph
.removeEvent(reg
.elem
, reg
.type
, reg
.fn
);
222 this.registeredEvents_
= [];
226 * Cancels further processing of an event. This is useful to prevent default
227 * browser actions, e.g. highlighting text on a double-click.
228 * Based on the article at
229 * http://www.switchonthecode.com/tutorials/javascript-tutorial-the-scroll-wheel
230 * @param {!Event} e The event whose normal behavior should be canceled.
233 Dygraph
.cancelEvent
= function(e
) {
234 e
= e
? e
: window
.event
;
235 if (e
.stopPropagation
) {
238 if (e
.preventDefault
) {
241 e
.cancelBubble
= true;
243 e
.returnValue
= false;
248 * Convert hsv values to an rgb(r,g,b) string. Taken from MochiKit.Color. This
249 * is used to generate default series colors which are evenly spaced on the
251 * @param { number } hue Range is 0.0-1.0.
252 * @param { number } saturation Range is 0.0-1.0.
253 * @param { number } value Range is 0.0-1.0.
254 * @return { string } "rgb(r,g,b)" where r, g and b range from 0-255.
257 Dygraph
.hsvToRGB
= function (hue
, saturation
, value
) {
261 if (saturation
=== 0) {
266 var i
= Math
.floor(hue
* 6);
267 var f
= (hue
* 6) - i
;
268 var p
= value
* (1 - saturation
);
269 var q
= value
* (1 - (saturation
* f
));
270 var t
= value
* (1 - (saturation
* (1 - f
)));
272 case 1: red
= q
; green
= value
; blue
= p
; break;
273 case 2: red
= p
; green
= value
; blue
= t
; break;
274 case 3: red
= p
; green
= q
; blue
= value
; break;
275 case 4: red
= t
; green
= p
; blue
= value
; break;
276 case 5: red
= value
; green
= p
; blue
= q
; break;
277 case 6: // fall through
278 case 0: red
= value
; green
= t
; blue
= p
; break;
281 red
= Math
.floor(255 * red
+ 0.5);
282 green
= Math
.floor(255 * green
+ 0.5);
283 blue
= Math
.floor(255 * blue
+ 0.5);
284 return 'rgb(' + red
+ ',' + green
+ ',' + blue
+ ')';
287 // The following functions are from quirksmode.org with a modification for Safari from
288 // http://blog.firetree.net/2005/07/04/javascript-find-position/
289 // http://www.quirksmode.org/js
/findpos
.html
290 // ... and modifications to support scrolling divs.
293 * Find the coordinates of an object relative to the top left of the page.
295 * TODO(danvk): change obj type from Node -> !Node
297 * @return {{x:number,y:number}}
300 Dygraph
.findPos
= function(obj
) {
301 var curleft
= 0, curtop
= 0;
302 if (obj
.offsetParent
) {
305 // NOTE: the if statement here is for IE8.
306 var borderLeft
= "0", borderTop
= "0";
307 if (window
.getComputedStyle
) {
308 var computedStyle
= window
.getComputedStyle(copyObj
, null);
309 borderLeft
= computedStyle
.borderLeft
|| "0";
310 borderTop
= computedStyle
.borderTop
|| "0";
312 curleft
+= parseInt(borderLeft
, 10) ;
313 curtop
+= parseInt(borderTop
, 10) ;
314 curleft
+= copyObj
.offsetLeft
;
315 curtop
+= copyObj
.offsetTop
;
316 if (!copyObj
.offsetParent
) {
319 copyObj
= copyObj
.offsetParent
;
322 // TODO(danvk): why would obj ever have these properties?
323 if (obj
.x
) curleft
+= obj
.x
;
324 if (obj
.y
) curtop
+= obj
.y
;
327 // This handles the case where the object is inside a scrolled div.
328 while (obj
&& obj
!= document
.body
) {
329 curleft
-= obj
.scrollLeft
;
330 curtop
-= obj
.scrollTop
;
331 obj
= obj
.parentNode
;
333 return {x
: curleft
, y
: curtop
};
337 * Returns the x-coordinate of the event in a coordinate system where the
338 * top-left corner of the page (not the window) is (0,0).
339 * Taken from MochiKit.Signal
344 Dygraph
.pageX
= function(e
) {
346 return (!e
.pageX
|| e
.pageX
< 0) ? 0 : e
.pageX
;
348 var de
= document
.documentElement
;
349 var b
= document
.body
;
351 (de
.scrollLeft
|| b
.scrollLeft
) -
352 (de
.clientLeft
|| 0);
357 * Returns the y-coordinate of the event in a coordinate system where the
358 * top-left corner of the page (not the window) is (0,0).
359 * Taken from MochiKit.Signal
364 Dygraph
.pageY
= function(e
) {
366 return (!e
.pageY
|| e
.pageY
< 0) ? 0 : e
.pageY
;
368 var de
= document
.documentElement
;
369 var b
= document
.body
;
371 (de
.scrollTop
|| b
.scrollTop
) -
377 * Converts page the x-coordinate of the event to pixel x-coordinates on the
378 * canvas (i.e. DOM Coords).
379 * @param {!Event} e Drag event.
380 * @param {!DygraphInteractionContext} context Interaction context object.
381 * @return {number} The amount by which the drag has moved to the right.
383 Dygraph
.dragGetX_
= function(e
, context
) {
384 return Dygraph
.pageX(e
) - context
.px
;
388 * Converts page the y-coordinate of the event to pixel y-coordinates on the
389 * canvas (i.e. DOM Coords).
390 * @param {!Event} e Drag event.
391 * @param {!DygraphInteractionContext} context Interaction context object.
392 * @return {number} The amount by which the drag has moved down.
394 Dygraph
.dragGetY_
= function(e
, context
) {
395 return Dygraph
.pageY(e
) - context
.py
;
399 * This returns true unless the parameter is 0, null, undefined or NaN.
400 * TODO(danvk): rename this function to something like 'isNonZeroNan'.
402 * @param {number} x The number to consider.
403 * @return {boolean} Whether the number is zero or NaN.
406 Dygraph
.isOK
= function(x
) {
407 return !!x
&& !isNaN(x
);
411 * @param {{x:?number,y:?number,yval:?number}} p The point to consider, valid
412 * points are {x, y} objects
413 * @param {boolean=} opt_allowNaNY Treat point with y=NaN as valid
414 * @return {boolean} Whether the point has numeric x and y.
417 Dygraph
.isValidPoint
= function(p
, opt_allowNaNY
) {
418 if (!p
) return false; // null or undefined object
419 if (p
.yval
=== null) return false; // missing point
420 if (p
.x
=== null || p
.x
=== undefined
) return false;
421 if (p
.y
=== null || p
.y
=== undefined
) return false;
422 if (isNaN(p
.x
) || (!opt_allowNaNY
&& isNaN(p
.y
))) return false;
427 * Number formatting function which mimicks the behavior of %g in printf, i.e.
428 * either exponential or fixed format (without trailing 0s) is used depending on
429 * the length of the generated string. The advantage of this format is that
430 * there is a predictable upper bound on the resulting string length,
431 * significant figures are not dropped, and normal numbers are not displayed in
432 * exponential notation.
434 * NOTE: JavaScript's native toPrecision() is NOT a drop-in replacement for %g.
435 * It creates strings which are too long for absolute values between 10^-4 and
436 * 10^-6, e.g. '0.00001' instead of '1e-5'. See tests/number-format.html for
439 * @param {number} x The number to format
440 * @param {number=} opt_precision The precision to use, default 2.
441 * @return {string} A string formatted like %g in printf. The max generated
442 * string length should be precision + 6 (e.g 1.123e+300).
444 Dygraph
.floatFormat
= function(x
, opt_precision
) {
445 // Avoid invalid precision values; [1, 21] is the valid range.
446 var p
= Math
.min(Math
.max(1, opt_precision
|| 2), 21);
448 // This is deceptively simple. The actual algorithm comes from:
450 // Max allowed length = p + 4
451 // where 4 comes from 'e+n' and '.'.
453 // Length of fixed format = 2 + y + p
454 // where 2 comes from '0.' and y = # of leading zeroes.
456 // Equating the two and solving for y yields y = 2, or 0.00xxxx which is
459 // Since the behavior of toPrecision() is identical for larger numbers, we
460 // don't have to worry about the other bound.
462 // Finally, the argument for toExponential() is the number of trailing digits,
463 // so we take off 1 for the value before the '.'.
464 return (Math
.abs(x
) < 1.0e-3 && x
!== 0.0) ?
465 x
.toExponential(p
- 1) : x
.toPrecision(p
);
469 * Converts '9' to '09' (useful for dates)
474 Dygraph
.zeropad
= function(x
) {
475 if (x
< 10) return "0" + x
; else return "" + x
;
479 * Return a string version of the hours, minutes and seconds portion of a date.
480 * @param {number} hh The hours (from 0-23)
481 * @param {number} mm The minutes (from 0-59)
482 * @param {number} ss The seconds (from 0-59)
483 * @return {string} A time of the form "HH:MM" or "HH:MM:SS"
486 Dygraph
.hmsString_
= function(hh
, mm
, ss
) {
487 var zeropad
= Dygraph
.zeropad
;
488 var ret
= zeropad(hh
) + ":" + zeropad(mm
);
490 ret
+= ":" + zeropad(ss
);
496 * Convert a JS date (millis since epoch) to a formatted string.
497 * @param {number} date The JavaScript date (ms since epoch)
498 * @param {boolean} utc Wether output UTC or local time
499 * @return {string} A date of one of these forms:
500 * "YYYY/MM/DD", "YYYY/MM/DD HH:MM" or "YYYY/MM/DD HH:MM:SS"
503 Dygraph
.dateString_
= function(date
, utc
) {
504 var zeropad
= Dygraph
.zeropad
;
505 var dt
= new Date(date
);
506 var y
, m
, d
, hh
, mm
, ss
;
508 y
= dt
.getUTCFullYear();
509 m
= dt
.getUTCMonth();
511 hh
= dt
.getUTCHours();
512 mm
= dt
.getUTCMinutes();
513 ss
= dt
.getUTCSeconds();
515 y
= dt
.getFullYear();
519 mm
= dt
.getMinutes();
520 ss
= dt
.getSeconds();
522 // Get a year string:
524 // Get a 0 padded month string
525 var month
= zeropad(m
+ 1); //months are 0-offset, sigh
526 // Get a 0 padded day string
527 var day
= zeropad(d
);
528 var frac
= hh
* 3600 + mm
* 60 + ss
;
529 var ret
= year
+ "/" + month + "/" + day
;
531 ret
+= " " + Dygraph
.hmsString_(hh
,mm
,ss
);
537 * Round a number to the specified number of digits past the decimal point.
538 * @param {number} num The number to round
539 * @param {number} places The number of decimals to which to round
540 * @return {number} The rounded number
543 Dygraph
.round_
= function(num
, places
) {
544 var shift
= Math
.pow(10, places
);
545 return Math
.round(num
* shift
)/shift
;
549 * Implementation of binary search over an array.
550 * Currently does not work when val is outside the range of arry's values.
551 * @param {number} val the value to search for
552 * @param {Array.<number>} arry is the value over which to search
553 * @param {number} abs If abs > 0, find the lowest entry greater than val
554 * If abs < 0, find the highest entry less than val.
555 * If abs == 0, find the entry that equals val.
556 * @param {number=} low The first index in arry to consider (optional)
557 * @param {number=} high The last index in arry to consider (optional)
558 * @return {number} Index of the element, or -1 if it isn't found.
561 Dygraph
.binarySearch
= function(val
, arry
, abs
, low
, high
) {
562 if (low
=== null || low
=== undefined
||
563 high
=== null || high
=== undefined
) {
565 high
= arry
.length
- 1;
570 if (abs
=== null || abs
=== undefined
) {
573 var validIndex
= function(idx
) {
574 return idx
>= 0 && idx
< arry
.length
;
576 var mid
= parseInt((low
+ high
) / 2, 10);
577 var element
= arry
[mid
];
579 if (element
== val
) {
581 } else if (element
> val
) {
583 // Accept if element > val, but also if prior element < val.
585 if (validIndex(idx
) && arry
[idx
] < val
) {
589 return Dygraph
.binarySearch(val
, arry
, abs
, low
, mid
- 1);
590 } else if (element
< val
) {
592 // Accept if element < val, but also if prior element > val.
594 if (validIndex(idx
) && arry
[idx
] > val
) {
598 return Dygraph
.binarySearch(val
, arry
, abs
, mid
+ 1, high
);
600 return -1; // can't actually happen, but makes closure compiler happy
604 * Parses a date, returning the number of milliseconds since epoch. This can be
605 * passed in as an xValueParser in the Dygraph constructor.
606 * TODO(danvk): enumerate formats that this understands.
608 * @param {string} dateStr A date in a variety of possible string formats.
609 * @return {number} Milliseconds since epoch.
612 Dygraph
.dateParser
= function(dateStr
) {
616 // Let the system try the format first, with one caveat:
617 // YYYY-MM-DD[ HH:MM:SS] is interpreted as UTC by a variety of browsers.
618 // dygraphs displays dates in local time, so this will result in surprising
619 // inconsistencies. But if you specify "T" or "Z" (i.e. YYYY-MM-DDTHH:MM:SS),
620 // then you probably know what you're doing, so we'll let you go ahead.
621 // Issue: http://code.google.com/p/dygraphs/issues/detail
?id
=255
622 if (dateStr
.search("-") == -1 ||
623 dateStr
.search("T") != -1 || dateStr
.search("Z") != -1) {
624 d
= Dygraph
.dateStrToMillis(dateStr
);
625 if (d
&& !isNaN(d
)) return d
;
628 if (dateStr
.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12'
629 dateStrSlashed
= dateStr
.replace("-", "/", "g");
630 while (dateStrSlashed
.search("-") != -1) {
631 dateStrSlashed
= dateStrSlashed
.replace("-", "/");
633 d
= Dygraph
.dateStrToMillis(dateStrSlashed
);
634 } else if (dateStr
.length
== 8) { // e.g. '20090712'
635 // TODO(danvk): remove support for this format. It's confusing.
636 dateStrSlashed
= dateStr
.substr(0,4) + "/" + dateStr.substr(4,2) + "/" +
638 d
= Dygraph
.dateStrToMillis(dateStrSlashed
);
640 // Any format that Date.parse will accept, e.g. "2009/07/12" or
641 // "2009/07/12 12:34:56"
642 d
= Dygraph
.dateStrToMillis(dateStr
);
645 if (!d
|| isNaN(d
)) {
646 Dygraph
.error("Couldn't parse " + dateStr
+ " as a date");
652 * This is identical to JavaScript's built-in Date.parse() method, except that
653 * it doesn't get replaced with an incompatible method by aggressive JS
654 * libraries like MooTools or Joomla.
655 * @param {string} str The date string, e.g. "2011/05/06"
656 * @return {number} millis since epoch
659 Dygraph
.dateStrToMillis
= function(str
) {
660 return new Date(str
).getTime();
663 // These functions are all based on MochiKit.
665 * Copies all the properties from o to self.
667 * @param {!Object} self
671 Dygraph
.update
= function(self
, o
) {
672 if (typeof(o
) != 'undefined' && o
!== null) {
674 if (o
.hasOwnProperty(k
)) {
683 * Copies all the properties from o to self.
685 * @param {!Object} self
690 Dygraph
.updateDeep
= function (self
, o
) {
691 // Taken from http://stackoverflow.com/questions
/384286/javascript
-isdom
-how
-do-you
-check
-if-a
-javascript
-object
-is
-a
-dom
-object
694 typeof Node
=== "object" ? o
instanceof Node
:
695 typeof o
=== "object" && typeof o
.nodeType
=== "number" && typeof o
.nodeName
==="string"
699 if (typeof(o
) != 'undefined' && o
!== null) {
701 if (o
.hasOwnProperty(k
)) {
704 } else if (Dygraph
.isArrayLike(o
[k
])) {
705 self
[k
] = o
[k
].slice();
706 } else if (isNode(o
[k
])) {
707 // DOM objects are shallowly-copied.
709 } else if (typeof(o
[k
]) == 'object') {
710 if (typeof(self
[k
]) != 'object' || self
[k
] === null) {
713 Dygraph
.updateDeep(self
[k
], o
[k
]);
728 Dygraph
.isArrayLike
= function(o
) {
731 (typ
!= 'object' && !(typ
== 'function' &&
732 typeof(o
.item
) == 'function')) ||
734 typeof(o
.length
) != 'number' ||
747 Dygraph
.isDateLike
= function (o
) {
748 if (typeof(o
) != "object" || o
=== null ||
749 typeof(o
.getTime
) != 'function') {
756 * Note: this only seems to work for arrays.
761 Dygraph
.clone
= function(o
) {
762 // TODO(danvk): figure out how MochiKit's version works
764 for (var i
= 0; i
< o
.length
; i
++) {
765 if (Dygraph
.isArrayLike(o
[i
])) {
766 r
.push(Dygraph
.clone(o
[i
]));
775 * Create a new canvas element. This is more complex than a simple
776 * document.createElement("canvas") because of IE and excanvas.
778 * @return {!HTMLCanvasElement}
781 Dygraph
.createCanvas
= function() {
782 var canvas
= document
.createElement("canvas");
784 var isIE
= (/MSIE/.test(navigator
.userAgent
) && !window
.opera
);
785 if (isIE
&& (typeof(G_vmlCanvasManager
) != 'undefined')) {
786 canvas
= G_vmlCanvasManager
.initElement(
787 /**@type{!HTMLCanvasElement}*/(canvas
));
794 * Checks whether the user is on an Android browser.
795 * Android does not fully support the <canvas> tag, e.g. w/r/t/ clipping.
799 Dygraph
.isAndroid
= function() {
800 return (/Android/).test(navigator
.userAgent
);
805 * TODO(danvk): use @template here when it's better supported for classes.
806 * @param {!Array} array
807 * @param {number} start
808 * @param {number} length
809 * @param {function(!Array,?):boolean=} predicate
812 Dygraph
.Iterator
= function(array
, start
, length
, predicate
) {
814 length
= length
|| array
.length
;
815 this.hasNext
= true; // Use to identify if there's another element.
816 this.peek
= null; // Use for look-ahead
819 this.predicate_
= predicate
;
820 this.end_
= Math
.min(array
.length
, start
+ length
);
821 this.nextIdx_
= start
- 1; // use -1 so initial advance works.
822 this.next(); // ignoring result.
828 Dygraph
.Iterator
.prototype.next
= function() {
834 var nextIdx
= this.nextIdx_
+ 1;
836 while (nextIdx
< this.end_
) {
837 if (!this.predicate_
|| this.predicate_(this.array_
, nextIdx
)) {
838 this.peek
= this.array_
[nextIdx
];
844 this.nextIdx_
= nextIdx
;
846 this.hasNext
= false;
853 * Returns a new iterator over array, between indexes start and
854 * start + length, and only returns entries that pass the accept function
856 * @param {!Array} array the array to iterate over.
857 * @param {number} start the first index to iterate over, 0 if absent.
858 * @param {number} length the number of elements in the array to iterate over.
859 * This, along with start, defines a slice of the array, and so length
860 * doesn't imply the number of elements in the iterator when accept doesn't
861 * always accept all values. array.length when absent.
862 * @param {function(?):boolean=} opt_predicate a function that takes
863 * parameters array and idx, which returns true when the element should be
864 * returned. If omitted, all elements are accepted.
867 Dygraph
.createIterator
= function(array
, start
, length
, opt_predicate
) {
868 return new Dygraph
.Iterator(array
, start
, length
, opt_predicate
);
871 // Shim layer with setTimeout fallback.
872 // From: http://paulirish.com/2011/requestanimationframe-for-smart-animating/
873 // Should be called with the window context:
874 // Dygraph.requestAnimFrame.call(window, function() {})
875 Dygraph
.requestAnimFrame
= (function() {
876 return window
.requestAnimationFrame
||
877 window
.webkitRequestAnimationFrame
||
878 window
.mozRequestAnimationFrame
||
879 window
.oRequestAnimationFrame
||
880 window
.msRequestAnimationFrame
||
881 function (callback
) {
882 window
.setTimeout(callback
, 1000 / 60);
887 * Call a function at most maxFrames times at an attempted interval of
888 * framePeriodInMillis, then call a cleanup function once. repeatFn is called
889 * once immediately, then at most (maxFrames - 1) times asynchronously. If
890 * maxFrames==1, then cleanup_fn() is also called synchronously. This function
891 * is used to sequence animation.
892 * @param {function(number)} repeatFn Called repeatedly -- takes the frame
893 * number (from 0 to maxFrames-1) as an argument.
894 * @param {number} maxFrames The max number of times to call repeatFn
895 * @param {number} framePeriodInMillis Max requested time between frames.
896 * @param {function()} cleanupFn A function to call after all repeatFn calls.
899 Dygraph
.repeatAndCleanup
= function(repeatFn
, maxFrames
, framePeriodInMillis
,
902 var previousFrameNumber
;
903 var startTime
= new Date().getTime();
904 repeatFn(frameNumber
);
905 if (maxFrames
== 1) {
909 var maxFrameArg
= maxFrames
- 1;
912 if (frameNumber
>= maxFrames
) return;
913 Dygraph
.requestAnimFrame
.call(window
, function() {
914 // Determine which frame to draw based on the delay so far. Will skip
915 // frames if necessary.
916 var currentTime
= new Date().getTime();
917 var delayInMillis
= currentTime
- startTime
;
918 previousFrameNumber
= frameNumber
;
919 frameNumber
= Math
.floor(delayInMillis
/ framePeriodInMillis
);
920 var frameDelta
= frameNumber
- previousFrameNumber
;
921 // If we predict that the subsequent repeatFn call will overshoot our
922 // total frame target, so our last call will cause a stutter, then jump to
923 // the last call immediately. If we're going to cause a stutter, better
924 // to do it faster than slower.
925 var predictOvershootStutter
= (frameNumber
+ frameDelta
) > maxFrameArg
;
926 if (predictOvershootStutter
|| (frameNumber
>= maxFrameArg
)) {
927 repeatFn(maxFrameArg
); // Ensure final call with maxFrameArg.
930 if (frameDelta
!== 0) { // Don't call repeatFn with duplicate frames.
931 repeatFn(frameNumber
);
940 * This function will scan the option list and determine if they
941 * require us to recalculate the pixel positions of each point.
942 * @param {!Array.<string>} labels a list of options to check.
943 * @param {!Object} attrs
944 * @return {boolean} true if the graph needs new points else false.
947 Dygraph
.isPixelChangingOptionList
= function(labels
, attrs
) {
948 // A whitelist of options that do not change pixel positions.
949 var pixelSafeOptions
= {
950 'annotationClickHandler': true,
951 'annotationDblClickHandler': true,
952 'annotationMouseOutHandler': true,
953 'annotationMouseOverHandler': true,
954 'axisLabelColor': true,
955 'axisLineColor': true,
956 'axisLineWidth': true,
957 'clickCallback': true,
958 'digitsAfterDecimal': true,
959 'drawCallback': true,
960 'drawHighlightPointCallback': true,
962 'drawPointCallback': true,
966 'gridLineColor': true,
967 'gridLineWidth': true,
968 'hideOverlayOnMouseOut': true,
969 'highlightCallback': true,
970 'highlightCircleSize': true,
971 'interactionModel': true,
972 'isZoomedIgnoreProgrammaticZoom': true,
974 'labelsDivStyles': true,
975 'labelsDivWidth': true,
978 'labelsSeparateLines': true,
979 'labelsShowZeroValues': true,
981 'maxNumberWidth': true,
982 'panEdgeFraction': true,
983 'pixelsPerYLabel': true,
984 'pointClickCallback': true,
986 'rangeSelectorPlotFillColor': true,
987 'rangeSelectorPlotStrokeColor': true,
988 'showLabelsOnHighlight': true,
992 'underlayCallback': true,
993 'unhighlightCallback': true,
994 'xAxisLabelFormatter': true,
996 'xValueFormatter': true,
997 'yAxisLabelFormatter': true,
998 'yValueFormatter': true,
1002 // Assume that we do not require new points.
1003 // This will change to true if we actually do need new points.
1004 var requiresNewPoints
= false;
1006 // Create a dictionary of series names for faster lookup.
1007 // If there are no labels, then the dictionary stays empty.
1008 var seriesNamesDictionary
= { };
1010 for (var i
= 1; i
< labels
.length
; i
++) {
1011 seriesNamesDictionary
[labels
[i
]] = true;
1015 // Iterate through the list of updated options.
1016 for (var property
in attrs
) {
1017 // Break early if we already know we need new points from a previous option.
1018 if (requiresNewPoints
) {
1021 if (attrs
.hasOwnProperty(property
)) {
1022 // Find out of this field is actually a series specific options list.
1023 if (seriesNamesDictionary
[property
]) {
1024 // This property value is a list of options for this series.
1025 // If any of these sub properties are not pixel safe, set the flag.
1026 for (var subProperty
in attrs
[property
]) {
1027 // Break early if we already know we need new points from a previous option.
1028 if (requiresNewPoints
) {
1031 if (attrs
[property
].hasOwnProperty(subProperty
) && !pixelSafeOptions
[subProperty
]) {
1032 requiresNewPoints
= true;
1035 // If this was not a series specific option list, check if its a pixel changing property.
1036 } else if (!pixelSafeOptions
[property
]) {
1037 requiresNewPoints
= true;
1042 return requiresNewPoints
;
1046 DEFAULT
: function(g
, name
, ctx
, canvasx
, canvasy
, color
, radius
) {
1048 ctx
.fillStyle
= color
;
1049 ctx
.arc(canvasx
, canvasy
, radius
, 0, 2 * Math
.PI
, false);
1052 // For more shapes, include extras/shapes.js
1056 * To create a "drag" interaction, you typically register a mousedown event
1057 * handler on the element where the drag begins. In that handler, you register a
1058 * mouseup handler on the window to determine when the mouse is released,
1059 * wherever that release happens. This works well, except when the user releases
1060 * the mouse over an off-domain iframe. In that case, the mouseup event is
1061 * handled by the iframe and never bubbles up to the window handler.
1063 * To deal with this issue, we cover iframes with high z-index divs to make sure
1064 * they don't capture mouseup.
1067 * element.addEventListener('mousedown', function() {
1068 * var tarper = new Dygraph.IFrameTarp();
1070 * var mouseUpHandler = function() {
1072 * window.removeEventListener(mouseUpHandler);
1075 * window.addEventListener('mouseup', mouseUpHandler);
1080 Dygraph
.IFrameTarp
= function() {
1081 /** @type {Array.<!HTMLDivElement>} */
1086 * Find all the iframes in the document and cover them with high z-index
1089 Dygraph
.IFrameTarp
.prototype.cover
= function() {
1090 var iframes
= document
.getElementsByTagName("iframe");
1091 for (var i
= 0; i
< iframes
.length
; i
++) {
1092 var iframe
= iframes
[i
];
1093 var pos
= Dygraph
.findPos(iframe
),
1096 width
= iframe
.offsetWidth
,
1097 height
= iframe
.offsetHeight
;
1099 var div
= document
.createElement("div");
1100 div
.style
.position
= "absolute";
1101 div
.style
.left
= x
+ 'px';
1102 div
.style
.top
= y
+ 'px';
1103 div
.style
.width
= width
+ 'px';
1104 div
.style
.height
= height
+ 'px';
1105 div
.style
.zIndex
= 999;
1106 document
.body
.appendChild(div
);
1107 this.tarps
.push(div
);
1112 * Remove all the iframe covers. You should call this in a mouseup handler.
1114 Dygraph
.IFrameTarp
.prototype.uncover
= function() {
1115 for (var i
= 0; i
< this.tarps
.length
; i
++) {
1116 this.tarps
[i
].parentNode
.removeChild(this.tarps
[i
]);
1122 * Determine whether |data| is delimited by CR, CRLF, LF, LFCR.
1123 * @param {string} data
1124 * @return {?string} the delimiter that was detected (or null on failure).
1126 Dygraph
.detectLineDelimiter
= function(data
) {
1127 for (var i
= 0; i
< data
.length
; i
++) {
1128 var code
= data
.charAt(i
);
1129 if (code
=== '\r') {
1130 // Might actually be "\r\n".
1131 if (((i
+ 1) < data
.length
) && (data
.charAt(i
+ 1) === '\n')) {
1136 if (code
=== '\n') {
1137 // Might actually be "\n\r".
1138 if (((i
+ 1) < data
.length
) && (data
.charAt(i
+ 1) === '\r')) {
1149 * Is one node contained by another?
1150 * @param {Node} containee The contained node.
1151 * @param {Node} container The container node.
1152 * @return {boolean} Whether containee is inside (or equal to) container.
1155 Dygraph
.isNodeContainedBy
= function(containee
, container
) {
1156 if (container
=== null || containee
=== null) {
1159 var containeeNode
= /** @type {Node} */ (containee
);
1160 while (containeeNode
&& containeeNode
!== container
) {
1161 containeeNode
= containeeNode
.parentNode
;
1163 return (containeeNode
=== container
);
1167 // This masks some numeric issues in older versions of Firefox,
1168 // where 1.0/Math
.pow(10,2) != Math
.pow(10,-2).
1169 /** @type {function(number,number):number} */
1170 Dygraph
.pow
= function(base
, exp
) {
1172 return 1.0 / Math
.pow(base
, -exp
);
1174 return Math
.pow(base
, exp
);
1178 * Converts any valid CSS color (hex, rgb(), named color) to an RGB tuple.
1180 * @param {!string} colorStr Any valid CSS color string.
1181 * @return {{r:number,g:number,b:number}} Parsed RGB tuple.
1184 Dygraph
.toRGB_
= function(colorStr
) {
1185 // TODO(danvk): cache color parses to avoid repeated DOM manipulation.
1186 var div
= document
.createElement('div');
1187 div
.style
.backgroundColor
= colorStr
;
1188 div
.style
.visibility
= 'hidden';
1189 document
.body
.appendChild(div
);
1190 var rgbStr
= window
.getComputedStyle(div
, null).backgroundColor
;
1191 document
.body
.removeChild(div
);
1192 var bits
= /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/.exec(rgbStr
);
1194 r
: parseInt(bits
[1], 10),
1195 g
: parseInt(bits
[2], 10),
1196 b
: parseInt(bits
[3], 10)
1201 * Checks whether the browser supports the <canvas> tag.
1202 * @param {HTMLCanvasElement=} opt_canvasElement Pass a canvas element as an
1203 * optimization if you have one.
1204 * @return {boolean} Whether the browser supports canvas.
1206 Dygraph
.isCanvasSupported
= function(opt_canvasElement
) {
1209 canvas
= opt_canvasElement
|| document
.createElement("canvas");
1210 canvas
.getContext("2d");
1213 var ie
= navigator
.appVersion
.match(/MSIE (\d\.\d)/);
1214 var opera
= (navigator
.userAgent
.toLowerCase().indexOf("opera") != -1);
1215 if ((!ie
) || (ie
[1] < 6) || (opera
))
1223 * Parses the value as a floating point number. This is like the parseFloat()
1224 * built-in, but with a few differences:
1225 * - the empty string is parsed as null, rather than NaN.
1226 * - if the string cannot be parsed at all, an error is logged.
1227 * If the string can't be parsed, this method returns null.
1228 * @param {string} x The string to be parsed
1229 * @param {number=} opt_line_no The line number from which the string comes.
1230 * @param {string=} opt_line The text of the line from which the string comes.
1232 Dygraph
.parseFloat_
= function(x
, opt_line_no
, opt_line
) {
1233 var val
= parseFloat(x
);
1234 if (!isNaN(val
)) return val
;
1236 // Try to figure out what happeend.
1237 // If the value is the empty string, parse it as null.
1238 if (/^ *$/.test(x
)) return null;
1240 // If it was actually "NaN", return it as NaN.
1241 if (/^ *nan *$/i.test(x
)) return NaN
;
1243 // Looks like a parsing error.
1244 var msg
= "Unable to parse '" + x
+ "' as a number";
1245 if (opt_line
!== undefined
&& opt_line_no
!== undefined
) {
1246 msg
+= " on line " + (1+(opt_line_no
||0)) + " ('" + opt_line
+ "') of CSV.";