Jump to content

User:SD0001/dark-mode-toggle.js

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by SD0001 (talk | contribs) at 12:13, 27 November 2021 (avoid reloading for dark mode enable/disable to take effect). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
/**
 * Enables or disables the dark-mode gadget.
 *
 * Authors: [[User:SD0001]], [[User:Nardog]]
 */

mw.messages.set({
	'darkmode-turn-on-label': 'Dark mode',
	'darkmode-turn-on-tooltip': 'Turn on dark mode',
	'darkmode-turn-off-label': 'Light mode',
	'darkmode-turn-off-tooltip': 'Turn off dark mode',
});

$.when($.ready, mw.loader.using(['mediawiki.util', 'mediawiki.api', 'mediawiki.Uri'])).then(function() {
	var inDarkMode = !!mw.user.options.get('gadget-dark-mode');

	var onOrOff = inDarkMode ? 'off' : 'on';
	var label = mw.msg('darkmode-turn-' + onOrOff + '-label');
	var tooltip = mw.msg('darkmode-turn-' + onOrOff + '-tooltip');
	mw.util.addPortletLink('p-cactions', '#', label, 'pt-darkmode', tooltip);

	$('#pt-darkmode').on('click', function(e) {
		e.preventDefault();
		var darkMode = !mw.user.options.get('gadget-dark-mode');
		new mw.Api().saveOption('gadget-dark-mode', darkMode ? '1' : '0');

		var onOrOff = darkMode ? 'off' : 'on';
		$('#pt-darkmode span').text(mw.msg('darkmode-turn-' + onOrOff + '-label'));
		$('#pt-darkmode a').attr('title', mw.msg('darkmode-turn-' + onOrOff + '-tooltip'));
		mw.user.options.set('gadget-dark-mode', darkMode ? 1 : 0);
		
		if (mw.loader.moduleRegistry['ext.gadget.dark-mode'].style) {
			var css = mw.loader.moduleRegistry['ext.gadget.dark-mode'].style.css[0];
			$('style').filter(function () {
				return this.textContent.indexOf(css) !== -1;
			}).prop('disabled', !darkMode);
		} else {
			if (darkMode) {
				mw.loader.load('ext.gadget.dark-mode');
			} else {
				$('link[rel="stylesheet"][href*="dark-mode"]').attr('href', function() {
					var uri = new mw.Uri(this.href);
					uri.query.modules = uri.query.modules
						.replace('ext.gadget.dark-mode', 'ext.gadget.') // dark-mode is first in the gadget list
						.replace(/,dark-mode,/, ',') // dark-mode is in middle of the list
						.replace(/,dark-mode$/, ''); // dark-mode is at the end of list
					return uri.getRelativePath();
				});
				mw.loader.moduleRegistry['ext.gadget.dark-mode'].state = 'registered'; // unset "ready" state
			}
		}
	});
});