Skip to content

Commit d91347e

Browse files
committed
2 parents d754519 + 1b260f6 commit d91347e

File tree

2 files changed

+21
-9
lines changed

2 files changed

+21
-9
lines changed

src/components/layout/theme-toggle.tsx

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,17 @@
1-
'use client'
2-
31
import * as React from 'react'
42
import { MoonStarIcon, SunIcon } from 'lucide-react'
53
import { Button } from '@/components/ui/button'
64

75
function ThemeToggle() {
86
const [theme, setTheme] = React.useState<'light' | 'dark'>(() => {
9-
// Read initial theme from DOM (already set by blocking script)
10-
if (typeof document !== 'undefined') {
7+
// Read initial theme from localStorage first, then DOM
8+
if (typeof window !== 'undefined') {
9+
const stored = localStorage.getItem('theme')
10+
11+
if (stored === 'light' || stored === 'dark') {
12+
return stored
13+
}
14+
1115
return document.documentElement.classList.contains('dark') ? 'dark' : 'light'
1216
}
1317

src/layouts/Layout.astro

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -43,12 +43,20 @@ const seoProps = Astro.props as Props
4343
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
4444
}
4545

46-
const theme = getTheme()
47-
if (theme === 'dark') {
48-
document.documentElement.classList.add('dark')
49-
} else {
50-
document.documentElement.classList.remove('dark')
46+
const applyTheme = () => {
47+
const theme = getTheme()
48+
if (theme === 'dark') {
49+
document.documentElement.classList.add('dark')
50+
} else {
51+
document.documentElement.classList.remove('dark')
52+
}
5153
}
54+
55+
// Apply theme immediately on initial load
56+
applyTheme()
57+
58+
// Re-apply theme on Astro page transitions
59+
document.addEventListener('astro:page-load', applyTheme)
5260
})()
5361
</script>
5462
<style>

0 commit comments

Comments
 (0)