Fix pointClickCallback and resizing coordinate weirdness when inside a
[dygraphs.git] / dygraph-utils.js
CommitLineData
004b5c90
DV
1// Copyright 2011 Dan Vanderkam (danvdk@gmail.com)
2// All Rights Reserved.
dedb4f5f 3
004b5c90
DV
4/**
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.
9 */
dedb4f5f
DV
10
11Dygraph.LOG_SCALE = 10;
12Dygraph.LN_TEN = Math.log(Dygraph.LOG_SCALE);
13
14/** @private */
15Dygraph.log10 = function(x) {
16 return Math.log(x) / Dygraph.LN_TEN;
17}
18
19// Various logging levels.
20Dygraph.DEBUG = 1;
21Dygraph.INFO = 2;
22Dygraph.WARNING = 3;
23Dygraph.ERROR = 3;
24
25// TODO(danvk): any way I can get the line numbers to be this.warn call?
26/**
27 * @private
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.
31 */
32Dygraph.log = function(severity, message) {
33 if (typeof(console) != 'undefined') {
34 switch (severity) {
35 case Dygraph.DEBUG:
36 console.debug('dygraphs: ' + message);
37 break;
38 case Dygraph.INFO:
39 console.info('dygraphs: ' + message);
40 break;
41 case Dygraph.WARNING:
42 console.warn('dygraphs: ' + message);
43 break;
44 case Dygraph.ERROR:
45 console.error('dygraphs: ' + message);
46 break;
47 }
48 }
49};
50
51/** @private */
52Dygraph.info = function(message) {
53 Dygraph.log(Dygraph.INFO, message);
54};
55/** @private */
56Dygraph.prototype.info = Dygraph.info;
57
58/** @private */
59Dygraph.warn = function(message) {
60 Dygraph.log(Dygraph.WARNING, message);
61};
62/** @private */
63Dygraph.prototype.warn = Dygraph.warn;
64
65/** @private */
66Dygraph.error = function(message) {
67 Dygraph.log(Dygraph.ERROR, message);
68};
69/** @private */
70Dygraph.prototype.error = Dygraph.error;
71
72/**
73 * @private
74 * Return the 2d context for a dygraph canvas.
75 *
76 * This method is only exposed for the sake of replacing the function in
77 * automated tests, e.g.
78 *
79 * var oldFunc = Dygraph.getContext();
80 * Dygraph.getContext = function(canvas) {
81 * var realContext = oldFunc(canvas);
82 * return new Proxy(realContext);
83 * };
84 */
85Dygraph.getContext = function(canvas) {
86 return canvas.getContext("2d");
87};
88
89/**
90 * @private
91 * Add an event handler. This smooths a difference between IE and the rest of
92 * the world.
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.
97 */
98Dygraph.addEvent = function(el, evt, fn) {
99 var normed_fn = function(e) {
100 if (!e) var e = window.event;
101 fn(e);
102 };
103 if (window.addEventListener) { // Mozilla, Netscape, Firefox
104 el.addEventListener(evt, normed_fn, false);
105 } else { // IE
106 el.attachEvent('on' + evt, normed_fn);
107 }
108};
109
110/**
111 * @private
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.
117 */
118Dygraph.cancelEvent = function(e) {
119 e = e ? e : window.event;
120 if (e.stopPropagation) {
121 e.stopPropagation();
122 }
123 if (e.preventDefault) {
124 e.preventDefault();
125 }
126 e.cancelBubble = true;
127 e.cancel = true;
128 e.returnValue = false;
129 return false;
130};
131
132/**
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
135 * color wheel.
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.
140 * @private
141 */
142Dygraph.hsvToRGB = function (hue, saturation, value) {
143 var red;
144 var green;
145 var blue;
146 if (saturation === 0) {
147 red = value;
148 green = value;
149 blue = value;
150 } else {
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)));
156 switch (i) {
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;
164 }
165 }
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 + ')';
170};
171
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
175
8442269f
RK
176/**
177 * Find the x-coordinate of the supplied object relative to the left side
178 * of the page.
179 * @private
180 */
dedb4f5f
DV
181Dygraph.findPosX = function(obj) {
182 var curleft = 0;
8442269f
RK
183 if(obj.offsetParent) {
184 var copyObj = obj;
185 while(1) {
186 curleft += copyObj.offsetLeft;
187 if(!copyObj.offsetParent) {
dedb4f5f 188 break;
8442269f
RK
189 }
190 copyObj = copyObj.offsetParent;
dedb4f5f 191 }
8442269f 192 } else if(obj.x) {
dedb4f5f 193 curleft += obj.x;
8442269f
RK
194 }
195 // This handles the case where the object is inside a scrolled div.
196 while(obj && obj != document.body) {
197 curleft -= obj.scrollLeft;
198 obj = obj.parentNode;
199 }
dedb4f5f
DV
200 return curleft;
201};
202
8442269f
RK
203/**
204 * Find the y-coordinate of the supplied object relative to the top of the
205 * page.
206 * @private
207 */
dedb4f5f
DV
208Dygraph.findPosY = function(obj) {
209 var curtop = 0;
8442269f
RK
210 if(obj.offsetParent) {
211 var copyObj = obj;
212 while(1) {
213 curtop += copyObj.offsetTop;
214 if(!copyObj.offsetParent) {
dedb4f5f 215 break;
8442269f
RK
216 }
217 copyObj = copyObj.offsetParent;
dedb4f5f 218 }
8442269f 219 } else if(obj.y) {
dedb4f5f 220 curtop += obj.y;
8442269f
RK
221 }
222 // This handles the case where the object is inside a scrolled div.
223 while(obj && obj != document.body) {
224 curtop -= obj.scrollTop;
225 obj = obj.parentNode;
226 }
dedb4f5f
DV
227 return curtop;
228};
229
230/**
231 * @private
232 * Returns the x-coordinate of the event in a coordinate system where the
233 * top-left corner of the page (not the window) is (0,0).
234 * Taken from MochiKit.Signal
235 */
236Dygraph.pageX = function(e) {
237 if (e.pageX) {
238 return (!e.pageX || e.pageX < 0) ? 0 : e.pageX;
239 } else {
240 var de = document;
241 var b = document.body;
242 return e.clientX +
243 (de.scrollLeft || b.scrollLeft) -
244 (de.clientLeft || 0);
245 }
246};
247
248/**
249 * @private
250 * Returns the y-coordinate of the event in a coordinate system where the
251 * top-left corner of the page (not the window) is (0,0).
252 * Taken from MochiKit.Signal
253 */
254Dygraph.pageY = function(e) {
255 if (e.pageY) {
256 return (!e.pageY || e.pageY < 0) ? 0 : e.pageY;
257 } else {
258 var de = document;
259 var b = document.body;
260 return e.clientY +
261 (de.scrollTop || b.scrollTop) -
262 (de.clientTop || 0);
263 }
264};
265
266/**
267 * @private
268 * @param { Number } x The number to consider.
269 * @return { Boolean } Whether the number is zero or NaN.
270 */
271// TODO(danvk): rename this function to something like 'isNonZeroNan'.
272Dygraph.isOK = function(x) {
273 return x && !isNaN(x);
274};
275
276/**
277 * Number formatting function which mimicks the behavior of %g in printf, i.e.
278 * either exponential or fixed format (without trailing 0s) is used depending on
279 * the length of the generated string. The advantage of this format is that
280 * there is a predictable upper bound on the resulting string length,
281 * significant figures are not dropped, and normal numbers are not displayed in
282 * exponential notation.
283 *
284 * NOTE: JavaScript's native toPrecision() is NOT a drop-in replacement for %g.
285 * It creates strings which are too long for absolute values between 10^-4 and
286 * 10^-6, e.g. '0.00001' instead of '1e-5'. See tests/number-format.html for
287 * output examples.
288 *
289 * @param {Number} x The number to format
290 * @param {Number} opt_precision The precision to use, default 2.
291 * @return {String} A string formatted like %g in printf. The max generated
292 * string length should be precision + 6 (e.g 1.123e+300).
293 */
294Dygraph.floatFormat = function(x, opt_precision) {
295 // Avoid invalid precision values; [1, 21] is the valid range.
296 var p = Math.min(Math.max(1, opt_precision || 2), 21);
297
298 // This is deceptively simple. The actual algorithm comes from:
299 //
300 // Max allowed length = p + 4
301 // where 4 comes from 'e+n' and '.'.
302 //
303 // Length of fixed format = 2 + y + p
304 // where 2 comes from '0.' and y = # of leading zeroes.
305 //
306 // Equating the two and solving for y yields y = 2, or 0.00xxxx which is
307 // 1.0e-3.
308 //
309 // Since the behavior of toPrecision() is identical for larger numbers, we
310 // don't have to worry about the other bound.
311 //
312 // Finally, the argument for toExponential() is the number of trailing digits,
313 // so we take off 1 for the value before the '.'.
314 return (Math.abs(x) < 1.0e-3 && x != 0.0) ?
315 x.toExponential(p - 1) : x.toPrecision(p);
316};
317
318/**
319 * @private
320 * Converts '9' to '09' (useful for dates)
321 */
322Dygraph.zeropad = function(x) {
323 if (x < 10) return "0" + x; else return "" + x;
324};
325
326/**
327 * Return a string version of the hours, minutes and seconds portion of a date.
328 * @param {Number} date The JavaScript date (ms since epoch)
329 * @return {String} A time of the form "HH:MM:SS"
330 * @private
331 */
332Dygraph.hmsString_ = function(date) {
333 var zeropad = Dygraph.zeropad;
334 var d = new Date(date);
335 if (d.getSeconds()) {
336 return zeropad(d.getHours()) + ":" +
337 zeropad(d.getMinutes()) + ":" +
338 zeropad(d.getSeconds());
339 } else {
340 return zeropad(d.getHours()) + ":" + zeropad(d.getMinutes());
341 }
342};
343
344/**
345 * Convert a JS date (millis since epoch) to YYYY/MM/DD
346 * @param {Number} date The JavaScript date (ms since epoch)
347 * @return {String} A date of the form "YYYY/MM/DD"
348 * @private
349 */
350Dygraph.dateString_ = function(date) {
351 var zeropad = Dygraph.zeropad;
352 var d = new Date(date);
353
354 // Get the year:
355 var year = "" + d.getFullYear();
356 // Get a 0 padded month string
357 var month = zeropad(d.getMonth() + 1); //months are 0-offset, sigh
358 // Get a 0 padded day string
359 var day = zeropad(d.getDate());
360
361 var ret = "";
362 var frac = d.getHours() * 3600 + d.getMinutes() * 60 + d.getSeconds();
363 if (frac) ret = " " + Dygraph.hmsString_(date);
364
365 return year + "/" + month + "/" + day + ret;
366};
367
368/**
369 * Round a number to the specified number of digits past the decimal point.
370 * @param {Number} num The number to round
371 * @param {Number} places The number of decimals to which to round
372 * @return {Number} The rounded number
373 * @private
374 */
375Dygraph.round_ = function(num, places) {
376 var shift = Math.pow(10, places);
377 return Math.round(num * shift)/shift;
378};
379
380/**
381 * @private
382 * Implementation of binary search over an array.
383 * Currently does not work when val is outside the range of arry's values.
384 * @param { Integer } val the value to search for
385 * @param { Integer[] } arry is the value over which to search
386 * @param { Integer } abs If abs > 0, find the lowest entry greater than val
387 * If abs < 0, find the highest entry less than val.
388 * if abs == 0, find the entry that equals val.
389 * @param { Integer } [low] The first index in arry to consider (optional)
390 * @param { Integer } [high] The last index in arry to consider (optional)
391 */
392Dygraph.binarySearch = function(val, arry, abs, low, high) {
393 if (low == null || high == null) {
394 low = 0;
395 high = arry.length - 1;
396 }
397 if (low > high) {
398 return -1;
399 }
400 if (abs == null) {
401 abs = 0;
402 }
403 var validIndex = function(idx) {
404 return idx >= 0 && idx < arry.length;
405 }
406 var mid = parseInt((low + high) / 2);
407 var element = arry[mid];
408 if (element == val) {
409 return mid;
410 }
411 if (element > val) {
412 if (abs > 0) {
413 // Accept if element > val, but also if prior element < val.
414 var idx = mid - 1;
415 if (validIndex(idx) && arry[idx] < val) {
416 return mid;
417 }
418 }
419 return Dygraph.binarySearch(val, arry, abs, low, mid - 1);
420 }
421 if (element < val) {
422 if (abs < 0) {
423 // Accept if element < val, but also if prior element > val.
424 var idx = mid + 1;
425 if (validIndex(idx) && arry[idx] > val) {
426 return mid;
427 }
428 }
429 return Dygraph.binarySearch(val, arry, abs, mid + 1, high);
430 }
431};
432
433/**
434 * @private
435 * Parses a date, returning the number of milliseconds since epoch. This can be
436 * passed in as an xValueParser in the Dygraph constructor.
437 * TODO(danvk): enumerate formats that this understands.
438 * @param {String} A date in YYYYMMDD format.
439 * @return {Number} Milliseconds since epoch.
440 */
441Dygraph.dateParser = function(dateStr) {
442 var dateStrSlashed;
443 var d;
444 if (dateStr.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12'
445 dateStrSlashed = dateStr.replace("-", "/", "g");
446 while (dateStrSlashed.search("-") != -1) {
447 dateStrSlashed = dateStrSlashed.replace("-", "/");
448 }
449 d = Dygraph.dateStrToMillis(dateStrSlashed);
450 } else if (dateStr.length == 8) { // e.g. '20090712'
451 // TODO(danvk): remove support for this format. It's confusing.
452 dateStrSlashed = dateStr.substr(0,4) + "/" + dateStr.substr(4,2)
453 + "/" + dateStr.substr(6,2);
454 d = Dygraph.dateStrToMillis(dateStrSlashed);
455 } else {
456 // Any format that Date.parse will accept, e.g. "2009/07/12" or
457 // "2009/07/12 12:34:56"
458 d = Dygraph.dateStrToMillis(dateStr);
459 }
460
461 if (!d || isNaN(d)) {
462 Dygraph.error("Couldn't parse " + dateStr + " as a date");
463 }
464 return d;
465};
466
467/**
468 * @private
469 * This is identical to JavaScript's built-in Date.parse() method, except that
470 * it doesn't get replaced with an incompatible method by aggressive JS
471 * libraries like MooTools or Joomla.
472 * @param { String } str The date string, e.g. "2011/05/06"
473 * @return { Integer } millis since epoch
474 */
475Dygraph.dateStrToMillis = function(str) {
476 return new Date(str).getTime();
477};
478
479// These functions are all based on MochiKit.
480/**
481 * Copies all the properties from o to self.
482 *
483 * @private
484 */
485Dygraph.update = function (self, o) {
486 if (typeof(o) != 'undefined' && o !== null) {
487 for (var k in o) {
488 if (o.hasOwnProperty(k)) {
489 self[k] = o[k];
490 }
491 }
492 }
493 return self;
494};
495
496/**
497 * @private
498 */
499Dygraph.isArrayLike = function (o) {
500 var typ = typeof(o);
501 if (
502 (typ != 'object' && !(typ == 'function' &&
503 typeof(o.item) == 'function')) ||
504 o === null ||
505 typeof(o.length) != 'number' ||
506 o.nodeType === 3
507 ) {
508 return false;
509 }
510 return true;
511};
512
513/**
514 * @private
515 */
516Dygraph.isDateLike = function (o) {
517 if (typeof(o) != "object" || o === null ||
518 typeof(o.getTime) != 'function') {
519 return false;
520 }
521 return true;
522};
523
524/**
525 * @private
526 */
527Dygraph.clone = function(o) {
528 // TODO(danvk): figure out how MochiKit's version works
529 var r = [];
530 for (var i = 0; i < o.length; i++) {
531 if (Dygraph.isArrayLike(o[i])) {
532 r.push(Dygraph.clone(o[i]));
533 } else {
534 r.push(o[i]);
535 }
536 }
537 return r;
538};
539
540/**
541 * @private
542 * Create a new canvas element. This is more complex than a simple
543 * document.createElement("canvas") because of IE and excanvas.
544 */
545Dygraph.createCanvas = function() {
546 var canvas = document.createElement("canvas");
547
548 isIE = (/MSIE/.test(navigator.userAgent) && !window.opera);
549 if (isIE && (typeof(G_vmlCanvasManager) != 'undefined')) {
550 canvas = G_vmlCanvasManager.initElement(canvas);
551 }
552
553 return canvas;
554};