Merge pull request #136 from klausw-g/non-logscale-x
[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.
498 d = Dygraph.dateStrToMillis(dateStr);
499 if (d && !isNaN(d)) return d;
500
501 if (dateStr.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12'
502 dateStrSlashed = dateStr.replace("-", "/", "g");
503 while (dateStrSlashed.search("-") != -1) {
504 dateStrSlashed = dateStrSlashed.replace("-", "/");
505 }
506 d = Dygraph.dateStrToMillis(dateStrSlashed);
507 } else if (dateStr.length == 8) { // e.g. '20090712'
508 // TODO(danvk): remove support for this format. It's confusing.
509 dateStrSlashed = dateStr.substr(0,4) + "/" + dateStr.substr(4,2) + "/" +
510 dateStr.substr(6,2);
511 d = Dygraph.dateStrToMillis(dateStrSlashed);
512 } else {
513 // Any format that Date.parse will accept, e.g. "2009/07/12" or
514 // "2009/07/12 12:34:56"
515 d = Dygraph.dateStrToMillis(dateStr);
516 }
517
518 if (!d || isNaN(d)) {
519 Dygraph.error("Couldn't parse " + dateStr + " as a date");
520 }
521 return d;
522};
523
524/**
525 * @private
526 * This is identical to JavaScript's built-in Date.parse() method, except that
527 * it doesn't get replaced with an incompatible method by aggressive JS
528 * libraries like MooTools or Joomla.
529 * @param { String } str The date string, e.g. "2011/05/06"
530 * @return { Integer } millis since epoch
531 */
532Dygraph.dateStrToMillis = function(str) {
533 return new Date(str).getTime();
534};
535
536// These functions are all based on MochiKit.
537/**
538 * Copies all the properties from o to self.
539 *
540 * @private
541 */
542Dygraph.update = function (self, o) {
543 if (typeof(o) != 'undefined' && o !== null) {
544 for (var k in o) {
545 if (o.hasOwnProperty(k)) {
546 self[k] = o[k];
547 }
548 }
549 }
550 return self;
551};
552
553/**
554 * Copies all the properties from o to self.
555 *
556 * @private
557 */
558Dygraph.updateDeep = function (self, o) {
559 // Taken from http://stackoverflow.com/questions/384286/javascript-isdom-how-do-you-check-if-a-javascript-object-is-a-dom-object
560 function isNode(o) {
561 return (
562 typeof Node === "object" ? o instanceof Node :
563 typeof o === "object" && typeof o.nodeType === "number" && typeof o.nodeName==="string"
564 );
565 }
566
567 if (typeof(o) != 'undefined' && o !== null) {
568 for (var k in o) {
569 if (o.hasOwnProperty(k)) {
570 if (o[k] === null) {
571 self[k] = null;
572 } else if (Dygraph.isArrayLike(o[k])) {
573 self[k] = o[k].slice();
574 } else if (isNode(o[k])) {
575 // DOM objects are shallowly-copied.
576 self[k] = o[k];
577 } else if (typeof(o[k]) == 'object') {
578 if (typeof(self[k]) != 'object') {
579 self[k] = {};
580 }
581 Dygraph.updateDeep(self[k], o[k]);
582 } else {
583 self[k] = o[k];
584 }
585 }
586 }
587 }
588 return self;
589};
590
591/**
592 * @private
593 */
594Dygraph.isArrayLike = function (o) {
595 var typ = typeof(o);
596 if (
597 (typ != 'object' && !(typ == 'function' &&
598 typeof(o.item) == 'function')) ||
599 o === null ||
600 typeof(o.length) != 'number' ||
601 o.nodeType === 3
602 ) {
603 return false;
604 }
605 return true;
606};
607
608/**
609 * @private
610 */
611Dygraph.isDateLike = function (o) {
612 if (typeof(o) != "object" || o === null ||
613 typeof(o.getTime) != 'function') {
614 return false;
615 }
616 return true;
617};
618
619/**
620 * Note: this only seems to work for arrays.
621 * @private
622 */
623Dygraph.clone = function(o) {
624 // TODO(danvk): figure out how MochiKit's version works
625 var r = [];
626 for (var i = 0; i < o.length; i++) {
627 if (Dygraph.isArrayLike(o[i])) {
628 r.push(Dygraph.clone(o[i]));
629 } else {
630 r.push(o[i]);
631 }
632 }
633 return r;
634};
635
636/**
637 * @private
638 * Create a new canvas element. This is more complex than a simple
639 * document.createElement("canvas") because of IE and excanvas.
640 */
641Dygraph.createCanvas = function() {
642 var canvas = document.createElement("canvas");
643
644 var isIE = (/MSIE/.test(navigator.userAgent) && !window.opera);
645 if (isIE && (typeof(G_vmlCanvasManager) != 'undefined')) {
646 canvas = G_vmlCanvasManager.initElement(canvas);
647 }
648
649 return canvas;
650};
651
652/**
653 * @private
654 * Checks whether the user is on an Android browser.
655 * Android does not fully support the <canvas> tag, e.g. w/r/t/ clipping.
656 */
657Dygraph.isAndroid = function() {
658 return (/Android/).test(navigator.userAgent);
659};
660
661/**
662 * @private
663 * Call a function N times at a given interval, then call a cleanup function
664 * once. repeat_fn is called once immediately, then (times - 1) times
665 * asynchronously. If times=1, then cleanup_fn() is also called synchronously.
666 * @param repeat_fn {Function} Called repeatedly -- takes the number of calls
667 * (from 0 to times-1) as an argument.
668 * @param times {number} The number of times to call repeat_fn
669 * @param every_ms {number} Milliseconds between calls
670 * @param cleanup_fn {Function} A function to call after all repeat_fn calls.
671 * @private
672 */
673Dygraph.repeatAndCleanup = function(repeat_fn, times, every_ms, cleanup_fn) {
674 var count = 0;
675 var start_time = new Date().getTime();
676 repeat_fn(count);
677 if (times == 1) {
678 cleanup_fn();
679 return;
680 }
681
682 (function loop() {
683 if (count >= times) return;
684 var target_time = start_time + (1 + count) * every_ms;
685 setTimeout(function() {
686 count++;
687 repeat_fn(count);
688 if (count >= times - 1) {
689 cleanup_fn();
690 } else {
691 loop();
692 }
693 }, target_time - new Date().getTime());
694 // TODO(danvk): adjust every_ms to produce evenly-timed function calls.
695 })();
696};
697
698/**
699 * @private
700 * This function will scan the option list and determine if they
701 * require us to recalculate the pixel positions of each point.
702 * @param { List } a list of options to check.
703 * @return { Boolean } true if the graph needs new points else false.
704 */
705Dygraph.isPixelChangingOptionList = function(labels, attrs) {
706 // A whitelist of options that do not change pixel positions.
707 var pixelSafeOptions = {
708 'annotationClickHandler': true,
709 'annotationDblClickHandler': true,
710 'annotationMouseOutHandler': true,
711 'annotationMouseOverHandler': true,
712 'axisLabelColor': true,
713 'axisLineColor': true,
714 'axisLineWidth': true,
715 'clickCallback': true,
716 'digitsAfterDecimal': true,
717 'drawCallback': true,
718 'drawHighlightPointCallback': true,
719 'drawPoints': true,
720 'drawPointCallback': true,
721 'drawXGrid': true,
722 'drawYGrid': true,
723 'fillAlpha': true,
724 'gridLineColor': true,
725 'gridLineWidth': true,
726 'hideOverlayOnMouseOut': true,
727 'highlightCallback': true,
728 'highlightCircleSize': true,
729 'interactionModel': true,
730 'isZoomedIgnoreProgrammaticZoom': true,
731 'labelsDiv': true,
732 'labelsDivStyles': true,
733 'labelsDivWidth': true,
734 'labelsKMB': true,
735 'labelsKMG2': true,
736 'labelsSeparateLines': true,
737 'labelsShowZeroValues': true,
738 'legend': true,
739 'maxNumberWidth': true,
740 'panEdgeFraction': true,
741 'pixelsPerYLabel': true,
742 'pointClickCallback': true,
743 'pointSize': true,
744 'rangeSelectorPlotFillColor': true,
745 'rangeSelectorPlotStrokeColor': true,
746 'showLabelsOnHighlight': true,
747 'showRoller': true,
748 'sigFigs': true,
749 'strokeWidth': true,
750 'underlayCallback': true,
751 'unhighlightCallback': true,
752 'xAxisLabelFormatter': true,
753 'xTicker': true,
754 'xValueFormatter': true,
755 'yAxisLabelFormatter': true,
756 'yValueFormatter': true,
757 'zoomCallback': true
758 };
759
760 // Assume that we do not require new points.
761 // This will change to true if we actually do need new points.
762 var requiresNewPoints = false;
763
764 // Create a dictionary of series names for faster lookup.
765 // If there are no labels, then the dictionary stays empty.
766 var seriesNamesDictionary = { };
767 if (labels) {
768 for (var i = 1; i < labels.length; i++) {
769 seriesNamesDictionary[labels[i]] = true;
770 }
771 }
772
773 // Iterate through the list of updated options.
774 for (var property in attrs) {
775 // Break early if we already know we need new points from a previous option.
776 if (requiresNewPoints) {
777 break;
778 }
779 if (attrs.hasOwnProperty(property)) {
780 // Find out of this field is actually a series specific options list.
781 if (seriesNamesDictionary[property]) {
782 // This property value is a list of options for this series.
783 // If any of these sub properties are not pixel safe, set the flag.
784 for (var subProperty in attrs[property]) {
785 // Break early if we already know we need new points from a previous option.
786 if (requiresNewPoints) {
787 break;
788 }
789 if (attrs[property].hasOwnProperty(subProperty) && !pixelSafeOptions[subProperty]) {
790 requiresNewPoints = true;
791 }
792 }
793 // If this was not a series specific option list, check if its a pixel changing property.
794 } else if (!pixelSafeOptions[property]) {
795 requiresNewPoints = true;
796 }
797 }
798 }
799
800 return requiresNewPoints;
801};
802
803/**
804 * Compares two arrays to see if they are equal. If either parameter is not an
805 * array it will return false. Does a shallow compare
806 * Dygraph.compareArrays([[1,2], [3, 4]], [[1,2], [3,4]]) === false.
807 * @param array1 first array
808 * @param array2 second array
809 * @return True if both parameters are arrays, and contents are equal.
810 */
811Dygraph.compareArrays = function(array1, array2) {
812 if (!Dygraph.isArrayLike(array1) || !Dygraph.isArrayLike(array2)) {
813 return false;
814 }
815 if (array1.length !== array2.length) {
816 return false;
817 }
818 for (var i = 0; i < array1.length; i++) {
819 if (array1[i] !== array2[i]) {
820 return false;
821 }
822 }
823 return true;
824};
825
826/**
827 * ctx: the canvas context
828 * sides: the number of sides in the shape.
829 * radius: the radius of the image.
830 * cx: center x coordate
831 * cy: center y coordinate
832 * rotationRadians: the shift of the initial angle, in radians.
833 * delta: the angle shift for each line. If missing, creates a regular
834 * polygon.
835 */
836Dygraph.regularShape_ = function(
837 ctx, sides, radius, cx, cy, rotationRadians, delta) {
838 rotationRadians = rotationRadians ? rotationRadians : 0;
839 delta = delta ? delta : Math.PI * 2 / sides;
840
841 ctx.beginPath();
842 var first = true;
843 var initialAngle = rotationRadians;
844 var angle = initialAngle;
845
846 var computeCoordinates = function() {
847 var x = cx + (Math.sin(angle) * radius);
848 var y = cy + (-Math.cos(angle) * radius);
849 return [x, y];
850 };
851
852 var initialCoordinates = computeCoordinates();
853 var x = initialCoordinates[0];
854 var y = initialCoordinates[1];
855 ctx.moveTo(x, y);
856
857 for (var idx = 0; idx < sides; idx++) {
858 angle = (idx == sides - 1) ? initialAngle : (angle + delta);
859 var coords = computeCoordinates();
860 ctx.lineTo(coords[0], coords[1]);
861 }
862 ctx.fill();
863 ctx.stroke();
864}
865
866Dygraph.shapeFunction_ = function(sides, rotationRadians, delta) {
867 return function(g, name, ctx, cx, cy, color, radius) {
868 ctx.strokeStyle = color;
869 ctx.fillStyle = "white";
870 Dygraph.regularShape_(ctx, sides, radius, cx, cy, rotationRadians, delta);
871 };
872};
873
874Dygraph.DrawPolygon_ = function(sides, rotationRadians, ctx, cx, cy, color, radius, delta) {
875 new Dygraph.RegularShape_(sides, rotationRadians, delta).draw(ctx, cx, cy, radius);
876}
877
878Dygraph.Circles = {
879 DEFAULT : function(g, name, ctx, canvasx, canvasy, color, radius) {
880 ctx.beginPath();
881 ctx.fillStyle = color;
882 ctx.arc(canvasx, canvasy, radius, 0, 2 * Math.PI, false);
883 ctx.fill();
884 },
885 TRIANGLE : Dygraph.shapeFunction_(3),
886 SQUARE : Dygraph.shapeFunction_(4, Math.PI / 4),
887 DIAMOND : Dygraph.shapeFunction_(4),
888 PENTAGON : Dygraph.shapeFunction_(5),
889 HEXAGON : Dygraph.shapeFunction_(6),
890 CIRCLE : function(g, name, ctx, cx, cy, color, radius) {
891 ctx.beginPath();
892 ctx.strokeStyle = color;
893 ctx.fillStyle = "white";
894 ctx.arc(cx, cy, radius, 0, 2 * Math.PI, false);
895 ctx.fill();
896 ctx.stroke();
897 },
898 STAR : Dygraph.shapeFunction_(5, 0, 4 * Math.PI / 5),
899 PLUS : function(g, name, ctx, cx, cy, color, radius) {
900 ctx.strokeStyle = color;
901
902 ctx.beginPath();
903 ctx.moveTo(cx + radius, cy);
904 ctx.lineTo(cx - radius, cy);
905 ctx.closePath();
906 ctx.stroke();
907
908 ctx.beginPath();
909 ctx.moveTo(cx, cy + radius);
910 ctx.lineTo(cx, cy - radius);
911 ctx.closePath();
912 ctx.stroke();
913 },
914 EX : function(g, name, ctx, cx, cy, color, radius) {
915 ctx.strokeStyle = color;
916
917 ctx.beginPath();
918 ctx.moveTo(cx + radius, cy + radius);
919 ctx.lineTo(cx - radius, cy - radius);
920 ctx.closePath();
921 ctx.stroke();
922
923 ctx.beginPath();
924 ctx.moveTo(cx + radius, cy - radius);
925 ctx.lineTo(cx - radius, cy + radius);
926 ctx.closePath();
927 ctx.stroke();
928 }
929};