blob: 04a5c12b92959e966ce6b1adaef8fffecc3def1e [file] [log] [blame]
Luigi Santivettid93cb0f2020-02-17 22:21:28 +00001var lw_timeago = function() {
2
3 var config = {
4 whitelist: "data-timeago", // Set to null to disable whitelisting
5
6 keepDate: true, // If true, appends the original date after the fuzzy one
7
8 suffixAgo: "ago",
9 suffixFromNow: "from now",
10 on: "on",
11
12 seconds: "less than a minute",
13 minute: "about a minute",
14 minutes: "%d minutes",
15 hour: "about an hour",
16 hours: "%d hours",
17 day: "about a day",
18 days: "%d days",
19 month: "about a month",
20 months: "%d months",
21 year: "about a year",
22 years: "%d years",
23 }
24
25 function inWords(distanceMillis) {
26 // Produce a string representing the milliseconds in a human-readable way
27
28 var suffix = distanceMillis < 0 ? config.suffixFromNow : config.suffixAgo;
29 var seconds = Math.abs(distanceMillis) / 1000;
30 var minutes = seconds / 60;
31 var hours = minutes / 60;
32 var days = hours / 24;
33 var years = days / 365;
34
35 function substitute(string, number) {
36 return string.replace(/%d/i, number);
37 }
38
39 var words =
40 seconds < 45 && substitute(config.seconds, Math.round(seconds)) ||
41 seconds < 90 && substitute(config.minute, 1) ||
42 minutes < 45 && substitute(config.minutes, Math.round(minutes)) ||
43 minutes < 90 && substitute(config.hour, 1) ||
44 hours < 24 && substitute(config.hours, Math.round(hours)) ||
45 hours < 42 && substitute(config.day, 1) ||
46 days < 30 && substitute(config.days, Math.round(days)) ||
47 days < 45 && substitute(config.month, 1) ||
48 days < 365 && substitute(config.months, Math.round(days / 30)) ||
49 years < 1.5 && substitute(config.year, 1) ||
50 substitute(config.years, Math.round(years));
51
52 return words + " " + suffix;
53 }
54
55 function diff(timestamp) {
56 // Get the number of milliseconds distance from the current time
57 return Date.now() - timestamp;
58 }
59
60 function doReplace(){
61 // Go over all <time> elements, grab the datetime attribute, then calculate
62 // and display a fuzzy representation of it.
63
64 var times = document.getElementsByTagName("time")
65 for (var i = 0; i < times.length; i++){
66
67 if (config.whitelist && !times[i].hasAttribute(config.whitelist))
68 break;
69
70 var datetime = times[i].getAttribute("datetime");
71 if (!datetime)
72 break;
73
74 var parsed = new Date(datetime);
75 if (!parsed)
76 break;
77
78 var words = inWords(diff(parsed.getTime()));
79 var title = times[i].innerHTML;
80 if (config.keepDate){
81 words += " " + config.on + " " + times[i].innerHTML;
82 title = parsed.toLocaleString()
83 }
84
85 times[i].title = title;
86 times[i].innerHTML = words;
87 }
88 }
89
90 return doReplace;
91}();