|
1 | 1 | import { writable } from "svelte/store"; |
2 | 2 |
|
3 | 3 | export type Theme = "dark" | "light"; |
| 4 | +export const followSystemTheme = writable<boolean>(shouldFollowSystemTheme()); |
4 | 5 | export const theme = writable<Theme>(loadTheme()); |
5 | 6 |
|
6 | 7 | export type CodeFont = "jetbrains" | "system"; |
@@ -29,26 +30,44 @@ function loadCodeFont(): CodeFont { |
29 | 30 | } |
30 | 31 | } |
31 | 32 |
|
| 33 | +function shouldFollowSystemTheme(): boolean { |
| 34 | + const storedTheme = localStorage ? localStorage.getItem("theme") : null; |
| 35 | + if (storedTheme === null) { |
| 36 | + return true; // default to following the system theme |
| 37 | + } else { |
| 38 | + return storedTheme === "system"; |
| 39 | + } |
| 40 | +} |
| 41 | + |
32 | 42 | function loadTheme(): Theme { |
33 | 43 | const { matches } = window.matchMedia("(prefers-color-scheme: dark)"); |
34 | 44 | const storedTheme = localStorage ? localStorage.getItem("theme") : null; |
35 | 45 |
|
36 | | - if (storedTheme === null) { |
| 46 | + if (storedTheme === null || storedTheme === "system") { |
37 | 47 | return matches ? "dark" : "light"; |
38 | 48 | } else { |
39 | 49 | return storedTheme as Theme; |
40 | 50 | } |
41 | 51 | } |
42 | 52 |
|
43 | | -export function storeTheme(newTheme: Theme): void { |
44 | | - theme.set(newTheme); |
| 53 | +export function storeTheme(newTheme: Theme | "system"): void { |
| 54 | + followSystemTheme.set(newTheme === "system" ? true : false); |
45 | 55 | if (localStorage) { |
46 | 56 | localStorage.setItem("theme", newTheme); |
47 | 57 | } else { |
48 | 58 | console.warn( |
49 | 59 | "localStorage isn't available, not able to persist the selected theme without it.", |
50 | 60 | ); |
51 | 61 | } |
| 62 | + if (newTheme !== "system") { |
| 63 | + // update the theme to newTheme |
| 64 | + theme.set(newTheme); |
| 65 | + } else { |
| 66 | + // update the theme to the current system theme |
| 67 | + theme.set( |
| 68 | + window.matchMedia("(prefers-color-scheme: dark)") ? "dark" : "light", |
| 69 | + ); |
| 70 | + } |
52 | 71 | } |
53 | 72 |
|
54 | 73 | export function storeCodeFont(newCodeFont: CodeFont): void { |
|
0 commit comments