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