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
);
22 Dygraph
.log10
= function(x
) {
23 return Math
.log(x
) / Dygraph
.LN_TEN
;
26 // Various logging levels.
32 // Set this to log stack traces on warnings, etc.
33 // This requires stacktrace.js, which is up to you to provide.
34 // A copy can be found in the dygraphs repo, or at
35 // https://github.com/eriwen
/javascript
-stacktrace
36 Dygraph
.LOG_STACK_TRACES
= false;
38 /** A dotted line stroke pattern. */
39 Dygraph
.DOTTED_LINE
= [2, 2];
40 /** A dashed line stroke pattern. */
41 Dygraph
.DASHED_LINE
= [7, 3];
42 /** A dot dash stroke pattern. */
43 Dygraph
.DOT_DASH_LINE
= [7, 2, 2, 2];
47 * Log an error on the JS console at the given severity.
48 * @param { Integer } severity One of Dygraph.{DEBUG,INFO,WARNING,ERROR}
49 * @param { String } The message to log.
51 Dygraph
.log
= function(severity
, message
) {
53 if (typeof(printStackTrace
) != 'undefined') {
54 // Remove uninteresting bits: logging functions and paths.
55 st
= printStackTrace({guess
:false});
56 while (st
[0].indexOf("stacktrace") != -1) {
61 for (var i
= 0; i
< st
.length
; i
++) {
62 st
[i
] = st
[i
].replace(/\([^)]*\/(.*)\)/, '@$1')
63 .replace(/\@.*\/([^\/]*)/, '@$1')
64 .replace('[object Object].', '');
66 var top_msg
= st
.splice(0, 1)[0];
67 message
+= ' (' + top_msg
.replace(/^.*@ ?/, '') + ')';
70 if (typeof(console
) != 'undefined') {
73 console
.debug('dygraphs: ' + message
);
76 console
.info('dygraphs: ' + message
);
79 console
.warn('dygraphs: ' + message
);
82 console
.error('dygraphs: ' + message
);
87 if (Dygraph
.LOG_STACK_TRACES
) {
88 console
.log(st
.join('\n'));
93 Dygraph
.info
= function(message
) {
94 Dygraph
.log(Dygraph
.INFO
, message
);
97 Dygraph
.prototype.info
= Dygraph
.info
;
100 Dygraph
.warn
= function(message
) {
101 Dygraph
.log(Dygraph
.WARNING
, message
);
104 Dygraph
.prototype.warn
= Dygraph
.warn
;
107 Dygraph
.error
= function(message
) {
108 Dygraph
.log(Dygraph
.ERROR
, message
);
111 Dygraph
.prototype.error
= Dygraph
.error
;
115 * Return the 2d context for a dygraph canvas.
117 * This method is only exposed for the sake of replacing the function in
118 * automated tests, e.g.
120 * var oldFunc = Dygraph.getContext();
121 * Dygraph.getContext = function(canvas) {
122 * var realContext = oldFunc(canvas);
123 * return new Proxy(realContext);
126 Dygraph
.getContext
= function(canvas
) {
127 return canvas
.getContext("2d");
132 * Add an event handler. This smooths a difference between IE and the rest of
134 * @param { DOM element } elem The element to add the event to.
135 * @param { String } type The type of the event, e.g. 'click' or 'mousemove'.
136 * @param { Function } fn The function to call on the event. The function takes
137 * one parameter: the event object.
139 Dygraph
.addEvent
= function addEvent(elem
, type
, fn
) {
140 if (elem
.addEventListener
) {
141 elem
.addEventListener(type
, fn
, false);
143 elem
[type
+fn
] = function(){fn(window
.event
);};
144 elem
.attachEvent('on'+type
, elem
[type
+fn
]);
150 * Remove an event handler. This smooths a difference between IE and the rest of
152 * @param { DOM element } elem The element to add the event to.
153 * @param { String } type The type of the event, e.g. 'click' or 'mousemove'.
154 * @param { Function } fn The function to call on the event. The function takes
155 * one parameter: the event object.
157 Dygraph
.removeEvent
= function addEvent(elem
, type
, fn
) {
158 if (elem
.removeEventListener
) {
159 elem
.removeEventListener(type
, fn
, false);
161 elem
.detachEvent('on'+type
, elem
[type
+fn
]);
162 elem
[type
+fn
] = null;
168 * Cancels further processing of an event. This is useful to prevent default
169 * browser actions, e.g. highlighting text on a double-click.
170 * Based on the article at
171 * http://www.switchonthecode.com/tutorials/javascript-tutorial-the-scroll-wheel
172 * @param { Event } e The event whose normal behavior should be canceled.
174 Dygraph
.cancelEvent
= function(e
) {
175 e
= e
? e
: window
.event
;
176 if (e
.stopPropagation
) {
179 if (e
.preventDefault
) {
182 e
.cancelBubble
= true;
184 e
.returnValue
= false;
189 * Convert hsv values to an rgb(r,g,b) string. Taken from MochiKit.Color. This
190 * is used to generate default series colors which are evenly spaced on the
192 * @param { Number } hue Range is 0.0-1.0.
193 * @param { Number } saturation Range is 0.0-1.0.
194 * @param { Number } value Range is 0.0-1.0.
195 * @return { String } "rgb(r,g,b)" where r, g and b range from 0-255.
198 Dygraph
.hsvToRGB
= function (hue
, saturation
, value
) {
202 if (saturation
=== 0) {
207 var i
= Math
.floor(hue
* 6);
208 var f
= (hue
* 6) - i
;
209 var p
= value
* (1 - saturation
);
210 var q
= value
* (1 - (saturation
* f
));
211 var t
= value
* (1 - (saturation
* (1 - f
)));
213 case 1: red
= q
; green
= value
; blue
= p
; break;
214 case 2: red
= p
; green
= value
; blue
= t
; break;
215 case 3: red
= p
; green
= q
; blue
= value
; break;
216 case 4: red
= t
; green
= p
; blue
= value
; break;
217 case 5: red
= value
; green
= p
; blue
= q
; break;
218 case 6: // fall through
219 case 0: red
= value
; green
= t
; blue
= p
; break;
222 red
= Math
.floor(255 * red
+ 0.5);
223 green
= Math
.floor(255 * green
+ 0.5);
224 blue
= Math
.floor(255 * blue
+ 0.5);
225 return 'rgb(' + red
+ ',' + green
+ ',' + blue
+ ')';
228 // The following functions are from quirksmode.org with a modification for Safari from
229 // http://blog.firetree.net/2005/07/04/javascript-find-position/
230 // http://www.quirksmode.org/js
/findpos
.html
231 // ... and modifications to support scrolling divs.
234 * Find the x-coordinate of the supplied object relative to the left side
238 Dygraph
.findPosX
= function(obj
) {
240 if(obj
.offsetParent
) {
243 curleft
+= copyObj
.offsetLeft
;
244 if(!copyObj
.offsetParent
) {
247 copyObj
= copyObj
.offsetParent
;
252 // This handles the case where the object is inside a scrolled div.
253 while(obj
&& obj
!= document
.body
) {
254 curleft
-= obj
.scrollLeft
;
255 obj
= obj
.parentNode
;
261 * Find the y-coordinate of the supplied object relative to the top of the
265 Dygraph
.findPosY
= function(obj
) {
267 if(obj
.offsetParent
) {
270 curtop
+= copyObj
.offsetTop
;
271 if(!copyObj
.offsetParent
) {
274 copyObj
= copyObj
.offsetParent
;
279 // This handles the case where the object is inside a scrolled div.
280 while(obj
&& obj
!= document
.body
) {
281 curtop
-= obj
.scrollTop
;
282 obj
= obj
.parentNode
;
289 * Returns the x-coordinate of the event in a coordinate system where the
290 * top-left corner of the page (not the window) is (0,0).
291 * Taken from MochiKit.Signal
293 Dygraph
.pageX
= function(e
) {
295 return (!e
.pageX
|| e
.pageX
< 0) ? 0 : e
.pageX
;
298 var b
= document
.body
;
300 (de
.scrollLeft
|| b
.scrollLeft
) -
301 (de
.clientLeft
|| 0);
307 * Returns the y-coordinate of the event in a coordinate system where the
308 * top-left corner of the page (not the window) is (0,0).
309 * Taken from MochiKit.Signal
311 Dygraph
.pageY
= function(e
) {
313 return (!e
.pageY
|| e
.pageY
< 0) ? 0 : e
.pageY
;
316 var b
= document
.body
;
318 (de
.scrollTop
|| b
.scrollTop
) -
325 * @param { Number } x The number to consider.
326 * @return { Boolean } Whether the number is zero or NaN.
328 // TODO(danvk): rename this function to something like 'isNonZeroNan'.
329 // TODO(danvk): determine when else this returns false (e.g. for undefined or null)
330 Dygraph
.isOK
= function(x
) {
331 return x
&& !isNaN(x
);
335 * Number formatting function which mimicks the behavior of %g in printf, i.e.
336 * either exponential or fixed format (without trailing 0s) is used depending on
337 * the length of the generated string. The advantage of this format is that
338 * there is a predictable upper bound on the resulting string length,
339 * significant figures are not dropped, and normal numbers are not displayed in
340 * exponential notation.
342 * NOTE: JavaScript's native toPrecision() is NOT a drop-in replacement for %g.
343 * It creates strings which are too long for absolute values between 10^-4 and
344 * 10^-6, e.g. '0.00001' instead of '1e-5'. See tests/number-format.html for
347 * @param {Number} x The number to format
348 * @param {Number} opt_precision The precision to use, default 2.
349 * @return {String} A string formatted like %g in printf. The max generated
350 * string length should be precision + 6 (e.g 1.123e+300).
352 Dygraph
.floatFormat
= function(x
, opt_precision
) {
353 // Avoid invalid precision values; [1, 21] is the valid range.
354 var p
= Math
.min(Math
.max(1, opt_precision
|| 2), 21);
356 // This is deceptively simple. The actual algorithm comes from:
358 // Max allowed length = p + 4
359 // where 4 comes from 'e+n' and '.'.
361 // Length of fixed format = 2 + y + p
362 // where 2 comes from '0.' and y = # of leading zeroes.
364 // Equating the two and solving for y yields y = 2, or 0.00xxxx which is
367 // Since the behavior of toPrecision() is identical for larger numbers, we
368 // don't have to worry about the other bound.
370 // Finally, the argument for toExponential() is the number of trailing digits,
371 // so we take off 1 for the value before the '.'.
372 return (Math
.abs(x
) < 1.0e-3 && x
!== 0.0) ?
373 x
.toExponential(p
- 1) : x
.toPrecision(p
);
378 * Converts '9' to '09' (useful for dates)
380 Dygraph
.zeropad
= function(x
) {
381 if (x
< 10) return "0" + x
; else return "" + x
;
385 * Return a string version of the hours, minutes and seconds portion of a date.
386 * @param {Number} date The JavaScript date (ms since epoch)
387 * @return {String} A time of the form "HH:MM:SS"
390 Dygraph
.hmsString_
= function(date
) {
391 var zeropad
= Dygraph
.zeropad
;
392 var d
= new Date(date
);
393 if (d
.getSeconds()) {
394 return zeropad(d
.getHours()) + ":" +
395 zeropad(d
.getMinutes()) + ":" +
396 zeropad(d
.getSeconds());
398 return zeropad(d
.getHours()) + ":" + zeropad(d
.getMinutes());
403 * Round a number to the specified number of digits past the decimal point.
404 * @param {Number} num The number to round
405 * @param {Number} places The number of decimals to which to round
406 * @return {Number} The rounded number
409 Dygraph
.round_
= function(num
, places
) {
410 var shift
= Math
.pow(10, places
);
411 return Math
.round(num
* shift
)/shift
;
416 * Implementation of binary search over an array.
417 * Currently does not work when val is outside the range of arry's values.
418 * @param { Integer } val the value to search for
419 * @param { Integer[] } arry is the value over which to search
420 * @param { Integer } abs If abs > 0, find the lowest entry greater than val
421 * If abs < 0, find the highest entry less than val.
422 * if abs == 0, find the entry that equals val.
423 * @param { Integer } [low] The first index in arry to consider (optional)
424 * @param { Integer } [high] The last index in arry to consider (optional)
426 Dygraph
.binarySearch
= function(val
, arry
, abs
, low
, high
) {
427 if (low
=== null || low
=== undefined
||
428 high
=== null || high
=== undefined
) {
430 high
= arry
.length
- 1;
435 if (abs
=== null || abs
=== undefined
) {
438 var validIndex
= function(idx
) {
439 return idx
>= 0 && idx
< arry
.length
;
441 var mid
= parseInt((low
+ high
) / 2, 10);
442 var element
= arry
[mid
];
443 if (element
== val
) {
450 // Accept if element > val, but also if prior element < val.
452 if (validIndex(idx
) && arry
[idx
] < val
) {
456 return Dygraph
.binarySearch(val
, arry
, abs
, low
, mid
- 1);
460 // Accept if element < val, but also if prior element > val.
462 if (validIndex(idx
) && arry
[idx
] > val
) {
466 return Dygraph
.binarySearch(val
, arry
, abs
, mid
+ 1, high
);
472 * Parses a date, returning the number of milliseconds since epoch. This can be
473 * passed in as an xValueParser in the Dygraph constructor.
474 * TODO(danvk): enumerate formats that this understands.
475 * @param {String} A date in YYYYMMDD format.
476 * @return {Number} Milliseconds since epoch.
478 Dygraph
.dateParser
= function(dateStr
) {
482 // Let the system try the format first.
483 d
= Dygraph
.dateStrToMillis(dateStr
);
484 if (d
&& !isNaN(d
)) return d
;
486 if (dateStr
.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12'
487 dateStrSlashed
= dateStr
.replace("-", "/", "g");
488 while (dateStrSlashed
.search("-") != -1) {
489 dateStrSlashed
= dateStrSlashed
.replace("-", "/");
491 d
= Dygraph
.dateStrToMillis(dateStrSlashed
);
492 } else if (dateStr
.length
== 8) { // e.g. '20090712'
493 // TODO(danvk): remove support for this format. It's confusing.
494 dateStrSlashed
= dateStr
.substr(0,4) + "/" + dateStr.substr(4,2) + "/" +
496 d
= Dygraph
.dateStrToMillis(dateStrSlashed
);
498 // Any format that Date.parse will accept, e.g. "2009/07/12" or
499 // "2009/07/12 12:34:56"
500 d
= Dygraph
.dateStrToMillis(dateStr
);
503 if (!d
|| isNaN(d
)) {
504 Dygraph
.error("Couldn't parse " + dateStr
+ " as a date");
511 * This is identical to JavaScript's built-in Date.parse() method, except that
512 * it doesn't get replaced with an incompatible method by aggressive JS
513 * libraries like MooTools or Joomla.
514 * @param { String } str The date string, e.g. "2011/05/06"
515 * @return { Integer } millis since epoch
517 Dygraph
.dateStrToMillis
= function(str
) {
518 return new Date(str
).getTime();
521 // These functions are all based on MochiKit.
523 * Copies all the properties from o to self.
527 Dygraph
.update
= function (self
, o
) {
528 if (typeof(o
) != 'undefined' && o
!== null) {
530 if (o
.hasOwnProperty(k
)) {
539 * Copies all the properties from o to self.
543 Dygraph
.updateDeep
= function (self
, o
) {
544 // Taken from http://stackoverflow.com/questions
/384286/javascript
-isdom
-how
-do-you
-check
-if-a
-javascript
-object
-is
-a
-dom
-object
547 typeof Node
=== "object" ? o
instanceof Node
:
548 typeof o
=== "object" && typeof o
.nodeType
=== "number" && typeof o
.nodeName
==="string"
552 if (typeof(o
) != 'undefined' && o
!== null) {
554 if (o
.hasOwnProperty(k
)) {
557 } else if (Dygraph
.isArrayLike(o
[k
])) {
558 self
[k
] = o
[k
].slice();
559 } else if (isNode(o
[k
])) {
560 // DOM objects are shallowly-copied.
562 } else if (typeof(o
[k
]) == 'object') {
563 if (typeof(self
[k
]) != 'object') {
566 Dygraph
.updateDeep(self
[k
], o
[k
]);
579 Dygraph
.isArrayLike
= function (o
) {
582 (typ
!= 'object' && !(typ
== 'function' &&
583 typeof(o
.item
) == 'function')) ||
585 typeof(o
.length
) != 'number' ||
596 Dygraph
.isDateLike
= function (o
) {
597 if (typeof(o
) != "object" || o
=== null ||
598 typeof(o
.getTime
) != 'function') {
605 * Note: this only seems to work for arrays.
608 Dygraph
.clone
= function(o
) {
609 // TODO(danvk): figure out how MochiKit's version works
611 for (var i
= 0; i
< o
.length
; i
++) {
612 if (Dygraph
.isArrayLike(o
[i
])) {
613 r
.push(Dygraph
.clone(o
[i
]));
623 * Create a new canvas element. This is more complex than a simple
624 * document.createElement("canvas") because of IE and excanvas.
626 Dygraph
.createCanvas
= function() {
627 var canvas
= document
.createElement("canvas");
629 var isIE
= (/MSIE/.test(navigator
.userAgent
) && !window
.opera
);
630 if (isIE
&& (typeof(G_vmlCanvasManager
) != 'undefined')) {
631 canvas
= G_vmlCanvasManager
.initElement(canvas
);
639 * Checks whether the user is on an Android browser.
640 * Android does not fully support the <canvas> tag, e.g. w/r/t/ clipping.
642 Dygraph
.isAndroid
= function() {
643 return (/Android/).test(navigator
.userAgent
);
648 * Call a function N times at a given interval, then call a cleanup function
649 * once. repeat_fn is called once immediately, then (times - 1) times
650 * asynchronously. If times=1, then cleanup_fn() is also called synchronously.
651 * @param repeat_fn {Function} Called repeatedly -- takes the number of calls
652 * (from 0 to times-1) as an argument.
653 * @param times {number} The number of times to call repeat_fn
654 * @param every_ms {number} Milliseconds between calls
655 * @param cleanup_fn {Function} A function to call after all repeat_fn calls.
658 Dygraph
.repeatAndCleanup
= function(repeat_fn
, times
, every_ms
, cleanup_fn
) {
660 var start_time
= new Date().getTime();
668 if (count
>= times
) return;
669 var target_time
= start_time
+ (1 + count
) * every_ms
;
670 setTimeout(function() {
673 if (count
>= times
- 1) {
678 }, target_time
- new Date().getTime());
679 // TODO(danvk): adjust every_ms to produce evenly-timed function calls.
685 * This function will scan the option list and determine if they
686 * require us to recalculate the pixel positions of each point.
687 * @param { List } a list of options to check.
688 * @return { Boolean } true if the graph needs new points else false.
690 Dygraph
.isPixelChangingOptionList
= function(labels
, attrs
) {
691 // A whitelist of options that do not change pixel positions.
692 var pixelSafeOptions
= {
693 'annotationClickHandler': true,
694 'annotationDblClickHandler': true,
695 'annotationMouseOutHandler': true,
696 'annotationMouseOverHandler': true,
697 'axisLabelColor': true,
698 'axisLineColor': true,
699 'axisLineWidth': true,
700 'clickCallback': true,
701 'digitsAfterDecimal': true,
702 'drawCallback': true,
707 'gridLineColor': true,
708 'gridLineWidth': true,
709 'hideOverlayOnMouseOut': true,
710 'highlightCallback': true,
711 'highlightCircleSize': true,
712 'interactionModel': true,
713 'isZoomedIgnoreProgrammaticZoom': true,
715 'labelsDivStyles': true,
716 'labelsDivWidth': true,
719 'labelsSeparateLines': true,
720 'labelsShowZeroValues': true,
722 'maxNumberWidth': true,
723 'panEdgeFraction': true,
724 'pixelsPerYLabel': true,
725 'pointClickCallback': true,
727 'rangeSelectorPlotFillColor': true,
728 'rangeSelectorPlotStrokeColor': true,
729 'showLabelsOnHighlight': true,
733 'underlayCallback': true,
734 'unhighlightCallback': true,
735 'xAxisLabelFormatter': true,
737 'xValueFormatter': true,
738 'yAxisLabelFormatter': true,
739 'yValueFormatter': true,
743 // Assume that we do not require new points.
744 // This will change to true if we actually do need new points.
745 var requiresNewPoints
= false;
747 // Create a dictionary of series names for faster lookup.
748 // If there are no labels, then the dictionary stays empty.
749 var seriesNamesDictionary
= { };
751 for (var i
= 1; i
< labels
.length
; i
++) {
752 seriesNamesDictionary
[labels
[i
]] = true;
756 // Iterate through the list of updated options.
757 for (var property
in attrs
) {
758 // Break early if we already know we need new points from a previous option.
759 if (requiresNewPoints
) {
762 if (attrs
.hasOwnProperty(property
)) {
763 // Find out of this field is actually a series specific options list.
764 if (seriesNamesDictionary
[property
]) {
765 // This property value is a list of options for this series.
766 // If any of these sub properties are not pixel safe, set the flag.
767 for (var subProperty
in attrs
[property
]) {
768 // Break early if we already know we need new points from a previous option.
769 if (requiresNewPoints
) {
772 if (attrs
[property
].hasOwnProperty(subProperty
) && !pixelSafeOptions
[subProperty
]) {
773 requiresNewPoints
= true;
776 // If this was not a series specific option list, check if its a pixel changing property.
777 } else if (!pixelSafeOptions
[property
]) {
778 requiresNewPoints
= true;
783 return requiresNewPoints
;
787 * Compares two arrays to see if they are equal. If either parameter is not an
788 * array it will return false. Does a shallow compare
789 * Dygraph.compareArrays([[1,2], [3, 4]], [[1,2], [3,4]]) === false.
790 * @param array1 first array
791 * @param array2 second array
792 * @return True if both parameters are arrays, and contents are equal.
794 Dygraph
.compareArrays
= function(array1
, array2
) {
795 if (!Dygraph
.isArrayLike(array1
) || !Dygraph
.isArrayLike(array2
)) {
798 if (array1
.length
!== array2
.length
) {
801 for (var i
= 0; i
< array1
.length
; i
++) {
802 if (array1
[i
] !== array2
[i
]) {