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