From ef36decc3c39e67a9e44ffbeff33804d3fa1aa5b Mon Sep 17 00:00:00 2001 From: kunish Date: Thu, 14 Sep 2023 17:12:55 +0800 Subject: [PATCH] refactor: auto switch theme --- src/pages/Config.tsx | 12 ++---------- src/signals/config.ts | 26 ++++++++------------------ 2 files changed, 10 insertions(+), 28 deletions(-) diff --git a/src/pages/Config.tsx b/src/pages/Config.tsx index 64abf6a..5fb5b0a 100644 --- a/src/pages/Config.tsx +++ b/src/pages/Config.tsx @@ -34,7 +34,6 @@ import { themes, } from '~/constants' import { - applyThemeByMode, autoCloseConns, autoSwitchTheme, backendConfig, @@ -280,10 +279,7 @@ const ConfigForXd = () => { { - setFavNightTheme(e.target.value) - applyThemeByMode() - }} + onChange={(e) => setFavNightTheme(e.target.value)} > {(theme) => ( @@ -327,7 +320,6 @@ const ConfigForXd = () => { value: autoSwitchTheme, onChange: (value: boolean) => { setAutoSwitchTheme(value) - applyThemeByMode() }, subChild: autoSwitchThemeSubChild, }, diff --git a/src/signals/config.ts b/src/signals/config.ts index 9c28f54..a74bc3b 100644 --- a/src/signals/config.ts +++ b/src/signals/config.ts @@ -1,5 +1,6 @@ +import { usePrefersDark } from '@solid-primitives/media' import { makePersisted } from '@solid-primitives/storage' -import { createSignal } from 'solid-js' +import { createEffect, createSignal } from 'solid-js' import { LATENCY_QUALITY_MAP_HTTP, LATENCY_QUALITY_MAP_HTTPS, @@ -90,25 +91,14 @@ export const isLatencyTestByHttps = () => export const latencyQualityMap = () => isLatencyTestByHttps() ? LATENCY_QUALITY_MAP_HTTPS : LATENCY_QUALITY_MAP_HTTP -const setTheme = (isDark: boolean) => { - if (autoSwitchTheme()) { - if (isDark) { - setCurTheme(favNightTheme()) - } else { - setCurTheme(favDayTheme()) - } - } -} - -export const applyThemeByMode = () => - setTheme(window.matchMedia('(prefers-color-scheme: dark)').matches) - export const useAutoSwitchTheme = () => { - applyThemeByMode() + const prefersDark = usePrefersDark() - window - .matchMedia('(prefers-color-scheme: dark)') - .addEventListener('change', (event) => setTheme(event.matches)) + createEffect(() => { + if (autoSwitchTheme()) { + setCurTheme(prefersDark() ? favNightTheme() : favDayTheme()) + } + }) } export const [backendConfig, setBackendConfig] = createSignal()