Начало 5-ой

This commit is contained in:
DyCTaTOR 2023-12-17 19:27:47 +04:00
parent 3c0cee9c79
commit f6f3c8fa1b
54 changed files with 3095 additions and 270 deletions

View File

@ -1,9 +1,14 @@
#### Окружение:
- nodejs 18;
- VSCode;
- ESLint плагин для VSCode;
### Окружение:
- [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
@ -16,14 +21,24 @@ npm create vite@latest ./ -- --template react
npm install
```
#### Запуск проекта:
#### Запуск проекта в режиме разработки (development):
```commandline
npm run dev
```
#### Сборка проекта:
#### Запуск проекта в продуктовом режиме (production):
```commandline
npm run build
```
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

Binary file not shown.

74
Lab5/data.json Normal file

File diff suppressed because one or more lines are too long

View File

@ -5,7 +5,8 @@
"target": "ES2020",
"jsx": "react",
"strictNullChecks": true,
"strictFunctionTypes": true
"strictFunctionTypes": true,
"sourceMap": true
},
"exclude": [
"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"
}

1868
Lab5/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,18 +1,21 @@
{
"name": "ulstu",
"name": "lec4",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview"
"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",
@ -20,13 +23,16 @@
},
"devDependencies": {
"@types/react": "^18.2.15",
"@types/react-dom": "^18.2.7",
"@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

View File

View File

@ -1,19 +1,21 @@
import PropTypes from 'prop-types';
import { Container } from 'react-bootstrap';
import { Toaster } from 'react-hot-toast';
import { Outlet } from 'react-router-dom';
import './App.css';
import { CartProvider } from './components/cart/CartContext.jsx';
import Footer from './components/footer/Footer.jsx';
import Navigation from './components/navigation/Navigation.jsx';
const App = ({ routes }) => {
return (
<>
<CartProvider>
<Navigation routes={routes}></Navigation>
<Container className='p-2' as="main" fluid>
<Container className='p-2' as='main' fluid>
<Outlet />
</Container>
<Footer />
</>
<Toaster position='top-center' reverseOrder={true} />
</CartProvider>
);
};

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

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,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,36 @@
import { useEffect, useState } from 'react';
import banner1 from '../../assets/banner1.png';
import banner2 from '../../assets/banner2.png';
import banner3 from '../../assets/banner3.png';
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,8 @@
.cart-image {
width: 3.1rem;
padding: .25rem;
}
.cart-item {
height: auto;
}

View File

@ -0,0 +1,59 @@
import { Button, ButtonGroup, Card } from 'react-bootstrap';
import { DashLg, PlusLg, XLg } from 'react-bootstrap-icons';
import imgPlaceholder from '../../assets/200.png';
import './Cart.css';
import useCart from './CartHook';
const Cart = () => {
const {
cart,
getCartSum,
addToCart,
removeFromCart,
clearCart,
} = useCart();
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'>Корзина</strong>
<Button variant='danger' onClick={() => clearCart()}>
<XLg /> Очистить
</Button>
</div>
{
cart.map((cartItem) =>
<Card key={cartItem.id} className='mb-2 col-12 col-md-8 col-lg-6'>
<Card.Body className='p-2 d-flex flex-column flex-sm-row align-items-center'>
<div className='cart-item flex-fill'>
<img className='cart-image' src={cartItem.image || imgPlaceholder} alt="Cart Image" />
{cartItem.type.name}
</div>
<div className='cart-item mt-2 mt-sm-0 d-flex flex-column align-items-center align-items-sm-end'>
<div>
{cartItem.price}
{' * '}
{cartItem.count}
{' = '}
{parseFloat(cartItem.price * cartItem.count).toFixed(2)}
</div>
<ButtonGroup className='mt-2 mt-sm-1' aria-label="Cart counter">
<Button variant="primary" onClick={() => addToCart(cartItem)}>
<PlusLg />
</Button>
<Button variant="danger" onClick={() => removeFromCart(cartItem)}>
<DashLg />
</Button>
</ButtonGroup>
</div>
</Card.Body>
</Card>)
}
<div className='mb-2 col-12 col-md-8 col-lg-6 d-flex justify-content-end'>
<strong>Итого: {getCartSum()} &#8381;</strong>
</div>
</div>
);
};
export default Cart;

View File

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

View File

@ -0,0 +1,26 @@
import { useContext } from 'react';
import CartContext from './CartContext.jsx';
import { cartAdd, cartClear, cartRemove } from './CartReducer';
const useCart = () => {
const { cart, dispatch } = useContext(CartContext);
const cartSum = () => {
return parseFloat(
cart?.reduce((sum, cartItem) => {
return sum + (cartItem.price * cartItem.count);
}, 0)
?? 0,
).toFixed(2);
};
return {
cart,
getCartSum: () => cartSum(),
addToCart: (item) => dispatch(cartAdd(item)),
removeFromCart: (item) => dispatch(cartRemove(item)),
clearCart: () => dispatch(cartClear()),
};
};
export default useCart;

View File

@ -0,0 +1,71 @@
const setCartCount = (cart, item, value) => {
return cart.map((cartItem) => {
if (cartItem.id === item.id) {
return { ...cartItem, count: cartItem.count + value };
}
return cartItem;
});
};
const addToCart = (cart, item) => {
const existsItem = cart.find((cartItem) => cartItem.id === item.id);
if (existsItem !== undefined) {
return setCartCount(cart, item, 1);
}
return [...cart, { ...item, count: 1 }];
};
const removeFromCart = (cart, item) => {
const existsItem = cart.find((cartItem) => cartItem.id === item.id);
if (existsItem !== undefined && existsItem.count > 1) {
return setCartCount(cart, item, -1);
}
return cart.filter((cartItem) => cartItem.id !== item.id);
};
const CART_KEY = 'localCart';
const CART_ADD = 'cart/add';
const CART_REMOVE = 'cart/remove';
const CART_CLEAR = 'cart/clear';
export const saveCart = (cart) => {
localStorage.setItem(CART_KEY, JSON.stringify(cart));
};
export const loadCart = (initialValue = []) => {
const cartData = localStorage.getItem(CART_KEY);
if (cartData) {
return JSON.parse(cartData);
}
return initialValue;
};
export const cartReducer = (cart, action) => {
const { item } = action;
switch (action.type) {
case CART_ADD: {
return addToCart(cart, item);
}
case CART_REMOVE: {
return removeFromCart(cart, 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

@ -1,10 +1,8 @@
import './Footer.css';
const Footer = () => {
// const year = new Date().getFullYear();
return (
<footer className="my-footer mt-auto d-flex flex-shrink-0 justify-content-center align-items-center">
<footer className='my-footer mt-auto d-flex flex-shrink-0 justify-content-center align-items-center'>
Адреса: ул. Северный Венец, 32; ул. Андрея Блаженного, 3
</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,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,34 @@
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='price' label='Цена' value={item.price} onChange={handleChange}
type='number' min='1000.0' step='0.50' required />
<Input name='count' label='Количество' value={item.count} onChange={handleChange}
type='number' min='1' step='1' 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,81 @@
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 image = formData.image.startsWith('data:image') ? formData.image : '';
return {
typeId: typeId.toString(),
price: price.toString(),
count: count.toString(),
sum: sum.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,5 @@
import ApiService from '../../api/ApiService';
const LinesApiService = new ApiService('lines');
export default LinesApiService;

View File

@ -0,0 +1,81 @@
import { Button, ButtonGroup } from 'react-bootstrap';
import { Link, useNavigate } from 'react-router-dom';
import useCart from '../../cart/CartHook';
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,
showFormModal,
currentItem,
handleItemChange,
handleFormSubmit,
handleFormClose,
} = useLinesFormModal(handleLinesChange);
const navigate = useNavigate();
const showEditPage = (id) => {
navigate(`/page-edit/${id}`);
};
const { addToCart } = useCart();
return (
<>
<ButtonGroup>
<Button variant='info' onClick={() => showFormModal()}>
Добавить товар (диалог)
</Button>
<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}
onAddCart={() => addToCart(line)}
onDelete={() => showDeleteModal(line.id)}
onEdit={() => showFormModal(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,38 @@
import PropTypes from 'prop-types';
import {
Cart, PencilFill, PencilSquare, Trash3,
} from 'react-bootstrap-icons';
const LinesTableRow = ({
index, line, onAddCart, onDelete, onEdit, onEditInPage,
}) => {
const handleAnchorClick = (event, action) => {
event.preventDefault();
action();
};
return (
<tr>
<th scope="row">{index + 1}</th>
<td>{line.type.name}</td>
<td>{parseFloat(line.price).toFixed(2)}</td>
<td>{line.count}</td>
<td>{parseFloat(line.sum).toFixed(2)}</td>
<td><a href="#" onClick={(event) => handleAnchorClick(event, onAddCart)}><Cart /></a></td>
<td><a href="#" onClick={(event) => handleAnchorClick(event, onEdit)}><PencilFill /></a></td>
<td><a href="#" onClick={(event) => handleAnchorClick(event, onEditInPage)}><PencilSquare /></a></td>
<td><a href="#" onClick={(event) => handleAnchorClick(event, onDelete)}><Trash3 /></a></td>
</tr>
);
};
LinesTableRow.propTypes = {
index: PropTypes.number,
line: PropTypes.object,
onAddCart: PropTypes.func,
onDelete: PropTypes.func,
onEdit: PropTypes.func,
onEditInPage: PropTypes.func,
};
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

@ -3,7 +3,7 @@
}
.my-navbar .link a:hover {
text-decoration: underline !important;
text-decoration: underline;
}
.my-navbar .logo {

View File

@ -1,18 +1,21 @@
import PropTypes from 'prop-types';
import {
Image, Container, Nav, Navbar,
Container, Nav, Navbar, Image,
} from 'react-bootstrap';
import { Cart2 } from 'react-bootstrap-icons';
import { Link, useLocation } from 'react-router-dom';
import useCart from '../cart/CartHook';
import './Navigation.css';
const Navigation = ({ routes }) => {
const { getCartSum } = useCart();
const location = useLocation();
const indexPageLink = routes.filter((route) => route.index === false).shift();
const pages = routes.filter((route) => Object.prototype.hasOwnProperty.call(route, 'title'));
return (
<header>
<Navbar expand='md' bg='dark' data-bs-theme='dark' className='my-navbar'>
<Navbar expand='md' data-bs-theme='dark' className='my-navbar'>
<Container fluid>
<Navbar.Brand as={Link} to={indexPageLink?.path ?? '/'}>
<Image src="./images/logo2.png" className='d-inline-block align-top me-1 logo' />
@ -27,6 +30,11 @@ const Navigation = ({ routes }) => {
</Nav.Link>)
}
</Nav>
<Nav>
<Navbar.Brand as={Link} to='/cart'>
<Cart2 className='d-inline-block align-top me-1 logo' /> {getCartSum() ?? ''} &#8381;
</Navbar.Brand>
</Nav>
</Navbar.Collapse>
</Container>
</Navbar >

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,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

@ -9,34 +9,6 @@ h2 {
h3 {
font-size: 1.1em;
}
.btn-mw {
width: 100%;
}
@media (min-width: 768px) {
.btn-mw {
width: 30%;
}
}
@media (min-width: 1200px) {
.btn-mw {
width: 20%;
}
}
.body{
display: flex;
flex-direction: column;
min-height: 100hv;
}
.stsp{
font-size: 30px;
color: #333333;
text-align: center;
margin-top: 70;
}
.mainSt{
color: #060647;
font-size: 50px;
@ -115,4 +87,10 @@ h3 {
.rectNew{
border-radius: 21px;
border: 3px #2582A3 solid;
}
.stsp{
font-size: 30px;
color: #333333;
text-align: center;
margin-top: 70;
}

View File

@ -10,30 +10,30 @@ import Page2 from './pages/Page2.jsx';
import Page3 from './pages/Page3.jsx';
import Page4 from './pages/Page4.jsx';
import Page5 from './pages/Page5.jsx';
import Admin from './pages/Admin.jsx';
import Reduse from './pages/Reduse.jsx';
import Admin from './pages/Admin.jsx';
const routes = [
{
index: true,
path: '/',
element: <Page1 />,
title: 'Новости',
title: 'Главная страница',
},
{
path: '/page2',
element: <Page2 />,
title: 'Об университете',
title: 'Вторая страница',
},
{
path: '/page3',
element: <Page3 />,
title: 'Абитуриенту',
title: 'Третья страница',
},
{
path: '/page4',
element: <Page4 />,
title: 'Вход',
title: 'Четвертая страница',
},
{
path: '/page5',

View File

@ -0,0 +1,9 @@
import Cart from '../components/cart/Cart.jsx';
const CartPage = () => {
return (
<Cart />
);
};
export default CartPage;

View File

@ -1,17 +1,18 @@
import { Alert, Button, Container } from 'react-bootstrap';
import { useNavigate } from 'react-router-dom';
import { useNavigate, useRouteError } from 'react-router-dom';
const ErrorPage = () => {
const navigate = useNavigate();
const error = useRouteError();
return (
<Container fluid className="p-2 row justify-content-center">
<Container className='col-md-6'>
<Alert variant="danger">
Страница не найдена
</Alert>
<Button className="w-25 mt-2" variant="primary" onClick={() => navigate(-1)}>Назад</Button>
</Container>
<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>
);
};

View File

@ -1,7 +1,7 @@
import { Link } from 'react-router-dom';
import {
Container, Button, Row, Col, Image,
} from 'react-bootstrap';
Container, Button, Row, Col, Image,
} from 'react-bootstrap';
const Page1 = () => {
return (

View File

@ -1,48 +1,115 @@
const Page3 = () => {
return (
<main className="container p-2 text-center">
<label className="mainSt d-flex justify-content-center" htmlFor="direction">
Направление
</label>
<input className="justify-content-md-center w-50"
type="search"
id="direction"
name="direction"
required />
import { useState } from 'react';
import { Button, Form } from 'react-bootstrap';
<div className="tbb1 p-3 table-responsive-md mt-4 row justify-content-start">
<table className="table col-lg2 w-50 mx-auto">
<thead>
<tr>
<th className="w-25">Код</th>
<th className="w-50">Направление</th>
<th className="w-25">Кафедра</th>
<th className="w-75">Предметы(ЕГЭ) по выбору</th>
</tr>
</thead>
<tbody>
<tr>
<td>01.03.04</td>
<td>Мат. Моделирование</td>
<td>Прикладная математика</td>
<td>Иностранный язык, информатика, физика, химия</td>
</tr>
<tr>
<td>09.03.04</td>
<td>Программная инженерия</td>
<td>Информационные системы</td>
<td>Информатика, физика</td>
</tr>
<tr>
<td>02.03.01</td>
<td>Информационные системы и технологии</td>
<td>Измерительно-вычислительные комплексы</td>
<td>Информатика, физика</td>
</tr>
</tbody>
</table>
</div>
</main>
const Page3 = () => {
const someValue = 'Некоторое значение';
const [validated, setValidated] = useState(false);
const [formData, setFormData] = useState({
lastname: '',
firstname: '',
email: '',
password: '',
date: '',
disabled: someValue,
readonly: someValue,
color: '#ff0055',
checkbox1: false,
checkbox2: false,
radio1: false,
radio2: false,
selected: '',
});
const handleSubmit = (event) => {
const form = event.currentTarget;
event.preventDefault();
event.stopPropagation();
if (form.checkValidity() !== false) {
console.log(formData);
}
setValidated(true);
};
const handleChange = (event) => {
const inputName = event.target.name;
const inputValue = event.target.type === 'checkbox' ? event.target.checked : event.target.value;
setFormData({
...formData,
[inputName]: inputValue,
});
};
return (
<div className='row justify-content-center'>
<Form className='col-md-6 m-0' noValidate validated={validated} onSubmit={handleSubmit}>
<Form.Group className='mb-2' controlId='lastname'>
<Form.Label>Фамилия</Form.Label>
<Form.Control type='text' name='lastname' required
value={formData.lastname} onChange={handleChange} />
<Form.Control.Feedback>Фамилия заполнена</Form.Control.Feedback>
<Form.Control.Feedback type='invalid'>Фамилия не заполнена</Form.Control.Feedback>
</Form.Group>
<Form.Group className='mb-2' controlId='firstname'>
<Form.Label>Имя</Form.Label>
<Form.Control type='text' name='firstname' required
value={formData.firstname} onChange={handleChange} />
</Form.Group>
<Form.Group className='mb-2' controlId='email'>
<Form.Label>E-mail</Form.Label>
<Form.Control type='email' name='email' placeholder='name@example.ru' required
value={formData.email} onChange={handleChange} />
</Form.Group>
<Form.Group className='mb-2' controlId='password'>
<Form.Label>Пароль</Form.Label>
<Form.Control type='password' name='password' required
value={formData.password} onChange={handleChange} />
</Form.Group>
<Form.Group className='mb-2' controlId='date'>
<Form.Label>Дата</Form.Label>
<Form.Control type='date' name='date' required
value={formData.date} onChange={handleChange} />
</Form.Group>
<Form.Group className='mb-2' controlId='disabled'>
<Form.Label>Выключенный компонент</Form.Label>
<Form.Control type='text' name='disabled' disabled
value={formData.disabled} onChange={handleChange} />
</Form.Group>
<Form.Group className='mb-2' controlId='readonly'>
<Form.Label>Компонент только для чтения</Form.Label>
<Form.Control type='text' name='readonly' readOnly
value={formData.readonly} onChange={handleChange} />
</Form.Group>
<Form.Group className='mb-2' controlId='color'>
<Form.Label>Выбор цвета</Form.Label>
<Form.Control type='color' name='color'
value={formData.color} onChange={handleChange} />
</Form.Group>
<Form.Group className='mb-2 d-md-flex flex-md-row'>
<Form.Check className='me-md-3' type='checkbox' name='checkbox1' label='Флажок 1'
value={formData.checkbox1} onChange={handleChange} />
<Form.Check className='me-md-3' type='checkbox' name='checkbox2' label='Флажок 2'
value={formData.checkbox2} onChange={handleChange} />
</Form.Group>
<Form.Group className='mb-2 d-md-flex flex-md-row'>
<Form.Check className='me-md-3' type='radio' name='radio1' label='Переключатель 1'
value={formData.radio1} onChange={handleChange} />
<Form.Check className='me-md-3' type='switch' name='radio2' label='Переключатель 2'
value={formData.radio2} onChange={handleChange} />
</Form.Group>
<Form.Group className='mb-2'>
<Form.Select name='selected' required
value={formData.selected} onChange={handleChange}>
<option value=''>Выберите значение</option>
<option value='1'>Один</option>
<option value='2'>Два</option>
<option value='3'>Три</option>
</Form.Select>
</Form.Group>
<div className='text-center'>
<Button className='w-50' variant='primary' type='submit'>Отправить</Button>
</div>
</Form>
</div>
);
};

View File

@ -1,26 +1,8 @@
import Lines from '../components/lines/table/Lines.jsx';
const Page4 = () => {
return (
<main className="container-fluid text-center">
<span className="mainSt">
<b>Личный кабинет</b>
</span>
<div className="rectpage4 d-flex row justify-content-center">
<form className="col-md-4 m-0 w-auto" action="./page4.html" method="get">
<div className="mb-2">
<label className="form-label" htmlFor="login"><b>Логин</b></label>
<input id="login" name="login" className="form-control"
placeholder="dyctator" type="text" required />
</div>
<div className="mb-2">
<label className="form-label" htmlFor="password"><b>Пароль</b></label>
<input id="password" name="password" className="form-control" type="password" required />
</div>
<div className="text-center">
<button className="btn btn-primary w-auto" type="button">Войти</button>
</div>
</form>
</div>
</main>
<Lines />
);
};

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>