allow lint.sh to take a file as a command-line argument
[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') {
df21c270
DV
54 try {
55 // Remove uninteresting bits: logging functions and paths.
56 st = printStackTrace({guess:false});
57 while (st[0].indexOf("stacktrace") != -1) {
58 st.splice(0, 1);
59 }
0d319fa5 60
df21c270
DV
61 st.splice(0, 2);
62 for (var i = 0; i < st.length; i++) {
63 st[i] = st[i].replace(/\([^)]*\/(.*)\)/, '@$1')
64 .replace(/\@.*\/([^\/]*)/, '@$1')
65 .replace('[object Object].', '');
66 }
67 var top_msg = st.splice(0, 1)[0];
68 message += ' (' + top_msg.replace(/^.*@ ?/, '') + ')';
69 } catch(e) {
70 // Oh well, it was worth a shot!
00639fab 71 }
00639fab
DV
72 }
73
dedb4f5f
DV
74 if (typeof(console) != 'undefined') {
75 switch (severity) {
76 case Dygraph.DEBUG:
77 console.debug('dygraphs: ' + message);
78 break;
79 case Dygraph.INFO:
80 console.info('dygraphs: ' + message);
81 break;
82 case Dygraph.WARNING:
83 console.warn('dygraphs: ' + message);
84 break;
85 case Dygraph.ERROR:
86 console.error('dygraphs: ' + message);
87 break;
88 }
89 }
00639fab
DV
90
91 if (Dygraph.LOG_STACK_TRACES) {
92 console.log(st.join('\n'));
93 }
dedb4f5f
DV
94};
95
96/** @private */
97Dygraph.info = function(message) {
98 Dygraph.log(Dygraph.INFO, message);
99};
100/** @private */
101Dygraph.prototype.info = Dygraph.info;
102
103/** @private */
104Dygraph.warn = function(message) {
105 Dygraph.log(Dygraph.WARNING, message);
106};
107/** @private */
108Dygraph.prototype.warn = Dygraph.warn;
109
110/** @private */
111Dygraph.error = function(message) {
112 Dygraph.log(Dygraph.ERROR, message);
113};
114/** @private */
115Dygraph.prototype.error = Dygraph.error;
116
117/**
118 * @private
119 * Return the 2d context for a dygraph canvas.
120 *
121 * This method is only exposed for the sake of replacing the function in
122 * automated tests, e.g.
123 *
124 * var oldFunc = Dygraph.getContext();
125 * Dygraph.getContext = function(canvas) {
126 * var realContext = oldFunc(canvas);
127 * return new Proxy(realContext);
128 * };
129 */
130Dygraph.getContext = function(canvas) {
131 return canvas.getContext("2d");
132};
133
134/**
135 * @private
136 * Add an event handler. This smooths a difference between IE and the rest of
137 * the world.
ccd9d7c2
PF
138 * @param { DOM element } elem The element to add the event to.
139 * @param { String } type The type of the event, e.g. 'click' or 'mousemove'.
dedb4f5f
DV
140 * @param { Function } fn The function to call on the event. The function takes
141 * one parameter: the event object.
142 */
1cc3540b 143Dygraph.addEvent = function addEvent(elem, type, fn) {
ccd9d7c2
PF
144 if (elem.addEventListener) {
145 elem.addEventListener(type, fn, false);
146 } else {
147 elem[type+fn] = function(){fn(window.event);};
148 elem.attachEvent('on'+type, elem[type+fn]);
149 }
1cc3540b
RK
150};
151
152/**
153 * @private
154 * Add an event handler. This event handler is kept until the graph is
155 * destroyed with a call to graph.destroy().
156 *
157 * @param { DOM element } elem The element to add the event to.
158 * @param { String } type The type of the event, e.g. 'click' or 'mousemove'.
159 * @param { Function } fn The function to call on the event. The function takes
160 * one parameter: the event object.
161 */
162Dygraph.prototype.addEvent = function addEvent(elem, type, fn) {
163 Dygraph.addEvent(elem, type, fn);
6a4587ac 164 this.registeredEvents_.push({ elem : elem, type : type, fn : fn });
ccd9d7c2
PF
165};
166
167/**
168 * @private
169 * Remove an event handler. This smooths a difference between IE and the rest of
170 * the world.
171 * @param { DOM element } elem The element to add the event to.
172 * @param { String } type The type of the event, e.g. 'click' or 'mousemove'.
173 * @param { Function } fn The function to call on the event. The function takes
174 * one parameter: the event object.
175 */
1cc3540b 176Dygraph.removeEvent = function addEvent(elem, type, fn) {
ccd9d7c2
PF
177 if (elem.removeEventListener) {
178 elem.removeEventListener(type, fn, false);
179 } else {
180 elem.detachEvent('on'+type, elem[type+fn]);
181 elem[type+fn] = null;
dedb4f5f
DV
182 }
183};
184
185/**
186 * @private
187 * Cancels further processing of an event. This is useful to prevent default
188 * browser actions, e.g. highlighting text on a double-click.
189 * Based on the article at
190 * http://www.switchonthecode.com/tutorials/javascript-tutorial-the-scroll-wheel
191 * @param { Event } e The event whose normal behavior should be canceled.
192 */
193Dygraph.cancelEvent = function(e) {
194 e = e ? e : window.event;
195 if (e.stopPropagation) {
196 e.stopPropagation();
197 }
198 if (e.preventDefault) {
199 e.preventDefault();
200 }
201 e.cancelBubble = true;
202 e.cancel = true;
203 e.returnValue = false;
204 return false;
205};
206
207/**
208 * Convert hsv values to an rgb(r,g,b) string. Taken from MochiKit.Color. This
209 * is used to generate default series colors which are evenly spaced on the
210 * color wheel.
211 * @param { Number } hue Range is 0.0-1.0.
212 * @param { Number } saturation Range is 0.0-1.0.
213 * @param { Number } value Range is 0.0-1.0.
214 * @return { String } "rgb(r,g,b)" where r, g and b range from 0-255.
215 * @private
216 */
217Dygraph.hsvToRGB = function (hue, saturation, value) {
218 var red;
219 var green;
220 var blue;
221 if (saturation === 0) {
222 red = value;
223 green = value;
224 blue = value;
225 } else {
226 var i = Math.floor(hue * 6);
227 var f = (hue * 6) - i;
228 var p = value * (1 - saturation);
229 var q = value * (1 - (saturation * f));
230 var t = value * (1 - (saturation * (1 - f)));
231 switch (i) {
232 case 1: red = q; green = value; blue = p; break;
233 case 2: red = p; green = value; blue = t; break;
234 case 3: red = p; green = q; blue = value; break;
235 case 4: red = t; green = p; blue = value; break;
236 case 5: red = value; green = p; blue = q; break;
237 case 6: // fall through
238 case 0: red = value; green = t; blue = p; break;
239 }
240 }
241 red = Math.floor(255 * red + 0.5);
242 green = Math.floor(255 * green + 0.5);
243 blue = Math.floor(255 * blue + 0.5);
244 return 'rgb(' + red + ',' + green + ',' + blue + ')';
245};
246
247// The following functions are from quirksmode.org with a modification for Safari from
248// http://blog.firetree.net/2005/07/04/javascript-find-position/
249// http://www.quirksmode.org/js/findpos.html
1bc38cbc 250// ... and modifications to support scrolling divs.
dedb4f5f 251
8442269f
RK
252/**
253 * Find the x-coordinate of the supplied object relative to the left side
254 * of the page.
255 * @private
256 */
dedb4f5f
DV
257Dygraph.findPosX = function(obj) {
258 var curleft = 0;
8442269f
RK
259 if(obj.offsetParent) {
260 var copyObj = obj;
261 while(1) {
262 curleft += copyObj.offsetLeft;
263 if(!copyObj.offsetParent) {
dedb4f5f 264 break;
8442269f
RK
265 }
266 copyObj = copyObj.offsetParent;
dedb4f5f 267 }
8442269f 268 } else if(obj.x) {
dedb4f5f 269 curleft += obj.x;
8442269f
RK
270 }
271 // This handles the case where the object is inside a scrolled div.
272 while(obj && obj != document.body) {
273 curleft -= obj.scrollLeft;
274 obj = obj.parentNode;
275 }
dedb4f5f
DV
276 return curleft;
277};
278
8442269f
RK
279/**
280 * Find the y-coordinate of the supplied object relative to the top of the
281 * page.
282 * @private
283 */
dedb4f5f
DV
284Dygraph.findPosY = function(obj) {
285 var curtop = 0;
8442269f
RK
286 if(obj.offsetParent) {
287 var copyObj = obj;
288 while(1) {
289 curtop += copyObj.offsetTop;
290 if(!copyObj.offsetParent) {
dedb4f5f 291 break;
8442269f
RK
292 }
293 copyObj = copyObj.offsetParent;
dedb4f5f 294 }
8442269f 295 } else if(obj.y) {
dedb4f5f 296 curtop += obj.y;
8442269f
RK
297 }
298 // This handles the case where the object is inside a scrolled div.
299 while(obj && obj != document.body) {
300 curtop -= obj.scrollTop;
301 obj = obj.parentNode;
302 }
dedb4f5f
DV
303 return curtop;
304};
305
306/**
307 * @private
308 * Returns the x-coordinate of the event in a coordinate system where the
309 * top-left corner of the page (not the window) is (0,0).
310 * Taken from MochiKit.Signal
311 */
312Dygraph.pageX = function(e) {
313 if (e.pageX) {
314 return (!e.pageX || e.pageX < 0) ? 0 : e.pageX;
315 } else {
316 var de = document;
317 var b = document.body;
318 return e.clientX +
319 (de.scrollLeft || b.scrollLeft) -
320 (de.clientLeft || 0);
321 }
322};
323
324/**
325 * @private
326 * Returns the y-coordinate of the event in a coordinate system where the
327 * top-left corner of the page (not the window) is (0,0).
328 * Taken from MochiKit.Signal
329 */
330Dygraph.pageY = function(e) {
331 if (e.pageY) {
332 return (!e.pageY || e.pageY < 0) ? 0 : e.pageY;
333 } else {
334 var de = document;
335 var b = document.body;
336 return e.clientY +
337 (de.scrollTop || b.scrollTop) -
338 (de.clientTop || 0);
339 }
340};
341
342/**
343 * @private
344 * @param { Number } x The number to consider.
345 * @return { Boolean } Whether the number is zero or NaN.
346 */
347// TODO(danvk): rename this function to something like 'isNonZeroNan'.
758a629f 348// TODO(danvk): determine when else this returns false (e.g. for undefined or null)
dedb4f5f
DV
349Dygraph.isOK = function(x) {
350 return x && !isNaN(x);
351};
352
353/**
62c3d2fd
KW
354 * @private
355 * @param { Object } p The point to consider, valid points are {x, y} objects
04c104d7 356 * @param { Boolean } allowNaNY Treat point with y=NaN as valid
62c3d2fd
KW
357 * @return { Boolean } Whether the point has numeric x and y.
358 */
04c104d7 359Dygraph.isValidPoint = function(p, allowNaNY) {
62c3d2fd 360 if (!p) return false; // null or undefined object
04c104d7
KW
361 if (p.yval === null) return false; // missing point
362 if (p.x === null || p.x === undefined) return false;
363 if (p.y === null || p.y === undefined) return false;
364 if (isNaN(p.x) || (!allowNaNY && isNaN(p.y))) return false;
62c3d2fd
KW
365 return true;
366};
367
368/**
dedb4f5f
DV
369 * Number formatting function which mimicks the behavior of %g in printf, i.e.
370 * either exponential or fixed format (without trailing 0s) is used depending on
371 * the length of the generated string. The advantage of this format is that
372 * there is a predictable upper bound on the resulting string length,
373 * significant figures are not dropped, and normal numbers are not displayed in
374 * exponential notation.
375 *
376 * NOTE: JavaScript's native toPrecision() is NOT a drop-in replacement for %g.
377 * It creates strings which are too long for absolute values between 10^-4 and
378 * 10^-6, e.g. '0.00001' instead of '1e-5'. See tests/number-format.html for
379 * output examples.
380 *
381 * @param {Number} x The number to format
382 * @param {Number} opt_precision The precision to use, default 2.
383 * @return {String} A string formatted like %g in printf. The max generated
384 * string length should be precision + 6 (e.g 1.123e+300).
385 */
386Dygraph.floatFormat = function(x, opt_precision) {
387 // Avoid invalid precision values; [1, 21] is the valid range.
388 var p = Math.min(Math.max(1, opt_precision || 2), 21);
389
390 // This is deceptively simple. The actual algorithm comes from:
391 //
392 // Max allowed length = p + 4
393 // where 4 comes from 'e+n' and '.'.
394 //
395 // Length of fixed format = 2 + y + p
396 // where 2 comes from '0.' and y = # of leading zeroes.
397 //
398 // Equating the two and solving for y yields y = 2, or 0.00xxxx which is
399 // 1.0e-3.
400 //
401 // Since the behavior of toPrecision() is identical for larger numbers, we
402 // don't have to worry about the other bound.
403 //
404 // Finally, the argument for toExponential() is the number of trailing digits,
405 // so we take off 1 for the value before the '.'.
758a629f 406 return (Math.abs(x) < 1.0e-3 && x !== 0.0) ?
dedb4f5f
DV
407 x.toExponential(p - 1) : x.toPrecision(p);
408};
409
410/**
411 * @private
412 * Converts '9' to '09' (useful for dates)
413 */
414Dygraph.zeropad = function(x) {
415 if (x < 10) return "0" + x; else return "" + x;
416};
417
418/**
419 * Return a string version of the hours, minutes and seconds portion of a date.
420 * @param {Number} date The JavaScript date (ms since epoch)
421 * @return {String} A time of the form "HH:MM:SS"
422 * @private
423 */
424Dygraph.hmsString_ = function(date) {
425 var zeropad = Dygraph.zeropad;
426 var d = new Date(date);
427 if (d.getSeconds()) {
428 return zeropad(d.getHours()) + ":" +
429 zeropad(d.getMinutes()) + ":" +
430 zeropad(d.getSeconds());
431 } else {
432 return zeropad(d.getHours()) + ":" + zeropad(d.getMinutes());
433 }
434};
435
436/**
dedb4f5f
DV
437 * Round a number to the specified number of digits past the decimal point.
438 * @param {Number} num The number to round
439 * @param {Number} places The number of decimals to which to round
440 * @return {Number} The rounded number
441 * @private
442 */
443Dygraph.round_ = function(num, places) {
444 var shift = Math.pow(10, places);
445 return Math.round(num * shift)/shift;
446};
447
448/**
449 * @private
450 * Implementation of binary search over an array.
451 * Currently does not work when val is outside the range of arry's values.
452 * @param { Integer } val the value to search for
453 * @param { Integer[] } arry is the value over which to search
454 * @param { Integer } abs If abs > 0, find the lowest entry greater than val
455 * If abs < 0, find the highest entry less than val.
456 * if abs == 0, find the entry that equals val.
457 * @param { Integer } [low] The first index in arry to consider (optional)
458 * @param { Integer } [high] The last index in arry to consider (optional)
459 */
460Dygraph.binarySearch = function(val, arry, abs, low, high) {
758a629f
DV
461 if (low === null || low === undefined ||
462 high === null || high === undefined) {
dedb4f5f
DV
463 low = 0;
464 high = arry.length - 1;
465 }
466 if (low > high) {
467 return -1;
468 }
758a629f 469 if (abs === null || abs === undefined) {
dedb4f5f
DV
470 abs = 0;
471 }
472 var validIndex = function(idx) {
473 return idx >= 0 && idx < arry.length;
758a629f
DV
474 };
475 var mid = parseInt((low + high) / 2, 10);
dedb4f5f
DV
476 var element = arry[mid];
477 if (element == val) {
478 return mid;
479 }
758a629f
DV
480
481 var idx;
dedb4f5f
DV
482 if (element > val) {
483 if (abs > 0) {
484 // Accept if element > val, but also if prior element < val.
758a629f 485 idx = mid - 1;
dedb4f5f
DV
486 if (validIndex(idx) && arry[idx] < val) {
487 return mid;
488 }
489 }
490 return Dygraph.binarySearch(val, arry, abs, low, mid - 1);
491 }
492 if (element < val) {
493 if (abs < 0) {
494 // Accept if element < val, but also if prior element > val.
758a629f 495 idx = mid + 1;
dedb4f5f
DV
496 if (validIndex(idx) && arry[idx] > val) {
497 return mid;
498 }
499 }
500 return Dygraph.binarySearch(val, arry, abs, mid + 1, high);
501 }
502};
503
504/**
505 * @private
506 * Parses a date, returning the number of milliseconds since epoch. This can be
507 * passed in as an xValueParser in the Dygraph constructor.
508 * TODO(danvk): enumerate formats that this understands.
509 * @param {String} A date in YYYYMMDD format.
510 * @return {Number} Milliseconds since epoch.
511 */
512Dygraph.dateParser = function(dateStr) {
513 var dateStrSlashed;
514 var d;
769e8bc7 515
3f675fe5
DV
516 // Let the system try the format first, with one caveat:
517 // YYYY-MM-DD[ HH:MM:SS] is interpreted as UTC by a variety of browsers.
518 // dygraphs displays dates in local time, so this will result in surprising
519 // inconsistencies. But if you specify "T" or "Z" (i.e. YYYY-MM-DDTHH:MM:SS),
520 // then you probably know what you're doing, so we'll let you go ahead.
521 // Issue: http://code.google.com/p/dygraphs/issues/detail?id=255
522 if (dateStr.search("-") == -1 ||
523 dateStr.search("T") != -1 || dateStr.search("Z") != -1) {
524 d = Dygraph.dateStrToMillis(dateStr);
525 if (d && !isNaN(d)) return d;
526 }
769e8bc7 527
dedb4f5f
DV
528 if (dateStr.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12'
529 dateStrSlashed = dateStr.replace("-", "/", "g");
530 while (dateStrSlashed.search("-") != -1) {
531 dateStrSlashed = dateStrSlashed.replace("-", "/");
532 }
533 d = Dygraph.dateStrToMillis(dateStrSlashed);
534 } else if (dateStr.length == 8) { // e.g. '20090712'
535 // TODO(danvk): remove support for this format. It's confusing.
758a629f
DV
536 dateStrSlashed = dateStr.substr(0,4) + "/" + dateStr.substr(4,2) + "/" +
537 dateStr.substr(6,2);
dedb4f5f
DV
538 d = Dygraph.dateStrToMillis(dateStrSlashed);
539 } else {
540 // Any format that Date.parse will accept, e.g. "2009/07/12" or
541 // "2009/07/12 12:34:56"
542 d = Dygraph.dateStrToMillis(dateStr);
543 }
544
545 if (!d || isNaN(d)) {
546 Dygraph.error("Couldn't parse " + dateStr + " as a date");
547 }
548 return d;
549};
550
551/**
552 * @private
553 * This is identical to JavaScript's built-in Date.parse() method, except that
554 * it doesn't get replaced with an incompatible method by aggressive JS
555 * libraries like MooTools or Joomla.
556 * @param { String } str The date string, e.g. "2011/05/06"
557 * @return { Integer } millis since epoch
558 */
559Dygraph.dateStrToMillis = function(str) {
560 return new Date(str).getTime();
561};
562
563// These functions are all based on MochiKit.
564/**
565 * Copies all the properties from o to self.
566 *
567 * @private
568 */
569Dygraph.update = function (self, o) {
570 if (typeof(o) != 'undefined' && o !== null) {
571 for (var k in o) {
572 if (o.hasOwnProperty(k)) {
573 self[k] = o[k];
574 }
575 }
576 }
577 return self;
578};
579
580/**
48e614ac
DV
581 * Copies all the properties from o to self.
582 *
583 * @private
584 */
585Dygraph.updateDeep = function (self, o) {
920208fb
PF
586 // Taken from http://stackoverflow.com/questions/384286/javascript-isdom-how-do-you-check-if-a-javascript-object-is-a-dom-object
587 function isNode(o) {
588 return (
589 typeof Node === "object" ? o instanceof Node :
590 typeof o === "object" && typeof o.nodeType === "number" && typeof o.nodeName==="string"
591 );
592 }
593
48e614ac
DV
594 if (typeof(o) != 'undefined' && o !== null) {
595 for (var k in o) {
596 if (o.hasOwnProperty(k)) {
758a629f 597 if (o[k] === null) {
48e614ac
DV
598 self[k] = null;
599 } else if (Dygraph.isArrayLike(o[k])) {
600 self[k] = o[k].slice();
920208fb 601 } else if (isNode(o[k])) {
66ad3609
RK
602 // DOM objects are shallowly-copied.
603 self[k] = o[k];
48e614ac 604 } else if (typeof(o[k]) == 'object') {
c1c5dfeb 605 if (typeof(self[k]) != 'object' || self[k] === null) {
48e614ac
DV
606 self[k] = {};
607 }
608 Dygraph.updateDeep(self[k], o[k]);
609 } else {
610 self[k] = o[k];
611 }
612 }
613 }
614 }
615 return self;
616};
617
618/**
dedb4f5f
DV
619 * @private
620 */
621Dygraph.isArrayLike = function (o) {
622 var typ = typeof(o);
623 if (
624 (typ != 'object' && !(typ == 'function' &&
625 typeof(o.item) == 'function')) ||
626 o === null ||
627 typeof(o.length) != 'number' ||
628 o.nodeType === 3
629 ) {
630 return false;
631 }
632 return true;
633};
634
635/**
636 * @private
637 */
638Dygraph.isDateLike = function (o) {
639 if (typeof(o) != "object" || o === null ||
640 typeof(o.getTime) != 'function') {
641 return false;
642 }
643 return true;
644};
645
646/**
48e614ac 647 * Note: this only seems to work for arrays.
dedb4f5f
DV
648 * @private
649 */
650Dygraph.clone = function(o) {
651 // TODO(danvk): figure out how MochiKit's version works
652 var r = [];
653 for (var i = 0; i < o.length; i++) {
654 if (Dygraph.isArrayLike(o[i])) {
655 r.push(Dygraph.clone(o[i]));
656 } else {
657 r.push(o[i]);
658 }
659 }
660 return r;
661};
662
663/**
664 * @private
665 * Create a new canvas element. This is more complex than a simple
666 * document.createElement("canvas") because of IE and excanvas.
667 */
668Dygraph.createCanvas = function() {
669 var canvas = document.createElement("canvas");
670
c0f54d4f 671 var isIE = (/MSIE/.test(navigator.userAgent) && !window.opera);
dedb4f5f
DV
672 if (isIE && (typeof(G_vmlCanvasManager) != 'undefined')) {
673 canvas = G_vmlCanvasManager.initElement(canvas);
674 }
675
676 return canvas;
677};
9ca829f2
DV
678
679/**
680 * @private
971870e5
DV
681 * Checks whether the user is on an Android browser.
682 * Android does not fully support the <canvas> tag, e.g. w/r/t/ clipping.
683 */
684Dygraph.isAndroid = function() {
758a629f 685 return (/Android/).test(navigator.userAgent);
971870e5
DV
686};
687
a26206cf
RK
688Dygraph.Iterator = function(array, start, length, predicate) {
689 start = start || 0;
690 length = length || array.length;
ff1074cd
RK
691 this.hasNext = true; // Use to identify if there's another element.
692 this.peek = null; // Use for look-ahead
0f20de1c 693 this.start_ = start;
a26206cf
RK
694 this.array_ = array;
695 this.predicate_ = predicate;
696 this.end_ = Math.min(array.length, start + length);
ff1074cd
RK
697 this.nextIdx_ = start - 1; // use -1 so initial advance works.
698 this.next(); // ignoring result.
a26206cf
RK
699}
700
701Dygraph.Iterator.prototype.next = function() {
ff1074cd
RK
702 if (!this.hasNext) {
703 return null;
a26206cf 704 }
ff1074cd 705 var obj = this.peek;
a26206cf 706
ff1074cd
RK
707 var nextIdx = this.nextIdx_ + 1;
708 var found = false;
709 while (nextIdx < this.end_) {
a26206cf 710 if (!this.predicate_ || this.predicate_(this.array_, nextIdx)) {
ff1074cd
RK
711 this.peek = this.array_[nextIdx];
712 found = true;
713 break;
a26206cf
RK
714 }
715 nextIdx++;
716 }
717 this.nextIdx_ = nextIdx;
ff1074cd
RK
718 if (!found) {
719 this.hasNext = false;
720 this.peek = null;
721 }
722 return obj;
a26206cf
RK
723}
724
971870e5
DV
725/**
726 * @private
7d1afbb9
RK
727 * Returns a new iterator over array, between indexes start and
728 * start + length, and only returns entries that pass the accept function
729 *
730 * @param array the array to iterate over.
a26206cf 731 * @param start the first index to iterate over, 0 if absent.
7d1afbb9
RK
732 * @param length the number of elements in the array to iterate over.
733 * This, along with start, defines a slice of the array, and so length
734 * doesn't imply the number of elements in the iterator when accept
a26206cf 735 * doesn't always accept all values. array.length when absent.
7d1afbb9
RK
736 * @param predicate a function that takes parameters array and idx, which
737 * returns true when the element should be returned. If omitted, all
738 * elements are accepted.
7d1afbb9
RK
739 */
740Dygraph.createIterator = function(array, start, length, predicate) {
a26206cf 741 return new Dygraph.Iterator(array, start, length, predicate);
7d1afbb9
RK
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};