This commit is contained in:
allllen4a 2023-12-25 18:07:22 +03:00
parent 7ef57df568
commit 0823ed978b
99 changed files with 8636 additions and 3 deletions

View File

@ -1,3 +0,0 @@
<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>

Before

Width:  |  Height:  |  Size: 463 B

24
Laba 5/.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
Laba 5/.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
Laba 5/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

126
Laba 5/data.json Normal file

File diff suppressed because one or more lines are too long

14
Laba 5/index.html Normal file
View File

@ -0,0 +1,14 @@
<html lang="ru">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Elitist</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
Laba 5/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
Laba 5/json-server.json Normal file
View File

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

5936
Laba 5/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

38
Laba 5/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"
}
}

28
Laba 5/src/App.jsx Normal file
View File

@ -0,0 +1,28 @@
import PropTypes from 'prop-types';
import { Container } from 'react-bootstrap';
import { Toaster } from 'react-hot-toast';
import { Outlet } from 'react-router-dom';
import Footer from './components/footer/Footer.jsx';
import Navigation from './components/navigation/Navigation.jsx';
import { UserProvider } from './components/users/UserContext.jsx';
const App = ({ routes }) => {
return (
<div className="d-flex flex-column min-vh-100">
<UserProvider>
<Navigation routes={routes}></Navigation>
<Container className="flex-grow-1 p-2" as="main" fluid>
<Outlet />
</Container>
<Footer />
<Toaster position='top-center' reverseOrder={true} />
</UserProvider>
</div>
);
};
App.propTypes = {
routes: PropTypes.array,
};
export default App;

BIN
Laba 5/src/assets/200.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

BIN
Laba 5/src/assets/4j.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 87 KiB

View File

@ -0,0 +1,2 @@
15.05.2023
19.12.2024

View File

@ -0,0 +1 @@
AC/DC - австралийская рок-группа, образованная в 1973 году. Их музыка сочетает в себе элементы хард-рока и блюза, создавая энергичное и зажигательное звучание. AC/DC известны своими хитами, включая "Highway to Hell", "Back in Black" и "Thunderstruck". Группа славится своими мощными гитарными рифами, мелодичными припевами и хриплым вокалом Брайана Джонсона. Они стали одной из самых успешных и влиятельных рок-групп в истории, продав более 200 миллионов копий своих альбомов. AC/DC оставили неизгладимый след в музыкальной индустрии и остаются почитаемыми и узнаваемыми до сих пор.

View File

@ -0,0 +1 @@
AC/DC

View File

@ -0,0 +1,2 @@
15.05.2023
19.12.2024

View File

@ -0,0 +1 @@
Deftones - американская рок-группа, образованная в 1988 году. Их музыка сочетает в себе элементы альтернативного метала, ню-метала и шугейзинга, создавая уникальное звучание. Группа известна своим энергичным звуком, мощными гитарными рифами и харизматичным вокалом Чино Морено. Они выпустили ряд успешных альбомов, включая "White Pony" (2000), "Diamond Eyes" (2010) и "Gore" (2016). Deftones получили мировое признание и оказали значительное влияние на альтернативную музыку.

View File

@ -0,0 +1 @@
Deftones

View File

@ -0,0 +1,2 @@
15.05.2023
19.12.2024

View File

@ -0,0 +1,7 @@
Placebo - британская альтернативная рок-группа, основанная в 1994 году. Они известны своим уникальным звучанием, погружающим слушателей в меланхоличную атмосферу и наполняющим музыку эмоциональным содержанием.
Группа состоит из трех участников: Брайана Молко (вокал, гитара), Стефана Олсдала (бас-гитара) и Стива Хьюитта (ударные). Их музыкальный стиль объединяет элементы альтернативного рока, гранжа, инди и электроники, что создает неповторимую их звуковую палитру.
Placebo известны своими яркими и эмоциональными текстами, в которых Брайан Молко касается тем тоски, любви, одиночества и личных борьб. Они обладают узнаваемым стилем исполнения, в котором эмоциональный вокал Молко смешивается с мощными гитарными рифами и характерной ритм-секцией группы.
С самого начала своей карьеры Placebo получили широкую популярность в Европе и за ее пределами. Они выпустили множество успешных альбомов, включая "Without You I'm Nothing" (1998), "Black Market Music" (2000), "Meds" (2006) и "Loud Like Love" (2013).

View File

@ -0,0 +1,24 @@
placeboplacebo
placeboplacebo
placeboplacebo
placeboplacebo
placeboplacebo
placeboplacebo
placeboplacebo
placeboplacebo
placeboplacebo
placeboplacebo
placeboplacebo
placeboplacebo
placeboplacebo
placeboplacebo
placeboplacebo
placeboplacebo
placeboplacebo
placeboplacebo
placeboplacebo
placeboplacebo
placeboplacebo
placeboplacebo
placeboplacebo
placeboplacebo

View File

@ -0,0 +1,2 @@
15.05.2023
19.12.2024

View File

@ -0,0 +1 @@
Slipknot - американская ню-метал группа, основанная в 1995 году. Они известны своим агрессивным звучанием, смешением хардкор-панк и тяжелого метала с индастриалом и элементами альтернативного рока. Группа состоит из 9 участников, носит маски и выпускает энергичные и бескомпромиссные песни, в которых затрагиваются темы психологической напряженности, стресса и яростной самоидентификации. Своими выступлениями Slipknot стали известными своими интенсивными концертами и эпатажной визуальной эстетикой. Они получили широкую популярность и стали влиятельной группой в своем жанре.

View File

@ -0,0 +1 @@
Slipknot

View File

@ -0,0 +1,2 @@
15.05.2023
19.12.2024

View File

@ -0,0 +1 @@
The Cure - британская рок-группа, образованная в 1976 году. Их музыка отличается меланхоличными и атмосферными звучанием, смешивая элементы пост-панка, готического рока и новой волны. Вокал Роберта Смита и неповторимое звучание группы создают неповторимую и замечательную эмоциональную ауру. The Cure стали иконами альтернативной и инди-музыки и получили широкое признание за свои хиты, такие как "Lovesong", "Boys Don't Cry" и "Friday I'm in Love".

View File

@ -0,0 +1 @@
The Cure

View File

@ -0,0 +1,2 @@
15.05.2023
19.12.2024

View File

@ -0,0 +1 @@
Weezer - американская альтернативная рок-группа, образованная в 1992 году. Их музыка сочетает в себе элементы рок-попа, панка и гранжа, создавая яркий и мелодичный звук. Weezer известны своими популярными хитами, такими как "Buddy Holly", "Island in the Sun" и "Say It Ain't So". Группа славится своим энергичным стилем и уникальным чувством юмора, привнесенным в свои песни и тексты. Они остаются популярными и влиятельными в современной музыкальной сцене.

View File

@ -0,0 +1 @@
Weezer

BIN
Laba 5/src/assets/gl.PNG Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 840 KiB

BIN
Laba 5/src/assets/kafka.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 130 KiB

BIN
Laba 5/src/assets/leot.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 265 KiB

BIN
Laba 5/src/assets/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

BIN
Laba 5/src/assets/pandp.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 113 KiB

View File

@ -0,0 +1,55 @@
.card-book {
padding: 15px;
text-align: center;
margin-bottom: 20px;
flex: 0 0 calc(20% - 20px); /* Уменьшение размера книг на 20% */
}
.card-text {
margin-top: 10px;
}
.card-title,
.card-author {
margin: 0;
padding: 0;
}
.card-book-margin {
margin-right: 10px; /* Устанавливает отступ справа между карточками */
}
.card-img {
width: 100%;
max-height: 340px;
border-radius: 5px;
margin-bottom: 10px;
}
/* Медиа-запросы для изменения ширины изображения на различных экранах */
@media screen and (max-width: 768px) {
.card-img {
max-width: 80%;
}
}
@media screen and (max-width: 576px) {
.card-img {
max-width: 100%;
}
}
/* Медиа-запросы для изменения ширины текста на различных экранах */
@media screen and (max-width: 768px) {
.card-title,
.card-author {
font-size: 1.2em;
}
}
@media screen and (max-width: 576px) {
.card-title,
.card-author {
font-size: 1em;
}
}

View File

@ -0,0 +1,17 @@
/* eslint-disable linebreak-style */
/* eslint-disable import/no-useless-path-segments */
// import React from 'react';
import '../CardBook/CardBook.css';
const CardBook = () => {
return (
<div className="card-book">
<img src="/src/assets/pandp.jpg" alt="Book" className="img-fluid" />
<h3>Гордость и Предубеждение</h3>
<h3>Д. Остен</h3>
</div>
);
};
export default CardBook;

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,41 @@
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}`);
}
async getByHandle(handle) {
return ApiClient.get(`${this.url}?handle=${handle}`);
}
async getByEmail(email) {
return ApiClient.get(`${this.url}?email=${email}`);
}
async getAllForUser(userId) {
return ApiClient.get(`${this.url}?userId=${userId}`);
}
}
export default ApiService;

View File

@ -0,0 +1,10 @@
.my-footer {
width: 100%;
font-family: Santa Catarina;
background-color: #382F1E;
color: white;
text-align: center;
padding: 10px 0;
bottom: 0;
left: 0;
}

View File

@ -0,0 +1,11 @@
import './Footer.css';
const Footer = () => {
return (
<footer className="my-footer mt-auto d-flex flex-shrink-0 justify-content-center align-items-center">
Жирнова Алена ПИбд-21
</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,44 @@
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 useAuthors from '../../types/hooks/AuthorsHook';
import './LinesItemForm.css';
const LinesItemForm = ({ item, handleChange }) => {
const { types } = useTypes();
const { authors } = useAuthors();
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 />
<Select values={authors} name='authorId' label='Автор' value={item.authorId} onChange={handleChange}
required />
<Input name='ItName' label='Название' value={item.ItName} onChange={handleChange}
type='text' required />
<Input name='count' label='Количество' value={item.count} onChange={handleChange}
type='number' min='1' step='1' required />
<div>
<label htmlFor='date' style={{ display: 'block' }}>Дата:</label>
<input type='date' id='date' name='date' value={item.date} onChange={handleChange} required style={{ display: 'block' }} />
</div>
<Input name='desc' label='Описание' value={item.desc} onChange={handleChange}
type='text' 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,30 @@
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=author&_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,85 @@
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 authorId = parseInt(formData.authorId, 10);
const { ItName } = formData;
const count = parseInt(formData.count, 10);
const { date } = formData;
const { desc } = formData;
const image = formData.image.startsWith('data:image') ? formData.image : '';
return {
typeId: typeId.toString(),
authorId: authorId.toString(),
ItName: ItName.toString(),
count: count.toString(),
date: date.toString(),
desc: desc.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,37 @@
import { useEffect, useState } from 'react';
import LinesApiService from '../service/LinesApiService';
const useLinesItem = (id) => {
const emptyItem = {
id: '',
typeId: '',
authorId: '',
ItName: '',
count: '',
date: '',
desc: '',
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,57 @@
body{
background-color: #403928;
}
.search-field {
font-size: 18px;
width: 300px;
height: 40px; /* Измените значение на нужное вам */
margin-top: 37px;
margin-left: 35px;
}
.button-overlayAdd button{
background-color: #ff5500;
color: #fff;
font-size: 15px;
width: 16vh;
}
@media (max-width: 1000px) {
.button-overlayAdd {
width:5vh;
}
}
.button-overlayAdd button:hover {
background-color: #5233ff;
color:aqua;
}
.product {
padding: 2%;
border: 5px solid black;
border-radius: 5px;
text-align: center;
color:#fafafa;
object-fit: cover;
}
.product img {
max-width: 100%;
height: auto;
border: 4px solid #403928;
border-radius: 5px;
max-width: 100%;
margin-bottom: 2%;
}
.product-info {
font-size: 20;
flex-basis: 50%;
}
.product-info h2 {
margin-top: 5;
}
.product-info p {
margin-bottom: 6%;
}

View File

@ -0,0 +1,75 @@
// eslint-disable-next-line no-tabs
/* eslint-disable no-tabs */
/* eslint-disable import/order */
import React, { useState } from 'react';
import Select from '../../input/Select.jsx';
import { Link } from 'react-router-dom';
import useTypeFilter from '../hooks/LinesFilterHook';
import useLines from '../hooks/LinesHook';
// eslint-disable-next-line import/extensions
import useAuthors from '../../types/hooks/AuthorsHook.js';
import './Catalog.css';
const Catalog = () => {
const { authors } = useAuthors();
const { types, currentFilter, handleFilterChange } = useTypeFilter();
const [searchTerm, setSearchTerm] = useState('');
const { lines } = useLines(currentFilter, authors);
const handleSearchChange = (event) => {
setSearchTerm(event.target.value);
};
const filteredLines = lines.filter((product) => {
return product.ItName.toLowerCase().includes(searchTerm.toLowerCase());
});
return (
<>
<main className="container-fluid ml-2 mr-2">
<div className="col-lg-4 mt-0 text-white">
<div className="d-flex">
<Select
className={'mt-2'}
values={types}
label="Фильтр по книгам"
value={currentFilter}
onChange={handleFilterChange}
/>
<input
type="text"
className="ml-3 search-field"
placeholder="Найти книгу"
value={searchTerm}
onChange={handleSearchChange}
/>
</div>
</div>
<div className="container">
<div className="row">
{filteredLines.map((product, index) => (
<div className="col-md-3 product mb-3" key={index}>
<div className="product-img">
<img src={product.image} alt={product.ItName} className="img-fluid product-image" />
</div>
<div className="product-info">
<h3>
<Link to={`/detailpage/${product.ItName}`} style={{ color: '#fafafa', outline: 'none' }}>
{product.ItName}
</Link>
<p>{product.author.name}</p>
</h3>
</div>
</div>
))}
</div>
</div>
</main>
</>
);
};
export default Catalog;

View File

@ -0,0 +1,34 @@
import PropTypes from 'prop-types';
import { Table } from 'react-bootstrap';
import React from 'react';
const LinesTable = ({ children }) => {
return (
<Table className='mt-2' striped responsive>
<thead>
<tr>
<th scope='col'></th>
<th scope='col' className='w-15'>Жанры</th>
<th scope="col" className='w-15'>Автор</th>
<th scope="col" className='w-15'>Название</th>
<th scope='col' className='w-15'>Колич.</th>
<th scope='col' className='w-15'>Дата</th>
<th scope='col' className='w-15'>Описание</th>
<th scope='col'></th>
<th scope='col'></th>
</tr>
</thead>
<tbody>
{React.Children.map(children, (child, index) => {
return React.cloneElement(child, { key: index });
})}
</tbody >
</Table >
);
};
LinesTable.propTypes = {
children: PropTypes.node,
};
export default LinesTable;

View File

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

View File

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

View File

@ -0,0 +1,77 @@
/* eslint-disable no-unused-vars */
import { Button, ButtonGroup } from 'react-bootstrap';
import { Link, useNavigate } from 'react-router-dom';
import Select from '../../input/Select.jsx';
import ModalConfirm from '../../modal/ModalConfirm.jsx';
import ModalForm from '../../modal/ModalForm.jsx';
import LinesItemForm from '../form/LinesItemForm.jsx';
import useLinesDeleteModal from '../hooks/LinesDeleteModalHook';
import useTypeFilter from '../hooks/LinesFilterHook';
import useLinesFormModal from '../hooks/LinesFormModalHook';
import useLines from '../hooks/LinesHook';
import LinesTable from './LinesTable.jsx';
import LinesTableRow from './LinesTableRow.jsx';
import useAuthors from '../../types/hooks/AuthorsHook';
const Lines = () => {
const { authors } = useAuthors();
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}`);
};
return (
<>
<ButtonGroup>
<Button variant='dark' 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}
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,32 @@
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-15'>Жанры</th>
<th scope="col" className='w-15'>Автор</th>
<th scope="col" className='w-15'>Название</th>
<th scope='col' className='w-15'>Колич.</th>
<th scope='col' className='w-15'>Дата</th>
<th scope='col' className='w-15'>Описание</th>
<th scope='col'></th>
<th scope='col'></th>
<th scope='col'></th>
</tr>
</thead>
<tbody>
{children}
</tbody >
</Table >
);
};
LinesTable.propTypes = {
children: PropTypes.node,
};
export default LinesTable;

View File

@ -0,0 +1,36 @@
import PropTypes from 'prop-types';
import { PencilFill, PencilSquare, Trash3 } from 'react-bootstrap-icons';
const LinesTableRow = ({
index, line, onDelete, onEdit, onEditInPage,
}) => {
const handleAnchorClick = (event, action) => {
event.preventDefault();
action();
};
return (
<tr>
<th scope="row">{index + 1}</th>
<td>{line.type.name}</td>
<td>{line.author.name}</td>
<td>{line.ItName}</td>
<td>{line.count}</td>
<td>{line.date}</td>
<td>{line.desc}</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,
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,17 @@
.my-navbar {
background-color: #382F1E !important;
}
.my-navbar .link a:hover {
text-decoration: underline !important;
}
.ml-auto.link {
margin-left: auto;
}
.custom-btn {
background-color: black;
color: white;
/* другие необходимые свойства стиля */
}

View File

@ -0,0 +1,65 @@
import PropTypes from 'prop-types';
import {
Container, Nav, Navbar, Button,
} from 'react-bootstrap';
import { Link, useLocation } from 'react-router-dom';
// eslint-disable-next-line no-unused-vars
import Image from 'react-bootstrap/Image';
import './Navigation.css';
// import useCart from '../card/cartHook';
const Navigation = ({ routes }) => {
// const { getCartSum } = useCart();
const location = useLocation();
const indexPageLink = routes.find((route) => route.index === true);
const pages = routes.filter((route) => Object.prototype.hasOwnProperty.call(route, 'title'));
const storedUserData = localStorage.getItem('user');
const storedUser = storedUserData ? JSON.parse(storedUserData) : {};
const userName = storedUser && storedUser.handle ? storedUser.handle : '';
const isAdmin = userName.toLowerCase() === 'admin';
return (
<Navbar expand='md' className='my-navbar'>
<Container fluid>
<Navbar.Brand as={Link} to={indexPageLink?.path ?? '/'}>
Elitist
</Navbar.Brand>
<Navbar.Toggle aria-controls='main-navbar' />
<Navbar.Collapse id='main-navbar'>
<Nav className='ml-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>
{userName ? (
<>
<Button className="custom-btn" as={Link} to="/personalAccount">
{userName}
</Button>
{isAdmin && (
<Button className="custom-btn" as={Link} to="/page4">
Панель
</Button>
)}
</>
) : (
<Button className="custom-btn" as={Link} to="/personalAccountLogin">
Профиль
</Button>
)}
</Nav>
</Navbar.Collapse>
</Container>
</Navbar>
);
};
Navigation.propTypes = {
routes: PropTypes.array,
};
export default Navigation;

View File

@ -0,0 +1,22 @@
/* eslint-disable linebreak-style */
import { useEffect, useState } from 'react';
import AuthorsApiService from '../service/AuthorsApiService';
const useAuthors = () => {
const [authors, setAuthors] = useState([]);
const getAuthors = async () => {
const data = await AuthorsApiService.getAll();
setAuthors(data ?? []);
};
useEffect(() => {
getAuthors();
}, []);
return {
authors,
};
};
export default useAuthors;

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,6 @@
/* eslint-disable linebreak-style */
import ApiService from '../../api/ApiService';
const AuthorsApiService = new ApiService('authors');
export default AuthorsApiService;

View File

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

View File

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

View File

@ -0,0 +1,20 @@
import UsersApiService from './service/UsersApiService';
import useUser from './userHook';
const useSubmit = () => {
const { userLogin } = useUser();
const onSubmit = async (data) => {
const res1 = await UsersApiService.getByHandle(data.handle);
if (res1.length === 0) {
return 1;
}
if (res1[0].password !== data.password) {
return 2;
}
userLogin(res1[0]);
return 3;
};
return { onSubmit };
};
export default useSubmit;

View File

@ -0,0 +1,34 @@
import UsersApiService from './service/UsersApiService';
import useUser from './userHook';
const useSubmit = () => {
const { userLogin } = useUser();
const getNewUser = (formData) => {
const emailt = formData.email;
const handlet = formData.handle;
const passwordt = formData.password;
return {
email: emailt,
handle: handlet,
password: passwordt,
};
};
const onSubmit = async (data) => {
console.log(data);
const res1 = await UsersApiService.getByHandle(data.handle);
if (res1.length !== 0) {
return 1;
}
const res2 = await UsersApiService.getByEmail(data.email);
if (res2.length !== 0) {
return 2;
}
const newUser = getNewUser(data);
const curUser = await UsersApiService.create(newUser);
userLogin(curUser);
return 3;
};
return { onSubmit };
};
export default useSubmit;

View File

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

View File

@ -0,0 +1,22 @@
/* eslint-disable import/no-named-as-default */
/* eslint-disable import/extensions */
import { useContext } from 'react';
import { userLogin, userLogout } from './userReducer.js';
import UserContext from './UserContext.jsx';
const useUser = () => {
const context = useContext(UserContext);
if (!context) {
throw new Error('useUser должен использоваться внутри UserProvider');
}
const { dispatch } = useContext(UserContext);
return {
userLogout: () => dispatch(userLogout()),
userLogin: (user) => dispatch(userLogin(user)),
};
};
export default useUser;

View File

@ -0,0 +1,39 @@
const USER_KEY = 'user';
const USER_LOGIN = 'user/login';
const USER_LOGOUT = 'user/logout';
export const saveUser = (user) => {
localStorage.setItem(USER_KEY, JSON.stringify(user));
};
export const loadUser = (initialValue = []) => {
const userData = localStorage.getItem(USER_KEY);
if (userData) {
return JSON.parse(userData);
}
return initialValue;
};
export const userReducer = (state, action) => {
console.log(action);
switch (action.type) {
case USER_LOGOUT: {
return null;
}
case USER_LOGIN: {
return action.user;
}
default: {
throw new Error(`Unknown action: ${action.type}`);
}
}
};
export const userLogout = () => ({
type: USER_LOGOUT,
});
export const userLogin = (user) => ({
type: USER_LOGIN,
user,
});

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;

32
Laba 5/src/index.css Normal file
View File

@ -0,0 +1,32 @@
h1 {
font-family: Santa Catarina;
color: black;
}
h2 {
font-family: Santa Catarina;
color: black;
}
h3 {
font-family: Santa Catarina;
color: black;
}
h4 {
font-family: Santa Catarina;
color: black;
}
.btn-mw {
width: 100%;
}
body {
overflow-x: hidden;
background-color: #403928;
color: black;
font-family: Santa Catarina;
}
.header {
display: none;
}

109
Laba 5/src/main.jsx Normal file
View File

@ -0,0 +1,109 @@
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 ErrorPage from './pages/ErrorPage.jsx';
import Page1 from './pages/Page1.jsx';
import Page2 from './pages/Page2.jsx';
import Page3 from './pages/Page3.jsx';
import Page4 from './pages/Page4.jsx';
import PageEdit from './pages/PageEdit.jsx';
import Page5 from './pages/Page5.jsx';
import CatalogPage from './pages/CatalogPage.jsx';
import Registration from './pages/Registration.jsx';
// eslint-disable-next-line camelcase
import LK_page from './pages/LK_page.jsx';
import DetailPage from './pages/DetailPage.jsx';
import PersonalAccountLogin from './pages/PersonalAccountLogin.jsx';
import PersonalAccount from './pages/PersonalAccount.jsx';
import PersonalAccountRegister from './pages/PersonalAccountRegister.jsx';
const routes = [
{
index: true,
path: '/',
element: <Page1 />,
title: 'Главная страница',
},
{
path: '/page2',
element: <Page2 />,
title: 'Жанры',
},
{
path: '/page5',
element: <Page5 />,
title: 'Бестселлеры',
},
{
path: '/CatalogPage',
element: <CatalogPage />,
title: 'Каталог',
},
{
path: '/page3',
element: <Page3 />,
},
{
path: '/page4',
element: <Page4 />,
},
{
path: '/page-edit',
element: <PageEdit />,
},
{
path: '/Registration',
element: <Registration />,
},
{
path: '/LK_page',
element: <LK_page />,
},
{
path: '/detailpage/:name',
element: <DetailPage />,
// title: 'Детальная страница',
},
{
path: '/personalAccountLogin',
element: <PersonalAccountLogin />,
},
{
path: '/personalAccount',
element: <PersonalAccount />,
},
{
path: '/personalAccountRegister',
element: <PersonalAccountRegister/>,
},
];
const router = createBrowserRouter([
{
path: '/',
element: <App routes={routes} />,
children: routes,
errorElement: <ErrorPage />,
},
{
path: '/',
element: <App routes={routes} />,
children: routes,
errorElement: <Registration />,
},
{
path: '/',
element: <App routes={routes} />,
children: routes,
errorElement: <LK_page />,
},
]);
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>,
);

View File

@ -0,0 +1,16 @@
/* eslint-disable linebreak-style */
/* eslint-disable no-tabs */
/* eslint-disable linebreak-style */
/* eslint-disable import/extensions */
/* eslint-disable linebreak-style */
/* eslint-disable import/no-unresolved */
/* eslint-disable linebreak-style */
/* eslint-disable quotes */
import Catalog from "../components/lines/serverCatalog/Catalog";
const CatalogPage = () => {
return (
<Catalog />
);
};
export default CatalogPage;

View File

@ -0,0 +1,58 @@
/* eslint-disable no-shadow */
import { useParams } from 'react-router-dom';
import { useState, useEffect } from 'react';
import '../pagescss/DetailPage.css';
import LinesApiService from '../components/lines/service/LinesApiService';
const DetailPage = () => {
const { name } = useParams();
const [desc, setDescription] = useState('');
const [date, setDates] = useState('');
const [count, setCount] = useState('');
useEffect(() => {
const loadDataFromServer = async (name) => {
try {
const data = await LinesApiService.getAll(`?ItName=${name}`);
setDescription(data[0].desc);
setDates(data[0].date);
setCount(data[0].count);
} catch (error) {
console.log('error');
console.error(error);
}
};
loadDataFromServer(name);
}, [name]);
return (
<div className="container-fluid">
<div id="container1">
<div className="row1">
<div className="info">
<div className="info-text">
<h2>Описание</h2>
<h3>{desc}</h3>
</div>
</div>
<div className="info">
<div className="info-text">
<h2>Дата издания</h2>
<h3 id="additional-info1">{date}</h3>
</div>
</div>
<div className="info">
<div className="info-text">
<h2>Количество</h2>
<h3 id="additional-info1">{count}</h3>
</div>
</div>
</div>
</div>
</div>
);
};
export default DetailPage;

View File

@ -0,0 +1,23 @@
/* eslint-disable no-use-before-define */
/* eslint-disable react/jsx-no-comment-textnodes */
import { Route, Switch, useParams } from 'react-router-dom';
import DetailPage from './DetailPage.jsx';
// ...
const App = () => {
return (
<Switch>
// eslint-disable-next-line no-use-before-define, no-use-before-define
<Route path="/detailpage/:name" component={DetailPageRoute} />
</Switch>
);
};
const DetailPageRoute = () => {
const { name } = useParams();
return <DetailPage name={name} />;
};
export default App;

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,39 @@
/* eslint-disable linebreak-style */
/* eslint-disable camelcase */
/* eslint-disable linebreak-style */
// eslint-disable linebreak-style /
// eslint-disable camelcase /
// eslint-disable linebreak-style /
// eslint-disable-next-line no-unused-vars
import React from 'react';
function LK_page() {
return (
<article className="container-fluid p-2">
<div className="row justify-content-center align-items-center h-75">
<h1 className="text-center">Личный кабинет</h1>
<form className="col-md-6 m-0">
<div className="mb-3">
<label htmlFor="lastname" className="form-label">Фамилия</label>
<input type="text" className="form-control" id="lastname" placeholder="Введите вашу фамилию" />
</div>
<div className="mb-3">
<label htmlFor="firstname" className="form-label">Имя</label>
<input type="text" className="form-control" id="firstname" placeholder="Введите ваше имя" />
</div>
<div className="mb-3">
<label htmlFor="status" className="form-label">Статус</label>
<select className="form-control" id="status">
<option>Студент</option>
<option>Школьник</option>
<option>Работающий</option>
</select>
</div>
<button className="btn btn-primary text-center d-flex justify-content-center" style={{ backgroundColor: 'black', color: 'white' }}>Сохранить</button>
</form>
</div>
</article>
);
}
export default LK_page;

View File

@ -0,0 +1,47 @@
.img-fluid {
width: 100%;
height: auto;
}
@media (max-width: 576px) {
h1 {
font-size: 48px;
text-align: center;
}
h2 {
font-size: 24px;
text-align: center;
}
h3 {
font-size: 18px;
text-align: center;
}
h4 {
font-size: 36px;
text-align: center;
}
}
@media (min-width: 576px) {
h1 {
font-size: 248px;
text-align: center;
margin-top: 30px;
}
h2 {
font-size: 62px;
text-align: center;
margin-top: 15px;
}
h3 {
font-size: 30px;
text-align: center;
margin-top: 10px;
}
h4 {
font-size: 236px;
text-align: center;
margin-top: 10px;
}
}

View File

@ -0,0 +1,32 @@
// import React from 'react';
import styles from './Page1.css';
const Page1 = () => {
return (
<article className="container-fluid mt-4">
<div className="row justify-content-center align-items-center">
<div className="col-md-6">
<img
src="src/assets/gl.PNG"
className="img-fluid"
style={{ maxWidth: '600px', maxHeight: '625px' }}
alt=""
/>
</div>
<div className={`col-md-6 text-center ${styles.Page1}`}>
<div className="row align-items-center">
<div className="col-12">
<h1 className={`${styles.h1} ${styles.Page1}`}>Elitist</h1>
<h2 className={`${styles.h2} ${styles.Page1}`}>
Моя родина там, где моя библиотека
</h2>
<h3 className={`${styles.h3} ${styles.Page1}`}>Эразм Роттердамский</h3>
</div>
</div>
</div>
</div>
</article>
);
};
export default Page1;

View File

@ -0,0 +1,47 @@
const Page2 = () => {
return (
<article className="container-fluid py-5" style={{ paddingLeft: 0 }}>
<div className="row justify-content-center align-items-center">
<div className="col-md-6 text-center">
<h1 style={{ marginTop: '5px' }}>ЖАНРЫ</h1>
<ul style={{ listStyleType: 'none', padding: 0 }}>
<li><a href="./magicheskiy-realizm.html"><h3 style={{ marginTop: '15px' }}>I Магический реализм</h3></a></li>
<li><a href="./filosofskaya-proza.html"><h3 style={{ marginTop: '15px' }}>II Философская проза</h3></a></li>
<li><a href="./metafizicheskaya-poeziya.html"><h3 style={{ marginTop: '15px' }}>III Метафизическая поэзия</h3></a></li>
<li><a href="./psihologicheskiy-roman.html"><h3 style={{ marginTop: '15px' }}>IV Психологический роман</h3></a></li>
<li><a href="./filosofskiy-roman.html"><h3 style={{ marginTop: '15px' }}>V Философский роман</h3></a></li>
</ul>
</div>
<div className="col-md-6 text-center">
<ul style={{ listStyleType: 'none', padding: 0 }}>
<li><a href="./epicheskaya-poesy.html"><h3 style={{ marginTop: '15px' }}>VI Эпическая поэзия</h3></a></li>
<li><a href="./socz-real.html"><h3 style={{ marginTop: '15px' }}>VII Социальный реализм</h3></a></li>
<li><a href="./fant-roman.html"><h3 style={{ marginTop: '15px' }}>VIII Фантастический роман</h3></a></li>
<li><a href="./avt-dram.html"><h3 style={{ marginTop: '15px' }}>IX Авторская драматургия</h3></a></li>
<li><a href="./Eksp-proza.html"><h3 style={{ marginTop: '15px' }}>X Авторская драматургия</h3></a></li>
</ul>
<div className="row justify-content-center">
<div className="col-md-3 mb-4 text-center">
<img
src="src/assets/4j.png"
alt="4j"
className="img-fluid"
style={{ width: '150px', margin: '10px', marginTop: '80px' }}
/>
</div>
<div className="col-md-3 mb-4 text-center">
<img
src="src/assets/4j.png"
alt="4j"
className="img-fluid"
style={{ width: '150px', margin: '10px', marginTop: '80px' }}
/>
</div>
</div>
</div>
</div>
</article>
);
};
export default Page2;

View File

@ -0,0 +1,47 @@
import { useState } from 'react';
import { Button, Form } from 'react-bootstrap';
// eslint-disable-next-line import/newline-after-import
import { Link } from 'react-router-dom';
const Page3 = () => {
const [validated, setValidated] = useState(false);
const handleSubmit = (event) => {
const form = event.currentTarget;
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
setValidated(true);
};
return (
<div className="row justify-content-center">
<div className="col-md-6 m-0 text-center">
<Form noValidate validated={validated} onSubmit={handleSubmit}>
<h1>Вход</h1>
<Form.Group controlId="login">
<Form.Label style={{ fontSize: '20px' }}>Логин</Form.Label>
<Form.Control type="text" name="login" required />
</Form.Group>
<Form.Group controlId="password">
<Form.Label style={{ fontSize: '20px' }}>Пароль</Form.Label>
<Form.Control type="password" name="password" required />
</Form.Group>
<p className="mb-2 text-white">
Нет аккаунта?
<Link to="/registration" style={{ color: 'black' }}>
Зарегистрироваться
</Link>
</p>
<Link to="/LK_page">
<Button className="btn btn-custom w-50 mx-auto" type="submit" style={{ backgroundColor: 'black' }}>
Войти
</Button>
</Link>
</Form>
</div>
</div>
);
};
export default Page3;

View File

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

View File

@ -0,0 +1,52 @@
/* eslint-disable linebreak-style */
/* eslint-disable no-trailing-spaces */
/* eslint-disable linebreak-style */
/* eslint-disable quotes */
const Page5 = () => {
return (
<article className="container py-5">
<h3 className="col-md-3 mb-4 text-center mx-auto">Бестселлеры</h3>
<div className="row justify-content-center">
<div className="col-md-3 mb-4 text-center">
<img
src="src/assets/kafka.jpg"
alt=""
className="img-fluid"
style={{ maxWidth: "260px", maxHeight: "372px" }}
/>
<h3 className="h7 mt-3">Ф.Кафка Превращение</h3>
</div>
<div className="col-md-3 mb-4 text-center">
<img
src="src/assets/pandp.jpg"
alt=""
className="img-fluid"
style={{ maxWidth: "260px", maxHeight: "372px" }}
/>
<h3 className="h7 mt-3">Д.Остен Гордость и предубеждение</h3>
</div>
<div className="col-md-3 mb-4 text-center">
<img
src="src/assets/leot.jpg"
alt=""
className="img-fluid"
style={{ maxWidth: "260px", maxHeight: "372px" }}
/>
<h3 className="h7 mt-3">Л.Толстой Смерть Ивана Ильича</h3>
</div>
<div className="col-md-3 mb-4 text-center">
<img
src="src/assets/stranger.jpg"
alt=""
className="img-fluid"
style={{ maxWidth: "260px", maxHeight: "372px" }}
/>
<h3 className="h7 mt-3">А.Камю Посторонний</h3>
</div>
</div>
</article>
);
};
export default Page5;

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,96 @@
/* eslint-disable no-restricted-globals */
import { useEffect, useState } from 'react';
import {
Container, Row, Col, Card, Form, Button,
} from 'react-bootstrap';
import { Link } from 'react-router-dom';
const PersonalAccount = () => {
const [validated, setValidated] = useState(false);
const [name, setName] = useState('');
const [surname, setSurname] = useState('');
const [email, setEmail] = useState('');
useEffect(() => {
const storedUserData = localStorage.getItem('user');
const storedUser = storedUserData ? JSON.parse(storedUserData) : {};
if (storedUser) {
setName(storedUser.handle || '');
setSurname(storedUser.surname || '');
setEmail(storedUser.email || '');
}
}, []);
const handleSubmit = (event) => {
const form = event.currentTarget;
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
} else {
const storedUserData = localStorage.getItem('user');
const storedUser = storedUserData ? JSON.parse(storedUserData) : {};
const newUserData = {
...storedUser,
handle: name,
surname,
email,
};
localStorage.setItem('user', JSON.stringify(newUserData));
}
setValidated(true);
};
const handleLogout = () => {
localStorage.removeItem('user');
history.push('/');
};
return (
<Container className="h-100">
<Row className="justify-content-center align-items-center h-100">
<Col xs={12} md={9} lg={7} xl={6}>
<Card style={{ borderRadius: '15px', borderColor: 'black' }}>
<Card.Body className="p-5">
<h2 className="text-uppercase text-center mb-5">Личный кабинет</h2>
<Form noValidate validated={validated} onSubmit={handleSubmit}>
<Form.Group className="mb-4">
<Form.Label>Ваше имя</Form.Label>
<Form.Control type="text" value={name} onChange={(e) => setName(e.target.value)} readOnly />
</Form.Group>
<Form.Group className="mb-4">
<Form.Label>Ваша фамилия</Form.Label>
<Form.Control type="text" value={surname} onChange={(e) => setSurname(e.target.value)} />
</Form.Group>
<Form.Group className="mb-4">
<Form.Label>Ваш адрес электронной почты</Form.Label>
<Form.Control type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
</Form.Group>
<div className="d-flex justify-content-center">
<Button variant="warning" type="submit" id="saveButton">
Сохранить
</Button>
</div>
<div className="d-flex justify-content-center mt-2">
<Link className="btn btn-outline-danger" type="button" onClick={handleLogout} to="/">
Выйти
</Link>
</div>
</Form>
</Card.Body>
</Card>
</Col>
</Row>
</Container>
);
};
export default PersonalAccount;

View File

@ -0,0 +1,98 @@
/* eslint-disable no-alert */
import {
Container, Row, Col, Card, Form, Button,
} from 'react-bootstrap';
import { useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import useUser from '../components/users/userHook';
import useSubmit from '../components/users/loginHook';
const PersonalAccountLogin = () => {
const [validated, setValidated] = useState(false);
const { userLogin } = useUser();
const { onSubmit } = useSubmit();
const navigate = useNavigate();
const handleSubmit = async (event) => {
const form = event.currentTarget;
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
} else {
event.preventDefault();
setValidated(true);
const formData = {
handle: form.elements.formHandle.value,
password: form.elements.formPassword.value,
};
const result = await onSubmit(formData);
if (result === 1) {
alert('Пользователь с таким хэндлом не существует');
} else if (result === 2) {
alert('Введен неверный пароль');
} else if (result === 3) {
userLogin(formData);
navigate('/PersonalAccount');
}
}
};
return (
<Container>
<Row className="d-flex justify-content-center align-items-center h-100">
<Col xs={12} md={9} lg={7} xl={6}>
<Card style={{ borderRadius: '15px', borderColor: 'black' }}>
<Card.Body className="p-5">
<h2 className="text-uppercase text-center mb-5">Войти</h2>
<Form noValidate validated={validated} onSubmit={handleSubmit}>
<Form.Group className="mb-4">
<Form.Control type="text" id="formHandle" required />
<Form.Control.Feedback>Имя заполнено</Form.Control.Feedback>
<Form.Control.Feedback type="invalid">Имя не заполнено</Form.Control.Feedback>
<Form.Label htmlFor="formHandle">Имя</Form.Label>
</Form.Group>
<Form.Group className="mb-4">
<Form.Control type="password" id="formPassword" size="lg" required />
<Form.Control.Feedback>Пароль заполнен</Form.Control.Feedback>
<Form.Control.Feedback type="invalid">Пароль не заполнен</Form.Control.Feedback>
<Form.Label htmlFor="formPassword">Пароль</Form.Label>
</Form.Group>
<Form.Group className="mb-2" controlId="formRememberMe">
<Form.Check type="checkbox" label="Запомнить меня" />
</Form.Group>
<p className="text-center text-muted mb-0">
Забыли пароль?{' '}
<Link to='/PasswordRecovery' className="fw-bold text-body" style={{ color: 'black', textDecoration: 'none' }}>
<u>Восстановление пароля</u>
</Link>
</p>
<div className="d-flex justify-content-center">
<Button to='/personalAccount' type="submit" className="btn-block btn-warning text-body mb-0">
Вход
</Button>
</div>
<p className="text-center text-muted mb-0">
У вас нет аккаунта?{' '}
<Link to='/personalAccountRegister' className="fw-bold text-body" style={{ color: 'black', textDecoration: 'none' }}>
<u>Регистрация</u>
</Link>
</p>
</Form>
</Card.Body>
</Card>
</Col>
</Row>
</Container>
);
};
export default PersonalAccountLogin;

View File

@ -0,0 +1,128 @@
/* eslint-disable no-alert */
import {
Container, Row, Col, Card, Form, Button,
} from 'react-bootstrap';
import { useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import UsersApiService from '../components/users/service/UsersApiService';
import useSubmit from '../components/users/regHook';
import useUser from '../components/users/userHook';
const PersonalAccountRegister = () => {
const [validated, setValidated] = useState(false);
const { userLogin } = useUser();
const { onSubmit } = useSubmit();
const navigate = useNavigate();
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const handleSubmit = async (event) => {
const form = event.currentTarget;
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
} else {
event.preventDefault();
setValidated(true);
const formData = {
handle: name,
email,
password,
};
const result = await onSubmit(formData);
if (result === 1) {
alert('Пользователь с таким хэндлом уже существует');
} else if (result === 2) {
alert('Пользователь с таким email уже существует');
} else if (result === 3) {
await UsersApiService.create(formData);
userLogin(formData);
navigate('/PersonalAccount');
}
}
};
return (
<Container className="h-100">
<Row className="justify-content-center align-items-center h-100">
<Col xs={12} md={9} lg={7} xl={6}>
<Card style={{ borderRadius: '15px', borderColor: 'gold' }}>
<Card.Body className="p-5">
<h2 className="text-uppercase text-center mb-5">Создать учетную запись</h2>
<Form noValidate validated={validated} onSubmit={handleSubmit}>
<Form.Group className="mb-4">
<Form.Control
type="text"
id="formHandle"
value={name}
onChange={(e) => setName(e.target.value)}
required
/>
<Form.Control.Feedback>Имя заполнено</Form.Control.Feedback>
<Form.Control.Feedback type="invalid">Имя не заполнено</Form.Control.Feedback>
<Form.Label>Ваше имя</Form.Label>
</Form.Group>
<Form.Group className="mb-4">
<Form.Control
type="email"
id="formEmail"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
/>
<Form.Control.Feedback>Email заполнен</Form.Control.Feedback>
<Form.Control.Feedback type="invalid">Email не заполнен</Form.Control.Feedback>
<Form.Label>Ваш адрес электронной почты</Form.Label>
</Form.Group>
<Form.Group className="mb-4">
<Form.Control
type="password"
id="formPassword"
size="lg"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
/>
<Form.Control.Feedback>Пароль заполнен</Form.Control.Feedback>
<Form.Control.Feedback type="invalid">Пароль не заполнен</Form.Control.Feedback>
<Form.Label htmlFor="form3Example4cg">Пароль</Form.Label>
</Form.Group>
<Form.Group controlId="formCheckbox" className="d-flex justify-content-center mb-5">
<Form.Check type="checkbox" label={
<span>
Я согласен со всеми утверждениями в{' '}
<a href="#!" className="text-body">
<u>Условиях обслуживания</u>
</a>
</span>
} />
</Form.Group>
<div className="d-flex justify-content-center">
<Button to='/personalAccount' type="submit" className="btn-block btn-warning text-body mb-0">
Вход
</Button>
</div>
<p className="text-center text-muted mb-0">
У вас уже есть учетная запись?{' '}
<Link to='/PersonalAccountLogin' className="fw-bold text-body" style={{ color: 'black', textDecoration: 'none' }}>
<u>Войдите здесь</u>
</Link>
</p>
</Form>
</Card.Body>
</Card>
</Col>
</Row>
</Container>
);
};
export default PersonalAccountRegister;

View File

@ -0,0 +1,44 @@
/* eslint-disable linebreak-style */
import { useState } from 'react';
import { Button, Form } from 'react-bootstrap';
// import { Link } from 'react-router-dom';
const Registration = () => {
const [validated, setValidated] = useState(false);
const handleSubmit = (event) => {
const form = event.currentTarget;
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
setValidated(true);
};
return (
<div className="row justify-content-center">
<div className="col-md-6 m-0 text-center">
<div className="registration-container">
<h1 style={{ textAlign: 'center' }}>ВХОД</h1>
<Form noValidate validated={validated} onSubmit={handleSubmit}>
<Form.Group controlId="login">
<Form.Label style={{ fontSize: '20px' }}>Логин</Form.Label>
<Form.Control type="text" name="login" required />
</Form.Group>
<Form.Group controlId="password">
<Form.Label style={{ fontSize: '20px' }}>Пароль</Form.Label>
<Form.Control type="password" name="password" required />
</Form.Group>
<Form.Group className="mb-2" controlId="email">
<Form.Label style={{ fontSize: '20px' }}>E-mail</Form.Label>
<Form.Control type="email" name="email" placeholder="name@example.ru" required />
</Form.Group>
<Button className="btn btn-custom w-50 mx-auto" type="submit" style={{ backgroundColor: 'black' }}>
Зарегистрироваться
</Button>
</Form>
</div>
</div>
</div>
);
};
export default Registration;

View File

@ -0,0 +1,70 @@
#image-container {
position: relative;
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
#image-container img {
width: auto;
height: auto;
max-width: 100%;
max-height: 70vh;
object-fit: contain;
}
#image-container .text-overlay {
position: absolute;
bottom: 10px;
left: 50%;
transform: translateX(-50%);
text-align: center;
color: #fff;
font-size: 30px;
width: 100%;
}
#container1 {
position: relative;
display: flex;
flex-direction: column;
gap: 2%;
color: #fafafa;
justify-content: center;
align-items: center;
text-align: center;
}
.row1 {
grid-column: span 2;
width: 100%;
}
.info {
background-color: #382F1E;
padding: 2%;
border: 5px solid #1b1818;
border-radius: 5px;
text-align: center;
word-wrap: break-word;
margin-bottom: 2%;
}
.info-text {
font-size: 20px;
width: 70%;
margin: 10px auto;
}
#container1 .info-text {
font-size: 16px;
width: 60%;
}
#container1 .info-title {
font-size: 20px;
width: 60%;
margin-bottom: 10px;
}

13
Laba 5/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,
},
});