This commit is contained in:
Галина Федоренко 2024-01-14 11:47:44 +04:00
commit 8031c983af
81 changed files with 8693 additions and 0 deletions

24
.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
.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
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

143
data.json Normal file

File diff suppressed because one or more lines are too long

15
index.html Normal file
View File

@ -0,0 +1,15 @@
<html lang="ru">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/src/img/book.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Книжный подвальчик</title>
</head>
<body>
<div id="root" class="h-100 d-flex flex-column"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>

15
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
json-server.json Normal file
View File

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

5936
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

38
package.json Normal file
View File

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

3
public/favicon.svg Normal file
View File

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

After

Width:  |  Height:  |  Size: 463 B

37
src/App.jsx Normal file
View File

@ -0,0 +1,37 @@
import PropTypes from 'prop-types';
import { Outlet } from 'react-router-dom';
import { useState } from 'react';
import Footer from './components/footer/Footer.jsx';
import Navigation from './components/navigation/Navigation.jsx';
import { CurrentUserContext } from './contexts/CurrentUserContext';
const App = ({ routes }) => {
const [currentUser, setCurrentUser] = useState(null);
return (
<>
<CurrentUserContext.Provider value={{
currentUser,
setCurrentUser,
}}>
<Navigation routes={routes}></Navigation>
<main className='w-100 flex-fill d-flex p-0 m-0'>
<Outlet />
</main>
<Footer />
</CurrentUserContext.Provider>
{/* <Navigation routes={routes}></Navigation>
<main className='w-100 flex-fill d-flex justify-content-center p-0 m-0'>
<Outlet />
</main>
<Footer /> */}
</>
);
};
App.propTypes = {
routes: PropTypes.array,
};
export default App;

BIN
src/assets/200.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

BIN
src/assets/banner1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 640 KiB

BIN
src/assets/banner2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 812 KiB

BIN
src/assets/banner3.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 767 KiB

BIN
src/assets/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 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,48 @@
import PropTypes from 'prop-types';
import { Button, Form } from 'react-bootstrap';
import { useNavigate } from 'react-router-dom';
import useBooksItemForm from '../hooks/BooksItemFormHook';
import BooksItemForm from './BooksItemForm.jsx';
const BooksForm = ({ id }) => {
const navigate = useNavigate();
const {
item,
validated,
handleSubmit,
handleChange,
} = useBooksItemForm(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}>
<BooksItemForm 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>
</>
);
};
BooksForm.propTypes = {
id: PropTypes.string,
};
export default BooksForm;

View File

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

View File

@ -0,0 +1,39 @@
/* eslint-disable max-len */
import PropTypes from 'prop-types';
import imgPlaceholder from '../../../assets/200.png';
import Input from '../../input/Input.jsx';
import Select from '../../input/Select.jsx';
import useGenres from '../../genres/hooks/GenresHook';
import './BooksItemForm.css';
const BooksItemForm = ({ item, handleChange }) => {
const { genres } = useGenres();
return (
<>
<div className='text-center'>
<img id='image-preview' className='rounded' alt='placeholder'
src={item.image || imgPlaceholder} />
</div>
<Input name='nameBook' label='Название' value={item.nameBook} onChange={handleChange}
type='text' required />
<Input name='author' label='Автор' value={item.author} onChange={handleChange}
type='text' required />
<Select values={genres} name='genreId' label='Жанр' value={item.genreId} onChange={handleChange}
required />
<Input name='year' label='Год' value={item.year} onChange={handleChange}
type='text' required />
<Input name='description' label='Описание' value={item.description} onChange={handleChange}
type='text' required />
<Input name='image' label='Изображение' onChange={handleChange}
type='file' accept='image/*' />
</>
);
};
BooksItemForm.propTypes = {
item: PropTypes.object,
handleChange: PropTypes.func,
};
export default BooksItemForm;

View File

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

View File

@ -0,0 +1,36 @@
import { useSearchParams } from 'react-router-dom';
import useGenres from '../../genres/hooks/GenresHook';
const useGenreFilter = () => {
const filterName = 'genre';
const [searchParams, setSearchParams] = useSearchParams();
const { genres } = useGenres();
const handleFilterChange = (event) => {
const genre = event.target.value;
if (genre) {
searchParams.set(filterName, event.target.value);
} else {
searchParams.delete(filterName);
}
setSearchParams(searchParams);
};
return {
genres,
currentFilter: searchParams.get(filterName) || '',
handleFilterChange,
};
};
export const useBookIdFilter = () => {
const filterName = 'book';
const [searchParams] = useSearchParams();
return searchParams.get(filterName) || '';
};
export default useGenreFilter;

View File

@ -0,0 +1,45 @@
import { useState } from 'react';
import useModal from '../../modal/ModalHook';
import useBooksItemForm from './BooksItemFormHook';
const useBooksFormModal = (booksChangeHandle) => {
const { isModalShow, showModal, hideModal } = useModal();
const [currentId, setCurrentId] = useState(0);
const {
item,
validated,
handleSubmit,
handleChange,
resetValidity,
} = useBooksItemForm(currentId, booksChangeHandle);
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 useBooksFormModal;

View File

@ -0,0 +1,66 @@
import { useEffect, useState } from 'react';
import BooksApiService from '../service/BooksApiService';
const useBooks = (genreFilter) => {
const [booksRefresh, setBooksRefresh] = useState(false);
const [books, setBooks] = useState([]);
const handleBooksChange = () => setBooksRefresh(!booksRefresh);
const getBooks = async () => {
let expand = '?_expand=genre';
if (genreFilter) {
expand = `${expand}&genreId=${genreFilter}`;
}
const data = await BooksApiService.getAll(expand);
setBooks(data ?? []);
};
useEffect(() => {
getBooks();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [booksRefresh, genreFilter]);
return {
books,
handleBooksChange,
};
};
export const useBookSearch = (searchValue) => {
const [books, setBooks] = useState([]);
const getBooks = async () => {
const expand = `?q=${searchValue}`;
const data = await BooksApiService.getAll(expand);
setBooks(data ?? []);
};
useEffect(() => {
getBooks();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [searchValue]);
return {
books,
};
};
export const useBook = (bookId) => {
const [booksRefresh] = useState(false);
const [book, setBook] = useState([]);
const getBook = async () => {
const expand = '?_expand=genre';
const data = await BooksApiService.get(bookId, expand);
setBook(data ?? []);
};
useEffect(() => {
getBook();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [booksRefresh, bookId]);
return book;
};
export default useBooks;

View File

@ -0,0 +1,86 @@
/* eslint-disable prefer-destructuring */
import { useState } from 'react';
import toast from 'react-hot-toast';
import getBase64FromFile from '../../utils/Base64';
import BooksApiService from '../service/BooksApiService';
import useBooksItem from './BooksItemHook';
const useBooksItemForm = (id, booksChangeHandle) => {
const { item, setItem } = useBooksItem(id);
const [validated, setValidated] = useState(false);
const resetValidity = () => {
setValidated(false);
};
const getBookObject = (formData) => {
const nameBook = formData.nameBook;
const author = formData.author;
const genreId = parseInt(formData.genreId, 10);
const year = formData.year;
const description = formData.description;
const image = formData.image.startsWith('data:image') ? formData.image : '';
console.log();
return {
nameBook: nameBook.toString(),
author: author.toString(),
genreId: genreId.toString(),
year: year.toString(),
description: description.toString(),
image,
};
};
const handleImageChange = async (event) => {
const { files } = event.target;
const file = await getBase64FromFile(files.item(0));
setItem({
...item,
image: file,
});
};
const handleChange = (event) => {
if (event.target.type === 'file') {
handleImageChange(event);
return;
}
const inputName = event.target.name;
const inputValue = event.target.type === 'checkbox' ? event.target.checked : event.target.value;
setItem({
...item,
[inputName]: inputValue,
});
};
const handleSubmit = async (event) => {
const form = event.currentTarget;
event.preventDefault();
event.stopPropagation();
const body = getBookObject(item);
console.log(item);
if (form.checkValidity()) {
if (id === undefined) {
await BooksApiService.create(body);
} else {
await BooksApiService.update(id, body);
}
if (booksChangeHandle) booksChangeHandle();
toast.success('Элемент успешно сохранен', { id: 'BooksTable' });
return true;
}
setValidated(true);
return false;
};
return {
item,
validated,
handleSubmit,
handleChange,
resetValidity,
};
};
export default useBooksItemForm;

View File

@ -0,0 +1,36 @@
import { useEffect, useState } from 'react';
import BooksApiService from '../service/BooksApiService';
const useBooksItem = (id) => {
const emptyItem = {
id: '',
nameBook: '',
author: '',
genreId: '',
year: '',
description: '',
image: '',
};
const [item, setItem] = useState({ ...emptyItem });
const getItem = async (itemId = undefined) => {
if (itemId && itemId > 0) {
const data = await BooksApiService.get(itemId);
setItem(data);
} else {
setItem({ ...emptyItem });
}
};
useEffect(() => {
getItem(id);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [id]);
return {
item,
setItem,
};
};
export default useBooksItem;

View File

@ -0,0 +1,54 @@
import { useEffect, useState } from 'react';
import FavoriteBooksApiService from '../service/FavoriteBooksApiService';
const useFavoriteBooks = (userFilter) => {
const [booksRefresh, setBooksRefresh] = useState(false);
const [books, setBooks] = useState([]);
const refreshBooks = () => setBooksRefresh(!booksRefresh);
const getBooks = async () => {
if (!userFilter) {
setBooks([]);
return;
}
let expand = '?_expand=book';
if (userFilter) {
expand = `${expand}&userId=${userFilter}`;
}
const data = await FavoriteBooksApiService.getAll(expand);
setBooks(data ?? []);
};
useEffect(() => {
getBooks();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [booksRefresh, userFilter]);
return { favoriteBooks: books.map((obj) => obj.book), refreshBooks };
};
export const useFavoriteBook = (userId, bookId) => {
const [booksRefresh] = useState(false);
const [book, setBooks] = useState([]);
const getBook = async () => {
if (!userId || !bookId) {
setBooks([]);
return;
}
let expand = '?_expand=book';
expand = `${expand}&userId=${userId}&bookId=${bookId}`;
const data = await FavoriteBooksApiService.getAll(expand);
setBooks(data ?? []);
};
useEffect(() => {
getBook();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [booksRefresh, userId, bookId]);
return book;
};
export default useFavoriteBooks;

View File

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

View File

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

View File

@ -0,0 +1,82 @@
import { useState, useEffect, useContext } from 'react';
import { useSearchParams } from 'react-router-dom';
import { Button, ButtonGroup } from 'react-bootstrap';
import useCart from '../../cart/CartHook';
import Select from '../../input/Select.jsx';
import ModalConfirm from '../../modal/ModalConfirm.jsx';
import ModalForm from '../../modal/ModalForm.jsx';
import BooksItemForm from '../form/BooksItemForm.jsx';
import useBooksDeleteModal from '../hooks/BooksDeleteModalHook';
import useGenreFilter from '../hooks/BooksFilterHook';
import useBooksFormModal from '../hooks/BooksFormModalHook';
import { useBookSearch} from '../hooks/BooksHook';
import BooksTable from './BooksTable.jsx';
import BooksTableRow from './BooksTableRow.jsx';
import Input from '../../input/Input.jsx';
const Books = () => {
/* const { genres, currentFilter, handleFilterChange } = useGenreFilter();
const { books, handleBooksChange } = useBooks(currentFilter); */
const [searchParams, setSearchParams] = useSearchParams();
const [searchValue, setSearchValue] = useState(searchParams.get('q') || '');
const { books, handleBooksChange } = useBookSearch(searchValue);
const {
isDeleteModalShow,
showDeleteModal,
handleDeleteConfirm,
handleDeleteCancel,
} = useBooksDeleteModal(handleBooksChange);
const {
isFormModalShow,
isFormValidated,
showFormModal,
currentItem,
handleItemChange,
handleFormSubmit,
handleFormClose,
} = useBooksFormModal(handleBooksChange);
useEffect(() => {
setSearchParams({ q: searchValue });
}, [searchValue]);
return (
<>
<ButtonGroup>
<Button variant='info' onClick={() => showFormModal()}>
Добавить книгу
</Button>
</ButtonGroup>
{/* <Select className='mt-2' values={genres} label='Фильтр по жанрам'
value={currentFilter} onChange={handleFilterChange} /> */}
<Input name='search' value = {searchValue} onChange={(e) => setSearchValue(e.target.value)}
type='text' required />
<BooksTable>
{
books.map((book, index) =>
<BooksTableRow key={book.id}
index={index} book={book}
onDelete={() => showDeleteModal(book.id)}
onEdit={() => showFormModal(book.id)}
/>)
}
</BooksTable>
<ModalConfirm show={isDeleteModalShow}
onConfirm={handleDeleteConfirm} onClose={handleDeleteCancel}
title='Удаление' message='Удалить элемент?' />
<ModalForm show={isFormModalShow} validated={isFormValidated}
onSubmit={handleFormSubmit} onClose={handleFormClose}
title='Редактирование'>
<BooksItemForm item={currentItem} handleChange={handleItemChange} />
</ModalForm>
</>
);
};
export default Books;

View File

@ -0,0 +1,30 @@
import PropTypes from 'prop-types';
import { Table } from 'react-bootstrap';
const BooksTable = ({ 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' className='w-25'>Описание</th>
<th scope='col'></th>
<th scope='col'></th>
</tr>
</thead>
<tbody>
{children}
</tbody >
</Table >
);
};
BooksTable.propTypes = {
children: PropTypes.node,
};
export default BooksTable;

View File

@ -0,0 +1,37 @@
/* eslint-disable max-len */
import PropTypes from 'prop-types';
import {
PencilFill, Trash3,
} from 'react-bootstrap-icons';
import useGenres from '../../genres/hooks/GenresHook';
const BooksTableRow = ({
index, book, onDelete, onEdit,
}) => {
const handleAnchorClick = (event, action) => {
event.preventDefault();
action();
};
return (
<tr>
<th scope="row">{index + 1}</th>
<td>{book.nameBook}</td>
<td>{book.author}</td>
<td>{book.genreId}</td>
<td>{book.year}</td>
<td>{book.description}</td>
<td><a href="#" onClick={(event) => handleAnchorClick(event, onEdit)}><PencilFill /></a></td>
<td><a href="#" onClick={(event) => handleAnchorClick(event, onDelete)}><Trash3 /></a></td>
</tr>
);
};
BooksTableRow.propTypes = {
index: PropTypes.number,
book: PropTypes.object,
onDelete: PropTypes.func,
onEdit: PropTypes.func,
};
export default BooksTableRow;

View File

@ -0,0 +1,37 @@
/* eslint-disable linebreak-style */
/* eslint-disable no-tabs */
import PropTypes from 'prop-types';
import { Button } from 'react-bootstrap';
import { Link } from 'react-router-dom/dist';
import useCardBook from './CardBookHook';
import '../../pages/styles/Catalog.css';
const BookCard = ({ book, refreshFunc }) => {
const {
currentUser,
updateFavorite,
} = useCardBook(book, refreshFunc);
return (
<div className="col-12 col-md-6 col-lg-4 col-xl-3">
<div className='book'>
<Link to={`/catalog?book=${book.id}`}>
<img src={book.image} alt={book.nameBook} className="img-fluid rounded-3" id="img-fluid" />
</Link>
<h3>{book.nameBook}</h3>
{
book.isFavorite && currentUser ? <Button className="btn-custom" onClick={updateFavorite}> Уже в избранном </Button>
: <Button className="btn-custom" onClick={updateFavorite}> В избранное </Button>
}
</div>
</div>
);
};
BookCard.propTypes = {
book: PropTypes.object,
updateFavorite: PropTypes.func,
refreshFunc: PropTypes.func,
};
export default BookCard;

View File

@ -0,0 +1,31 @@
/* eslint-disable linebreak-style */
/* eslint-disable prefer-destructuring */
/* eslint-disable no-tabs */
/* eslint-disable eqeqeq */
import { useContext } from 'react';
import FavoriteBooksApiService from '../books/service/FavoriteBooksApiService';
import { CurrentUserContext } from '../../contexts/CurrentUserContext';
const useCardBook = (book, refreshFunc) => {
const { currentUser } = useContext(CurrentUserContext);
const updateFavorite = async () => {
const favs = await FavoriteBooksApiService.getAll(`?userId=${currentUser.id}&bookId=${book.id}`);
if (favs.length == 0) {
await FavoriteBooksApiService.create({
userId: currentUser.id,
bookId: book.id,
});
} else {
await FavoriteBooksApiService.delete(favs.pop().id);
}
refreshFunc();
};
return {
currentUser,
updateFavorite,
};
};
export default useCardBook;

View File

@ -0,0 +1,8 @@
.cart-image {
width: 3.1rem;
padding: .25rem;
}
.cart-item {
height: auto;
}

View File

@ -0,0 +1,48 @@
import { Button, ButtonGroup, Card } from 'react-bootstrap';
import { Trash, Download, XLg } from 'react-bootstrap-icons';
import imgPlaceholder from '../../assets/200.png';
import './Cart.css';
import useCart from './CartHook';
const Cart = () => {
const {
cart,
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.nameBook}
</div>
<div className='cart-item mt-2 mt-sm-0 d-flex flex-column align-items-center align-items-sm-end'>
<ButtonGroup className='mt-2 mt-sm-1' aria-label="Cart counter">
<Button variant="primary" onClick={() => addToCart(cartItem)}>
<Download />
</Button>
<Button variant="danger" onClick={() => removeFromCart(cartItem)}>
<Trash />
</Button>
</ButtonGroup>
</div>
</Card.Body>
</Card>)
}
</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,16 @@
import { useContext } from 'react';
import CartContext from './CartContext.jsx';
import { cartAdd, cartClear, cartRemove } from './CartReducer';
const useCart = () => {
const { cart, dispatch } = useContext(CartContext);
return {
cart,
addToCart: (item) => dispatch(cartAdd(item)),
removeFromCart: (item) => dispatch(cartRemove(item)),
clearCart: () => dispatch(cartClear()),
};
};
export default useCart;

View File

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

View File

@ -0,0 +1,9 @@
.footer {
font-family: 'Jost', sans-serif;
position: fixed;
bottom: 0;
width: 100%;
padding: 5px 0;
background-color: #452A21 !important;
z-index: 999;
}

View File

@ -0,0 +1,11 @@
import './Footer.css';
const Footer = () => {
return (
<footer className="footer mt-auto d-flex flex-shrink-0 justify-content-center align-items-center text-white">
Федоренко Галина, ПИбд-22
</footer>
);
};
export default Footer;

View File

@ -0,0 +1,21 @@
import { useEffect, useState } from 'react';
import GenresApiService from '../service/GenresApiService';
const useGenres = () => {
const [genres, setGenres] = useState([]);
const getGenres = async () => {
const data = await GenresApiService.getAll();
setGenres(data ?? []);
};
useEffect(() => {
getGenres();
}, []);
return {
genres,
};
};
export default useGenres;

View File

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

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,30 @@
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((genre) => <option key={genre.id}
value={genre.id}>{genre.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,3 @@
.modal-title {
font-size: 1.2rem;
}

View File

@ -0,0 +1,39 @@
import PropTypes from 'prop-types';
import { Button, Form, Modal } from 'react-bootstrap';
import { createPortal } from 'react-dom';
import './Modal.css';
const ModalBook = ({
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='primary' className='col-5 m-0 ms-2' type='submit'>
В избранное
</Button>
</Modal.Footer>
</Form>
</Modal>,
document.body,
);
};
ModalBook.propTypes = {
show: PropTypes.bool,
title: PropTypes.string,
validated: PropTypes.bool,
onSubmit: PropTypes.func,
onClose: PropTypes.func,
children: PropTypes.node,
};
export default ModalBook;

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,35 @@
.logo {
width: 36px;
height: 36px;
}
.nav-link {
font-family: 'Jost', sans-serif;
font-size: 24px;
margin-right: 25px;
color: white !important;
}
.nav-link:hover{
color: #91745f !important;
}
.navbar-brand svg path {
transition: fill .4s;
}
.navbar-brand:hover svg path {
fill: #91745f;
}
.navbar {
background-color: #452A21 !important;
}
@media (max-width: 767px) {
.nav-link {
font-size: 18px;
margin-right: 10px;
margin-left: 10px;
}
}

View File

@ -0,0 +1,87 @@
/* eslint-disable eqeqeq */
import PropTypes from 'prop-types';
import { Container, Nav, Navbar } from 'react-bootstrap';
import { Heart } from 'react-bootstrap-icons';
import { Link, useLocation } from 'react-router-dom';
import { useContext } from 'react';
import { CurrentUserContext } from '../../contexts/CurrentUserContext';
import './Navigation.css';
const Navigation = ({ routes }) => {
const location = useLocation();
const { currentUser } = useContext(CurrentUserContext);
const indexPageLink = routes.filter((route) => route.index === false).shift();
let pages = routes.filter((route) => Object.prototype.hasOwnProperty.call(route, 'title'));
if (currentUser) {
pages = pages.filter((route) => route.authored == null || route.authored == true);
if (!currentUser.isAdmin) {
pages = pages.filter((route) => route.onlyAdmin == false);
}
} else {
pages = pages.filter((route) => (route.authored == null || route.authored == false));
}
return (
<header>
<Navbar expand='md' bg='dark' data-bs-theme='dark'>
<Container>
<Navbar.Brand as={Link} to={indexPageLink?.path ?? '/'}>
<svg
width={60}
height={60}
viewBox="0 0 60 60"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
id="Vector"
d="M5 7.5H20C22.6522 7.5 25.1957 8.55357 27.0711 10.4289C28.9464 12.3043 30 14.8478 30 17.5V52.5C30 50.5109 29.2098 48.6032 27.8033 47.1967C26.3968 45.7902 24.4891 45 22.5 45H5V7.5Z"
stroke="white"
strokeWidth={2}
strokeLinecap="round"
strokeLinejoin="round"
/>
<path
id="Vector_2"
d="M55 7.5H40C37.3478 7.5 34.8043 8.55357 32.9289 10.4289C31.0536 12.3043 30 14.8478 30 17.5V52.5C30 50.5109 30.7902 48.6032 32.1967 47.1967C33.6032 45.7902 35.5109 45 37.5 45H55V7.5Z"
stroke="white"
strokeWidth={2}
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
</Navbar.Brand>
<Navbar.Toggle aria-controls='main-navbar' />
<Navbar.Collapse id='main-navbar'>
<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>)
}
{
currentUser != null
? <Navbar.Brand as={Link} to='/lk'>
<Heart className='d-inline-block align-top me-1 logo' />
</Navbar.Brand>
: ''
}
</Nav>
</Navbar.Collapse>
{
currentUser != null ? <Nav.Link disabled className='active d-none d-lg-block' as={Link} to='/catalog'>Здравствуй, {currentUser.username}!</Nav.Link> : ''
}
</Container>
</Navbar >
</header>
);
};
Navigation.propTypes = {
routes: PropTypes.array,
};
export default Navigation;

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,3 @@
import { createContext } from "react";
export const CurrentUserContext = createContext(null);

BIN
src/img/background.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 MiB

BIN
src/img/backgroung_sign.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 878 KiB

BIN
src/img/book.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 531 B

BIN
src/img/mast-marg.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 128 KiB

1
src/index.css Normal file
View File

@ -0,0 +1 @@
@import url('https://fonts.googleapis.com/css2?family=Jost:wght@200&display=swap');

80
src/main.jsx Normal file
View File

@ -0,0 +1,80 @@
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 Page5 from './pages/Page5.jsx';
import Lk from './pages/Lk.jsx';
import Logout from './pages/Logout.jsx';
const routes = [
{
index: true,
path: '/',
element: <Page1 />,
authored: null,
onlyAdmin: false,
},
{
path: '/catalog',
element: <Page2 />,
title: 'Каталог',
authored: true,
onlyAdmin: false,
},
{
path: '/sign_in',
element: <Page3 />,
title: 'Вход',
authored: false,
onlyAdmin: false,
},
{
path: '/sign_up',
element: <Page4 />,
title: 'Регистрация',
authored: false,
onlyAdmin: false,
},
{
path: '/admin_page',
element: <Page5 />,
title: 'Админка',
authored: true,
onlyAdmin: true,
},
{
path: '/lk',
element: <Lk />,
authored: true,
onlyAdmin: false,
},
{
path: '/logout',
element: <Logout />,
title: 'Выйти',
authored: true,
onlyAdmin: false,
},
];
const router = createBrowserRouter([
{
path: '/',
element: <App routes={routes} />,
children: routes,
errorElement: <ErrorPage />,
},
]);
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>,
);

9
src/pages/CartPage.jsx Normal file
View File

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

61
src/pages/Catalog.jsx Normal file
View File

@ -0,0 +1,61 @@
/* eslint-disable linebreak-style */
/* eslint-disable prefer-const */
/* eslint-disable no-tabs */
import { useContext } from 'react';
import useBooks, { useBook } from '../components/books/hooks/BooksHook';
import { useBookIdFilter } from '../components/books/hooks/BooksFilterHook';
import BookCard from '../components/cardBook/CardBook.jsx';
import useFavoriteBooks from '../components/books/hooks/FavoriteBooksHook';
import { CurrentUserContext } from '../contexts/CurrentUserContext';
import './styles/About.css';
const Catalog = () => {
const { books, handleBooksChange } = useBooks('');
const { currentUser } = useContext(CurrentUserContext);
let { favoriteBooks, refreshBooks } = useFavoriteBooks(currentUser.id);
favoriteBooks = favoriteBooks.map((m) => m.id);
// eslint-disable-next-line no-plusplus
for (let index = 0; index < books.length; index++) {
let m = books[index];
books[index].isFavorite = false;
if (favoriteBooks.includes(m.id)) {
books[index].isFavorite = true;
}
}
const refreshFunc = () => {
handleBooksChange();
refreshBooks();
};
const bookIdFilter = useBookIdFilter();
const currentbook = useBook(bookIdFilter);
if (bookIdFilter && currentbook.genre) {
return (
<div className="about p-0">
<img className="w-50 mr-3" src={currentbook.image} alt={currentbook.nameBook} />
<div className='descript'>
<p>Название: {currentbook.nameBook}</p>
<p>Год издания: {currentbook.year}</p>
<p>Жанр: {currentbook.genre.name}</p>
<p>Описание: {currentbook.description}</p>
</div>
</div>
);
}
return (
<div className='row d-flex justify-content-start'>
{
books.map((book) => <BookCard book={book} key={book.id} refreshFunc={refreshFunc} />)
}
</div>
);
};
export default Catalog;

19
src/pages/ErrorPage.jsx Normal file
View File

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

47
src/pages/Lk.jsx Normal file
View File

@ -0,0 +1,47 @@
/* eslint-disable no-plusplus */
/* eslint-disable no-tabs */
import { useContext } from 'react';
import { useNavigate } from 'react-router-dom';
import useFavoriteBooks from '../components/books/hooks/FavoriteBooksHook';
import './styles/Lk.css';
import { CurrentUserContext } from '../contexts/CurrentUserContext';
import BookCard from '../components/cardBook/CardBook.jsx';
const Lk = () => {
const { currentUser } = useContext(CurrentUserContext);
const navigate = useNavigate();
if (!currentUser) {
navigate('/');
}
let { favoriteBooks, refreshBooks } = useFavoriteBooks(currentUser.id);
for (let i = 0; i < favoriteBooks.length; i++) {
favoriteBooks[i].isFavorite = true;
}
const refresh = () => {
refreshBooks();
// handleMoviesChange();
};
return (
<>
<div className="container-fluid d-flex flex-column">
<div className="title-category d-flex flex-row justify-content-around align-items-center">
<span className="text-center"> Избранное </span>
</div>
<div className='row d-flex justify-content-start'>
{
favoriteBooks.map((favoriteBook, index) =>
<BookCard book={favoriteBook} key={index} refreshFunc={refresh} />)
}
</div>
</div>
</>
);
};
export default Lk;

24
src/pages/Logout.jsx Normal file
View File

@ -0,0 +1,24 @@
import { useContext } from 'react';
import { useNavigate } from 'react-router-dom';
import { CurrentUserContext } from '../contexts/CurrentUserContext';
import './styles/About.css';
const Logout = () => {
const navig = useNavigate();
const { setCurrentUser } = useContext(CurrentUserContext);
setTimeout(() => {
setCurrentUser(null);
navig('/');
// window.location.pathname = '/';
}, 500);
return (
<main className="main-page flex-fill d-flex flex-column justify-content-center" id='catalog-page'>
<p className="text-light fs-1 w-100 text-center lout">Вы вышли</p>
<script>
</script>
</main >
);
};
export default Logout;

26
src/pages/Page1.jsx Normal file
View File

@ -0,0 +1,26 @@
// import { Link } from 'react-router-dom';
import './styles/Title.css';
const Page1 = () => {
return (
<div className="background-style">
<div className="container text-center">
<h1 className="display-4">Книжный подвальчик</h1>
<div className="row">
<div className="col-6"></div>
<div className="col-6">
<blockquote className="blockquote text-right">
<p>
Без книг пуста человеческая жизнь. Книга не только наш друг, но и
постоянный вечный спутник.
</p>
<footer className="blockquote-footer">Д. Бедный</footer>
</blockquote>
</div>
</div>
</div>
</div>
);
};
export default Page1;

12
src/pages/Page2.jsx Normal file
View File

@ -0,0 +1,12 @@
import './styles/Catalog.css';
import Catalog from './Catalog.jsx';
const Page2 = () => {
return (
<div className="container flex-fill p-0" id='main'>
<Catalog></Catalog>
</div>
);
};
export default Page2;

120
src/pages/Page3.jsx Normal file
View File

@ -0,0 +1,120 @@
/* eslint-disable no-shadow */
/* eslint-disable prefer-const */
/* eslint-disable no-multiple-empty-lines */
/* eslint-disable padded-blocks */
/* eslint-disable no-tabs */
/* import { useState } from 'react';
import { Button, Form } from 'react-bootstrap'; */
import { Link, useNavigate } from 'react-router-dom';
import { useState, useEffect, useContext } from 'react';
import UsersApiService from '../users/service/UsersApiService';
import { CurrentUserContext } from '../contexts/CurrentUserContext';
import './styles/Sign.css';
const Page3 = () => {
const { setCurrentUser } = useContext(CurrentUserContext);
const [inputFields, setInputFields] = useState({
username: '',
password: '',
});
const [errors, setErrors] = useState({});
const [submitting, setSubmitting] = useState(false);
const navig = useNavigate();
const validateValues = (inputValues) => {
let errors = {};
if (inputValues.username.length <= 0) {
errors.username = 'Введите имя пользователя';
}
if (inputValues.password.length <= 0) {
errors.password = 'Введите пароль';
}
return errors;
};
const handleChange = (e) => {
setInputFields({ ...inputFields, [e.target.name]: e.target.value });
};
const handleSubmit = (event) => {
event.preventDefault();
setErrors(validateValues(inputFields));
setSubmitting(true);
};
const finishSubmit = async () => {
const expand = `?username=${inputFields.username}&password=${inputFields.password}`;
const data = await UsersApiService.getAll(expand);
if (data.length == 0) {
alert('Неверные логин или пароль!');
}
else if (data.length == 1) {
setCurrentUser(data.pop());
navig('/');
// window.location.pathname = '/lk'
}
else {
alert('Что-то пошло не так..');
}
};
useEffect(() => {
if (Object.keys(errors).length === 0 && submitting) {
finishSubmit();
}
}, [errors]);
return (
<div className="background-image">
<div className="sign-in-container">
<h2 className="custom-h">Добро пожаловать!</h2>
<form id="into-page" onSubmit={handleSubmit}>
<div className="row justify-content-center">
<input id="username" className="form-control" placeholder="Имя пользователя / Эл. Почта"
type="username"
name='username'
value={inputFields.username}
onChange={handleChange}>
</input>
{errors.username ? (
<p className="error mt-2">
Введите имя пользователя
</p>
) : null}
<input id="password" className="form-control" placeholder="Пароль"
type="password"
name='password'
value={inputFields.password}
onChange={handleChange}
>
</input>
{errors.password ? (
<p className="error mt-2">
Введите пароль
</p>
) : null}
<button type="submit" className="btn btn-custom">
ВОЙТИ
</button>
<p className="custom-text">
Ещё нет аккаунта?{}
<Link to="/sign_up" className="custom-a">
Зарегистрироваться
</Link>
</p>
</div>
</form>
</div>
</div>
);
};
export default Page3;

158
src/pages/Page4.jsx Normal file
View File

@ -0,0 +1,158 @@
/* eslint-disable padded-blocks */
/* eslint-disable no-tabs */
/* import { Button, ButtonGroup, Table } from 'react-bootstrap';
import { Link } from 'react-router-dom'; */
import './styles/Sign.css';
import { Link } from 'react-router-dom';
import { useState, useEffect } from 'react';
import UsersApiService from '../users/service/UsersApiService';
import { useNavigate } from 'react-router-dom';
const Page4 = () => {
const [inputFields, setInputFields] = useState({
username: "",
password: "",
passwordrepeat: "",
});
//
var [isAdminValue, setIsSubscribed] = useState(false);
const [errors, setErrors] = useState({});
const [submitting, setSubmitting] = useState(false);
const validateValues = (inputValues) => {
let errors = {};
if (inputValues.username.length <= 0) {
errors.username = "Введите имя пользователя";
}
if (inputValues.password.length <= 0) {
errors.password = "Введите пароль";
}
if (inputValues.passwordrepeat.length <= 0) {
errors.passwordrepeat = "Введите пароль";
}
if (inputValues.password != inputValues.passwordrepeat) {
errors.passwordsNotEquals = "Пароли не совпадают";
}
return errors;
};
const handleChange = (e) => {
setInputFields({ ...inputFields, [e.target.name]: e.target.value });
};
const isCheckedAdmin = event => {
if (event.target.checked) {
isAdminValue = true;
} else {
isAdminValue = false;
}
setIsSubscribed(current => current);
};
const handleSubmit = (event) => {
event.preventDefault();
setErrors(validateValues(inputFields));
setSubmitting(true);
};
const navig = useNavigate();
const finishSubmit = async () => {
const user = await UsersApiService.getAll(`?username=${inputFields.username}&password=${inputFields.password}&isAdmin=${isAdminValue}`);
if (user.length == 0) {
await UsersApiService.create({
username: inputFields.username,
password: inputFields.password,
isAdmin: isAdminValue
});
navig('/');
}
if (user.length == 1) {
alert("такой пользователь уже есть");
}
};
useEffect(() => {
if (Object.keys(errors).length === 0 && submitting) {
finishSubmit();
}
}, [errors]);
return (
<div className="background-image">
<div className="sign-up-container">
<h2 className="custom-h">Регистрация</h2>
<form id="login-page" onSubmit={handleSubmit}>
<div className="row justify-content-center">
<input id="username" className="form-control" placeholder="Имя пользователя"
type="username"
name='username'
value={inputFields.username}
onChange={handleChange}
>
</input>
{errors.username ? (
<p className="error">
Введите имя пользователя
</p>
) : null}
<input id="password" className="form-control" placeholder="Пароль"
type="password"
name='password'
value={inputFields.password}
onChange={handleChange}
>
</input>
{errors.username ? (
<p className="error">
Введите пароль
</p>
) : null}
<input id="passwordrepeat" className="form-control" placeholder="Пароль повторно"
type="password"
name='passwordrepeat'
value={inputFields.passwordrepeat}
onChange={handleChange}
>
</input>
{errors.username ? (
<p className="error">
Введите пароль повторно
</p>
) : null}
{errors.passwordsNotEquals ? (
<p className="error">
Пароли не совпадают
</p>
) : null}
<div className="check-admin mt-4 d-flex flex-row justify-content-center mb-4">
<input className='isAdmin-check'
type="checkbox"
value={isAdminValue}
onChange={isCheckedAdmin}
/>
<label className='are-you-admin'> Вы админ? </label>
</div>
<button type="submit" className="btn btn-custom">
ЗАРЕГИСТРИРОВАТЬСЯ
</button>
<p className="custom-text">
Уже есть аккаунт?{}
<Link to="/sign_in" className="custom-a">
Войти
</Link>
</p>
</div>
</form>
</div>
</div>
);
};
export default Page4;

12
src/pages/Page5.jsx Normal file
View File

@ -0,0 +1,12 @@
import './styles/Admin.css';
import Books from '../components/books/table/Books.jsx';
const Admin = () => {
return (
<div className="container flex-fill p-2" id='main'>
<Books></Books>
</div>
);
};
export default Admin;

53
src/pages/PageEdit.jsx Normal file
View File

@ -0,0 +1,53 @@
import { useState } from 'react';
import { Button, Form } from 'react-bootstrap';
import { Link } from 'react-router-dom';
const PageEdit = () => {
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="text-center">
<img id="image-preview" src="https://via.placeholder.com/200" className="rounded rounded-circle"
alt="placeholder" />
</div>
<Form id="items-form" noValidate validated={validated} onSubmit={handleSubmit}>
<Form.Group className="mb-2" controlId="item">
<Form.Label htmlFor="item" className="form-label">Товары</Form.Label>
<Form.Select name='selected' required>
</Form.Select>
</Form.Group>
<Form.Group className="mb-2" controlId="price">
<Form.Label>Цена</Form.Label>
<Form.Control type="number" name="price"
value="0.00" min="1000.00" step="0.50" required />
</Form.Group>
<Form.Group className="mb-2" controlId="count">
<Form.Label>Количество</Form.Label>
<Form.Control type="number" name="count"
value="0" min="1" step="1" required />
</Form.Group>
<Form.Group className="mb-2" controlId="file">
<Form.Label>Изображение</Form.Label>
<Form.Control type="file" name="image" accept="image/*" />
</Form.Group>
<Form.Group className="d-flex flex-md-row flex-column justify-content-center">
<Button className="btn-mw me-md-3 mb-md-0 mb-2" as={Link} to="/page4" variant="secondary">Назад</Button>
<Button className="btn-mw me-md-3" type="submit" variant="primary">Сохранить</Button>
</Form.Group>
</Form>
</>
);
};
export default PageEdit;

View File

@ -0,0 +1,30 @@
.about {
display: flex;
align-items: center;
flex-direction: row;
justify-content: flex-start;
padding-bottom: 50px !important;
}
.about img {
width: 250px !important;
height: 380px !important;
border-radius: 5px;
}
.descript {
margin: 10px;
color: white;
}
.lout {
font-family: 'Jost', sans-serif;
font-size: 50px;
color: white !important;
}
@media (max-width: 767px) {
.about {
flex-direction: column;
}
}

View File

@ -0,0 +1,48 @@
.row {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
}
/*.table {
--bs-th-bg: #452A21;
--bs-table-border-color: #d6b0a2;
--bs-tb-bg: #d6b0a2;
}
thead {
background-color: #452A21 !important;
}
tbody {
background-color: #d6b0a2 !important;
}
*/
h1 {
font-size: 1.5em;
}
h2 {
font-size: 1.25em;
}
h3 {
font-size: 1.1em;
}
.btn-admin {
bottom: 5px;
background-color: #452A21 !important;
color: white !important;
}
.btn-admin:hover {
background-color: #866a60 !important;
color: black !important;
}
#image-preview {
width: 200px;
}

View File

@ -0,0 +1,86 @@
body {
background-color: #91745f;
}
.book {
padding: 15px;
text-align: center;
margin-bottom: 20px;
flex: 0 0 calc(25% - 30px);
}
.book img {
width: 140px;
height: 215px;
border-radius: 5px;
margin-bottom: 10px;
}
.book h3 {
color: #FFF;
text-align: center;
font-family: Jost;
font-size: 25px;
font-style: normal;
font-weight: 300;
line-height: normal;
height: 100px;
}
.btn-custom {
border-radius: 8px;
width: 250px !important;
height: 50px;
margin-bottom: 20px;
background-color: #452B21;
color: #fff;
text-align: center;
font-family: Jost;
font-size: 25px !important;
font-style: normal;
font-weight: 400;
line-height: normal;
border: 2px solid #452B21;
}
.btn-custom:hover {
background-color: #61453a;
border: 2px solid #61453a;
}
.btn-custom:active {
background-color: #452B21 !important;
color: #fff !important;
border: 2px solid #452B21 !important;
}
.footer {
font-family: 'Jost', sans-serif;
position: fixed;
bottom: 0;
width: 100%;
padding: 5px 0;
background-color: #452A21 !important;
z-index: 999;
}
.about {
margin-top: 20px;
color: white;
font-family: Jost;
text-align:justify;
font-size: 24px;
}
@media (max-width: 767px) {
.book img {
width: 210px;
height: 320px;
border-radius: 5px;
margin-bottom: 10px;
}
.book h3 {
height: 90px;
}
}

11
src/pages/styles/Lk.css Normal file
View File

@ -0,0 +1,11 @@
.title-category {
font-size: 50px;
font-family: 'Jost';
}
@media screen and (max-width: 576px) {
.title-category {
font-size: min(10vw, 30px);
}
}

158
src/pages/styles/Sign.css Normal file
View File

@ -0,0 +1,158 @@
.nav-item svg path {
transition: fill .4s;
}
.nav-item:hover svg path {
fill: #79584c;
}
.background-image {
background-image: url("../../img/backgroung_sign.png");
background-size: cover;
width: 50%;
height: 100vh;
display: inline-block;
}
.sign-in-container {
background-color: #ffffff;
border-radius: 15px;
padding: 20px;
width: 500px;
height: 400px;
position: relative;
top: 8%;
right: 0;
bottom: 0;
left: 50%;
margin: auto;
}
.sign-up-container {
background-color: #ffffff;
border-radius: 15px;
padding: 20px;
width: 500px;
height: 550px;
position: relative;
top: 1%;
right: 0;
bottom: 0;
left: 50%;
margin: auto;
}
.custom-h {
color: #000;
text-align: center;
font-family: Jost;
font-size: 50px;
font-style: normal;
font-weight: 300;
line-height: normal;
margin-bottom: 20px;
}
.input-box {
border-radius: 8px;
font-size: 17px;
width: 450px;
height: 60px;
margin-bottom: 20px;
}
.form-control {
border-radius: 8px;
font-size: 17px;
width: 450px;
height: 60px;
margin-bottom: 20px;
}
.btn-custom {
border-radius: 8px;
width: 450px;
height: 60px;
background-color: #452B21;
margin-bottom: 20px;
color: #fff;
text-align: center;
font-family: Jost;
font-size: 32px;
font-style: normal;
font-weight: 400;
line-height: normal;
border: 2px solid #452B21;
}
.btn-custom:hover {
background-color: #66442B;
border: 2px solid #66442B;
}
.are-you-admin {
font-size: 20px;
}
.custom-text {
color: #8C8C8C;
text-align: center;
font-family: Jost;
font-size: 20px;
font-style: normal;
font-weight: 400;
line-height: normal;
}
.custom-a {
color: #452B21;
font-family: Jost;
font-size: 20px;
font-style: normal;
font-weight: 400;
line-height: normal;
}
.custom-a:hover {
color: #9c614a;
}
.error {
border-color: red !important;
background-color: rgba(255, 222, 222, 0.26) !important;
}
@media (max-width: 767px) {
.sign-in-container {
width: 290px;
height: 375px;
padding: 10px;
left:5%;
}
.sign-up-container {
width: 290px;
height: 525px;
padding: 10px;
top: 5%;
left:5%;
}
.custom-h {
font-size: 28px;
}
.form-control {
width: 80%;
}
.btn-custom {
width: 80%;
font-size: 90%;
}
.are-you-admin {
font-size: min(10vw, 25px);
}
}

View File

@ -0,0 +1,90 @@
/*body {
background-image: url("../../../public/background.jpg");
background-size: cover;
background-position: center;
height: 100vh;
}*/
.background-style{
background-image: url("../../img/background.jpg");
background-size: cover;
background-position: center;
height: 100vh;
width: 100%;
margin: 0;
padding: 0;
}
.nav-link {
font-family: 'Jost', sans-serif;
font-size: 24px;
margin-right: 25px;
color: white !important;
}
.nav-link:hover{
color: #79584c !important;
}
.nav-item svg path {
transition: fill .4s;
}
.nav-item:hover svg path {
fill: #79584c;
}
.display-4 {
color: #FFF;
font-family: 'Source Serif 4';
font-size: 96px;
font-style: normal;
margin-top: 100px;
}
blockquote {
color: white;
font-family: 'Source Serif 4';
text-align: right;
font-size: 24px;
margin-top: 30px;
}
blockquote footer {
color: white !important;
font-family: 'Source Serif 4';
text-align: right;
font-size: 24px;
}
.footer {
font-family: 'Jost', sans-serif;
position: fixed;
bottom: 0;
width: 100%;
padding: 5px 0;
background-color: #452A21 !important;
z-index: 999;
}
@media (max-width: 767px) {
.nav-link {
font-size: 18px;
margin-right: 10px;
margin-left: 10px;
}
.display-4 {
font-size: 40px;
margin-top: 50px;
}
blockquote {
font-size: 18px !important;
margin-top: 20px;
}
blockquote footer {
font-size: 18px;
}
}

View File

@ -0,0 +1,44 @@
import { useEffect, useState } from "react";
import UsersApiService from "../service/UsersApiService";
export const useUser = (username, password) => {
const [userRefresh] = useState(false);
const [user, setUser] = useState([]);
const getUser = async () => {
const expand = `username=${username}&password=${password}`;
const data = await UsersApiService.getAll(expand);
setUser(data ?? []);
};
useEffect(() => {
getUser();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [userRefresh, username, password]);
return user;
};
export const useCurrentUser = () => {
const [userRefresh] = useState(false);
const [user, setUser] = useState([]);
const getUser = async () => {
const userId = localStorage.getItem("userId");
if (userId != null) {
const user = await UsersApiService.get(userId);
setUser(user ?? null);
} else {
setUser(null);
}
};
useEffect(() => {
getUser();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [userRefresh]);
return user;
};
export default useUser;

View File

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

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