fix: theme toggle error

This commit is contained in:
radishzzz 2025-01-23 10:49:44 +00:00
parent 20fd3b65f3
commit 9d47579a87

View file

@ -20,11 +20,21 @@
document.startViewTransition(switchTheme) document.startViewTransition(switchTheme)
} }
// Sync theme on page navigation // Apply theme to document
document.addEventListener('astro:after-swap', () => { function applyTheme(doc: Document) {
const theme = localStorage.getItem('theme') const theme = localStorage.getItem('theme')
document.documentElement.classList.toggle('dark', theme === 'dark') const isDark = theme === 'dark'
themeToggle.setAttribute('aria-pressed', String(theme === 'dark')) doc.documentElement.classList.toggle('dark', isDark)
const button = doc === document ? themeToggle : doc.querySelector('button[aria-pressed]')
if (button) {
button.setAttribute('aria-pressed', String(isDark))
}
}
// Initialize theme and handle page navigation
applyTheme(document)
document.addEventListener('astro:before-swap', (e) => {
applyTheme(e.newDocument)
}) })
themeToggle.addEventListener('click', toggleTheme) themeToggle.addEventListener('click', toggleTheme)