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

Content deleted Content added
+nextnode, requested on talk
Remove mw.uri
 
(24 intermediate revisions by 8 users not shown)
Line 5:
*/
 
// 'Dark mode' and 'Light mode' messages must match the ::before content in
mw.messages.set({
// [[MediaWiki:Gadget-dark-mode-toggle-pagestyles.css]] and [[MediaWiki:Gadget-dark-mode.css]], respectively.
'darkmode-turn-on-label': 'Dark mode',
// Don't overwrite existing messages, if already set on a foreign wiki prior to loading this file
'darkmode-turn-on-tooltip': 'Turn on dark mode',
if (!mw.messages.get('darkmode-turn-offon-label':)) 'Light mode',{
mw.messages.set({
'darkmode-turn-off-tooltip': 'Turn off dark mode',
'darkmode-turn-on-label': 'Dark mode',
});
'darkmode-turn-on-tooltip': 'Turn dark mode on',
'darkmode-turn-off-label': 'Light mode',
'darkmode-turn-off-tooltip': 'Turn dark mode off',
});
}
 
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 inDarkMode = !!mw.user.options.get('gadget-dark-mode');
 
var broadcastChannel = new BroadcastChannel('gadget-dark-mode');
var onOrOff = inDarkMode ? 'off' : 'on';
var label = mw.msg('darkmode-turn-' + onOrOff + '-label');
var tooltip = mw.msg('darkmode-turn-' + onOrOff + '-tooltip');
var nextnode = mw.config.get('skin') === 'minerva' ? 'li:has([data-event-name="menu.unStar"])' : '#pt-watchlist';
mw.util.addPortletLink('p-personal', '#', label, 'pt-darkmode', tooltip, '', nextnode);
 
function toggleModesetThemeColor() {
// Update the theme-color used by some browsers for coloration of the tab headers and surrounding UI
var darkMode = !mw.user.options.get('gadget-dark-mode');
$('meta[name="theme-color"]').attr('content', isOn ? '#000000' : '#eaecf0');
new mw.Api().saveOption('gadget-dark-mode', darkMode ? '1' : '0');
}
mw.user.options.set('gadget-dark-mode', darkMode ? 1 : 0);
 
function setHtmlClass() {
var onOrOff = darkMode ? 'off' : 'on';
// 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).toggleClass('client-dark-mode', isOn);
}
 
function vectorStickyCallback() {
// Toggle portlet link label and tooltip
mw.hook('vector.page_title_scroll').remove(vectorStickyCallback);
var labelSelector = ['vector', 'minerva'].includes(mw.config.get('skin')) ? '#pt-darkmode span:not(.mw-ui-icon)' : '#pt-darkmode a';
$ if (labelSelector)document.text(mw.msggetElementById('pt-darkmode-turnsticky-' + onOrOff + '-labelheader')) return;
makePortletLink('p-personal-sticky-header', 'pt-darkmode-sticky-header', '#pt-watchlist-sticky-header');
$('#pt-darkmode a').attr('title', mw.msg('darkmode-turn-' + onOrOff + '-tooltip'));
}
 
function addPortlets() {
// Modify the <link> element on the page to include/exclude dark-mode styles
makePortletLink('p-personal', 'pt-darkmode', '#pt-watchlist');
// We can't use mw.loader as it doesn't work both ways (see talk page)
 
var gadgetsLinkElement = $('link[rel="stylesheet"][href*="ext.gadget."]').get(0);
if (mw.config.get('skin') === 'vector-2022') {
if (gadgetsLinkElement) {
mw.hook('vector.page_title_scroll').add(vectorStickyCallback);
var uri = new mw.Uri(gadgetsLinkElement.href);
}
if (darkMode) {
}
uri.query.modules += ',dark-mode';
 
} else {
function getMsg(suffix) {
uri.query.modules = uri.query.modules
var key = 'darkmode-turn-' + (isOn ? 'off' : 'on') + '-' + suffix;
.replace('ext.gadget.dark-mode', 'ext.gadget.') // dark-mode is first in the gadget list
return mw.msg(key);
.replace(/,dark-mode(,|$)/, '$1'); // dark-mode is in middle or end of the list
}
 
gadgetsLinkElement.href = uri.getRelativePath();
function makePortletLink(portletId, portletLinkId, nextnode) {
var label = getMsg('label');
var tooltip = getMsg('tooltip');
$(mw.util.addPortletLink(portletId, '#', label, portletLinkId, tooltip, '', nextnode))
.children().on('click', function (e) {
e.preventDefault();
toggleMode();
});
}
 
function togglePortlets() {
var labelSelector;
switch (mw.config.get('skin')) {
case 'vector':
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 gadgets containing styles are enabled
// dark-mode is the only module in this link
$('<link>').attr('rel', 'stylesheet')
$gadgetsLink.remove();
.attr('href', mw.util.wikiScript('load') + '?lang=' + mw.config.get('wgUserLanguage') +
return;
'&modules=ext.gadget.dark-mode&only=styles&skin=' + mw.config.get('skin')).appendTo('head');
}
url.searchParams.set('modules', url.searchParams.get('modules')
.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').on('click', function(e) {
new mw.Api().saveOption('gadget-dark-mode', isOn ? '1' : '0');
e.preventDefault();
}
toggleMode();
});
 
function savePreferenceLocally() {
if (window.wpDarkModeAutoToggle) {
mw.user.options.set('gadget-dark-mode', Number(isOn));
var toggleBasedOnSystemColourScheme = function () {
var systemSchemeNow = matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
var systemSchemeLast = mw.storage.get('dark-mode-system-scheme') || 'light';
 
// In case the user navigates to another page too quickly
var wpSchemeNow = mw.user.options.get('gadget-dark-mode') ? 'dark' : 'light';
mw.storage.session.set('dark-mode-toggled', isOn ? '1' : '0');
}
 
function notifyOtherTabs() {
if (systemSchemeNow !== systemSchemeLast && systemSchemeNow !== wpSchemeNow) {
// Broadcast state change to other tabs
toggleMode();
broadcastChannel.postMessage(isOn);
}
}
mw.storage.set('dark-mode-system-scheme', systemSchemeNow);
};
 
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
broadcastChannel.onmessage = function (msg) {
if (msg.data !== isOn) {
toggleMode(true);
}
};
 
if (window.wpDarkModeAutoToggle) {
toggleBasedOnSystemColourScheme();
 
Line 82 ⟶ 181:
}
}
 
});