User:Mxn/CommentsInLocalTime/sandbox.js: Difference between revisions

Content deleted Content added
 
Migrate to Intl.RelativeTimeFormat and Intl.DateTimeFormat
Line 10:
* @author [[User:Mxn]]
*/
 
const DateFormatter = require("mediawiki.DateFormatter");
 
/**
Line 229 ⟶ 231:
/**
* Returns a formatted string for the given momentdate object.
*
* @param {MomentDate} then The momentdate object to format.
* @param {String} fmt A format string or function.
* @returns {String} A formatted string.
*/
function formatMomentformatDate(then, fmt) {
returnif (fmt instanceof Function) ? fmt(then) : then.format(fmt);{
return fmt(then);
} else {
}
}
}
Line 247 ⟶ 253:
function formatTimestamp(idx, elt) {
var iso = $(elt).attr("datetime");
var then = moment(iso,new momentDate(Date.ISO_8601parse(iso));
var now = momentnew Date();
var withinHours = Math.abs(then.diff(now, "hours", true))
<= moment.relativeTimeThreshold("h");
var formats = LocalComments.formats;
var lang = mw.config.get("wgPageViewLanguage");
var text;
if (withinHours) {
text = formatMoment(then, formats.day || formats.other);
}
else {
var dayDiff = then.diff(moment().startOf("day"), "days", true);
if (dayDiff > -6 && dayDiff < 7) {
text = formatMoment(then, formats.week || formats.other);
}
else text = formatMoment(then, formats.other);
}
$(elt).text(text);
// Add a tooltip with multiple formats.
elt.title = $.map(LocalComments.tooltipFormats, function (fmt, idx) {
return formatMomentformatDate(then, fmt);
}).join("\n");
// Register for periodic updates.
var value;
var withinMinutes = withinHours
var unit;
&& Math.abs(then.diff(now, "minutes", true))
var seconds = (now - then) / 1000; // convert ms to s
<= moment.relativeTimeThreshold("m");
value = seconds;
var withinSeconds = withinMinutes
&&unit Math.abs(then.diff(now,= "seconds", true));
var minutes = seconds / 60;
<=if (Math.abs(seconds) > 45) { // moment.relativeTimeThreshold("s");
var unit = withinSeconds ? "seconds" :
(withinMinutesvalue ?= "minutes" :;
unit = "minutes";
(withinHours ? "hours" : "days"));
}
var hours = minutes / 60;
<=if (Math.abs(minutes) > 45) { // moment.relativeTimeThreshold("m");
value = hours;
unit = "hours";
}
var days = hours / 24;
<=if (Math.abs(hours) > 22) { // moment.relativeTimeThreshold("h");
value = days;
unit = "days";
}
var weeks = days / 7;
if (Math.abs(days) > 7) {
value = weeks;
unit = "weeks";
}
$(elt).attr("data-localcomments-unit", unit);
// Replace the text.
var format;
var text;
if (unit === "weeks") {
format = new Intl.DateTimeFormat(lang, {dateStyle: "long", timeStyle: "short"});
text = format.format(then);
} else {
format = new Intl.RelativeTimeFormat(lang, {numeric: "auto"});
text = format.format(Math.round(value), unit);
}
$(elt).text(text);
}