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.
16 Dygraph
.LOG_SCALE
= 10;
17 Dygraph
.LN_TEN
= Math
.log(Dygraph
.LOG_SCALE
);
20 Dygraph
.log10
= function(x
) {
21 return Math
.log(x
) / Dygraph
.LN_TEN
;
24 // Various logging levels.
30 // Set this to log stack traces on warnings, etc.
31 // This requires stacktrace.js, which is up to you to provide.
32 // A copy can be found in the dygraphs repo, or at
33 // https://github.com/eriwen
/javascript
-stacktrace
34 Dygraph
.LOG_STACK_TRACES
= false;
38 * Log an error on the JS console at the given severity.
39 * @param { Integer } severity One of Dygraph.{DEBUG,INFO,WARNING,ERROR}
40 * @param { String } The message to log.
42 Dygraph
.log
= function(severity
, message
) {
44 if (typeof(printStackTrace
) != 'undefined') {
45 // Remove uninteresting bits: logging functions and paths.
46 var st
= printStackTrace({guess
:false});
47 while (st
[0].indexOf("Function.log") != 0) {
51 for (var i
= 0; i
< st
.length
; i
++) {
52 st
[i
] = st
[i
].replace(/\([^)]*\/(.*)\)/, '($1)')
53 .replace(/\@.*\/([^\/]*)/, '@$1')
54 .replace('[object Object].', '');
56 message
+= ' (' + st
.splice(0, 1) + ')';
59 if (typeof(console
) != 'undefined') {
62 console
.debug('dygraphs: ' + message
);
65 console
.info('dygraphs: ' + message
);
68 console
.warn('dygraphs: ' + message
);
71 console
.error('dygraphs: ' + message
);
76 if (Dygraph
.LOG_STACK_TRACES
) {
77 console
.log(st
.join('\n'));
82 Dygraph
.info
= function(message
) {
83 Dygraph
.log(Dygraph
.INFO
, message
);
86 Dygraph
.prototype.info
= Dygraph
.info
;
89 Dygraph
.warn
= function(message
) {
90 Dygraph
.log(Dygraph
.WARNING
, message
);
93 Dygraph
.prototype.warn
= Dygraph
.warn
;
96 Dygraph
.error
= function(message
) {
97 Dygraph
.log(Dygraph
.ERROR
, message
);
100 Dygraph
.prototype.error
= Dygraph
.error
;
104 * Return the 2d context for a dygraph canvas.
106 * This method is only exposed for the sake of replacing the function in
107 * automated tests, e.g.
109 * var oldFunc = Dygraph.getContext();
110 * Dygraph.getContext = function(canvas) {
111 * var realContext = oldFunc(canvas);
112 * return new Proxy(realContext);
115 Dygraph
.getContext
= function(canvas
) {
116 return canvas
.getContext("2d");
121 * Add an event handler. This smooths a difference between IE and the rest of
123 * @param { DOM element } elem The element to add the event to.
124 * @param { String } type The type of the event, e.g. 'click' or 'mousemove'.
125 * @param { Function } fn The function to call on the event. The function takes
126 * one parameter: the event object.
128 Dygraph
.addEvent
= function addEvent(elem
, type
, fn
) {
129 if (elem
.addEventListener
) {
130 elem
.addEventListener(type
, fn
, false);
132 elem
[type
+fn
] = function(){fn(window
.event
);};
133 elem
.attachEvent('on'+type
, elem
[type
+fn
]);
139 * Remove an event handler. This smooths a difference between IE and the rest of
141 * @param { DOM element } elem The element to add the event to.
142 * @param { String } type The type of the event, e.g. 'click' or 'mousemove'.
143 * @param { Function } fn The function to call on the event. The function takes
144 * one parameter: the event object.
146 Dygraph
.removeEvent
= function addEvent(elem
, type
, fn
) {
147 if (elem
.removeEventListener
) {
148 elem
.removeEventListener(type
, fn
, false);
150 elem
.detachEvent('on'+type
, elem
[type
+fn
]);
151 elem
[type
+fn
] = null;
157 * Cancels further processing of an event. This is useful to prevent default
158 * browser actions, e.g. highlighting text on a double-click.
159 * Based on the article at
160 * http://www.switchonthecode.com/tutorials/javascript-tutorial-the-scroll-wheel
161 * @param { Event } e The event whose normal behavior should be canceled.
163 Dygraph
.cancelEvent
= function(e
) {
164 e
= e
? e
: window
.event
;
165 if (e
.stopPropagation
) {
168 if (e
.preventDefault
) {
171 e
.cancelBubble
= true;
173 e
.returnValue
= false;
178 * Convert hsv values to an rgb(r,g,b) string. Taken from MochiKit.Color. This
179 * is used to generate default series colors which are evenly spaced on the
181 * @param { Number } hue Range is 0.0-1.0.
182 * @param { Number } saturation Range is 0.0-1.0.
183 * @param { Number } value Range is 0.0-1.0.
184 * @return { String } "rgb(r,g,b)" where r, g and b range from 0-255.
187 Dygraph
.hsvToRGB
= function (hue
, saturation
, value
) {
191 if (saturation
=== 0) {
196 var i
= Math
.floor(hue
* 6);
197 var f
= (hue
* 6) - i
;
198 var p
= value
* (1 - saturation
);
199 var q
= value
* (1 - (saturation
* f
));
200 var t
= value
* (1 - (saturation
* (1 - f
)));
202 case 1: red
= q
; green
= value
; blue
= p
; break;
203 case 2: red
= p
; green
= value
; blue
= t
; break;
204 case 3: red
= p
; green
= q
; blue
= value
; break;
205 case 4: red
= t
; green
= p
; blue
= value
; break;
206 case 5: red
= value
; green
= p
; blue
= q
; break;
207 case 6: // fall through
208 case 0: red
= value
; green
= t
; blue
= p
; break;
211 red
= Math
.floor(255 * red
+ 0.5);
212 green
= Math
.floor(255 * green
+ 0.5);
213 blue
= Math
.floor(255 * blue
+ 0.5);
214 return 'rgb(' + red
+ ',' + green
+ ',' + blue
+ ')';
217 // The following functions are from quirksmode.org with a modification for Safari from
218 // http://blog.firetree.net/2005/07/04/javascript-find-position/
219 // http://www.quirksmode.org/js
/findpos
.html
220 // ... and modifications to support scrolling divs.
223 * Find the x-coordinate of the supplied object relative to the left side
227 Dygraph
.findPosX
= function(obj
) {
229 if(obj
.offsetParent
) {
232 curleft
+= copyObj
.offsetLeft
;
233 if(!copyObj
.offsetParent
) {
236 copyObj
= copyObj
.offsetParent
;
241 // This handles the case where the object is inside a scrolled div.
242 while(obj
&& obj
!= document
.body
) {
243 curleft
-= obj
.scrollLeft
;
244 obj
= obj
.parentNode
;
250 * Find the y-coordinate of the supplied object relative to the top of the
254 Dygraph
.findPosY
= function(obj
) {
256 if(obj
.offsetParent
) {
259 curtop
+= copyObj
.offsetTop
;
260 if(!copyObj
.offsetParent
) {
263 copyObj
= copyObj
.offsetParent
;
268 // This handles the case where the object is inside a scrolled div.
269 while(obj
&& obj
!= document
.body
) {
270 curtop
-= obj
.scrollTop
;
271 obj
= obj
.parentNode
;
278 * Returns the x-coordinate of the event in a coordinate system where the
279 * top-left corner of the page (not the window) is (0,0).
280 * Taken from MochiKit.Signal
282 Dygraph
.pageX
= function(e
) {
284 return (!e
.pageX
|| e
.pageX
< 0) ? 0 : e
.pageX
;
287 var b
= document
.body
;
289 (de
.scrollLeft
|| b
.scrollLeft
) -
290 (de
.clientLeft
|| 0);
296 * Returns the y-coordinate of the event in a coordinate system where the
297 * top-left corner of the page (not the window) is (0,0).
298 * Taken from MochiKit.Signal
300 Dygraph
.pageY
= function(e
) {
302 return (!e
.pageY
|| e
.pageY
< 0) ? 0 : e
.pageY
;
305 var b
= document
.body
;
307 (de
.scrollTop
|| b
.scrollTop
) -
314 * @param { Number } x The number to consider.
315 * @return { Boolean } Whether the number is zero or NaN.
317 // TODO(danvk): rename this function to something like 'isNonZeroNan'.
318 Dygraph
.isOK
= function(x
) {
319 return x
&& !isNaN(x
);
323 * Number formatting function which mimicks the behavior of %g in printf, i.e.
324 * either exponential or fixed format (without trailing 0s) is used depending on
325 * the length of the generated string. The advantage of this format is that
326 * there is a predictable upper bound on the resulting string length,
327 * significant figures are not dropped, and normal numbers are not displayed in
328 * exponential notation.
330 * NOTE: JavaScript's native toPrecision() is NOT a drop-in replacement for %g.
331 * It creates strings which are too long for absolute values between 10^-4 and
332 * 10^-6, e.g. '0.00001' instead of '1e-5'. See tests/number-format.html for
335 * @param {Number} x The number to format
336 * @param {Number} opt_precision The precision to use, default 2.
337 * @return {String} A string formatted like %g in printf. The max generated
338 * string length should be precision + 6 (e.g 1.123e+300).
340 Dygraph
.floatFormat
= function(x
, opt_precision
) {
341 // Avoid invalid precision values; [1, 21] is the valid range.
342 var p
= Math
.min(Math
.max(1, opt_precision
|| 2), 21);
344 // This is deceptively simple. The actual algorithm comes from:
346 // Max allowed length = p + 4
347 // where 4 comes from 'e+n' and '.'.
349 // Length of fixed format = 2 + y + p
350 // where 2 comes from '0.' and y = # of leading zeroes.
352 // Equating the two and solving for y yields y = 2, or 0.00xxxx which is
355 // Since the behavior of toPrecision() is identical for larger numbers, we
356 // don't have to worry about the other bound.
358 // Finally, the argument for toExponential() is the number of trailing digits,
359 // so we take off 1 for the value before the '.'.
360 return (Math
.abs(x
) < 1.0e-3 && x
!= 0.0) ?
361 x
.toExponential(p
- 1) : x
.toPrecision(p
);
366 * Converts '9' to '09' (useful for dates)
368 Dygraph
.zeropad
= function(x
) {
369 if (x
< 10) return "0" + x
; else return "" + x
;
373 * Return a string version of the hours, minutes and seconds portion of a date.
374 * @param {Number} date The JavaScript date (ms since epoch)
375 * @return {String} A time of the form "HH:MM:SS"
378 Dygraph
.hmsString_
= function(date
) {
379 var zeropad
= Dygraph
.zeropad
;
380 var d
= new Date(date
);
381 if (d
.getSeconds()) {
382 return zeropad(d
.getHours()) + ":" +
383 zeropad(d
.getMinutes()) + ":" +
384 zeropad(d
.getSeconds());
386 return zeropad(d
.getHours()) + ":" + zeropad(d
.getMinutes());
391 * Round a number to the specified number of digits past the decimal point.
392 * @param {Number} num The number to round
393 * @param {Number} places The number of decimals to which to round
394 * @return {Number} The rounded number
397 Dygraph
.round_
= function(num
, places
) {
398 var shift
= Math
.pow(10, places
);
399 return Math
.round(num
* shift
)/shift
;
404 * Implementation of binary search over an array.
405 * Currently does not work when val is outside the range of arry's values.
406 * @param { Integer } val the value to search for
407 * @param { Integer[] } arry is the value over which to search
408 * @param { Integer } abs If abs > 0, find the lowest entry greater than val
409 * If abs < 0, find the highest entry less than val.
410 * if abs == 0, find the entry that equals val.
411 * @param { Integer } [low] The first index in arry to consider (optional)
412 * @param { Integer } [high] The last index in arry to consider (optional)
414 Dygraph
.binarySearch
= function(val
, arry
, abs
, low
, high
) {
415 if (low
== null || high
== null) {
417 high
= arry
.length
- 1;
425 var validIndex
= function(idx
) {
426 return idx
>= 0 && idx
< arry
.length
;
428 var mid
= parseInt((low
+ high
) / 2);
429 var element
= arry
[mid
];
430 if (element
== val
) {
435 // Accept if element > val, but also if prior element < val.
437 if (validIndex(idx
) && arry
[idx
] < val
) {
441 return Dygraph
.binarySearch(val
, arry
, abs
, low
, mid
- 1);
445 // Accept if element < val, but also if prior element > val.
447 if (validIndex(idx
) && arry
[idx
] > val
) {
451 return Dygraph
.binarySearch(val
, arry
, abs
, mid
+ 1, high
);
457 * Parses a date, returning the number of milliseconds since epoch. This can be
458 * passed in as an xValueParser in the Dygraph constructor.
459 * TODO(danvk): enumerate formats that this understands.
460 * @param {String} A date in YYYYMMDD format.
461 * @return {Number} Milliseconds since epoch.
463 Dygraph
.dateParser
= function(dateStr
) {
466 if (dateStr
.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12'
467 dateStrSlashed
= dateStr
.replace("-", "/", "g");
468 while (dateStrSlashed
.search("-") != -1) {
469 dateStrSlashed
= dateStrSlashed
.replace("-", "/");
471 d
= Dygraph
.dateStrToMillis(dateStrSlashed
);
472 } else if (dateStr
.length
== 8) { // e.g. '20090712'
473 // TODO(danvk): remove support for this format. It's confusing.
474 dateStrSlashed
= dateStr
.substr(0,4) + "/" + dateStr
.substr(4,2)
475 + "/" + dateStr
.substr(6,2);
476 d
= Dygraph
.dateStrToMillis(dateStrSlashed
);
478 // Any format that Date.parse will accept, e.g. "2009/07/12" or
479 // "2009/07/12 12:34:56"
480 d
= Dygraph
.dateStrToMillis(dateStr
);
483 if (!d
|| isNaN(d
)) {
484 Dygraph
.error("Couldn't parse " + dateStr
+ " as a date");
491 * This is identical to JavaScript's built-in Date.parse() method, except that
492 * it doesn't get replaced with an incompatible method by aggressive JS
493 * libraries like MooTools or Joomla.
494 * @param { String } str The date string, e.g. "2011/05/06"
495 * @return { Integer } millis since epoch
497 Dygraph
.dateStrToMillis
= function(str
) {
498 return new Date(str
).getTime();
501 // These functions are all based on MochiKit.
503 * Copies all the properties from o to self.
507 Dygraph
.update
= function (self
, o
) {
508 if (typeof(o
) != 'undefined' && o
!== null) {
510 if (o
.hasOwnProperty(k
)) {
519 * Copies all the properties from o to self.
523 Dygraph
.updateDeep
= function (self
, o
) {
524 // Taken from http://stackoverflow.com/questions
/384286/javascript
-isdom
-how
-do-you
-check
-if-a
-javascript
-object
-is
-a
-dom
-object
527 typeof Node
=== "object" ? o
instanceof Node
:
528 typeof o
=== "object" && typeof o
.nodeType
=== "number" && typeof o
.nodeName
==="string"
532 if (typeof(o
) != 'undefined' && o
!== null) {
534 if (o
.hasOwnProperty(k
)) {
537 } else if (Dygraph
.isArrayLike(o
[k
])) {
538 self
[k
] = o
[k
].slice();
539 } else if (isNode(o
[k
])) {
540 // DOM objects are shallowly-copied.
542 } else if (typeof(o
[k
]) == 'object') {
543 if (typeof(self
[k
]) != 'object') {
546 Dygraph
.updateDeep(self
[k
], o
[k
]);
559 Dygraph
.isArrayLike
= function (o
) {
562 (typ
!= 'object' && !(typ
== 'function' &&
563 typeof(o
.item
) == 'function')) ||
565 typeof(o
.length
) != 'number' ||
576 Dygraph
.isDateLike
= function (o
) {
577 if (typeof(o
) != "object" || o
=== null ||
578 typeof(o
.getTime
) != 'function') {
585 * Note: this only seems to work for arrays.
588 Dygraph
.clone
= function(o
) {
589 // TODO(danvk): figure out how MochiKit's version works
591 for (var i
= 0; i
< o
.length
; i
++) {
592 if (Dygraph
.isArrayLike(o
[i
])) {
593 r
.push(Dygraph
.clone(o
[i
]));
603 * Create a new canvas element. This is more complex than a simple
604 * document.createElement("canvas") because of IE and excanvas.
606 Dygraph
.createCanvas
= function() {
607 var canvas
= document
.createElement("canvas");
609 var isIE
= (/MSIE/.test(navigator
.userAgent
) && !window
.opera
);
610 if (isIE
&& (typeof(G_vmlCanvasManager
) != 'undefined')) {
611 canvas
= G_vmlCanvasManager
.initElement(canvas
);
619 * Call a function N times at a given interval, then call a cleanup function
620 * once. repeat_fn is called once immediately, then (times - 1) times
621 * asynchronously. If times=1, then cleanup_fn() is also called synchronously.
622 * @param repeat_fn {Function} Called repeatedly -- takes the number of calls
623 * (from 0 to times-1) as an argument.
624 * @param times {number} The number of times to call repeat_fn
625 * @param every_ms {number} Milliseconds between calls
626 * @param cleanup_fn {Function} A function to call after all repeat_fn calls.
629 Dygraph
.repeatAndCleanup
= function(repeat_fn
, times
, every_ms
, cleanup_fn
) {
631 var start_time
= new Date().getTime();
639 if (count
>= times
) return;
640 var target_time
= start_time
+ (1 + count
) * every_ms
;
641 setTimeout(function() {
644 if (count
>= times
- 1) {
649 }, target_time
- new Date().getTime());
650 // TODO(danvk): adjust every_ms to produce evenly-timed function calls.
656 * This function will scan the option list and determine if they
657 * require us to recalculate the pixel positions of each point.
658 * @param { List } a list of options to check.
659 * @return { Boolean } true if the graph needs new points else false.
661 Dygraph
.isPixelChangingOptionList
= function(labels
, attrs
) {
662 // A whitelist of options that do not change pixel positions.
663 var pixelSafeOptions
= {
664 'annotationClickHandler': true,
665 'annotationDblClickHandler': true,
666 'annotationMouseOutHandler': true,
667 'annotationMouseOverHandler': true,
668 'axisLabelColor': true,
669 'axisLineColor': true,
670 'axisLineWidth': true,
671 'clickCallback': true,
672 'digitsAfterDecimal': true,
673 'drawCallback': true,
678 'gridLineColor': true,
679 'gridLineWidth': true,
680 'hideOverlayOnMouseOut': true,
681 'highlightCallback': true,
682 'highlightCircleSize': true,
683 'interactionModel': true,
684 'isZoomedIgnoreProgrammaticZoom': true,
686 'labelsDivStyles': true,
687 'labelsDivWidth': true,
690 'labelsSeparateLines': true,
691 'labelsShowZeroValues': true,
693 'maxNumberWidth': true,
694 'panEdgeFraction': true,
695 'pixelsPerYLabel': true,
696 'pointClickCallback': true,
698 'rangeSelectorPlotFillColor': true,
699 'rangeSelectorPlotStrokeColor': true,
700 'showLabelsOnHighlight': true,
704 'underlayCallback': true,
705 'unhighlightCallback': true,
706 'xAxisLabelFormatter': true,
708 'xValueFormatter': true,
709 'yAxisLabelFormatter': true,
710 'yValueFormatter': true,
714 // Assume that we do not require new points.
715 // This will change to true if we actually do need new points.
716 var requiresNewPoints
= false;
718 // Create a dictionary of series names for faster lookup.
719 // If there are no labels, then the dictionary stays empty.
720 var seriesNamesDictionary
= { };
722 for (var i
= 1; i
< labels
.length
; i
++) {
723 seriesNamesDictionary
[labels
[i
]] = true;
727 // Iterate through the list of updated options.
728 for (var property
in attrs
) {
729 // Break early if we already know we need new points from a previous option.
730 if (requiresNewPoints
) {
733 if (attrs
.hasOwnProperty(property
)) {
734 // Find out of this field is actually a series specific options list.
735 if (seriesNamesDictionary
[property
]) {
736 // This property value is a list of options for this series.
737 // If any of these sub properties are not pixel safe, set the flag.
738 for (var subProperty
in attrs
[property
]) {
739 // Break early if we already know we need new points from a previous option.
740 if (requiresNewPoints
) {
743 if (attrs
[property
].hasOwnProperty(subProperty
) && !pixelSafeOptions
[subProperty
]) {
744 requiresNewPoints
= true;
747 // If this was not a series specific option list, check if its a pixel changing property.
748 } else if (!pixelSafeOptions
[property
]) {
749 requiresNewPoints
= true;
754 return requiresNewPoints
;