fix: theme toggle error and improve global styles

- Refactored theme toggle logic to synchronize theme state with user preferences and system settings.
- Introduced a new method to set the theme based on saved preferences or system color scheme.
- Updated global CSS to support dark mode by default when the system prefers it, and added functional styles for better user experience.
- Improved theme toggle animation and ensured compatibility with view transitions API.
- Enhanced accessibility by updating aria attributes for the theme toggle button.
This commit is contained in:
radishzzz 2025-01-23 09:08:16 +00:00
parent 1af92d92c8
commit 77f94f646f
2 changed files with 48 additions and 14 deletions

View file

@ -1,25 +1,39 @@
<script>
// Initialize theme toggle button
const themeToggle = document.querySelector('button[aria-pressed]') as HTMLButtonElement
themeToggle.setAttribute('aria-pressed', String(document.documentElement.classList.contains('dark')))
// Core theme switching logic
function switchTheme() {
const isDark = document.documentElement.classList.toggle('dark')
// Set theme and sync all states
function setTheme(isDark: boolean) {
const theme = isDark ? 'dark' : 'light'
document.documentElement.setAttribute('data-theme', theme)
document.documentElement.classList.toggle('dark', isDark)
themeToggle.setAttribute('aria-pressed', String(isDark))
localStorage.setItem('theme', isDark ? 'dark' : 'light')
localStorage.setItem('theme', theme)
document.dispatchEvent(new Event('theme-changed'))
}
// Handle theme toggle with view transitions API
// Initialize theme: use saved preference or fallback to system preference
const savedTheme = localStorage.getItem('theme')
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
setTheme(savedTheme ? savedTheme === 'dark' : prefersDark)
// Toggle theme with view transitions API support
function toggleTheme() {
const isDark = document.documentElement.getAttribute('data-theme') !== 'dark'
if (!document.startViewTransition) {
switchTheme()
setTheme(isDark)
return
}
document.startViewTransition(switchTheme)
document.startViewTransition(() => setTheme(isDark))
}
// Sync with system theme changes only if user hasn't set a preference
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
if (!localStorage.getItem('theme')) {
setTheme(e.matches)
}
})
themeToggle.addEventListener('click', toggleTheme)
</script>