lab5 it is wrong
This commit is contained in:
parent
0833817b74
commit
61abe13183
@ -1,5 +1,25 @@
|
||||
{
|
||||
"categories": [
|
||||
"users": [
|
||||
{
|
||||
"id": 1,
|
||||
"name": "admin",
|
||||
"password": "123",
|
||||
"role": "admin"
|
||||
},
|
||||
{
|
||||
"name": "testUser",
|
||||
"password": "123",
|
||||
"role": "user",
|
||||
"id": 2
|
||||
},
|
||||
{
|
||||
"name": "testUser2",
|
||||
"password": "123",
|
||||
"role": "user",
|
||||
"id": 3
|
||||
}
|
||||
],
|
||||
"types": [
|
||||
{
|
||||
"id": 1,
|
||||
"name": "Ода"
|
||||
@ -33,7 +53,7 @@
|
||||
],
|
||||
"books": [
|
||||
{
|
||||
"categoriesId": "3",
|
||||
"typesId": "3",
|
||||
"authorsId": "1",
|
||||
"name": "Зимний вечер",
|
||||
"year": "1830",
|
||||
@ -41,7 +61,7 @@
|
||||
"id": 1
|
||||
},
|
||||
{
|
||||
"categoriesId": "1",
|
||||
"typesId": "1",
|
||||
"authorsId": "2",
|
||||
"name": "Властителям и судиям",
|
||||
"year": "1780",
|
||||
@ -49,7 +69,7 @@
|
||||
"id": 2
|
||||
},
|
||||
{
|
||||
"categoriesId": "1",
|
||||
"typesId": "1",
|
||||
"authorsId": "3",
|
||||
"name": "Exegi monumentum",
|
||||
"year": "23 до н. э.",
|
||||
@ -57,7 +77,7 @@
|
||||
"id": 3
|
||||
},
|
||||
{
|
||||
"categoriesId": "2",
|
||||
"typesId": "2",
|
||||
"authorsId": "4",
|
||||
"name": "К бедному поэту",
|
||||
"year": "1796",
|
||||
|
@ -1,14 +1,15 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Node",
|
||||
"target": "ES2020",
|
||||
"jsx": "react",
|
||||
"strictNullChecks": true,
|
||||
"strictFunctionTypes": true
|
||||
},
|
||||
"exclude": [
|
||||
"node_modules",
|
||||
"**/node_modules/*"
|
||||
]
|
||||
"compilerOptions": {
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Node",
|
||||
"target": "ES2020",
|
||||
"jsx": "react",
|
||||
"strictNullChecks": true,
|
||||
"strictFunctionTypes": true,
|
||||
"sourceMap": true
|
||||
},
|
||||
"exclude": [
|
||||
"node_modules",
|
||||
"**/node_modules/*"
|
||||
]
|
||||
}
|
1626
ReactLibrary/package-lock.json
generated
1626
ReactLibrary/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@ -4,15 +4,18 @@
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0",
|
||||
"preview": "vite preview"
|
||||
"rest": "json-server --watch data.json -p 8081",
|
||||
"vite": "vite",
|
||||
"dev": "npm-run-all --parallel rest vite",
|
||||
"prod": "npm-run-all lint vite --parallel rest 'vite preview'"
|
||||
},
|
||||
"dependencies": {
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-router-dom": "^6.18.0",
|
||||
"react-hot-toast": "^2.4.1",
|
||||
"axios": "^1.6.1",
|
||||
"bootstrap": "^5.3.2",
|
||||
"react-bootstrap": "^2.9.1",
|
||||
"react-bootstrap-icons": "^1.10.3",
|
||||
@ -20,13 +23,16 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^18.2.15",
|
||||
"@types/react-dom": "^18.2.7",
|
||||
"@types/react-dom": "^18.2.15",
|
||||
"@vitejs/plugin-react": "^4.0.3",
|
||||
"eslint": "^8.45.0",
|
||||
"eslint-config-airbnb-base": "^15.0.0",
|
||||
"eslint-plugin-import": "^2.29.0",
|
||||
"eslint-plugin-react": "^7.32.2",
|
||||
"eslint-plugin-react-hooks": "^4.6.0",
|
||||
"eslint-plugin-react-refresh": "^0.4.3",
|
||||
"json-server": "^0.17.4",
|
||||
"npm-run-all": "^4.1.5",
|
||||
"vite": "^4.4.5"
|
||||
}
|
||||
}
|
@ -1,19 +1,21 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import { Container } from 'react-bootstrap';
|
||||
import { Toaster } from 'react-hot-toast';
|
||||
import { Outlet } from 'react-router-dom';
|
||||
import './App.css';
|
||||
import { IdProvider } from './components/users/context_hooks/AuthorizationContext.jsx';
|
||||
import Footer from './components/footer/Footer.jsx';
|
||||
import Navigation from './components/navigation/Navigation.jsx';
|
||||
|
||||
const App = ({ routes }) => {
|
||||
return (
|
||||
<>
|
||||
<IdProvider>
|
||||
<Navigation routes={routes}></Navigation>
|
||||
<Container className='p-2' as="main" fluid>
|
||||
<Outlet />
|
||||
</Container>
|
||||
<Footer/>
|
||||
</>
|
||||
<Toaster position='top-center' reverseOrder={true} />
|
||||
</IdProvider>
|
||||
);
|
||||
};
|
||||
|
||||
|
BIN
ReactLibrary/src/assets/200.png
Normal file
BIN
ReactLibrary/src/assets/200.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 1.5 KiB |
40
ReactLibrary/src/components/api/ApiClient.js
Normal file
40
ReactLibrary/src/components/api/ApiClient.js
Normal 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);
|
29
ReactLibrary/src/components/api/ApiService.js
Normal file
29
ReactLibrary/src/components/api/ApiService.js
Normal 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;
|
21
ReactLibrary/src/components/authors/hooks/AuthorsHook.js
Normal file
21
ReactLibrary/src/components/authors/hooks/AuthorsHook.js
Normal file
@ -0,0 +1,21 @@
|
||||
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;
|
@ -0,0 +1,5 @@
|
||||
import ApiService from '../../api/ApiService';
|
||||
|
||||
const AuthorsApiService = new ApiService('authors');
|
||||
|
||||
export default AuthorsApiService;
|
@ -1,5 +1,5 @@
|
||||
.my-footer {
|
||||
background-color: #000000;
|
||||
height: 32px;
|
||||
height: 100px;
|
||||
color: #ffffff;
|
||||
}
|
@ -1,11 +1,16 @@
|
||||
import './Footer.css';
|
||||
import useAuthorization from '../users/context_hooks/AuthorizationHook';
|
||||
|
||||
const Footer = () => {
|
||||
const year = new Date().getFullYear();
|
||||
// let { id } = useAuthorization();
|
||||
let id = localStorage.getItem('userId');
|
||||
id = parseInt(id, 10);
|
||||
|
||||
return (
|
||||
<footer className="my-footer mt-auto d-flex flex-shrink-0 justify-content-center align-items-center">
|
||||
Захаров Р. А., {year}
|
||||
<footer className="my-footer mt-auto d-block flex-shrink-0 align-items-center">
|
||||
<p>Id: {id || 'гость'}</p>
|
||||
<p className='d-flex justify-content-center'>Захаров Р. А., {year}</p>
|
||||
</footer>
|
||||
);
|
||||
};
|
||||
|
23
ReactLibrary/src/components/input/Input.jsx
Normal file
23
ReactLibrary/src/components/input/Input.jsx
Normal 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;
|
29
ReactLibrary/src/components/input/Select.jsx
Normal file
29
ReactLibrary/src/components/input/Select.jsx
Normal 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;
|
48
ReactLibrary/src/components/lines/form/LinesForm.jsx
Normal file
48
ReactLibrary/src/components/lines/form/LinesForm.jsx
Normal 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='lib-btn col-5 col-lg-2 m-0 me-2' onClick={() => onBack()}>
|
||||
Назад
|
||||
</Button>
|
||||
<Button className='lib-btn col-5 col-lg-2 m-0 ms-2' type='submit'>
|
||||
Сохранить
|
||||
</Button>
|
||||
</Form.Group>
|
||||
</Form>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
LinesForm.propTypes = {
|
||||
id: PropTypes.string,
|
||||
};
|
||||
|
||||
export default LinesForm;
|
3
ReactLibrary/src/components/lines/form/LinesItemForm.css
Normal file
3
ReactLibrary/src/components/lines/form/LinesItemForm.css
Normal file
@ -0,0 +1,3 @@
|
||||
#image-preview {
|
||||
width: 200px;
|
||||
}
|
38
ReactLibrary/src/components/lines/form/LinesItemForm.jsx
Normal file
38
ReactLibrary/src/components/lines/form/LinesItemForm.jsx
Normal file
@ -0,0 +1,38 @@
|
||||
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 '../../authors/hooks/AuthorsHook';
|
||||
import './LinesItemForm.css';
|
||||
|
||||
const LinesItemForm = ({ item, handleChange }) => {
|
||||
const { types } = useTypes();
|
||||
const { authors } = useAuthors();
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className='text-center'>
|
||||
<img id='image-preview' src={item.image || imgPlaceholder} />
|
||||
</div>
|
||||
|
||||
<Input name='name' label='Название' value={item.name} onChange={handleChange}
|
||||
required />
|
||||
<Select values={authors} name='authorsId' label='Автор' value={item.authorsId} onChange={handleChange}
|
||||
required />
|
||||
<Select values={types} name='typesId' label='Жанр' value={item.typesId} onChange={handleChange}
|
||||
required />
|
||||
<Input name='year' label='Год' value={item.year} onChange={handleChange}
|
||||
required />
|
||||
<Input name='image' label='Изображение' onChange={handleChange}
|
||||
type='file' accept='image/*' />
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
LinesItemForm.propTypes = {
|
||||
item: PropTypes.object,
|
||||
handleChange: PropTypes.func,
|
||||
};
|
||||
|
||||
export default LinesItemForm;
|
@ -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;
|
28
ReactLibrary/src/components/lines/hooks/LinesFilterHook.js
Normal file
28
ReactLibrary/src/components/lines/hooks/LinesFilterHook.js
Normal 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;
|
@ -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;
|
29
ReactLibrary/src/components/lines/hooks/LinesHook.js
Normal file
29
ReactLibrary/src/components/lines/hooks/LinesHook.js
Normal file
@ -0,0 +1,29 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import LinesApiService from '../service/LinesApiService';
|
||||
|
||||
const useLines = (typeFilter) => {
|
||||
const [linesRefresh, setLinesRefresh] = useState(false);
|
||||
const [lines, setLines] = useState([]);
|
||||
const handleLinesChange = () => setLinesRefresh(!linesRefresh);
|
||||
|
||||
const getLines = async () => {
|
||||
let expand = '?_expand=authors&_expand=types';
|
||||
if (typeFilter) {
|
||||
expand = `${expand}&typesId=${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;
|
81
ReactLibrary/src/components/lines/hooks/LinesItemFormHook.js
Normal file
81
ReactLibrary/src/components/lines/hooks/LinesItemFormHook.js
Normal file
@ -0,0 +1,81 @@
|
||||
import { useState } from 'react';
|
||||
import toast from 'react-hot-toast';
|
||||
import getBase64FromFile from '../../utils/Base64';
|
||||
import LinesApiService from '../service/LinesApiService';
|
||||
import useLinesItem from './LinesItemHook';
|
||||
|
||||
const useLinesItemForm = (id, linesChangeHandle) => {
|
||||
const { item, setItem } = useLinesItem(id);
|
||||
|
||||
const [validated, setValidated] = useState(false);
|
||||
|
||||
const resetValidity = () => {
|
||||
setValidated(false);
|
||||
};
|
||||
|
||||
const getLineObject = (formData) => {
|
||||
const typesId = parseInt(formData.typesId, 10);
|
||||
const authorsId = parseInt(formData.authorsId, 10);
|
||||
const { name } = formData;
|
||||
const { year } = formData;
|
||||
const image = formData.image.startsWith('data:image') ? formData.image : '';
|
||||
return {
|
||||
typesId: typesId.toString(),
|
||||
authorsId: authorsId.toString(),
|
||||
name: name.toString(),
|
||||
year: year.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;
|
35
ReactLibrary/src/components/lines/hooks/LinesItemHook.js
Normal file
35
ReactLibrary/src/components/lines/hooks/LinesItemHook.js
Normal file
@ -0,0 +1,35 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import LinesApiService from '../service/LinesApiService';
|
||||
|
||||
const useLinesItem = (id) => {
|
||||
const emptyItem = {
|
||||
typesId: '',
|
||||
authorsId: '',
|
||||
name: '',
|
||||
image: '',
|
||||
years: '',
|
||||
id: '',
|
||||
};
|
||||
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;
|
@ -0,0 +1,5 @@
|
||||
import ApiService from '../../api/ApiService';
|
||||
|
||||
const LinesApiService = new ApiService('books');
|
||||
|
||||
export default LinesApiService;
|
64
ReactLibrary/src/components/lines/table/Lines.jsx
Normal file
64
ReactLibrary/src/components/lines/table/Lines.jsx
Normal file
@ -0,0 +1,64 @@
|
||||
import { Button } from 'react-bootstrap';
|
||||
import Select from '../../input/Select.jsx';
|
||||
import ModalConfirm from '../../modal/ModalConfirm.jsx';
|
||||
import ModalForm from '../../modal/ModalForm.jsx';
|
||||
import LinesItemForm from '../form/LinesItemForm.jsx';
|
||||
import useLinesDeleteModal from '../hooks/LinesDeleteModalHook';
|
||||
import useTypeFilter from '../hooks/LinesFilterHook';
|
||||
import useLinesFormModal from '../hooks/LinesFormModalHook';
|
||||
import useLines from '../hooks/LinesHook';
|
||||
import LinesTable from './LinesTable.jsx';
|
||||
import LinesTableRow from './LinesTableRow.jsx';
|
||||
|
||||
const Lines = () => {
|
||||
const { types, currentFilter, handleFilterChange } = useTypeFilter();
|
||||
|
||||
const { lines, handleLinesChange } = useLines(currentFilter);
|
||||
|
||||
const {
|
||||
isDeleteModalShow,
|
||||
showDeleteModal,
|
||||
handleDeleteConfirm,
|
||||
handleDeleteCancel,
|
||||
} = useLinesDeleteModal(handleLinesChange);
|
||||
|
||||
const {
|
||||
isFormModalShow,
|
||||
isFormValidated,
|
||||
showFormModal,
|
||||
currentItem,
|
||||
handleItemChange,
|
||||
handleFormSubmit,
|
||||
handleFormClose,
|
||||
} = useLinesFormModal(handleLinesChange);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button className='lib-btn' onClick={() => showFormModal()}>
|
||||
Добавить книгу
|
||||
</Button>
|
||||
<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)}
|
||||
/>)
|
||||
}
|
||||
</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;
|
29
ReactLibrary/src/components/lines/table/LinesTable.jsx
Normal file
29
ReactLibrary/src/components/lines/table/LinesTable.jsx
Normal file
@ -0,0 +1,29 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import { Table } from 'react-bootstrap';
|
||||
|
||||
const LinesTable = ({ children }) => {
|
||||
return (
|
||||
<Table className='mt-2' striped responsive>
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope='col'>№</th>
|
||||
<th scope='col' className='w-25'>Название</th>
|
||||
<th scope='col' className='w-25'>Автор</th>
|
||||
<th scope='col' className='w-25'>Жанр</th>
|
||||
<th scope='col' className='w-25'>Год</th>
|
||||
<th scope='col'></th>
|
||||
<th scope='col'></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{children}
|
||||
</tbody >
|
||||
</Table >
|
||||
);
|
||||
};
|
||||
|
||||
LinesTable.propTypes = {
|
||||
children: PropTypes.node,
|
||||
};
|
||||
|
||||
export default LinesTable;
|
33
ReactLibrary/src/components/lines/table/LinesTableRow.jsx
Normal file
33
ReactLibrary/src/components/lines/table/LinesTableRow.jsx
Normal file
@ -0,0 +1,33 @@
|
||||
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.name}</td>
|
||||
<td>{line.authors.name}</td>
|
||||
<td>{line.types.name}</td>
|
||||
<td>{line.year}</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;
|
3
ReactLibrary/src/components/modal/Modal.css
Normal file
3
ReactLibrary/src/components/modal/Modal.css
Normal file
@ -0,0 +1,3 @@
|
||||
.modal-title {
|
||||
font-size: 1.2rem;
|
||||
}
|
42
ReactLibrary/src/components/modal/ModalConfirm.jsx
Normal file
42
ReactLibrary/src/components/modal/ModalConfirm.jsx
Normal 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;
|
43
ReactLibrary/src/components/modal/ModalForm.jsx
Normal file
43
ReactLibrary/src/components/modal/ModalForm.jsx
Normal 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;
|
21
ReactLibrary/src/components/modal/ModalHook.js
Normal file
21
ReactLibrary/src/components/modal/ModalHook.js
Normal 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;
|
21
ReactLibrary/src/components/types/hooks/TypesHook.js
Normal file
21
ReactLibrary/src/components/types/hooks/TypesHook.js
Normal 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;
|
@ -0,0 +1,5 @@
|
||||
import ApiService from '../../api/ApiService';
|
||||
|
||||
const TypesApiService = new ApiService('types');
|
||||
|
||||
export default TypesApiService;
|
@ -0,0 +1,54 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import { Button, Form } from 'react-bootstrap';
|
||||
import { useNavigate, Link } from 'react-router-dom';
|
||||
import useAuthorizationForm from '../hooks/AuthorizationFormHook';
|
||||
import AuthorizationInput from './AuthorizationInput.jsx';
|
||||
|
||||
const RegistrationForm = () => {
|
||||
const navigate = useNavigate();
|
||||
|
||||
const {
|
||||
user,
|
||||
validated,
|
||||
handleSubmit,
|
||||
handleChange,
|
||||
} = useAuthorizationForm();
|
||||
|
||||
const onBack = () => {
|
||||
navigate(-1);
|
||||
};
|
||||
|
||||
const onSubmit = async (event) => {
|
||||
if (await handleSubmit(event)) {
|
||||
// onBack();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<h1 className='mt-2 text-center'>
|
||||
Вход в аккаунт.
|
||||
</h1>
|
||||
<Form className='m-0 p-2' noValidate validated={validated} onSubmit={onSubmit}>
|
||||
<AuthorizationInput user={user} handleChange={handleChange} />
|
||||
<Form.Group className='row justify-content-center m-0 mt-3'>
|
||||
<Button className='lib-btn col-5 col-lg-2 m-0 me-2' onClick={() => onBack()}>
|
||||
Назад
|
||||
</Button>
|
||||
<Button className='lib-btn col-5 col-lg-2 m-0 ms-2' type='submit'>
|
||||
Войти
|
||||
</Button>
|
||||
<Button className="lib-btn col-5 col-lg-2 m-0 ms-2" as={Link} to="/reg-page">
|
||||
Зарегистрироваться
|
||||
</Button>
|
||||
</Form.Group>
|
||||
</Form>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
RegistrationForm.propTypes = {
|
||||
id: PropTypes.string,
|
||||
};
|
||||
|
||||
export default RegistrationForm;
|
@ -0,0 +1,20 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import Input from '../../../input/Input.jsx';
|
||||
|
||||
const AuthorizationInput = ({ user, handleChange }) => {
|
||||
return (
|
||||
<>
|
||||
<Input name='name' label='Логин' value={user.name} onChange={handleChange}
|
||||
required />
|
||||
<Input name='password' label='Пароль' value={user.password} onChange={handleChange}
|
||||
required />
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
AuthorizationInput.propTypes = {
|
||||
user: PropTypes.object,
|
||||
handleChange: PropTypes.func,
|
||||
};
|
||||
|
||||
export default AuthorizationInput;
|
@ -0,0 +1,67 @@
|
||||
import { useState } from 'react';
|
||||
import toast from 'react-hot-toast';
|
||||
import UsersApiService from '../../service/UsersApiService';
|
||||
import useUserObject from '../../hooks/UserObjectHook';
|
||||
import useAuthorization from '../../context_hooks/AuthorizationHook';
|
||||
|
||||
const useAuthorizationForm = () => {
|
||||
const { user, setUser } = useUserObject();
|
||||
|
||||
const [validated, setValidated] = useState(false);
|
||||
|
||||
const resetValidity = () => {
|
||||
setValidated(false);
|
||||
};
|
||||
|
||||
const { userLogin } = useAuthorization();
|
||||
|
||||
const getProperties = (formData) => {
|
||||
const { name } = formData;
|
||||
const { password } = formData;
|
||||
const { role } = formData;
|
||||
return {
|
||||
name: name.toString(),
|
||||
password: password.toString(),
|
||||
role: role.toString(),
|
||||
};
|
||||
};
|
||||
|
||||
const handleChange = (event) => {
|
||||
const inputName = event.target.name;
|
||||
const inputValue = event.target.type === 'checkbox' ? event.target.checked : event.target.value;
|
||||
setUser({
|
||||
...user,
|
||||
[inputName]: inputValue,
|
||||
});
|
||||
};
|
||||
|
||||
const handleSubmit = async (event) => {
|
||||
const form = event.currentTarget;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const body = getProperties(user);
|
||||
const { name, password } = body;
|
||||
if (form.checkValidity()) {
|
||||
const expand = `?name=${name}&password=${password}`;
|
||||
const data = await UsersApiService.getAll(expand);
|
||||
if (data.length !== 0) {
|
||||
userLogin(data[0].id);
|
||||
toast.success('Успешный вход в аккаунт', { id: 'Authorization' });
|
||||
return true;
|
||||
}
|
||||
}
|
||||
toast.error('Неправильно введен логин или пароль', { id: 'Authorization' });
|
||||
setValidated(true);
|
||||
return false;
|
||||
};
|
||||
|
||||
return {
|
||||
user,
|
||||
validated,
|
||||
handleSubmit,
|
||||
handleChange,
|
||||
resetValidity,
|
||||
};
|
||||
};
|
||||
|
||||
export default useAuthorizationForm;
|
@ -0,0 +1,33 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import {
|
||||
createContext,
|
||||
useEffect,
|
||||
useReducer,
|
||||
} from 'react';
|
||||
import { authorizationReducer, loadId, saveId } from './AuthorizationReducer';
|
||||
|
||||
const UserContext = createContext(null);
|
||||
|
||||
export const IdProvider = ({ children }) => {
|
||||
const [id, dispatch] = useReducer(authorizationReducer, null, loadId);
|
||||
|
||||
useEffect(() => {
|
||||
if (id && id !== undefined) {
|
||||
saveId(id);
|
||||
} else {
|
||||
loadId();
|
||||
}
|
||||
}, [id]);
|
||||
|
||||
return (
|
||||
<UserContext.Provider value={{ user_id: id, dispatch }}>
|
||||
{children}
|
||||
</UserContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
IdProvider.propTypes = {
|
||||
children: PropTypes.node,
|
||||
};
|
||||
|
||||
export default UserContext;
|
@ -0,0 +1,23 @@
|
||||
import { useContext } from 'react';
|
||||
import AuthorizationContext from './AuthorizationContext.jsx';
|
||||
import { userLogin, userLogout } from './AuthorizationReducer';
|
||||
|
||||
const useAuthorization = () => {
|
||||
const { id, dispatch } = useContext(AuthorizationContext);
|
||||
|
||||
const getId = () => {
|
||||
if (!id) {
|
||||
return '';
|
||||
}
|
||||
return id.toString();
|
||||
};
|
||||
|
||||
return {
|
||||
id,
|
||||
getId,
|
||||
userLogin: (item) => dispatch(userLogin(item)),
|
||||
userLogout: () => dispatch(userLogout()),
|
||||
};
|
||||
};
|
||||
|
||||
export default useAuthorization;
|
@ -0,0 +1,40 @@
|
||||
const USER_ID = 'userId';
|
||||
const USER_LOGIN = 'user/login';
|
||||
const USER_LOGOUT = 'user/logout';
|
||||
|
||||
export const saveId = (id) => {
|
||||
localStorage.setItem(USER_ID, JSON.stringify(id));
|
||||
};
|
||||
|
||||
export const loadId = (initialValue = null) => {
|
||||
const idData = localStorage.getItem(USER_ID);
|
||||
if (idData) {
|
||||
return JSON.parse(idData);
|
||||
}
|
||||
return initialValue;
|
||||
};
|
||||
|
||||
export const authorizationReducer = (id, action) => {
|
||||
const { item: user } = action;
|
||||
window.location.reload();
|
||||
switch (action.type) {
|
||||
case USER_LOGIN: {
|
||||
return user;
|
||||
}
|
||||
case USER_LOGOUT: {
|
||||
localStorage.removeItem(USER_ID);
|
||||
return '';
|
||||
}
|
||||
default: {
|
||||
throw Error(`Unknown action: ${action.type}`);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export const userLogin = (item) => ({
|
||||
type: USER_LOGIN, item,
|
||||
});
|
||||
|
||||
export const userLogout = () => ({
|
||||
type: USER_LOGOUT,
|
||||
});
|
18
ReactLibrary/src/components/users/hooks/UserObjectHook.js
Normal file
18
ReactLibrary/src/components/users/hooks/UserObjectHook.js
Normal file
@ -0,0 +1,18 @@
|
||||
import { useState } from 'react';
|
||||
|
||||
const useUserObject = () => {
|
||||
const emptyObject = {
|
||||
name: '',
|
||||
password: '',
|
||||
role: 'user',
|
||||
id: '',
|
||||
};
|
||||
const [userObject, setUserObject] = useState({ ...emptyObject });
|
||||
|
||||
return {
|
||||
user: userObject,
|
||||
setUser: setUserObject,
|
||||
};
|
||||
};
|
||||
|
||||
export default useUserObject;
|
21
ReactLibrary/src/components/users/hooks/UsersHook.js
Normal file
21
ReactLibrary/src/components/users/hooks/UsersHook.js
Normal file
@ -0,0 +1,21 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import UsersApiService from '../service/UsersApiService';
|
||||
|
||||
const useUsers = () => {
|
||||
const [users, setUsers] = useState([]);
|
||||
|
||||
const getUsers = async () => {
|
||||
const data = await UsersApiService.getAll();
|
||||
setUsers(data ?? []);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
getUsers();
|
||||
}, []);
|
||||
|
||||
return {
|
||||
types: users,
|
||||
};
|
||||
};
|
||||
|
||||
export default useUsers;
|
@ -0,0 +1,48 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import { Button, Form } from 'react-bootstrap';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import useRegistrationForm from '../hooks/RegistrationFormHook';
|
||||
import RegistrationInput from './RegistrationInput.jsx';
|
||||
|
||||
const RegistrationForm = () => {
|
||||
const navigate = useNavigate();
|
||||
|
||||
const {
|
||||
user,
|
||||
validated,
|
||||
handleSubmit,
|
||||
handleChange,
|
||||
} = useRegistrationForm();
|
||||
|
||||
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}>
|
||||
<RegistrationInput user={user} handleChange={handleChange} />
|
||||
<Form.Group className='row justify-content-center m-0 mt-3'>
|
||||
<Button className='lib-btn col-5 col-lg-2 m-0 me-2' onClick={() => onBack()}>
|
||||
Назад
|
||||
</Button>
|
||||
<Button className='lib-btn col-5 col-lg-2 m-0 ms-2' type='submit'>
|
||||
Сохранить
|
||||
</Button>
|
||||
</Form.Group>
|
||||
</Form>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
RegistrationForm.propTypes = {
|
||||
id: PropTypes.string,
|
||||
};
|
||||
|
||||
export default RegistrationForm;
|
@ -0,0 +1,20 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import Input from '../../../input/Input.jsx';
|
||||
|
||||
const RegistrationInput = ({ user, handleChange }) => {
|
||||
return (
|
||||
<>
|
||||
<Input name='name' label='Логин' value={user.name} onChange={handleChange}
|
||||
required />
|
||||
<Input name='password' label='Пароль' value={user.password} onChange={handleChange}
|
||||
required />
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
RegistrationInput.propTypes = {
|
||||
user: PropTypes.object,
|
||||
handleChange: PropTypes.func,
|
||||
};
|
||||
|
||||
export default RegistrationInput;
|
@ -0,0 +1,72 @@
|
||||
import { useState } from 'react';
|
||||
import toast from 'react-hot-toast';
|
||||
import UsersApiService from '../../service/UsersApiService';
|
||||
import useUserObject from '../../hooks/UserObjectHook';
|
||||
import useAuthorization from '../../context_hooks/AuthorizationHook';
|
||||
|
||||
const useRegistrationForm = () => {
|
||||
const { user, setUser } = useUserObject();
|
||||
|
||||
const [validated, setValidated] = useState(false);
|
||||
|
||||
const resetValidity = () => {
|
||||
setValidated(false);
|
||||
};
|
||||
|
||||
const { userLogin } = useAuthorization();
|
||||
|
||||
const getProperties = (formData) => {
|
||||
const { name } = formData;
|
||||
const { password } = formData;
|
||||
const { role } = formData;
|
||||
return {
|
||||
name: name.toString(),
|
||||
password: password.toString(),
|
||||
role: role.toString(),
|
||||
};
|
||||
};
|
||||
|
||||
const handleChange = (event) => {
|
||||
const inputName = event.target.name;
|
||||
const inputValue = event.target.type === 'checkbox' ? event.target.checked : event.target.value;
|
||||
setUser({
|
||||
...user,
|
||||
[inputName]: inputValue,
|
||||
});
|
||||
};
|
||||
|
||||
const handleSubmit = async (event) => {
|
||||
const form = event.currentTarget;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const body = getProperties(user);
|
||||
const { name, password } = body;
|
||||
if (form.checkValidity()) {
|
||||
let expand = `?name=${name}`;
|
||||
let data = await UsersApiService.getAll(expand);
|
||||
if (data.length !== 0) {
|
||||
toast.error('Имя уже занято', { id: 'Registration' });
|
||||
setValidated(true);
|
||||
return false;
|
||||
}
|
||||
await UsersApiService.create(body);
|
||||
toast.success('Элемент успешно сохранен', { id: 'Registration' });
|
||||
expand = `?name=${name}&password=${password}`;
|
||||
data = await UsersApiService.getAll(expand);
|
||||
userLogin(data[0].id);
|
||||
return true;
|
||||
}
|
||||
setValidated(true);
|
||||
return false;
|
||||
};
|
||||
|
||||
return {
|
||||
user,
|
||||
validated,
|
||||
handleSubmit,
|
||||
handleChange,
|
||||
resetValidity,
|
||||
};
|
||||
};
|
||||
|
||||
export default useRegistrationForm;
|
@ -0,0 +1,5 @@
|
||||
import ApiService from '../../api/ApiService';
|
||||
|
||||
const UsersApiService = new ApiService('users');
|
||||
|
||||
export default UsersApiService;
|
26
ReactLibrary/src/components/users/userPage/UserObjectHook.js
Normal file
26
ReactLibrary/src/components/users/userPage/UserObjectHook.js
Normal file
@ -0,0 +1,26 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import PropTypes from 'prop-types';
|
||||
import UsersApiService from '../service/UsersApiService';
|
||||
|
||||
const useUserObject = async (id) => {
|
||||
// debugger;
|
||||
let userObject = {
|
||||
name: 'user',
|
||||
password: '',
|
||||
role: 'user',
|
||||
id: '',
|
||||
};
|
||||
const data = await UsersApiService.get(id);
|
||||
if (data && data.name) {
|
||||
//userObject.name = data.name;
|
||||
}
|
||||
return {
|
||||
userObject,
|
||||
};
|
||||
};
|
||||
|
||||
useUserObject.propTypes = {
|
||||
id: PropTypes.number,
|
||||
};
|
||||
|
||||
export default useUserObject;
|
29
ReactLibrary/src/components/users/userPage/UserPageInfo.jsx
Normal file
29
ReactLibrary/src/components/users/userPage/UserPageInfo.jsx
Normal file
@ -0,0 +1,29 @@
|
||||
import { Button } from 'react-bootstrap';
|
||||
import { Link } from 'react-router-dom';
|
||||
import useAuthorization from '../context_hooks/AuthorizationHook';
|
||||
import useUserObject from './UserObjectHook';
|
||||
|
||||
const UserPageInfo = () => {
|
||||
debugger;
|
||||
// const id = parseInt(localStorage.getItem('userId'), 10);
|
||||
const { userLogout } = useAuthorization();
|
||||
return (
|
||||
<>
|
||||
<h1 className='mt-2 text-md-start text-center'>
|
||||
Здравствуйте, {null || 'гость'}
|
||||
</h1>
|
||||
<p className="mt-2 text-md-start text-center">
|
||||
Это ваш личный кабинет.
|
||||
Здесь вы можете посмотреть вашу Историю чтения и Избранные книги.
|
||||
</p>
|
||||
<div className="d-grid gap-2 mt-2 d-md-flex justify-content-md-start">
|
||||
<Button as={Link} to="/user-favorities" className='lib-btn'>Избранное</Button>
|
||||
<Button as={Link} to="/user-history" className='lib-btn'>История</Button>
|
||||
<Button className='lib-btn' onClick={userLogout}>Выйти</Button>
|
||||
<Button as={Link} to="/admin-page" className='lib-btn'>Страница администратора</Button>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default UserPageInfo;
|
15
ReactLibrary/src/components/utils/Base64.js
Normal file
15
ReactLibrary/src/components/utils/Base64.js
Normal 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;
|
@ -31,7 +31,6 @@ const routes = [
|
||||
{
|
||||
path: '/login-page',
|
||||
element: <LoginPage/>,
|
||||
title: 'Войти',
|
||||
},
|
||||
{
|
||||
path: '/user-page',
|
||||
|
@ -1,54 +1,15 @@
|
||||
import { useState } from 'react';
|
||||
import { Button, Form } from 'react-bootstrap';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useParams } from 'react-router-dom';
|
||||
import LinesForm from '../components/lines/form/LinesForm.jsx';
|
||||
|
||||
const BookEdit = () => {
|
||||
const [validated, setValidated] = useState(false);
|
||||
const navigate = useNavigate();
|
||||
const handleSubmit = (event) => {
|
||||
const form = event.currentTarget;
|
||||
if (form.checkValidity() === false) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
}
|
||||
setValidated(true);
|
||||
};
|
||||
const { id } = useParams();
|
||||
|
||||
return (
|
||||
<>
|
||||
<h1 className='mt-2 text-center'>
|
||||
Добавление/редактирование книги.
|
||||
</h1>
|
||||
<div className="text-center">
|
||||
<img id="image-preview" src="https://via.placeholder.com/200" alt="placeholder"/>
|
||||
</div>
|
||||
<Form id="books-form" noValidate validated={validated} onSubmit={handleSubmit}>
|
||||
<Form.Group className="mb-2" controlId="author">
|
||||
<Form.Label>Автор</Form.Label>
|
||||
<Form.Select name='selected' required>
|
||||
</Form.Select>
|
||||
</Form.Group>
|
||||
<Form.Group className="mb-2" controlId="name">
|
||||
<Form.Label>Название</Form.Label>
|
||||
<Form.Control type="text" name="name" required/>
|
||||
</Form.Group>
|
||||
<Form.Group className="mb-2" controlId="category">
|
||||
<Form.Label>Категория</Form.Label>
|
||||
<Form.Select name='selected' required>
|
||||
</Form.Select>
|
||||
</Form.Group>
|
||||
<Form.Group className="mb-2" controlId="year">
|
||||
<Form.Label>Год издания</Form.Label>
|
||||
<Form.Control type="text" name="year" required/>
|
||||
</Form.Group>
|
||||
<Form.Group className="mb-2" controlId="file">
|
||||
<Form.Label>Изображение</Form.Label>
|
||||
<Form.Control type="file" name="image" accept="image/*"/>
|
||||
</Form.Group>
|
||||
<div className="d-grid gap-2 mt-4 d-md-flex justify-content-md-center">
|
||||
<Button className="lib-btn" onClick={() => navigate(-1)}>Назад</Button>
|
||||
<Button className="lib-btn" type="submit">Сохранить</Button>
|
||||
</div>
|
||||
</Form>
|
||||
<LinesForm id={id} />
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
@ -1,5 +1,4 @@
|
||||
import { Button, Table } from 'react-bootstrap';
|
||||
import { Link } from 'react-router-dom';
|
||||
import Lines from '../components/lines/table/Lines.jsx';
|
||||
|
||||
const BooksTable = () => {
|
||||
return (
|
||||
@ -7,20 +6,7 @@ const BooksTable = () => {
|
||||
<h1 className='mt-2 text-md-start text-center'>
|
||||
Таблица книг.
|
||||
</h1>
|
||||
<Button as={Link} to="/book-edit" className='lib-btn'>Добавить книгу</Button>
|
||||
<Table className="mt-2 lib-table" striped>
|
||||
<thead><tr>
|
||||
<th scope="col">№</th>
|
||||
<th scope="col" className="w-25">Автор</th>
|
||||
<th scope="col" className="w-25">Название</th>
|
||||
<th scope="col" className="w-25">Категория</th>
|
||||
<th scope="col" className="w-25">Год издания</th>
|
||||
<th scope="col"></th>
|
||||
<th scope="col"></th>
|
||||
<th scope="col"></th>
|
||||
</tr></thead>
|
||||
<tbody></tbody>
|
||||
</Table>
|
||||
<Lines />
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
@ -1,43 +1,9 @@
|
||||
import { useState } from 'react';
|
||||
import { Button, Form } from 'react-bootstrap';
|
||||
import { Link } from 'react-router-dom';
|
||||
import AuthorizationForm from '../components/users/authorization/form/AuthorizationForm.jsx';
|
||||
|
||||
const LoginPage = () => {
|
||||
const [validated, setValidated] = useState(false);
|
||||
const handleSubmit = (event) => {
|
||||
const form = event.currentTarget;
|
||||
if (form.checkValidity() === false) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
}
|
||||
setValidated(true);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<h1 className='mt-2 text-center'>
|
||||
Вход в аккаунт.
|
||||
</h1>
|
||||
<div className="row justify-content-center">
|
||||
<Form className="col-md-6 m-0" noValidate validated={validated} onSubmit={handleSubmit}>
|
||||
<Form.Group className="mb-2" controlId="email">
|
||||
<Form.Label>E-mail</Form.Label>
|
||||
<Form.Control type="email" name="email" placeholder="name@example.ru" required />
|
||||
<Form.Control.Feedback>Почта заполнена</Form.Control.Feedback>
|
||||
<Form.Control.Feedback type="invalid">Почта не заполнена</Form.Control.Feedback>
|
||||
</Form.Group>
|
||||
<Form.Group className="mb-2" controlId="password">
|
||||
<Form.Label>Пароль</Form.Label>
|
||||
<Form.Control type="password" name="password" required />
|
||||
<Form.Control.Feedback>Пароль заполнен</Form.Control.Feedback>
|
||||
<Form.Control.Feedback type="invalid">Пароль не заполнен</Form.Control.Feedback>
|
||||
</Form.Group>
|
||||
<div className="d-grid gap-2 mt-4 d-md-flex justify-content-md-center">
|
||||
<Button className="lib-btn" type="submit">Отправить</Button>
|
||||
<Button as={Link} to="/reg-page" className="lib-btn">У меня нет аккаунта</Button>
|
||||
</div>
|
||||
</Form>
|
||||
</div>
|
||||
<AuthorizationForm />
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
@ -1,53 +1,12 @@
|
||||
import { useState } from 'react';
|
||||
import { Button, Form } from 'react-bootstrap';
|
||||
import RegistrationForm from '../components/users/registration/form/RegistrationForm.jsx';
|
||||
|
||||
const RegPage = () => {
|
||||
const [validated, setValidated] = useState(false);
|
||||
const handleSubmit = (event) => {
|
||||
const form = event.currentTarget;
|
||||
if (form.checkValidity() === false) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
}
|
||||
setValidated(true);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<h1 className='mt-2 text-center'>
|
||||
Создание аккаунта.
|
||||
</h1>
|
||||
<div className="row justify-content-center">
|
||||
<Form className="col-md-6 m-0" noValidate validated={validated} onSubmit={handleSubmit}>
|
||||
<Form.Group className="mb-2" controlId="name">
|
||||
<Form.Label>Никнейм</Form.Label>
|
||||
<Form.Control type="text" name="name" required />
|
||||
<Form.Control.Feedback>Никнейм заполнен</Form.Control.Feedback>
|
||||
<Form.Control.Feedback type="invalid">Никнейм не заполнен</Form.Control.Feedback>
|
||||
</Form.Group>
|
||||
<Form.Group className="mb-2" controlId="email">
|
||||
<Form.Label>E-mail</Form.Label>
|
||||
<Form.Control type="email" name="email" placeholder="name@example.ru" required />
|
||||
<Form.Control.Feedback>Почта заполнена</Form.Control.Feedback>
|
||||
<Form.Control.Feedback type="invalid">Почта не заполнена</Form.Control.Feedback>
|
||||
</Form.Group>
|
||||
<Form.Group className="mb-2" controlId="password">
|
||||
<Form.Label>Пароль</Form.Label>
|
||||
<Form.Control type="password" name="password" required />
|
||||
<Form.Control.Feedback>Пароль заполнен</Form.Control.Feedback>
|
||||
<Form.Control.Feedback type="invalid">Пароль не заполнен</Form.Control.Feedback>
|
||||
</Form.Group>
|
||||
<Form.Group className="mb-2" controlId="password">
|
||||
<Form.Label>Повторите пароль</Form.Label>
|
||||
<Form.Control type="password" name="password" required />
|
||||
<Form.Control.Feedback>Пароль повторен</Form.Control.Feedback>
|
||||
<Form.Control.Feedback type="invalid">Пароль не повторен</Form.Control.Feedback>
|
||||
</Form.Group>
|
||||
<div className="d-grid gap-2 mt-4 d-md-flex justify-content-md-center">
|
||||
<Button className="lib-btn" type="submit">Отправить</Button>
|
||||
</div>
|
||||
</Form>
|
||||
</div>
|
||||
<RegistrationForm />
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
@ -1,21 +1,18 @@
|
||||
import { Button } from 'react-bootstrap';
|
||||
import { Link } from 'react-router-dom';
|
||||
import AuthorizationForm from '../components/users/authorization/form/AuthorizationForm.jsx';
|
||||
import UserPageInfo from '../components/users/userPage/UserPageInfo.jsx';
|
||||
import useAuthorization from '../components/users/context_hooks/AuthorizationHook.js';
|
||||
|
||||
const UserPage = () => {
|
||||
let { id } = useAuthorization();
|
||||
// let id = localStorage.getItem('userId');
|
||||
id = parseInt(id, 10);
|
||||
if (!id) {
|
||||
return (
|
||||
<AuthorizationForm />
|
||||
);
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<h1 className='mt-2 text-md-start text-center'>
|
||||
Ваш личный кабинет.
|
||||
</h1>
|
||||
<p className="mt-2 text-md-start text-center">
|
||||
Здесь вы можете посмотреть вашу Историю чтения и Избранные книги.
|
||||
</p>
|
||||
<div className="d-grid gap-2 mt-2 d-md-flex justify-content-md-start">
|
||||
<Button as={Link} to="/user-favorities" className='lib-btn'>Избранное</Button>
|
||||
<Button as={Link} to="/user-history" className='lib-btn'>История</Button>
|
||||
<Button as={Link} to="/admin-page" className='lib-btn'>Страница администратора</Button>
|
||||
</div>
|
||||
</>
|
||||
<UserPageInfo />
|
||||
);
|
||||
};
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user