temporarily disable some ticker tests
[dygraphs.git] / dygraph-utils.js
CommitLineData
88e95c46
DV
1/**
2 * @license
3 * Copyright 2011 Dan Vanderkam (danvdk@gmail.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
5 */
dedb4f5f 6
004b5c90
DV
7/**
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.
12 */
dedb4f5f
DV
13
14Dygraph.LOG_SCALE = 10;
15Dygraph.LN_TEN = Math.log(Dygraph.LOG_SCALE);
16
17/** @private */
18Dygraph.log10 = function(x) {
19 return Math.log(x) / Dygraph.LN_TEN;
20}
21
22// Various logging levels.
23Dygraph.DEBUG = 1;
24Dygraph.INFO = 2;
25Dygraph.WARNING = 3;
26Dygraph.ERROR = 3;
27
28// TODO(danvk): any way I can get the line numbers to be this.warn call?
29/**
30 * @private
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.
34 */
35Dygraph.log = function(severity, message) {
36 if (typeof(console) != 'undefined') {
37 switch (severity) {
38 case Dygraph.DEBUG:
39 console.debug('dygraphs: ' + message);
40 break;
41 case Dygraph.INFO:
42 console.info('dygraphs: ' + message);
43 break;
44 case Dygraph.WARNING:
45 console.warn('dygraphs: ' + message);
46 break;
47 case Dygraph.ERROR:
48 console.error('dygraphs: ' + message);
49 break;
50 }
51 }
52};
53
54/** @private */
55Dygraph.info = function(message) {
56 Dygraph.log(Dygraph.INFO, message);
57};
58/** @private */
59Dygraph.prototype.info = Dygraph.info;
60
61/** @private */
62Dygraph.warn = function(message) {
63 Dygraph.log(Dygraph.WARNING, message);
64};
65/** @private */
66Dygraph.prototype.warn = Dygraph.warn;
67
68/** @private */
69Dygraph.error = function(message) {
70 Dygraph.log(Dygraph.ERROR, message);
71};
72/** @private */
73Dygraph.prototype.error = Dygraph.error;
74
75/**
76 * @private
77 * Return the 2d context for a dygraph canvas.
78 *
79 * This method is only exposed for the sake of replacing the function in
80 * automated tests, e.g.
81 *
82 * var oldFunc = Dygraph.getContext();
83 * Dygraph.getContext = function(canvas) {
84 * var realContext = oldFunc(canvas);
85 * return new Proxy(realContext);
86 * };
87 */
88Dygraph.getContext = function(canvas) {
89 return canvas.getContext("2d");
90};
91
92/**
93 * @private
94 * Add an event handler. This smooths a difference between IE and the rest of
95 * the world.
ccd9d7c2
PF
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'.
dedb4f5f
DV
98 * @param { Function } fn The function to call on the event. The function takes
99 * one parameter: the event object.
100 */
ccd9d7c2
PF
101Dygraph.addEvent = function addEvent(elem, type, fn) {
102 if (elem.addEventListener) {
103 elem.addEventListener(type, fn, false);
104 } else {
105 elem[type+fn] = function(){fn(window.event);};
106 elem.attachEvent('on'+type, elem[type+fn]);
107 }
108};
109
110/**
111 * @private
112 * Remove an event handler. This smooths a difference between IE and the rest of
113 * the world.
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.
118 */
119Dygraph.removeEvent = function addEvent(elem, type, fn) {
120 if (elem.removeEventListener) {
121 elem.removeEventListener(type, fn, false);
122 } else {
123 elem.detachEvent('on'+type, elem[type+fn]);
124 elem[type+fn] = null;
dedb4f5f
DV
125 }
126};
127
128/**
129 * @private
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.
135 */
136Dygraph.cancelEvent = function(e) {
137 e = e ? e : window.event;
138 if (e.stopPropagation) {
139 e.stopPropagation();
140 }
141 if (e.preventDefault) {
142 e.preventDefault();
143 }
144 e.cancelBubble = true;
145 e.cancel = true;
146 e.returnValue = false;
147 return false;
148};
149
150/**
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
153 * color wheel.
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.
158 * @private
159 */
160Dygraph.hsvToRGB = function (hue, saturation, value) {
161 var red;
162 var green;
163 var blue;
164 if (saturation === 0) {
165 red = value;
166 green = value;
167 blue = value;
168 } else {
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)));
174 switch (i) {
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;
182 }
183 }
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 + ')';
188};
189
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
1bc38cbc 193// ... and modifications to support scrolling divs.
dedb4f5f 194
8442269f
RK
195/**
196 * Find the x-coordinate of the supplied object relative to the left side
197 * of the page.
198 * @private
199 */
dedb4f5f
DV
200Dygraph.findPosX = function(obj) {
201 var curleft = 0;
8442269f
RK
202 if(obj.offsetParent) {
203 var copyObj = obj;
204 while(1) {
205 curleft += copyObj.offsetLeft;
206 if(!copyObj.offsetParent) {
dedb4f5f 207 break;
8442269f
RK
208 }
209 copyObj = copyObj.offsetParent;
dedb4f5f 210 }
8442269f 211 } else if(obj.x) {
dedb4f5f 212 curleft += obj.x;
8442269f
RK
213 }
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;
218 }
dedb4f5f
DV
219 return curleft;
220};
221
8442269f
RK
222/**
223 * Find the y-coordinate of the supplied object relative to the top of the
224 * page.
225 * @private
226 */
dedb4f5f
DV
227Dygraph.findPosY = function(obj) {
228 var curtop = 0;
8442269f
RK
229 if(obj.offsetParent) {
230 var copyObj = obj;
231 while(1) {
232 curtop += copyObj.offsetTop;
233 if(!copyObj.offsetParent) {
dedb4f5f 234 break;
8442269f
RK
235 }
236 copyObj = copyObj.offsetParent;
dedb4f5f 237 }
8442269f 238 } else if(obj.y) {
dedb4f5f 239 curtop += obj.y;
8442269f
RK
240 }
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;
245 }
dedb4f5f
DV
246 return curtop;
247};
248
249/**
250 * @private
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
254 */
255Dygraph.pageX = function(e) {
256 if (e.pageX) {
257 return (!e.pageX || e.pageX < 0) ? 0 : e.pageX;
258 } else {
259 var de = document;
260 var b = document.body;
261 return e.clientX +
262 (de.scrollLeft || b.scrollLeft) -
263 (de.clientLeft || 0);
264 }
265};
266
267/**
268 * @private
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
272 */
273Dygraph.pageY = function(e) {
274 if (e.pageY) {
275 return (!e.pageY || e.pageY < 0) ? 0 : e.pageY;
276 } else {
277 var de = document;
278 var b = document.body;
279 return e.clientY +
280 (de.scrollTop || b.scrollTop) -
281 (de.clientTop || 0);
282 }
283};
284
285/**
286 * @private
287 * @param { Number } x The number to consider.
288 * @return { Boolean } Whether the number is zero or NaN.
289 */
290// TODO(danvk): rename this function to something like 'isNonZeroNan'.
291Dygraph.isOK = function(x) {
292 return x && !isNaN(x);
293};
294
295/**
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.
302 *
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
306 * output examples.
307 *
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).
312 */
313Dygraph.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);
316
317 // This is deceptively simple. The actual algorithm comes from:
318 //
319 // Max allowed length = p + 4
320 // where 4 comes from 'e+n' and '.'.
321 //
322 // Length of fixed format = 2 + y + p
323 // where 2 comes from '0.' and y = # of leading zeroes.
324 //
325 // Equating the two and solving for y yields y = 2, or 0.00xxxx which is
326 // 1.0e-3.
327 //
328 // Since the behavior of toPrecision() is identical for larger numbers, we
329 // don't have to worry about the other bound.
330 //
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);
335};
336
337/**
338 * @private
339 * Converts '9' to '09' (useful for dates)
340 */
341Dygraph.zeropad = function(x) {
342 if (x < 10) return "0" + x; else return "" + x;
343};
344
345/**
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"
349 * @private
350 */
351Dygraph.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());
358 } else {
359 return zeropad(d.getHours()) + ":" + zeropad(d.getMinutes());
360 }
361};
362
363/**
dedb4f5f
DV
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
368 * @private
369 */
370Dygraph.round_ = function(num, places) {
371 var shift = Math.pow(10, places);
372 return Math.round(num * shift)/shift;
373};
374
375/**
376 * @private
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)
386 */
387Dygraph.binarySearch = function(val, arry, abs, low, high) {
388 if (low == null || high == null) {
389 low = 0;
390 high = arry.length - 1;
391 }
392 if (low > high) {
393 return -1;
394 }
395 if (abs == null) {
396 abs = 0;
397 }
398 var validIndex = function(idx) {
399 return idx >= 0 && idx < arry.length;
400 }
401 var mid = parseInt((low + high) / 2);
402 var element = arry[mid];
403 if (element == val) {
404 return mid;
405 }
406 if (element > val) {
407 if (abs > 0) {
408 // Accept if element > val, but also if prior element < val.
409 var idx = mid - 1;
410 if (validIndex(idx) && arry[idx] < val) {
411 return mid;
412 }
413 }
414 return Dygraph.binarySearch(val, arry, abs, low, mid - 1);
415 }
416 if (element < val) {
417 if (abs < 0) {
418 // Accept if element < val, but also if prior element > val.
419 var idx = mid + 1;
420 if (validIndex(idx) && arry[idx] > val) {
421 return mid;
422 }
423 }
424 return Dygraph.binarySearch(val, arry, abs, mid + 1, high);
425 }
426};
427
428/**
429 * @private
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.
435 */
436Dygraph.dateParser = function(dateStr) {
437 var dateStrSlashed;
438 var d;
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("-", "/");
443 }
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);
450 } else {
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);
454 }
455
456 if (!d || isNaN(d)) {
457 Dygraph.error("Couldn't parse " + dateStr + " as a date");
458 }
459 return d;
460};
461
462/**
463 * @private
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
469 */
470Dygraph.dateStrToMillis = function(str) {
471 return new Date(str).getTime();
472};
473
474// These functions are all based on MochiKit.
475/**
476 * Copies all the properties from o to self.
477 *
478 * @private
479 */
480Dygraph.update = function (self, o) {
481 if (typeof(o) != 'undefined' && o !== null) {
482 for (var k in o) {
483 if (o.hasOwnProperty(k)) {
484 self[k] = o[k];
485 }
486 }
487 }
488 return self;
489};
490
491/**
48e614ac
DV
492 * Copies all the properties from o to self.
493 *
494 * @private
495 */
496Dygraph.updateDeep = function (self, o) {
497 if (typeof(o) != 'undefined' && o !== null) {
498 for (var k in o) {
499 if (o.hasOwnProperty(k)) {
500 if (o[k] == null) {
501 self[k] = null;
502 } else if (Dygraph.isArrayLike(o[k])) {
503 self[k] = o[k].slice();
504 } else if (typeof(o[k]) == 'object') {
505 if (typeof(self[k]) != 'object') {
506 self[k] = {};
507 }
508 Dygraph.updateDeep(self[k], o[k]);
509 } else {
510 self[k] = o[k];
511 }
512 }
513 }
514 }
515 return self;
516};
517
518/**
dedb4f5f
DV
519 * @private
520 */
521Dygraph.isArrayLike = function (o) {
522 var typ = typeof(o);
523 if (
524 (typ != 'object' && !(typ == 'function' &&
525 typeof(o.item) == 'function')) ||
526 o === null ||
527 typeof(o.length) != 'number' ||
528 o.nodeType === 3
529 ) {
530 return false;
531 }
532 return true;
533};
534
535/**
536 * @private
537 */
538Dygraph.isDateLike = function (o) {
539 if (typeof(o) != "object" || o === null ||
540 typeof(o.getTime) != 'function') {
541 return false;
542 }
543 return true;
544};
545
546/**
48e614ac 547 * Note: this only seems to work for arrays.
dedb4f5f
DV
548 * @private
549 */
550Dygraph.clone = function(o) {
551 // TODO(danvk): figure out how MochiKit's version works
552 var r = [];
553 for (var i = 0; i < o.length; i++) {
554 if (Dygraph.isArrayLike(o[i])) {
555 r.push(Dygraph.clone(o[i]));
556 } else {
557 r.push(o[i]);
558 }
559 }
560 return r;
561};
562
563/**
564 * @private
565 * Create a new canvas element. This is more complex than a simple
566 * document.createElement("canvas") because of IE and excanvas.
567 */
568Dygraph.createCanvas = function() {
569 var canvas = document.createElement("canvas");
570
571 isIE = (/MSIE/.test(navigator.userAgent) && !window.opera);
572 if (isIE && (typeof(G_vmlCanvasManager) != 'undefined')) {
573 canvas = G_vmlCanvasManager.initElement(canvas);
574 }
575
576 return canvas;
577};
9ca829f2
DV
578
579/**
580 * @private
581 * This function will scan the option list and determine if they
582 * require us to recalculate the pixel positions of each point.
583 * @param { List } a list of options to check.
584 * @return { Boolean } true if the graph needs new points else false.
585 */
586Dygraph.isPixelChangingOptionList = function(labels, attrs) {
587 // A whitelist of options that do not change pixel positions.
588 var pixelSafeOptions = {
589 'annotationClickHandler': true,
590 'annotationDblClickHandler': true,
591 'annotationMouseOutHandler': true,
592 'annotationMouseOverHandler': true,
593 'axisLabelColor': true,
594 'axisLineColor': true,
595 'axisLineWidth': true,
596 'clickCallback': true,
597 'colorSaturation': true,
598 'colorValue': true,
599 'colors': true,
600 'connectSeparatedPoints': true,
601 'digitsAfterDecimal': true,
602 'drawCallback': true,
603 'drawPoints': true,
604 'drawXGrid': true,
605 'drawYGrid': true,
606 'fillAlpha': true,
607 'gridLineColor': true,
608 'gridLineWidth': true,
609 'hideOverlayOnMouseOut': true,
610 'highlightCallback': true,
611 'highlightCircleSize': true,
612 'interactionModel': true,
613 'isZoomedIgnoreProgrammaticZoom': true,
614 'labelsDiv': true,
615 'labelsDivStyles': true,
616 'labelsDivWidth': true,
617 'labelsKMB': true,
618 'labelsKMG2': true,
619 'labelsSeparateLines': true,
620 'labelsShowZeroValues': true,
621 'legend': true,
622 'maxNumberWidth': true,
623 'panEdgeFraction': true,
624 'pixelsPerYLabel': true,
625 'pointClickCallback': true,
626 'pointSize': true,
ccd9d7c2
PF
627 'rangeSelectorPlotFillColor': true,
628 'rangeSelectorPlotStrokeColor': true,
9ca829f2
DV
629 'showLabelsOnHighlight': true,
630 'showRoller': true,
631 'sigFigs': true,
632 'strokeWidth': true,
633 'underlayCallback': true,
634 'unhighlightCallback': true,
635 'xAxisLabelFormatter': true,
636 'xTicker': true,
637 'xValueFormatter': true,
638 'yAxisLabelFormatter': true,
639 'yValueFormatter': true,
640 'zoomCallback': true
ccd9d7c2 641 };
9ca829f2
DV
642
643 // Assume that we do not require new points.
644 // This will change to true if we actually do need new points.
645 var requiresNewPoints = false;
646
647 // Create a dictionary of series names for faster lookup.
648 // If there are no labels, then the dictionary stays empty.
649 var seriesNamesDictionary = { };
650 if (labels) {
651 for (var i = 1; i < labels.length; i++) {
652 seriesNamesDictionary[labels[i]] = true;
653 }
654 }
655
656 // Iterate through the list of updated options.
657 for (property in attrs) {
658 // Break early if we already know we need new points from a previous option.
659 if (requiresNewPoints) {
660 break;
661 }
662 if (attrs.hasOwnProperty(property)) {
663 // Find out of this field is actually a series specific options list.
664 if (seriesNamesDictionary[property]) {
665 // This property value is a list of options for this series.
666 // If any of these sub properties are not pixel safe, set the flag.
667 for (subProperty in attrs[property]) {
668 // Break early if we already know we need new points from a previous option.
669 if (requiresNewPoints) {
670 break;
671 }
672 if (attrs[property].hasOwnProperty(subProperty) && !pixelSafeOptions[subProperty]) {
673 requiresNewPoints = true;
674 }
675 }
676 // If this was not a series specific option list, check if its a pixel changing property.
677 } else if (!pixelSafeOptions[property]) {
678 requiresNewPoints = true;
ccd9d7c2 679 }
9ca829f2
DV
680 }
681 }
682
683 return requiresNewPoints;
684};