fix disappearing annotations bug
[dygraphs.git] / dygraph-utils.js
CommitLineData
004b5c90 1// Copyright 2011 Dan Vanderkam (danvdk@gmail.com)
5108eb20 2// MIT-licensed (http://opensource.org/licenses/MIT)
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
1bc38cbc 175// ... and modifications to support scrolling divs.
dedb4f5f 176
8442269f
RK
177/**
178 * Find the x-coordinate of the supplied object relative to the left side
179 * of the page.
180 * @private
181 */
dedb4f5f
DV
182Dygraph.findPosX = function(obj) {
183 var curleft = 0;
8442269f
RK
184 if(obj.offsetParent) {
185 var copyObj = obj;
186 while(1) {
187 curleft += copyObj.offsetLeft;
188 if(!copyObj.offsetParent) {
dedb4f5f 189 break;
8442269f
RK
190 }
191 copyObj = copyObj.offsetParent;
dedb4f5f 192 }
8442269f 193 } else if(obj.x) {
dedb4f5f 194 curleft += obj.x;
8442269f
RK
195 }
196 // This handles the case where the object is inside a scrolled div.
197 while(obj && obj != document.body) {
198 curleft -= obj.scrollLeft;
199 obj = obj.parentNode;
200 }
dedb4f5f
DV
201 return curleft;
202};
203
8442269f
RK
204/**
205 * Find the y-coordinate of the supplied object relative to the top of the
206 * page.
207 * @private
208 */
dedb4f5f
DV
209Dygraph.findPosY = function(obj) {
210 var curtop = 0;
8442269f
RK
211 if(obj.offsetParent) {
212 var copyObj = obj;
213 while(1) {
214 curtop += copyObj.offsetTop;
215 if(!copyObj.offsetParent) {
dedb4f5f 216 break;
8442269f
RK
217 }
218 copyObj = copyObj.offsetParent;
dedb4f5f 219 }
8442269f 220 } else if(obj.y) {
dedb4f5f 221 curtop += obj.y;
8442269f
RK
222 }
223 // This handles the case where the object is inside a scrolled div.
224 while(obj && obj != document.body) {
225 curtop -= obj.scrollTop;
226 obj = obj.parentNode;
227 }
dedb4f5f
DV
228 return curtop;
229};
230
231/**
232 * @private
233 * Returns the x-coordinate of the event in a coordinate system where the
234 * top-left corner of the page (not the window) is (0,0).
235 * Taken from MochiKit.Signal
236 */
237Dygraph.pageX = function(e) {
238 if (e.pageX) {
239 return (!e.pageX || e.pageX < 0) ? 0 : e.pageX;
240 } else {
241 var de = document;
242 var b = document.body;
243 return e.clientX +
244 (de.scrollLeft || b.scrollLeft) -
245 (de.clientLeft || 0);
246 }
247};
248
249/**
250 * @private
251 * Returns the y-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
254 */
255Dygraph.pageY = function(e) {
256 if (e.pageY) {
257 return (!e.pageY || e.pageY < 0) ? 0 : e.pageY;
258 } else {
259 var de = document;
260 var b = document.body;
261 return e.clientY +
262 (de.scrollTop || b.scrollTop) -
263 (de.clientTop || 0);
264 }
265};
266
267/**
268 * @private
269 * @param { Number } x The number to consider.
270 * @return { Boolean } Whether the number is zero or NaN.
271 */
272// TODO(danvk): rename this function to something like 'isNonZeroNan'.
273Dygraph.isOK = function(x) {
274 return x && !isNaN(x);
275};
276
277/**
278 * Number formatting function which mimicks the behavior of %g in printf, i.e.
279 * either exponential or fixed format (without trailing 0s) is used depending on
280 * the length of the generated string. The advantage of this format is that
281 * there is a predictable upper bound on the resulting string length,
282 * significant figures are not dropped, and normal numbers are not displayed in
283 * exponential notation.
284 *
285 * NOTE: JavaScript's native toPrecision() is NOT a drop-in replacement for %g.
286 * It creates strings which are too long for absolute values between 10^-4 and
287 * 10^-6, e.g. '0.00001' instead of '1e-5'. See tests/number-format.html for
288 * output examples.
289 *
290 * @param {Number} x The number to format
291 * @param {Number} opt_precision The precision to use, default 2.
292 * @return {String} A string formatted like %g in printf. The max generated
293 * string length should be precision + 6 (e.g 1.123e+300).
294 */
295Dygraph.floatFormat = function(x, opt_precision) {
296 // Avoid invalid precision values; [1, 21] is the valid range.
297 var p = Math.min(Math.max(1, opt_precision || 2), 21);
298
299 // This is deceptively simple. The actual algorithm comes from:
300 //
301 // Max allowed length = p + 4
302 // where 4 comes from 'e+n' and '.'.
303 //
304 // Length of fixed format = 2 + y + p
305 // where 2 comes from '0.' and y = # of leading zeroes.
306 //
307 // Equating the two and solving for y yields y = 2, or 0.00xxxx which is
308 // 1.0e-3.
309 //
310 // Since the behavior of toPrecision() is identical for larger numbers, we
311 // don't have to worry about the other bound.
312 //
313 // Finally, the argument for toExponential() is the number of trailing digits,
314 // so we take off 1 for the value before the '.'.
315 return (Math.abs(x) < 1.0e-3 && x != 0.0) ?
316 x.toExponential(p - 1) : x.toPrecision(p);
317};
318
319/**
320 * @private
321 * Converts '9' to '09' (useful for dates)
322 */
323Dygraph.zeropad = function(x) {
324 if (x < 10) return "0" + x; else return "" + x;
325};
326
327/**
328 * Return a string version of the hours, minutes and seconds portion of a date.
329 * @param {Number} date The JavaScript date (ms since epoch)
330 * @return {String} A time of the form "HH:MM:SS"
331 * @private
332 */
333Dygraph.hmsString_ = function(date) {
334 var zeropad = Dygraph.zeropad;
335 var d = new Date(date);
336 if (d.getSeconds()) {
337 return zeropad(d.getHours()) + ":" +
338 zeropad(d.getMinutes()) + ":" +
339 zeropad(d.getSeconds());
340 } else {
341 return zeropad(d.getHours()) + ":" + zeropad(d.getMinutes());
342 }
343};
344
345/**
dedb4f5f
DV
346 * Round a number to the specified number of digits past the decimal point.
347 * @param {Number} num The number to round
348 * @param {Number} places The number of decimals to which to round
349 * @return {Number} The rounded number
350 * @private
351 */
352Dygraph.round_ = function(num, places) {
353 var shift = Math.pow(10, places);
354 return Math.round(num * shift)/shift;
355};
356
357/**
358 * @private
359 * Implementation of binary search over an array.
360 * Currently does not work when val is outside the range of arry's values.
361 * @param { Integer } val the value to search for
362 * @param { Integer[] } arry is the value over which to search
363 * @param { Integer } abs If abs > 0, find the lowest entry greater than val
364 * If abs < 0, find the highest entry less than val.
365 * if abs == 0, find the entry that equals val.
366 * @param { Integer } [low] The first index in arry to consider (optional)
367 * @param { Integer } [high] The last index in arry to consider (optional)
368 */
369Dygraph.binarySearch = function(val, arry, abs, low, high) {
370 if (low == null || high == null) {
371 low = 0;
372 high = arry.length - 1;
373 }
374 if (low > high) {
375 return -1;
376 }
377 if (abs == null) {
378 abs = 0;
379 }
380 var validIndex = function(idx) {
381 return idx >= 0 && idx < arry.length;
382 }
383 var mid = parseInt((low + high) / 2);
384 var element = arry[mid];
385 if (element == val) {
386 return mid;
387 }
388 if (element > val) {
389 if (abs > 0) {
390 // Accept if element > val, but also if prior element < val.
391 var idx = mid - 1;
392 if (validIndex(idx) && arry[idx] < val) {
393 return mid;
394 }
395 }
396 return Dygraph.binarySearch(val, arry, abs, low, mid - 1);
397 }
398 if (element < val) {
399 if (abs < 0) {
400 // Accept if element < val, but also if prior element > val.
401 var idx = mid + 1;
402 if (validIndex(idx) && arry[idx] > val) {
403 return mid;
404 }
405 }
406 return Dygraph.binarySearch(val, arry, abs, mid + 1, high);
407 }
408};
409
410/**
411 * @private
412 * Parses a date, returning the number of milliseconds since epoch. This can be
413 * passed in as an xValueParser in the Dygraph constructor.
414 * TODO(danvk): enumerate formats that this understands.
415 * @param {String} A date in YYYYMMDD format.
416 * @return {Number} Milliseconds since epoch.
417 */
418Dygraph.dateParser = function(dateStr) {
419 var dateStrSlashed;
420 var d;
421 if (dateStr.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12'
422 dateStrSlashed = dateStr.replace("-", "/", "g");
423 while (dateStrSlashed.search("-") != -1) {
424 dateStrSlashed = dateStrSlashed.replace("-", "/");
425 }
426 d = Dygraph.dateStrToMillis(dateStrSlashed);
427 } else if (dateStr.length == 8) { // e.g. '20090712'
428 // TODO(danvk): remove support for this format. It's confusing.
429 dateStrSlashed = dateStr.substr(0,4) + "/" + dateStr.substr(4,2)
430 + "/" + dateStr.substr(6,2);
431 d = Dygraph.dateStrToMillis(dateStrSlashed);
432 } else {
433 // Any format that Date.parse will accept, e.g. "2009/07/12" or
434 // "2009/07/12 12:34:56"
435 d = Dygraph.dateStrToMillis(dateStr);
436 }
437
438 if (!d || isNaN(d)) {
439 Dygraph.error("Couldn't parse " + dateStr + " as a date");
440 }
441 return d;
442};
443
444/**
445 * @private
446 * This is identical to JavaScript's built-in Date.parse() method, except that
447 * it doesn't get replaced with an incompatible method by aggressive JS
448 * libraries like MooTools or Joomla.
449 * @param { String } str The date string, e.g. "2011/05/06"
450 * @return { Integer } millis since epoch
451 */
452Dygraph.dateStrToMillis = function(str) {
453 return new Date(str).getTime();
454};
455
456// These functions are all based on MochiKit.
457/**
458 * Copies all the properties from o to self.
459 *
460 * @private
461 */
462Dygraph.update = function (self, o) {
463 if (typeof(o) != 'undefined' && o !== null) {
464 for (var k in o) {
465 if (o.hasOwnProperty(k)) {
466 self[k] = o[k];
467 }
468 }
469 }
470 return self;
471};
472
473/**
48e614ac
DV
474 * Copies all the properties from o to self.
475 *
476 * @private
477 */
478Dygraph.updateDeep = function (self, o) {
479 if (typeof(o) != 'undefined' && o !== null) {
480 for (var k in o) {
481 if (o.hasOwnProperty(k)) {
482 if (o[k] == null) {
483 self[k] = null;
484 } else if (Dygraph.isArrayLike(o[k])) {
485 self[k] = o[k].slice();
486 } else if (typeof(o[k]) == 'object') {
487 if (typeof(self[k]) != 'object') {
488 self[k] = {};
489 }
490 Dygraph.updateDeep(self[k], o[k]);
491 } else {
492 self[k] = o[k];
493 }
494 }
495 }
496 }
497 return self;
498};
499
500/**
dedb4f5f
DV
501 * @private
502 */
503Dygraph.isArrayLike = function (o) {
504 var typ = typeof(o);
505 if (
506 (typ != 'object' && !(typ == 'function' &&
507 typeof(o.item) == 'function')) ||
508 o === null ||
509 typeof(o.length) != 'number' ||
510 o.nodeType === 3
511 ) {
512 return false;
513 }
514 return true;
515};
516
517/**
518 * @private
519 */
520Dygraph.isDateLike = function (o) {
521 if (typeof(o) != "object" || o === null ||
522 typeof(o.getTime) != 'function') {
523 return false;
524 }
525 return true;
526};
527
528/**
48e614ac 529 * Note: this only seems to work for arrays.
dedb4f5f
DV
530 * @private
531 */
532Dygraph.clone = function(o) {
533 // TODO(danvk): figure out how MochiKit's version works
534 var r = [];
535 for (var i = 0; i < o.length; i++) {
536 if (Dygraph.isArrayLike(o[i])) {
537 r.push(Dygraph.clone(o[i]));
538 } else {
539 r.push(o[i]);
540 }
541 }
542 return r;
543};
544
545/**
546 * @private
547 * Create a new canvas element. This is more complex than a simple
548 * document.createElement("canvas") because of IE and excanvas.
549 */
550Dygraph.createCanvas = function() {
551 var canvas = document.createElement("canvas");
552
553 isIE = (/MSIE/.test(navigator.userAgent) && !window.opera);
554 if (isIE && (typeof(G_vmlCanvasManager) != 'undefined')) {
555 canvas = G_vmlCanvasManager.initElement(canvas);
556 }
557
558 return canvas;
559};
9ca829f2
DV
560
561/**
562 * @private
563 * This function will scan the option list and determine if they
564 * require us to recalculate the pixel positions of each point.
565 * @param { List } a list of options to check.
566 * @return { Boolean } true if the graph needs new points else false.
567 */
568Dygraph.isPixelChangingOptionList = function(labels, attrs) {
569 // A whitelist of options that do not change pixel positions.
570 var pixelSafeOptions = {
571 'annotationClickHandler': true,
572 'annotationDblClickHandler': true,
573 'annotationMouseOutHandler': true,
574 'annotationMouseOverHandler': true,
575 'axisLabelColor': true,
576 'axisLineColor': true,
577 'axisLineWidth': true,
578 'clickCallback': true,
579 'colorSaturation': true,
580 'colorValue': true,
581 'colors': true,
582 'connectSeparatedPoints': true,
583 'digitsAfterDecimal': true,
584 'drawCallback': true,
585 'drawPoints': true,
586 'drawXGrid': true,
587 'drawYGrid': true,
588 'fillAlpha': true,
589 'gridLineColor': true,
590 'gridLineWidth': true,
591 'hideOverlayOnMouseOut': true,
592 'highlightCallback': true,
593 'highlightCircleSize': true,
594 'interactionModel': true,
595 'isZoomedIgnoreProgrammaticZoom': true,
596 'labelsDiv': true,
597 'labelsDivStyles': true,
598 'labelsDivWidth': true,
599 'labelsKMB': true,
600 'labelsKMG2': true,
601 'labelsSeparateLines': true,
602 'labelsShowZeroValues': true,
603 'legend': true,
604 'maxNumberWidth': true,
605 'panEdgeFraction': true,
606 'pixelsPerYLabel': true,
607 'pointClickCallback': true,
608 'pointSize': true,
609 'showLabelsOnHighlight': true,
610 'showRoller': true,
611 'sigFigs': true,
612 'strokeWidth': true,
613 'underlayCallback': true,
614 'unhighlightCallback': true,
615 'xAxisLabelFormatter': true,
616 'xTicker': true,
617 'xValueFormatter': true,
618 'yAxisLabelFormatter': true,
619 'yValueFormatter': true,
620 'zoomCallback': true
621 };
622
623 // Assume that we do not require new points.
624 // This will change to true if we actually do need new points.
625 var requiresNewPoints = false;
626
627 // Create a dictionary of series names for faster lookup.
628 // If there are no labels, then the dictionary stays empty.
629 var seriesNamesDictionary = { };
630 if (labels) {
631 for (var i = 1; i < labels.length; i++) {
632 seriesNamesDictionary[labels[i]] = true;
633 }
634 }
635
636 // Iterate through the list of updated options.
637 for (property in attrs) {
638 // Break early if we already know we need new points from a previous option.
639 if (requiresNewPoints) {
640 break;
641 }
642 if (attrs.hasOwnProperty(property)) {
643 // Find out of this field is actually a series specific options list.
644 if (seriesNamesDictionary[property]) {
645 // This property value is a list of options for this series.
646 // If any of these sub properties are not pixel safe, set the flag.
647 for (subProperty in attrs[property]) {
648 // Break early if we already know we need new points from a previous option.
649 if (requiresNewPoints) {
650 break;
651 }
652 if (attrs[property].hasOwnProperty(subProperty) && !pixelSafeOptions[subProperty]) {
653 requiresNewPoints = true;
654 }
655 }
656 // If this was not a series specific option list, check if its a pixel changing property.
657 } else if (!pixelSafeOptions[property]) {
658 requiresNewPoints = true;
659 }
660 }
661 }
662
663 return requiresNewPoints;
664};