mirror of https://git.lenooby09.tech/LeNooby09/social-app.git
1import React from 'react'
2import {ColorSchemeName, useColorScheme} from 'react-native'
3import * as SystemUI from 'expo-system-ui'
4
5import {isWeb} from 'platform/detection'
6import {useThemePrefs} from 'state/shell'
7import {dark, dim, light} from '#/alf/themes'
8import {ThemeName} from '#/alf/types'
9
10export function useColorModeTheme(): ThemeName {
11 const theme = useThemeName()
12
13 React.useLayoutEffect(() => {
14 updateDocument(theme)
15 SystemUI.setBackgroundColorAsync(getBackgroundColor(theme))
16 }, [theme])
17
18 return theme
19}
20
21export function useThemeName(): ThemeName {
22 const colorScheme = useColorScheme()
23 const {colorMode, darkTheme} = useThemePrefs()
24
25 return getThemeName(colorScheme, colorMode, darkTheme)
26}
27
28function getThemeName(
29 colorScheme: ColorSchemeName,
30 colorMode: 'system' | 'light' | 'dark',
31 darkTheme?: ThemeName,
32) {
33 if (
34 (colorMode === 'system' && colorScheme === 'light') ||
35 colorMode === 'light'
36 ) {
37 return 'light'
38 } else {
39 return darkTheme ?? 'dim'
40 }
41}
42
43function updateDocument(theme: ThemeName) {
44 // @ts-ignore web only
45 if (isWeb && typeof window !== 'undefined') {
46 // @ts-ignore web only
47 const html = window.document.documentElement
48 // @ts-ignore web only
49 const meta = window.document.querySelector('meta[name="theme-color"]')
50
51 // remove any other color mode classes
52 html.className = html.className.replace(/(theme)--\w+/g, '')
53 html.classList.add(`theme--${theme}`)
54 // set color to 'theme-color' meta tag
55 meta?.setAttribute('content', getBackgroundColor(theme))
56 }
57}
58
59export function getBackgroundColor(theme: ThemeName): string {
60 switch (theme) {
61 case 'light':
62 return light.atoms.bg.backgroundColor
63 case 'dark':
64 return dark.atoms.bg.backgroundColor
65 case 'dim':
66 return dim.atoms.bg.backgroundColor
67 }
68}