UNPKG

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