Jump to content

User:Ahecht/Scripts/refrescue.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
/******************************************************************************/
/* 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>&lt;references&gt;&lt;/references&gt;</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();
	});
}