Add
 
No edit summary
Line 1: Line 1:
/**
/**
  * Batch-fill bare URL refs via WMF Citoid (reFill-like, source editor).
  * reFill.js — batch-fill bare URL <ref>s via WMF Citoid
  * Review the diff before saving.
  * Source editor only. Preview and check every citation before saving.
  */
  */
(function () {
(function () {
if (!mw.config.get('wgIsArticle') && mw.config.get('wgAction') !== 'edit') {
'use strict';
 
var action = mw.config.get('wgAction');
if (action !== 'edit' && action !== 'submit') {
return;
return;
}
}


var CITOID = 'https://en.wikipedia.org/api/rest_v1/data/citation/mediawiki/';
var CITOID = 'https://en.wikipedia.org/api/rest_v1/data/citation/mediawiki/';
var TYPE_MAP = {
var TYPE_MAP = {
webpage: 'Cite web',
artwork: 'Citation',
audioRecording: 'Citation',
bill: 'Citation',
blogPost: 'Cite web',
blogPost: 'Cite web',
book: 'Cite book',
bookSection: 'Citation',
case: 'Citation',
computerProgram: 'Citation',
conferencePaper: 'Cite journal',
dataset: 'Citation',
dictionaryEntry: 'Citation',
document: 'Citation',
email: 'Cite web',
email: 'Cite web',
encyclopediaArticle: 'Citation',
film: 'Citation',
forumPost: 'Cite web',
forumPost: 'Cite web',
hearing: 'Citation',
instantMessage: 'Citation',
interview: 'Citation',
journalArticle: 'Cite journal',
letter: 'Citation',
magazineArticle: 'Cite news',
manuscript: 'Cite book',
map: 'Citation',
newspaperArticle: 'Cite news',
newspaperArticle: 'Cite news',
magazineArticle: 'Cite news',
patent: 'Cite patent',
journalArticle: 'Cite journal',
podcast: 'Citation',
conferencePaper: 'Cite journal',
preprint: 'Citation',
presentation: 'Cite journal',
presentation: 'Cite journal',
book: 'Cite book',
radioBroadcast: 'Citation',
manuscript: 'Cite book',
report: 'Cite report',
standard: 'Citation',
statute: 'Citation',
thesis: 'Cite thesis',
tvBroadcast: 'Citation',
videoRecording: 'Cite AV media',
webpage: 'Cite web',
_default: 'Cite web'
_default: 'Cite web'
};
};


function esc(s) {
function esc(s) {
return String(s || '').replace(/\|/g, '{{!}}').replace(/\n/g, ' ');
return String(s || '').replace(/\|/g, '{{!}}').replace(/\n/g, ' ').trim();
}
 
function accessDate() {
return new Date().toISOString().slice(0, 10);
}
}


function templateFromCitoid(item) {
function templateFromCitoid(item, fallbackUrl) {
var name = TYPE_MAP[item.itemType] || TYPE_MAP._default;
var name = TYPE_MAP[item && item.itemType] || TYPE_MAP._default;
var p = [];
var p = [];
if (item.url) p.push('url=' + esc(item.url));
var url = (item && item.url) || fallbackUrl;
if (item.title) p.push('title=' + esc(item.title));
if (url) {
var site = item.websiteTitle || item.publicationTitle || item.publisher;
p.push('url=' + esc(url));
}
if (item && item.title) {
p.push('title=' + esc(item.title));
}
var site = item && (item.websiteTitle || item.publicationTitle || item.publisher);
if (site) {
if (site) {
p.push((name === 'Cite news' || name === 'Cite journal' ? 'work=' : 'website=') + esc(site));
if (name === 'Cite news' || name === 'Cite journal') {
p.push('work=' + esc(site));
} else if (name === 'Cite book') {
p.push('publisher=' + esc(site));
} else {
p.push('website=' + esc(site));
}
}
}
if (item.date) p.push('date=' + esc(item.date));
if (item && item.date) {
if (item.author && item.author[0]) {
p.push('date=' + esc(item.date));
}
if (item && item.author && item.author[0]) {
var a = item.author[0];
var a = item.author[0];
if (a[1]) p.push('last=' + esc(a[1]));
if (a[1]) {
if (a[0]) p.push('first=' + esc(a[0]));
p.push('last=' + esc(a[1]));
}
if (a[0]) {
p.push('first=' + esc(a[0]));
}
}
}
var today = new Date();
p.push('access-date=' + accessDate());
var iso = today.toISOString().slice(0, 10);
p.push('access-date=' + iso);
return '{{' + name + '|' + p.join('|') + '}}';
return '{{' + name + '|' + p.join('|') + '}}';
}
}


function findBare(wikitext) {
function findBare(wikitext) {
var re = /<ref(\s[^>]*)?>\s*(https?:\/\/[^\s<>[\]]+)\s*<\/ref>/gi;
var re = /<ref(\s[^>]*)?>\s*(https?:\/\/[^\s<>[\]|]+)\s*<\/ref>/gi;
var out = [], m;
var out = [];
var m;
while ((m = re.exec(wikitext)) !== null) {
while ((m = re.exec(wikitext)) !== null) {
out.push({ full: m[0], attrs: m[1] || '', url: m[2] });
out.push({
full: m[0],
attrs: m[1] || '',
url: m[2]
});
}
}
return out;
return out;
}
function getTextarea() {
var $ta = $('#wpTextbox1');
if ($ta.length) {
return $ta;
}
var $vis = $('textarea.ve-ui-wikitextSurface, textarea.mw-editfont-monospace, #editform textarea');
if ($vis.length) {
return $vis.first();
}
return $();
}
}


Line 62: Line 128:
headers: { Accept: 'application/json' }
headers: { Accept: 'application/json' }
}).then(function (r) {
}).then(function (r) {
if (!r.ok) throw new Error(r.status);
if (!r.ok) {
throw new Error('HTTP ' + r.status);
}
return r.json();
return r.json();
}).then(function (data) {
}).then(function (data) {
Line 70: Line 138:


function run() {
function run() {
var $ta = $('#wpTextbox1');
var $ta = getTextarea();
if (!$ta.length) {
if (!$ta.length) {
mw.notify('Open the page in the source editor.');
mw.notify('Open this page in the source editor (?action=edit), not VisualEditor.');
return;
return;
}
}
var text = $ta.val();
var text = $ta.val();
var bare = findBare(text);
var bare = findBare(text);
if (!bare.length) {
if (!bare.length) {
mw.notify('No bare URL refs found.');
mw.notify('No bare URL refs found. Need <ref>https://example.com</ref>.');
return;
return;
}
}
var $btn = $('#refill-bare-btn');
$btn.prop('disabled', true);
mw.notify('Filling ' + bare.length + ' bare URL(s)…');
mw.notify('Filling ' + bare.length + ' bare URL(s)…');


var chain = Promise.resolve();
var chain = Promise.resolve();
bare.forEach(function (item, i) {
var ok = 0;
var fail = 0;
 
bare.forEach(function (item) {
chain = chain.then(function () {
chain = chain.then(function () {
return fetchOne(item.url).then(function (meta) {
return fetchOne(item.url).then(function (meta) {
var tmpl = templateFromCitoid(meta || { url: item.url });
var tmpl = templateFromCitoid(meta || {}, item.url);
var open = '<ref' + item.attrs + '>';
var next = '<ref' + item.attrs + '>' + tmpl + '</ref>';
text = text.replace(item.full, open + tmpl + '</ref>');
text = text.replace(item.full, next);
}).catch(function () {
ok++;
/* leave this ref unchanged */
}).catch(function (err) {
fail++;
mw.log.warn('reFill failed', item.url, err);
}).then(function () {
}).then(function () {
return new Promise(function (res) { setTimeout(res, 300); });
return new Promise(function (resolve) {
setTimeout(resolve, 350);
});
});
});
});
});
Line 100: Line 179:
chain.then(function () {
chain.then(function () {
$ta.val(text);
$ta.val(text);
mw.notify('Done. Preview and check every citation before saving.');
if ($ta[0] && $ta[0].dispatchEvent) {
$ta[0].dispatchEvent(new Event('input', { bubbles: true }));
}
$btn.prop('disabled', false);
mw.notify('reFill done. Filled ' + ok + ', left ' + fail + '. Preview before saving.');
});
}
 
function addButton() {
if ($('#refill-bare-btn').length) {
return true;
}
 
var $btn = $('<button type="button" id="refill-bare-btn"></button>');
$btn.text('Fill bare URLs');
$btn.attr('title', 'Expand bare URL references with Citoid');
$btn.css({
margin: '8px 8px 8px 0',
padding: '6px 12px',
cursor: 'pointer',
fontWeight: 'bold'
});
});
$btn.on('click', function (e) {
e.preventDefault();
run();
});
var $box = getTextarea();
if ($box.length) {
$box.before($btn);
return true;
}
var $host = $('#editform, form.mw-editform, #wikiEditor-ui, .wikiEditor-ui, #mw-content-text').first();
if ($host.length) {
$host.prepend($btn);
return true;
}
return false;
}
}


mw.loader.using(['mediawiki.util', 'mediawiki.notify']).then(function () {
mw.loader.using(['mediawiki.util', 'mediawiki.notify', 'jquery']).then(function () {
mw.util.addPortletLink('p-cactions', '#', 'Fill bare URLs', 'ca-refill-bare')
addButton();
.addEventListener('click', function (e) {
setTimeout(addButton, 800);
e.preventDefault();
setTimeout(addButton, 2000);
run();
setTimeout(addButton, 4000);
});
});
});
})();
})();

Revision as of 10:46, 25 September 2026

/**
 * reFill.js — batch-fill bare URL <ref>s via WMF Citoid
 * Source editor only. Preview and check every citation before saving.
 */
(function () {
	'use strict';

	var action = mw.config.get('wgAction');
	if (action !== 'edit' && action !== 'submit') {
		return;
	}

	var CITOID = 'https://en.wikipedia.org/api/rest_v1/data/citation/mediawiki/';

	var TYPE_MAP = {
		artwork: 'Citation',
		audioRecording: 'Citation',
		bill: 'Citation',
		blogPost: 'Cite web',
		book: 'Cite book',
		bookSection: 'Citation',
		case: 'Citation',
		computerProgram: 'Citation',
		conferencePaper: 'Cite journal',
		dataset: 'Citation',
		dictionaryEntry: 'Citation',
		document: 'Citation',
		email: 'Cite web',
		encyclopediaArticle: 'Citation',
		film: 'Citation',
		forumPost: 'Cite web',
		hearing: 'Citation',
		instantMessage: 'Citation',
		interview: 'Citation',
		journalArticle: 'Cite journal',
		letter: 'Citation',
		magazineArticle: 'Cite news',
		manuscript: 'Cite book',
		map: 'Citation',
		newspaperArticle: 'Cite news',
		patent: 'Cite patent',
		podcast: 'Citation',
		preprint: 'Citation',
		presentation: 'Cite journal',
		radioBroadcast: 'Citation',
		report: 'Cite report',
		standard: 'Citation',
		statute: 'Citation',
		thesis: 'Cite thesis',
		tvBroadcast: 'Citation',
		videoRecording: 'Cite AV media',
		webpage: 'Cite web',
		_default: 'Cite web'
	};

	function esc(s) {
		return String(s || '').replace(/\|/g, '{{!}}').replace(/\n/g, ' ').trim();
	}

	function accessDate() {
		return new Date().toISOString().slice(0, 10);
	}

	function templateFromCitoid(item, fallbackUrl) {
		var name = TYPE_MAP[item && item.itemType] || TYPE_MAP._default;
		var p = [];
		var url = (item && item.url) || fallbackUrl;
		if (url) {
			p.push('url=' + esc(url));
		}
		if (item && item.title) {
			p.push('title=' + esc(item.title));
		}
		var site = item && (item.websiteTitle || item.publicationTitle || item.publisher);
		if (site) {
			if (name === 'Cite news' || name === 'Cite journal') {
				p.push('work=' + esc(site));
			} else if (name === 'Cite book') {
				p.push('publisher=' + esc(site));
			} else {
				p.push('website=' + esc(site));
			}
		}
		if (item && item.date) {
			p.push('date=' + esc(item.date));
		}
		if (item && item.author && item.author[0]) {
			var a = item.author[0];
			if (a[1]) {
				p.push('last=' + esc(a[1]));
			}
			if (a[0]) {
				p.push('first=' + esc(a[0]));
			}
		}
		p.push('access-date=' + accessDate());
		return '{{' + name + '|' + p.join('|') + '}}';
	}

	function findBare(wikitext) {
		var re = /<ref(\s[^>]*)?>\s*(https?:\/\/[^\s<>[\]|]+)\s*<\/ref>/gi;
		var out = [];
		var m;
		while ((m = re.exec(wikitext)) !== null) {
			out.push({
				full: m[0],
				attrs: m[1] || '',
				url: m[2]
			});
		}
		return out;
	}

	function getTextarea() {
		var $ta = $('#wpTextbox1');
		if ($ta.length) {
			return $ta;
		}
		var $vis = $('textarea.ve-ui-wikitextSurface, textarea.mw-editfont-monospace, #editform textarea');
		if ($vis.length) {
			return $vis.first();
		}
		return $();
	}

	function fetchOne(url) {
		return fetch(CITOID + encodeURIComponent(url), {
			headers: { Accept: 'application/json' }
		}).then(function (r) {
			if (!r.ok) {
				throw new Error('HTTP ' + r.status);
			}
			return r.json();
		}).then(function (data) {
			return Array.isArray(data) ? data[0] : data;
		});
	}

	function run() {
		var $ta = getTextarea();
		if (!$ta.length) {
			mw.notify('Open this page in the source editor (?action=edit), not VisualEditor.');
			return;
		}

		var text = $ta.val();
		var bare = findBare(text);
		if (!bare.length) {
			mw.notify('No bare URL refs found. Need <ref>https://example.com</ref>.');
			return;
		}

		var $btn = $('#refill-bare-btn');
		$btn.prop('disabled', true);
		mw.notify('Filling ' + bare.length + ' bare URL(s)…');

		var chain = Promise.resolve();
		var ok = 0;
		var fail = 0;

		bare.forEach(function (item) {
			chain = chain.then(function () {
				return fetchOne(item.url).then(function (meta) {
					var tmpl = templateFromCitoid(meta || {}, item.url);
					var next = '<ref' + item.attrs + '>' + tmpl + '</ref>';
					text = text.replace(item.full, next);
					ok++;
				}).catch(function (err) {
					fail++;
					mw.log.warn('reFill failed', item.url, err);
				}).then(function () {
					return new Promise(function (resolve) {
						setTimeout(resolve, 350);
					});
				});
			});
		});

		chain.then(function () {
			$ta.val(text);
			if ($ta[0] && $ta[0].dispatchEvent) {
				$ta[0].dispatchEvent(new Event('input', { bubbles: true }));
			}
			$btn.prop('disabled', false);
			mw.notify('reFill done. Filled ' + ok + ', left ' + fail + '. Preview before saving.');
		});
	}

	function addButton() {
		if ($('#refill-bare-btn').length) {
			return true;
		}

		var $btn = $('<button type="button" id="refill-bare-btn"></button>');
		$btn.text('Fill bare URLs');
		$btn.attr('title', 'Expand bare URL references with Citoid');
		$btn.css({
			margin: '8px 8px 8px 0',
			padding: '6px 12px',
			cursor: 'pointer',
			fontWeight: 'bold'
		});
		$btn.on('click', function (e) {
			e.preventDefault();
			run();
		});

		var $box = getTextarea();
		if ($box.length) {
			$box.before($btn);
			return true;
		}

		var $host = $('#editform, form.mw-editform, #wikiEditor-ui, .wikiEditor-ui, #mw-content-text').first();
		if ($host.length) {
			$host.prepend($btn);
			return true;
		}

		return false;
	}

	mw.loader.using(['mediawiki.util', 'mediawiki.notify', 'jquery']).then(function () {
		addButton();
		setTimeout(addButton, 800);
		setTimeout(addButton, 2000);
		setTimeout(addButton, 4000);
	});
})();