2022-10-19 16:17:57 +08:00
|
|
|
import { builtInLanguages as builtInConsoleLanguages } from '@logto/phrases';
|
2023-02-23 16:49:45 +08:00
|
|
|
import { useEffect, useMemo } from 'react';
|
2022-06-07 16:05:24 +08:00
|
|
|
import { z } from 'zod';
|
|
|
|
|
2023-03-16 13:34:23 +08:00
|
|
|
import { appearanceModeStorageKey } from '@/consts';
|
2023-03-17 14:31:29 +08:00
|
|
|
import { getAppearanceModeFromLocalStorage } from '@/contexts/AppThemeProvider';
|
2023-03-16 13:34:23 +08:00
|
|
|
import { appearanceModeGuard } from '@/types/appearance-mode';
|
2022-06-07 16:05:24 +08:00
|
|
|
|
2023-02-23 16:49:45 +08:00
|
|
|
import useMeCustomData from './use-me-custom-data';
|
|
|
|
|
|
|
|
const adminConsolePreferencesKey = 'adminConsolePreferences';
|
2022-06-07 16:05:24 +08:00
|
|
|
|
|
|
|
const userPreferencesGuard = z.object({
|
2022-10-19 16:17:57 +08:00
|
|
|
language: z.enum(builtInConsoleLanguages).optional(),
|
2023-03-16 13:34:23 +08:00
|
|
|
appearanceMode: appearanceModeGuard,
|
2022-06-07 16:05:24 +08:00
|
|
|
experienceNoticeConfirmed: z.boolean().optional(),
|
2022-07-02 09:43:03 +08:00
|
|
|
getStartedHidden: z.boolean().optional(),
|
2022-11-03 10:52:34 +08:00
|
|
|
connectorSieNoticeConfirmed: z.boolean().optional(),
|
2022-06-07 16:05:24 +08:00
|
|
|
});
|
|
|
|
|
|
|
|
export type UserPreferences = z.infer<typeof userPreferencesGuard>;
|
|
|
|
|
|
|
|
const useUserPreferences = () => {
|
2023-02-23 16:49:45 +08:00
|
|
|
const { data, error, isLoading, isLoaded, update: updateMeCustomData } = useMeCustomData();
|
|
|
|
|
|
|
|
const userPreferences = useMemo(() => {
|
|
|
|
const parsed = z.object({ [adminConsolePreferencesKey]: userPreferencesGuard }).safeParse(data);
|
|
|
|
|
|
|
|
return parsed.success
|
|
|
|
? parsed.data[adminConsolePreferencesKey]
|
|
|
|
: {
|
2023-03-16 13:34:23 +08:00
|
|
|
appearanceMode: getAppearanceModeFromLocalStorage(),
|
2023-02-23 16:49:45 +08:00
|
|
|
};
|
2022-06-07 16:05:24 +08:00
|
|
|
}, [data]);
|
|
|
|
|
|
|
|
const update = async (data: Partial<UserPreferences>) => {
|
2023-02-23 16:49:45 +08:00
|
|
|
await updateMeCustomData({
|
|
|
|
[adminConsolePreferencesKey]: {
|
|
|
|
...userPreferences,
|
|
|
|
...data,
|
|
|
|
},
|
|
|
|
});
|
2022-06-07 16:05:24 +08:00
|
|
|
};
|
|
|
|
|
|
|
|
useEffect(() => {
|
2023-03-16 13:34:23 +08:00
|
|
|
localStorage.setItem(appearanceModeStorageKey, userPreferences.appearanceMode);
|
2022-06-07 16:05:24 +08:00
|
|
|
}, [userPreferences.appearanceMode]);
|
|
|
|
|
|
|
|
return {
|
2023-02-23 16:49:45 +08:00
|
|
|
isLoading,
|
|
|
|
isLoaded,
|
2022-06-07 16:05:24 +08:00
|
|
|
data: userPreferences,
|
|
|
|
update,
|
|
|
|
error,
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
export default useUserPreferences;
|