Created
January 30, 2024 17:32
-
-
Save tregoning/fb3211c2772cce1ec097d4e10cb4cdf1 to your computer and use it in GitHub Desktop.
Helper module for interacting with OS level theme preferences
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* OS theme preference related helper functions & live binding | |
* - liveUserOSThemePref: live binding to the user's OS theme preference | |
* - getCurrentOSTheme: returns the current OS theme preference | |
* - setOSThemeChangeCallback: sets a callback function to be called when the OS theme preference changes | |
*/ | |
let userOSThemePref; | |
let themeChangeCallback; | |
export {userOSThemePref as liveUserOSThemePref}; | |
export const getCurrentOSTheme = () => { | |
return userOSThemePref; | |
}; | |
export const setOSThemeChangeCallback = (callback) => { | |
themeChangeCallback = callback; | |
}; | |
const onOSThemeChange = (theme) => { | |
if (themeChangeCallback) { | |
themeChangeCallback(theme); | |
} | |
} | |
const prefersDarkScheme = window.matchMedia("(prefers-color-scheme: dark)"); | |
const setOSThemePref = () => { | |
userOSThemePref = prefersDarkScheme.matches ? 'dark' : 'light'; | |
onOSThemeChange(userOSThemePref); | |
}; | |
prefersDarkScheme.addEventListener('change', () => { | |
setOSThemePref(); | |
}, false); | |
setOSThemePref(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment