mediawiki-skins-Citizen/resources/skins.citizen.scripts/theme.js

55 lines
1.2 KiB
JavaScript
Raw Normal View History

/**
* @param {Window} window
* @return {void}
*/
function initThemeSettings( window ) {
const userTheme = window.mw.user.options.get( 'CitizenThemeUser' ),
setLocalStorage = ( theme ) => {
try {
localStorage.setItem( 'skin-citizen-theme', theme );
} catch ( e ) {}
};
let theme = ( userTheme !== null ) ? userTheme : 'auto';
if ( theme === 'auto' ) {
2021-06-09 18:40:44 +00:00
const prefersDark = window.matchMedia( '(prefers-color-scheme: dark)' ),
applyTheme = () => {
window.applyPref();
// So that theme is applied but localStorage keeps the auto config
setLocalStorage( 'auto' );
};
theme = prefersDark.matches ? 'dark' : 'light';
// Monitor prefers-color-scheme changes
prefersDark.addEventListener( 'change', ( event ) => {
setLocalStorage( event.matches ? 'dark' : 'light' );
2021-06-09 18:40:44 +00:00
applyTheme();
} );
2021-06-09 18:40:44 +00:00
setLocalStorage( theme );
applyTheme();
} else {
setLocalStorage( theme );
window.applyPref();
}
}
/**
* @param {Window} window
* @return {void}
*/
function initTheme( window ) {
if ( typeof window.mw !== 'undefined' ) {
2021-06-09 18:40:44 +00:00
const theme = window.localStorage.getItem( 'skin-citizen-theme' );
if ( theme === null || theme === 'auto' ) {
initThemeSettings( window );
}
}
}
module.exports = {
init: initTheme
};