User:Sophisticatedevening/Timestamp.js
//
$(function () {
const pageName = mw.config.get('wgPageName');
const isEdit = mw.config.get('wgAction') === 'edit';
const useFixTimestamp = new URLSearchParams(window.location.search).get('useFixTimestamp') === '1';
if (!isEdit) {
mw.util.addPortletLink(
'p-cactions',
mw.util.getUrl(pageName, { action: 'edit', useFixTimestamp: '1' }),
'Fix timestamp',
'ca-fixtimestamp',
'Open editor and fix AfC timestamps'
);
}
if (!isEdit || !useFixTimestamp) return;
const editSummaryText = "Fixed malformed AfC timestamp";
function fixTimestamp(text) {
const months = {
January: '01', February: '02', March: '03', April: '04',
May: '05', June: '06', July: '07', August: '08',
September: '09', October: '10', November: '11', December: '12'
};
return text.replace(/\{\{AFC submission\|([^|}]*)\|ts=([^\|}]+)\}\}/gi, function (match, param, tsText) {
const cleanParam = param.trim().toLowerCase().match(/^[a-z]$/i) ? '' : param.trim();
const dateMatch = tsText.match(/(\d{1,2}):(\d{2}), (\d{1,2}) ([A-Za-z]+) (\d{4})/);
if (!dateMatch) return match;
let [, hour, minute, day, monthName, year] = dateMatch;
hour = hour.padStart(2, '0');
minute = minute.padStart(2, '0');
day = day.padStart(2, '0');
const month = months[monthName] || '01';
const fixedTimestamp = `${year}${month}${day}${hour}${minute}00`;
return `{{AFC submission${cleanParam ? '|' + cleanParam : ''}|ts=${fixedTimestamp}}}`;
});
}
function handleClassic() {
const attemptFix = () => {
const $ta = $('#wpTextbox1');
if ($ta.length && $ta.val().length > 0) {
const orig = $ta.val();
const fixed = fixTimestamp(orig);
if (fixed !== orig) {
$ta.val(fixed);
}
$('#wpSummary').val(editSummaryText);
return true;
}
return false;
};
const rafLoop = () => {
if (!attemptFix()) {
requestAnimationFrame(rafLoop);
}
};
rafLoop();
}
function handleVE() {
mw.hook('ve.activationComplete').add(() => {
const surface = ve.init.target.getSurface();
const model = surface.getModel();
const doc = model.getDocument();
const orig = doc.getText();
const fixed = fixTimestamp(orig);
if (fixed !== orig) {
model.setLinearContentFromText(fixed);
}
const $summary = $('#wpSummary');
if ($summary.length) {
$summary.val(editSummaryText);
}
});
}
if ($('#wpTextbox1').length) {
handleClassic();
} else {
handleVE();
}
});
//