MediaWiki:Gadget-fixedWidthToggle.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 i18n = {
		toggle: 'Toggle fixed width',
		toastTitle: 'Fixed width toggle',
		failedToast: 'Could not save fixed width preference.',
	};

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