Added removeCard page, adapted admin design for big screens, some code refactors

This commit is contained in:
Dmitriy Shishkov 2020-09-22 19:51:51 +05:00
parent ca6c639052
commit 7960974e6b
No known key found for this signature in database
GPG Key ID: D76D70029F55183E
22 changed files with 382 additions and 91 deletions

View File

@ -1,4 +1,4 @@
import React, { useEffect, useRef, useState } from 'react';
import React, { useState } from 'react';
import { Switch, Route, useHistory } from 'react-router-dom';
import './App.css';
@ -10,26 +10,14 @@ import SubjectList from './views/SubjectList';
import { ILoadingState, IFilterQuery } from './types';
import NothingFound from './views/NothingFound';
import Admin from './views/Admin';
const useDidUpdate: typeof useEffect = (func, dependencies) => {
const didMountRef = useRef(false);
useEffect(() => {
if (didMountRef.current) {
func();
} else {
didMountRef.current = true;
}
return () => {};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, dependencies);
};
import { useDidUpdate } from './utils';
const App = () => {
const history = useHistory();
const [token, setToken] = useState<string | null>(localStorage.getItem('token'));
const [token, setToken] = useState<string | null>(
localStorage.getItem('token')
);
const [loading, setLoading] = useState<ILoadingState>({
fetching: true,
@ -72,7 +60,11 @@ const App = () => {
/>
</Route>
<Route path="/a">
<Admin token={token} setToken={setToken} setLoading={setLoading} />
<Admin
token={token}
setToken={setToken}
setLoading={setLoading}
/>
</Route>
<Route path="*">
<NothingFound setLoading={setLoading} />

View File

@ -13,6 +13,7 @@
#name h1 {
text-align: center;
line-height: 6vh;
font-size: 4vh;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;

View File

@ -10,18 +10,26 @@ const genName = (
}
if (path === '/a/u') {
return 'Upload form';
return 'Загрузить';
}
if (path === '/a/l') {
return 'login';
return 'Вход';
}
if (path === '/a/r') {
return 'Удалить';
}
if (path === '/list' && searchQuery) {
let result = '';
if (searchQuery.type_num) {
result = result + searchQuery.type_num;
}
if (searchQuery.class_num) {
result = result + searchQuery.class_num + ' класс';
result = result + ' ' + searchQuery.class_num + ' класс';
}
if (searchQuery.predmet_type) {

View File

@ -125,7 +125,7 @@ const Navbar: React.FC<props> = ({ setSearchQuery, query }) => {
id="filters"
ref={formRef}
>
<div>
<div className='centerContent'>
<label htmlFor="teacherFilter">
<h2>Преподаватель</h2>
</label>
@ -152,7 +152,7 @@ const Navbar: React.FC<props> = ({ setSearchQuery, query }) => {
<option value="Конкина Н.В">Конкина Н.В</option>
</select>
</div>
<div>
<div className='centerContent'>
<label htmlFor="typeFilter">
<h2>Тип задания</h2>
</label>
@ -169,7 +169,7 @@ const Navbar: React.FC<props> = ({ setSearchQuery, query }) => {
<option value="Потоковые">Потоковые</option>
</select>
</div>
<div>
<div className='centerContent'>
<label htmlFor="predmetFilter">
<h2>Предмет</h2>
</label>
@ -186,7 +186,7 @@ const Navbar: React.FC<props> = ({ setSearchQuery, query }) => {
<option value="Информатика">Информатика</option>
</select>
</div>
<div>
<div className='centerContent'>
<label htmlFor="classFilter">
<h2>Класс</h2>
</label>

View File

@ -74,6 +74,12 @@
z-index: 1;
}
.centerContent {
display: flex;
align-items: center;
flex-direction: column;
}
#filters label h2 {
margin: 1.5vh 0;
text-align: left;
@ -92,5 +98,5 @@
}
body {
padding-bottom: 10.5vh;
padding-bottom: 10vh;
}

View File

@ -1,3 +1,6 @@
import { Dispatch, SetStateAction, useEffect, useRef } from 'react';
import { IData, ILoadingState } from './types';
const useFocus = (focusRef: React.RefObject<HTMLInputElement>) => {
const setFocus = () => {
setTimeout(() => {
@ -8,27 +11,42 @@ const useFocus = (focusRef: React.RefObject<HTMLInputElement>) => {
return setFocus;
};
const handleFormSubmit = (
e: React.FormEvent<HTMLFormElement>,
uri: string,
callBack?: (res: Response) => void,
headers?: Headers | string[][] | Record<string, string> | undefined
) => {
e.preventDefault();
const data = new FormData(e.currentTarget);
const useDidUpdate: typeof useEffect = (func, dependencies) => {
const didMountRef = useRef(false);
const options: RequestInit = {
method: 'POST',
body: data,
headers: headers
};
useEffect(() => {
if (didMountRef.current) {
func();
} else {
didMountRef.current = true;
}
fetch('https://upml-bank.dmitriy.icu/' + uri, options)
.then((res) => {
if (!res.ok) throw res.statusText;
if (callBack) callBack(res);
})
.catch((err) => console.log(err));
return () => {};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, dependencies);
};
export { useFocus, handleFormSubmit };
const fetchCardList = (
setData: Dispatch<SetStateAction<IData[]>>,
setLoading?: Dispatch<SetStateAction<ILoadingState>>
) => {
if (setLoading) setLoading({ fetching: true, error: '' });
const requestURL = 'https://upml-bank.dmitriy.icu/api/cards';
fetch(requestURL)
.then((res) => {
if (!res.ok) throw res.statusText;
return res.json();
})
.then((data) => {
setData(data);
if (setLoading) setLoading({ fetching: false, error: '' });
})
.catch((err) => {
if (setLoading) setLoading({ fetching: false, error: err });
console.error(err);
});
};
export { useFocus, useDidUpdate, fetchCardList };

View File

@ -1,8 +1,10 @@
import React, { Dispatch, SetStateAction, useEffect } from 'react';
import React, { Dispatch, SetStateAction, useEffect, useState } from 'react';
import { useHistory } from 'react-router-dom';
import { ILoadingState } from '../../../types';
import { handleFormSubmit } from '../../../utils';
import { handleFormSubmit } from '../utils';
import { IErrorStatus } from '../types';
import { handleLoginError } from '../UploadForm/handlers';
import { handleSuccessfulLogin } from './handlers';
import './main.css';
@ -15,6 +17,10 @@ type props = {
const LogInForm: React.FC<props> = ({ setLoading, token, setToken }) => {
const { push: historyPush } = useHistory();
const [errorStatus, setErrorStatus] = useState<IErrorStatus>({
successful: true
});
useEffect(() => {
setLoading({ fetching: false, error: '' });
if (token) {
@ -26,8 +32,12 @@ const LogInForm: React.FC<props> = ({ setLoading, token, setToken }) => {
<form
id="logIn"
onSubmit={(e) =>
handleFormSubmit(e, 'api/login', (res: Response) =>
handleSuccessfulLogin(res, setToken)
handleFormSubmit(
e,
'api/login',
(err) => handleLoginError(err, setErrorStatus),
(res: Response) => handleSuccessfulLogin(res, setToken),
{ 'Access-Control-Allow-Origin': '*' }
)
}
>
@ -38,6 +48,7 @@ const LogInForm: React.FC<props> = ({ setLoading, token, setToken }) => {
<input type="password" name="password" />
<input type="submit" value="Вход" />
{!errorStatus.successful ? <p>{errorStatus.errorMessage}</p> : ''}
</form>
);
};

View File

@ -8,6 +8,10 @@
padding-top: 5vh;
}
#logIn label {
font-size: 2.5vh;
}
#logIn input {
height: 6vh;
border: none;
@ -16,6 +20,7 @@
padding: 0 2vh;
width: 100%;
margin: 1vh 0;
font-size: 2.5vh;
}
#logIn input[type='submit'] {

View File

@ -0,0 +1,40 @@
import React, { Dispatch, SetStateAction, useEffect, useState } from 'react';
import { IData, ILoadingState } from '../../../types';
import { fetchCardList } from '../../../utils';
import './main.css';
import removeIcon from './remove.svg';
import { removeItem } from './utils';
type props = {
setLoading: Dispatch<SetStateAction<ILoadingState>>;
token: string | null;
setToken: Dispatch<SetStateAction<string | null>>;
};
const RemoveList: React.FC<props> = ({ setLoading, token, setToken }) => {
const [data, setData] = useState<IData[]>([]);
useEffect(() => fetchCardList(setData), []);
return (
<div id="deleteList">
{data.map((el, index) => (
<div key={index} className="deleteCard">
<h1>{el.title}</h1>
<h2>{el.class_num}</h2>
<p>{el.predmet_type}</p>
<p>{el.teacher}</p>
<button
onClick={async () => {
await removeItem(el.slug, token!);
}}
>
<img src={removeIcon} alt="удалить" />
</button>
</div>
))}
</div>
);
};
export default RemoveList;

View File

@ -0,0 +1,36 @@
#deleteList {
display: grid;
grid-template-columns: 1fr;
gap: 2vh;
padding: 2vh;
align-content: start;
}
.deleteCard {
background-color: rgb(255, 109, 109);
color: white;
padding: 1.5vh;
border-radius: 5px;
position: relative;
}
.deleteCard * {
padding: 0.2vh 0;
}
.deleteCard button {
position: absolute;
top: 1.5vh;
right: 1.5vh;
height: 2.5h;
width: 2.5vh;
background: none;
border: none;
cursor: pointer;
}
@media (orientation: landscape) {
#deleteList {
grid-template-columns: 1fr 1fr;
}
}

View File

@ -0,0 +1,41 @@
<?xml version="1.0" encoding="iso-8859-1"?>
<!-- Generator: Adobe Illustrator 19.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 298.667 298.667" style="enable-background:new 0 0 298.667 298.667;" xml:space="preserve">
<g fill="#ffffff">
<g>
<polygon points="298.667,30.187 268.48,0 149.333,119.147 30.187,0 0,30.187 119.147,149.333 0,268.48 30.187,298.667
149.333,179.52 268.48,298.667 298.667,268.48 179.52,149.333 "/>
</g>
</g>
<g>
</g>
<g>
</g>
<g>
</g>
<g>
</g>
<g>
</g>
<g>
</g>
<g>
</g>
<g>
</g>
<g>
</g>
<g>
</g>
<g>
</g>
<g>
</g>
<g>
</g>
<g>
</g>
<g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 774 B

View File

@ -0,0 +1,17 @@
const removeItem = async (slug: string, token: string) => {
try {
const res = await fetch(
`https://upml-bank.dmitriy.icu/api/card/${slug}/delete`,
{
method: 'delete',
headers: { Authentification: `Token ${token}` }
}
);
if (!res.ok) throw res.statusText;
return res.text();
} catch (err) {
console.log();
}
};
export { removeItem };

View File

@ -0,0 +1,15 @@
import { Dispatch, SetStateAction } from 'react';
import { IErrorStatus } from '../types';
const handleLoginError = (
err: ErrorEvent,
setErrorStatus: Dispatch<SetStateAction<IErrorStatus>>
) => {
console.log(err);
setErrorStatus({
successful: false,
errorMessage: err.toString()
});
};
export { handleLoginError };

View File

@ -3,7 +3,7 @@ import { useHistory } from 'react-router-dom';
import Select from '../../../components/uploadForm/Select';
import { ILoadingState } from '../../../types';
import { handleFormSubmit } from '../../../utils';
import { handleFormSubmit } from '../utils';
import selectOptions from './selectOptions.json';
import './main.css';
@ -26,8 +26,8 @@ const UploadForm: React.FC<props> = ({ setLoading, token, setToken }) => {
<form
id="uploadForm"
onSubmit={(e) =>
handleFormSubmit(e, 'api/card/create', undefined, {
Authorization: `Token ${localStorage.token}`
handleFormSubmit(e, 'api/card/create', () => {}, undefined, {
'Authorization': `Token ${localStorage.token}`
})
}
>

View File

@ -4,6 +4,10 @@
flex-direction: column;
}
#uploadForm>label {
font-size: 2.5vh;
}
#uploadForm>input,
#uploadForm>select,
#uploadForm>aside {
@ -16,6 +20,7 @@
width: 100%;
background-color: white;
margin: 1vh 0;
font-size: 2.5vh;
color: inherit;
}
@ -25,4 +30,7 @@
justify-content: center;
}
#uploadFrom input[type='file'] {}
#uploadForm input[type='submit'] {
background-color: rgb(255, 109, 109);
color: white;
}

View File

@ -1,10 +1,18 @@
import React, { Dispatch, SetStateAction, useEffect } from 'react';
import { Link, Redirect, Route, Switch, useRouteMatch } from 'react-router-dom';
import {
Link,
Redirect,
Route,
Switch,
useLocation,
useRouteMatch
} from 'react-router-dom';
import { ILoadingState } from '../../types';
import LogInForm from './LogInForm';
import UploadForm from './UploadForm';
import './main.css';
import RemoveList from './RemoveList';
type props = {
token: string | null;
@ -15,6 +23,8 @@ type props = {
const Admin: React.FC<props> = ({ token, setToken, setLoading }) => {
const { path, url } = useRouteMatch();
const { pathname } = useLocation();
useEffect(() => {
setLoading({ fetching: false, error: '' });
}, [setLoading]);
@ -23,22 +33,34 @@ const Admin: React.FC<props> = ({ token, setToken, setLoading }) => {
<div id="admin">
<nav>
<ul>
<li>
<li
className={
!token || pathname === `${url}/u` ? 'current' : ''
}
>
<Link to={`${url}/u`}>Добавить</Link>
</li>
<li>
<li
className={
!token || pathname === `${url}/r` ? 'current' : ''
}
>
<Link to={`${url}/r`}>Удалить</Link>
</li>
</ul>
<button
onClick={() => {
localStorage.removeItem('token');
setToken(null);
}}
id="logSwitch"
>
<Link to={`${url}/l`}>Выход</Link>
</button>
{token ? (
<button
onClick={() => {
localStorage.removeItem('token');
setToken(null);
}}
id="logSwitch"
>
<Link to={`${url}/l`}>Выход</Link>
</button>
) : (
''
)}
</nav>
<Switch>
<Route path={`${path}/u`}>
@ -55,6 +77,13 @@ const Admin: React.FC<props> = ({ token, setToken, setLoading }) => {
setToken={setToken}
/>
</Route>
<Route path={`${path}/r`}>
<RemoveList
setLoading={setLoading}
token={token}
setToken={setToken}
/>
</Route>
<Route path={`${path}/`}>
<Redirect to={`${path}/l`} />
</Route>

View File

@ -1,6 +1,5 @@
#admin {
min-height: calc(79.5vh + 20px);
height: 100%;
min-height: 80vh;
}
#admin nav {
@ -23,11 +22,17 @@
#admin nav li {
list-style-type: none;
font-size: 2.3vh;
}
#admin nav li a {
color: rgb(255, 109, 109);
border-bottom: 1px solid rgb(255, 109, 109);
border-bottom: 2px solid rgb(255, 109, 109);
}
#admin nav li.current a {
color: rgb(54, 54, 69);
border-bottom: none;
}
#admin nav li a,
@ -39,8 +44,8 @@
position: absolute;
background-color: rgb(255, 109, 109);
border: none;
padding: 1.5vh;
height: 6vh;
padding: 0 1.5vh;
line-height: 6vh;
border-radius: 20px;
font-size: 2.5vh;
right: 2vh;
@ -49,4 +54,45 @@
#admin nav #logSwitch a {
color: white;
}
@media (orientation: landscape) {
#admin {
display: grid;
height: 80vh;
grid-template-columns: 1fr 5fr;
}
#admin nav {
height: calc(80vh + 40px);
}
#admin nav ul {
justify-content: start;
gap: 1.5vh;
margin-top: 1.25vh;
padding: 1.5vh 0;
}
#admin nav ul li {
background-color: rgb(255, 109, 109);
padding: 1.5vh;
border-radius: 20px;
}
#admin nav ul li.current {
background-color: rgb(54, 54, 69);
}
#admin nav ul li a {
color: white;
}
#admin nav ul li.current a {
color: white;
}
#admin nav #logSwitch {
top: initial;
right: initial;
left: 2vh;
bottom: calc(20px + 2vh);
}
#admin>* {
height: 80vh;
overflow-y: scroll;
}
}

6
src/views/Admin/types.ts Normal file
View File

@ -0,0 +1,6 @@
interface IErrorStatus {
successful: boolean;
errorMessage?: string;
}
export type { IErrorStatus };

25
src/views/Admin/utils.ts Normal file
View File

@ -0,0 +1,25 @@
const handleFormSubmit = (
e: React.FormEvent<HTMLFormElement>,
uri: string,
errorHandler: (err: any) => void,
callBack?: (res: Response) => void,
headers?: Headers | string[][] | Record<string, string> | undefined
) => {
e.preventDefault();
const data = new FormData(e.currentTarget);
const options: RequestInit = {
method: 'POST',
body: data,
headers: headers
};
fetch('https://upml-bank.dmitriy.icu/' + uri, options)
.then((res) => {
if (!res.ok) throw res.statusText;
if (callBack) callBack(res);
})
.catch((err) => errorHandler(err));
};
export {handleFormSubmit}

View File

@ -6,6 +6,7 @@ import NothingFound from '../NothingFound';
import { IData, IFilterQuery, ILoadingState } from '../../types';
import { handleShowMore } from './handlers';
import './main.css';
import { fetchCardList } from '../../utils';
type props = {
setLoading: Dispatch<SetStateAction<ILoadingState>>;
@ -15,21 +16,7 @@ type props = {
const Home: React.FC<props> = ({ setLoading, setSearchQuery }) => {
const [data, setData] = useState<IData[]>([]);
useEffect(() => {
setLoading({ fetching: true, error: '' });
const requestURL = 'https://upml-bank.dmitriy.icu/api/cards';
fetch(requestURL)
.then((res) => res.json())
.then((data) => {
setData(data);
setLoading({ fetching: false, error: '' });
})
.catch((err) => {
setLoading({ fetching: false, error: err });
console.error(err);
});
}, [setLoading]);
useEffect(() => fetchCardList(setData, setLoading), [setLoading]);
const classes: number[] = [
...Array.from(new Set(data.map((el) => parseInt(el.class_num)).sort()))

View File

@ -1,5 +1,5 @@
.homeContainer {
min-height: calc(79.5vh + 20px);
min-height: calc(80vh + 20px);
}
.classContainer {
@ -7,7 +7,7 @@
padding-top: calc(20px + 2vh);
margin-top: -20px;
position: relative;
overflow: visible;
overflow: hidden;
}
.subjectContainer {

View File

@ -2844,9 +2844,9 @@ caniuse-api@^3.0.0:
lodash.uniq "^4.5.0"
caniuse-lite@^1.0.0, caniuse-lite@^1.0.30000981, caniuse-lite@^1.0.30001020, caniuse-lite@^1.0.30001035:
version "1.0.30001035"
resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30001035.tgz#2bb53b8aa4716b2ed08e088d4dc816a5fe089a1e"
integrity sha512-C1ZxgkuA4/bUEdMbU5WrGY4+UhMFFiXrgNAfxiMIqWgFTWfv/xsZCS2xEHT2LMq7xAZfuAnu6mcqyDl0ZR6wLQ==
version "1.0.30001135"
resolved "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001135.tgz"
integrity sha512-ziNcheTGTHlu9g34EVoHQdIu5g4foc8EsxMGC7Xkokmvw0dqNtX8BS8RgCgFBaAiSp2IdjvBxNdh0ssib28eVQ==
capture-exit@^2.0.0:
version "2.0.0"