Skip to content

Instantly share code, notes, and snippets.

@tregoning
Created January 30, 2024 17:32
Show Gist options
  • Save tregoning/fb3211c2772cce1ec097d4e10cb4cdf1 to your computer and use it in GitHub Desktop.
Save tregoning/fb3211c2772cce1ec097d4e10cb4cdf1 to your computer and use it in GitHub Desktop.
Helper module for interacting with OS level theme preferences
/**
* 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