3 * Copyright 2011 Dan Vanderkam (danvdk@gmail.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
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.
14 /*global Dygraph:false, Node:false */
17 import * as DygraphTickers from
'./dygraph-tickers';
19 export var LOG_SCALE
= 10;
20 export var LN_TEN
= Math
.log(LOG_SCALE
);
27 export var log10
= function(x
) {
28 return Math
.log(x
) / LN_TEN
;
31 /** A dotted line stroke pattern. */
32 export var DOTTED_LINE
= [2, 2];
33 /** A dashed line stroke pattern. */
34 export var DASHED_LINE
= [7, 3];
35 /** A dot dash stroke pattern. */
36 export var DOT_DASH_LINE
= [7, 2, 2, 2];
38 // Directions for panning and zooming. Use bit operations when combined
39 // values are possible.
40 export var HORIZONTAL
= 1;
41 export var VERTICAL
= 2;
44 * Return the 2d context for a dygraph canvas.
46 * This method is only exposed for the sake of replacing the function in
49 * @param {!HTMLCanvasElement} canvas
50 * @return {!CanvasRenderingContext2D}
53 export var getContext
= function(canvas
) {
54 return /** @type{!CanvasRenderingContext2D}*/(canvas
.getContext("2d"));
58 * Add an event handler.
59 * @param {!Node} elem The element to add the event to.
60 * @param {string} type The type of the event, e.g. 'click' or 'mousemove'.
61 * @param {function(Event):(boolean|undefined)} fn The function to call
62 * on the event. The function takes one parameter: the event object.
65 export var addEvent
= function addEvent(elem
, type
, fn
) {
66 elem
.addEventListener(type
, fn
, false);
70 * Remove an event handler.
71 * @param {!Node} elem The element to remove the event from.
72 * @param {string} type The type of the event, e.g. 'click' or 'mousemove'.
73 * @param {function(Event):(boolean|undefined)} fn The function to call
74 * on the event. The function takes one parameter: the event object.
76 export function removeEvent(elem
, type
, fn
) {
77 elem
.removeEventListener(type
, fn
, false);
81 * Cancels further processing of an event. This is useful to prevent default
82 * browser actions, e.g. highlighting text on a double-click.
83 * Based on the article at
84 * http://www.switchonthecode.com/tutorials/javascript-tutorial-the-scroll-wheel
85 * @param {!Event} e The event whose normal behavior should be canceled.
88 export function cancelEvent(e
) {
89 e
= e
? e
: window
.event
;
90 if (e
.stopPropagation
) {
93 if (e
.preventDefault
) {
96 e
.cancelBubble
= true;
98 e
.returnValue
= false;
103 * Convert hsv values to an rgb(r,g,b) string. Taken from MochiKit.Color. This
104 * is used to generate default series colors which are evenly spaced on the
106 * @param { number } hue Range is 0.0-1.0.
107 * @param { number } saturation Range is 0.0-1.0.
108 * @param { number } value Range is 0.0-1.0.
109 * @return { string } "rgb(r,g,b)" where r, g and b range from 0-255.
112 export function hsvToRGB(hue
, saturation
, value
) {
116 if (saturation
=== 0) {
121 var i
= Math
.floor(hue
* 6);
122 var f
= (hue
* 6) - i
;
123 var p
= value
* (1 - saturation
);
124 var q
= value
* (1 - (saturation
* f
));
125 var t
= value
* (1 - (saturation
* (1 - f
)));
127 case 1: red
= q
; green
= value
; blue
= p
; break;
128 case 2: red
= p
; green
= value
; blue
= t
; break;
129 case 3: red
= p
; green
= q
; blue
= value
; break;
130 case 4: red
= t
; green
= p
; blue
= value
; break;
131 case 5: red
= value
; green
= p
; blue
= q
; break;
132 case 6: // fall through
133 case 0: red
= value
; green
= t
; blue
= p
; break;
136 red
= Math
.floor(255 * red
+ 0.5);
137 green
= Math
.floor(255 * green
+ 0.5);
138 blue
= Math
.floor(255 * blue
+ 0.5);
139 return 'rgb(' + red
+ ',' + green
+ ',' + blue
+ ')';
143 * Find the coordinates of an object relative to the top left of the page.
146 * @return {{x:number,y:number}}
149 export function findPos(obj
) {
150 var p
= obj
.getBoundingClientRect(),
152 d
= document
.documentElement
;
155 x
: p
.left
+ (w
.pageXOffset
|| d
.scrollLeft
),
156 y
: p
.top
+ (w
.pageYOffset
|| d
.scrollTop
)
161 * Returns the x-coordinate of the event in a coordinate system where the
162 * top-left corner of the page (not the window) is (0,0).
163 * Taken from MochiKit.Signal
168 export function pageX(e
) {
169 return (!e
.pageX
|| e
.pageX
< 0) ? 0 : e
.pageX
;
173 * Returns the y-coordinate of the event in a coordinate system where the
174 * top-left corner of the page (not the window) is (0,0).
175 * Taken from MochiKit.Signal
180 export function pageY(e
) {
181 return (!e
.pageY
|| e
.pageY
< 0) ? 0 : e
.pageY
;
185 * Converts page the x-coordinate of the event to pixel x-coordinates on the
186 * canvas (i.e. DOM Coords).
187 * @param {!Event} e Drag event.
188 * @param {!DygraphInteractionContext} context Interaction context object.
189 * @return {number} The amount by which the drag has moved to the right.
191 export function dragGetX_(e
, context
) {
192 return pageX(e
) - context
.px
;
196 * Converts page the y-coordinate of the event to pixel y-coordinates on the
197 * canvas (i.e. DOM Coords).
198 * @param {!Event} e Drag event.
199 * @param {!DygraphInteractionContext} context Interaction context object.
200 * @return {number} The amount by which the drag has moved down.
202 export function dragGetY_(e
, context
) {
203 return pageY(e
) - context
.py
;
207 * This returns true unless the parameter is 0, null, undefined or NaN.
208 * TODO(danvk): rename this function to something like 'isNonZeroNan'.
210 * @param {number} x The number to consider.
211 * @return {boolean} Whether the number is zero or NaN.
214 export function isOK(x
) {
215 return !!x
&& !isNaN(x
);
219 * @param {{x:?number,y:?number,yval:?number}} p The point to consider, valid
220 * points are {x, y} objects
221 * @param {boolean=} opt_allowNaNY Treat point with y=NaN as valid
222 * @return {boolean} Whether the point has numeric x and y.
225 export function isValidPoint(p
, opt_allowNaNY
) {
226 if (!p
) return false; // null or undefined object
227 if (p
.yval
=== null) return false; // missing point
228 if (p
.x
=== null || p
.x
=== undefined
) return false;
229 if (p
.y
=== null || p
.y
=== undefined
) return false;
230 if (isNaN(p
.x
) || (!opt_allowNaNY
&& isNaN(p
.y
))) return false;
235 * Number formatting function which mimicks the behavior of %g in printf, i.e.
236 * either exponential or fixed format (without trailing 0s) is used depending on
237 * the length of the generated string. The advantage of this format is that
238 * there is a predictable upper bound on the resulting string length,
239 * significant figures are not dropped, and normal numbers are not displayed in
240 * exponential notation.
242 * NOTE: JavaScript's native toPrecision() is NOT a drop-in replacement for %g.
243 * It creates strings which are too long for absolute values between 10^-4 and
244 * 10^-6, e.g. '0.00001' instead of '1e-5'. See tests/number-format.html for
247 * @param {number} x The number to format
248 * @param {number=} opt_precision The precision to use, default 2.
249 * @return {string} A string formatted like %g in printf. The max generated
250 * string length should be precision + 6 (e.g 1.123e+300).
252 export function floatFormat(x
, opt_precision
) {
253 // Avoid invalid precision values; [1, 21] is the valid range.
254 var p
= Math
.min(Math
.max(1, opt_precision
|| 2), 21);
256 // This is deceptively simple. The actual algorithm comes from:
258 // Max allowed length = p + 4
259 // where 4 comes from 'e+n' and '.'.
261 // Length of fixed format = 2 + y + p
262 // where 2 comes from '0.' and y = # of leading zeroes.
264 // Equating the two and solving for y yields y = 2, or 0.00xxxx which is
267 // Since the behavior of toPrecision() is identical for larger numbers, we
268 // don't have to worry about the other bound.
270 // Finally, the argument for toExponential() is the number of trailing digits,
271 // so we take off 1 for the value before the '.'.
272 return (Math
.abs(x
) < 1.0e-3 && x
!== 0.0) ?
273 x
.toExponential(p
- 1) : x
.toPrecision(p
);
277 * Converts '9' to '09' (useful for dates)
282 export function zeropad(x
) {
283 if (x
< 10) return "0" + x
; else return "" + x
;
287 * Date accessors to get the parts of a calendar date (year, month,
288 * day, hour, minute, second and millisecond) according to local time,
289 * and factory method to call the Date constructor with an array of arguments.
291 export var DateAccessorsLocal
= {
292 getFullYear
: d
=> d
.getFullYear(),
293 getMonth
: d
=> d
.getMonth(),
294 getDate
: d
=> d
.getDate(),
295 getHours
: d
=> d
.getHours(),
296 getMinutes
: d
=> d
.getMinutes(),
297 getSeconds
: d
=> d
.getSeconds(),
298 getMilliseconds
: d
=> d
.getMilliseconds(),
299 getDay
: d
=> d
.getDay(),
300 makeDate
: function(y
, m
, d
, hh
, mm
, ss
, ms
) {
301 return new Date(y
, m
, d
, hh
, mm
, ss
, ms
);
306 * Date accessors to get the parts of a calendar date (year, month,
307 * day of month, hour, minute, second and millisecond) according to UTC time,
308 * and factory method to call the Date constructor with an array of arguments.
310 export var DateAccessorsUTC
= {
311 getFullYear
: d
=> d
.getUTCFullYear(),
312 getMonth
: d
=> d
.getUTCMonth(),
313 getDate
: d
=> d
.getUTCDate(),
314 getHours
: d
=> d
.getUTCHours(),
315 getMinutes
: d
=> d
.getUTCMinutes(),
316 getSeconds
: d
=> d
.getUTCSeconds(),
317 getMilliseconds
: d
=> d
.getUTCMilliseconds(),
318 getDay
: d
=> d
.getUTCDay(),
319 makeDate
: function(y
, m
, d
, hh
, mm
, ss
, ms
) {
320 return new Date(Date
.UTC(y
, m
, d
, hh
, mm
, ss
, ms
));
325 * Return a string version of the hours, minutes and seconds portion of a date.
326 * @param {number} hh The hours (from 0-23)
327 * @param {number} mm The minutes (from 0-59)
328 * @param {number} ss The seconds (from 0-59)
329 * @return {string} A time of the form "HH:MM" or "HH:MM:SS"
332 export function hmsString_(hh
, mm
, ss
) {
333 var ret
= zeropad(hh
) + ":" + zeropad(mm
);
335 ret
+= ":" + zeropad(ss
);
341 * Convert a JS date (millis since epoch) to a formatted string.
342 * @param {number} time The JavaScript time value (ms since epoch)
343 * @param {boolean} utc Wether output UTC or local time
344 * @return {string} A date of one of these forms:
345 * "YYYY/MM/DD", "YYYY/MM/DD HH:MM" or "YYYY/MM/DD HH:MM:SS"
348 export function dateString_(time
, utc
) {
349 var accessors
= utc
? DateAccessorsUTC
: DateAccessorsLocal
;
350 var date
= new Date(time
);
351 var y
= accessors
.getFullYear(date
);
352 var m
= accessors
.getMonth(date
);
353 var d
= accessors
.getDate(date
);
354 var hh
= accessors
.getHours(date
);
355 var mm
= accessors
.getMinutes(date
);
356 var ss
= accessors
.getSeconds(date
);
357 // Get a year string:
359 // Get a 0 padded month string
360 var month
= zeropad(m
+ 1); //months are 0-offset, sigh
361 // Get a 0 padded day string
362 var day
= zeropad(d
);
363 var frac
= hh
* 3600 + mm
* 60 + ss
;
364 var ret
= year
+ "/" + month + "/" + day
;
366 ret
+= " " + hmsString_(hh
, mm
, ss
);
372 * Round a number to the specified number of digits past the decimal point.
373 * @param {number} num The number to round
374 * @param {number} places The number of decimals to which to round
375 * @return {number} The rounded number
378 export function round_(num
, places
) {
379 var shift
= Math
.pow(10, places
);
380 return Math
.round(num
* shift
)/shift
;
384 * Implementation of binary search over an array.
385 * Currently does not work when val is outside the range of arry's values.
386 * @param {number} val the value to search for
387 * @param {Array.<number>} arry is the value over which to search
388 * @param {number} abs If abs > 0, find the lowest entry greater than val
389 * If abs < 0, find the highest entry less than val.
390 * If abs == 0, find the entry that equals val.
391 * @param {number=} low The first index in arry to consider (optional)
392 * @param {number=} high The last index in arry to consider (optional)
393 * @return {number} Index of the element, or -1 if it isn't found.
396 export function binarySearch(val
, arry
, abs
, low
, high
) {
397 if (low
=== null || low
=== undefined
||
398 high
=== null || high
=== undefined
) {
400 high
= arry
.length
- 1;
405 if (abs
=== null || abs
=== undefined
) {
408 var validIndex
= function(idx
) {
409 return idx
>= 0 && idx
< arry
.length
;
411 var mid
= parseInt((low
+ high
) / 2, 10);
412 var element
= arry
[mid
];
414 if (element
== val
) {
416 } else if (element
> val
) {
418 // Accept if element > val, but also if prior element < val.
420 if (validIndex(idx
) && arry
[idx
] < val
) {
424 return binarySearch(val
, arry
, abs
, low
, mid
- 1);
425 } else if (element
< val
) {
427 // Accept if element < val, but also if prior element > val.
429 if (validIndex(idx
) && arry
[idx
] > val
) {
433 return binarySearch(val
, arry
, abs
, mid
+ 1, high
);
435 return -1; // can't actually happen, but makes closure compiler happy
439 * Parses a date, returning the number of milliseconds since epoch. This can be
440 * passed in as an xValueParser in the Dygraph constructor.
441 * TODO(danvk): enumerate formats that this understands.
443 * @param {string} dateStr A date in a variety of possible string formats.
444 * @return {number} Milliseconds since epoch.
447 export function dateParser(dateStr
) {
451 // Let the system try the format first, with one caveat:
452 // YYYY-MM-DD[ HH:MM:SS] is interpreted as UTC by a variety of browsers.
453 // dygraphs displays dates in local time, so this will result in surprising
454 // inconsistencies. But if you specify "T" or "Z" (i.e. YYYY-MM-DDTHH:MM:SS),
455 // then you probably know what you're doing, so we'll let you go ahead.
456 // Issue: http://code.google.com/p/dygraphs/issues/detail
?id
=255
457 if (dateStr
.search("-") == -1 ||
458 dateStr
.search("T") != -1 || dateStr
.search("Z") != -1) {
459 d
= dateStrToMillis(dateStr
);
460 if (d
&& !isNaN(d
)) return d
;
463 if (dateStr
.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12'
464 dateStrSlashed
= dateStr
.replace("-", "/", "g");
465 while (dateStrSlashed
.search("-") != -1) {
466 dateStrSlashed
= dateStrSlashed
.replace("-", "/");
468 d
= dateStrToMillis(dateStrSlashed
);
469 } else if (dateStr
.length
== 8) { // e.g. '20090712'
470 // TODO(danvk): remove support for this format. It's confusing.
471 dateStrSlashed
= dateStr
.substr(0,4) + "/" + dateStr.substr(4,2) + "/" +
473 d
= dateStrToMillis(dateStrSlashed
);
475 // Any format that Date.parse will accept, e.g. "2009/07/12" or
476 // "2009/07/12 12:34:56"
477 d
= dateStrToMillis(dateStr
);
480 if (!d
|| isNaN(d
)) {
481 console
.error("Couldn't parse " + dateStr
+ " as a date");
487 * This is identical to JavaScript's built-in Date.parse() method, except that
488 * it doesn't get replaced with an incompatible method by aggressive JS
489 * libraries like MooTools or Joomla.
490 * @param {string} str The date string, e.g. "2011/05/06"
491 * @return {number} millis since epoch
494 export function dateStrToMillis(str
) {
495 return new Date(str
).getTime();
498 // These functions are all based on MochiKit.
500 * Copies all the properties from o to self.
502 * @param {!Object} self
506 export function update(self
, o
) {
507 if (typeof(o
) != 'undefined' && o
!== null) {
509 if (o
.hasOwnProperty(k
)) {
518 * Copies all the properties from o to self.
520 * @param {!Object} self
525 export function updateDeep(self
, o
) {
526 // Taken from http://stackoverflow.com/questions
/384286/javascript
-isdom
-how
-do-you
-check
-if-a
-javascript
-object
-is
-a
-dom
-object
529 typeof Node
=== "object" ? o
instanceof Node
:
530 typeof o
=== "object" && typeof o
.nodeType
=== "number" && typeof o
.nodeName
==="string"
534 if (typeof(o
) != 'undefined' && o
!== null) {
536 if (o
.hasOwnProperty(k
)) {
539 } else if (isArrayLike(o
[k
])) {
540 self
[k
] = o
[k
].slice();
541 } else if (isNode(o
[k
])) {
542 // DOM objects are shallowly-copied.
544 } else if (typeof(o
[k
]) == 'object') {
545 if (typeof(self
[k
]) != 'object' || self
[k
] === null) {
548 updateDeep(self
[k
], o
[k
]);
563 export function isArrayLike(o
) {
566 (typ
!= 'object' && !(typ
== 'function' &&
567 typeof(o
.item
) == 'function')) ||
569 typeof(o
.length
) != 'number' ||
582 export function isDateLike(o
) {
583 if (typeof(o
) != "object" || o
=== null ||
584 typeof(o
.getTime
) != 'function') {
591 * Note: this only seems to work for arrays.
596 export function clone(o
) {
597 // TODO(danvk): figure out how MochiKit's version works
599 for (var i
= 0; i
< o
.length
; i
++) {
600 if (isArrayLike(o
[i
])) {
610 * Create a new canvas element.
612 * @return {!HTMLCanvasElement}
615 export function createCanvas() {
616 return document
.createElement('canvas');
620 * Returns the context's pixel ratio, which is the ratio between the device
621 * pixel ratio and the backing store ratio. Typically this is 1 for conventional
622 * displays, and > 1 for HiDPI displays (such as the Retina MBP).
623 * See http://www.html5rocks.com/en/tutorials/canvas/hidpi/ for more details.
625 * @param {!CanvasRenderingContext2D} context The canvas's 2d context.
626 * @return {number} The ratio of the device pixel ratio and the backing store
627 * ratio for the specified context.
629 export function getContextPixelRatio(context
) {
631 var devicePixelRatio
= window
.devicePixelRatio
;
632 var backingStoreRatio
= context
.webkitBackingStorePixelRatio
||
633 context
.mozBackingStorePixelRatio
||
634 context
.msBackingStorePixelRatio
||
635 context
.oBackingStorePixelRatio
||
636 context
.backingStorePixelRatio
|| 1;
637 if (devicePixelRatio
!== undefined
) {
638 return devicePixelRatio
/ backingStoreRatio
;
640 // At least devicePixelRatio must be defined for this ratio to make sense.
641 // We default backingStoreRatio to 1: this does not exist on some browsers
642 // (i.e. desktop Chrome).
651 * Checks whether the user is on an Android browser.
652 * Android does not fully support the <canvas> tag, e.g. w/r/t/ clipping.
656 export function isAndroid() {
657 return (/Android/).test(navigator
.userAgent
);
662 * TODO(danvk): use @template here when it's better supported for classes.
663 * @param {!Array} array
664 * @param {number} start
665 * @param {number} length
666 * @param {function(!Array,?):boolean=} predicate
669 export function Iterator(array
, start
, length
, predicate
) {
671 length
= length
|| array
.length
;
672 this.hasNext
= true; // Use to identify if there's another element.
673 this.peek
= null; // Use for look-ahead
676 this.predicate_
= predicate
;
677 this.end_
= Math
.min(array
.length
, start
+ length
);
678 this.nextIdx_
= start
- 1; // use -1 so initial advance works.
679 this.next(); // ignoring result.
685 Iterator
.prototype.next
= function() {
691 var nextIdx
= this.nextIdx_
+ 1;
693 while (nextIdx
< this.end_
) {
694 if (!this.predicate_
|| this.predicate_(this.array_
, nextIdx
)) {
695 this.peek
= this.array_
[nextIdx
];
701 this.nextIdx_
= nextIdx
;
703 this.hasNext
= false;
710 * Returns a new iterator over array, between indexes start and
711 * start + length, and only returns entries that pass the accept function
713 * @param {!Array} array the array to iterate over.
714 * @param {number} start the first index to iterate over, 0 if absent.
715 * @param {number} length the number of elements in the array to iterate over.
716 * This, along with start, defines a slice of the array, and so length
717 * doesn't imply the number of elements in the iterator when accept doesn't
718 * always accept all values. array.length when absent.
719 * @param {function(?):boolean=} opt_predicate a function that takes
720 * parameters array and idx, which returns true when the element should be
721 * returned. If omitted, all elements are accepted.
724 export function createIterator(array
, start
, length
, opt_predicate
) {
725 return new Iterator(array
, start
, length
, opt_predicate
);
728 // Shim layer with setTimeout fallback.
729 // From: http://paulirish.com/2011/requestanimationframe-for-smart-animating/
730 // Should be called with the window context:
731 // Dygraph.requestAnimFrame.call(window, function() {})
732 export var requestAnimFrame
= (function() {
733 return window
.requestAnimationFrame
||
734 window
.webkitRequestAnimationFrame
||
735 window
.mozRequestAnimationFrame
||
736 window
.oRequestAnimationFrame
||
737 window
.msRequestAnimationFrame
||
738 function (callback
) {
739 window
.setTimeout(callback
, 1000 / 60);
744 * Call a function at most maxFrames times at an attempted interval of
745 * framePeriodInMillis, then call a cleanup function once. repeatFn is called
746 * once immediately, then at most (maxFrames - 1) times asynchronously. If
747 * maxFrames==1, then cleanup_fn() is also called synchronously. This function
748 * is used to sequence animation.
749 * @param {function(number)} repeatFn Called repeatedly -- takes the frame
750 * number (from 0 to maxFrames-1) as an argument.
751 * @param {number} maxFrames The max number of times to call repeatFn
752 * @param {number} framePeriodInMillis Max requested time between frames.
753 * @param {function()} cleanupFn A function to call after all repeatFn calls.
756 export function repeatAndCleanup(repeatFn
, maxFrames
, framePeriodInMillis
,
759 var previousFrameNumber
;
760 var startTime
= new Date().getTime();
761 repeatFn(frameNumber
);
762 if (maxFrames
== 1) {
766 var maxFrameArg
= maxFrames
- 1;
769 if (frameNumber
>= maxFrames
) return;
770 requestAnimFrame
.call(window
, function() {
771 // Determine which frame to draw based on the delay so far. Will skip
772 // frames if necessary.
773 var currentTime
= new Date().getTime();
774 var delayInMillis
= currentTime
- startTime
;
775 previousFrameNumber
= frameNumber
;
776 frameNumber
= Math
.floor(delayInMillis
/ framePeriodInMillis
);
777 var frameDelta
= frameNumber
- previousFrameNumber
;
778 // If we predict that the subsequent repeatFn call will overshoot our
779 // total frame target, so our last call will cause a stutter, then jump to
780 // the last call immediately. If we're going to cause a stutter, better
781 // to do it faster than slower.
782 var predictOvershootStutter
= (frameNumber
+ frameDelta
) > maxFrameArg
;
783 if (predictOvershootStutter
|| (frameNumber
>= maxFrameArg
)) {
784 repeatFn(maxFrameArg
); // Ensure final call with maxFrameArg.
787 if (frameDelta
!== 0) { // Don't call repeatFn with duplicate frames.
788 repeatFn(frameNumber
);
796 // A whitelist of options that do not change pixel positions.
797 var pixelSafeOptions
= {
798 'annotationClickHandler': true,
799 'annotationDblClickHandler': true,
800 'annotationMouseOutHandler': true,
801 'annotationMouseOverHandler': true,
802 'axisLabelColor': true,
803 'axisLineColor': true,
804 'axisLineWidth': true,
805 'clickCallback': true,
806 'drawCallback': true,
807 'drawHighlightPointCallback': true,
809 'drawPointCallback': true,
812 'gridLineColor': true,
813 'gridLineWidth': true,
814 'hideOverlayOnMouseOut': true,
815 'highlightCallback': true,
816 'highlightCircleSize': true,
817 'interactionModel': true,
818 'isZoomedIgnoreProgrammaticZoom': true,
820 'labelsDivStyles': true,
821 'labelsDivWidth': true,
824 'labelsSeparateLines': true,
825 'labelsShowZeroValues': true,
827 'panEdgeFraction': true,
828 'pixelsPerYLabel': true,
829 'pointClickCallback': true,
831 'rangeSelectorPlotFillColor': true,
832 'rangeSelectorPlotFillGradientColor': true,
833 'rangeSelectorPlotStrokeColor': true,
834 'rangeSelectorBackgroundStrokeColor': true,
835 'rangeSelectorBackgroundLineWidth': true,
836 'rangeSelectorPlotLineWidth': true,
837 'rangeSelectorForegroundStrokeColor': true,
838 'rangeSelectorForegroundLineWidth': true,
839 'rangeSelectorAlpha': true,
840 'showLabelsOnHighlight': true,
843 'underlayCallback': true,
844 'unhighlightCallback': true,
849 * This function will scan the option list and determine if they
850 * require us to recalculate the pixel positions of each point.
851 * TODO: move this into dygraph-options.js
852 * @param {!Array.<string>} labels a list of options to check.
853 * @param {!Object} attrs
854 * @return {boolean} true if the graph needs new points else false.
857 export function isPixelChangingOptionList(labels
, attrs
) {
858 // Assume that we do not require new points.
859 // This will change to true if we actually do need new points.
861 // Create a dictionary of series names for faster lookup.
862 // If there are no labels, then the dictionary stays empty.
863 var seriesNamesDictionary
= { };
865 for (var i
= 1; i
< labels
.length
; i
++) {
866 seriesNamesDictionary
[labels
[i
]] = true;
870 // Scan through a flat (i.e. non-nested) object of options.
871 // Returns true/false depending on whether
new points are needed
.
872 var scanFlatOptions
= function(options
) {
873 for (var property
in options
) {
874 if (options
.hasOwnProperty(property
) &&
875 !pixelSafeOptions
[property
]) {
882 // Iterate through the list of updated options.
883 for (var property
in attrs
) {
884 if (!attrs
.hasOwnProperty(property
)) continue;
886 // Find out of this field is actually a series specific options list.
887 if (property
== 'highlightSeriesOpts' ||
888 (seriesNamesDictionary
[property
] && !attrs
.series
)) {
889 // This property value is a list of options for this series.
890 if (scanFlatOptions(attrs
[property
])) return true;
891 } else if (property
== 'series' || property
== 'axes') {
892 // This is twice-nested options list.
893 var perSeries
= attrs
[property
];
894 for (var series
in perSeries
) {
895 if (perSeries
.hasOwnProperty(series
) &&
896 scanFlatOptions(perSeries
[series
])) {
901 // If this was not a series specific option list, check if it's a pixel
902 // changing property.
903 if (!pixelSafeOptions
[property
]) return true;
910 export var Circles
= {
911 DEFAULT
: function(g
, name
, ctx
, canvasx
, canvasy
, color
, radius
) {
913 ctx
.fillStyle
= color
;
914 ctx
.arc(canvasx
, canvasy
, radius
, 0, 2 * Math
.PI
, false);
917 // For more shapes, include extras/shapes.js
921 * To create a "drag" interaction, you typically register a mousedown event
922 * handler on the element where the drag begins. In that handler, you register a
923 * mouseup handler on the window to determine when the mouse is released,
924 * wherever that release happens. This works well, except when the user releases
925 * the mouse over an off-domain iframe. In that case, the mouseup event is
926 * handled by the iframe and never bubbles up to the window handler.
928 * To deal with this issue, we cover iframes with high z-index divs to make sure
929 * they don't capture mouseup.
932 * element.addEventListener('mousedown', function() {
933 * var tarper = new utils.IFrameTarp();
935 * var mouseUpHandler = function() {
937 * window.removeEventListener(mouseUpHandler);
940 * window.addEventListener('mouseup', mouseUpHandler);
945 export function IFrameTarp() {
946 /** @type {Array.<!HTMLDivElement>} */
951 * Find all the iframes in the document and cover them with high z-index
954 IFrameTarp
.prototype.cover
= function() {
955 var iframes
= document
.getElementsByTagName("iframe");
956 for (var i
= 0; i
< iframes
.length
; i
++) {
957 var iframe
= iframes
[i
];
958 var pos
= Dygraph
.findPos(iframe
),
961 width
= iframe
.offsetWidth
,
962 height
= iframe
.offsetHeight
;
964 var div
= document
.createElement("div");
965 div
.style
.position
= "absolute";
966 div
.style
.left
= x
+ 'px';
967 div
.style
.top
= y
+ 'px';
968 div
.style
.width
= width
+ 'px';
969 div
.style
.height
= height
+ 'px';
970 div
.style
.zIndex
= 999;
971 document
.body
.appendChild(div
);
972 this.tarps
.push(div
);
977 * Remove all the iframe covers. You should call this in a mouseup handler.
979 IFrameTarp
.prototype.uncover
= function() {
980 for (var i
= 0; i
< this.tarps
.length
; i
++) {
981 this.tarps
[i
].parentNode
.removeChild(this.tarps
[i
]);
987 * Determine whether |data| is delimited by CR, CRLF, LF, LFCR.
988 * @param {string} data
989 * @return {?string} the delimiter that was detected (or null on failure).
991 export function detectLineDelimiter(data
) {
992 for (var i
= 0; i
< data
.length
; i
++) {
993 var code
= data
.charAt(i
);
995 // Might actually be "\r\n".
996 if (((i
+ 1) < data
.length
) && (data
.charAt(i
+ 1) === '\n')) {
1001 if (code
=== '\n') {
1002 // Might actually be "\n\r".
1003 if (((i
+ 1) < data
.length
) && (data
.charAt(i
+ 1) === '\r')) {
1014 * Is one node contained by another?
1015 * @param {Node} containee The contained node.
1016 * @param {Node} container The container node.
1017 * @return {boolean} Whether containee is inside (or equal to) container.
1020 export function isNodeContainedBy(containee
, container
) {
1021 if (container
=== null || containee
=== null) {
1024 var containeeNode
= /** @type {Node} */ (containee
);
1025 while (containeeNode
&& containeeNode
!== container
) {
1026 containeeNode
= containeeNode
.parentNode
;
1028 return (containeeNode
=== container
);
1032 // This masks some numeric issues in older versions of Firefox,
1033 // where 1.0/Math
.pow(10,2) != Math
.pow(10,-2).
1034 /** @type {function(number,number):number} */
1035 export function pow(base
, exp
) {
1037 return 1.0 / Math
.pow(base
, -exp
);
1039 return Math
.pow(base
, exp
);
1042 var RGBA_RE
= /^rgba?\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})(?:,\s*([01](?:\.\d+)?))?\)$/;
1045 * Helper for Dygraph.toRGB_ which parses strings of the form:
1047 * rgba(123, 45, 67, 0.5)
1048 * @return parsed {r,g,b,a?} tuple or null.
1050 function parseRGBA(rgbStr
) {
1051 var bits
= RGBA_RE
.exec(rgbStr
);
1052 if (!bits
) return null;
1053 var r
= parseInt(bits
[1], 10),
1054 g
= parseInt(bits
[2], 10),
1055 b
= parseInt(bits
[3], 10);
1057 return {r
: r
, g
: g
, b
: b
, a
: parseFloat(bits
[4])};
1059 return {r
: r
, g
: g
, b
: b
};
1064 * Converts any valid CSS color (hex, rgb(), named color) to an RGB tuple.
1066 * @param {!string} colorStr Any valid CSS color string.
1067 * @return {{r:number,g:number,b:number,a:number?}} Parsed RGB tuple.
1070 export function toRGB_(colorStr
) {
1071 // Strategy: First try to parse colorStr directly. This is fast & avoids DOM
1072 // manipulation. If that fails (e.g. for named colors like 'red'), then
1073 // create a hidden DOM element and parse its computed color.
1074 var rgb
= parseRGBA(colorStr
);
1075 if (rgb
) return rgb
;
1077 var div
= document
.createElement('div');
1078 div
.style
.backgroundColor
= colorStr
;
1079 div
.style
.visibility
= 'hidden';
1080 document
.body
.appendChild(div
);
1081 var rgbStr
= window
.getComputedStyle(div
, null).backgroundColor
;
1082 document
.body
.removeChild(div
);
1083 return parseRGBA(rgbStr
);
1087 * Checks whether the browser supports the <canvas> tag.
1088 * @param {HTMLCanvasElement=} opt_canvasElement Pass a canvas element as an
1089 * optimization if you have one.
1090 * @return {boolean} Whether the browser supports canvas.
1092 export function isCanvasSupported(opt_canvasElement
) {
1094 var canvas
= opt_canvasElement
|| document
.createElement("canvas");
1095 canvas
.getContext("2d");
1103 * Parses the value as a floating point number. This is like the parseFloat()
1104 * built-in, but with a few differences:
1105 * - the empty string is parsed as null, rather than NaN.
1106 * - if the string cannot be parsed at all, an error is logged.
1107 * If the string can't be parsed, this method returns null.
1108 * @param {string} x The string to be parsed
1109 * @param {number=} opt_line_no The line number from which the string comes.
1110 * @param {string=} opt_line The text of the line from which the string comes.
1112 export function parseFloat_(x
, opt_line_no
, opt_line
) {
1113 var val
= parseFloat(x
);
1114 if (!isNaN(val
)) return val
;
1116 // Try to figure out what happeend.
1117 // If the value is the empty string, parse it as null.
1118 if (/^ *$/.test(x
)) return null;
1120 // If it was actually "NaN", return it as NaN.
1121 if (/^ *nan *$/i.test(x
)) return NaN
;
1123 // Looks like a parsing error.
1124 var msg
= "Unable to parse '" + x
+ "' as a number";
1125 if (opt_line
!== undefined
&& opt_line_no
!== undefined
) {
1126 msg
+= " on line " + (1+(opt_line_no
||0)) + " ('" + opt_line
+ "') of CSV.";
1134 // Label constants for the labelsKMB and labelsKMG2 options.
1135 // (i.e. '100000' -> '100K')
1136 var KMB_LABELS
= [ 'K', 'M', 'B', 'T', 'Q' ];
1137 var KMG2_BIG_LABELS
= [ 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y' ];
1138 var KMG2_SMALL_LABELS
= [ 'm', 'u', 'n', 'p', 'f', 'a', 'z', 'y' ];
1142 * Return a string version of a number. This respects the digitsAfterDecimal
1143 * and maxNumberWidth options.
1144 * @param {number} x The number to be formatted
1145 * @param {Dygraph} opts An options view
1147 export function numberValueFormatter(x
, opts
) {
1148 var sigFigs
= opts('sigFigs');
1150 if (sigFigs
!== null) {
1151 // User has opted for a fixed number of significant figures.
1152 return floatFormat(x
, sigFigs
);
1155 var digits
= opts('digitsAfterDecimal');
1156 var maxNumberWidth
= opts('maxNumberWidth');
1158 var kmb
= opts('labelsKMB');
1159 var kmg2
= opts('labelsKMG2');
1163 // switch to scientific notation if we underflow or overflow fixed display.
1165 (Math
.abs(x
) >= Math
.pow(10, maxNumberWidth
) ||
1166 Math
.abs(x
) < Math
.pow(10, -digits
))) {
1167 label
= x
.toExponential(digits
);
1169 label
= '' + round_(x
, digits
);
1178 k_labels
= KMB_LABELS
;
1181 if (kmb
) console
.warn("Setting both labelsKMB and labelsKMG2. Pick one!");
1183 k_labels
= KMG2_BIG_LABELS
;
1184 m_labels
= KMG2_SMALL_LABELS
;
1187 var absx
= Math
.abs(x
);
1188 var n
= pow(k
, k_labels
.length
);
1189 for (var j
= k_labels
.length
- 1; j
>= 0; j
--, n
/= k
) {
1191 label
= round_(x
/ n
, digits
) + k_labels
[j
];
1196 // TODO(danvk): clean up this logic. Why so different than kmb?
1197 var x_parts
= String(x
.toExponential()).split('e-');
1198 if (x_parts
.length
=== 2 && x_parts
[1] >= 3 && x_parts
[1] <= 24) {
1199 if (x_parts
[1] % 3 > 0) {
1200 label
= round_(x_parts
[0] /
1201 pow(10, (x_parts
[1] % 3)),
1204 label
= Number(x_parts
[0]).toFixed(2);
1206 label
+= m_labels
[Math
.floor(x_parts
[1] / 3) - 1];
1215 * variant for use as an axisLabelFormatter.
1218 export function numberAxisLabelFormatter(x
, granularity
, opts
) {
1219 return numberValueFormatter
.call(this, x
, opts
);
1223 * @type {!Array.<string>}
1227 var SHORT_MONTH_NAMES_
= ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
1231 * Convert a JS date to a string appropriate to display on an axis that
1232 * is displaying values at the stated granularity. This respects the
1234 * @param {Date} date The date to format
1235 * @param {number} granularity One of the Dygraph granularity constants
1236 * @param {Dygraph} opts An options view
1237 * @return {string} The date formatted as local time
1240 export function dateAxisLabelFormatter(date
, granularity
, opts
) {
1241 var utc
= opts('labelsUTC');
1242 var accessors
= utc
? DateAccessorsUTC
: DateAccessorsLocal
;
1244 var year
= accessors
.getFullYear(date
),
1245 month
= accessors
.getMonth(date
),
1246 day
= accessors
.getDate(date
),
1247 hours
= accessors
.getHours(date
),
1248 mins
= accessors
.getMinutes(date
),
1249 secs
= accessors
.getSeconds(date
),
1250 millis
= accessors
.getSeconds(date
);
1252 if (granularity
>= DygraphTickers
.Granularity
.DECADAL
) {
1254 } else if (granularity
>= DygraphTickers
.Granularity
.MONTHLY
) {
1255 return SHORT_MONTH_NAMES_
[month
] + ' ' + year
;
1257 var frac
= hours
* 3600 + mins
* 60 + secs
+ 1e-3 * millis
;
1258 if (frac
=== 0 || granularity
>= DygraphTickers
.Granularity
.DAILY
) {
1259 // e.g. '21 Jan' (%d%b)
1260 return zeropad(day
) + ' ' + SHORT_MONTH_NAMES_
[month
];
1262 return hmsString_(hours
, mins
, secs
);
1266 // alias in case anyone is referencing the old method.
1267 // Dygraph.dateAxisFormatter = Dygraph.dateAxisLabelFormatter;
1270 * Return a string version of a JS date for a value label. This respects the
1272 * @param {Date} date The date to be formatted
1273 * @param {Dygraph} opts An options view
1276 export function dateValueFormatter(d
, opts
) {
1277 return dateString_(d
, opts('labelsUTC'));