Debian Codegraph @

online/static/flot/jquery.flot.time.js

raw symbols SCIP
1 /* Pretty handling of time axes.
2
3 Copyright (c) 2007-2014 IOLA and Ole Laursen.
4 Licensed under the MIT license.
5
6 Set axis.mode to "time" to enable. See the section "Time series data" in
7 API.txt for details.
8 */
9
10 (function($) {
11 'use strict';
12
13 var options = {
14 xaxis: {
15 timezone: null, // "browser" for local to the client or timezone for timezone-js
16 timeformat: null, // format string to use
17 twelveHourClock: false, // 12 or 24 time in time mode
18 monthNames: null, // list of names of months
19 timeBase: 'seconds' // are the values in given in mircoseconds, milliseconds or seconds
20 },
21 yaxis: {
22 timeBase: 'seconds'
23 }
24 };
25
26 var floorInBase = $.plot.saturated.floorInBase;
27
28 // Method to provide microsecond support to Date like classes.
29 var CreateMicroSecondDate = function(DateType, microEpoch) {
30 var newDate = new DateType(microEpoch);
31
32 var oldSetTime = newDate.setTime.bind(newDate);
33 newDate.update = function(microEpoch) {
34 // Round epoch to 3 decimal accuracy
35 microEpoch = Math.round(microEpoch * 1000) / 1000;
36
37 oldSetTime(microEpoch);
38
39 // Microseconds are stored as integers
40 this.microseconds = 1000 * (microEpoch - Math.floor(microEpoch));
41 };
42
43 var oldGetTime = newDate.getTime.bind(newDate);
44 newDate.getTime = function () {
45 var microEpoch = oldGetTime() + this.microseconds / 1000;
46 return microEpoch;
47 };
48
49 newDate.setTime = function (microEpoch) {
50 this.update(microEpoch);
51 };
52
53 newDate.getMicroseconds = function() {
54 return this.microseconds;
55 };
56
57 newDate.setMicroseconds = function(microseconds) {
58 var epochWithoutMicroseconds = oldGetTime();
59 var newEpoch = epochWithoutMicroseconds + microseconds / 1000;
60 this.update(newEpoch);
61 };
62
63 newDate.setUTCMicroseconds = function(microseconds) { this.setMicroseconds(microseconds); }
64
65 newDate.getUTCMicroseconds = function() { return this.getMicroseconds(); }
66
67 newDate.microseconds = null;
68 newDate.microEpoch = null;
69 newDate.update(microEpoch);
70 return newDate;
71 }
72
73 // Returns a string with the date d formatted according to fmt.
74 // A subset of the Open Group's strftime format is supported.
75
76 function formatDate(d, fmt, monthNames, dayNames) {
77 if (typeof d.strftime === "function") {
78 return d.strftime(fmt);
79 }
80
81 var leftPad = function(n, pad) {
82 n = "" + n;
83 pad = "" + (pad == null ? "0" : pad);
84 return n.length === 1 ? pad + n : n;
85 };
86
87 var formatSubSeconds = function(milliseconds, microseconds, numberDecimalPlaces) {
88 var totalMicroseconds = milliseconds * 1000 + microseconds;
89 var formattedString;
90 if (numberDecimalPlaces < 6 && numberDecimalPlaces > 0) {
91 var magnitude = parseFloat('1e' + (numberDecimalPlaces - 6));
92 totalMicroseconds = Math.round(Math.round(totalMicroseconds * magnitude) / magnitude);
93 formattedString = ('00000' + totalMicroseconds).slice(-6, -(6 - numberDecimalPlaces));
94 } else {
95 totalMicroseconds = Math.round(totalMicroseconds)
96 formattedString = ('00000' + totalMicroseconds).slice(-6);
97 }
98 return formattedString;
99 };
100
101 var r = [];
102 var escape = false;
103 var hours = d.getHours();
104 var isAM = hours < 12;
105
106 if (!monthNames) {
107 monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
108 }
109
110 if (!dayNames) {
111 dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
112 }
113
114 var hours12;
115 if (hours > 12) {
116 hours12 = hours - 12;
117 } else if (hours === 0) {
118 hours12 = 12;
119 } else {
120 hours12 = hours;
121 }
122
123 var decimals = -1;
124 for (var i = 0; i < fmt.length; ++i) {
125 var c = fmt.charAt(i);
126
127 if (!isNaN(Number(c)) && Number(c) > 0) {
128 decimals = Number(c);
129 } else if (escape) {
130 switch (c) {
131 case 'a': c = "" + dayNames[d.getDay()]; break;
132 case 'b': c = "" + monthNames[d.getMonth()]; break;
133 case 'd': c = leftPad(d.getDate()); break;
134 case 'e': c = leftPad(d.getDate(), " "); break;
135 case 'h': // For back-compat with 0.7; remove in 1.0
136 case 'H': c = leftPad(hours); break;
137 case 'I': c = leftPad(hours12); break;
138 case 'l': c = leftPad(hours12, " "); break;
139 case 'm': c = leftPad(d.getMonth() + 1); break;
140 case 'M': c = leftPad(d.getMinutes()); break;
141 // quarters not in Open Group's strftime specification
142 case 'q':
143 c = "" + (Math.floor(d.getMonth() / 3) + 1); break;
144 case 'S': c = leftPad(d.getSeconds()); break;
145 case 's': c = "" + formatSubSeconds(d.getMilliseconds(), d.getMicroseconds(), decimals); break;
146 case 'y': c = leftPad(d.getFullYear() % 100); break;
147 case 'Y': c = "" + d.getFullYear(); break;
148 case 'p': c = (isAM) ? ("" + "am") : ("" + "pm"); break;
149 case 'P': c = (isAM) ? ("" + "AM") : ("" + "PM"); break;
150 case 'w': c = "" + d.getDay(); break;
151 }
152 r.push(c);
153 escape = false;
154 } else {
155 if (c === "%") {
156 escape = true;
157 } else {
158 r.push(c);
159 }
160 }
161 }
162
163 return r.join("");
164 }
165
166 // To have a consistent view of time-based data independent of which time
167 // zone the client happens to be in we need a date-like object independent
168 // of time zones. This is done through a wrapper that only calls the UTC
169 // versions of the accessor methods.
170
171 function makeUtcWrapper(d) {
172 function addProxyMethod(sourceObj, sourceMethod, targetObj, targetMethod) {
173 sourceObj[sourceMethod] = function() {
174 return targetObj[targetMethod].apply(targetObj, arguments);
175 };
176 }
177
178 var utc = {
179 date: d
180 };
181
182 // support strftime, if found
183 if (d.strftime !== undefined) {
184 addProxyMethod(utc, "strftime", d, "strftime");
185 }
186
187 addProxyMethod(utc, "getTime", d, "getTime");
188 addProxyMethod(utc, "setTime", d, "setTime");
189
190 var props = ["Date", "Day", "FullYear", "Hours", "Minutes", "Month", "Seconds", "Milliseconds", "Microseconds"];
191
192 for (var p = 0; p < props.length; p++) {
193 addProxyMethod(utc, "get" + props[p], d, "getUTC" + props[p]);
194 addProxyMethod(utc, "set" + props[p], d, "setUTC" + props[p]);
195 }
196
197 return utc;
198 }
199
200 // select time zone strategy. This returns a date-like object tied to the
201 // desired timezone
202 function dateGenerator(ts, opts) {
203 var maxDateValue = 8640000000000000;
204
205 if (opts && opts.timeBase === 'seconds') {
206 ts *= 1000;
207 } else if (opts.timeBase === 'microseconds') {
208 ts /= 1000;
209 }
210
211 if (ts > maxDateValue) {
212 ts = maxDateValue;
213 } else if (ts < -maxDateValue) {
214 ts = -maxDateValue;
215 }
216
217 if (opts.timezone === "browser") {
218 return CreateMicroSecondDate(Date, ts);
219 } else if (!opts.timezone || opts.timezone === "utc") {
220 return makeUtcWrapper(CreateMicroSecondDate(Date, ts));
221 } else if (typeof timezoneJS !== "undefined" && typeof timezoneJS.Date !== "undefined") {
222 var d = CreateMicroSecondDate(timezoneJS.Date, ts);
223 // timezone-js is fickle, so be sure to set the time zone before
224 // setting the time.
225 d.setTimezone(opts.timezone);
226 d.setTime(ts);
227 return d;
228 } else {
229 return makeUtcWrapper(CreateMicroSecondDate(Date, ts));
230 }
231 }
232
233 // map of app. size of time units in seconds
234 var timeUnitSizeSeconds = {
235 "microsecond": 0.000001,
236 "millisecond": 0.001,
237 "second": 1,
238 "minute": 60,
239 "hour": 60 * 60,
240 "day": 24 * 60 * 60,
241 "month": 30 * 24 * 60 * 60,
242 "quarter": 3 * 30 * 24 * 60 * 60,
243 "year": 365.2425 * 24 * 60 * 60
244 };
245
246 // map of app. size of time units in milliseconds
247 var timeUnitSizeMilliseconds = {
248 "microsecond": 0.001,
249 "millisecond": 1,
250 "second": 1000,
251 "minute": 60 * 1000,
252 "hour": 60 * 60 * 1000,
253 "day": 24 * 60 * 60 * 1000,
254 "month": 30 * 24 * 60 * 60 * 1000,
255 "quarter": 3 * 30 * 24 * 60 * 60 * 1000,
256 "year": 365.2425 * 24 * 60 * 60 * 1000
257 };
258
259 // map of app. size of time units in microseconds
260 var timeUnitSizeMicroseconds = {
261 "microsecond": 1,
262 "millisecond": 1000,
263 "second": 1000000,
264 "minute": 60 * 1000000,
265 "hour": 60 * 60 * 1000000,
266 "day": 24 * 60 * 60 * 1000000,
267 "month": 30 * 24 * 60 * 60 * 1000000,
268 "quarter": 3 * 30 * 24 * 60 * 60 * 1000000,
269 "year": 365.2425 * 24 * 60 * 60 * 1000000
270 };
271
272 // the allowed tick sizes, after 1 year we use
273 // an integer algorithm
274
275 var baseSpec = [
276 [1, "microsecond"], [2, "microsecond"], [5, "microsecond"], [10, "microsecond"],
277 [25, "microsecond"], [50, "microsecond"], [100, "microsecond"], [250, "microsecond"], [500, "microsecond"],
278 [1, "millisecond"], [2, "millisecond"], [5, "millisecond"], [10, "millisecond"],
279 [25, "millisecond"], [50, "millisecond"], [100, "millisecond"], [250, "millisecond"], [500, "millisecond"],
280 [1, "second"], [2, "second"], [5, "second"], [10, "second"],
281 [30, "second"],
282 [1, "minute"], [2, "minute"], [5, "minute"], [10, "minute"],
283 [30, "minute"],
284 [1, "hour"], [2, "hour"], [4, "hour"],
285 [8, "hour"], [12, "hour"],
286 [1, "day"], [2, "day"], [3, "day"],
287 [0.25, "month"], [0.5, "month"], [1, "month"],
288 [2, "month"]
289 ];
290
291 // we don't know which variant(s) we'll need yet, but generating both is
292 // cheap
293
294 var specMonths = baseSpec.concat([[3, "month"], [6, "month"],
295 [1, "year"]]);
296 var specQuarters = baseSpec.concat([[1, "quarter"], [2, "quarter"],
297 [1, "year"]]);
298
299 function dateTickGenerator(axis) {
300 var opts = axis.options,
301 ticks = [],
302 d = dateGenerator(axis.min, opts),
303 minSize = 0;
304
305 // make quarter use a possibility if quarters are
306 // mentioned in either of these options
307 var spec = (opts.tickSize && opts.tickSize[1] ===
308 "quarter") ||
309 (opts.minTickSize && opts.minTickSize[1] ===
310 "quarter") ? specQuarters : specMonths;
311
312 var timeUnitSize;
313 if (opts.timeBase === 'seconds') {
314 timeUnitSize = timeUnitSizeSeconds;
315 } else if (opts.timeBase === 'microseconds') {
316 timeUnitSize = timeUnitSizeMicroseconds;
317 } else {
318 timeUnitSize = timeUnitSizeMilliseconds;
319 }
320
321 if (opts.minTickSize !== null && opts.minTickSize !== undefined) {
322 if (typeof opts.tickSize === "number") {
323 minSize = opts.tickSize;
324 } else {
325 minSize = opts.minTickSize[0] * timeUnitSize[opts.minTickSize[1]];
326 }
327 }
328
329 for (var i = 0; i < spec.length - 1; ++i) {
330 if (axis.delta < (spec[i][0] * timeUnitSize[spec[i][1]] +
331 spec[i + 1][0] * timeUnitSize[spec[i + 1][1]]) / 2 &&
332 spec[i][0] * timeUnitSize[spec[i][1]] >= minSize) {
333 break;
334 }
335 }
336
337 var size = spec[i][0];
338 var unit = spec[i][1];
339 // special-case the possibility of several years
340 if (unit === "year") {
341 // if given a minTickSize in years, just use it,
342 // ensuring that it's an integer
343
344 if (opts.minTickSize !== null && opts.minTickSize !== undefined && opts.minTickSize[1] === "year") {
345 size = Math.floor(opts.minTickSize[0]);
346 } else {
347 var magn = parseFloat('1e' + Math.floor(Math.log(axis.delta / timeUnitSize.year) / Math.LN10));
348 var norm = (axis.delta / timeUnitSize.year) / magn;
349
350 if (norm < 1.5) {
351 size = 1;
352 } else if (norm < 3) {
353 size = 2;
354 } else if (norm < 7.5) {
355 size = 5;
356 } else {
357 size = 10;
358 }
359
360 size *= magn;
361 }
362
363 // minimum size for years is 1
364
365 if (size < 1) {
366 size = 1;
367 }
368 }
369
370 axis.tickSize = opts.tickSize || [size, unit];
371 var tickSize = axis.tickSize[0];
372 unit = axis.tickSize[1];
373
374 var step = tickSize * timeUnitSize[unit];
375
376 if (unit === "microsecond") {
377 d.setMicroseconds(floorInBase(d.getMicroseconds(), tickSize));
378 } else if (unit === "millisecond") {
379 d.setMilliseconds(floorInBase(d.getMilliseconds(), tickSize));
380 } else if (unit === "second") {
381 d.setSeconds(floorInBase(d.getSeconds(), tickSize));
382 } else if (unit === "minute") {
383 d.setMinutes(floorInBase(d.getMinutes(), tickSize));
384 } else if (unit === "hour") {
385 d.setHours(floorInBase(d.getHours(), tickSize));
386 } else if (unit === "month") {
387 d.setMonth(floorInBase(d.getMonth(), tickSize));
388 } else if (unit === "quarter") {
389 d.setMonth(3 * floorInBase(d.getMonth() / 3,
390 tickSize));
391 } else if (unit === "year") {
392 d.setFullYear(floorInBase(d.getFullYear(), tickSize));
393 }
394
395 // reset smaller components
396
397 if (step >= timeUnitSize.millisecond) {
398 d.setMicroseconds(0);
399 }
400 if (step >= timeUnitSize.second) {
401 d.setMilliseconds(0);
402 }
403 if (step >= timeUnitSize.minute) {
404 d.setSeconds(0);
405 }
406 if (step >= timeUnitSize.hour) {
407 d.setMinutes(0);
408 }
409 if (step >= timeUnitSize.day) {
410 d.setHours(0);
411 }
412 if (step >= timeUnitSize.day * 4) {
413 d.setDate(1);
414 }
415 if (step >= timeUnitSize.month * 2) {
416 d.setMonth(floorInBase(d.getMonth(), 3));
417 }
418 if (step >= timeUnitSize.quarter * 2) {
419 d.setMonth(floorInBase(d.getMonth(), 6));
420 }
421 if (step >= timeUnitSize.year) {
422 d.setMonth(0);
423 }
424
425 var carry = 0;
426 var v = Number.NaN;
427 var v1000;
428 var prev;
429 do {
430 prev = v;
431 v1000 = d.getTime();
432 if (opts && opts.timeBase === 'seconds') {
433 v = v1000 / 1000;
434 } else if (opts && opts.timeBase === 'microseconds') {
435 v = v1000 * 1000;
436 } else {
437 v = v1000;
438 }
439
440 ticks.push(v);
441
442 if (unit === "month" || unit === "quarter") {
443 if (tickSize < 1) {
444 // a bit complicated - we'll divide the
445 // month/quarter up but we need to take
446 // care of fractions so we don't end up in
447 // the middle of a day
448 d.setDate(1);
449 var start = d.getTime();
450 d.setMonth(d.getMonth() +
451 (unit === "quarter" ? 3 : 1));
452 var end = d.getTime();
453 d.setTime((v + carry * timeUnitSize.hour + (end - start) * tickSize));
454 carry = d.getHours();
455 d.setHours(0);
456 } else {
457 d.setMonth(d.getMonth() +
458 tickSize * (unit === "quarter" ? 3 : 1));
459 }
460 } else if (unit === "year") {
461 d.setFullYear(d.getFullYear() + tickSize);
462 } else {
463 if (opts.timeBase === 'seconds') {
464 d.setTime((v + step) * 1000);
465 } else if (opts.timeBase === 'microseconds') {
466 d.setTime((v + step) / 1000);
467 } else {
468 d.setTime(v + step);
469 }
470 }
471 } while (v < axis.max && v !== prev);
472
473 return ticks;
474 };
475
476 function init(plot) {
477 plot.hooks.processOptions.push(function (plot) {
478 $.each(plot.getAxes(), function(axisName, axis) {
479 var opts = axis.options;
480 if (opts.mode === "time") {
481 axis.tickGenerator = dateTickGenerator;
482
483 // if a tick formatter is already provided do not overwrite it
484 if ('tickFormatter' in opts && typeof opts.tickFormatter === 'function') return;
485
486 axis.tickFormatter = function (v, axis) {
487 var d = dateGenerator(v, axis.options);
488
489 // first check global format
490 if (opts.timeformat != null) {
491 return formatDate(d, opts.timeformat, opts.monthNames, opts.dayNames);
492 }
493
494 // possibly use quarters if quarters are mentioned in
495 // any of these places
496 var useQuarters = (axis.options.tickSize &&
497 axis.options.tickSize[1] === "quarter") ||
498 (axis.options.minTickSize &&
499 axis.options.minTickSize[1] === "quarter");
500
501 var timeUnitSize;
502 if (opts.timeBase === 'seconds') {
503 timeUnitSize = timeUnitSizeSeconds;
504 } else if (opts.timeBase === 'microseconds') {
505 timeUnitSize = timeUnitSizeMicroseconds;
506 } else {
507 timeUnitSize = timeUnitSizeMilliseconds;
508 }
509
510 var t = axis.tickSize[0] * timeUnitSize[axis.tickSize[1]];
511 var span = axis.max - axis.min;
512 var suffix = (opts.twelveHourClock) ? " %p" : "";
513 var hourCode = (opts.twelveHourClock) ? "%I" : "%H";
514 var factor;
515 var fmt;
516
517 if (opts.timeBase === 'seconds') {
518 factor = 1;
519 } else if (opts.timeBase === 'microseconds') {
520 factor = 1000000
521 } else {
522 factor = 1000;
523 }
524
525 if (t < timeUnitSize.second) {
526 var decimals = -Math.floor(Math.log10(t / factor))
527
528 // the two-and-halves require an additional decimal
529 if (String(t).indexOf('25') > -1) {
530 decimals++;
531 }
532
533 fmt = "%S.%" + decimals + "s";
534 } else
535 if (t < timeUnitSize.minute) {
536 fmt = hourCode + ":%M:%S" + suffix;
537 } else if (t < timeUnitSize.day) {
538 if (span < 2 * timeUnitSize.day) {
539 fmt = hourCode + ":%M" + suffix;
540 } else {
541 fmt = "%b %d " + hourCode + ":%M" + suffix;
542 }
543 } else if (t < timeUnitSize.month) {
544 fmt = "%b %d";
545 } else if ((useQuarters && t < timeUnitSize.quarter) ||
546 (!useQuarters && t < timeUnitSize.year)) {
547 if (span < timeUnitSize.year) {
548 fmt = "%b";
549 } else {
550 fmt = "%b %Y";
551 }
552 } else if (useQuarters && t < timeUnitSize.year) {
553 if (span < timeUnitSize.year) {
554 fmt = "Q%q";
555 } else {
556 fmt = "Q%q %Y";
557 }
558 } else {
559 fmt = "%Y";
560 }
561
562 var rt = formatDate(d, fmt, opts.monthNames, opts.dayNames);
563
564 return rt;
565 };
566 }
567 });
568 });
569 }
570
571 $.plot.plugins.push({
572 init: init,
573 options: options,
574 name: 'time',
575 version: '1.0'
576 });
577
578 // Time-axis support used to be in Flot core, which exposed the
579 // formatDate function on the plot object. Various plugins depend
580 // on the function, so we need to re-expose it here.
581
582 $.plot.formatDate = formatDate;
583 $.plot.dateGenerator = dateGenerator;
584 $.plot.dateTickGenerator = dateTickGenerator;
585 $.plot.makeUtcWrapper = makeUtcWrapper;
586 })(jQuery);