Skip to content

Commit 311cab6

Browse files
committed
feat(theme): detect and apply OS theme preference
Add support for prefers-color-scheme media query to automatically apply dark/light themes based on OS settings when no user preference is saved. Includes listener for dynamic OS theme changes.
1 parent d403518 commit 311cab6

File tree

1 file changed

+17
-1
lines changed

1 file changed

+17
-1
lines changed

src/layouts/BaseLayout.astro

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -213,8 +213,17 @@ const ogImageURL = image ? new URL(image, Astro.url) : OPEN_GRAPH.image.src;
213213
localStorage.setItem('theme', id);
214214
}
215215

216+
function getOSThemePreference() {
217+
if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
218+
return 'dark';
219+
} else if (window.matchMedia('(prefers-color-scheme: light)').matches) {
220+
return 'light';
221+
}
222+
return null; // no preference or not supported
223+
}
224+
216225
// Apply saved theme on load
217-
applyTheme(localStorage.getItem('theme') || 'terminal-dark');
226+
applyTheme(localStorage.getItem('theme') || getOSThemePreference() || 'terminal-dark');
218227

219228
// Handle all theme links (desktop dropdown and mobile menu)
220229
document.querySelectorAll('[data-theme]').forEach(el => {
@@ -224,6 +233,13 @@ const ogImageURL = image ? new URL(image, Astro.url) : OPEN_GRAPH.image.src;
224233
if (themeId) applyTheme(themeId);
225234
});
226235
});
236+
237+
// Listen for OS theme changes (only if no saved preference)
238+
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
239+
if (!localStorage.getItem('theme')) {
240+
applyTheme(e.matches ? 'dark' : 'light');
241+
}
242+
});
227243
})();
228244
</script>
229245

0 commit comments

Comments
 (0)