This commit is contained in:
2020-06-24 18:56:24 +03:00
parent 9447ee613b
commit 5d4972145b
119 changed files with 5412 additions and 5086 deletions
Regular → Executable
View File
Executable
+1
View File
@@ -0,0 +1 @@
REACT_EDITOR=goland
Regular → Executable
View File
Generated Regular → Executable
+3286 -3618
View File
File diff suppressed because it is too large Load Diff
Regular → Executable
+23 -29
View File
@@ -3,35 +3,31 @@
"version": "0.1.0", "version": "0.1.0",
"private": true, "private": true,
"dependencies": { "dependencies": {
"@fortawesome/fontawesome-svg-core": "^1.2.26", "@fortawesome/fontawesome-svg-core": "1.2.28",
"@fortawesome/free-brands-svg-icons": "^5.12.1", "@fortawesome/free-brands-svg-icons": "5.13.0",
"@fortawesome/free-solid-svg-icons": "^5.12.1", "@fortawesome/free-solid-svg-icons": "5.13.0",
"@fortawesome/react-fontawesome": "^0.1.8", "@fortawesome/react-fontawesome": "0.1.10",
"@sentry/browser": "^5.7.1", "@sentry/browser": "^5.7.1",
"@types/react-infinite-scroller": "^1.2.1", "bbcode-to-react": "0.2.9",
"axios": "^0.19.0", "react": "16.13.1",
"bbcode-to-react": "^0.2.9", "react-dom": "16.13.1",
"react": "^16.12.0", "react-loader-spinner": "3.1.14",
"react-dom": "^16.12.0", "react-redux": "7.2.0",
"react-infinite-scroller": "^1.2.4", "react-router-dom": "5.2.0",
"react-loader-spinner": "^3.1.4", "react-transition-group": "4.4.1",
"react-recaptcha": "^2.3.10", "redux": "4.0.5"
"react-redux": "^7.1.3",
"react-router-dom": "^5.1.2",
"react-transition-group": "^4.3.0",
"redux": "^4.0.5"
}, },
"devDependencies": { "devDependencies": {
"@types/node": "12.12.26", "@types/node": "14.0.13",
"@types/react": "16.9.19", "@types/react": "16.9.36",
"@types/react-dom": "^16.9.5", "@types/react-dom": "16.9.8",
"@types/react-redux": "^7.1.7", "@types/react-redux": "7.1.9",
"@types/react-router-dom": "^5.1.3", "@types/react-router-dom": "5.1.5",
"@types/react-transition-group": "^4.2.4", "@types/react-transition-group": "4.4.0",
"node-sass": "^4.13.1", "node-sass": "4.14.1",
"redux-devtools-extension": "^2.13.8", "redux-devtools-extension": "2.13.8",
"typescript": "^3.8.2", "typescript": "3.9.5",
"react-scripts": "^3.3.1" "react-scripts": "3.4.1"
}, },
"scripts": { "scripts": {
"start": "react-scripts start", "start": "react-scripts start",
@@ -47,9 +43,7 @@
"not op_mini all" "not op_mini all"
], ],
"development": [ "development": [
"last 1 chrome version", "last 1 chrome version"
"last 1 firefox version",
"last 1 safari version"
] ]
} }
} }
Regular → Executable
View File

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 13 KiB

Regular → Executable
View File
Regular → Executable
View File
Regular → Executable
View File
View File

Before

Width:  |  Height:  |  Size: 1.4 KiB

After

Width:  |  Height:  |  Size: 1.4 KiB

View File

Before

Width:  |  Height:  |  Size: 2.3 KiB

After

Width:  |  Height:  |  Size: 2.3 KiB

View File

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

Before

Width:  |  Height:  |  Size: 304 B

After

Width:  |  Height:  |  Size: 304 B

View File

Before

Width:  |  Height:  |  Size: 402 B

After

Width:  |  Height:  |  Size: 402 B

Regular → Executable
View File

Before

Width:  |  Height:  |  Size: 6.2 KiB

After

Width:  |  Height:  |  Size: 6.2 KiB

View File

Before

Width:  |  Height:  |  Size: 1.0 KiB

After

Width:  |  Height:  |  Size: 1.0 KiB

Regular → Executable
View File

Before

Width:  |  Height:  |  Size: 5.6 KiB

After

Width:  |  Height:  |  Size: 5.6 KiB

+1 -1
View File
@@ -6,7 +6,7 @@
$mainColor: #efefef $mainColor: #efefef
$secondaryColor: #aaaaaa $secondaryColor: #aaaaaa
$linkHoverColor: #dddddd $linkHoverColor: #dfdfdf
// BLACK // BLACK
$primaryBackgroundColor: #121212 $primaryBackgroundColor: #121212
Regular → Executable
+13 -7
View File
@@ -1,17 +1,22 @@
const baseUrl = process.env.NODE_ENV === "development" ? 'http://localhost:8080/v1' : 'https://api.unmei.nix13.pw/v1'; const baseUrl = process.env.NODE_ENV === "development" ? 'http://localhost:8080/v1' : 'https://api.unmei.nix13.pw/v1';
export const response = async (url: string, method: string, body?: any) => { export const response = async (url: string, method: string, body?: string | FormData) => {
let bUrl = baseUrl; let bUrl = baseUrl;
if(baseUrl.endsWith('/')) bUrl = bUrl.slice(0, baseUrl.length-1); if(baseUrl.endsWith('/')) bUrl = bUrl.slice(0, baseUrl.length-1);
if(url.startsWith('/')) url = url.slice(1, baseUrl.length); if(url.startsWith('/')) url = url.slice(1, baseUrl.length);
if(typeof body === 'object') body = JSON.stringify(body);
const res = await fetch(`${bUrl}/${url}`, { const res = await fetch(`${bUrl}/${url}`, {
method, body, method, body,
credentials: "include" credentials: "include"
}); });
const json: ApiResponse = await res.json(); let json: ApiResponse;
try {
json = await res.json();
} catch (e) {
json = { error: false };
}
if(res.status === 429) return new Promise(res => { if(res.status === 429) return new Promise(res => {
setTimeout(res.bind(null, response(url, method, body)), 1500); setTimeout(res.bind(null, response(url, method, body)), 1500);
@@ -21,10 +26,10 @@ export const response = async (url: string, method: string, body?: any) => {
return Promise.resolve(json.data); return Promise.resolve(json.data);
} }
const get = (url: string, data?: object) => response(url, 'GET', data); const get = (url: string, data?: object) => response(url, 'GET', JSON.stringify(data));
const post = (url: string, data?: object) => response(url, 'POST', data); const post = (url: string, data?: object | FormData) => response(url, 'POST', data instanceof FormData ? data : JSON.stringify(data));
const put = (url: string, data?: object) => response(url, 'PUT', data); const put = (url: string, data?: object) => response(url, 'PUT', JSON.stringify(data));
const del = (url: string, data?: object) => response(url, 'DELETE', data); const del = (url: string, data?: object) => response(url, 'DELETE', JSON.stringify(data));
const TranslateStatus: { [id: string]: string } = { const TranslateStatus: { [id: string]: string } = {
planned: 'Запланировано', planned: 'Запланировано',
@@ -35,5 +40,6 @@ const TranslateStatus: { [id: string]: string } = {
}; };
export const getVersion = () => get('version'); export const getVersion = () => get('version');
export const version = '0.9';
export { get, post, put, del, TranslateStatus }; export { get, post, put, del, TranslateStatus };
Regular → Executable
View File
Regular → Executable
View File
Regular → Executable
View File
Regular → Executable
+6 -4
View File
@@ -1,6 +1,8 @@
import {get} from './api'; import {get, put} from './api';
const getNews = () => get('news'); const fetchNews = () => get('news');
const getPost = (id: number) => get(`news/${id}`);
export { getNews, getPost } const fetchPost = (id: number) => get(`news/${id}`);
const updatePost = (post: PostType) => put(`news/${post.id}`, post);
export { fetchNews, fetchPost, updatePost }
Regular → Executable
View File
Regular → Executable
+5 -1
View File
@@ -5,7 +5,7 @@ export const fetchUsers = () => get('users');
export const fetchUser = (id: number) => get(`users/${id}`); export const fetchUser = (id: number) => get(`users/${id}`);
export const updateUser = (user: UserType) => put(`users/${user.id}`, { user }) export const updateUser = (user: UserType) => put(`users/${user.id}`, { user })
export const fetchCurrentUser = () => get('users/current'); export const fetchCurrentUser = () => get('users/me');
export const fetchUserNovels = (id: number) => get(`users/${id}/novels`); export const fetchUserNovels = (id: number) => get(`users/${id}/novels`);
export const registerUser = (login: string, password: string, email: string, recaptcha: string) => post('auth/register', { login, password, email, recaptcha }); export const registerUser = (login: string, password: string, email: string, recaptcha: string) => post('auth/register', { login, password, email, recaptcha });
@@ -15,4 +15,8 @@ export const userLogout = () => post('auth/logout');
export const activateAccount = (token: string) => post('auth/activate', { token }); export const activateAccount = (token: string) => post('auth/activate', { token });
export const generateActivateLink = () => post('auth/activateToken'); export const generateActivateLink = () => post('auth/activateToken');
export const fetchUserSettings = () => get('users/me/settings');
export const updateUserSettings = (use_gravatar: boolean, avatar: string) => post('users/me/settings', { use_gravatar, avatar });
export const uploadAvatar = (avatar: FormData) => post('users/me/avatar', avatar);
export const generateRestoreLink = (email: string, recaptcha: string) => post('auth/restoreToken', { email, recaptcha }); export const generateRestoreLink = (email: string, recaptcha: string) => post('auth/restoreToken', { email, recaptcha });
+31
View File
@@ -0,0 +1,31 @@
export interface ObjectClassNames {
[index: string]: boolean;
}
export type ClassName = number | string | ObjectClassNames | false | null | undefined;
export default function classNames(...classNames: ClassName[]) {
let result: string[] = [];
classNames.forEach((item: ClassName): void => {
if (!item) {
return;
}
switch (typeof item) {
case 'string':
result.push(item);
break;
case 'object':
Object.keys(item).forEach((key: string) => {
if (item[key]) {
result.push(key);
}
});
break;
default:
result.push(`${item}`);
}
});
return result.join(' ');
}
-29
View File
@@ -1,29 +0,0 @@
.News
background-color: var(--sec-bg-color)
padding: .5rem
&__Title
display: flex
flex-direction: row
justify-content: space-between
font-size: 1.5rem
font-weight: 600
margin-bottom: .5rem
.Post
background-color: var(--block-color)
padding: .5rem
&__Title
font-size: 1.2rem
&__Content
border-top: var(--link-color) 1px solid
border-bottom: var(--link-color) 1px solid
&__Footer
display: flex
justify-content: space-between
&:not(:last-child)
margin-bottom: 1rem
-49
View File
@@ -1,49 +0,0 @@
import React from "react";
import {getNews} from "../../api/news";
import Loading from "../Loading";
import {Link} from "react-router-dom";
type State = {
news: PostType[]
}
class News extends React.Component<{}, State> {
state: State = {
news: []
};
componentDidMount() {
getNews().then((news: PostType[]) => {
news.forEach(p => p.date = new Date(p.date));
this.setState({ news })
});
}
render() {
const { news } = this.state;
if(news.length === 0) return <Loading/>;
return (
<div className="News">
<div className="News__Title">
<div>Новости</div>
<Link to={'/news'}>Все новости</Link>
</div>
{news.slice(0, 5).map(post => (
<div className={'Post'} key={post.id}>
<div className="Post__Title"><Link to={`/news/${post.id }`}>{post.title}</Link></div>
<div className="Post__Content">{post.short_post}</div>
<div className="Post__Footer">
<div>
Автор: <Link to={`/user/${post.author_id}`}>{post.author}</Link>
</div>
<div>Дата: {post.date.toLocaleDateString()}, {post.date.toLocaleTimeString()}</div>
</div>
</div>
))}
</div>
);
}
}
export default News;
-22
View File
@@ -1,22 +0,0 @@
.Modal__Overlay
display: flex
align-items: center
justify-content: center
position: fixed
top: 0
right: 0
left: 0
bottom: 0
background-color: #0f0f0fef
z-index: 9999
opacity: 1
overflow: hidden
.Modal__CloseButton
background: none
border: none
font-size: 1.5rem
position: absolute
top: 0
right: 0
margin: 1rem
@@ -1,13 +0,0 @@
.PasswordRestore
display: flex
flex-direction: column
button, input
margin: .5rem
font-size: 1.2rem
input
width: 100%
button
align-self: flex-start
Regular → Executable
+1 -1
View File
@@ -7,7 +7,7 @@ import store from "./store/store";
// import * as Sentry from '@sentry/browser'; // import * as Sentry from '@sentry/browser';
import App from './components/App/App'; import App from './pages/App/App';
import * as serviceWorker from './serviceWorker'; import * as serviceWorker from './serviceWorker';
+1 -1
View File
@@ -3,7 +3,7 @@ import {activateAccount} from "../api/users";
import {connect} from "react-redux"; import {connect} from "react-redux";
import {addNotification} from "../store/actions"; import {addNotification} from "../store/actions";
import errors from "../api/errors"; import errors from "../api/errors";
import Loading from "./Loading"; import Loading from "../ui/Loading";
type Props = { type Props = {
history: { push: (path: string) => void } history: { push: (path: string) => void }
@@ -1,4 +1,4 @@
@import "../Constants" @import "../../Constants"
.AdminPanel .AdminPanel
background-color: var(--sec-bg-color) background-color: var(--sec-bg-color)
@@ -7,6 +7,8 @@ import {Link} from "react-router-dom";
import AdminPanelUsers from "./Users/AdminPanelUsers"; import AdminPanelUsers from "./Users/AdminPanelUsers";
import AdminPanelNovels from "./Novels/AdminPanelNovels"; import AdminPanelNovels from "./Novels/AdminPanelNovels";
import ModifyUser from "./Users/ModifyUser"; import ModifyUser from "./Users/ModifyUser";
import APNews from "./News/APNews";
import APModifyPost from "./News/APModifyPost";
type Props = { type Props = {
user: UserType user: UserType
@@ -14,9 +16,7 @@ type Props = {
location: { pathname: string } location: { pathname: string }
} }
type State = { type State = {}
}
class AdminPanel extends React.Component<Props, State> { class AdminPanel extends React.Component<Props, State> {
render() { render() {
@@ -28,14 +28,16 @@ class AdminPanel extends React.Component<Props, State> {
switch(subPath) { switch(subPath) {
case 'users': component = <AdminPanelUsers path={`${path}/${subPath}`}/>; break; case 'users': component = <AdminPanelUsers path={`${path}/${subPath}`}/>; break;
case 'novels': component = <AdminPanelNovels/>; break; case 'novels': component = <AdminPanelNovels/>; break;
case 'news': component = <div>Новости</div>; break; case 'news': component = <APNews path={`${path}/${subPath}`}/>; break;
default: { default: {
const users = /users\/(\d+)/; const users = /users\/(\d+)/;
const news = /news\/(\d+)/;
const userMatch = subPath.match(users); const userMatch = subPath.match(users);
const newsMatch = subPath.match(news);
if(userMatch) if(userMatch) component = <ModifyUser userId={parseInt(userMatch[1])}/>;
component = <ModifyUser userId={parseInt(userMatch[1])}/>; if(newsMatch) component = <APModifyPost postId={parseInt(newsMatch[1])}/>;
} }
} }
+120
View File
@@ -0,0 +1,120 @@
import React, {ChangeEvent, FormEvent} from "react";
import Group from "../../../ui/Group/Group";
import NotFoundError from "../../NotFoundError";
import {fetchPost, updatePost} from "../../../api/news";
import './APNews.sass';
import '../../../ui/TextField/TextField.sass'
import Input from "../../../ui/Input/Input";
import Button from "../../../ui/Button/Button";
import BBEditor from "../../../ui/BBEditor/BBEditor";
// @ts-ignore
import parser from 'bbcode-to-react';
import Title from "../../../ui/Title/Title";
type Props = {
postId: number
//addNotification: (notification: React.ReactNode) => void
};
type State = {
post: PostType | null
title: string
previewShort: string
previewFull: string
};
class APModifyPost extends React.Component<Props, State> {
private shortPost = React.createRef<HTMLTextAreaElement>();
private fullPost = React.createRef<HTMLTextAreaElement>();
state: State = {
post: null, title: '',
previewShort: '', previewFull: ''
}
componentDidMount() {
const { postId } = this.props;
fetchPost(postId).then((post: PostType) => {
this.setState({ post, title: post.title });
});
}
savePost = async (event: FormEvent) => {
event.preventDefault();
const post = this.state.post;
if(!post) return;
if(!this.shortPost.current || !this.fullPost.current) return;
post.short_post = this.shortPost.current.value;
post.full_post = this.fullPost.current.value;
await updatePost(post);
}
componentDidUpdate(prevProps: Readonly<Props>, prevState: Readonly<State>) {
if(prevState.post) return;
if(!this.state.post) return;
if(!this.shortPost.current || !this.fullPost.current) return;
this.shortPost.current.value = this.state.post.short_post;
this.fullPost.current.value = this.state.post.full_post;
}
previewShort = () => {
if(!this.shortPost.current) return;
this.setState({ previewShort: parser.toReact(this.shortPost.current.value) })
}
previewFull = () => {
if(!this.fullPost.current) return;
this.setState({ previewFull: parser.toReact(this.fullPost.current.value) })
}
changeTitle = (event: ChangeEvent<HTMLInputElement>) => {
const post = this.state.post;
if(!post) return;
post.title = event.target.value;
this.setState({ post });
}
render() {
const { post, title, previewShort, previewFull } = this.state;
if(!post) return <NotFoundError/>;
return (
<Group title={title}>
<form onSubmit={this.savePost} className={'APPost'}>
<Input type="text" placeholder={'Заголовок'} value={post.title} onChange={this.changeTitle}/>
<div className={'APPost__Short'}>
<Title>Короткая новость</Title>
<BBEditor inputRef={this.shortPost} placeholder={'Короткая новость'} />
{previewShort.length > 0 && (<>
<Title>Предпросмотр</Title>
<div className={'APPost__Short_Preview TextField'}>{previewShort}</div>
</>)}
<Button type={"button"} onClick={this.previewShort}>Предпросмотр</Button>
</div>
<div className={'APPost__Full'}>
<Title>Полная новость</Title>
<BBEditor inputRef={this.fullPost} placeholder={'Полная новость'} />
{previewFull.length > 0 && (<>
<Title>Предпросмотр</Title>
<div className={'APPost__Full_Preview TextField'}>{previewFull}</div>
</>)}
<Button type={"button"} onClick={this.previewFull}>Предпросмотр</Button>
</div>
<div>
<Button>Сохранить</Button>
<Button type={"button"} style={{ color: 'var(--error) '}}>Удалить</Button>
</div>
</form>
</Group>
)
}
}
export default APModifyPost;
+20
View File
@@ -0,0 +1,20 @@
.APPost
display: flex
flex-direction: column
.Input, .TextField, .Button
font-size: 1.2rem
.Input, .TextField
margin-bottom: 1rem
.TextField
width: 100%
min-height: 4rem
resize: none
&__Short, &__Full
display: flex
flex-direction: column
align-items: flex-start
margin-bottom: 1rem
+42
View File
@@ -0,0 +1,42 @@
import React from "react";
import {fetchNews} from "../../../api/news";
import Group from "../../../ui/Group/Group";
import {Link} from "react-router-dom";
type Props = {
path: string
};
type State = {
news: PostType[]
};
class APNews extends React.Component<Props, State> {
state: State = {
news: []
}
componentDidMount() {
fetchNews().then(news => this.setState({ news }));
}
render() {
const { news } = this.state;
const { path } = this.props;
return (
<Group title={'Новости'}>
{news.map(post => (
<Link to={`${path}/${post.id}`} key={post.id}>
<div style={{ display: "flex" }}>
<div style={{ marginRight: '.5rem', fontWeight: 600 }}>{post.id}</div>
<div>{post.title}</div>
</div>
</Link>
))}
</Group>
)
}
}
export default APNews;
@@ -1,10 +1,11 @@
import React, {ChangeEvent, FormEvent} from "react"; import React, {ChangeEvent, FormEvent} from "react";
import {connect} from "react-redux"; import {connect} from "react-redux";
import {fetchUser, updateUser} from "../../../api/users"; import {fetchUser, updateUser} from "../../../api/users";
import Loading from "../../Loading"; import Loading from "../../../ui/Loading";
import './APUser.sass'; import './APUser.sass';
import {addNotification} from "../../../store/actions"; import {addNotification} from "../../../store/actions";
import NotificationMessage from "../../Notifications/NotificationMessage"; import NotificationMessage from "../../../ui/Notifications/NotificationMessage";
import Button from "../../../ui/Button/Button";
type Props = { type Props = {
userId: number userId: number
@@ -72,7 +73,7 @@ class ModifyUser extends React.Component<Props, State> {
<label>Активирован: <input type='checkbox' onChange={this.onChange} name={'is_activated'} checked={user.is_activated}/></label> <label>Активирован: <input type='checkbox' onChange={this.onChange} name={'is_activated'} checked={user.is_activated}/></label>
<div style={{ textAlign: "right" }}> <div style={{ textAlign: "right" }}>
<button>Сохранить!</button> <Button>Сохранить!</Button>
</div> </div>
</form> </form>
</div> </div>
+5 -26
View File
@@ -1,5 +1,5 @@
@import url('https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap') @import url('https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap')
@import "../Constants" @import "../../Constants"
html, body, #root html, body, #root
width: 100% width: 100%
@@ -75,37 +75,13 @@ a
&:hover &:hover
color: var(--link-color) color: var(--link-color)
input, button, textarea
color: var(--main-color)
&:disabled
color: var(--sec-color)
button
cursor: pointer
padding: .2rem
border-radius: $borderRadius
background-color: var(--block-color)
border: 1px solid var(--main-color)
&:hover
background-color: var(--block-sec-color)
color: var(--link-color)
border: 1px solid var(--link-color)
input
background-color: var(--sec-block-color) !important
border: none
border-bottom: 1px solid var(--main-color) !important
* *
scrollbar-color: #eee #222 scrollbar-color: #eee #222
scrollbar-width: thin scrollbar-width: thin
.Container .Container
max-width: 1200px max-width: 1200px
min-height: calc(100% - 4rem) min-height: calc(100vh - 16rem)
margin: .5rem auto margin: .5rem auto
.Notifications .Notifications
@@ -113,7 +89,10 @@ input
bottom: 0 bottom: 0
left: 0 left: 0
z-index: 100000 z-index: 100000
@media (min-width: 500px)
padding: 1rem padding: 1rem
box-sizing: border-box
.Successful, .Error .Successful, .Error
border: var(--link-color) 1px solid border: var(--link-color) 1px solid
+25 -35
View File
@@ -9,16 +9,14 @@ import NotFoundError from "../NotFoundError";
import {fetchCurrentUser} from "../../api/users"; import {fetchCurrentUser} from "../../api/users";
import {connect} from "react-redux"; import {connect} from "react-redux";
import {setUser} from "../../store/actions"; import {setUser} from "../../store/actions";
import LoginModal from "../LoginModal/LoginModal";
import RegisterModal from "../LoginModal/RegisterModal";
import Character from "../Character/Character"; import Character from "../Character/Character";
// @ts-ignore // @ts-ignore
import parser from 'bbcode-to-react'; import parser from 'bbcode-to-react';
import SpoilerTag from "../Spoiler/SpoilerTag"; import SpoilerTag from "../../ui/Spoiler/SpoilerTag";
import Novels from "../Novels/Novels"; import Novels from "../Novels/Novels";
import Footer from '../Footer/Footer'; import Footer from '../Footer/Footer';
import UserNovels from '../User/Novels/UserNovels'; import UserNovels from '../User/Novels/UserNovels';
import ColorTag from "../Tags/ColorTag"; import ColorTag from "../../ui/Tags/ColorTag";
import ActivateAccount from "../ActivateAccount"; import ActivateAccount from "../ActivateAccount";
import AllNews from "../News/AllNews"; import AllNews from "../News/AllNews";
import Post from "../News/Post"; import Post from "../News/Post";
@@ -26,30 +24,23 @@ import AdminPanel from "../AdminPanel/AdminPanel";
import PasswordRestoreGenerate from "../PasswordRestore/PasswordRestoreGenerate"; import PasswordRestoreGenerate from "../PasswordRestore/PasswordRestoreGenerate";
import PasswordRestore from "../PasswordRestore/PasswordRestore"; import PasswordRestore from "../PasswordRestore/PasswordRestore";
import Users from "../Users/Users"; import Users from "../Users/Users";
import {getVersion} from "../../api/api"; import {getVersion, version} from "../../api/api";
import Settings from "../User/Settings/Settings";
type Props = { type Props = {
notifications: React.ReactNode[] notifications: React.ReactNode[]
setUser: (user: UserType) => void setUser: (user: UserType) => void
modal: React.ReactNode
}; };
type State = { type State = {}
loginModalVisible: boolean
registerModalVisible: boolean
error: string
login: string
password: string
}
class App extends React.Component<Props, State> { class App extends React.Component<Props, State> {
state: State = {}
constructor(props: Props) { constructor(props: Props) {
super(props); super(props);
this.state = {
loginModalVisible: false, registerModalVisible: false, error: '',
login: '', password: ''
};
const { setUser } = this.props; const { setUser } = this.props;
fetchCurrentUser().then(setUser).catch((err: ApiError) => { fetchCurrentUser().then(setUser).catch((err: ApiError) => {
if(err.code !== 3 && err.text) console.error(err.text); if(err.code !== 3 && err.text) console.error(err.text);
@@ -62,24 +53,26 @@ class App extends React.Component<Props, State> {
parser.registerTag('spoiler', SpoilerTag); parser.registerTag('spoiler', SpoilerTag);
parser.registerTag('color', ColorTag); parser.registerTag('color', ColorTag);
// In future do something normal with this version getVersion().then(res => {
getVersion().then(res => console.debug(`Current back-end version: ${res.version}`)) if(version !== res.version) {
console.debug(`Current back-end version: ${res.version}. Clearing cache`);
caches.keys().then(names => {
names.forEach(name => caches.delete(name).catch(console.error))
});
}
});
} }
showLoginModal = () => this.setState({ loginModalVisible: true, registerModalVisible: false });
hideLoginModal = () => this.setState({ loginModalVisible: false });
showRegisterModal = () => this.setState({ registerModalVisible: true, loginModalVisible: false });
hideRegisterModal = () => this.setState({ registerModalVisible: false });
render() { render() {
const { loginModalVisible, registerModalVisible } = this.state; const { modal } = this.props;
const notificationWidth = window.screen.width >= 500 ? 500 : window.screen.width;
return ( return (
<> <>
<Navbar showLoginModal={this.showLoginModal} showRegisterModal={this.showRegisterModal}/> <Navbar/>
<div className={'Container'}> <div className={'Container'}>
<div className="Notifications"> <div className="Notifications" style={{ width: notificationWidth }}>
{this.props.notifications.map((n, i) => ( {this.props.notifications.map((n, i) => (
<React.Fragment key={i}> <React.Fragment key={i}>
{n} {n}
@@ -98,6 +91,7 @@ class App extends React.Component<Props, State> {
<Route exact path={'/users'} component={Users}/> <Route exact path={'/users'} component={Users}/>
<Route exact path={'/user/:userId'} component={User}/> <Route exact path={'/user/:userId'} component={User}/>
<Route exact path={'/user/:userId/novels'} component={UserNovels}/> <Route exact path={'/user/:userId/novels'} component={UserNovels}/>
<Route exact path={'/user/:userId/settings'} component={Settings}/>
<Route exact path={'/character/:charId'} component={Character}/> <Route exact path={'/character/:charId'} component={Character}/>
@@ -111,12 +105,7 @@ class App extends React.Component<Props, State> {
<Route component={NotFoundError}/> <Route component={NotFoundError}/>
</Switch> </Switch>
{loginModalVisible && ( {modal && modal}
<LoginModal hideModal={this.hideLoginModal} openRegisterModal={this.showRegisterModal}/>
)}
{registerModalVisible && (
<RegisterModal hideModal={this.hideRegisterModal}/>
)}
</div> </div>
<Footer/> <Footer/>
</> </>
@@ -126,7 +115,8 @@ class App extends React.Component<Props, State> {
export default connect( export default connect(
(state: StoreState) => ({ (state: StoreState) => ({
notifications: state.notifications notifications: state.notifications,
modal: state.modal
}), }),
dispatch => ({ dispatch => ({
setUser: (userData: UserType) => { setUser: (userData: UserType) => {
+1 -1
View File
@@ -1,4 +1,4 @@
@import '../Constants' @import '../../Constants'
.Character .Character
.Character__Main .Character__Main
+2 -2
View File
@@ -3,8 +3,8 @@ import {fetchChar, fetchCharNovels} from "../../api/characters";
import './Character.sass' import './Character.sass'
// @ts-ignore // @ts-ignore
import parser from 'bbcode-to-react'; import parser from 'bbcode-to-react';
import NovelItem from "../NovelItem/NovelItem"; import NovelItem from "../../ui/NovelItem/NovelItem";
import Loading from "../Loading"; import Loading from "../../ui/Loading";
import NotFoundError from "../NotFoundError"; import NotFoundError from "../NotFoundError";
type Props = { type Props = {
+1 -1
View File
@@ -1,4 +1,4 @@
@import '../Constants' @import '../../Constants'
.Comments .Comments
margin-top: 1rem margin-top: 1rem
+8 -7
View File
@@ -1,13 +1,14 @@
import React from 'react'; import React from 'react';
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faBold, faExclamationTriangle, faItalic, faStrikethrough, faUnderline, faTint } from "@fortawesome/free-solid-svg-icons"; import { faBold, faExclamationTriangle, faItalic, faStrikethrough, faUnderline, faTint } from "@fortawesome/free-solid-svg-icons";
import Comment from './Comment'; import Comment from '../../ui/Comment/Comment';
import './Comments.sass'; import './Comments.sass';
import Loading from "../Loading"; import Loading from "../../ui/Loading";
import {fetchUser} from "../../api/users"; import {fetchUser} from "../../api/users";
import {connect} from "react-redux"; import {connect} from "react-redux";
import {addNotification} from "../../store/actions"; import {addNotification} from "../../store/actions";
import NotificationMessage from "../Notifications/NotificationMessage"; import NotificationMessage from "../../ui/Notifications/NotificationMessage";
import Button from "../../ui/Button/Button";
type Props = { type Props = {
comments: CommentType[] comments: CommentType[]
@@ -80,7 +81,7 @@ class Comments extends React.Component<Props, State> {
render() { render() {
const { user, comments, hasMore, loadMore } = this.props; const { user, comments, hasMore, loadMore } = this.props;
const { users } = this.state; const { users, commentText } = this.state;
if(!user) return <Loading/>; if(!user) return <Loading/>;
return ( return (
@@ -98,16 +99,16 @@ class Comments extends React.Component<Props, State> {
<textarea <textarea
className={'Comments_TextArea'} className={'Comments_TextArea'}
placeholder={'Текст комментария'} placeholder={'Текст комментария'}
value={this.state.commentText} value={commentText}
onChange={(event) => this.setState({ commentText: event.target.value })} onChange={(event) => this.setState({ commentText: event.target.value })}
ref={ref => this.input = ref} ref={ref => this.input = ref}
/> />
<div style={{ display: "flex", justifyContent: "space-between" }}> <div style={{ display: "flex", justifyContent: "space-between" }}>
<div style={{ display: "flex", alignItems: "center" }}> <div style={{ display: "flex", alignItems: "center" }}>
<button type="submit" className={'Comments_Submit'}>Написать</button> <Button type="submit" className={'Comments_Submit'}>Написать</Button>
<div style={{ marginLeft: '.5rem', color: '#bb3333' }}>Комментарии в разработке!</div> <div style={{ marginLeft: '.5rem', color: '#bb3333' }}>Комментарии в разработке!</div>
</div> </div>
{hasMore && <button type={"button"} onClick={loadMore}>Загрузить ещё</button>} {hasMore && <Button onClick={loadMore}>Загрузить ещё</Button>}
</div> </div>
</form>} </form>}
{!comments && ( {!comments && (
View File
+1 -1
View File
@@ -36,7 +36,7 @@ const Footer: React.FC = () => {
<a href="https://vk.com/unmei_site"> <a href="https://vk.com/unmei_site">
<div className="Link"><FontAwesomeIcon icon={faVk}/></div> <div className="Link"><FontAwesomeIcon icon={faVk}/></div>
</a> </a>
<a href="https://discord.gg/GMMymRU"> <a href="https://discord.gg/4CA8Cju">
<div className="Link"><FontAwesomeIcon icon={faDiscord}/></div> <div className="Link"><FontAwesomeIcon icon={faDiscord}/></div>
</a> </a>
<a href="https://t.me/unmei_site"> <a href="https://t.me/unmei_site">
+11
View File
@@ -0,0 +1,11 @@
.News
background-color: var(--sec-bg-color)
padding: .5rem
&__Title
display: flex
flex-direction: row
justify-content: space-between
font-size: 1.5rem
font-weight: 600
margin-bottom: .5rem
View File
+43
View File
@@ -0,0 +1,43 @@
import React from "react";
import {fetchNews} from "../../api/news";
import Loading from "../../ui/Loading";
import {Link} from "react-router-dom";
import NewsPost from "../../ui/NewsPost/NewsPost";
type State = {
news: PostType[]
}
class News extends React.Component<{}, State> {
state: State = {
news: []
};
componentDidMount() {
fetchNews().then((news: PostType[]) => {
news.forEach(p => p.date = new Date(p.date));
this.setState({ news })
});
}
render() {
const { news } = this.state;
if(news.length === 0) return <Loading/>;
return (
<div className="News">
<div className="News__Title">
<div>Новости</div>
<Link to={'/news'}>Все новости</Link>
</div>
{news.slice(0, 3).map(post => (
<Link key={post.id} to={`/news/${post.id}`}>
<NewsPost {...post} />
</Link>
))}
</div>
);
}
}
export default News;
+1 -1
View File
@@ -1,4 +1,4 @@
@import '../Constants' @import '../../Constants'
.LoginModal .LoginModal
border-radius: $borderRadius border-radius: $borderRadius
+23 -16
View File
@@ -1,19 +1,22 @@
import React, {FormEvent, ChangeEvent} from "react"; import React, {FormEvent, ChangeEvent} from "react";
import Modal from "../Modal/Modal"; import Modal from "../../ui/Modal/Modal";
import {login} from "../../api/users"; import {login} from "../../api/users";
import {connect} from "react-redux"; import {connect} from "react-redux";
import {addNotification, setUser} from "../../store/actions"; import {addNotification, hideModal, setModal, setUser} from "../../store/actions";
import './LoginModal.sass' import './LoginModal.sass'
import {Link} from "react-router-dom"; import {Link} from "react-router-dom";
import errors from "../../api/errors"; import errors from "../../api/errors";
import NotificationMessage from "../Notifications/NotificationMessage"; import NotificationMessage from "../../ui/Notifications/NotificationMessage";
import Recaptcha from '../Recaptcha/Recaptcha' import Recaptcha from '../../ui/Recaptcha/Recaptcha'
import Button from "../../ui/Button/Button";
import RegisterModal from "./RegisterModal";
import Input from "../../ui/Input/Input";
type Props = { type Props = {
setUser: (user: UserType) => void setUser: (user: UserType) => void
hideModal: () => void
openRegisterModal: () => void
addNotification: (notification: React.ReactNode) => void addNotification: (notification: React.ReactNode) => void
setModal: (modal: React.ReactNode | null) => void
hideModal: () => void
}; };
type State = { type State = {
@@ -31,8 +34,9 @@ class LoginModal extends React.Component<Props, State> {
loginAndFetchToken = (event: FormEvent) => { loginAndFetchToken = (event: FormEvent) => {
event.preventDefault(); event.preventDefault();
const { setUser, hideModal, addNotification } = this.props; const { setUser, addNotification, setModal } = this.props;
const { login: log, password, recaptcha } = this.state; const { login: log, password, recaptcha } = this.state;
login(log, password, recaptcha).then(user => { login(log, password, recaptcha).then(user => {
if(!user) return; if(!user) return;
@@ -43,7 +47,7 @@ class LoginModal extends React.Component<Props, State> {
</NotificationMessage> </NotificationMessage>
); );
addNotification(successful); addNotification(successful);
hideModal(); setModal(null);
}) })
.catch((r: ApiError) => { .catch((r: ApiError) => {
this.setState({ error: errors[r.code] }); this.setState({ error: errors[r.code] });
@@ -56,12 +60,13 @@ class LoginModal extends React.Component<Props, State> {
render() { render() {
const { login, password, error, recaptchaNeeded } = this.state; const { login, password, error, recaptchaNeeded } = this.state;
const { hideModal, setModal } = this.props;
return ( return (
<Modal onCloseRequest={this.props.hideModal} className={'LoginModal'}> <Modal className={'LoginModal'} title={'Авторизация'}>
<h1>Авторизация</h1>
{error && <div className="LoginModal__Error">{error}</div>} {error && <div className="LoginModal__Error">{error}</div>}
<form className={'LoginModal__Form'} onSubmit={this.loginAndFetchToken}> <form className={'LoginModal__Form'} onSubmit={this.loginAndFetchToken}>
<input <Input
type="text" type="text"
name={'login'} name={'login'}
placeholder={'Логин'} placeholder={'Логин'}
@@ -69,7 +74,7 @@ class LoginModal extends React.Component<Props, State> {
onChange={this.handleLoginChange} onChange={this.handleLoginChange}
value={login} value={login}
/> />
<input <Input
type="password" type="password"
name={'password'} name={'password'}
placeholder={'Пароль'} placeholder={'Пароль'}
@@ -83,12 +88,12 @@ class LoginModal extends React.Component<Props, State> {
theme={'dark'} theme={'dark'}
sitekey={'6LfnDsMUAAAAAEDfD5ubCdFQbNUnKxxJlMWeUMzN'} sitekey={'6LfnDsMUAAAAAEDfD5ubCdFQbNUnKxxJlMWeUMzN'}
/>} />}
<button className={'LoginModal__Submit'} type={"submit"}>Войти</button> <Button className={'LoginModal__Submit'}>Войти</Button>
</form> </form>
<div className="LoginModal__Links"> <div className="LoginModal__Links">
<Link to={'/restore'}>Забыли пароль?</Link> <Link to={'/restore'} onClick={hideModal}>Забыли пароль?</Link>
<p>|</p> <p>|</p>
<Link to={''} onClick={this.props.openRegisterModal}>Регистрация</Link> <Link to={''} onClick={() => setModal(<RegisterModal/>)}>Регистрация</Link>
</div> </div>
</Modal> </Modal>
) )
@@ -98,6 +103,8 @@ class LoginModal extends React.Component<Props, State> {
export default connect(null, export default connect(null,
dispatch => ({ dispatch => ({
setUser: (user: UserType) => dispatch(setUser(user)), setUser: (user: UserType) => dispatch(setUser(user)),
addNotification: (notification: React.ReactNode) => dispatch(addNotification(notification)) addNotification: (notification: React.ReactNode) => dispatch(addNotification(notification)),
setModal: (modal: React.ReactNode | null) => dispatch(setModal(modal)),
hideModal: () => dispatch(hideModal())
}) })
)(LoginModal); )(LoginModal);
@@ -1,4 +1,4 @@
@import '../Constants' @import '../../Constants'
.RegisterModal .RegisterModal
border-radius: $borderRadius border-radius: $borderRadius
+17 -16
View File
@@ -1,15 +1,17 @@
import React from "react"; import React from "react";
import Modal from "../Modal/Modal"; import Modal from "../../ui/Modal/Modal";
import Recaptcha from '../Recaptcha/Recaptcha' import Recaptcha from '../../ui/Recaptcha/Recaptcha'
import './RegisterModal.sass' import './RegisterModal.sass'
import {registerUser} from "../../api/users"; import {registerUser} from "../../api/users";
import {connect} from "react-redux"; import {connect} from "react-redux";
import {addNotification} from "../../store/actions"; import {addNotification, setModal} from "../../store/actions";
import NotificationMessage from "../Notifications/NotificationMessage"; import NotificationMessage from "../../ui/Notifications/NotificationMessage";
import Button from "../../ui/Button/Button";
import Input from "../../ui/Input/Input";
type Props = { type Props = {
addNotification: (notification: React.ReactNode) => void addNotification: (notification: React.ReactNode) => void
hideModal: () => void setModal: (modal: React.ReactNode | null) => void
} }
type State = { type State = {
@@ -55,23 +57,21 @@ class RegisterModal extends React.Component<Props, State> {
Проверьте почту <strong>{email}</strong>. На неё была отправлена ссылка для подтверждения аккаунта. Проверьте почту <strong>{email}</strong>. На неё была отправлена ссылка для подтверждения аккаунта.
</NotificationMessage> </NotificationMessage>
); );
const { addNotification, hideModal } = this.props; const { addNotification, setModal } = this.props;
addNotification(notification); addNotification(notification);
hideModal(); setModal(null);
}).catch(console.error); }).catch(console.error);
} }
}; };
render() { render() {
const { hideModal } = this.props;
const { error, email, login, password1, password2 } = this.state; const { error, email, login, password1, password2 } = this.state;
return ( return (
<Modal onCloseRequest={hideModal} className={'RegisterModal'}> <Modal className={'RegisterModal'} title={'Регистрация'}>
<h1>Регистрация</h1>
{error && <div className="RegisterModal__Error" dangerouslySetInnerHTML={{ __html: error }}/>} {error && <div className="RegisterModal__Error" dangerouslySetInnerHTML={{ __html: error }}/>}
<form className="RegisterModal__Form" onSubmit={this.submitForm}> <form className="RegisterModal__Form" onSubmit={this.submitForm}>
<input <Input
type="text" type="text"
min={4} min={4}
max={20} max={20}
@@ -81,7 +81,7 @@ class RegisterModal extends React.Component<Props, State> {
className={'RegisterModal__Field'} className={'RegisterModal__Field'}
onChange={this.handleLoginChange} onChange={this.handleLoginChange}
value={login}/> value={login}/>
<input <Input
type="email" type="email"
name={'email'} name={'email'}
placeholder={'E-mail'} placeholder={'E-mail'}
@@ -89,14 +89,14 @@ class RegisterModal extends React.Component<Props, State> {
className={'RegisterModal__Field'} className={'RegisterModal__Field'}
onChange={this.handleEmailChange} onChange={this.handleEmailChange}
value={email}/> value={email}/>
<input <Input
type="password" type="password"
name={'password1'} name={'password1'}
placeholder={'Пароль'} placeholder={'Пароль'}
className={'RegisterModal__Field'} className={'RegisterModal__Field'}
onChange={this.handlePassword1Change} onChange={this.handlePassword1Change}
value={password1}/> value={password1}/>
<input <Input
type="password" type="password"
name={'password2'} name={'password2'}
placeholder={'Повтор пароля'} placeholder={'Повтор пароля'}
@@ -110,7 +110,7 @@ class RegisterModal extends React.Component<Props, State> {
theme={'dark'} theme={'dark'}
sitekey={'6LfnDsMUAAAAAEDfD5ubCdFQbNUnKxxJlMWeUMzN'}/> sitekey={'6LfnDsMUAAAAAEDfD5ubCdFQbNUnKxxJlMWeUMzN'}/>
<button className={'RegisterModal__Submit'} type={"submit"}>Регистрация</button> <Button className={'RegisterModal__Submit'}>Регистрация</Button>
</form> </form>
</Modal> </Modal>
) )
@@ -119,6 +119,7 @@ class RegisterModal extends React.Component<Props, State> {
export default connect(null, export default connect(null,
dispatch => ({ dispatch => ({
addNotification: (notification: React.ReactNode) => dispatch(addNotification(notification)) addNotification: (notification: React.ReactNode) => dispatch(addNotification(notification)),
setModal: (modal: React.ReactNode | null) => dispatch(setModal(modal))
}) })
)(RegisterModal); )(RegisterModal);
+2 -2
View File
@@ -75,8 +75,8 @@ $hoverColor: #f22
left: 0 left: 0
height: 0 height: 0
background: $hoverColor background: $hoverColor
transition: heigth .1s ease-in transition: heigth .1s linear
-webkit-transition: height .1s ease-in -webkit-transition: height .1s linear
&:hover &:hover
background-color: var(--main-bg-color) background-color: var(--main-bg-color)
+26 -18
View File
@@ -3,25 +3,27 @@ import './Navbar.sass'
import {connect} from "react-redux"; import {connect} from "react-redux";
import {userLogout} from "../../api/users"; import {userLogout} from "../../api/users";
import {Link} from "react-router-dom"; import {Link} from "react-router-dom";
import {logout} from "../../store/actions"; import {logout, setModal} from "../../store/actions";
import {hasAccessToAdminPanel} from "../../utils"; import {hasAccessToAdminPanel} from "../../utils";
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome'; import {FontAwesomeIcon} from '@fortawesome/react-fontawesome';
import {faBars} from '@fortawesome/free-solid-svg-icons'; import {faBars} from '@fortawesome/free-solid-svg-icons';
import RegisterModal from "../Modals/RegisterModal";
import LoginModal from "../Modals/LoginModal";
type Props = { type Props = {
showRegisterModal: () => void setModal: SetModalType
showLoginModal: () => void
logout: () => void logout: () => void
currentUser: UserType currentUser: UserType
}; };
type State = { type State = {
expand: boolean expand: boolean
width: number
} }
class Navbar extends React.Component<Props, State> { class Navbar extends React.Component<Props, State> {
state: State = { state: State = {
expand: false expand: false, width: window.screen.width
} }
logout = () => { logout = () => {
@@ -34,8 +36,15 @@ class Navbar extends React.Component<Props, State> {
this.setState({ expand: !this.state.expand }) this.setState({ expand: !this.state.expand })
} }
componentDidMount() {
window.addEventListener("resize", () => {
if(this.state.width !== window.screen.width)
this.setState({ width: window.screen.width });
})
}
render() { render() {
const { currentUser, showRegisterModal, showLoginModal } = this.props; const { currentUser, setModal } = this.props;
const { expand } = this.state; const { expand } = this.state;
const isMinimized = window.screen.width <= 1000; const isMinimized = window.screen.width <= 1000;
@@ -68,25 +77,22 @@ class Navbar extends React.Component<Props, State> {
)} )}
{currentUser && {currentUser &&
(<div className={'Header__User'}> (<div className={'Header__User'}>
{currentUser.authorized && ( {currentUser.authorized ? (<>
<Link to={`/user/${currentUser.id}`} className="Header__User_Profile"> <Link to={`/user/${currentUser.id}`} className="Header__User_Profile">
<div className={'Header__User_Avatar'} style={{ backgroundImage: `url(${currentUser.avatar})` }}/> <div className={'Header__User_Avatar'} style={{ backgroundImage: `url(${currentUser.avatar}?s=40&t=${new Date().getTime()})` }}/>
<div>{this.props.currentUser.username}</div> <div>{this.props.currentUser.username}</div>
</Link> </Link>
)}
{currentUser.group && hasAccessToAdminPanel(currentUser) && ( {currentUser.group && hasAccessToAdminPanel(currentUser) && (
<Link to={'/kawaii__neko'} className={'Header_Button'}> <Link to={'/kawaii__neko'} className={'Header_Button'}>
Админ-панель Админ-панель
</Link> </Link>
)} )}
{!currentUser.authorized && ( <Link className="Header_Button" to={`/user/${currentUser.id}/settings`}>Настройки</Link>
<div className={'Header_Button'} onClick={showRegisterModal}>Регистрация</div>
)}
{!currentUser.authorized ? (
<div className={'Header_Button'} onClick={showLoginModal}>Войти</div>
) : (
<div className={'Header_Button'} onClick={this.logout}>Выйти</div> <div className={'Header_Button'} onClick={this.logout}>Выйти</div>
)} </>) : (<>
<div className={'Header_Button'} onClick={() => setModal(<RegisterModal/>)}>Регистрация</div>
<div className={'Header_Button'} onClick={() => setModal(<LoginModal/>)}>Войти</div>
</>)}
</div>) </div>)
} }
</nav> </nav>
@@ -95,9 +101,11 @@ class Navbar extends React.Component<Props, State> {
} }
export default connect( export default connect(
(state: any) => ({ (state: StoreState) => ({
currentUser: state.currentUser currentUser: state.currentUser
}), }),
dispatch => ({ dispatch => ({
logout: () => dispatch(logout()) logout: () => dispatch(logout()),
}))(Navbar); setModal: (modal: React.ReactNode | null) => dispatch(setModal(modal))
})
)(Navbar);
+7 -13
View File
@@ -1,6 +1,7 @@
import React from "react"; import React from "react";
import Loading from "../Loading"; import Loading from "../../ui/Loading";
import {getNews} from "../../api/news"; import {fetchNews} from "../../api/news";
import NewsPost from "../../ui/NewsPost/NewsPost";
import {Link} from "react-router-dom"; import {Link} from "react-router-dom";
type State = { type State = {
@@ -14,7 +15,7 @@ class AllNews extends React.Component<{}, State> {
componentDidMount() { componentDidMount() {
document.title = 'Новости'; document.title = 'Новости';
getNews().then((news: PostType[]) => { fetchNews().then((news: PostType[]) => {
news.forEach(p => p.date = new Date(p.date)); news.forEach(p => p.date = new Date(p.date));
this.setState({ news }) this.setState({ news })
}); });
@@ -30,16 +31,9 @@ class AllNews extends React.Component<{}, State> {
Новости Новости
</div> </div>
{news.map(post => ( {news.map(post => (
<div className={'Post'} key={post.id}> <Link key={post.id} to={`/post/${post.id}`}>
<div className="Post__Title">{post.title}</div> <NewsPost {...post} />
<div className="Post__Content">{post.short_post}</div> </Link>
<div className="Post__Footer">
<div>
Автор: <Link to={`/user/${post.author_id}`}>{post.author}</Link>
</div>
<div>Дата: {post.date.toLocaleDateString()}, {post.date.toLocaleTimeString()}</div>
</div>
</div>
))} ))}
</div> </div>
); );
View File
+13 -9
View File
@@ -1,9 +1,11 @@
import React from "react"; import React from "react";
import {getPost} from "../../api/news"; import {fetchPost} from "../../api/news";
import Loading from "../Loading"; import Loading from "../../ui/Loading";
import NotFoundError from "../NotFoundError"; import NotFoundError from "../NotFoundError";
import './Post.sass'; import './Post.sass'
import {Link} from "react-router-dom"; import {Link} from "react-router-dom";
// @ts-ignore
import parser from 'bbcode-to-react';
type Props = { type Props = {
match: { params: { postId: number } } match: { params: { postId: number } }
@@ -22,8 +24,9 @@ class Post extends React.Component<Props, State> {
componentDidMount(): void { componentDidMount(): void {
const { match: { params: { postId }} } = this.props; const { match: { params: { postId }} } = this.props;
getPost(postId).then((post: PostType) => { fetchPost(postId).then((post: PostType) => {
this.setState({ post }) post.date = new Date(post.date);
this.setState({ post });
}).catch((error: ApiError) => { }).catch((error: ApiError) => {
this.setState({ code: error.code }) this.setState({ code: error.code })
}); });
@@ -36,13 +39,14 @@ class Post extends React.Component<Props, State> {
if(!post) return <Loading/>; if(!post) return <Loading/>;
return ( return (
<div className={'Post'}> <div className={'Post'}>
<div className={'Post__Title'}>{post.title}</div> <div className="Post__Title">{post.title}</div>
<div className="Post__Content"> <pre className='Post__Content'>{parser.toReact(post.short_post)}</pre>
{post.full_post || post.short_post}
</div>
<div className="Post__Footer"> <div className="Post__Footer">
<div>
Автор: <Link to={`/user/${post.author_id}`}>{post.author}</Link> Автор: <Link to={`/user/${post.author_id}`}>{post.author}</Link>
</div> </div>
<div>Дата: {post.date.toLocaleDateString()}, {post.date.toLocaleTimeString()}</div>
</div>
</div> </div>
) )
} }
View File
+1 -1
View File
@@ -1,4 +1,4 @@
@import "../Constants" @import "../../Constants"
.Novel .Novel
.Novel__Main .Novel__Main
+2 -2
View File
@@ -12,9 +12,9 @@ import {
fetchNovelGenres, postNovelComment, createUserNovel fetchNovelGenres, postNovelComment, createUserNovel
} from "../../api/novels"; } from "../../api/novels";
import {Link} from "react-router-dom"; import {Link} from "react-router-dom";
import Loading from "../Loading"; import Loading from "../../ui/Loading";
import { TranslateStatus } from "../../api/api"; import { TranslateStatus } from "../../api/api";
import Comments from "../Comment/Comments"; import Comments from "../Comments/Comments";
type Props = { type Props = {
currentUser: UserType currentUser: UserType
+1 -1
View File
@@ -1,4 +1,4 @@
@import "../Constants" @import "../../Constants"
.Novels .Novels
background-color: var(--sec-bg-color) background-color: var(--sec-bg-color)
+2 -2
View File
@@ -1,8 +1,8 @@
import './Novels.sass' import './Novels.sass'
import React from "react"; import React from "react";
import {fetchNovels} from "../../api/novels"; import {fetchNovels} from "../../api/novels";
import NovelItem from '../NovelItem/NovelItem'; import NovelItem from '../../ui/NovelItem/NovelItem';
import Loading from "../Loading"; import Loading from "../../ui/Loading";
type State = { type State = {
novels: NovelType[] | null novels: NovelType[] | null
+15
View File
@@ -0,0 +1,15 @@
.PasswordRestore
display: flex
flex-direction: column
padding: .5rem
.Button, input
font-size: 1.2rem
input
width: 100%
margin-bottom: .5rem
.Button
align-self: flex-start
margin-top: .5rem
@@ -2,6 +2,7 @@ import React from "react";
import {restore} from "../../api/auth"; import {restore} from "../../api/auth";
import errors from "../../api/errors"; import errors from "../../api/errors";
import './PasswordRestore.sass'; import './PasswordRestore.sass';
import Button from "../../ui/Button/Button";
type Props = { type Props = {
match: { params: { token: string } } match: { params: { token: string } }
@@ -69,7 +70,7 @@ class PasswordRestore extends React.Component<Props, State> {
onChange={event => this.setState({ p2: event.target.value })} onChange={event => this.setState({ p2: event.target.value })}
required required
/> />
<button>Сменить</button> <Button>Сменить</Button>
</form> </form>
) )
} }
@@ -1,9 +1,10 @@
import React from "react"; import React from "react";
// @ts-ignore // @ts-ignore
// import Recaptcha from "react-recaptcha"; // import Recaptcha from "react-recaptcha";
import Recaptcha from '../Recaptcha/Recaptcha'; import Recaptcha from '../../ui/Recaptcha/Recaptcha';
import './PasswordRestore.sass'; import './PasswordRestore.sass';
import {generateRestoreLink} from "../../api/users"; import {generateRestoreLink} from "../../api/users";
import Button from "../../ui/Button/Button";
type State = { type State = {
email: string email: string
@@ -43,7 +44,7 @@ class PasswordRestoreGenerate extends React.Component<{}, State> {
theme={'dark'} theme={'dark'}
sitekey={'6LfnDsMUAAAAAEDfD5ubCdFQbNUnKxxJlMWeUMzN'} sitekey={'6LfnDsMUAAAAAEDfD5ubCdFQbNUnKxxJlMWeUMzN'}
/> />
<button>Восстановить</button> <Button>Восстановить</Button>
</form> </form>
); );
} }
@@ -1,4 +1,4 @@
@import "../../Constants" @import "../../../Constants"
.UserNovels .UserNovels
background-color: var(--sec-bg-color) background-color: var(--sec-bg-color)
@@ -1,8 +1,8 @@
import React from 'react'; import React from 'react';
import './UserNovels.sass'; import './UserNovels.sass';
import { fetchUserNovels, fetchUser } from '../../../api/users'; import { fetchUserNovels, fetchUser } from '../../../api/users';
import Loading from '../../Loading'; import Loading from '../../../ui/Loading';
import NovelItem from '../../NovelItem/NovelItem'; import NovelItem from '../../../ui/NovelItem/NovelItem';
import {capitalize, generateClassName, getRandomInt} from "../../../utils"; import {capitalize, generateClassName, getRandomInt} from "../../../utils";
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome"; import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
import {faAlignJustify, faThLarge} from "@fortawesome/free-solid-svg-icons"; import {faAlignJustify, faThLarge} from "@fortawesome/free-solid-svg-icons";
@@ -75,7 +75,7 @@ class UserNovels extends React.Component<Props, State> {
<button onClick={this.getRandomNovel}>Рандомная новелла</button> <button onClick={this.getRandomNovel}>Рандомная новелла</button>
</div> </div>
<div className={generateClassName("UserNovels__List_Novels", capitalize(viewType) || 'Grid')}> <div className={generateClassName("UserNovels__List_Novels", capitalize(viewType) || 'Grid')}>
{planned.map(novel => <NovelItem {...novel} key={novel.id} viewType={viewType}/>)} {planned.map((novel, id) => <NovelItem {...novel} key={novel.id} novelId={id+1} viewType={viewType}/>)}
</div> </div>
</div>} </div>}
@@ -84,7 +84,7 @@ class UserNovels extends React.Component<Props, State> {
Пройденные Пройденные
</div> </div>
<div className={generateClassName("UserNovels__List_Novels", capitalize(viewType) || 'Grid')}> <div className={generateClassName("UserNovels__List_Novels", capitalize(viewType) || 'Grid')}>
{completed.map(novel => <NovelItem {...novel} key={novel.id} viewType={viewType}/>)} {completed.map((novel, id) => <NovelItem {...novel} key={novel.id} novelId={id+1} viewType={viewType}/>)}
</div> </div>
</div>} </div>}
</div> </div>
+12
View File
@@ -0,0 +1,12 @@
.Group
.Settings_Avatar
form
display: flex
flex-direction: column
align-items: flex-start
input
margin: .5rem 0
.Button
flex-grow: 0
+83
View File
@@ -0,0 +1,83 @@
import React, {ChangeEvent, FormEvent} from "react";
import Group from "../../../ui/Group/Group";
import {connect} from "react-redux";
import NotFoundError from "../../NotFoundError";
import Button from "../../../ui/Button/Button";
import './Settings.sass';
import {fetchUserSettings, updateUserSettings, uploadAvatar} from "../../../api/users";
import {setUser} from "../../../store/actions";
type Props = {
match: { params: { userId: string } }
currentUser: UserType
setUser: (user: UserType) => void
}
type State = {
// Avatar
useGravatar: boolean
avatar: File | null
}
class Settings extends React.Component<Props, State> {
state: State = {
useGravatar: false, avatar: null
}
componentDidMount() {
fetchUserSettings().then(settings => {
this.setState({ useGravatar: settings.use_gravatar })
})
}
onChangeAvatar = (event: ChangeEvent<HTMLInputElement>) => {
const files = event.target.files;
if(!files) return;
this.setState({ avatar: files[0] });
}
saveAvatar = (event: FormEvent) => {
event.preventDefault();
const { avatar, useGravatar } = this.state;
const { setUser } = this.props;
if(avatar) {
const formData = new FormData();
formData.append('avatar', avatar);
uploadAvatar(formData).then(avatarUrl => {
updateUserSettings(useGravatar, avatarUrl).then(setUser)
})
} else {
updateUserSettings(useGravatar, '').then(setUser)
}
}
render() {
const { currentUser, match: { params: { userId } } } = this.props;
const { useGravatar } = this.state
if(parseInt(userId) !== currentUser.id) return <NotFoundError/>;
return (
<Group title={'Настройки'}>
<Group title={'Аватар'} className={'Settings_Avatar'}>
<form onSubmit={this.saveAvatar}>
<label>Использовать Gravatar <input type="checkbox" onChange={event => this.setState({ useGravatar: event.target.checked })} checked={useGravatar}/></label>
<label>Загрузить аватар <input type="file" onChange={this.onChangeAvatar} disabled={useGravatar}/></label>
<Button>Сохранить</Button>
</form>
</Group>
</Group>
);
}
}
export default connect(
(state: StoreState) => ({
currentUser: state.currentUser
}),
dispatch => ({
setUser: (user: UserType) => dispatch(setUser(user))
})
)(Settings);
+4 -1
View File
@@ -42,7 +42,10 @@
font-weight: 600 font-weight: 600
&_Group &_Group
border: 1px solid #eeeeee border-color: #eeeeee
border-width: 1px 1px 1px 4px
border-style: solid
border-radius: 4px border-radius: 4px
padding: .2rem padding: .2rem
text-align: center text-align: center
+6 -5
View File
@@ -3,9 +3,10 @@ import {fetchUser, fetchUserNovels, generateActivateLink} from "../../api/users"
import './User.sass' import './User.sass'
import NotFoundError from "../NotFoundError"; import NotFoundError from "../NotFoundError";
import {Link} from "react-router-dom"; import {Link} from "react-router-dom";
import Loading from "../Loading"; import Loading from "../../ui/Loading";
import NovelItem from "../NovelItem/NovelItem"; import NovelItem from "../../ui/NovelItem/NovelItem";
import {connect} from "react-redux"; import {connect} from "react-redux";
import Button from "../../ui/Button/Button";
type Props = { type Props = {
match: { params: { userId: string } } match: { params: { userId: string } }
@@ -55,7 +56,7 @@ class User extends React.Component<Props, State> {
<h2>Ваш аккаунт не активирован!</h2> <h2>Ваш аккаунт не активирован!</h2>
<p>Активируйте аккаунт, для доступа ко многим функциям. Так же актвация аккаунта позволит восстановить пароль.</p> <p>Активируйте аккаунт, для доступа ко многим функциям. Так же актвация аккаунта позволит восстановить пароль.</p>
<div style={{ display: "flex", justifyContent: "flex-end" }}> <div style={{ display: "flex", justifyContent: "flex-end" }}>
<button onClick={this.sendActivateLink} style={{ fontSize: '1.2rem' }}>Активировать!</button> <Button onClick={this.sendActivateLink} style={{ fontSize: '1.2rem' }}>Активировать!</Button>
</div> </div>
</div> </div>
)} )}
@@ -63,7 +64,7 @@ class User extends React.Component<Props, State> {
<div className="User__Info" style={style}> <div className="User__Info" style={style}>
{user.cover && <div className="User__Info_Cover" style={{ backgroundImage: `url(${user.cover})` }}/>} {user.cover && <div className="User__Info_Cover" style={{ backgroundImage: `url(${user.cover})` }}/>}
<div className={'User__Info_Main'}> <div className={'User__Info_Main'}>
<div className="User__Info_Avatar" style={{ backgroundImage: `url(${user.avatar})` }} /> <div className="User__Info_Avatar" style={{ backgroundImage: `url(${user.avatar}?s=96&t=${new Date().getTime()})` }} />
<div> <div>
<div className='User__Info_Nick'>{user.username}</div> <div className='User__Info_Nick'>{user.username}</div>
<div className='User__Info_Group' style={{ borderColor: user.group.color, color: user.group.color }}>{user.group.name}</div> <div className='User__Info_Group' style={{ borderColor: user.group.color, color: user.group.color }}>{user.group.name}</div>
@@ -91,7 +92,7 @@ class User extends React.Component<Props, State> {
</div> </div>
<div className="User__List_Items"> <div className="User__List_Items">
{novels.length > 0 ? {novels.length > 0 ?
novels.slice(0, 4).map((novel) => <NovelItem {...novel} key={novel.id} viewType={'grid'} /> novels.slice(0, 4).map((novel, id) => <NovelItem {...novel} key={novel.id} novelId={id+1} viewType={'grid'} />
) : ( ) : (
<div>У этого пользователя нет новелл!</div> <div>У этого пользователя нет новелл!</div>
)} )}
View File
+2 -2
View File
@@ -1,6 +1,6 @@
import React from "react"; import React from "react";
import {fetchUsers} from "../../api/users"; import {fetchUsers} from "../../api/users";
import Loading from "../Loading"; import Loading from "../../ui/Loading";
import './Users.sass'; import './Users.sass';
import {Link} from "react-router-dom"; import {Link} from "react-router-dom";
@@ -29,7 +29,7 @@ class Users extends React.Component<Props, State> {
<div className={'Users'}> <div className={'Users'}>
{users.map(user => ( {users.map(user => (
<Link className={'Users__User'} key={user.id} to={`user/${user.id}`}> <Link className={'Users__User'} key={user.id} to={`user/${user.id}`}>
<div className="Users__User_Avatar" style={{ backgroundImage: `url(${user.avatar})` }}/> <div className="Users__User_Avatar" style={{ backgroundImage: `url(${user.avatar}?s=96?t=${new Date().getTime()})` }}/>
{user.username} {user.username}
</Link> </Link>
))} ))}
Vendored Regular → Executable
View File
Regular → Executable
View File
Regular → Executable
+3 -1
View File
@@ -1,7 +1,9 @@
enum ActionTypes { enum ActionTypes {
SET_USER = 'SET_USER', SET_USER = 'SET_USER',
LOGOUT = 'LOGOUT', LOGOUT = 'LOGOUT',
ADD_NOTIFICATION = 'ADD_NOTIFICATION' ADD_NOTIFICATION = 'ADD_NOTIFICATION',
SET_MODAL = 'SET_MODAL',
HIDE_MODAL = 'HIDE_MODAL'
} }
export default ActionTypes; export default ActionTypes;
Regular → Executable
+10 -1
View File
@@ -14,5 +14,14 @@ const addNotification = (notification: React.ReactNode) => ({
notification notification
}); });
const setModal = (modal: React.ReactNode | null) => ({
type: ActionTypes.SET_MODAL,
modal
});
const hideModal = () => ({
type: ActionTypes.HIDE_MODAL
})
export { setUser, logout, export { setUser, logout,
addNotification }; addNotification,
setModal, hideModal };
View File
Regular → Executable
+2 -2
View File
@@ -1,6 +1,6 @@
import {combineReducers} from "redux"; import {combineReducers} from "redux";
import currentUser from "./currentUser"; import currentUser from "./currentUser";
import notifications from "./notifications"; import notifications from "./notifications";
import modal from "./modal";
export default combineReducers({ currentUser, notifications, modal })
export default combineReducers({ currentUser, notifications })
+21
View File
@@ -0,0 +1,21 @@
import React from "react";
import ActionTypes from "../actionTypes";
const initialState: React.ReactNode | null = null;
type Action = {
type: string
modal: React.ReactNode | null
}
export default (state=initialState, action: Action) => {
switch (action.type) {
case ActionTypes.SET_MODAL: {
return action.modal;
}
case ActionTypes.HIDE_MODAL: {
return null;
}
default: return state;
}
}
View File
Regular → Executable
View File
Vendored Regular → Executable
+4 -1
View File
@@ -79,5 +79,8 @@ type PostType = {
type StoreState = { type StoreState = {
currentUser: UserType currentUser: UserType
notifications: React.Component[] notifications: React.ReactNode[]
modal: React.ReactNode
} }
type SetModalType = (modal: React.ReactNode | null) => void
+16
View File
@@ -0,0 +1,16 @@
.BBCodes
font-size: 1.3rem
margin-bottom: .2rem
svg
cursor: pointer
padding: 0
svg:first-child
padding-right: .5rem
svg:last-child
padding-left: .5rem
svg:not(:first-child):not(:last-child)
padding: 0 .5rem
+51
View File
@@ -0,0 +1,51 @@
import React, {useState} from "react";
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
import {
faBold,
faExclamationTriangle,
faItalic,
faStrikethrough,
faTint,
faUnderline
} from "@fortawesome/free-solid-svg-icons";
import './BBEditor.sass';
import TextField from "../TextField/TextField";
interface Props extends React.DetailedHTMLProps<React.TextareaHTMLAttributes<HTMLTextAreaElement>, HTMLTextAreaElement> {
inputRef: React.RefObject<HTMLTextAreaElement>
}
const BBEditor = ({ inputRef, ref, ...props }: Props) => {
const [text, setText] = useState('');
const addTag = (event: React.MouseEvent, tag: string, defaultValue?: string) => {
event.preventDefault();
const [start, end] = [inputRef.current!!.selectionStart, inputRef.current!!.selectionEnd];
const openTag = `${tag}${defaultValue ? `=${defaultValue}` : ''}`;
setText(`${text.slice(0, start)}[${openTag}]${text.slice(start, end)}[/${tag}]${text.slice(end, text.length)}`)
inputRef.current!!.focus();
}
return (
<div style={{ width: '100%' }}>
<div className="BBCodes">
<FontAwesomeIcon onClick={event => addTag(event, 'b')} icon={faBold}/>
<FontAwesomeIcon onClick={event => addTag(event, 'i')} icon={faItalic}/>
<FontAwesomeIcon onClick={event => addTag(event, 'u')} icon={faUnderline}/>
<FontAwesomeIcon onClick={event => addTag(event, 's')} icon={faStrikethrough}/>
<FontAwesomeIcon onClick={event => addTag(event, 'spoiler')} icon={faExclamationTriangle}/>
<FontAwesomeIcon onClick={event => addTag(event, 'color', 'white')} icon={faTint}/>
</div>
<TextField
ref={inputRef}
style={{ width: '100%' }}
value={text}
onChange={event => setText(event.target.value)}
{...props}
/>
</div>
)
}
export default BBEditor;
+17
View File
@@ -0,0 +1,17 @@
@import "../../Constants"
.Button
cursor: pointer
padding: .2rem
border-radius: $borderRadius
background-color: var(--block-color)
border: 1px solid var(--main-color)
color: var(--main-color)
&:disabled
color: var(--sec-color)
&:hover
background-color: var(--block-sec-color)
color: var(--link-color)
border: 1px solid var(--link-color)
+14
View File
@@ -0,0 +1,14 @@
import React, {ButtonHTMLAttributes} from "react";
import './Button.sass';
import classNames from "../../classNames";
const Button = (restProps: ButtonHTMLAttributes<HTMLElement>) => {
const { className, children, ...props } = restProps;
return (
<button className={classNames('Button', className)} {...props}>
{children}
</button>
)
}
export default Button;
+1 -1
View File
@@ -1,4 +1,4 @@
@import "../Constants" @import "../../Constants"
.Comment .Comment
display: flex display: flex
View File
+7
View File
@@ -0,0 +1,7 @@
.Buttons
display: flex
justify-content: flex-end
.Button
margin: 1rem .5rem 0
font-size: 1.3rem
+53
View File
@@ -0,0 +1,53 @@
import React from "react";
import Button from "../Button/Button";
import './ConfirmPopout.sass'
import '../Modal/Modal.sass';
import {connect} from "react-redux";
import {hideModal} from "../../store/actions";
type Props = {
hideModal: () => void
onConfirm?: () => void
onDismiss?: () => void
title?: string
children: any
}
class ConfirmPopout extends React.Component<Props> {
onConfirm = () => {
const { hideModal, onConfirm } = this.props;
if(onConfirm) onConfirm();
hideModal();
}
onDismiss = () => {
const { hideModal, onDismiss } = this.props;
if(onDismiss) onDismiss();
hideModal();
}
render() {
const { children, title } = this.props;
return (
<div className="Modal__Overlay">
<div className={"Modal"}>
{title && <div className="Modal__Header">
{title}
</div>}
{children}
<div className={'Buttons'}>
<Button onClick={this.onConfirm}>Да</Button>
<Button onClick={this.onDismiss}>Нет</Button>
</div>
</div>
</div>
)
}
}
export default connect(null,
dispatch => ({
hideModal: () => dispatch(hideModal())
})
)(ConfirmPopout);
+11
View File
@@ -0,0 +1,11 @@
@import "../../Constants"
.Group
background-color: var(--sec-bg-color)
border-radius: $borderRadius
padding: .5rem
&__Title
font-size: 1.2rem
font-weight: 600
margin-bottom: .5rem
+29
View File
@@ -0,0 +1,29 @@
import React, {HTMLAttributes} from "react";
import classNames from "../../classNames";
import './Group.sass'
interface Props extends HTMLAttributes<HTMLElement> {
title: string
direction?: 'column' | 'row'
}
const Group = (restProps: Props) => {
const { title, direction, className, children, ...props } = restProps;
let style: React.CSSProperties = {};
if(direction === 'column') {
style = {
display: 'flex',
flexDirection: 'column'
}
}
return (
<div className={classNames('Group', className)} {...props}>
<div className="Group__Title">{title}</div>
<div style={style}>
{children}
</div>
</div>
)
}
export default Group;
+8
View File
@@ -0,0 +1,8 @@
.Input
background-color: var(--sec-block-color) !important
border: none
border-bottom: 1px solid var(--main-color) !important
color: var(--main-color)
&:disabled
color: var(--sec-color)
+12
View File
@@ -0,0 +1,12 @@
import React, {InputHTMLAttributes} from "react";
import classNames from "../../classNames";
import './Input.sass';
const Input = (restProps: InputHTMLAttributes<HTMLElement>) => {
const { className, ...props } = restProps;
return (
<input className={classNames('Input', className)} {...props} />
)
}
export default Input;
View File

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