diff --git a/build.sh b/build.sh index 3fe9edc..2651cd9 100644 --- a/build.sh +++ b/build.sh @@ -1,10 +1,9 @@ cd $(dirname $0) export PATH=$PATH:$PWD/node_modules/.bin -esbuild --minify --bundle --outdir=temp lib/theme-script.ts -echo "" > lib/theme-script.astro +echo "{/* Auto-generated by build.sh */}" > lib/theme-script.astro echo "" >> lib/theme-script.astro astro build diff --git a/lib/theme-script.astro b/lib/theme-script.astro index 41d4dbc..67b52ee 100644 --- a/lib/theme-script.astro +++ b/lib/theme-script.astro @@ -1,4 +1,4 @@ - +{/* Auto-generated by build.sh */} diff --git a/lib/theme-script.ts b/lib/theme-script.ts index 97de560..cabfb1e 100644 --- a/lib/theme-script.ts +++ b/lib/theme-script.ts @@ -3,22 +3,24 @@ const storageKey = 'theme-toggle' + let currentTheme: Theme | undefined + function getSystemTheme(): Theme { return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light' } - function getUserTheme(): Theme | null { + function getStoredTheme(): Theme | null { const theme = localStorage.getItem(storageKey) return theme === 'dark' || theme === 'light' ? theme : null } function getTheme(): Theme { - return getUserTheme() || getSystemTheme() + return currentTheme || getStoredTheme() || getSystemTheme() } - function setUserTheme(theme: Theme) { + function setStoredTheme(theme: Theme) { if (theme === getSystemTheme()) { localStorage.removeItem(storageKey) } else { @@ -34,7 +36,8 @@ } function setTheme(theme: Theme) { - setUserTheme(theme) + currentTheme = theme + setStoredTheme(theme) setStyle(theme) }