Skip to content

Commit

Permalink
♻️ refactor: refactor the user store with auth slice
Browse files Browse the repository at this point in the history
  • Loading branch information
arvinxx committed May 2, 2024
1 parent a5dad80 commit 869466f
Show file tree
Hide file tree
Showing 15 changed files with 71 additions and 23 deletions.
4 changes: 2 additions & 2 deletions src/app/(main)/chat/(mobile)/features/SessionHeader.tsx
Expand Up @@ -10,7 +10,7 @@ import SyncStatusInspector from '@/features/SyncStatusInspector';
import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
import { useSessionStore } from '@/store/session';
import { useUserStore } from '@/store/user';
import { commonSelectors } from '@/store/user/selectors';
import { userProfileSelectors } from '@/store/user/selectors';
import { mobileHeaderSticky } from '@/styles/mobileHeader';

export const useStyles = createStyles(({ css, token }) => ({
Expand All @@ -26,7 +26,7 @@ export const useStyles = createStyles(({ css, token }) => ({
const Header = memo(() => {
const [createSession] = useSessionStore((s) => [s.createSession]);
const router = useRouter();
const avatar = useUserStore(commonSelectors.userAvatar);
const avatar = useUserStore(userProfileSelectors.userAvatar);
const { showCreateSession } = useServerConfigStore(featureFlagsSelectors);

return (
Expand Down
4 changes: 2 additions & 2 deletions src/app/(main)/chat/features/ShareButton/ShareModal.tsx
Expand Up @@ -7,7 +7,7 @@ import { Flexbox } from 'react-layout-kit';
import { FORM_STYLE } from '@/const/layoutTokens';
import { useChatStore } from '@/store/chat';
import { useUserStore } from '@/store/user';
import { commonSelectors } from '@/store/user/selectors';
import { userProfileSelectors } from '@/store/user/selectors';

import Preview from './Preview';
import { FieldType, ImageType } from './type';
Expand Down Expand Up @@ -49,7 +49,7 @@ const ShareModal = memo<ModalProps>(({ onCancel, open }) => {
const [fieldValue, setFieldValue] = useState<FieldType>(DEFAULT_FIELD_VALUE);
const [tab, setTab] = useState<Tab>(Tab.Screenshot);
const { t } = useTranslation('chat');
const avatar = useUserStore(commonSelectors.userAvatar);
const avatar = useUserStore(userProfileSelectors.userAvatar);
const [shareLoading, shareToShareGPT] = useChatStore((s) => [s.shareLoading, s.shareToShareGPT]);
const { loading, onDownload, title } = useScreenshot(fieldValue.imageType);

Expand Down
4 changes: 2 additions & 2 deletions src/app/(main)/settings/(mobile)/index.tsx
Expand Up @@ -8,7 +8,7 @@ import { Center, Flexbox } from 'react-layout-kit';
import { CURRENT_VERSION } from '@/const/version';
import AvatarWithUpload from '@/features/AvatarWithUpload';
import { useUserStore } from '@/store/user';
import { commonSelectors } from '@/store/user/selectors';
import { userProfileSelectors } from '@/store/user/selectors';

import SettingList from '../features/SettingList';
import AvatarBanner from './features/AvatarBanner';
Expand All @@ -26,7 +26,7 @@ const useStyles = createStyles(({ css, token }) => ({
}));

const Setting = memo(() => {
const avatar = useUserStore(commonSelectors.userAvatar);
const avatar = useUserStore(userProfileSelectors.userAvatar);
const { styles } = useStyles();

return (
Expand Down
4 changes: 2 additions & 2 deletions src/features/AvatarWithUpload/index.tsx
Expand Up @@ -5,7 +5,7 @@ import { CSSProperties, memo, useCallback } from 'react';

import { DEFAULT_USER_AVATAR_URL } from '@/const/meta';
import { useUserStore } from '@/store/user';
import { commonSelectors } from '@/store/user/selectors';
import { userProfileSelectors } from '@/store/user/selectors';
import { imageToBase64 } from '@/utils/imageToBase64';
import { createUploadImageHandler } from '@/utils/uploadFIle';

Expand Down Expand Up @@ -39,7 +39,7 @@ const AvatarWithUpload = memo<AvatarWithUploadProps>(
({ size = 40, compressSize = 256, style, id }) => {
const { styles } = useStyle();
const [avatar, updateAvatar] = useUserStore((s) => [
commonSelectors.userAvatar(s),
userProfileSelectors.userAvatar(s),
s.updateAvatar,
]);

Expand Down
4 changes: 2 additions & 2 deletions src/services/chat.ts
Expand Up @@ -15,10 +15,10 @@ import { useToolStore } from '@/store/tool';
import { pluginSelectors, toolSelectors } from '@/store/tool/selectors';
import { useUserStore } from '@/store/user';
import {
commonSelectors,
modelConfigSelectors,
modelProviderSelectors,
preferenceSelectors,
userProfileSelectors,
} from '@/store/user/selectors';
import { ChatErrorType } from '@/types/fetch';
import { ChatMessage } from '@/types/message';
Expand Down Expand Up @@ -482,7 +482,7 @@ class ChatService {
...trace,
enabled: true,
tags: [tag, ...(trace?.tags || []), ...tags].filter(Boolean) as string[],
userId: commonSelectors.userId(useUserStore.getState()),
userId: userProfileSelectors.userId(useUserStore.getState()),
};
}

Expand Down
4 changes: 2 additions & 2 deletions src/store/chat/slices/message/selectors.ts
Expand Up @@ -8,7 +8,7 @@ import { agentSelectors } from '@/store/agent/selectors';
import { useSessionStore } from '@/store/session';
import { sessionMetaSelectors } from '@/store/session/selectors';
import { useUserStore } from '@/store/user';
import { commonSelectors } from '@/store/user/selectors';
import { userProfileSelectors } from '@/store/user/selectors';
import { ChatMessage } from '@/types/message';
import { MetaData } from '@/types/meta';
import { merge } from '@/utils/merge';
Expand All @@ -20,7 +20,7 @@ const getMeta = (message: ChatMessage) => {
switch (message.role) {
case 'user': {
return {
avatar: commonSelectors.userAvatar(useUserStore.getState()) || DEFAULT_USER_AVATAR,
avatar: userProfileSelectors.userAvatar(useUserStore.getState()) || DEFAULT_USER_AVATAR,
};
}

Expand Down
4 changes: 3 additions & 1 deletion src/store/user/initialState.ts
@@ -1,11 +1,13 @@
import { UserAuthState, initialAuthState } from './slices/auth/initialState';
import { UserCommonState, initialCommonState } from './slices/common/initialState';
import { UserPreferenceState, initialPreferenceState } from './slices/preference/initialState';
import { UserSettingsState, initialSettingsState } from './slices/settings/initialState';

export type UserState = UserCommonState & UserSettingsState & UserPreferenceState;
export type UserState = UserCommonState & UserSettingsState & UserPreferenceState & UserAuthState;

export const initialState: UserState = {
...initialCommonState,
...initialSettingsState,
...initialPreferenceState,
...initialAuthState,
};
2 changes: 1 addition & 1 deletion src/store/user/selectors.ts
@@ -1,4 +1,4 @@
export { commonSelectors } from './slices/common/selectors';
export { userProfileSelectors } from './slices/auth/selectors';
export { preferenceSelectors } from './slices/preference/selectors';
export {
modelConfigSelectors,
Expand Down
22 changes: 22 additions & 0 deletions src/store/user/slices/auth/action.ts
@@ -0,0 +1,22 @@
import { StateCreator } from 'zustand/vanilla';

import { setNamespace } from '@/utils/storeDebug';

import { UserStore } from '../../store';

const n = setNamespace('auth');

export interface UserAuthAction {
getUserConfig: () => void;
}

export const createAuthSlice: StateCreator<
UserStore,
[['zustand/devtools', never]],
[],
UserAuthAction
> = () => ({
getUserConfig: () => {
console.log(n('userconfig'));
},

Check warning on line 21 in src/store/user/slices/auth/action.ts

View check run for this annotation

Codecov / codecov/patch

src/store/user/slices/auth/action.ts#L20-L21

Added lines #L20 - L21 were not covered by tests
});
20 changes: 20 additions & 0 deletions src/store/user/slices/auth/initialState.ts
@@ -0,0 +1,20 @@
export interface LobeUser {
avatar?: string;
firstName?: string | null;
fullName?: string | null;
id: string;
latestName?: string | null;
username?: string | null;
}

export interface UserAuthState {
/**
* @deprecated
*/
avatar?: string;
isSignedIn?: boolean;
user?: LobeUser;
userId?: string;
}

export const initialAuthState: UserAuthState = {};
@@ -1,6 +1,6 @@
import { UserStore } from '@/store/user';

export const commonSelectors = {
export const userProfileSelectors = {
userAvatar: (s: UserStore) => s.avatar || '',
userId: (s: UserStore) => s.userId,
};
6 changes: 3 additions & 3 deletions src/store/user/slices/common/action.test.ts
Expand Up @@ -7,7 +7,7 @@ import { globalService } from '@/services/global';
import { messageService } from '@/services/message';
import { userService } from '@/services/user';
import { useUserStore } from '@/store/user';
import { commonSelectors } from '@/store/user/slices/common/selectors';
import { userProfileSelectors } from '@/store/user/slices/auth/selectors';
import { preferenceSelectors } from '@/store/user/slices/preference/selectors';
import { syncSettingsSelectors } from '@/store/user/slices/settings/selectors';
import { GlobalServerConfig } from '@/types/serverConfig';
Expand Down Expand Up @@ -159,7 +159,7 @@ describe('createCommonSlice', () => {
const { result } = renderHook(() => useUserStore());
const onEvent = vi.fn();

vi.spyOn(commonSelectors, 'userId').mockReturnValueOnce(undefined);
vi.spyOn(userProfileSelectors, 'userId').mockReturnValueOnce(undefined as any);
const triggerEnableSyncSpy = vi.spyOn(result.current, 'triggerEnableSync');

await act(async () => {
Expand All @@ -174,7 +174,7 @@ describe('createCommonSlice', () => {
const onEvent = vi.fn();
const userId = 'user-id';

vi.spyOn(commonSelectors, 'userId').mockReturnValueOnce(userId);
vi.spyOn(userProfileSelectors, 'userId').mockReturnValueOnce(userId);
const triggerEnableSyncSpy = vi.spyOn(result.current, 'triggerEnableSync');

await act(async () => {
Expand Down
4 changes: 2 additions & 2 deletions src/store/user/slices/common/action.ts
Expand Up @@ -14,9 +14,9 @@ import { merge } from '@/utils/merge';
import { browserInfo } from '@/utils/platform';
import { setNamespace } from '@/utils/storeDebug';

import { userProfileSelectors } from '../auth/selectors';
import { preferenceSelectors } from '../preference/selectors';
import { settingsSelectors, syncSettingsSelectors } from '../settings/selectors';
import { commonSelectors } from './selectors';

const n = setNamespace('common');

Expand Down Expand Up @@ -47,7 +47,7 @@ export const createCommonSlice: StateCreator<
CommonAction
> = (set, get) => ({
refreshConnection: async (onEvent) => {
const userId = commonSelectors.userId(get());
const userId = userProfileSelectors.userId(get());

if (!userId) return;

Expand Down
2 changes: 0 additions & 2 deletions src/store/user/slices/settings/initialState.ts
Expand Up @@ -7,14 +7,12 @@ import { GlobalServerConfig } from '@/types/serverConfig';
import { GlobalSettings } from '@/types/settings';

export interface UserSettingsState {
avatar?: string;
defaultModelProviderList: ModelProviderCard[];
defaultSettings: GlobalSettings;
editingCustomCardModel?: { id: string; provider: string } | undefined;
modelProviderList: ModelProviderCard[];
serverConfig: GlobalServerConfig;
settings: DeepPartial<GlobalSettings>;
userId?: string;
}

export const initialSettingsState: UserSettingsState = {
Expand Down
8 changes: 7 additions & 1 deletion src/store/user/store.ts
Expand Up @@ -6,19 +6,25 @@ import { StateCreator } from 'zustand/vanilla';
import { isDev } from '@/utils/env';

import { type UserState, initialState } from './initialState';
import { type UserAuthAction, createAuthSlice } from './slices/auth/action';
import { type CommonAction, createCommonSlice } from './slices/common/action';
import { type PreferenceAction, createPreferenceSlice } from './slices/preference/action';
import { type SettingsAction, createSettingsSlice } from './slices/settings/actions';

// =============== 聚合 createStoreFn ============ //

export type UserStore = CommonAction & UserState & SettingsAction & PreferenceAction;
export type UserStore = CommonAction &
UserState &
SettingsAction &
PreferenceAction &
UserAuthAction;

const createStore: StateCreator<UserStore, [['zustand/devtools', never]]> = (...parameters) => ({
...initialState,
...createCommonSlice(...parameters),
...createSettingsSlice(...parameters),
...createPreferenceSlice(...parameters),
...createAuthSlice(...parameters),
});

// =============== 实装 useStore ============ //
Expand Down

0 comments on commit 869466f

Please sign in to comment.