No edit summary
No edit summary
Line 1: Line 1:
/**
/**
  * reFill.js — batch-fill bare URL <ref>s via WMF Citoid
  * reFill.js — BharatpediaNeo-safe
  * Source editor only. Preview and check every citation before saving.
  * Fixed "Fill bare URLs" button + Citoid batch fill.
  */
  */
(function () {
(function () {
'use strict';
'use strict';


var action = mw.config.get('wgAction');
function ready(fn) {
if (action !== 'edit' && action !== 'submit') {
if (document.readyState === 'loading') {
return;
document.addEventListener('DOMContentLoaded', fn);
} else {
fn();
}
}
 
function getTextarea() {
return document.querySelector('#wpTextbox1') ||
document.querySelector('#editform textarea') ||
document.querySelector('.mw-editform textarea') ||
document.querySelector('textarea.ve-ce-documentNode') ||
document.querySelector('#mw-content-text textarea') ||
document.querySelector('textarea');
}
}


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 = {
artwork: 'Citation',
webpage: 'Cite web',
audioRecording: 'Citation',
bill: 'Citation',
blogPost: 'Cite web',
blogPost: 'Cite web',
newspaperArticle: 'Cite news',
magazineArticle: 'Cite news',
journalArticle: 'Cite journal',
conferencePaper: 'Cite journal',
book: 'Cite book',
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',
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 58: Line 40:
}
}


function accessDate() {
function templateFromCitoid(item, url) {
return new Date().toISOString().slice(0, 10);
}
 
function templateFromCitoid(item, fallbackUrl) {
var name = TYPE_MAP[item && item.itemType] || TYPE_MAP._default;
var name = TYPE_MAP[item && item.itemType] || TYPE_MAP._default;
var p = [];
var p = ['url=' + esc((item && item.url) || url)];
var url = (item && item.url) || fallbackUrl;
if (url) {
p.push('url=' + esc(url));
}
if (item && item.title) {
if (item && item.title) {
p.push('title=' + esc(item.title));
p.push('title=' + esc(item.title));
Line 74: Line 48:
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) {
p.push('date=' + esc(item.date));
p.push('date=' + esc(item.date));
}
}
if (item && item.author && item.author[0]) {
p.push('access-date=' + new Date().toISOString().slice(0, 10));
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('|') + '}}';
return '{{' + name + '|' + p.join('|') + '}}';
}
}


function findBare(wikitext) {
function findBare(text) {
var re = /<ref(\s[^>]*)?>\s*(https?:\/\/[^\s<>[\]|]+)\s*<\/ref>/gi;
var re = /<ref(\s[^>]*)?>\s*(https?:\/\/[^\s<>[\]|]+)\s*<\/ref>/gi;
var out = [];
var out = [], m;
var m;
while ((m = re.exec(text)) !== 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 $();
}
}


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


function run() {
function run() {
var $ta = getTextarea();
var ta = getTextarea();
if (!$ta.length) {
if (!ta) {
mw.notify('Open this page in the source editor (?action=edit), not VisualEditor.');
window.alert('reFill: no editor textarea. Use Edit source (?action=edit).');
return;
return;
}
}
 
var text = ta.value;
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. Need <ref>https://example.com</ref>.');
window.alert('reFill: no <ref>https://…</ref> found.');
return;
return;
}
}
 
var btn = document.getElementById('refill-bare-btn');
var $btn = $('#refill-bare-btn');
if (btn) {
$btn.prop('disabled', true);
btn.disabled = true;
mw.notify('Filling ' + bare.length + ' bare URL(s)…');
btn.textContent = 'Filling ' + bare.length + '…';
 
}
var chain = Promise.resolve();
var chain = Promise.resolve();
var ok = 0;
var ok = 0;
var fail = 0;
bare.forEach(function (item) {
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 || {}, item.url);
text = text.replace(item.full, '<ref' + item.attrs + '>' + templateFromCitoid(meta, item.url) + '</ref>');
var next = '<ref' + item.attrs + '>' + tmpl + '</ref>';
text = text.replace(item.full, next);
ok++;
ok++;
}).catch(function (err) {
}).catch(function () { /* leave ref */ }).then(function () {
fail++;
return new Promise(function (res) { setTimeout(res, 350); });
mw.log.warn('reFill failed', item.url, err);
}).then(function () {
return new Promise(function (resolve) {
setTimeout(resolve, 350);
});
});
});
});
});
});
});
chain.then(function () {
chain.then(function () {
$ta.val(text);
ta.value = text;
if ($ta[0] && $ta[0].dispatchEvent) {
ta.dispatchEvent(new Event('input', { bubbles: true }));
$ta[0].dispatchEvent(new Event('input', { bubbles: true }));
if (btn) {
btn.disabled = false;
btn.textContent = 'Fill bare URLs';
}
}
$btn.prop('disabled', false);
window.alert('reFill finished: ' + ok + '/' + bare.length + '. Preview before saving.');
mw.notify('reFill done. Filled ' + ok + ', left ' + fail + '. Preview before saving.');
});
});
}
}


function addButton() {
function addButton() {
if ($('#refill-bare-btn').length) {
if (document.getElementById('refill-bare-btn')) {
return true;
return;
}
}
 
var btn = document.createElement('button');
var $btn = $('<button type="button" id="refill-bare-btn"></button>');
btn.id = 'refill-bare-btn';
$btn.text('Fill bare URLs');
btn.type = 'button';
$btn.attr('title', 'Expand bare URL references with Citoid');
btn.textContent = 'Fill bare URLs';
$btn.css({
btn.style.cssText = [
margin: '8px 8px 8px 0',
'position:fixed',
padding: '6px 12px',
'right:16px',
cursor: 'pointer',
'bottom:16px',
fontWeight: 'bold'
'z-index:2147483647',
});
'padding:10px 14px',
$btn.on('click', function (e) {
'font:600 14px/1.2 sans-serif',
'color:#fff',
'background:#b32424',
'border:0',
'border-radius:6px',
'cursor:pointer',
'box-shadow:0 2px 8px rgba(0,0,0,.35)'
].join(';');
btn.addEventListener('click', function (e) {
e.preventDefault();
e.preventDefault();
e.stopPropagation();
run();
run();
});
});
 
document.body.appendChild(btn);
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 () {
ready(function () {
addButton();
addButton();
setTimeout(addButton, 800);
setTimeout(addButton, 500);
setTimeout(addButton, 2000);
setTimeout(addButton, 2000);
setTimeout(addButton, 4000);
setTimeout(addButton, 5000);
});
});
})();
})();

Revision as of 10:49, 25 September 2026

/**
 * reFill.js — BharatpediaNeo-safe
 * Fixed "Fill bare URLs" button + Citoid batch fill.
 */
(function () {
	'use strict';

	function ready(fn) {
		if (document.readyState === 'loading') {
			document.addEventListener('DOMContentLoaded', fn);
		} else {
			fn();
		}
	}

	function getTextarea() {
		return document.querySelector('#wpTextbox1') ||
			document.querySelector('#editform textarea') ||
			document.querySelector('.mw-editform textarea') ||
			document.querySelector('textarea.ve-ce-documentNode') ||
			document.querySelector('#mw-content-text textarea') ||
			document.querySelector('textarea');
	}

	var CITOID = 'https://en.wikipedia.org/api/rest_v1/data/citation/mediawiki/';
	var TYPE_MAP = {
		webpage: 'Cite web',
		blogPost: 'Cite web',
		newspaperArticle: 'Cite news',
		magazineArticle: 'Cite news',
		journalArticle: 'Cite journal',
		conferencePaper: 'Cite journal',
		book: 'Cite book',
		manuscript: 'Cite book',
		_default: 'Cite web'
	};

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

	function templateFromCitoid(item, url) {
		var name = TYPE_MAP[item && item.itemType] || TYPE_MAP._default;
		var p = ['url=' + esc((item && item.url) || 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));
		}
		p.push('access-date=' + new Date().toISOString().slice(0, 10));
		return '{{' + name + '|' + p.join('|') + '}}';
	}

	function findBare(text) {
		var re = /<ref(\s[^>]*)?>\s*(https?:\/\/[^\s<>[\]|]+)\s*<\/ref>/gi;
		var out = [], m;
		while ((m = re.exec(text)) !== 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(String(r.status));
				}
				return r.json();
			})
			.then(function (data) {
				return Array.isArray(data) ? data[0] : data;
			});
	}

	function run() {
		var ta = getTextarea();
		if (!ta) {
			window.alert('reFill: no editor textarea. Use Edit source (?action=edit).');
			return;
		}
		var text = ta.value;
		var bare = findBare(text);
		if (!bare.length) {
			window.alert('reFill: no <ref>https://…</ref> found.');
			return;
		}
		var btn = document.getElementById('refill-bare-btn');
		if (btn) {
			btn.disabled = true;
			btn.textContent = 'Filling ' + bare.length + '…';
		}
		var chain = Promise.resolve();
		var ok = 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 () { /* leave ref */ }).then(function () {
					return new Promise(function (res) { setTimeout(res, 350); });
				});
			});
		});
		chain.then(function () {
			ta.value = text;
			ta.dispatchEvent(new Event('input', { bubbles: true }));
			if (btn) {
				btn.disabled = false;
				btn.textContent = 'Fill bare URLs';
			}
			window.alert('reFill finished: ' + ok + '/' + bare.length + '. Preview before saving.');
		});
	}

	function addButton() {
		if (document.getElementById('refill-bare-btn')) {
			return;
		}
		var btn = document.createElement('button');
		btn.id = 'refill-bare-btn';
		btn.type = 'button';
		btn.textContent = 'Fill bare URLs';
		btn.style.cssText = [
			'position:fixed',
			'right:16px',
			'bottom:16px',
			'z-index:2147483647',
			'padding:10px 14px',
			'font:600 14px/1.2 sans-serif',
			'color:#fff',
			'background:#b32424',
			'border:0',
			'border-radius:6px',
			'cursor:pointer',
			'box-shadow:0 2px 8px rgba(0,0,0,.35)'
		].join(';');
		btn.addEventListener('click', function (e) {
			e.preventDefault();
			e.stopPropagation();
			run();
		});
		document.body.appendChild(btn);
	}

	ready(function () {
		addButton();
		setTimeout(addButton, 500);
		setTimeout(addButton, 2000);
		setTimeout(addButton, 5000);
	});
})();