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 Dygraph
.LOG_SCALE
= 10;
15 Dygraph
.LN_TEN
= Math
.log(Dygraph
.LOG_SCALE
);
18 Dygraph
.log10
= function(x
) {
19 return Math
.log(x
) / Dygraph
.LN_TEN
;
22 // Various logging levels.
28 // TODO(danvk): any way I can get the line numbers to be this.warn call?
31 * Log an error on the JS console at the given severity.
32 * @param { Integer } severity One of Dygraph.{DEBUG,INFO,WARNING,ERROR}
33 * @param { String } The message to log.
35 Dygraph
.log
= function(severity
, message
) {
36 if (typeof(console
) != 'undefined') {
39 console
.debug('dygraphs: ' + message
);
42 console
.info('dygraphs: ' + message
);
45 console
.warn('dygraphs: ' + message
);
48 console
.error('dygraphs: ' + message
);
55 Dygraph
.info
= function(message
) {
56 Dygraph
.log(Dygraph
.INFO
, message
);
59 Dygraph
.prototype.info
= Dygraph
.info
;
62 Dygraph
.warn
= function(message
) {
63 Dygraph
.log(Dygraph
.WARNING
, message
);
66 Dygraph
.prototype.warn
= Dygraph
.warn
;
69 Dygraph
.error
= function(message
) {
70 Dygraph
.log(Dygraph
.ERROR
, message
);
73 Dygraph
.prototype.error
= Dygraph
.error
;
77 * Return the 2d context for a dygraph canvas.
79 * This method is only exposed for the sake of replacing the function in
80 * automated tests, e.g.
82 * var oldFunc = Dygraph.getContext();
83 * Dygraph.getContext = function(canvas) {
84 * var realContext = oldFunc(canvas);
85 * return new Proxy(realContext);
88 Dygraph
.getContext
= function(canvas
) {
89 return canvas
.getContext("2d");
94 * Add an event handler. This smooths a difference between IE and the rest of
96 * @param { DOM element } elem The element to add the event to.
97 * @param { String } type The type of the event, e.g. 'click' or 'mousemove'.
98 * @param { Function } fn The function to call on the event. The function takes
99 * one parameter: the event object.
101 Dygraph
.addEvent
= function addEvent(elem
, type
, fn
) {
102 if (elem
.addEventListener
) {
103 elem
.addEventListener(type
, fn
, false);
105 elem
[type
+fn
] = function(){fn(window
.event
);};
106 elem
.attachEvent('on'+type
, elem
[type
+fn
]);
112 * Remove an event handler. This smooths a difference between IE and the rest of
114 * @param { DOM element } elem The element to add the event to.
115 * @param { String } type The type of the event, e.g. 'click' or 'mousemove'.
116 * @param { Function } fn The function to call on the event. The function takes
117 * one parameter: the event object.
119 Dygraph
.removeEvent
= function addEvent(elem
, type
, fn
) {
120 if (elem
.removeEventListener
) {
121 elem
.removeEventListener(type
, fn
, false);
123 elem
.detachEvent('on'+type
, elem
[type
+fn
]);
124 elem
[type
+fn
] = null;
130 * Cancels further processing of an event. This is useful to prevent default
131 * browser actions, e.g. highlighting text on a double-click.
132 * Based on the article at
133 * http://www.switchonthecode.com/tutorials/javascript-tutorial-the-scroll-wheel
134 * @param { Event } e The event whose normal behavior should be canceled.
136 Dygraph
.cancelEvent
= function(e
) {
137 e
= e
? e
: window
.event
;
138 if (e
.stopPropagation
) {
141 if (e
.preventDefault
) {
144 e
.cancelBubble
= true;
146 e
.returnValue
= false;
151 * Convert hsv values to an rgb(r,g,b) string. Taken from MochiKit.Color. This
152 * is used to generate default series colors which are evenly spaced on the
154 * @param { Number } hue Range is 0.0-1.0.
155 * @param { Number } saturation Range is 0.0-1.0.
156 * @param { Number } value Range is 0.0-1.0.
157 * @return { String } "rgb(r,g,b)" where r, g and b range from 0-255.
160 Dygraph
.hsvToRGB
= function (hue
, saturation
, value
) {
164 if (saturation
=== 0) {
169 var i
= Math
.floor(hue
* 6);
170 var f
= (hue
* 6) - i
;
171 var p
= value
* (1 - saturation
);
172 var q
= value
* (1 - (saturation
* f
));
173 var t
= value
* (1 - (saturation
* (1 - f
)));
175 case 1: red
= q
; green
= value
; blue
= p
; break;
176 case 2: red
= p
; green
= value
; blue
= t
; break;
177 case 3: red
= p
; green
= q
; blue
= value
; break;
178 case 4: red
= t
; green
= p
; blue
= value
; break;
179 case 5: red
= value
; green
= p
; blue
= q
; break;
180 case 6: // fall through
181 case 0: red
= value
; green
= t
; blue
= p
; break;
184 red
= Math
.floor(255 * red
+ 0.5);
185 green
= Math
.floor(255 * green
+ 0.5);
186 blue
= Math
.floor(255 * blue
+ 0.5);
187 return 'rgb(' + red
+ ',' + green
+ ',' + blue
+ ')';
190 // The following functions are from quirksmode.org with a modification for Safari from
191 // http://blog.firetree.net/2005/07/04/javascript-find-position/
192 // http://www.quirksmode.org/js
/findpos
.html
193 // ... and modifications to support scrolling divs.
196 * Find the x-coordinate of the supplied object relative to the left side
200 Dygraph
.findPosX
= function(obj
) {
202 if(obj
.offsetParent
) {
205 curleft
+= copyObj
.offsetLeft
;
206 if(!copyObj
.offsetParent
) {
209 copyObj
= copyObj
.offsetParent
;
214 // This handles the case where the object is inside a scrolled div.
215 while(obj
&& obj
!= document
.body
) {
216 curleft
-= obj
.scrollLeft
;
217 obj
= obj
.parentNode
;
223 * Find the y-coordinate of the supplied object relative to the top of the
227 Dygraph
.findPosY
= function(obj
) {
229 if(obj
.offsetParent
) {
232 curtop
+= copyObj
.offsetTop
;
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 curtop
-= obj
.scrollTop
;
244 obj
= obj
.parentNode
;
251 * Returns the x-coordinate of the event in a coordinate system where the
252 * top-left corner of the page (not the window) is (0,0).
253 * Taken from MochiKit.Signal
255 Dygraph
.pageX
= function(e
) {
257 return (!e
.pageX
|| e
.pageX
< 0) ? 0 : e
.pageX
;
260 var b
= document
.body
;
262 (de
.scrollLeft
|| b
.scrollLeft
) -
263 (de
.clientLeft
|| 0);
269 * Returns the y-coordinate of the event in a coordinate system where the
270 * top-left corner of the page (not the window) is (0,0).
271 * Taken from MochiKit.Signal
273 Dygraph
.pageY
= function(e
) {
275 return (!e
.pageY
|| e
.pageY
< 0) ? 0 : e
.pageY
;
278 var b
= document
.body
;
280 (de
.scrollTop
|| b
.scrollTop
) -
287 * @param { Number } x The number to consider.
288 * @return { Boolean } Whether the number is zero or NaN.
290 // TODO(danvk): rename this function to something like 'isNonZeroNan'.
291 Dygraph
.isOK
= function(x
) {
292 return x
&& !isNaN(x
);
296 * Number formatting function which mimicks the behavior of %g in printf, i.e.
297 * either exponential or fixed format (without trailing 0s) is used depending on
298 * the length of the generated string. The advantage of this format is that
299 * there is a predictable upper bound on the resulting string length,
300 * significant figures are not dropped, and normal numbers are not displayed in
301 * exponential notation.
303 * NOTE: JavaScript's native toPrecision() is NOT a drop-in replacement for %g.
304 * It creates strings which are too long for absolute values between 10^-4 and
305 * 10^-6, e.g. '0.00001' instead of '1e-5'. See tests/number-format.html for
308 * @param {Number} x The number to format
309 * @param {Number} opt_precision The precision to use, default 2.
310 * @return {String} A string formatted like %g in printf. The max generated
311 * string length should be precision + 6 (e.g 1.123e+300).
313 Dygraph
.floatFormat
= function(x
, opt_precision
) {
314 // Avoid invalid precision values; [1, 21] is the valid range.
315 var p
= Math
.min(Math
.max(1, opt_precision
|| 2), 21);
317 // This is deceptively simple. The actual algorithm comes from:
319 // Max allowed length = p + 4
320 // where 4 comes from 'e+n' and '.'.
322 // Length of fixed format = 2 + y + p
323 // where 2 comes from '0.' and y = # of leading zeroes.
325 // Equating the two and solving for y yields y = 2, or 0.00xxxx which is
328 // Since the behavior of toPrecision() is identical for larger numbers, we
329 // don't have to worry about the other bound.
331 // Finally, the argument for toExponential() is the number of trailing digits,
332 // so we take off 1 for the value before the '.'.
333 return (Math
.abs(x
) < 1.0e-3 && x
!= 0.0) ?
334 x
.toExponential(p
- 1) : x
.toPrecision(p
);
339 * Converts '9' to '09' (useful for dates)
341 Dygraph
.zeropad
= function(x
) {
342 if (x
< 10) return "0" + x
; else return "" + x
;
346 * Return a string version of the hours, minutes and seconds portion of a date.
347 * @param {Number} date The JavaScript date (ms since epoch)
348 * @return {String} A time of the form "HH:MM:SS"
351 Dygraph
.hmsString_
= function(date
) {
352 var zeropad
= Dygraph
.zeropad
;
353 var d
= new Date(date
);
354 if (d
.getSeconds()) {
355 return zeropad(d
.getHours()) + ":" +
356 zeropad(d
.getMinutes()) + ":" +
357 zeropad(d
.getSeconds());
359 return zeropad(d
.getHours()) + ":" + zeropad(d
.getMinutes());
364 * Round a number to the specified number of digits past the decimal point.
365 * @param {Number} num The number to round
366 * @param {Number} places The number of decimals to which to round
367 * @return {Number} The rounded number
370 Dygraph
.round_
= function(num
, places
) {
371 var shift
= Math
.pow(10, places
);
372 return Math
.round(num
* shift
)/shift
;
377 * Implementation of binary search over an array.
378 * Currently does not work when val is outside the range of arry's values.
379 * @param { Integer } val the value to search for
380 * @param { Integer[] } arry is the value over which to search
381 * @param { Integer } abs If abs > 0, find the lowest entry greater than val
382 * If abs < 0, find the highest entry less than val.
383 * if abs == 0, find the entry that equals val.
384 * @param { Integer } [low] The first index in arry to consider (optional)
385 * @param { Integer } [high] The last index in arry to consider (optional)
387 Dygraph
.binarySearch
= function(val
, arry
, abs
, low
, high
) {
388 if (low
== null || high
== null) {
390 high
= arry
.length
- 1;
398 var validIndex
= function(idx
) {
399 return idx
>= 0 && idx
< arry
.length
;
401 var mid
= parseInt((low
+ high
) / 2);
402 var element
= arry
[mid
];
403 if (element
== val
) {
408 // Accept if element > val, but also if prior element < val.
410 if (validIndex(idx
) && arry
[idx
] < val
) {
414 return Dygraph
.binarySearch(val
, arry
, abs
, low
, mid
- 1);
418 // Accept if element < val, but also if prior element > val.
420 if (validIndex(idx
) && arry
[idx
] > val
) {
424 return Dygraph
.binarySearch(val
, arry
, abs
, mid
+ 1, high
);
430 * Parses a date, returning the number of milliseconds since epoch. This can be
431 * passed in as an xValueParser in the Dygraph constructor.
432 * TODO(danvk): enumerate formats that this understands.
433 * @param {String} A date in YYYYMMDD format.
434 * @return {Number} Milliseconds since epoch.
436 Dygraph
.dateParser
= function(dateStr
) {
439 if (dateStr
.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12'
440 dateStrSlashed
= dateStr
.replace("-", "/", "g");
441 while (dateStrSlashed
.search("-") != -1) {
442 dateStrSlashed
= dateStrSlashed
.replace("-", "/");
444 d
= Dygraph
.dateStrToMillis(dateStrSlashed
);
445 } else if (dateStr
.length
== 8) { // e.g. '20090712'
446 // TODO(danvk): remove support for this format. It's confusing.
447 dateStrSlashed
= dateStr
.substr(0,4) + "/" + dateStr
.substr(4,2)
448 + "/" + dateStr
.substr(6,2);
449 d
= Dygraph
.dateStrToMillis(dateStrSlashed
);
451 // Any format that Date.parse will accept, e.g. "2009/07/12" or
452 // "2009/07/12 12:34:56"
453 d
= Dygraph
.dateStrToMillis(dateStr
);
456 if (!d
|| isNaN(d
)) {
457 Dygraph
.error("Couldn't parse " + dateStr
+ " as a date");
464 * This is identical to JavaScript's built-in Date.parse() method, except that
465 * it doesn't get replaced with an incompatible method by aggressive JS
466 * libraries like MooTools or Joomla.
467 * @param { String } str The date string, e.g. "2011/05/06"
468 * @return { Integer } millis since epoch
470 Dygraph
.dateStrToMillis
= function(str
) {
471 return new Date(str
).getTime();
474 // These functions are all based on MochiKit.
476 * Copies all the properties from o to self.
480 Dygraph
.update
= function (self
, o
) {
481 if (typeof(o
) != 'undefined' && o
!== null) {
483 if (o
.hasOwnProperty(k
)) {
492 * Copies all the properties from o to self.
496 Dygraph
.updateDeep
= function (self
, o
) {
497 if (typeof(o
) != 'undefined' && o
!== null) {
499 if (o
.hasOwnProperty(k
)) {
502 } else if (Dygraph
.isArrayLike(o
[k
])) {
503 self
[k
] = o
[k
].slice();
504 } else if (o
[k
] instanceof Node
) {
505 // DOM objects are shallowly-copied.
507 } else if (typeof(o
[k
]) == 'object') {
508 if (typeof(self
[k
]) != 'object') {
511 Dygraph
.updateDeep(self
[k
], o
[k
]);
524 Dygraph
.isArrayLike
= function (o
) {
527 (typ
!= 'object' && !(typ
== 'function' &&
528 typeof(o
.item
) == 'function')) ||
530 typeof(o
.length
) != 'number' ||
541 Dygraph
.isDateLike
= function (o
) {
542 if (typeof(o
) != "object" || o
=== null ||
543 typeof(o
.getTime
) != 'function') {
550 * Note: this only seems to work for arrays.
553 Dygraph
.clone
= function(o
) {
554 // TODO(danvk): figure out how MochiKit's version works
556 for (var i
= 0; i
< o
.length
; i
++) {
557 if (Dygraph
.isArrayLike(o
[i
])) {
558 r
.push(Dygraph
.clone(o
[i
]));
568 * Create a new canvas element. This is more complex than a simple
569 * document.createElement("canvas") because of IE and excanvas.
571 Dygraph
.createCanvas
= function() {
572 var canvas
= document
.createElement("canvas");
574 isIE
= (/MSIE/.test(navigator
.userAgent
) && !window
.opera
);
575 if (isIE
&& (typeof(G_vmlCanvasManager
) != 'undefined')) {
576 canvas
= G_vmlCanvasManager
.initElement(canvas
);
584 * This function will scan the option list and determine if they
585 * require us to recalculate the pixel positions of each point.
586 * @param { List } a list of options to check.
587 * @return { Boolean } true if the graph needs new points else false.
589 Dygraph
.isPixelChangingOptionList
= function(labels
, attrs
) {
590 // A whitelist of options that do not change pixel positions.
591 var pixelSafeOptions
= {
592 'annotationClickHandler': true,
593 'annotationDblClickHandler': true,
594 'annotationMouseOutHandler': true,
595 'annotationMouseOverHandler': true,
596 'axisLabelColor': true,
597 'axisLineColor': true,
598 'axisLineWidth': true,
599 'clickCallback': true,
600 'colorSaturation': true,
603 'connectSeparatedPoints': true,
604 'digitsAfterDecimal': true,
605 'drawCallback': true,
610 'gridLineColor': true,
611 'gridLineWidth': true,
612 'hideOverlayOnMouseOut': true,
613 'highlightCallback': true,
614 'highlightCircleSize': true,
615 'interactionModel': true,
616 'isZoomedIgnoreProgrammaticZoom': true,
618 'labelsDivStyles': true,
619 'labelsDivWidth': true,
622 'labelsSeparateLines': true,
623 'labelsShowZeroValues': true,
625 'maxNumberWidth': true,
626 'panEdgeFraction': true,
627 'pixelsPerYLabel': true,
628 'pointClickCallback': true,
630 'rangeSelectorPlotFillColor': true,
631 'rangeSelectorPlotStrokeColor': true,
632 'showLabelsOnHighlight': true,
636 'underlayCallback': true,
637 'unhighlightCallback': true,
638 'xAxisLabelFormatter': true,
640 'xValueFormatter': true,
641 'yAxisLabelFormatter': true,
642 'yValueFormatter': true,
646 // Assume that we do not require new points.
647 // This will change to true if we actually do need new points.
648 var requiresNewPoints
= false;
650 // Create a dictionary of series names for faster lookup.
651 // If there are no labels, then the dictionary stays empty.
652 var seriesNamesDictionary
= { };
654 for (var i
= 1; i
< labels
.length
; i
++) {
655 seriesNamesDictionary
[labels
[i
]] = true;
659 // Iterate through the list of updated options.
660 for (property
in attrs
) {
661 // Break early if we already know we need new points from a previous option.
662 if (requiresNewPoints
) {
665 if (attrs
.hasOwnProperty(property
)) {
666 // Find out of this field is actually a series specific options list.
667 if (seriesNamesDictionary
[property
]) {
668 // This property value is a list of options for this series.
669 // If any of these sub properties are not pixel safe, set the flag.
670 for (subProperty
in attrs
[property
]) {
671 // Break early if we already know we need new points from a previous option.
672 if (requiresNewPoints
) {
675 if (attrs
[property
].hasOwnProperty(subProperty
) && !pixelSafeOptions
[subProperty
]) {
676 requiresNewPoints
= true;
679 // If this was not a series specific option list, check if its a pixel changing property.
680 } else if (!pixelSafeOptions
[property
]) {
681 requiresNewPoints
= true;
686 return requiresNewPoints
;