Skip to content

Commit b7e1c5b

Browse files
author
huseinkntrc
committed
Follow system theme by default
1 parent 26ea8d9 commit b7e1c5b

1 file changed

Lines changed: 13 additions & 6 deletions

File tree

src/components/theme/ThemeScript.astro

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,18 @@
22
---
33

44
<script is:inline>
5-
if (!localStorage.theme) {
6-
localStorage.theme = 'dark'
7-
}
5+
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)')
6+
const hasStoredTheme = 'theme' in localStorage
7+
88
if (
9-
localStorage.theme === 'dark' ||
10-
(!('theme' in localStorage) &&
11-
window.matchMedia('(prefers-color-scheme: dark)').matches)
9+
(hasStoredTheme && localStorage.theme === 'dark') ||
10+
(!hasStoredTheme && prefersDark.matches)
1211
) {
1312
document.documentElement.classList.add('dark')
1413
} else {
1514
document.documentElement.classList.remove('dark')
1615
}
16+
1717
function attachEvent(selector, event, fn) {
1818
const matches = document.querySelectorAll(selector)
1919
if (matches && matches.length) {
@@ -22,6 +22,13 @@
2222
})
2323
}
2424
}
25+
26+
if (!hasStoredTheme) {
27+
prefersDark.addEventListener('change', (event) => {
28+
document.documentElement.classList.toggle('dark', event.matches)
29+
})
30+
}
31+
2532
window.onload = function () {
2633
attachEvent('[data-aw-toggle-color-scheme]', 'click', function () {
2734
document.documentElement.classList.add('theme-animating')

0 commit comments

Comments
 (0)