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