mirror of
https://github.com/hazemKrimi/personal-website.git
synced 2026-05-01 18:00:26 +00:00
Fix color theme
This commit is contained in:
+14
-2
@@ -9,6 +9,10 @@ const reducer = (state: boolean, action: { type: string }) => {
|
|||||||
switch (action.type) {
|
switch (action.type) {
|
||||||
case 'TOGGLE':
|
case 'TOGGLE':
|
||||||
return !state;
|
return !state;
|
||||||
|
case 'DARK':
|
||||||
|
return true;
|
||||||
|
case 'LIGHT':
|
||||||
|
return false;
|
||||||
default:
|
default:
|
||||||
return state;
|
return state;
|
||||||
}
|
}
|
||||||
@@ -16,10 +20,18 @@ const reducer = (state: boolean, action: { type: string }) => {
|
|||||||
|
|
||||||
const DarkMode: FC = ({ children }) => {
|
const DarkMode: FC = ({ children }) => {
|
||||||
const [dark, dispatch] = useReducer(reducer, false);
|
const [dark, dispatch] = useReducer(reducer, false);
|
||||||
const toggle = () => dispatch({ type: 'TOGGLE' });
|
const toggle = () => {
|
||||||
|
if (dark) window.localStorage.setItem('theme', 'light');
|
||||||
|
else window.localStorage.setItem('theme', 'dark');
|
||||||
|
|
||||||
|
dispatch({ type: 'TOGGLE' });
|
||||||
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) toggle();
|
const root = window.document.documentElement;
|
||||||
|
const initialTheme = root.style.getPropertyValue('--theme');
|
||||||
|
|
||||||
|
dispatch({ type: initialTheme === 'dark' ? 'DARK' : 'LIGHT' });
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
return <DarkModeContext.Provider value={{ dark, toggle }}>{children}</DarkModeContext.Provider>;
|
return <DarkModeContext.Provider value={{ dark, toggle }}>{children}</DarkModeContext.Provider>;
|
||||||
|
|||||||
@@ -43,6 +43,36 @@ class Doc extends Document {
|
|||||||
`
|
`
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
<script
|
||||||
|
dangerouslySetInnerHTML={{
|
||||||
|
__html: `
|
||||||
|
function getInitialColorMode() {
|
||||||
|
const persistedColorPreference = window.localStorage.getItem('theme');
|
||||||
|
const hasPersistedPreference = typeof persistedColorPreference === 'string';
|
||||||
|
|
||||||
|
if (hasPersistedPreference) {
|
||||||
|
return persistedColorPreference;
|
||||||
|
}
|
||||||
|
|
||||||
|
const mql = window.matchMedia('(prefers-color-scheme: dark)');
|
||||||
|
const hasMediaQueryPreference = typeof mql.matches === 'boolean';
|
||||||
|
|
||||||
|
if (hasMediaQueryPreference) {
|
||||||
|
return mql.matches ? 'dark' : 'light';
|
||||||
|
}
|
||||||
|
|
||||||
|
return 'light';
|
||||||
|
}
|
||||||
|
|
||||||
|
(() => {
|
||||||
|
const colorMode = getInitialColorMode();
|
||||||
|
const root = document.documentElement;
|
||||||
|
|
||||||
|
root.style.setProperty('--theme', colorMode);
|
||||||
|
})();
|
||||||
|
`
|
||||||
|
}}
|
||||||
|
/>
|
||||||
</Head>
|
</Head>
|
||||||
<body>
|
<body>
|
||||||
<Main />
|
<Main />
|
||||||
|
|||||||
Reference in New Issue
Block a user