jquery.flot.time.js 19 KB

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