Merge pull request 'Update #2 - Electric Boogaloo' (#2) from Navy.gif/webserver-framework-frontend:master into master

Reviewed-on: #2
This commit is contained in:
D3vision 2022-11-24 10:33:24 +01:00
commit 4755517a02
12 changed files with 217 additions and 149 deletions

View File

@ -1,70 +1,8 @@
# Getting Started with Create React App
# Navy's webserver framework frontend
A template repository for creating Node.js based webservers with sharding.
Main repository: https://git.corgi.wtf/Navy.gif/webserver-framework-frontend
Backend: https://git.corgi.wtf/Navy.gif/webserver-framework
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in your browser.
The page will reload when you make changes.\
You may also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you can't go back!**
If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own.
You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
### Code Splitting
This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
### Analyzing the Bundle Size
This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
### Making a Progressive Web App
This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
### Advanced Configuration
This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
### Deployment
This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
### `npm run build` fails to minify
This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)
# Technologies
- React
- React router

View File

@ -1,4 +1,4 @@
import React, { useEffect } from 'react';
import React, { useEffect, useState } from 'react';
import { BrowserRouter, Navigate, Route, Routes} from 'react-router-dom';
import './css/App.css';
@ -16,34 +16,41 @@ import Admin from './pages/Admin';
function App() {
const [user] = useLoginContext();
const [user, updateUser] = useLoginContext();
const [loading, setLoading] = useState(true);
useEffect(() => {
fetchUser();
(async () => {
await fetchUser();
updateUser();
setLoading(false);
})();
}, []);
const menuItems = [
{ to: '/home', label: 'Home' },
{ to: '/users', label: 'Users' },
{ to: '/admin', label: 'Admin' }
];
];
if (loading) return null;
return (
<div className='app is-full-screen'>
<header className="card">
<UserControls />
</header>
<div className='background'>
<BrowserRouter>
{user ?
<Sidebar>
<SidebarMenu menuItems={menuItems} />
</Sidebar>
<div>
<header className="card">
<UserControls />
</header>
<Sidebar>
<SidebarMenu menuItems={menuItems} />
</Sidebar>
</div>
: null}
<div className='main-content'>

24
src/components/Table.js Normal file
View File

@ -0,0 +1,24 @@
import React from "react";
export const TableListEntry = ({onClick, item, itemKeys}) => {
return <tr onClick={onClick}>
{itemKeys.map(key => <td key={key}>{item[key]}</td>)}
</tr>;
};
export const Table = ({headerItems, children, items, itemKeys}) => {
let i = 0;
return <table className="striped hover" >
<thead>
<tr>
{headerItems.map(item => <th key={item}>{item}</th>)}
</tr>
</thead>
<tbody>
{children ? children : items.map(item => <TableListEntry key={i++} item={item} itemKeys={itemKeys} />)}
</tbody>
</table>;
};

View File

@ -1,24 +1,41 @@
import React from "react";
import React, { useRef } from "react";
import '../css/components/UserControls.css';
import { useLoginContext } from "../structures/UserContext";
import ClickDetector from "../util/ClickDetector";
import { clearSession, post } from "../util/Util";
const UserControls = () => {
const [user] = useLoginContext();
const [user, updateUser] = useLoginContext();
const detailsRef = useRef();
if (!user) return;
return <details className='dropdown user-controls'>
<summary className="is-vertical-align">
Hello {user.displayName}
<img className="profile-picture" src="https://cdn.discordapp.com/avatars/187613017733726210/ee764860975d78bfd52652c6ddaed47b.webp?size=64"></img>
</summary>
<div className="card">
<p><a href="#">Profile</a></p>
<hr/>
<p><a href="#" className="text-error">Logout</a></p>
</div>
</details>;
const logOut = async () => {
const response = await post('/api/logout');
if (response.status === 200) {
clearSession();
updateUser();
}
};
return <ClickDetector callback={() => {
if (detailsRef.current) detailsRef.current.removeAttribute('open');
}}>
<details ref={detailsRef} className='dropdown user-controls'>
<summary className="is-vertical-align">
Hello {user.displayName}
<img className="profile-picture" src="https://cdn.discordapp.com/avatars/187613017733726210/ee764860975d78bfd52652c6ddaed47b.webp?size=64"></img>
</summary>
<div className="card">
<p><a href="#">Profile</a></p>
<hr />
<p><a onClick={logOut} href="#" className="text-error">Logout</a></p>
</div>
</details>
</ClickDetector >;
};

View File

@ -68,7 +68,7 @@ body{
}
.pageTitle{
margin: 0.7em 0 0.7em;
margin: 0;
}
.flex {

View File

@ -2,7 +2,7 @@ import React from 'react';
import ReactDOM from 'react-dom/client';
import './css/index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
// import reportWebVitals from './reportWebVitals';
import { UserContext } from './structures/UserContext';
const root = ReactDOM.createRoot(document.getElementById('root'));
@ -11,6 +11,9 @@ root.render(<React.StrictMode>
<App />
</UserContext>
</React.StrictMode>);
// root.render(<UserContext>
// <App />
// </UserContext>);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))

View File

@ -4,7 +4,7 @@ import '../css/pages/Admin.css';
const Admin = () => {
return <div className="user-page">
<h4 className="pageTitle">Admin</h4>
<h2 className="pageTitle">Admin</h2>
<div className='card'>
</div>
</div>;

View File

@ -4,7 +4,7 @@ import '../css/pages/Empty.css';
const Empty = () => {
return <div className="user-page">
<h4 className="pageTitle">Empty</h4>
<h2 className="pageTitle">Empty</h2>
<div className='card'>
</div>
</div>;

View File

@ -1,11 +1,17 @@
import React from "react";
import '../css/pages/Home.css';
import { get } from "../util/Util";
const Home = () => {
return <div className="user-page">
<h4 className="pageTitle">Home</h4>
<h2 className="pageTitle">Home</h2>
<div className='card'>
<button onClick={async () => {
console.log(await get('/api/test'));
}}>
Test
</button>
</div>
</div>;
};

View File

@ -3,6 +3,7 @@ import { Route, Routes, useNavigate, useParams } from "react-router";
import ErrorBoundary from "../util/ErrorBoundary";
import { get } from '../util/Util';
import '../css/pages/Users.css';
import { Table, TableListEntry } from "../components/Table";
const Permission = ({name, value}) => {
return <li className="flex is-vertical-align">
@ -61,17 +62,36 @@ const Permissions = ({ perms }) => {
</div>;
};
// TODO: Make generic table list component and use it here and the user list
const ApplicationList = ({ apps }) => {
const navigate = useNavigate();
return <Table headerItems={['Name', 'ID']}>
{apps.map(app => <TableListEntry
onClick={() => {
navigate(`${window.location.pathname}/applications/${app.id}`);
}}
key={app.id}
item={app}
itemKeys={['name', 'id']}
/>)}
</Table>;
};
const Application = ({ app }) => {
const descProps = {defaultValue: app.description, placeholder: 'Describe your application'};
return <div>
<h4>{app.name} ({app.id})</h4>
<b>Description</b>
<textarea {...descProps} >
</textarea>
</div>;
};
// TODO: Groups, description, notes
const User = ({ user }) => {
const navigate = useNavigate();
@ -79,10 +99,17 @@ const User = ({ user }) => {
useEffect(() => {
(async () => {
const response = await get(`/api/users/${user._id}/applications`);
const response = await get(`/api/users/${user.id}/applications`);
if(response.status === 200) updateApps(response.data);
})();
}, [user]);
}, []);
const ApplicationWrapper = () => {
const { appid } = useParams();
const app = apps.find(a => a.id === appid);
if (!app) return null;
return <Application app={app} />;
};
return <div className='user-card'>
@ -92,24 +119,32 @@ const User = ({ user }) => {
<button className="button primary" onClick={() => {
navigate(-1);
}}>Back</button>
<h3>User {user._id}</h3>
<h2>User {user.id}</h2>
</div>
{user.disabled ? <button>Enable</button> : <button>Disable</button>}
<button>Delete</button>
<p><b>Created: </b>{new Date(user.createdTimestamp).toDateString()}</p>
<p><b>2FA: </b>{user.twoFactor.toString()}</p>
<p><b>Disabled: </b>{user.disabled.toString()}</p>
<label htmlFor='username'>Username:</label>
<input id='username' defaultValue={user.username} />
<input autoComplete='off' id='username' defaultValue={user.username} />
<label htmlFor='displayName'>Display Name:</label>
<input id='displayName' placeholder='Name to display instead of username' defaultValue={user.displayName} />
<input autoComplete='off' id='displayName' placeholder='Name to display instead of username' defaultValue={user.displayName} />
<select>
<option>User</option>
<option>Bob</option>
</select>
<h4>Applications</h4>
<h3>Applications</h3>
<Routes>
<Route path='/' element={<ApplicationList apps={apps} />} />
<Route path='/applications/:appid' element={<ApplicationWrapper />} />
</Routes>
{apps.map(app => <Application key={app._id} app={app} />)}
</div>
@ -125,35 +160,19 @@ const User = ({ user }) => {
</div>;
};
const UserListEntry = ({ user }) => {
const navigate = useNavigate();
const CreateUserField = () => {
const onClick = () => {
navigate(`/users/${user._id}`);
const [link, setLink] = useState(null);
const getSignupCode = async () => {
const response = await get('/api/signup/code');
if(response.status === 200) setLink(response.data);
};
return <tr onClick={onClick}>
<td>{user.username}</td>
<td>{user._id}</td>
</tr>;
};
return <div className="">
{link ? link : <button onClick={getSignupCode} className="is-center">Create sign-up link</button>}
// TODO: Make table list generic component
const UserList = ({ users }) => {
return <table className="striped hover" style={{maxWidth: '30em', marginBottom: '10px'}}>
<thead>
<tr>
<th>Username</th>
<th>ID</th>
</tr>
</thead>
<tbody>
{users.map(user => <UserListEntry key={user._id} user={user} />)}
</tbody>
</table>;
{/* TODO: Create form */}
</div>;
};
@ -175,35 +194,55 @@ const Users = () => {
const UserWrapper = () => {
const { id } = useParams();
const user = users.find(u => u._id === id);
const user = users.find(u => u.id === id);
if (!user) return null;
return <User user={user} />;
};
const navigate = useNavigate();
const UserListWrapper = () => {
return <div className="user-list-wrapper">
<UserList users={users} />
<div className='flex is-vertical-align page-controls'>
<button className="button dark" onClick={() => setPage(page - 1 || 1)}>Previous</button>
<p>Page: {page}</p>
<button className="button dark" onClick={() => {
if (users.length === 10) setPage(page + 1);
}}>Next</button>
return <div className="user-list-wrapper row">
<div className="col-6">
<Table headerItems={['Username', 'ID']}>
{users.map(user => <TableListEntry
onClick={() => {
navigate(`/users/${user.id}`);
}}
key={user.id}
item={user}
itemKeys={['username', 'id']} />)}
</Table>
<div className='flex is-vertical-align is-center page-controls'>
<button className="button dark" onClick={() => setPage(page - 1 || 1)}>Previous</button>
<p>Page: {page}</p>
<button className="button dark" onClick={() => {
if (users.length === 10) setPage(page + 1);
}}>Next</button>
</div>
</div>
<div className="col-6">
<CreateUserField />
</div>
</div>;
};
return <div className="user-page">
<h4 className="pageTitle">Users</h4>
<h2 className="pageTitle">Users</h2>
{error && <p>{error}</p>}
<div className='user-list card'>
<ErrorBoundary>
<Routes>
<Route path='/:id/*' element={<UserWrapper />} />
<Route path='/' element={<UserListWrapper />} />
</Routes>
</ErrorBoundary>
<div className='card'>
<div className="user-list">
<ErrorBoundary>
<Routes>
<Route path='/:id/*' element={<UserWrapper />} />
<Route path='/' element={<UserListWrapper />} />
</Routes>
</ErrorBoundary>
</div>
</div>
</div>;

35
src/util/ClickDetector.js Normal file
View File

@ -0,0 +1,35 @@
import React, { useEffect, useRef } from "react";
const alerter = (ref, callback) => {
useEffect(() => {
const listener = (event) => {
if (ref.current && !ref.current.contains(event.target)) {
return callback();
}
};
document.addEventListener('mousedown', listener);
return () => {
document.removeEventListener('mousedown', listener);
};
}, [ref]);
};
// Component wrapper to enable listening for clicks outside of the given component
const ClickDetector = ({ children, callback }) => {
const wrapperRef = useRef(null);
alerter(wrapperRef, callback);
return (
<div ref={wrapperRef}>
{children}
</div>
);
};
export default ClickDetector;

View File

@ -57,7 +57,6 @@ export const post = async (url, body) => {
},
body: JSON.stringify(body)
});
console.log(response);
return parseResponse(response);
};