User:Gary/comments in local time.js: Difference between revisions

Content deleted Content added
Major restructuring
fixes
 
(22 intermediate revisions by 3 users not shown)
Line 1:
// Generated by CoffeeScript 1.7.1
 
/**
* COMMENTS IN LOCAL TIME
Line 11 ⟶ 9:
* [[Wikipedia:Comments in Local Time]]
*/
$(() => {
var CommentsInLocalTime;
/**
* Given a number, add a leading zero if necessary, so that the final number
* has two characters.
*
* @param {number} number Number
* @returns {string} The number with a leading zero, if necessary.
*/
function addLeadingZero(number) {
const numberArg = number;
 
if (numberArg < 10) {
CommentsInLocalTime = (function() {
return `0${numberArg}`;
var LocalComments, language;
}
 
return numberArg;
function CommentsInLocalTime() {}
}
 
function convertMonthToNumber(month) {
language = '';
return new Date(`${month} 1, 2001`).getMonth();
 
if (typeof LocalComments === "undefined" || LocalComments === null) {
LocalComments = {};
}
 
function getDates(time) {
const [, oldHour, oldMinute, oldDay, oldMonth, oldYear] = time;
 
/*/ Today
const today = new Date();
Language
LOCALIZING THIS SCRIPT
To localize this script, change the terms below,
to the RIGHT of the colons, to the correct term used in that language.
For example, in the French language,
'Today' : 'Today',
would be
'Today' : "Aujourd'hui",
*/
 
// Yesterday
LocalComments.language = {
const yesterday = new Date();
 
yesterday.setDate(yesterday.getDate() - 1);
/* relative terms */
'Today': 'Today',
'Yesterday': 'Yesterday',
'Tomorrow': 'Tomorrow',
'last': 'last',
'this': 'this',
 
/*/ days of the week */Tomorrow
const tomorrow = new Date();
'Sunday': 'Sunday',
'Monday': 'Monday',
'Tuesday': 'Tuesday',
'Wednesday': 'Wednesday',
'Thursday': 'Thursday',
'Friday': 'Friday',
'Saturday': 'Saturday',
 
tomorrow.setDate(tomorrow.getDate() + 1);
/* months of the year */
'January': 'January',
'February': 'February',
'March': 'March',
'April': 'April',
'May': 'May',
'June': 'June',
'July': 'July',
'August': 'August',
'September': 'September',
'October': 'October',
'November': 'November',
'December': 'December',
 
/*/ differenceSet wordsthe */date entered.
const newTime = new Date();
'ago': 'ago',
'from now': 'from now',
 
newTime.setUTCFullYear(oldYear, convertMonthToNumber(oldMonth), oldDay);
/* date phrases */
newTime.setUTCHours(oldHour);
'year': 'year',
newTime.setUTCMinutes(oldMinute);
'years': 'years',
'month': 'month',
'months': 'months',
'day': 'day',
'days': 'days'
};
 
return { time: newTime, today, tomorrow, yesterday };
}
 
/**
* Determine whether to use the singular or plural word, and use that.
APPLICATION
*
* @param {string} term Original term
* @param {number} count Count of items
* @param {string} plural Pluralized term
* @returns {string} The word to use
*/
function pluralize(term, count, plural = null) {
let pluralArg = plural;
 
// No unique pluralized word is found, so just use a general one.
CommentsInLocalTime.init = function() {
if (!pluralArg) {
pluralArg = `${term}s`;
}
 
// There's only one item, so just use the singular word.
/*
if (count Settings=== 1) {
*/ return term;
var contentText, namespace, pageAction;
if (LocalComments.language == null) {
return false;
}
language = this.setDefaultSetting('language', LocalComments.language);
this.setDefaultSetting({
'dateDifference': true,
'dateFormat': 'dmy',
'dayOfWeek': true,
'dropDays': 0,
'dropMonths': 0,
'timeFirst': true,
'twentyFourHours': false
});
 
// There are multiple items, so use the plural word.
/*
return End SettingspluralArg;
*/}
 
namespace = mw.config.get('wgCanonicalNamespace');
class CommentsInLocalTime {
pageAction = mw.config.get('wgAction');
constructor() {
if (['', 'MediaWiki', 'Special'].indexOf(namespace) > -1 || pageAction === 'history') {
returnthis.language false= '';
this.LocalComments = {};
 
/**
* Settings
*/
this.settings();
 
this.language = this.setDefaultSetting(
'language',
this.LocalComments.language
);
 
// These values are also reflected in the documentation:
// https://en.wikipedia.org/wiki/Wikipedia:Comments_in_Local_Time#Default_settings
this.setDefaultSetting({
dateDifference: true,
dateFormat: 'dmy',
dayOfWeek: true,
dropDays: 0,
dropMonths: 0,
timeFirst: true,
twentyFourHours: false,
});
}
 
contentText = document.getElementById('mw-content-text');
adjustTime(originalTimestamp, search) {
if (mw.config.get('wgAction') !== 'view' || (contentText == null)) {
const { time, today, tomorrow, yesterday } = getDates(
return false;
originalTimestamp.match(search)
);
 
// A string matching the date pattern was found, but it cannot be
// converted to a Date object. Return it with no changes made.
if (Number.isNaN(time)) {
return [originalTimestamp, ''];
}
 
const date = this.determineDateText({
time,
today,
tomorrow,
yesterday,
});
 
const { ampm, hour } = this.getHour(time);
const minute = addLeadingZero(time.getMinutes());
const finalTime = `${hour}:${minute}${ampm}`;
 
// Determine the time offset.
const utcValue = (-1 * time.getTimezoneOffset()) / 60;
const utcOffset =
utcValue >= 0 ? `+${utcValue}` : `−${Math.abs(utcValue.toFixed(1))}`;
 
const utcPart = `(UTC${utcOffset})`;
 
const returnDate = this.LocalComments.timeFirst
? `${finalTime}, ${date} ${utcPart}`
: `${date}, ${finalTime} ${utcPart}`;
 
return returnDate;
}
return this.replaceText(contentText, /(\d{1,2}):(\d{2}), (\d{1,2}) ([A-Z][a-z]+) (\d{4}) \(UTC\)/);
};
 
convertNumberToMonth(number) {
CommentsInLocalTime.replaceText = function(node, search) {
return [
var after, afterMatch, before, beforeMatch, child, children, length, match, matches, parent, position, span, timeArray, timestamp, value, _i, _len, _results;
this.language.January,
if (!node) {
this.language.February,
return false;
this.language.March,
this.language.April,
this.language.May,
this.language.June,
this.language.July,
this.language.August,
this.language.September,
this.language.October,
this.language.November,
this.language.December,
][number];
}
 
if (node.nodeType === 3) {
createDateText({ day, month, time, today, year }) {
value = node.nodeValue;
// Calculate day of week
matches = value.match(search);
ifconst (matchesdayNames != null) {[
match = matches[0];this.language.Sunday,
position = valuethis.search(search);language.Monday,
length = matchthis.toString()language.length;Tuesday,
this.language.Wednesday,
beforeMatch = value.substring(0, position);
this.language.Thursday,
afterMatch = value.substring(position + length);
timeArray = this.adjustTime(matchlanguage.toString()Friday, search);
this.language.Saturday,
timestamp = timeArray[1] ? timeArray[1].getTime() : '';
];
span = document.createElement('span');
const span.classNamedayOfTheWeek = 'localcomments'dayNames[time.getDay()];
let span.style.fontSizedescriptiveDifference = '95%';
let span.style.whiteSpacelast = 'nowrap';
 
span.setAttribute('timestamp', timestamp);
// Create a relative descriptive difference
span.title = match;
if (this.LocalComments.dateDifference) {
span.appendChild(document.createTextNode(timeArray[0]));
({ descriptiveDifference, last } = this.createRelativeDate(
parent = node.parentNode;
parent.replaceChild(span, node); today,
before = document.createElement('span');time
));
before.className = 'before-localcomments';
before.appendChild(document.createTextNode(beforeMatch));
after = document.createElement('span');
after.className = 'after-localcomments';
after.appendChild(document.createTextNode(afterMatch));
parent.insertBefore(before, span);
return parent.insertBefore(after, span.nextSibling);
}
 
} else {
const monthName = this.convertNumberToMonth(time.getMonth());
children = [];
 
child = node.childNodes[0];
// Format the date according to user preferences
while (child) {
let formattedDate = '';
children.push(child);
 
child = child.nextSibling;
switch (this.LocalComments.dateFormat.toLowerCase()) {
case 'dmy':
formattedDate = `${day} ${monthName} ${year}`;
 
break;
case 'mdy':
formattedDate = `${monthName} ${day}, ${year}`;
 
break;
default:
formattedDate = `${year}-${month}-${addLeadingZero(day)}`;
}
_results = [];
for (_i = 0, _len = children.length; _i < _len; _i++) {
child = children[_i];
_results.push(this.replaceText(child, search));
}
return _results;
}
};
 
const formattedDayOfTheWeek = this.LocalComments.dayOfWeek
CommentsInLocalTime.adjustTime = function(originalTimestamp, search) {
? `, ${last}${dayOfTheWeek}`
var ampm, date, day, dayNames, dayOfTheWeek, descriptiveDifference, finalTime, formattedDate, formattedDayOfTheWeek, hour, last, minute, month, monthName, oldDay, oldHour, oldMinute, oldMonth, oldYear, returnDate, time, today, tomorrow, utcOffset, year, yesterday, _ref, _ref1;
: '';
time = originalTimestamp.match(search);
 
_ref = [time[1], time[2], time[3], time[4], time[5]], oldHour = _ref[0], oldMinute = _ref[1], oldDay = _ref[2], oldMonth = _ref[3], oldYear = _ref[4];
return `${formattedDate}${formattedDayOfTheWeek}${descriptiveDifference}`;
today = new Date();
yesterday = new Date();
tomorrow = new Date();
yesterday.setDate(yesterday.getDate() - 1);
tomorrow.setDate(tomorrow.getDate() + 1);
time = new Date();
time.setUTCFullYear(oldYear, this.convertMonthToNumber(oldMonth), oldDay);
time.setUTCHours(oldHour);
time.setUTCMinutes(oldMinute);
if (isNaN(time)) {
return [originalTimestamp, ''];
}
 
utcOffset = -1 * time.getTimezoneOffset() / 60;
/**
utcOffset = utcOffset >= 0 ? '+' + utcOffset : '−' + Math.abs(utcOffset);
* Create relative date data.
year = time.getFullYear();
*
month = this.addLeadingZero(time.getMonth() + 1);
* @param {Date} today Today
day = time.getDate();
* @param {Date} time The timestamp from a comment
hour = parseInt(time.getHours());
* @returns {Object.<string, *>} Relative date data
minute = this.addLeadingZero(time.getMinutes());
ampm = '';*/
createRelativeDate(today, time) {
if (LocalComments.twentyFourHours) {
/**
hour = this.addLeadingZero(hour);
* The time difference from today, in milliseconds.
} else {
*
ampm = hour <= 11 ? ' am' : ' pm';
if (hour* > 12)@type {number}
hour -= 12;*/
const millisecondsAgo = today.getTime() - time.getTime();
} else if (hour === 0) {
 
hour = 12;
/**
* The number of days ago, that we will display. It's not necessarily the
* total days ago.
*
* @type {number}
*/
let daysAgo = Math.abs(Math.round(millisecondsAgo / 1000 / 60 / 60 / 24));
const { differenceWord, last } = this.relativeText({
daysAgo,
millisecondsAgo,
});
 
// This method of computing the years and months is not exact. However,
// it's better than the previous method that used 1 January + delta days.
// That was usually quite off because it mapped the second delta month to
// February, which has only 28 days. This method is usually not more than
// one day off, except perhaps over very distant dates.
 
/**
* The number of months ago, that we will display. It's not necessarily
* the total months ago.
*
* @type {number}
*/
let monthsAgo = Math.floor((daysAgo / 365) * 12);
 
/**
* The total amount of time ago, in months.
*
* @type {number}
*/
const totalMonthsAgo = monthsAgo;
 
/**
* The number of years ago that we will display. It's not necessarily the
* total years ago.
*
* @type {number}
*/
let yearsAgo = Math.floor(totalMonthsAgo / 12);
 
if (totalMonthsAgo < this.LocalComments.dropMonths) {
yearsAgo = 0;
} else if (this.LocalComments.dropMonths > 0) {
monthsAgo = 0;
} else {
monthsAgo -= yearsAgo * 12;
}
 
}
if (daysAgo < this.LocalComments.dropDays) {
if (year === today.getFullYear() && month === this.addLeadingZero(today.getMonth() + 1) && day === today.getDate()) {
date monthsAgo = language['Today']0;
yearsAgo = 0;
} else if (year === yesterday.getFullYear() && month === this.addLeadingZero(yesterday.getMonth() + 1) && day === yesterday.getDate()) {
} else if (this.LocalComments.dropDays > 0 && totalMonthsAgo >= 1) {
date = language['Yesterday'];
daysAgo = 0;
} else if (year === tomorrow.getFullYear() && month === this.addLeadingZero(tomorrow.getMonth() + 1) && day === tomorrow.getDate()) {
date} =else language['Tomorrow'];{
daysAgo -= Math.floor((totalMonthsAgo * 365) / 12);
} else {
dayNames = [language['Sunday'], language['Monday'], language['Tuesday'], language['Wednesday'], language['Thursday'], language['Friday'], language['Saturday']];
dayOfTheWeek = dayNames[time.getDay()];
descriptiveDifference = '';
last = '';
if (LocalComments.dateDifference) {
_ref1 = this.createRelativeDate(today, time), descriptiveDifference = _ref1.descriptiveDifference, last = _ref1.last;
}
 
formattedDate = '';
const descriptiveParts = [];
monthName = this.convertNumberToMonth(time.getMonth());
 
formattedDate = (function() {
// There is years text to add.
switch (LocalComments.dateFormat.toLowerCase()) {
if (yearsAgo > 0) case 'dmy':{
descriptiveParts.push(
return day + ' ' + monthName + ' ' + year;
case`${yearsAgo} 'mdy':${pluralize(
return monthName + ' ' + day + ', ' + this.language.year;,
default: yearsAgo,
return year + '-' + month + '-' + this.addLeadingZero(day);language.years
)}`
}).call(this );
formattedDayOfTheWeek = '';
if (LocalComments.dayOfWeek) {
formattedDayOfTheWeek = ', ' + last + dayOfTheWeek;
}
 
date = formattedDate + formattedDayOfTheWeek + descriptiveDifference;
// There is months text to add.
if (monthsAgo > 0) {
descriptiveParts.push(
`${monthsAgo} ${pluralize(
this.language.month,
monthsAgo,
this.language.months
)}`
);
}
 
// There is days text to add.
if (daysAgo > 0) {
descriptiveParts.push(
`${daysAgo} ${pluralize(
this.language.day,
daysAgo,
this.language.days
)}`
);
}
 
return {
descriptiveDifference: ` (${descriptiveParts.join(
', '
)} ${differenceWord})`,
last,
};
}
finalTime = hour + ':' + minute + ampm;
if (LocalComments.timeFirst) {
returnDate = finalTime + ', ' + date + ' (UTC' + utcOffset + ')';
} else {
returnDate = date + ', ' + finalTime + ' (UTC' + utcOffset + ')';
}
return [returnDate, time];
};
 
determineDateText({ time, today, tomorrow, yesterday }) {
CommentsInLocalTime.createRelativeDate = function(today, time) {
// Set the date bits to output.
var daysAgo, descriptiveParts, differenceWord, fmtDays, fmtMonths, fmtYears, last, millisecondsAgo, monthsAgo, totalMonthsAgo, yearsAgo;
millisecondsAgo = today.getTime()const -year = time.getTimegetFullYear();
const month = addLeadingZero(time.getMonth() + 1);
daysAgo = Math.abs(Math.round(millisecondsAgo / 1000 / 60 / 60 / 24));
differenceWord const day = ''time.getDate();
 
last = '';
// Return 'today' or 'yesterday' if that is the case
if (millisecondsAgo >= 0) {
if (
differenceWord = language['ago'];
if (daysAgo <year === 7today.getFullYear() {&&
lastmonth === language['last']addLeadingZero(today.getMonth() + '1) ';&&
day === today.getDate()
) {
return this.language.Today;
}
 
} else {
if (
differenceWord = language['from now'];
if (daysAgo <year === 7yesterday.getFullYear() {&&
lastmonth === language['this']addLeadingZero(yesterday.getMonth() + '1) ';&&
day === yesterday.getDate()
) {
return this.language.Yesterday;
}
 
if (
year === tomorrow.getFullYear() &&
month === addLeadingZero(tomorrow.getMonth() + 1) &&
day === tomorrow.getDate()
) {
return this.language.Tomorrow;
}
 
return this.createDateText({ day, month, time, today, year });
}
 
monthsAgo = Math.floor(daysAgo / 365 * 12);
getHour(time) {
totalMonthsAgo = monthsAgo;
let ampm;
yearsAgo = Math.floor(monthsAgo / 12);
let hour = Number.parseInt(time.getHours(), 10);
if (monthsAgo < LocalComments.dropMonths) {
 
yearsAgo = 0;
} else if (this.LocalComments.dropMonths > 0twentyFourHours) {
monthsAgo ampm = 0'';
hour = addLeadingZero(hour);
} else {
} else {
monthsAgo = monthsAgo - yearsAgo * 12;
// Output am or pm depending on the date.
}
ampm = hour <= 11 ? ' am' : ' pm';
if (daysAgo < LocalComments.dropDays) {
 
monthsAgo = 0;
yearsAgo = 0;if (hour > 12) {
hour -= 12;
} else if (LocalComments.dropDays > 0) {
daysAgo } else if (hour === 0;) {
} else { hour = 12;
}
daysAgo = daysAgo - Math.floor(totalMonthsAgo * 365 / 12);
}
 
descriptiveParts = [];
if (yearsAgo > 0)return { ampm, hour };
fmtYears = yearsAgo + ' ' + this.pluralize(language['year'], yearsAgo, language['years']);
descriptiveParts.push(fmtYears);
}
if (monthsAgo > 0) {
fmtMonths = monthsAgo + ' ' + this.pluralize(language['month'], monthsAgo, language['months']);
descriptiveParts.push(fmtMonths);
}
if (daysAgo > 0) {
fmtDays = daysAgo + ' ' + this.pluralize(language['day'], daysAgo, language['days']);
descriptiveParts.push(fmtDays);
}
return {
descriptiveDifference: ' (' + descriptiveParts.join(', ') + ' ' + differenceWord + ')',
last: last
};
};
 
relativeText({ daysAgo, millisecondsAgo }) {
let differenceWord = '';
let last = '';
 
// The date is in the past.
/*
if (millisecondsAgo >= 0) {
HELPERS
differenceWord = this.language.ago;
*/
 
if (daysAgo <= 7) {
CommentsInLocalTime.addLeadingZero = function(number) {
last = `${this.language.last} `;
if (number < 10) {
number = '0' + number;}
 
// The date is in the future.
} else {
differenceWord = this.language['from now'];
 
if (daysAgo <= 7) {
last = `${this.language.this} `;
}
}
 
return { differenceWord, last };
}
return number;
};
 
replaceText(node, search) {
CommentsInLocalTime.convertMonthToNumber = function(month) {
if (!node) {
return (new Date(month + ' 1, 2001')).getMonth();
return;
};
}
 
// Check if this is a text node.
CommentsInLocalTime.convertNumberToMonth = function(number) {
if (node.nodeType === 3) {
return [language['January'], language['February'], language['March'], language['April'], language['May'], language['June'], language['July'], language['August'], language['September'], language['October'], language['November'], language['December']][number];
// Don't continue if this text node's parent tag is one of these.
};
if (['CODE', 'PRE'].includes(node.parentNode.nodeName)) {
return;
}
 
const value = node.nodeValue;
CommentsInLocalTime.pluralize = function(term, count, plural) {
const matches = value.match(search);
if (plural === null) {
 
plural = term + 's';
if (matches) {
// Only act on the first timestamp we found in this node. This is for
// the rare occassion that there is more than one timestamp in the
// same text node.
const [match] = matches;
const position = value.search(search);
const stringLength = match.toString().length;
 
// Grab the text content before and after the matching timestamp,
// which we'll then wrap in their own SPAN nodes.
const beforeMatch = value.slice(0, position);
const afterMatch = value.slice(position + stringLength);
const returnDate = this.adjustTime(match.toString(), search);
 
// Create the code to display the new local comments content.
const $span = $(
`<span class="localcomments" style="font-size: 95%;" title="${match}">${returnDate}</span>`
);
 
// Replace the existing text node in the page with our new local
// comments node.
$(node).replaceWith($span);
 
// Replace the text content that appears before the timestamp.
if (beforeMatch) {
$span.before(
`<span class="before-localcomments">${beforeMatch}</span>`
);
}
 
// Replace the text content that appears after the timestamp.
if (afterMatch) {
$span.after(
`<span class="after-localcomments">${afterMatch}</span>`
);
}
}
} else {
const children = [];
let child;
 
[child] = node.childNodes;
 
while (child) {
children.push(child);
child = child.nextSibling;
}
 
// Loop through children and run this func on it again, recursively.
children.forEach((child2) => {
this.replaceText(child2, search);
});
}
}
if (count === 1) {
return term;
} else {
return plural;
}
};
 
run() {
CommentsInLocalTime.setDefaultSetting = function() {
if (
var defaultSetting, name, settings;
['', 'MediaWiki', 'Special'].includes(
if (!arguments.length) {
mw.config.get('wgCanonicalNamespace')
return false;
)
) {
return;
}
 
// Check for disabled URLs.
const isDisabledUrl = ['action=history'].some((disabledUrl) =>
document.___location.href.includes(disabledUrl)
);
 
if (isDisabledUrl) {
return;
}
 
this.replaceText(
document.querySelector('.mw-body-content .mw-parser-output'),
/(\d{1,2}):(\d{2}), (\d{1,2}) ([A-Z][a-z]+) (\d{4}) \(UTC\)/
);
}
 
if (typeof arguments[0] === 'object') {
setDefaultSetting(...args) {
settings = arguments[0];
for// (nameThere inare settings)no {arguments.
if defaultSetting(args.length === 0) settings[name];{
LocalComments[name]return = defaultSettingfalse;
}
 
return settings;
// The first arg is an object, so just set that data directly onto the
} else if (typeof arguments[0] === 'string') {
// settings object. like {setting 1: true, setting 2: false}
name = arguments[0];
if (typeof args[0] === 'object') {
defaultSetting = arguments[1];
if (LocalComments const [namesettings] == null) {args;
 
LocalComments[name] = defaultSetting;
// Loop through each setting.
Object.keys(settings).forEach((name) => {
const value = settings[name];
 
if (typeof this.LocalComments[name] === 'undefined') {
this.LocalComments[name] = value;
}
});
 
return settings;
}
 
return LocalComments[name];
// The first arg is a string, so use the first arg as the settings key,
// and the second arg as the value to set it to.
const [name, setting] = args;
 
if (typeof this.LocalComments[name] === 'undefined') {
this.LocalComments[name] = setting;
}
 
return this.LocalComments[name];
}
};
 
/**
return CommentsInLocalTime;
* Set the script's settings.
*
* @returns {undefined}
*/
settings() {
// The user has set custom settings, so use those.
if (window.LocalComments) {
this.LocalComments = window.LocalComments;
}
 
/**
})();
* Language
*
* LOCALIZING THIS SCRIPT
* To localize this script, change the terms below,
* to the RIGHT of the colons, to the correct term used in that language.
*
* For example, in the French language,
*
* 'Today' : 'Today',
*
* would be
*
* 'Today' : "Aujourd'hui",
*/
this.LocalComments.language = {
// Relative terms
Today: 'Today',
Yesterday: 'Yesterday',
Tomorrow: 'Tomorrow',
last: 'last',
this: 'this',
 
// Days of the week
$(window).load(function() {
Sunday: 'Sunday',
if (window.___location.href.indexOf('&disable=loco') === -1) {
Monday: 'Monday',
return CommentsInLocalTime.init();
Tuesday: 'Tuesday',
Wednesday: 'Wednesday',
Thursday: 'Thursday',
Friday: 'Friday',
Saturday: 'Saturday',
 
// Months of the year
January: 'January',
February: 'February',
March: 'March',
April: 'April',
May: 'May',
June: 'June',
July: 'July',
August: 'August',
September: 'September',
October: 'October',
November: 'November',
December: 'December',
 
// Difference words
ago: 'ago',
'from now': 'from now',
 
// Date phrases
year: 'year',
years: 'years',
month: 'month',
months: 'months',
day: 'day',
days: 'days',
};
}
}
 
// Check if we've already ran this script.
if (window.commentsInLocalTimeWasRun) {
return;
}
 
window.commentsInLocalTimeWasRun = true;
 
const commentsInLocalTime = new CommentsInLocalTime();
 
commentsInLocalTime.run();
});