Готовая лабораторная работа 5 с отчётом

This commit is contained in:
Никита Белянин 2023-12-25 15:55:36 +04:00
parent 591129ee34
commit c489f9b4ed
72 changed files with 8387 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?

47
Lab5/README.md Normal file
View File

@ -0,0 +1,47 @@
### Окружение:
- [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. Updating Objects in State - https://react.dev/learn/updating-objects-in-state
2. Sharing State Between Components - https://react.dev/learn/sharing-state-between-components
3. React Hot Toast - https://react-hot-toast.com
4. Axios - https://axios-http.com
5. Axios & Error handling like a boss - https://dev.to/mperon/axios-error-handling-like-a-boss-333d
6. Separation of Concerns in React How to Use Container and Presentational Components - https://www.freecodecamp.org/news/separation-of-concerns-react-container-and-presentational-components/
7. Separation of concerns in React and React Native - https://dev.to/sathishskdev/separation-of-concerns-in-react-and-react-native-45b7
8. React Bootstrap - https://react-bootstrap.netlify.app
9. React Bootstrap Icons - https://github.com/ismamz/react-bootstrap-icons
10. JSON Server - https://www.npmjs.com/package/json-server

104
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="/src/assets/free-icon-home.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>My Website</title>
</head>
<body>
<div id="root" class="h-100 d-flex flex-column"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>

15
Lab5/jsconfig.json Normal file
View File

@ -0,0 +1,15 @@
{
"compilerOptions": {
"module": "ESNext",
"moduleResolution": "Node",
"target": "ES2020",
"jsx": "react",
"strictNullChecks": true,
"strictFunctionTypes": true,
"sourceMap": 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"
}
}

3
Lab5/public/favicon.svg Normal file
View File

@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-cart2" viewBox="0 0 16 16">
<path d="M0 2.5A.5.5 0 0 1 .5 2H2a.5.5 0 0 1 .485.379L2.89 4H14.5a.5.5 0 0 1 .485.621l-1.5 6A.5.5 0 0 1 13 11H4a.5.5 0 0 1-.485-.379L1.61 3H.5a.5.5 0 0 1-.5-.5zM3.14 5l1.25 5h8.22l1.25-5H3.14zM5 13a1 1 0 1 0 0 2 1 1 0 0 0 0-2zm-2 1a2 2 0 1 1 4 0 2 2 0 0 1-4 0zm9-1a1 1 0 1 0 0 2 1 1 0 0 0 0-2zm-2 1a2 2 0 1 1 4 0 2 2 0 0 1-4 0z"/>
</svg>

After

Width:  |  Height:  |  Size: 463 B

BIN
Lab5/src/assets/exit.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.1 KiB

View File

@ -0,0 +1,240 @@
.cartadvert-image {
height: 500px;
}
.card{
padding:0 !important;
}
.carousel{
padding:0 !important;
}
.cart-item {
height: auto;
}
.cart-text{
color: White;
font-size: 32px;
}
.textlinkcart{
color: white;
}
.textus5{
color: Black;
font-size: 42px;
}
.textus4{
color: Black;
font-size: 38px;
}
.textus3{
color: Black;
font-size: 32px;
}
.textus33{
color: Black;
font-size: 24px;
}
@media(max-width: 1200px) {
.textus5{
color: Black;
font-size: 38px;
}
.textus4{
color: Black;
font-size: 34px;
}
.textus3{
color: Black;
font-size: 28px;
}
.textus33{
color: Black;
font-size: 20px;
}
}
@media(max-width: 900px) {
.textus5{
color: Black;
font-size: 32px;
}
.textus4{
color: Black;
font-size: 30px;
}
.textus3{
color: Black;
font-size: 24px;
}
.textus33{
color: Black;
font-size: 16px;
}
}
@media(max-width: 700px) {
.cartadvert-image {
height: 420px;
}
.textus5{
color: Black;
font-size: 26px;
}
.textus4{
color: Black;
font-size: 22px;
}
.textus3{
color: Black;
font-size: 20px;
}
.textus33{
color: Black;
font-size: 14px;
}
}
@media(max-width: 600px) {
.textus5{
color: Black;
font-size: 20px;
}
.textus4{
color: Black;
font-size: 18px;
}
.textus3{
color: Black;
font-size: 14px;
}
.textus33{
color: Black;
font-size: 14px;
}
}
@media(max-width: 550px) {
.cartadvert-image {
height: 380px;
}
.textus5{
color: Black;
font-size: 20px;
}
.textus4{
color: Black;
font-size: 18px;
}
.textus3{
color: Black;
font-size: 14px;
}
.textus33{
color: Black;
font-size: 14px;
}
}
@media(max-width: 480px) {
.cartadvert-image {
height: 320px;
}
.buttord1{
height: 40px;
font-size: 12px;
}
.textus5{
color: Black;
font-size: 16px;
}
.textus4{
color: Black;
font-size: 15px;
}
.textus3{
color: Black;
font-size: 12px;
}
.textus33{
color: Black;
font-size: 12px;
}
}
@media(max-width: 384px) {
.buttback{
width: 80px;
height: 60px;
font-size: 10px;
}
.cartadvert-image {
height: 240px;
}
.textus5{
color: Black;
font-size: 12px;
}
.textus4{
color: Black;
font-size: 10px;
}
.textus3{
color: Black;
font-size: 8px;
}
.textus33{
color: Black;
font-size: 8px;
}
}
@media(max-width: 320px) {
.cartadvert-image {
height: 160px;
}
}
@media(max-width:290px) {
.cartadvert-image{
display: none;;
}
}

View File

@ -0,0 +1,61 @@
import { Button, Card } from 'react-bootstrap';
import { Link, useNavigate } from 'react-router-dom';
import { XLg } from 'react-bootstrap-icons';
import imgPlaceholder from '../../assets/200.png';
import './CartAdvert.css';
import useCart from './CartAdvertHook';
const CartAdvert = () => {
const {
cartAdvert,
clearAdvertCart,
} = useCart();
const ForwardGoOrder = useNavigate();
const GoOrder = () => {
ForwardGoOrder('/pageOrder');
};
const GoBack = () => {
clearAdvertCart();
ForwardGoOrder('/pageMyBulletin');
};
return (
<div className='d-flex flex-column align-items-center'>
<div className='mb-2 col-12 col-md-8 col-lg-6 d-flex align-items-center'>
<strong className='flex-fill col-3 cart-text'> Объявление </strong>
<Button className='w-25 buttback' variant='danger' onClick={() => GoBack() } type='submit'>
<XLg /> <Link to="/pageMyBulletin" className='textlinkcart'> Вернуться назад </Link>
</Button>
</div>
{
cartAdvert.map((cartItem) =>
<Card key={cartItem.id} className='mb-2 w-100'>
<Card.Body className='p-2 d-flex'>
<div className='cart-item flex-fill'>
<img className='cartadvert-image w-100' src={cartItem.image || imgPlaceholder} alt="Cart Image" />
</div>
<div className='cart-item mt-2 mt-sm-0 d-flex flex-column align-items-center'>
<div className='col ps-4 pe-4'>
<p className='textus4'> {cartItem.type.name} </p>
<p className='mt-2 textus5'> Описание объявления</p>
<p className='textus3'> {cartItem.description} </p>
<p className='textus3'> Цена: {cartItem.price} рублей</p>
<p className='textus3'> Номер телефона: +7(900)-785-84-56 </p>
<Button className='buttord1' onSubmit={GoOrder} variant="success" onClick={() => clearAdvertCart()} type="submit">
<Link to="/OrderPage" className='textlinkcart'> Оформить заказ </Link>
</Button>
</div>
</div>
</Card.Body>
</Card>)
}
</div>
);
};
export default CartAdvert;

View File

@ -0,0 +1,29 @@
import PropTypes from 'prop-types';
import {
createContext,
useEffect,
useReducer,
} from 'react';
import { cartReducer, loadCart, saveCart } from './CartAdvertReducer';
const AdvertContext = createContext(null);
export const AdvertProvider = ({ children }) => {
const [cartAdvert, dispatch] = useReducer(cartReducer, [], loadCart);
useEffect(() => {
saveCart(cartAdvert || []);
}, [cartAdvert]);
return (
<AdvertContext.Provider value={{ cartAdvert, dispatch }}>
{children}
</AdvertContext.Provider>
);
};
AdvertProvider.propTypes = {
children: PropTypes.node,
};
export default AdvertContext;

View File

@ -0,0 +1,26 @@
import { useContext } from 'react';
import CartContext from './CartAdvertContext.jsx';
import { cartAdd, cartClear, cartRemove } from './CartAdvertReducer';
const useAdvertCart = () => {
const { cartAdvert, dispatch } = useContext(CartContext);
const cartSum = () => {
return parseFloat(
cartAdvert?.reduce((sum, cartItem) => {
return sum + (cartItem.price * cartItem.count);
}, 0)
?? 0,
).toFixed(2);
};
return {
cartAdvert,
getCartSum: () => cartSum(),
addToAdvertCart: (item) => dispatch(cartAdd(item)),
removeAdvertFromCart: (item) => dispatch(cartRemove(item)),
clearAdvertCart: () => dispatch(cartClear()),
};
};
export default useAdvertCart;

View File

@ -0,0 +1,71 @@
const setCartCount = (cartAdvert, item) => {
return cartAdvert.map((cartItem) => {
if (cartItem.id === item.id) {
return { ...cartItem, count: cartItem.count };
}
return cartItem;
});
};
const addToCart = (cartAdvert, item) => {
const existsItem = cartAdvert.find((cartItem) => cartItem.id === item.id);
if (existsItem !== undefined) {
return setCartCount(cartAdvert, item, 1);
}
return [...cartAdvert, { ...item, count: 1 }];
};
const removeFromCart = (cartAdvert, item) => {
const existsItem = cartAdvert.find((cartItem) => cartItem.id === item.id);
if (existsItem !== undefined && existsItem.count > 1) {
return setCartCount(cartAdvert, item, -1);
}
return cartAdvert.filter((cartItem) => cartItem.id !== item.id);
};
const CART_KEY = 'localAdvertCart';
const CART_ADD = 'cart/add';
const CART_REMOVE = 'cart/remove';
const CART_CLEAR = 'cart/clear';
export const saveCart = (cartAdvert) => {
localStorage.setItem(CART_KEY, JSON.stringify(cartAdvert));
};
export const loadCart = (initialValue = []) => {
const cartDataNew = localStorage.getItem(CART_KEY);
if (cartDataNew) {
return JSON.parse(cartDataNew);
}
return initialValue;
};
export const cartReducer = (cartAdvert, action) => {
const { item } = action;
switch (action.type) {
case CART_ADD: {
return addToCart(cartAdvert, item);
}
case CART_REMOVE: {
return removeFromCart(cartAdvert, item);
}
case CART_CLEAR: {
return [];
}
default: {
throw Error(`Unknown action: ${action.type}`);
}
}
};
export const cartAdd = (item) => ({
type: CART_ADD, item,
});
export const cartRemove = (item) => ({
type: CART_REMOVE, item,
});
export const cartClear = () => ({
type: CART_CLEAR,
});

View File

@ -0,0 +1,25 @@
#banner {
margin: 2px;
display: flex;
align-items: center;
flex-direction: column;
}
#banner img {
border: 1px solid #3c3c3f;
border-radius: 5px;
}
#banner img.banner-show {
width: 100%;
opacity: 1;
transition: opacity 1s, visibility 0s;
}
#banner img.banner-hide {
height: 0;
width: 0;
opacity: 0;
visibility: hidden;
transition: opacity 1s, visibility 0s 1s;
}

View File

@ -0,0 +1,17 @@
import './Banner.css';
import useBannerHook from './BannerHook';
const Banner = () => {
const { banners, getBannerClass } = useBannerHook();
return (
<div id="banner" >
{
banners.map((banner, index) =>
<img key={index} className={getBannerClass(index)} src={banner} alt={`banner${index}`} />)
}
</div >
);
};
export default Banner;

View File

@ -0,0 +1,37 @@
import { useEffect, useState } from 'react';
import banner1 from '../../assets/Image3.png';
import banner2 from '../../assets/Image4.png';
import banner3 from '../../assets/Image5.png';
import './Banner.css';
const useBannerHook = () => {
const [currentBanner, setCurrentBanner] = useState(0);
const banners = [banner1, banner2, banner3];
const getBannerClass = (index) => {
return currentBanner === index ? 'banner-show' : 'banner-hide';
};
useEffect(() => {
const bannerInterval = setInterval(
() => {
console.info('Banner changed');
let current = currentBanner + 1;
if (current === banners.length) {
current = 0;
}
setCurrentBanner(current);
},
5000,
);
return () => clearInterval(bannerInterval);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return {
banners,
getBannerClass,
};
};
export default useBannerHook;

View File

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

View File

@ -0,0 +1,35 @@
import { useEffect, useState } from 'react';
import LinesApiService from '../../types/service/FavoritesApi';
const useLinesFavorites = (id) => {
const emptyItem = {
id: '',
typeId: '',
price: '0',
count: '1',
description: '',
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 useLinesFavorites;

View File

@ -0,0 +1,67 @@
import { useState } from 'react';
import toast from 'react-hot-toast';
import LinesApiService from '../../types/service/FavoritesApi';
import useLinesItem from './LinesItemFavorites';
const useLinesItemOrder = (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).toFixed(2);
const count = parseInt(formData.count, 10);
const description = String(formData.description, 30);
const image = formData.image.startsWith('data:image') ? formData.image : '';
return {
typeId: typeId.toString(),
price: price.toString(),
count: count.toString(),
description: description.toString(),
image,
};
};
const handleChange = (event) => {
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: 'user' });
return true;
}
setValidated(true);
return false;
};
return {
item,
validated,
handleSubmit,
handleChange,
resetValidity,
};
};
export default useLinesItemOrder;

View File

@ -0,0 +1,7 @@
.my-footer {
background-color: #636363;
padding-top: 15px;
padding-bottom: 15px;
height: 64px;
color: #fff;
}

View File

@ -0,0 +1,15 @@
import './Footer.css';
const Footer = () => {
const year = new Date().getFullYear();
return (
<footer className="my-footer mt-auto fixed bottom-0 w-100">
<div className="copywriter p-2">
&copy; {year} UlRent Белянин Никита ПИбд-21 | Все права защищены ;)
</div>
</footer>
);
};
export default Footer;

View File

@ -0,0 +1,49 @@
import PropTypes from 'prop-types';
import { Button, Form } from 'react-bootstrap';
import { useNavigate } from 'react-router-dom';
import useLinesItemForm from '../hooks/LinesItemOrderHook';
import LinesItemForm from './LinesItemFormOrder.jsx';
import './LinesItemFormOrder.css';
const LinesForm = ({ id }) => {
const navigate = useNavigate();
const {
item,
validated,
handleSubmit,
handleChange,
} = useLinesItemForm(id);
const onBack = () => {
navigate('/pageMyBulletin');
};
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,24 @@
import PropTypes from 'prop-types';
import Input from '../../input/Input.jsx';
import './LinesItemFormOrder.css';
const LinesItemForm = ({ item, handleChange }) => {
return (
<>
<div className='w-50 col-md-8 offset-md-3'>
<Input name='descriptionName' label='Имя' value={item.descriptionName} onChange={handleChange} type='text' required />
<Input name='descriptionSurname' label='Фамилия' value={item.descriptionSurname} onChange={handleChange} type='text' required />
<Input name='descriptiondate' label='Дата' value={item.descriptiondate} onChange={handleChange} type='date' required />
<Input name='descriptionNumberCard' label='Номер карты' value={item.descriptionNumberCard} onChange={handleChange} type='text' required />
<Input name='descriptionCVC' label='CVC' value={item.descriptionCVC} onChange={handleChange} type='text' required />
</div>
</>
);
};
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).toFixed(2);
const count = parseInt(formData.count, 10);
const sum = parseFloat(price * count).toFixed(2);
const description = String(formData.description, 30);
const image = formData.image.startsWith('data:image') ? formData.image : '';
return {
typeId: typeId.toString(),
price: price.toString(),
count: count.toString(),
sum: sum.toString(),
description: description.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,35 @@
import { useEffect, useState } from 'react';
import LinesApiService from '../service/LinesApiService';
const useLinesItem = (id) => {
const emptyItem = {
id: '',
typeId: '',
price: '0',
count: '1',
description: '',
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 '../order/LinesApiOrder';
const useLinesOrder = (id) => {
const emptyItem = {
id: '',
descriptionName: '',
descriptionSurname: '',
typeId: '',
descriptionNumberCard: '',
};
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 useLinesOrder;

View File

@ -0,0 +1,67 @@
import { useState } from 'react';
import toast from 'react-hot-toast';
import LinesApiService from '../order/LinesApiOrder';
import useLinesItem from './LinesItemOrder';
const useLinesItemOrder = (id, linesChangeHandle) => {
const { item, setItem } = useLinesItem(id);
const [validated, setValidated] = useState(false);
const resetValidity = () => {
setValidated(false);
};
const getLineObject = (formData) => {
const descriptionName = String(formData.descriptionName, 10);
const descriptionSurname = String(formData.descriptionSurname, 10);
const descriptiondate = String(formData.descriptiondate, 20);
const descriptionNumberCard = String(formData.descriptionNumberCard, 30);
const descriptionCVC = String(formData.descriptionCVC, 30);
return {
descriptionName: descriptionName.toString(),
descriptionSurname: descriptionSurname.toString(),
descriptiondate: descriptiondate.toString(),
descriptionNumberCard: descriptionNumberCard.toString(),
descriptionCVC: descriptionCVC.toString(),
};
};
const handleChange = (event) => {
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 useLinesItemOrder;

View File

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

View File

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

View File

@ -0,0 +1,64 @@
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 useLinesDeleteModal from '../hooks/LinesDeleteModalHook';
import useTypeFilter from '../hooks/LinesFilterHook';
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 navigate = useNavigate();
const showEditPage = (id) => {
navigate(`/page-edit/${id}`);
};
return (
<>
<div className="TitleMyBulletin">
<p> Администратор </p>
</div>
<ButtonGroup className='ms-5'>
<Button as={Link} to='/page-edit' variant='success'>
Добавить товар (страница)
</Button>
</ButtonGroup>
<Button type="button" className="btn1 btn-info me-5 ms-5 mt-5 mb-5" >
<Link to='/pageMyBulletin' className='textlinkButMy mt-4'> Лента объявлений </Link>
</Button>
<Select className='ms-5 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='Удалить элемент?' />
</>
);
};
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 fluid className='container-fluid mt-5 mb-5'>
<div className='mt-2'> <Row> {children} </Row> </div>
</Container>
);
};
LinesTable.propTypes = {
children: PropTypes.node,
};
export default LinesTable;

View File

@ -0,0 +1,43 @@
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import { Button, Row, Col } from 'react-bootstrap';
import { PencilSquare, Trash3 } from 'react-bootstrap-icons';
const LinesTableRow = ({
line, onDelete, onEditInPage,
}) => {
const handleAnchorClick = (event, action) => {
event.preventDefault();
action();
};
return (
<div className="col pb-5">
<div className="card mx-auto">
<img src={line.image} alt='image'></img>
<div className="card-body">
<h5 className="card-title"> {line.type.name} </h5>
<p className="card-text"> {line.description} </p>
<Row className='row'>
<Button type="button" className="btn1">
<Link to='/page5' className='textlinkBut mt-4'> {parseFloat(line.price).toFixed(2)} </Link>
</Button>
</Row>
<Row className='mx-auto text-center mt-3'>
<Col> <a href="#" onClick={(event) => handleAnchorClick(event, onEditInPage)}><PencilSquare /></a> </Col>
<Col> <a href="#" onClick={(event) => handleAnchorClick(event, onDelete)}><Trash3 /></a> </Col>
</Row>
</div>
</div>
</div>
);
};
LinesTableRow.propTypes = {
index: PropTypes.number,
line: PropTypes.object,
onDelete: PropTypes.func,
onEditInPage: PropTypes.func,
};
export default LinesTableRow;

View File

@ -0,0 +1,56 @@
import { Button } from 'react-bootstrap';
import { Link } from 'react-router-dom';
import Select from '../../input/Select.jsx';
import useTypeFilter from '../hooks/LinesFilterHook';
import useLines from '../hooks/LinesHook';
import LinesTable from './LinesTable.jsx';
import LinesTableRow from './LinesTableRow.jsx';
import useCart from '../../cart/CartHook';
import { GetUserId } from '../../login/users/UserReducer';
import useAdvertCart from '../../advert/CartAdvertHook';
const Lines = () => {
const { types, currentFilter, handleFilterChange } = useTypeFilter();
const { lines } = useLines(currentFilter);
const { addToCart } = useCart();
const { addToAdvertCart, clearAdvertCart } = useAdvertCart();
const id = GetUserId();
console.log(id);
// const id = localStorage.getItem('UserId');
// const data = await LinesApiService.getUser(id);
// const data = await LinesApiService.get(itemId);
return (
<>
<div className="TitleMyBulletin">
<p>Лента Объявлений</p>
</div>
<Button type="button" className="btn1 btn-info me-5 ms-5 mt-2 mb-1" >
<Link to='/page1' className='textlinkButMy mt-4'> Администрация </Link>
</Button>
<Select className='ms-4 mt-2' values={types} label='Фильтр по объявлениям'
value={currentFilter} onChange={handleFilterChange} />
<LinesTable>
{
lines.map((line, index) =>
<LinesTableRow key={line.id}
index={index} line={line}
onAddAdvertCart={() => addToAdvertCart(line)}
clearCartAdvert={() => clearAdvertCart(line)}
onAddCart={() => addToCart(line)}
/>)
}
</LinesTable>
</>
);
};
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 fluid className='container-fluid mt-5 mb-5'>
<div className='mt-2'> <Row> {children} </Row> </div>
</Container>
);
};
LinesTable.propTypes = {
children: PropTypes.node,
};
export default LinesTable;

View File

@ -0,0 +1,56 @@
import PropTypes from 'prop-types';
import { Link, useNavigate } from 'react-router-dom';
import { Button, Row, Col } from 'react-bootstrap';
const LinesTableRow = ({
line, onAddCart, onAddAdvertCart, clearCartAdvert,
}) => {
const handleAnchorClick = (event, action) => {
event.preventDefault();
action();
};
const Go = useNavigate();
const GoNext = () => {
Go('/page5');
};
const handleCart = (eventcart, addcart, actioncart) => {
GoNext();
clearCartAdvert();
onAddAdvertCart();
eventcart.preventDefault();
actioncart();
};
return (
<div className="col pb-5">
<div className="card mx-auto">
<img src={line.image} alt='image'></img>
<div className="card-body">
<h5 className="card-title"> {line.type.name} </h5>
<p className="card-text"> {(line.description)} </p>
<Row className='row'>
<Button type="button" className="btn1" onClick={(eventcart) => handleCart(eventcart, clearCartAdvert, onAddAdvertCart, GoNext) }>
<Link to='/page5' className='textlinkBut mt-4'> {parseFloat(line.price).toFixed(2)} </Link>
</Button>
<Col className='text-center mt-3'> <a href="#" onClick={(event) => handleAnchorClick(event, onAddCart)}> <i className="fa fa-home" aria-hidden="true"> Добавить в избранное </i> </a> </Col>
</Row>
</div>
</div>
</div>
);
};
LinesTableRow.propTypes = {
id: PropTypes.string,
index: PropTypes.number,
line: PropTypes.object,
onAddCart: PropTypes.func,
onAddAdvertCart: PropTypes.func,
clearCartAdvert: PropTypes.func,
};
export default LinesTableRow;

View File

@ -0,0 +1,55 @@
/* eslint-disable import/extensions */
/* eslint-disable import/no-unresolved */
import { Button, Form, Nav } from 'react-bootstrap';
import { useNavigate, Link } from 'react-router-dom';
import useLinesItemForm from '../hooks/LoginFormHook';
import LinesItemForm from './LoginItemForm';
import useUser from '../users/UserCardHook';
const LoginForm = () => {
const navigate = useNavigate();
const {
SetUserId,
} = useUser();
const {
item,
validated,
handleSubmit,
handleChange,
} = useLinesItemForm();
const onBack = () => {
navigate('/pageMyBulletin');
};
const SetLogin = () => {
SetUserId();
};
const onSubmit = async (event) => {
if (await handleSubmit(event)) {
onBack();
}
};
return (
<>
<Form className="col-md-6 m-0" noValidate validated={validated} onSubmit={onSubmit}>
<Form.Group className="mb-2" controlId="lastname">
<LinesItemForm item={item} handleChange={handleChange} />
</Form.Group>
<Nav.Link as={Link} to ="/SignIn">Нет аккаунта? Зарегистрироваться</Nav.Link>
<div className="d-grid gap-2 pt-5 mx-auto w-100">
<Button className="w-50 btnLog btn btn-light mx-auto" variant="primary" type="submit" onClick={() => SetLogin()}>
<Link to="/page1" className='textlink'> Войти </Link>
</Button>
</div>
</Form>
</>
);
};
export default LoginForm;

View File

@ -0,0 +1,19 @@
import PropTypes from 'prop-types';
import Input from '../../input/Input.jsx';
const LinesItemForm = ({ item, handleChange }) => {
return (
<>
<Input name='Email' label='Введите ваш логин' value={item.Email} onChange={handleChange}
type='Email' required />
<Input name='password' label='Введите пароль' value={item.password} onChange={handleChange} type='password' required />
</>
);
};
LinesItemForm.propTypes = {
item: PropTypes.object,
handleChange: PropTypes.func,
};
export default LinesItemForm;

View File

@ -0,0 +1,71 @@
import { useState } from 'react';
import useLinesItem from './LoginItemHook';
import useLines from './UsersHook';
import { SetUserId } from '../users/UserReducer';
const useLinesItemForm = (id) => {
const { item, setItem } = useLinesItem(id);
const { users } = useLines();
const [validated, setValidated] = useState(false);
const resetValidity = () => {
setValidated(false);
};
const getLineObject = (formData) => {
const Email = formData.Email.toString();
const password = formData.password.toString();
return {
Email: Email.toString(),
password: password.toString(),
};
};
const handleChange = (event) => {
const inputName = event.target.name;
const inputValue = event.target.type === 'checkbox' ? event.target.checked : event.target.value;
setItem({
...item,
[inputName]: inputValue,
});
localStorage.setItem('Email', event.target.value);
};
const handleSubmit = async (event) => {
const form = event.currentTarget;
event.preventDefault();
event.stopPropagation();
let userId = null;
const body = getLineObject(item);
users.map((line) => {
if ((line.Email === body.Email) && (line.password === body.password)) {
SetUserId(line.id);
userId = true;
return null;
}
return null;
});
if (form.checkValidity()) {
if (userId === true) {
return true;
// eslint-disable-next-line no-else-return
} else {
console.log('we dont have');
return false;
}
}
setValidated(true);
return false;
};
return {
item,
validated,
handleSubmit,
handleChange,
resetValidity,
};
};
export default useLinesItemForm;

View File

@ -0,0 +1,17 @@
import { useState } from 'react';
const useLinesItem = () => {
const emptyItem = {
id: '',
Email: '',
password: '',
};
const [item, setItem] = useState({ ...emptyItem });
return {
item,
setItem,
};
};
export default useLinesItem;

View File

@ -0,0 +1,24 @@
import { useEffect, useState } from 'react';
import LinesApiService from '../../sign/LinesApiSign';
const useLines = (typeFilter) => {
const [linesRefresh, setLinesRefresh] = useState(false);
const [users, setLines] = useState([]);
const handleLinesChange = () => setLinesRefresh(!linesRefresh);
const getLines = async () => {
const data = await LinesApiService.getAll();
setLines(data ?? []);
};
useEffect(() => {
getLines();
}, [linesRefresh, typeFilter]);
return {
users,
handleLinesChange,
};
};
export default useLines;

View File

@ -0,0 +1,16 @@
import { useContext } from 'react';
import UserUseContext from './UserContext.jsx';
import { userAdd, userRemove } from './UserReducer';
const useUser = () => {
const { User, dispatch } = useContext(UserUseContext);
return {
User,
SetUserId: (user) => dispatch(userAdd(user)),
ExitUsedId: () => dispatch(userRemove()),
GetUserId: User?.id || -1,
};
};
export default useUser;

View File

@ -0,0 +1,29 @@
import PropTypes from 'prop-types';
import {
createContext,
useEffect,
useReducer,
} from 'react';
import { cartReducer, loadUser, saveUser } from './UserReducer';
export const UserContext = createContext(null);
export const UserProvider = ({ children }) => {
const [User, dispatch] = useReducer(cartReducer, null, loadUser);
useEffect(() => {
saveUser(User || []);
}, [User]);
return (
<UserContext.Provider value={{ User, dispatch }}>
{children}
</UserContext.Provider>
);
};
UserProvider.propTypes = {
children: PropTypes.node,
};
export default UserContext;

View File

@ -0,0 +1,64 @@
const USER_KEY = 'localUser';
const USER_ADD = 'user/add';
const USER_REMOVE = 'user/remove';
const USER_VIEW = 'user/view';
const SetUserId = (user) => {
return localStorage.setItem(USER_KEY, user);
};
export const GetUserId = () => {
const usid = localStorage.getItem(USER_KEY);
return usid;
};
const ExitUsedId = () => {
const UserId = -1;
localStorage.setItem(USER_KEY, UserId);
// localStorage.getItem(USER_KEY);
return localStorage.getItem(USER_KEY, UserId);
};
export { SetUserId, ExitUsedId };
export const saveUser = () => {
return SetUserId;
};
export const loadUser = (initialValue = -1) => {
const userDataNew = localStorage.getItem(USER_KEY);
if (userDataNew) {
return GetUserId;
}
return initialValue;
};
export const cartReducer = (user, action) => {
const { item } = action;
switch (action.type) {
case USER_ADD: {
return SetUserId(user, item);
}
case USER_REMOVE: {
return ExitUsedId(user, item);
}
case USER_VIEW: {
return loadUser();
}
default: {
throw Error(`Unknown action: ${action.type}`);
}
}
};
export const userAdd = (user, item) => ({
type: USER_ADD, user, item,
});
export const userRemove = (item) => ({
type: USER_REMOVE, item,
});
export const userViews = (item) => ({
type: USER_VIEW, item,
});

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,77 @@
.navbar{
background-color: #85DADA !important;
}
.my-navbar {
background-color: #85DADA !important;
}
.my-navbar .link a:hover {
text-decoration: underline !important;
}
.my-navbar .logo {
width: 20px;
height: 20px;
}
.logo{
width: 100px;
height: 80px;
}
.main-navbar{
font-size: 24px;
justify-content: end;
}
.Name{
color: #ffffff;
font-size: 24px;
text-decoration: none;
}
@media (max-width: 600px) {
.logo{
width: 80px;
height: 60px;
}
.Name{
font-size: 22px;
}
}
@media (max-width: 360px){
.Name{
font-size: 20px;
}
.logo{
width: 60px;
height: 50px;
}
}
@media (max-width: 300px){
.logo{
width: 50px;
height: 50px;
}
}
@media (max-width: 270px){
.Name{
font-size: 14px;
}
.logo{
width: 50px;
height: 40px;
}
.copywriter{
font-size: 14px;
}
}

View File

@ -0,0 +1,53 @@
import PropTypes from 'prop-types';
import {
Container, Nav, Navbar, NavbarCollapse, NavbarToggle,
} from 'react-bootstrap';
import { Link, useLocation } from 'react-router-dom';
import Logo from '../../assets/Image1.png';
import { ExitUsedId } from '../login/users/UserReducer';
import './Navigation.css';
const Navigation = ({ routes }) => {
const location = useLocation();
const indexPageLink = routes.filter((route) => route.index === false).shift();
const pages = routes.filter((route) => Object.prototype.hasOwnProperty.call(route, 'title'));
const Exit = () => {
ExitUsedId(-1);
};
return (
<header>
<Navbar expand='md' bg='dark' data-bs-theme='dark' className='navbar navbar-expand-md navbar-dark'>
<Container fluid>
<Navbar.Brand as={Link} to={indexPageLink?.path ?? '/'}>
<img src={Logo} className="logo me-5" alt="логотип" />
</Navbar.Brand>
<Navbar className='Name' as={Link} to={indexPageLink?.path ?? '/'}>
<div className="Name"> UlRent </div>
</Navbar>
<NavbarToggle aria-controls='main-navbar' />
<NavbarCollapse className="justify-content-end me-5" id='main-navbar '>
<Nav className='main-navbar' activeKey={location.pathname}>
{
pages.map((page) =>
<Nav.Link as={Link} key={page.path} eventKey={page.path} to={page.path ?? '/'}>
{page.title}
</Nav.Link>)
}
<Nav.Link as={Link} to ="/logIn" aria-current="page">
<img src="src/assets/exit.png" alt="home" width ="40" height ="40" onClick={Exit}/>
</Nav.Link>
</Nav>
</NavbarCollapse>
</Container>
</Navbar >
</header>
);
};
Navigation.propTypes = {
routes: PropTypes.array,
};
export default Navigation;

View File

@ -0,0 +1,46 @@
import PropTypes from 'prop-types';
import { Button, Form } from 'react-bootstrap';
import { useNavigate } from 'react-router-dom';
import useLinesItemForm from '../hooks/LinesItemSignHook';
import LinesItemForm from './LinesItemFormSign.jsx';
import './LinesItemFormSign.css';
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-2 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,23 @@
import PropTypes from 'prop-types';
import Input from '../../input/Input.jsx';
import './LinesItemFormSign.css';
const LinesItemForm = ({ item, handleChange }) => {
return (
<>
<div className='w-50 col-md-8 offset-md-3'>
<Input name='Name' label='Как пользователям к вам обращаться' placeholder='Ваше имя и фамилия' value={item.Name} onChange={handleChange} type='text' required />
<Input name='Email' label='Ваш Логин' placeholder='Электронная почта' value={item.Email} onChange={handleChange} type='email' required />
<Input name='NumberPhone' label='Номер телефона' placeholder='Только мобильный телефон' value={item.NumberPhone} onChange={handleChange} type='text' minLength='11' maxLength='11' required />
<Input name='password' label='Пароль' placeholder='от 6 до 16 символов' value={item.password} onChange={handleChange} type='text' required />
</div>
</>
);
};
LinesItemForm.propTypes = {
item: PropTypes.object,
handleChange: PropTypes.func,
};
export default LinesItemForm;

View File

@ -0,0 +1,35 @@
import { useEffect, useState } from 'react';
import LinesApiService from '../../sign/LinesApiSign';
const useLinesOrder = (id) => {
const emptyItem = {
id: '',
Name: '',
Email: '',
typeId: '',
NumberPhone: '',
password: '',
};
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 useLinesOrder;

View File

@ -0,0 +1,65 @@
import { useState } from 'react';
import toast from 'react-hot-toast';
import LinesApiService from '../../sign/LinesApiSign';
import useLinesItem from './LinesItemSign';
const useLinesItemOrder = (id, linesChangeHandle) => {
const { item, setItem } = useLinesItem(id);
const [validated, setValidated] = useState(false);
const resetValidity = () => {
setValidated(false);
};
const getLineObject = (formData) => {
const Name = String(formData.Name, 30);
const Email = String(formData.Email, 30);
const NumberPhone = String(formData.NumberPhone, 30);
const password = String(formData.password, 30);
return {
Name: Name.toString(),
Email: Email.toString(),
NumberPhone: NumberPhone.toString(),
password: password.toString(),
};
};
const handleChange = (event) => {
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: 'user' });
return true;
}
setValidated(true);
return false;
};
return {
item,
validated,
handleSubmit,
handleChange,
resetValidity,
};
};
export default useLinesItemOrder;

View File

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

View File

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

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 FavouritesLinesApi = new ApiService('favourites');
export default FavouritesLinesApi;

View File

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

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;

View File

@ -0,0 +1,34 @@
// let UserId;
// const SetUserId = (id) => {
// UserId = id;
// localStorage.setItem('UserId', UserId);
// };
// const GetUserId = () => {
// const usid = localStorage.getItem('UserId');
// return usid;
// };
// const ExitUsedId = () => {
// UserId = -1;
// localStorage.setItem('UserId', UserId);
// localStorage.getItem('UserId');
// return localStorage.getItem('UserId', UserId);
// };
// export { SetUserId, GetUserId, ExitUsedId };
// export const saveLogin = () => {
// localStorage.setItem('UserId', UserId);
// // console.log(UserId);
// };
// export const getLogin = () => {
// localStorage.getItem('UserId', UserId);
// };
// // // const data = await LinesApiService.getUser();
// // // console.log(UserId);
// // // console.log(data[0]);
// // // console.log(localStorage.getItem('UserId'));

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,
},
});