MediaWiki:Gadget-darkModeToggle.js

From Final Fantasy XIV Online Wiki
Jump to navigation Jump to search

Note: After saving, 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)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
/**Credits to Minecraft Wiki for code: https://minecraft.wiki/w/MediaWiki:Gadget-fixedWidthToggle.js
   and MarkusRost for debugging**/
$(function() {
	var i19n = {
		toggle: 'Toggle dark mode',
		toastTitle: 'Dark mode toggle',
		failedToast: 'Could not save dark mode preference.',
	};

	var isDefaultEnabled = mw.user.options.get('gadget-darkMode') || 0,
	cookieOptions = {
		prefix: '',
		expires: 365 * 86400
	},
	portletLink = mw.util.addPortletLink(
		'p-personal',
		'',
		'',
		( isDefaultEnabled ? 'pt-dm-disable' : 'pt-dm-enable' ),
		i19n.toggle,
		null,
		$('#pt-dm-toggle, #pt-userpage, #pt-anonuserpage, #pt-createaccount')[0]
	);
	
	if ( mw.user.isAnon() ) {
		var useDarkMode = mw.cookie.get('darkMode', cookieOptions.prefix, isDefaultEnabled && 'true') === 'true';
		if ( useDarkMode != isDefaultEnabled ) { // bool != int
			toggleDarkMode(isDefaultEnabled);
		}
	}
	
	$(portletLink).find('a').click(function(e) {
		e.preventDefault();
		
		var isEnabled = mw.user.options.get('gadget-darkMode') || 0;
		if ( mw.user.isAnon() ) {
			mw.cookie.set('darkMode', isEnabled ? 'false' : 'true', cookieOptions);
		}
		else {
			new mw.Api().saveOption('gadget-darkMode', isEnabled ? 0 : 1).fail(function() {
				mw.notify(i19n.failedToast, {
					title: i19n.toastTitle,
					type: 'warn',
					tag: 'darkModeToggle'
				});
			});
		}
		toggleDarkMode(isEnabled);
	});
	
	function toggleDarkMode(isEnabled) {
		if ( isEnabled ) {
			mw.user.options.set('gadget-darkMode', 0);
			document.documentElement.style.setProperty('--dark-mode', '100vw');
			portletLink.id = 'pt-dm-enable';
		}
		else {
			mw.user.options.set('gadget-darkMode', 1);
			document.documentElement.style.setProperty('--dark-mode', '');
			mw.loader.using(['ext.gadget.darkMode']).then(function() {
				portletLink.id = 'pt-dm-disable';
			});
		}
	}
});