jquery.flot.time.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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. var options = {
  9. xaxis: {
  10. timezone: null, // "browser" for local to the client or timezone for timezone-js
  11. timeformat: null, // format string to use
  12. twelveHourClock: false, // 12 or 24 time in time mode
  13. monthNames: null // list of names of months
  14. }
  15. };
  16. // round to nearby lower multiple of base
  17. function floorInBase(n, base) {
  18. return base * Math.floor(n / base);
  19. }
  20. // Returns a string with the date d formatted according to fmt.
  21. // A subset of the Open Group's strftime format is supported.
  22. function formatDate(d, fmt, monthNames, dayNames) {
  23. if (typeof d.strftime == "function") {
  24. return d.strftime(fmt);
  25. }
  26. var leftPad = function(n, pad) {
  27. n = "" + n;
  28. pad = "" + (pad == null ? "0" : pad);
  29. return n.length == 1 ? pad + n : n;
  30. };
  31. var r = [];
  32. var escape = false;
  33. var hours = d.getHours();
  34. var isAM = hours < 12;
  35. if (monthNames == null) {
  36. monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
  37. }
  38. if (dayNames == null) {
  39. dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
  40. }
  41. var hours12;
  42. if (hours > 12) {
  43. hours12 = hours - 12;
  44. } else if (hours == 0) {
  45. hours12 = 12;
  46. } else {
  47. hours12 = hours;
  48. }
  49. for (var i = 0; i < fmt.length; ++i) {
  50. var c = fmt.charAt(i);
  51. if (escape) {
  52. switch (c) {
  53. case 'a': c = "" + dayNames[d.getDay()]; break;
  54. case 'b': c = "" + monthNames[d.getMonth()]; break;
  55. case 'd': c = leftPad(d.getDate()); break;
  56. case 'e': c = leftPad(d.getDate(), " "); break;
  57. case 'h': // For back-compat with 0.7; remove in 1.0
  58. case 'H': c = leftPad(hours); break;
  59. case 'I': c = leftPad(hours12); break;
  60. case 'l': c = leftPad(hours12, " "); break;
  61. case 'm': c = leftPad(d.getMonth() + 1); break;
  62. case 'M': c = leftPad(d.getMinutes()); break;
  63. // quarters not in Open Group's strftime specification
  64. case 'q':
  65. c = "" + (Math.floor(d.getMonth() / 3) + 1); break;
  66. case 'S': c = leftPad(d.getSeconds()); break;
  67. case 'y': c = leftPad(d.getFullYear() % 100); break;
  68. case 'Y': c = "" + d.getFullYear(); break;
  69. case 'p': c = (isAM) ? ("" + "am") : ("" + "pm"); break;
  70. case 'P': c = (isAM) ? ("" + "AM") : ("" + "PM"); break;
  71. case 'w': c = "" + d.getDay(); break;
  72. }
  73. r.push(c);
  74. escape = false;
  75. } else {
  76. if (c == "%") {
  77. escape = true;
  78. } else {
  79. r.push(c);
  80. }
  81. }
  82. }
  83. return r.join("");
  84. }
  85. // To have a consistent view of time-based data independent of which time
  86. // zone the client happens to be in we need a date-like object independent
  87. // of time zones. This is done through a wrapper that only calls the UTC
  88. // versions of the accessor methods.
  89. function makeUtcWrapper(d) {
  90. function addProxyMethod(sourceObj, sourceMethod, targetObj, targetMethod) {
  91. sourceObj[sourceMethod] = function() {
  92. return targetObj[targetMethod].apply(targetObj, arguments);
  93. };
  94. };
  95. var utc = {
  96. date: d
  97. };
  98. // support strftime, if found
  99. if (d.strftime != undefined) {
  100. addProxyMethod(utc, "strftime", d, "strftime");
  101. }
  102. addProxyMethod(utc, "getTime", d, "getTime");
  103. addProxyMethod(utc, "setTime", d, "setTime");
  104. var props = ["Date", "Day", "FullYear", "Hours", "Milliseconds", "Minutes", "Month", "Seconds"];
  105. for (var p = 0; p < props.length; p++) {
  106. addProxyMethod(utc, "get" + props[p], d, "getUTC" + props[p]);
  107. addProxyMethod(utc, "set" + props[p], d, "setUTC" + props[p]);
  108. }
  109. return utc;
  110. };
  111. // select time zone strategy. This returns a date-like object tied to the
  112. // desired timezone
  113. function dateGenerator(ts, opts) {
  114. if (opts.timezone == "browser") {
  115. return new Date(ts);
  116. } else if (!opts.timezone || opts.timezone == "utc") {
  117. return makeUtcWrapper(new Date(ts));
  118. } else if (typeof timezoneJS != "undefined" && typeof timezoneJS.Date != "undefined") {
  119. var d = new timezoneJS.Date();
  120. // timezone-js is fickle, so be sure to set the time zone before
  121. // setting the time.
  122. d.setTimezone(opts.timezone);
  123. d.setTime(ts);
  124. return d;
  125. } else {
  126. return makeUtcWrapper(new Date(ts));
  127. }
  128. }
  129. // map of app. size of time units in milliseconds
  130. var timeUnitSize = {
  131. "second": 1000,
  132. "minute": 60 * 1000,
  133. "hour": 60 * 60 * 1000,
  134. "day": 24 * 60 * 60 * 1000,
  135. "month": 30 * 24 * 60 * 60 * 1000,
  136. "quarter": 3 * 30 * 24 * 60 * 60 * 1000,
  137. "year": 365.2425 * 24 * 60 * 60 * 1000
  138. };
  139. // the allowed tick sizes, after 1 year we use
  140. // an integer algorithm
  141. var baseSpec = [
  142. [1, "second"], [2, "second"], [5, "second"], [10, "second"],
  143. [30, "second"],
  144. [1, "minute"], [2, "minute"], [5, "minute"], [10, "minute"],
  145. [30, "minute"],
  146. [1, "hour"], [2, "hour"], [4, "hour"],
  147. [8, "hour"], [12, "hour"],
  148. [1, "day"], [2, "day"], [3, "day"],
  149. [0.25, "month"], [0.5, "month"], [1, "month"],
  150. [2, "month"]
  151. ];
  152. // we don't know which variant(s) we'll need yet, but generating both is
  153. // cheap
  154. var specMonths = baseSpec.concat([[3, "month"], [6, "month"],
  155. [1, "year"]]);
  156. var specQuarters = baseSpec.concat([[1, "quarter"], [2, "quarter"],
  157. [1, "year"]]);
  158. function init(plot) {
  159. plot.hooks.processOptions.push(function (plot, options) {
  160. $.each(plot.getAxes(), function(axisName, axis) {
  161. var opts = axis.options;
  162. if (opts.mode == "time") {
  163. axis.tickGenerator = function(axis) {
  164. var ticks = [];
  165. var d = dateGenerator(axis.min, opts);
  166. var minSize = 0;
  167. // make quarter use a possibility if quarters are
  168. // mentioned in either of these options
  169. var spec = (opts.tickSize && opts.tickSize[1] ===
  170. "quarter") ||
  171. (opts.minTickSize && opts.minTickSize[1] ===
  172. "quarter") ? specQuarters : specMonths;
  173. if (opts.minTickSize != null) {
  174. if (typeof opts.tickSize == "number") {
  175. minSize = opts.tickSize;
  176. } else {
  177. minSize = opts.minTickSize[0] * timeUnitSize[opts.minTickSize[1]];
  178. }
  179. }
  180. for (var i = 0; i < spec.length - 1; ++i) {
  181. if (axis.delta < (spec[i][0] * timeUnitSize[spec[i][1]]
  182. + spec[i + 1][0] * timeUnitSize[spec[i + 1][1]]) / 2
  183. && spec[i][0] * timeUnitSize[spec[i][1]] >= minSize) {
  184. break;
  185. }
  186. }
  187. var size = spec[i][0];
  188. var unit = spec[i][1];
  189. // special-case the possibility of several years
  190. if (unit == "year") {
  191. // if given a minTickSize in years, just use it,
  192. // ensuring that it's an integer
  193. if (opts.minTickSize != null && opts.minTickSize[1] == "year") {
  194. size = Math.floor(opts.minTickSize[0]);
  195. } else {
  196. var magn = Math.pow(10, Math.floor(Math.log(axis.delta / timeUnitSize.year) / Math.LN10));
  197. var norm = (axis.delta / timeUnitSize.year) / magn;
  198. if (norm < 1.5) {
  199. size = 1;
  200. } else if (norm < 3) {
  201. size = 2;
  202. } else if (norm < 7.5) {
  203. size = 5;
  204. } else {
  205. size = 10;
  206. }
  207. size *= magn;
  208. }
  209. // minimum size for years is 1
  210. if (size < 1) {
  211. size = 1;
  212. }
  213. }
  214. axis.tickSize = opts.tickSize || [size, unit];
  215. var tickSize = axis.tickSize[0];
  216. unit = axis.tickSize[1];
  217. var step = tickSize * timeUnitSize[unit];
  218. if (unit == "second") {
  219. d.setSeconds(floorInBase(d.getSeconds(), tickSize));
  220. } else if (unit == "minute") {
  221. d.setMinutes(floorInBase(d.getMinutes(), tickSize));
  222. } else if (unit == "hour") {
  223. d.setHours(floorInBase(d.getHours(), tickSize));
  224. } else if (unit == "month") {
  225. d.setMonth(floorInBase(d.getMonth(), tickSize));
  226. } else if (unit == "quarter") {
  227. d.setMonth(3 * floorInBase(d.getMonth() / 3,
  228. tickSize));
  229. } else if (unit == "year") {
  230. d.setFullYear(floorInBase(d.getFullYear(), tickSize));
  231. }
  232. // reset smaller components
  233. d.setMilliseconds(0);
  234. if (step >= timeUnitSize.minute) {
  235. d.setSeconds(0);
  236. }
  237. if (step >= timeUnitSize.hour) {
  238. d.setMinutes(0);
  239. }
  240. if (step >= timeUnitSize.day) {
  241. d.setHours(0);
  242. }
  243. if (step >= timeUnitSize.day * 4) {
  244. d.setDate(1);
  245. }
  246. if (step >= timeUnitSize.month * 2) {
  247. d.setMonth(floorInBase(d.getMonth(), 3));
  248. }
  249. if (step >= timeUnitSize.quarter * 2) {
  250. d.setMonth(floorInBase(d.getMonth(), 6));
  251. }
  252. if (step >= timeUnitSize.year) {
  253. d.setMonth(0);
  254. }
  255. var carry = 0;
  256. var v = Number.NaN;
  257. var prev;
  258. do {
  259. prev = v;
  260. v = d.getTime();
  261. ticks.push(v);
  262. if (unit == "month" || unit == "quarter") {
  263. if (tickSize < 1) {
  264. // a bit complicated - we'll divide the
  265. // month/quarter up but we need to take
  266. // care of fractions so we don't end up in
  267. // the middle of a day
  268. d.setDate(1);
  269. var start = d.getTime();
  270. d.setMonth(d.getMonth() +
  271. (unit == "quarter" ? 3 : 1));
  272. var end = d.getTime();
  273. d.setTime(v + carry * timeUnitSize.hour + (end - start) * tickSize);
  274. carry = d.getHours();
  275. d.setHours(0);
  276. } else {
  277. d.setMonth(d.getMonth() +
  278. tickSize * (unit == "quarter" ? 3 : 1));
  279. }
  280. } else if (unit == "year") {
  281. d.setFullYear(d.getFullYear() + tickSize);
  282. } else {
  283. d.setTime(v + step);
  284. }
  285. } while (v < axis.max && v != prev);
  286. return ticks;
  287. };
  288. axis.tickFormatter = function (v, axis) {
  289. var d = dateGenerator(v, axis.options);
  290. // first check global format
  291. if (opts.timeformat != null) {
  292. return formatDate(d, opts.timeformat, opts.monthNames, opts.dayNames);
  293. }
  294. // possibly use quarters if quarters are mentioned in
  295. // any of these places
  296. var useQuarters = (axis.options.tickSize &&
  297. axis.options.tickSize[1] == "quarter") ||
  298. (axis.options.minTickSize &&
  299. axis.options.minTickSize[1] == "quarter");
  300. var t = axis.tickSize[0] * timeUnitSize[axis.tickSize[1]];
  301. var span = axis.max - axis.min;
  302. var suffix = (opts.twelveHourClock) ? " %p" : "";
  303. var hourCode = (opts.twelveHourClock) ? "%I" : "%H";
  304. var fmt;
  305. if (t < timeUnitSize.minute) {
  306. fmt = hourCode + ":%M:%S" + suffix;
  307. } else if (t < timeUnitSize.day) {
  308. if (span < 2 * timeUnitSize.day) {
  309. fmt = hourCode + ":%M" + suffix;
  310. } else {
  311. fmt = "%b %d " + hourCode + ":%M" + suffix;
  312. }
  313. } else if (t < timeUnitSize.month) {
  314. fmt = "%b %d";
  315. } else if ((useQuarters && t < timeUnitSize.quarter) ||
  316. (!useQuarters && t < timeUnitSize.year)) {
  317. if (span < timeUnitSize.year) {
  318. fmt = "%b";
  319. } else {
  320. fmt = "%b %Y";
  321. }
  322. } else if (useQuarters && t < timeUnitSize.year) {
  323. if (span < timeUnitSize.year) {
  324. fmt = "Q%q";
  325. } else {
  326. fmt = "Q%q %Y";
  327. }
  328. } else {
  329. fmt = "%Y";
  330. }
  331. var rt = formatDate(d, fmt, opts.monthNames, opts.dayNames);
  332. return rt;
  333. };
  334. }
  335. });
  336. });
  337. }
  338. $.plot.plugins.push({
  339. init: init,
  340. options: options,
  341. name: 'time',
  342. version: '1.0'
  343. });
  344. // Time-axis support used to be in Flot core, which exposed the
  345. // formatDate function on the plot object. Various plugins depend
  346. // on the function, so we need to re-expose it here.
  347. $.plot.formatDate = formatDate;
  348. $.plot.dateGenerator = dateGenerator;
  349. })(jQuery);