User:Erutuon/scripts/mainspaceHeaders.js

Note – after saving, you may have to bypass your browser’s cache to see the changes.

  • Mozilla / Firefox / Safari: hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (Command-R on a Macintosh);
  • Konqueror and Chrome: click Reload or press F5;
  • Opera: clear the cache in Tools → Preferences;
  • Internet Explorer: hold Ctrl while clicking Refresh, or press Ctrl-F5.

mw.loader.using('mediawiki.Title').done(function () {
	const search = new mw.Title('Special:Search');

	$('tr td:first-child').get().forEach(function (element) {
		let parent;
		const textNode = (function (node) {
			while (node && !(node instanceof Text))
				parent = node, node = node.firstChild;
			return node;
		})(element);
		
		if (!(textNode instanceof Text))
			 return console.error(element);
		
		const text = textNode.nodeValue;
		const query = '"' + text + '" insource:/= *'
			+ text.replace(/[\/"]/g, '\\$&') + ' *=/';
		const url = search.getUrl({ search: query, ns0: 1 });
		
		const link = document.createElement('a');
		link.href = url;
		link.appendChild(textNode);
		parent.appendChild(link);
		
		// Add class to parent table row so that crossed out headers can be hidden.
		if (parent.nodeName === 'DEL') {
			let tableRow = parent;
			while (tableRow && tableRow.nodeName !== 'TR')
				tableRow = tableRow.parentNode;
			tableRow.classList.add('crossed-out');
		}
	});
	
	const crossedOut = $('.crossed-out');
	if (crossedOut.length === 0)
		return;
	
	mw.loader.using('oojs-ui').done(function () {
		const what = 'crossed-out headers';
		const hideText = 'Hide ' + what;
		const showText = 'Show ' + what;
		
		const button = new OO.ui.ButtonWidget();
		
		button.setLabel(showText);
		crossedOut.first().closest('table').before(button.$element);
		
		var shown = false;
		crossedOut.toggle(shown);
		
		button.$element.click(function () {
			shown = !shown;
			crossedOut.toggle(shown);
			button.setLabel(shown ? hideText : showText);
		});
	});
});