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
;
38 export var logRangeFraction
= function(r0
, r1
, pct
) {
39 // Computing the inverse of toPercentXCoord. The function was arrived at with
40 // the following steps:
42 // Original calcuation:
43 // pct = (log(x) - log(xRange[0])) / (log(xRange
[1]) - log(xRange
[0])));
45 // Multiply both sides by the right-side denominator.
46 // pct * (log(xRange[1] - log(xRange[0]))) = log(x) - log(xRange[0])
48 // add log(xRange[0]) to both sides
49 // log(xRange[0]) + (pct * (log(xRange[1]) - log(xRange[0])) = log(x);
51 // Swap both sides of the equation,
52 // log(x) = log(xRange[0]) + (pct * (log(xRange[1]) - log(xRange[0]))
54 // Use both sides as the exponent in 10^exp and we're done.
55 // x = 10 ^ (log(xRange[0]) + (pct * (log(xRange[1]) - log(xRange[0])))
57 var logr0
= log10(r0
);
58 var logr1
= log10(r1
);
59 var exponent
= logr0
+ (pct
* (logr1
- logr0
));
60 var value
= Math
.pow(LOG_SCALE
, exponent
);
64 /** A dotted line stroke pattern. */
65 export var DOTTED_LINE
= [2, 2];
66 /** A dashed line stroke pattern. */
67 export var DASHED_LINE
= [7, 3];
68 /** A dot dash stroke pattern. */
69 export var DOT_DASH_LINE
= [7, 2, 2, 2];
71 // Directions for panning and zooming. Use bit operations when combined
72 // values are possible.
73 export var HORIZONTAL
= 1;
74 export var VERTICAL
= 2;
77 * Return the 2d context for a dygraph canvas.
79 * This method is only exposed for the sake of replacing the function in
82 * @param {!HTMLCanvasElement} canvas
83 * @return {!CanvasRenderingContext2D}
86 export var getContext
= function(canvas
) {
87 return /** @type{!CanvasRenderingContext2D}*/(canvas
.getContext("2d"));
91 * Add an event handler.
92 * @param {!Node} elem The element to add the event to.
93 * @param {string} type The type of the event, e.g. 'click' or 'mousemove'.
94 * @param {function(Event):(boolean|undefined)} fn The function to call
95 * on the event. The function takes one parameter: the event object.
98 export var addEvent
= function addEvent(elem
, type
, fn
) {
99 elem
.addEventListener(type
, fn
, false);
103 * Remove an event handler.
104 * @param {!Node} elem The element to remove the event from.
105 * @param {string} type The type of the event, e.g. 'click' or 'mousemove'.
106 * @param {function(Event):(boolean|undefined)} fn The function to call
107 * on the event. The function takes one parameter: the event object.
109 export function removeEvent(elem
, type
, fn
) {
110 elem
.removeEventListener(type
, fn
, false);
114 * Cancels further processing of an event. This is useful to prevent default
115 * browser actions, e.g. highlighting text on a double-click.
116 * Based on the article at
117 * http://www.switchonthecode.com/tutorials/javascript-tutorial-the-scroll-wheel
118 * @param {!Event} e The event whose normal behavior should be canceled.
121 export function cancelEvent(e
) {
122 e
= e
? e
: window
.event
;
123 if (e
.stopPropagation
) {
126 if (e
.preventDefault
) {
129 e
.cancelBubble
= true;
131 e
.returnValue
= false;
136 * Convert hsv values to an rgb(r,g,b) string. Taken from MochiKit.Color. This
137 * is used to generate default series colors which are evenly spaced on the
139 * @param { number } hue Range is 0.0-1.0.
140 * @param { number } saturation Range is 0.0-1.0.
141 * @param { number } value Range is 0.0-1.0.
142 * @return { string } "rgb(r,g,b)" where r, g and b range from 0-255.
145 export function hsvToRGB(hue
, saturation
, value
) {
149 if (saturation
=== 0) {
154 var i
= Math
.floor(hue
* 6);
155 var f
= (hue
* 6) - i
;
156 var p
= value
* (1 - saturation
);
157 var q
= value
* (1 - (saturation
* f
));
158 var t
= value
* (1 - (saturation
* (1 - f
)));
160 case 1: red
= q
; green
= value
; blue
= p
; break;
161 case 2: red
= p
; green
= value
; blue
= t
; break;
162 case 3: red
= p
; green
= q
; blue
= value
; break;
163 case 4: red
= t
; green
= p
; blue
= value
; break;
164 case 5: red
= value
; green
= p
; blue
= q
; break;
165 case 6: // fall through
166 case 0: red
= value
; green
= t
; blue
= p
; break;
169 red
= Math
.floor(255 * red
+ 0.5);
170 green
= Math
.floor(255 * green
+ 0.5);
171 blue
= Math
.floor(255 * blue
+ 0.5);
172 return 'rgb(' + red
+ ',' + green
+ ',' + blue
+ ')';
176 * Find the coordinates of an object relative to the top left of the page.
179 * @return {{x:number,y:number}}
182 export function findPos(obj
) {
183 var p
= obj
.getBoundingClientRect(),
185 d
= document
.documentElement
;
188 x
: p
.left
+ (w
.pageXOffset
|| d
.scrollLeft
),
189 y
: p
.top
+ (w
.pageYOffset
|| d
.scrollTop
)
194 * Returns the x-coordinate of the event in a coordinate system where the
195 * top-left corner of the page (not the window) is (0,0).
196 * Taken from MochiKit.Signal
201 export function pageX(e
) {
202 if (e
.isTouchOver
) return (!e
.changedTouches
[0] || e
.changedTouches
[0].pageX
< 0) ? 0 : e
.changedTouches
[0].pageX
;
203 return (!e
.pageX
|| e
.pageX
< 0) ? 0 : e
.pageX
;
207 * Returns the y-coordinate of the event in a coordinate system where the
208 * top-left corner of the page (not the window) is (0,0).
209 * Taken from MochiKit.Signal
214 export function pageY(e
) {
215 if (e
.isTouchOver
) return (!e
.changedTouches
[0] || e
.changedTouches
[0].pageY
< 0) ? 0 : e
.changedTouches
[0].pageY
;
216 return (!e
.pageY
|| e
.pageY
< 0) ? 0 : e
.pageY
;
220 * Converts page the x-coordinate of the event to pixel x-coordinates on the
221 * canvas (i.e. DOM Coords).
222 * @param {!Event} e Drag event.
223 * @param {!DygraphInteractionContext} context Interaction context object.
224 * @return {number} The amount by which the drag has moved to the right.
226 export function dragGetX_(e
, context
) {
227 return pageX(e
) - context
.px
;
231 * Converts page the y-coordinate of the event to pixel y-coordinates on the
232 * canvas (i.e. DOM Coords).
233 * @param {!Event} e Drag event.
234 * @param {!DygraphInteractionContext} context Interaction context object.
235 * @return {number} The amount by which the drag has moved down.
237 export function dragGetY_(e
, context
) {
238 return pageY(e
) - context
.py
;
242 * This returns true unless the parameter is 0, null, undefined or NaN.
243 * TODO(danvk): rename this function to something like 'isNonZeroNan'.
245 * @param {number} x The number to consider.
246 * @return {boolean} Whether the number is zero or NaN.
249 export function isOK(x
) {
250 return !!x
&& !isNaN(x
);
254 * @param {{x:?number,y:?number,yval:?number}} p The point to consider, valid
255 * points are {x, y} objects
256 * @param {boolean=} opt_allowNaNY Treat point with y=NaN as valid
257 * @return {boolean} Whether the point has numeric x and y.
260 export function isValidPoint(p
, opt_allowNaNY
) {
261 if (!p
) return false; // null or undefined object
262 if (p
.yval
=== null) return false; // missing point
263 if (p
.x
=== null || p
.x
=== undefined
) return false;
264 if (p
.y
=== null || p
.y
=== undefined
) return false;
265 if (isNaN(p
.x
) || (!opt_allowNaNY
&& isNaN(p
.y
))) return false;
270 * Number formatting function which mimics the behavior of %g in printf, i.e.
271 * either exponential or fixed format (without trailing 0s) is used depending on
272 * the length of the generated string. The advantage of this format is that
273 * there is a predictable upper bound on the resulting string length,
274 * significant figures are not dropped, and normal numbers are not displayed in
275 * exponential notation.
277 * NOTE: JavaScript's native toPrecision() is NOT a drop-in replacement for %g.
278 * It creates strings which are too long for absolute values between 10^-4 and
279 * 10^-6, e.g. '0.00001' instead of '1e-5'. See tests/number-format.html for
282 * @param {number} x The number to format
283 * @param {number=} opt_precision The precision to use, default 2.
284 * @return {string} A string formatted like %g in printf. The max generated
285 * string length should be precision + 6 (e.g 1.123e+300).
287 export function floatFormat(x
, opt_precision
) {
288 // Avoid invalid precision values; [1, 21] is the valid range.
289 var p
= Math
.min(Math
.max(1, opt_precision
|| 2), 21);
291 // This is deceptively simple. The actual algorithm comes from:
293 // Max allowed length = p + 4
294 // where 4 comes from 'e+n' and '.'.
296 // Length of fixed format = 2 + y + p
297 // where 2 comes from '0.' and y = # of leading zeroes.
299 // Equating the two and solving for y yields y = 2, or 0.00xxxx which is
302 // Since the behavior of toPrecision() is identical for larger numbers, we
303 // don't have to worry about the other bound.
305 // Finally, the argument for toExponential() is the number of trailing digits,
306 // so we take off 1 for the value before the '.'.
307 return (Math
.abs(x
) < 1.0e-3 && x
!== 0.0) ?
308 x
.toExponential(p
- 1) : x
.toPrecision(p
);
312 * Converts '9' to '09' (useful for dates)
317 export function zeropad(x
) {
318 if (x
< 10) return "0" + x
; else return "" + x
;
322 * Date accessors to get the parts of a calendar date (year, month,
323 * day, hour, minute, second and millisecond) according to local time,
324 * and factory method to call the Date constructor with an array of arguments.
326 export var DateAccessorsLocal
= {
327 getFullYear
: d
=> d
.getFullYear(),
328 getMonth
: d
=> d
.getMonth(),
329 getDate
: d
=> d
.getDate(),
330 getHours
: d
=> d
.getHours(),
331 getMinutes
: d
=> d
.getMinutes(),
332 getSeconds
: d
=> d
.getSeconds(),
333 getMilliseconds
: d
=> d
.getMilliseconds(),
334 getDay
: d
=> d
.getDay(),
335 makeDate
: function(y
, m
, d
, hh
, mm
, ss
, ms
) {
336 return new Date(y
, m
, d
, hh
, mm
, ss
, ms
);
341 * Date accessors to get the parts of a calendar date (year, month,
342 * day of month, hour, minute, second and millisecond) according to UTC time,
343 * and factory method to call the Date constructor with an array of arguments.
345 export var DateAccessorsUTC
= {
346 getFullYear
: d
=> d
.getUTCFullYear(),
347 getMonth
: d
=> d
.getUTCMonth(),
348 getDate
: d
=> d
.getUTCDate(),
349 getHours
: d
=> d
.getUTCHours(),
350 getMinutes
: d
=> d
.getUTCMinutes(),
351 getSeconds
: d
=> d
.getUTCSeconds(),
352 getMilliseconds
: d
=> d
.getUTCMilliseconds(),
353 getDay
: d
=> d
.getUTCDay(),
354 makeDate
: function(y
, m
, d
, hh
, mm
, ss
, ms
) {
355 return new Date(Date
.UTC(y
, m
, d
, hh
, mm
, ss
, ms
));
360 * Return a string version of the hours, minutes and seconds portion of a date.
361 * @param {number} hh The hours (from 0-23)
362 * @param {number} mm The minutes (from 0-59)
363 * @param {number} ss The seconds (from 0-59)
364 * @return {string} A time of the form "HH:MM" or "HH:MM:SS"
367 export function hmsString_(hh
, mm
, ss
, ms
) {
368 var ret
= zeropad(hh
) + ":" + zeropad(mm
);
370 ret
+= ":" + zeropad(ss
);
373 ret
+= "." + ('000'+str
).substring(str
.length
);
380 * Convert a JS date (millis since epoch) to a formatted string.
381 * @param {number} time The JavaScript time value (ms since epoch)
382 * @param {boolean} utc Whether output UTC or local time
383 * @return {string} A date of one of these forms:
384 * "YYYY/MM/DD", "YYYY/MM/DD HH:MM" or "YYYY/MM/DD HH:MM:SS"
387 export function dateString_(time
, utc
) {
388 var accessors
= utc
? DateAccessorsUTC
: DateAccessorsLocal
;
389 var date
= new Date(time
);
390 var y
= accessors
.getFullYear(date
);
391 var m
= accessors
.getMonth(date
);
392 var d
= accessors
.getDate(date
);
393 var hh
= accessors
.getHours(date
);
394 var mm
= accessors
.getMinutes(date
);
395 var ss
= accessors
.getSeconds(date
);
396 var ms
= accessors
.getMilliseconds(date
);
397 // Get a year string:
399 // Get a 0 padded month string
400 var month
= zeropad(m
+ 1); //months are 0-offset, sigh
401 // Get a 0 padded day string
402 var day
= zeropad(d
);
403 var frac
= hh
* 3600 + mm
* 60 + ss
+ 1e-3 * ms
;
404 var ret
= year
+ "/" + month + "/" + day
;
406 ret
+= " " + hmsString_(hh
, mm
, ss
, ms
);
412 * Round a number to the specified number of digits past the decimal point.
413 * @param {number} num The number to round
414 * @param {number} places The number of decimals to which to round
415 * @return {number} The rounded number
418 export function round_(num
, places
) {
419 var shift
= Math
.pow(10, places
);
420 return Math
.round(num
* shift
)/shift
;
424 * Implementation of binary search over an array.
425 * Currently does not work when val is outside the range of arry's values.
426 * @param {number} val the value to search for
427 * @param {Array.<number>} arry is the value over which to search
428 * @param {number} abs If abs > 0, find the lowest entry greater than val
429 * If abs < 0, find the highest entry less than val.
430 * If abs == 0, find the entry that equals val.
431 * @param {number=} low The first index in arry to consider (optional)
432 * @param {number=} high The last index in arry to consider (optional)
433 * @return {number} Index of the element, or -1 if it isn't found.
436 export function binarySearch(val
, arry
, abs
, low
, high
) {
437 if (low
=== null || low
=== undefined
||
438 high
=== null || high
=== undefined
) {
440 high
= arry
.length
- 1;
445 if (abs
=== null || abs
=== undefined
) {
448 var validIndex
= function(idx
) {
449 return idx
>= 0 && idx
< arry
.length
;
451 var mid
= parseInt((low
+ high
) / 2, 10);
452 var element
= arry
[mid
];
454 if (element
== val
) {
456 } else if (element
> val
) {
458 // Accept if element > val, but also if prior element < val.
460 if (validIndex(idx
) && arry
[idx
] < val
) {
464 return binarySearch(val
, arry
, abs
, low
, mid
- 1);
465 } else if (element
< val
) {
467 // Accept if element < val, but also if prior element > val.
469 if (validIndex(idx
) && arry
[idx
] > val
) {
473 return binarySearch(val
, arry
, abs
, mid
+ 1, high
);
475 return -1; // can't actually happen, but makes closure compiler happy
479 * Parses a date, returning the number of milliseconds since epoch. This can be
480 * passed in as an xValueParser in the Dygraph constructor.
481 * TODO(danvk): enumerate formats that this understands.
483 * @param {string} dateStr A date in a variety of possible string formats.
484 * @return {number} Milliseconds since epoch.
487 export function dateParser(dateStr
) {
491 // Let the system try the format first, with one caveat:
492 // YYYY-MM-DD[ HH:MM:SS] is interpreted as UTC by a variety of browsers.
493 // dygraphs displays dates in local time, so this will result in surprising
494 // inconsistencies. But if you specify "T" or "Z" (i.e. YYYY-MM-DDTHH:MM:SS),
495 // then you probably know what you're doing, so we'll let you go ahead.
496 // Issue: http://code.google.com/p/dygraphs/issues/detail
?id
=255
497 if (dateStr
.search("-") == -1 ||
498 dateStr
.search("T") != -1 || dateStr
.search("Z") != -1) {
499 d
= dateStrToMillis(dateStr
);
500 if (d
&& !isNaN(d
)) return d
;
503 if (dateStr
.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12'
504 dateStrSlashed
= dateStr
.replace("-", "/", "g");
505 while (dateStrSlashed
.search("-") != -1) {
506 dateStrSlashed
= dateStrSlashed
.replace("-", "/");
508 d
= dateStrToMillis(dateStrSlashed
);
509 } else if (dateStr
.length
== 8) { // e.g. '20090712'
510 // TODO(danvk): remove support for this format. It's confusing.
511 dateStrSlashed
= dateStr
.substr(0,4) + "/" + dateStr.substr(4,2) + "/" +
513 d
= dateStrToMillis(dateStrSlashed
);
515 // Any format that Date.parse will accept, e.g. "2009/07/12" or
516 // "2009/07/12 12:34:56"
517 d
= dateStrToMillis(dateStr
);
520 if (!d
|| isNaN(d
)) {
521 console
.error("Couldn't parse " + dateStr
+ " as a date");
527 * This is identical to JavaScript's built-in Date.parse() method, except that
528 * it doesn't get replaced with an incompatible method by aggressive JS
529 * libraries like MooTools or Joomla.
530 * @param {string} str The date string, e.g. "2011/05/06"
531 * @return {number} millis since epoch
534 export function dateStrToMillis(str
) {
535 return new Date(str
).getTime();
538 // These functions are all based on MochiKit.
540 * Copies all the properties from o to self.
542 * @param {!Object} self
546 export function update(self
, o
) {
547 if (typeof(o
) != 'undefined' && o
!== null) {
549 if (o
.hasOwnProperty(k
)) {
558 * Copies all the properties from o to self.
560 * @param {!Object} self
565 export function updateDeep(self
, o
) {
566 // Taken from http://stackoverflow.com/questions
/384286/javascript
-isdom
-how
-do-you
-check
-if-a
-javascript
-object
-is
-a
-dom
-object
569 typeof Node
=== "object" ? o
instanceof Node
:
570 typeof o
=== "object" && typeof o
.nodeType
=== "number" && typeof o
.nodeName
==="string"
574 if (typeof(o
) != 'undefined' && o
!== null) {
576 if (o
.hasOwnProperty(k
)) {
579 } else if (isArrayLike(o
[k
])) {
580 self
[k
] = o
[k
].slice();
581 } else if (isNode(o
[k
])) {
582 // DOM objects are shallowly-copied.
584 } else if (typeof(o
[k
]) == 'object') {
585 if (typeof(self
[k
]) != 'object' || self
[k
] === null) {
588 updateDeep(self
[k
], o
[k
]);
603 export function isArrayLike(o
) {
606 (typ
!= 'object' && !(typ
== 'function' &&
607 typeof(o
.item
) == 'function')) ||
609 typeof(o
.length
) != 'number' ||
622 export function isDateLike(o
) {
623 if (typeof(o
) != "object" || o
=== null ||
624 typeof(o
.getTime
) != 'function') {
631 * Note: this only seems to work for arrays.
636 export function clone(o
) {
637 // TODO(danvk): figure out how MochiKit's version works
639 for (var i
= 0; i
< o
.length
; i
++) {
640 if (isArrayLike(o
[i
])) {
650 * Create a new canvas element.
652 * @return {!HTMLCanvasElement}
655 export function createCanvas() {
656 return document
.createElement('canvas');
660 * Returns the context's pixel ratio, which is the ratio between the device
661 * pixel ratio and the backing store ratio. Typically this is 1 for conventional
662 * displays, and > 1 for HiDPI displays (such as the Retina MBP).
663 * See http://www.html5rocks.com/en/tutorials/canvas/hidpi/ for more details.
665 * @param {!CanvasRenderingContext2D} context The canvas's 2d context.
666 * @return {number} The ratio of the device pixel ratio and the backing store
667 * ratio for the specified context.
669 export function getContextPixelRatio(context
) {
671 var devicePixelRatio
= window
.devicePixelRatio
;
672 var backingStoreRatio
= context
.webkitBackingStorePixelRatio
||
673 context
.mozBackingStorePixelRatio
||
674 context
.msBackingStorePixelRatio
||
675 context
.oBackingStorePixelRatio
||
676 context
.backingStorePixelRatio
|| 1;
677 if (devicePixelRatio
!== undefined
) {
678 return devicePixelRatio
/ backingStoreRatio
;
680 // At least devicePixelRatio must be defined for this ratio to make sense.
681 // We default backingStoreRatio to 1: this does not exist on some browsers
682 // (i.e. desktop Chrome).
691 * TODO(danvk): use @template here when it's better supported for classes.
692 * @param {!Array} array
693 * @param {number} start
694 * @param {number} length
695 * @param {function(!Array,?):boolean=} predicate
698 export function Iterator(array
, start
, length
, predicate
) {
700 length
= length
|| array
.length
;
701 this.hasNext
= true; // Use to identify if there's another element.
702 this.peek
= null; // Use for look-ahead
705 this.predicate_
= predicate
;
706 this.end_
= Math
.min(array
.length
, start
+ length
);
707 this.nextIdx_
= start
- 1; // use -1 so initial advance works.
708 this.next(); // ignoring result.
714 Iterator
.prototype.next
= function() {
720 var nextIdx
= this.nextIdx_
+ 1;
722 while (nextIdx
< this.end_
) {
723 if (!this.predicate_
|| this.predicate_(this.array_
, nextIdx
)) {
724 this.peek
= this.array_
[nextIdx
];
730 this.nextIdx_
= nextIdx
;
732 this.hasNext
= false;
739 * Returns a new iterator over array, between indexes start and
740 * start + length, and only returns entries that pass the accept function
742 * @param {!Array} array the array to iterate over.
743 * @param {number} start the first index to iterate over, 0 if absent.
744 * @param {number} length the number of elements in the array to iterate over.
745 * This, along with start, defines a slice of the array, and so length
746 * doesn't imply the number of elements in the iterator when accept doesn't
747 * always accept all values. array.length when absent.
748 * @param {function(?):boolean=} opt_predicate a function that takes
749 * parameters array and idx, which returns true when the element should be
750 * returned. If omitted, all elements are accepted.
753 export function createIterator(array
, start
, length
, opt_predicate
) {
754 return new Iterator(array
, start
, length
, opt_predicate
);
757 // Shim layer with setTimeout fallback.
758 // From: http://paulirish.com/2011/requestanimationframe-for-smart-animating/
759 // Should be called with the window context:
760 // Dygraph.requestAnimFrame.call(window, function() {})
761 export var requestAnimFrame
= (function() {
762 return window
.requestAnimationFrame
||
763 window
.webkitRequestAnimationFrame
||
764 window
.mozRequestAnimationFrame
||
765 window
.oRequestAnimationFrame
||
766 window
.msRequestAnimationFrame
||
767 function (callback
) {
768 window
.setTimeout(callback
, 1000 / 60);
773 * Call a function at most maxFrames times at an attempted interval of
774 * framePeriodInMillis, then call a cleanup function once. repeatFn is called
775 * once immediately, then at most (maxFrames - 1) times asynchronously. If
776 * maxFrames==1, then cleanup_fn() is also called synchronously. This function
777 * is used to sequence animation.
778 * @param {function(number)} repeatFn Called repeatedly -- takes the frame
779 * number (from 0 to maxFrames-1) as an argument.
780 * @param {number} maxFrames The max number of times to call repeatFn
781 * @param {number} framePeriodInMillis Max requested time between frames.
782 * @param {function()} cleanupFn A function to call after all repeatFn calls.
785 export function repeatAndCleanup(repeatFn
, maxFrames
, framePeriodInMillis
,
788 var previousFrameNumber
;
789 var startTime
= new Date().getTime();
790 repeatFn(frameNumber
);
791 if (maxFrames
== 1) {
795 var maxFrameArg
= maxFrames
- 1;
798 if (frameNumber
>= maxFrames
) return;
799 requestAnimFrame
.call(window
, function() {
800 // Determine which frame to draw based on the delay so far. Will skip
801 // frames if necessary.
802 var currentTime
= new Date().getTime();
803 var delayInMillis
= currentTime
- startTime
;
804 previousFrameNumber
= frameNumber
;
805 frameNumber
= Math
.floor(delayInMillis
/ framePeriodInMillis
);
806 var frameDelta
= frameNumber
- previousFrameNumber
;
807 // If we predict that the subsequent repeatFn call will overshoot our
808 // total frame target, so our last call will cause a stutter, then jump to
809 // the last call immediately. If we're going to cause a stutter, better
810 // to do it faster than slower.
811 var predictOvershootStutter
= (frameNumber
+ frameDelta
) > maxFrameArg
;
812 if (predictOvershootStutter
|| (frameNumber
>= maxFrameArg
)) {
813 repeatFn(maxFrameArg
); // Ensure final call with maxFrameArg.
816 if (frameDelta
!== 0) { // Don't call repeatFn with duplicate frames.
817 repeatFn(frameNumber
);
825 // A whitelist of options that do not change pixel positions.
826 var pixelSafeOptions
= {
827 'annotationClickHandler': true,
828 'annotationDblClickHandler': true,
829 'annotationMouseOutHandler': true,
830 'annotationMouseOverHandler': true,
831 'axisLineColor': true,
832 'axisLineWidth': true,
833 'clickCallback': true,
834 'drawCallback': true,
835 'drawHighlightPointCallback': true,
837 'drawPointCallback': true,
840 'gridLineColor': true,
841 'gridLineWidth': true,
842 'hideOverlayOnMouseOut': true,
843 'highlightCallback': true,
844 'highlightCircleSize': true,
845 'interactionModel': true,
849 'labelsSeparateLines': true,
850 'labelsShowZeroValues': true,
852 'panEdgeFraction': true,
853 'pixelsPerYLabel': true,
854 'pointClickCallback': true,
856 'rangeSelectorPlotFillColor': true,
857 'rangeSelectorPlotFillGradientColor': true,
858 'rangeSelectorPlotStrokeColor': true,
859 'rangeSelectorBackgroundStrokeColor': true,
860 'rangeSelectorBackgroundLineWidth': true,
861 'rangeSelectorPlotLineWidth': true,
862 'rangeSelectorForegroundStrokeColor': true,
863 'rangeSelectorForegroundLineWidth': true,
864 'rangeSelectorAlpha': true,
865 'showLabelsOnHighlight': true,
868 'underlayCallback': true,
869 'unhighlightCallback': true,
874 * This function will scan the option list and determine if they
875 * require us to recalculate the pixel positions of each point.
876 * TODO: move this into dygraph-options.js
877 * @param {!Array.<string>} labels a list of options to check.
878 * @param {!Object} attrs
879 * @return {boolean} true if the graph needs new points else false.
882 export function isPixelChangingOptionList(labels
, attrs
) {
883 // Assume that we do not require new points.
884 // This will change to true if we actually do need new points.
886 // Create a dictionary of series names for faster lookup.
887 // If there are no labels, then the dictionary stays empty.
888 var seriesNamesDictionary
= { };
890 for (var i
= 1; i
< labels
.length
; i
++) {
891 seriesNamesDictionary
[labels
[i
]] = true;
895 // Scan through a flat (i.e. non-nested) object of options.
896 // Returns true/false depending on whether
new points are needed
.
897 var scanFlatOptions
= function(options
) {
898 for (var property
in options
) {
899 if (options
.hasOwnProperty(property
) &&
900 !pixelSafeOptions
[property
]) {
907 // Iterate through the list of updated options.
908 for (var property
in attrs
) {
909 if (!attrs
.hasOwnProperty(property
)) continue;
911 // Find out of this field is actually a series specific options list.
912 if (property
== 'highlightSeriesOpts' ||
913 (seriesNamesDictionary
[property
] && !attrs
.series
)) {
914 // This property value is a list of options for this series.
915 if (scanFlatOptions(attrs
[property
])) return true;
916 } else if (property
== 'series' || property
== 'axes') {
917 // This is twice-nested options list.
918 var perSeries
= attrs
[property
];
919 for (var series
in perSeries
) {
920 if (perSeries
.hasOwnProperty(series
) &&
921 scanFlatOptions(perSeries
[series
])) {
926 // If this was not a series specific option list, check if it's a pixel
927 // changing property.
928 if (!pixelSafeOptions
[property
]) return true;
935 export var Circles
= {
936 DEFAULT
: function(g
, name
, ctx
, canvasx
, canvasy
, color
, radius
) {
938 ctx
.fillStyle
= color
;
939 ctx
.arc(canvasx
, canvasy
, radius
, 0, 2 * Math
.PI
, false);
942 // For more shapes, include extras/shapes.js
946 * Determine whether |data| is delimited by CR, CRLF, LF, LFCR.
947 * @param {string} data
948 * @return {?string} the delimiter that was detected (or null on failure).
950 export function detectLineDelimiter(data
) {
951 for (var i
= 0; i
< data
.length
; i
++) {
952 var code
= data
.charAt(i
);
954 // Might actually be "\r\n".
955 if (((i
+ 1) < data
.length
) && (data
.charAt(i
+ 1) === '\n')) {
961 // Might actually be "\n\r".
962 if (((i
+ 1) < data
.length
) && (data
.charAt(i
+ 1) === '\r')) {
973 * Is one node contained by another?
974 * @param {Node} containee The contained node.
975 * @param {Node} container The container node.
976 * @return {boolean} Whether containee is inside (or equal to) container.
979 export function isNodeContainedBy(containee
, container
) {
980 if (container
=== null || containee
=== null) {
983 var containeeNode
= /** @type {Node} */ (containee
);
984 while (containeeNode
&& containeeNode
!== container
) {
985 containeeNode
= containeeNode
.parentNode
;
987 return (containeeNode
=== container
);
990 // This masks some numeric issues in older versions of Firefox,
991 // where 1.0/Math
.pow(10,2) != Math
.pow(10,-2).
992 /** @type {function(number,number):number} */
993 export function pow(base
, exp
) {
995 return 1.0 / Math
.pow(base
, -exp
);
997 return Math
.pow(base
, exp
);
1000 var RGBA_RE
= /^rgba?\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})(?:,\s*([01](?:\.\d+)?))?\)$/;
1003 * Helper for toRGB_ which parses strings of the form:
1005 * rgba(123, 45, 67, 0.5)
1006 * @return parsed {r,g,b,a?} tuple or null.
1008 function parseRGBA(rgbStr
) {
1009 var bits
= RGBA_RE
.exec(rgbStr
);
1010 if (!bits
) return null;
1011 var r
= parseInt(bits
[1], 10),
1012 g
= parseInt(bits
[2], 10),
1013 b
= parseInt(bits
[3], 10);
1015 return {r
: r
, g
: g
, b
: b
, a
: parseFloat(bits
[4])};
1017 return {r
: r
, g
: g
, b
: b
};
1022 * Converts any valid CSS color (hex, rgb(), named color) to an RGB tuple.
1024 * @param {!string} colorStr Any valid CSS color string.
1025 * @return {{r:number,g:number,b:number,a:number?}} Parsed RGB tuple.
1028 export function toRGB_(colorStr
) {
1029 // Strategy: First try to parse colorStr directly. This is fast & avoids DOM
1030 // manipulation. If that fails (e.g. for named colors like 'red'), then
1031 // create a hidden DOM element and parse its computed color.
1032 var rgb
= parseRGBA(colorStr
);
1033 if (rgb
) return rgb
;
1035 var div
= document
.createElement('div');
1036 div
.style
.backgroundColor
= colorStr
;
1037 div
.style
.visibility
= 'hidden';
1038 document
.body
.appendChild(div
);
1039 var rgbStr
= window
.getComputedStyle(div
, null).backgroundColor
;
1040 document
.body
.removeChild(div
);
1041 return parseRGBA(rgbStr
);
1045 * Checks whether the browser supports the <canvas> tag.
1046 * @param {HTMLCanvasElement=} opt_canvasElement Pass a canvas element as an
1047 * optimization if you have one.
1048 * @return {boolean} Whether the browser supports canvas.
1050 export function isCanvasSupported(opt_canvasElement
) {
1052 var canvas
= opt_canvasElement
|| document
.createElement("canvas");
1053 canvas
.getContext("2d");
1061 * Parses the value as a floating point number. This is like the parseFloat()
1062 * built-in, but with a few differences:
1063 * - the empty string is parsed as null, rather than NaN.
1064 * - if the string cannot be parsed at all, an error is logged.
1065 * If the string can't be parsed, this method returns null.
1066 * @param {string} x The string to be parsed
1067 * @param {number=} opt_line_no The line number from which the string comes.
1068 * @param {string=} opt_line The text of the line from which the string comes.
1070 export function parseFloat_(x
, opt_line_no
, opt_line
) {
1071 var val
= parseFloat(x
);
1072 if (!isNaN(val
)) return val
;
1074 // Try to figure out what happeend.
1075 // If the value is the empty string, parse it as null.
1076 if (/^ *$/.test(x
)) return null;
1078 // If it was actually "NaN", return it as NaN.
1079 if (/^ *nan *$/i.test(x
)) return NaN
;
1081 // Looks like a parsing error.
1082 var msg
= "Unable to parse '" + x
+ "' as a number";
1083 if (opt_line
!== undefined
&& opt_line_no
!== undefined
) {
1084 msg
+= " on line " + (1+(opt_line_no
||0)) + " ('" + opt_line
+ "') of CSV.";
1092 // Label constants for the labelsKMB and labelsKMG2 options.
1093 // (i.e. '100000' -> '100K')
1094 var KMB_LABELS
= [ 'K', 'M', 'B', 'T', 'Q' ];
1095 var KMG2_BIG_LABELS
= [ 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y' ];
1096 var KMG2_SMALL_LABELS
= [ 'm', 'u', 'n', 'p', 'f', 'a', 'z', 'y' ];
1100 * Return a string version of a number. This respects the digitsAfterDecimal
1101 * and maxNumberWidth options.
1102 * @param {number} x The number to be formatted
1103 * @param {Dygraph} opts An options view
1105 export function numberValueFormatter(x
, opts
) {
1106 var sigFigs
= opts('sigFigs');
1108 if (sigFigs
!== null) {
1109 // User has opted for a fixed number of significant figures.
1110 return floatFormat(x
, sigFigs
);
1113 var digits
= opts('digitsAfterDecimal');
1114 var maxNumberWidth
= opts('maxNumberWidth');
1116 var kmb
= opts('labelsKMB');
1117 var kmg2
= opts('labelsKMG2');
1121 // switch to scientific notation if we underflow or overflow fixed display.
1123 (Math
.abs(x
) >= Math
.pow(10, maxNumberWidth
) ||
1124 Math
.abs(x
) < Math
.pow(10, -digits
))) {
1125 label
= x
.toExponential(digits
);
1127 label
= '' + round_(x
, digits
);
1136 k_labels
= KMB_LABELS
;
1139 if (kmb
) console
.warn("Setting both labelsKMB and labelsKMG2. Pick one!");
1141 k_labels
= KMG2_BIG_LABELS
;
1142 m_labels
= KMG2_SMALL_LABELS
;
1145 var absx
= Math
.abs(x
);
1146 var n
= pow(k
, k_labels
.length
);
1147 for (var j
= k_labels
.length
- 1; j
>= 0; j
--, n
/= k
) {
1149 label
= round_(x
/ n
, digits
) + k_labels
[j
];
1154 // TODO(danvk): clean up this logic. Why so different than kmb?
1155 var x_parts
= String(x
.toExponential()).split('e-');
1156 if (x_parts
.length
=== 2 && x_parts
[1] >= 3 && x_parts
[1] <= 24) {
1157 if (x_parts
[1] % 3 > 0) {
1158 label
= round_(x_parts
[0] /
1159 pow(10, (x_parts
[1] % 3)),
1162 label
= Number(x_parts
[0]).toFixed(2);
1164 label
+= m_labels
[Math
.floor(x_parts
[1] / 3) - 1];
1173 * variant for use as an axisLabelFormatter.
1176 export function numberAxisLabelFormatter(x
, granularity
, opts
) {
1177 return numberValueFormatter
.call(this, x
, opts
);
1181 * @type {!Array.<string>}
1185 var SHORT_MONTH_NAMES_
= ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
1189 * Convert a JS date to a string appropriate to display on an axis that
1190 * is displaying values at the stated granularity. This respects the
1192 * @param {Date} date The date to format
1193 * @param {number} granularity One of the Dygraph granularity constants
1194 * @param {Dygraph} opts An options view
1195 * @return {string} The date formatted as local time
1198 export function dateAxisLabelFormatter(date
, granularity
, opts
) {
1199 var utc
= opts('labelsUTC');
1200 var accessors
= utc
? DateAccessorsUTC
: DateAccessorsLocal
;
1202 var year
= accessors
.getFullYear(date
),
1203 month
= accessors
.getMonth(date
),
1204 day
= accessors
.getDate(date
),
1205 hours
= accessors
.getHours(date
),
1206 mins
= accessors
.getMinutes(date
),
1207 secs
= accessors
.getSeconds(date
),
1208 millis
= accessors
.getMilliseconds(date
);
1210 if (granularity
>= DygraphTickers
.Granularity
.DECADAL
) {
1212 } else if (granularity
>= DygraphTickers
.Granularity
.MONTHLY
) {
1213 return SHORT_MONTH_NAMES_
[month
] + ' ' + year
;
1215 var frac
= hours
* 3600 + mins
* 60 + secs
+ 1e-3 * millis
;
1216 if (frac
=== 0 || granularity
>= DygraphTickers
.Granularity
.DAILY
) {
1217 // e.g. '21 Jan' (%d%b)
1218 return zeropad(day
) + ' ' + SHORT_MONTH_NAMES_
[month
];
1219 } else if (granularity
< DygraphTickers
.Granularity
.SECONDLY
) {
1220 // e.g. 40.310 (meaning 40 seconds and 310 milliseconds)
1221 var str
= "" + millis
;
1222 return zeropad(secs
) + "." + ('000'+str
).substring(str
.length
);
1223 } else if (granularity
> DygraphTickers
.Granularity
.MINUTELY
) {
1224 return hmsString_(hours
, mins
, secs
, 0);
1226 return hmsString_(hours
, mins
, secs
, millis
);
1230 // alias in case anyone is referencing the old method.
1231 // Dygraph.dateAxisFormatter = Dygraph.dateAxisLabelFormatter;
1234 * Return a string version of a JS date for a value label. This respects the
1236 * @param {Date} date The date to be formatted
1237 * @param {Dygraph} opts An options view
1240 export function dateValueFormatter(d
, opts
) {
1241 return dateString_(d
, opts('labelsUTC'));