mediawiki-skins-Citizen/resources/skins.citizen.scripts/theme.js
alistair3149 047f830d1a
fix: FOUC of light theme when user is using auto theme and prefer dark
The prefer-dark script was previously deferred which causes a delay to detect and switch theme for the user. It is now inlined to prevent the delay.
2022-04-19 18:17:53 -04:00

43 lines
991 B
JavaScript

/**
* @param {Window} window
* @return {void}
*/
function initThemeSettings( window ) {
const setLocalStorage = ( themeName ) => {
try {
// eslint-disable-next-line indent
localStorage.setItem( 'skin-citizen-theme', themeName );
} catch ( e ) {}
};
const prefersDark = window.matchMedia( '(prefers-color-scheme: dark)' ),
applyTheme = () => {
window.applyPref();
// So that theme is applied but localStorage keeps the auto config
setLocalStorage( 'auto' );
};
// Monitor prefers-color-scheme changes
prefersDark.addEventListener( 'change', ( event ) => {
setLocalStorage( event.matches ? 'dark' : 'light' );
applyTheme();
} );
}
/**
* @param {Window} window
* @return {void}
*/
function initTheme( window ) {
if ( typeof window.mw !== 'undefined' ) {
const theme = window.localStorage.getItem( 'skin-citizen-theme' );
if ( theme === null || theme === 'auto' ) {
initThemeSettings( window );
}
}
}
module.exports = {
init: initTheme
};