refactor: auto switch theme

This commit is contained in:
kunish 2023-09-14 17:12:55 +08:00
parent d7932a8f28
commit ef36decc3c
No known key found for this signature in database
GPG Key ID: 647A12B4F782C430
2 changed files with 10 additions and 28 deletions

View File

@ -34,7 +34,6 @@ import {
themes,
} from '~/constants'
import {
applyThemeByMode,
autoCloseConns,
autoSwitchTheme,
backendConfig,
@ -280,10 +279,7 @@ const ConfigForXd = () => {
<select
class="select select-bordered w-full max-w-xs"
onChange={(e) => {
setFavDayTheme(e.target.value)
applyThemeByMode()
}}
onChange={(e) => setFavDayTheme(e.target.value)}
>
<For each={themes}>
{(theme) => (
@ -299,10 +295,7 @@ const ConfigForXd = () => {
<select
class="select select-bordered w-full max-w-xs"
onChange={(e) => {
setFavNightTheme(e.target.value)
applyThemeByMode()
}}
onChange={(e) => setFavNightTheme(e.target.value)}
>
<For each={themes}>
{(theme) => (
@ -327,7 +320,6 @@ const ConfigForXd = () => {
value: autoSwitchTheme,
onChange: (value: boolean) => {
setAutoSwitchTheme(value)
applyThemeByMode()
},
subChild: autoSwitchThemeSubChild,
},

View File

@ -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<Config>()