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