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