30 lines
893 B
JavaScript
30 lines
893 B
JavaScript
import { onMounted, onUnmounted, ref } from 'vue';
|
|
|
|
const preference = ref('system');
|
|
|
|
function applyTheme() {
|
|
const resolved = preference.value === 'system'
|
|
? (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light')
|
|
: preference.value;
|
|
document.documentElement.dataset.theme = resolved;
|
|
}
|
|
|
|
export function useTheme() {
|
|
function setTheme(nextTheme) {
|
|
preference.value = nextTheme;
|
|
localStorage.setItem('pokemon-inventory-theme', nextTheme);
|
|
applyTheme();
|
|
}
|
|
|
|
onMounted(() => {
|
|
preference.value = localStorage.getItem('pokemon-inventory-theme') ?? 'system';
|
|
applyTheme();
|
|
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', applyTheme);
|
|
});
|
|
|
|
onUnmounted(() => {
|
|
window.matchMedia('(prefers-color-scheme: dark)').removeEventListener('change', applyTheme);
|
|
});
|
|
|
|
return { preference, setTheme };
|
|
} |