User:Fish bowl/zhRedirect.js

mw.loader.load(['mediawiki.cookie', 'mediawiki.util']);

// IDEA: also only do stuff if the URL contains #Chinese....

let doStuff = ($('body').hasClass('action-view') && mw.config.get('wgCanonicalNamespace') === ''); let isEnabled = true; let settings = JSON.parse(localStorage.getItem('zhRedirectSettings'));

function boolAsOnOff(bool) { return (bool ? 'on' : 'off') }

function initializeEnabledCookie { if (mw.cookie.get('zhRedirectEnabled') === null) { mw.cookie.set('zhRedirectEnabled', true); } }

function retrieveEnabledCookie { isEnabled = (mw.cookie.get('zhRedirectEnabled') === 'true'); // https://stackoverflow.com/a/264037 }

function toggleEnabledCookie { isEnabled = ! isEnabled; mw.cookie.set('zhRedirectEnabled', isEnabled); $('#zh-redirect-status').text(boolAsOnOff(isEnabled)); }

function addPortletLink { let portletLink = mw.util.addPortletLink(		'p-tb',		'#',		'zhRedirect is ',		't-zhredirect',		'Enable or disable automatic redirection from Chinese simplified or variant form entries to the main entry'	);

$(portletLink).click(function(event) {		event.preventDefault;		toggleEnabledCookie;	});

$(' ').attr('id', 'zh-redirect-status').text(boolAsOnOff(isEnabled)).appendTo(portletLink); }

function followRedirect { let originalEntry = mw.config.get('wgPageName'); let zhSee = $('[style*="eeeeee"]'); // temp let zhPron = $('[style*="width:500px"]'); // temp let redirectMe = zhSee.length === 1 && zhPron.length === 0;

if (redirectMe && settings.secondaryDesiredLanguages) { $.each(settings.secondaryDesiredLanguages, function(languageName, keepThisLanguage) {			if ($('.mw-headline#' + languageName).length) {				redirectMe = false;				mw.notify('There is a ' + languageName + ' entry on this page so you have not been redirected.');				return;			}		}); }	let tradEntryLink = zhSee.find('b a')[0]; // temp

if (redirectMe) { redirectMe = ! (tradEntryLink.classList.contains('new')); // red link in zh-see }

if (redirectMe) { window.location = mw.util.getUrl(tradEntryLink.title, { zhRedirect: originalEntry }); } }

function redirectNotice { let originalEntryRecovered = mw.util.getParamValue('zhRedirect');

if (originalEntryRecovered !== null) { originalEntryRecovered = decodeURIComponent(originalEntryRecovered);

mw.notify('Redirected from ' + originalEntryRecovered + '.'); } }

if (doStuff) { initializeEnabledCookie; retrieveEnabledCookie;

if (isEnabled) { followRedirect; }

redirectNotice; addPortletLink; }