This commit is contained in:
GokaPek 2023-12-16 16:12:15 +04:00
parent 5d8d3241af
commit 4b600870f7
157 changed files with 398419 additions and 0 deletions

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/Bookfill/.gitignore vendored Normal file
View File

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

44
Lab5/Bookfill/README.md Normal file
View File

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

106
Lab5/Bookfill/data.json Normal file

File diff suppressed because one or more lines are too long

15
Lab5/Bookfill/index.html Normal file
View File

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

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/*"
]
}

View File

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

5954
Lab5/Bookfill/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,41 @@
{
"name": "lec4",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0",
"build": "vite build",
"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": {
"axios": "^1.6.1",
"bootstrap": "^5.3.2",
"fa": "^1.0.1",
"prop-types": "^15.8.1",
"react": "^18.2.0",
"react-bootstrap": "^2.9.1",
"react-bootstrap-icons": "^1.10.3",
"react-dom": "^18.2.0",
"react-hot-toast": "^2.4.1",
"react-icons": "^4.12.0",
"react-router-dom": "^6.18.0"
},
"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"
}
}

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

26
Lab5/Bookfill/src/App.jsx Normal file
View File

@ -0,0 +1,26 @@
import PropTypes from 'prop-types';
import { Container } from 'react-bootstrap';
import { Toaster } from 'react-hot-toast';
import { Outlet } from 'react-router-dom';
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>
<Outlet />
</Container>
<Footer />
<Toaster position='top-center' reverseOrder={true} />
</CartProvider>
);
};
App.propTypes = {
routes: PropTypes.array,
};
export default App;

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 640 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 812 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 767 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 545 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 149 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 258 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 172 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 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,
});

Binary file not shown.

View File

@ -0,0 +1,9 @@
@font-face {
font-family: 'ITC Eras';
src: local('ITC Eras Bold'), local('ITC-Eras-Bold'),
url('ITCErasStd-Bold.woff2') format('woff2'),
url('ITCErasStd-Bold.woff') format('woff'),
url('ITCErasStd-Bold.ttf') format('truetype');
font-weight: 700;
font-style: normal;
}

View File

@ -0,0 +1,9 @@
.my-footer {
height: 100px;
background-color: #c03000;
}
.logos {
height: 100px;
width: auto;
}

View File

@ -0,0 +1,13 @@
import './Footer.css';
const Footer = () => {
return (
<footer className="my-footer mt-auto d-flex flex-shrink-0 justify-content-center align-items-center w-100">
<div className="container">
<img className="logos ml-0" src="src/assets/logo.png" alt="Логотип" />
</div>
</footer>
);
};
export default Footer;

View File

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

View File

@ -0,0 +1,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,78 @@
import { Button, ButtonGroup } from 'react-bootstrap';
import { 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>
</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

@ -0,0 +1,42 @@
.my-navbar {
width: 100%;
background-color: #c03000 !important;
height: 70px;
border-radius: 4% / 60%;
z-index: 1030;
}
.my-navbar .link a:hover {
text-decoration: underline !important;
text-decoration: none;
color: white;
}
.my-navbar .logo {
width: auto;
}
.navbar-collapse.show{
background-color: #c03000;
}
.user-photo {
width: 50px;
height: 50px;
border-radius: 50%;
background-color: white;
}
.logo {
height: 45px;
width: auto;
}
.navbar-nav {
font-family: "ITCErasStd-Bold";
font-size: 25px;
align-items: center;
}
.me-auto-link {
text-decoration: none;
color: white;
}

View File

@ -0,0 +1,57 @@
import PropTypes from 'prop-types';
import {
Navbar, Container, Nav, Form, FormControl, Button, Image,
} from 'react-bootstrap';
import { Link, useLocation } from 'react-router-dom';
import { FaSearch } from 'react-icons/fa';
import './Navigation.css';
const Navigation = ({ routes }) => {
const location = useLocation();
const pages = routes.filter((route) => Object.prototype.hasOwnProperty.call(route, 'title'));
return (
<header>
<Navbar expand='lg' bg='dark' variant='dark' className='my-navbar'>
<Container fluid>
<Navbar.Brand as={Link} to='/'>
<Image className='logo pb-2' src='src/assets/big-logo.png' alt='Логотип' />
</Navbar.Brand>
<Navbar.Toggle aria-controls='navbarSupportedContent' />
<Navbar.Collapse id='navbarSupportedContent'>
<Nav className='me-auto'>
<Form className='d-flex mr-4 mt-1' as={Link} to='/search'>
<FormControl
type='search'
placeholder='Search'
className='m-1'
aria-label='Search'
/>
<Button variant='outline-success' type='submit'>
<FaSearch />
</Button>
</Form>
<Nav className='me-auto-link' activeKey={location.pathname}>
{
pages.map((page) =>
<Nav.Link as={Link} key={page.path} eventKey={page.path} to={page.path ?? '/'}>
{page.title}
</Nav.Link>)
}
</Nav>
<Nav.Link as={Link} to='/login'>
<img id='profile' className='user-photo mt-1 ml-4 mr-3' />
</Nav.Link>
</Nav>
</Navbar.Collapse>
</Container>
</Navbar>
</header>
);
};
Navigation.propTypes = {
routes: PropTypes.array,
};
export default Navigation;

View File

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

View File

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

View File

@ -0,0 +1,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,8 @@
@import url("./src/components/fonts/style.css");
@font-face {
font-family: "ITCErasStd-Bold";
src: url('./src/components/fonts/ITCErasStd-Bold.woff2') format('woff2'),
url('./src/components/fonts/ITCErasStd-Bold.woff') format('woff');
font-style: normal;
font-weight: 400;
}

View File

@ -0,0 +1,73 @@
import 'bootstrap/dist/css/bootstrap.min.css';
import React from 'react';
import ReactDOM from 'react-dom/client';
import { RouterProvider, createBrowserRouter } from 'react-router-dom';
import App from './App.jsx';
import './index.css';
import CartPage from './pages/CartPage.jsx';
import ErrorPage from './pages/ErrorPage.jsx';
import Page1 from './pages/Page1.jsx';
import Page3 from './pages/Page3.jsx';
import Page4 from './pages/Page4.jsx';
import PageEdit from './pages/PageEdit.jsx';
import Admin from './pages/Admin.jsx';
import Login from './pages/Login.jsx';
import Search from './pages/Search.jsx';
const routes = [
{
index: true,
path: '/',
element: <Page1 />,
},
{
path: '/page2',
element: <CartPage />,
title: 'Favourite',
},
{
path: '/page3',
element: <Page3 />,
title: 'Audio',
},
{
path: '/page4',
element: <Page4 />,
title: 'Comics',
},
{
path: '/page-edit',
element: <PageEdit />,
},
{
path: '/cart',
element: <CartPage />,
},
{
path: '/admin',
element: <Admin />,
},
{
path: '/login',
element: <Login />,
},
{
path: '/search',
element: <Search />,
},
];
const router = createBrowserRouter([
{
path: '/',
element: <App routes={routes} />,
children: routes,
errorElement: <ErrorPage />,
},
]);
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>,
);

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,29 @@
import './pages.css';
import { Form, Button } from 'react-bootstrap';
import { Link } from 'react-router-dom';
const Login = () => {
return (
<Form className="col-md-6 mr-sm-10 mx-auto mt-3 pt-5" method="get">
<Form.Group controlId="firstname">
<Form.Control type="text" placeholder="name" className="mb-3" required/>
</Form.Group>
<Form.Group controlId="email">
<Form.Control type="email" placeholder="mail@example.ru" className="mb-3" required/>
</Form.Group>
<Form.Group controlId="password">
<Form.Control type="password" placeholder="password" className="mb-3" required/>
</Form.Group>
<div className="text-center">
<Button variant="primary" type="submit" className="w-50">
<>Submit</>
</Button>
<Button variant="primary" type="submit" as={Link} to='/admin' className="w-50">
<>Admin</>
</Button>
</div>
</Form>
);
};
export default Login;

View File

@ -0,0 +1,32 @@
import './pages.css';
import { Carousel } from 'react-bootstrap';
const Page1 = () => {
return (
<Carousel className="container-fluid p-0 mt-5">
<Carousel.Item className="p-5">
<img
className="img d-block w-100 pt-3 mx-auto"
src="src/assets/books/metro.jpg"
alt="First slide"
/>
</Carousel.Item>
<Carousel.Item className="p-5">
<img
className="img d-block w-100 pt-3 mx-auto"
src="src/assets/books/blev.jpg"
alt="Second slide"
/>
</Carousel.Item>
<Carousel.Item className="p-5">
<img
className="img d-block w-100 pt-3 mx-auto"
src="src/assets/books/capital.jpg"
alt="Third slide"
/>
</Carousel.Item>
</Carousel>
);
};
export default Page1;

View File

@ -0,0 +1,43 @@
import { Table } from 'react-bootstrap';
import ulstuLogo from '../assets/logo.png';
const Page2 = () => {
return (
<>
<p className='text-center'>
Вторая страница содержит пример рисунка (рис. 1) и таблицы (таб. 1).
</p>
<div className='text-center'>
<img src={ulstuLogo} alt='logo' width='128' />
<br />
Рис. 1. Пример рисунка.
</div>
<div className='mt-3 row justify-content-center'>
<Table className='w-50' bordered>
<caption>Таблица 1. Пример таблицы.</caption>
<thead>
<tr>
<th className='w-25'>Номер</th>
<th>ФИО</th>
<th className='w-25'>Телефон</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Иванов</td>
<td>89999999999</td>
</tr>
<tr>
<td>2</td>
<td>Петров</td>
<td>89999999991</td>
</tr>
</tbody>
</Table>
</div>
</>
);
};
export default Page2;

View File

@ -0,0 +1,32 @@
import './pages.css';
import { Carousel } from 'react-bootstrap';
const Page3 = () => {
return (
<Carousel className="container-fluid p-0 mt-5">
<Carousel.Item className="p-5">
<img
className="img d-block w-100 pt-3 mx-auto"
src="src/assets/books/capital.jpg"
alt="First slide"
/>
</Carousel.Item>
<Carousel.Item className="p-5">
<img
className="img d-block w-100 pt-3 mx-auto"
src="src/assets/books/capital.jpg"
alt="Second slide"
/>
</Carousel.Item>
<Carousel.Item className="p-5">
<img
className="img d-block w-100 pt-3 mx-auto"
src="src/assets/books/capital.jpg"
alt="Third slide"
/>
</Carousel.Item>
</Carousel>
);
};
export default Page3;

View File

@ -0,0 +1,32 @@
import './pages.css';
import { Carousel } from 'react-bootstrap';
const Page4 = () => {
return (
<Carousel className="container-fluid p-0 mt-5">
<Carousel.Item className="p-5">
<img
className="img d-block w-100 pt-3 mx-auto"
src="src/assets/books/blev.jpg"
alt="First slide"
/>
</Carousel.Item>
<Carousel.Item className="p-5">
<img
className="img d-block w-100 pt-3 mx-auto"
src="src/assets/books/blev.jpg"
alt="Second slide"
/>
</Carousel.Item>
<Carousel.Item className="p-5">
<img
className="img d-block w-100 pt-3 mx-auto"
src="src/assets/books/blev.jpg"
alt="Third slide"
/>
</Carousel.Item>
</Carousel>
);
};
export default Page4;

View File

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

View File

@ -0,0 +1,58 @@
import {
Form, InputGroup, FormControl, Button, Dropdown, Table,
} from 'react-bootstrap';
const Search = () => {
return (
<Form className="form-inlinecustom-search mx-auto mt-3 pt-5" id="big-search">
<InputGroup>
<FormControl type="search" placeholder="Search" aria-label="Search" className="mb-3" />
<Dropdown >
<Dropdown.Toggle variant="success" id="dropdown-basic" className="mb-3">
Choose category...
</Dropdown.Toggle>
<Dropdown.Menu>
<Dropdown.Item>1</Dropdown.Item>
<Dropdown.Item>2</Dropdown.Item>
<Dropdown.Item>3</Dropdown.Item>
</Dropdown.Menu>
</Dropdown>
<Button variant="outline-success" className="mb-3">Search</Button>
</InputGroup>
<div className="scroll-panel-favour">
<Table striped bordered hover>
<thead>
<tr>
<th>#</th>
<th>Book</th>
<th>Author</th>
<th>Gener</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Capital</td>
<td>Marks K.</td>
<td>Philosofy</td>
</tr>
<tr>
<td>2</td>
<td>Capital</td>
<td>Marks K.</td>
<td>Philosofy</td>
</tr>
<tr>
<td>3</td>
<td>Capital</td>
<td>Marks K.</td>
<td>Philosofy</td>
</tr>
</tbody>
</Table>
</div>
</Form>
);
};
export default Search;

View File

@ -0,0 +1,21 @@
.Carousel {
width: 80%;
background: #c03000;
height: 400px;
border-radius: 17% / 60%;
}
.img {
max-width: 200px;
overflow: hidden;
}
.btn-info{
background-color: #c03000;
color: white;
}
.btn{
background-color: #c03000;
color: white;
}

51
Lab5/Bookfill/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>

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

File diff suppressed because it is too large Load Diff

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/PrBookfill/.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?

29
Lab5/PrBookfill/README.md Normal file
View File

@ -0,0 +1,29 @@
#### Окружение:
- nodejs 18;
- VSCode;
- ESLint плагин для VSCode;
- для отладки необходимы бразузеры Chrome или Edge.
#### Создание пустого проекта:
```commandline
npm create vite@latest ./ -- --template react
```
#### Установка зависимостей:
```commandline
npm install
```
#### Запуск проекта:
```commandline
npm run dev
```
#### Сборка проекта:
```commandline
npm run build
```

67
Lab5/PrBookfill/data.json Normal file

File diff suppressed because one or more lines are too long

View File

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

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/*"
]
}

View File

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

5975
Lab5/PrBookfill/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,39 @@
{
"name": "BookFill",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "npm-run-all --parallel rest vite",
"build": "vite build",
"vite": "vite",
"rest": "json-server data.json",
"lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview"
},
"dependencies": {
"axios": "^1.6.1",
"bootstrap": "^5.3.2",
"prop-types": "^15.8.1",
"react": "^18.2.0",
"react-bootstrap": "^2.9.1",
"react-bootstrap-icons": "^1.10.3",
"react-dom": "^18.2.0",
"react-hot-toast": "^2.4.1",
"react-icons": "^4.12.0",
"react-router-dom": "^6.18.0"
},
"devDependencies": {
"@types/react": "^18.2.15",
"@types/react-dom": "^18.2.7",
"@vitejs/plugin-react": "^4.0.3",
"eslint": "^8.45.0",
"eslint-config-airbnb-base": "^15.0.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"
}
}

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 0v16h16V0H0zm15 15H1V1h13v13zM1 0a1 1 0 0 0-1 1v13a1 1 0 0 0 1 1h1V1h1v14h1V1h1v14h1V1h1v14h1V1h1v14h1V1h1v14h1V1h1v13a1 1 0 0 0 1 1h1V1a1 1 0 0 0-1-1h-2z"/>
</svg>

After

Width:  |  Height:  |  Size: 302 B

View File

View File

@ -0,0 +1,24 @@
import PropTypes from 'prop-types';
import { Container } from 'react-bootstrap';
import { Outlet } from 'react-router-dom';
import './App.css';
import Footer from './components/footer/Footer.jsx';
import Navigation from './components/navigation/Navigation.jsx';
const App = ({ routes }) => {
return (
<>
<Navigation routes={routes}></Navigation>
<Container className='p-2' as="main" fluid>
<Outlet />
</Container>
<Footer />
</>
);
};
App.propTypes = {
routes: PropTypes.array,
};
export default App;

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 640 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 812 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 767 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 545 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 149 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

Some files were not shown because too many files have changed in this diff Show More