[Feature Request] Provide option to set color and width for annotation line (#703)
[dygraphs.git] / src / 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/*global Dygraph:false, Node:false */
15"use strict";
16
17import * as DygraphTickers from './dygraph-tickers';
18
19export var LOG_SCALE = 10;
20export var LN_TEN = Math.log(LOG_SCALE);
21
22/**
23 * @private
24 * @param {number} x
25 * @return {number}
26 */
27export var log10 = function(x) {
28 return Math.log(x) / LN_TEN;
29};
30
31/**
32 * @private
33 * @param {number} r0
34 * @param {number} r1
35 * @param {number} pct
36 * @return {number}
37 */
38export var logRangeFraction = function(r0, r1, pct) {
39 // Computing the inverse of toPercentXCoord. The function was arrived at with
40 // the following steps:
41 //
42 // Original calcuation:
43 // pct = (log(x) - log(xRange[0])) / (log(xRange[1]) - log(xRange[0])));
44 //
45 // Multiply both sides by the right-side demoninator.
46 // pct * (log(xRange[1] - log(xRange[0]))) = log(x) - log(xRange[0])
47 //
48 // add log(xRange[0]) to both sides
49 // log(xRange[0]) + (pct * (log(xRange[1]) - log(xRange[0])) = log(x);
50 //
51 // Swap both sides of the equation,
52 // log(x) = log(xRange[0]) + (pct * (log(xRange[1]) - log(xRange[0]))
53 //
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])))
56
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);
61 return value;
62};
63
64/** A dotted line stroke pattern. */
65export var DOTTED_LINE = [2, 2];
66/** A dashed line stroke pattern. */
67export var DASHED_LINE = [7, 3];
68/** A dot dash stroke pattern. */
69export var DOT_DASH_LINE = [7, 2, 2, 2];
70
71// Directions for panning and zooming. Use bit operations when combined
72// values are possible.
73export var HORIZONTAL = 1;
74export var VERTICAL = 2;
75
76/**
77 * Return the 2d context for a dygraph canvas.
78 *
79 * This method is only exposed for the sake of replacing the function in
80 * automated tests.
81 *
82 * @param {!HTMLCanvasElement} canvas
83 * @return {!CanvasRenderingContext2D}
84 * @private
85 */
86export var getContext = function(canvas) {
87 return /** @type{!CanvasRenderingContext2D}*/(canvas.getContext("2d"));
88};
89
90/**
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.
96 * @private
97 */
98export var addEvent = function addEvent(elem, type, fn) {
99 elem.addEventListener(type, fn, false);
100};
101
102/**
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.
108 */
109export function removeEvent(elem, type, fn) {
110 elem.removeEventListener(type, fn, false);
111};
112
113/**
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.
119 * @private
120 */
121export function cancelEvent(e) {
122 e = e ? e : window.event;
123 if (e.stopPropagation) {
124 e.stopPropagation();
125 }
126 if (e.preventDefault) {
127 e.preventDefault();
128 }
129 e.cancelBubble = true;
130 e.cancel = true;
131 e.returnValue = false;
132 return false;
133};
134
135/**
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
138 * color wheel.
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.
143 * @private
144 */
145export function hsvToRGB(hue, saturation, value) {
146 var red;
147 var green;
148 var blue;
149 if (saturation === 0) {
150 red = value;
151 green = value;
152 blue = value;
153 } else {
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)));
159 switch (i) {
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;
167 }
168 }
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 + ')';
173};
174
175/**
176 * Find the coordinates of an object relative to the top left of the page.
177 *
178 * @param {Node} obj
179 * @return {{x:number,y:number}}
180 * @private
181 */
182export function findPos(obj) {
183 var p = obj.getBoundingClientRect(),
184 w = window,
185 d = document.documentElement;
186
187 return {
188 x: p.left + (w.pageXOffset || d.scrollLeft),
189 y: p.top + (w.pageYOffset || d.scrollTop)
190 }
191};
192
193/**
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
197 * @param {!Event} e
198 * @return {number}
199 * @private
200 */
201export function pageX(e) {
202 return (!e.pageX || e.pageX < 0) ? 0 : e.pageX;
203};
204
205/**
206 * Returns the y-coordinate of the event in a coordinate system where the
207 * top-left corner of the page (not the window) is (0,0).
208 * Taken from MochiKit.Signal
209 * @param {!Event} e
210 * @return {number}
211 * @private
212 */
213export function pageY(e) {
214 return (!e.pageY || e.pageY < 0) ? 0 : e.pageY;
215};
216
217/**
218 * Converts page the x-coordinate of the event to pixel x-coordinates on the
219 * canvas (i.e. DOM Coords).
220 * @param {!Event} e Drag event.
221 * @param {!DygraphInteractionContext} context Interaction context object.
222 * @return {number} The amount by which the drag has moved to the right.
223 */
224export function dragGetX_(e, context) {
225 return pageX(e) - context.px;
226};
227
228/**
229 * Converts page the y-coordinate of the event to pixel y-coordinates on the
230 * canvas (i.e. DOM Coords).
231 * @param {!Event} e Drag event.
232 * @param {!DygraphInteractionContext} context Interaction context object.
233 * @return {number} The amount by which the drag has moved down.
234 */
235export function dragGetY_(e, context) {
236 return pageY(e) - context.py;
237};
238
239/**
240 * This returns true unless the parameter is 0, null, undefined or NaN.
241 * TODO(danvk): rename this function to something like 'isNonZeroNan'.
242 *
243 * @param {number} x The number to consider.
244 * @return {boolean} Whether the number is zero or NaN.
245 * @private
246 */
247export function isOK(x) {
248 return !!x && !isNaN(x);
249};
250
251/**
252 * @param {{x:?number,y:?number,yval:?number}} p The point to consider, valid
253 * points are {x, y} objects
254 * @param {boolean=} opt_allowNaNY Treat point with y=NaN as valid
255 * @return {boolean} Whether the point has numeric x and y.
256 * @private
257 */
258export function isValidPoint(p, opt_allowNaNY) {
259 if (!p) return false; // null or undefined object
260 if (p.yval === null) return false; // missing point
261 if (p.x === null || p.x === undefined) return false;
262 if (p.y === null || p.y === undefined) return false;
263 if (isNaN(p.x) || (!opt_allowNaNY && isNaN(p.y))) return false;
264 return true;
265};
266
267/**
268 * Number formatting function which mimicks the behavior of %g in printf, i.e.
269 * either exponential or fixed format (without trailing 0s) is used depending on
270 * the length of the generated string. The advantage of this format is that
271 * there is a predictable upper bound on the resulting string length,
272 * significant figures are not dropped, and normal numbers are not displayed in
273 * exponential notation.
274 *
275 * NOTE: JavaScript's native toPrecision() is NOT a drop-in replacement for %g.
276 * It creates strings which are too long for absolute values between 10^-4 and
277 * 10^-6, e.g. '0.00001' instead of '1e-5'. See tests/number-format.html for
278 * output examples.
279 *
280 * @param {number} x The number to format
281 * @param {number=} opt_precision The precision to use, default 2.
282 * @return {string} A string formatted like %g in printf. The max generated
283 * string length should be precision + 6 (e.g 1.123e+300).
284 */
285export function floatFormat(x, opt_precision) {
286 // Avoid invalid precision values; [1, 21] is the valid range.
287 var p = Math.min(Math.max(1, opt_precision || 2), 21);
288
289 // This is deceptively simple. The actual algorithm comes from:
290 //
291 // Max allowed length = p + 4
292 // where 4 comes from 'e+n' and '.'.
293 //
294 // Length of fixed format = 2 + y + p
295 // where 2 comes from '0.' and y = # of leading zeroes.
296 //
297 // Equating the two and solving for y yields y = 2, or 0.00xxxx which is
298 // 1.0e-3.
299 //
300 // Since the behavior of toPrecision() is identical for larger numbers, we
301 // don't have to worry about the other bound.
302 //
303 // Finally, the argument for toExponential() is the number of trailing digits,
304 // so we take off 1 for the value before the '.'.
305 return (Math.abs(x) < 1.0e-3 && x !== 0.0) ?
306 x.toExponential(p - 1) : x.toPrecision(p);
307};
308
309/**
310 * Converts '9' to '09' (useful for dates)
311 * @param {number} x
312 * @return {string}
313 * @private
314 */
315export function zeropad(x) {
316 if (x < 10) return "0" + x; else return "" + x;
317};
318
319/**
320 * Date accessors to get the parts of a calendar date (year, month,
321 * day, hour, minute, second and millisecond) according to local time,
322 * and factory method to call the Date constructor with an array of arguments.
323 */
324export var DateAccessorsLocal = {
325 getFullYear: d => d.getFullYear(),
326 getMonth: d => d.getMonth(),
327 getDate: d => d.getDate(),
328 getHours: d => d.getHours(),
329 getMinutes: d => d.getMinutes(),
330 getSeconds: d => d.getSeconds(),
331 getMilliseconds: d => d.getMilliseconds(),
332 getDay: d => d.getDay(),
333 makeDate: function(y, m, d, hh, mm, ss, ms) {
334 return new Date(y, m, d, hh, mm, ss, ms);
335 }
336};
337
338/**
339 * Date accessors to get the parts of a calendar date (year, month,
340 * day of month, hour, minute, second and millisecond) according to UTC time,
341 * and factory method to call the Date constructor with an array of arguments.
342 */
343export var DateAccessorsUTC = {
344 getFullYear: d => d.getUTCFullYear(),
345 getMonth: d => d.getUTCMonth(),
346 getDate: d => d.getUTCDate(),
347 getHours: d => d.getUTCHours(),
348 getMinutes: d => d.getUTCMinutes(),
349 getSeconds: d => d.getUTCSeconds(),
350 getMilliseconds: d => d.getUTCMilliseconds(),
351 getDay: d => d.getUTCDay(),
352 makeDate: function(y, m, d, hh, mm, ss, ms) {
353 return new Date(Date.UTC(y, m, d, hh, mm, ss, ms));
354 }
355};
356
357/**
358 * Return a string version of the hours, minutes and seconds portion of a date.
359 * @param {number} hh The hours (from 0-23)
360 * @param {number} mm The minutes (from 0-59)
361 * @param {number} ss The seconds (from 0-59)
362 * @return {string} A time of the form "HH:MM" or "HH:MM:SS"
363 * @private
364 */
365export function hmsString_(hh, mm, ss, ms) {
366 var ret = zeropad(hh) + ":" + zeropad(mm);
367 if (ss) {
368 ret += ":" + zeropad(ss);
369 if (ms) {
370 var str = "" + ms;
371 ret += "." + ('000'+str).substring(str.length);
372 }
373 }
374 return ret;
375};
376
377/**
378 * Convert a JS date (millis since epoch) to a formatted string.
379 * @param {number} time The JavaScript time value (ms since epoch)
380 * @param {boolean} utc Wether output UTC or local time
381 * @return {string} A date of one of these forms:
382 * "YYYY/MM/DD", "YYYY/MM/DD HH:MM" or "YYYY/MM/DD HH:MM:SS"
383 * @private
384 */
385export function dateString_(time, utc) {
386 var accessors = utc ? DateAccessorsUTC : DateAccessorsLocal;
387 var date = new Date(time);
388 var y = accessors.getFullYear(date);
389 var m = accessors.getMonth(date);
390 var d = accessors.getDate(date);
391 var hh = accessors.getHours(date);
392 var mm = accessors.getMinutes(date);
393 var ss = accessors.getSeconds(date);
394 var ms = accessors.getMilliseconds(date);
395 // Get a year string:
396 var year = "" + y;
397 // Get a 0 padded month string
398 var month = zeropad(m + 1); //months are 0-offset, sigh
399 // Get a 0 padded day string
400 var day = zeropad(d);
401 var frac = hh * 3600 + mm * 60 + ss + 1e-3 * ms;
402 var ret = year + "/" + month + "/" + day;
403 if (frac) {
404 ret += " " + hmsString_(hh, mm, ss, ms);
405 }
406 return ret;
407};
408
409/**
410 * Round a number to the specified number of digits past the decimal point.
411 * @param {number} num The number to round
412 * @param {number} places The number of decimals to which to round
413 * @return {number} The rounded number
414 * @private
415 */
416export function round_(num, places) {
417 var shift = Math.pow(10, places);
418 return Math.round(num * shift)/shift;
419};
420
421/**
422 * Implementation of binary search over an array.
423 * Currently does not work when val is outside the range of arry's values.
424 * @param {number} val the value to search for
425 * @param {Array.<number>} arry is the value over which to search
426 * @param {number} abs If abs > 0, find the lowest entry greater than val
427 * If abs < 0, find the highest entry less than val.
428 * If abs == 0, find the entry that equals val.
429 * @param {number=} low The first index in arry to consider (optional)
430 * @param {number=} high The last index in arry to consider (optional)
431 * @return {number} Index of the element, or -1 if it isn't found.
432 * @private
433 */
434export function binarySearch(val, arry, abs, low, high) {
435 if (low === null || low === undefined ||
436 high === null || high === undefined) {
437 low = 0;
438 high = arry.length - 1;
439 }
440 if (low > high) {
441 return -1;
442 }
443 if (abs === null || abs === undefined) {
444 abs = 0;
445 }
446 var validIndex = function(idx) {
447 return idx >= 0 && idx < arry.length;
448 };
449 var mid = parseInt((low + high) / 2, 10);
450 var element = arry[mid];
451 var idx;
452 if (element == val) {
453 return mid;
454 } else if (element > val) {
455 if (abs > 0) {
456 // Accept if element > val, but also if prior element < val.
457 idx = mid - 1;
458 if (validIndex(idx) && arry[idx] < val) {
459 return mid;
460 }
461 }
462 return binarySearch(val, arry, abs, low, mid - 1);
463 } else if (element < val) {
464 if (abs < 0) {
465 // Accept if element < val, but also if prior element > val.
466 idx = mid + 1;
467 if (validIndex(idx) && arry[idx] > val) {
468 return mid;
469 }
470 }
471 return binarySearch(val, arry, abs, mid + 1, high);
472 }
473 return -1; // can't actually happen, but makes closure compiler happy
474};
475
476/**
477 * Parses a date, returning the number of milliseconds since epoch. This can be
478 * passed in as an xValueParser in the Dygraph constructor.
479 * TODO(danvk): enumerate formats that this understands.
480 *
481 * @param {string} dateStr A date in a variety of possible string formats.
482 * @return {number} Milliseconds since epoch.
483 * @private
484 */
485export function dateParser(dateStr) {
486 var dateStrSlashed;
487 var d;
488
489 // Let the system try the format first, with one caveat:
490 // YYYY-MM-DD[ HH:MM:SS] is interpreted as UTC by a variety of browsers.
491 // dygraphs displays dates in local time, so this will result in surprising
492 // inconsistencies. But if you specify "T" or "Z" (i.e. YYYY-MM-DDTHH:MM:SS),
493 // then you probably know what you're doing, so we'll let you go ahead.
494 // Issue: http://code.google.com/p/dygraphs/issues/detail?id=255
495 if (dateStr.search("-") == -1 ||
496 dateStr.search("T") != -1 || dateStr.search("Z") != -1) {
497 d = dateStrToMillis(dateStr);
498 if (d && !isNaN(d)) return d;
499 }
500
501 if (dateStr.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12'
502 dateStrSlashed = dateStr.replace("-", "/", "g");
503 while (dateStrSlashed.search("-") != -1) {
504 dateStrSlashed = dateStrSlashed.replace("-", "/");
505 }
506 d = dateStrToMillis(dateStrSlashed);
507 } else if (dateStr.length == 8) { // e.g. '20090712'
508 // TODO(danvk): remove support for this format. It's confusing.
509 dateStrSlashed = dateStr.substr(0,4) + "/" + dateStr.substr(4,2) + "/" +
510 dateStr.substr(6,2);
511 d = dateStrToMillis(dateStrSlashed);
512 } else {
513 // Any format that Date.parse will accept, e.g. "2009/07/12" or
514 // "2009/07/12 12:34:56"
515 d = dateStrToMillis(dateStr);
516 }
517
518 if (!d || isNaN(d)) {
519 console.error("Couldn't parse " + dateStr + " as a date");
520 }
521 return d;
522};
523
524/**
525 * This is identical to JavaScript's built-in Date.parse() method, except that
526 * it doesn't get replaced with an incompatible method by aggressive JS
527 * libraries like MooTools or Joomla.
528 * @param {string} str The date string, e.g. "2011/05/06"
529 * @return {number} millis since epoch
530 * @private
531 */
532export function dateStrToMillis(str) {
533 return new Date(str).getTime();
534};
535
536// These functions are all based on MochiKit.
537/**
538 * Copies all the properties from o to self.
539 *
540 * @param {!Object} self
541 * @param {!Object} o
542 * @return {!Object}
543 */
544export function update(self, o) {
545 if (typeof(o) != 'undefined' && o !== null) {
546 for (var k in o) {
547 if (o.hasOwnProperty(k)) {
548 self[k] = o[k];
549 }
550 }
551 }
552 return self;
553};
554
555/**
556 * Copies all the properties from o to self.
557 *
558 * @param {!Object} self
559 * @param {!Object} o
560 * @return {!Object}
561 * @private
562 */
563export function updateDeep(self, o) {
564 // Taken from http://stackoverflow.com/questions/384286/javascript-isdom-how-do-you-check-if-a-javascript-object-is-a-dom-object
565 function isNode(o) {
566 return (
567 typeof Node === "object" ? o instanceof Node :
568 typeof o === "object" && typeof o.nodeType === "number" && typeof o.nodeName==="string"
569 );
570 }
571
572 if (typeof(o) != 'undefined' && o !== null) {
573 for (var k in o) {
574 if (o.hasOwnProperty(k)) {
575 if (o[k] === null) {
576 self[k] = null;
577 } else if (isArrayLike(o[k])) {
578 self[k] = o[k].slice();
579 } else if (isNode(o[k])) {
580 // DOM objects are shallowly-copied.
581 self[k] = o[k];
582 } else if (typeof(o[k]) == 'object') {
583 if (typeof(self[k]) != 'object' || self[k] === null) {
584 self[k] = {};
585 }
586 updateDeep(self[k], o[k]);
587 } else {
588 self[k] = o[k];
589 }
590 }
591 }
592 }
593 return self;
594};
595
596/**
597 * @param {*} o
598 * @return {boolean}
599 * @private
600 */
601export function isArrayLike(o) {
602 var typ = typeof(o);
603 if (
604 (typ != 'object' && !(typ == 'function' &&
605 typeof(o.item) == 'function')) ||
606 o === null ||
607 typeof(o.length) != 'number' ||
608 o.nodeType === 3
609 ) {
610 return false;
611 }
612 return true;
613};
614
615/**
616 * @param {Object} o
617 * @return {boolean}
618 * @private
619 */
620export function isDateLike(o) {
621 if (typeof(o) != "object" || o === null ||
622 typeof(o.getTime) != 'function') {
623 return false;
624 }
625 return true;
626};
627
628/**
629 * Note: this only seems to work for arrays.
630 * @param {!Array} o
631 * @return {!Array}
632 * @private
633 */
634export function clone(o) {
635 // TODO(danvk): figure out how MochiKit's version works
636 var r = [];
637 for (var i = 0; i < o.length; i++) {
638 if (isArrayLike(o[i])) {
639 r.push(clone(o[i]));
640 } else {
641 r.push(o[i]);
642 }
643 }
644 return r;
645};
646
647/**
648 * Create a new canvas element.
649 *
650 * @return {!HTMLCanvasElement}
651 * @private
652 */
653export function createCanvas() {
654 return document.createElement('canvas');
655};
656
657/**
658 * Returns the context's pixel ratio, which is the ratio between the device
659 * pixel ratio and the backing store ratio. Typically this is 1 for conventional
660 * displays, and > 1 for HiDPI displays (such as the Retina MBP).
661 * See http://www.html5rocks.com/en/tutorials/canvas/hidpi/ for more details.
662 *
663 * @param {!CanvasRenderingContext2D} context The canvas's 2d context.
664 * @return {number} The ratio of the device pixel ratio and the backing store
665 * ratio for the specified context.
666 */
667export function getContextPixelRatio(context) {
668 try {
669 var devicePixelRatio = window.devicePixelRatio;
670 var backingStoreRatio = context.webkitBackingStorePixelRatio ||
671 context.mozBackingStorePixelRatio ||
672 context.msBackingStorePixelRatio ||
673 context.oBackingStorePixelRatio ||
674 context.backingStorePixelRatio || 1;
675 if (devicePixelRatio !== undefined) {
676 return devicePixelRatio / backingStoreRatio;
677 } else {
678 // At least devicePixelRatio must be defined for this ratio to make sense.
679 // We default backingStoreRatio to 1: this does not exist on some browsers
680 // (i.e. desktop Chrome).
681 return 1;
682 }
683 } catch (e) {
684 return 1;
685 }
686};
687
688/**
689 * TODO(danvk): use @template here when it's better supported for classes.
690 * @param {!Array} array
691 * @param {number} start
692 * @param {number} length
693 * @param {function(!Array,?):boolean=} predicate
694 * @constructor
695 */
696export function Iterator(array, start, length, predicate) {
697 start = start || 0;
698 length = length || array.length;
699 this.hasNext = true; // Use to identify if there's another element.
700 this.peek = null; // Use for look-ahead
701 this.start_ = start;
702 this.array_ = array;
703 this.predicate_ = predicate;
704 this.end_ = Math.min(array.length, start + length);
705 this.nextIdx_ = start - 1; // use -1 so initial advance works.
706 this.next(); // ignoring result.
707};
708
709/**
710 * @return {Object}
711 */
712Iterator.prototype.next = function() {
713 if (!this.hasNext) {
714 return null;
715 }
716 var obj = this.peek;
717
718 var nextIdx = this.nextIdx_ + 1;
719 var found = false;
720 while (nextIdx < this.end_) {
721 if (!this.predicate_ || this.predicate_(this.array_, nextIdx)) {
722 this.peek = this.array_[nextIdx];
723 found = true;
724 break;
725 }
726 nextIdx++;
727 }
728 this.nextIdx_ = nextIdx;
729 if (!found) {
730 this.hasNext = false;
731 this.peek = null;
732 }
733 return obj;
734};
735
736/**
737 * Returns a new iterator over array, between indexes start and
738 * start + length, and only returns entries that pass the accept function
739 *
740 * @param {!Array} array the array to iterate over.
741 * @param {number} start the first index to iterate over, 0 if absent.
742 * @param {number} length the number of elements in the array to iterate over.
743 * This, along with start, defines a slice of the array, and so length
744 * doesn't imply the number of elements in the iterator when accept doesn't
745 * always accept all values. array.length when absent.
746 * @param {function(?):boolean=} opt_predicate a function that takes
747 * parameters array and idx, which returns true when the element should be
748 * returned. If omitted, all elements are accepted.
749 * @private
750 */
751export function createIterator(array, start, length, opt_predicate) {
752 return new Iterator(array, start, length, opt_predicate);
753};
754
755// Shim layer with setTimeout fallback.
756// From: http://paulirish.com/2011/requestanimationframe-for-smart-animating/
757// Should be called with the window context:
758// Dygraph.requestAnimFrame.call(window, function() {})
759export var requestAnimFrame = (function() {
760 return window.requestAnimationFrame ||
761 window.webkitRequestAnimationFrame ||
762 window.mozRequestAnimationFrame ||
763 window.oRequestAnimationFrame ||
764 window.msRequestAnimationFrame ||
765 function (callback) {
766 window.setTimeout(callback, 1000 / 60);
767 };
768})();
769
770/**
771 * Call a function at most maxFrames times at an attempted interval of
772 * framePeriodInMillis, then call a cleanup function once. repeatFn is called
773 * once immediately, then at most (maxFrames - 1) times asynchronously. If
774 * maxFrames==1, then cleanup_fn() is also called synchronously. This function
775 * is used to sequence animation.
776 * @param {function(number)} repeatFn Called repeatedly -- takes the frame
777 * number (from 0 to maxFrames-1) as an argument.
778 * @param {number} maxFrames The max number of times to call repeatFn
779 * @param {number} framePeriodInMillis Max requested time between frames.
780 * @param {function()} cleanupFn A function to call after all repeatFn calls.
781 * @private
782 */
783export function repeatAndCleanup(repeatFn, maxFrames, framePeriodInMillis,
784 cleanupFn) {
785 var frameNumber = 0;
786 var previousFrameNumber;
787 var startTime = new Date().getTime();
788 repeatFn(frameNumber);
789 if (maxFrames == 1) {
790 cleanupFn();
791 return;
792 }
793 var maxFrameArg = maxFrames - 1;
794
795 (function loop() {
796 if (frameNumber >= maxFrames) return;
797 requestAnimFrame.call(window, function() {
798 // Determine which frame to draw based on the delay so far. Will skip
799 // frames if necessary.
800 var currentTime = new Date().getTime();
801 var delayInMillis = currentTime - startTime;
802 previousFrameNumber = frameNumber;
803 frameNumber = Math.floor(delayInMillis / framePeriodInMillis);
804 var frameDelta = frameNumber - previousFrameNumber;
805 // If we predict that the subsequent repeatFn call will overshoot our
806 // total frame target, so our last call will cause a stutter, then jump to
807 // the last call immediately. If we're going to cause a stutter, better
808 // to do it faster than slower.
809 var predictOvershootStutter = (frameNumber + frameDelta) > maxFrameArg;
810 if (predictOvershootStutter || (frameNumber >= maxFrameArg)) {
811 repeatFn(maxFrameArg); // Ensure final call with maxFrameArg.
812 cleanupFn();
813 } else {
814 if (frameDelta !== 0) { // Don't call repeatFn with duplicate frames.
815 repeatFn(frameNumber);
816 }
817 loop();
818 }
819 });
820 })();
821};
822
823// A whitelist of options that do not change pixel positions.
824var pixelSafeOptions = {
825 'annotationClickHandler': true,
826 'annotationDblClickHandler': true,
827 'annotationMouseOutHandler': true,
828 'annotationMouseOverHandler': true,
829 'axisLineColor': true,
830 'axisLineWidth': true,
831 'clickCallback': true,
832 'drawCallback': true,
833 'drawHighlightPointCallback': true,
834 'drawPoints': true,
835 'drawPointCallback': true,
836 'drawGrid': true,
837 'fillAlpha': true,
838 'gridLineColor': true,
839 'gridLineWidth': true,
840 'hideOverlayOnMouseOut': true,
841 'highlightCallback': true,
842 'highlightCircleSize': true,
843 'interactionModel': true,
844 'isZoomedIgnoreProgrammaticZoom': true,
845 'labelsDiv': true,
846 'labelsKMB': true,
847 'labelsKMG2': true,
848 'labelsSeparateLines': true,
849 'labelsShowZeroValues': true,
850 'legend': true,
851 'panEdgeFraction': true,
852 'pixelsPerYLabel': true,
853 'pointClickCallback': true,
854 'pointSize': true,
855 'rangeSelectorPlotFillColor': true,
856 'rangeSelectorPlotFillGradientColor': true,
857 'rangeSelectorPlotStrokeColor': true,
858 'rangeSelectorBackgroundStrokeColor': true,
859 'rangeSelectorBackgroundLineWidth': true,
860 'rangeSelectorPlotLineWidth': true,
861 'rangeSelectorForegroundStrokeColor': true,
862 'rangeSelectorForegroundLineWidth': true,
863 'rangeSelectorAlpha': true,
864 'showLabelsOnHighlight': true,
865 'showRoller': true,
866 'strokeWidth': true,
867 'underlayCallback': true,
868 'unhighlightCallback': true,
869 'zoomCallback': true
870};
871
872/**
873 * This function will scan the option list and determine if they
874 * require us to recalculate the pixel positions of each point.
875 * TODO: move this into dygraph-options.js
876 * @param {!Array.<string>} labels a list of options to check.
877 * @param {!Object} attrs
878 * @return {boolean} true if the graph needs new points else false.
879 * @private
880 */
881export function isPixelChangingOptionList(labels, attrs) {
882 // Assume that we do not require new points.
883 // This will change to true if we actually do need new points.
884
885 // Create a dictionary of series names for faster lookup.
886 // If there are no labels, then the dictionary stays empty.
887 var seriesNamesDictionary = { };
888 if (labels) {
889 for (var i = 1; i < labels.length; i++) {
890 seriesNamesDictionary[labels[i]] = true;
891 }
892 }
893
894 // Scan through a flat (i.e. non-nested) object of options.
895 // Returns true/false depending on whether new points are needed.
896 var scanFlatOptions = function(options) {
897 for (var property in options) {
898 if (options.hasOwnProperty(property) &&
899 !pixelSafeOptions[property]) {
900 return true;
901 }
902 }
903 return false;
904 };
905
906 // Iterate through the list of updated options.
907 for (var property in attrs) {
908 if (!attrs.hasOwnProperty(property)) continue;
909
910 // Find out of this field is actually a series specific options list.
911 if (property == 'highlightSeriesOpts' ||
912 (seriesNamesDictionary[property] && !attrs.series)) {
913 // This property value is a list of options for this series.
914 if (scanFlatOptions(attrs[property])) return true;
915 } else if (property == 'series' || property == 'axes') {
916 // This is twice-nested options list.
917 var perSeries = attrs[property];
918 for (var series in perSeries) {
919 if (perSeries.hasOwnProperty(series) &&
920 scanFlatOptions(perSeries[series])) {
921 return true;
922 }
923 }
924 } else {
925 // If this was not a series specific option list, check if it's a pixel
926 // changing property.
927 if (!pixelSafeOptions[property]) return true;
928 }
929 }
930
931 return false;
932};
933
934export var Circles = {
935 DEFAULT : function(g, name, ctx, canvasx, canvasy, color, radius) {
936 ctx.beginPath();
937 ctx.fillStyle = color;
938 ctx.arc(canvasx, canvasy, radius, 0, 2 * Math.PI, false);
939 ctx.fill();
940 }
941 // For more shapes, include extras/shapes.js
942};
943
944/**
945 * Determine whether |data| is delimited by CR, CRLF, LF, LFCR.
946 * @param {string} data
947 * @return {?string} the delimiter that was detected (or null on failure).
948 */
949export function detectLineDelimiter(data) {
950 for (var i = 0; i < data.length; i++) {
951 var code = data.charAt(i);
952 if (code === '\r') {
953 // Might actually be "\r\n".
954 if (((i + 1) < data.length) && (data.charAt(i + 1) === '\n')) {
955 return '\r\n';
956 }
957 return code;
958 }
959 if (code === '\n') {
960 // Might actually be "\n\r".
961 if (((i + 1) < data.length) && (data.charAt(i + 1) === '\r')) {
962 return '\n\r';
963 }
964 return code;
965 }
966 }
967
968 return null;
969};
970
971/**
972 * Is one node contained by another?
973 * @param {Node} containee The contained node.
974 * @param {Node} container The container node.
975 * @return {boolean} Whether containee is inside (or equal to) container.
976 * @private
977 */
978export function isNodeContainedBy(containee, container) {
979 if (container === null || containee === null) {
980 return false;
981 }
982 var containeeNode = /** @type {Node} */ (containee);
983 while (containeeNode && containeeNode !== container) {
984 containeeNode = containeeNode.parentNode;
985 }
986 return (containeeNode === container);
987};
988
989// This masks some numeric issues in older versions of Firefox,
990// where 1.0/Math.pow(10,2) != Math.pow(10,-2).
991/** @type {function(number,number):number} */
992export function pow(base, exp) {
993 if (exp < 0) {
994 return 1.0 / Math.pow(base, -exp);
995 }
996 return Math.pow(base, exp);
997};
998
999var RGBA_RE = /^rgba?\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})(?:,\s*([01](?:\.\d+)?))?\)$/;
1000
1001/**
1002 * Helper for toRGB_ which parses strings of the form:
1003 * rgb(123, 45, 67)
1004 * rgba(123, 45, 67, 0.5)
1005 * @return parsed {r,g,b,a?} tuple or null.
1006 */
1007function parseRGBA(rgbStr) {
1008 var bits = RGBA_RE.exec(rgbStr);
1009 if (!bits) return null;
1010 var r = parseInt(bits[1], 10),
1011 g = parseInt(bits[2], 10),
1012 b = parseInt(bits[3], 10);
1013 if (bits[4]) {
1014 return {r: r, g: g, b: b, a: parseFloat(bits[4])};
1015 } else {
1016 return {r: r, g: g, b: b};
1017 }
1018}
1019
1020/**
1021 * Converts any valid CSS color (hex, rgb(), named color) to an RGB tuple.
1022 *
1023 * @param {!string} colorStr Any valid CSS color string.
1024 * @return {{r:number,g:number,b:number,a:number?}} Parsed RGB tuple.
1025 * @private
1026 */
1027export function toRGB_(colorStr) {
1028 // Strategy: First try to parse colorStr directly. This is fast & avoids DOM
1029 // manipulation. If that fails (e.g. for named colors like 'red'), then
1030 // create a hidden DOM element and parse its computed color.
1031 var rgb = parseRGBA(colorStr);
1032 if (rgb) return rgb;
1033
1034 var div = document.createElement('div');
1035 div.style.backgroundColor = colorStr;
1036 div.style.visibility = 'hidden';
1037 document.body.appendChild(div);
1038 var rgbStr = window.getComputedStyle(div, null).backgroundColor;
1039 document.body.removeChild(div);
1040 return parseRGBA(rgbStr);
1041};
1042
1043/**
1044 * Checks whether the browser supports the &lt;canvas&gt; tag.
1045 * @param {HTMLCanvasElement=} opt_canvasElement Pass a canvas element as an
1046 * optimization if you have one.
1047 * @return {boolean} Whether the browser supports canvas.
1048 */
1049export function isCanvasSupported(opt_canvasElement) {
1050 try {
1051 var canvas = opt_canvasElement || document.createElement("canvas");
1052 canvas.getContext("2d");
1053 } catch (e) {
1054 return false;
1055 }
1056 return true;
1057};
1058
1059/**
1060 * Parses the value as a floating point number. This is like the parseFloat()
1061 * built-in, but with a few differences:
1062 * - the empty string is parsed as null, rather than NaN.
1063 * - if the string cannot be parsed at all, an error is logged.
1064 * If the string can't be parsed, this method returns null.
1065 * @param {string} x The string to be parsed
1066 * @param {number=} opt_line_no The line number from which the string comes.
1067 * @param {string=} opt_line The text of the line from which the string comes.
1068 */
1069export function parseFloat_(x, opt_line_no, opt_line) {
1070 var val = parseFloat(x);
1071 if (!isNaN(val)) return val;
1072
1073 // Try to figure out what happeend.
1074 // If the value is the empty string, parse it as null.
1075 if (/^ *$/.test(x)) return null;
1076
1077 // If it was actually "NaN", return it as NaN.
1078 if (/^ *nan *$/i.test(x)) return NaN;
1079
1080 // Looks like a parsing error.
1081 var msg = "Unable to parse '" + x + "' as a number";
1082 if (opt_line !== undefined && opt_line_no !== undefined) {
1083 msg += " on line " + (1+(opt_line_no||0)) + " ('" + opt_line + "') of CSV.";
1084 }
1085 console.error(msg);
1086
1087 return null;
1088};
1089
1090
1091// Label constants for the labelsKMB and labelsKMG2 options.
1092// (i.e. '100000' -> '100K')
1093var KMB_LABELS = [ 'K', 'M', 'B', 'T', 'Q' ];
1094var KMG2_BIG_LABELS = [ 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y' ];
1095var KMG2_SMALL_LABELS = [ 'm', 'u', 'n', 'p', 'f', 'a', 'z', 'y' ];
1096
1097/**
1098 * @private
1099 * Return a string version of a number. This respects the digitsAfterDecimal
1100 * and maxNumberWidth options.
1101 * @param {number} x The number to be formatted
1102 * @param {Dygraph} opts An options view
1103 */
1104export function numberValueFormatter(x, opts) {
1105 var sigFigs = opts('sigFigs');
1106
1107 if (sigFigs !== null) {
1108 // User has opted for a fixed number of significant figures.
1109 return floatFormat(x, sigFigs);
1110 }
1111
1112 var digits = opts('digitsAfterDecimal');
1113 var maxNumberWidth = opts('maxNumberWidth');
1114
1115 var kmb = opts('labelsKMB');
1116 var kmg2 = opts('labelsKMG2');
1117
1118 var label;
1119
1120 // switch to scientific notation if we underflow or overflow fixed display.
1121 if (x !== 0.0 &&
1122 (Math.abs(x) >= Math.pow(10, maxNumberWidth) ||
1123 Math.abs(x) < Math.pow(10, -digits))) {
1124 label = x.toExponential(digits);
1125 } else {
1126 label = '' + round_(x, digits);
1127 }
1128
1129 if (kmb || kmg2) {
1130 var k;
1131 var k_labels = [];
1132 var m_labels = [];
1133 if (kmb) {
1134 k = 1000;
1135 k_labels = KMB_LABELS;
1136 }
1137 if (kmg2) {
1138 if (kmb) console.warn("Setting both labelsKMB and labelsKMG2. Pick one!");
1139 k = 1024;
1140 k_labels = KMG2_BIG_LABELS;
1141 m_labels = KMG2_SMALL_LABELS;
1142 }
1143
1144 var absx = Math.abs(x);
1145 var n = pow(k, k_labels.length);
1146 for (var j = k_labels.length - 1; j >= 0; j--, n /= k) {
1147 if (absx >= n) {
1148 label = round_(x / n, digits) + k_labels[j];
1149 break;
1150 }
1151 }
1152 if (kmg2) {
1153 // TODO(danvk): clean up this logic. Why so different than kmb?
1154 var x_parts = String(x.toExponential()).split('e-');
1155 if (x_parts.length === 2 && x_parts[1] >= 3 && x_parts[1] <= 24) {
1156 if (x_parts[1] % 3 > 0) {
1157 label = round_(x_parts[0] /
1158 pow(10, (x_parts[1] % 3)),
1159 digits);
1160 } else {
1161 label = Number(x_parts[0]).toFixed(2);
1162 }
1163 label += m_labels[Math.floor(x_parts[1] / 3) - 1];
1164 }
1165 }
1166 }
1167
1168 return label;
1169};
1170
1171/**
1172 * variant for use as an axisLabelFormatter.
1173 * @private
1174 */
1175export function numberAxisLabelFormatter(x, granularity, opts) {
1176 return numberValueFormatter.call(this, x, opts);
1177};
1178
1179/**
1180 * @type {!Array.<string>}
1181 * @private
1182 * @constant
1183 */
1184var SHORT_MONTH_NAMES_ = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
1185
1186
1187/**
1188 * Convert a JS date to a string appropriate to display on an axis that
1189 * is displaying values at the stated granularity. This respects the
1190 * labelsUTC option.
1191 * @param {Date} date The date to format
1192 * @param {number} granularity One of the Dygraph granularity constants
1193 * @param {Dygraph} opts An options view
1194 * @return {string} The date formatted as local time
1195 * @private
1196 */
1197export function dateAxisLabelFormatter(date, granularity, opts) {
1198 var utc = opts('labelsUTC');
1199 var accessors = utc ? DateAccessorsUTC : DateAccessorsLocal;
1200
1201 var year = accessors.getFullYear(date),
1202 month = accessors.getMonth(date),
1203 day = accessors.getDate(date),
1204 hours = accessors.getHours(date),
1205 mins = accessors.getMinutes(date),
1206 secs = accessors.getSeconds(date),
1207 millis = accessors.getMilliseconds(date);
1208
1209 if (granularity >= DygraphTickers.Granularity.DECADAL) {
1210 return '' + year;
1211 } else if (granularity >= DygraphTickers.Granularity.MONTHLY) {
1212 return SHORT_MONTH_NAMES_[month] + '&#160;' + year;
1213 } else {
1214 var frac = hours * 3600 + mins * 60 + secs + 1e-3 * millis;
1215 if (frac === 0 || granularity >= DygraphTickers.Granularity.DAILY) {
1216 // e.g. '21 Jan' (%d%b)
1217 return zeropad(day) + '&#160;' + SHORT_MONTH_NAMES_[month];
1218 } else {
1219 return hmsString_(hours, mins, secs, millis);
1220 }
1221 }
1222};
1223// alias in case anyone is referencing the old method.
1224// Dygraph.dateAxisFormatter = Dygraph.dateAxisLabelFormatter;
1225
1226/**
1227 * Return a string version of a JS date for a value label. This respects the
1228 * labelsUTC option.
1229 * @param {Date} date The date to be formatted
1230 * @param {Dygraph} opts An options view
1231 * @private
1232 */
1233export function dateValueFormatter(d, opts) {
1234 return dateString_(d, opts('labelsUTC'));
1235};