From b050924caa24cdf2166a8845e6b0bf43b12cf85d Mon Sep 17 00:00:00 2001 From: Jappie3 Date: Sat, 26 Oct 2024 16:23:29 +0200 Subject: [PATCH] add follow system theme button & functionality --- src/App/Settings.svelte | 17 +++++++++++++++-- src/lib/appearance.ts | 25 ++++++++++++++++++++++--- 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/src/App/Settings.svelte b/src/App/Settings.svelte index 912297a65..4dfb53dc1 100644 --- a/src/App/Settings.svelte +++ b/src/App/Settings.svelte @@ -5,6 +5,7 @@ storeCodeFont, storeTheme, theme, + followSystemTheme, } from "@app/lib/appearance"; import Button from "@app/components/Button.svelte"; @@ -43,7 +44,9 @@ @@ -51,10 +54,20 @@ +
+
diff --git a/src/lib/appearance.ts b/src/lib/appearance.ts index 63660af7a..b986682ea 100644 --- a/src/lib/appearance.ts +++ b/src/lib/appearance.ts @@ -1,6 +1,7 @@ import { writable } from "svelte/store"; export type Theme = "dark" | "light"; +export const followSystemTheme = writable(shouldFollowSystemTheme()); export const theme = writable(loadTheme()); export type CodeFont = "jetbrains" | "system"; @@ -29,19 +30,28 @@ function loadCodeFont(): CodeFont { } } +function shouldFollowSystemTheme(): boolean { + const storedTheme = localStorage ? localStorage.getItem("theme") : null; + if (storedTheme === null) { + return true; // default to following the system theme + } else { + return storedTheme === "system"; + } +} + function loadTheme(): Theme { const { matches } = window.matchMedia("(prefers-color-scheme: dark)"); const storedTheme = localStorage ? localStorage.getItem("theme") : null; - if (storedTheme === null) { + if (storedTheme === null || storedTheme === "system") { return matches ? "dark" : "light"; } else { return storedTheme as Theme; } } -export function storeTheme(newTheme: Theme): void { - theme.set(newTheme); +export function storeTheme(newTheme: Theme | "system"): void { + followSystemTheme.set(newTheme === "system" ? true : false); if (localStorage) { localStorage.setItem("theme", newTheme); } else { @@ -49,6 +59,15 @@ export function storeTheme(newTheme: Theme): void { "localStorage isn't available, not able to persist the selected theme without it.", ); } + if (newTheme !== "system") { + // update the theme to newTheme + theme.set(newTheme); + } else { + // update the theme to the current system theme + theme.set( + window.matchMedia("(prefers-color-scheme: dark)") ? "dark" : "light", + ); + } } export function storeCodeFont(newCodeFont: CodeFont): void {