From 4ee22410f791078bf948a083e29a583433ad3354 Mon Sep 17 00:00:00 2001 From: Nicolas Mowen Date: Wed, 20 Mar 2024 17:10:47 -0600 Subject: [PATCH] Make conig editor respect system theme --- web/src/context/theme-provider.tsx | 24 ++++++++++++++++-------- web/src/pages/ConfigEditor.tsx | 4 ++-- 2 files changed, 18 insertions(+), 10 deletions(-) diff --git a/web/src/context/theme-provider.tsx b/web/src/context/theme-provider.tsx index 26d6ef244..70dfaced1 100644 --- a/web/src/context/theme-provider.tsx +++ b/web/src/context/theme-provider.tsx @@ -1,4 +1,4 @@ -import { createContext, useContext, useEffect, useState } from "react"; +import { createContext, useContext, useEffect, useMemo, useState } from "react"; type Theme = "dark" | "light" | "system"; type ColorScheme = @@ -41,6 +41,7 @@ type ThemeProviderProps = { type ThemeProviderState = { theme: Theme; + systemTheme?: Theme; colorScheme: ColorScheme; setTheme: (theme: Theme) => void; setColorScheme: (colorScheme: ColorScheme) => void; @@ -48,6 +49,7 @@ type ThemeProviderState = { const initialState: ThemeProviderState = { theme: "system", + systemTheme: undefined, colorScheme: "theme-default", setTheme: () => null, setColorScheme: () => null, @@ -86,6 +88,16 @@ export function ThemeProvider({ } }); + const systemTheme = useMemo(() => { + if (theme != "system") { + return undefined; + } + + return window.matchMedia("(prefers-color-scheme: dark)").matches + ? "dark" + : "light"; + }, [theme]); + useEffect(() => { //localStorage.removeItem(storageKey); //console.log(localStorage.getItem(storageKey)); @@ -95,21 +107,17 @@ export function ThemeProvider({ root.classList.add(theme, colorScheme); - if (theme === "system") { - const systemTheme = window.matchMedia("(prefers-color-scheme: dark)") - .matches - ? "dark" - : "light"; - + if (systemTheme) { root.classList.add(systemTheme); return; } root.classList.add(theme); - }, [theme, colorScheme]); + }, [theme, colorScheme, systemTheme]); const value = { theme, + systemTheme, colorScheme, setTheme: (theme: Theme) => { localStorage.setItem(storageKey, JSON.stringify({ theme, colorScheme })); diff --git a/web/src/pages/ConfigEditor.tsx b/web/src/pages/ConfigEditor.tsx index cbfa17a74..eca6b8fc8 100644 --- a/web/src/pages/ConfigEditor.tsx +++ b/web/src/pages/ConfigEditor.tsx @@ -19,7 +19,7 @@ function ConfigEditor() { const { data: config } = useSWR("config/raw"); - const { theme } = useTheme(); + const { theme, systemTheme } = useTheme(); const [error, setError] = useState(); const editorRef = useRef(null); @@ -107,7 +107,7 @@ function ConfigEditor() { language: "yaml", model: modelRef.current, scrollBeyondLastLine: false, - theme: theme == "dark" ? "vs-dark" : "vs-light", + theme: (systemTheme || theme) == "dark" ? "vs-dark" : "vs-light", }); }