No edit summary
No edit summary
Line 1: Line 1:
/**
/**
  * reFill.js — batch-fill bare URL refs via WMF Citoid
  * reFill.js — one WikiEditor tab, same row as Cite
* Toolbar button next to Cite (WikiEditor). BharatpediaNeo + CodeMirror safe.
  */
  */
(function () {
(function () {
Line 9: Line 8:


var TYPE_MAP = {
var TYPE_MAP = {
artwork: 'Citation',
audioRecording: 'Citation',
bill: 'Citation',
blogPost: 'Cite web',
blogPost: 'Cite web',
book: 'Cite book',
webpage: 'Cite web',
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',
newspaperArticle: 'Cite news',
instantMessage: 'Citation',
magazineArticle: 'Cite news',
interview: 'Citation',
journalArticle: 'Cite journal',
journalArticle: 'Cite journal',
letter: 'Citation',
conferencePaper: 'Cite journal',
magazineArticle: 'Cite news',
presentation: 'Cite journal',
book: 'Cite book',
manuscript: 'Cite book',
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'
_default: 'Cite web'
};
};
Line 88: Line 61:
var site = item && (item.websiteTitle || item.publicationTitle || item.publisher);
var site = item && (item.websiteTitle || item.publicationTitle || item.publisher);
if (site) {
if (site) {
if (name === 'Cite news' || name === 'Cite journal') {
p.push((name === 'Cite news' || name === 'Cite journal' ? 'work=' : 'website=') + esc(site));
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) {
if (item && item.date) {
Line 132: Line 99:
return Array.isArray(data) ? data[0] : data;
return Array.isArray(data) ? data[0] : data;
});
});
}
function setBusy(on, n) {
var nodes = document.querySelectorAll('#refill-toolbar-btn, #refill-bare-btn');
for (var i = 0; i < nodes.length; i++) {
nodes[i].disabled = !!on;
if (nodes[i].id === 'refill-toolbar-btn') {
nodes[i].textContent = on ? ('Filling ' + n + '…') : 'reFill';
} else {
nodes[i].textContent = on ? ('Filling ' + n + '…') : 'Fill bare URLs';
}
}
}
}


Line 157: Line 112:
return;
return;
}
}
setBusy(true, bare.length);
var tab = document.querySelector('.tab-refill, [rel="refill"]');
if (tab) {
tab.textContent = 'Filling…';
}
var chain = Promise.resolve();
var chain = Promise.resolve();
var ok = 0;
var ok = 0;
Line 180: Line 138:
chain.then(function () {
chain.then(function () {
setWikitext(text);
setWikitext(text);
setBusy(false);
if (tab) {
window.alert('reFill finished: ' + ok + ' filled, ' + fail + ' failed. Check the text, then Preview.');
tab.textContent = 'reFill';
}
window.alert('reFill finished: ' + ok + ' filled, ' + fail + ' failed. Preview before saving.');
});
});
}
}


function addWikiEditorSection($textarea) {
function addSection($textarea) {
if (!$textarea || !$textarea.length || !$textarea.wikiEditor) {
if (!$textarea || !$textarea.length || typeof $textarea.wikiEditor !== 'function') {
return false;
return;
}
}
if ($textarea.data('refillToolbarAdded')) {
if ($textarea.data('refillAdded')) {
return true;
return;
}
}
try {
try {
Line 201: Line 161:
}
}
});
});
$textarea.wikiEditor('addToToolbar', {
$textarea.data('refillAdded', true);
section: 'refill',
} catch (e) { /* already exists */ }
groups: {
refill: {
label: '',
tools: {
fillbare: {
label: 'Fill bare URLs',
type: 'button',
action: {
type: 'callback',
execute: function () {
run();
}
}
}
}
}
}
});
$textarea.data('refillToolbarAdded', true);
return true;
} catch (e) {
return false;
}
}
}


function addTabBesideCite() {
function bindTab() {
if (document.getElementById('refill-toolbar-btn')) {
var root = document.querySelector('.wikiEditor-ui-toolbar');
return true;
if (!root || root.getAttribute('data-refill-bound')) {
return;
}
}
var cite = document.querySelector(
root.setAttribute('data-refill-bound', '1');
'.wikiEditor-ui-toolbar .tab-cite, .wikiEditor-ui-toolbar [rel="cite"], .wikiEditor-ui-toolbar .tabs .tab[rel="cite"]'
root.addEventListener('click', function (e) {
);
var t = e.target.closest('.tab-refill, [rel="refill"], .wikiEditor-ui-toolbar [rel="refill"]');
var tabs = document.querySelector('.wikiEditor-ui-toolbar .tabs, .wikiEditor-ui-toolbar .wikiEditor-ui-tabs');
if (!t) {
if (!cite && !tabs) {
return;
return false;
}
}
var btn = document.createElement('button');
btn.id = 'refill-toolbar-btn';
btn.type = 'button';
btn.textContent = 'reFill';
btn.title = 'Fill bare URL references';
btn.className = 'tab tab-refill';
btn.style.cssText = 'margin-left:8px;padding:2px 8px;cursor:pointer;font:inherit;background:transparent;border:0;color:inherit;';
btn.addEventListener('click', function (e) {
e.preventDefault();
e.preventDefault();
e.stopPropagation();
e.stopPropagation();
run();
run();
});
}, true);
if (cite && cite.parentNode) {
cite.parentNode.insertBefore(btn, cite.nextSibling);
} else {
tabs.appendChild(btn);
}
return true;
}
}


function addFallbackFloat() {
function cleanupStray() {
if (document.getElementById('refill-bare-btn') || document.getElementById('refill-toolbar-btn')) {
var stray = document.getElementById('refill-toolbar-btn');
return;
if (stray) {
stray.remove();
}
}
var btn = document.createElement('button');
var flt = document.getElementById('refill-bare-btn');
btn.id = 'refill-bare-btn';
if (flt) {
btn.type = 'button';
flt.remove();
btn.textContent = 'Fill bare URLs';
btn.style.cssText = 'position:fixed;right:16px;bottom:16px;z-index:2147483647;padding:10px 14px;font:600 14px sans-serif;color:#fff;background:#b32424;border:0;border-radius:6px;cursor:pointer;';
btn.addEventListener('click', function (e) {
e.preventDefault();
run();
});
document.body.appendChild(btn);
}
 
function tryPlace() {
addWikiEditorSection($box());
if (!addTabBesideCite()) {
addFallbackFloat();
} else {
var f = document.getElementById('refill-bare-btn');
if (f) {
f.remove();
}
}
}
}
}


function start() {
function start() {
tryPlace();
addSection($box());
bindTab();
cleanupStray();
if (mw.hook) {
if (mw.hook) {
mw.hook('wikiEditor.toolbarReady').add(function ($textarea) {
mw.hook('wikiEditor.toolbarReady').add(function ($textarea) {
addWikiEditorSection($textarea);
addSection($textarea);
addTabBesideCite();
bindTab();
var f = document.getElementById('refill-bare-btn');
cleanupStray();
if (f) {
f.remove();
}
});
});
}
}
setTimeout(tryPlace, 400);
setTimeout(function () {
setTimeout(tryPlace, 1500);
addSection($box());
setTimeout(tryPlace, 4000);
bindTab();
cleanupStray();
}, 800);
}
}


if (document.readyState === 'loading') {
mw.loader.using(['jquery', 'jquery.textSelection', 'ext.wikiEditor']).then(start).catch(start);
document.addEventListener('DOMContentLoaded', function () {
mw.loader.using(['jquery', 'jquery.textSelection', 'ext.wikiEditor']).then(start).catch(start);
});
} else if (mw.loader && mw.loader.using) {
mw.loader.using(['jquery', 'jquery.textSelection', 'ext.wikiEditor']).then(start).catch(start);
} else {
start();
}
})();
})();

Revision as of 11:26, 25 September 2026

/**
 * reFill.js — one WikiEditor tab, same row as Cite
 */
(function () {
	'use strict';

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

	var TYPE_MAP = {
		blogPost: 'Cite web',
		webpage: 'Cite web',
		email: 'Cite web',
		forumPost: 'Cite web',
		newspaperArticle: 'Cite news',
		magazineArticle: 'Cite news',
		journalArticle: 'Cite journal',
		conferencePaper: 'Cite journal',
		presentation: 'Cite journal',
		book: 'Cite book',
		manuscript: 'Cite book',
		_default: 'Cite web'
	};

	function $box() {
		return $('#wpTextbox1');
	}

	function getWikitext() {
		var $t = $box();
		if ($t.length && $.fn.textSelection) {
			return $t.textSelection('getContents');
		}
		return $t.length ? $t.val() : '';
	}

	function setWikitext(text) {
		var $t = $box();
		if ($t.length && $.fn.textSelection) {
			$t.textSelection('setContents', text);
			return;
		}
		if ($t.length) {
			$t.val(text).trigger('input');
		}
	}

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

	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) {
			p.push((name === 'Cite news' || name === 'Cite journal' ? 'work=' : '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=' + new Date().toISOString().slice(0, 10));
		return '{{' + name + '|' + p.join('|') + '}}';
	}

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

	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 text = getWikitext();
		if (!text) {
			window.alert('reFill: no editor text.');
			return;
		}
		var bare = findBare(text);
		if (!bare.length) {
			window.alert('reFill: no <ref>https://…</ref> found.');
			return;
		}
		var tab = document.querySelector('.tab-refill, [rel="refill"]');
		if (tab) {
			tab.textContent = 'Filling…';
		}
		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) {
					text = text.replace(
						item.full,
						'<ref' + item.attrs + '>' + templateFromCitoid(meta || {}, item.url) + '</ref>'
					);
					ok++;
				}).catch(function () {
					fail++;
				}).then(function () {
					return new Promise(function (res) {
						setTimeout(res, 350);
					});
				});
			});
		});
		chain.then(function () {
			setWikitext(text);
			if (tab) {
				tab.textContent = 'reFill';
			}
			window.alert('reFill finished: ' + ok + ' filled, ' + fail + ' failed. Preview before saving.');
		});
	}

	function addSection($textarea) {
		if (!$textarea || !$textarea.length || typeof $textarea.wikiEditor !== 'function') {
			return;
		}
		if ($textarea.data('refillAdded')) {
			return;
		}
		try {
			$textarea.wikiEditor('addToToolbar', {
				sections: {
					refill: {
						type: 'toolbar',
						label: 'reFill'
					}
				}
			});
			$textarea.data('refillAdded', true);
		} catch (e) { /* already exists */ }
	}

	function bindTab() {
		var root = document.querySelector('.wikiEditor-ui-toolbar');
		if (!root || root.getAttribute('data-refill-bound')) {
			return;
		}
		root.setAttribute('data-refill-bound', '1');
		root.addEventListener('click', function (e) {
			var t = e.target.closest('.tab-refill, [rel="refill"], .wikiEditor-ui-toolbar [rel="refill"]');
			if (!t) {
				return;
			}
			e.preventDefault();
			e.stopPropagation();
			run();
		}, true);
	}

	function cleanupStray() {
		var stray = document.getElementById('refill-toolbar-btn');
		if (stray) {
			stray.remove();
		}
		var flt = document.getElementById('refill-bare-btn');
		if (flt) {
			flt.remove();
		}
	}

	function start() {
		addSection($box());
		bindTab();
		cleanupStray();
		if (mw.hook) {
			mw.hook('wikiEditor.toolbarReady').add(function ($textarea) {
				addSection($textarea);
				bindTab();
				cleanupStray();
			});
		}
		setTimeout(function () {
			addSection($box());
			bindTab();
			cleanupStray();
		}, 800);
	}

	mw.loader.using(['jquery', 'jquery.textSelection', 'ext.wikiEditor']).then(start).catch(start);
})();