From ae25506987aeacb912e06432d2d36081cfd1ab39 Mon Sep 17 00:00:00 2001 From: lawvs <18554747+lawvs@users.noreply.github.com> Date: Tue, 23 Apr 2024 18:08:02 +0800 Subject: [PATCH] refactor: use ResolvedTheme instead of SystemTheme --- src/components/preview-panel.tsx | 4 ++-- src/components/theme-provider.tsx | 26 ++++++++++---------------- 2 files changed, 12 insertions(+), 18 deletions(-) diff --git a/src/components/preview-panel.tsx b/src/components/preview-panel.tsx index 692e345..0cedcd9 100644 --- a/src/components/preview-panel.tsx +++ b/src/components/preview-panel.tsx @@ -10,7 +10,7 @@ import { useTheme } from "./theme-provider"; import { Button } from "./ui/button"; export function PreviewPanel() { - const { theme, systemPreferenceTheme } = useTheme(); + const { resolvedTheme } = useTheme(); const [yDoc] = useYDoc(); const [config] = useConfig(); const [addDialogOpen, setAddDialogOpen] = useState(false); @@ -87,7 +87,7 @@ export function PreviewPanel() { setDeleteDialogOpen(true); }} displaySize={config.showSize} - theme={theme === "system" ? systemPreferenceTheme : theme} + theme={resolvedTheme} defaultInspectDepth={2} valueTypes={[yDataType]} /> diff --git a/src/components/theme-provider.tsx b/src/components/theme-provider.tsx index ced21ea..ca830fd 100644 --- a/src/components/theme-provider.tsx +++ b/src/components/theme-provider.tsx @@ -1,7 +1,7 @@ import { createContext, useContext, useEffect, useState } from "react"; -type SystemTheme = "dark" | "light"; -type Theme = SystemTheme | "system"; +type ResolvedTheme = "dark" | "light"; +type Theme = ResolvedTheme | "system"; type ThemeProviderProps = { children: React.ReactNode; @@ -11,13 +11,13 @@ type ThemeProviderProps = { type ThemeProviderState = { theme: Theme; - systemPreferenceTheme: SystemTheme; + resolvedTheme: ResolvedTheme; setTheme: (theme: Theme) => void; }; const initialState: ThemeProviderState = { theme: "system", - systemPreferenceTheme: "light", + resolvedTheme: "light", setTheme: () => null, }; @@ -47,24 +47,18 @@ export function ThemeProvider({ const [theme, setTheme] = useState( () => (localStorage.getItem(storageKey) as Theme) || defaultTheme, ); - const systemPreferenceDark = useSystemPreferenceDark(); - const systemTheme: SystemTheme = systemPreferenceDark ? "dark" : "light"; + const systemPreferenceTheme = useSystemPreferenceDark() ? "dark" : "light"; + const resolvedTheme: ResolvedTheme = + theme === "system" ? systemPreferenceTheme : theme; useEffect(() => { const root = window.document.documentElement; - root.classList.remove("light", "dark"); - - if (theme === "system") { - root.classList.add(systemTheme); - return; - } - - root.classList.add(theme); - }, [systemTheme, theme]); + root.classList.add(resolvedTheme); + }, [resolvedTheme, theme]); const value = { theme, - systemPreferenceTheme: systemTheme, + resolvedTheme: resolvedTheme, setTheme: (theme: Theme) => { localStorage.setItem(storageKey, theme); setTheme(theme);