Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
/**
 * 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);
	});
})();