mishig HF staff commited on
Commit
c4b38e4
1 Parent(s): f08464b

support system theme and reactive change

Browse files
Files changed (1) hide show
  1. src/routes/+layout.svelte +35 -5
src/routes/+layout.svelte CHANGED
@@ -1,11 +1,41 @@
1
- <script>
2
  import "../app.css";
3
- import { browser } from '$app/environment';
4
- import { page } from '$app/stores';
 
5
 
6
- $: if (browser && $page.url.searchParams.get('__theme') === 'dark') {
7
- document.documentElement.classList.add('dark');
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  </script>
10
 
11
  <slot></slot>
 
1
+ <script lang="ts">
2
  import "../app.css";
3
+ import { onMount } from "svelte";
4
+ import { browser } from "$app/environment";
5
+ import { page } from "$app/stores";
6
 
7
+ type Theme = "light" | "dark" | "system" | null | undefined;
8
+
9
+ let systemPrefersDark = false;
10
+
11
+ function updateTheme(theme: Theme, systemPrefersDark: boolean) {
12
+ if (theme === "dark" || (theme === "system" && systemPrefersDark)) {
13
+ document.documentElement.classList.add("dark");
14
+ } else {
15
+ document.documentElement.classList.remove("dark");
16
+ }
17
+ }
18
+
19
+ $: if (browser) {
20
+ const theme = $page.url.searchParams.get("__theme") as Theme;
21
+ updateTheme(theme, systemPrefersDark);
22
  }
23
+
24
+ onMount(() => {
25
+ if (browser) {
26
+ const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
27
+ systemPrefersDark = mediaQuery.matches;
28
+
29
+ const handleChange = (event: MediaQueryListEvent) => {
30
+ systemPrefersDark = event.matches;
31
+ updateTheme($page.url.searchParams.get("__theme") as Theme, systemPrefersDark);
32
+ };
33
+
34
+ mediaQuery.addEventListener("change", handleChange);
35
+
36
+ return () => mediaQuery.removeEventListener("change", handleChange);
37
+ }
38
+ });
39
  </script>
40
 
41
  <slot></slot>