remove all traces of Dygraph.log
[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 13
758a629f
DV
14/*jshint globalstrict: true */
15/*global Dygraph:false, G_vmlCanvasManager:false, Node:false, printStackTrace: false */
c0f54d4f
DV
16"use strict";
17
dedb4f5f
DV
18Dygraph.LOG_SCALE = 10;
19Dygraph.LN_TEN = Math.log(Dygraph.LOG_SCALE);
20
f11283de
DV
21/**
22 * @private
23 * @param {number} x
24 * @return {number}
25 */
dedb4f5f
DV
26Dygraph.log10 = function(x) {
27 return Math.log(x) / Dygraph.LN_TEN;
758a629f 28};
dedb4f5f 29
79253bd0 30/** A dotted line stroke pattern. */
31Dygraph.DOTTED_LINE = [2, 2];
32/** A dashed line stroke pattern. */
33Dygraph.DASHED_LINE = [7, 3];
34/** A dot dash stroke pattern. */
35Dygraph.DOT_DASH_LINE = [7, 2, 2, 2];
36
dedb4f5f 37/**
dedb4f5f
DV
38 * Return the 2d context for a dygraph canvas.
39 *
40 * This method is only exposed for the sake of replacing the function in
41 * automated tests, e.g.
42 *
43 * var oldFunc = Dygraph.getContext();
44 * Dygraph.getContext = function(canvas) {
45 * var realContext = oldFunc(canvas);
46 * return new Proxy(realContext);
47 * };
f11283de
DV
48 * @param {!HTMLCanvasElement} canvas
49 * @return {!CanvasRenderingContext2D}
50 * @private
dedb4f5f
DV
51 */
52Dygraph.getContext = function(canvas) {
f11283de 53 return /** @type{!CanvasRenderingContext2D}*/(canvas.getContext("2d"));
dedb4f5f
DV
54};
55
56/**
dedb4f5f
DV
57 * Add an event handler. This smooths a difference between IE and the rest of
58 * the world.
39b33f9f
DV
59 * @param {!Node} elem The element to add the event to.
60 * @param {string} type The type of the event, e.g. 'click' or 'mousemove'.
61 * @param {function(Event):(boolean|undefined)} fn The function to call
f11283de
DV
62 * on the event. The function takes one parameter: the event object.
63 * @private
dedb4f5f 64 */
1cc3540b 65Dygraph.addEvent = function addEvent(elem, type, fn) {
ccd9d7c2
PF
66 if (elem.addEventListener) {
67 elem.addEventListener(type, fn, false);
68 } else {
69 elem[type+fn] = function(){fn(window.event);};
70 elem.attachEvent('on'+type, elem[type+fn]);
71 }
1cc3540b
RK
72};
73
74/**
1cc3540b
RK
75 * Add an event handler. This event handler is kept until the graph is
76 * destroyed with a call to graph.destroy().
77 *
39b33f9f
DV
78 * @param {!Node} elem The element to add the event to.
79 * @param {string} type The type of the event, e.g. 'click' or 'mousemove'.
80 * @param {function(Event):(boolean|undefined)} fn The function to call
f11283de
DV
81 * on the event. The function takes one parameter: the event object.
82 * @private
1cc3540b 83 */
aeca29ac 84Dygraph.prototype.addAndTrackEvent = function(elem, type, fn) {
1cc3540b 85 Dygraph.addEvent(elem, type, fn);
6a4587ac 86 this.registeredEvents_.push({ elem : elem, type : type, fn : fn });
ccd9d7c2
PF
87};
88
89/**
f11283de
DV
90 * Remove an event handler. This smooths a difference between IE and the rest
91 * of the world.
39b33f9f 92 * @param {!Node} elem The element to remove the event from.
f11283de
DV
93 * @param {string} type The type of the event, e.g. 'click' or 'mousemove'.
94 * @param {function(Event):(boolean|undefined)} fn The function to call
95 * on the event. The function takes one parameter: the event object.
ccd9d7c2 96 * @private
ccd9d7c2 97 */
a537fd67 98Dygraph.removeEvent = function(elem, type, fn) {
ccd9d7c2
PF
99 if (elem.removeEventListener) {
100 elem.removeEventListener(type, fn, false);
101 } else {
e2769469
DV
102 try {
103 elem.detachEvent('on'+type, elem[type+fn]);
104 } catch(e) {
105 // We only detach event listeners on a "best effort" basis in IE. See:
106 // http://stackoverflow.com/questions/2553632/detachevent-not-working-with-named-inline-functions
107 }
ccd9d7c2 108 elem[type+fn] = null;
dedb4f5f
DV
109 }
110};
111
aeca29ac
RK
112Dygraph.prototype.removeTrackedEvents_ = function() {
113 if (this.registeredEvents_) {
114 for (var idx = 0; idx < this.registeredEvents_.length; idx++) {
115 var reg = this.registeredEvents_[idx];
116 Dygraph.removeEvent(reg.elem, reg.type, reg.fn);
117 }
118 }
119
120 this.registeredEvents_ = [];
f914bed1 121};
aeca29ac 122
dedb4f5f 123/**
dedb4f5f
DV
124 * Cancels further processing of an event. This is useful to prevent default
125 * browser actions, e.g. highlighting text on a double-click.
126 * Based on the article at
127 * http://www.switchonthecode.com/tutorials/javascript-tutorial-the-scroll-wheel
39b33f9f 128 * @param {!Event} e The event whose normal behavior should be canceled.
f11283de 129 * @private
dedb4f5f
DV
130 */
131Dygraph.cancelEvent = function(e) {
132 e = e ? e : window.event;
133 if (e.stopPropagation) {
134 e.stopPropagation();
135 }
136 if (e.preventDefault) {
137 e.preventDefault();
138 }
139 e.cancelBubble = true;
140 e.cancel = true;
141 e.returnValue = false;
142 return false;
143};
144
145/**
146 * Convert hsv values to an rgb(r,g,b) string. Taken from MochiKit.Color. This
147 * is used to generate default series colors which are evenly spaced on the
148 * color wheel.
f11283de
DV
149 * @param { number } hue Range is 0.0-1.0.
150 * @param { number } saturation Range is 0.0-1.0.
151 * @param { number } value Range is 0.0-1.0.
152 * @return { string } "rgb(r,g,b)" where r, g and b range from 0-255.
dedb4f5f
DV
153 * @private
154 */
155Dygraph.hsvToRGB = function (hue, saturation, value) {
156 var red;
157 var green;
158 var blue;
159 if (saturation === 0) {
160 red = value;
161 green = value;
162 blue = value;
163 } else {
164 var i = Math.floor(hue * 6);
165 var f = (hue * 6) - i;
166 var p = value * (1 - saturation);
167 var q = value * (1 - (saturation * f));
168 var t = value * (1 - (saturation * (1 - f)));
169 switch (i) {
170 case 1: red = q; green = value; blue = p; break;
171 case 2: red = p; green = value; blue = t; break;
172 case 3: red = p; green = q; blue = value; break;
173 case 4: red = t; green = p; blue = value; break;
174 case 5: red = value; green = p; blue = q; break;
175 case 6: // fall through
176 case 0: red = value; green = t; blue = p; break;
177 }
178 }
179 red = Math.floor(255 * red + 0.5);
180 green = Math.floor(255 * green + 0.5);
181 blue = Math.floor(255 * blue + 0.5);
182 return 'rgb(' + red + ',' + green + ',' + blue + ')';
183};
184
185// The following functions are from quirksmode.org with a modification for Safari from
186// http://blog.firetree.net/2005/07/04/javascript-find-position/
187// http://www.quirksmode.org/js/findpos.html
1bc38cbc 188// ... and modifications to support scrolling divs.
dedb4f5f 189
8442269f 190/**
464b5f50
DV
191 * Find the coordinates of an object relative to the top left of the page.
192 *
f11283de
DV
193 * TODO(danvk): change obj type from Node -&gt; !Node
194 * @param {Node} obj
464b5f50 195 * @return {{x:number,y:number}}
8442269f
RK
196 * @private
197 */
464b5f50
DV
198Dygraph.findPos = function(obj) {
199 var curleft = 0, curtop = 0;
200 if (obj.offsetParent) {
8442269f 201 var copyObj = obj;
464b5f50 202 while (1) {
ecdb6dff 203 // NOTE: the if statement here is for IE8.
464b5f50 204 var borderLeft = "0", borderTop = "0";
4ff8c62e 205 if (window.getComputedStyle) {
464b5f50
DV
206 var computedStyle = window.getComputedStyle(copyObj, null);
207 borderLeft = computedStyle.borderLeft || "0";
208 borderTop = computedStyle.borderTop || "0";
4ff8c62e 209 }
abc8c570 210 curleft += parseInt(borderLeft, 10) ;
abc8c570 211 curtop += parseInt(borderTop, 10) ;
464b5f50 212 curleft += copyObj.offsetLeft;
8442269f 213 curtop += copyObj.offsetTop;
464b5f50 214 if (!copyObj.offsetParent) {
dedb4f5f 215 break;
8442269f
RK
216 }
217 copyObj = copyObj.offsetParent;
dedb4f5f 218 }
464b5f50
DV
219 } else {
220 // TODO(danvk): why would obj ever have these properties?
221 if (obj.x) curleft += obj.x;
222 if (obj.y) curtop += obj.y;
8442269f 223 }
464b5f50 224
8442269f 225 // This handles the case where the object is inside a scrolled div.
464b5f50
DV
226 while (obj && obj != document.body) {
227 curleft -= obj.scrollLeft;
8442269f
RK
228 curtop -= obj.scrollTop;
229 obj = obj.parentNode;
230 }
464b5f50 231 return {x: curleft, y: curtop};
dedb4f5f
DV
232};
233
234/**
dedb4f5f
DV
235 * Returns the x-coordinate of the event in a coordinate system where the
236 * top-left corner of the page (not the window) is (0,0).
237 * Taken from MochiKit.Signal
f11283de
DV
238 * @param {!Event} e
239 * @return {number}
240 * @private
dedb4f5f
DV
241 */
242Dygraph.pageX = function(e) {
243 if (e.pageX) {
244 return (!e.pageX || e.pageX < 0) ? 0 : e.pageX;
245 } else {
f11283de 246 var de = document.documentElement;
dedb4f5f
DV
247 var b = document.body;
248 return e.clientX +
249 (de.scrollLeft || b.scrollLeft) -
250 (de.clientLeft || 0);
251 }
252};
253
254/**
dedb4f5f
DV
255 * Returns the y-coordinate of the event in a coordinate system where the
256 * top-left corner of the page (not the window) is (0,0).
257 * Taken from MochiKit.Signal
f11283de
DV
258 * @param {!Event} e
259 * @return {number}
260 * @private
dedb4f5f
DV
261 */
262Dygraph.pageY = function(e) {
263 if (e.pageY) {
264 return (!e.pageY || e.pageY < 0) ? 0 : e.pageY;
265 } else {
f11283de 266 var de = document.documentElement;
dedb4f5f
DV
267 var b = document.body;
268 return e.clientY +
269 (de.scrollTop || b.scrollTop) -
270 (de.clientTop || 0);
271 }
272};
273
274/**
806f92c1
DV
275 * Converts page the x-coordinate of the event to pixel x-coordinates on the
276 * canvas (i.e. DOM Coords).
277 * @param {!Event} e Drag event.
278 * @param {!DygraphInteractionContext} context Interaction context object.
279 * @return {number} The amount by which the drag has moved to the right.
280 */
281Dygraph.dragGetX_ = function(e, context) {
282 return Dygraph.pageX(e) - context.px;
283};
284
285/**
286 * Converts page the y-coordinate of the event to pixel y-coordinates on the
287 * canvas (i.e. DOM Coords).
288 * @param {!Event} e Drag event.
289 * @param {!DygraphInteractionContext} context Interaction context object.
290 * @return {number} The amount by which the drag has moved down.
291 */
292Dygraph.dragGetY_ = function(e, context) {
293 return Dygraph.pageY(e) - context.py;
294};
295
296/**
f11283de
DV
297 * This returns true unless the parameter is 0, null, undefined or NaN.
298 * TODO(danvk): rename this function to something like 'isNonZeroNan'.
299 *
300 * @param {number} x The number to consider.
301 * @return {boolean} Whether the number is zero or NaN.
dedb4f5f 302 * @private
dedb4f5f 303 */
dedb4f5f 304Dygraph.isOK = function(x) {
f11283de 305 return !!x && !isNaN(x);
dedb4f5f
DV
306};
307
308/**
55deb02f 309 * @param {{x:?number,y:?number,yval:?number}} p The point to consider, valid
f11283de 310 * points are {x, y} objects
55deb02f
DV
311 * @param {boolean=} opt_allowNaNY Treat point with y=NaN as valid
312 * @return {boolean} Whether the point has numeric x and y.
62c3d2fd 313 * @private
62c3d2fd 314 */
55deb02f 315Dygraph.isValidPoint = function(p, opt_allowNaNY) {
f11283de
DV
316 if (!p) return false; // null or undefined object
317 if (p.yval === null) return false; // missing point
04c104d7
KW
318 if (p.x === null || p.x === undefined) return false;
319 if (p.y === null || p.y === undefined) return false;
55deb02f 320 if (isNaN(p.x) || (!opt_allowNaNY && isNaN(p.y))) return false;
62c3d2fd
KW
321 return true;
322};
323
324/**
dedb4f5f
DV
325 * Number formatting function which mimicks the behavior of %g in printf, i.e.
326 * either exponential or fixed format (without trailing 0s) is used depending on
327 * the length of the generated string. The advantage of this format is that
328 * there is a predictable upper bound on the resulting string length,
329 * significant figures are not dropped, and normal numbers are not displayed in
330 * exponential notation.
331 *
332 * NOTE: JavaScript's native toPrecision() is NOT a drop-in replacement for %g.
333 * It creates strings which are too long for absolute values between 10^-4 and
334 * 10^-6, e.g. '0.00001' instead of '1e-5'. See tests/number-format.html for
335 * output examples.
336 *
f11283de
DV
337 * @param {number} x The number to format
338 * @param {number=} opt_precision The precision to use, default 2.
339 * @return {string} A string formatted like %g in printf. The max generated
dedb4f5f
DV
340 * string length should be precision + 6 (e.g 1.123e+300).
341 */
342Dygraph.floatFormat = function(x, opt_precision) {
343 // Avoid invalid precision values; [1, 21] is the valid range.
344 var p = Math.min(Math.max(1, opt_precision || 2), 21);
345
346 // This is deceptively simple. The actual algorithm comes from:
347 //
348 // Max allowed length = p + 4
349 // where 4 comes from 'e+n' and '.'.
350 //
351 // Length of fixed format = 2 + y + p
352 // where 2 comes from '0.' and y = # of leading zeroes.
353 //
354 // Equating the two and solving for y yields y = 2, or 0.00xxxx which is
355 // 1.0e-3.
356 //
357 // Since the behavior of toPrecision() is identical for larger numbers, we
358 // don't have to worry about the other bound.
359 //
360 // Finally, the argument for toExponential() is the number of trailing digits,
361 // so we take off 1 for the value before the '.'.
758a629f 362 return (Math.abs(x) < 1.0e-3 && x !== 0.0) ?
dedb4f5f
DV
363 x.toExponential(p - 1) : x.toPrecision(p);
364};
365
366/**
dedb4f5f 367 * Converts '9' to '09' (useful for dates)
f11283de
DV
368 * @param {number} x
369 * @return {string}
370 * @private
dedb4f5f
DV
371 */
372Dygraph.zeropad = function(x) {
373 if (x < 10) return "0" + x; else return "" + x;
374};
375
376/**
377 * Return a string version of the hours, minutes and seconds portion of a date.
f11283de
DV
378 *
379 * @param {number} date The JavaScript date (ms since epoch)
380 * @return {string} A time of the form "HH:MM:SS"
dedb4f5f
DV
381 * @private
382 */
383Dygraph.hmsString_ = function(date) {
384 var zeropad = Dygraph.zeropad;
385 var d = new Date(date);
386 if (d.getSeconds()) {
387 return zeropad(d.getHours()) + ":" +
388 zeropad(d.getMinutes()) + ":" +
389 zeropad(d.getSeconds());
390 } else {
391 return zeropad(d.getHours()) + ":" + zeropad(d.getMinutes());
392 }
393};
394
395/**
464b5f50
DV
396 * Convert a JS date (millis since epoch) to YYYY/MM/DD
397 * @param {number} date The JavaScript date (ms since epoch)
398 * @return {string} A date of the form "YYYY/MM/DD"
399 * @private
400 */
401Dygraph.dateString_ = function(date) {
402 var zeropad = Dygraph.zeropad;
403 var d = new Date(date);
404
405 // Get the year:
406 var year = "" + d.getFullYear();
407 // Get a 0 padded month string
408 var month = zeropad(d.getMonth() + 1); //months are 0-offset, sigh
409 // Get a 0 padded day string
410 var day = zeropad(d.getDate());
411
412 var ret = "";
413 var frac = d.getHours() * 3600 + d.getMinutes() * 60 + d.getSeconds();
414 if (frac) ret = " " + Dygraph.hmsString_(date);
415
416 return year + "/" + month + "/" + day + ret;
417};
418
419/**
dedb4f5f 420 * Round a number to the specified number of digits past the decimal point.
f11283de
DV
421 * @param {number} num The number to round
422 * @param {number} places The number of decimals to which to round
423 * @return {number} The rounded number
dedb4f5f
DV
424 * @private
425 */
426Dygraph.round_ = function(num, places) {
427 var shift = Math.pow(10, places);
428 return Math.round(num * shift)/shift;
429};
430
431/**
dedb4f5f
DV
432 * Implementation of binary search over an array.
433 * Currently does not work when val is outside the range of arry's values.
f11283de
DV
434 * @param {number} val the value to search for
435 * @param {Array.<number>} arry is the value over which to search
436 * @param {number} abs If abs > 0, find the lowest entry greater than val
437 * If abs < 0, find the highest entry less than val.
438 * If abs == 0, find the entry that equals val.
439 * @param {number=} low The first index in arry to consider (optional)
440 * @param {number=} high The last index in arry to consider (optional)
441 * @return {number} Index of the element, or -1 if it isn't found.
442 * @private
dedb4f5f
DV
443 */
444Dygraph.binarySearch = function(val, arry, abs, low, high) {
758a629f
DV
445 if (low === null || low === undefined ||
446 high === null || high === undefined) {
dedb4f5f
DV
447 low = 0;
448 high = arry.length - 1;
449 }
450 if (low > high) {
451 return -1;
452 }
758a629f 453 if (abs === null || abs === undefined) {
dedb4f5f
DV
454 abs = 0;
455 }
456 var validIndex = function(idx) {
457 return idx >= 0 && idx < arry.length;
758a629f
DV
458 };
459 var mid = parseInt((low + high) / 2, 10);
dedb4f5f 460 var element = arry[mid];
f11283de 461 var idx;
dedb4f5f
DV
462 if (element == val) {
463 return mid;
f11283de 464 } else if (element > val) {
dedb4f5f
DV
465 if (abs > 0) {
466 // Accept if element > val, but also if prior element < val.
758a629f 467 idx = mid - 1;
dedb4f5f
DV
468 if (validIndex(idx) && arry[idx] < val) {
469 return mid;
470 }
471 }
472 return Dygraph.binarySearch(val, arry, abs, low, mid - 1);
f11283de 473 } else if (element < val) {
dedb4f5f
DV
474 if (abs < 0) {
475 // Accept if element < val, but also if prior element > val.
758a629f 476 idx = mid + 1;
dedb4f5f
DV
477 if (validIndex(idx) && arry[idx] > val) {
478 return mid;
479 }
480 }
481 return Dygraph.binarySearch(val, arry, abs, mid + 1, high);
482 }
f11283de 483 return -1; // can't actually happen, but makes closure compiler happy
dedb4f5f
DV
484};
485
486/**
dedb4f5f
DV
487 * Parses a date, returning the number of milliseconds since epoch. This can be
488 * passed in as an xValueParser in the Dygraph constructor.
489 * TODO(danvk): enumerate formats that this understands.
f11283de
DV
490 *
491 * @param {string} dateStr A date in a variety of possible string formats.
492 * @return {number} Milliseconds since epoch.
493 * @private
dedb4f5f
DV
494 */
495Dygraph.dateParser = function(dateStr) {
496 var dateStrSlashed;
497 var d;
769e8bc7 498
3f675fe5
DV
499 // Let the system try the format first, with one caveat:
500 // YYYY-MM-DD[ HH:MM:SS] is interpreted as UTC by a variety of browsers.
501 // dygraphs displays dates in local time, so this will result in surprising
502 // inconsistencies. But if you specify "T" or "Z" (i.e. YYYY-MM-DDTHH:MM:SS),
503 // then you probably know what you're doing, so we'll let you go ahead.
504 // Issue: http://code.google.com/p/dygraphs/issues/detail?id=255
505 if (dateStr.search("-") == -1 ||
506 dateStr.search("T") != -1 || dateStr.search("Z") != -1) {
507 d = Dygraph.dateStrToMillis(dateStr);
508 if (d && !isNaN(d)) return d;
509 }
769e8bc7 510
dedb4f5f
DV
511 if (dateStr.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12'
512 dateStrSlashed = dateStr.replace("-", "/", "g");
513 while (dateStrSlashed.search("-") != -1) {
514 dateStrSlashed = dateStrSlashed.replace("-", "/");
515 }
516 d = Dygraph.dateStrToMillis(dateStrSlashed);
517 } else if (dateStr.length == 8) { // e.g. '20090712'
518 // TODO(danvk): remove support for this format. It's confusing.
758a629f
DV
519 dateStrSlashed = dateStr.substr(0,4) + "/" + dateStr.substr(4,2) + "/" +
520 dateStr.substr(6,2);
dedb4f5f
DV
521 d = Dygraph.dateStrToMillis(dateStrSlashed);
522 } else {
523 // Any format that Date.parse will accept, e.g. "2009/07/12" or
524 // "2009/07/12 12:34:56"
525 d = Dygraph.dateStrToMillis(dateStr);
526 }
527
528 if (!d || isNaN(d)) {
8a68db7d 529 console.error("Couldn't parse " + dateStr + " as a date");
dedb4f5f
DV
530 }
531 return d;
532};
533
534/**
dedb4f5f
DV
535 * This is identical to JavaScript's built-in Date.parse() method, except that
536 * it doesn't get replaced with an incompatible method by aggressive JS
537 * libraries like MooTools or Joomla.
f11283de
DV
538 * @param {string} str The date string, e.g. "2011/05/06"
539 * @return {number} millis since epoch
540 * @private
dedb4f5f
DV
541 */
542Dygraph.dateStrToMillis = function(str) {
543 return new Date(str).getTime();
544};
545
546// These functions are all based on MochiKit.
547/**
548 * Copies all the properties from o to self.
549 *
f11283de
DV
550 * @param {!Object} self
551 * @param {!Object} o
552 * @return {!Object}
dedb4f5f 553 */
f11283de 554Dygraph.update = function(self, o) {
dedb4f5f
DV
555 if (typeof(o) != 'undefined' && o !== null) {
556 for (var k in o) {
557 if (o.hasOwnProperty(k)) {
558 self[k] = o[k];
559 }
560 }
561 }
562 return self;
563};
564
565/**
48e614ac
DV
566 * Copies all the properties from o to self.
567 *
f11283de
DV
568 * @param {!Object} self
569 * @param {!Object} o
570 * @return {!Object}
48e614ac
DV
571 * @private
572 */
573Dygraph.updateDeep = function (self, o) {
920208fb
PF
574 // Taken from http://stackoverflow.com/questions/384286/javascript-isdom-how-do-you-check-if-a-javascript-object-is-a-dom-object
575 function isNode(o) {
576 return (
577 typeof Node === "object" ? o instanceof Node :
578 typeof o === "object" && typeof o.nodeType === "number" && typeof o.nodeName==="string"
579 );
580 }
581
48e614ac
DV
582 if (typeof(o) != 'undefined' && o !== null) {
583 for (var k in o) {
584 if (o.hasOwnProperty(k)) {
758a629f 585 if (o[k] === null) {
48e614ac
DV
586 self[k] = null;
587 } else if (Dygraph.isArrayLike(o[k])) {
588 self[k] = o[k].slice();
920208fb 589 } else if (isNode(o[k])) {
66ad3609
RK
590 // DOM objects are shallowly-copied.
591 self[k] = o[k];
48e614ac 592 } else if (typeof(o[k]) == 'object') {
c1c5dfeb 593 if (typeof(self[k]) != 'object' || self[k] === null) {
48e614ac
DV
594 self[k] = {};
595 }
596 Dygraph.updateDeep(self[k], o[k]);
597 } else {
598 self[k] = o[k];
599 }
600 }
601 }
602 }
603 return self;
604};
605
606/**
55deb02f 607 * @param {*} o
f11283de 608 * @return {boolean}
dedb4f5f
DV
609 * @private
610 */
f11283de 611Dygraph.isArrayLike = function(o) {
dedb4f5f
DV
612 var typ = typeof(o);
613 if (
614 (typ != 'object' && !(typ == 'function' &&
615 typeof(o.item) == 'function')) ||
616 o === null ||
617 typeof(o.length) != 'number' ||
618 o.nodeType === 3
619 ) {
620 return false;
621 }
622 return true;
623};
624
625/**
f11283de
DV
626 * @param {Object} o
627 * @return {boolean}
dedb4f5f
DV
628 * @private
629 */
630Dygraph.isDateLike = function (o) {
631 if (typeof(o) != "object" || o === null ||
632 typeof(o.getTime) != 'function') {
633 return false;
634 }
635 return true;
636};
637
638/**
48e614ac 639 * Note: this only seems to work for arrays.
f11283de
DV
640 * @param {!Array} o
641 * @return {!Array}
dedb4f5f
DV
642 * @private
643 */
644Dygraph.clone = function(o) {
645 // TODO(danvk): figure out how MochiKit's version works
646 var r = [];
647 for (var i = 0; i < o.length; i++) {
648 if (Dygraph.isArrayLike(o[i])) {
649 r.push(Dygraph.clone(o[i]));
650 } else {
651 r.push(o[i]);
652 }
653 }
654 return r;
655};
656
657/**
dedb4f5f
DV
658 * Create a new canvas element. This is more complex than a simple
659 * document.createElement("canvas") because of IE and excanvas.
f11283de
DV
660 *
661 * @return {!HTMLCanvasElement}
662 * @private
dedb4f5f
DV
663 */
664Dygraph.createCanvas = function() {
665 var canvas = document.createElement("canvas");
666
c0f54d4f 667 var isIE = (/MSIE/.test(navigator.userAgent) && !window.opera);
dedb4f5f 668 if (isIE && (typeof(G_vmlCanvasManager) != 'undefined')) {
f11283de
DV
669 canvas = G_vmlCanvasManager.initElement(
670 /**@type{!HTMLCanvasElement}*/(canvas));
dedb4f5f
DV
671 }
672
673 return canvas;
674};
9ca829f2
DV
675
676/**
37819481
PH
677 * Returns the context's pixel ratio, which is the ratio between the device
678 * pixel ratio and the backing store ratio. Typically this is 1 for conventional
679 * displays, and > 1 for HiDPI displays (such as the Retina MBP).
680 * See http://www.html5rocks.com/en/tutorials/canvas/hidpi/ for more details.
681 *
682 * @param {!CanvasRenderingContext2D} context The canvas's 2d context.
683 * @return {number} The ratio of the device pixel ratio and the backing store
684 * ratio for the specified context.
685 */
686Dygraph.getContextPixelRatio = function(context) {
687 try {
8241944b
GJ
688 var devicePixelRatio = window.devicePixelRatio;
689 var backingStoreRatio = context.webkitBackingStorePixelRatio ||
37819481
PH
690 context.mozBackingStorePixelRatio ||
691 context.msBackingStorePixelRatio ||
692 context.oBackingStorePixelRatio ||
8241944b
GJ
693 context.backingStorePixelRatio;
694 if (devicePixelRatio !== undefined &&
695 backingStorePixelRatio !== undefined) {
696 return devicePixelRatio / backingStoreRatio;
697 } else {
698 // If either value is undefined, the ratio is meaningless so we want to
699 // return 1.
700 return 1;
701 }
37819481
PH
702 } catch (e) {
703 return 1;
704 }
705};
706
707/**
971870e5
DV
708 * Checks whether the user is on an Android browser.
709 * Android does not fully support the <canvas> tag, e.g. w/r/t/ clipping.
f11283de
DV
710 * @return {boolean}
711 * @private
971870e5
DV
712 */
713Dygraph.isAndroid = function() {
758a629f 714 return (/Android/).test(navigator.userAgent);
971870e5
DV
715};
716
f11283de
DV
717
718/**
719 * TODO(danvk): use @template here when it's better supported for classes.
720 * @param {!Array} array
721 * @param {number} start
722 * @param {number} length
45a8c16f 723 * @param {function(!Array,?):boolean=} predicate
f11283de
DV
724 * @constructor
725 */
a26206cf
RK
726Dygraph.Iterator = function(array, start, length, predicate) {
727 start = start || 0;
728 length = length || array.length;
ff1074cd
RK
729 this.hasNext = true; // Use to identify if there's another element.
730 this.peek = null; // Use for look-ahead
0f20de1c 731 this.start_ = start;
a26206cf
RK
732 this.array_ = array;
733 this.predicate_ = predicate;
734 this.end_ = Math.min(array.length, start + length);
ff1074cd
RK
735 this.nextIdx_ = start - 1; // use -1 so initial advance works.
736 this.next(); // ignoring result.
42a9ebb8 737};
a26206cf 738
f11283de
DV
739/**
740 * @return {Object}
741 */
a26206cf 742Dygraph.Iterator.prototype.next = function() {
ff1074cd
RK
743 if (!this.hasNext) {
744 return null;
a26206cf 745 }
ff1074cd 746 var obj = this.peek;
a26206cf 747
ff1074cd
RK
748 var nextIdx = this.nextIdx_ + 1;
749 var found = false;
750 while (nextIdx < this.end_) {
a26206cf 751 if (!this.predicate_ || this.predicate_(this.array_, nextIdx)) {
ff1074cd
RK
752 this.peek = this.array_[nextIdx];
753 found = true;
754 break;
a26206cf
RK
755 }
756 nextIdx++;
757 }
758 this.nextIdx_ = nextIdx;
ff1074cd
RK
759 if (!found) {
760 this.hasNext = false;
761 this.peek = null;
762 }
763 return obj;
42a9ebb8 764};
a26206cf 765
971870e5 766/**
222d67c9 767 * Returns a new iterator over array, between indexes start and
7d1afbb9
RK
768 * start + length, and only returns entries that pass the accept function
769 *
f11283de
DV
770 * @param {!Array} array the array to iterate over.
771 * @param {number} start the first index to iterate over, 0 if absent.
772 * @param {number} length the number of elements in the array to iterate over.
773 * This, along with start, defines a slice of the array, and so length
774 * doesn't imply the number of elements in the iterator when accept doesn't
775 * always accept all values. array.length when absent.
45a8c16f 776 * @param {function(?):boolean=} opt_predicate a function that takes
f11283de
DV
777 * parameters array and idx, which returns true when the element should be
778 * returned. If omitted, all elements are accepted.
779 * @private
7d1afbb9 780 */
f11283de
DV
781Dygraph.createIterator = function(array, start, length, opt_predicate) {
782 return new Dygraph.Iterator(array, start, length, opt_predicate);
7d1afbb9
RK
783};
784
a96b8ba3
A
785// Shim layer with setTimeout fallback.
786// From: http://paulirish.com/2011/requestanimationframe-for-smart-animating/
e9a32469
A
787// Should be called with the window context:
788// Dygraph.requestAnimFrame.call(window, function() {})
bec100ae 789Dygraph.requestAnimFrame = (function() {
a96b8ba3
A
790 return window.requestAnimationFrame ||
791 window.webkitRequestAnimationFrame ||
792 window.mozRequestAnimationFrame ||
793 window.oRequestAnimationFrame ||
794 window.msRequestAnimationFrame ||
795 function (callback) {
796 window.setTimeout(callback, 1000 / 60);
797 };
798})();
799
800/**
d91ba598
A
801 * Call a function at most maxFrames times at an attempted interval of
802 * framePeriodInMillis, then call a cleanup function once. repeatFn is called
803 * once immediately, then at most (maxFrames - 1) times asynchronously. If
804 * maxFrames==1, then cleanup_fn() is also called synchronously. This function
805 * is used to sequence animation.
806 * @param {function(number)} repeatFn Called repeatedly -- takes the frame
807 * number (from 0 to maxFrames-1) as an argument.
808 * @param {number} maxFrames The max number of times to call repeatFn
809 * @param {number} framePeriodInMillis Max requested time between frames.
810 * @param {function()} cleanupFn A function to call after all repeatFn calls.
811 * @private
812 */
813Dygraph.repeatAndCleanup = function(repeatFn, maxFrames, framePeriodInMillis,
bec100ae 814 cleanupFn) {
d91ba598
A
815 var frameNumber = 0;
816 var previousFrameNumber;
817 var startTime = new Date().getTime();
818 repeatFn(frameNumber);
819 if (maxFrames == 1) {
820 cleanupFn();
b1a3b195
DV
821 return;
822 }
d91ba598 823 var maxFrameArg = maxFrames - 1;
b1a3b195
DV
824
825 (function loop() {
d91ba598 826 if (frameNumber >= maxFrames) return;
e9a32469 827 Dygraph.requestAnimFrame.call(window, function() {
d91ba598
A
828 // Determine which frame to draw based on the delay so far. Will skip
829 // frames if necessary.
830 var currentTime = new Date().getTime();
831 var delayInMillis = currentTime - startTime;
832 previousFrameNumber = frameNumber;
833 frameNumber = Math.floor(delayInMillis / framePeriodInMillis);
834 var frameDelta = frameNumber - previousFrameNumber;
835 // If we predict that the subsequent repeatFn call will overshoot our
836 // total frame target, so our last call will cause a stutter, then jump to
837 // the last call immediately. If we're going to cause a stutter, better
838 // to do it faster than slower.
839 var predictOvershootStutter = (frameNumber + frameDelta) > maxFrameArg;
840 if (predictOvershootStutter || (frameNumber >= maxFrameArg)) {
841 repeatFn(maxFrameArg); // Ensure final call with maxFrameArg.
842 cleanupFn();
b1a3b195 843 } else {
83b0c192 844 if (frameDelta !== 0) { // Don't call repeatFn with duplicate frames.
d91ba598
A
845 repeatFn(frameNumber);
846 }
b1a3b195
DV
847 loop();
848 }
a96b8ba3 849 });
b1a3b195
DV
850 })();
851};
852
853/**
9ca829f2
DV
854 * This function will scan the option list and determine if they
855 * require us to recalculate the pixel positions of each point.
f11283de 856 * @param {!Array.<string>} labels a list of options to check.
222d67c9 857 * @param {!Object} attrs
f11283de
DV
858 * @return {boolean} true if the graph needs new points else false.
859 * @private
9ca829f2
DV
860 */
861Dygraph.isPixelChangingOptionList = function(labels, attrs) {
862 // A whitelist of options that do not change pixel positions.
863 var pixelSafeOptions = {
864 'annotationClickHandler': true,
865 'annotationDblClickHandler': true,
866 'annotationMouseOutHandler': true,
867 'annotationMouseOverHandler': true,
868 'axisLabelColor': true,
869 'axisLineColor': true,
870 'axisLineWidth': true,
871 'clickCallback': true,
9ca829f2
DV
872 'digitsAfterDecimal': true,
873 'drawCallback': true,
5879307d 874 'drawHighlightPointCallback': true,
9ca829f2 875 'drawPoints': true,
78e58af4 876 'drawPointCallback': true,
9ca829f2
DV
877 'drawXGrid': true,
878 'drawYGrid': true,
879 'fillAlpha': true,
880 'gridLineColor': true,
881 'gridLineWidth': true,
882 'hideOverlayOnMouseOut': true,
883 'highlightCallback': true,
884 'highlightCircleSize': true,
885 'interactionModel': true,
886 'isZoomedIgnoreProgrammaticZoom': true,
887 'labelsDiv': true,
888 'labelsDivStyles': true,
889 'labelsDivWidth': true,
890 'labelsKMB': true,
891 'labelsKMG2': true,
892 'labelsSeparateLines': true,
893 'labelsShowZeroValues': true,
894 'legend': true,
895 'maxNumberWidth': true,
896 'panEdgeFraction': true,
897 'pixelsPerYLabel': true,
898 'pointClickCallback': true,
899 'pointSize': true,
ccd9d7c2
PF
900 'rangeSelectorPlotFillColor': true,
901 'rangeSelectorPlotStrokeColor': true,
9ca829f2
DV
902 'showLabelsOnHighlight': true,
903 'showRoller': true,
904 'sigFigs': true,
905 'strokeWidth': true,
906 'underlayCallback': true,
907 'unhighlightCallback': true,
908 'xAxisLabelFormatter': true,
909 'xTicker': true,
910 'xValueFormatter': true,
911 'yAxisLabelFormatter': true,
912 'yValueFormatter': true,
913 'zoomCallback': true
ccd9d7c2 914 };
9ca829f2
DV
915
916 // Assume that we do not require new points.
917 // This will change to true if we actually do need new points.
918 var requiresNewPoints = false;
919
920 // Create a dictionary of series names for faster lookup.
921 // If there are no labels, then the dictionary stays empty.
922 var seriesNamesDictionary = { };
923 if (labels) {
924 for (var i = 1; i < labels.length; i++) {
925 seriesNamesDictionary[labels[i]] = true;
926 }
927 }
928
929 // Iterate through the list of updated options.
5061b42f 930 for (var property in attrs) {
9ca829f2
DV
931 // Break early if we already know we need new points from a previous option.
932 if (requiresNewPoints) {
933 break;
934 }
935 if (attrs.hasOwnProperty(property)) {
936 // Find out of this field is actually a series specific options list.
937 if (seriesNamesDictionary[property]) {
938 // This property value is a list of options for this series.
939 // If any of these sub properties are not pixel safe, set the flag.
5061b42f 940 for (var subProperty in attrs[property]) {
9ca829f2
DV
941 // Break early if we already know we need new points from a previous option.
942 if (requiresNewPoints) {
943 break;
944 }
945 if (attrs[property].hasOwnProperty(subProperty) && !pixelSafeOptions[subProperty]) {
946 requiresNewPoints = true;
947 }
948 }
949 // If this was not a series specific option list, check if its a pixel changing property.
950 } else if (!pixelSafeOptions[property]) {
951 requiresNewPoints = true;
ccd9d7c2 952 }
9ca829f2
DV
953 }
954 }
955
956 return requiresNewPoints;
957};
78e58af4 958
78e58af4
RK
959Dygraph.Circles = {
960 DEFAULT : function(g, name, ctx, canvasx, canvasy, color, radius) {
961 ctx.beginPath();
962 ctx.fillStyle = color;
963 ctx.arc(canvasx, canvasy, radius, 0, 2 * Math.PI, false);
964 ctx.fill();
78e58af4 965 }
b7a1dc22 966 // For more shapes, include extras/shapes.js
78e58af4 967};
2bad4d92
DV
968
969/**
970 * To create a "drag" interaction, you typically register a mousedown event
971 * handler on the element where the drag begins. In that handler, you register a
972 * mouseup handler on the window to determine when the mouse is released,
973 * wherever that release happens. This works well, except when the user releases
974 * the mouse over an off-domain iframe. In that case, the mouseup event is
975 * handled by the iframe and never bubbles up to the window handler.
976 *
977 * To deal with this issue, we cover iframes with high z-index divs to make sure
978 * they don't capture mouseup.
979 *
980 * Usage:
981 * element.addEventListener('mousedown', function() {
982 * var tarper = new Dygraph.IFrameTarp();
983 * tarper.cover();
984 * var mouseUpHandler = function() {
985 * ...
986 * window.removeEventListener(mouseUpHandler);
987 * tarper.uncover();
988 * };
989 * window.addEventListener('mouseup', mouseUpHandler);
990 * };
222d67c9 991 *
2bad4d92
DV
992 * @constructor
993 */
994Dygraph.IFrameTarp = function() {
f11283de 995 /** @type {Array.<!HTMLDivElement>} */
2bad4d92
DV
996 this.tarps = [];
997};
998
999/**
1000 * Find all the iframes in the document and cover them with high z-index
1001 * transparent divs.
1002 */
1003Dygraph.IFrameTarp.prototype.cover = function() {
1004 var iframes = document.getElementsByTagName("iframe");
1005 for (var i = 0; i < iframes.length; i++) {
1006 var iframe = iframes[i];
1bc88216
DV
1007 var pos = Dygraph.findPos(iframe),
1008 x = pos.x,
1009 y = pos.y,
2bad4d92
DV
1010 width = iframe.offsetWidth,
1011 height = iframe.offsetHeight;
1012
1013 var div = document.createElement("div");
1014 div.style.position = "absolute";
1015 div.style.left = x + 'px';
1016 div.style.top = y + 'px';
1017 div.style.width = width + 'px';
1018 div.style.height = height + 'px';
1019 div.style.zIndex = 999;
1020 document.body.appendChild(div);
1021 this.tarps.push(div);
1022 }
1023};
1024
1025/**
1026 * Remove all the iframe covers. You should call this in a mouseup handler.
1027 */
1028Dygraph.IFrameTarp.prototype.uncover = function() {
1029 for (var i = 0; i < this.tarps.length; i++) {
1030 this.tarps[i].parentNode.removeChild(this.tarps[i]);
1031 }
1032 this.tarps = [];
1033};
e5763589
DV
1034
1035/**
df268bcc 1036 * Determine whether |data| is delimited by CR, CRLF, LF, LFCR.
e5763589 1037 * @param {string} data
f11283de 1038 * @return {?string} the delimiter that was detected (or null on failure).
e5763589
DV
1039 */
1040Dygraph.detectLineDelimiter = function(data) {
1041 for (var i = 0; i < data.length; i++) {
df268bcc
JH
1042 var code = data.charAt(i);
1043 if (code === '\r') {
1044 // Might actually be "\r\n".
1045 if (((i + 1) < data.length) && (data.charAt(i + 1) === '\n')) {
1046 return '\r\n';
1047 }
1048 return code;
1049 }
1050 if (code === '\n') {
e5763589 1051 // Might actually be "\n\r".
df268bcc
JH
1052 if (((i + 1) < data.length) && (data.charAt(i + 1) === '\r')) {
1053 return '\n\r';
1054 }
e5763589
DV
1055 return code;
1056 }
1057 }
1058
1059 return null;
1060};
def24194
DV
1061
1062/**
bcb545f4
LB
1063 * Is one node contained by another?
1064 * @param {Node} containee The contained node.
1065 * @param {Node} container The container node.
def24194
DV
1066 * @return {boolean} Whether containee is inside (or equal to) container.
1067 * @private
1068 */
bcb545f4 1069Dygraph.isNodeContainedBy = function(containee, container) {
def24194
DV
1070 if (container === null || containee === null) {
1071 return false;
1072 }
db775859
RK
1073 var containeeNode = /** @type {Node} */ (containee);
1074 while (containeeNode && containeeNode !== container) {
1075 containeeNode = containeeNode.parentNode;
def24194 1076 }
db775859 1077 return (containeeNode === container);
def24194 1078};
2fd143d3
DV
1079
1080
1081// This masks some numeric issues in older versions of Firefox,
1082// where 1.0/Math.pow(10,2) != Math.pow(10,-2).
1083/** @type {function(number,number):number} */
1084Dygraph.pow = function(base, exp) {
1085 if (exp < 0) {
1086 return 1.0 / Math.pow(base, -exp);
1087 }
1088 return Math.pow(base, exp);
1089};
1090
9a4fd029
DV
1091// For Dygraph.setDateSameTZ, below.
1092Dygraph.dateSetters = {
1093 ms: Date.prototype.setMilliseconds,
1094 s: Date.prototype.setSeconds,
1095 m: Date.prototype.setMinutes,
1096 h: Date.prototype.setHours
1097};
1098
1099/**
1100 * This is like calling d.setSeconds(), d.setMinutes(), etc, except that it
1101 * adjusts for time zone changes to keep the date/time parts consistent.
1102 *
1103 * For example, d.getSeconds(), d.getMinutes() and d.getHours() will all be
1104 * the same before/after you call setDateSameTZ(d, {ms: 0}). The same is not
1105 * true if you call d.setMilliseconds(0).
1106 *
1107 * @type {function(!Date, Object.<number>)}
1108 */
1109Dygraph.setDateSameTZ = function(d, parts) {
1110 var tz = d.getTimezoneOffset();
1111 for (var k in parts) {
1112 if (!parts.hasOwnProperty(k)) continue;
1113 var setter = Dygraph.dateSetters[k];
1114 if (!setter) throw "Invalid setter: " + k;
1115 setter.call(d, parts[k]);
1116 if (d.getTimezoneOffset() != tz) {
1117 d.setTime(d.getTime() + (tz - d.getTimezoneOffset()) * 60 * 1000);
1118 }
1119 }
1120};
464b5f50
DV
1121
1122/**
1123 * Converts any valid CSS color (hex, rgb(), named color) to an RGB tuple.
1124 *
b7a1dc22 1125 * @param {!string} colorStr Any valid CSS color string.
464b5f50
DV
1126 * @return {{r:number,g:number,b:number}} Parsed RGB tuple.
1127 * @private
1128 */
b7a1dc22 1129Dygraph.toRGB_ = function(colorStr) {
464b5f50
DV
1130 // TODO(danvk): cache color parses to avoid repeated DOM manipulation.
1131 var div = document.createElement('div');
b7a1dc22 1132 div.style.backgroundColor = colorStr;
464b5f50
DV
1133 div.style.visibility = 'hidden';
1134 document.body.appendChild(div);
1bc88216 1135 var rgbStr = window.getComputedStyle(div, null).backgroundColor;
464b5f50 1136 document.body.removeChild(div);
b7a1dc22 1137 var bits = /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/.exec(rgbStr);
464b5f50
DV
1138 return {
1139 r: parseInt(bits[1], 10),
1140 g: parseInt(bits[2], 10),
1141 b: parseInt(bits[3], 10)
1142 };
1143};
55deb02f
DV
1144
1145/**
1146 * Checks whether the browser supports the &lt;canvas&gt; tag.
1147 * @param {HTMLCanvasElement=} opt_canvasElement Pass a canvas element as an
1148 * optimization if you have one.
1149 * @return {boolean} Whether the browser supports canvas.
1150 */
1151Dygraph.isCanvasSupported = function(opt_canvasElement) {
1152 var canvas;
1153 try {
1154 canvas = opt_canvasElement || document.createElement("canvas");
1155 canvas.getContext("2d");
1156 }
1157 catch (e) {
1158 var ie = navigator.appVersion.match(/MSIE (\d\.\d)/);
1159 var opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
1160 if ((!ie) || (ie[1] < 6) || (opera))
1161 return false;
1162 return true;
1163 }
1164 return true;
1165};
1166
1167/**
1168 * Parses the value as a floating point number. This is like the parseFloat()
1169 * built-in, but with a few differences:
1170 * - the empty string is parsed as null, rather than NaN.
1171 * - if the string cannot be parsed at all, an error is logged.
1172 * If the string can't be parsed, this method returns null.
1173 * @param {string} x The string to be parsed
1174 * @param {number=} opt_line_no The line number from which the string comes.
1175 * @param {string=} opt_line The text of the line from which the string comes.
1176 */
1177Dygraph.parseFloat_ = function(x, opt_line_no, opt_line) {
1178 var val = parseFloat(x);
1179 if (!isNaN(val)) return val;
1180
1181 // Try to figure out what happeend.
1182 // If the value is the empty string, parse it as null.
1183 if (/^ *$/.test(x)) return null;
1184
1185 // If it was actually "NaN", return it as NaN.
1186 if (/^ *nan *$/i.test(x)) return NaN;
1187
1188 // Looks like a parsing error.
1189 var msg = "Unable to parse '" + x + "' as a number";
1190 if (opt_line !== undefined && opt_line_no !== undefined) {
1191 msg += " on line " + (1+(opt_line_no||0)) + " ('" + opt_line + "') of CSV.";
1192 }
8a68db7d 1193 console.error(msg);
55deb02f
DV
1194
1195 return null;
1196};