Skip to content

Commit

Permalink
Add theme initialization to all pages
Browse files Browse the repository at this point in the history
Initially just a swap between light and dark, but can optionally have more later
  • Loading branch information
Snugug committed Jun 23, 2023
1 parent e5d76a6 commit 79b0b8f
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
37 changes: 37 additions & 0 deletions astro/src/js/theme.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { writable } from 'svelte/store';

/**
* Creates a writable store for the theme
* @return {WritableStore<'dark' | 'light'>} Returns a writable store
*/
function createThemeStore() {
const { subscribe, set } = writable();

return {
subscribe,
set(theme: 'dark' | 'light') {
if ('localStorage' in window) {
localStorage.setItem('theme', theme);
}
set(theme);
},
init() {
let theme;
if ('localStorage' in window) {
theme = localStorage.getItem('theme') || null;
}

if (theme === null) {
theme =
window.matchMedia &&
window.matchMedia('(prefers-color-scheme: dark)').matches
? 'dark'
: 'light';
}

set(theme);
},
};
}

export const theme = createThemeStore();
5 changes: 5 additions & 0 deletions astro/src/layouts/wrapper.astro
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,11 @@ const microcopy = getMicrocopy(locale.code);
<SubscribeFooter lang={locale.code} />
<Footer lang={locale.code} />

<script>
import { theme } from '$js/theme';
theme.init();
</script>

<!-- Cookie Disclaimer -->

<!-- Global site tag (gtag.js) - Google Analytics -->
Expand Down

0 comments on commit 79b0b8f

Please sign in to comment.