fix XSS in labels
[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/**
22 * @private
23 * @param {number} x
24 * @return {number}
25 */
26Dygraph.log10 = function(x) {
27 return Math.log(x) / Dygraph.LN_TEN;
28};
29
30// Various logging levels.
31Dygraph.DEBUG = 1;
32Dygraph.INFO = 2;
33Dygraph.WARNING = 3;
34Dygraph.ERROR = 3;
35
36// <REMOVE_FOR_COMBINED>
37// Set this to log stack traces on warnings, etc.
38// This requires stacktrace.js, which is up to you to provide.
39// A copy can be found in the dygraphs repo, or at
40// https://github.com/eriwen/javascript-stacktrace
41Dygraph.LOG_STACK_TRACES = false;
42// </REMOVE_FOR_COMBINED>
43
44/** A dotted line stroke pattern. */
45Dygraph.DOTTED_LINE = [2, 2];
46/** A dashed line stroke pattern. */
47Dygraph.DASHED_LINE = [7, 3];
48/** A dot dash stroke pattern. */
49Dygraph.DOT_DASH_LINE = [7, 2, 2, 2];
50
51/**
52 * Log an error on the JS console at the given severity.
53 * @param {number} severity One of Dygraph.{DEBUG,INFO,WARNING,ERROR}
54 * @param {string} message The message to log.
55 * @private
56 */
57Dygraph.log = function(severity, message) {
58 // <REMOVE_FOR_COMBINED>
59 var st;
60 if (typeof(printStackTrace) != 'undefined') {
61 try {
62 // Remove uninteresting bits: logging functions and paths.
63 st = printStackTrace({guess:false});
64 while (st[0].indexOf("stacktrace") != -1) {
65 st.splice(0, 1);
66 }
67
68 st.splice(0, 2);
69 for (var i = 0; i < st.length; i++) {
70 st[i] = st[i].replace(/\([^)]*\/(.*)\)/, '@$1')
71 .replace(/\@.*\/([^\/]*)/, '@$1')
72 .replace('[object Object].', '');
73 }
74 var top_msg = st.splice(0, 1)[0];
75 message += ' (' + top_msg.replace(/^.*@ ?/, '') + ')';
76 } catch(e) {
77 // Oh well, it was worth a shot!
78 }
79 }
80 // </REMOVE_FOR_COMBINED>
81
82 if (typeof(window.console) != 'undefined') {
83 // In older versions of Firefox, only console.log is defined.
84 var console = window.console;
85 var log = function(console, method, msg) {
86 if (method && typeof(method) == 'function') {
87 method.call(console, msg);
88 } else {
89 console.log(msg);
90 }
91 };
92
93 switch (severity) {
94 case Dygraph.DEBUG:
95 log(console, console.debug, 'dygraphs: ' + message);
96 break;
97 case Dygraph.INFO:
98 log(console, console.info, 'dygraphs: ' + message);
99 break;
100 case Dygraph.WARNING:
101 log(console, console.warn, 'dygraphs: ' + message);
102 break;
103 case Dygraph.ERROR:
104 log(console, console.error, 'dygraphs: ' + message);
105 break;
106 }
107 }
108
109 // <REMOVE_FOR_COMBINED>
110 if (Dygraph.LOG_STACK_TRACES) {
111 window.console.log(st.join('\n'));
112 }
113 // </REMOVE_FOR_COMBINED>
114};
115
116/**
117 * @param {string} message
118 * @private
119 */
120Dygraph.info = function(message) {
121 Dygraph.log(Dygraph.INFO, message);
122};
123
124/**
125 * @param {string} message
126 * @private
127 */
128Dygraph.warn = function(message) {
129 Dygraph.log(Dygraph.WARNING, message);
130};
131
132/**
133 * @param {string} message
134 */
135Dygraph.error = function(message) {
136 Dygraph.log(Dygraph.ERROR, message);
137};
138
139/**
140 * Return the 2d context for a dygraph canvas.
141 *
142 * This method is only exposed for the sake of replacing the function in
143 * automated tests, e.g.
144 *
145 * var oldFunc = Dygraph.getContext();
146 * Dygraph.getContext = function(canvas) {
147 * var realContext = oldFunc(canvas);
148 * return new Proxy(realContext);
149 * };
150 * @param {!HTMLCanvasElement} canvas
151 * @return {!CanvasRenderingContext2D}
152 * @private
153 */
154Dygraph.getContext = function(canvas) {
155 return /** @type{!CanvasRenderingContext2D}*/(canvas.getContext("2d"));
156};
157
158/**
159 * Add an event handler. This smooths a difference between IE and the rest of
160 * the world.
161 * @param {!Node} elem The element to add the event to.
162 * @param {string} type The type of the event, e.g. 'click' or 'mousemove'.
163 * @param {function(Event):(boolean|undefined)} fn The function to call
164 * on the event. The function takes one parameter: the event object.
165 * @private
166 */
167Dygraph.addEvent = function addEvent(elem, type, fn) {
168 if (elem.addEventListener) {
169 elem.addEventListener(type, fn, false);
170 } else {
171 elem[type+fn] = function(){fn(window.event);};
172 elem.attachEvent('on'+type, elem[type+fn]);
173 }
174};
175
176/**
177 * Add an event handler. This event handler is kept until the graph is
178 * destroyed with a call to graph.destroy().
179 *
180 * @param {!Node} elem The element to add the event to.
181 * @param {string} type The type of the event, e.g. 'click' or 'mousemove'.
182 * @param {function(Event):(boolean|undefined)} fn The function to call
183 * on the event. The function takes one parameter: the event object.
184 * @private
185 */
186Dygraph.prototype.addAndTrackEvent = function(elem, type, fn) {
187 Dygraph.addEvent(elem, type, fn);
188 this.registeredEvents_.push({ elem : elem, type : type, fn : fn });
189};
190
191/**
192 * Remove an event handler. This smooths a difference between IE and the rest
193 * of the world.
194 * @param {!Node} elem The element to remove the event from.
195 * @param {string} type The type of the event, e.g. 'click' or 'mousemove'.
196 * @param {function(Event):(boolean|undefined)} fn The function to call
197 * on the event. The function takes one parameter: the event object.
198 * @private
199 */
200Dygraph.removeEvent = function(elem, type, fn) {
201 if (elem.removeEventListener) {
202 elem.removeEventListener(type, fn, false);
203 } else {
204 try {
205 elem.detachEvent('on'+type, elem[type+fn]);
206 } catch(e) {
207 // We only detach event listeners on a "best effort" basis in IE. See:
208 // http://stackoverflow.com/questions/2553632/detachevent-not-working-with-named-inline-functions
209 }
210 elem[type+fn] = null;
211 }
212};
213
214Dygraph.prototype.removeTrackedEvents_ = function() {
215 if (this.registeredEvents_) {
216 for (var idx = 0; idx < this.registeredEvents_.length; idx++) {
217 var reg = this.registeredEvents_[idx];
218 Dygraph.removeEvent(reg.elem, reg.type, reg.fn);
219 }
220 }
221
222 this.registeredEvents_ = [];
223};
224
225/**
226 * Cancels further processing of an event. This is useful to prevent default
227 * browser actions, e.g. highlighting text on a double-click.
228 * Based on the article at
229 * http://www.switchonthecode.com/tutorials/javascript-tutorial-the-scroll-wheel
230 * @param {!Event} e The event whose normal behavior should be canceled.
231 * @private
232 */
233Dygraph.cancelEvent = function(e) {
234 e = e ? e : window.event;
235 if (e.stopPropagation) {
236 e.stopPropagation();
237 }
238 if (e.preventDefault) {
239 e.preventDefault();
240 }
241 e.cancelBubble = true;
242 e.cancel = true;
243 e.returnValue = false;
244 return false;
245};
246
247/**
248 * Convert hsv values to an rgb(r,g,b) string. Taken from MochiKit.Color. This
249 * is used to generate default series colors which are evenly spaced on the
250 * color wheel.
251 * @param { number } hue Range is 0.0-1.0.
252 * @param { number } saturation Range is 0.0-1.0.
253 * @param { number } value Range is 0.0-1.0.
254 * @return { string } "rgb(r,g,b)" where r, g and b range from 0-255.
255 * @private
256 */
257Dygraph.hsvToRGB = function (hue, saturation, value) {
258 var red;
259 var green;
260 var blue;
261 if (saturation === 0) {
262 red = value;
263 green = value;
264 blue = value;
265 } else {
266 var i = Math.floor(hue * 6);
267 var f = (hue * 6) - i;
268 var p = value * (1 - saturation);
269 var q = value * (1 - (saturation * f));
270 var t = value * (1 - (saturation * (1 - f)));
271 switch (i) {
272 case 1: red = q; green = value; blue = p; break;
273 case 2: red = p; green = value; blue = t; break;
274 case 3: red = p; green = q; blue = value; break;
275 case 4: red = t; green = p; blue = value; break;
276 case 5: red = value; green = p; blue = q; break;
277 case 6: // fall through
278 case 0: red = value; green = t; blue = p; break;
279 }
280 }
281 red = Math.floor(255 * red + 0.5);
282 green = Math.floor(255 * green + 0.5);
283 blue = Math.floor(255 * blue + 0.5);
284 return 'rgb(' + red + ',' + green + ',' + blue + ')';
285};
286
287// The following functions are from quirksmode.org with a modification for Safari from
288// http://blog.firetree.net/2005/07/04/javascript-find-position/
289// http://www.quirksmode.org/js/findpos.html
290// ... and modifications to support scrolling divs.
291
292/**
293 * Find the coordinates of an object relative to the top left of the page.
294 *
295 * TODO(danvk): change obj type from Node -&gt; !Node
296 * @param {Node} obj
297 * @return {{x:number,y:number}}
298 * @private
299 */
300Dygraph.findPos = function(obj) {
301 var curleft = 0, curtop = 0;
302 if (obj.offsetParent) {
303 var copyObj = obj;
304 while (1) {
305 // NOTE: the if statement here is for IE8.
306 var borderLeft = "0", borderTop = "0";
307 if (window.getComputedStyle) {
308 var computedStyle = window.getComputedStyle(copyObj, null);
309 borderLeft = computedStyle.borderLeft || "0";
310 borderTop = computedStyle.borderTop || "0";
311 }
312 curleft += parseInt(borderLeft, 10) ;
313 curtop += parseInt(borderTop, 10) ;
314 curleft += copyObj.offsetLeft;
315 curtop += copyObj.offsetTop;
316 if (!copyObj.offsetParent) {
317 break;
318 }
319 copyObj = copyObj.offsetParent;
320 }
321 } else {
322 // TODO(danvk): why would obj ever have these properties?
323 if (obj.x) curleft += obj.x;
324 if (obj.y) curtop += obj.y;
325 }
326
327 // This handles the case where the object is inside a scrolled div.
328 while (obj && obj != document.body) {
329 curleft -= obj.scrollLeft;
330 curtop -= obj.scrollTop;
331 obj = obj.parentNode;
332 }
333 return {x: curleft, y: curtop};
334};
335
336/**
337 * Returns the x-coordinate of the event in a coordinate system where the
338 * top-left corner of the page (not the window) is (0,0).
339 * Taken from MochiKit.Signal
340 * @param {!Event} e
341 * @return {number}
342 * @private
343 */
344Dygraph.pageX = function(e) {
345 if (e.pageX) {
346 return (!e.pageX || e.pageX < 0) ? 0 : e.pageX;
347 } else {
348 var de = document.documentElement;
349 var b = document.body;
350 return e.clientX +
351 (de.scrollLeft || b.scrollLeft) -
352 (de.clientLeft || 0);
353 }
354};
355
356/**
357 * Returns the y-coordinate of the event in a coordinate system where the
358 * top-left corner of the page (not the window) is (0,0).
359 * Taken from MochiKit.Signal
360 * @param {!Event} e
361 * @return {number}
362 * @private
363 */
364Dygraph.pageY = function(e) {
365 if (e.pageY) {
366 return (!e.pageY || e.pageY < 0) ? 0 : e.pageY;
367 } else {
368 var de = document.documentElement;
369 var b = document.body;
370 return e.clientY +
371 (de.scrollTop || b.scrollTop) -
372 (de.clientTop || 0);
373 }
374};
375
376/**
377 * Converts page the x-coordinate of the event to pixel x-coordinates on the
378 * canvas (i.e. DOM Coords).
379 * @param {!Event} e Drag event.
380 * @param {!DygraphInteractionContext} context Interaction context object.
381 * @return {number} The amount by which the drag has moved to the right.
382 */
383Dygraph.dragGetX_ = function(e, context) {
384 return Dygraph.pageX(e) - context.px;
385};
386
387/**
388 * Converts page the y-coordinate of the event to pixel y-coordinates on the
389 * canvas (i.e. DOM Coords).
390 * @param {!Event} e Drag event.
391 * @param {!DygraphInteractionContext} context Interaction context object.
392 * @return {number} The amount by which the drag has moved down.
393 */
394Dygraph.dragGetY_ = function(e, context) {
395 return Dygraph.pageY(e) - context.py;
396};
397
398/**
399 * This returns true unless the parameter is 0, null, undefined or NaN.
400 * TODO(danvk): rename this function to something like 'isNonZeroNan'.
401 *
402 * @param {number} x The number to consider.
403 * @return {boolean} Whether the number is zero or NaN.
404 * @private
405 */
406Dygraph.isOK = function(x) {
407 return !!x && !isNaN(x);
408};
409
410/**
411 * @param {{x:?number,y:?number,yval:?number}} p The point to consider, valid
412 * points are {x, y} objects
413 * @param {boolean=} opt_allowNaNY Treat point with y=NaN as valid
414 * @return {boolean} Whether the point has numeric x and y.
415 * @private
416 */
417Dygraph.isValidPoint = function(p, opt_allowNaNY) {
418 if (!p) return false; // null or undefined object
419 if (p.yval === null) return false; // missing point
420 if (p.x === null || p.x === undefined) return false;
421 if (p.y === null || p.y === undefined) return false;
422 if (isNaN(p.x) || (!opt_allowNaNY && isNaN(p.y))) return false;
423 return true;
424};
425
426/**
427 * Number formatting function which mimicks the behavior of %g in printf, i.e.
428 * either exponential or fixed format (without trailing 0s) is used depending on
429 * the length of the generated string. The advantage of this format is that
430 * there is a predictable upper bound on the resulting string length,
431 * significant figures are not dropped, and normal numbers are not displayed in
432 * exponential notation.
433 *
434 * NOTE: JavaScript's native toPrecision() is NOT a drop-in replacement for %g.
435 * It creates strings which are too long for absolute values between 10^-4 and
436 * 10^-6, e.g. '0.00001' instead of '1e-5'. See tests/number-format.html for
437 * output examples.
438 *
439 * @param {number} x The number to format
440 * @param {number=} opt_precision The precision to use, default 2.
441 * @return {string} A string formatted like %g in printf. The max generated
442 * string length should be precision + 6 (e.g 1.123e+300).
443 */
444Dygraph.floatFormat = function(x, opt_precision) {
445 // Avoid invalid precision values; [1, 21] is the valid range.
446 var p = Math.min(Math.max(1, opt_precision || 2), 21);
447
448 // This is deceptively simple. The actual algorithm comes from:
449 //
450 // Max allowed length = p + 4
451 // where 4 comes from 'e+n' and '.'.
452 //
453 // Length of fixed format = 2 + y + p
454 // where 2 comes from '0.' and y = # of leading zeroes.
455 //
456 // Equating the two and solving for y yields y = 2, or 0.00xxxx which is
457 // 1.0e-3.
458 //
459 // Since the behavior of toPrecision() is identical for larger numbers, we
460 // don't have to worry about the other bound.
461 //
462 // Finally, the argument for toExponential() is the number of trailing digits,
463 // so we take off 1 for the value before the '.'.
464 return (Math.abs(x) < 1.0e-3 && x !== 0.0) ?
465 x.toExponential(p - 1) : x.toPrecision(p);
466};
467
468/**
469 * Converts '9' to '09' (useful for dates)
470 * @param {number} x
471 * @return {string}
472 * @private
473 */
474Dygraph.zeropad = function(x) {
475 if (x < 10) return "0" + x; else return "" + x;
476};
477
478/**
479 * Return a string version of the hours, minutes and seconds portion of a date.
480 *
481 * @param {number} date The JavaScript date (ms since epoch)
482 * @return {string} A time of the form "HH:MM:SS"
483 * @private
484 */
485Dygraph.hmsString_ = function(date) {
486 var zeropad = Dygraph.zeropad;
487 var d = new Date(date);
488 if (d.getSeconds()) {
489 return zeropad(d.getHours()) + ":" +
490 zeropad(d.getMinutes()) + ":" +
491 zeropad(d.getSeconds());
492 } else {
493 return zeropad(d.getHours()) + ":" + zeropad(d.getMinutes());
494 }
495};
496
497/**
498 * Convert a JS date (millis since epoch) to YYYY/MM/DD
499 * @param {number} date The JavaScript date (ms since epoch)
500 * @return {string} A date of the form "YYYY/MM/DD"
501 * @private
502 */
503Dygraph.dateString_ = function(date) {
504 var zeropad = Dygraph.zeropad;
505 var d = new Date(date);
506
507 // Get the year:
508 var year = "" + d.getFullYear();
509 // Get a 0 padded month string
510 var month = zeropad(d.getMonth() + 1); //months are 0-offset, sigh
511 // Get a 0 padded day string
512 var day = zeropad(d.getDate());
513
514 var ret = "";
515 var frac = d.getHours() * 3600 + d.getMinutes() * 60 + d.getSeconds();
516 if (frac) ret = " " + Dygraph.hmsString_(date);
517
518 return year + "/" + month + "/" + day + ret;
519};
520
521/**
522 * Round a number to the specified number of digits past the decimal point.
523 * @param {number} num The number to round
524 * @param {number} places The number of decimals to which to round
525 * @return {number} The rounded number
526 * @private
527 */
528Dygraph.round_ = function(num, places) {
529 var shift = Math.pow(10, places);
530 return Math.round(num * shift)/shift;
531};
532
533/**
534 * Implementation of binary search over an array.
535 * Currently does not work when val is outside the range of arry's values.
536 * @param {number} val the value to search for
537 * @param {Array.<number>} arry is the value over which to search
538 * @param {number} abs If abs > 0, find the lowest entry greater than val
539 * If abs < 0, find the highest entry less than val.
540 * If abs == 0, find the entry that equals val.
541 * @param {number=} low The first index in arry to consider (optional)
542 * @param {number=} high The last index in arry to consider (optional)
543 * @return {number} Index of the element, or -1 if it isn't found.
544 * @private
545 */
546Dygraph.binarySearch = function(val, arry, abs, low, high) {
547 if (low === null || low === undefined ||
548 high === null || high === undefined) {
549 low = 0;
550 high = arry.length - 1;
551 }
552 if (low > high) {
553 return -1;
554 }
555 if (abs === null || abs === undefined) {
556 abs = 0;
557 }
558 var validIndex = function(idx) {
559 return idx >= 0 && idx < arry.length;
560 };
561 var mid = parseInt((low + high) / 2, 10);
562 var element = arry[mid];
563 var idx;
564 if (element == val) {
565 return mid;
566 } else if (element > val) {
567 if (abs > 0) {
568 // Accept if element > val, but also if prior element < val.
569 idx = mid - 1;
570 if (validIndex(idx) && arry[idx] < val) {
571 return mid;
572 }
573 }
574 return Dygraph.binarySearch(val, arry, abs, low, mid - 1);
575 } else if (element < val) {
576 if (abs < 0) {
577 // Accept if element < val, but also if prior element > val.
578 idx = mid + 1;
579 if (validIndex(idx) && arry[idx] > val) {
580 return mid;
581 }
582 }
583 return Dygraph.binarySearch(val, arry, abs, mid + 1, high);
584 }
585 return -1; // can't actually happen, but makes closure compiler happy
586};
587
588/**
589 * Parses a date, returning the number of milliseconds since epoch. This can be
590 * passed in as an xValueParser in the Dygraph constructor.
591 * TODO(danvk): enumerate formats that this understands.
592 *
593 * @param {string} dateStr A date in a variety of possible string formats.
594 * @return {number} Milliseconds since epoch.
595 * @private
596 */
597Dygraph.dateParser = function(dateStr) {
598 var dateStrSlashed;
599 var d;
600
601 // Let the system try the format first, with one caveat:
602 // YYYY-MM-DD[ HH:MM:SS] is interpreted as UTC by a variety of browsers.
603 // dygraphs displays dates in local time, so this will result in surprising
604 // inconsistencies. But if you specify "T" or "Z" (i.e. YYYY-MM-DDTHH:MM:SS),
605 // then you probably know what you're doing, so we'll let you go ahead.
606 // Issue: http://code.google.com/p/dygraphs/issues/detail?id=255
607 if (dateStr.search("-") == -1 ||
608 dateStr.search("T") != -1 || dateStr.search("Z") != -1) {
609 d = Dygraph.dateStrToMillis(dateStr);
610 if (d && !isNaN(d)) return d;
611 }
612
613 if (dateStr.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12'
614 dateStrSlashed = dateStr.replace("-", "/", "g");
615 while (dateStrSlashed.search("-") != -1) {
616 dateStrSlashed = dateStrSlashed.replace("-", "/");
617 }
618 d = Dygraph.dateStrToMillis(dateStrSlashed);
619 } else if (dateStr.length == 8) { // e.g. '20090712'
620 // TODO(danvk): remove support for this format. It's confusing.
621 dateStrSlashed = dateStr.substr(0,4) + "/" + dateStr.substr(4,2) + "/" +
622 dateStr.substr(6,2);
623 d = Dygraph.dateStrToMillis(dateStrSlashed);
624 } else {
625 // Any format that Date.parse will accept, e.g. "2009/07/12" or
626 // "2009/07/12 12:34:56"
627 d = Dygraph.dateStrToMillis(dateStr);
628 }
629
630 if (!d || isNaN(d)) {
631 Dygraph.error("Couldn't parse " + dateStr + " as a date");
632 }
633 return d;
634};
635
636/**
637 * This is identical to JavaScript's built-in Date.parse() method, except that
638 * it doesn't get replaced with an incompatible method by aggressive JS
639 * libraries like MooTools or Joomla.
640 * @param {string} str The date string, e.g. "2011/05/06"
641 * @return {number} millis since epoch
642 * @private
643 */
644Dygraph.dateStrToMillis = function(str) {
645 return new Date(str).getTime();
646};
647
648// These functions are all based on MochiKit.
649/**
650 * Copies all the properties from o to self.
651 *
652 * @param {!Object} self
653 * @param {!Object} o
654 * @return {!Object}
655 */
656Dygraph.update = function(self, o) {
657 if (typeof(o) != 'undefined' && o !== null) {
658 for (var k in o) {
659 if (o.hasOwnProperty(k)) {
660 self[k] = o[k];
661 }
662 }
663 }
664 return self;
665};
666
667/**
668 * Copies all the properties from o to self.
669 *
670 * @param {!Object} self
671 * @param {!Object} o
672 * @return {!Object}
673 * @private
674 */
675Dygraph.updateDeep = function (self, o) {
676 // Taken from http://stackoverflow.com/questions/384286/javascript-isdom-how-do-you-check-if-a-javascript-object-is-a-dom-object
677 function isNode(o) {
678 return (
679 typeof Node === "object" ? o instanceof Node :
680 typeof o === "object" && typeof o.nodeType === "number" && typeof o.nodeName==="string"
681 );
682 }
683
684 if (typeof(o) != 'undefined' && o !== null) {
685 for (var k in o) {
686 if (o.hasOwnProperty(k)) {
687 if (o[k] === null) {
688 self[k] = null;
689 } else if (Dygraph.isArrayLike(o[k])) {
690 self[k] = o[k].slice();
691 } else if (isNode(o[k])) {
692 // DOM objects are shallowly-copied.
693 self[k] = o[k];
694 } else if (typeof(o[k]) == 'object') {
695 if (typeof(self[k]) != 'object' || self[k] === null) {
696 self[k] = {};
697 }
698 Dygraph.updateDeep(self[k], o[k]);
699 } else {
700 self[k] = o[k];
701 }
702 }
703 }
704 }
705 return self;
706};
707
708/**
709 * @param {*} o
710 * @return {boolean}
711 * @private
712 */
713Dygraph.isArrayLike = function(o) {
714 var typ = typeof(o);
715 if (
716 (typ != 'object' && !(typ == 'function' &&
717 typeof(o.item) == 'function')) ||
718 o === null ||
719 typeof(o.length) != 'number' ||
720 o.nodeType === 3
721 ) {
722 return false;
723 }
724 return true;
725};
726
727/**
728 * @param {Object} o
729 * @return {boolean}
730 * @private
731 */
732Dygraph.isDateLike = function (o) {
733 if (typeof(o) != "object" || o === null ||
734 typeof(o.getTime) != 'function') {
735 return false;
736 }
737 return true;
738};
739
740/**
741 * Note: this only seems to work for arrays.
742 * @param {!Array} o
743 * @return {!Array}
744 * @private
745 */
746Dygraph.clone = function(o) {
747 // TODO(danvk): figure out how MochiKit's version works
748 var r = [];
749 for (var i = 0; i < o.length; i++) {
750 if (Dygraph.isArrayLike(o[i])) {
751 r.push(Dygraph.clone(o[i]));
752 } else {
753 r.push(o[i]);
754 }
755 }
756 return r;
757};
758
759/**
760 * Create a new canvas element. This is more complex than a simple
761 * document.createElement("canvas") because of IE and excanvas.
762 *
763 * @return {!HTMLCanvasElement}
764 * @private
765 */
766Dygraph.createCanvas = function() {
767 var canvas = document.createElement("canvas");
768
769 var isIE = (/MSIE/.test(navigator.userAgent) && !window.opera);
770 if (isIE && (typeof(G_vmlCanvasManager) != 'undefined')) {
771 canvas = G_vmlCanvasManager.initElement(
772 /**@type{!HTMLCanvasElement}*/(canvas));
773 }
774
775 return canvas;
776};
777
778/**
779 * Checks whether the user is on an Android browser.
780 * Android does not fully support the <canvas> tag, e.g. w/r/t/ clipping.
781 * @return {boolean}
782 * @private
783 */
784Dygraph.isAndroid = function() {
785 return (/Android/).test(navigator.userAgent);
786};
787
788
789/**
790 * TODO(danvk): use @template here when it's better supported for classes.
791 * @param {!Array} array
792 * @param {number} start
793 * @param {number} length
794 * @param {function(!Array,?):boolean=} predicate
795 * @constructor
796 */
797Dygraph.Iterator = function(array, start, length, predicate) {
798 start = start || 0;
799 length = length || array.length;
800 this.hasNext = true; // Use to identify if there's another element.
801 this.peek = null; // Use for look-ahead
802 this.start_ = start;
803 this.array_ = array;
804 this.predicate_ = predicate;
805 this.end_ = Math.min(array.length, start + length);
806 this.nextIdx_ = start - 1; // use -1 so initial advance works.
807 this.next(); // ignoring result.
808};
809
810/**
811 * @return {Object}
812 */
813Dygraph.Iterator.prototype.next = function() {
814 if (!this.hasNext) {
815 return null;
816 }
817 var obj = this.peek;
818
819 var nextIdx = this.nextIdx_ + 1;
820 var found = false;
821 while (nextIdx < this.end_) {
822 if (!this.predicate_ || this.predicate_(this.array_, nextIdx)) {
823 this.peek = this.array_[nextIdx];
824 found = true;
825 break;
826 }
827 nextIdx++;
828 }
829 this.nextIdx_ = nextIdx;
830 if (!found) {
831 this.hasNext = false;
832 this.peek = null;
833 }
834 return obj;
835};
836
837/**
838 * Returns a new iterator over array, between indexes start and
839 * start + length, and only returns entries that pass the accept function
840 *
841 * @param {!Array} array the array to iterate over.
842 * @param {number} start the first index to iterate over, 0 if absent.
843 * @param {number} length the number of elements in the array to iterate over.
844 * This, along with start, defines a slice of the array, and so length
845 * doesn't imply the number of elements in the iterator when accept doesn't
846 * always accept all values. array.length when absent.
847 * @param {function(?):boolean=} opt_predicate a function that takes
848 * parameters array and idx, which returns true when the element should be
849 * returned. If omitted, all elements are accepted.
850 * @private
851 */
852Dygraph.createIterator = function(array, start, length, opt_predicate) {
853 return new Dygraph.Iterator(array, start, length, opt_predicate);
854};
855
856// Shim layer with setTimeout fallback.
857// From: http://paulirish.com/2011/requestanimationframe-for-smart-animating/
858// Should be called with the window context:
859// Dygraph.requestAnimFrame.call(window, function() {})
860Dygraph.requestAnimFrame = (function() {
861 return window.requestAnimationFrame ||
862 window.webkitRequestAnimationFrame ||
863 window.mozRequestAnimationFrame ||
864 window.oRequestAnimationFrame ||
865 window.msRequestAnimationFrame ||
866 function (callback) {
867 window.setTimeout(callback, 1000 / 60);
868 };
869})();
870
871/**
872 * Call a function at most maxFrames times at an attempted interval of
873 * framePeriodInMillis, then call a cleanup function once. repeatFn is called
874 * once immediately, then at most (maxFrames - 1) times asynchronously. If
875 * maxFrames==1, then cleanup_fn() is also called synchronously. This function
876 * is used to sequence animation.
877 * @param {function(number)} repeatFn Called repeatedly -- takes the frame
878 * number (from 0 to maxFrames-1) as an argument.
879 * @param {number} maxFrames The max number of times to call repeatFn
880 * @param {number} framePeriodInMillis Max requested time between frames.
881 * @param {function()} cleanupFn A function to call after all repeatFn calls.
882 * @private
883 */
884Dygraph.repeatAndCleanup = function(repeatFn, maxFrames, framePeriodInMillis,
885 cleanupFn) {
886 var frameNumber = 0;
887 var previousFrameNumber;
888 var startTime = new Date().getTime();
889 repeatFn(frameNumber);
890 if (maxFrames == 1) {
891 cleanupFn();
892 return;
893 }
894 var maxFrameArg = maxFrames - 1;
895
896 (function loop() {
897 if (frameNumber >= maxFrames) return;
898 Dygraph.requestAnimFrame.call(window, function() {
899 // Determine which frame to draw based on the delay so far. Will skip
900 // frames if necessary.
901 var currentTime = new Date().getTime();
902 var delayInMillis = currentTime - startTime;
903 previousFrameNumber = frameNumber;
904 frameNumber = Math.floor(delayInMillis / framePeriodInMillis);
905 var frameDelta = frameNumber - previousFrameNumber;
906 // If we predict that the subsequent repeatFn call will overshoot our
907 // total frame target, so our last call will cause a stutter, then jump to
908 // the last call immediately. If we're going to cause a stutter, better
909 // to do it faster than slower.
910 var predictOvershootStutter = (frameNumber + frameDelta) > maxFrameArg;
911 if (predictOvershootStutter || (frameNumber >= maxFrameArg)) {
912 repeatFn(maxFrameArg); // Ensure final call with maxFrameArg.
913 cleanupFn();
914 } else {
915 if (frameDelta !== 0) { // Don't call repeatFn with duplicate frames.
916 repeatFn(frameNumber);
917 }
918 loop();
919 }
920 });
921 })();
922};
923
924/**
925 * This function will scan the option list and determine if they
926 * require us to recalculate the pixel positions of each point.
927 * @param {!Array.<string>} labels a list of options to check.
928 * @param {!Object} attrs
929 * @return {boolean} true if the graph needs new points else false.
930 * @private
931 */
932Dygraph.isPixelChangingOptionList = function(labels, attrs) {
933 // A whitelist of options that do not change pixel positions.
934 var pixelSafeOptions = {
935 'annotationClickHandler': true,
936 'annotationDblClickHandler': true,
937 'annotationMouseOutHandler': true,
938 'annotationMouseOverHandler': true,
939 'axisLabelColor': true,
940 'axisLineColor': true,
941 'axisLineWidth': true,
942 'clickCallback': true,
943 'digitsAfterDecimal': true,
944 'drawCallback': true,
945 'drawHighlightPointCallback': true,
946 'drawPoints': true,
947 'drawPointCallback': true,
948 'drawXGrid': true,
949 'drawYGrid': true,
950 'fillAlpha': true,
951 'gridLineColor': true,
952 'gridLineWidth': true,
953 'hideOverlayOnMouseOut': true,
954 'highlightCallback': true,
955 'highlightCircleSize': true,
956 'interactionModel': true,
957 'isZoomedIgnoreProgrammaticZoom': true,
958 'labelsDiv': true,
959 'labelsDivStyles': true,
960 'labelsDivWidth': true,
961 'labelsKMB': true,
962 'labelsKMG2': true,
963 'labelsSeparateLines': true,
964 'labelsShowZeroValues': true,
965 'legend': true,
966 'maxNumberWidth': true,
967 'panEdgeFraction': true,
968 'pixelsPerYLabel': true,
969 'pointClickCallback': true,
970 'pointSize': true,
971 'rangeSelectorPlotFillColor': true,
972 'rangeSelectorPlotStrokeColor': true,
973 'showLabelsOnHighlight': true,
974 'showRoller': true,
975 'sigFigs': true,
976 'strokeWidth': true,
977 'underlayCallback': true,
978 'unhighlightCallback': true,
979 'xAxisLabelFormatter': true,
980 'xTicker': true,
981 'xValueFormatter': true,
982 'yAxisLabelFormatter': true,
983 'yValueFormatter': true,
984 'zoomCallback': true
985 };
986
987 // Assume that we do not require new points.
988 // This will change to true if we actually do need new points.
989 var requiresNewPoints = false;
990
991 // Create a dictionary of series names for faster lookup.
992 // If there are no labels, then the dictionary stays empty.
993 var seriesNamesDictionary = { };
994 if (labels) {
995 for (var i = 1; i < labels.length; i++) {
996 seriesNamesDictionary[labels[i]] = true;
997 }
998 }
999
1000 // Iterate through the list of updated options.
1001 for (var property in attrs) {
1002 // Break early if we already know we need new points from a previous option.
1003 if (requiresNewPoints) {
1004 break;
1005 }
1006 if (attrs.hasOwnProperty(property)) {
1007 // Find out of this field is actually a series specific options list.
1008 if (seriesNamesDictionary[property]) {
1009 // This property value is a list of options for this series.
1010 // If any of these sub properties are not pixel safe, set the flag.
1011 for (var subProperty in attrs[property]) {
1012 // Break early if we already know we need new points from a previous option.
1013 if (requiresNewPoints) {
1014 break;
1015 }
1016 if (attrs[property].hasOwnProperty(subProperty) && !pixelSafeOptions[subProperty]) {
1017 requiresNewPoints = true;
1018 }
1019 }
1020 // If this was not a series specific option list, check if its a pixel changing property.
1021 } else if (!pixelSafeOptions[property]) {
1022 requiresNewPoints = true;
1023 }
1024 }
1025 }
1026
1027 return requiresNewPoints;
1028};
1029
1030Dygraph.Circles = {
1031 DEFAULT : function(g, name, ctx, canvasx, canvasy, color, radius) {
1032 ctx.beginPath();
1033 ctx.fillStyle = color;
1034 ctx.arc(canvasx, canvasy, radius, 0, 2 * Math.PI, false);
1035 ctx.fill();
1036 }
1037 // For more shapes, include extras/shapes.js
1038};
1039
1040/**
1041 * To create a "drag" interaction, you typically register a mousedown event
1042 * handler on the element where the drag begins. In that handler, you register a
1043 * mouseup handler on the window to determine when the mouse is released,
1044 * wherever that release happens. This works well, except when the user releases
1045 * the mouse over an off-domain iframe. In that case, the mouseup event is
1046 * handled by the iframe and never bubbles up to the window handler.
1047 *
1048 * To deal with this issue, we cover iframes with high z-index divs to make sure
1049 * they don't capture mouseup.
1050 *
1051 * Usage:
1052 * element.addEventListener('mousedown', function() {
1053 * var tarper = new Dygraph.IFrameTarp();
1054 * tarper.cover();
1055 * var mouseUpHandler = function() {
1056 * ...
1057 * window.removeEventListener(mouseUpHandler);
1058 * tarper.uncover();
1059 * };
1060 * window.addEventListener('mouseup', mouseUpHandler);
1061 * };
1062 *
1063 * @constructor
1064 */
1065Dygraph.IFrameTarp = function() {
1066 /** @type {Array.<!HTMLDivElement>} */
1067 this.tarps = [];
1068};
1069
1070/**
1071 * Find all the iframes in the document and cover them with high z-index
1072 * transparent divs.
1073 */
1074Dygraph.IFrameTarp.prototype.cover = function() {
1075 var iframes = document.getElementsByTagName("iframe");
1076 for (var i = 0; i < iframes.length; i++) {
1077 var iframe = iframes[i];
1078 var pos = Dygraph.findPos(iframe),
1079 x = pos.x,
1080 y = pos.y,
1081 width = iframe.offsetWidth,
1082 height = iframe.offsetHeight;
1083
1084 var div = document.createElement("div");
1085 div.style.position = "absolute";
1086 div.style.left = x + 'px';
1087 div.style.top = y + 'px';
1088 div.style.width = width + 'px';
1089 div.style.height = height + 'px';
1090 div.style.zIndex = 999;
1091 document.body.appendChild(div);
1092 this.tarps.push(div);
1093 }
1094};
1095
1096/**
1097 * Remove all the iframe covers. You should call this in a mouseup handler.
1098 */
1099Dygraph.IFrameTarp.prototype.uncover = function() {
1100 for (var i = 0; i < this.tarps.length; i++) {
1101 this.tarps[i].parentNode.removeChild(this.tarps[i]);
1102 }
1103 this.tarps = [];
1104};
1105
1106/**
1107 * Determine whether |data| is delimited by CR, CRLF, LF, LFCR.
1108 * @param {string} data
1109 * @return {?string} the delimiter that was detected (or null on failure).
1110 */
1111Dygraph.detectLineDelimiter = function(data) {
1112 for (var i = 0; i < data.length; i++) {
1113 var code = data.charAt(i);
1114 if (code === '\r') {
1115 // Might actually be "\r\n".
1116 if (((i + 1) < data.length) && (data.charAt(i + 1) === '\n')) {
1117 return '\r\n';
1118 }
1119 return code;
1120 }
1121 if (code === '\n') {
1122 // Might actually be "\n\r".
1123 if (((i + 1) < data.length) && (data.charAt(i + 1) === '\r')) {
1124 return '\n\r';
1125 }
1126 return code;
1127 }
1128 }
1129
1130 return null;
1131};
1132
1133/**
1134 * Is one node contained by another?
1135 * @param {Node} containee The contained node.
1136 * @param {Node} container The container node.
1137 * @return {boolean} Whether containee is inside (or equal to) container.
1138 * @private
1139 */
1140Dygraph.isNodeContainedBy = function(containee, container) {
1141 if (container === null || containee === null) {
1142 return false;
1143 }
1144 var containeeNode = /** @type {Node} */ (containee);
1145 while (containeeNode && containeeNode !== container) {
1146 containeeNode = containeeNode.parentNode;
1147 }
1148 return (containeeNode === container);
1149};
1150
1151
1152// This masks some numeric issues in older versions of Firefox,
1153// where 1.0/Math.pow(10,2) != Math.pow(10,-2).
1154/** @type {function(number,number):number} */
1155Dygraph.pow = function(base, exp) {
1156 if (exp < 0) {
1157 return 1.0 / Math.pow(base, -exp);
1158 }
1159 return Math.pow(base, exp);
1160};
1161
1162// For Dygraph.setDateSameTZ, below.
1163Dygraph.dateSetters = {
1164 ms: Date.prototype.setMilliseconds,
1165 s: Date.prototype.setSeconds,
1166 m: Date.prototype.setMinutes,
1167 h: Date.prototype.setHours
1168};
1169
1170/**
1171 * This is like calling d.setSeconds(), d.setMinutes(), etc, except that it
1172 * adjusts for time zone changes to keep the date/time parts consistent.
1173 *
1174 * For example, d.getSeconds(), d.getMinutes() and d.getHours() will all be
1175 * the same before/after you call setDateSameTZ(d, {ms: 0}). The same is not
1176 * true if you call d.setMilliseconds(0).
1177 *
1178 * @type {function(!Date, Object.<number>)}
1179 */
1180Dygraph.setDateSameTZ = function(d, parts) {
1181 var tz = d.getTimezoneOffset();
1182 for (var k in parts) {
1183 if (!parts.hasOwnProperty(k)) continue;
1184 var setter = Dygraph.dateSetters[k];
1185 if (!setter) throw "Invalid setter: " + k;
1186 setter.call(d, parts[k]);
1187 if (d.getTimezoneOffset() != tz) {
1188 d.setTime(d.getTime() + (tz - d.getTimezoneOffset()) * 60 * 1000);
1189 }
1190 }
1191};
1192
1193/**
1194 * Converts any valid CSS color (hex, rgb(), named color) to an RGB tuple.
1195 *
1196 * @param {!string} colorStr Any valid CSS color string.
1197 * @return {{r:number,g:number,b:number}} Parsed RGB tuple.
1198 * @private
1199 */
1200Dygraph.toRGB_ = function(colorStr) {
1201 // TODO(danvk): cache color parses to avoid repeated DOM manipulation.
1202 var div = document.createElement('div');
1203 div.style.backgroundColor = colorStr;
1204 div.style.visibility = 'hidden';
1205 document.body.appendChild(div);
1206 var rgbStr = window.getComputedStyle(div, null).backgroundColor;
1207 document.body.removeChild(div);
1208 var bits = /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/.exec(rgbStr);
1209 return {
1210 r: parseInt(bits[1], 10),
1211 g: parseInt(bits[2], 10),
1212 b: parseInt(bits[3], 10)
1213 };
1214};
1215
1216/**
1217 * Checks whether the browser supports the &lt;canvas&gt; tag.
1218 * @param {HTMLCanvasElement=} opt_canvasElement Pass a canvas element as an
1219 * optimization if you have one.
1220 * @return {boolean} Whether the browser supports canvas.
1221 */
1222Dygraph.isCanvasSupported = function(opt_canvasElement) {
1223 var canvas;
1224 try {
1225 canvas = opt_canvasElement || document.createElement("canvas");
1226 canvas.getContext("2d");
1227 }
1228 catch (e) {
1229 var ie = navigator.appVersion.match(/MSIE (\d\.\d)/);
1230 var opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
1231 if ((!ie) || (ie[1] < 6) || (opera))
1232 return false;
1233 return true;
1234 }
1235 return true;
1236};
1237
1238/**
1239 * Parses the value as a floating point number. This is like the parseFloat()
1240 * built-in, but with a few differences:
1241 * - the empty string is parsed as null, rather than NaN.
1242 * - if the string cannot be parsed at all, an error is logged.
1243 * If the string can't be parsed, this method returns null.
1244 * @param {string} x The string to be parsed
1245 * @param {number=} opt_line_no The line number from which the string comes.
1246 * @param {string=} opt_line The text of the line from which the string comes.
1247 */
1248Dygraph.parseFloat_ = function(x, opt_line_no, opt_line) {
1249 var val = parseFloat(x);
1250 if (!isNaN(val)) return val;
1251
1252 // Try to figure out what happeend.
1253 // If the value is the empty string, parse it as null.
1254 if (/^ *$/.test(x)) return null;
1255
1256 // If it was actually "NaN", return it as NaN.
1257 if (/^ *nan *$/i.test(x)) return NaN;
1258
1259 // Looks like a parsing error.
1260 var msg = "Unable to parse '" + x + "' as a number";
1261 if (opt_line !== undefined && opt_line_no !== undefined) {
1262 msg += " on line " + (1+(opt_line_no||0)) + " ('" + opt_line + "') of CSV.";
1263 }
1264 Dygraph.error(msg);
1265
1266 return null;
1267};