MediaWiki:Common.js

From eMushpedia
Revision as of 03:45, 9 April 2026 by Admin (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

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.
// Override the page the user is redirected to when clicking the logo
// based only on ?uselang=fr|en|es in the URL, then remember it.
(function () {
	const ALLOWED_LANGS = [ 'fr', 'en', 'es' ];
	const STORAGE_KEY = 'emushpedia_lang';

	function getLangFromUrl() {
		const params = new URLSearchParams( window.location.search );
		const uselang = params.get( 'uselang' );
		return ALLOWED_LANGS.includes( uselang ) ? uselang : null;
	}

	function getStoredLang() {
		const stored = localStorage.getItem( STORAGE_KEY );
		return ALLOWED_LANGS.includes( stored ) ? stored : null;
	}

	function saveLang( lang ) {
		if ( ALLOWED_LANGS.includes( lang ) ) {
			localStorage.setItem( STORAGE_KEY, lang );
		}
	}

	function getLang() {
		const urlLang = getLangFromUrl();

		if ( urlLang ) {
			saveLang( urlLang );
			return urlLang;
		}

		return getStoredLang() || 'en';
	}

	function getHomeTitle( lang ) {
		if ( lang === 'fr' ) {
			return 'Accueil';
		}
		if ( lang === 'es' ) {
			return 'Inicio';
		}
		return 'Home';
	}

	function rewriteLink( a, url, title, text ) {
		if ( !a ) {
			return;
		}

		a.href = url;
		a.title = title;

		if ( text ) {
			const span = a.querySelector( 'span' );
			if ( span ) {
				span.textContent = text;
			} else {
				a.textContent = text;
			}
		}
	}

	function rewriteMainLinks() {
		const lang = getLang();
		const target = getHomeTitle( lang );
		const url = mw.util.getUrl( target, { uselang: lang } );

		// Logo links
		document.querySelectorAll( 'a.mw-wiki-logo, a.mw-logo' ).forEach( function ( a ) {
			rewriteLink( a, url, target, null );
		} );

		// Sidebar custom main page item
		document.querySelectorAll( '#n-lang-mainpage a' ).forEach( function ( a ) {
			rewriteLink( a, url, target, target );
		} );

		// Fallbacks for default main page links if they still exist somewhere
		document.querySelectorAll( '#n-mainpage-description a, a[accesskey="z"]' ).forEach( function ( a ) {
			rewriteLink( a, url, target, target );
		} );
	}

	mw.loader.using( [ 'mediawiki.util' ] ).then( function () {
		rewriteMainLinks();
	} );
}());