Skip to content

Commit

Permalink
fixup! feat: [ts-starter #6] implement theming infrastructure
Browse files Browse the repository at this point in the history
  • Loading branch information
ehsanmmd committed Mar 18, 2024
1 parent 1de31d6 commit 6440f23
Showing 1 changed file with 21 additions and 16 deletions.
37 changes: 21 additions & 16 deletions src/components/ThemeProvider/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,39 +42,44 @@ const getStoredTheme = (): Theme => {
export default function ThemeProvider({
children,
}: PropsWithChildren<EmptyObject>): ReactElement {
const [currentTheme, setCurrentTheme] = useState<DefaultTheme>(lightTheme);
const [currentThemeName, setCurrentThemeName] =
useState<Theme>(getStoredTheme());
const [currentTheme, setCurrentTheme] = useState(() =>
selectInitialTheme(currentThemeName),
);

const selectTheme = useCallback((theme: Theme) => {
const selectInitialTheme = useCallback((theme: Theme) => {
if (theme === "system") {
detectSystemTheme();
return detectSystemTheme();
} else if (theme === "dark") {
setCurrentTheme(darkTheme);
return darkTheme;
} else {
setCurrentTheme(lightTheme);
return lightTheme;
}
localStorage.setItem("theme", theme);
setCurrentThemeName(theme);
}, []);

const detectSystemTheme = () => {
const selectTheme = useCallback(
(theme: Theme) => {
setCurrentThemeName(theme);
localStorage.setItem("theme", theme);
setCurrentTheme(selectInitialTheme(theme));
},
[selectInitialTheme],
);

function detectSystemTheme(): DefaultTheme {
if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
setCurrentTheme(darkTheme);
return darkTheme;
} else {
setCurrentTheme(lightTheme);
return lightTheme;
}
};

useEffect(() => {
selectTheme(getStoredTheme());
}, [selectTheme]);
}

useEffect(() => {
const mediaQueryList = window.matchMedia("(prefers-color-scheme: dark)");
const handleChange = () => {
if (currentThemeName === "system") {
detectSystemTheme();
setCurrentTheme(detectSystemTheme());
}
};
mediaQueryList.addEventListener("change", handleChange);
Expand Down

0 comments on commit 6440f23

Please sign in to comment.