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