Skip to content

Commit 2218b72

Browse files
committed
Implement theme management with helper script and update ThemeSelect component
1 parent fafac04 commit 2218b72

File tree

3 files changed

+45
-5
lines changed

3 files changed

+45
-5
lines changed

src/app.html

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@
4242

4343
<link rel="icon" href="%sveltekit.assets%/favicon.ico" />
4444
<meta name="viewport" content="width=device-width, initial-scale=1" />
45-
<script src="https://cdn.jsdelivr.net/npm/theme-change@2.0.2/index.js"></script>
45+
4646
<script
4747
src="https://cdn.jsdelivr.net/npm/notyf@3.10.0/notyf.min.js"
4848
defer
@@ -51,6 +51,9 @@
5151
rel="stylesheet"
5252
href="https://cdn.jsdelivr.net/npm/notyf@3.10.0/notyf.min.css"
5353
/>
54+
55+
<script src="%sveltekit.assets%/theme-helper.js"></script>
56+
5457
%sveltekit.head%
5558
</head>
5659
<body data-sveltekit-preload-data="hover">

src/lib/client/components/ThemeSelect.svelte

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,33 @@
1-
<!-- This uses the following library to handle theme changes -->
2-
<!-- https://github.com/saadeghi/theme-change -->
1+
<!--
2+
This uses the following helper to handle theme changes and is loaded
3+
in the head of the document to prevent any flash of unstyled content.
4+
5+
/static/theme-helper.js
6+
-->
37

48
<script lang="ts">
9+
import { onMount } from "svelte";
10+
511
interface Props {
612
class?: string;
713
}
814
let { class: className = "" }: Props = $props();
15+
16+
let currentTheme = $state("");
17+
onMount(() => {
18+
const theme = (window as any).getTheme();
19+
currentTheme = theme || "system";
20+
});
21+
22+
$effect(() => {
23+
(window as any).setTheme(currentTheme);
24+
});
925
</script>
1026

1127
<label class="select {className}">
1228
<span class="label">Theme</span>
13-
<select data-choose-theme>
14-
<option value="">System 🖥️</option>
29+
<select bind:value={currentTheme}>
30+
<option value="system">System 🖥️</option>
1531
<option value="light">Light ☀️</option>
1632
<option value="dark">Dark 🌑</option>
1733
<option value="dracula">Dracula 🧛</option>

static/theme-helper.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
function initThemeHelper() {
2+
function getTheme() {
3+
const theme = localStorage.getItem("theme");
4+
return theme || "";
5+
}
6+
7+
function setTheme(theme) {
8+
if (theme === "system") theme = "";
9+
10+
localStorage.setItem("theme", theme);
11+
document.documentElement.setAttribute("data-theme", theme);
12+
}
13+
14+
window.getTheme = getTheme;
15+
window.setTheme = setTheme;
16+
17+
const theme = getTheme();
18+
setTheme(theme);
19+
}
20+
21+
initThemeHelper();

0 commit comments

Comments
 (0)