MediaWiki:Gadget-dark-mode-toggle.js: Difference between revisions

Content deleted Content added
Implementing changes requested on talk page (diff, permalink) for an interface admin.
Remove mw.uri
 
(16 intermediate revisions by 7 users not shown)
Line 17:
}
 
var isOn = mw.loader.getState('ext.gadget.dark-mode') === 'ready';
$.when($.ready, mw.loader.using(['mediawiki.util', 'mediawiki.api', 'mediawiki.Uri', 'mediawiki.storage', 'es6-polyfills'])).then(function () {
var isOn = !!mw.user.options.get('gadget-dark-mode');
 
var broadcastChannel = new BroadcastChannel('gadget-dark-mode');
if (isOn) {
// CSS class for externally styling elements in dark mode via TemplateStyles (or CSS from other gadgets or common.css)
// A brief flash of the original styles will occur, so this is only suitable for style changes for which flashes are tolerable.
// For others, update Gadget-dark-mode.css directly which is loaded without FOUCs
document.documentElement.classList.add('client-dark-mode');
// Update the initial mobile theme-color
$('meta[name="theme-color"]').attr('content', '#000000');
}
 
function setThemeColor() {
var onOrOff = isOn ? 'off' : 'on';
// Update the theme-color used by some browsers for coloration of the tab headers and surrounding UI
var label = mw.msg('darkmode-turn-' + onOrOff + '-label');
$('meta[name="theme-color"]').attr('content', isOn ? '#000000' : '#eaecf0');
var tooltip = mw.msg('darkmode-turn-' + onOrOff + '-tooltip');
}
var nextnode = mw.config.get('skin') !== 'minerva' && '#pt-watchlist';
mw.util.addPortletLink('p-personal', '#', label, 'pt-darkmode', tooltip, '', nextnode);
mw.util.addPortletLink('p-personal-sticky-header', '#', label, 'pt-darkmode-sticky-header', tooltip, '', nextnode + '-sticky-header');
 
function toggleModesetHtmlClass() {
// CSS class for externally styling elements in dark mode via TemplateStyles (or CSS from other gadgets or common.css)
var newState = Number(!mw.user.options.get('gadget-dark-mode'));
// A brief flash of the original styles will occur, so this is only suitable for style changes for which flashes are tolerable.
new mw.Api().saveOption('gadget-dark-mode', newState);
// For others, update Gadget-dark-mode.css directly which is loaded without FOUCs
mw.user.options.set('gadget-dark-mode', newState);
$(document.documentElement).toggleClass('client-dark-mode', !!newStateisOn);
}
 
function vectorStickyCallback() {
// In case the user navigates to another page too quickly
mw.hook('vector.page_title_scroll').remove(vectorStickyCallback);
mw.storage.session.set('dark-mode-toggled', newState);
if (document.getElementById('pt-darkmode-sticky-header')) return;
makePortletLink('p-personal-sticky-header', 'pt-darkmode-sticky-header', '#pt-watchlist-sticky-header');
}
 
function addPortlets() {
var onOrOff = ['on', 'off'][newState];
makePortletLink('p-personal', 'pt-darkmode', '#pt-watchlist');
 
if (mw.config.get('skin') === 'vector-2022') {
// Toggle portlet link label and tooltip
mw.hook('vector.page_title_scroll').add(vectorStickyCallback);
var labelSelector = ['vector', 'vector-2022', 'minerva'].includes(mw.config.get('skin')) ? '#pt-darkmode span:not(.mw-ui-icon), #pt-darkmode-sticky-header span:not(.mw-ui-icon)' : '#pt-darkmode a';
}
$(labelSelector).text(mw.msg('darkmode-turn-' + onOrOff + '-label'));
}
$('#pt-darkmode a, #pt-darkmode-sticky-header a').attr('title', mw.msg('darkmode-turn-' + onOrOff + '-tooltip'));
// Update the mobile theme-color
$('meta[name="theme-color"]').attr('content', newState ? '#000000' : '#eaecf0');
 
function getMsg(suffix) {
// Modify the <link> element on the page to include/exclude dark-mode styles
var key = 'darkmode-turn-' + (isOn ? 'off' : 'on') + '-' + suffix;
// We can't use mw.loader as it doesn't work both ways (see talk page)
return mw.msg(key);
var scriptPath = mw.util.wikiScript('load');
}
var $gadgetsLink = $('link[rel="stylesheet"][href^="' + scriptPath + '?"][href*="ext.gadget."]');
 
if ($gadgetsLink.length) {
function makePortletLink(portletId, portletLinkId, nextnode) {
var uri = new mw.Uri($gadgetsLink.prop('href'));
var label = getMsg('label');
if (newState) {
var tooltip = getMsg('tooltip');
uri.query.modules += ',dark-mode';
$(mw.util.addPortletLink(portletId, '#', label, portletLinkId, tooltip, '', nextnode))
} else {
.children().on('click', function (e) {
if (uri.query.modules === 'ext.gadget.dark-mode') {
e.preventDefault();
// dark-mode is the only module in this link
$gadgetsLink.removetoggleMode();
return});
}
}
 
uri.query.modules = uri.query.modules
function togglePortlets() {
.replace('ext.gadget.dark-mode,', 'ext.gadget.') // dark-mode is first in the gadget list
var labelSelector;
.replace(/,dark-mode(,|$)/, '$1'); // dark-mode is in middle or end of the list
switch (mw.config.get('skin')) {
}
case 'vector':
$gadgetsLink.prop('href', uri.getRelativePath());
case 'vector-2022':
case 'minerva':
labelSelector = '#pt-darkmode span:not(:empty), #pt-darkmode-sticky-header span:not(:empty)';
break;
default:
labelSelector = '#pt-darkmode a';
}
$(labelSelector).text(getMsg('label'));
$('#pt-darkmode a, #pt-darkmode-sticky-header a')
.attr('title', getMsg('tooltip'));
}
 
function actuallyToggleDarkMode() {
// Modify the <link> element on the page to include/exclude dark-mode styles
// We can't use mw.loader as it doesn't work both ways (see talk page)
var scriptPath = mw.util.wikiScript('load');
var $gadgetsLink = $('link[rel="stylesheet"][href^="' + scriptPath + '?"][href*="ext.gadget."]');
if ($gadgetsLink.length) {
var url = new URL($gadgetsLink.prop('href'));
if (isOn) {
url.searchParams.set('modules', url.searchParams.get('modules') + ',dark-mode');
} else {
if (url.searchParams.get('modules') === 'ext.gadget.dark-mode') {
// No gadget-containing styles are enabled
// dark-mode is the only module in this link
$('<link>').attr({
$gadgetsLink.remove();
rel: 'stylesheet',
return;
href: scriptPath + '?lang=' + mw.config.get('wgUserLanguage') +
}
'&modules=ext.gadget.dark-mode&only=styles&skin=' + mw.config.get('skin')
url.searchParams.set('modules', url.searchParams.get('modules')
}).appendTo(document.head);
.replace('ext.gadget.dark-mode,', 'ext.gadget.') // dark-mode is first in the gadget list
.replace(/,dark-mode(,|$)/, '$1')); // dark-mode is in middle or end of the list
}
$gadgetsLink.prop('href', url.pathname + url.search);
} else {
// No gadget-containing styles are enabled
$('<link>').attr({
rel: 'stylesheet',
href: scriptPath + '?lang=' + mw.config.get('wgUserLanguage') +
'&modules=ext.gadget.dark-mode&only=styles&skin=' + mw.config.get('skin')
}).appendTo(document.head);
}
}
 
function savePreference() {
$('#pt-darkmode, #pt-darkmode-sticky-header').on('click', function (e) {
new mw.Api().saveOption('gadget-dark-mode', isOn ? '1' : '0');
e.preventDefault();
}
toggleMode();
 
});
function savePreferenceLocally() {
mw.user.options.set('gadget-dark-mode', Number(isOn));
 
// In case the user navigates to another page too quickly
mw.storage.session.set('dark-mode-toggled', isOn ? '1' : '0');
}
 
function notifyOtherTabs() {
// Broadcast state change to other tabs
broadcastChannel.postMessage(isOn);
}
 
function toggleMode(offline) {
isOn = !isOn;
if (!offline) {
savePreference();
notifyOtherTabs();
}
setHtmlClass();
setThemeColor();
savePreferenceLocally();
togglePortlets();
actuallyToggleDarkMode();
}
 
function toggleBasedOnSystemColourScheme() {
var systemSchemeNow = matchMedia('(prefers-color-scheme: dark)').matches;
var systemSchemeLast = mw.storage.get('dark-mode-system-scheme') === '1';
 
if (systemSchemeNow !== systemSchemeLast) {
if (systemSchemeNow !== isOn) {
toggleMode();
}
mw.requestIdleCallback(function () {
mw.storage.set('dark-mode-system-scheme', systemSchemeNow ? '1' : '0');
});
}
}
 
 
$.when($.ready, mw.loader.using(['mediawiki.util', 'mediawiki.api', 'mediawiki.storage'])).then(function () {
setHtmlClass();
setThemeColor();
addPortlets();
 
// Recover state if the navigation was too quick
var storageState = mw.storage.session.get('dark-mode-toggled');
if (storageState && Number(storageState) !== Number(isOn)) {
toggleMode(true);
}
 
// Listen to dark mode state change made on other tabs
if (window.wpDarkModeAutoToggle) {
var toggleBasedOnSystemColourScheme broadcastChannel.onmessage = function (msg) {
if (msg.data !== isOn) {
var systemSchemeNow = matchMedia('(prefers-color-scheme: dark)').matches;
toggleMode(true);
var systemSchemeLast = mw.storage.get('dark-mode-system-scheme') === '1';
}
 
};
var wpSchemeNow = !!mw.user.options.get('gadget-dark-mode');
 
if (systemSchemeNow !== systemSchemeLast) {
if (systemSchemeNow !== wpSchemeNow) {
toggleMode();
}
mw.requestIdleCallback(function () {
mw.storage.set('dark-mode-system-scheme', Number(systemSchemeNow));
});
}
};
 
if (window.wpDarkModeAutoToggle) {
toggleBasedOnSystemColourScheme();