3 Dygraph
.LOG_SCALE
= 10;
4 Dygraph
.LN_TEN
= Math
.log(Dygraph
.LOG_SCALE
);
7 Dygraph
.log10
= function(x
) {
8 return Math
.log(x
) / Dygraph
.LN_TEN
;
11 // Various logging levels.
17 // TODO(danvk): any way I can get the line numbers to be this.warn call?
20 * Log an error on the JS console at the given severity.
21 * @param { Integer } severity One of Dygraph.{DEBUG,INFO,WARNING,ERROR}
22 * @param { String } The message to log.
24 Dygraph
.log
= function(severity
, message
) {
25 if (typeof(console
) != 'undefined') {
28 console
.debug('dygraphs: ' + message
);
31 console
.info('dygraphs: ' + message
);
34 console
.warn('dygraphs: ' + message
);
37 console
.error('dygraphs: ' + message
);
44 Dygraph
.info
= function(message
) {
45 Dygraph
.log(Dygraph
.INFO
, message
);
48 Dygraph
.prototype.info
= Dygraph
.info
;
51 Dygraph
.warn
= function(message
) {
52 Dygraph
.log(Dygraph
.WARNING
, message
);
55 Dygraph
.prototype.warn
= Dygraph
.warn
;
58 Dygraph
.error
= function(message
) {
59 Dygraph
.log(Dygraph
.ERROR
, message
);
62 Dygraph
.prototype.error
= Dygraph
.error
;
66 * Return the 2d context for a dygraph canvas.
68 * This method is only exposed for the sake of replacing the function in
69 * automated tests, e.g.
71 * var oldFunc = Dygraph.getContext();
72 * Dygraph.getContext = function(canvas) {
73 * var realContext = oldFunc(canvas);
74 * return new Proxy(realContext);
77 Dygraph
.getContext
= function(canvas
) {
78 return canvas
.getContext("2d");
83 * Add an event handler. This smooths a difference between IE and the rest of
85 * @param { DOM element } el The element to add the event to.
86 * @param { String } evt The name of the event, e.g. 'click' or 'mousemove'.
87 * @param { Function } fn The function to call on the event. The function takes
88 * one parameter: the event object.
90 Dygraph
.addEvent
= function(el
, evt
, fn
) {
91 var normed_fn
= function(e
) {
92 if (!e
) var e
= window
.event
;
95 if (window
.addEventListener
) { // Mozilla, Netscape, Firefox
96 el
.addEventListener(evt
, normed_fn
, false);
98 el
.attachEvent('on' + evt
, normed_fn
);
104 * Cancels further processing of an event. This is useful to prevent default
105 * browser actions, e.g. highlighting text on a double-click.
106 * Based on the article at
107 * http://www.switchonthecode.com/tutorials/javascript-tutorial-the-scroll-wheel
108 * @param { Event } e The event whose normal behavior should be canceled.
110 Dygraph
.cancelEvent
= function(e
) {
111 e
= e
? e
: window
.event
;
112 if (e
.stopPropagation
) {
115 if (e
.preventDefault
) {
118 e
.cancelBubble
= true;
120 e
.returnValue
= false;
125 * Convert hsv values to an rgb(r,g,b) string. Taken from MochiKit.Color. This
126 * is used to generate default series colors which are evenly spaced on the
128 * @param { Number } hue Range is 0.0-1.0.
129 * @param { Number } saturation Range is 0.0-1.0.
130 * @param { Number } value Range is 0.0-1.0.
131 * @return { String } "rgb(r,g,b)" where r, g and b range from 0-255.
134 Dygraph
.hsvToRGB
= function (hue
, saturation
, value
) {
138 if (saturation
=== 0) {
143 var i
= Math
.floor(hue
* 6);
144 var f
= (hue
* 6) - i
;
145 var p
= value
* (1 - saturation
);
146 var q
= value
* (1 - (saturation
* f
));
147 var t
= value
* (1 - (saturation
* (1 - f
)));
149 case 1: red
= q
; green
= value
; blue
= p
; break;
150 case 2: red
= p
; green
= value
; blue
= t
; break;
151 case 3: red
= p
; green
= q
; blue
= value
; break;
152 case 4: red
= t
; green
= p
; blue
= value
; break;
153 case 5: red
= value
; green
= p
; blue
= q
; break;
154 case 6: // fall through
155 case 0: red
= value
; green
= t
; blue
= p
; break;
158 red
= Math
.floor(255 * red
+ 0.5);
159 green
= Math
.floor(255 * green
+ 0.5);
160 blue
= Math
.floor(255 * blue
+ 0.5);
161 return 'rgb(' + red
+ ',' + green
+ ',' + blue
+ ')';
164 // The following functions are from quirksmode.org with a modification for Safari from
165 // http://blog.firetree.net/2005/07/04/javascript-find-position/
166 // http://www.quirksmode.org/js
/findpos
.html
169 Dygraph
.findPosX
= function(obj
) {
174 curleft
+= obj
.offsetLeft
;
175 if(!obj
.offsetParent
)
177 obj
= obj
.offsetParent
;
185 Dygraph
.findPosY
= function(obj
) {
190 curtop
+= obj
.offsetTop
;
191 if(!obj
.offsetParent
)
193 obj
= obj
.offsetParent
;
202 * Returns the x-coordinate of the event in a coordinate system where the
203 * top-left corner of the page (not the window) is (0,0).
204 * Taken from MochiKit.Signal
206 Dygraph
.pageX
= function(e
) {
208 return (!e
.pageX
|| e
.pageX
< 0) ? 0 : e
.pageX
;
211 var b
= document
.body
;
213 (de
.scrollLeft
|| b
.scrollLeft
) -
214 (de
.clientLeft
|| 0);
220 * Returns the y-coordinate of the event in a coordinate system where the
221 * top-left corner of the page (not the window) is (0,0).
222 * Taken from MochiKit.Signal
224 Dygraph
.pageY
= function(e
) {
226 return (!e
.pageY
|| e
.pageY
< 0) ? 0 : e
.pageY
;
229 var b
= document
.body
;
231 (de
.scrollTop
|| b
.scrollTop
) -
238 * @param { Number } x The number to consider.
239 * @return { Boolean } Whether the number is zero or NaN.
241 // TODO(danvk): rename this function to something like 'isNonZeroNan'.
242 Dygraph
.isOK
= function(x
) {
243 return x
&& !isNaN(x
);
247 * Number formatting function which mimicks the behavior of %g in printf, i.e.
248 * either exponential or fixed format (without trailing 0s) is used depending on
249 * the length of the generated string. The advantage of this format is that
250 * there is a predictable upper bound on the resulting string length,
251 * significant figures are not dropped, and normal numbers are not displayed in
252 * exponential notation.
254 * NOTE: JavaScript's native toPrecision() is NOT a drop-in replacement for %g.
255 * It creates strings which are too long for absolute values between 10^-4 and
256 * 10^-6, e.g. '0.00001' instead of '1e-5'. See tests/number-format.html for
259 * @param {Number} x The number to format
260 * @param {Number} opt_precision The precision to use, default 2.
261 * @return {String} A string formatted like %g in printf. The max generated
262 * string length should be precision + 6 (e.g 1.123e+300).
264 Dygraph
.floatFormat
= function(x
, opt_precision
) {
265 // Avoid invalid precision values; [1, 21] is the valid range.
266 var p
= Math
.min(Math
.max(1, opt_precision
|| 2), 21);
268 // This is deceptively simple. The actual algorithm comes from:
270 // Max allowed length = p + 4
271 // where 4 comes from 'e+n' and '.'.
273 // Length of fixed format = 2 + y + p
274 // where 2 comes from '0.' and y = # of leading zeroes.
276 // Equating the two and solving for y yields y = 2, or 0.00xxxx which is
279 // Since the behavior of toPrecision() is identical for larger numbers, we
280 // don't have to worry about the other bound.
282 // Finally, the argument for toExponential() is the number of trailing digits,
283 // so we take off 1 for the value before the '.'.
284 return (Math
.abs(x
) < 1.0e-3 && x
!= 0.0) ?
285 x
.toExponential(p
- 1) : x
.toPrecision(p
);
290 * Converts '9' to '09' (useful for dates)
292 Dygraph
.zeropad
= function(x
) {
293 if (x
< 10) return "0" + x
; else return "" + x
;
297 * Return a string version of the hours, minutes and seconds portion of a date.
298 * @param {Number} date The JavaScript date (ms since epoch)
299 * @return {String} A time of the form "HH:MM:SS"
302 Dygraph
.hmsString_
= function(date
) {
303 var zeropad
= Dygraph
.zeropad
;
304 var d
= new Date(date
);
305 if (d
.getSeconds()) {
306 return zeropad(d
.getHours()) + ":" +
307 zeropad(d
.getMinutes()) + ":" +
308 zeropad(d
.getSeconds());
310 return zeropad(d
.getHours()) + ":" + zeropad(d
.getMinutes());
315 * Convert a JS date (millis since epoch) to YYYY/MM/DD
316 * @param {Number} date The JavaScript date (ms since epoch)
317 * @return {String} A date of the form "YYYY/MM/DD"
320 Dygraph
.dateString_
= function(date
) {
321 var zeropad
= Dygraph
.zeropad
;
322 var d
= new Date(date
);
325 var year
= "" + d
.getFullYear();
326 // Get a 0 padded month string
327 var month
= zeropad(d
.getMonth() + 1); //months are 0-offset, sigh
328 // Get a 0 padded day string
329 var day
= zeropad(d
.getDate());
332 var frac
= d
.getHours() * 3600 + d
.getMinutes() * 60 + d
.getSeconds();
333 if (frac
) ret
= " " + Dygraph
.hmsString_(date
);
335 return year
+ "/" + month + "/" + day
+ ret
;
339 * Round a number to the specified number of digits past the decimal point.
340 * @param {Number} num The number to round
341 * @param {Number} places The number of decimals to which to round
342 * @return {Number} The rounded number
345 Dygraph
.round_
= function(num
, places
) {
346 var shift
= Math
.pow(10, places
);
347 return Math
.round(num
* shift
)/shift
;
352 * Implementation of binary search over an array.
353 * Currently does not work when val is outside the range of arry's values.
354 * @param { Integer } val the value to search for
355 * @param { Integer[] } arry is the value over which to search
356 * @param { Integer } abs If abs > 0, find the lowest entry greater than val
357 * If abs < 0, find the highest entry less than val.
358 * if abs == 0, find the entry that equals val.
359 * @param { Integer } [low] The first index in arry to consider (optional)
360 * @param { Integer } [high] The last index in arry to consider (optional)
362 Dygraph
.binarySearch
= function(val
, arry
, abs
, low
, high
) {
363 if (low
== null || high
== null) {
365 high
= arry
.length
- 1;
373 var validIndex
= function(idx
) {
374 return idx
>= 0 && idx
< arry
.length
;
376 var mid
= parseInt((low
+ high
) / 2);
377 var element
= arry
[mid
];
378 if (element
== val
) {
383 // Accept if element > val, but also if prior element < val.
385 if (validIndex(idx
) && arry
[idx
] < val
) {
389 return Dygraph
.binarySearch(val
, arry
, abs
, low
, mid
- 1);
393 // Accept if element < val, but also if prior element > val.
395 if (validIndex(idx
) && arry
[idx
] > val
) {
399 return Dygraph
.binarySearch(val
, arry
, abs
, mid
+ 1, high
);
405 * Parses a date, returning the number of milliseconds since epoch. This can be
406 * passed in as an xValueParser in the Dygraph constructor.
407 * TODO(danvk): enumerate formats that this understands.
408 * @param {String} A date in YYYYMMDD format.
409 * @return {Number} Milliseconds since epoch.
411 Dygraph
.dateParser
= function(dateStr
) {
414 if (dateStr
.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12'
415 dateStrSlashed
= dateStr
.replace("-", "/", "g");
416 while (dateStrSlashed
.search("-") != -1) {
417 dateStrSlashed
= dateStrSlashed
.replace("-", "/");
419 d
= Dygraph
.dateStrToMillis(dateStrSlashed
);
420 } else if (dateStr
.length
== 8) { // e.g. '20090712'
421 // TODO(danvk): remove support for this format. It's confusing.
422 dateStrSlashed
= dateStr
.substr(0,4) + "/" + dateStr
.substr(4,2)
423 + "/" + dateStr
.substr(6,2);
424 d
= Dygraph
.dateStrToMillis(dateStrSlashed
);
426 // Any format that Date.parse will accept, e.g. "2009/07/12" or
427 // "2009/07/12 12:34:56"
428 d
= Dygraph
.dateStrToMillis(dateStr
);
431 if (!d
|| isNaN(d
)) {
432 Dygraph
.error("Couldn't parse " + dateStr
+ " as a date");
439 * This is identical to JavaScript's built-in Date.parse() method, except that
440 * it doesn't get replaced with an incompatible method by aggressive JS
441 * libraries like MooTools or Joomla.
442 * @param { String } str The date string, e.g. "2011/05/06"
443 * @return { Integer } millis since epoch
445 Dygraph
.dateStrToMillis
= function(str
) {
446 return new Date(str
).getTime();
449 // These functions are all based on MochiKit.
451 * Copies all the properties from o to self.
455 Dygraph
.update
= function (self
, o
) {
456 if (typeof(o
) != 'undefined' && o
!== null) {
458 if (o
.hasOwnProperty(k
)) {
469 Dygraph
.isArrayLike
= function (o
) {
472 (typ
!= 'object' && !(typ
== 'function' &&
473 typeof(o
.item
) == 'function')) ||
475 typeof(o
.length
) != 'number' ||
486 Dygraph
.isDateLike
= function (o
) {
487 if (typeof(o
) != "object" || o
=== null ||
488 typeof(o
.getTime
) != 'function') {
497 Dygraph
.clone
= function(o
) {
498 // TODO(danvk): figure out how MochiKit's version works
500 for (var i
= 0; i
< o
.length
; i
++) {
501 if (Dygraph
.isArrayLike(o
[i
])) {
502 r
.push(Dygraph
.clone(o
[i
]));
512 * Create a new canvas element. This is more complex than a simple
513 * document.createElement("canvas") because of IE and excanvas.
515 Dygraph
.createCanvas
= function() {
516 var canvas
= document
.createElement("canvas");
518 isIE
= (/MSIE/.test(navigator
.userAgent
) && !window
.opera
);
519 if (isIE
&& (typeof(G_vmlCanvasManager
) != 'undefined')) {
520 canvas
= G_vmlCanvasManager
.initElement(canvas
);