2023-07-07 13:58:15 +00:00
|
|
|
import { useAppDispatch, useAppSelector } from '$app/stores/store';
|
2023-08-04 11:27:14 +00:00
|
|
|
import { useCallback, useEffect, useMemo } from 'react';
|
2023-07-07 13:58:15 +00:00
|
|
|
import { UserSettingController } from '$app/stores/effects/user/user_setting_controller';
|
|
|
|
import { currentUserActions } from '$app_reducers/current-user/slice';
|
2023-08-04 11:27:14 +00:00
|
|
|
import { Theme as ThemeType, ThemeMode } from '$app/interfaces';
|
2023-07-07 13:58:15 +00:00
|
|
|
import { createTheme } from '@mui/material/styles';
|
|
|
|
import { getDesignTokens } from '$app/utils/mui';
|
2023-07-31 03:39:44 +00:00
|
|
|
import { useTranslation } from 'react-i18next';
|
2023-07-07 13:58:15 +00:00
|
|
|
|
|
|
|
export function useUserSetting() {
|
|
|
|
const dispatch = useAppDispatch();
|
2023-07-31 03:39:44 +00:00
|
|
|
const { i18n } = useTranslation();
|
2023-07-07 13:58:15 +00:00
|
|
|
const currentUser = useAppSelector((state) => state.currentUser);
|
|
|
|
const userSettingController = useMemo(() => {
|
|
|
|
if (!currentUser?.id) return;
|
|
|
|
const controller = new UserSettingController(currentUser.id);
|
|
|
|
|
|
|
|
return controller;
|
|
|
|
}, [currentUser?.id]);
|
|
|
|
|
2023-08-04 11:27:14 +00:00
|
|
|
const loadUserSetting = useCallback(async () => {
|
|
|
|
if (!userSettingController) return;
|
|
|
|
const settings = await userSettingController.getAppearanceSetting();
|
|
|
|
|
|
|
|
if (!settings) return;
|
|
|
|
dispatch(currentUserActions.setUserSetting(settings));
|
|
|
|
await i18n.changeLanguage(settings.language);
|
|
|
|
}, [dispatch, i18n, userSettingController]);
|
|
|
|
|
2023-07-07 13:58:15 +00:00
|
|
|
useEffect(() => {
|
2023-08-04 11:27:14 +00:00
|
|
|
void loadUserSetting();
|
|
|
|
}, [loadUserSetting]);
|
2023-07-07 13:58:15 +00:00
|
|
|
|
|
|
|
const { themeMode = ThemeMode.Light, theme: themeType = ThemeType.Default } = useAppSelector((state) => {
|
|
|
|
return state.currentUser.userSetting || {};
|
|
|
|
});
|
|
|
|
|
|
|
|
const muiTheme = useMemo(() => createTheme(getDesignTokens(themeMode)), [themeMode]);
|
|
|
|
|
|
|
|
return {
|
|
|
|
muiTheme,
|
|
|
|
themeMode,
|
|
|
|
themeType,
|
|
|
|
userSettingController,
|
|
|
|
};
|
|
|
|
}
|