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,14 +28,14 @@ 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 />} />
<Route
path="go/:gameId"
element={<Auth><Engine /></Auth>}
loader={({ params }) => ajax(`/api/engine/${params.gameId}`).catch(x => {console.log(x); return null})}
loader={({ params }) => ajax(`/api/engine/${params.gameId}`).catch(x => { console.log(x); return null })}
/>
{/* <Route
path="admin"
@ -52,22 +53,26 @@ const router = createBrowserRouter(
<Route path="*" element={<NoMatch />} />
</Route>
)
);
function App() {
)
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,102 +1,104 @@
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();
useEffect(() => {
setUser(params)
}, [params])
const { user, setUser } = UserProvider.useContainer();
const AppLayout = () => {
const params = useLoaderData()
const navigate = useNavigate()
const location = useLocation()
useEffect(() => {
setUser(params)
}, [params])
const { user, setUser } = UserProvider.useContainer()
const logout = () => {
ajax("/api/user/logout", {
method: "POST",
})
.then(() => { setUser(null); navigate("/login") })
.catch(() => { setUser(null); navigate("/login") })
}
let items = [
{ key: "login", label: "Вход", link: "/login" },
{ key: "register", label: "Регистрация", link: "/register" }
]
if (user != null) {
items = [
{
key: "quests",
label: "Квесты",
link: "/quests"
},
{
key: "user",
label: user.username,
children: [
{
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",
label: <Progress
value={user.experience}
percent={((user.experience - user.expToCurrentLevel) / (user.expToNextLevel - user.expToCurrentLevel) * 100)}
size="small"
showInfo={false}
/>
},
{
type: "group",
key: "nextLevel",
label: `Следующий уровень - ${user.expToNextLevel} очков опыта`
},
{
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 getItemByPath = (items, path) => {
const x = path.pop()
const item = items.find(y => y.key === x);
if (path.length == 0) {
return item
}
return getItemByPath(item.children, path)
}
return (<Layout>
<Header style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
<Link to="/" className="navbar-brand"></Link>
<Menu
mode="horizontal"
items={items}
selectedKeys={location.pathname.replace("/", "")}
onClick={menuHandler}
const logout = () => {
ajax('/api/user/logout', {
method: 'POST'
})
.then(() => { setUser(null); navigate('/login') })
.catch(() => { setUser(null); navigate('/login') })
}
let items = [
{ key: 'login', label: 'Вход', link: '/login' },
{ key: 'register', label: 'Регистрация', link: '/register' }
]
if (user != null) {
items = [
{
key: 'quests',
label: 'Квесты',
link: '/quests'
},
{
key: 'user',
label: user.username,
children: [
{
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',
label: <Progress
value={user.experience}
percent={((user.experience - user.expToCurrentLevel) / (user.expToNextLevel - user.expToCurrentLevel) * 100)}
size="small"
showInfo={false}
/>
</Header>
<Content style={{ padding: '0 24px' }}>
<Outlet />
</Content>
</Layout>);
},
{
type: 'group',
key: 'nextLevel',
label: `Следующий уровень - ${user.expToNextLevel} очков опыта`
},
{
key: 'logout',
label: 'Выход',
handler: logout
}
]
}
]
}
const menuHandler = (x) => {
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) {
return item
}
return getItemByPath(item.children, path)
}
return (<Layout>
<Header style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
<Link to="/" className="navbar-brand"></Link>
<Menu
mode="horizontal"
items={items}
selectedKeys={location.pathname.replace('/', '')}
onClick={menuHandler}
/>
</Header>
<Content style={{ padding: '0 24px' }}>
<Outlet />
</Content>
</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,70 +1,67 @@
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("Неверный код")
break
case "old_code":
message.error("Этот код уже вводился")
break
case "next_level":
message.success("Переход на новый уровень")
break
case "ok_code":
message.success("Код принят, ищите оставшиеся")
break
useEffect(() => {
switch (task.message) {
case 'invalid_code':
message.error('Неверный код')
break
case 'old_code':
message.error('Этот код уже вводился')
break
case 'next_level':
message.success('Переход на новый уровень')
break
case 'ok_code':
message.success('Код принят, ищите оставшиеся')
break
}
}, [task.message])
const [form] = Form.useForm()
const onFinish = ({ code }) => {
ajax(`/api/engine/${params.gameId}/code`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({ code })
})
.then((x) => {
if (x != null) {
setTask(x)
form.setFieldsValue({ code: '' })
}
}, [task.message])
}).catch(e => {
console.warn(e)
})
}
const [form] = Form.useForm();
const onFinish = ({ code }) => {
ajax(`/api/engine/${params.gameId}/code`, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({ code })
}).
then((x) => {
if (x != null) {
setTask(x);
form.setFieldsValue({ code: '' });
}
}).catch(e => {
console.warn(e);
});
};
if (task && task.message == "game_complete") {
return (<div style={{ padding: 8 }}>
if (task && task.message === 'game_complete') {
return (<div style={{ padding: 8 }}>
<Alert type="success" message="Вы прошли все уровни!" />
<Link to={"/"}>К списку игр</Link>
</div>);
}
if (!task) {
return (<div style={{ padding: 8 }}>
<Link to={'/'}>К списку игр</Link>
</div>)
}
if (!task) {
return (<div style={{ padding: 8 }}>
<Alert type="warning" message="Для вас не предусмотренно уровней" />
<Link to={"/"}>К списку игр</Link>
</div>);
}
<Link to={'/'}>К списку игр</Link>
</div>)
}
return (<>
return (<>
<Title>{task.title}</Title>
<Row gutter={8}>
<Col xs={24} sm={24} md={18}>
@ -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();
return (<>
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.Group>
<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,49 +1,49 @@
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 { state } = useLocation()
const [error, setError] = useState(null);
const navigate = useNavigate();
const [form] = Form.useForm();
const Login = () => {
const { user, setUser } = UserProvider.useContainer()
const { state } = useLocation()
const [error, setError] = useState(null)
const navigate = useNavigate()
const [form] = Form.useForm()
useEffect(() => {
if (user) {
navigate(state && state.from ? state.from : "/");
}
}, [user])
const onFinish = (values) => {
ajax("/api/user/login", {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(values)
}).
then(setUser).
catch(({ message }) => setError("Проверьте e-mail и пароль"));
useEffect(() => {
if (user) {
navigate(state && state.from ? state.from : '/')
}
}, [user])
return (<>
const onFinish = (values) => {
ajax('/api/user/login', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(values)
})
.then(setUser)
.catch(({ message }) => setError('Проверьте e-mail и пароль'))
}
return (<>
<h1>Вход</h1>
{error ? <Alert type="error" message={error} /> : null}
<Form
form={form}
name="login"
labelCol={{
span: 8,
span: 8
}}
wrapperCol={{
span: 16,
span: 16
}}
style={{
maxWidth: 600,
maxWidth: 600
}}
onFinish={onFinish}>
@ -51,14 +51,14 @@ export default () => {
label="E-mail"
name="email"
rules={[
{
required: true,
message: 'Обязательное поле',
},
{
type: 'email',
message: 'E-mail некорректный',
},
{
required: true,
message: 'Обязательное поле'
},
{
type: 'email',
message: 'E-mail некорректный'
}
]}
>
<Input
@ -70,18 +70,18 @@ export default () => {
label="Пароль"
name="password"
rules={[
{
required: true,
message: 'Обязательное поле',
},
{
required: true,
message: 'Обязательное поле'
}
]}
>
<Input.Password />
</Form.Item>
<Form.Item
wrapperCol={{
offset: 8,
span: 16,
offset: 8,
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,47 +1,43 @@
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 (<>
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>,
const actions = [
<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>)
let questAction = (<span>Необходимо войти</span>)
if (user) {
questAction = (user.games.find(x => x.id === item.id)
? <span>Вы уже прошли этот квест</span>
: <Button onClick={() => navigate(`/go/${item.id}`)} type="primary">Начать квест</Button>
)
}
if (!!user) {
questAction = (!!user.games.find(x => x.id === item.id)
? <span>Вы уже прошли этот квест</span>
: <Button onClick={() => navigate(`/go/${item.id}`)} type="primary">Начать квест</Button>
);
}
return (
return (
<Card
key={item.id}
actions={actions}
@ -49,12 +45,14 @@ const renderItem = (user, navigate, item) => {
style={{ marginBottom: 8 }}
>
<Avatar src={`/api/file/${item.icon}`} style={{float:'left', margin: '4px'}} />
<Avatar src={`/api/file/${item.icon}`} style={{ float: 'left', margin: '4px' }} />
<Markdown
remarkPlugins={[remarkGfm]}>
{item.description}
</Markdown>
<Space>{questAction}</Space>
</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;
}, [user])
const onFinish = (values) => {
ajax("/api/user/register", {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(values)
}).
then(setUser).
catch(({ message }) => setError("Ошибка регистрации"));
useEffect(() => {
if (user) {
navigate('/')
}
return (<>
}, [user])
const onFinish = (values) => {
ajax('/api/user/register', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(values)
})
.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}>
@ -44,10 +48,10 @@ export default () => {
label="Имя пользователя"
name="username"
rules={[
{
required: true,
message: 'Обязательное поле',
},
{
required: true,
message: 'Обязательное поле'
}
]}
>
<Input />
@ -56,14 +60,14 @@ export default () => {
label="E-mail"
name="email"
rules={[
{
required: true,
message: 'Обязательное поле',
},
{
type: 'email',
message: 'E-mail некорректный',
},
{
required: true,
message: 'Обязательное поле'
},
{
type: 'email',
message: 'E-mail некорректный'
}
]}
help="Не видно другим пользователям"
>
@ -76,10 +80,10 @@ export default () => {
label="Пароль"
name="password"
rules={[
{
required: true,
message: 'Обязательное поле',
},
{
required: true,
message: 'Обязательное поле'
}
]}
>
<Input.Password />
@ -90,26 +94,26 @@ export default () => {
dependencies={['password']}
hasFeedback
rules={[
{
required: true,
message: 'Обязательное поле',
},
({ getFieldValue }) => ({
validator(_, value) {
if (!value || getFieldValue('password') === value) {
return Promise.resolve();
}
return Promise.reject(new Error('Пароли отличаются!'));
},
}),
{
required: true,
message: 'Обязательное поле'
},
({ getFieldValue }) => ({
validator (_, value) {
if (!value || getFieldValue('password') === value) {
return Promise.resolve()
}
return Promise.reject(new Error('Пароли отличаются!'))
}
})
]}
>
<Input.Password />
</Form.Item>
<Form.Item
wrapperCol={{
offset: 8,
span: 16,
offset: 8,
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);
return { user, setUser }
};
const [user, setUser] = useState(null)
return { user, setUser }
}
export const UserProvider = createContainer(useUser);
export const UserProvider = createContainer(useUser)

View file

@ -1,10 +1,10 @@
export const ajax = async (path, params) => {
return fetch(path, params)
.then(r => {
if (r.status < 200 || r.status >= 300) {
throw Error(r.statusText)
}
return r
})
.then(r => r.json())
return fetch(path, params)
.then(r => {
if (r.status < 200 || r.status >= 300) {
throw Error(r.statusText)
}
return r
})
.then(r => r.json())
}

View file

@ -1,24 +1,24 @@
import { UserProvider } from "../store/user"
import { UserProvider } from '../store/user'
const roleHierarchy = {
"user": {
"user": true
},
"creator": {
"user": true,
"creator": true,
},
"admin": {
"user": true,
"creator": true,
"admin": true,
}
user: {
user: true
},
creator: {
user: true,
creator: 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]
}
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
}
})