blob: 227b35c628b66186f8e1b9eb61ce00233911d486 [file] [log] [blame]
idillon3470d072022-11-22 15:22:34 -05001/*
2 * Copyright (C) 2022 Savoir-faire Linux Inc.
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU Affero General Public License as
6 * published by the Free Software Foundation; either version 3 of the
7 * License, or (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU Affero General Public License for more details.
13 *
14 * You should have received a copy of the GNU Affero General Public
15 * License along with this program. If not, see
16 * <https://www.gnu.org/licenses/>.
17 */
18import { PaletteMode } from '@mui/material';
19import { ThemeProvider } from '@mui/material/styles';
20import { createContext, useCallback, useEffect, useMemo, useState } from 'react';
21
22import { buildDefaultTheme } from '../themes/Default';
23import { WithChildren } from '../utils/utils';
24
25interface ICustomThemeContext {
26 mode: PaletteMode;
27 toggleMode: () => void;
28}
29
30export const CustomThemeContext = createContext<ICustomThemeContext>(undefined!);
31
32export default ({ children }: WithChildren) => {
33 const [mode, setMode] = useState<PaletteMode>('light');
34
35 useEffect(() => {
Ziwei Wangcd687a42023-01-04 16:40:53 -050036 const themeModeInStorage = localStorage.getItem('themeMode');
37 let themeModeValue = 'light';
38 // localStorage returns null if no value is found for the given key
39 if (typeof themeModeInStorage === 'string') {
40 themeModeValue = JSON.parse(themeModeInStorage);
41 }
42 //can't set it directly with the value because of the type check
43 setMode(themeModeValue === 'dark' ? 'dark' : 'light');
idillon3470d072022-11-22 15:22:34 -050044 }, []);
45
Ziwei Wangcd687a42023-01-04 16:40:53 -050046 const toggleMode = useCallback(() => {
47 setMode((mode) => {
48 const newMode = mode === 'light' ? 'dark' : 'light';
49 localStorage.setItem('themeMode', JSON.stringify(newMode));
50 return newMode;
51 });
52 }, [setMode]);
idillon3470d072022-11-22 15:22:34 -050053
54 const theme = useMemo(() => buildDefaultTheme(mode), [mode]);
55
simon5c677962022-12-02 16:51:54 -050056 const value = useMemo(
57 () => ({
58 mode,
59 toggleMode,
60 }),
61 [mode, toggleMode]
62 );
63
idillon3470d072022-11-22 15:22:34 -050064 return (
simon5c677962022-12-02 16:51:54 -050065 <CustomThemeContext.Provider value={value}>
idillon3470d072022-11-22 15:22:34 -050066 <ThemeProvider theme={theme}>{children}</ThemeProvider>
67 </CustomThemeContext.Provider>
68 );
69};