Add hints in dygraphs benchmark for parameters.
[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
a26206cf
RK
684Dygraph.Iterator = function(array, start, length, predicate) {
685 start = start || 0;
686 length = length || array.length;
687 this.array_ = array;
688 this.predicate_ = predicate;
689 this.end_ = Math.min(array.length, start + length);
690 this.nextIdx_ = start - 1; // use -1 so initial call to advance works.
691 this.hasNext_ = true;
692 this.peek_ = null;
693 this.advance_();
694}
695
696Dygraph.Iterator.prototype.hasNext = function() {
697 return this.hasNext_;
698}
699
700Dygraph.Iterator.prototype.next = function() {
701 if (this.hasNext_) {
702 var obj = this.peek_;
703 this.advance_();
704 return obj;
705 }
706 return null;
707}
708
709Dygraph.Iterator.prototype.peek = function() {
710 return this.peek_;
711}
712
713Dygraph.Iterator.prototype.advance_ = function() {
714 var nextIdx = this.nextIdx_;
715 nextIdx++;
716 while(nextIdx < this.end_) {
717 if (!this.predicate_ || this.predicate_(this.array_, nextIdx)) {
718 this.peek_ = this.array_[nextIdx];
719 this.nextIdx_ = nextIdx;
720 return;
721 }
722 nextIdx++;
723 }
724 this.nextIdx_ = nextIdx;
725 this.hasNext_ = false;
726 this.peek_ = null;
727}
728
971870e5
DV
729/**
730 * @private
7d1afbb9
RK
731 * Returns a new iterator over array, between indexes start and
732 * start + length, and only returns entries that pass the accept function
733 *
734 * @param array the array to iterate over.
a26206cf 735 * @param start the first index to iterate over, 0 if absent.
7d1afbb9
RK
736 * @param length the number of elements in the array to iterate over.
737 * This, along with start, defines a slice of the array, and so length
738 * doesn't imply the number of elements in the iterator when accept
a26206cf 739 * doesn't always accept all values. array.length when absent.
7d1afbb9
RK
740 * @param predicate a function that takes parameters array and idx, which
741 * returns true when the element should be returned. If omitted, all
742 * elements are accepted.
7d1afbb9
RK
743 */
744Dygraph.createIterator = function(array, start, length, predicate) {
a26206cf 745 return new Dygraph.Iterator(array, start, length, predicate);
7d1afbb9
RK
746};
747
748/**
749 * @private
b1a3b195
DV
750 * Call a function N times at a given interval, then call a cleanup function
751 * once. repeat_fn is called once immediately, then (times - 1) times
752 * asynchronously. If times=1, then cleanup_fn() is also called synchronously.
753 * @param repeat_fn {Function} Called repeatedly -- takes the number of calls
754 * (from 0 to times-1) as an argument.
755 * @param times {number} The number of times to call repeat_fn
756 * @param every_ms {number} Milliseconds between calls
757 * @param cleanup_fn {Function} A function to call after all repeat_fn calls.
758 * @private
759 */
760Dygraph.repeatAndCleanup = function(repeat_fn, times, every_ms, cleanup_fn) {
761 var count = 0;
762 var start_time = new Date().getTime();
763 repeat_fn(count);
764 if (times == 1) {
765 cleanup_fn();
766 return;
767 }
768
769 (function loop() {
770 if (count >= times) return;
771 var target_time = start_time + (1 + count) * every_ms;
772 setTimeout(function() {
773 count++;
758a629f 774 repeat_fn(count);
b1a3b195
DV
775 if (count >= times - 1) {
776 cleanup_fn();
777 } else {
778 loop();
779 }
780 }, target_time - new Date().getTime());
781 // TODO(danvk): adjust every_ms to produce evenly-timed function calls.
782 })();
783};
784
785/**
786 * @private
9ca829f2
DV
787 * This function will scan the option list and determine if they
788 * require us to recalculate the pixel positions of each point.
789 * @param { List } a list of options to check.
790 * @return { Boolean } true if the graph needs new points else false.
791 */
792Dygraph.isPixelChangingOptionList = function(labels, attrs) {
793 // A whitelist of options that do not change pixel positions.
794 var pixelSafeOptions = {
795 'annotationClickHandler': true,
796 'annotationDblClickHandler': true,
797 'annotationMouseOutHandler': true,
798 'annotationMouseOverHandler': true,
799 'axisLabelColor': true,
800 'axisLineColor': true,
801 'axisLineWidth': true,
802 'clickCallback': true,
9ca829f2
DV
803 'digitsAfterDecimal': true,
804 'drawCallback': true,
5879307d 805 'drawHighlightPointCallback': true,
9ca829f2 806 'drawPoints': true,
78e58af4 807 'drawPointCallback': true,
9ca829f2
DV
808 'drawXGrid': true,
809 'drawYGrid': true,
810 'fillAlpha': true,
811 'gridLineColor': true,
812 'gridLineWidth': true,
813 'hideOverlayOnMouseOut': true,
814 'highlightCallback': true,
815 'highlightCircleSize': true,
816 'interactionModel': true,
817 'isZoomedIgnoreProgrammaticZoom': true,
818 'labelsDiv': true,
819 'labelsDivStyles': true,
820 'labelsDivWidth': true,
821 'labelsKMB': true,
822 'labelsKMG2': true,
823 'labelsSeparateLines': true,
824 'labelsShowZeroValues': true,
825 'legend': true,
826 'maxNumberWidth': true,
827 'panEdgeFraction': true,
828 'pixelsPerYLabel': true,
829 'pointClickCallback': true,
830 'pointSize': true,
ccd9d7c2
PF
831 'rangeSelectorPlotFillColor': true,
832 'rangeSelectorPlotStrokeColor': true,
9ca829f2
DV
833 'showLabelsOnHighlight': true,
834 'showRoller': true,
835 'sigFigs': true,
836 'strokeWidth': true,
837 'underlayCallback': true,
838 'unhighlightCallback': true,
839 'xAxisLabelFormatter': true,
840 'xTicker': true,
841 'xValueFormatter': true,
842 'yAxisLabelFormatter': true,
843 'yValueFormatter': true,
844 'zoomCallback': true
ccd9d7c2 845 };
9ca829f2
DV
846
847 // Assume that we do not require new points.
848 // This will change to true if we actually do need new points.
849 var requiresNewPoints = false;
850
851 // Create a dictionary of series names for faster lookup.
852 // If there are no labels, then the dictionary stays empty.
853 var seriesNamesDictionary = { };
854 if (labels) {
855 for (var i = 1; i < labels.length; i++) {
856 seriesNamesDictionary[labels[i]] = true;
857 }
858 }
859
860 // Iterate through the list of updated options.
5061b42f 861 for (var property in attrs) {
9ca829f2
DV
862 // Break early if we already know we need new points from a previous option.
863 if (requiresNewPoints) {
864 break;
865 }
866 if (attrs.hasOwnProperty(property)) {
867 // Find out of this field is actually a series specific options list.
868 if (seriesNamesDictionary[property]) {
869 // This property value is a list of options for this series.
870 // If any of these sub properties are not pixel safe, set the flag.
5061b42f 871 for (var subProperty in attrs[property]) {
9ca829f2
DV
872 // Break early if we already know we need new points from a previous option.
873 if (requiresNewPoints) {
874 break;
875 }
876 if (attrs[property].hasOwnProperty(subProperty) && !pixelSafeOptions[subProperty]) {
877 requiresNewPoints = true;
878 }
879 }
880 // If this was not a series specific option list, check if its a pixel changing property.
881 } else if (!pixelSafeOptions[property]) {
882 requiresNewPoints = true;
ccd9d7c2 883 }
9ca829f2
DV
884 }
885 }
886
887 return requiresNewPoints;
888};
78e58af4 889
79253bd0 890/**
891 * Compares two arrays to see if they are equal. If either parameter is not an
892 * array it will return false. Does a shallow compare
893 * Dygraph.compareArrays([[1,2], [3, 4]], [[1,2], [3,4]]) === false.
894 * @param array1 first array
895 * @param array2 second array
896 * @return True if both parameters are arrays, and contents are equal.
897 */
898Dygraph.compareArrays = function(array1, array2) {
899 if (!Dygraph.isArrayLike(array1) || !Dygraph.isArrayLike(array2)) {
900 return false;
901 }
902 if (array1.length !== array2.length) {
903 return false;
904 }
905 for (var i = 0; i < array1.length; i++) {
906 if (array1[i] !== array2[i]) {
907 return false;
908 }
909 }
910 return true;
911};
2996a18e 912
240c0b11 913/**
5879307d
RK
914 * ctx: the canvas context
915 * sides: the number of sides in the shape.
916 * radius: the radius of the image.
917 * cx: center x coordate
918 * cy: center y coordinate
919 * rotationRadians: the shift of the initial angle, in radians.
920 * delta: the angle shift for each line. If missing, creates a regular
240c0b11
RK
921 * polygon.
922 */
5879307d
RK
923Dygraph.regularShape_ = function(
924 ctx, sides, radius, cx, cy, rotationRadians, delta) {
925 rotationRadians = rotationRadians ? rotationRadians : 0;
926 delta = delta ? delta : Math.PI * 2 / sides;
78e58af4 927
240c0b11
RK
928 ctx.beginPath();
929 var first = true;
5879307d 930 var initialAngle = rotationRadians;
240c0b11
RK
931 var angle = initialAngle;
932
933 var computeCoordinates = function() {
934 var x = cx + (Math.sin(angle) * radius);
935 var y = cy + (-Math.cos(angle) * radius);
936 return [x, y];
937 };
938
939 var initialCoordinates = computeCoordinates();
940 var x = initialCoordinates[0];
941 var y = initialCoordinates[1];
942 ctx.moveTo(x, y);
943
5879307d
RK
944 for (var idx = 0; idx < sides; idx++) {
945 angle = (idx == sides - 1) ? initialAngle : (angle + delta);
240c0b11
RK
946 var coords = computeCoordinates();
947 ctx.lineTo(coords[0], coords[1]);
948 }
a8ef67a8 949 ctx.fill();
85ff97a2 950 ctx.stroke();
78e58af4
RK
951}
952
5879307d
RK
953Dygraph.shapeFunction_ = function(sides, rotationRadians, delta) {
954 return function(g, name, ctx, cx, cy, color, radius) {
5879307d 955 ctx.strokeStyle = color;
a8ef67a8 956 ctx.fillStyle = "white";
5879307d
RK
957 Dygraph.regularShape_(ctx, sides, radius, cx, cy, rotationRadians, delta);
958 };
959};
960
961Dygraph.DrawPolygon_ = function(sides, rotationRadians, ctx, cx, cy, color, radius, delta) {
962 new Dygraph.RegularShape_(sides, rotationRadians, delta).draw(ctx, cx, cy, radius);
78e58af4
RK
963}
964
965Dygraph.Circles = {
966 DEFAULT : function(g, name, ctx, canvasx, canvasy, color, radius) {
967 ctx.beginPath();
968 ctx.fillStyle = color;
969 ctx.arc(canvasx, canvasy, radius, 0, 2 * Math.PI, false);
970 ctx.fill();
971 },
5879307d
RK
972 TRIANGLE : Dygraph.shapeFunction_(3),
973 SQUARE : Dygraph.shapeFunction_(4, Math.PI / 4),
974 DIAMOND : Dygraph.shapeFunction_(4),
975 PENTAGON : Dygraph.shapeFunction_(5),
976 HEXAGON : Dygraph.shapeFunction_(6),
78e58af4
RK
977 CIRCLE : function(g, name, ctx, cx, cy, color, radius) {
978 ctx.beginPath();
4ab51f75 979 ctx.strokeStyle = color;
a8ef67a8 980 ctx.fillStyle = "white";
78e58af4 981 ctx.arc(cx, cy, radius, 0, 2 * Math.PI, false);
a8ef67a8 982 ctx.fill();
85ff97a2 983 ctx.stroke();
78e58af4 984 },
5879307d 985 STAR : Dygraph.shapeFunction_(5, 0, 4 * Math.PI / 5),
240c0b11 986 PLUS : function(g, name, ctx, cx, cy, color, radius) {
240c0b11
RK
987 ctx.strokeStyle = color;
988
989 ctx.beginPath();
990 ctx.moveTo(cx + radius, cy);
991 ctx.lineTo(cx - radius, cy);
a8ef67a8 992 ctx.closePath();
85ff97a2 993 ctx.stroke();
240c0b11
RK
994
995 ctx.beginPath();
996 ctx.moveTo(cx, cy + radius);
997 ctx.lineTo(cx, cy - radius);
a8ef67a8 998 ctx.closePath();
85ff97a2 999 ctx.stroke();
240c0b11
RK
1000 },
1001 EX : function(g, name, ctx, cx, cy, color, radius) {
a8ef67a8 1002 ctx.strokeStyle = color;
240c0b11
RK
1003
1004 ctx.beginPath();
1005 ctx.moveTo(cx + radius, cy + radius);
1006 ctx.lineTo(cx - radius, cy - radius);
1007 ctx.closePath();
1008 ctx.stroke();
1009
1010 ctx.beginPath();
1011 ctx.moveTo(cx + radius, cy - radius);
1012 ctx.lineTo(cx - radius, cy + radius);
1013 ctx.closePath();
240c0b11 1014 ctx.stroke();
78e58af4 1015 }
78e58af4 1016};