feat: light/dark modes switch immediately with the system theme (#95)

This commit is contained in:
xingo xu
2024-06-06 02:20:05 +09:00
committed by GitHub
parent 3f4e7e9f97
commit c3ac8d9728
3 changed files with 62 additions and 22 deletions

View File

@@ -1,22 +1,52 @@
<script lang="ts">
import Icon from "@iconify/svelte"
import {i18n} from '@i18n/translation'
import type { LIGHT_DARK_MODE } from '@/types/config.ts'
import {
AUTO_MODE,
DARK_MODE,
LIGHT_MODE,
} from '@constants/constants.ts'
import I18nKey from '@i18n/i18nKey'
import {setTheme, getStoredTheme} from '../utils/setting-utils.ts'
import {onMount} from "svelte";
import {AUTO_MODE, DARK_MODE, LIGHT_MODE} from "@constants/constants.ts";
import { i18n } from '@i18n/translation'
import Icon from '@iconify/svelte'
import {
applyThemeToDocument,
getStoredTheme,
setTheme,
} from '@utils/setting-utils.ts'
import { onMount } from 'svelte'
const seq = [LIGHT_MODE, DARK_MODE, AUTO_MODE]
let mode = AUTO_MODE
const seq: LIGHT_DARK_MODE[] = [
LIGHT_MODE,
DARK_MODE,
AUTO_MODE,
]
let mode: LIGHT_DARK_MODE = AUTO_MODE
onMount(() => {
mode = getStoredTheme()
mode = getStoredTheme()
const darkModePreference = window.matchMedia(
'(prefers-color-scheme: dark)',
)
const changeThemeWhenSchemeChanged: Parameters<
typeof darkModePreference.addEventListener<'change'>
>[1] = e => {
applyThemeToDocument(mode)
}
darkModePreference.addEventListener(
'change',
changeThemeWhenSchemeChanged,
)
return () => {
darkModePreference.removeEventListener(
'change',
changeThemeWhenSchemeChanged,
)
}
})
function switchScheme(newMode: string) {
mode = newMode
setTheme(newMode)
function switchScheme(newMode: LIGHT_DARK_MODE) {
mode = newMode
setTheme(newMode)
}
function toggleScheme() {