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