factor out dygraph-utils.js
[dygraphs.git] / dygraph-utils.js
CommitLineData
dedb4f5f
DV
1
2
3Dygraph.LOG_SCALE = 10;
4Dygraph.LN_TEN = Math.log(Dygraph.LOG_SCALE);
5
6/** @private */
7Dygraph.log10 = function(x) {
8 return Math.log(x) / Dygraph.LN_TEN;
9}
10
11// Various logging levels.
12Dygraph.DEBUG = 1;
13Dygraph.INFO = 2;
14Dygraph.WARNING = 3;
15Dygraph.ERROR = 3;
16
17// TODO(danvk): any way I can get the line numbers to be this.warn call?
18/**
19 * @private
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.
23 */
24Dygraph.log = function(severity, message) {
25 if (typeof(console) != 'undefined') {
26 switch (severity) {
27 case Dygraph.DEBUG:
28 console.debug('dygraphs: ' + message);
29 break;
30 case Dygraph.INFO:
31 console.info('dygraphs: ' + message);
32 break;
33 case Dygraph.WARNING:
34 console.warn('dygraphs: ' + message);
35 break;
36 case Dygraph.ERROR:
37 console.error('dygraphs: ' + message);
38 break;
39 }
40 }
41};
42
43/** @private */
44Dygraph.info = function(message) {
45 Dygraph.log(Dygraph.INFO, message);
46};
47/** @private */
48Dygraph.prototype.info = Dygraph.info;
49
50/** @private */
51Dygraph.warn = function(message) {
52 Dygraph.log(Dygraph.WARNING, message);
53};
54/** @private */
55Dygraph.prototype.warn = Dygraph.warn;
56
57/** @private */
58Dygraph.error = function(message) {
59 Dygraph.log(Dygraph.ERROR, message);
60};
61/** @private */
62Dygraph.prototype.error = Dygraph.error;
63
64/**
65 * @private
66 * Return the 2d context for a dygraph canvas.
67 *
68 * This method is only exposed for the sake of replacing the function in
69 * automated tests, e.g.
70 *
71 * var oldFunc = Dygraph.getContext();
72 * Dygraph.getContext = function(canvas) {
73 * var realContext = oldFunc(canvas);
74 * return new Proxy(realContext);
75 * };
76 */
77Dygraph.getContext = function(canvas) {
78 return canvas.getContext("2d");
79};
80
81/**
82 * @private
83 * Add an event handler. This smooths a difference between IE and the rest of
84 * the world.
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.
89 */
90Dygraph.addEvent = function(el, evt, fn) {
91 var normed_fn = function(e) {
92 if (!e) var e = window.event;
93 fn(e);
94 };
95 if (window.addEventListener) { // Mozilla, Netscape, Firefox
96 el.addEventListener(evt, normed_fn, false);
97 } else { // IE
98 el.attachEvent('on' + evt, normed_fn);
99 }
100};
101
102/**
103 * @private
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.
109 */
110Dygraph.cancelEvent = function(e) {
111 e = e ? e : window.event;
112 if (e.stopPropagation) {
113 e.stopPropagation();
114 }
115 if (e.preventDefault) {
116 e.preventDefault();
117 }
118 e.cancelBubble = true;
119 e.cancel = true;
120 e.returnValue = false;
121 return false;
122};
123
124/**
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
127 * color wheel.
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.
132 * @private
133 */
134Dygraph.hsvToRGB = function (hue, saturation, value) {
135 var red;
136 var green;
137 var blue;
138 if (saturation === 0) {
139 red = value;
140 green = value;
141 blue = value;
142 } else {
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)));
148 switch (i) {
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;
156 }
157 }
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 + ')';
162};
163
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
167
168/** @private */
169Dygraph.findPosX = function(obj) {
170 var curleft = 0;
171 if(obj.offsetParent)
172 while(1)
173 {
174 curleft += obj.offsetLeft;
175 if(!obj.offsetParent)
176 break;
177 obj = obj.offsetParent;
178 }
179 else if(obj.x)
180 curleft += obj.x;
181 return curleft;
182};
183
184/** @private */
185Dygraph.findPosY = function(obj) {
186 var curtop = 0;
187 if(obj.offsetParent)
188 while(1)
189 {
190 curtop += obj.offsetTop;
191 if(!obj.offsetParent)
192 break;
193 obj = obj.offsetParent;
194 }
195 else if(obj.y)
196 curtop += obj.y;
197 return curtop;
198};
199
200/**
201 * @private
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
205 */
206Dygraph.pageX = function(e) {
207 if (e.pageX) {
208 return (!e.pageX || e.pageX < 0) ? 0 : e.pageX;
209 } else {
210 var de = document;
211 var b = document.body;
212 return e.clientX +
213 (de.scrollLeft || b.scrollLeft) -
214 (de.clientLeft || 0);
215 }
216};
217
218/**
219 * @private
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
223 */
224Dygraph.pageY = function(e) {
225 if (e.pageY) {
226 return (!e.pageY || e.pageY < 0) ? 0 : e.pageY;
227 } else {
228 var de = document;
229 var b = document.body;
230 return e.clientY +
231 (de.scrollTop || b.scrollTop) -
232 (de.clientTop || 0);
233 }
234};
235
236/**
237 * @private
238 * @param { Number } x The number to consider.
239 * @return { Boolean } Whether the number is zero or NaN.
240 */
241// TODO(danvk): rename this function to something like 'isNonZeroNan'.
242Dygraph.isOK = function(x) {
243 return x && !isNaN(x);
244};
245
246/**
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.
253 *
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
257 * output examples.
258 *
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).
263 */
264Dygraph.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);
267
268 // This is deceptively simple. The actual algorithm comes from:
269 //
270 // Max allowed length = p + 4
271 // where 4 comes from 'e+n' and '.'.
272 //
273 // Length of fixed format = 2 + y + p
274 // where 2 comes from '0.' and y = # of leading zeroes.
275 //
276 // Equating the two and solving for y yields y = 2, or 0.00xxxx which is
277 // 1.0e-3.
278 //
279 // Since the behavior of toPrecision() is identical for larger numbers, we
280 // don't have to worry about the other bound.
281 //
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);
286};
287
288/**
289 * @private
290 * Converts '9' to '09' (useful for dates)
291 */
292Dygraph.zeropad = function(x) {
293 if (x < 10) return "0" + x; else return "" + x;
294};
295
296/**
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"
300 * @private
301 */
302Dygraph.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());
309 } else {
310 return zeropad(d.getHours()) + ":" + zeropad(d.getMinutes());
311 }
312};
313
314/**
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"
318 * @private
319 */
320Dygraph.dateString_ = function(date) {
321 var zeropad = Dygraph.zeropad;
322 var d = new Date(date);
323
324 // Get the year:
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());
330
331 var ret = "";
332 var frac = d.getHours() * 3600 + d.getMinutes() * 60 + d.getSeconds();
333 if (frac) ret = " " + Dygraph.hmsString_(date);
334
335 return year + "/" + month + "/" + day + ret;
336};
337
338/**
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
343 * @private
344 */
345Dygraph.round_ = function(num, places) {
346 var shift = Math.pow(10, places);
347 return Math.round(num * shift)/shift;
348};
349
350/**
351 * @private
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)
361 */
362Dygraph.binarySearch = function(val, arry, abs, low, high) {
363 if (low == null || high == null) {
364 low = 0;
365 high = arry.length - 1;
366 }
367 if (low > high) {
368 return -1;
369 }
370 if (abs == null) {
371 abs = 0;
372 }
373 var validIndex = function(idx) {
374 return idx >= 0 && idx < arry.length;
375 }
376 var mid = parseInt((low + high) / 2);
377 var element = arry[mid];
378 if (element == val) {
379 return mid;
380 }
381 if (element > val) {
382 if (abs > 0) {
383 // Accept if element > val, but also if prior element < val.
384 var idx = mid - 1;
385 if (validIndex(idx) && arry[idx] < val) {
386 return mid;
387 }
388 }
389 return Dygraph.binarySearch(val, arry, abs, low, mid - 1);
390 }
391 if (element < val) {
392 if (abs < 0) {
393 // Accept if element < val, but also if prior element > val.
394 var idx = mid + 1;
395 if (validIndex(idx) && arry[idx] > val) {
396 return mid;
397 }
398 }
399 return Dygraph.binarySearch(val, arry, abs, mid + 1, high);
400 }
401};
402
403/**
404 * @private
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.
410 */
411Dygraph.dateParser = function(dateStr) {
412 var dateStrSlashed;
413 var d;
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("-", "/");
418 }
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);
425 } else {
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);
429 }
430
431 if (!d || isNaN(d)) {
432 Dygraph.error("Couldn't parse " + dateStr + " as a date");
433 }
434 return d;
435};
436
437/**
438 * @private
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
444 */
445Dygraph.dateStrToMillis = function(str) {
446 return new Date(str).getTime();
447};
448
449// These functions are all based on MochiKit.
450/**
451 * Copies all the properties from o to self.
452 *
453 * @private
454 */
455Dygraph.update = function (self, o) {
456 if (typeof(o) != 'undefined' && o !== null) {
457 for (var k in o) {
458 if (o.hasOwnProperty(k)) {
459 self[k] = o[k];
460 }
461 }
462 }
463 return self;
464};
465
466/**
467 * @private
468 */
469Dygraph.isArrayLike = function (o) {
470 var typ = typeof(o);
471 if (
472 (typ != 'object' && !(typ == 'function' &&
473 typeof(o.item) == 'function')) ||
474 o === null ||
475 typeof(o.length) != 'number' ||
476 o.nodeType === 3
477 ) {
478 return false;
479 }
480 return true;
481};
482
483/**
484 * @private
485 */
486Dygraph.isDateLike = function (o) {
487 if (typeof(o) != "object" || o === null ||
488 typeof(o.getTime) != 'function') {
489 return false;
490 }
491 return true;
492};
493
494/**
495 * @private
496 */
497Dygraph.clone = function(o) {
498 // TODO(danvk): figure out how MochiKit's version works
499 var r = [];
500 for (var i = 0; i < o.length; i++) {
501 if (Dygraph.isArrayLike(o[i])) {
502 r.push(Dygraph.clone(o[i]));
503 } else {
504 r.push(o[i]);
505 }
506 }
507 return r;
508};
509
510/**
511 * @private
512 * Create a new canvas element. This is more complex than a simple
513 * document.createElement("canvas") because of IE and excanvas.
514 */
515Dygraph.createCanvas = function() {
516 var canvas = document.createElement("canvas");
517
518 isIE = (/MSIE/.test(navigator.userAgent) && !window.opera);
519 if (isIE && (typeof(G_vmlCanvasManager) != 'undefined')) {
520 canvas = G_vmlCanvasManager.initElement(canvas);
521 }
522
523 return canvas;
524};