3 * Copyright 2011 Dan Vanderkam (danvdk@gmail.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
8 * @fileoverview This file contains utility functions used by dygraphs. These
9 * are typically static (i.e. not related to any particular dygraph). Examples
10 * include date/time formatting functions, basic algorithms (e.g. binary
11 * search) and generic DOM-manipulation functions.
14 /*jshint globalstrict: true */
15 /*global Dygraph:false, G_vmlCanvasManager:false, Node:false, printStackTrace: false */
18 Dygraph
.LOG_SCALE
= 10;
19 Dygraph
.LN_TEN
= Math
.log(Dygraph
.LOG_SCALE
);
26 Dygraph
.log10
= function(x
) {
27 return Math
.log(x
) / Dygraph
.LN_TEN
;
30 // Various logging levels.
36 // Set this to log stack traces on warnings, etc.
37 // This requires stacktrace.js, which is up to you to provide.
38 // A copy can be found in the dygraphs repo, or at
39 // https://github.com/eriwen
/javascript
-stacktrace
40 Dygraph
.LOG_STACK_TRACES
= false;
42 /** A dotted line stroke pattern. */
43 Dygraph
.DOTTED_LINE
= [2, 2];
44 /** A dashed line stroke pattern. */
45 Dygraph
.DASHED_LINE
= [7, 3];
46 /** A dot dash stroke pattern. */
47 Dygraph
.DOT_DASH_LINE
= [7, 2, 2, 2];
50 * Log an error on the JS console at the given severity.
51 * @param {number} severity One of Dygraph.{DEBUG,INFO,WARNING,ERROR}
52 * @param {string} message The message to log.
55 Dygraph
.log
= function(severity
, message
) {
57 if (typeof(printStackTrace
) != 'undefined') {
59 // Remove uninteresting bits: logging functions and paths.
60 st
= printStackTrace({guess
:false});
61 while (st
[0].indexOf("stacktrace") != -1) {
66 for (var i
= 0; i
< st
.length
; i
++) {
67 st
[i
] = st
[i
].replace(/\([^)]*\/(.*)\)/, '@$1')
68 .replace(/\@.*\/([^\/]*)/, '@$1')
69 .replace('[object Object].', '');
71 var top_msg
= st
.splice(0, 1)[0];
72 message
+= ' (' + top_msg
.replace(/^.*@ ?/, '') + ')';
74 // Oh well, it was worth a shot!
78 if (typeof(window
.console
) != 'undefined') {
81 window
.console
.debug('dygraphs: ' + message
);
84 window
.console
.info('dygraphs: ' + message
);
87 window
.console
.warn('dygraphs: ' + message
);
90 window
.console
.error('dygraphs: ' + message
);
95 if (Dygraph
.LOG_STACK_TRACES
) {
96 window
.console
.log(st
.join('\n'));
101 * @param {string} message
104 Dygraph
.info
= function(message
) {
105 Dygraph
.log(Dygraph
.INFO
, message
);
108 * @param {string} message
111 Dygraph
.prototype.info
= Dygraph
.info
;
114 * @param {string} message
117 Dygraph
.warn
= function(message
) {
118 Dygraph
.log(Dygraph
.WARNING
, message
);
121 * @param {string} message
124 Dygraph
.prototype.warn
= Dygraph
.warn
;
127 * @param {string} message
130 Dygraph
.error
= function(message
) {
131 Dygraph
.log(Dygraph
.ERROR
, message
);
134 * @param {string} message
137 Dygraph
.prototype.error
= Dygraph
.error
;
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 { !Element } 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 { !Element } 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.addEvent
= function addEvent(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 {!Element} elem The element to add the event to.
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 addEvent(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;
215 * Cancels further processing of an event. This is useful to prevent default
216 * browser actions, e.g. highlighting text on a double-click.
217 * Based on the article at
218 * http://www.switchonthecode.com/tutorials/javascript-tutorial-the-scroll-wheel
219 * @param { !Event } e The event whose normal behavior should be canceled.
222 Dygraph
.cancelEvent
= function(e
) {
223 e
= e
? e
: window
.event
;
224 if (e
.stopPropagation
) {
227 if (e
.preventDefault
) {
230 e
.cancelBubble
= true;
232 e
.returnValue
= false;
237 * Convert hsv values to an rgb(r,g,b) string. Taken from MochiKit.Color. This
238 * is used to generate default series colors which are evenly spaced on the
240 * @param { number } hue Range is 0.0-1.0.
241 * @param { number } saturation Range is 0.0-1.0.
242 * @param { number } value Range is 0.0-1.0.
243 * @return { string } "rgb(r,g,b)" where r, g and b range from 0-255.
246 Dygraph
.hsvToRGB
= function (hue
, saturation
, value
) {
250 if (saturation
=== 0) {
255 var i
= Math
.floor(hue
* 6);
256 var f
= (hue
* 6) - i
;
257 var p
= value
* (1 - saturation
);
258 var q
= value
* (1 - (saturation
* f
));
259 var t
= value
* (1 - (saturation
* (1 - f
)));
261 case 1: red
= q
; green
= value
; blue
= p
; break;
262 case 2: red
= p
; green
= value
; blue
= t
; break;
263 case 3: red
= p
; green
= q
; blue
= value
; break;
264 case 4: red
= t
; green
= p
; blue
= value
; break;
265 case 5: red
= value
; green
= p
; blue
= q
; break;
266 case 6: // fall through
267 case 0: red
= value
; green
= t
; blue
= p
; break;
270 red
= Math
.floor(255 * red
+ 0.5);
271 green
= Math
.floor(255 * green
+ 0.5);
272 blue
= Math
.floor(255 * blue
+ 0.5);
273 return 'rgb(' + red
+ ',' + green
+ ',' + blue
+ ')';
276 // The following functions are from quirksmode.org with a modification for Safari from
277 // http://blog.firetree.net/2005/07/04/javascript-find-position/
278 // http://www.quirksmode.org/js
/findpos
.html
279 // ... and modifications to support scrolling divs.
282 * Find the x-coordinate of the supplied object relative to the left side
284 * TODO(danvk): change obj type from Node -> !Node
289 Dygraph
.findPosX
= function(obj
) {
291 if(obj
.offsetParent
) {
294 curleft
+= copyObj
.offsetLeft
;
295 if(!copyObj
.offsetParent
) {
298 copyObj
= copyObj
.offsetParent
;
303 // This handles the case where the object is inside a scrolled div.
304 while(obj
&& obj
!= document
.body
) {
305 curleft
-= obj
.scrollLeft
;
306 obj
= obj
.parentNode
;
312 * Find the y-coordinate of the supplied object relative to the top of the
314 * TODO(danvk): change obj type from Node -> !Node
315 * TODO(danvk): consolidate with findPosX and return an {x, y} object.
320 Dygraph
.findPosY
= function(obj
) {
322 if(obj
.offsetParent
) {
325 curtop
+= copyObj
.offsetTop
;
326 if(!copyObj
.offsetParent
) {
329 copyObj
= copyObj
.offsetParent
;
334 // This handles the case where the object is inside a scrolled div.
335 while(obj
&& obj
!= document
.body
) {
336 curtop
-= obj
.scrollTop
;
337 obj
= obj
.parentNode
;
343 * Returns the x-coordinate of the event in a coordinate system where the
344 * top-left corner of the page (not the window) is (0,0).
345 * Taken from MochiKit.Signal
350 Dygraph
.pageX
= function(e
) {
352 return (!e
.pageX
|| e
.pageX
< 0) ? 0 : e
.pageX
;
354 var de
= document
.documentElement
;
355 var b
= document
.body
;
357 (de
.scrollLeft
|| b
.scrollLeft
) -
358 (de
.clientLeft
|| 0);
363 * Returns the y-coordinate of the event in a coordinate system where the
364 * top-left corner of the page (not the window) is (0,0).
365 * Taken from MochiKit.Signal
370 Dygraph
.pageY
= function(e
) {
372 return (!e
.pageY
|| e
.pageY
< 0) ? 0 : e
.pageY
;
374 var de
= document
.documentElement
;
375 var b
= document
.body
;
377 (de
.scrollTop
|| b
.scrollTop
) -
383 * This returns true unless the parameter is 0, null, undefined or NaN.
384 * TODO(danvk): rename this function to something like 'isNonZeroNan'.
386 * @param {number} x The number to consider.
387 * @return {boolean} Whether the number is zero or NaN.
390 Dygraph
.isOK
= function(x
) {
391 return !!x
&& !isNaN(x
);
395 * @param { {x:?number,y:?number,yval:?number} } p The point to consider, valid
396 * points are {x, y} objects
397 * @param { boolean } allowNaNY Treat point with y=NaN as valid
398 * @return { boolean } Whether the point has numeric x and y.
401 Dygraph
.isValidPoint
= function(p
, allowNaNY
) {
402 if (!p
) return false; // null or undefined object
403 if (p
.yval
=== null) return false; // missing point
404 if (p
.x
=== null || p
.x
=== undefined
) return false;
405 if (p
.y
=== null || p
.y
=== undefined
) return false;
406 if (isNaN(p
.x
) || (!allowNaNY
&& isNaN(p
.y
))) return false;
411 * Number formatting function which mimicks the behavior of %g in printf, i.e.
412 * either exponential or fixed format (without trailing 0s) is used depending on
413 * the length of the generated string. The advantage of this format is that
414 * there is a predictable upper bound on the resulting string length,
415 * significant figures are not dropped, and normal numbers are not displayed in
416 * exponential notation.
418 * NOTE: JavaScript's native toPrecision() is NOT a drop-in replacement for %g.
419 * It creates strings which are too long for absolute values between 10^-4 and
420 * 10^-6, e.g. '0.00001' instead of '1e-5'. See tests/number-format.html for
423 * @param {number} x The number to format
424 * @param {number=} opt_precision The precision to use, default 2.
425 * @return {string} A string formatted like %g in printf. The max generated
426 * string length should be precision + 6 (e.g 1.123e+300).
428 Dygraph
.floatFormat
= function(x
, opt_precision
) {
429 // Avoid invalid precision values; [1, 21] is the valid range.
430 var p
= Math
.min(Math
.max(1, opt_precision
|| 2), 21);
432 // This is deceptively simple. The actual algorithm comes from:
434 // Max allowed length = p + 4
435 // where 4 comes from 'e+n' and '.'.
437 // Length of fixed format = 2 + y + p
438 // where 2 comes from '0.' and y = # of leading zeroes.
440 // Equating the two and solving for y yields y = 2, or 0.00xxxx which is
443 // Since the behavior of toPrecision() is identical for larger numbers, we
444 // don't have to worry about the other bound.
446 // Finally, the argument for toExponential() is the number of trailing digits,
447 // so we take off 1 for the value before the '.'.
448 return (Math
.abs(x
) < 1.0e-3 && x
!== 0.0) ?
449 x
.toExponential(p
- 1) : x
.toPrecision(p
);
453 * Converts '9' to '09' (useful for dates)
458 Dygraph
.zeropad
= function(x
) {
459 if (x
< 10) return "0" + x
; else return "" + x
;
463 * Return a string version of the hours, minutes and seconds portion of a date.
465 * @param {number} date The JavaScript date (ms since epoch)
466 * @return {string} A time of the form "HH:MM:SS"
469 Dygraph
.hmsString_
= function(date
) {
470 var zeropad
= Dygraph
.zeropad
;
471 var d
= new Date(date
);
472 if (d
.getSeconds()) {
473 return zeropad(d
.getHours()) + ":" +
474 zeropad(d
.getMinutes()) + ":" +
475 zeropad(d
.getSeconds());
477 return zeropad(d
.getHours()) + ":" + zeropad(d
.getMinutes());
482 * Round a number to the specified number of digits past the decimal point.
483 * @param {number} num The number to round
484 * @param {number} places The number of decimals to which to round
485 * @return {number} The rounded number
488 Dygraph
.round_
= function(num
, places
) {
489 var shift
= Math
.pow(10, places
);
490 return Math
.round(num
* shift
)/shift
;
494 * Implementation of binary search over an array.
495 * Currently does not work when val is outside the range of arry's values.
496 * @param {number} val the value to search for
497 * @param {Array.<number>} arry is the value over which to search
498 * @param {number} abs If abs > 0, find the lowest entry greater than val
499 * If abs < 0, find the highest entry less than val.
500 * If abs == 0, find the entry that equals val.
501 * @param {number=} low The first index in arry to consider (optional)
502 * @param {number=} high The last index in arry to consider (optional)
503 * @return {number} Index of the element, or -1 if it isn't found.
506 Dygraph
.binarySearch
= function(val
, arry
, abs
, low
, high
) {
507 if (low
=== null || low
=== undefined
||
508 high
=== null || high
=== undefined
) {
510 high
= arry
.length
- 1;
515 if (abs
=== null || abs
=== undefined
) {
518 var validIndex
= function(idx
) {
519 return idx
>= 0 && idx
< arry
.length
;
521 var mid
= parseInt((low
+ high
) / 2, 10);
522 var element
= arry
[mid
];
524 if (element
== val
) {
526 } else if (element
> val
) {
528 // Accept if element > val, but also if prior element < val.
530 if (validIndex(idx
) && arry
[idx
] < val
) {
534 return Dygraph
.binarySearch(val
, arry
, abs
, low
, mid
- 1);
535 } else if (element
< val
) {
537 // Accept if element < val, but also if prior element > val.
539 if (validIndex(idx
) && arry
[idx
] > val
) {
543 return Dygraph
.binarySearch(val
, arry
, abs
, mid
+ 1, high
);
545 return -1; // can't actually happen, but makes closure compiler happy
549 * Parses a date, returning the number of milliseconds since epoch. This can be
550 * passed in as an xValueParser in the Dygraph constructor.
551 * TODO(danvk): enumerate formats that this understands.
553 * @param {string} dateStr A date in a variety of possible string formats.
554 * @return {number} Milliseconds since epoch.
557 Dygraph
.dateParser
= function(dateStr
) {
561 // Let the system try the format first, with one caveat:
562 // YYYY-MM-DD[ HH:MM:SS] is interpreted as UTC by a variety of browsers.
563 // dygraphs displays dates in local time, so this will result in surprising
564 // inconsistencies. But if you specify "T" or "Z" (i.e. YYYY-MM-DDTHH:MM:SS),
565 // then you probably know what you're doing, so we'll let you go ahead.
566 // Issue: http://code.google.com/p/dygraphs/issues/detail
?id
=255
567 if (dateStr
.search("-") == -1 ||
568 dateStr
.search("T") != -1 || dateStr
.search("Z") != -1) {
569 d
= Dygraph
.dateStrToMillis(dateStr
);
570 if (d
&& !isNaN(d
)) return d
;
573 if (dateStr
.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12'
574 dateStrSlashed
= dateStr
.replace("-", "/", "g");
575 while (dateStrSlashed
.search("-") != -1) {
576 dateStrSlashed
= dateStrSlashed
.replace("-", "/");
578 d
= Dygraph
.dateStrToMillis(dateStrSlashed
);
579 } else if (dateStr
.length
== 8) { // e.g. '20090712'
580 // TODO(danvk): remove support for this format. It's confusing.
581 dateStrSlashed
= dateStr
.substr(0,4) + "/" + dateStr.substr(4,2) + "/" +
583 d
= Dygraph
.dateStrToMillis(dateStrSlashed
);
585 // Any format that Date.parse will accept, e.g. "2009/07/12" or
586 // "2009/07/12 12:34:56"
587 d
= Dygraph
.dateStrToMillis(dateStr
);
590 if (!d
|| isNaN(d
)) {
591 Dygraph
.error("Couldn't parse " + dateStr
+ " as a date");
597 * This is identical to JavaScript's built-in Date.parse() method, except that
598 * it doesn't get replaced with an incompatible method by aggressive JS
599 * libraries like MooTools or Joomla.
600 * @param {string} str The date string, e.g. "2011/05/06"
601 * @return {number} millis since epoch
604 Dygraph
.dateStrToMillis
= function(str
) {
605 return new Date(str
).getTime();
608 // These functions are all based on MochiKit.
610 * Copies all the properties from o to self.
612 * @param {!Object} self
617 Dygraph
.update
= function(self
, o
) {
618 if (typeof(o
) != 'undefined' && o
!== null) {
620 if (o
.hasOwnProperty(k
)) {
629 * Copies all the properties from o to self.
631 * @param {!Object} self
636 Dygraph
.updateDeep
= function (self
, o
) {
637 // Taken from http://stackoverflow.com/questions
/384286/javascript
-isdom
-how
-do-you
-check
-if-a
-javascript
-object
-is
-a
-dom
-object
640 typeof Node
=== "object" ? o
instanceof Node
:
641 typeof o
=== "object" && typeof o
.nodeType
=== "number" && typeof o
.nodeName
==="string"
645 if (typeof(o
) != 'undefined' && o
!== null) {
647 if (o
.hasOwnProperty(k
)) {
650 } else if (Dygraph
.isArrayLike(o
[k
])) {
651 self
[k
] = o
[k
].slice();
652 } else if (isNode(o
[k
])) {
653 // DOM objects are shallowly-copied.
655 } else if (typeof(o
[k
]) == 'object') {
656 if (typeof(self
[k
]) != 'object' || self
[k
] === null) {
659 Dygraph
.updateDeep(self
[k
], o
[k
]);
674 Dygraph
.isArrayLike
= function(o
) {
677 (typ
!= 'object' && !(typ
== 'function' &&
678 typeof(o
.item
) == 'function')) ||
680 typeof(o
.length
) != 'number' ||
693 Dygraph
.isDateLike
= function (o
) {
694 if (typeof(o
) != "object" || o
=== null ||
695 typeof(o
.getTime
) != 'function') {
702 * Note: this only seems to work for arrays.
707 Dygraph
.clone
= function(o
) {
708 // TODO(danvk): figure out how MochiKit's version works
710 for (var i
= 0; i
< o
.length
; i
++) {
711 if (Dygraph
.isArrayLike(o
[i
])) {
712 r
.push(Dygraph
.clone(o
[i
]));
721 * Create a new canvas element. This is more complex than a simple
722 * document.createElement("canvas") because of IE and excanvas.
724 * @return {!HTMLCanvasElement}
727 Dygraph
.createCanvas
= function() {
728 var canvas
= document
.createElement("canvas");
730 var isIE
= (/MSIE/.test(navigator
.userAgent
) && !window
.opera
);
731 if (isIE
&& (typeof(G_vmlCanvasManager
) != 'undefined')) {
732 canvas
= G_vmlCanvasManager
.initElement(
733 /**@type{!HTMLCanvasElement}*/(canvas
));
740 * Checks whether the user is on an Android browser.
741 * Android does not fully support the <canvas> tag, e.g. w/r/t/ clipping.
745 Dygraph
.isAndroid
= function() {
746 return (/Android/).test(navigator
.userAgent
);
751 * TODO(danvk): use @template here when it's better supported for classes.
752 * @param {!Array} array
753 * @param {number} start
754 * @param {number} length
755 * @param {function(!Array,?):boolean=} predicate
758 Dygraph
.Iterator
= function(array
, start
, length
, predicate
) {
760 length
= length
|| array
.length
;
761 this.hasNext
= true; // Use to identify if there's another element.
762 this.peek
= null; // Use for look-ahead
765 this.predicate_
= predicate
;
766 this.end_
= Math
.min(array
.length
, start
+ length
);
767 this.nextIdx_
= start
- 1; // use -1 so initial advance works.
768 this.next(); // ignoring result.
774 Dygraph
.Iterator
.prototype.next
= function() {
780 var nextIdx
= this.nextIdx_
+ 1;
782 while (nextIdx
< this.end_
) {
783 if (!this.predicate_
|| this.predicate_(this.array_
, nextIdx
)) {
784 this.peek
= this.array_
[nextIdx
];
790 this.nextIdx_
= nextIdx
;
792 this.hasNext
= false;
799 * Returns a new iterator over array, between indexes start and
800 * start + length, and only returns entries that pass the accept function
802 * @param {!Array} array the array to iterate over.
803 * @param {number} start the first index to iterate over, 0 if absent.
804 * @param {number} length the number of elements in the array to iterate over.
805 * This, along with start, defines a slice of the array, and so length
806 * doesn't imply the number of elements in the iterator when accept doesn't
807 * always accept all values. array.length when absent.
808 * @param {function(?):boolean=} opt_predicate a function that takes
809 * parameters array and idx, which returns true when the element should be
810 * returned. If omitted, all elements are accepted.
813 Dygraph
.createIterator
= function(array
, start
, length
, opt_predicate
) {
814 return new Dygraph
.Iterator(array
, start
, length
, opt_predicate
);
817 // Shim layer with setTimeout fallback.
818 // From: http://paulirish.com/2011/requestanimationframe-for-smart-animating/
819 // Should be called with the window context:
820 // Dygraph.requestAnimFrame.call(window, function() {})
821 Dygraph
.requestAnimFrame
= (function() {
822 return window
.requestAnimationFrame
||
823 window
.webkitRequestAnimationFrame
||
824 window
.mozRequestAnimationFrame
||
825 window
.oRequestAnimationFrame
||
826 window
.msRequestAnimationFrame
||
827 function (callback
) {
828 window
.setTimeout(callback
, 1000 / 60);
833 * Call a function at most maxFrames times at an attempted interval of
834 * framePeriodInMillis, then call a cleanup function once. repeatFn is called
835 * once immediately, then at most (maxFrames - 1) times asynchronously. If
836 * maxFrames==1, then cleanup_fn() is also called synchronously. This function
837 * is used to sequence animation.
838 * @param {function(number)} repeatFn Called repeatedly -- takes the frame
839 * number (from 0 to maxFrames-1) as an argument.
840 * @param {number} maxFrames The max number of times to call repeatFn
841 * @param {number} framePeriodInMillis Max requested time between frames.
842 * @param {function()} cleanupFn A function to call after all repeatFn calls.
845 Dygraph
.repeatAndCleanup
= function(repeatFn
, maxFrames
, framePeriodInMillis
,
848 var previousFrameNumber
;
849 var startTime
= new Date().getTime();
850 repeatFn(frameNumber
);
851 if (maxFrames
== 1) {
855 var maxFrameArg
= maxFrames
- 1;
858 if (frameNumber
>= maxFrames
) return;
859 Dygraph
.requestAnimFrame
.call(window
, function() {
860 // Determine which frame to draw based on the delay so far. Will skip
861 // frames if necessary.
862 var currentTime
= new Date().getTime();
863 var delayInMillis
= currentTime
- startTime
;
864 previousFrameNumber
= frameNumber
;
865 frameNumber
= Math
.floor(delayInMillis
/ framePeriodInMillis
);
866 var frameDelta
= frameNumber
- previousFrameNumber
;
867 // If we predict that the subsequent repeatFn call will overshoot our
868 // total frame target, so our last call will cause a stutter, then jump to
869 // the last call immediately. If we're going to cause a stutter, better
870 // to do it faster than slower.
871 var predictOvershootStutter
= (frameNumber
+ frameDelta
) > maxFrameArg
;
872 if (predictOvershootStutter
|| (frameNumber
>= maxFrameArg
)) {
873 repeatFn(maxFrameArg
); // Ensure final call with maxFrameArg.
876 if (frameDelta
!= 0) { // Don't call repeatFn with duplicate frames.
877 repeatFn(frameNumber
);
886 * This function will scan the option list and determine if they
887 * require us to recalculate the pixel positions of each point.
888 * @param {!Array.<string>} labels a list of options to check.
889 * @param {!Object} attrs
890 * @return {boolean} true if the graph needs new points else false.
893 Dygraph
.isPixelChangingOptionList
= function(labels
, attrs
) {
894 // A whitelist of options that do not change pixel positions.
895 var pixelSafeOptions
= {
896 'annotationClickHandler': true,
897 'annotationDblClickHandler': true,
898 'annotationMouseOutHandler': true,
899 'annotationMouseOverHandler': true,
900 'axisLabelColor': true,
901 'axisLineColor': true,
902 'axisLineWidth': true,
903 'clickCallback': true,
904 'digitsAfterDecimal': true,
905 'drawCallback': true,
906 'drawHighlightPointCallback': true,
908 'drawPointCallback': true,
912 'gridLineColor': true,
913 'gridLineWidth': true,
914 'hideOverlayOnMouseOut': true,
915 'highlightCallback': true,
916 'highlightCircleSize': true,
917 'interactionModel': true,
918 'isZoomedIgnoreProgrammaticZoom': true,
920 'labelsDivStyles': true,
921 'labelsDivWidth': true,
924 'labelsSeparateLines': true,
925 'labelsShowZeroValues': true,
927 'maxNumberWidth': true,
928 'panEdgeFraction': true,
929 'pixelsPerYLabel': true,
930 'pointClickCallback': true,
932 'rangeSelectorPlotFillColor': true,
933 'rangeSelectorPlotStrokeColor': true,
934 'showLabelsOnHighlight': true,
938 'underlayCallback': true,
939 'unhighlightCallback': true,
940 'xAxisLabelFormatter': true,
942 'xValueFormatter': true,
943 'yAxisLabelFormatter': true,
944 'yValueFormatter': true,
948 // Assume that we do not require new points.
949 // This will change to true if we actually do need new points.
950 var requiresNewPoints
= false;
952 // Create a dictionary of series names for faster lookup.
953 // If there are no labels, then the dictionary stays empty.
954 var seriesNamesDictionary
= { };
956 for (var i
= 1; i
< labels
.length
; i
++) {
957 seriesNamesDictionary
[labels
[i
]] = true;
961 // Iterate through the list of updated options.
962 for (var property
in attrs
) {
963 // Break early if we already know we need new points from a previous option.
964 if (requiresNewPoints
) {
967 if (attrs
.hasOwnProperty(property
)) {
968 // Find out of this field is actually a series specific options list.
969 if (seriesNamesDictionary
[property
]) {
970 // This property value is a list of options for this series.
971 // If any of these sub properties are not pixel safe, set the flag.
972 for (var subProperty
in attrs
[property
]) {
973 // Break early if we already know we need new points from a previous option.
974 if (requiresNewPoints
) {
977 if (attrs
[property
].hasOwnProperty(subProperty
) && !pixelSafeOptions
[subProperty
]) {
978 requiresNewPoints
= true;
981 // If this was not a series specific option list, check if its a pixel changing property.
982 } else if (!pixelSafeOptions
[property
]) {
983 requiresNewPoints
= true;
988 return requiresNewPoints
;
992 * Compares two arrays to see if they are equal. If either parameter is not an
993 * array it will return false. Does a shallow compare
994 * Dygraph.compareArrays([[1,2], [3, 4]], [[1,2], [3,4]]) === false.
995 * @param {!Array.<T>} array1 first array
996 * @param {!Array.<T>} array2 second array
997 * @return {boolean} True if both parameters are arrays, and contents are equal.
1000 Dygraph
.compareArrays
= function(array1
, array2
) {
1001 if (!Dygraph
.isArrayLike(array1
) || !Dygraph
.isArrayLike(array2
)) {
1004 if (array1
.length
!== array2
.length
) {
1007 for (var i
= 0; i
< array1
.length
; i
++) {
1008 if (array1
[i
] !== array2
[i
]) {
1016 * @param {!CanvasRenderingContext2D} ctx the canvas context
1017 * @param {number} sides the number of sides in the shape.
1018 * @param {number} radius the radius of the image.
1019 * @param {number} cx center x coordate
1020 * @param {number} cy center y coordinate
1021 * @param {number=} rotationRadians the shift of the initial angle, in radians.
1022 * @param {number=} delta the angle shift for each line. If missing, creates a
1026 Dygraph
.regularShape_
= function(
1027 ctx
, sides
, radius
, cx
, cy
, rotationRadians
, delta
) {
1028 rotationRadians
= rotationRadians
|| 0;
1029 delta
= delta
|| Math
.PI
* 2 / sides
;
1033 var initialAngle
= rotationRadians
;
1034 var angle
= initialAngle
;
1036 var computeCoordinates
= function() {
1037 var x
= cx
+ (Math
.sin(angle
) * radius
);
1038 var y
= cy
+ (-Math
.cos(angle
) * radius
);
1042 var initialCoordinates
= computeCoordinates();
1043 var x
= initialCoordinates
[0];
1044 var y
= initialCoordinates
[1];
1047 for (var idx
= 0; idx
< sides
; idx
++) {
1048 angle
= (idx
== sides
- 1) ? initialAngle
: (angle
+ delta
);
1049 var coords
= computeCoordinates();
1050 ctx
.lineTo(coords
[0], coords
[1]);
1057 * TODO(danvk): be more specific on the return type.
1058 * @param {number} sides
1059 * @param {number=} rotationRadians
1060 * @param {number=} delta
1061 * @return {Function}
1064 Dygraph
.shapeFunction_
= function(sides
, rotationRadians
, delta
) {
1065 return function(g
, name
, ctx
, cx
, cy
, color
, radius
) {
1066 ctx
.strokeStyle
= color
;
1067 ctx
.fillStyle
= "white";
1068 Dygraph
.regularShape_(ctx
, sides
, radius
, cx
, cy
, rotationRadians
, delta
);
1073 DEFAULT
: function(g
, name
, ctx
, canvasx
, canvasy
, color
, radius
) {
1075 ctx
.fillStyle
= color
;
1076 ctx
.arc(canvasx
, canvasy
, radius
, 0, 2 * Math
.PI
, false);
1079 TRIANGLE
: Dygraph
.shapeFunction_(3),
1080 SQUARE
: Dygraph
.shapeFunction_(4, Math
.PI
/ 4),
1081 DIAMOND
: Dygraph
.shapeFunction_(4),
1082 PENTAGON
: Dygraph
.shapeFunction_(5),
1083 HEXAGON
: Dygraph
.shapeFunction_(6),
1084 CIRCLE
: function(g
, name
, ctx
, cx
, cy
, color
, radius
) {
1086 ctx
.strokeStyle
= color
;
1087 ctx
.fillStyle
= "white";
1088 ctx
.arc(cx
, cy
, radius
, 0, 2 * Math
.PI
, false);
1092 STAR
: Dygraph
.shapeFunction_(5, 0, 4 * Math
.PI
/ 5),
1093 PLUS
: function(g
, name
, ctx
, cx
, cy
, color
, radius
) {
1094 ctx
.strokeStyle
= color
;
1097 ctx
.moveTo(cx
+ radius
, cy
);
1098 ctx
.lineTo(cx
- radius
, cy
);
1103 ctx
.moveTo(cx
, cy
+ radius
);
1104 ctx
.lineTo(cx
, cy
- radius
);
1108 EX
: function(g
, name
, ctx
, cx
, cy
, color
, radius
) {
1109 ctx
.strokeStyle
= color
;
1112 ctx
.moveTo(cx
+ radius
, cy
+ radius
);
1113 ctx
.lineTo(cx
- radius
, cy
- radius
);
1118 ctx
.moveTo(cx
+ radius
, cy
- radius
);
1119 ctx
.lineTo(cx
- radius
, cy
+ radius
);
1126 * To create a "drag" interaction, you typically register a mousedown event
1127 * handler on the element where the drag begins. In that handler, you register a
1128 * mouseup handler on the window to determine when the mouse is released,
1129 * wherever that release happens. This works well, except when the user releases
1130 * the mouse over an off-domain iframe. In that case, the mouseup event is
1131 * handled by the iframe and never bubbles up to the window handler.
1133 * To deal with this issue, we cover iframes with high z-index divs to make sure
1134 * they don't capture mouseup.
1137 * element.addEventListener('mousedown', function() {
1138 * var tarper = new Dygraph.IFrameTarp();
1140 * var mouseUpHandler = function() {
1142 * window.removeEventListener(mouseUpHandler);
1145 * window.addEventListener('mouseup', mouseUpHandler);
1150 Dygraph
.IFrameTarp
= function() {
1151 /** @type {Array.<!HTMLDivElement>} */
1156 * Find all the iframes in the document and cover them with high z-index
1159 Dygraph
.IFrameTarp
.prototype.cover
= function() {
1160 var iframes
= document
.getElementsByTagName("iframe");
1161 for (var i
= 0; i
< iframes
.length
; i
++) {
1162 var iframe
= iframes
[i
];
1163 var x
= Dygraph
.findPosX(iframe
),
1164 y
= Dygraph
.findPosY(iframe
),
1165 width
= iframe
.offsetWidth
,
1166 height
= iframe
.offsetHeight
;
1168 var div
= document
.createElement("div");
1169 div
.style
.position
= "absolute";
1170 div
.style
.left
= x
+ 'px';
1171 div
.style
.top
= y
+ 'px';
1172 div
.style
.width
= width
+ 'px';
1173 div
.style
.height
= height
+ 'px';
1174 div
.style
.zIndex
= 999;
1175 document
.body
.appendChild(div
);
1176 this.tarps
.push(div
);
1181 * Remove all the iframe covers. You should call this in a mouseup handler.
1183 Dygraph
.IFrameTarp
.prototype.uncover
= function() {
1184 for (var i
= 0; i
< this.tarps
.length
; i
++) {
1185 this.tarps
[i
].parentNode
.removeChild(this.tarps
[i
]);
1191 * Determine whether |data| is delimited by CR, CRLF, LF, LFCR.
1192 * @param {string} data
1193 * @return {?string} the delimiter that was detected (or null on failure).
1195 Dygraph
.detectLineDelimiter
= function(data
) {
1196 for (var i
= 0; i
< data
.length
; i
++) {
1197 var code
= data
.charAt(i
);
1198 if (code
=== '\r') {
1199 // Might actually be "\r\n".
1200 if (((i
+ 1) < data
.length
) && (data
.charAt(i
+ 1) === '\n')) {
1205 if (code
=== '\n') {
1206 // Might actually be "\n\r".
1207 if (((i
+ 1) < data
.length
) && (data
.charAt(i
+ 1) === '\r')) {