65 lines
1.5 KiB
TypeScript
65 lines
1.5 KiB
TypeScript
import type { ColorSchemeName } from 'react-native'
|
|
import AsyncStorage from '@react-native-async-storage/async-storage'
|
|
import { Appearance } from 'react-native'
|
|
import { create } from 'zustand'
|
|
import { createJSONStorage, persist } from 'zustand/middleware'
|
|
|
|
export type ThemeScheme = 'light' | 'dark' | 'auto'
|
|
|
|
interface AppState {
|
|
themeScheme: ThemeScheme
|
|
isDark: boolean
|
|
|
|
setThemeScheme: (theme: ThemeScheme) => void
|
|
syncWithSystem: () => void
|
|
}
|
|
|
|
function getIsDark(theme: ThemeScheme, system: ColorSchemeName) {
|
|
if (theme === 'auto') {
|
|
return system === 'dark'
|
|
}
|
|
return theme === 'dark'
|
|
}
|
|
|
|
export const useAppStore = create<AppState>()(
|
|
persist(
|
|
(set, get) => {
|
|
const system = Appearance.getColorScheme()
|
|
|
|
return {
|
|
themeScheme: 'auto',
|
|
|
|
isDark: getIsDark('auto', system),
|
|
|
|
setThemeScheme: (theme) => {
|
|
const system = Appearance.getColorScheme()
|
|
|
|
set({
|
|
themeScheme: theme,
|
|
isDark: getIsDark(theme, system),
|
|
})
|
|
},
|
|
|
|
syncWithSystem: () => {
|
|
const { themeScheme } = get()
|
|
const system = Appearance.getColorScheme()
|
|
|
|
if (themeScheme === 'auto') {
|
|
set({
|
|
isDark: getIsDark(themeScheme, system),
|
|
})
|
|
}
|
|
},
|
|
}
|
|
},
|
|
{
|
|
name: 'app-storage',
|
|
partialize: state => ({
|
|
themeScheme: state.themeScheme,
|
|
}),
|
|
|
|
storage: createJSONStorage(() => AsyncStorage),
|
|
},
|
|
),
|
|
)
|