Skip to content

Commit

Permalink
fix: persist dark mode
Browse files Browse the repository at this point in the history
  • Loading branch information
jesperorb committed Mar 23, 2024
1 parent 7eb46ab commit 3f53205
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
4 changes: 3 additions & 1 deletion src/lib/components/ui/DarkModeToggle.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,12 @@
const change = (event: Event) => {
const target = event.target as HTMLInputElement;
const element = browser ? document.querySelector('html') : null;
if (element) {
if (element && browser) {
if (target.checked) {
localStorage.setItem("dark-mode", "1");
element.setAttribute('data-dark-mode', 'true');
} else {
localStorage.removeItem("dark-mode");
element.removeAttribute('data-dark-mode');
}
}
Expand Down
8 changes: 7 additions & 1 deletion src/routes/+layout.svelte
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<script lang="ts">
import type { Page } from '@sveltejs/kit';
import { dev } from '$app/environment';
import { dev, browser } from '$app/environment';
import type { FormatMethodsKeys } from '$lib/format-methods';
import { page, navigating } from '$app/stores';
Expand All @@ -9,12 +9,18 @@
import SkipLink from '$lib/components/ui/SkipLink.svelte';
import ProgressBar from '$lib/components/ui/ProgressBar.svelte';
import Header from '$lib/components/ui/Header.svelte';
import { onMount } from 'svelte';
let routeId: FormatMethodsKeys | 'Playground';
const getRouteId = (page: Page<Record<string, string>>): void => {
routeId = page.route.id?.replace('/', '') as FormatMethodsKeys;
};
$: getRouteId($page);
onMount(() => {
if(browser && localStorage.getItem("dark-mode")) {
document.querySelector("html")?.setAttribute("data-dark-mode", "true");
}
})
</script>

<svelte:head>
Expand Down

0 comments on commit 3f53205

Please sign in to comment.