diff --git a/assets/js/theme.js b/assets/js/theme.js new file mode 100644 index 0000000..ed738ce --- /dev/null +++ b/assets/js/theme.js @@ -0,0 +1,21 @@ +// https://web.dev/building-a-theme-switch-component/ +const storageKey = 'theme-preference' + +const getColorPreference = () => { + if (localStorage.getItem(storageKey)) + return localStorage.getItem(storageKey) + else + return window.matchMedia('(prefers-color-scheme: dark)').matches + ? 'dark' + : 'light' +} + +const setPreference = () => { + localStorage.setItem(storageKey, theme.value) + reflectPreference() +} + +window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', ({matches:isDark}) => { + theme.value = isDark ? 'dark' : 'light' + setPreference() +}) \ No newline at end of file