This commit is contained in:
Максим Яковлев 2024-01-08 18:02:42 +04:00
parent 6d73c6c0a7
commit cdfa76e8c9
86 changed files with 8440 additions and 0 deletions

3
.idea/.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml

View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

6
.idea/misc.xml Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

8
.idea/modules.xml Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/PIbd-21_Yakovlev_M.G_IP.iml" filepath="$PROJECT_DIR$/.idea/PIbd-21_Yakovlev_M.G_IP.iml" />
</modules>
</component>
</project>

6
.idea/vcs.xml Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

20
Lab5/site/.eslintrc.cjs Normal file
View File

@ -0,0 +1,20 @@
module.exports = {
root: true,
env: { browser: true, es2020: true },
extends: [
'eslint:recommended',
'plugin:react/recommended',
'plugin:react/jsx-runtime',
'plugin:react-hooks/recommended',
],
ignorePatterns: ['dist', '.eslintrc.cjs'],
parserOptions: { ecmaVersion: 'latest', sourceType: 'module' },
settings: { react: { version: '18.2' } },
plugins: ['react-refresh'],
rules: {
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
},
}

24
Lab5/site/.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?

8
Lab5/site/README.md Normal file
View File

@ -0,0 +1,8 @@
# React + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh

103
Lab5/site/data.json Normal file

File diff suppressed because one or more lines are too long

14
Lab5/site/index.html Normal file
View File

@ -0,0 +1,14 @@
<html lang="ru" data-bs-theme="dark">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Gamepad.ru</title>
</head>
<body class="d-flex flex-column min-vh-100">
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>

15
Lab5/site/jsconfig.json Normal file
View File

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

5953
Lab5/site/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

38
Lab5/site/package.json Normal file
View File

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

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

0
Lab5/site/src/App.css Normal file
View File

32
Lab5/site/src/App.jsx Normal file
View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 122 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

View File

@ -0,0 +1,20 @@
const useLogin= () =>{
const LoginChange = (name) =>{
localStorage.setItem('Name', name.target.value);
};
const Login = () =>{
return localStorage.getItem('Name');
}
return {
LoginChange,
Login
};
}
export default useLogin;

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:3000/',
timeout: '3000',
headers: {
Accept: 'application/json',
},
});
ApiClient.interceptors.response.use(responseHandler, responseErrorHandler);

View File

@ -0,0 +1,29 @@
import { ApiClient } from './ApiClient';
class ApiService {
constructor(url) {
this.url = url;
}
async getAll(expand) {
return ApiClient.get(`${this.url}${expand || ''}`);
}
async get(id, expand) {
return ApiClient.get(`${this.url}/${id}${expand || ''}`);
}
async create(body) {
return ApiClient.post(this.url, body);
}
async update(id, body) {
return ApiClient.put(`${this.url}/${id}`, body);
}
async delete(id) {
return ApiClient.delete(`${this.url}/${id}`);
}
}
export default ApiService;

View File

@ -0,0 +1,25 @@
#banner {
margin: 2px;
display: flex;
align-items: center;
flex-direction: column;
}
#banner img {
border: 1px solid #3c3c3f;
border-radius: 5px;
}
#banner img.banner-show {
width: 100%;
opacity: 1;
transition: opacity 1s, visibility 0s;
}
#banner img.banner-hide {
height: 0;
width: 0;
opacity: 0;
visibility: hidden;
transition: opacity 1s, visibility 0s 1s;
}

View File

@ -0,0 +1,18 @@
import './Banner.css';
import useBannerHook from './BannerHook';
const Banner = () => {
const { banners, getBannerClass } = useBannerHook();
return (
<div id="banner">
{
banners.map((banner, index) =>
<img key={index} className={getBannerClass(index)} src={banner} alt={`banner${index}`} />)
}
</div>
);
};
export default Banner;

View File

@ -0,0 +1,36 @@
import { useEffect, useState } from "react";
import banner1 from '../../assets/poe.jpg';
import banner2 from '../../assets/risk-of-rain-returns.jpg';
import banner3 from '../../assets/sekiro.jpg';
import banner4 from '../../assets/eldenring.jpg';
const useBannerHook = () => {
const [currentBanner, setCurrentBanner] = useState(0);
const banners = [banner1, banner2, banner3, banner4];
const getBannerClass = (index) => {
return currentBanner === index ? 'banner-show w-100' : '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 {
banners,
getBannerClass,
};
};
export default useBannerHook;

View File

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

View File

@ -0,0 +1,58 @@
import { Button, ButtonGroup, Card } from 'react-bootstrap';
import { DashLg, PlusLg, XLg } from 'react-bootstrap-icons';
import './Cart.css';
import useCart from './CartHook';
const Cart = () => {
const {
cart,
getCartSum,
addToCart,
removeFromCart,
clearCart,
} = useCart();
return (
<div className='d-flex ps-4 flex-column align-items-center'>
<div className='mb-2 w-100 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 w-100'>
<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 || "https://via.placeholder.com/450x250"} alt="Cart Image" />
{cartItem.nameGame}
</div>
<div className='cart-item mt-2 mt-sm-0 d-flex flex-column align-items-center align-items-sm-end'>
<div>
{cartItem.price}
{' * '}
{cartItem.count}
{' = '}
{parseFloat(cartItem.price * cartItem.count).toFixed(2)}
</div>
<ButtonGroup className='mt-2 mt-sm-1' aria-label="Cart counter">
<Button variant="primary" onClick={() => addToCart(cartItem)}>
<PlusLg />
</Button>
<Button variant="danger" onClick={() => removeFromCart(cartItem)}>
<DashLg />
</Button>
</ButtonGroup>
</div>
</Card.Body>
</Card>)
}
<div className='mb-2 col-12 col-md-8 col-lg-6 d-flex justify-content-end'>
<strong>Итого: {getCartSum()} &#8381;</strong>
</div>
</div>
);
};
export default Cart;

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,41 @@
import { Button, ButtonGroup, Card } from 'react-bootstrap';
import { DashLg, Cart } from 'react-bootstrap-icons';
import './Cart.css';
import useFavor from './FavorHook';
import useCart from '../cart/CartHook';
const Favor = () => {
const {
favor,
removeFromFavor,
} = useFavor();
const { addToCart } = useCart();
return (
<div className='d-flex ps-4 align-items-center'>
{
favor.map((favorItem) =>
<Card key={favorItem.id} className='mb-2 h-100'>
<Card.Body className='p-2 flex-sm-row align-items-center'>
<div className='cart-item'>
<img className='cart-image' src={favorItem.image || "https://via.placeholder.com/450x250"} alt="Favor Image" /><br/>
{favorItem.nameGame}
</div>
<div className='cart-item mt-2 mt-sm-0'>
<ButtonGroup className='mt-2 mt-sm-1' aria-label="Favor counter">
<Button variant="danger" onClick={() => removeFromFavor(favorItem)}>
<DashLg />
</Button>
<Button variant="success" onClick={() => addToCart(favorItem)}>
<Cart />
</Button>
</ButtonGroup>
</div>
</Card.Body>
</Card>)
}
</div>
);
};
export default Favor;

View File

@ -0,0 +1,29 @@
import PropTypes from 'prop-types';
import {
createContext,
useEffect,
useReducer,
} from 'react';
import { favorReducer, loadFavor, saveFavor } from './FavorReducer';
const FavorContext = createContext(null);
export const FavorProvider = ({ children }) => {
const [favor, dispatch] = useReducer(favorReducer, [], loadFavor);
useEffect(() => {
saveFavor(favor || []);
}, [favor]);
return (
<FavorContext.Provider value={{ favor, dispatch }}>
{children}
</FavorContext.Provider>
);
};
FavorProvider.propTypes = {
children: PropTypes.node,
};
export default FavorContext;

View File

@ -0,0 +1,17 @@
import { useContext } from 'react';
import FavorContext from './FavorContext.jsx';
import { favorAdd, favorClear, favorRemove } from './FavorReducer.js';
const useFavor = () => {
const { favor, dispatch } = useContext(FavorContext);
return {
favor,
addToFavor: (item) => dispatch(favorAdd(item)),
removeFromFavor: (item) => dispatch(favorRemove(item)),
clearFavor: () => dispatch(favorClear()),
};
};
export default useFavor;

View File

@ -0,0 +1,71 @@
const setFavorCount = (favor, item) => {
return favor.map((favorItem) => {
if (favorItem.id === item.id) {
return { ...favorItem, count: favorItem.count };
}
return favorItem;
});
};
const addToFavor = (favor, item) => {
const existsItem = favor.find((favorItem) => favorItem.id === item.id);
if (existsItem !== undefined) {
return setFavorCount(favor, item, 1);
}
return [...favor, { ...item, count: 1 }];
};
const removeFromFavor = (favor, item) => {
const existsItem = favor.find((favorItem) => favorItem.id === item.id);
if (existsItem !== undefined && existsItem.count > 1) {
return setFavorCount(favor, item, -1);
}
return favor.filter((favorItem) => favorItem.id !== item.id);
};
const FAVOR_KEY = 'localFavor';
const FAVOR_ADD = 'favor/add';
const FAVOR_REMOVE = 'favor/remove';
const FAVOR_CLEAR = 'favor/clear';
export const saveFavor = (favor) => {
localStorage.setItem(FAVOR_KEY, JSON.stringify(favor));
};
export const loadFavor = (initialValue = []) => {
const favorData = localStorage.getItem(FAVOR_KEY);
if (favorData) {
return JSON.parse(favorData);
}
return initialValue;
};
export const favorReducer = (favor, action) => {
const { item } = action;
switch (action.type) {
case FAVOR_ADD: {
return addToFavor(favor, item);
}
case FAVOR_REMOVE: {
return removeFromFavor(favor, item);
}
case FAVOR_CLEAR: {
return [];
}
default: {
throw Error(`Unknown action: ${action.type}`);
}
}
};
export const favorAdd = (item) => ({
type: FAVOR_ADD, item,
});
export const favorRemove = (item) => ({
type: FAVOR_REMOVE, item,
});
export const favorClear = () => ({
type: FAVOR_CLEAR,
});

View File

@ -0,0 +1,5 @@
footer {
background-color: #FF2E63;
color:black;
height:32px;
}

View File

@ -0,0 +1,12 @@
const Footer = () => {
const year = new Date().getFullYear();
return (
<footer className="footer mt-auto d-flex flex-shrink-0 justify-content-end align-items-center">
GAMEPAD.RU © {year}
</footer>
);
};
export default Footer;

View File

@ -0,0 +1,27 @@
import PropTypes from 'prop-types';
import { Form } from 'react-bootstrap';
const Input = ({
name, label, value, onChange, className, check, checkLabel, ...rest
}) => {
return (
<Form.Group className={`${className || ''}`} controlId={name}>
<Form.Label className={checkLabel || ""}>{label}</Form.Label>
<Form.Control className={check || ""} 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,
as: PropTypes.string,
rows: PropTypes.number,
check: PropTypes.string,
checkLabel: 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='d-flex mt-0 row pt-3 ps-3 main' noValidate validated={validated} onSubmit={onSubmit}>
<LinesItemForm item={item} handleChange={handleChange} />
<Form.Group className='text-center py-4'>
<Button variant='secondary' onClick={() => onBack()}>
Назад
</Button>
<Button type='submit' variant='primary'>
Сохранить
</Button>
</Form.Group>
</Form>
</>
);
};
LinesForm.propTypes = {
id: PropTypes.string,
};
export default LinesForm;

View File

@ -0,0 +1,46 @@
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 useGenres from '../../types/hooks/GenresHook';
const LinesItemForm = ({ item, handleChange }) => {
const { types } = useTypes();
const { genres } = useGenres();
return (
<>
<div className="mb-0 h4 mx-auto text-center">Настройка поста</div>
<div className="text-center p-3">
<img id="image-preview" src={item.image || "https://via.placeholder.com/450x250"} alt="placeholder" width="50%" accept="image/*" />
</div>
<div className="w-50">
<Input name="image" label="Изображение" onChange={handleChange} type="file" accept="image/*" />
</div>
<div className="w-25">
<Select values={types} name="typeId" label="Вид товара" value={item.typeId} onChange={handleChange} required />
</div>
<div className="w-25">
<Select values={genres} name="genreId" label="Жанр товара" value={item.genreId} onChange={handleChange} required />
</div>
<div>
<Input name='price' label='Цена' className={'w-25'} value={item.price} onChange={handleChange} type='number' min='100.0' step='0.50' required />
</div>
<div>
<Input name='nameGame' label='Название игры' className={'w-25'} value={item.nameGame} onChange={handleChange} type='text' required />
</div>
<div>
<Input as='textarea' value={item.description} rows={6} className={"w-50"} name="description" label='Описание' onChange={handleChange} required />
</div>
</>
);
};
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,29 @@
import useGenres from '../../types/hooks/GenresHook';
import { useSearchParams } from 'react-router-dom';
const useGenreFilter = () =>{
const filterName = 'genre';
const [searchParams, setSearchParams] = useSearchParams();
const { genres } = useGenres();
const handleFilterChange = (event) => {
const genre = event.target.value;
if (genre) {
searchParams.set(filterName, event.target.value);
} else {
searchParams.delete(filterName);
}
setSearchParams(searchParams);
};
return {
genres,
currentFilter: searchParams.get(filterName) || '',
handleFilterChange,
filterName,
};
}
export default useGenreFilter;

View File

@ -0,0 +1,29 @@
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,
filterName,
};
};
export default useTypeFilter;

View File

@ -0,0 +1,35 @@
import { useEffect, useState } from 'react';
import LinesApiService from '../service/LinesApiService';
const useLines = (typeFilter, name) => {
const [linesRefresh, setLinesRefresh] = useState(false);
const [lines, setLines] = useState([]);
const handleLinesChange = () => setLinesRefresh(!linesRefresh);
const getLines = async () => {
let expand = '?_expand=genre&_expand=type';
if (typeFilter && name === "type" ) {
expand = `${expand}&typeId=${typeFilter}`;
}
if (typeFilter && name === "genre" ) {
expand = `${expand}&genreId=${typeFilter}`;
}
if (typeFilter && name === "nameGame" ) {
expand = `${expand}&nameGame=${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,83 @@
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 nameGame = formData.nameGame;
const price = parseFloat(formData.price).toFixed(2);
const description = formData.description;
const genreId = parseInt(formData.genreId,10);
const image = formData.image.startsWith('data:image') ? formData.image : '';
return {
typeId: typeId.toString(),
nameGame: nameGame.toString(),
price: price.toString(),
description: description.toString(),
genreId: genreId.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,36 @@
import { useEffect, useState } from 'react';
import LinesApiService from '../service/LinesApiService';
const useLinesItem = (id) => {
const emptyItem = {
id: '',
typeId: '',
nameGame:'',
price: '0',
description: '',
genreId: '',
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,29 @@
import { useSearchParams } from 'react-router-dom';
import useNames from '../../types/hooks/NamesHook';
const useTypeFilter = () => {
const filterName = 'nameGame';
const [searchParams, setSearchParams] = useSearchParams();
const { names } = useNames();
const handleFilterChange = (event) => {
const name = event.target.value;
if (name) {
searchParams.set(filterName, event.target.value);
} else {
searchParams.delete(filterName);
}
setSearchParams(searchParams);
};
return {
names,
currentFilter: searchParams.get(filterName) || '',
handleFilterChange,
filterName,
};
};
export default useTypeFilter;

View File

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

View File

@ -0,0 +1,16 @@
import PropTypes from 'prop-types';
//import { Table } from 'react-bootstrap';
const LinesTable = ({ children }) => {
return (
<div className='row price'>
{children}
</div>
);
};
LinesTable.propTypes = {
children: PropTypes.node,
};
export default LinesTable;

View File

@ -0,0 +1,58 @@
import { useNavigate } from 'react-router-dom';
//import Select from '../../input/Select.jsx';
//import LinesItemForm from '../form/LinesItemForm.jsx';
import ModalConfirm from '../../modal/ModalConfirm.jsx';
import useLinesDeleteModal from '../hooks/LinesDeleteModalHook';
import useNameFilter from '../hooks/NameFilterHook.js';
import useLines from '../hooks/LinesHook';
import LinesTable from './CategoryLInesTable.jsx';
import CategoryTableRow from './CategoryTable.jsx';
import useCart from '../../cart/CartHook';
//import { Form } from 'react-bootstrap';
//import Input from '../../input/Input.jsx';
const Lines = () => {
const { currentFilter, handleFilterChange, filterName } = useNameFilter();
const { lines, handleLinesChange } = useLines(currentFilter, filterName);
const {
isDeleteModalShow,
showDeleteModal,
handleDeleteConfirm,
handleDeleteCancel,
} = useLinesDeleteModal(handleLinesChange);
const navigate = useNavigate();
const showEditPage = (id) => {
navigate(`/addgame/${id}`);
};
const { addToCart } = useCart();
return (
<>
<input className="form-control mb-3 price" placeholder="Поиск" onChange={handleFilterChange}/>
<LinesTable>
{
lines.map((line) =>
<CategoryTableRow key={line.id}
line={line}
onAddCart={() => addToCart(line)}
onDelete={() => showDeleteModal(line.id)}
onEditInPage={() => showEditPage(line.id)}
/>)
}
</LinesTable>
<ModalConfirm show={isDeleteModalShow}
onConfirm={handleDeleteConfirm} onClose={handleDeleteCancel}
title='Удаление' message='Удалить элемент?' />
</>
);
};
export default Lines;

View File

@ -0,0 +1,35 @@
import PropTypes from 'prop-types';
import {Cart } from 'react-bootstrap-icons';
const CategoryTableRow = ({
line, onAddCart,
}) => {
const handleAnchorClick = (event, action) => {
event.preventDefault();
action();
};
return (
<>
<div className='col-2 '>
<div className='p-2'><img className='w-100' src={line.image} /></div>
<div className='px-2 py-1'>{line.nameGame}</div>
<div className='px-2 py-1'>{"Цена: "+line.price}</div>
<div className='px-2 py-1'>{"Жанр: "+line.genre.name}</div>
<div className='px-2 py-2'><a href="#" onClick={(event) => handleAnchorClick(event, onAddCart)}><Cart /></a></div>
</div>
</>
);
};
CategoryTableRow.propTypes = {
index: PropTypes.number,
line: PropTypes.object,
onDelete: PropTypes.func,
onAddCart: PropTypes.func,
onEdit: PropTypes.func,
onEditInPage: PropTypes.func,
};
export default CategoryTableRow;

View File

@ -0,0 +1,56 @@
import { useNavigate } from 'react-router-dom';
import Select from '../../input/Select.jsx';
//import LinesItemForm from '../form/LinesItemForm.jsx';
import ModalConfirm from '../../modal/ModalConfirm.jsx';
import useLinesDeleteModal from '../hooks/LinesDeleteModalHook';
import useTypeFilter from '../hooks/LinesFilterHook';
import useLines from '../hooks/LinesHook';
import LinesTable from './LinesTable.jsx';
import LinesTableRow from './LinesTableRow.jsx';
import useCart from '../../cart/CartHook';
const Lines = () => {
const { types, currentFilter, handleFilterChange, filterName } = useTypeFilter();
const { lines, handleLinesChange } = useLines(currentFilter, filterName);
const {
isDeleteModalShow,
showDeleteModal,
handleDeleteConfirm,
handleDeleteCancel,
} = useLinesDeleteModal(handleLinesChange);
const navigate = useNavigate();
const showEditPage = (id) => {
navigate(`/addgame/${id}`);
};
const { addToCart } = useCart();
return (
<>
<Select className='mt-2' values={types} label='Фильтр по товарам'
value={currentFilter} onChange={handleFilterChange} />
<LinesTable>
{
lines.map((line) =>
<LinesTableRow key={line.id}
line={line}
onAddCart={() => addToCart(line)}
onDelete={() => showDeleteModal(line.id)}
onEditInPage={() => showEditPage(line.id)}
/>)
}
</LinesTable>
<ModalConfirm show={isDeleteModalShow}
onConfirm={handleDeleteConfirm} onClose={handleDeleteCancel}
title='Удаление' message='Удалить элемент?' />
</>
);
};
export default Lines;

View File

@ -0,0 +1,58 @@
import { useNavigate } from 'react-router-dom';
import Select from '../../input/Select.jsx';
//import LinesItemForm from '../form/LinesItemForm.jsx';
import ModalConfirm from '../../modal/ModalConfirm.jsx';
import useLinesDeleteModal from '../hooks/LinesDeleteModalHook';
import useGenreFilter from '../hooks/LinesFilterGenresHook';
import useLines from '../hooks/LinesHook';
import LinesTable from './LinesTable.jsx';
import LinesTableRow from './LinesTableRow.jsx';
import useCart from '../../cart/CartHook';
import useFavor from '../../favourites/FavorHook';
const Lines = () => {
const { genres, currentFilter, handleFilterChange, filterName } = useGenreFilter();
const { lines, handleLinesChange } = useLines(currentFilter, filterName);
const {
isDeleteModalShow,
showDeleteModal,
handleDeleteConfirm,
handleDeleteCancel,
} = useLinesDeleteModal(handleLinesChange);
const navigate = useNavigate();
const showEditPage = (id) => {
navigate(`/addgame/${id}`);
};
const { addToCart } = useCart();
const { addToFavor } = useFavor();
return (
<>
<Select className='mt-2 w-25' values={genres} label='Жанры'
value={currentFilter} onChange={handleFilterChange} />
<LinesTable>
{
lines.map((line) =>
<LinesTableRow key={line.id}
line={line}
onAddCart={() => addToCart(line)}
onAddFavor={() => addToFavor(line)}
onDelete={() => showDeleteModal(line.id)}
onEditInPage={() => showEditPage(line.id)}
/>)
}
</LinesTable>
<ModalConfirm show={isDeleteModalShow}
onConfirm={handleDeleteConfirm} onClose={handleDeleteCancel}
title='Удаление' message='Удалить элемент?' />
</>
);
};
export default Lines;

View File

@ -0,0 +1,20 @@
import PropTypes from 'prop-types';
//import { Table } from 'react-bootstrap';
const LinesTable = ({ children }) => {
return (
<div className='table-responsive'>
<table className='table'>
<tbody>
{children}
</tbody >
</table >
</div>
);
};
LinesTable.propTypes = {
children: PropTypes.node,
};
export default LinesTable;

View File

@ -0,0 +1,37 @@
import PropTypes from 'prop-types';
import { Star, Cart, PencilSquare, Trash3 } from 'react-bootstrap-icons';
const LinesTableRow = ({
line, onAddCart, onAddFavor, onDelete, onEditInPage,
}) => {
const handleAnchorClick = (event, action) => {
event.preventDefault();
action();
};
return (
<tr>
<td className='w-25'><img className='w-100' src={line.image} /></td>
<td>{line.type.name}</td>
<td>{line.description}</td>
<td>{"Цена: "+line.price}</td>
<td>{"Жанр: "+line.genre.name}</td>
<td><a href="#" onClick={(event) => handleAnchorClick(event, onAddCart)}><Cart /></a></td>
<td><a href="#" onClick={(event) => handleAnchorClick(event, onAddFavor)}><Star /></a></td>
<td><a href="#" onClick={(event) => handleAnchorClick(event, onEditInPage)}><PencilSquare /></a></td>
<td><a href="#" onClick={(event) => handleAnchorClick(event, onDelete)}><Trash3 /></a></td>
</tr>
);
};
LinesTableRow.propTypes = {
index: PropTypes.number,
line: PropTypes.object,
onDelete: PropTypes.func,
onAddCart: PropTypes.func,
onAddFavor: PropTypes.func,
onEdit: PropTypes.func,
onEditInPage: PropTypes.func,
};
export default LinesTableRow;

View File

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

View File

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

View File

@ -0,0 +1,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,12 @@
.my-navbar {
background-color: #08D9D6 !important;
}
.my-navbar .link a:hover {
text-decoration: underline !important;
}
.my-navbar .logo {
width: 26px;
height: 26px;
}

View File

@ -0,0 +1,49 @@
import PropTypes from 'prop-types';
import { Container, Nav, Navbar } from 'react-bootstrap';
import { Cart2 } from 'react-bootstrap-icons';
import { Controller } from 'react-bootstrap-icons';
import { Link, useLocation } from 'react-router-dom';
import './Navigation.css';
import useCart from '../cart/CartHook';
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='dark' data-bs-theme='dark' className='my-navbar'>
<Container fluid>
<Navbar.Brand as={Link} to={indexPageLink?.path ?? '/'}>
<Controller className='bi-controller align-top me-1 logo' />
GAMEPAD.RU
</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='/page4'>
<Cart2 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,21 @@
import { useEffect, useState } from 'react';
import GenresApiService from '../service/GenresApiService';
const useGenres = () => {
const [genres, setGenres] = useState([]);
const getGenres = async () => {
const data = await GenresApiService.getAll();
setGenres(data ?? []);
};
useEffect(() => {
getGenres();
}, []);
return {
genres,
};
};
export default useGenres;

View File

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

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 GenresApiService = new ApiService('genres');
export default GenresApiService;

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;

157
Lab5/site/src/index.css Normal file
View File

@ -0,0 +1,157 @@
header nav{
background-color: #08D9D6;
color: black;
}
.category{
width:55%;
}
@media (min-width:768px){
.im{
display: none;
}
}
@media (max-width:768px){
.imm{
display: none;
}
}
.butt{
max-height: 63px;
}
@media (max-width:900px){
.text{
padding-left: 100px;
}
.div{
display:none;
}
.ots {
align-items: center;
align-content: center;
justify-content: center;
}
.img{
width:100%;
}
}
@media (max-width:600px){
.categ{
display:none;
}
.imrow{
width:250px;
}
.destext{
width:200px;
height: 70px;
overflow: auto;
}
.cart{
display: none;
}
}
@media (max-width:1500px){
.category{
width:65%;
}
}
@media (max-width:1250px){
.search{
max-width: 100%;
}
.category{
width: 75%;
}
}
@media (max-width:830px){
.category{
width:100%;
}
}
@media (max-width:1040px){
.images{
display: none;
}
.cata{
gap: 4px;
grid-template-columns: 3fr;
}
.imrow{
width:100%;
}
}
.textmain
header nav a:hover{
text-decoration: underline;
}
html, body {
background-color: #252A34;
height: 100%;
color:white;
}
footer {
background-color: #FF2E63;
color:black;
height:32px;
}
.push {
height: 32px;
}
.main {
background-color: #353b47;
color:white;
max-width:1000px;
margin: 0 auto -32px;
}
.cost-input {
width:80px;
border-radius: 10px;
}
.search-input{
border-radius: 15px;
width: 100%;
}
.select {
border-radius: 10px;
color: white;
border:1px;
}
.disc{
border: 1px solid black;
line-height: 2.5;
max-width:360px;
border-radius: 10px;
}
.textbx {
border-radius: 10px;
border: 1px;
}
input[type="email"]::placeholder {color: grey;}
.check {
border:1px;
}
.sign-form{
padding-top:25%;
width: 200px;
}
.but{
padding-bottom: 200px;
}

72
Lab5/site/src/main.jsx Normal file
View File

@ -0,0 +1,72 @@
import 'bootstrap/dist/css/bootstrap.min.css';
import React from 'react';
import ReactDOM from 'react-dom/client';
import { RouterProvider, createBrowserRouter } from 'react-router-dom';
import App from './App.jsx';
import './index.css';
import ErrorPage from './pages/ErrorPage.jsx';
import Page1 from './pages/Page1.jsx';
import Page2 from './pages/Page2.jsx';
import Page3 from './pages/Page3.jsx';
import Page4 from './pages/Page4.jsx';
import Page5 from './pages/Page5.jsx';
import Reg from './pages/Reg.jsx';
import Addgame from './pages/AddGame.jsx';
import PersonalAccount from './pages/PersonalAccount.jsx';
const routes = [
{
index: true,
path: '/',
element: <Page1 />,
title: 'Главная страница',
},
{
path: '/page2',
element: <Page2 />,
title: 'Каталог',
},
{
path: '/page3',
element: <Page3 />,
title: 'Новинки',
},
{
path: '/page4',
element: <Page4 />,
title: 'Корзина',
},
{
path: '/page5',
element: <Page5 />,
title: 'Личный кабинет',
},
{
path: '/reg',
element: <Reg />,
},
{
path: '/addgame/:id?',
element: <Addgame />,
},
{
path: '/personalaccount',
element: <PersonalAccount />,
},
];
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,14 @@
import './index.css';
import { useParams } from 'react-router-dom';
import LinesForm from '../components/lines/form/LinesForm.jsx';
const AddGame = () => {
const { id } = useParams();
return(
<LinesForm id={id} />
);
};
export default AddGame;

View File

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

View File

@ -0,0 +1,39 @@
import poeImage from '../assets/poe.jpg';
import './index.css';
import LinesGen from '../components/lines/table/LinesGen.jsx';
import RoR from '../assets/risk-of-rain-returns.jpg';
import Sekiro from '../assets/sekiro.jpg';
//import Elden from '../../assets/eldenring.jpg';
//import Input from '../components/input/Input.jsx';
const Page1 = () => {
return (
<>
<div className="main flex-column mx-auto">
<div className="row mx-auto">
<div className="img pt-4 ps-5 mt-4 col-8">
<img className="img" src={poeImage} width="100%" />
</div>
<div className="pe-3 flex-column div col-4">
<div className="pt-4 ps-2">Популярные новинки:</div>
<div><img className="p-2" src={RoR} width="100%" /></div>
<div><img className="p-2" src={Sekiro} width="100%" /></div>
</div>
</div>
<div className="row mx-auto">
<div className="pb-4 col">
<LinesGen />
</div>
</div>
</div>
</>
);
};
export default Page1;

View File

@ -0,0 +1,25 @@
import './index.css';
import CategoryLines from '../components/lines/table/CategoryLines.jsx';
const Page2 = () =>{
return(
<>
<div className="row py-5 mx-auto px-5">
<CategoryLines />
</div>
</>
);
};
export default Page2;
/*
<div className="row pt-3">
<div className="col-lg-6 ps-3">Платформа:</div>
<div className="col-2 ps-0"><i className="bi bi-windows"></i></div>
<div className="col-2 ps-0"><i className="bi bi-xbox"></i></div>
<div className="col-2 ps-0"><i className="bi bi-playstation"></i></div>
</div>
*/

View File

@ -0,0 +1,38 @@
import './index.css';
import Banner from '../components/banner/Banner.jsx';
import { Link } from 'react-router-dom';
import Lines from '../components/lines/table/Lines.jsx';
const Page3 = () => {
return (
<>
<div className=" main mx-auto">
<div className="flex-column">
<div className="btn-group p-3" role="group">
<Link className="btn btn-success" to="/AddGame">Добавить товар</Link>
</div>
<div className="p-2 h4">Новинки</div>
<div className="px-4">
<Banner />
</div>
<div className="d-flex flex-column p-3">
<Lines />
</div>
</div>
</div>
</>
);
};
export default Page3;
/*
<div className="row mx-auto gx-4">
<div className="px-4" id="banner">
<img className="banner-hide" src="images/risk-of-rain-returns.jpg" width="100%" alt="banner1" />
<img className="banner-hide" src="images/sekiro.jpg" width="100%" alt="banner1" />
<img className="banner-hide" src="images/eldenring.jpg" width="100%" alt="banner1" />
</div>
</div>
*/

View File

@ -0,0 +1,65 @@
import './index.css';
import {useState} from 'react';
import { Form } from 'react-bootstrap';
import Cart from '../components/cart/Cart.jsx';
import { Button } from 'react-bootstrap';
import useCart from '../components/cart/CartHook';
const Page4 = () => {
const [validated, setValidated] = useState(false);
const handleSubmit = (event) => {
const form = event.currentTarget;
if(form.checkValidity() === false){
event.preventDefault();
event.stopPropagation();
}
setValidated(true);
};
const {
clearCart,
} = useCart();
return(
<>
<div className="d-flex main justify-content-center">
<Form className="pe-4 pb-4" validated={validated} onSubmit={handleSubmit}>
<div className="h4 p-4">Оформление заказа</div>
<Cart />
<hr className="ms-4" />
<div className="h5 ps-4 pt-3">Способ оплаты</div>
<div className="ps-4">
<select className="form-select select">
<option value="1">Банковская карта</option>
<option value="2">QIWI Кошелёк</option>
</select>
</div>
<hr className="ms-4" />
<div className="h5 ps-4">Скидка постоянным покупателям</div>
<div className="ps-4"><p className="disc px-4 py-2" >2000р-------------------------------------7%<br />
1500р-------------------------------------6%<br />
1100р-------------------------------------5%<br />
950р--------------------------------------4%<br />
800р--------------------------------------3%<br />
500р--------------------------------------2%<br />
300р--------------------------------------1%</p>
</div>
<hr className="ms-4" />
<div className="h5 ps-4">E-mail</div>
<div className="ps-4 py-2"><input type="email" className="form-control" placeholder="name@example.com" required /></div>
<div className="ps-4 py-2"><input type="email" className="form-control" placeholder="repeat name@example.com" required /></div>
<div className="ps-4 py-2 ">
<Form.Check type="checkbox" id="access" label="Я ознакомлен с описанием товара и региональными ограничениями, и даю согласие на обработку данных." required />
</div>
<hr className="ms-4" />
<div className="ps-4 pt-2"><Button className=" w-100 " type="submit" onClick={() => clearCart()}>Далее</Button></div>
</Form>
</div>
</>
);
};
export default Page4;

View File

@ -0,0 +1,47 @@
import './index.css';
import {Link} from 'react-router-dom';
import {useState} from 'react';
import { Form } from 'react-bootstrap';
import useLogin from '../components/PersAcc/LoginHook';
const Page5 = () => {
const [validated, setValidated] = useState(false);
const handleSubmit = (event) => {
const form = event.currentTarget;
if(form.checkValidity() === false){
event.preventDefault();
event.stopPropagation();
}
setValidated(true);
};
const { LoginChange } = useLogin();
return(
<>
<div className="main d-flex mt-0 row justify-content-center">
<Form className="col-md-6 sign-form " action="/personalaccount" validated={validated} onSubmit={handleSubmit}>
<div className="mb-0 h4">Войти</div>
<div className="pb-2"><Link to="/reg"><small>Зарегистрироваться</small></Link></div>
<div className="pb-3">
<Form.Label className="form-label" htmlFor="login" >Логин</Form.Label>
<input id="login" name="login" className="form-control border-0" onChange={LoginChange} required />
</div>
<div className="pb-3">
<Form.Label className="form-label" htmlFor="password">Пароль</Form.Label>
<Form.Control id="password" name="password" className="form-control border-0" type="password" required />
</div>
<div className="but text-center">
<button className="btn btn-primary w-50" type="submit">Далее</button>
</div>
</Form>
</div>
</>
);
};
export default Page5;

View File

@ -0,0 +1,25 @@
import './index.css';
import Favor from '../components/favourites/Favor.jsx';
import useLogin from '../components/PersAcc/LoginHook';
const PersonalAccount = () => {
const { Login } = useLogin();
const name = Login();
return(
<>
<div className="flex-column main justify-content-center pb-4">
<div className="p-3 h4">{`Здравствуй ${name}!`}</div>
<div className="p-3"><img src="src/assets/avatar.png" width="130px" /></div>
<div className="p-3 gx-3 h4">Список желаемого</div>
<div className="row mx-auto">
<Favor />
</div>
</div>
<div className="push"></div>
</>)
}
export default PersonalAccount;

View File

@ -0,0 +1,58 @@
import './index.css';
import {useState} from 'react';
import {Link} from 'react-router-dom';
import { Form } from 'react-bootstrap';
const Reg = () => {
const [validated, setValidated] = useState(false);
const handleSubmit = (event) => {
const form = event.currentTarget;
if(form.checkValidity() === false){
event.preventDefault();
event.stopPropagation();
}
setValidated(true);
};
const saveLogin = (name) =>{
localStorage.setItem('Name', name.target.value);
}
return(
<>
<div className="main d-flex mt-0 row justify-content-center">
<Form className="col-md-6 sign-form" action="/personalaccount" validated={validated} onSubmit={handleSubmit}>
<div className="mb-0 h4">Зарегистрироваться</div>
<div className="pb-2"><Link to="/Page5"><small>Уже зарегестрированны?</small></Link></div>
<div className="pb-3">
<Form.Label className="form-label" htmlFor="login" >Логин</Form.Label>
<input id="login" name="login" className="form-control border-0" onChange={saveLogin} required />
</div>
<div className="pb-3">
<Form.Label className="form-label" htmlFor="email">Почта</Form.Label>
<Form.Control id="email" name="" className="form-control border-0" placeholder="name@example.com" type="email" required />
</div>
<div className="pb-3">
<Form.Label className="form-label" htmlFor="password">Пароль</Form.Label>
<Form.Control id="password" name="" className="form-control border-0" type="password" required />
</div>
<div className="pb-3">
<Form.Label className="form-label" htmlFor="password1">Повторите пароль</Form.Label>
<Form.Control id="password1" name="" className="form-control border-0" type="password" required />
</div>
<div className="but text-center">
<button className="btn btn-primary w-50" type="submit">Далее</button>
</div>
</Form>
</div>
</>
);
};
export default Reg;

View File

@ -0,0 +1,166 @@
header nav{
background-color: #08D9D6;
color: black;
}
.category{
width:55%;
}
@media (min-width:768px){
.im{
display: none;
}
}
@media (max-width:900px){
.text{
padding-left: 100px;
}
.div{
display:none;
}
.ots {
align-items: center;
align-content: center;
justify-content: center;
}
.img{
width:100%;
}
}
@media (max-width:600px){
.categ{
display:none;
}
.imrow{
width:250px;
}
.destext{
width:200px;
height: 70px;
overflow: auto;
}
.cart{
display: none;
}
}
@media (max-width:1500px){
.category{
width:65%;
}
}
@media (max-width:1250px){
.search{
max-width: 100%;
}
.category{
width: 75%;
}
}
@media (max-width:830px){
.category{
width:100%;
}
}
@media (max-width:1040px){
.images{
display: none;
}
.cata{
gap: 4px;
grid-template-columns: 3fr;
}
.imrow{
width:100%;
}
}
.textmain
header nav a:hover{
text-decoration: underline;
}
html, body {
background-color: #252A34;
height: 100%;
color:white;
}
body {
min-height: 100vh;
flex-direction: column;
}
.price {
background-color: #212529;
}
.footer {
background-color: #FF2E63;
color:black;
height:32px;
}
main {
height: 100%;
}
.push {
height: 32px;
}
center {
width: 900px;
margin: 0 auto ;
background-color: #353b47;
}
.main {
background-color: #353b47;
color:white;
max-width:1000px;
margin: 0 auto 32px;
}
.cost-input {
width:80px;
border-radius: 10px;
}
.search-input{
border-radius: 15px;
width: 100%;
}
.select {
border-radius: 10px;
color: white;
border:1px;
}
.disc{
border: 1px solid black;
line-height: 2.5;
max-width:360px;
border-radius: 10px;
}
.textbx {
border-radius: 10px;
border: 1px;
}
input[type="email"]::placeholder {color: grey;}
.check {
border:1px;
}
.sign-form{
padding-top:25%;
width: 200px;
}
.but{
padding-bottom: 200px;
}

7
Lab5/site/vite.config.js Normal file
View File

@ -0,0 +1,7 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
})