1 // Copyright 2011 Dan Vanderkam (danvdk@gmail.com)
2 // All Rights Reserved.
5 * @fileoverview This file contains utility functions used by dygraphs. These
6 * are typically static (i.e. not related to any particular dygraph). Examples
7 * include date/time formatting functions, basic algorithms (e.g. binary
8 * search) and generic DOM-manipulation functions.
11 Dygraph
.LOG_SCALE
= 10;
12 Dygraph
.LN_TEN
= Math
.log(Dygraph
.LOG_SCALE
);
15 Dygraph
.log10
= function(x
) {
16 return Math
.log(x
) / Dygraph
.LN_TEN
;
19 // Various logging levels.
25 // TODO(danvk): any way I can get the line numbers to be this.warn call?
28 * Log an error on the JS console at the given severity.
29 * @param { Integer } severity One of Dygraph.{DEBUG,INFO,WARNING,ERROR}
30 * @param { String } The message to log.
32 Dygraph
.log
= function(severity
, message
) {
33 if (typeof(console
) != 'undefined') {
36 console
.debug('dygraphs: ' + message
);
39 console
.info('dygraphs: ' + message
);
42 console
.warn('dygraphs: ' + message
);
45 console
.error('dygraphs: ' + message
);
52 Dygraph
.info
= function(message
) {
53 Dygraph
.log(Dygraph
.INFO
, message
);
56 Dygraph
.prototype.info
= Dygraph
.info
;
59 Dygraph
.warn
= function(message
) {
60 Dygraph
.log(Dygraph
.WARNING
, message
);
63 Dygraph
.prototype.warn
= Dygraph
.warn
;
66 Dygraph
.error
= function(message
) {
67 Dygraph
.log(Dygraph
.ERROR
, message
);
70 Dygraph
.prototype.error
= Dygraph
.error
;
74 * Return the 2d context for a dygraph canvas.
76 * This method is only exposed for the sake of replacing the function in
77 * automated tests, e.g.
79 * var oldFunc = Dygraph.getContext();
80 * Dygraph.getContext = function(canvas) {
81 * var realContext = oldFunc(canvas);
82 * return new Proxy(realContext);
85 Dygraph
.getContext
= function(canvas
) {
86 return canvas
.getContext("2d");
91 * Add an event handler. This smooths a difference between IE and the rest of
93 * @param { DOM element } el The element to add the event to.
94 * @param { String } evt The name of the event, e.g. 'click' or 'mousemove'.
95 * @param { Function } fn The function to call on the event. The function takes
96 * one parameter: the event object.
98 Dygraph
.addEvent
= function(el
, evt
, fn
) {
99 var normed_fn
= function(e
) {
100 if (!e
) var e
= window
.event
;
103 if (window
.addEventListener
) { // Mozilla, Netscape, Firefox
104 el
.addEventListener(evt
, normed_fn
, false);
106 el
.attachEvent('on' + evt
, normed_fn
);
112 * Cancels further processing of an event. This is useful to prevent default
113 * browser actions, e.g. highlighting text on a double-click.
114 * Based on the article at
115 * http://www.switchonthecode.com/tutorials/javascript-tutorial-the-scroll-wheel
116 * @param { Event } e The event whose normal behavior should be canceled.
118 Dygraph
.cancelEvent
= function(e
) {
119 e
= e
? e
: window
.event
;
120 if (e
.stopPropagation
) {
123 if (e
.preventDefault
) {
126 e
.cancelBubble
= true;
128 e
.returnValue
= false;
133 * Convert hsv values to an rgb(r,g,b) string. Taken from MochiKit.Color. This
134 * is used to generate default series colors which are evenly spaced on the
136 * @param { Number } hue Range is 0.0-1.0.
137 * @param { Number } saturation Range is 0.0-1.0.
138 * @param { Number } value Range is 0.0-1.0.
139 * @return { String } "rgb(r,g,b)" where r, g and b range from 0-255.
142 Dygraph
.hsvToRGB
= function (hue
, saturation
, value
) {
146 if (saturation
=== 0) {
151 var i
= Math
.floor(hue
* 6);
152 var f
= (hue
* 6) - i
;
153 var p
= value
* (1 - saturation
);
154 var q
= value
* (1 - (saturation
* f
));
155 var t
= value
* (1 - (saturation
* (1 - f
)));
157 case 1: red
= q
; green
= value
; blue
= p
; break;
158 case 2: red
= p
; green
= value
; blue
= t
; break;
159 case 3: red
= p
; green
= q
; blue
= value
; break;
160 case 4: red
= t
; green
= p
; blue
= value
; break;
161 case 5: red
= value
; green
= p
; blue
= q
; break;
162 case 6: // fall through
163 case 0: red
= value
; green
= t
; blue
= p
; break;
166 red
= Math
.floor(255 * red
+ 0.5);
167 green
= Math
.floor(255 * green
+ 0.5);
168 blue
= Math
.floor(255 * blue
+ 0.5);
169 return 'rgb(' + red
+ ',' + green
+ ',' + blue
+ ')';
172 // The following functions are from quirksmode.org with a modification for Safari from
173 // http://blog.firetree.net/2005/07/04/javascript-find-position/
174 // http://www.quirksmode.org/js
/findpos
.html
177 Dygraph
.findPosX
= function(obj
) {
182 curleft
+= obj
.offsetLeft
;
183 if(!obj
.offsetParent
)
185 obj
= obj
.offsetParent
;
193 Dygraph
.findPosY
= function(obj
) {
198 curtop
+= obj
.offsetTop
;
199 if(!obj
.offsetParent
)
201 obj
= obj
.offsetParent
;
210 * Returns the x-coordinate of the event in a coordinate system where the
211 * top-left corner of the page (not the window) is (0,0).
212 * Taken from MochiKit.Signal
214 Dygraph
.pageX
= function(e
) {
216 return (!e
.pageX
|| e
.pageX
< 0) ? 0 : e
.pageX
;
219 var b
= document
.body
;
221 (de
.scrollLeft
|| b
.scrollLeft
) -
222 (de
.clientLeft
|| 0);
228 * Returns the y-coordinate of the event in a coordinate system where the
229 * top-left corner of the page (not the window) is (0,0).
230 * Taken from MochiKit.Signal
232 Dygraph
.pageY
= function(e
) {
234 return (!e
.pageY
|| e
.pageY
< 0) ? 0 : e
.pageY
;
237 var b
= document
.body
;
239 (de
.scrollTop
|| b
.scrollTop
) -
246 * @param { Number } x The number to consider.
247 * @return { Boolean } Whether the number is zero or NaN.
249 // TODO(danvk): rename this function to something like 'isNonZeroNan'.
250 Dygraph
.isOK
= function(x
) {
251 return x
&& !isNaN(x
);
255 * Number formatting function which mimicks the behavior of %g in printf, i.e.
256 * either exponential or fixed format (without trailing 0s) is used depending on
257 * the length of the generated string. The advantage of this format is that
258 * there is a predictable upper bound on the resulting string length,
259 * significant figures are not dropped, and normal numbers are not displayed in
260 * exponential notation.
262 * NOTE: JavaScript's native toPrecision() is NOT a drop-in replacement for %g.
263 * It creates strings which are too long for absolute values between 10^-4 and
264 * 10^-6, e.g. '0.00001' instead of '1e-5'. See tests/number-format.html for
267 * @param {Number} x The number to format
268 * @param {Number} opt_precision The precision to use, default 2.
269 * @return {String} A string formatted like %g in printf. The max generated
270 * string length should be precision + 6 (e.g 1.123e+300).
272 Dygraph
.floatFormat
= function(x
, opt_precision
) {
273 // Avoid invalid precision values; [1, 21] is the valid range.
274 var p
= Math
.min(Math
.max(1, opt_precision
|| 2), 21);
276 // This is deceptively simple. The actual algorithm comes from:
278 // Max allowed length = p + 4
279 // where 4 comes from 'e+n' and '.'.
281 // Length of fixed format = 2 + y + p
282 // where 2 comes from '0.' and y = # of leading zeroes.
284 // Equating the two and solving for y yields y = 2, or 0.00xxxx which is
287 // Since the behavior of toPrecision() is identical for larger numbers, we
288 // don't have to worry about the other bound.
290 // Finally, the argument for toExponential() is the number of trailing digits,
291 // so we take off 1 for the value before the '.'.
292 return (Math
.abs(x
) < 1.0e-3 && x
!= 0.0) ?
293 x
.toExponential(p
- 1) : x
.toPrecision(p
);
298 * Converts '9' to '09' (useful for dates)
300 Dygraph
.zeropad
= function(x
) {
301 if (x
< 10) return "0" + x
; else return "" + x
;
305 * Return a string version of the hours, minutes and seconds portion of a date.
306 * @param {Number} date The JavaScript date (ms since epoch)
307 * @return {String} A time of the form "HH:MM:SS"
310 Dygraph
.hmsString_
= function(date
) {
311 var zeropad
= Dygraph
.zeropad
;
312 var d
= new Date(date
);
313 if (d
.getSeconds()) {
314 return zeropad(d
.getHours()) + ":" +
315 zeropad(d
.getMinutes()) + ":" +
316 zeropad(d
.getSeconds());
318 return zeropad(d
.getHours()) + ":" + zeropad(d
.getMinutes());
323 * Convert a JS date (millis since epoch) to YYYY/MM/DD
324 * @param {Number} date The JavaScript date (ms since epoch)
325 * @return {String} A date of the form "YYYY/MM/DD"
328 Dygraph
.dateString_
= function(date
) {
329 var zeropad
= Dygraph
.zeropad
;
330 var d
= new Date(date
);
333 var year
= "" + d
.getFullYear();
334 // Get a 0 padded month string
335 var month
= zeropad(d
.getMonth() + 1); //months are 0-offset, sigh
336 // Get a 0 padded day string
337 var day
= zeropad(d
.getDate());
340 var frac
= d
.getHours() * 3600 + d
.getMinutes() * 60 + d
.getSeconds();
341 if (frac
) ret
= " " + Dygraph
.hmsString_(date
);
343 return year
+ "/" + month + "/" + day
+ ret
;
347 * Round a number to the specified number of digits past the decimal point.
348 * @param {Number} num The number to round
349 * @param {Number} places The number of decimals to which to round
350 * @return {Number} The rounded number
353 Dygraph
.round_
= function(num
, places
) {
354 var shift
= Math
.pow(10, places
);
355 return Math
.round(num
* shift
)/shift
;
360 * Implementation of binary search over an array.
361 * Currently does not work when val is outside the range of arry's values.
362 * @param { Integer } val the value to search for
363 * @param { Integer[] } arry is the value over which to search
364 * @param { Integer } abs If abs > 0, find the lowest entry greater than val
365 * If abs < 0, find the highest entry less than val.
366 * if abs == 0, find the entry that equals val.
367 * @param { Integer } [low] The first index in arry to consider (optional)
368 * @param { Integer } [high] The last index in arry to consider (optional)
370 Dygraph
.binarySearch
= function(val
, arry
, abs
, low
, high
) {
371 if (low
== null || high
== null) {
373 high
= arry
.length
- 1;
381 var validIndex
= function(idx
) {
382 return idx
>= 0 && idx
< arry
.length
;
384 var mid
= parseInt((low
+ high
) / 2);
385 var element
= arry
[mid
];
386 if (element
== val
) {
391 // Accept if element > val, but also if prior element < val.
393 if (validIndex(idx
) && arry
[idx
] < val
) {
397 return Dygraph
.binarySearch(val
, arry
, abs
, low
, mid
- 1);
401 // Accept if element < val, but also if prior element > val.
403 if (validIndex(idx
) && arry
[idx
] > val
) {
407 return Dygraph
.binarySearch(val
, arry
, abs
, mid
+ 1, high
);
413 * Parses a date, returning the number of milliseconds since epoch. This can be
414 * passed in as an xValueParser in the Dygraph constructor.
415 * TODO(danvk): enumerate formats that this understands.
416 * @param {String} A date in YYYYMMDD format.
417 * @return {Number} Milliseconds since epoch.
419 Dygraph
.dateParser
= function(dateStr
) {
422 if (dateStr
.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12'
423 dateStrSlashed
= dateStr
.replace("-", "/", "g");
424 while (dateStrSlashed
.search("-") != -1) {
425 dateStrSlashed
= dateStrSlashed
.replace("-", "/");
427 d
= Dygraph
.dateStrToMillis(dateStrSlashed
);
428 } else if (dateStr
.length
== 8) { // e.g. '20090712'
429 // TODO(danvk): remove support for this format. It's confusing.
430 dateStrSlashed
= dateStr
.substr(0,4) + "/" + dateStr
.substr(4,2)
431 + "/" + dateStr
.substr(6,2);
432 d
= Dygraph
.dateStrToMillis(dateStrSlashed
);
434 // Any format that Date.parse will accept, e.g. "2009/07/12" or
435 // "2009/07/12 12:34:56"
436 d
= Dygraph
.dateStrToMillis(dateStr
);
439 if (!d
|| isNaN(d
)) {
440 Dygraph
.error("Couldn't parse " + dateStr
+ " as a date");
447 * This is identical to JavaScript's built-in Date.parse() method, except that
448 * it doesn't get replaced with an incompatible method by aggressive JS
449 * libraries like MooTools or Joomla.
450 * @param { String } str The date string, e.g. "2011/05/06"
451 * @return { Integer } millis since epoch
453 Dygraph
.dateStrToMillis
= function(str
) {
454 return new Date(str
).getTime();
457 // These functions are all based on MochiKit.
459 * Copies all the properties from o to self.
463 Dygraph
.update
= function (self
, o
) {
464 if (typeof(o
) != 'undefined' && o
!== null) {
466 if (o
.hasOwnProperty(k
)) {
477 Dygraph
.isArrayLike
= function (o
) {
480 (typ
!= 'object' && !(typ
== 'function' &&
481 typeof(o
.item
) == 'function')) ||
483 typeof(o
.length
) != 'number' ||
494 Dygraph
.isDateLike
= function (o
) {
495 if (typeof(o
) != "object" || o
=== null ||
496 typeof(o
.getTime
) != 'function') {
505 Dygraph
.clone
= function(o
) {
506 // TODO(danvk): figure out how MochiKit's version works
508 for (var i
= 0; i
< o
.length
; i
++) {
509 if (Dygraph
.isArrayLike(o
[i
])) {
510 r
.push(Dygraph
.clone(o
[i
]));
520 * Create a new canvas element. This is more complex than a simple
521 * document.createElement("canvas") because of IE and excanvas.
523 Dygraph
.createCanvas
= function() {
524 var canvas
= document
.createElement("canvas");
526 isIE
= (/MSIE/.test(navigator
.userAgent
) && !window
.opera
);
527 if (isIE
&& (typeof(G_vmlCanvasManager
) != 'undefined')) {
528 canvas
= G_vmlCanvasManager
.initElement(canvas
);