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 */
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 /** A dotted line stroke pattern. */
31 Dygraph
.DOTTED_LINE
= [2, 2];
32 /** A dashed line stroke pattern. */
33 Dygraph
.DASHED_LINE
= [7, 3];
34 /** A dot dash stroke pattern. */
35 Dygraph
.DOT_DASH_LINE
= [7, 2, 2, 2];
38 * Return the 2d context for a dygraph canvas.
40 * This method is only exposed for the sake of replacing the function in
41 * automated tests, e.g.
43 * var oldFunc = Dygraph.getContext();
44 * Dygraph.getContext = function(canvas) {
45 * var realContext = oldFunc(canvas);
46 * return new Proxy(realContext);
48 * @param {!HTMLCanvasElement} canvas
49 * @return {!CanvasRenderingContext2D}
52 Dygraph
.getContext
= function(canvas
) {
53 return /** @type{!CanvasRenderingContext2D}*/(canvas
.getContext("2d"));
57 * Add an event handler. This smooths a difference between IE and the rest of
59 * @param {!Node} elem The element to add the event to.
60 * @param {string} type The type of the event, e.g. 'click' or 'mousemove'.
61 * @param {function(Event):(boolean|undefined)} fn The function to call
62 * on the event. The function takes one parameter: the event object.
65 Dygraph
.addEvent
= function addEvent(elem
, type
, fn
) {
66 if (elem
.addEventListener
) {
67 elem
.addEventListener(type
, fn
, false);
69 elem
[type
+fn
] = function(){fn(window
.event
);};
70 elem
.attachEvent('on'+type
, elem
[type
+fn
]);
75 * Add an event handler. This event handler is kept until the graph is
76 * destroyed with a call to graph.destroy().
78 * @param {!Node} elem The element to add the event to.
79 * @param {string} type The type of the event, e.g. 'click' or 'mousemove'.
80 * @param {function(Event):(boolean|undefined)} fn The function to call
81 * on the event. The function takes one parameter: the event object.
84 Dygraph
.prototype.addAndTrackEvent
= function(elem
, type
, fn
) {
85 Dygraph
.addEvent(elem
, type
, fn
);
86 this.registeredEvents_
.push({ elem
: elem
, type
: type
, fn
: fn
});
90 * Remove an event handler. This smooths a difference between IE and the rest
92 * @param {!Node} elem The element to remove the event from.
93 * @param {string} type The type of the event, e.g. 'click' or 'mousemove'.
94 * @param {function(Event):(boolean|undefined)} fn The function to call
95 * on the event. The function takes one parameter: the event object.
98 Dygraph
.removeEvent
= function(elem
, type
, fn
) {
99 if (elem
.removeEventListener
) {
100 elem
.removeEventListener(type
, fn
, false);
103 elem
.detachEvent('on'+type
, elem
[type
+fn
]);
105 // We only detach event listeners on a "best effort" basis in IE. See:
106 // http://stackoverflow.com/questions
/2553632/detachevent-not
-working
-with-named
-inline
-functions
108 elem
[type
+fn
] = null;
112 Dygraph
.prototype.removeTrackedEvents_
= function() {
113 if (this.registeredEvents_
) {
114 for (var idx
= 0; idx
< this.registeredEvents_
.length
; idx
++) {
115 var reg
= this.registeredEvents_
[idx
];
116 Dygraph
.removeEvent(reg
.elem
, reg
.type
, reg
.fn
);
120 this.registeredEvents_
= [];
124 * Cancels further processing of an event. This is useful to prevent default
125 * browser actions, e.g. highlighting text on a double-click.
126 * Based on the article at
127 * http://www.switchonthecode.com/tutorials/javascript-tutorial-the-scroll-wheel
128 * @param {!Event} e The event whose normal behavior should be canceled.
131 Dygraph
.cancelEvent
= function(e
) {
132 e
= e
? e
: window
.event
;
133 if (e
.stopPropagation
) {
136 if (e
.preventDefault
) {
139 e
.cancelBubble
= true;
141 e
.returnValue
= false;
146 * Convert hsv values to an rgb(r,g,b) string. Taken from MochiKit.Color. This
147 * is used to generate default series colors which are evenly spaced on the
149 * @param { number } hue Range is 0.0-1.0.
150 * @param { number } saturation Range is 0.0-1.0.
151 * @param { number } value Range is 0.0-1.0.
152 * @return { string } "rgb(r,g,b)" where r, g and b range from 0-255.
155 Dygraph
.hsvToRGB
= function (hue
, saturation
, value
) {
159 if (saturation
=== 0) {
164 var i
= Math
.floor(hue
* 6);
165 var f
= (hue
* 6) - i
;
166 var p
= value
* (1 - saturation
);
167 var q
= value
* (1 - (saturation
* f
));
168 var t
= value
* (1 - (saturation
* (1 - f
)));
170 case 1: red
= q
; green
= value
; blue
= p
; break;
171 case 2: red
= p
; green
= value
; blue
= t
; break;
172 case 3: red
= p
; green
= q
; blue
= value
; break;
173 case 4: red
= t
; green
= p
; blue
= value
; break;
174 case 5: red
= value
; green
= p
; blue
= q
; break;
175 case 6: // fall through
176 case 0: red
= value
; green
= t
; blue
= p
; break;
179 red
= Math
.floor(255 * red
+ 0.5);
180 green
= Math
.floor(255 * green
+ 0.5);
181 blue
= Math
.floor(255 * blue
+ 0.5);
182 return 'rgb(' + red
+ ',' + green
+ ',' + blue
+ ')';
185 // The following functions are from quirksmode.org with a modification for Safari from
186 // http://blog.firetree.net/2005/07/04/javascript-find-position/
187 // http://www.quirksmode.org/js
/findpos
.html
188 // ... and modifications to support scrolling divs.
191 * Find the coordinates of an object relative to the top left of the page.
193 * TODO(danvk): change obj type from Node -> !Node
195 * @return {{x:number,y:number}}
198 Dygraph
.findPos
= function(obj
) {
199 var curleft
= 0, curtop
= 0;
200 if (obj
.offsetParent
) {
203 // NOTE: the if statement here is for IE8.
204 var borderLeft
= "0", borderTop
= "0";
205 if (window
.getComputedStyle
) {
206 var computedStyle
= window
.getComputedStyle(copyObj
, null);
207 borderLeft
= computedStyle
.borderLeft
|| "0";
208 borderTop
= computedStyle
.borderTop
|| "0";
210 curleft
+= parseInt(borderLeft
, 10) ;
211 curtop
+= parseInt(borderTop
, 10) ;
212 curleft
+= copyObj
.offsetLeft
;
213 curtop
+= copyObj
.offsetTop
;
214 if (!copyObj
.offsetParent
) {
217 copyObj
= copyObj
.offsetParent
;
220 // TODO(danvk): why would obj ever have these properties?
221 if (obj
.x
) curleft
+= obj
.x
;
222 if (obj
.y
) curtop
+= obj
.y
;
225 // This handles the case where the object is inside a scrolled div.
226 while (obj
&& obj
!= document
.body
) {
227 curleft
-= obj
.scrollLeft
;
228 curtop
-= obj
.scrollTop
;
229 obj
= obj
.parentNode
;
231 return {x
: curleft
, y
: curtop
};
235 * Returns the x-coordinate of the event in a coordinate system where the
236 * top-left corner of the page (not the window) is (0,0).
237 * Taken from MochiKit.Signal
242 Dygraph
.pageX
= function(e
) {
244 return (!e
.pageX
|| e
.pageX
< 0) ? 0 : e
.pageX
;
246 var de
= document
.documentElement
;
247 var b
= document
.body
;
249 (de
.scrollLeft
|| b
.scrollLeft
) -
250 (de
.clientLeft
|| 0);
255 * Returns the y-coordinate of the event in a coordinate system where the
256 * top-left corner of the page (not the window) is (0,0).
257 * Taken from MochiKit.Signal
262 Dygraph
.pageY
= function(e
) {
264 return (!e
.pageY
|| e
.pageY
< 0) ? 0 : e
.pageY
;
266 var de
= document
.documentElement
;
267 var b
= document
.body
;
269 (de
.scrollTop
|| b
.scrollTop
) -
275 * Converts page the x-coordinate of the event to pixel x-coordinates on the
276 * canvas (i.e. DOM Coords).
277 * @param {!Event} e Drag event.
278 * @param {!DygraphInteractionContext} context Interaction context object.
279 * @return {number} The amount by which the drag has moved to the right.
281 Dygraph
.dragGetX_
= function(e
, context
) {
282 return Dygraph
.pageX(e
) - context
.px
;
286 * Converts page the y-coordinate of the event to pixel y-coordinates on the
287 * canvas (i.e. DOM Coords).
288 * @param {!Event} e Drag event.
289 * @param {!DygraphInteractionContext} context Interaction context object.
290 * @return {number} The amount by which the drag has moved down.
292 Dygraph
.dragGetY_
= function(e
, context
) {
293 return Dygraph
.pageY(e
) - context
.py
;
297 * This returns true unless the parameter is 0, null, undefined or NaN.
298 * TODO(danvk): rename this function to something like 'isNonZeroNan'.
300 * @param {number} x The number to consider.
301 * @return {boolean} Whether the number is zero or NaN.
304 Dygraph
.isOK
= function(x
) {
305 return !!x
&& !isNaN(x
);
309 * @param {{x:?number,y:?number,yval:?number}} p The point to consider, valid
310 * points are {x, y} objects
311 * @param {boolean=} opt_allowNaNY Treat point with y=NaN as valid
312 * @return {boolean} Whether the point has numeric x and y.
315 Dygraph
.isValidPoint
= function(p
, opt_allowNaNY
) {
316 if (!p
) return false; // null or undefined object
317 if (p
.yval
=== null) return false; // missing point
318 if (p
.x
=== null || p
.x
=== undefined
) return false;
319 if (p
.y
=== null || p
.y
=== undefined
) return false;
320 if (isNaN(p
.x
) || (!opt_allowNaNY
&& isNaN(p
.y
))) return false;
325 * Number formatting function which mimicks the behavior of %g in printf, i.e.
326 * either exponential or fixed format (without trailing 0s) is used depending on
327 * the length of the generated string. The advantage of this format is that
328 * there is a predictable upper bound on the resulting string length,
329 * significant figures are not dropped, and normal numbers are not displayed in
330 * exponential notation.
332 * NOTE: JavaScript's native toPrecision() is NOT a drop-in replacement for %g.
333 * It creates strings which are too long for absolute values between 10^-4 and
334 * 10^-6, e.g. '0.00001' instead of '1e-5'. See tests/number-format.html for
337 * @param {number} x The number to format
338 * @param {number=} opt_precision The precision to use, default 2.
339 * @return {string} A string formatted like %g in printf. The max generated
340 * string length should be precision + 6 (e.g 1.123e+300).
342 Dygraph
.floatFormat
= function(x
, opt_precision
) {
343 // Avoid invalid precision values; [1, 21] is the valid range.
344 var p
= Math
.min(Math
.max(1, opt_precision
|| 2), 21);
346 // This is deceptively simple. The actual algorithm comes from:
348 // Max allowed length = p + 4
349 // where 4 comes from 'e+n' and '.'.
351 // Length of fixed format = 2 + y + p
352 // where 2 comes from '0.' and y = # of leading zeroes.
354 // Equating the two and solving for y yields y = 2, or 0.00xxxx which is
357 // Since the behavior of toPrecision() is identical for larger numbers, we
358 // don't have to worry about the other bound.
360 // Finally, the argument for toExponential() is the number of trailing digits,
361 // so we take off 1 for the value before the '.'.
362 return (Math
.abs(x
) < 1.0e-3 && x
!== 0.0) ?
363 x
.toExponential(p
- 1) : x
.toPrecision(p
);
367 * Converts '9' to '09' (useful for dates)
372 Dygraph
.zeropad
= function(x
) {
373 if (x
< 10) return "0" + x
; else return "" + x
;
377 * Date accessors to get the parts of a calendar date (year, month,
378 * day, hour, minute, second and millisecond) according to local time,
379 * and factory method to call the Date constructor with an array of arguments.
381 Dygraph
.DateAccessorsLocal
= {
382 getFullYear
: function(d
) {return d
.getFullYear();},
383 getMonth
: function(d
) {return d
.getMonth();},
384 getDate
: function(d
) {return d
.getDate();},
385 getHours
: function(d
) {return d
.getHours();},
386 getMinutes
: function(d
) {return d
.getMinutes();},
387 getSeconds
: function(d
) {return d
.getSeconds();},
388 getMilliseconds
: function(d
) {return d
.getMilliseconds();},
389 getDay
: function(d
) {return d
.getDay();},
390 makeDate
: function(y
, m
, d
, hh
, mm
, ss
, ms
) {
391 return new Date(y
, m
, d
, hh
, mm
, ss
, ms
);
396 * Date accessors to get the parts of a calendar date (year, month,
397 * day of month, hour, minute, second and millisecond) according to UTC time,
398 * and factory method to call the Date constructor with an array of arguments.
400 Dygraph
.DateAccessorsUTC
= {
401 getFullYear
: function(d
) {return d
.getUTCFullYear();},
402 getMonth
: function(d
) {return d
.getUTCMonth();},
403 getDate
: function(d
) {return d
.getUTCDate();},
404 getHours
: function(d
) {return d
.getUTCHours();},
405 getMinutes
: function(d
) {return d
.getUTCMinutes();},
406 getSeconds
: function(d
) {return d
.getUTCSeconds();},
407 getMilliseconds
: function(d
) {return d
.getUTCMilliseconds();},
408 getDay
: function(d
) {return d
.getUTCDay();},
409 makeDate
: function(y
, m
, d
, hh
, mm
, ss
, ms
) {
410 return new Date(Date
.UTC(y
, m
, d
, hh
, mm
, ss
, ms
));
415 * Return a string version of the hours, minutes and seconds portion of a date.
416 * @param {number} hh The hours (from 0-23)
417 * @param {number} mm The minutes (from 0-59)
418 * @param {number} ss The seconds (from 0-59)
419 * @return {string} A time of the form "HH:MM" or "HH:MM:SS"
422 Dygraph
.hmsString_
= function(hh
, mm
, ss
) {
423 var zeropad
= Dygraph
.zeropad
;
424 var ret
= zeropad(hh
) + ":" + zeropad(mm
);
426 ret
+= ":" + zeropad(ss
);
432 * Convert a JS date (millis since epoch) to a formatted string.
433 * @param {number} time The JavaScript time value (ms since epoch)
434 * @param {boolean} utc Wether output UTC or local time
435 * @return {string} A date of one of these forms:
436 * "YYYY/MM/DD", "YYYY/MM/DD HH:MM" or "YYYY/MM/DD HH:MM:SS"
439 Dygraph
.dateString_
= function(time
, utc
) {
440 var zeropad
= Dygraph
.zeropad
;
441 var accessors
= utc
? Dygraph
.DateAccessorsUTC
: Dygraph
.DateAccessorsLocal
;
442 var date
= new Date(time
);
443 var y
= accessors
.getFullYear(date
);
444 var m
= accessors
.getMonth(date
);
445 var d
= accessors
.getDate(date
);
446 var hh
= accessors
.getHours(date
);
447 var mm
= accessors
.getMinutes(date
);
448 var ss
= accessors
.getSeconds(date
);
449 // Get a year string:
451 // Get a 0 padded month string
452 var month
= zeropad(m
+ 1); //months are 0-offset, sigh
453 // Get a 0 padded day string
454 var day
= zeropad(d
);
455 var frac
= hh
* 3600 + mm
* 60 + ss
;
456 var ret
= year
+ "/" + month + "/" + day
;
458 ret
+= " " + Dygraph
.hmsString_(hh
, mm
, ss
);
464 * Round a number to the specified number of digits past the decimal point.
465 * @param {number} num The number to round
466 * @param {number} places The number of decimals to which to round
467 * @return {number} The rounded number
470 Dygraph
.round_
= function(num
, places
) {
471 var shift
= Math
.pow(10, places
);
472 return Math
.round(num
* shift
)/shift
;
476 * Implementation of binary search over an array.
477 * Currently does not work when val is outside the range of arry's values.
478 * @param {number} val the value to search for
479 * @param {Array.<number>} arry is the value over which to search
480 * @param {number} abs If abs > 0, find the lowest entry greater than val
481 * If abs < 0, find the highest entry less than val.
482 * If abs == 0, find the entry that equals val.
483 * @param {number=} low The first index in arry to consider (optional)
484 * @param {number=} high The last index in arry to consider (optional)
485 * @return {number} Index of the element, or -1 if it isn't found.
488 Dygraph
.binarySearch
= function(val
, arry
, abs
, low
, high
) {
489 if (low
=== null || low
=== undefined
||
490 high
=== null || high
=== undefined
) {
492 high
= arry
.length
- 1;
497 if (abs
=== null || abs
=== undefined
) {
500 var validIndex
= function(idx
) {
501 return idx
>= 0 && idx
< arry
.length
;
503 var mid
= parseInt((low
+ high
) / 2, 10);
504 var element
= arry
[mid
];
506 if (element
== val
) {
508 } else if (element
> val
) {
510 // Accept if element > val, but also if prior element < val.
512 if (validIndex(idx
) && arry
[idx
] < val
) {
516 return Dygraph
.binarySearch(val
, arry
, abs
, low
, mid
- 1);
517 } else if (element
< val
) {
519 // Accept if element < val, but also if prior element > val.
521 if (validIndex(idx
) && arry
[idx
] > val
) {
525 return Dygraph
.binarySearch(val
, arry
, abs
, mid
+ 1, high
);
527 return -1; // can't actually happen, but makes closure compiler happy
531 * Parses a date, returning the number of milliseconds since epoch. This can be
532 * passed in as an xValueParser in the Dygraph constructor.
533 * TODO(danvk): enumerate formats that this understands.
535 * @param {string} dateStr A date in a variety of possible string formats.
536 * @return {number} Milliseconds since epoch.
539 Dygraph
.dateParser
= function(dateStr
) {
543 // Let the system try the format first, with one caveat:
544 // YYYY-MM-DD[ HH:MM:SS] is interpreted as UTC by a variety of browsers.
545 // dygraphs displays dates in local time, so this will result in surprising
546 // inconsistencies. But if you specify "T" or "Z" (i.e. YYYY-MM-DDTHH:MM:SS),
547 // then you probably know what you're doing, so we'll let you go ahead.
548 // Issue: http://code.google.com/p/dygraphs/issues/detail
?id
=255
549 if (dateStr
.search("-") == -1 ||
550 dateStr
.search("T") != -1 || dateStr
.search("Z") != -1) {
551 d
= Dygraph
.dateStrToMillis(dateStr
);
552 if (d
&& !isNaN(d
)) return d
;
555 if (dateStr
.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12'
556 dateStrSlashed
= dateStr
.replace("-", "/", "g");
557 while (dateStrSlashed
.search("-") != -1) {
558 dateStrSlashed
= dateStrSlashed
.replace("-", "/");
560 d
= Dygraph
.dateStrToMillis(dateStrSlashed
);
561 } else if (dateStr
.length
== 8) { // e.g. '20090712'
562 // TODO(danvk): remove support for this format. It's confusing.
563 dateStrSlashed
= dateStr
.substr(0,4) + "/" + dateStr.substr(4,2) + "/" +
565 d
= Dygraph
.dateStrToMillis(dateStrSlashed
);
567 // Any format that Date.parse will accept, e.g. "2009/07/12" or
568 // "2009/07/12 12:34:56"
569 d
= Dygraph
.dateStrToMillis(dateStr
);
572 if (!d
|| isNaN(d
)) {
573 console
.error("Couldn't parse " + dateStr
+ " as a date");
579 * This is identical to JavaScript's built-in Date.parse() method, except that
580 * it doesn't get replaced with an incompatible method by aggressive JS
581 * libraries like MooTools or Joomla.
582 * @param {string} str The date string, e.g. "2011/05/06"
583 * @return {number} millis since epoch
586 Dygraph
.dateStrToMillis
= function(str
) {
587 return new Date(str
).getTime();
590 // These functions are all based on MochiKit.
592 * Copies all the properties from o to self.
594 * @param {!Object} self
598 Dygraph
.update
= function(self
, o
) {
599 if (typeof(o
) != 'undefined' && o
!== null) {
601 if (o
.hasOwnProperty(k
)) {
610 * Copies all the properties from o to self.
612 * @param {!Object} self
617 Dygraph
.updateDeep
= function (self
, o
) {
618 // Taken from http://stackoverflow.com/questions
/384286/javascript
-isdom
-how
-do-you
-check
-if-a
-javascript
-object
-is
-a
-dom
-object
621 typeof Node
=== "object" ? o
instanceof Node
:
622 typeof o
=== "object" && typeof o
.nodeType
=== "number" && typeof o
.nodeName
==="string"
626 if (typeof(o
) != 'undefined' && o
!== null) {
628 if (o
.hasOwnProperty(k
)) {
631 } else if (Dygraph
.isArrayLike(o
[k
])) {
632 self
[k
] = o
[k
].slice();
633 } else if (isNode(o
[k
])) {
634 // DOM objects are shallowly-copied.
636 } else if (typeof(o
[k
]) == 'object') {
637 if (typeof(self
[k
]) != 'object' || self
[k
] === null) {
640 Dygraph
.updateDeep(self
[k
], o
[k
]);
655 Dygraph
.isArrayLike
= function(o
) {
658 (typ
!= 'object' && !(typ
== 'function' &&
659 typeof(o
.item
) == 'function')) ||
661 typeof(o
.length
) != 'number' ||
674 Dygraph
.isDateLike
= function (o
) {
675 if (typeof(o
) != "object" || o
=== null ||
676 typeof(o
.getTime
) != 'function') {
683 * Note: this only seems to work for arrays.
688 Dygraph
.clone
= function(o
) {
689 // TODO(danvk): figure out how MochiKit's version works
691 for (var i
= 0; i
< o
.length
; i
++) {
692 if (Dygraph
.isArrayLike(o
[i
])) {
693 r
.push(Dygraph
.clone(o
[i
]));
702 * Create a new canvas element. This is more complex than a simple
703 * document.createElement("canvas") because of IE and excanvas.
705 * @return {!HTMLCanvasElement}
708 Dygraph
.createCanvas
= function() {
709 var canvas
= document
.createElement("canvas");
711 var isIE
= (/MSIE/.test(navigator
.userAgent
) && !window
.opera
);
712 if (isIE
&& (typeof(G_vmlCanvasManager
) != 'undefined')) {
713 canvas
= G_vmlCanvasManager
.initElement(
714 /**@type{!HTMLCanvasElement}*/(canvas
));
721 * Returns the context's pixel ratio, which is the ratio between the device
722 * pixel ratio and the backing store ratio. Typically this is 1 for conventional
723 * displays, and > 1 for HiDPI displays (such as the Retina MBP).
724 * See http://www.html5rocks.com/en/tutorials/canvas/hidpi/ for more details.
726 * @param {!CanvasRenderingContext2D} context The canvas's 2d context.
727 * @return {number} The ratio of the device pixel ratio and the backing store
728 * ratio for the specified context.
730 Dygraph
.getContextPixelRatio
= function(context
) {
732 var devicePixelRatio
= window
.devicePixelRatio
;
733 var backingStoreRatio
= context
.webkitBackingStorePixelRatio
||
734 context
.mozBackingStorePixelRatio
||
735 context
.msBackingStorePixelRatio
||
736 context
.oBackingStorePixelRatio
||
737 context
.backingStorePixelRatio
|| 1;
738 if (devicePixelRatio
!== undefined
) {
739 return devicePixelRatio
/ backingStoreRatio
;
741 // At least devicePixelRatio must be defined for this ratio to make sense.
742 // We default backingStoreRatio to 1: this does not exist on some browsers
743 // (i.e. desktop Chrome).
752 * Checks whether the user is on an Android browser.
753 * Android does not fully support the <canvas> tag, e.g. w/r/t/ clipping.
757 Dygraph
.isAndroid
= function() {
758 return (/Android/).test(navigator
.userAgent
);
763 * TODO(danvk): use @template here when it's better supported for classes.
764 * @param {!Array} array
765 * @param {number} start
766 * @param {number} length
767 * @param {function(!Array,?):boolean=} predicate
770 Dygraph
.Iterator
= function(array
, start
, length
, predicate
) {
772 length
= length
|| array
.length
;
773 this.hasNext
= true; // Use to identify if there's another element.
774 this.peek
= null; // Use for look-ahead
777 this.predicate_
= predicate
;
778 this.end_
= Math
.min(array
.length
, start
+ length
);
779 this.nextIdx_
= start
- 1; // use -1 so initial advance works.
780 this.next(); // ignoring result.
786 Dygraph
.Iterator
.prototype.next
= function() {
792 var nextIdx
= this.nextIdx_
+ 1;
794 while (nextIdx
< this.end_
) {
795 if (!this.predicate_
|| this.predicate_(this.array_
, nextIdx
)) {
796 this.peek
= this.array_
[nextIdx
];
802 this.nextIdx_
= nextIdx
;
804 this.hasNext
= false;
811 * Returns a new iterator over array, between indexes start and
812 * start + length, and only returns entries that pass the accept function
814 * @param {!Array} array the array to iterate over.
815 * @param {number} start the first index to iterate over, 0 if absent.
816 * @param {number} length the number of elements in the array to iterate over.
817 * This, along with start, defines a slice of the array, and so length
818 * doesn't imply the number of elements in the iterator when accept doesn't
819 * always accept all values. array.length when absent.
820 * @param {function(?):boolean=} opt_predicate a function that takes
821 * parameters array and idx, which returns true when the element should be
822 * returned. If omitted, all elements are accepted.
825 Dygraph
.createIterator
= function(array
, start
, length
, opt_predicate
) {
826 return new Dygraph
.Iterator(array
, start
, length
, opt_predicate
);
829 // Shim layer with setTimeout fallback.
830 // From: http://paulirish.com/2011/requestanimationframe-for-smart-animating/
831 // Should be called with the window context:
832 // Dygraph.requestAnimFrame.call(window, function() {})
833 Dygraph
.requestAnimFrame
= (function() {
834 return window
.requestAnimationFrame
||
835 window
.webkitRequestAnimationFrame
||
836 window
.mozRequestAnimationFrame
||
837 window
.oRequestAnimationFrame
||
838 window
.msRequestAnimationFrame
||
839 function (callback
) {
840 window
.setTimeout(callback
, 1000 / 60);
845 * Call a function at most maxFrames times at an attempted interval of
846 * framePeriodInMillis, then call a cleanup function once. repeatFn is called
847 * once immediately, then at most (maxFrames - 1) times asynchronously. If
848 * maxFrames==1, then cleanup_fn() is also called synchronously. This function
849 * is used to sequence animation.
850 * @param {function(number)} repeatFn Called repeatedly -- takes the frame
851 * number (from 0 to maxFrames-1) as an argument.
852 * @param {number} maxFrames The max number of times to call repeatFn
853 * @param {number} framePeriodInMillis Max requested time between frames.
854 * @param {function()} cleanupFn A function to call after all repeatFn calls.
857 Dygraph
.repeatAndCleanup
= function(repeatFn
, maxFrames
, framePeriodInMillis
,
860 var previousFrameNumber
;
861 var startTime
= new Date().getTime();
862 repeatFn(frameNumber
);
863 if (maxFrames
== 1) {
867 var maxFrameArg
= maxFrames
- 1;
870 if (frameNumber
>= maxFrames
) return;
871 Dygraph
.requestAnimFrame
.call(window
, function() {
872 // Determine which frame to draw based on the delay so far. Will skip
873 // frames if necessary.
874 var currentTime
= new Date().getTime();
875 var delayInMillis
= currentTime
- startTime
;
876 previousFrameNumber
= frameNumber
;
877 frameNumber
= Math
.floor(delayInMillis
/ framePeriodInMillis
);
878 var frameDelta
= frameNumber
- previousFrameNumber
;
879 // If we predict that the subsequent repeatFn call will overshoot our
880 // total frame target, so our last call will cause a stutter, then jump to
881 // the last call immediately. If we're going to cause a stutter, better
882 // to do it faster than slower.
883 var predictOvershootStutter
= (frameNumber
+ frameDelta
) > maxFrameArg
;
884 if (predictOvershootStutter
|| (frameNumber
>= maxFrameArg
)) {
885 repeatFn(maxFrameArg
); // Ensure final call with maxFrameArg.
888 if (frameDelta
!== 0) { // Don't call repeatFn with duplicate frames.
889 repeatFn(frameNumber
);
898 * This function will scan the option list and determine if they
899 * require us to recalculate the pixel positions of each point.
900 * @param {!Array.<string>} labels a list of options to check.
901 * @param {!Object} attrs
902 * @return {boolean} true if the graph needs new points else false.
905 Dygraph
.isPixelChangingOptionList
= function(labels
, attrs
) {
906 // A whitelist of options that do not change pixel positions.
907 var pixelSafeOptions
= {
908 'annotationClickHandler': true,
909 'annotationDblClickHandler': true,
910 'annotationMouseOutHandler': true,
911 'annotationMouseOverHandler': true,
912 'axisLabelColor': true,
913 'axisLineColor': true,
914 'axisLineWidth': true,
915 'clickCallback': true,
916 'digitsAfterDecimal': true,
917 'drawCallback': true,
918 'drawHighlightPointCallback': true,
920 'drawPointCallback': true,
924 'gridLineColor': true,
925 'gridLineWidth': true,
926 'hideOverlayOnMouseOut': true,
927 'highlightCallback': true,
928 'highlightCircleSize': true,
929 'interactionModel': true,
930 'isZoomedIgnoreProgrammaticZoom': true,
932 'labelsDivStyles': true,
933 'labelsDivWidth': true,
936 'labelsSeparateLines': true,
937 'labelsShowZeroValues': true,
939 'maxNumberWidth': true,
940 'panEdgeFraction': true,
941 'pixelsPerYLabel': true,
942 'pointClickCallback': true,
944 'rangeSelectorPlotFillColor': true,
945 'rangeSelectorPlotStrokeColor': true,
946 'showLabelsOnHighlight': true,
950 'underlayCallback': true,
951 'unhighlightCallback': true,
952 'xAxisLabelFormatter': true,
954 'xValueFormatter': true,
955 'yAxisLabelFormatter': true,
956 'yValueFormatter': true,
960 // Assume that we do not require new points.
961 // This will change to true if we actually do need new points.
962 var requiresNewPoints
= false;
964 // Create a dictionary of series names for faster lookup.
965 // If there are no labels, then the dictionary stays empty.
966 var seriesNamesDictionary
= { };
968 for (var i
= 1; i
< labels
.length
; i
++) {
969 seriesNamesDictionary
[labels
[i
]] = true;
973 // Iterate through the list of updated options.
974 for (var property
in attrs
) {
975 // Break early if we already know we need new points from a previous option.
976 if (requiresNewPoints
) {
979 if (attrs
.hasOwnProperty(property
)) {
980 // Find out of this field is actually a series specific options list.
981 if (seriesNamesDictionary
[property
]) {
982 // This property value is a list of options for this series.
983 // If any of these sub properties are not pixel safe, set the flag.
984 for (var subProperty
in attrs
[property
]) {
985 // Break early if we already know we need new points from a previous option.
986 if (requiresNewPoints
) {
989 if (attrs
[property
].hasOwnProperty(subProperty
) && !pixelSafeOptions
[subProperty
]) {
990 requiresNewPoints
= true;
993 // If this was not a series specific option list, check if its a pixel changing property.
994 } else if (!pixelSafeOptions
[property
]) {
995 requiresNewPoints
= true;
1000 return requiresNewPoints
;
1004 DEFAULT
: function(g
, name
, ctx
, canvasx
, canvasy
, color
, radius
) {
1006 ctx
.fillStyle
= color
;
1007 ctx
.arc(canvasx
, canvasy
, radius
, 0, 2 * Math
.PI
, false);
1010 // For more shapes, include extras/shapes.js
1014 * To create a "drag" interaction, you typically register a mousedown event
1015 * handler on the element where the drag begins. In that handler, you register a
1016 * mouseup handler on the window to determine when the mouse is released,
1017 * wherever that release happens. This works well, except when the user releases
1018 * the mouse over an off-domain iframe. In that case, the mouseup event is
1019 * handled by the iframe and never bubbles up to the window handler.
1021 * To deal with this issue, we cover iframes with high z-index divs to make sure
1022 * they don't capture mouseup.
1025 * element.addEventListener('mousedown', function() {
1026 * var tarper = new Dygraph.IFrameTarp();
1028 * var mouseUpHandler = function() {
1030 * window.removeEventListener(mouseUpHandler);
1033 * window.addEventListener('mouseup', mouseUpHandler);
1038 Dygraph
.IFrameTarp
= function() {
1039 /** @type {Array.<!HTMLDivElement>} */
1044 * Find all the iframes in the document and cover them with high z-index
1047 Dygraph
.IFrameTarp
.prototype.cover
= function() {
1048 var iframes
= document
.getElementsByTagName("iframe");
1049 for (var i
= 0; i
< iframes
.length
; i
++) {
1050 var iframe
= iframes
[i
];
1051 var pos
= Dygraph
.findPos(iframe
),
1054 width
= iframe
.offsetWidth
,
1055 height
= iframe
.offsetHeight
;
1057 var div
= document
.createElement("div");
1058 div
.style
.position
= "absolute";
1059 div
.style
.left
= x
+ 'px';
1060 div
.style
.top
= y
+ 'px';
1061 div
.style
.width
= width
+ 'px';
1062 div
.style
.height
= height
+ 'px';
1063 div
.style
.zIndex
= 999;
1064 document
.body
.appendChild(div
);
1065 this.tarps
.push(div
);
1070 * Remove all the iframe covers. You should call this in a mouseup handler.
1072 Dygraph
.IFrameTarp
.prototype.uncover
= function() {
1073 for (var i
= 0; i
< this.tarps
.length
; i
++) {
1074 this.tarps
[i
].parentNode
.removeChild(this.tarps
[i
]);
1080 * Determine whether |data| is delimited by CR, CRLF, LF, LFCR.
1081 * @param {string} data
1082 * @return {?string} the delimiter that was detected (or null on failure).
1084 Dygraph
.detectLineDelimiter
= function(data
) {
1085 for (var i
= 0; i
< data
.length
; i
++) {
1086 var code
= data
.charAt(i
);
1087 if (code
=== '\r') {
1088 // Might actually be "\r\n".
1089 if (((i
+ 1) < data
.length
) && (data
.charAt(i
+ 1) === '\n')) {
1094 if (code
=== '\n') {
1095 // Might actually be "\n\r".
1096 if (((i
+ 1) < data
.length
) && (data
.charAt(i
+ 1) === '\r')) {
1107 * Is one node contained by another?
1108 * @param {Node} containee The contained node.
1109 * @param {Node} container The container node.
1110 * @return {boolean} Whether containee is inside (or equal to) container.
1113 Dygraph
.isNodeContainedBy
= function(containee
, container
) {
1114 if (container
=== null || containee
=== null) {
1117 var containeeNode
= /** @type {Node} */ (containee
);
1118 while (containeeNode
&& containeeNode
!== container
) {
1119 containeeNode
= containeeNode
.parentNode
;
1121 return (containeeNode
=== container
);
1125 // This masks some numeric issues in older versions of Firefox,
1126 // where 1.0/Math
.pow(10,2) != Math
.pow(10,-2).
1127 /** @type {function(number,number):number} */
1128 Dygraph
.pow
= function(base
, exp
) {
1130 return 1.0 / Math
.pow(base
, -exp
);
1132 return Math
.pow(base
, exp
);
1136 * Converts any valid CSS color (hex, rgb(), named color) to an RGB tuple.
1138 * @param {!string} colorStr Any valid CSS color string.
1139 * @return {{r:number,g:number,b:number}} Parsed RGB tuple.
1142 Dygraph
.toRGB_
= function(colorStr
) {
1143 // TODO(danvk): cache color parses to avoid repeated DOM manipulation.
1144 var div
= document
.createElement('div');
1145 div
.style
.backgroundColor
= colorStr
;
1146 div
.style
.visibility
= 'hidden';
1147 document
.body
.appendChild(div
);
1148 var rgbStr
= window
.getComputedStyle(div
, null).backgroundColor
;
1149 document
.body
.removeChild(div
);
1150 var bits
= /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/.exec(rgbStr
);
1152 r
: parseInt(bits
[1], 10),
1153 g
: parseInt(bits
[2], 10),
1154 b
: parseInt(bits
[3], 10)
1159 * Checks whether the browser supports the <canvas> tag.
1160 * @param {HTMLCanvasElement=} opt_canvasElement Pass a canvas element as an
1161 * optimization if you have one.
1162 * @return {boolean} Whether the browser supports canvas.
1164 Dygraph
.isCanvasSupported
= function(opt_canvasElement
) {
1167 canvas
= opt_canvasElement
|| document
.createElement("canvas");
1168 canvas
.getContext("2d");
1171 var ie
= navigator
.appVersion
.match(/MSIE (\d\.\d)/);
1172 var opera
= (navigator
.userAgent
.toLowerCase().indexOf("opera") != -1);
1173 if ((!ie
) || (ie
[1] < 6) || (opera
))
1181 * Parses the value as a floating point number. This is like the parseFloat()
1182 * built-in, but with a few differences:
1183 * - the empty string is parsed as null, rather than NaN.
1184 * - if the string cannot be parsed at all, an error is logged.
1185 * If the string can't be parsed, this method returns null.
1186 * @param {string} x The string to be parsed
1187 * @param {number=} opt_line_no The line number from which the string comes.
1188 * @param {string=} opt_line The text of the line from which the string comes.
1190 Dygraph
.parseFloat_
= function(x
, opt_line_no
, opt_line
) {
1191 var val
= parseFloat(x
);
1192 if (!isNaN(val
)) return val
;
1194 // Try to figure out what happeend.
1195 // If the value is the empty string, parse it as null.
1196 if (/^ *$/.test(x
)) return null;
1198 // If it was actually "NaN", return it as NaN.
1199 if (/^ *nan *$/i.test(x
)) return NaN
;
1201 // Looks like a parsing error.
1202 var msg
= "Unable to parse '" + x
+ "' as a number";
1203 if (opt_line
!== undefined
&& opt_line_no
!== undefined
) {
1204 msg
+= " on line " + (1+(opt_line_no
||0)) + " ('" + opt_line
+ "') of CSV.";