Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions src/app.html
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,17 @@
/>

<script>
// Prevent flash of light theme on load :)
if (localStorage.getItem('theme') === 'dark') document.documentElement.classList.add('dark');
if (localStorage.getItem('theme') === null) {
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
// Prevent flash of light theme on load
document.documentElement.classList.add('dark');
}
} else if (localStorage.getItem('theme') === 'dark')
// Prevent flash of light theme on load
document.documentElement.classList.add('dark');
</script>
</head>

<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
</body>
Expand Down
7 changes: 7 additions & 0 deletions src/lib/components/ThemeSwitch.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,13 @@
let theme = getContext<ThemeContext>('theme');

function handleClick() {
if ($theme === undefined) {
let browserDefault: 'light' | 'dark' =
window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches
? 'light'
: 'dark';
theme.update((value) => browserDefault);
}
theme.update((value) => (value === 'dark' ? 'light' : 'dark'));
}
</script>
Expand Down
14 changes: 14 additions & 0 deletions src/routes/+layout.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,20 @@
} else {
document.documentElement.classList.remove('dark');
}
} else {
if (localStorage.getItem('theme') === null) {
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches) {
$theme = 'light';
} else {
$theme = 'dark';
}
} else {
if (localStorage.getItem('theme') === 'light') {
$theme = 'light';
} else {
$theme = 'dark';
}
}
}
});
</script>
Expand Down