mirror of
https://github.com/reonokiy/blog.nokiy.net.git
synced 2025-06-17 20:01:33 +02:00
fix: theme toggle error
- Streamlined theme toggle logic to better synchronize with user preferences and system settings. - Updated the initialization of the theme to utilize a more robust method for determining the default mode. - Improved accessibility by ensuring aria attributes are correctly set for the theme toggle button. - Enhanced global CSS styles for better consistency and added support for view transitions during theme changes. - Removed redundant code and improved overall readability of the theme toggle component.
This commit is contained in:
parent
77f94f646f
commit
419b8b5611
3 changed files with 49 additions and 82 deletions
|
@ -1,39 +1,25 @@
|
|||
<script>
|
||||
// Initialize theme toggle button
|
||||
const themeToggle = document.querySelector('button[aria-pressed]') as HTMLButtonElement
|
||||
themeToggle.setAttribute('aria-pressed', String(document.documentElement.classList.contains('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)
|
||||
// Core theme switching logic
|
||||
function switchTheme() {
|
||||
const isDark = document.documentElement.classList.toggle('dark')
|
||||
themeToggle.setAttribute('aria-pressed', String(isDark))
|
||||
localStorage.setItem('theme', theme)
|
||||
localStorage.setItem('theme', isDark ? 'dark' : 'light')
|
||||
document.dispatchEvent(new Event('theme-changed'))
|
||||
}
|
||||
|
||||
// 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
|
||||
// Handle theme toggle with view transitions API
|
||||
function toggleTheme() {
|
||||
const isDark = document.documentElement.getAttribute('data-theme') !== 'dark'
|
||||
if (!document.startViewTransition) {
|
||||
setTheme(isDark)
|
||||
switchTheme()
|
||||
return
|
||||
}
|
||||
document.startViewTransition(() => setTheme(isDark))
|
||||
document.startViewTransition(switchTheme)
|
||||
}
|
||||
|
||||
// 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>
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue