User:Nardog/Unpipe.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
['edit', 'submit'].includes(mw.config.get('wgAction')) &&
$.when(
	$.ajax(
		'//tools-static.wmflabs.org/meta/scripts/pathoschild.templatescript.js',
		{ dataType: 'script', cache: true }
	),
	mw.loader.using(['mediawiki.api', 'mediawiki.Title'])
).then(function unpipe() {
	let replace = data => {
		Object.entries(data.tokens).forEach(([source, ts]) => {
			if (!ts.some(t => data.redirs[t.pn])) return;
			let links = ts.map(t => {
				let r = data.redirs[t.pn] || {};
				return [r.to || t.pn, t.fragment || r.tofragment].join('#');
			});
			if (links[0] !== links[1]) return;
			data.repl = data.repl.split(source).join(source.replace(/^[^|]+\|/, '[['));
		});
		if (data.repl === data.orig) {
			mw.notify('No change.');
			return;
		}
		data.editor
			.set(data.repl)
			.appendEditSummary('unpiped links using [[User:Nardog/Unpipe|script]]')
			.options({ minor: true })
			.clickDiff();
	};
	let query = (titles, data) => {
		if (!titles.length) {
			replace(data);
			return;
		}
		new mw.Api().post({
			action: 'query',
			titles: titles.slice(0, 50),
			redirects: 1,
			formatversion: 2
		}).then(response => {
			(response.query.redirects || []).forEach(r => {
				data.redirs[r.from] = r;
			});
			query(titles.slice(50), data);
		});
	};
	window.pathoschild.TemplateScript.add([{
		name: 'Unpipe links',
		script: editor => {
			let orig = editor.get(), repl = orig, tokens = {};
			let titles = new Set();
			let match, re = /\[\[([^|\]]+)\|([^\]]+)\]\]/g;
			while ((match = re.exec(orig))) {
				if (tokens[match[0]]) continue;
				let ts = match.slice(1).map(s => mw.Title.newFromText(s));
				if (ts.some(t => !t || t.namespace)) continue;
				let pns = ts.map(t => t.toText());
				if (pns[0].endsWith(' (disambiguation)')) continue;
				if (pns[0] === pns[1] && ts[0].fragment === ts[1].fragment) {
					repl = repl.split(match[0]).join(`[[${match[2]}]]`);
					continue;
				}
				tokens[match[0]] = pns.map((pn, i) => {
					titles.add(pn);
					return { pn, fragment: ts[i].fragment };
				});
			}
			query([...titles], { editor, orig, repl, tokens, redirs: {} });
		}
	}]);
});