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