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 * Return a string version of the hours, minutes and seconds portion of a date.
379 * @param {number} date The JavaScript date (ms since epoch)
380 * @return {string} A time of the form "HH:MM:SS"
383 Dygraph
.hmsString_
= function(date
) {
384 var zeropad
= Dygraph
.zeropad
;
385 var d
= new Date(date
);
386 if (d
.getSeconds()) {
387 return zeropad(d
.getHours()) + ":" +
388 zeropad(d
.getMinutes()) + ":" +
389 zeropad(d
.getSeconds());
391 return zeropad(d
.getHours()) + ":" + zeropad(d
.getMinutes());
396 * Convert a JS date (millis since epoch) to YYYY/MM/DD
397 * @param {number} date The JavaScript date (ms since epoch)
398 * @return {string} A date of the form "YYYY/MM/DD"
401 Dygraph
.dateString_
= function(date
) {
402 var zeropad
= Dygraph
.zeropad
;
403 var d
= new Date(date
);
406 var year
= "" + d
.getFullYear();
407 // Get a 0 padded month string
408 var month
= zeropad(d
.getMonth() + 1); //months are 0-offset, sigh
409 // Get a 0 padded day string
410 var day
= zeropad(d
.getDate());
413 var frac
= d
.getHours() * 3600 + d
.getMinutes() * 60 + d
.getSeconds();
414 if (frac
) ret
= " " + Dygraph
.hmsString_(date
);
416 return year
+ "/" + month + "/" + day
+ ret
;
420 * Round a number to the specified number of digits past the decimal point.
421 * @param {number} num The number to round
422 * @param {number} places The number of decimals to which to round
423 * @return {number} The rounded number
426 Dygraph
.round_
= function(num
, places
) {
427 var shift
= Math
.pow(10, places
);
428 return Math
.round(num
* shift
)/shift
;
432 * Implementation of binary search over an array.
433 * Currently does not work when val is outside the range of arry's values.
434 * @param {number} val the value to search for
435 * @param {Array.<number>} arry is the value over which to search
436 * @param {number} abs If abs > 0, find the lowest entry greater than val
437 * If abs < 0, find the highest entry less than val.
438 * If abs == 0, find the entry that equals val.
439 * @param {number=} low The first index in arry to consider (optional)
440 * @param {number=} high The last index in arry to consider (optional)
441 * @return {number} Index of the element, or -1 if it isn't found.
444 Dygraph
.binarySearch
= function(val
, arry
, abs
, low
, high
) {
445 if (low
=== null || low
=== undefined
||
446 high
=== null || high
=== undefined
) {
448 high
= arry
.length
- 1;
453 if (abs
=== null || abs
=== undefined
) {
456 var validIndex
= function(idx
) {
457 return idx
>= 0 && idx
< arry
.length
;
459 var mid
= parseInt((low
+ high
) / 2, 10);
460 var element
= arry
[mid
];
462 if (element
== val
) {
464 } else if (element
> val
) {
466 // Accept if element > val, but also if prior element < val.
468 if (validIndex(idx
) && arry
[idx
] < val
) {
472 return Dygraph
.binarySearch(val
, arry
, abs
, low
, mid
- 1);
473 } else if (element
< val
) {
475 // Accept if element < val, but also if prior element > val.
477 if (validIndex(idx
) && arry
[idx
] > val
) {
481 return Dygraph
.binarySearch(val
, arry
, abs
, mid
+ 1, high
);
483 return -1; // can't actually happen, but makes closure compiler happy
487 * Parses a date, returning the number of milliseconds since epoch. This can be
488 * passed in as an xValueParser in the Dygraph constructor.
489 * TODO(danvk): enumerate formats that this understands.
491 * @param {string} dateStr A date in a variety of possible string formats.
492 * @return {number} Milliseconds since epoch.
495 Dygraph
.dateParser
= function(dateStr
) {
499 // Let the system try the format first, with one caveat:
500 // YYYY-MM-DD[ HH:MM:SS] is interpreted as UTC by a variety of browsers.
501 // dygraphs displays dates in local time, so this will result in surprising
502 // inconsistencies. But if you specify "T" or "Z" (i.e. YYYY-MM-DDTHH:MM:SS),
503 // then you probably know what you're doing, so we'll let you go ahead.
504 // Issue: http://code.google.com/p/dygraphs/issues/detail
?id
=255
505 if (dateStr
.search("-") == -1 ||
506 dateStr
.search("T") != -1 || dateStr
.search("Z") != -1) {
507 d
= Dygraph
.dateStrToMillis(dateStr
);
508 if (d
&& !isNaN(d
)) return d
;
511 if (dateStr
.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12'
512 dateStrSlashed
= dateStr
.replace("-", "/", "g");
513 while (dateStrSlashed
.search("-") != -1) {
514 dateStrSlashed
= dateStrSlashed
.replace("-", "/");
516 d
= Dygraph
.dateStrToMillis(dateStrSlashed
);
517 } else if (dateStr
.length
== 8) { // e.g. '20090712'
518 // TODO(danvk): remove support for this format. It's confusing.
519 dateStrSlashed
= dateStr
.substr(0,4) + "/" + dateStr.substr(4,2) + "/" +
521 d
= Dygraph
.dateStrToMillis(dateStrSlashed
);
523 // Any format that Date.parse will accept, e.g. "2009/07/12" or
524 // "2009/07/12 12:34:56"
525 d
= Dygraph
.dateStrToMillis(dateStr
);
528 if (!d
|| isNaN(d
)) {
529 console
.error("Couldn't parse " + dateStr
+ " as a date");
535 * This is identical to JavaScript's built-in Date.parse() method, except that
536 * it doesn't get replaced with an incompatible method by aggressive JS
537 * libraries like MooTools or Joomla.
538 * @param {string} str The date string, e.g. "2011/05/06"
539 * @return {number} millis since epoch
542 Dygraph
.dateStrToMillis
= function(str
) {
543 return new Date(str
).getTime();
546 // These functions are all based on MochiKit.
548 * Copies all the properties from o to self.
550 * @param {!Object} self
554 Dygraph
.update
= function(self
, o
) {
555 if (typeof(o
) != 'undefined' && o
!== null) {
557 if (o
.hasOwnProperty(k
)) {
566 * Copies all the properties from o to self.
568 * @param {!Object} self
573 Dygraph
.updateDeep
= function (self
, o
) {
574 // Taken from http://stackoverflow.com/questions
/384286/javascript
-isdom
-how
-do-you
-check
-if-a
-javascript
-object
-is
-a
-dom
-object
577 typeof Node
=== "object" ? o
instanceof Node
:
578 typeof o
=== "object" && typeof o
.nodeType
=== "number" && typeof o
.nodeName
==="string"
582 if (typeof(o
) != 'undefined' && o
!== null) {
584 if (o
.hasOwnProperty(k
)) {
587 } else if (Dygraph
.isArrayLike(o
[k
])) {
588 self
[k
] = o
[k
].slice();
589 } else if (isNode(o
[k
])) {
590 // DOM objects are shallowly-copied.
592 } else if (typeof(o
[k
]) == 'object') {
593 if (typeof(self
[k
]) != 'object' || self
[k
] === null) {
596 Dygraph
.updateDeep(self
[k
], o
[k
]);
611 Dygraph
.isArrayLike
= function(o
) {
614 (typ
!= 'object' && !(typ
== 'function' &&
615 typeof(o
.item
) == 'function')) ||
617 typeof(o
.length
) != 'number' ||
630 Dygraph
.isDateLike
= function (o
) {
631 if (typeof(o
) != "object" || o
=== null ||
632 typeof(o
.getTime
) != 'function') {
639 * Note: this only seems to work for arrays.
644 Dygraph
.clone
= function(o
) {
645 // TODO(danvk): figure out how MochiKit's version works
647 for (var i
= 0; i
< o
.length
; i
++) {
648 if (Dygraph
.isArrayLike(o
[i
])) {
649 r
.push(Dygraph
.clone(o
[i
]));
658 * Create a new canvas element. This is more complex than a simple
659 * document.createElement("canvas") because of IE and excanvas.
661 * @return {!HTMLCanvasElement}
664 Dygraph
.createCanvas
= function() {
665 var canvas
= document
.createElement("canvas");
667 var isIE
= (/MSIE/.test(navigator
.userAgent
) && !window
.opera
);
668 if (isIE
&& (typeof(G_vmlCanvasManager
) != 'undefined')) {
669 canvas
= G_vmlCanvasManager
.initElement(
670 /**@type{!HTMLCanvasElement}*/(canvas
));
677 * Returns the context's pixel ratio, which is the ratio between the device
678 * pixel ratio and the backing store ratio. Typically this is 1 for conventional
679 * displays, and > 1 for HiDPI displays (such as the Retina MBP).
680 * See http://www.html5rocks.com/en/tutorials/canvas/hidpi/ for more details.
682 * @param {!CanvasRenderingContext2D} context The canvas's 2d context.
683 * @return {number} The ratio of the device pixel ratio and the backing store
684 * ratio for the specified context.
686 Dygraph
.getContextPixelRatio
= function(context
) {
688 var devicePixelRatio
= window
.devicePixelRatio
;
689 var backingStoreRatio
= context
.webkitBackingStorePixelRatio
||
690 context
.mozBackingStorePixelRatio
||
691 context
.msBackingStorePixelRatio
||
692 context
.oBackingStorePixelRatio
||
693 context
.backingStorePixelRatio
;
694 if (devicePixelRatio
!== undefined
&&
695 backingStorePixelRatio
!== undefined
) {
696 return devicePixelRatio
/ backingStoreRatio
;
698 // If either value is undefined, the ratio is meaningless so we want to
708 * Checks whether the user is on an Android browser.
709 * Android does not fully support the <canvas> tag, e.g. w/r/t/ clipping.
713 Dygraph
.isAndroid
= function() {
714 return (/Android/).test(navigator
.userAgent
);
719 * TODO(danvk): use @template here when it's better supported for classes.
720 * @param {!Array} array
721 * @param {number} start
722 * @param {number} length
723 * @param {function(!Array,?):boolean=} predicate
726 Dygraph
.Iterator
= function(array
, start
, length
, predicate
) {
728 length
= length
|| array
.length
;
729 this.hasNext
= true; // Use to identify if there's another element.
730 this.peek
= null; // Use for look-ahead
733 this.predicate_
= predicate
;
734 this.end_
= Math
.min(array
.length
, start
+ length
);
735 this.nextIdx_
= start
- 1; // use -1 so initial advance works.
736 this.next(); // ignoring result.
742 Dygraph
.Iterator
.prototype.next
= function() {
748 var nextIdx
= this.nextIdx_
+ 1;
750 while (nextIdx
< this.end_
) {
751 if (!this.predicate_
|| this.predicate_(this.array_
, nextIdx
)) {
752 this.peek
= this.array_
[nextIdx
];
758 this.nextIdx_
= nextIdx
;
760 this.hasNext
= false;
767 * Returns a new iterator over array, between indexes start and
768 * start + length, and only returns entries that pass the accept function
770 * @param {!Array} array the array to iterate over.
771 * @param {number} start the first index to iterate over, 0 if absent.
772 * @param {number} length the number of elements in the array to iterate over.
773 * This, along with start, defines a slice of the array, and so length
774 * doesn't imply the number of elements in the iterator when accept doesn't
775 * always accept all values. array.length when absent.
776 * @param {function(?):boolean=} opt_predicate a function that takes
777 * parameters array and idx, which returns true when the element should be
778 * returned. If omitted, all elements are accepted.
781 Dygraph
.createIterator
= function(array
, start
, length
, opt_predicate
) {
782 return new Dygraph
.Iterator(array
, start
, length
, opt_predicate
);
785 // Shim layer with setTimeout fallback.
786 // From: http://paulirish.com/2011/requestanimationframe-for-smart-animating/
787 // Should be called with the window context:
788 // Dygraph.requestAnimFrame.call(window, function() {})
789 Dygraph
.requestAnimFrame
= (function() {
790 return window
.requestAnimationFrame
||
791 window
.webkitRequestAnimationFrame
||
792 window
.mozRequestAnimationFrame
||
793 window
.oRequestAnimationFrame
||
794 window
.msRequestAnimationFrame
||
795 function (callback
) {
796 window
.setTimeout(callback
, 1000 / 60);
801 * Call a function at most maxFrames times at an attempted interval of
802 * framePeriodInMillis, then call a cleanup function once. repeatFn is called
803 * once immediately, then at most (maxFrames - 1) times asynchronously. If
804 * maxFrames==1, then cleanup_fn() is also called synchronously. This function
805 * is used to sequence animation.
806 * @param {function(number)} repeatFn Called repeatedly -- takes the frame
807 * number (from 0 to maxFrames-1) as an argument.
808 * @param {number} maxFrames The max number of times to call repeatFn
809 * @param {number} framePeriodInMillis Max requested time between frames.
810 * @param {function()} cleanupFn A function to call after all repeatFn calls.
813 Dygraph
.repeatAndCleanup
= function(repeatFn
, maxFrames
, framePeriodInMillis
,
816 var previousFrameNumber
;
817 var startTime
= new Date().getTime();
818 repeatFn(frameNumber
);
819 if (maxFrames
== 1) {
823 var maxFrameArg
= maxFrames
- 1;
826 if (frameNumber
>= maxFrames
) return;
827 Dygraph
.requestAnimFrame
.call(window
, function() {
828 // Determine which frame to draw based on the delay so far. Will skip
829 // frames if necessary.
830 var currentTime
= new Date().getTime();
831 var delayInMillis
= currentTime
- startTime
;
832 previousFrameNumber
= frameNumber
;
833 frameNumber
= Math
.floor(delayInMillis
/ framePeriodInMillis
);
834 var frameDelta
= frameNumber
- previousFrameNumber
;
835 // If we predict that the subsequent repeatFn call will overshoot our
836 // total frame target, so our last call will cause a stutter, then jump to
837 // the last call immediately. If we're going to cause a stutter, better
838 // to do it faster than slower.
839 var predictOvershootStutter
= (frameNumber
+ frameDelta
) > maxFrameArg
;
840 if (predictOvershootStutter
|| (frameNumber
>= maxFrameArg
)) {
841 repeatFn(maxFrameArg
); // Ensure final call with maxFrameArg.
844 if (frameDelta
!== 0) { // Don't call repeatFn with duplicate frames.
845 repeatFn(frameNumber
);
854 * This function will scan the option list and determine if they
855 * require us to recalculate the pixel positions of each point.
856 * @param {!Array.<string>} labels a list of options to check.
857 * @param {!Object} attrs
858 * @return {boolean} true if the graph needs new points else false.
861 Dygraph
.isPixelChangingOptionList
= function(labels
, attrs
) {
862 // A whitelist of options that do not change pixel positions.
863 var pixelSafeOptions
= {
864 'annotationClickHandler': true,
865 'annotationDblClickHandler': true,
866 'annotationMouseOutHandler': true,
867 'annotationMouseOverHandler': true,
868 'axisLabelColor': true,
869 'axisLineColor': true,
870 'axisLineWidth': true,
871 'clickCallback': true,
872 'digitsAfterDecimal': true,
873 'drawCallback': true,
874 'drawHighlightPointCallback': true,
876 'drawPointCallback': true,
880 'gridLineColor': true,
881 'gridLineWidth': true,
882 'hideOverlayOnMouseOut': true,
883 'highlightCallback': true,
884 'highlightCircleSize': true,
885 'interactionModel': true,
886 'isZoomedIgnoreProgrammaticZoom': true,
888 'labelsDivStyles': true,
889 'labelsDivWidth': true,
892 'labelsSeparateLines': true,
893 'labelsShowZeroValues': true,
895 'maxNumberWidth': true,
896 'panEdgeFraction': true,
897 'pixelsPerYLabel': true,
898 'pointClickCallback': true,
900 'rangeSelectorPlotFillColor': true,
901 'rangeSelectorPlotStrokeColor': true,
902 'showLabelsOnHighlight': true,
906 'underlayCallback': true,
907 'unhighlightCallback': true,
908 'xAxisLabelFormatter': true,
910 'xValueFormatter': true,
911 'yAxisLabelFormatter': true,
912 'yValueFormatter': true,
916 // Assume that we do not require new points.
917 // This will change to true if we actually do need new points.
918 var requiresNewPoints
= false;
920 // Create a dictionary of series names for faster lookup.
921 // If there are no labels, then the dictionary stays empty.
922 var seriesNamesDictionary
= { };
924 for (var i
= 1; i
< labels
.length
; i
++) {
925 seriesNamesDictionary
[labels
[i
]] = true;
929 // Iterate through the list of updated options.
930 for (var property
in attrs
) {
931 // Break early if we already know we need new points from a previous option.
932 if (requiresNewPoints
) {
935 if (attrs
.hasOwnProperty(property
)) {
936 // Find out of this field is actually a series specific options list.
937 if (seriesNamesDictionary
[property
]) {
938 // This property value is a list of options for this series.
939 // If any of these sub properties are not pixel safe, set the flag.
940 for (var subProperty
in attrs
[property
]) {
941 // Break early if we already know we need new points from a previous option.
942 if (requiresNewPoints
) {
945 if (attrs
[property
].hasOwnProperty(subProperty
) && !pixelSafeOptions
[subProperty
]) {
946 requiresNewPoints
= true;
949 // If this was not a series specific option list, check if its a pixel changing property.
950 } else if (!pixelSafeOptions
[property
]) {
951 requiresNewPoints
= true;
956 return requiresNewPoints
;
960 DEFAULT
: function(g
, name
, ctx
, canvasx
, canvasy
, color
, radius
) {
962 ctx
.fillStyle
= color
;
963 ctx
.arc(canvasx
, canvasy
, radius
, 0, 2 * Math
.PI
, false);
966 // For more shapes, include extras/shapes.js
970 * To create a "drag" interaction, you typically register a mousedown event
971 * handler on the element where the drag begins. In that handler, you register a
972 * mouseup handler on the window to determine when the mouse is released,
973 * wherever that release happens. This works well, except when the user releases
974 * the mouse over an off-domain iframe. In that case, the mouseup event is
975 * handled by the iframe and never bubbles up to the window handler.
977 * To deal with this issue, we cover iframes with high z-index divs to make sure
978 * they don't capture mouseup.
981 * element.addEventListener('mousedown', function() {
982 * var tarper = new Dygraph.IFrameTarp();
984 * var mouseUpHandler = function() {
986 * window.removeEventListener(mouseUpHandler);
989 * window.addEventListener('mouseup', mouseUpHandler);
994 Dygraph
.IFrameTarp
= function() {
995 /** @type {Array.<!HTMLDivElement>} */
1000 * Find all the iframes in the document and cover them with high z-index
1003 Dygraph
.IFrameTarp
.prototype.cover
= function() {
1004 var iframes
= document
.getElementsByTagName("iframe");
1005 for (var i
= 0; i
< iframes
.length
; i
++) {
1006 var iframe
= iframes
[i
];
1007 var pos
= Dygraph
.findPos(iframe
),
1010 width
= iframe
.offsetWidth
,
1011 height
= iframe
.offsetHeight
;
1013 var div
= document
.createElement("div");
1014 div
.style
.position
= "absolute";
1015 div
.style
.left
= x
+ 'px';
1016 div
.style
.top
= y
+ 'px';
1017 div
.style
.width
= width
+ 'px';
1018 div
.style
.height
= height
+ 'px';
1019 div
.style
.zIndex
= 999;
1020 document
.body
.appendChild(div
);
1021 this.tarps
.push(div
);
1026 * Remove all the iframe covers. You should call this in a mouseup handler.
1028 Dygraph
.IFrameTarp
.prototype.uncover
= function() {
1029 for (var i
= 0; i
< this.tarps
.length
; i
++) {
1030 this.tarps
[i
].parentNode
.removeChild(this.tarps
[i
]);
1036 * Determine whether |data| is delimited by CR, CRLF, LF, LFCR.
1037 * @param {string} data
1038 * @return {?string} the delimiter that was detected (or null on failure).
1040 Dygraph
.detectLineDelimiter
= function(data
) {
1041 for (var i
= 0; i
< data
.length
; i
++) {
1042 var code
= data
.charAt(i
);
1043 if (code
=== '\r') {
1044 // Might actually be "\r\n".
1045 if (((i
+ 1) < data
.length
) && (data
.charAt(i
+ 1) === '\n')) {
1050 if (code
=== '\n') {
1051 // Might actually be "\n\r".
1052 if (((i
+ 1) < data
.length
) && (data
.charAt(i
+ 1) === '\r')) {
1063 * Is one node contained by another?
1064 * @param {Node} containee The contained node.
1065 * @param {Node} container The container node.
1066 * @return {boolean} Whether containee is inside (or equal to) container.
1069 Dygraph
.isNodeContainedBy
= function(containee
, container
) {
1070 if (container
=== null || containee
=== null) {
1073 var containeeNode
= /** @type {Node} */ (containee
);
1074 while (containeeNode
&& containeeNode
!== container
) {
1075 containeeNode
= containeeNode
.parentNode
;
1077 return (containeeNode
=== container
);
1081 // This masks some numeric issues in older versions of Firefox,
1082 // where 1.0/Math
.pow(10,2) != Math
.pow(10,-2).
1083 /** @type {function(number,number):number} */
1084 Dygraph
.pow
= function(base
, exp
) {
1086 return 1.0 / Math
.pow(base
, -exp
);
1088 return Math
.pow(base
, exp
);
1091 // For Dygraph.setDateSameTZ, below.
1092 Dygraph
.dateSetters
= {
1093 ms
: Date
.prototype.setMilliseconds
,
1094 s
: Date
.prototype.setSeconds
,
1095 m
: Date
.prototype.setMinutes
,
1096 h
: Date
.prototype.setHours
1100 * This is like calling d.setSeconds(), d.setMinutes(), etc, except that it
1101 * adjusts for time zone changes to keep the date/time parts consistent.
1103 * For example, d.getSeconds(), d.getMinutes() and d.getHours() will all be
1104 * the same before/after you call setDateSameTZ(d, {ms: 0}). The same is not
1105 * true if you call d.setMilliseconds(0).
1107 * @type {function(!Date, Object.<number>)}
1109 Dygraph
.setDateSameTZ
= function(d
, parts
) {
1110 var tz
= d
.getTimezoneOffset();
1111 for (var k
in parts
) {
1112 if (!parts
.hasOwnProperty(k
)) continue;
1113 var setter
= Dygraph
.dateSetters
[k
];
1114 if (!setter
) throw "Invalid setter: " + k
;
1115 setter
.call(d
, parts
[k
]);
1116 if (d
.getTimezoneOffset() != tz
) {
1117 d
.setTime(d
.getTime() + (tz
- d
.getTimezoneOffset()) * 60 * 1000);
1123 * Converts any valid CSS color (hex, rgb(), named color) to an RGB tuple.
1125 * @param {!string} colorStr Any valid CSS color string.
1126 * @return {{r:number,g:number,b:number}} Parsed RGB tuple.
1129 Dygraph
.toRGB_
= function(colorStr
) {
1130 // TODO(danvk): cache color parses to avoid repeated DOM manipulation.
1131 var div
= document
.createElement('div');
1132 div
.style
.backgroundColor
= colorStr
;
1133 div
.style
.visibility
= 'hidden';
1134 document
.body
.appendChild(div
);
1135 var rgbStr
= window
.getComputedStyle(div
, null).backgroundColor
;
1136 document
.body
.removeChild(div
);
1137 var bits
= /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/.exec(rgbStr
);
1139 r
: parseInt(bits
[1], 10),
1140 g
: parseInt(bits
[2], 10),
1141 b
: parseInt(bits
[3], 10)
1146 * Checks whether the browser supports the <canvas> tag.
1147 * @param {HTMLCanvasElement=} opt_canvasElement Pass a canvas element as an
1148 * optimization if you have one.
1149 * @return {boolean} Whether the browser supports canvas.
1151 Dygraph
.isCanvasSupported
= function(opt_canvasElement
) {
1154 canvas
= opt_canvasElement
|| document
.createElement("canvas");
1155 canvas
.getContext("2d");
1158 var ie
= navigator
.appVersion
.match(/MSIE (\d\.\d)/);
1159 var opera
= (navigator
.userAgent
.toLowerCase().indexOf("opera") != -1);
1160 if ((!ie
) || (ie
[1] < 6) || (opera
))
1168 * Parses the value as a floating point number. This is like the parseFloat()
1169 * built-in, but with a few differences:
1170 * - the empty string is parsed as null, rather than NaN.
1171 * - if the string cannot be parsed at all, an error is logged.
1172 * If the string can't be parsed, this method returns null.
1173 * @param {string} x The string to be parsed
1174 * @param {number=} opt_line_no The line number from which the string comes.
1175 * @param {string=} opt_line The text of the line from which the string comes.
1177 Dygraph
.parseFloat_
= function(x
, opt_line_no
, opt_line
) {
1178 var val
= parseFloat(x
);
1179 if (!isNaN(val
)) return val
;
1181 // Try to figure out what happeend.
1182 // If the value is the empty string, parse it as null.
1183 if (/^ *$/.test(x
)) return null;
1185 // If it was actually "NaN", return it as NaN.
1186 if (/^ *nan *$/i.test(x
)) return NaN
;
1188 // Looks like a parsing error.
1189 var msg
= "Unable to parse '" + x
+ "' as a number";
1190 if (opt_line
!== undefined
&& opt_line_no
!== undefined
) {
1191 msg
+= " on line " + (1+(opt_line_no
||0)) + " ('" + opt_line
+ "') of CSV.";