Added lints and manifest file

This commit is contained in:
Александр Кирюхин 2024-01-21 00:50:52 +03:00
parent 05cd57eb2b
commit 61c7b04d34
20 changed files with 3622 additions and 547 deletions

33
frontend/.eslintrc.cjs Normal file
View file

@ -0,0 +1,33 @@
module.exports = {
env: {
browser: true,
es2021: true
},
extends: [
'standard',
'plugin:react/recommended',
'plugin:react/jsx-runtime'
],
overrides: [
{
env: {
node: true
},
files: [
'.eslintrc.{js,cjs}'
],
parserOptions: {
sourceType: 'script'
}
}
],
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module'
},
plugins: [
'react'
],
rules: {
}
}

View file

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

View file

@ -1,12 +1,14 @@
<!doctype html>
<html lang="en">
<html lang="ru">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>NQuest</title>
</head>
<body>
<div id="root"></div>
<div id="root">
Загрузка...
</div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>

File diff suppressed because it is too large Load diff

View file

@ -6,7 +6,7 @@
"scripts": {
"dev": "vite",
"build": "vite build",
"lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0",
"lint": "eslint src --fix --ext js,jsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview"
},
"dependencies": {
@ -24,10 +24,16 @@
"@types/react": "^18.2.15",
"@types/react-dom": "^18.2.7",
"@vitejs/plugin-react": "^4.0.3",
"eslint": "^8.45.0",
"eslint-plugin-react": "^7.32.2",
"eslint": "^8.56.0",
"eslint-config-standard": "^17.1.0",
"eslint-plugin-import": "^2.29.1",
"eslint-plugin-n": "^16.6.2",
"eslint-plugin-promise": "^6.1.1",
"eslint-plugin-react": "^7.33.2",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.3",
"vite": "^4.4.5"
"vite": "^4.4.5",
"vite-plugin-pwa": "^0.17.4",
"workbox-window": "^7.0.0"
}
}

View file

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

Before

Width:  |  Height:  |  Size: 1.5 KiB

View file

@ -1,4 +1,5 @@
import { Navigate, Route, RouterProvider, createBrowserRouter, createRoutesFromElements, useLocation, useNavigate, useRouteLoaderData } from 'react-router-dom'
import { Navigate, Route, RouterProvider, createBrowserRouter, createRoutesFromElements, useLocation, useRouteLoaderData } from 'react-router-dom'
import PropTypes from 'prop-types'
import Layout from './components/Layout'
@ -17,7 +18,7 @@ const router = createBrowserRouter(
path="/"
id="root"
element={<Layout />}
loader={async () => ajax("/api/user").catch(x => {console.log(x); return null})}
loader={async () => ajax('/api/user').catch(x => { console.log(x); return null })}
>
<Route
index
@ -27,7 +28,7 @@ const router = createBrowserRouter(
id="quests"
path="/quests"
element={<Auth><Quests /></Auth>}
loader={() => ajax("/api/games").catch(x => {console.log(x); return null})}
loader={() => ajax('/api/games').catch(x => { console.log(x); return null })}
/>
<Route path="login" element={<Login />} />
<Route path="register" element={<Register />} />
@ -52,22 +53,26 @@ const router = createBrowserRouter(
<Route path="*" element={<NoMatch />} />
</Route>
)
);
)
function App () {
return (
<RouterProvider router={router} />
)
}
function Auth({ children }) {
const baseUser = useRouteLoaderData("root")
const { user } = UserProvider.useContainer();
const location = useLocation();
function Auth (props) {
const baseUser = useRouteLoaderData('root')
const { user } = UserProvider.useContainer()
const location = useLocation()
if (!user && !baseUser) {
return <Navigate to="/login" state={{ from: location }} replace />;
return <Navigate to="/login" state={{ from: location }} replace />
}
return children;
return props.children
}
Auth.propTypes = {
children: PropTypes.any
}
export default App

View file

@ -1,54 +1,54 @@
import { Link, Outlet, useLoaderData, useLocation, useNavigate, useNavigation } from "react-router-dom";
import { UserProvider } from "../store/user";
import { useEffect, useRef, useState } from "react";
import { ajax } from "../utils/fetch";
import { useRole } from "../utils/roles";
import { Layout, Menu, Progress, Space } from "antd";
import { FireTwoTone, StarTwoTone } from '@ant-design/icons';
import { Content, Header } from "antd/es/layout/layout";
import { Link, Outlet, useLoaderData, useLocation, useNavigate } from 'react-router-dom'
import { UserProvider } from '../store/user'
import { useEffect } from 'react'
import { ajax } from '../utils/fetch'
import { Layout, Menu, Progress, Space } from 'antd'
import { FireTwoTone, StarTwoTone } from '@ant-design/icons'
import { Content, Header } from 'antd/es/layout/layout'
export default () => {
const params = useLoaderData();
const navigate = useNavigate();
const location = useLocation();
const AppLayout = () => {
const params = useLoaderData()
const navigate = useNavigate()
const location = useLocation()
useEffect(() => {
setUser(params)
}, [params])
const { user, setUser } = UserProvider.useContainer();
const { user, setUser } = UserProvider.useContainer()
const logout = () => {
ajax("/api/user/logout", {
method: "POST",
ajax('/api/user/logout', {
method: 'POST'
})
.then(() => { setUser(null); navigate("/login") })
.catch(() => { setUser(null); navigate("/login") })
.then(() => { setUser(null); navigate('/login') })
.catch(() => { setUser(null); navigate('/login') })
}
let items = [
{ key: "login", label: "Вход", link: "/login" },
{ key: "register", label: "Регистрация", link: "/register" }
{ key: 'login', label: 'Вход', link: '/login' },
{ key: 'register', label: 'Регистрация', link: '/register' }
]
if (user != null) {
items = [
{
key: "quests",
label: "Квесты",
link: "/quests"
key: 'quests',
label: 'Квесты',
link: '/quests'
},
{
key: "user",
key: 'user',
label: user.username,
children: [
{
type: "group",
key: "exp",
label: (<Space>
type: 'group',
key: 'exp',
label: (
<Space>
<Space title={`${user.level} уровень`}><StarTwoTone />{user.level} уровень</Space>
<Space title={`${user.experience} опыта`}><FireTwoTone />{user.experience} опыт</Space>
</Space>)
},
{
type: "group",
key: "progress",
type: 'group',
key: 'progress',
label: <Progress
value={user.experience}
percent={((user.experience - user.expToCurrentLevel) / (user.expToNextLevel - user.expToCurrentLevel) * 100)}
@ -57,29 +57,29 @@ export default () => {
/>
},
{
type: "group",
key: "nextLevel",
type: 'group',
key: 'nextLevel',
label: `Следующий уровень - ${user.expToNextLevel} очков опыта`
},
{
key: "logout",
label: "Выход",
handler: logout,
key: 'logout',
label: 'Выход',
handler: logout
}
]
}
],
},
]
}
const menuHandler = (x) => {
const item = getItemByPath(items, x.keyPath);
item.link ? navigate(item.link) : null;
item.handler ? item.handler() : null;
const item = getItemByPath(items, x.keyPath)
if (item.link) { navigate(item.link) }
if (item.handler) { item.handler() }
}
const getItemByPath = (items, path) => {
const x = path.pop()
const item = items.find(y => y.key === x);
if (path.length == 0) {
const item = items.find(y => y.key === x)
if (path.length === 0) {
return item
}
return getItemByPath(item.children, path)
@ -91,12 +91,14 @@ export default () => {
<Menu
mode="horizontal"
items={items}
selectedKeys={location.pathname.replace("/", "")}
selectedKeys={location.pathname.replace('/', '')}
onClick={menuHandler}
/>
</Header>
<Content style={{ padding: '0 24px' }}>
<Outlet />
</Content>
</Layout>);
</Layout>)
}
export default AppLayout

View file

@ -1,13 +1,13 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import { Compose } from '@neonxp/compose';
import { App as AntdApp, ConfigProvider, theme } from 'antd';
const { darkAlgorithm } = theme;
import ruRU from "antd/locale/ru_RU";
import "./assets/styles.css"
import { Compose } from '@neonxp/compose'
import { App as AntdApp, ConfigProvider, theme } from 'antd'
import ruRU from 'antd/locale/ru_RU'
import './assets/styles.css'
import App from './App.jsx'
import { store } from './store/provider.js';
import { store } from './store/provider.js'
const { darkAlgorithm } = theme
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
@ -16,19 +16,19 @@ ReactDOM.createRoot(document.getElementById('root')).render(
locale={ruRU}
theme={{
token: {
"colorPrimary": "#fb923c",
"colorInfo": "#fb923c",
"colorSuccess": "#15803d",
"colorBgBase": "#171e26",
"borderRadius": 3,
"wireframe": false
colorPrimary: '#fb923c',
colorInfo: '#fb923c',
colorSuccess: '#15803d',
colorBgBase: '#171e26',
borderRadius: 3,
wireframe: false
},
algorithm: darkAlgorithm,
algorithm: darkAlgorithm
}}>
<AntdApp>
<App />
</AntdApp>
</ConfigProvider>
</Compose>
</React.StrictMode>,
);
</React.StrictMode>
)

View file

@ -1,67 +1,64 @@
import { Link, useLoaderData, useParams } from "react-router-dom";
import Markdown from "react-markdown";
import { useEffect, useState } from "react";
import { ajax } from "../utils/fetch";
import Title from "antd/es/typography/Title";
import { Alert, App, Badge, Button, Card, Col, Form, Input, List, Row } from "antd";
import { useEffect, useState } from 'react'
import { Link, useLoaderData, useParams } from 'react-router-dom'
import Markdown from 'react-markdown'
import { ajax } from '../utils/fetch'
import Title from 'antd/es/typography/Title'
import { Alert, App, Button, Card, Col, Form, Input, List, Row } from 'antd'
export default () => {
const params = useParams();
const loadedTask = useLoaderData();
const [task, setTask] = useState(loadedTask);
const { message, notification, modal } = App.useApp();
const Engine = () => {
const params = useParams()
const loadedTask = useLoaderData()
const [task, setTask] = useState(loadedTask)
const { message } = App.useApp()
useEffect(() => {
switch (task.message) {
case "invalid_code":
message.error("Неверный код")
case 'invalid_code':
message.error('Неверный код')
break
case "old_code":
message.error("Этот код уже вводился")
case 'old_code':
message.error('Этот код уже вводился')
break
case "next_level":
message.success("Переход на новый уровень")
case 'next_level':
message.success('Переход на новый уровень')
break
case "ok_code":
message.success("Код принят, ищите оставшиеся")
case 'ok_code':
message.success('Код принят, ищите оставшиеся')
break
}
}, [task.message])
const [form] = Form.useForm();
const [form] = Form.useForm()
const onFinish = ({ code }) => {
ajax(`/api/engine/${params.gameId}/code`, {
method: "POST",
method: 'POST',
headers: {
'Accept': 'application/json',
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({ code })
}).
then((x) => {
})
.then((x) => {
if (x != null) {
setTask(x);
form.setFieldsValue({ code: '' });
setTask(x)
form.setFieldsValue({ code: '' })
}
}).catch(e => {
console.warn(e);
});
};
console.warn(e)
})
}
if (task && task.message == "game_complete") {
if (task && task.message === 'game_complete') {
return (<div style={{ padding: 8 }}>
<Alert type="success" message="Вы прошли все уровни!" />
<Link to={"/"}>К списку игр</Link>
</div>);
<Link to={'/'}>К списку игр</Link>
</div>)
}
if (!task) {
return (<div style={{ padding: 8 }}>
<Alert type="warning" message="Для вас не предусмотренно уровней" />
<Link to={"/"}>К списку игр</Link>
</div>);
<Link to={'/'}>К списку игр</Link>
</div>)
}
return (<>
@ -77,7 +74,7 @@ export default () => {
renderItem={(c, idx) => (
<List.Item
key={idx}
extra={!!c.code ? (<Alert type="success" message={`Принят ${c.code}`} />) : (<Alert type="info " message="Не введён" />)}
extra={c.code ? (<Alert type="success" message={`Принят ${c.code}`} />) : (<Alert type="info " message="Не введён" />)}
>
{c.description}
</List.Item>)}
@ -105,11 +102,13 @@ export default () => {
</Form.Item>
</Form>
</Card>
{task.message == "invalid_code" ? (<Alert type="error" message="Неверный код" />) : null}
{task.message == "old_code" ? (<Alert type="warning" message="Этот код уже вводился" />) : null}
{task.message == "next_level" ? (<Alert type="success" message="Переход на новый уровень" />) : null}
{task.message == "ok_code" ? (<Alert type="success" message="Код принят, ищите оставшиеся" />) : null}
{task.message === 'invalid_code' ? (<Alert type="error" message="Неверный код" />) : null}
{task.message === 'old_code' ? (<Alert type="warning" message="Этот код уже вводился" />) : null}
{task.message === 'next_level' ? (<Alert type="success" message="Переход на новый уровень" />) : null}
{task.message === 'ok_code' ? (<Alert type="success" message="Код принят, ищите оставшиеся" />) : null}
</Col>
</Row>
</>);
</>)
}
export default Engine

View file

@ -1,22 +1,26 @@
import { useNavigate } from "react-router-dom";
import { UserProvider } from "../store/user";
import { Typography, Button } from 'antd';
import React from "react";
import { useNavigate } from 'react-router-dom'
import { Typography, Button } from 'antd'
import { UserProvider } from '../store/user'
const { Title, Text, Paragraph } = Typography;
const { Title, Paragraph } = Typography
export default () => {
const { user } = UserProvider.useContainer();
const navigate = useNavigate();
const Index = () => {
const { user } = UserProvider.useContainer()
const navigate = useNavigate()
return (<>
<Title>NQuest</Title>
<Paragraph>Привет! Это платформа для ARG игр.</Paragraph>
<Paragraph>Если ты попал сюда случайно, то скорее всего, для тебя здесь нет ничего интересного. А если ты знаешь зачем пришёл, то добро пожаловать!</Paragraph>
<Paragraph>
Если ты попал сюда случайно, то скорее всего, для тебя здесь нет ничего интересного.
А если ты знаешь зачем пришёл, то добро пожаловать!
</Paragraph>
{!user
? (<Button.Group>
<Button type="primary" onClick={() => navigate("/login")}>Вход</Button>
<Button onClick={() => navigate("/register")}>Регистрация</Button>
<Button type="primary" onClick={() => navigate('/login')}>Вход</Button>
<Button onClick={() => navigate('/register')}>Регистрация</Button>
</Button.Group>)
: (<Button type="primary" onClick={() => navigate("/quests")}>К квестам</Button>)}
</>);
: (<Button type="primary" onClick={() => navigate('/quests')}>К квестам</Button>)}
</>)
}
export default Index

View file

@ -1,33 +1,33 @@
import { useEffect, useState } from "react";
import { UserProvider } from "../store/user";
import { useLocation, useNavigate } from "react-router-dom";
import { ajax } from "../utils/fetch";
import { Alert, App, Button, Form, Input } from "antd";
import { useEffect, useState } from 'react'
import { UserProvider } from '../store/user'
import { useLocation, useNavigate } from 'react-router-dom'
import { ajax } from '../utils/fetch'
import { Alert, Button, Form, Input } from 'antd'
export default () => {
const { user, setUser } = UserProvider.useContainer();
const Login = () => {
const { user, setUser } = UserProvider.useContainer()
const { state } = useLocation()
const [error, setError] = useState(null);
const navigate = useNavigate();
const [form] = Form.useForm();
const [error, setError] = useState(null)
const navigate = useNavigate()
const [form] = Form.useForm()
useEffect(() => {
if (user) {
navigate(state && state.from ? state.from : "/");
navigate(state && state.from ? state.from : '/')
}
}, [user])
const onFinish = (values) => {
ajax("/api/user/login", {
method: "POST",
ajax('/api/user/login', {
method: 'POST',
headers: {
'Accept': 'application/json',
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(values)
}).
then(setUser).
catch(({ message }) => setError("Проверьте e-mail и пароль"));
})
.then(setUser)
.catch(({ message }) => setError('Проверьте e-mail и пароль'))
}
return (<>
@ -37,13 +37,13 @@ export default () => {
form={form}
name="login"
labelCol={{
span: 8,
span: 8
}}
wrapperCol={{
span: 16,
span: 16
}}
style={{
maxWidth: 600,
maxWidth: 600
}}
onFinish={onFinish}>
@ -53,12 +53,12 @@ export default () => {
rules={[
{
required: true,
message: 'Обязательное поле',
message: 'Обязательное поле'
},
{
type: 'email',
message: 'E-mail некорректный',
},
message: 'E-mail некорректный'
}
]}
>
<Input
@ -72,8 +72,8 @@ export default () => {
rules={[
{
required: true,
message: 'Обязательное поле',
},
message: 'Обязательное поле'
}
]}
>
<Input.Password />
@ -81,7 +81,7 @@ export default () => {
<Form.Item
wrapperCol={{
offset: 8,
span: 16,
span: 16
}}
>
<Button type="primary" htmlType="submit">
@ -90,4 +90,6 @@ export default () => {
</Form.Item>
</Form >
</>)
};
}
export default Login

View file

@ -1,3 +1,5 @@
export default () => (<>
const NoMatch = () => (<>
<h1>404!</h1>
</>);
</>)
export default NoMatch

View file

@ -1,44 +1,40 @@
import { Link, useLoaderData, useNavigate } from "react-router-dom";
import Markdown from "react-markdown";
import remarkGfm from 'remark-gfm';
import moment from 'moment/min/moment-with-locales';
import { UserProvider } from "../store/user";
import { Avatar, List, Typography, Button, Space, Table, Card } from 'antd';
import { FireTwoTone, BuildTwoTone } from '@ant-design/icons';
import React from "react";
import { useLoaderData, useNavigate } from 'react-router-dom'
import Markdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
import moment from 'moment/min/moment-with-locales'
import { Avatar, Typography, Button, Space, Card } from 'antd'
import { UserProvider } from '../store/user'
const { Title } = Typography;
const { Title } = Typography
export default () => {
moment.locale('ru');
const games = useLoaderData();
const { user } = UserProvider.useContainer();
const navigate = useNavigate();
const Quests = () => {
moment.locale('ru')
const games = useLoaderData()
const { user } = UserProvider.useContainer()
const navigate = useNavigate()
return (<>
<Title>Квесты</Title>
{games.map(item => renderItem(user, navigate, item))}
{!games ? (<strong>Квестов пока не анонсировано</strong>) : null}
</>);
</>)
}
const renderItem = (user, navigate, item) => {
const actions = [
<Space title={`${item.points} опыта за выполнение квеста`}>Оп: {item.points}</Space>,
<Space title={`${item.taskCount} уровней в квесте`}>Ур: {item.taskCount}</Space>,
<Space key='exp' title={`${item.points} опыта за выполнение квеста`}>Оп: {item.points}</Space>,
<Space key='taskCount' title={`${item.taskCount} уровней в квесте`}>Ур: {item.taskCount}</Space>,
<>{moment(item.createdAt).fromNow()}</>,
<>Автор(ы) {item.authors.map(a => a.username)}</>,
];
<>Автор(ы) {item.authors.map(a => a.username)}</>
]
let questAction = (<span>Необходимо войти</span>)
if (!!user) {
questAction = (!!user.games.find(x => x.id === item.id)
if (user) {
questAction = (user.games.find(x => x.id === item.id)
? <span>Вы уже прошли этот квест</span>
: <Button onClick={() => navigate(`/go/${item.id}`)} type="primary">Начать квест</Button>
);
)
}
return (
@ -58,3 +54,5 @@ const renderItem = (user, navigate, item) => {
</Card>
)
}
export default Quests

View file

@ -1,42 +1,46 @@
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { UserProvider } from "../store/user";
import { ajax } from "../utils/fetch";
import { Alert, Button, Form, Input } from "antd";
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { UserProvider } from '../store/user'
import { ajax } from '../utils/fetch'
import { Alert, Button, Form, Input } from 'antd'
export default () => {
const { user, setUser } = UserProvider.useContainer();
const [error, setError] = useState(null);
const navigate = useNavigate();
const Register = () => {
const { user, setUser } = UserProvider.useContainer()
const [error, setError] = useState(null)
const navigate = useNavigate()
useEffect(() => {
user ? navigate("/") : null;
if (user) {
navigate('/')
}
}, [user])
const onFinish = (values) => {
ajax("/api/user/register", {
method: "POST",
ajax('/api/user/register', {
method: 'POST',
headers: {
'Accept': 'application/json',
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(values)
}).
then(setUser).
catch(({ message }) => setError("Ошибка регистрации"));
})
.then(setUser)
.catch(({ message }) => setError('Ошибка регистрации'))
}
return (<>
<h1>Регистрация</h1>
{error ? <Alert type="error" message={error} /> : null}
<Form
name="register"
labelCol={{
span: 8,
span: 8
}}
wrapperCol={{
span: 16,
span: 16
}}
style={{
maxWidth: 600,
maxWidth: 600
}}
onFinish={onFinish}>
@ -46,8 +50,8 @@ export default () => {
rules={[
{
required: true,
message: 'Обязательное поле',
},
message: 'Обязательное поле'
}
]}
>
<Input />
@ -58,12 +62,12 @@ export default () => {
rules={[
{
required: true,
message: 'Обязательное поле',
message: 'Обязательное поле'
},
{
type: 'email',
message: 'E-mail некорректный',
},
message: 'E-mail некорректный'
}
]}
help="Не видно другим пользователям"
>
@ -78,8 +82,8 @@ export default () => {
rules={[
{
required: true,
message: 'Обязательное поле',
},
message: 'Обязательное поле'
}
]}
>
<Input.Password />
@ -92,16 +96,16 @@ export default () => {
rules={[
{
required: true,
message: 'Обязательное поле',
message: 'Обязательное поле'
},
({ getFieldValue }) => ({
validator (_, value) {
if (!value || getFieldValue('password') === value) {
return Promise.resolve();
return Promise.resolve()
}
return Promise.reject(new Error('Пароли отличаются!'));
},
}),
return Promise.reject(new Error('Пароли отличаются!'))
}
})
]}
>
<Input.Password />
@ -109,7 +113,7 @@ export default () => {
<Form.Item
wrapperCol={{
offset: 8,
span: 16,
span: 16
}}
>
<Button type="primary" htmlType="submit">
@ -119,3 +123,5 @@ export default () => {
</Form >
</>)
}
export default Register

View file

@ -1,5 +1,5 @@
import { UserProvider } from "./user";
import { UserProvider } from './user'
export const store = [
UserProvider.Provider,
];
UserProvider.Provider
]

View file

@ -1,9 +1,9 @@
import { useState } from 'react';
import { createContainer } from 'unstated-next';
import { useState } from 'react'
import { createContainer } from 'unstated-next'
const useUser = () => {
const [user, setUser] = useState(null);
const [user, setUser] = useState(null)
return { user, setUser }
};
}
export const UserProvider = createContainer(useUser);
export const UserProvider = createContainer(useUser)

View file

@ -1,22 +1,22 @@
import { UserProvider } from "../store/user"
import { UserProvider } from '../store/user'
const roleHierarchy = {
"user": {
"user": true
user: {
user: true
},
"creator": {
"user": true,
"creator": true,
creator: {
user: true,
creator: true
},
"admin": {
"user": true,
"creator": true,
"admin": true,
admin: {
user: true,
creator: true,
admin: true
}
}
export const useRole = () => {
const { user } = UserProvider.useContainer();
const { user } = UserProvider.useContainer()
return {
hasRole: (role) => user && user.role && !!roleHierarchy[user.role][role]

View file

@ -1,17 +1,38 @@
import { defineConfig } from 'vite'
import { defineConfig, splitVendorChunkPlugin } from 'vite'
import react from '@vitejs/plugin-react'
import { VitePWA } from 'vite-plugin-pwa'
const manifest = {
registerType: 'prompt',
includeAssets: ['assets/icon.png'],
manifest: {
name: 'NQuest',
short_name: 'NQuest',
description: 'NQuest - платформа для ARG игр.',
icons: [],
theme_color: '#fb923c',
background_color: '#171e26',
display: 'standalone',
scope: '/',
start_url: '/quests'
}
}
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
plugins: [react(), splitVendorChunkPlugin(), VitePWA(manifest)],
server: {
proxy: {
'/api': {
target: 'http://localhost:8000',
changeOrigin: true,
secure: false,
ws: false,
ws: false
}
}
},
build: {
// generate .vite/manifest.json in outDir
manifest: true
}
})