This commit is contained in:
Леонид Малафеев 2024-01-11 00:42:45 +04:00
parent 257a4679c9
commit 89e44990c2
100 changed files with 7988 additions and 0 deletions

24
lab5/.eslintrc.cjs Normal file
View File

@ -0,0 +1,24 @@
module.exports = {
root: true,
env: { browser: true, es2020: true },
extends: [
'airbnb-base',
'plugin:react/recommended',
'plugin:react/jsx-runtime',
'plugin:react-hooks/recommended',
],
ignorePatterns: ['dist', '.eslintrc.cjs'],
parserOptions: { ecmaVersion: 12, sourceType: 'module' },
settings: { react: { version: '18.2' } },
plugins: ['react-refresh'],
rules: {
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
'indent': 'off',
'no-console': 'off',
'arrow-body-style': 'off',
'implicit-arrow-linebreak': 'off',
},
}

24
lab5/.gitignore vendored Normal file
View File

@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

44
lab5/README.md Normal file
View File

@ -0,0 +1,44 @@
### Окружение:
- [nodejs 20 LTS latest](https://nodejs.org/en/download/);
- [VSCode](https://code.visualstudio.com/download);
- [ESLint](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint) плагин для VSCode;
- [CSS Class Intellisense](https://marketplace.visualstudio.com/items?itemName=Tarrow.css-class-intellisense) плагин для автодополнения CSS-классов в HTML;
- для отладки необходимы бразузеры Chrome или Edge.
Настройки плагина CSS Class Intellisense находятся в файле ./vscode/cssconfig.json
### Команды
#### Создание пустого проекта:
```commandline
npm create vite@latest ./ -- --template react
```
#### Установка зависимостей:
```commandline
npm install
```
#### Запуск проекта в режиме разработки (development):
```commandline
npm run dev
```
#### Запуск проекта в продуктовом режиме (production):
```commandline
npm run prod
```
### Полезные ссылки
1. Global Object - https://developer.mozilla.org/en-US/docs/Glossary/Global_object
2. Global Scope - https://developer.mozilla.org/en-US/docs/Glossary/Global_scope
3. localStorage - https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
4. JavaScript Execution Context How JS Works Behind The Scenes - https://www.freecodecamp.org/news/execution-context-how-javascript-works-behind-the-scenes/
5. Extracting State Logic into a Reducer - https://react.dev/learn/extracting-state-logic-into-a-reducer
6. Passing Data Deeply with Context - https://react.dev/learn/passing-data-deeply-with-context
7. Scaling Up with Reducer and Context - https://react.dev/learn/scaling-up-with-reducer-and-context

154
lab5/data.json Normal file

File diff suppressed because one or more lines are too long

15
lab5/index.html Normal file
View File

@ -0,0 +1,15 @@
<html lang="ru">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Автосалон</title>
</head>
<body>
<div id="root" class="h-100 d-flex flex-column"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>

14
lab5/jsconfig.json Normal file
View File

@ -0,0 +1,14 @@
{
"compilerOptions": {
"module": "ESNext",
"moduleResolution": "Node",
"target": "ES2020",
"jsx": "react",
"strictNullChecks": true,
"strictFunctionTypes": true
},
"exclude": [
"node_modules",
"**/node_modules/*"
]
}

5
lab5/json-server.json Normal file
View File

@ -0,0 +1,5 @@
{
"static": "./node_modules/json-server/public",
"port": 8081,
"watch": "true"
}

5936
lab5/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

38
lab5/package.json Normal file
View File

@ -0,0 +1,38 @@
{
"name": "lec4",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0",
"rest": "json-server data.json",
"vite": "vite",
"dev": "npm-run-all --parallel rest vite",
"prod": "npm-run-all lint 'vite build' --parallel rest 'vite preview'"
},
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.18.0",
"react-hot-toast": "^2.4.1",
"axios": "^1.6.1",
"bootstrap": "^5.3.2",
"react-bootstrap": "^2.9.1",
"react-bootstrap-icons": "^1.10.3",
"prop-types": "^15.8.1"
},
"devDependencies": {
"@types/react": "^18.2.15",
"@types/react-dom": "^18.2.15",
"@vitejs/plugin-react": "^4.0.3",
"eslint": "^8.45.0",
"eslint-config-airbnb-base": "^15.0.0",
"eslint-plugin-import": "^2.29.0",
"eslint-plugin-react": "^7.32.2",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.3",
"json-server": "^0.17.4",
"npm-run-all": "^4.1.5",
"vite": "^4.4.5"
}
}

79
lab5/public/favicon.svg Normal file
View File

@ -0,0 +1,79 @@
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN"
"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg version="1.0" xmlns="http://www.w3.org/2000/svg"
width="512.000000pt" height="512.000000pt" viewBox="0 0 512.000000 512.000000"
preserveAspectRatio="xMidYMid meet">
<g transform="translate(0.000000,512.000000) scale(0.100000,-0.100000)"
fill="#000000" stroke="none">
<path d="M2472 5105 c-23 -7 -65 -30 -93 -51 -138 -106 -153 -321 -31 -448 37
-39 122 -86 155 -86 15 0 17 -13 17 -131 l0 -132 -36 6 c-19 3 -56 19 -82 35
-26 16 -86 54 -135 85 -166 105 -277 121 -463 68 -260 -75 -562 -103 -1328
-121 -249 -6 -447 -15 -457 -21 -41 -22 -12 -109 56 -164 106 -87 347 -163
546 -172 l117 -6 11 -37 c14 -48 72 -107 130 -133 35 -16 73 -22 152 -25 l107
-4 18 -39 c50 -113 214 -182 377 -159 66 10 142 33 163 51 10 8 18 1 33 -29
28 -54 68 -100 104 -119 37 -19 143 -19 207 0 42 12 48 11 89 -12 78 -43 198
-39 369 14 l22 7 0 -477 c0 -449 -1 -476 -17 -471 -10 3 -70 14 -133 26 -389
71 -530 119 -596 205 -59 78 -48 199 26 266 46 42 112 63 156 50 66 -20 80
-32 108 -96 39 -90 94 -149 157 -170 96 -32 191 -2 197 64 9 88 -143 212 -280
228 -29 3 -71 16 -93 27 -32 17 -58 21 -126 21 -85 0 -88 -1 -144 -40 -75 -51
-108 -116 -113 -223 -5 -95 14 -146 77 -205 86 -80 207 -127 447 -172 210 -39
197 -34 136 -57 -84 -32 -173 -97 -207 -152 -27 -45 -30 -57 -30 -136 0 -79 3
-91 30 -136 36 -57 109 -110 202 -145 34 -13 63 -27 63 -30 0 -3 -19 -12 -42
-19 -104 -31 -195 -95 -229 -161 -24 -47 -26 -144 -3 -197 30 -73 100 -128
220 -171 l73 -27 -55 -28 c-78 -41 -107 -83 -112 -161 -7 -101 42 -171 151
-220 l49 -21 -37 -28 c-53 -41 -79 -104 -72 -179 7 -73 43 -135 113 -192 l50
-41 -70 -64 c-128 -119 -203 -280 -141 -304 27 -10 43 5 59 51 22 65 69 134
129 190 l52 48 5 -159 c4 -137 7 -160 23 -170 12 -8 22 -8 35 0 15 10 18 33
22 167 l5 156 34 -26 c48 -38 117 -135 136 -193 19 -56 47 -79 72 -59 21 18
12 75 -23 147 -18 37 -56 85 -110 139 l-82 82 45 35 c88 68 130 151 120 237
-8 62 -29 102 -73 135 l-35 27 62 32 c78 39 116 84 130 155 21 100 -18 173
-120 222 l-45 22 52 17 c83 28 171 80 203 118 39 47 63 130 55 189 -14 101
-102 186 -235 228 -34 11 -61 22 -61 25 0 3 19 12 43 19 111 33 207 104 243
179 24 49 24 152 1 213 -25 66 -107 138 -199 176 -62 26 -69 31 -48 36 14 3
87 17 164 31 251 47 383 101 461 188 53 58 69 109 62 192 -9 122 -86 230 -181
256 -60 16 -167 6 -211 -20 -20 -11 -52 -21 -70 -21 -125 0 -301 -138 -293
-229 9 -101 198 -108 281 -10 19 21 50 72 70 113 36 73 38 75 88 90 93 28 175
-11 217 -102 52 -114 23 -203 -88 -270 -90 -54 -224 -89 -592 -156 l-78 -14 0
475 0 475 23 -7 c170 -53 290 -58 369 -13 34 19 50 23 68 16 45 -17 143 -25
184 -16 57 13 98 48 132 111 l28 55 36 -17 c71 -36 186 -53 275 -40 112 16
207 75 245 153 l21 44 107 4 c91 3 115 8 158 30 60 31 107 82 124 132 l12 36
83 0 c105 0 221 22 358 67 177 59 280 134 293 215 11 63 3 65 -253 72 -1004
26 -1265 47 -1548 127 -95 27 -122 31 -200 27 -104 -4 -170 -30 -296 -116 -90
-60 -171 -102 -199 -102 -19 0 -20 6 -20 130 0 119 2 130 18 130 33 0 120 51
157 92 56 61 78 120 78 203 0 95 -29 160 -100 225 -81 74 -179 97 -281 65z
m142 -76 c94 -23 155 -107 156 -211 0 -72 -12 -103 -58 -152 -94 -98 -212
-101 -302 -7 -88 90 -93 213 -13 302 64 71 128 91 217 68z m-524 -646 c29 -9
107 -52 174 -95 73 -47 148 -87 189 -100 l67 -22 0 -302 0 -302 -27 -5 c-16
-3 -64 -15 -108 -27 -105 -28 -189 -23 -245 14 -46 30 -51 31 -105 11 -22 -8
-66 -14 -97 -15 -72 0 -105 26 -148 115 -16 34 -37 66 -46 69 -8 3 -50 -11
-92 -32 -64 -31 -90 -38 -153 -41 -151 -6 -253 49 -284 154 -8 29 -21 55 -27
57 -7 3 -35 0 -63 -5 -82 -15 -177 -4 -229 27 -49 28 -86 85 -86 130 0 14 -5
28 -11 31 -6 4 -70 8 -142 10 -109 2 -153 8 -251 34 -118 30 -237 80 -286 120
-14 11 -22 22 -19 25 2 3 196 10 429 16 760 18 1051 46 1305 124 95 29 183 32
255 9z m1191 -8 c176 -53 400 -86 709 -105 136 -8 771 -27 1000 -30 l35 -1
-39 -34 c-44 -39 -157 -86 -296 -122 -73 -19 -125 -26 -227 -28 -72 -2 -136
-6 -142 -10 -6 -3 -11 -16 -11 -28 0 -12 -9 -41 -19 -64 -37 -81 -161 -121
-298 -96 -28 6 -56 7 -62 4 -5 -3 -19 -32 -31 -63 -40 -107 -132 -154 -284
-146 -69 4 -91 10 -154 42 -40 21 -78 36 -85 33 -7 -3 -27 -34 -45 -69 -17
-35 -43 -74 -56 -88 -34 -31 -117 -39 -185 -16 -64 21 -64 21 -111 -10 -56
-37 -140 -42 -245 -14 -44 12 -92 24 -107 27 l-28 5 0 304 0 303 42 12 c57 15
125 50 235 121 160 104 248 119 404 73z m-1045 -1381 c47 -27 107 -91 99 -105
-8 -12 -65 -12 -103 2 -30 10 -73 64 -92 115 -10 25 -9 25 22 19 18 -4 52 -18
74 -31z m730 -11 c-35 -70 -66 -95 -124 -101 -29 -2 -52 0 -56 6 -15 24 88
113 152 132 51 16 53 12 28 -37z m-446 -813 c0 -143 -4 -260 -9 -260 -34 0
-210 69 -253 99 -111 76 -130 200 -45 289 48 50 219 129 285 131 l22 1 0 -260z
m206 229 c179 -63 249 -141 230 -257 -16 -101 -114 -168 -338 -229 -17 -4 -18
13 -18 256 0 303 -13 279 126 230z m-210 -1056 c-8 -8 -130 29 -195 58 -103
47 -151 102 -151 174 0 99 83 165 270 213 l75 20 3 -231 c1 -126 1 -232 -2
-234z m204 431 c145 -44 217 -99 227 -172 3 -23 3 -52 -1 -66 -9 -38 -63 -94
-115 -120 -43 -22 -201 -76 -222 -76 -5 0 -9 94 -9 236 0 219 1 235 18 230 9
-3 55 -17 102 -32z m-200 -703 l0 -160 -42 15 c-104 35 -168 95 -168 156 0 38
13 62 50 88 30 21 123 59 148 60 9 0 12 -38 12 -159z m197 122 c63 -29 93 -64
93 -108 0 -64 -62 -123 -167 -159 l-43 -15 0 160 0 161 33 -7 c17 -4 56 -18
84 -32z m-199 -620 l-3 -78 -41 38 c-100 90 -98 193 4 246 l37 19 3 -74 c2
-41 2 -109 0 -151z m186 144 c12 -26 16 -48 12 -72 -7 -38 -58 -109 -93 -133
l-23 -14 0 152 0 151 43 -23 c27 -15 49 -37 61 -61z"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 5.4 KiB

35
lab5/src/App.jsx Normal file
View File

@ -0,0 +1,35 @@
import PropTypes from 'prop-types';
import { Container } from 'react-bootstrap';
import { Toaster } from 'react-hot-toast';
import { Outlet } from 'react-router-dom';
import Footer from './components/footer/Footer.jsx';
import Navigation from './components/navigation/Navigation.jsx';
import UserContext from './components/users/UserContext.jsx';
import appHook from '../src/components/users/AppHook';
const App = ({ routes }) => {
const {
user, setUser, logged, setLogged, curUser, setCurUser,
} = appHook();
return (
<>
<UserContext.Provider value={{
user, setUser, logged, setLogged, curUser, setCurUser,
}}>
<Navigation routes={routes}></Navigation>
<Container className='p-2' as='main' fluid>
<Outlet />
</Container>
</UserContext.Provider>
<Footer />
<Toaster position='top-center' reverseOrder={true} />
</>
);
};
App.propTypes = {
routes: PropTypes.array,
};
export default App;

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 137 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 204 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 157 KiB

BIN
lab5/src/assets/200.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 416 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 808 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 107 KiB

BIN
lab5/src/assets/banner1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 640 KiB

BIN
lab5/src/assets/banner2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 812 KiB

BIN
lab5/src/assets/banner3.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 767 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 117 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 308 KiB

BIN
lab5/src/assets/car1-1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 278 KiB

BIN
lab5/src/assets/car1-2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 201 KiB

BIN
lab5/src/assets/car1-3.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 302 KiB

BIN
lab5/src/assets/car1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

BIN
lab5/src/assets/car2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

BIN
lab5/src/assets/car3.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

BIN
lab5/src/assets/car4.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 491 KiB

BIN
lab5/src/assets/ferrari.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 287 KiB

BIN
lab5/src/assets/joker.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

BIN
lab5/src/assets/lamba.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 107 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 382 KiB

BIN
lab5/src/assets/like.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 119 KiB

BIN
lab5/src/assets/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 553 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 451 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

BIN
lab5/src/assets/man4.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 193 KiB

BIN
lab5/src/assets/man5.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 238 KiB

BIN
lab5/src/assets/noimage.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 240 KiB

BIN
lab5/src/assets/phone.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 577 B

View File

@ -0,0 +1,40 @@
import axios from 'axios';
import toast from 'react-hot-toast';
export class HttpError extends Error {
constructor(message = '') {
super(message);
this.name = 'HttpError';
Object.setPrototypeOf(this, new.target.prototype);
toast.error(message, { id: 'HttpError' });
}
}
function responseHandler(response) {
if (response.status === 200 || response.status === 201) {
const data = response?.data;
if (!data) {
throw new HttpError('API Error. No data!');
}
return data;
}
throw new HttpError(`API Error! Invalid status code ${response.status}!`);
}
function responseErrorHandler(error) {
if (error === null) {
throw new Error('Unrecoverable error!! Error is null!');
}
toast.error(error.message, { id: 'AxiosError' });
return Promise.reject(error.message);
}
export const ApiClient = axios.create({
baseURL: 'http://localhost:8081/',
timeout: '3000',
headers: {
Accept: 'application/json',
},
});
ApiClient.interceptors.response.use(responseHandler, responseErrorHandler);

View File

@ -0,0 +1,29 @@
import { ApiClient } from './ApiClient';
class ApiService {
constructor(url) {
this.url = url;
}
async getAll(expand) {
return ApiClient.get(`${this.url}${expand || ''}`);
}
async get(id, expand) {
return ApiClient.get(`${this.url}/${id}${expand || ''}`);
}
async create(body) {
return ApiClient.post(this.url, body);
}
async update(id, body) {
return ApiClient.put(`${this.url}/${id}`, body);
}
async delete(id) {
return ApiClient.delete(`${this.url}/${id}`);
}
}
export default ApiService;

View File

@ -0,0 +1,26 @@
import Image from 'react-bootstrap/Image';
const Footer = () => {
return (
<footer className="footer mt-auto" style={{ backgroundColor: 'aquamarine' }}>
<div className="containerok fixed bottom-0">
<div className="d-flex">
<div className="p-2">
<a href='/Admin'><Image variant="top" src="src/assets/logo.png"/></a>
</div>
<div className="p-2 flex-grow-1">
<p>
Время работы:
<br />
Пн-пт 08:00 - 20:00
<br />
Сб-Вс 10:00 - 20:00
</p>
</div>
</div>
</div>
</footer>
);
};
export default Footer;

View File

@ -0,0 +1,23 @@
import PropTypes from 'prop-types';
import { Form } from 'react-bootstrap';
const Input = ({
name, label, value, onChange, className, ...rest
}) => {
return (
<Form.Group className={`mb-2 ${className || ''}`} controlId={name}>
<Form.Label>{label}</Form.Label>
<Form.Control name={name || ''} value={value || ''} onChange={onChange} {...rest} />
</Form.Group>
);
};
Input.propTypes = {
name: PropTypes.string,
label: PropTypes.string,
value: PropTypes.string,
onChange: PropTypes.func,
className: PropTypes.string,
};
export default Input;

View File

@ -0,0 +1,23 @@
import PropTypes from 'prop-types';
import { Form } from 'react-bootstrap';
const InputSearch = ({
name, label, value, onChange, className, ...rest
}) => {
return (
<Form.Group className={`m-3 ${className || ''}`} controlId={name}>
<Form.Label>{label}</Form.Label>
<Form.Control name={name || ''} value={value || ''} onChange={onChange} {...rest} />
</Form.Group>
);
};
InputSearch.propTypes = {
name: PropTypes.string,
label: PropTypes.string,
value: PropTypes.string,
onChange: PropTypes.func,
className: PropTypes.string,
};
export default InputSearch;

View File

@ -0,0 +1,29 @@
import PropTypes from 'prop-types';
import { Form } from 'react-bootstrap';
const Select = ({
values, name, label, value, onChange, className, ...rest
}) => {
return (
<Form.Group className={`mb-2 ${className || ''}`} controlId={name}>
<Form.Label className='form-label'>{label}</Form.Label>
<Form.Select name={name || ''} value={value || ''} onChange={onChange} {...rest}>
<option value=''>Поиск</option>
{
values.map((type) => <option key={type.id} value={type.id}>{type.name}</option>)
}
</Form.Select>
</Form.Group>
);
};
Select.propTypes = {
values: PropTypes.array,
name: PropTypes.string,
label: PropTypes.string,
value: PropTypes.string,
onChange: PropTypes.func,
className: PropTypes.string,
};
export default Select;

View File

@ -0,0 +1,48 @@
import PropTypes from 'prop-types';
import { Button, Form } from 'react-bootstrap';
import { useNavigate } from 'react-router-dom';
import useLinesItemForm from '../hooks/LinesItemFormHook';
import LinesItemForm from './LinesItemForm.jsx';
const LinesForm = ({ id }) => {
const navigate = useNavigate();
const {
item,
validated,
handleSubmit,
handleChange,
} = useLinesItemForm(id);
const onBack = () => {
navigate(-1);
};
const onSubmit = async (event) => {
if (await handleSubmit(event)) {
onBack();
}
};
return (
<>
<Form className='m-0 p-2' noValidate validated={validated} onSubmit={onSubmit}>
<LinesItemForm item={item} handleChange={handleChange} />
<Form.Group className='row justify-content-center m-0 mt-3'>
<Button className='col-5 col-lg-2 m-0 me-2' variant='secondary' onClick={() => onBack()}>
Назад
</Button>
<Button className='col-5 col-lg-2 m-0 ms-2' type='submit' variant='primary'>
Сохранить
</Button>
</Form.Group>
</Form>
</>
);
};
LinesForm.propTypes = {
id: PropTypes.string,
};
export default LinesForm;

View File

@ -0,0 +1,3 @@
#image-preview {
width: 200px;
}

View File

@ -0,0 +1,36 @@
import PropTypes from 'prop-types';
import imgPlaceholder from '../../../assets/200.png';
import Input from '../../input/Input.jsx';
import Select from '../../input/Select.jsx';
import useTypes from '../../types/hooks/TypesHook';
import './LinesItemForm.css';
const LinesItemForm = ({ item, handleChange }) => {
const { types } = useTypes();
return (
<>
<div className='text-center'>
<img id='image-preview' className='rounded' alt='placeholder'
src={item.image || imgPlaceholder} />
</div>
<Select values={types} name='typeId' label='Марка авто' value={item.typeId} onChange={handleChange}
required />
<Input name='model' label='Модель' value={item.model} onChange={handleChange} type='text' required />
<Input name='price' label='Цена' value={item.price} onChange={handleChange}
type='number' min='100000' step='1' required />
<Input name='count' label='Год Выпуска' value={item.count} onChange={handleChange}
type='number' min='1990' max='2023' step='1' required />
<Input name='description' label='Описание' value={item.description} onChange={handleChange} type='text' as="textarea" rows={5} required />
<Input name='image' label='Изображение' onChange={handleChange}
type='file' accept='image/*' />
</>
);
};
LinesItemForm.propTypes = {
item: PropTypes.object,
handleChange: PropTypes.func,
};
export default LinesItemForm;

View File

@ -0,0 +1,34 @@
import { useState } from 'react';
import toast from 'react-hot-toast';
import useModal from '../../modal/ModalHook';
import LinesApiService from '../service/LinesApiService';
const useLinesDeleteModal = (linesChangeHandle) => {
const { isModalShow, showModal, hideModal } = useModal();
const [currentId, setCurrentId] = useState(0);
const showModalDialog = (id) => {
showModal();
setCurrentId(id);
};
const onClose = () => {
hideModal();
};
const onDelete = async () => {
await LinesApiService.delete(currentId);
linesChangeHandle();
toast.success('Элемент успешно удален', { id: 'LinesTable' });
onClose();
};
return {
isDeleteModalShow: isModalShow,
showDeleteModal: showModalDialog,
handleDeleteConfirm: onDelete,
handleDeleteCancel: onClose,
};
};
export default useLinesDeleteModal;

View File

@ -0,0 +1,28 @@
import { useSearchParams } from 'react-router-dom';
import useTypes from '../../types/hooks/TypesHook';
const useTypeFilter = () => {
const filterName = 'type';
const [searchParams, setSearchParams] = useSearchParams();
const { types } = useTypes();
const handleFilterChange = (event) => {
const type = event.target.value;
if (type) {
searchParams.set(filterName, event.target.value);
} else {
searchParams.delete(filterName);
}
setSearchParams(searchParams);
};
return {
types,
currentFilter: searchParams.get(filterName) || '',
handleFilterChange,
};
};
export default useTypeFilter;

View File

@ -0,0 +1,45 @@
import { useState } from 'react';
import useModal from '../../modal/ModalHook';
import useLinesItemForm from './LinesItemFormHook';
const useLinesFormModal = (linesChangeHandle) => {
const { isModalShow, showModal, hideModal } = useModal();
const [currentId, setCurrentId] = useState(0);
const {
item,
validated,
handleSubmit,
handleChange,
resetValidity,
} = useLinesItemForm(currentId, linesChangeHandle);
const showModalDialog = (id) => {
setCurrentId(id);
resetValidity();
showModal();
};
const onClose = () => {
setCurrentId(-1);
hideModal();
};
const onSubmit = async (event) => {
if (await handleSubmit(event)) {
onClose();
}
};
return {
isFormModalShow: isModalShow,
isFormValidated: validated,
showFormModal: showModalDialog,
currentItem: item,
handleItemChange: handleChange,
handleFormSubmit: onSubmit,
handleFormClose: onClose,
};
};
export default useLinesFormModal;

View File

@ -0,0 +1,29 @@
import { useEffect, useState } from 'react';
import LinesApiService from '../service/LinesApiService';
const useLines = (typeFilter) => {
const [linesRefresh, setLinesRefresh] = useState(false);
const [lines, setLines] = useState([]);
const handleLinesChange = () => setLinesRefresh(!linesRefresh);
const getLines = async () => {
let expand = '?_expand=type';
if (typeFilter) {
expand = `${expand}&typeId=${typeFilter}`;
}
const data = await LinesApiService.getAll(expand);
setLines(data ?? []);
};
useEffect(() => {
getLines();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [linesRefresh, typeFilter]);
return {
lines,
handleLinesChange,
};
};
export default useLines;

View File

@ -0,0 +1,83 @@
import { useState } from 'react';
import toast from 'react-hot-toast';
import getBase64FromFile from '../../utils/Base64';
import LinesApiService from '../service/LinesApiService';
import useLinesItem from './LinesItemHook';
const useLinesItemForm = (id, linesChangeHandle) => {
const { item, setItem } = useLinesItem(id);
const [validated, setValidated] = useState(false);
const resetValidity = () => {
setValidated(false);
};
const getLineObject = (formData) => {
const typeId = parseInt(formData.typeId, 10);
const price = parseFloat(formData.price);
const count = parseInt(formData.count, 10);
const description = String(formData.description, 30);
const model = String(formData.model, 30);
const image = formData.image.startsWith('data:image') ? formData.image : '';
return {
typeId: typeId.toString(),
price: price.toString(),
count: count.toString(),
description: description.toString(),
model: model.toString(),
image,
};
};
const handleImageChange = async (event) => {
const { files } = event.target;
const file = await getBase64FromFile(files.item(0));
setItem({
...item,
image: file,
});
};
const handleChange = (event) => {
if (event.target.type === 'file') {
handleImageChange(event);
return;
}
const inputName = event.target.name;
const inputValue = event.target.type === 'checkbox' ? event.target.checked : event.target.value;
setItem({
...item,
[inputName]: inputValue,
});
};
const handleSubmit = async (event) => {
const form = event.currentTarget;
event.preventDefault();
event.stopPropagation();
const body = getLineObject(item);
if (form.checkValidity()) {
if (id === undefined) {
await LinesApiService.create(body);
} else {
await LinesApiService.update(id, body);
}
if (linesChangeHandle) linesChangeHandle();
toast.success('Элемент успешно сохранен', { id: 'LinesTable' });
return true;
}
setValidated(true);
return false;
};
return {
item,
validated,
handleSubmit,
handleChange,
resetValidity,
};
};
export default useLinesItemForm;

View File

@ -0,0 +1,34 @@
import { useEffect, useState } from 'react';
import LinesApiService from '../service/LinesApiService';
const useLinesItem = (id) => {
const emptyItem = {
id: '',
typeId: '',
price: '0',
count: '0',
image: '',
};
const [item, setItem] = useState({ ...emptyItem });
const getItem = async (itemId = undefined) => {
if (itemId && itemId > 0) {
const data = await LinesApiService.get(itemId);
setItem(data);
} else {
setItem({ ...emptyItem });
}
};
useEffect(() => {
getItem(id);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [id]);
return {
item,
setItem,
};
};
export default useLinesItem;

View File

@ -0,0 +1,34 @@
import { useEffect, useState } from 'react';
import LinesApiService from '../service/LinesApiService';
const useCarsItem = (id) => {
const emptyItem = {
id: '',
typeId: '',
price: '0',
count: '0',
image: '',
};
const [item, setItem] = useState({ ...emptyItem });
const getItem = async (itemId = undefined) => {
if (itemId && itemId > 0) {
const data = await LinesApiService.get(itemId, '?_expand=type');
setItem(data);
} else {
setItem({ ...emptyItem });
}
};
useEffect(() => {
getItem(id);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [id]);
return {
item,
setItem,
};
};
export default useCarsItem;

View File

@ -0,0 +1,5 @@
import ApiService from '../../api/ApiService';
const LinesApiService = new ApiService('lines');
export default LinesApiService;

View File

@ -0,0 +1,72 @@
import { Button, ButtonGroup } from 'react-bootstrap';
import { Link, useNavigate } from 'react-router-dom';
import Select from '../../input/Select.jsx';
import ModalConfirm from '../../modal/ModalConfirm.jsx';
import ModalForm from '../../modal/ModalForm.jsx';
import LinesItemForm from '../form/LinesItemForm.jsx';
import useLinesDeleteModal from '../hooks/LinesDeleteModalHook';
import useTypeFilter from '../hooks/LinesFilterHook';
import useLinesFormModal from '../hooks/LinesFormModalHook';
import useLines from '../hooks/LinesHook';
import LinesTable from './LinesTable.jsx';
import LinesTableRow from './LinesTableRow.jsx';
const Lines = () => {
const { types, currentFilter, handleFilterChange } = useTypeFilter();
const { lines, handleLinesChange } = useLines(currentFilter);
const {
isDeleteModalShow,
showDeleteModal,
handleDeleteConfirm,
handleDeleteCancel,
} = useLinesDeleteModal(handleLinesChange);
const {
isFormModalShow,
isFormValidated,
currentItem,
handleItemChange,
handleFormSubmit,
handleFormClose,
} = useLinesFormModal(handleLinesChange);
const navigate = useNavigate();
const showEditPage = (id) => {
navigate(`/page-edit/${id}`);
};
return (
<>
<ButtonGroup>
<Button as={Link} to='/page-edit' variant='success'>
Добавить товар
</Button>
</ButtonGroup>
<Select className='mt-2' values={types} label='Фильтр по маркам'
value={currentFilter} onChange={handleFilterChange} />
<LinesTable>
{
lines.map((line, index) =>
<LinesTableRow key={line.id}
index={index} line={line}
onDelete={() => showDeleteModal(line.id)}
onEditInPage={() => showEditPage(line.id)}
/>)
}
</LinesTable>
<ModalConfirm show={isDeleteModalShow}
onConfirm={handleDeleteConfirm} onClose={handleDeleteCancel}
title='Удаление' message='Удалить элемент?' />
<ModalForm show={isFormModalShow} validated={isFormValidated}
onSubmit={handleFormSubmit} onClose={handleFormClose}
title='Редактирование'>
<LinesItemForm item={currentItem} handleChange={handleItemChange} />
</ModalForm>
</>
);
};
export default Lines;

View File

@ -0,0 +1,31 @@
import PropTypes from 'prop-types';
import { Table } from 'react-bootstrap';
const LinesTable = ({ children }) => {
return (
<Table className='mt-2' striped responsive>
<thead>
<tr>
<th scope='col'></th>
<th scope='col' className='w-25'>Марка</th>
<th scope='col' className='w-25'>Модель</th>
<th scope='col' className='w-25'>Цена</th>
<th scope='col' className='w-25'>Год выпуска</th>
<th scope='col'></th>
<th scope='col'></th>
<th scope='col'></th>
<th scope='col'></th>
</tr>
</thead>
<tbody>
{children}
</tbody >
</Table >
);
};
LinesTable.propTypes = {
children: PropTypes.node,
};
export default LinesTable;

View File

@ -0,0 +1,36 @@
import PropTypes from 'prop-types';
import {
PencilFill, Trash3,
} from 'react-bootstrap-icons';
const LinesTableRow = ({
index, line, onDelete, onEditInPage,
}) => {
const handleAnchorClick = (event, action) => {
event.preventDefault();
action();
};
return (
<tr>
<th scope="row">{index + 1}</th>
<td>{line.type.name}</td>
<td>{line.model}</td>
<td>{line.price}</td>
<td>{line.count}</td>
<td></td>
<td></td>
<td><a href="#" onClick={(event) => handleAnchorClick(event, onEditInPage)}><PencilFill /></a></td>
<td><a href="#" onClick={(event) => handleAnchorClick(event, onDelete)}><Trash3 /></a></td>
</tr>
);
};
LinesTableRow.propTypes = {
index: PropTypes.number,
line: PropTypes.object,
onDelete: PropTypes.func,
onEditInPage: PropTypes.func,
};
export default LinesTableRow;

View File

@ -0,0 +1,22 @@
import { Container } from 'react-bootstrap';
import useLines from '../hooks/LinesHook';
import LinesTable from './LinesTable.jsx';
import LinesTableRow from './LinesTableRow.jsx';
const Lines = () => {
const { lines } = useLines();
return (
<Container>
<LinesTable>
{
lines.map((line) =>
<LinesTableRow key={line.id}
line={line}
/>)
}
</LinesTable>
</Container>
);
};
export default Lines;

View File

@ -0,0 +1,16 @@
import PropTypes from 'prop-types';
import { Container, Row } from 'react-bootstrap';
const LinesTable = ({ children }) => {
return (
<Container className='mb-5'>
<Row> {children} </Row>
</Container>
);
};
LinesTable.propTypes = {
children: PropTypes.node,
};
export default LinesTable;

View File

@ -0,0 +1,35 @@
import PropTypes from 'prop-types';
import Card from 'react-bootstrap/Card';
import Col from 'react-bootstrap/Col';
import { useNavigate } from 'react-router-dom';
const LinesTableRow = ({ line }) => {
const navigate = useNavigate();
const showCarPage = () => {
navigate(`/CarPage/${line.id}`);
};
const handleAnchorClick = (event, action) => {
event.preventDefault();
action();
};
return (
<Col md={6} lg={6} xl={4} xxl={3} mb={4}>
<Card style={{ width: '18rem' }} h={100} className='mb-5'>
<a href='#' onClick={(event) => handleAnchorClick(event, showCarPage)}><Card.Img variant="top" id='ultraCar' src={line.image}/></a>
<Card.Body>
<Card.Title>{line.type.name} {line.model}</Card.Title>
<Card.Text>
{line.count} Года выпуска
</Card.Text>
<p>{line.price} Руб.</p>
</Card.Body>
</Card>
</Col>
);
};
LinesTableRow.propTypes = {
line: PropTypes.object,
};
export default LinesTableRow;

View File

@ -0,0 +1,3 @@
.modal-title {
font-size: 1.2rem;
}

View File

@ -0,0 +1,42 @@
import PropTypes from 'prop-types';
import { Button, Modal } from 'react-bootstrap';
import { createPortal } from 'react-dom';
import './Modal.css';
const ModalConfirm = ({
show, title, message, onConfirm, onClose,
}) => {
return createPortal(
<Modal show={show} backdrop='static' onHide={() => onClose()}>
<Modal.Header className='pt-2 pb-2 ps-3 pe-3' closeButton>
<Modal.Title>{title}</Modal.Title>
</Modal.Header>
<Modal.Body>
{message}
</Modal.Body>
<Modal.Footer className='m-0 pt-2 pb-2 ps-3 pe-3 row justify-content-center'>
<Button variant='secondary' className='col-5 m-0 me-2'
onClick={() => onClose()}>
Нет
</Button>
<Button variant='primary' className='col-5 m-0 ms-2'
onClick={() => onConfirm()}>
Да
</Button>
</Modal.Footer>
</Modal>,
document.body,
);
};
ModalConfirm.propTypes = {
show: PropTypes.bool,
title: PropTypes.string,
message: PropTypes.string,
onConfirm: PropTypes.func,
onClose: PropTypes.func,
};
export default ModalConfirm;

View File

@ -0,0 +1,43 @@
import PropTypes from 'prop-types';
import { Button, Form, Modal } from 'react-bootstrap';
import { createPortal } from 'react-dom';
import './Modal.css';
const ModalForm = ({
show, title, validated, onSubmit, onClose, children,
}) => {
return createPortal(
<Modal show={show} backdrop='static' onHide={() => onClose()}>
<Modal.Header className='pt-2 pb-2 ps-3 pe-3' closeButton>
<Modal.Title>{title}</Modal.Title>
</Modal.Header>
<Form className='m-0' noValidate validated={validated} onSubmit={onSubmit}>
<Modal.Body>
{children}
</Modal.Body>
<Modal.Footer className='m-0 pt-2 pb-2 ps-3 pe-3 row justify-content-center'>
<Button variant='secondary' className='col-5 m-0 me-2'
onClick={() => onClose()}>
Отмена
</Button>
<Button variant='primary' className='col-5 m-0 ms-2' type='submit'>
Сохранить
</Button>
</Modal.Footer>
</Form>
</Modal>,
document.body,
);
};
ModalForm.propTypes = {
show: PropTypes.bool,
title: PropTypes.string,
validated: PropTypes.bool,
onSubmit: PropTypes.func,
onClose: PropTypes.func,
children: PropTypes.node,
};
export default ModalForm;

View File

@ -0,0 +1,21 @@
import { useState } from 'react';
const useModal = () => {
const [showModal, setShowModal] = useState(false);
const showModalDialog = () => {
setShowModal(true);
};
const hideModalDialog = () => {
setShowModal(false);
};
return {
isModalShow: showModal,
showModal: showModalDialog,
hideModal: hideModalDialog,
};
};
export default useModal;

View File

@ -0,0 +1,58 @@
import Nav from 'react-bootstrap/Nav';
import Navbar from 'react-bootstrap/Navbar';
import Image from 'react-bootstrap/Image';
import Stack from 'react-bootstrap/Stack';
import { useContext } from 'react';
import UserContext from '../users/UserContext.jsx';
const Navigation = () => {
const {
logged, setLogged,
} = useContext(UserContext);
let first;
let second;
const onClick = async () => {
localStorage.removeItem('User');
//await CurrentUserApiService.create(clearedUser);
setLogged(false);
};
if (!logged) {
first = <div className="p-2">
<Nav.Link href="/SignUp" id='textNav'>Регистрация</Nav.Link>
</div>;
second = <div className="p-2">
<Nav.Link href="/SignIn" id='textNav'>Войти</Nav.Link>
</div>;
} else {
first = <div className="p-2">
<Nav.Link href="/" id='textNav' onClick={onClick} >Выйти</Nav.Link>
</div>;
second = <div className="p-2">
</div>;
}
return (
<header>
<Navbar expand="lg">
<Stack direction="horizontal" gap={3}>
<div className="p-2">
<Navbar.Brand href="/">
<Image src="src/assets/logo.png" rounded />
</Navbar.Brand>
</div>
<div className='d-flex justify-content-aruond'>
<div className="p-2">
<Nav.Link href="/Page2" id='textNav'>Услуги</Nav.Link>
</div>
<div className="p-2">
<Nav.Link href="/Page3" id='textNav'>Вакансии</Nav.Link>
</div>
{first}
{second}
</div>
</Stack>
</Navbar>
</header>
);
};
export default Navigation;

View File

@ -0,0 +1,21 @@
import { useEffect, useState } from 'react';
import TypesApiService from '../service/TypesApiService';
const useTypes = () => {
const [types, setTypes] = useState([]);
const getTypes = async () => {
const data = await TypesApiService.getAll();
setTypes(data ?? []);
};
useEffect(() => {
getTypes();
}, []);
return {
types,
};
};
export default useTypes;

View File

@ -0,0 +1,5 @@
import ApiService from '../../api/ApiService';
const TypesApiService = new ApiService('types');
export default TypesApiService;

View File

@ -0,0 +1,23 @@
import { useEffect, useState } from 'react';
import useUsers from '../users/UsersHook';
const appHook = (id) => {
const { user, setUser } = useUsers(-1);
const [logged, setLogged] = useState(false);
const [curUser, setCurUser] = useState(null);
const load = async () => {
const data = localStorage.getItem('User');
if (localStorage.getItem('User') !== null) {
setCurUser(data);
setLogged(true);
}
};
useEffect(() => {
load();
}, []);
return {
user, setUser, logged, setLogged, curUser, setCurUser
};
};
export default appHook;

View File

@ -0,0 +1,5 @@
import ApiService from '../api/ApiService';
const CurrentUserApiService = new ApiService('currentUser');
export default CurrentUserApiService;

View File

@ -0,0 +1,61 @@
import { useState, useContext } from 'react';
import { useNavigate } from 'react-router-dom';
import toast from 'react-hot-toast';
import UsersApiService from './UsersApiService';
import UserContext from './UserContext.jsx';
const SignInn = () => {
const [validated, setValidated] = useState(false);
const navigate = useNavigate();
const {
user, setUser, setLogged, setCurUser,
} = useContext(UserContext);
const onBack = () => {
navigate(-1);
};
const handleChange = (event) => {
const inputName = event.target.name;
const inputValue = event.target.type === 'checkbox' ? event.target.checked : event.target.value;
setUser({
...user,
[inputName]: inputValue,
});
};
const getUserObject = (formData) => {
const email = String(formData.email, 30);
const password = String(formData.password, 30);
return {
email: email.toString(),
password: password.toString(),
};
};
const handleSubmit = async (event) => {
event.preventDefault();
event.stopPropagation();
const body = getUserObject(user);
const data = await UsersApiService.getAll(`?email=${body.email}`);
if (data) {
if (data[0].password === body.password) {
toast.success('Успешный вход', { id: 'User' });
localStorage.setItem('User', JSON.stringify(data[0]));
//await CurrentUserApiService.create(data[0]);
setCurUser(data[0]);
setLogged(true);
setValidated(true);
return true;
}
}
return false;
};
const onSubmit = async (event) => {
if (await handleSubmit(event)) {
onBack();
}
};
return {
user, handleChange, handleSubmit, onSubmit, validated
};
};
export default SignInn;

View File

@ -0,0 +1,5 @@
import { createContext } from 'react';
const UserContext = createContext(undefined);
export default UserContext;

View File

@ -0,0 +1,5 @@
import ApiService from '../api/ApiService';
const UsersApiService = new ApiService('users');
export default UsersApiService;

View File

@ -0,0 +1,33 @@
import { useEffect, useState } from 'react';
import UsersApiService from './UsersApiService';
const useUsers = (id) => {
const emptyUser = {
id: '',
name: '',
email: '',
password: '',
};
const [user, setUser] = useState({ ...emptyUser });
const getUser = async (userId = undefined) => {
if (userId && userId > 0) {
const data = await UsersApiService.get(userId);
setUser(data);
} else {
setUser({ ...emptyUser });
}
};
useEffect(() => {
getUser(id);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [id]);
return {
user,
setUser,
};
};
export default useUsers;

View File

@ -0,0 +1,15 @@
const getBase64FromFile = async (file) => {
const reader = new FileReader();
return new Promise((resolve, reject) => {
reader.onloadend = () => {
const fileContent = reader.result;
resolve(fileContent);
};
reader.onerror = () => {
reject(new Error('Oops, something went wrong with the file reader.'));
};
reader.readAsDataURL(file);
});
};
export default getBase64FromFile;

89
lab5/src/index.css Normal file
View File

@ -0,0 +1,89 @@
body
{
background-color: aquamarine;
}
#sslk:link{color: black;}
#sslk:visited{color: black;}
.card {
background: #33C598;
}
.containerok {
padding: 0 15px;
margin: 0;
}
.ct
{
font-size: 30px;
}
.btn2:link {background-color: #33C598}
.btn2:visited{background-color: #33C598;}
.btn2 {
border: black;
color: black;
}
.margo {
margin: 20px;
}
.inptt {
margin: 30px;
background-color: aquamarine;
}
.btnsend {
margin-top: 20px;
}
#aboutme {
height: 500px;
}
.card-body {
margin: 0;
}
ul li{
font-size: 30px;
}
ul
{
font-size: 40px;
}
#TextMain {
font-size: 40px;
}
#BtnForm {
border:#154436;
background-color: #33C598;
color: black;
font-size: 25px;
}
#BtnSend {
border:#154436;
background-color: #33C598;
color: black;
font-size: 17px;
}
#man1 {
height: 550px;
width: 800px;
}
#man2 {
height: 550px;
width: 580px;
}
#car{
height: auto;
width: auto;
}
#lutiText {
font-size: 30px;
}
#ultraCar {
height: 285px;
width: 285px;
object-fit: cover;
}
#carPageCar {
height: 500px;
width: 700px;
object-fit: cover;
}

75
lab5/src/main.jsx Normal file
View File

@ -0,0 +1,75 @@
import 'bootstrap/dist/css/bootstrap.min.css';
import React from 'react';
import ReactDOM from 'react-dom/client';
import { RouterProvider, createBrowserRouter } from 'react-router-dom';
import App from './App.jsx';
import './index.css';
import CarPage from './pages/CarPage.jsx';
import ErrorPage from './pages/ErrorPage.jsx';
import Page1 from './pages/Page1.jsx';
import Page2 from './pages/Page2.jsx';
import Page3 from './pages/Page3.jsx';
import Page4 from './pages/Page4.jsx';
import Admin from './pages/Admin.jsx';
import SignUp from './pages/SignUp.jsx';
import SignIn from './pages/SignIn.jsx';
import PageEdit from './pages/PageEdit.jsx';
const routes = [
{
index: true,
path: '/',
element: <Page1 />,
title: 'Главная страница',
},
{
path: '/page2',
element: <Page2 />,
title: 'Вторая страница',
},
{
path: '/page3',
element: <Page3 />,
title: 'Третья страница',
},
{
path: '/page4',
element: <Page4 />,
title: 'Четвертая страница',
},
{
path: '/page-edit/:id?',
element: <PageEdit />,
},
{
path: '/CarPage/:id?',
element: <CarPage />,
},
{
path: '/admin',
element: <Admin />,
},
{
path: '/signup',
element: <SignUp />,
},
{
path: '/signin',
element: <SignIn />,
},
];
const router = createBrowserRouter([
{
path: '/',
element: <App routes={routes} />,
children: routes,
errorElement: <ErrorPage />,
},
]);
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>,
);

9
lab5/src/pages/Admin.jsx Normal file
View File

@ -0,0 +1,9 @@
import Lines from '../components/lines/table/Lines.jsx';
const Admin = () => {
return (
<Lines />
);
};
export default Admin;

View File

@ -0,0 +1,36 @@
import { useParams } from 'react-router-dom';
import Container from 'react-bootstrap/Container';
import Row from 'react-bootstrap/Row';
import Card from 'react-bootstrap/Card';
import Image from 'react-bootstrap/Image';
import useCarsItem from '../components/lines/hooks/SelectCarPage';
const CarPage = () => {
const { id } = useParams();
const { item } = useCarsItem(id);
let itemname = 'подгрузка)';
if (item.type) {
itemname = item.type.name;
}
return (
<Container>
<Row className='m-5'>
<Image src={item.image}
className='rounded mx-auto d-block img-fluid' id="carPageCar"/>
<div className='p-2'>
<Card>
<Card.Body>
<Card.Title id='lutiText'>{itemname} {item.model}</Card.Title>
<Card.Text id='lutiText'>
{item.description}
</Card.Text>
<p id='lutiText'>{item.price}</p>
</Card.Body>
</Card>
</div>
</Row>
</Container>
);
};
export default CarPage;

View File

@ -0,0 +1,20 @@
import { Alert, Button, Container } from 'react-bootstrap';
import { useNavigate, useRouteError } from 'react-router-dom';
const ErrorPage = () => {
const navigate = useNavigate();
const error = useRouteError();
return (
<Container fluid className='m-0 p-3 row justify-content-center'>
<Alert className='col-12 col-lg-6' variant='danger'>
{error?.message ?? 'Страница не найдена'}
</Alert>
<div className='w-100'></div>
<Button className='col-12 col-lg-6' variant='primary'
onClick={() => navigate(-1)}>Назад</Button>
</Container>
);
};
export default ErrorPage;

11
lab5/src/pages/Page1.jsx Normal file
View File

@ -0,0 +1,11 @@
import Lines from '../components/lines/tableCar/Lines.jsx';
const Page1 = () => {
return (
<>
<Lines />
</>
);
};
export default Page1;

39
lab5/src/pages/Page2.jsx Normal file
View File

@ -0,0 +1,39 @@
import Row from 'react-bootstrap/Row';
import ListGroup from 'react-bootstrap/ListGroup';
import Image from 'react-bootstrap/Image';
import Container from 'react-bootstrap/Container';
import Col from 'react-bootstrap/Col';
const Page2 = () => {
return (
<Container>
<Row>
<div className='d-flex justify-content-evenly'>
<div className='p-2'>
<ListGroup as="ul"> Наши услуги:
<li>Тест-драйв</li>
<li>Гарантия</li>
<li>Тех осмотр</li>
<li>Скидки покупателям</li>
<li>Уникальные предложения</li>
</ListGroup>
</div>
<div className='p-2'>
<Image src="src/assets/like.png"
className='rounded mx-auto d-block img-fluid' style={{ width: 200, height: 200 }}/>
</div>
</div>
</Row>
<Row>
<Col md={6} lg={6} xl={6} xxl={6}>
<Image src="src/assets/man1page2.png" id='man1' />
</Col>
<Col md={6} lg={6} xl={6} xxl={6}>
<Image src="src/assets/man2page2.png" id='man2'/>
</Col>
</Row>
</Container>
);
};
export default Page2;

39
lab5/src/pages/Page3.jsx Normal file
View File

@ -0,0 +1,39 @@
import Col from 'react-bootstrap/Col';
import Row from 'react-bootstrap/Row';
import Card from 'react-bootstrap/Card';
import Button from 'react-bootstrap/Button';
import Container from 'react-bootstrap/Container';
const Page3 = () => {
return (
<Container>
<Row>
<Col sm={12} md={6} lg={6} xl={6} xxl={6}>
<div className='p-2'>
<Card>
<Card.Body>
<Card.Text id='TextMain'> Механик <br /> Зарплата 50.000</Card.Text>
<Card.Img src="src/assets/man4.png" />
</Card.Body>
</Card>
</div>
</Col>
<Col sm={12} md={6} lg={6} xl={6} xxl={6}>
<div className='p-2'>
<Card>
<Card.Body>
<Card.Text id='TextMain'> Администратор <br /> Зарплата 90.000</Card.Text>
<Card.Img src="src/assets/man5.png" />
</Card.Body>
</Card>
</div>
</Col>
<Col>
<Button id='BtnForm' className='m-2' href='/Page4'>Подать заявку на работу.</Button>{''}
</Col>
</Row>
</Container>
);
};
export default Page3;

38
lab5/src/pages/Page4.jsx Normal file
View File

@ -0,0 +1,38 @@
import Form from 'react-bootstrap/Form';
import Col from 'react-bootstrap/Col';
import Container from 'react-bootstrap/Container';
import Button from 'react-bootstrap/Button';
const Page4 = () => {
return (
<Container>
<Form>
<Form.Group className="mb-3">
<Form.Label>Фамилия, Имя, Отчество</Form.Label>
<Form.Control placeholder="Иванов Иван Иваныч" />
</Form.Group>
<Form.Group className="mb-3" controlId="exampleForm.ControlInput1">
<Form.Label>Почта</Form.Label>
<Form.Control type="email" placeholder="name@example.com" />
</Form.Group>
<Form.Group className="mb-3">
<Form.Label>дата рождения</Form.Label>
<Form.Control type="date"/>
</Form.Group>
<Form.Group className="mb-3">
<Form.Label>Номер телефона</Form.Label>
<Form.Control type="phone" placeholder="+79374456712" />
</Form.Group>
<Form.Group className="mb-3" controlId="exampleForm.ControlTextarea1">
<Form.Label>Расскажите о себе</Form.Label>
<Form.Control as="textarea" rows={5} />
</Form.Group>
</Form>
<Col>
<Button id='BtnSend' href='/Page4'>Отправить лютую заявку</Button>{''}
</Col>
</Container>
);
};
export default Page4;

View File

@ -0,0 +1,12 @@
import { useParams } from 'react-router-dom';
import LinesForm from '../components/lines/form/LinesForm.jsx';
const PageEdit = () => {
const { id } = useParams();
return (
<LinesForm id={id} />
);
};
export default PageEdit;

19
lab5/src/pages/SignIn.jsx Normal file
View File

@ -0,0 +1,19 @@
import { Container, Form, Button } from 'react-bootstrap';
import SignInn from '../components/users/SignInHook';
import Input from '../components/input/Input.jsx';
const SignIn = () => {
const { user, handleChange, validated, onSubmit } = SignInn();
return (
<Container>
<Form id="items-form" noValidate validated={validated} onSubmit={onSubmit}>
<Input name='email' type='email' placeholder='Введите почту' onChange={handleChange} value={user.email}></Input>
<Input name='password' type='password' placeholder='Введите пароль'onChange={handleChange} value={user.password}></Input>
<Button type='submit'>Войти</Button>
</Form>
</Container>
);
};
export default SignIn;

68
lab5/src/pages/SignUp.jsx Normal file
View File

@ -0,0 +1,68 @@
import { Container, Form, Button } from 'react-bootstrap';
import { useContext, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import toast from 'react-hot-toast';
import Input from '../components/input/Input.jsx';
import UserContext from '../components/users/UserContext.jsx';
import UsersApiService from '../components/users/UsersApiService';
const Signup = () => {
const [validated, setValidated] = useState(false);
const navigate = useNavigate();
const { user, setUser } = useContext(UserContext);
const onBack = () => {
navigate(-1);
};
const handleChange = (event) => {
const inputName = event.target.name;
const inputValue = event.target.type === 'checkbox' ? event.target.checked : event.target.value;
setUser({
...user,
[inputName]: inputValue,
});
};
const getUserObject = (formData) => {
const email = String(formData.email, 10);
const name = String(formData.name, 30);
const password = String(formData.password, 30);
return {
email: email.toString(),
name: name.toString(),
password: password.toString(),
};
};
const handleSubmit = async (event) => {
event.preventDefault();
event.stopPropagation();
const body = getUserObject(user);
if (user.id === '') {
await UsersApiService.create(body);
} else {
await UsersApiService.update(user.id, body);
}
if (body) {
toast.success('Пользователь зарегестрирован', { id: 'User' });
setValidated(true);
return true;
}
return false;
};
const onSubmit = async (event) => {
if (await handleSubmit(event)) {
onBack();
}
};
return (
<Container>
<Form id="items-form" noValidate validated={validated} onSubmit={onSubmit}>
<Input name='name' type='text' label='Имя' placeholder='Введите nick' required onChange={handleChange} value={user.name}></Input>
<Input name='email' type='email' label='Почта' placeholder='Введите почту' required onChange={handleChange} value={user.email}></Input>
<Input name='password' type='password' label='Пароль' placeholder='Введите пароль' required onChange={handleChange} value={user.password}></Input>
<Button type='submit'>Зарегистрироваться</Button>
</Form>
</Container>
);
};
export default Signup;

51
lab5/test.html Normal file
View File

@ -0,0 +1,51 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Stateful app</title>
<link rel="stylesheet" href="./node_modules/bootstrap/dist/css/bootstrap.css">
</head>
<body class="container-fluid p-2 col-12 col-md-8 col-lg-6">
<div class="card text-center mb-2">
<div class="card-title">
Переменная в глобальном контексте
</div>
<div class="card-body">
<div class="card-text" id="gc-content"></div>
<button class="btn btn-primary col-6 mt-2" onclick="updateGcContent(1)">Up</button>
</div>
</div>
<div class="card text-center">
<div class="card-title">
Переменная в хранилище
</div>
<div class="card-body">
<div class="card-text" id="ls-content"></div>
<button class="btn btn-primary col-6 mt-2" onclick="updateLsContent(1)">Up</button>
</div>
</div>
</body>
<script>
document.addEventListener('DOMContentLoaded', () => {
updateGcContent();
updateLsContent();
});
const updateGcContent = (value = 0) => {
const newState = (globalThis.myAppState || 0) + value;
globalThis.myAppState = newState;
document.getElementById('gc-content').innerText = newState;
}
const updateLsContent = (value = 0) => {
const lsKey = 'state';
const newState = parseInt(localStorage.getItem(lsKey) || 0) + value;
localStorage.setItem(lsKey, newState);
document.getElementById('ls-content').innerText = newState;
}
</script>
</html>

13
lab5/vite.config.js Normal file
View File

@ -0,0 +1,13 @@
/* eslint-disable import/no-extraneous-dependencies */
import react from '@vitejs/plugin-react';
import { defineConfig } from 'vite';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
build: {
sourcemap: true,
chunkSizeWarningLimit: 1024,
emptyOutDir: true,
},
});

Binary file not shown.