User:Nardog/dark-mode-toggle.js: Difference between revisions

Content deleted Content added
No edit summary
No edit summary
 
(48 intermediate revisions by 2 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', 'oojs-ui.styles.icons-accessibility'
])).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');
 
function setThemeColor() {
// Update the initial mobile theme-color
// Update the theme-color used by some browsers for coloration of the tab headers and surrounding UI
$('meta[name="theme-color"]').attr('content', '#000');
$('meta[name="theme-color"]').attr('content', isOn ? '#000000' : '#eaecf0');
}
}
 
function setHtmlClass() {
var onOrOff = isOn ? 'off' : 'on';
// CSS class for externally styling elements in dark mode via TemplateStyles (or CSS from other gadgets or common.css)
var label = mw.msg('darkmode-turn-' + onOrOff + '-label');
// A brief flash of the original styles will occur, so this is only suitable for style changes for which flashes are tolerable.
var tooltip = mw.msg('darkmode-turn-' + onOrOff + '-tooltip');
// For others, update Gadget-dark-mode.css directly which is loaded without FOUCs
var nextnode = mw.config.get('skin') !== 'minerva' && '#pt-watchlist';
$(document.documentElement).toggleClass('client-dark-mode', isOn);
var portletLink = mw.util.addPortletLink('p-personal', '#', label, 'pt-darkmode', tooltip, '', nextnode);
}
 
function toggleModevectorStickyCallback() {
mw.hook('vector.page_title_scroll').remove(vectorStickyCallback);
var newState = Number(!mw.user.options.get('gadget-dark-mode'));
if (document.getElementById('pt-darkmode-sticky-header')) return;
new mw.Api().saveOption('gadget-dark-mode', newState);
makePortletLink('p-personal-sticky-header', 'pt-darkmode-sticky-header', '#pt-watchlist-sticky-header');
mw.user.options.set('gadget-dark-mode', newState);
}
$(document.documentElement).toggleClass('client-dark-mode', !!newState);
$('meta[name="theme-color"]').attr('content', newState ? '#000' : '#eaecf0');
mw.storage.session.set('dark-mode-toggled', newState);
 
function addPortlets() {
// Toggle portlet link label and tooltip
makePortletLink('p-personal', 'pt-darkmode', '#pt-watchlist');
var onOrOff = ['on', 'off'][newState];
 
$('#pt-darkmode, #pt-darkmode *').contents().each(function () {
if (mw.config.get('skin') === 'vector-2022') {
// If it's a text node and has more than just whitespace
mw.hook('vector.page_title_scroll').add(vectorStickyCallback);
if (this.nodeType === 3 && /\S/.test(this.textContent)) {
}
this.textContent = mw.msg('darkmode-turn-' + onOrOff + '-label');
}
return false; // break
 
}
function getMsg(suffix) {
var key = 'darkmode-turn-' + (isOn ? 'off' : 'on') + '-' + suffix;
return mw.msg(key);
}
 
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();
});
}
$('#pt-darkmode a').attr('title', mw.msg('darkmode-turn-' + onOrOff + '-tooltip'));
 
function togglePortlets() {
// Swap classes
var labelSelector;
$('#pt-darkmode .mw-ui-icon').toggleClass('mw-ui-icon-moon mw-ui-icon-bright');
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
// 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)
// We can't use mw.loader as it doesn't work both ways (see talk page)
var scriptPath = mw.util.wikiScript('load');
var scriptPath = mw.util.wikiScript('load');
var gadgetsLinkElement = $('link[rel="stylesheet"][href^="' + scriptPath + '?"][href*="ext.gadget."]')[0];
var $gadgetsLink = $('link[rel="stylesheet"][href^="' + scriptPath + '?"][href*="ext.gadget."]');
if (gadgetsLinkElement) {
if ($gadgetsLink.length) {
var uri = new mw.Uri(gadgetsLinkElement.href);
var url = new URL($gadgetsLink.prop('href'));
if (newState) {
uri.query.var modules += url.searchParams.get(',dark-modemodules');
}if else(isOn) {
uri.query.modules += uri.query.modules',dark-mode';
.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
}
gadgetsLinkElement.href = uri.getRelativePath();
} else {
if (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')
modules = 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
}
url.searchParams.set('modules', modules);
$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);
}
}
 
$(portletLink).on('click', function savePreference(e) {
new mw.Api().saveOption('gadget-dark-mode', isOn ? '1' : '0');
e.preventDefault();
}
toggleMode();
});
 
function savePreferenceLocally() {
var $icon = $('.mw-ui-icon', portletLink);
mw.user.options.set('gadget-dark-mode', Number(isOn));
if ($icon.length) {
 
$icon.addClass(isOn ? 'mw-ui-icon-bright' : 'mw-ui-icon-moon');
// 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.Uri', '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();