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