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

View File

@ -1,5 +1,6 @@
import { usePrefersDark } from '@solid-primitives/media'
import { makePersisted } from '@solid-primitives/storage' import { makePersisted } from '@solid-primitives/storage'
import { createSignal } from 'solid-js' import { createEffect, createSignal } from 'solid-js'
import { import {
LATENCY_QUALITY_MAP_HTTP, LATENCY_QUALITY_MAP_HTTP,
LATENCY_QUALITY_MAP_HTTPS, LATENCY_QUALITY_MAP_HTTPS,
@ -90,25 +91,14 @@ export const isLatencyTestByHttps = () =>
export const latencyQualityMap = () => export const latencyQualityMap = () =>
isLatencyTestByHttps() ? LATENCY_QUALITY_MAP_HTTPS : LATENCY_QUALITY_MAP_HTTP 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 = () => { export const useAutoSwitchTheme = () => {
applyThemeByMode() const prefersDark = usePrefersDark()
window createEffect(() => {
.matchMedia('(prefers-color-scheme: dark)') if (autoSwitchTheme()) {
.addEventListener('change', (event) => setTheme(event.matches)) setCurTheme(prefersDark() ? favNightTheme() : favDayTheme())
}
})
} }
export const [backendConfig, setBackendConfig] = createSignal<Config>() export const [backendConfig, setBackendConfig] = createSignal<Config>()