mirror of
https://github.com/linux-do/new-api.git
synced 2025-11-13 17:43:40 +08:00
refactor: dark mode
This commit is contained in:
36
web/src/context/Theme/index.js
Normal file
36
web/src/context/Theme/index.js
Normal file
@@ -0,0 +1,36 @@
|
||||
import { createContext, useCallback, useContext, useState } from 'react';
|
||||
|
||||
const ThemeContext = createContext(null);
|
||||
export const useTheme = () => useContext(ThemeContext);
|
||||
|
||||
const SetThemeContext = createContext(null);
|
||||
export const useSetTheme = () => useContext(SetThemeContext);
|
||||
|
||||
export const ThemeProvider = ({ children }) => {
|
||||
const [theme, _setTheme] = useState(() => {
|
||||
try {
|
||||
return localStorage.getItem('theme-mode') || null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
|
||||
const setTheme = useCallback((input) => {
|
||||
_setTheme(input ? 'dark' : 'light');
|
||||
|
||||
const body = document.body;
|
||||
if (!input) {
|
||||
body.removeAttribute('theme-mode');
|
||||
localStorage.setItem('theme-mode', 'light');
|
||||
} else {
|
||||
body.setAttribute('theme-mode', 'dark');
|
||||
localStorage.setItem('theme-mode', 'dark');
|
||||
}
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<SetThemeContext.Provider value={setTheme}>
|
||||
<ThemeContext.Provider value={theme}>{children}</ThemeContext.Provider>
|
||||
</SetThemeContext.Provider>
|
||||
);
|
||||
};
|
||||
Reference in New Issue
Block a user