Skip to content

Commit

Permalink
add shared modules and event bus
Browse files Browse the repository at this point in the history
  • Loading branch information
u4aew committed Dec 28, 2023
1 parent 688f996 commit 9cd71df
Show file tree
Hide file tree
Showing 13 changed files with 62 additions and 51 deletions.
10 changes: 3 additions & 7 deletions packages/cards/src/pages/CardDetail/CardDetail.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@ import { useDispatch, useSelector } from 'react-redux';
import { getCardDetails } from '@modules/cards/store/features/cards/slice';
import { AppDispatch } from '@modules/cards/store/store';
import { userCardsDetailsSelector } from '@modules/cards/store/features/cards/selectors';
import { USER_ROLE, onChangeUserRole } from 'shared';

export const CardDetail = () => {
const dispatch: AppDispatch = useDispatch();
const cardDetails = useSelector(userCardsDetailsSelector);
//@ts-ignore
const [role, setRole] = useState(window.host.common.user.role);
const [role, setRole] = useState(USER_ROLE);

useEffect(() => {
const load = async () => {
Expand All @@ -25,7 +25,6 @@ export const CardDetail = () => {
};

const handleEdit = () => {
console.log('Submit edit');
setIsModalVisible(false);
};

Expand All @@ -40,10 +39,7 @@ export const CardDetail = () => {
};

useEffect(() => {
window.addEventListener('hostEvent:ChangeRole', (event) => {
//@ts-ignore
setRole(event.detail.role);
});
onChangeUserRole(setRole);
}, []);

if (!cardDetails) {
Expand Down
10 changes: 2 additions & 8 deletions packages/host/src/layouts/MainLayout/MainLayout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,26 +7,20 @@ import { useDispatch, useSelector } from 'react-redux';
import { userSelector } from '@host/store/features/common/selectors';
import { setRole } from '@host/store/features/common/slice';
import { AppDispatch } from '@host/store/store';
import { useCommunication } from 'shared';
import { emitChangeUserRole } from 'shared';

const { Option } = Select;

export const MainLayout = ({ children }) => {
const dispatch: AppDispatch = useDispatch();
const [collapsed, setCollapsed] = useState(false);
const user = useSelector(userSelector);
console.log(useCommunication(), 'useWebAuthn()');
const {
token: { colorBgContainer },
} = theme.useToken();

const handleRoleChange = (newRole) => {
//@ts-ignore
const event = new CustomEvent('hostEvent:ChangeRole', {
detail: { role: newRole },
});
window.dispatchEvent(event);
//@ts-ignore
emitChangeUserRole(newRole);
dispatch(setRole(newRole));
};

Expand Down
19 changes: 6 additions & 13 deletions packages/host/src/store/features/common/slice.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import { createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit';
import config from '@host/config';
import { Fetch } from '@host/types';
import { TypeUser } from 'shared';
import { EnumRole, TypeUser } from 'shared';
import axios from 'axios';

export interface ResponseError {
Expand Down Expand Up @@ -32,7 +32,6 @@ export const getUserInfo = createAsyncThunk(
const { data } = await axios.get(config.routes.user);
return data;
} catch (error) {
// Используйте rejectWithValue для отправки ошибки, если это необходимо
return rejectWithValue(error.response.data);
}
},
Expand All @@ -43,30 +42,24 @@ const slice = createSlice({
initialState,
reducers: {
reset: (): SliceState => initialState,
setRole: (state, action) => {
console.log(action.payload, 'action');
// Проверка на существование state.common и state.common.user
// Непосредственное изменение роли пользователя
// @ts-ignore
state.user.role = action.payload;
setRole: (state, action: PayloadAction<EnumRole>) => {
if (state.user) {
state.user.role = action.payload;
}
},
},
extraReducers: (builder) => {
/** getUserInfo */

builder.addCase(getUserInfo.pending, (state) => {
state.fetchingState = Fetch.Pending;
console.log(state.fetchingState, 'state.fetchingState');
state.error = null;
});
builder.addCase(getUserInfo.fulfilled, (state, action) => {
console.log(action.payload, 'action.payload');
state.user = action.payload;
state.fetchingState = Fetch.Fulfilled;
});
builder.addCase(getUserInfo.rejected, (state, action) => {
state.fetchingState = Fetch.Rejected;
// @ts-ignore
state.error = action.error;
});
},
Expand Down
27 changes: 11 additions & 16 deletions packages/host/src/store/store.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,17 @@
import { configureStore, Middleware } from '@reduxjs/toolkit';
import rootReducer from './features';
import rootReducer, { RootState } from './features';
const windowStateMiddleware: Middleware<{}, RootState> =
(store) => (next) => (action) => {
const result = next(action);
(window as any).host = store.getState();
return result;
};

const windowStateMiddleware: Middleware = (store) => (next) => (action) => {
const result = next(action);
// @ts-ignore
window.host = store.getState();
// @ts-ignore
console.log(window.host, 'global state');
return result;
};

const loadFromWindow = () => {
const loadFromWindow = (): RootState | undefined => {
try {
// @ts-ignore
if (window.host === null) return undefined;
// @ts-ignore
return window.host;
const hostState = (window as any).host;
if (hostState === null) return undefined;
return hostState;
} catch (e) {
console.warn('Error loading state from window:', e);
return undefined;
Expand All @@ -33,4 +29,3 @@ const store = configureStore({
export default store;

export type AppDispatch = typeof store.dispatch;
export type RootState = ReturnType<typeof store.getState>;
1 change: 1 addition & 0 deletions packages/host/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"extends": "../../tsconfig.json",
"compilerOptions": {
"baseUrl": "src",
"noImplicitAny": false,
"paths": {
"@host/*": ["*"],
"shared/*": ["../../shared/*"]
Expand Down
3 changes: 3 additions & 0 deletions packages/shared/src/events/const/channels.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export enum Channels {
changeUserRole = 'change:userRole',
}
1 change: 1 addition & 0 deletions packages/shared/src/events/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './userRole';
18 changes: 18 additions & 0 deletions packages/shared/src/events/userRole.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Channels } from '@/events/const/channels';
import { EnumRole } from '@/types';

export const onChangeUserRole = (cb: (role: EnumRole) => void): void => {
window.addEventListener(Channels.changeUserRole, (event: Event) => {
const customEvent = event as CustomEvent<{ role: EnumRole }>;
if (customEvent.detail) {
cb(customEvent.detail.role);
}
});
};

export const emitChangeUserRole = (newRole: EnumRole): void => {
const event = new CustomEvent(Channels.changeUserRole, {
detail: { role: newRole },
});
window.dispatchEvent(event);
};
1 change: 0 additions & 1 deletion packages/shared/src/hooks/index.ts

This file was deleted.

5 changes: 0 additions & 5 deletions packages/shared/src/hooks/useCommunication.ts

This file was deleted.

3 changes: 2 additions & 1 deletion packages/shared/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from '@/hooks';
export * from '@/events';
export * from '@/types';
export * from '@/utils';
export * from '@/variables';
12 changes: 12 additions & 0 deletions packages/shared/src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,15 @@ export type TypeUser = {
name: string;
email: string;
};

declare global {
interface Window {
host: {
common: {
user: {
role: EnumRole;
};
};
};
}
}
3 changes: 3 additions & 0 deletions packages/shared/src/variables/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export const USER_ROLE = () => {
return window.host.common.user.role;
};

0 comments on commit 9cd71df

Please sign in to comment.