Add missing_points.js to the bunch (as part of prior move .. oooops)
[dygraphs.git] / dygraph-utils.js
... / ...
CommitLineData
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
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;
24};
25
26// Various logging levels.
27Dygraph.DEBUG = 1;
28Dygraph.INFO = 2;
29Dygraph.WARNING = 3;
30Dygraph.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
36Dygraph.LOG_STACK_TRACES = false;
37
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
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) {
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 */
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.
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 */
139Dygraph.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};
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);
160 this.registeredEvents_.push({ elem : elem, type : type, fn : fn });
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 */
172Dygraph.removeEvent = function addEvent(elem, type, fn) {
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;
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
246// ... and modifications to support scrolling divs.
247
248/**
249 * Find the x-coordinate of the supplied object relative to the left side
250 * of the page.
251 * @private
252 */
253Dygraph.findPosX = function(obj) {
254 var curleft = 0;
255 if(obj.offsetParent) {
256 var copyObj = obj;
257 while(1) {
258 curleft += copyObj.offsetLeft;
259 if(!copyObj.offsetParent) {
260 break;
261 }
262 copyObj = copyObj.offsetParent;
263 }
264 } else if(obj.x) {
265 curleft += obj.x;
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 }
272 return curleft;
273};
274
275/**
276 * Find the y-coordinate of the supplied object relative to the top of the
277 * page.
278 * @private
279 */
280Dygraph.findPosY = function(obj) {
281 var curtop = 0;
282 if(obj.offsetParent) {
283 var copyObj = obj;
284 while(1) {
285 curtop += copyObj.offsetTop;
286 if(!copyObj.offsetParent) {
287 break;
288 }
289 copyObj = copyObj.offsetParent;
290 }
291 } else if(obj.y) {
292 curtop += obj.y;
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 }
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'.
344// TODO(danvk): determine when else this returns false (e.g. for undefined or null)
345Dygraph.isOK = function(x) {
346 return x && !isNaN(x);
347};
348
349/**
350 * @private
351 * @param { Object } p The point to consider, valid points are {x, y} objects
352 * @param { Boolean } allowNaNY Treat point with y=NaN as valid
353 * @return { Boolean } Whether the point has numeric x and y.
354 */
355Dygraph.isValidPoint = function(p, allowNaNY) {
356 if (!p) return false; // null or undefined object
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;
361 return true;
362};
363
364/**
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 '.'.
402 return (Math.abs(x) < 1.0e-3 && x !== 0.0) ?
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/**
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) {
457 if (low === null || low === undefined ||
458 high === null || high === undefined) {
459 low = 0;
460 high = arry.length - 1;
461 }
462 if (low > high) {
463 return -1;
464 }
465 if (abs === null || abs === undefined) {
466 abs = 0;
467 }
468 var validIndex = function(idx) {
469 return idx >= 0 && idx < arry.length;
470 };
471 var mid = parseInt((low + high) / 2, 10);
472 var element = arry[mid];
473 if (element == val) {
474 return mid;
475 }
476
477 var idx;
478 if (element > val) {
479 if (abs > 0) {
480 // Accept if element > val, but also if prior element < val.
481 idx = mid - 1;
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.
491 idx = mid + 1;
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;
511
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 }
523
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.
532 dateStrSlashed = dateStr.substr(0,4) + "/" + dateStr.substr(4,2) + "/" +
533 dateStr.substr(6,2);
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/**
577 * Copies all the properties from o to self.
578 *
579 * @private
580 */
581Dygraph.updateDeep = function (self, o) {
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
590 if (typeof(o) != 'undefined' && o !== null) {
591 for (var k in o) {
592 if (o.hasOwnProperty(k)) {
593 if (o[k] === null) {
594 self[k] = null;
595 } else if (Dygraph.isArrayLike(o[k])) {
596 self[k] = o[k].slice();
597 } else if (isNode(o[k])) {
598 // DOM objects are shallowly-copied.
599 self[k] = o[k];
600 } else if (typeof(o[k]) == 'object') {
601 if (typeof(self[k]) != 'object' || self[k] === null) {
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/**
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/**
643 * Note: this only seems to work for arrays.
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
667 var isIE = (/MSIE/.test(navigator.userAgent) && !window.opera);
668 if (isIE && (typeof(G_vmlCanvasManager) != 'undefined')) {
669 canvas = G_vmlCanvasManager.initElement(canvas);
670 }
671
672 return canvas;
673};
674
675/**
676 * @private
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() {
681 return (/Android/).test(navigator.userAgent);
682};
683
684/**
685 * @private
686 * Call a function N times at a given interval, then call a cleanup function
687 * once. repeat_fn is called once immediately, then (times - 1) times
688 * asynchronously. If times=1, then cleanup_fn() is also called synchronously.
689 * @param repeat_fn {Function} Called repeatedly -- takes the number of calls
690 * (from 0 to times-1) as an argument.
691 * @param times {number} The number of times to call repeat_fn
692 * @param every_ms {number} Milliseconds between calls
693 * @param cleanup_fn {Function} A function to call after all repeat_fn calls.
694 * @private
695 */
696Dygraph.repeatAndCleanup = function(repeat_fn, times, every_ms, cleanup_fn) {
697 var count = 0;
698 var start_time = new Date().getTime();
699 repeat_fn(count);
700 if (times == 1) {
701 cleanup_fn();
702 return;
703 }
704
705 (function loop() {
706 if (count >= times) return;
707 var target_time = start_time + (1 + count) * every_ms;
708 setTimeout(function() {
709 count++;
710 repeat_fn(count);
711 if (count >= times - 1) {
712 cleanup_fn();
713 } else {
714 loop();
715 }
716 }, target_time - new Date().getTime());
717 // TODO(danvk): adjust every_ms to produce evenly-timed function calls.
718 })();
719};
720
721/**
722 * @private
723 * This function will scan the option list and determine if they
724 * require us to recalculate the pixel positions of each point.
725 * @param { List } a list of options to check.
726 * @return { Boolean } true if the graph needs new points else false.
727 */
728Dygraph.isPixelChangingOptionList = function(labels, attrs) {
729 // A whitelist of options that do not change pixel positions.
730 var pixelSafeOptions = {
731 'annotationClickHandler': true,
732 'annotationDblClickHandler': true,
733 'annotationMouseOutHandler': true,
734 'annotationMouseOverHandler': true,
735 'axisLabelColor': true,
736 'axisLineColor': true,
737 'axisLineWidth': true,
738 'clickCallback': true,
739 'digitsAfterDecimal': true,
740 'drawCallback': true,
741 'drawHighlightPointCallback': true,
742 'drawPoints': true,
743 'drawPointCallback': true,
744 'drawXGrid': true,
745 'drawYGrid': true,
746 'fillAlpha': true,
747 'gridLineColor': true,
748 'gridLineWidth': true,
749 'hideOverlayOnMouseOut': true,
750 'highlightCallback': true,
751 'highlightCircleSize': true,
752 'interactionModel': true,
753 'isZoomedIgnoreProgrammaticZoom': true,
754 'labelsDiv': true,
755 'labelsDivStyles': true,
756 'labelsDivWidth': true,
757 'labelsKMB': true,
758 'labelsKMG2': true,
759 'labelsSeparateLines': true,
760 'labelsShowZeroValues': true,
761 'legend': true,
762 'maxNumberWidth': true,
763 'panEdgeFraction': true,
764 'pixelsPerYLabel': true,
765 'pointClickCallback': true,
766 'pointSize': true,
767 'rangeSelectorPlotFillColor': true,
768 'rangeSelectorPlotStrokeColor': true,
769 'showLabelsOnHighlight': true,
770 'showRoller': true,
771 'sigFigs': true,
772 'strokeWidth': true,
773 'underlayCallback': true,
774 'unhighlightCallback': true,
775 'xAxisLabelFormatter': true,
776 'xTicker': true,
777 'xValueFormatter': true,
778 'yAxisLabelFormatter': true,
779 'yValueFormatter': true,
780 'zoomCallback': true
781 };
782
783 // Assume that we do not require new points.
784 // This will change to true if we actually do need new points.
785 var requiresNewPoints = false;
786
787 // Create a dictionary of series names for faster lookup.
788 // If there are no labels, then the dictionary stays empty.
789 var seriesNamesDictionary = { };
790 if (labels) {
791 for (var i = 1; i < labels.length; i++) {
792 seriesNamesDictionary[labels[i]] = true;
793 }
794 }
795
796 // Iterate through the list of updated options.
797 for (var property in attrs) {
798 // Break early if we already know we need new points from a previous option.
799 if (requiresNewPoints) {
800 break;
801 }
802 if (attrs.hasOwnProperty(property)) {
803 // Find out of this field is actually a series specific options list.
804 if (seriesNamesDictionary[property]) {
805 // This property value is a list of options for this series.
806 // If any of these sub properties are not pixel safe, set the flag.
807 for (var subProperty in attrs[property]) {
808 // Break early if we already know we need new points from a previous option.
809 if (requiresNewPoints) {
810 break;
811 }
812 if (attrs[property].hasOwnProperty(subProperty) && !pixelSafeOptions[subProperty]) {
813 requiresNewPoints = true;
814 }
815 }
816 // If this was not a series specific option list, check if its a pixel changing property.
817 } else if (!pixelSafeOptions[property]) {
818 requiresNewPoints = true;
819 }
820 }
821 }
822
823 return requiresNewPoints;
824};
825
826/**
827 * Compares two arrays to see if they are equal. If either parameter is not an
828 * array it will return false. Does a shallow compare
829 * Dygraph.compareArrays([[1,2], [3, 4]], [[1,2], [3,4]]) === false.
830 * @param array1 first array
831 * @param array2 second array
832 * @return True if both parameters are arrays, and contents are equal.
833 */
834Dygraph.compareArrays = function(array1, array2) {
835 if (!Dygraph.isArrayLike(array1) || !Dygraph.isArrayLike(array2)) {
836 return false;
837 }
838 if (array1.length !== array2.length) {
839 return false;
840 }
841 for (var i = 0; i < array1.length; i++) {
842 if (array1[i] !== array2[i]) {
843 return false;
844 }
845 }
846 return true;
847};
848
849/**
850 * ctx: the canvas context
851 * sides: the number of sides in the shape.
852 * radius: the radius of the image.
853 * cx: center x coordate
854 * cy: center y coordinate
855 * rotationRadians: the shift of the initial angle, in radians.
856 * delta: the angle shift for each line. If missing, creates a regular
857 * polygon.
858 */
859Dygraph.regularShape_ = function(
860 ctx, sides, radius, cx, cy, rotationRadians, delta) {
861 rotationRadians = rotationRadians ? rotationRadians : 0;
862 delta = delta ? delta : Math.PI * 2 / sides;
863
864 ctx.beginPath();
865 var first = true;
866 var initialAngle = rotationRadians;
867 var angle = initialAngle;
868
869 var computeCoordinates = function() {
870 var x = cx + (Math.sin(angle) * radius);
871 var y = cy + (-Math.cos(angle) * radius);
872 return [x, y];
873 };
874
875 var initialCoordinates = computeCoordinates();
876 var x = initialCoordinates[0];
877 var y = initialCoordinates[1];
878 ctx.moveTo(x, y);
879
880 for (var idx = 0; idx < sides; idx++) {
881 angle = (idx == sides - 1) ? initialAngle : (angle + delta);
882 var coords = computeCoordinates();
883 ctx.lineTo(coords[0], coords[1]);
884 }
885 ctx.fill();
886 ctx.stroke();
887}
888
889Dygraph.shapeFunction_ = function(sides, rotationRadians, delta) {
890 return function(g, name, ctx, cx, cy, color, radius) {
891 ctx.strokeStyle = color;
892 ctx.fillStyle = "white";
893 Dygraph.regularShape_(ctx, sides, radius, cx, cy, rotationRadians, delta);
894 };
895};
896
897Dygraph.DrawPolygon_ = function(sides, rotationRadians, ctx, cx, cy, color, radius, delta) {
898 new Dygraph.RegularShape_(sides, rotationRadians, delta).draw(ctx, cx, cy, radius);
899}
900
901Dygraph.Circles = {
902 DEFAULT : function(g, name, ctx, canvasx, canvasy, color, radius) {
903 ctx.beginPath();
904 ctx.fillStyle = color;
905 ctx.arc(canvasx, canvasy, radius, 0, 2 * Math.PI, false);
906 ctx.fill();
907 },
908 TRIANGLE : Dygraph.shapeFunction_(3),
909 SQUARE : Dygraph.shapeFunction_(4, Math.PI / 4),
910 DIAMOND : Dygraph.shapeFunction_(4),
911 PENTAGON : Dygraph.shapeFunction_(5),
912 HEXAGON : Dygraph.shapeFunction_(6),
913 CIRCLE : function(g, name, ctx, cx, cy, color, radius) {
914 ctx.beginPath();
915 ctx.strokeStyle = color;
916 ctx.fillStyle = "white";
917 ctx.arc(cx, cy, radius, 0, 2 * Math.PI, false);
918 ctx.fill();
919 ctx.stroke();
920 },
921 STAR : Dygraph.shapeFunction_(5, 0, 4 * Math.PI / 5),
922 PLUS : function(g, name, ctx, cx, cy, color, radius) {
923 ctx.strokeStyle = color;
924
925 ctx.beginPath();
926 ctx.moveTo(cx + radius, cy);
927 ctx.lineTo(cx - radius, cy);
928 ctx.closePath();
929 ctx.stroke();
930
931 ctx.beginPath();
932 ctx.moveTo(cx, cy + radius);
933 ctx.lineTo(cx, cy - radius);
934 ctx.closePath();
935 ctx.stroke();
936 },
937 EX : function(g, name, ctx, cx, cy, color, radius) {
938 ctx.strokeStyle = color;
939
940 ctx.beginPath();
941 ctx.moveTo(cx + radius, cy + radius);
942 ctx.lineTo(cx - radius, cy - radius);
943 ctx.closePath();
944 ctx.stroke();
945
946 ctx.beginPath();
947 ctx.moveTo(cx + radius, cy - radius);
948 ctx.lineTo(cx - radius, cy + radius);
949 ctx.closePath();
950 ctx.stroke();
951 }
952};