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 — 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);
	});
})();