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 aa5dbd6 commit 688f996
Show file tree
Hide file tree
Showing 28 changed files with 778 additions and 76 deletions.
3 changes: 3 additions & 0 deletions .github/workflows/cards.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ jobs:
- name: Install Dependencies
run: yarn install

- name: Build Shared
run: yarn workspace shared build

- name: Build Cards
run: yarn workspace cards build

Expand Down
3 changes: 3 additions & 0 deletions .github/workflows/host.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ jobs:
- name: Install Dependencies
run: yarn install

- name: Build Shared
run: yarn workspace shared build

- name: Build Host
run: yarn workspace host build

Expand Down
3 changes: 3 additions & 0 deletions .github/workflows/transactions.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ jobs:
- name: Install Dependencies
run: yarn install

- name: Build Shared
run: yarn workspace shared build

- name: Build Transactions
run: yarn workspace transactions build

Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
"format": "prettier --write 'packages/**/*.js'",
"build:cards": "yarn workspace cards build",
"build:host": "yarn workspace host build",
"build:transactions": "yarn workspace transactions build"
"build:transactions": "yarn workspace transactions build",
"build:shared": "yarn workspace shared build"
},
"author": "Sergey Uchaev <dialoggg1994@gmail.com>",
"license": "ISC",
Expand Down
29 changes: 24 additions & 5 deletions packages/cards/src/pages/CardDetail/CardDetail.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ import { userCardsDetailsSelector } from '@modules/cards/store/features/cards/se
export const CardDetail = () => {
const dispatch: AppDispatch = useDispatch();
const cardDetails = useSelector(userCardsDetailsSelector);
//@ts-ignore
const [role, setRole] = useState(window.host.common.user.role);

useEffect(() => {
const load = async () => {
await dispatch(getCardDetails('1'));
Expand Down Expand Up @@ -36,21 +39,37 @@ export const CardDetail = () => {
});
};

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

if (!cardDetails) {
return <div>loading...</div>;
}

return (
<>
<Card
actions={[
const getActions = () => {
switch (role) {
case 'ADMIN':
return [
<Button key="edit" type="primary" onClick={showEditModal}>
Edit
</Button>,
<Button key="delete" type="dashed" onClick={handleDelete}>
Delete
</Button>,
]}
];
default:
return [];
}
};

return (
<>
<Card
actions={getActions()}
title={`Card Details - ${cardDetails.cardHolderName}`}
>
<p>PAN: {cardDetails.pan}</p>
Expand Down
3 changes: 2 additions & 1 deletion packages/host/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@
"react-redux": "8.1.3",
"react-router-dom": "6.20.1",
"styled-components": "6.1.1",
"svg-url-loader": "8.0.0"
"svg-url-loader": "8.0.0",
"shared": "1.0.0"
},
"license": "MIT"
}
2 changes: 1 addition & 1 deletion packages/host/src/bootstrap.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import store from './store/configureStore';
import store from './store/store';
import App from './root/App';

// @ts-ignore
Expand Down
24 changes: 17 additions & 7 deletions packages/host/src/layouts/MainLayout/MainLayout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,31 @@ import { Layout, Button, Row, Col, Select, theme } from 'antd';
import Nav from '@host/components/Nav/Nav';
const { Header, Sider, Content } = Layout;
import { MenuFoldOutlined, MenuUnfoldOutlined } from '@ant-design/icons';
import { useSelector } from 'react-redux';
import { userSelector } from '@host/store/features/account/selectors';
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';

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) => {
console.log('Selected Role:', newRole);
// Handle role change here (e.g., update state or make API call)
//@ts-ignore
const event = new CustomEvent('hostEvent:ChangeRole', {
detail: { role: newRole },
});
window.dispatchEvent(event);
//@ts-ignore
dispatch(setRole(newRole));
};

return (
Expand Down Expand Up @@ -49,9 +59,9 @@ export const MainLayout = ({ children }) => {
style={{ width: 120, marginLeft: 10 }}
onChange={handleRoleChange}
>
<Option value="manager">Manager</Option>
<Option value="admin">Admin</Option>
<Option value="user">User</Option>
<Option value="MANAGER">Manager</Option>
<Option value="ADMIN">Admin</Option>
<Option value="USER">User</Option>
</Select>
</span>
</Col>
Expand Down
6 changes: 3 additions & 3 deletions packages/host/src/root/Pages.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import { Main } from '../pages/Main';
import { MainLayout } from '@host/layouts/MainLayout';
import { useDispatch, useSelector } from 'react-redux';
import { getUserInfo } from '@host/store/features/account/slice';
import { AppDispatch } from '@host/store/configureStore';
import { isLoadingUserSelector } from '@host/store/features/account/selectors';
import { getUserInfo } from '@host/store/features/common/slice';
import { AppDispatch } from '@host/store/store';
import { isLoadingUserSelector } from '@host/store/features/common/selectors';
import { Spin } from 'antd';

const Cards = React.lazy(() => import('remote-modules-cards/Cards'));
Expand Down
34 changes: 0 additions & 34 deletions packages/host/src/store/configureStore.ts

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@ import { Fetch } from '@host/types';
* Информация о пользователе
* @param state
*/
export const userSelector = (state) => state.account.user;
export const userSelector = (state) => state.common.user;

/**
* Есть ли активный запрос к за инфоль к пользователю
* @param state
*/
export const isLoadingUserSelector = (state): boolean => {
return state.account.fetchingState === Fetch.Pending;
return state.common.fetchingState === Fetch.Pending;
};
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import config from '../../../config';
import config from '@host/config';
import { Fetch } from '@host/types';
import { TypeUser } from 'shared';
import axios from 'axios';

export interface ResponseError {
Expand All @@ -10,7 +11,7 @@ export interface ResponseError {
}

export interface SliceState {
user: object | null;
user: TypeUser | null;
fetchingState: Fetch;
error: ResponseError | null;
}
Expand Down Expand Up @@ -42,6 +43,13 @@ 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;
},
},
extraReducers: (builder) => {
/** getUserInfo */
Expand All @@ -64,6 +72,6 @@ const slice = createSlice({
},
});

export const { reset } = slice.actions;
export const { reset, setRole } = slice.actions;

export default slice.reducer;
4 changes: 2 additions & 2 deletions packages/host/src/store/features/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { combineReducers } from '@reduxjs/toolkit';
import account from './account/slice';
import common from './common/slice';

const rootReducer = combineReducers({
account,
common,
});

export default rootReducer;
Expand Down
36 changes: 36 additions & 0 deletions packages/host/src/store/store.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { configureStore, Middleware } from '@reduxjs/toolkit';
import rootReducer from './features';

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 = () => {
try {
// @ts-ignore
if (window.host === null) return undefined;
// @ts-ignore
return window.host;
} catch (e) {
console.warn('Error loading state from window:', e);
return undefined;
}
};

// Создание хранилища с подключенным middleware
const store = configureStore({
reducer: rootReducer,
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(windowStateMiddleware),
preloadedState: loadFromWindow(),
});

export default store;

export type AppDispatch = typeof store.dispatch;
export type RootState = ReturnType<typeof store.getState>;
3 changes: 2 additions & 1 deletion packages/host/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
"compilerOptions": {
"baseUrl": "src",
"paths": {
"@host/*": ["*"]
"@host/*": ["*"],
"shared/*": ["../../shared/*"]
}
}
}
1 change: 1 addition & 0 deletions packages/shared/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
init
13 changes: 13 additions & 0 deletions packages/shared/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Example</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
48 changes: 48 additions & 0 deletions packages/shared/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
{
"name": "shared",
"keywords": [],
"version": "1.0.0",
"description": "shared",
"type": "module",
"scripts": {
"start:demo": "vite",
"build": "tsc && vite build && tsc --project tsconfig.json && tsc-alias",
"lint": "eslint 'src/**/*.{js,ts,tsx}'",
"format": "prettier --write 'src/**/*.{js,ts,tsx}'"
},
"license": "ISC",
"main": "dist/index.cjs.js",
"module": "dist/index.es.js",
"types": "dist/index.d.ts",
"exports": {
".": {
"import": "./dist/index.es.js"
},
"./types": {
"import": "./dist/types/index.d.ts"
}
},
"sideEffects": false,
"files": [
"dist"
],
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^6.7.4",
"@typescript-eslint/parser": "^6.7.4",
"@vitejs/plugin-react": "2.2.0",
"eslint": "8.22.0",
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-prettier": "^5.0.0",
"prettier": "3.0.3",
"tsc-alias": "1.7.0",
"typescript": "^4.6.4",
"vite": "3.2.0"
},
"repository": {
"type": "git",
"url": ""
},
"publishConfig": {
"registry": "https://registry.npmjs.org/"
}
}
1 change: 1 addition & 0 deletions packages/shared/src/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './useCommunication';
5 changes: 5 additions & 0 deletions packages/shared/src/hooks/useCommunication.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export function useCommunication() {
// const event = new CustomEvent('hostEvent:ChangeRole', {
// detail: { role: newRole },
// });
}
3 changes: 3 additions & 0 deletions packages/shared/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export * from '@/hooks';
export * from '@/types';
export * from '@/utils';
Loading

0 comments on commit 688f996

Please sign in to comment.