Skip to content

Instantly share code, notes, and snippets.

@ninjakuro
Created February 4, 2024 23:39
Show Gist options
  • Save ninjakuro/fbe81168477a6ca34000057487ab3a71 to your computer and use it in GitHub Desktop.
Save ninjakuro/fbe81168477a6ca34000057487ab3a71 to your computer and use it in GitHub Desktop.
ts theme
export enum Theme {
LIGHT = 'light',
DARK = 'dark',
}
const colorScheme = window.matchMedia(`(prefers-color-scheme: ${Theme.DARK})`);
export const setTheme = (theme: Theme) => {
document.documentElement.setAttribute('data-theme', theme);
localStorage.setItem('theme', theme);
};
export const getTheme = (): Theme => {
if (localStorage.getItem('theme') === Theme.DARK || colorScheme.matches) {
return Theme.DARK
}
return Theme.LIGHT;
};
export const toggleTheme = () => {
const theme = getTheme();
setTheme(theme === Theme.DARK ? Theme.LIGHT : Theme.DARK);
};
colorScheme?.addEventListener('change', event => {
setTheme(event.matches ? Theme.DARK : Theme.LIGHT);
});
const theme = getTheme();
setTheme(theme);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment