No edit summary
No edit summary
Line 1: Line 1:
/**
/**
  * reFill.js — WikiEditor tab
  * reFill.js — WikiEditor tab
  * Fills <ref>https://…</ref> and <ref>[https://… title]</ref>
  * Fills bare and [url title] refs
  * Names a ref only when the same URL is used more than once
  * Names only duplicate URLs
  * After OK on the result dialog, opens Show changes (action=submit + wpDiff)
* Reuses existing names; never restarts at :0
  * After OK, opens Show changes
  */
  */
(function () {
(function () {
Line 121: Line 122:
p.push('access-date=' + new Date().toISOString().slice(0, 10));
p.push('access-date=' + new Date().toISOString().slice(0, 10));
return '{{' + name + '|' + p.join('|') + '}}';
return '{{' + name + '|' + p.join('|') + '}}';
}
function extractUrlFromCite(body) {
var m = String(body || '').match(/\|\s*url\s*=\s*([^\s|}]+)/i);
return m ? m[1] : '';
}
function scanExisting(text) {
var used = {};
var urlToName = {};
var maxN = -1;
var re = /<ref(\s[^>]*)?>([\s\S]*?)<\/ref>/gi;
var m;
while ((m = re.exec(text)) !== null) {
var attrs = m[1] || '';
var body = m[2] || '';
var nm = attrs.match(/\bname\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s>]+))/i);
var name = nm ? (nm[1] || nm[2] || nm[3]) : null;
if (name) {
used[name] = true;
var auto = name.match(/^:(\d+)$/);
if (auto) {
maxN = Math.max(maxN, parseInt(auto[1], 10));
}
}
var url = extractUrlFromCite(body);
if (url && name && !urlToName[normUrl(url)]) {
urlToName[normUrl(url)] = name;
}
}
var self = /<ref\s+name\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s>]+))\s*\/>/gi;
while ((m = self.exec(text)) !== null) {
used[m[1] || m[2] || m[3]] = true;
}
return { used: used, urlToName: urlToName, nextNum: maxN + 1 };
}
function repairDuplicateNames(text) {
var seenNameUrl = {};
var maxN = -1;
var reN = /<ref[^>]*\bname\s*=\s*["']?:(\d+)["']?/g;
var mm;
while ((mm = reN.exec(text)) !== null) {
maxN = Math.max(maxN, parseInt(mm[1], 10));
}
var re = /<ref(\s[^>]*\bname\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s>]+))[^>]*)>([\s\S]*?)<\/ref>/gi;
var matches = [];
var m;
while ((m = re.exec(text)) !== null) {
matches.push({
full: m[0],
attrs: m[1],
name: m[2] || m[3] || m[4],
body: m[5],
index: m.index
});
}
matches.sort(function (a, b) {
return b.index - a.index;
});
matches.forEach(function (item) {
if (!/\{\{\s*cite/i.test(item.body)) {
return;
}
var url = normUrl(extractUrlFromCite(item.body));
var key = item.name;
if (!seenNameUrl[key]) {
seenNameUrl[key] = url;
return;
}
if (seenNameUrl[key] === url) {
text = text.slice(0, item.index) + '<ref name="' + item.name + '" />' +
text.slice(item.index + item.full.length);
return;
}
maxN += 1;
var neuName = ':' + maxN;
var neu = item.full.replace(
/\bname\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/i,
'name="' + neuName + '"'
);
text = text.slice(0, item.index) + neu + text.slice(item.index + item.full.length);
seenNameUrl[neuName] = url;
});
return text;
}
}
function findBare(wikitext) {
function findBare(wikitext) {
var out = [], m, seen = {};
var out = [], m, seen = {};
function add(full, attrs, url, index) {
function add(full, attrs, url, index) {
if (seen[index]) {
if (seen[index] || /\{\{\s*cite/i.test(full)) {
return;
return;
}
}
Line 168: Line 251:
}
}
function run() {
function run() {
var text = getWikitext();
var text = repairDuplicateNames(getWikitext());
if (!text) {
if (!text) {
window.alert('reFill: no editor text.');
window.alert('reFill: no editor text.');
return;
return;
}
}
var existing = scanExisting(text);
var bare = findBare(text);
var bare = findBare(text);
if (!bare.length) {
if (!bare.length) {
window.alert('reFill: no <ref>https://…</ref> or <ref>[https://… title]</ref> found.');
setWikitext(text);
window.alert('reFill finished: 0 filled, 0 failed.\nRepaired existing named refs if needed.');
showDiff();
return;
return;
}
}
Line 188: Line 274:
var key = normUrl(item.url);
var key = normUrl(item.url);
if (!groups[key]) {
if (!groups[key]) {
groups[key] = { url: item.url, count: 0, first: true };
groups[key] = {
url: item.url,
count: 0,
first: true,
name: existing.urlToName[key] || null
};
order.push(key);
order.push(key);
}
}
Line 194: Line 285:
});
});


var nextNum = 0;
var nextNum = existing.nextNum;
order.forEach(function (key) {
order.forEach(function (key) {
if (groups[key].count > 1) {
var g = groups[key];
groups[key].name = ':' + nextNum++;
if (g.name) {
return;
}
if (g.count > 1) {
while (existing.used[':' + nextNum]) {
nextNum++;
}
g.name = ':' + nextNum;
existing.used[g.name] = true;
nextNum++;
}
}
});
});
Line 205: Line 305:
var fail = 0;
var fail = 0;
order.forEach(function (key) {
order.forEach(function (key) {
if (existing.urlToName[key] && groups[key].count >= 1) {
metaByUrl[key] = { url: groups[key].url, already: true };
return;
}
chain = chain.then(function () {
chain = chain.then(function () {
return fetchOne(groups[key].url).then(function (meta) {
return fetchOne(groups[key].url).then(function (meta) {
Line 229: Line 333:
var meta = metaByUrl[key] || { url: item.url };
var meta = metaByUrl[key] || { url: item.url };
var neu;
var neu;
if (g.count <= 1) {
if (meta.already || (g.name && existing.urlToName[key] && !g.first)) {
g.first = false;
neu = '<ref name="' + g.name + '" />';
} else if (!g.name || g.count <= 1) {
neu = '<ref>' + templateFromCitoid(meta, item.url) + '</ref>';
neu = '<ref>' + templateFromCitoid(meta, item.url) + '</ref>';
} else if (g.first) {
} else if (g.first) {

Revision as of 11:36, 29 September 2026

/**
 * reFill.js — WikiEditor tab
 * Fills bare and [url title] refs
 * Names only duplicate URLs
 * Reuses existing names; never restarts at :0
 * After OK, opens Show changes
 */
(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 setSummary(ok, fail) {
		var $s = $('#wpSummary');
		if (!$s.length) {
			return;
		}
		var note = 'Filled in ' + ok + ' bare reference' + (ok === 1 ? '' : 's') + ' with [[Bharatpedia:reFill|reFill]]';
		if (fail) {
			note += ' (' + fail + ' failed)';
		}
		var cur = ($s.val() || '').trim();
		if (!cur) {
			$s.val(note);
		} else if (cur.toLowerCase().indexOf('refill') === -1) {
			$s.val(cur.replace(/\s*$/, '') + '; ' + note);
		}
		$s.trigger('change');
	}
	function showDiff() {
		var btn = document.getElementById('wpDiff');
		if (btn) {
			btn.click();
			return;
		}
		var form = document.getElementById('editform');
		if (!form) {
			return;
		}
		var input = document.createElement('input');
		input.type = 'hidden';
		input.name = 'wpDiff';
		input.value = 'Show changes';
		form.appendChild(input);
		form.submit();
	}
	function esc(s) {
		return String(s || '').replace(/\|/g, '{{!}}').replace(/\n/g, ' ').trim();
	}
	function hostTitle(url) {
		try {
			return new URL(url).hostname.replace(/^www\./, '');
		} catch (e) {
			return '';
		}
	}
	function normUrl(url) {
		return String(url || '').trim().replace(/\/+$/, '').toLowerCase();
	}
	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));
		}
		var title = item && item.title;
		if (!title && url) {
			title = hostTitle(url);
		}
		if (title) {
			p.push('title=' + esc(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 extractUrlFromCite(body) {
		var m = String(body || '').match(/\|\s*url\s*=\s*([^\s|}]+)/i);
		return m ? m[1] : '';
	}
	function scanExisting(text) {
		var used = {};
		var urlToName = {};
		var maxN = -1;
		var re = /<ref(\s[^>]*)?>([\s\S]*?)<\/ref>/gi;
		var m;
		while ((m = re.exec(text)) !== null) {
			var attrs = m[1] || '';
			var body = m[2] || '';
			var nm = attrs.match(/\bname\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s>]+))/i);
			var name = nm ? (nm[1] || nm[2] || nm[3]) : null;
			if (name) {
				used[name] = true;
				var auto = name.match(/^:(\d+)$/);
				if (auto) {
					maxN = Math.max(maxN, parseInt(auto[1], 10));
				}
			}
			var url = extractUrlFromCite(body);
			if (url && name && !urlToName[normUrl(url)]) {
				urlToName[normUrl(url)] = name;
			}
		}
		var self = /<ref\s+name\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s>]+))\s*\/>/gi;
		while ((m = self.exec(text)) !== null) {
			used[m[1] || m[2] || m[3]] = true;
		}
		return { used: used, urlToName: urlToName, nextNum: maxN + 1 };
	}
	function repairDuplicateNames(text) {
		var seenNameUrl = {};
		var maxN = -1;
		var reN = /<ref[^>]*\bname\s*=\s*["']?:(\d+)["']?/g;
		var mm;
		while ((mm = reN.exec(text)) !== null) {
			maxN = Math.max(maxN, parseInt(mm[1], 10));
		}
		var re = /<ref(\s[^>]*\bname\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s>]+))[^>]*)>([\s\S]*?)<\/ref>/gi;
		var matches = [];
		var m;
		while ((m = re.exec(text)) !== null) {
			matches.push({
				full: m[0],
				attrs: m[1],
				name: m[2] || m[3] || m[4],
				body: m[5],
				index: m.index
			});
		}
		matches.sort(function (a, b) {
			return b.index - a.index;
		});
		matches.forEach(function (item) {
			if (!/\{\{\s*cite/i.test(item.body)) {
				return;
			}
			var url = normUrl(extractUrlFromCite(item.body));
			var key = item.name;
			if (!seenNameUrl[key]) {
				seenNameUrl[key] = url;
				return;
			}
			if (seenNameUrl[key] === url) {
				text = text.slice(0, item.index) + '<ref name="' + item.name + '" />' +
					text.slice(item.index + item.full.length);
				return;
			}
			maxN += 1;
			var neuName = ':' + maxN;
			var neu = item.full.replace(
				/\bname\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/i,
				'name="' + neuName + '"'
			);
			text = text.slice(0, item.index) + neu + text.slice(item.index + item.full.length);
			seenNameUrl[neuName] = url;
		});
		return text;
	}
	function findBare(wikitext) {
		var out = [], m, seen = {};
		function add(full, attrs, url, index) {
			if (seen[index] || /\{\{\s*cite/i.test(full)) {
				return;
			}
			seen[index] = true;
			out.push({ full: full, attrs: attrs || '', url: url, index: index });
		}
		var reBare = /<ref(\s[^>]*)?>\s*(https?:\/\/[^\s<>[\]|{]+)\s*(?:\{\{[^}]+\}\})?\s*<\/ref>/gi;
		while ((m = reBare.exec(wikitext)) !== null) {
			add(m[0], m[1], m[2], m.index);
		}
		var reLink = /<ref(\s[^>]*)?>\s*\[(https?:\/\/[^\s\]]+)\s+[^\]]*\]\s*<\/ref>/gi;
		while ((m = reLink.exec(wikitext)) !== null) {
			add(m[0], m[1], m[2], m.index);
		}
		out.sort(function (a, b) {
			return a.index - b.index;
		});
		return out;
	}
	function fetchOne(url) {
		function once() {
			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) {
				var item = Array.isArray(data) ? data[0] : data;
				if (!item) {
					throw new Error('empty');
				}
				return item;
			});
		}
		return once().catch(function () {
			return new Promise(function (res) {
				setTimeout(res, 700);
			}).then(once);
		});
	}
	function run() {
		var text = repairDuplicateNames(getWikitext());
		if (!text) {
			window.alert('reFill: no editor text.');
			return;
		}
		var existing = scanExisting(text);
		var bare = findBare(text);
		if (!bare.length) {
			setWikitext(text);
			window.alert('reFill finished: 0 filled, 0 failed.\nRepaired existing named refs if needed.');
			showDiff();
			return;
		}
		var tab = document.querySelector('.tab-refill, [rel="refill"]');
		if (tab) {
			tab.textContent = 'Filling…';
		}

		var groups = {};
		var order = [];
		bare.forEach(function (item) {
			var key = normUrl(item.url);
			if (!groups[key]) {
				groups[key] = {
					url: item.url,
					count: 0,
					first: true,
					name: existing.urlToName[key] || null
				};
				order.push(key);
			}
			groups[key].count++;
		});

		var nextNum = existing.nextNum;
		order.forEach(function (key) {
			var g = groups[key];
			if (g.name) {
				return;
			}
			if (g.count > 1) {
				while (existing.used[':' + nextNum]) {
					nextNum++;
				}
				g.name = ':' + nextNum;
				existing.used[g.name] = true;
				nextNum++;
			}
		});

		var metaByUrl = {};
		var chain = Promise.resolve();
		var fail = 0;
		order.forEach(function (key) {
			if (existing.urlToName[key] && groups[key].count >= 1) {
				metaByUrl[key] = { url: groups[key].url, already: true };
				return;
			}
			chain = chain.then(function () {
				return fetchOne(groups[key].url).then(function (meta) {
					metaByUrl[key] = meta;
				}).catch(function () {
					fail++;
					metaByUrl[key] = { url: groups[key].url };
				}).then(function () {
					return new Promise(function (res) {
						setTimeout(res, 350);
					});
				});
			});
		});

		chain.then(function () {
			var ok = 0;
			bare.forEach(function (item) {
				var key = normUrl(item.url);
				var g = groups[key];
				if (!g) {
					return;
				}
				var meta = metaByUrl[key] || { url: item.url };
				var neu;
				if (meta.already || (g.name && existing.urlToName[key] && !g.first)) {
					g.first = false;
					neu = '<ref name="' + g.name + '" />';
				} else if (!g.name || g.count <= 1) {
					neu = '<ref>' + templateFromCitoid(meta, item.url) + '</ref>';
				} else if (g.first) {
					g.first = false;
					neu = '<ref name="' + g.name + '">' + templateFromCitoid(meta, item.url) + '</ref>';
				} else {
					neu = '<ref name="' + g.name + '" />';
				}
				var pos = text.indexOf(item.full);
				if (pos !== -1) {
					text = text.slice(0, pos) + neu + text.slice(pos + item.full.length);
					ok++;
				}
			});
			setWikitext(text);
			setSummary(ok, fail);
			if (tab) {
				tab.textContent = 'reFill';
			}
			window.alert('reFill finished: ' + ok + ' filled, ' + fail + ' failed.');
			showDiff();
		});
	}
	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) {}
	}
	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 start() {
		addSection($box());
		bindTab();
		if (mw.hook) {
			mw.hook('wikiEditor.toolbarReady').add(function ($textarea) {
				addSection($textarea);
				bindTab();
			});
		}
		setTimeout(function () {
			addSection($box());
			bindTab();
		}, 800);
	}
	mw.loader.using(['jquery', 'jquery.textSelection', 'ext.wikiEditor']).then(start).catch(start);
})();