jquery.timeago.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. /**
  2. * Timeago is a jQuery plugin that makes it easy to support automatically
  3. * updating fuzzy timestamps (e.g. "4 minutes ago" or "about 1 day ago").
  4. *
  5. * @name timeago
  6. * @version 1.5.4
  7. * @requires jQuery v1.2.3+
  8. * @author Ryan McGeary
  9. * @license MIT License - http://www.opensource.org/licenses/mit-license.php
  10. *
  11. * For usage and examples, visit:
  12. * http://timeago.yarp.com/
  13. *
  14. * Copyright (c) 2008-2017, Ryan McGeary (ryan -[at]- mcgeary [*dot*] org)
  15. */
  16. (function (factory) {
  17. if (typeof define === 'function' && define.amd) {
  18. // AMD. Register as an anonymous module.
  19. define(['jquery'], factory);
  20. } else if (typeof module === 'object' && typeof module.exports === 'object') {
  21. factory(require('jquery'));
  22. } else {
  23. // Browser globals
  24. factory(jQuery);
  25. }
  26. }(function ($) {
  27. $.timeago = function(timestamp) {
  28. if (timestamp instanceof Date) {
  29. return inWords(timestamp);
  30. } else if (typeof timestamp === "string") {
  31. return inWords($.timeago.parse(timestamp));
  32. } else if (typeof timestamp === "number") {
  33. return inWords(new Date(timestamp));
  34. } else {
  35. return inWords($.timeago.datetime(timestamp));
  36. }
  37. };
  38. var $t = $.timeago;
  39. $.extend($.timeago, {
  40. settings: {
  41. refreshMillis: 60000,
  42. allowPast: true,
  43. allowFuture: false,
  44. localeTitle: false,
  45. cutoff: 0,
  46. autoDispose: true,
  47. strings: {
  48. prefixAgo: null,
  49. prefixFromNow: null,
  50. suffixAgo: "ago",
  51. suffixFromNow: "from now",
  52. inPast: 'any moment now',
  53. seconds: "less than a minute",
  54. minute: "about a minute",
  55. minutes: "%d minutes",
  56. hour: "about an hour",
  57. hours: "about %d hours",
  58. day: "a day",
  59. days: "%d days",
  60. month: "about a month",
  61. months: "%d months",
  62. year: "about a year",
  63. years: "%d years",
  64. wordSeparator: " ",
  65. numbers: []
  66. }
  67. },
  68. inWords: function(distanceMillis) {
  69. if (!this.settings.allowPast && ! this.settings.allowFuture) {
  70. throw 'timeago allowPast and allowFuture settings can not both be set to false.';
  71. }
  72. var $l = this.settings.strings;
  73. var prefix = $l.prefixAgo;
  74. var suffix = $l.suffixAgo;
  75. if (this.settings.allowFuture) {
  76. if (distanceMillis < 0) {
  77. prefix = $l.prefixFromNow;
  78. suffix = $l.suffixFromNow;
  79. }
  80. }
  81. if (!this.settings.allowPast && distanceMillis >= 0) {
  82. return this.settings.strings.inPast;
  83. }
  84. var seconds = Math.abs(distanceMillis) / 1000;
  85. var minutes = seconds / 60;
  86. var hours = minutes / 60;
  87. var days = hours / 24;
  88. var years = days / 365;
  89. function substitute(stringOrFunction, number) {
  90. var string = $.isFunction(stringOrFunction) ? stringOrFunction(number, distanceMillis) : stringOrFunction;
  91. var value = ($l.numbers && $l.numbers[number]) || number;
  92. return string.replace(/%d/i, value);
  93. }
  94. var words = seconds < 45 && substitute($l.seconds, Math.round(seconds)) ||
  95. seconds < 90 && substitute($l.minute, 1) ||
  96. minutes < 45 && substitute($l.minutes, Math.round(minutes)) ||
  97. minutes < 90 && substitute($l.hour, 1) ||
  98. hours < 24 && substitute($l.hours, Math.round(hours)) ||
  99. hours < 42 && substitute($l.day, 1) ||
  100. days < 30 && substitute($l.days, Math.round(days)) ||
  101. days < 45 && substitute($l.month, 1) ||
  102. days < 365 && substitute($l.months, Math.round(days / 30)) ||
  103. years < 1.5 && substitute($l.year, 1) ||
  104. substitute($l.years, Math.round(years));
  105. var separator = $l.wordSeparator || "";
  106. if ($l.wordSeparator === undefined) { separator = " "; }
  107. return $.trim([prefix, words, suffix].join(separator));
  108. },
  109. parse: function(iso8601) {
  110. var s = $.trim(iso8601);
  111. s = s.replace(/\.\d+/,""); // remove milliseconds
  112. s = s.replace(/-/,"/").replace(/-/,"/");
  113. s = s.replace(/T/," ").replace(/Z/," UTC");
  114. s = s.replace(/([\+\-]\d\d)\:?(\d\d)/," $1$2"); // -04:00 -> -0400
  115. s = s.replace(/([\+\-]\d\d)$/," $100"); // +09 -> +0900
  116. return new Date(s);
  117. },
  118. datetime: function(elem) {
  119. var iso8601 = $t.isTime(elem) ? $(elem).attr("datetime") : $(elem).attr("title");
  120. return $t.parse(iso8601);
  121. },
  122. isTime: function(elem) {
  123. // jQuery's `is()` doesn't play well with HTML5 in IE
  124. return $(elem).get(0).tagName.toLowerCase() === "time"; // $(elem).is("time");
  125. }
  126. });
  127. // functions that can be called via $(el).timeago('action')
  128. // init is default when no action is given
  129. // functions are called with context of a single element
  130. var functions = {
  131. init: function() {
  132. functions.dispose.call(this);
  133. var refresh_el = $.proxy(refresh, this);
  134. refresh_el();
  135. var $s = $t.settings;
  136. if ($s.refreshMillis > 0) {
  137. this._timeagoInterval = setInterval(refresh_el, $s.refreshMillis);
  138. }
  139. },
  140. update: function(timestamp) {
  141. var date = (timestamp instanceof Date) ? timestamp : $t.parse(timestamp);
  142. $(this).data('timeago', { datetime: date });
  143. if ($t.settings.localeTitle) {
  144. $(this).attr("title", date.toLocaleString());
  145. }
  146. refresh.apply(this);
  147. },
  148. updateFromDOM: function() {
  149. $(this).data('timeago', { datetime: $t.parse( $t.isTime(this) ? $(this).attr("datetime") : $(this).attr("title") ) });
  150. refresh.apply(this);
  151. },
  152. dispose: function () {
  153. if (this._timeagoInterval) {
  154. window.clearInterval(this._timeagoInterval);
  155. this._timeagoInterval = null;
  156. }
  157. }
  158. };
  159. $.fn.timeago = function(action, options) {
  160. var fn = action ? functions[action] : functions.init;
  161. if (!fn) {
  162. throw new Error("Unknown function name '"+ action +"' for timeago");
  163. }
  164. // each over objects here and call the requested function
  165. this.each(function() {
  166. fn.call(this, options);
  167. });
  168. return this;
  169. };
  170. function refresh() {
  171. var $s = $t.settings;
  172. //check if it's still visible
  173. if ($s.autoDispose && !$.contains(document.documentElement,this)) {
  174. //stop if it has been removed
  175. $(this).timeago("dispose");
  176. return this;
  177. }
  178. var data = prepareData(this);
  179. if (!isNaN(data.datetime)) {
  180. if ( $s.cutoff === 0 || Math.abs(distance(data.datetime)) < $s.cutoff) {
  181. $(this).text(inWords(data.datetime));
  182. } else {
  183. if ($(this).attr('title').length > 0) {
  184. $(this).text($(this).attr('title'));
  185. }
  186. }
  187. }
  188. return this;
  189. }
  190. function prepareData(element) {
  191. element = $(element);
  192. if (!element.data("timeago")) {
  193. element.data("timeago", { datetime: $t.datetime(element) });
  194. var text = $.trim(element.text());
  195. if ($t.settings.localeTitle) {
  196. element.attr("title", element.data('timeago').datetime.toLocaleString());
  197. } else if (text.length > 0 && !($t.isTime(element) && element.attr("title"))) {
  198. element.attr("title", text);
  199. }
  200. }
  201. return element.data("timeago");
  202. }
  203. function inWords(date) {
  204. return $t.inWords(distance(date));
  205. }
  206. function distance(date) {
  207. return (new Date().getTime() - date.getTime());
  208. }
  209. // fix for IE6 suckage
  210. document.createElement("abbr");
  211. document.createElement("time");
  212. }));