3 * Copyright 2011 Dan Vanderkam (danvdk@gmail.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
8 * @fileoverview This file contains utility functions used by dygraphs. These
9 * are typically static (i.e. not related to any particular dygraph). Examples
10 * include date/time formatting functions, basic algorithms (e.g. binary
11 * search) and generic DOM-manipulation functions.
14 /*jshint globalstrict: true */
15 /*global Dygraph:false, G_vmlCanvasManager:false, Node:false, printStackTrace: false */
18 Dygraph
.LOG_SCALE
= 10;
19 Dygraph
.LN_TEN
= Math
.log(Dygraph
.LOG_SCALE
);
26 Dygraph
.log10
= function(x
) {
27 return Math
.log(x
) / Dygraph
.LN_TEN
;
30 // Various logging levels.
36 // Set this to log stack traces on warnings, etc.
37 // This requires stacktrace.js, which is up to you to provide.
38 // A copy can be found in the dygraphs repo, or at
39 // https://github.com/eriwen
/javascript
-stacktrace
40 Dygraph
.LOG_STACK_TRACES
= false;
42 /** A dotted line stroke pattern. */
43 Dygraph
.DOTTED_LINE
= [2, 2];
44 /** A dashed line stroke pattern. */
45 Dygraph
.DASHED_LINE
= [7, 3];
46 /** A dot dash stroke pattern. */
47 Dygraph
.DOT_DASH_LINE
= [7, 2, 2, 2];
50 * Log an error on the JS console at the given severity.
51 * @param {number} severity One of Dygraph.{DEBUG,INFO,WARNING,ERROR}
52 * @param {string} message The message to log.
55 Dygraph
.log
= function(severity
, message
) {
57 if (typeof(printStackTrace
) != 'undefined') {
59 // Remove uninteresting bits: logging functions and paths.
60 st
= printStackTrace({guess
:false});
61 while (st
[0].indexOf("stacktrace") != -1) {
66 for (var i
= 0; i
< st
.length
; i
++) {
67 st
[i
] = st
[i
].replace(/\([^)]*\/(.*)\)/, '@$1')
68 .replace(/\@.*\/([^\/]*)/, '@$1')
69 .replace('[object Object].', '');
71 var top_msg
= st
.splice(0, 1)[0];
72 message
+= ' (' + top_msg
.replace(/^.*@ ?/, '') + ')';
74 // Oh well, it was worth a shot!
78 if (typeof(window
.console
) != 'undefined') {
79 // In older versions of Firefox, only console.log is defined.
80 var console
= window
.console
;
81 var log
= function(console
, method
, msg
) {
82 if (method
&& typeof(method
) == 'function') {
83 method
.call(console
, msg
);
91 log(console
, console
.debug
, 'dygraphs: ' + message
);
94 log(console
, console
.info
, 'dygraphs: ' + message
);
97 log(console
, console
.warn
, 'dygraphs: ' + message
);
100 log(console
, console
.error
, 'dygraphs: ' + message
);
105 if (Dygraph
.LOG_STACK_TRACES
) {
106 window
.console
.log(st
.join('\n'));
111 * @param {string} message
114 Dygraph
.info
= function(message
) {
115 Dygraph
.log(Dygraph
.INFO
, message
);
118 * @param {string} message
121 Dygraph
.prototype.info
= Dygraph
.info
;
124 * @param {string} message
127 Dygraph
.warn
= function(message
) {
128 Dygraph
.log(Dygraph
.WARNING
, message
);
131 * @param {string} message
134 Dygraph
.prototype.warn
= Dygraph
.warn
;
137 * @param {string} message
139 Dygraph
.error
= function(message
) {
140 Dygraph
.log(Dygraph
.ERROR
, message
);
143 * @param {string} message
146 Dygraph
.prototype.error
= Dygraph
.error
;
149 * Return the 2d context for a dygraph canvas.
151 * This method is only exposed for the sake of replacing the function in
152 * automated tests, e.g.
154 * var oldFunc = Dygraph.getContext();
155 * Dygraph.getContext = function(canvas) {
156 * var realContext = oldFunc(canvas);
157 * return new Proxy(realContext);
159 * @param {!HTMLCanvasElement} canvas
160 * @return {!CanvasRenderingContext2D}
163 Dygraph
.getContext
= function(canvas
) {
164 return /** @type{!CanvasRenderingContext2D}*/(canvas
.getContext("2d"));
168 * Add an event handler. This smooths a difference between IE and the rest of
170 * @param { !Element } elem The element to add the event to.
171 * @param { string } type The type of the event, e.g. 'click' or 'mousemove'.
172 * @param { function(Event):(boolean|undefined) } fn The function to call
173 * on the event. The function takes one parameter: the event object.
176 Dygraph
.addEvent
= function addEvent(elem
, type
, fn
) {
177 if (elem
.addEventListener
) {
178 elem
.addEventListener(type
, fn
, false);
180 elem
[type
+fn
] = function(){fn(window
.event
);};
181 elem
.attachEvent('on'+type
, elem
[type
+fn
]);
186 * Add an event handler. This event handler is kept until the graph is
187 * destroyed with a call to graph.destroy().
189 * @param { !Element } elem The element to add the event to.
190 * @param { string } type The type of the event, e.g. 'click' or 'mousemove'.
191 * @param { function(Event):(boolean|undefined) } fn The function to call
192 * on the event. The function takes one parameter: the event object.
195 Dygraph
.prototype.addAndTrackEvent
= function(elem
, type
, fn
) {
196 Dygraph
.addEvent(elem
, type
, fn
);
197 this.registeredEvents_
.push({ elem
: elem
, type
: type
, fn
: fn
});
201 * Remove an event handler. This smooths a difference between IE and the rest
203 * @param {!Element} elem The element to add the event to.
204 * @param {string} type The type of the event, e.g. 'click' or 'mousemove'.
205 * @param {function(Event):(boolean|undefined)} fn The function to call
206 * on the event. The function takes one parameter: the event object.
209 Dygraph
.removeEvent
= function(elem
, type
, fn
) {
210 if (elem
.removeEventListener
) {
211 elem
.removeEventListener(type
, fn
, false);
214 elem
.detachEvent('on'+type
, elem
[type
+fn
]);
216 // We only detach event listeners on a "best effort" basis in IE. See:
217 // http://stackoverflow.com/questions
/2553632/detachevent-not
-working
-with-named
-inline
-functions
219 elem
[type
+fn
] = null;
223 Dygraph
.prototype.removeTrackedEvents_
= function() {
224 if (this.registeredEvents_
) {
225 for (var idx
= 0; idx
< this.registeredEvents_
.length
; idx
++) {
226 var reg
= this.registeredEvents_
[idx
];
227 Dygraph
.removeEvent(reg
.elem
, reg
.type
, reg
.fn
);
231 this.registeredEvents_
= [];
235 * Cancels further processing of an event. This is useful to prevent default
236 * browser actions, e.g. highlighting text on a double-click.
237 * Based on the article at
238 * http://www.switchonthecode.com/tutorials/javascript-tutorial-the-scroll-wheel
239 * @param { !Event } e The event whose normal behavior should be canceled.
242 Dygraph
.cancelEvent
= function(e
) {
243 e
= e
? e
: window
.event
;
244 if (e
.stopPropagation
) {
247 if (e
.preventDefault
) {
250 e
.cancelBubble
= true;
252 e
.returnValue
= false;
257 * Convert hsv values to an rgb(r,g,b) string. Taken from MochiKit.Color. This
258 * is used to generate default series colors which are evenly spaced on the
260 * @param { number } hue Range is 0.0-1.0.
261 * @param { number } saturation Range is 0.0-1.0.
262 * @param { number } value Range is 0.0-1.0.
263 * @return { string } "rgb(r,g,b)" where r, g and b range from 0-255.
266 Dygraph
.hsvToRGB
= function (hue
, saturation
, value
) {
270 if (saturation
=== 0) {
275 var i
= Math
.floor(hue
* 6);
276 var f
= (hue
* 6) - i
;
277 var p
= value
* (1 - saturation
);
278 var q
= value
* (1 - (saturation
* f
));
279 var t
= value
* (1 - (saturation
* (1 - f
)));
281 case 1: red
= q
; green
= value
; blue
= p
; break;
282 case 2: red
= p
; green
= value
; blue
= t
; break;
283 case 3: red
= p
; green
= q
; blue
= value
; break;
284 case 4: red
= t
; green
= p
; blue
= value
; break;
285 case 5: red
= value
; green
= p
; blue
= q
; break;
286 case 6: // fall through
287 case 0: red
= value
; green
= t
; blue
= p
; break;
290 red
= Math
.floor(255 * red
+ 0.5);
291 green
= Math
.floor(255 * green
+ 0.5);
292 blue
= Math
.floor(255 * blue
+ 0.5);
293 return 'rgb(' + red
+ ',' + green
+ ',' + blue
+ ')';
296 // The following functions are from quirksmode.org with a modification for Safari from
297 // http://blog.firetree.net/2005/07/04/javascript-find-position/
298 // http://www.quirksmode.org/js
/findpos
.html
299 // ... and modifications to support scrolling divs.
302 * Find the x-coordinate of the supplied object relative to the left side
304 * TODO(danvk): change obj type from Node -> !Node
309 Dygraph
.findPosX
= function(obj
) {
311 if(obj
.offsetParent
) {
314 // NOTE: the if statement here is for IE8.
315 var borderLeft
= "0";
316 if (window
.getComputedStyle
) {
317 borderLeft
= window
.getComputedStyle(copyObj
, null).borderLeft
|| "0";
319 curleft
+= parseInt(borderLeft
, 10) ;
320 curleft
+= copyObj
.offsetLeft
;
321 if(!copyObj
.offsetParent
) {
324 copyObj
= copyObj
.offsetParent
;
329 // This handles the case where the object is inside a scrolled div.
330 while(obj
&& obj
!= document
.body
) {
331 curleft
-= obj
.scrollLeft
;
332 obj
= obj
.parentNode
;
338 * Find the y-coordinate of the supplied object relative to the top of the
340 * TODO(danvk): change obj type from Node -> !Node
341 * TODO(danvk): consolidate with findPosX and return an {x, y} object.
346 Dygraph
.findPosY
= function(obj
) {
348 if(obj
.offsetParent
) {
351 // NOTE: the if statement here is for IE8.
353 if (window
.getComputedStyle
) {
354 borderTop
= window
.getComputedStyle(copyObj
, null).borderTop
|| "0";
356 curtop
+= parseInt(borderTop
, 10) ;
357 curtop
+= copyObj
.offsetTop
;
358 if(!copyObj
.offsetParent
) {
361 copyObj
= copyObj
.offsetParent
;
366 // This handles the case where the object is inside a scrolled div.
367 while(obj
&& obj
!= document
.body
) {
368 curtop
-= obj
.scrollTop
;
369 obj
= obj
.parentNode
;
375 * Returns the x-coordinate of the event in a coordinate system where the
376 * top-left corner of the page (not the window) is (0,0).
377 * Taken from MochiKit.Signal
382 Dygraph
.pageX
= function(e
) {
384 return (!e
.pageX
|| e
.pageX
< 0) ? 0 : e
.pageX
;
386 var de
= document
.documentElement
;
387 var b
= document
.body
;
389 (de
.scrollLeft
|| b
.scrollLeft
) -
390 (de
.clientLeft
|| 0);
395 * Returns the y-coordinate of the event in a coordinate system where the
396 * top-left corner of the page (not the window) is (0,0).
397 * Taken from MochiKit.Signal
402 Dygraph
.pageY
= function(e
) {
404 return (!e
.pageY
|| e
.pageY
< 0) ? 0 : e
.pageY
;
406 var de
= document
.documentElement
;
407 var b
= document
.body
;
409 (de
.scrollTop
|| b
.scrollTop
) -
415 * This returns true unless the parameter is 0, null, undefined or NaN.
416 * TODO(danvk): rename this function to something like 'isNonZeroNan'.
418 * @param {number} x The number to consider.
419 * @return {boolean} Whether the number is zero or NaN.
422 Dygraph
.isOK
= function(x
) {
423 return !!x
&& !isNaN(x
);
427 * @param { {x:?number,y:?number,yval:?number} } p The point to consider, valid
428 * points are {x, y} objects
429 * @param { boolean } allowNaNY Treat point with y=NaN as valid
430 * @return { boolean } Whether the point has numeric x and y.
433 Dygraph
.isValidPoint
= function(p
, allowNaNY
) {
434 if (!p
) return false; // null or undefined object
435 if (p
.yval
=== null) return false; // missing point
436 if (p
.x
=== null || p
.x
=== undefined
) return false;
437 if (p
.y
=== null || p
.y
=== undefined
) return false;
438 if (isNaN(p
.x
) || (!allowNaNY
&& isNaN(p
.y
))) return false;
443 * Number formatting function which mimicks the behavior of %g in printf, i.e.
444 * either exponential or fixed format (without trailing 0s) is used depending on
445 * the length of the generated string. The advantage of this format is that
446 * there is a predictable upper bound on the resulting string length,
447 * significant figures are not dropped, and normal numbers are not displayed in
448 * exponential notation.
450 * NOTE: JavaScript's native toPrecision() is NOT a drop-in replacement for %g.
451 * It creates strings which are too long for absolute values between 10^-4 and
452 * 10^-6, e.g. '0.00001' instead of '1e-5'. See tests/number-format.html for
455 * @param {number} x The number to format
456 * @param {number=} opt_precision The precision to use, default 2.
457 * @return {string} A string formatted like %g in printf. The max generated
458 * string length should be precision + 6 (e.g 1.123e+300).
460 Dygraph
.floatFormat
= function(x
, opt_precision
) {
461 // Avoid invalid precision values; [1, 21] is the valid range.
462 var p
= Math
.min(Math
.max(1, opt_precision
|| 2), 21);
464 // This is deceptively simple. The actual algorithm comes from:
466 // Max allowed length = p + 4
467 // where 4 comes from 'e+n' and '.'.
469 // Length of fixed format = 2 + y + p
470 // where 2 comes from '0.' and y = # of leading zeroes.
472 // Equating the two and solving for y yields y = 2, or 0.00xxxx which is
475 // Since the behavior of toPrecision() is identical for larger numbers, we
476 // don't have to worry about the other bound.
478 // Finally, the argument for toExponential() is the number of trailing digits,
479 // so we take off 1 for the value before the '.'.
480 return (Math
.abs(x
) < 1.0e-3 && x
!== 0.0) ?
481 x
.toExponential(p
- 1) : x
.toPrecision(p
);
485 * Converts '9' to '09' (useful for dates)
490 Dygraph
.zeropad
= function(x
) {
491 if (x
< 10) return "0" + x
; else return "" + x
;
495 * Return a string version of the hours, minutes and seconds portion of a date.
497 * @param {number} date The JavaScript date (ms since epoch)
498 * @return {string} A time of the form "HH:MM:SS"
501 Dygraph
.hmsString_
= function(date
) {
502 var zeropad
= Dygraph
.zeropad
;
503 var d
= new Date(date
);
504 if (d
.getSeconds()) {
505 return zeropad(d
.getHours()) + ":" +
506 zeropad(d
.getMinutes()) + ":" +
507 zeropad(d
.getSeconds());
509 return zeropad(d
.getHours()) + ":" + zeropad(d
.getMinutes());
514 * Round a number to the specified number of digits past the decimal point.
515 * @param {number} num The number to round
516 * @param {number} places The number of decimals to which to round
517 * @return {number} The rounded number
520 Dygraph
.round_
= function(num
, places
) {
521 var shift
= Math
.pow(10, places
);
522 return Math
.round(num
* shift
)/shift
;
526 * Implementation of binary search over an array.
527 * Currently does not work when val is outside the range of arry's values.
528 * @param {number} val the value to search for
529 * @param {Array.<number>} arry is the value over which to search
530 * @param {number} abs If abs > 0, find the lowest entry greater than val
531 * If abs < 0, find the highest entry less than val.
532 * If abs == 0, find the entry that equals val.
533 * @param {number=} low The first index in arry to consider (optional)
534 * @param {number=} high The last index in arry to consider (optional)
535 * @return {number} Index of the element, or -1 if it isn't found.
538 Dygraph
.binarySearch
= function(val
, arry
, abs
, low
, high
) {
539 if (low
=== null || low
=== undefined
||
540 high
=== null || high
=== undefined
) {
542 high
= arry
.length
- 1;
547 if (abs
=== null || abs
=== undefined
) {
550 var validIndex
= function(idx
) {
551 return idx
>= 0 && idx
< arry
.length
;
553 var mid
= parseInt((low
+ high
) / 2, 10);
554 var element
= arry
[mid
];
556 if (element
== val
) {
558 } else if (element
> val
) {
560 // Accept if element > val, but also if prior element < val.
562 if (validIndex(idx
) && arry
[idx
] < val
) {
566 return Dygraph
.binarySearch(val
, arry
, abs
, low
, mid
- 1);
567 } else if (element
< val
) {
569 // Accept if element < val, but also if prior element > val.
571 if (validIndex(idx
) && arry
[idx
] > val
) {
575 return Dygraph
.binarySearch(val
, arry
, abs
, mid
+ 1, high
);
577 return -1; // can't actually happen, but makes closure compiler happy
581 * Parses a date, returning the number of milliseconds since epoch. This can be
582 * passed in as an xValueParser in the Dygraph constructor.
583 * TODO(danvk): enumerate formats that this understands.
585 * @param {string} dateStr A date in a variety of possible string formats.
586 * @return {number} Milliseconds since epoch.
589 Dygraph
.dateParser
= function(dateStr
) {
593 // Let the system try the format first, with one caveat:
594 // YYYY-MM-DD[ HH:MM:SS] is interpreted as UTC by a variety of browsers.
595 // dygraphs displays dates in local time, so this will result in surprising
596 // inconsistencies. But if you specify "T" or "Z" (i.e. YYYY-MM-DDTHH:MM:SS),
597 // then you probably know what you're doing, so we'll let you go ahead.
598 // Issue: http://code.google.com/p/dygraphs/issues/detail
?id
=255
599 if (dateStr
.search("-") == -1 ||
600 dateStr
.search("T") != -1 || dateStr
.search("Z") != -1) {
601 d
= Dygraph
.dateStrToMillis(dateStr
);
602 if (d
&& !isNaN(d
)) return d
;
605 if (dateStr
.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12'
606 dateStrSlashed
= dateStr
.replace("-", "/", "g");
607 while (dateStrSlashed
.search("-") != -1) {
608 dateStrSlashed
= dateStrSlashed
.replace("-", "/");
610 d
= Dygraph
.dateStrToMillis(dateStrSlashed
);
611 } else if (dateStr
.length
== 8) { // e.g. '20090712'
612 // TODO(danvk): remove support for this format. It's confusing.
613 dateStrSlashed
= dateStr
.substr(0,4) + "/" + dateStr.substr(4,2) + "/" +
615 d
= Dygraph
.dateStrToMillis(dateStrSlashed
);
617 // Any format that Date.parse will accept, e.g. "2009/07/12" or
618 // "2009/07/12 12:34:56"
619 d
= Dygraph
.dateStrToMillis(dateStr
);
622 if (!d
|| isNaN(d
)) {
623 Dygraph
.error("Couldn't parse " + dateStr
+ " as a date");
629 * This is identical to JavaScript's built-in Date.parse() method, except that
630 * it doesn't get replaced with an incompatible method by aggressive JS
631 * libraries like MooTools or Joomla.
632 * @param {string} str The date string, e.g. "2011/05/06"
633 * @return {number} millis since epoch
636 Dygraph
.dateStrToMillis
= function(str
) {
637 return new Date(str
).getTime();
640 // These functions are all based on MochiKit.
642 * Copies all the properties from o to self.
644 * @param {!Object} self
648 Dygraph
.update
= function(self
, o
) {
649 if (typeof(o
) != 'undefined' && o
!== null) {
651 if (o
.hasOwnProperty(k
)) {
660 * Copies all the properties from o to self.
662 * @param {!Object} self
667 Dygraph
.updateDeep
= function (self
, o
) {
668 // Taken from http://stackoverflow.com/questions
/384286/javascript
-isdom
-how
-do-you
-check
-if-a
-javascript
-object
-is
-a
-dom
-object
671 typeof Node
=== "object" ? o
instanceof Node
:
672 typeof o
=== "object" && typeof o
.nodeType
=== "number" && typeof o
.nodeName
==="string"
676 if (typeof(o
) != 'undefined' && o
!== null) {
678 if (o
.hasOwnProperty(k
)) {
681 } else if (Dygraph
.isArrayLike(o
[k
])) {
682 self
[k
] = o
[k
].slice();
683 } else if (isNode(o
[k
])) {
684 // DOM objects are shallowly-copied.
686 } else if (typeof(o
[k
]) == 'object') {
687 if (typeof(self
[k
]) != 'object' || self
[k
] === null) {
690 Dygraph
.updateDeep(self
[k
], o
[k
]);
705 Dygraph
.isArrayLike
= function(o
) {
708 (typ
!= 'object' && !(typ
== 'function' &&
709 typeof(o
.item
) == 'function')) ||
711 typeof(o
.length
) != 'number' ||
724 Dygraph
.isDateLike
= function (o
) {
725 if (typeof(o
) != "object" || o
=== null ||
726 typeof(o
.getTime
) != 'function') {
733 * Note: this only seems to work for arrays.
738 Dygraph
.clone
= function(o
) {
739 // TODO(danvk): figure out how MochiKit's version works
741 for (var i
= 0; i
< o
.length
; i
++) {
742 if (Dygraph
.isArrayLike(o
[i
])) {
743 r
.push(Dygraph
.clone(o
[i
]));
752 * Create a new canvas element. This is more complex than a simple
753 * document.createElement("canvas") because of IE and excanvas.
755 * @return {!HTMLCanvasElement}
758 Dygraph
.createCanvas
= function() {
759 var canvas
= document
.createElement("canvas");
761 var isIE
= (/MSIE/.test(navigator
.userAgent
) && !window
.opera
);
762 if (isIE
&& (typeof(G_vmlCanvasManager
) != 'undefined')) {
763 canvas
= G_vmlCanvasManager
.initElement(
764 /**@type{!HTMLCanvasElement}*/(canvas
));
771 * Returns the context's pixel ratio, which is the ratio between the device
772 * pixel ratio and the backing store ratio. Typically this is 1 for conventional
773 * displays, and > 1 for HiDPI displays (such as the Retina MBP).
774 * See http://www.html5rocks.com/en/tutorials/canvas/hidpi/ for more details.
776 * @param {!CanvasRenderingContext2D} context The canvas's 2d context.
777 * @return {number} The ratio of the device pixel ratio and the backing store
778 * ratio for the specified context.
780 Dygraph
.getContextPixelRatio
= function(context
) {
782 var devicePixelRatio
= window
.devicePixelRatio
|| 1,
783 backingStoreRatio
= context
.webkitBackingStorePixelRatio
||
784 context
.mozBackingStorePixelRatio
||
785 context
.msBackingStorePixelRatio
||
786 context
.oBackingStorePixelRatio
||
787 context
.backingStorePixelRatio
|| 1;
788 return devicePixelRatio
/ backingStoreRatio
;
795 * Checks whether the user is on an Android browser.
796 * Android does not fully support the <canvas> tag, e.g. w/r/t/ clipping.
800 Dygraph
.isAndroid
= function() {
801 return (/Android/).test(navigator
.userAgent
);
806 * TODO(danvk): use @template here when it's better supported for classes.
807 * @param {!Array} array
808 * @param {number} start
809 * @param {number} length
810 * @param {function(!Array,?):boolean=} predicate
813 Dygraph
.Iterator
= function(array
, start
, length
, predicate
) {
815 length
= length
|| array
.length
;
816 this.hasNext
= true; // Use to identify if there's another element.
817 this.peek
= null; // Use for look-ahead
820 this.predicate_
= predicate
;
821 this.end_
= Math
.min(array
.length
, start
+ length
);
822 this.nextIdx_
= start
- 1; // use -1 so initial advance works.
823 this.next(); // ignoring result.
829 Dygraph
.Iterator
.prototype.next
= function() {
835 var nextIdx
= this.nextIdx_
+ 1;
837 while (nextIdx
< this.end_
) {
838 if (!this.predicate_
|| this.predicate_(this.array_
, nextIdx
)) {
839 this.peek
= this.array_
[nextIdx
];
845 this.nextIdx_
= nextIdx
;
847 this.hasNext
= false;
854 * Returns a new iterator over array, between indexes start and
855 * start + length, and only returns entries that pass the accept function
857 * @param {!Array} array the array to iterate over.
858 * @param {number} start the first index to iterate over, 0 if absent.
859 * @param {number} length the number of elements in the array to iterate over.
860 * This, along with start, defines a slice of the array, and so length
861 * doesn't imply the number of elements in the iterator when accept doesn't
862 * always accept all values. array.length when absent.
863 * @param {function(?):boolean=} opt_predicate a function that takes
864 * parameters array and idx, which returns true when the element should be
865 * returned. If omitted, all elements are accepted.
868 Dygraph
.createIterator
= function(array
, start
, length
, opt_predicate
) {
869 return new Dygraph
.Iterator(array
, start
, length
, opt_predicate
);
872 // Shim layer with setTimeout fallback.
873 // From: http://paulirish.com/2011/requestanimationframe-for-smart-animating/
874 // Should be called with the window context:
875 // Dygraph.requestAnimFrame.call(window, function() {})
876 Dygraph
.requestAnimFrame
= (function() {
877 return window
.requestAnimationFrame
||
878 window
.webkitRequestAnimationFrame
||
879 window
.mozRequestAnimationFrame
||
880 window
.oRequestAnimationFrame
||
881 window
.msRequestAnimationFrame
||
882 function (callback
) {
883 window
.setTimeout(callback
, 1000 / 60);
888 * Call a function at most maxFrames times at an attempted interval of
889 * framePeriodInMillis, then call a cleanup function once. repeatFn is called
890 * once immediately, then at most (maxFrames - 1) times asynchronously. If
891 * maxFrames==1, then cleanup_fn() is also called synchronously. This function
892 * is used to sequence animation.
893 * @param {function(number)} repeatFn Called repeatedly -- takes the frame
894 * number (from 0 to maxFrames-1) as an argument.
895 * @param {number} maxFrames The max number of times to call repeatFn
896 * @param {number} framePeriodInMillis Max requested time between frames.
897 * @param {function()} cleanupFn A function to call after all repeatFn calls.
900 Dygraph
.repeatAndCleanup
= function(repeatFn
, maxFrames
, framePeriodInMillis
,
903 var previousFrameNumber
;
904 var startTime
= new Date().getTime();
905 repeatFn(frameNumber
);
906 if (maxFrames
== 1) {
910 var maxFrameArg
= maxFrames
- 1;
913 if (frameNumber
>= maxFrames
) return;
914 Dygraph
.requestAnimFrame
.call(window
, function() {
915 // Determine which frame to draw based on the delay so far. Will skip
916 // frames if necessary.
917 var currentTime
= new Date().getTime();
918 var delayInMillis
= currentTime
- startTime
;
919 previousFrameNumber
= frameNumber
;
920 frameNumber
= Math
.floor(delayInMillis
/ framePeriodInMillis
);
921 var frameDelta
= frameNumber
- previousFrameNumber
;
922 // If we predict that the subsequent repeatFn call will overshoot our
923 // total frame target, so our last call will cause a stutter, then jump to
924 // the last call immediately. If we're going to cause a stutter, better
925 // to do it faster than slower.
926 var predictOvershootStutter
= (frameNumber
+ frameDelta
) > maxFrameArg
;
927 if (predictOvershootStutter
|| (frameNumber
>= maxFrameArg
)) {
928 repeatFn(maxFrameArg
); // Ensure final call with maxFrameArg.
931 if (frameDelta
!== 0) { // Don't call repeatFn with duplicate frames.
932 repeatFn(frameNumber
);
941 * This function will scan the option list and determine if they
942 * require us to recalculate the pixel positions of each point.
943 * @param {!Array.<string>} labels a list of options to check.
944 * @param {!Object} attrs
945 * @return {boolean} true if the graph needs new points else false.
948 Dygraph
.isPixelChangingOptionList
= function(labels
, attrs
) {
949 // A whitelist of options that do not change pixel positions.
950 var pixelSafeOptions
= {
951 'annotationClickHandler': true,
952 'annotationDblClickHandler': true,
953 'annotationMouseOutHandler': true,
954 'annotationMouseOverHandler': true,
955 'axisLabelColor': true,
956 'axisLineColor': true,
957 'axisLineWidth': true,
958 'clickCallback': true,
959 'digitsAfterDecimal': true,
960 'drawCallback': true,
961 'drawHighlightPointCallback': true,
963 'drawPointCallback': true,
967 'gridLineColor': true,
968 'gridLineWidth': true,
969 'hideOverlayOnMouseOut': true,
970 'highlightCallback': true,
971 'highlightCircleSize': true,
972 'interactionModel': true,
973 'isZoomedIgnoreProgrammaticZoom': true,
975 'labelsDivStyles': true,
976 'labelsDivWidth': true,
979 'labelsSeparateLines': true,
980 'labelsShowZeroValues': true,
982 'maxNumberWidth': true,
983 'panEdgeFraction': true,
984 'pixelsPerYLabel': true,
985 'pointClickCallback': true,
987 'rangeSelectorPlotFillColor': true,
988 'rangeSelectorPlotStrokeColor': true,
989 'showLabelsOnHighlight': true,
993 'underlayCallback': true,
994 'unhighlightCallback': true,
995 'xAxisLabelFormatter': true,
997 'xValueFormatter': true,
998 'yAxisLabelFormatter': true,
999 'yValueFormatter': true,
1000 'zoomCallback': true
1003 // Assume that we do not require new points.
1004 // This will change to true if we actually do need new points.
1005 var requiresNewPoints
= false;
1007 // Create a dictionary of series names for faster lookup.
1008 // If there are no labels, then the dictionary stays empty.
1009 var seriesNamesDictionary
= { };
1011 for (var i
= 1; i
< labels
.length
; i
++) {
1012 seriesNamesDictionary
[labels
[i
]] = true;
1016 // Iterate through the list of updated options.
1017 for (var property
in attrs
) {
1018 // Break early if we already know we need new points from a previous option.
1019 if (requiresNewPoints
) {
1022 if (attrs
.hasOwnProperty(property
)) {
1023 // Find out of this field is actually a series specific options list.
1024 if (seriesNamesDictionary
[property
]) {
1025 // This property value is a list of options for this series.
1026 // If any of these sub properties are not pixel safe, set the flag.
1027 for (var subProperty
in attrs
[property
]) {
1028 // Break early if we already know we need new points from a previous option.
1029 if (requiresNewPoints
) {
1032 if (attrs
[property
].hasOwnProperty(subProperty
) && !pixelSafeOptions
[subProperty
]) {
1033 requiresNewPoints
= true;
1036 // If this was not a series specific option list, check if its a pixel changing property.
1037 } else if (!pixelSafeOptions
[property
]) {
1038 requiresNewPoints
= true;
1043 return requiresNewPoints
;
1047 * Compares two arrays to see if they are equal. If either parameter is not an
1048 * array it will return false. Does a shallow compare
1049 * Dygraph.compareArrays([[1,2], [3, 4]], [[1,2], [3,4]]) === false.
1050 * @param {!Array.<T>} array1 first array
1051 * @param {!Array.<T>} array2 second array
1052 * @return {boolean} True if both parameters are arrays, and contents are equal.
1055 Dygraph
.compareArrays
= function(array1
, array2
) {
1056 if (!Dygraph
.isArrayLike(array1
) || !Dygraph
.isArrayLike(array2
)) {
1059 if (array1
.length
!== array2
.length
) {
1062 for (var i
= 0; i
< array1
.length
; i
++) {
1063 if (array1
[i
] !== array2
[i
]) {
1071 * @param {!CanvasRenderingContext2D} ctx the canvas context
1072 * @param {number} sides the number of sides in the shape.
1073 * @param {number} radius the radius of the image.
1074 * @param {number} cx center x coordate
1075 * @param {number} cy center y coordinate
1076 * @param {number=} rotationRadians the shift of the initial angle, in radians.
1077 * @param {number=} delta the angle shift for each line. If missing, creates a
1081 Dygraph
.regularShape_
= function(
1082 ctx
, sides
, radius
, cx
, cy
, rotationRadians
, delta
) {
1083 rotationRadians
= rotationRadians
|| 0;
1084 delta
= delta
|| Math
.PI
* 2 / sides
;
1087 var initialAngle
= rotationRadians
;
1088 var angle
= initialAngle
;
1090 var computeCoordinates
= function() {
1091 var x
= cx
+ (Math
.sin(angle
) * radius
);
1092 var y
= cy
+ (-Math
.cos(angle
) * radius
);
1096 var initialCoordinates
= computeCoordinates();
1097 var x
= initialCoordinates
[0];
1098 var y
= initialCoordinates
[1];
1101 for (var idx
= 0; idx
< sides
; idx
++) {
1102 angle
= (idx
== sides
- 1) ? initialAngle
: (angle
+ delta
);
1103 var coords
= computeCoordinates();
1104 ctx
.lineTo(coords
[0], coords
[1]);
1111 * TODO(danvk): be more specific on the return type.
1112 * @param {number} sides
1113 * @param {number=} rotationRadians
1114 * @param {number=} delta
1115 * @return {Function}
1118 Dygraph
.shapeFunction_
= function(sides
, rotationRadians
, delta
) {
1119 return function(g
, name
, ctx
, cx
, cy
, color
, radius
) {
1120 ctx
.strokeStyle
= color
;
1121 ctx
.fillStyle
= "white";
1122 Dygraph
.regularShape_(ctx
, sides
, radius
, cx
, cy
, rotationRadians
, delta
);
1127 DEFAULT
: function(g
, name
, ctx
, canvasx
, canvasy
, color
, radius
) {
1129 ctx
.fillStyle
= color
;
1130 ctx
.arc(canvasx
, canvasy
, radius
, 0, 2 * Math
.PI
, false);
1133 TRIANGLE
: Dygraph
.shapeFunction_(3),
1134 SQUARE
: Dygraph
.shapeFunction_(4, Math
.PI
/ 4),
1135 DIAMOND
: Dygraph
.shapeFunction_(4),
1136 PENTAGON
: Dygraph
.shapeFunction_(5),
1137 HEXAGON
: Dygraph
.shapeFunction_(6),
1138 CIRCLE
: function(g
, name
, ctx
, cx
, cy
, color
, radius
) {
1140 ctx
.strokeStyle
= color
;
1141 ctx
.fillStyle
= "white";
1142 ctx
.arc(cx
, cy
, radius
, 0, 2 * Math
.PI
, false);
1146 STAR
: Dygraph
.shapeFunction_(5, 0, 4 * Math
.PI
/ 5),
1147 PLUS
: function(g
, name
, ctx
, cx
, cy
, color
, radius
) {
1148 ctx
.strokeStyle
= color
;
1151 ctx
.moveTo(cx
+ radius
, cy
);
1152 ctx
.lineTo(cx
- radius
, cy
);
1157 ctx
.moveTo(cx
, cy
+ radius
);
1158 ctx
.lineTo(cx
, cy
- radius
);
1162 EX
: function(g
, name
, ctx
, cx
, cy
, color
, radius
) {
1163 ctx
.strokeStyle
= color
;
1166 ctx
.moveTo(cx
+ radius
, cy
+ radius
);
1167 ctx
.lineTo(cx
- radius
, cy
- radius
);
1172 ctx
.moveTo(cx
+ radius
, cy
- radius
);
1173 ctx
.lineTo(cx
- radius
, cy
+ radius
);
1180 * To create a "drag" interaction, you typically register a mousedown event
1181 * handler on the element where the drag begins. In that handler, you register a
1182 * mouseup handler on the window to determine when the mouse is released,
1183 * wherever that release happens. This works well, except when the user releases
1184 * the mouse over an off-domain iframe. In that case, the mouseup event is
1185 * handled by the iframe and never bubbles up to the window handler.
1187 * To deal with this issue, we cover iframes with high z-index divs to make sure
1188 * they don't capture mouseup.
1191 * element.addEventListener('mousedown', function() {
1192 * var tarper = new Dygraph.IFrameTarp();
1194 * var mouseUpHandler = function() {
1196 * window.removeEventListener(mouseUpHandler);
1199 * window.addEventListener('mouseup', mouseUpHandler);
1204 Dygraph
.IFrameTarp
= function() {
1205 /** @type {Array.<!HTMLDivElement>} */
1210 * Find all the iframes in the document and cover them with high z-index
1213 Dygraph
.IFrameTarp
.prototype.cover
= function() {
1214 var iframes
= document
.getElementsByTagName("iframe");
1215 for (var i
= 0; i
< iframes
.length
; i
++) {
1216 var iframe
= iframes
[i
];
1217 var x
= Dygraph
.findPosX(iframe
),
1218 y
= Dygraph
.findPosY(iframe
),
1219 width
= iframe
.offsetWidth
,
1220 height
= iframe
.offsetHeight
;
1222 var div
= document
.createElement("div");
1223 div
.style
.position
= "absolute";
1224 div
.style
.left
= x
+ 'px';
1225 div
.style
.top
= y
+ 'px';
1226 div
.style
.width
= width
+ 'px';
1227 div
.style
.height
= height
+ 'px';
1228 div
.style
.zIndex
= 999;
1229 document
.body
.appendChild(div
);
1230 this.tarps
.push(div
);
1235 * Remove all the iframe covers. You should call this in a mouseup handler.
1237 Dygraph
.IFrameTarp
.prototype.uncover
= function() {
1238 for (var i
= 0; i
< this.tarps
.length
; i
++) {
1239 this.tarps
[i
].parentNode
.removeChild(this.tarps
[i
]);
1245 * Determine whether |data| is delimited by CR, CRLF, LF, LFCR.
1246 * @param {string} data
1247 * @return {?string} the delimiter that was detected (or null on failure).
1249 Dygraph
.detectLineDelimiter
= function(data
) {
1250 for (var i
= 0; i
< data
.length
; i
++) {
1251 var code
= data
.charAt(i
);
1252 if (code
=== '\r') {
1253 // Might actually be "\r\n".
1254 if (((i
+ 1) < data
.length
) && (data
.charAt(i
+ 1) === '\n')) {
1259 if (code
=== '\n') {
1260 // Might actually be "\n\r".
1261 if (((i
+ 1) < data
.length
) && (data
.charAt(i
+ 1) === '\r')) {
1272 * Is one node contained by another?
1273 * @param {Node} containee The contained node.
1274 * @param {Node} container The container node.
1275 * @return {boolean} Whether containee is inside (or equal to) container.
1278 Dygraph
.isNodeContainedBy
= function(containee
, container
) {
1279 if (container
=== null || containee
=== null) {
1282 var containeeNode
= /** @type {Node} */ (containee
);
1283 while (containeeNode
&& containeeNode
!== container
) {
1284 containeeNode
= containeeNode
.parentNode
;
1286 return (containeeNode
=== container
);
1290 // This masks some numeric issues in older versions of Firefox,
1291 // where 1.0/Math
.pow(10,2) != Math
.pow(10,-2).
1292 /** @type {function(number,number):number} */
1293 Dygraph
.pow
= function(base
, exp
) {
1295 return 1.0 / Math
.pow(base
, -exp
);
1297 return Math
.pow(base
, exp
);
1300 // For Dygraph.setDateSameTZ, below.
1301 Dygraph
.dateSetters
= {
1302 ms
: Date
.prototype.setMilliseconds
,
1303 s
: Date
.prototype.setSeconds
,
1304 m
: Date
.prototype.setMinutes
,
1305 h
: Date
.prototype.setHours
1309 * This is like calling d.setSeconds(), d.setMinutes(), etc, except that it
1310 * adjusts for time zone changes to keep the date/time parts consistent.
1312 * For example, d.getSeconds(), d.getMinutes() and d.getHours() will all be
1313 * the same before/after you call setDateSameTZ(d, {ms: 0}). The same is not
1314 * true if you call d.setMilliseconds(0).
1316 * @type {function(!Date, Object.<number>)}
1318 Dygraph
.setDateSameTZ
= function(d
, parts
) {
1319 var tz
= d
.getTimezoneOffset();
1320 for (var k
in parts
) {
1321 if (!parts
.hasOwnProperty(k
)) continue;
1322 var setter
= Dygraph
.dateSetters
[k
];
1323 if (!setter
) throw "Invalid setter: " + k
;
1324 setter
.call(d
, parts
[k
]);
1325 if (d
.getTimezoneOffset() != tz
) {
1326 d
.setTime(d
.getTime() + (tz
- d
.getTimezoneOffset()) * 60 * 1000);