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