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