User:Ahecht/Scripts/refrescue.js
Appearance
< User:Ahecht | Scripts
Code that you insert on this page could contain malicious content capable of compromising your account. If you import a script from another page with "importScript", "mw.loader.load", "iusc", or "lusc", take note that this causes you to dynamically load a remote script, which could be changed by others. Editors are responsible for all edits and actions they perform, including by scripts. User scripts are not centrally supported and may malfunction or become inoperable due to software changes. A guide to help you find broken scripts is available. If you are unsure whether code you are adding to this page is safe, you can ask at the appropriate village pump.
This code will be executed when previewing this page.
This code will be executed when previewing this page.
This user script seems to have a documentation page at User:Ahecht/Scripts/refrescue.
/******************************************************************************/
/* This script is designed to run on both pages with errors about missing */
/* references and on the page where the references can be found. */
/* */
/* This script is particularly useful when splitting pages that use named */
/* named references. getNames() is run on the new page created after the */
/* split, and getRefs() is run on the source page (in edit mode). The list of */
/* references produced by getRefs() can be inserted into the new page as */
/* [[Help:List-defined references]]. */
/******************************************************************************/
const rrCS1ErrorSpans = document.querySelectorAll('span.mw-ext-cite-error');
const rrHarvErrorSpans = document.querySelectorAll('span.harv-error');
// Run from the page with missing reference errors
function getNames() {
const refNames = [];
rrCS1ErrorSpans.forEach(span => {
const codeTag = span.querySelector('code');
if (codeTag) {
const refName = codeTag.textContent.trim();
if (refName) {
refNames.push(refName);
}
}
});
rrHarvErrorSpans.forEach(span => {
const errText = span.textContent.trim();
const refName = errText.match(/no target: (CITEREF.*?) \(help\)/)
if (refName && refName[1]) {
refNames.push(refName[1]);
}
});
if (refNames.length > 0) {
console.log(refNames.join());
prompt("Copy the below list of refnames using CTRL+C on your keyboard:", refNames.join())
} else {
console.log("No missing references found!");
alert("No missing references found!")
}
}
// Helper functions
function popUpRefs(refs, harvRefs, notFound) {
const hasRefs = refs.length > 0
const hasHarv = harvRefs.length > 0
const $dialogDiv = $('<div>', {
id: 'rrdiv',
title: 'Rescued references.'
});
const textAreaCss = {
width: '96%',
fontFamily: 'inherit',
padding: '5px'
};
const $refTextArea = $('<textarea>', {
readonly: true,
text: refs.join('\n'),
id: 'rrreftextarea',
rows: Math.max(refs.length, 6),
}).css(textAreaCss);
const $harvRefTextArea = $('<textarea>', {
readonly: true,
text: harvRefs.join('\n'),
id: 'rrharvtextarea',
rows: Math.max(harvRefs.length, 6)
}).css(textAreaCss);
$dialogDiv.append('<p>Copy and paste these into the page with missing ref errors.</p>')
if (hasRefs) {
$dialogDiv.append('<p>The follow references should go in a <code><references></references></code> tag block. <a href="#" id="rrRefCopyLink">Click here to copy.</a></p>').append($refTextArea);
}
if (hasHarv) {
$dialogDiv.append('<p>The follow harv/sfn references should go between <code>{{refbegin}}</code> and <code>{{refend}}</code>. <a href="#" id="rrHarvCopyLink">Click here to copy.</a></p>').append($harvRefTextArea);
}
if (notFound.length > 0) {
$dialogDiv.append('<p>The following reference names were not found:</p><ul><li>'+notFound.join('</li><li>')+'</li></ul>')
}
$('body').append($dialogDiv);
$dialogDiv.dialog({
width: '75%',
buttons: {
"Close": function() {
$(this).dialog("close");
}
},
open: function() {
if (hasRefs) {
$refTextArea.trigger('focus').select();
$(this).find( '#rrRefCopyLink' ).on('click', function ( e ) {
e.preventDefault();
navigator.clipboard.writeText($refTextArea.val()).then(() => {
$(e.target).text("Copied!");
});
});
} else if (hasHarv) {
$harvRefTextArea.trigger('focus').select();
}
if (hasHarv) {
$(this).find( '#rrHarvCopyLink' ).on('click', function ( e ) {
e.preventDefault();
navigator.clipboard.writeText($harvRefTextArea.val()).then(() => {
$(e.target).text("Copied!");
});
});
}
},
close: function() {
$(this).dialog("destroy").remove();
}
});
}
async function getHarvMatches(textareaContent) {
const harvRegex = /\{\{\s*cite\s+[\w\s]+\|(?:[^{}]|\{\{[^{}]*\}\})*?\}\}/gis;
const crRegex = /id=["'](CITEREF[^"']+)["']/is;
const parsedRefs = Object.create(null);
const promises = [];
let count = 0;
const matches = [...textareaContent.matchAll(harvRegex)];
const matchLength = matches.length;
if (matchLength > 0) {
mw.notify('Parsing references...', {tag: 'count'});
}
for (const match of matches) {
const thisMatch = match[0];
promises.push(
new mw.Api().parse(thisMatch, {disablelimitreport: 1}).done( d => {
count++;
mw.notify(`Parsing reference ${count} of ${matchLength}.`, {tag: 'count'});
const citeRef = d.match(crRegex);
if (citeRef !== null && citeRef[1] !== null) {
const key = citeRef[1].replace(/&#(\d+);/g, (match, dec) => String.fromCharCode(dec));
parsedRefs[key] = thisMatch;
}
}).fail(e => {
console.warn("Error parsing" + thisMatch);
console.warn(e);
})
);
}
await Promise.all(promises);
mw.notify('Done parsing references', {tag: 'count'});
return parsedRefs;
}
// Edit the page that has the references you need and run the following script
async function getRefs() {
var inputNames = prompt('Please enter or paste (CTRL+V) a comma-separated list of ref names:');
const refs = [];
const harvRefs = [];
const notFound = [];
const matches = Object.create(null);
const names = inputNames.split(',').map(name => name.trim());
const textareaContent = document.getElementById('wpTextbox1').value;
const refRegex = /<ref\s+name\s*=\s*['"]?([^'">]+?)['"]?\s*>([\s\S]*?)<\/ref>/gis;
let match;
while ((match = refRegex.exec(textareaContent)) !== null) {
if (typeof match === 'object' && typeof match[1] === 'string') {
matches[match[1]] = match[0];
}
}
let harvMatches;
const hasHarv = names.some(name => name.match(/^CITEREF/) !== null);
if (hasHarv) {
harvMatches = await getHarvMatches(textareaContent);
}
names.forEach(name => {
if (typeof harvMatches === 'object' && typeof harvMatches[name] === 'string') {
harvRefs.push("* " + harvMatches[name]);
} else if (typeof matches[name] === 'string') {
refs.push(matches[name]);
} else {
notFound.push(name);
}
});
console.log("References:", refs.join('\n'));
console.log("Harv/Sfn references:", harvRefs.join('\n'));
console.log("The following references were not found:", notFound.join());
popUpRefs(refs, harvRefs, notFound);
}
var portletLink
if (rrCS1ErrorSpans.length > 0 || rrHarvErrorSpans.length > 0) {
portletLink = mw.util.addPortletLink("p-cactions", "#", "Gather missing refs", "pt-rrgather", "Gather names of missing references to rescue.");
$( portletLink ).click( function ( e ) {
e.preventDefault();
getNames();
});
}
if (document.getElementById('wpTextbox1') !== null) {
portletLink = mw.util.addPortletLink("p-cactions", "#", "Rescue refs", "pt-rrextract", "Extract references given a list of reference names.");
$( portletLink ).click( function ( e ) {
e.preventDefault();
getRefs();
});
}