5 лаба

This commit is contained in:
Alenka 2023-12-05 14:58:00 +04:00
parent 01bd008c9a
commit 00a753c86d
107 changed files with 8311 additions and 0 deletions

View File

@ -0,0 +1,24 @@
module.exports = {
root: true,
env: { browser: true, es2020: true },
extends: [
'airbnb-base',
'plugin:react/recommended',
'plugin:react/jsx-runtime',
'plugin:react-hooks/recommended',
],
ignorePatterns: ['dist', '.eslintrc.cjs'],
parserOptions: { ecmaVersion: 12, sourceType: 'module' },
settings: { react: { version: '18.2' } },
plugins: ['react-refresh'],
rules: {
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
'indent': 'off',
'no-console': 'off',
'arrow-body-style': 'off',
'implicit-arrow-linebreak': 'off',
},
}

24
5 лаба ИП/.gitignore vendored Normal file
View File

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

44
5 лаба ИП/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

56
5 лаба ИП/data.json Normal file

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-house-check" viewBox="0 0 16 16">
<path d="M7.293 1.5a1 1 0 0 1 1.414 0L11 3.793V2.5a.5.5 0 0 1 .5-.5h1a.5.5 0 0 1 .5.5v3.293l2.354 2.353a.5.5 0 0 1-.708.708L8 2.207l-5 5V13.5a.5.5 0 0 0 .5.5h4a.5.5 0 0 1 0 1h-4A1.5 1.5 0 0 1 2 13.5V8.207l-.646.647a.5.5 0 1 1-.708-.708L7.293 1.5Z"/>
<path d="M12.5 16a3.5 3.5 0 1 0 0-7 3.5 3.5 0 0 0 0 7Zm1.679-4.493-1.335 2.226a.75.75 0 0 1-1.174.144l-.774-.773a.5.5 0 0 1 .708-.707l.547.547 1.17-1.951a.5.5 0 1 1 .858.514Z"/>
</svg>

After

Width:  |  Height:  |  Size: 568 B

View File

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

View File

@ -0,0 +1,15 @@
{
"compilerOptions": {
"module": "ESNext",
"moduleResolution": "Node",
"target": "ES2020",
"jsx": "react",
"strictNullChecks": true,
"strictFunctionTypes": true,
"sourceMap": true
},
"exclude": [
"node_modules",
"**/node_modules/*"
]
}

View File

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

5936
5 лаба ИП/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

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"
}
}

View File

@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-house-check" viewBox="0 0 16 16">
<path d="M7.293 1.5a1 1 0 0 1 1.414 0L11 3.793V2.5a.5.5 0 0 1 .5-.5h1a.5.5 0 0 1 .5.5v3.293l2.354 2.353a.5.5 0 0 1-.708.708L8 2.207l-5 5V13.5a.5.5 0 0 0 .5.5h4a.5.5 0 0 1 0 1h-4A1.5 1.5 0 0 1 2 13.5V8.207l-.646.647a.5.5 0 1 1-.708-.708L7.293 1.5Z"/>
<path d="M12.5 16a3.5 3.5 0 1 0 0-7 3.5 3.5 0 0 0 0 7Zm1.679-4.493-1.335 2.226a.75.75 0 0 1-1.174.144l-.774-.773a.5.5 0 0 1 .708-.707l.547.547 1.17-1.951a.5.5 0 1 1 .858.514Z"/>
</svg>

After

Width:  |  Height:  |  Size: 568 B

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 640 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 812 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 767 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 174 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 87 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 254 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 278 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 317 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 499 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 153 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 640 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 812 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 767 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

View File

@ -0,0 +1,26 @@
import { Button, Card } from 'react-bootstrap';
import { Link } from 'react-router-dom';
import PropTypes from 'prop-types';
import './index.css';
const CardOfRoom = ({ name, price, image }) => {
return (
<div className="col-md-3 col-6 mb-sm-0 align-self-end">
<Card>
<Button className='justify-content-center' > <img src={image} className="card-img-top" alt="..." /></Button>
<div className="card-body">
<p className="card-title mt-0 mb-0">{name}</p>
<p className="card-text ">{price}</p>
</div>
</Card>
</div>
);
};
export default CardOfRoom;
CardOfRoom.propTypes = {
name: PropTypes.string,
price: PropTypes.string,
image: PropTypes.string,
};

View File

@ -0,0 +1,31 @@
import { Card, Button } from 'react-bootstrap';
import { Link } from 'react-router-dom';
import PropTypes from 'prop-types';
import useCart from './cart/CartHook';
const CardOfRoom = ({ name, info, image, card}) => {
const { cart, addToCart } = useCart();
const handleAnchorClick = (event, action) => {
event.preventDefault();
action();
};
return (
<div className="col-md-3 col-6 mb-sm-0 align-self-end ">
<Card>
<Link to="/PageAdmin" > <img src={image} className="card-img-top" alt="..." /></Link>
<div className="card-body">
<p className="card-title mt-0 mb-0">{name}</p>
<p className="card-text ">{info}</p>
<Button className='primary' onClick={(event) => handleAnchorClick(event, () => addToCart(card))}>Add to Cart</Button>
</div>
</Card>
</div>
);
};
export default CardOfRoom;
CardOfRoom.propTypes = {
name: PropTypes.string,
info: PropTypes.string,
image: PropTypes.string,
};

View File

@ -0,0 +1,16 @@
// import { Table } from 'react-bootstrap';
import otz from '../assets/assets/отзыв.png';
import otz1 from '../assets/assets/отз.png';
import './index.css';
const Comment = () => {
return (
<div className="col-md-3 col-6 mb-sm-0 align-self-end ">
<h4><i > Инкогнито: </i></h4>
<img src={otz} style={{ width: '200%', height: '700%', paddingTop: '20px' }} alt="logo" />
<h4><i>Kto-to: </i></h4>
<img src={otz1} style={{ width: '400%', height: '700%', paddingTop: '20px' }} alt="logo" />
</div>
);
};
export default Comment;

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,30 @@
#banner {
margin: 2px;
display: flex;
align-items: center;
flex-direction: column;
}
#banner img {
border: 1px solid #3c3c3f;
border-radius: 5px;
}
#banner img.banner-show {
width: 100%;
opacity: 1;
transition: opacity 1s, visibility 0s;
}
#banner img.banner-hide {
height: 0;
width: 0;
opacity: 0;
visibility: hidden;
transition: opacity 1s, visibility 0s 1s;
}
@media (max-width: 390px) {
.banner {
height: 180 px;
}
}

View File

@ -0,0 +1,39 @@
import { useEffect, useState } from 'react';
import banner1 from '../../assets/assets/банер.png';
import banner2 from '../../assets/assets/банер11.png';
import './Banner.css';
const Banner = () => {
const [currentBanner, setCurrentBanner] = useState(0);
const banners = [banner1, banner2];
const getBannerClass = (index) => {
return currentBanner === index ? 'banner-show' : 'banner-hide';
};
useEffect(() => {
const bannerInterval = setInterval(
() => {
console.info('Banner changed');
let current = currentBanner + 1;
if (current === banners.length) {
current = 0;
}
setCurrentBanner(current);
},
5000,
);
return () => clearInterval(bannerInterval);
});
return (
<div id="banner" >
{
banners.map((banner, index) =>
<img key={index} className={getBannerClass(index)} src={banner} alt={`banner${index}`} />)
}
</div >
);
};
export default Banner;

View File

@ -0,0 +1,12 @@
.cart-image {
width: 12.1rem;
padding: .25rem;
}
.cart-item {
height: auto;
}
.card {
width: 300px;
height: 200px;
}

View File

@ -0,0 +1,65 @@
import { Button, ButtonGroup, Card } from 'react-bootstrap';
import { DashLg, PlusLg, XLg } from 'react-bootstrap-icons';
import imgPlaceholder from '../../assets/200.png';
import './Cart.css';
import useCart from './CartHook';
import Modal from './Modal.jsx';
const Cart = () => {
const {
cart,
getCartSum,
addToCart,
removeFromCart,
clearCart,
} = useCart();
return (
<div className='d-flex flex-column align-items-left'>
<div className='mb-2 col-12 col-md-8 col-lg-6 d-flex align-items-center'>
</div>
<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} width="300" alt="Cart Image" />
{cartItem.type.name}
</div>
<div className='cart-item mt-2 mt-sm-0 d-flex flex-column align-items-center align-items-sm-end'>
<div>
{cartItem.price}
{' * '}
{cartItem.count}
{' = '}
{parseFloat(cartItem.price * cartItem.count).toFixed(2)}
</div>
<ButtonGroup className='mt-2 mt-sm-1' aria-label="Cart counter">
<Button variant="success" onClick={() => addToCart(cartItem)}>
<PlusLg />
</Button>
<Button variant="danger" onClick={() => removeFromCart(cartItem)}>
<DashLg />
</Button>
</ButtonGroup>
</div>
</Card.Body>
</Card>)
}
<div className='mb-2 col-12 col-md-8 col-lg-6 d-flex justify-content-end'>
<strong>Итого: {getCartSum()} &#8381;</strong>
</div>
<div> <Modal Clear={clearCart}/></div>
</div>
</div>
);
};
export default Cart;

View File

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

View File

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

View File

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

View File

@ -0,0 +1,16 @@
import useInputValue from './Local.jsx';
const InputComponent = () => {
const input = useInputValue('');
return (
<input
type="text"
value={input.value}
onChange={input.onChange}
id='input'
/>
);
};
export default InputComponent;

View File

@ -0,0 +1,32 @@
import { useState, useEffect } from 'react';
const useInputValue = (initialValue) => {
const [value, setValue] = useState(initialValue);
// useEffect(() => {
// const storedValue = localStorage.getItem('inputValue');
// if (storedValue) {
// setValue(storedValue);
// }
// }, []);
const handleInputChange = (e) => {
setValue(e.target.value);
};
useEffect(() => {
localStorage.clear();
localStorage.setItem('inputValue', value);
}, [value]);
const ClearStor = () => {
localStorage.clear();
};
return {
value,
onChange: handleInputChange,
Clear: ClearStor,
};
};
export default useInputValue;

View File

@ -0,0 +1,47 @@
import { useState } from 'react';
import { Button } from 'react-bootstrap';
import Modal from 'react-bootstrap/Modal';
import InputComponent from './Local copy.jsx';
function Example({Clear}) {
const [show, setShow] = useState(false);
const handleClose = () => {
setShow(false);
document.getElementById('input').value = ' ';
console.log(document.getElementById('input').value);
};
const handleShow = () => setShow(true);
const Close = () =>{
handleClose();
Clear();
};
return (
<>
<Button variant="primary" onClick={handleShow}>
Забронировать
</Button>
<Modal show={show} onHide={handleClose} >
<Modal.Header closeButton>
<Modal.Title>Бронирование</Modal.Title>
</Modal.Header>
<Modal.Body>
<strong className='flex-fill me-4'>Введите Ваше ФИО</strong>
<InputComponent/>
<p>Спасибо, что выбрали нас! В ближайшее время с
Вами свяжется оператор</p> </Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={handleClose}>
Отмена
</Button>
<Button variant="primary" onClick={Close}>
Сохранить
</Button>
</Modal.Footer>
</Modal>
</>
);
}
export default Example;

View File

@ -0,0 +1,5 @@
.my-footer {
background-color: pink;
height: 32px;
color: rgb(0, 0, 0)101;
}

View File

@ -0,0 +1,13 @@
import './Footer.css';
const Footer = () => {
const year = new Date().getFullYear();
return (
<footer className="my-footer mt-auto d-flex flex-shrink-0 justify-content-center align-items-center">
Ульяновск, {year}
</footer>
);
};
export default Footer;

View File

@ -0,0 +1,131 @@
h1 {
font-size: 1.5em;
}
h2 {
font-size: 1.25em;
}
h3 {
font-size: 1.1em;
}
.card-text {
margin-top: 0;
padding: auto;
text-align: center;
font-weight: bold;
}
.btn-card {
background: rgb(233, 120, 184);
width: 85%;
padding: 40px;
}
.card {
background: rgb(238, 138, 248) !important;
transition: 0.3s;
/* margin-bottom: 30px; */
padding-top: 30px;
width: 250px; /* увеличение ширины карточки */
height: 300px; /* увеличение высоты карточки */
}
.card-title {
margin-top: 0;
padding: auto;
text-align: center !important;
font-weight: bold !important;
}
.btn-mw {
width: 100%;
}
@media (max-width:768px) {
.col-bott {
margin-top: 10px;
}
.banner-text {
font-size: 24px;
}
}
@media (max-width : 376px) {
footer {
height: 80px;
}
}
@media (max-width: 768px) {
header nav {
height: 90px;
}
@media (max-width : 390px) {
.card {
height: 100px;
width: 170px;
}
}
@media (max-width : 390px) {
.card-body {
background: rgb(238, 138, 248) !important;
}
}
@media (max-width : 390px) {
footer {
height: 80px;
}
}
.panel-col {
display: flex;
flex-direction: row;
justify-content: center;
}
}
@media (max-width: 766px) {
.banner-main {
width: 30vw;
}
}
@media (max-width: 368px) {
.panel-col {
display: flex;
flex-direction: column;
}
.banner-main {
width: auto;
}
}
@media (min-width: 768px) {
.btn-mw {
width: 30%;
}
}
@media (min-width: 1200px) {
.btn-mw {
width: 20%;
}
}

View File

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

View File

@ -0,0 +1,29 @@
import PropTypes from 'prop-types';
import { Form } from 'react-bootstrap';
const Select = ({
values, name, label, value, onChange, className, ...rest
}) => {
return (
<Form.Group className={`mb-2 ${className || ''}`} controlId={name}>
<Form.Label className='form-label'>{label}</Form.Label>
<Form.Select name={name || ''} value={value || ''} onChange={onChange} {...rest}>
<option value=''>Выберите значение</option>
{
values.map((type) => <option key={type.id} value={type.id}>{type.name}</option>)
}
</Form.Select>
</Form.Group>
);
};
Select.propTypes = {
values: PropTypes.array,
name: PropTypes.string,
label: PropTypes.string,
value: PropTypes.string,
onChange: PropTypes.func,
className: PropTypes.string,
};
export default Select;

View File

@ -0,0 +1,48 @@
import PropTypes from 'prop-types';
import { Button, Form } from 'react-bootstrap';
import { useNavigate } from 'react-router-dom';
import useLinesItemForm from '../hooks/LinesItemFormHook';
import LinesItemForm from './LinesItemForm.jsx';
const LinesForm = ({ id }) => {
const navigate = useNavigate();
const {
item,
validated,
handleSubmit,
handleChange,
} = useLinesItemForm(id);
const onBack = () => {
navigate(-1);
};
const onSubmit = async (event) => {
if (await handleSubmit(event)) {
onBack();
}
};
return (
<>
<Form className='m-0 p-2' noValidate validated={validated} onSubmit={onSubmit}>
<LinesItemForm item={item} handleChange={handleChange} />
<Form.Group className='row justify-content-center m-0 mt-3'>
<Button className='col-5 col-lg-2 m-0 me-2' variant='secondary' onClick={() => onBack()}>
Назад
</Button>
<Button className='col-5 col-lg-2 m-0 ms-2' type='submit' variant='primary'>
Сохранить
</Button>
</Form.Group>
</Form>
</>
);
};
LinesForm.propTypes = {
id: PropTypes.string,
};
export default LinesForm;

View File

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

View File

@ -0,0 +1,34 @@
import PropTypes from 'prop-types';
import imgPlaceholder from '../../../assets/200.png';
import Input from '../../input/Input.jsx';
import Select from '../../input/Select.jsx';
import useTypes from '../../types/hooks/TypesHook';
import './LinesItemForm.css';
const LinesItemForm = ({ item, handleChange }) => {
const { types } = useTypes();
return (
<>
<div className='text-center'>
<img id='image-preview' className='rounded' alt='placeholder'
src={item.image || imgPlaceholder} />
</div>
<Select values={types} name='typeId' label='Вид номера' value={item.typeId} onChange={handleChange}
required />
<Input name='price' label='Цена' value={item.price} onChange={handleChange}
type='number' min='1000.0' step='0.50' required />
<Input name='count' label='Вместимость' value={item.count} onChange={handleChange}
type='number' min='1' step='1' required />
<Input name='image' label='Изображение' onChange={handleChange}
type='file' accept='image/*' />
</>
);
};
LinesItemForm.propTypes = {
item: PropTypes.object,
handleChange: PropTypes.func,
};
export default LinesItemForm;

View File

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

View File

@ -0,0 +1,28 @@
import { useSearchParams } from 'react-router-dom';
import useTypes from '../../types/hooks/TypesHook';
const useTypeFilter = () => {
const filterName = 'type';
const [searchParams, setSearchParams] = useSearchParams();
const { types } = useTypes();
const handleFilterChange = (event) => {
const type = event.target.value;
if (type) {
searchParams.set(filterName, event.target.value);
} else {
searchParams.delete(filterName);
}
setSearchParams(searchParams);
};
return {
types,
currentFilter: searchParams.get(filterName) || '',
handleFilterChange,
};
};
export default useTypeFilter;

View File

@ -0,0 +1,45 @@
import { useState } from 'react';
import useModal from '../../modal/ModalHook';
import useLinesItemForm from './LinesItemFormHook';
const useLinesFormModal = (linesChangeHandle) => {
const { isModalShow, showModal, hideModal } = useModal();
const [currentId, setCurrentId] = useState(0);
const {
item,
validated,
handleSubmit,
handleChange,
resetValidity,
} = useLinesItemForm(currentId, linesChangeHandle);
const showModalDialog = (id) => {
setCurrentId(id);
resetValidity();
showModal();
};
const onClose = () => {
setCurrentId(-1);
hideModal();
};
const onSubmit = async (event) => {
if (await handleSubmit(event)) {
onClose();
}
};
return {
isFormModalShow: isModalShow,
isFormValidated: validated,
showFormModal: showModalDialog,
currentItem: item,
handleItemChange: handleChange,
handleFormSubmit: onSubmit,
handleFormClose: onClose,
};
};
export default useLinesFormModal;

View File

@ -0,0 +1,29 @@
import { useEffect, useState } from 'react';
import LinesApiService from '../service/LinesApiService';
const useLines = (typeFilter) => {
const [linesRefresh, setLinesRefresh] = useState(false);
const [lines, setLines] = useState([]);
const handleLinesChange = () => setLinesRefresh(!linesRefresh);
const getLines = async () => {
let expand = '?_expand=type';
if (typeFilter) {
expand = `${expand}&typeId=${typeFilter}`;
}
const data = await LinesApiService.getAll(expand);
setLines(data ?? []);
};
useEffect(() => {
getLines();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [linesRefresh, typeFilter]);
return {
lines,
handleLinesChange,
};
};
export default useLines;

View File

@ -0,0 +1,81 @@
import { useState } from 'react';
import toast from 'react-hot-toast';
import getBase64FromFile from '../../utils/Base64';
import LinesApiService from '../service/LinesApiService';
import useLinesItem from './LinesItemHook';
const useLinesItemForm = (id, linesChangeHandle) => {
const { item, setItem } = useLinesItem(id);
const [validated, setValidated] = useState(false);
const resetValidity = () => {
setValidated(false);
};
const getLineObject = (formData) => {
const typeId = parseInt(formData.typeId, 10);
const price = parseFloat(formData.price).toFixed(2);
const count = parseInt(formData.count, 10);
const sum = parseFloat(price * count).toFixed(2);
const image = formData.image.startsWith('data:image') ? formData.image : '';
return {
typeId: typeId.toString(),
price: price.toString(),
count: count.toString(),
sum: sum.toString(),
image,
};
};
const handleImageChange = async (event) => {
const { files } = event.target;
const file = await getBase64FromFile(files.item(0));
setItem({
...item,
image: file,
});
};
const handleChange = (event) => {
if (event.target.type === 'file') {
handleImageChange(event);
return;
}
const inputName = event.target.name;
const inputValue = event.target.type === 'checkbox' ? event.target.checked : event.target.value;
setItem({
...item,
[inputName]: inputValue,
});
};
const handleSubmit = async (event) => {
const form = event.currentTarget;
event.preventDefault();
event.stopPropagation();
const body = getLineObject(item);
if (form.checkValidity()) {
if (id === undefined) {
await LinesApiService.create(body);
} else {
await LinesApiService.update(id, body);
}
if (linesChangeHandle) linesChangeHandle();
toast.success('Элемент успешно сохранен', { id: 'LinesTable' });
return true;
}
setValidated(true);
return false;
};
return {
item,
validated,
handleSubmit,
handleChange,
resetValidity,
};
};
export default useLinesItemForm;

View File

@ -0,0 +1,34 @@
import { useEffect, useState } from 'react';
import LinesApiService from '../service/LinesApiService';
const useLinesItem = (id) => {
const emptyItem = {
id: '',
typeId: '',
price: '0',
count: '0',
image: '',
};
const [item, setItem] = useState({ ...emptyItem });
const getItem = async (itemId = undefined) => {
if (itemId && itemId > 0) {
const data = await LinesApiService.get(itemId);
setItem(data);
} else {
setItem({ ...emptyItem });
}
};
useEffect(() => {
getItem(id);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [id]);
return {
item,
setItem,
};
};
export default useLinesItem;

View File

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

View File

@ -0,0 +1,12 @@
import LinesTableRow from './LinesTableRowForCatalog.jsx';
const Lines = () => {
return (
<>
<h4> <i> Номера отеля</i></h4>
<LinesTableRow />
</>
);
};
export default Lines;

View File

@ -0,0 +1,70 @@
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 LinesItemForm from '../form/LinesItemForm.jsx';
import useLinesDeleteModal from '../hooks/LinesDeleteModalHook';
import useTypeFilter from '../hooks/LinesFilterHook';
import useLinesFormModal from '../hooks/LinesFormModalHook';
import useLines from '../hooks/LinesHook';
import LinesTable from './LinesTable.jsx';
import LinesTableRow from './LinesTableRow.jsx';
const Lines = () => {
const { types, currentFilter, handleFilterChange } = useTypeFilter();
const { lines, handleLinesChange } = useLines(currentFilter);
const {
isDeleteModalShow,
showDeleteModal,
handleDeleteConfirm,
handleDeleteCancel,
} = useLinesDeleteModal(handleLinesChange);
const {
isFormModalShow,
isFormValidated,
showFormModal,
currentItem,
handleItemChange,
handleFormSubmit,
handleFormClose,
} = useLinesFormModal(handleLinesChange);
const { addToCart } = useCart();
return (
<>
<ButtonGroup>
<Button variant='success' onClick={() => showFormModal()}>
Добавить номер
</Button>
</ButtonGroup>
<Select className='mt-2' values={types} label='Фильтр по номерам'
value={currentFilter} onChange={handleFilterChange} />
<LinesTable>
{
lines.map((line, index) =>
<LinesTableRow key={line.id}
index={index} line={line}
onAddCart={() => addToCart(line)}
onDelete={() => showDeleteModal(line.id)}
onEdit={() => showFormModal(line.id)}
/>)
}
</LinesTable>
<ModalConfirm show={isDeleteModalShow}
onConfirm={handleDeleteConfirm} onClose={handleDeleteCancel}
title='Удаление' message='Удалить элемент?' />
<ModalForm show={isFormModalShow} validated={isFormValidated}
onSubmit={handleFormSubmit} onClose={handleFormClose}
title='Редактирование'>
<LinesItemForm item={currentItem} handleChange={handleItemChange} />
</ModalForm>
</>
);
};
export default Lines;

View File

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

View File

@ -0,0 +1,23 @@
import PropTypes from 'prop-types';
import { Table } from 'react-bootstrap';
const LinesTable = ({ children }) => {
return (
<Table className='mt-2' striped bordered hover variant>
<thead>
<tr>
</tr>
</thead>
<tbody>
{children}
</tbody >
</Table >
);
};
LinesTable.propTypes = {
children: PropTypes.node,
};
export default LinesTable;

View File

@ -0,0 +1,34 @@
import PropTypes from 'prop-types';
import {
PencilFill, Trash3,
} from 'react-bootstrap-icons';
const LinesTableRow = ({
index, line, onDelete, onEdit,
}) => {
const handleAnchorClick = (event, action) => {
event.preventDefault();
action();
};
return (
<tr>
<th scope="row">{index + 1}</th>
<td>{line.type.name}</td>
<td>{parseFloat(line.price).toFixed(2)}</td>
<td>{line.count}</td>
<td><img src={line.image} alt={line.name} width="100" height="100"/></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,
};
export default LinesTableRow;

View File

@ -0,0 +1,32 @@
import PropTypes from 'prop-types';
import { Row } from 'react-bootstrap';
import CardOfRoom from '../../CardOfSpa.jsx';
import useLines from '../hooks/LinesHook';
const LinesTableRow = () => {
const { lines } = useLines();
function allCards() {
return lines.map((card) =>
<CardOfRoom key={card.id}
name={card.type.name} price={card.price} image={card.image} card={card} />)
}
return (
<>
<h3 className="ms-5 mt-4 mb-4">Каталог</h3>
<div id="catalog">
<Row className="justify-content-evenly ">
{allCards()}
</Row>
</div>
</>
);
};
LinesTableRow.propTypes = {
index: PropTypes.number,
line: PropTypes.object,
onAddCart: PropTypes.func,
};
export default LinesTableRow;

View File

@ -0,0 +1,3 @@
.modal-title {
font-size: 1.2rem;
}

View File

@ -0,0 +1,42 @@
import PropTypes from 'prop-types';
import { Button, Modal } from 'react-bootstrap';
import { createPortal } from 'react-dom';
import './Modal.css';
const ModalConfirm = ({
show, title, message, onConfirm, onClose,
}) => {
return createPortal(
<Modal show={show} backdrop='static' onHide={() => onClose()}>
<Modal.Header className='pt-2 pb-2 ps-3 pe-3' closeButton>
<Modal.Title>{title}</Modal.Title>
</Modal.Header>
<Modal.Body>
{message}
</Modal.Body>
<Modal.Footer className='m-0 pt-2 pb-2 ps-3 pe-3 row justify-content-center'>
<Button variant='secondary' className='col-5 m-0 me-2'
onClick={() => onClose()}>
Нет
</Button>
<Button variant='primary' className='col-5 m-0 ms-2'
onClick={() => onConfirm()}>
Да
</Button>
</Modal.Footer>
</Modal>,
document.body,
);
};
ModalConfirm.propTypes = {
show: PropTypes.bool,
title: PropTypes.string,
message: PropTypes.string,
onConfirm: PropTypes.func,
onClose: PropTypes.func,
};
export default ModalConfirm;

View File

@ -0,0 +1,43 @@
import PropTypes from 'prop-types';
import { Button, Form, Modal } from 'react-bootstrap';
import { createPortal } from 'react-dom';
import './Modal.css';
const ModalForm = ({
show, title, validated, onSubmit, onClose, children,
}) => {
return createPortal(
<Modal show={show} backdrop='static' onHide={() => onClose()}>
<Modal.Header className='pt-2 pb-2 ps-3 pe-3' closeButton>
<Modal.Title>{title}</Modal.Title>
</Modal.Header>
<Form className='m-0' noValidate validated={validated} onSubmit={onSubmit}>
<Modal.Body>
{children}
</Modal.Body>
<Modal.Footer className='m-0 pt-2 pb-2 ps-3 pe-3 row justify-content-center'>
<Button variant='secondary' className='col-5 m-0 me-2'
onClick={() => onClose()}>
Отмена
</Button>
<Button variant='primary' className='col-5 m-0 ms-2' type='submit'>
Сохранить
</Button>
</Modal.Footer>
</Form>
</Modal>,
document.body,
);
};
ModalForm.propTypes = {
show: PropTypes.bool,
title: PropTypes.string,
validated: PropTypes.bool,
onSubmit: PropTypes.func,
onClose: PropTypes.func,
children: PropTypes.node,
};
export default ModalForm;

View File

@ -0,0 +1,21 @@
import { useState } from 'react';
const useModal = () => {
const [showModal, setShowModal] = useState(false);
const showModalDialog = () => {
setShowModal(true);
};
const hideModalDialog = () => {
setShowModal(false);
};
return {
isModalShow: showModal,
showModal: showModalDialog,
hideModal: hideModalDialog,
};
};
export default useModal;

View File

@ -0,0 +1,13 @@
.my-navbar {
background-color: pink;
}
.my-navbar .link a:hover {
text-decoration: underline !important;
}
.my-navbar .logo {
width: 26px;
height: 26px;
}

View File

@ -0,0 +1,48 @@
import PropTypes from 'prop-types';
import { Container, Nav, Navbar } from 'react-bootstrap';
import { House } from 'react-bootstrap-icons';
import { Link, useLocation } from 'react-router-dom';
import useCart from '../cart/CartHook';
import './Navigation.css';
const Navigation = ({ routes }) => {
const { getCartSum } = useCart();
const location = useLocation();
const indexPageLink = routes.filter((route) => route.index === false).shift();
const pages = routes.filter((route) => Object.prototype.hasOwnProperty.call(route, 'title'));
return (
<header>
<Navbar expand='md' bg='' data-bs-theme='black' className='my-navbar'>
<Container fluid>
<Navbar.Brand as={Link} to={indexPageLink?.path ?? '/'}>
{/* { <Cart2 className='d-inline-block align-top me-1 logo' /> } */}
Luxury
</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>)
}
</Nav>
<Nav>
<Navbar.Brand as={Link} to='/cart'>
<House className='d-inline-block align-top me-1 logo' /> {getCartSum() ?? ''} &#8381;
</Navbar.Brand>
</Nav>
</Navbar.Collapse>
</Container>
</Navbar >
</header>
);
};
Navigation.propTypes = {
routes: PropTypes.array,
};
export default Navigation;

View File

@ -0,0 +1,24 @@
import PropTypes from 'prop-types';
const ReviewCard = ({item, onDelete}) => {
const handleAnchorClick = (event, action) => {
event.preventDefault();
action();
};
return (
<div className="text-start p-2 rounded-8 my-2 light-grey hfitcon wfitcon">
<div className='row'>
<h5 className="fw-normal text-start text-dark col">{item.name}</h5>
<a href="#" className='col text-end me-2' onClick={(event) => handleAnchorClick(event, onDelete)}><img /></a>
</div>
<h6>{item.text}</h6>
</div>
)
}
export default ReviewCard;
ReviewCard.propTypes = {
name: PropTypes.string,
text: PropTypes.string,
image: PropTypes.string,
};

View File

@ -0,0 +1,58 @@
import { Button } from 'react-bootstrap';
import { useNavigate } from 'react-router-dom';
import ModalConfirm from '../../modal/ModalConfirm.jsx';
import ModalForm from '../../modal/ModalForm.jsx';
import useReviews from '../hooks/RevievsHook';
import useReviewsFormModal from '../hooks/ReviewsFormModalHook';
import ReviewsItemForm from './ReviewsItemForm.jsx';
import ReviewCard from './ReviewCard.jsx';
import useReviewsDeleteModal from '../hooks/ReviewsDeleteModalHook';
const Reviews = () => {
const { reviews, handleReviewsChange } = useReviews();
const {
isDeleteModalShow,
showDeleteModal,
handleDeleteConfirm,
handleDeleteCancel,
} = useReviewsDeleteModal(handleReviewsChange);
const {
isFormModalShow,
isFormValidated,
showFormModal,
currentItem,
handleItemChange,
handleFormSubmit,
handleFormClose,
} = useReviewsFormModal(handleReviewsChange);
const navigate = useNavigate();
return (
<div className='formStyle formSizeStyle rounded-8 p-2 mx-auto'>
<Button variant='info' className='rounded-pill ms-3 mb-3 purple text-light' onClick={() => showFormModal()}>
Написать отзыв
</Button>
<div className='container overflow-y-auto height-500'>
{
reviews.map((item) =>
<ReviewCard key={item.id} item={item}
onDelete={() => showDeleteModal(item.id)}/>
)
}
</div>
<ModalConfirm show={isDeleteModalShow}
onConfirm={handleDeleteConfirm} onClose={handleDeleteCancel}
title='Удаление' message='Удалить отзыв?' />
<ModalForm show={isFormModalShow} validated={isFormValidated}
onSubmit={handleFormSubmit} onClose={handleFormClose}
title='Новый отзыв'>
<ReviewsItemForm item={currentItem} handleChange={handleItemChange} />
</ModalForm>
</div>
);
};
export default Reviews;

View File

@ -0,0 +1,20 @@
import PropTypes from 'prop-types';
import Input from '../../input/Input.jsx';
const ReviewsItemForm = ({ item, handleChange }) => {
return (
<>
<Input name='name' label='Имя' value={item.name} onChange={handleChange}
type='text' required />
<Input name='text' label='Текст отзыва' value={item.text} onChange={handleChange}
type='text' required/>
</>
);
};
ReviewsItemForm.propTypes = {
item: PropTypes.object,
handleChange: PropTypes.func,
};
export default ReviewsItemForm;

View File

@ -0,0 +1,24 @@
import { useEffect, useState } from 'react';
import ReviewApiService from '../service/ReviewApiService';
const useReviews = () => {
const [reviewsRefresh, setReviewsRefresh] = useState(false);
const [reviews, setReviews] = useState([]);
const handleReviewsChange = () => setReviewsRefresh(!reviewsRefresh);
const getReviews = async () => {
const data = await ReviewApiService.getAll();
setReviews(data ?? []);
};
useEffect(() => {
getReviews();
}, [reviewsRefresh]);
return {
reviews,
handleReviewsChange,
};
};
export default useReviews;

View File

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

View File

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

View File

@ -0,0 +1,62 @@
import { useState } from 'react';
import toast from 'react-hot-toast';
import getBase64FromFile from '../../utils/Base64';
import ReviewApiService from "../service/ReviewApiService.js";
import useReviewsItem from "./ReviewsItemHook.js";
const useReviewsItemForm = (id, linesChangeHandle) => {
const { item, setItem } = useReviewsItem(id);
const [validated, setValidated] = useState(false);
const resetValidity = () => {
setValidated(false);
};
const getReviewObject = (formData) => {
const name = formData.name;
const text = formData.text;
return {
name: name.toString(),
text: text.toString()
};
};
const handleChange = (event) => {
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 = getReviewObject(item);
if (form.checkValidity()) {
if (id === undefined) {
await ReviewApiService.create(body);
} else {
await ReviewApiService.update(id, body);
}
if (linesChangeHandle) linesChangeHandle();
toast.success('Отзыв успешно сохранен', { id: 'Reviews' });
return true;
}
setValidated(true);
return false;
};
return {
item,
validated,
handleSubmit,
handleChange,
resetValidity,
};
};
export default useReviewsItemForm;

View File

@ -0,0 +1,31 @@
import { useEffect, useState } from 'react';
import ReviewApiService from "../service/ReviewApiService.js";
const useReviewsItem = (id) => {
const emptyItem = {
id: '',
name: '',
text: ''
};
const [item, setItem] = useState({ ...emptyItem });
const getItem = async (itemId = undefined) => {
if (itemId && itemId > 0) {
const data = await ReviewApiService.get(itemId);
setItem(data);
} else {
setItem({ ...emptyItem });
}
};
useEffect(() => {
getItem(id);
}, [id]);
return {
item,
setItem,
};
};
export default useReviewsItem;

View File

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

View File

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

View File

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

View File

@ -0,0 +1,15 @@
const getBase64FromFile = async (file) => {
const reader = new FileReader();
return new Promise((resolve, reject) => {
reader.onloadend = () => {
const fileContent = reader.result;
resolve(fileContent);
};
reader.onerror = () => {
reject(new Error('Oops, something went wrong with the file reader.'));
};
reader.readAsDataURL(file);
});
};
export default getBase64FromFile;

View File

@ -0,0 +1,37 @@
h1 {
font-size: 1.5em;
color: black;
}
h2 {
font-size: 1.25em;
color: black;
}
h3 {
font-size: 1.1em;
color: black;
}
h4 {
font-size: 2.1em;
color: black;
text-align: center;
line-height: 1.5em;
}
.btn-mw {
width: 100%;
}
@media (min-width: 768px) {
.btn-mw {
width: 30%;
}
}
@media (min-width: 1200px) {
.btn-mw {
width: 20%;
}
}

View File

@ -0,0 +1,73 @@
import 'bootstrap/dist/css/bootstrap.min.css';
import React from 'react';
import ReactDOM from 'react-dom/client';
import { RouterProvider, createBrowserRouter } from 'react-router-dom';
import App from './App.jsx';
import './index.css';
import ErrorPage from './pages/ErrorPage.jsx';
import Page1 from './pages/Page1.jsx';
import Page2 from './pages/Page2.jsx';
import Page4 from './pages/Page4.jsx';
import Page5 from './pages/Page5.jsx';
import Page6 from './pages/Page6.jsx';
import Page7 from './pages/Page7.jsx';
import CartPage from './pages/CartPage.jsx';
import PageEdit from './pages/PageEdit.jsx';
const routes = [
{
index: true,
path: '/',
element: <Page1 />,
title: 'Главная страница',
},
{
path: '/page2',
element: <Page2 />,
title: 'Инфраструктура',
},
{
path: '/page4',
element: <Page4 />,
title: 'Редактор',
},
{
path: '/page5',
element: <Page5 />,
title: 'Отзывы',
},
{
path: '/page6',
element: <Page6 />,
title: 'Номера',
},
{
path: '/page7',
element: <Page7 />,
title: '',
},
{
path: '/cart',
element: <CartPage />,
},
{
path: '/page-edit',
element: <PageEdit />,
},
];
const router = createBrowserRouter([
{
path: '/',
element: <App routes={routes} />,
children: routes,
errorElement: <ErrorPage />,
},
]);
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>,
);

View File

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

View File

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

View File

@ -0,0 +1,11 @@
import Banner from '../components/banner/Banner.jsx';
const Page1 = () => {
return (
<>
<Banner />
</>
);
};
export default Page1;

View File

@ -0,0 +1,23 @@
// import { Table } from 'react-bootstrap';
import Spa from '../assets/assets/спа.jpg';
import Restoran from '../assets/assets/рестик.jpg';
import CardOfSpa from '../components/CardOfSpa.jsx';
const Page2 = () => {
return (
<>
<div className="container">
<h4 style={{ marginTop: '20px' }}> <i> Инфракструктура</i></h4>
</div>
<div className="row justify-content-evenly ">
<CardOfSpa name='Спа' info='Бесплатно для жителей отеля' image={Spa} />
<CardOfSpa name='Ресторан' info='Демократичные цены' image={Restoran} />
</div>
</>
);
};
export default Page2;

View File

@ -0,0 +1,49 @@
import { InputGroup, FormControl, Button } from 'react-bootstrap';
import { Link } from 'react-router-dom';
const Page3 = () => {
return (
<div className="container">
<div className="row">
<div className="col">
<i>ФИО</i>
</div>
<div className="form-group">
<InputGroup size="sm" className="mb-3">
<InputGroup.Text id="inputGroup-sizing-sm">name</InputGroup.Text>
<FormControl aria-label="Sizing example input" aria-describedby="inputGroup-sizing-sm" />
</InputGroup>
<div className="row">
<div className="col">
<i >Введите эл.адрес</i>
<div className="form-group">
<InputGroup className="mb-3">
<FormControl type="text" placeholder="Password" />
</InputGroup>
</div>
</div>
</div>
<div className="row">
<div className="col">
<i>Пароль</i>
<div className="form-group">
<InputGroup className="mb-3">
<FormControl type="text" placeholder="Password" />
</InputGroup>
</div>
</div>
</div>
</div>
<div className='text-center'>
<Button className='w-50' variant='primary' type='submit'>
<Link to="/page7" className="btn btn-catalog btn-primary rounded-0 mt-1 border">Отправить</Link>
</Button>
</div>
</div>
</div>
);
};
export default Page3;

View File

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

View File

@ -0,0 +1,10 @@
// import { Table } from 'react-bootstrap';
import Use from '../components/reviews/Reviews/Reviews.jsx';
const Page5 = () => {
return (
<Use/>
);
};
export default Page5;

View File

@ -0,0 +1,10 @@
// import { Table } from 'react-bootstrap';
import Lines from '../components/lines/table/Catalog.jsx';
const Page6 = () => {
return (
<Lines />
);
};
export default Page6;

View File

@ -0,0 +1,28 @@
// import { Table } from 'react-bootstrap';
import Banner from '../components/banner/Banner.jsx';
const Page7 = () => {
return (
<>
<div className="container">
<div className="row">
<div className="col-sm">
<i> Ваш логин : Alena</i>
</div>
<div className="row">
<h3 style={{ marginTop: '20px' }}> <i> Вы забронировали Люкс на 28.12.23 </i></h3>
</div>
<div className="row">
<div className="col">
<Banner />
</div>
</div>
</div>
</div>
</>
);
};
export default Page7;

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