refactor with component hook pattern

This commit is contained in:
Roland Osborne 2022-03-16 00:21:53 -07:00
parent fa8ac2cfa8
commit 1af1ef807d
15 changed files with 320 additions and 190 deletions

View File

@ -1,6 +1,10 @@
import login from './login.png';
import { AppContextProvider } from './context/AppContext';
import { Root } from './components/Root';
import { AppContextProvider } from './AppContext/AppContext';
import { Home } from './Home/Home';
import { Login } from './Login/Login';
import { Create } from './Create/Create';
import { User } from './User/User';
import { HashRouter as Router, Routes, Route } from "react-router-dom";
import 'antd/dist/antd.css';
function App() {
@ -10,8 +14,15 @@ function App() {
<div style={{ width: '100%', height: '100vh', backgroundColor: '#8fbea7' }}>
<img src={login} alt="" style={{ position: 'absolute', width: '33%', bottom: 0, right: 0 }}/>
</div>
<div style={{ position: 'absolute', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', top: 0, left: 0, width: '100%', height: '100%' }}>
<Root />
<div style={{ position: 'absolute', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', top: 0, left: 0, width: '100%', height: '100%' }}>
<Router>
<Routes>
<Route path="/" element={ <Home /> } />
<Route path="/Login" element={ <Login /> } />
<Route path="/Create" element={ <Create /> } />
<Route path="/User" element={ <User /> } />
</Routes>
</Router>
</div>
</AppContextProvider>
);

View File

@ -4,9 +4,9 @@ import useAppContext from './useAppContext.hook';
export const AppContext = createContext({});
export function AppContextProvider({ children }) {
const state = useAppContext();
const { state, actions } = useAppContext();
return (
<AppContext.Provider value={state}>
<AppContext.Provider value={{ state, actions }}>
{children}
</AppContext.Provider>
);

View File

@ -21,13 +21,13 @@ export async function getAvailable() {
return await available.json()
}
export async function getUsername(name: string) {
export async function getUsername(name) {
let available = await fetchWithTimeout('/account/username?name=' + encodeURIComponent(name), { method: 'GET', timeout: FETCH_TIMEOUT })
checkResponse(available)
return await available.json()
}
export async function setLogin(username: string, password: string) {
export async function setLogin(username, password) {
let headers = new Headers()
headers.append('Authorization', 'Basic ' + base64.encode(username + ":" + password));
let app = { Name: "indicom", Description: "decentralized communication" }
@ -36,7 +36,7 @@ export async function setLogin(username: string, password: string) {
return await login.json()
}
export async function createAccount(username: string, password: string) {
export async function createAccount(username, password) {
let headers = new Headers()
headers.append('Credentials', 'Basic ' + base64.encode(username + ":" + password));
let profile = await fetchWithTimeout("/account/profile", { method: 'POST', timeout: FETCH_TIMEOUT, headers: headers })

View File

@ -2,17 +2,17 @@ import { useEffect, useState, useRef } from 'react';
import { getAvailable, getUsername, setLogin, createAccount } from './fetchUtil';
export default function useAppContext() {
const [state, setState] = useState(null);
const [state, setAppState] = useState(null);
const ws = useRef(null);
const login = async (username: string, password: string) => {
const login = async (username, password) => {
let access = await setLogin(username, password)
setState({ appToken: access, access: 'user', actions: userActions });
setAppState({ appToken: access, access: 'user' });
localStorage.setItem("session", JSON.stringify({ token: access, access: 'user' }));
connectStatus(access);
}
const create = async (username: string, password: string) => {
const create = async (username, password) => {
await createAccount(username, password);
try {
await login(username, password)
@ -23,15 +23,13 @@ export default function useAppContext() {
const logout = () => {
ws.current.onclose = () => {}
ws.current.close(1000, "bye")
ws.current.close()
ws.current = null
setState({ actions: accessActions })
setAppState({ actions: accessActions })
localStorage.removeItem("session");
}
const userActions = {
setListener: setListener,
clearListener: clearListener,
logout: logout,
}
@ -46,7 +44,7 @@ export default function useAppContext() {
available: getAvailable,
}
const connectStatus = (token: string) => {
const connectStatus = (token) => {
ws.current = new WebSocket("wss://" + window.location.host + "/status");
ws.current.onmessage = (ev) => {
console.log(ev)
@ -77,33 +75,34 @@ export default function useAppContext() {
try {
const session = JSON.parse(storage)
if (session?.access === 'admin') {
setState({ appToken: session.token, access: session.access, actions: adminActions })
setAppState({ token: session.token, access: session.access })
connectStatus(session.token);
} else if (session?.access === 'user') {
setState({ appToken: session.token, access: session.access, actions: userActions })
setAppState({ token: session.token, access: session.access })
connectStatus(session.token);
} else {
setState({ actions: accessActions })
setAppState({ })
}
}
catch(err) {
console.log(err)
setState({ actions: accessActions })
setAppState({ actions: accessActions })
}
} else {
setState({ actions: accessActions })
setAppState({ actions: accessActions })
}
}, []);
return state;
}
function setListener(name: string, callback: (objectId: string) => void) {
return
}
function clearListener(callback: (objectId: string) => void) {
return
if (!state) {
return {}
}
if (state.access === 'user') {
return { state, actions: userActions }
}
if (state.access === 'admin') {
return { state, actions: adminActions }
}
return { actions: accessActions }
}

View File

@ -0,0 +1,25 @@
import React, { useContext, useState, useEffect, useRef } from 'react'
import { AppContext } from '../AppContext/AppContext';
import { Input, Button } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { useCreate } from './useCreate.hook';
export function Create() {
const { state, actions } = useCreate()
return (
<div style={{ position: 'absolute', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', top: 0, left: 0, width: '100%', height: '100%' }}>
<div style={{ backgroundColor: '#ffffff', display: 'flex', flexDirection: 'column', padding: '16px', borderRadius: '8px', width: '500px' }}>
<div style={{ textAlign: 'center', fontSize: '24px', fontWeight: 'bold', color: '#555555' }}>indicom</div>
<div style={{ fontSize: '12px', display: 'flex', borderBottom: '1px solid black', color: '#444444', paddingLeft: '16px', paddingRight: '16px' }}>
<span style={{ textAlign: 'center', width: '100%' }}>Communication for the Decentralized Web</span>
</div>
<Input size="large" spellCheck="false" addonAfter={state.conflict} onChange={(e) => actions.setUsername(e.target.value)} value={state.username} placeholder="username" prefix={<UserOutlined />} style={{ marginTop: '16px' }} />
<Input.Password size="large" spellCheck="false" onChange={(e) => actions.setPassword(e.target.value)} value={state.password} placeholder="password" prefix={<LockOutlined />} style={{ marginTop: '16px' }} />
<Input.Password size="large" spellCheck="false" onChange={(e) => actions.setConfirmed(e.target.value)} value={state.confirmed} placeholder="password" prefix={<LockOutlined />} style={{ marginTop: '16px' }} />
<Button type="primary" onClick={() => actions.onCreate()} disabled={actions.isDisabled()} style={{ alignSelf: 'center', marginTop: '16px', width: '33%' }}>Create Account</Button>
</div>
<Button type="link" onClick={() => actions.onLogin()} style={{ marginTop: '4px' }}>Account Sign In</Button>
</div>
)
}

View File

@ -0,0 +1,89 @@
import { useContext, useState, useEffect, useRef } from 'react';
import { AppContext } from '../AppContext/AppContext';
import { useNavigate } from "react-router-dom";
export function useCreate() {
const [checked, setChecked] = useState(true)
const [conflict, setConflict] = useState('')
const [state, setState] = useState({
username: '',
password: '',
confirmed: '',
conflict: '',
});
const navigate = useNavigate();
const app = useContext(AppContext);
const debounce = useRef(null)
const actions = {
setUsername: (username) => {
actions.updateState({ username });
usernameSet(username)
},
setPassword: (password) => {
actions.updateState({ password });
},
setConfirmed: (confirmed) => {
actions.updateState({ confirmed });
},
isDisabled: () => {
if (state.username != '' && state.password != '' && state.password == state.confirmed &&
checked && state.conflict == '') {
return false
}
return true
},
onLogin: async () => {
navigate('/login')
},
onCreate: async () => {
try {
app.actions.create(state.username, state.password)
}
catch (err) {
window.alert(err);
}
},
updateState: (value) => {
setState((s) => ({ ...s, ...value }));
},
};
const usernameSet = (name) => {
setChecked(false)
clearTimeout(debounce.current)
debounce.current = setTimeout(async () => {
if (app.actions && app.actions.username) {
if (name == '') {
setChecked(true)
actions.updateState({ conflict: '' })
}
else {
let valid = await app.actions.username(name)
setChecked(true)
if (!valid) {
actions.updateState({ conflict: 'not available' })
} else {
actions.updateState({ conflict: '' })
}
}
}
}, 500)
}
useEffect(() => {
if (app) {
if (app.state) {
if (app.state.access == 'user') {
navigate('/user')
}
if (app.state.access == 'admin') {
navigate('/admin')
}
}
}
}, [app])
return { state, actions };
}

27
net/web/src/Home/Home.jsx Normal file
View File

@ -0,0 +1,27 @@
import React, { useContext, useState, useEffect, useRef } from 'react'
import { useNavigate } from "react-router-dom";
import { HashRouter as Router, Routes, Route } from "react-router-dom";
import { AppContext } from '../AppContext/AppContext';
export function Home() {
const navigate = useNavigate();
const app = useContext(AppContext);
useEffect(() => {
if (app) {
if (app.state == null) {
navigate('/login')
}
else if (app.state.access === 'user') {
navigate('/user')
}
else if (app.state.access === 'admin') {
navigate('/admin')
}
}
}, [])
return <></>
}

View File

@ -0,0 +1,24 @@
import React, { useContext, useState, useEffect, useRef } from 'react'
import { AppContext } from '../AppContext/AppContext';
import { Input, Button } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { useLogin } from './useLogin.hook';
export function Login() {
const { state, actions } = useLogin()
return (
<div style={{ position: 'absolute', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', top: 0, left: 0, width: '100%', height: '100%' }}>
<div style={{ backgroundColor: '#ffffff', display: 'flex', flexDirection: 'column', padding: '16px', borderRadius: '8px', width: '500px' }}>
<div style={{ textAlign: 'center', fontSize: '24px', fontWeight: 'bold', color: '#555555' }}>indicom</div>
<div style={{ fontSize: '12px', display: 'flex', borderBottom: '1px solid black', color: '#444444', paddingLeft: '16px', paddingRight: '16px' }}>
<span style={{ textAlign: 'center', width: '100%' }}>Communication for the Decentralized Web</span>
</div>
<Input size="large" spellCheck="false" onChange={(e) => actions.setUsername(e.target.value)} value={state.username} placeholder="username" prefix={<UserOutlined />} style={{ marginTop: '16px' }} />
<Input.Password spellCheck="false" size="large" onChange={(e) => actions.setPassword(e.target.value)} value={state.password} placeholder="password" prefix={<LockOutlined />} style={{ marginTop: '16px' }} />
<Button type="primary" spellCheck="false" onClick={() => actions.onLogin()} disabled={actions.isDisabled()} style={{ alignSelf: 'center', marginTop: '16px', width: '33%' }}>Sign In</Button>
</div>
<Button type="link" onClick={() => actions.onCreate()} disabled={!state.available} style={{ marginTop: '4px' }}>Create Account</Button>
</div>
)
}

View File

@ -0,0 +1,66 @@
import { useContext, useState, useEffect } from 'react';
import { AppContext } from '../AppContext/AppContext';
import { useNavigate } from "react-router-dom";
export function useLogin() {
const [state, setState] = useState({
username: '',
password: '',
available: false,
});
const navigate = useNavigate();
const app = useContext(AppContext);
const actions = {
setUsername: (username) => {
actions.updateState({ username });
},
setPassword: (password) => {
actions.updateState({ password });
},
isDisabled: () => {
if (state.username === '' || state.password === '') {
return true
}
return false
},
onLogin: async () => {
try {
await app.actions.login(state.username, state.password)
}
catch (err) {
window.alert(err)
}
},
onCreate: () => {
navigate('/create')
},
updateState: (value) => {
setState((s) => ({ ...s, ...value }));
},
};
useEffect(() => {
if (app) {
if (app.state) {
if (app.state.access == 'user') {
navigate('/user')
}
if (app.state.access == 'admin') {
navigate('/admin')
}
}
if (app.actions && app.actions.available) {
const count = async () => {
const available = await app.actions.available()
actions.updateState({ available: available != 0 })
}
count();
}
}
}, [app])
return { state, actions };
}

14
net/web/src/User/User.jsx Normal file
View File

@ -0,0 +1,14 @@
import React, { useContext, useState, useEffect, useRef } from 'react'
import { useNavigate } from "react-router-dom";
import { HashRouter as Router, Routes, Route } from "react-router-dom";
import { AppContext } from '../AppContext/AppContext';
import { useUser } from './useUser.hook';
import { Input, Button } from 'antd';
export function User() {
const { state, actions } = useUser()
return <Button type="primary" onClick={() => actions.onLogout()} style={{ alignSelf: 'center', marginTop: '16px', width: '33%' }}>Sign Out</Button>
}

View File

@ -0,0 +1,33 @@
import { useContext, useState, useEffect } from 'react';
import { AppContext } from '../AppContext/AppContext';
import { useNavigate } from "react-router-dom";
export function useUser() {
const [state, setState] = useState({});
const navigate = useNavigate();
const app = useContext(AppContext);
const actions = {
onLogout: async () => {
app.actions.logout()
},
updateState: (value) => {
setState((s) => ({ ...s, ...value }));
},
};
useEffect(() => {
if (app) {
if (app.state == null) {
navigate('/')
}
else if (app.state.access == 'admin') {
navigate('/admin')
}
}
}, [app])
return { state, actions };
}

View File

@ -1,106 +0,0 @@
import React, { useContext, useState, useEffect, useRef } from 'react'
import { useNavigate } from "react-router-dom";
import { AppContext } from '../context/AppContext';
import { Input, Button } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
export function Access() {
const [available, setAvailable] = useState(false)
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [confirmed, setConfirmed] = useState('')
const [creatable, setCreatable] = useState(false)
const [conflict, setConflict] = useState('')
const [loginMode, setLoginMode] = useState(true);
const [context, setContext] = useState(false);
const appContext = useContext(AppContext);
const navigate = useNavigate();
const debounce = useRef(null)
useEffect(() => {
console.log(appContext)
if (appContext) {
if (appContext.access === 'admin') {
navigate("/admin")
} else if (appContext.access === 'user') {
navigate("/user")
} else {
setContext(true)
appContext.actions.available().then(a => {
setAvailable(a > 0)
}).catch(err => {
console.log(err)
})
}
}
}, [appContext, navigate])
const usernameSet = (name) => {
setCreatable(false)
setUsername(name)
clearTimeout(debounce.current)
debounce.current = setTimeout(async () => {
let valid = await appContext.actions.username(name)
setCreatable(valid)
if (!valid) {
setConflict('not available')
} else {
setConflict('')
}
}, 500)
}
const onLogin = async () => {
try {
await appContext.actions.login(username, password)
} catch(err) {
window.alert(err)
}
}
const onCreate = async () => {
try {
await appContext.actions.create(username, password)
}
catch(err) {
window.alert(err)
}
}
if (context && loginMode) {
return (
<div style={{ position: 'absolute', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', top: 0, left: 0, width: '100%', height: '100%' }}>
<div style={{ backgroundColor: '#ffffff', display: 'flex', flexDirection: 'column', padding: '16px', borderRadius: '8px', width: '500px' }}>
<div style={{ textAlign: 'center', fontSize: '24px', fontWeight: 'bold', color: '#555555' }}>indicom</div>
<div style={{ fontSize: '12px', display: 'flex', borderBottom: '1px solid black', color: '#444444', paddingLeft: '16px', paddingRight: '16px' }}>
<span style={{ textAlign: 'center', width: '100%' }}>Communication for the Decentralized Web</span>
</div>
<Input size="large" spellCheck="false" onChange={(e) => usernameSet(e.target.value)} value={username} placeholder="username" prefix={<UserOutlined />} style={{ marginTop: '16px' }} />
<Input.Password size="large" onChange={(e) => setPassword(e.target.value)} value={password} placeholder="password" prefix={<LockOutlined />} style={{ marginTop: '16px' }} />
<Button type="primary" onClick={onLogin} disabled={username===''||password===''} style={{ alignSelf: 'center', marginTop: '16px', width: '33%' }}>Sign In</Button>
</div>
<Button type="link" onClick={() => setLoginMode(false)} disabled={!available} style={{ marginTop: '4px' }}>Create Account</Button>
</div>
)
}
if (context && !loginMode) {
return (
<div style={{ position: 'absolute', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', top: 0, left: 0, width: '100%', height: '100%' }}>
<div style={{ backgroundColor: '#ffffff', display: 'flex', flexDirection: 'column', padding: '16px', borderRadius: '8px', width: '500px' }}>
<div style={{ textAlign: 'center', fontSize: '24px', fontWeight: 'bold', color: '#555555' }}>indicom</div>
<div style={{ fontSize: '12px', display: 'flex', borderBottom: '1px solid black', color: '#444444', paddingLeft: '16px', paddingRight: '16px' }}>
<span style={{ textAlign: 'center', width: '100%' }}>Communication for the Decentralized Web</span>
</div>
<Input size="large" spellCheck="false" addonAfter={conflict} onChange={(e) => usernameSet(e.target.value)} value={username} placeholder="username" prefix={<UserOutlined />} style={{ marginTop: '16px' }} />
<Input.Password size="large" onChange={(e) => setPassword(e.target.value)} value={password} placeholder="password" prefix={<LockOutlined />} style={{ marginTop: '16px' }} />
<Input.Password size="large" onChange={(e) => setConfirmed(e.target.value)} value={confirmed} placeholder="confirm password" prefix={<LockOutlined />} style={{ marginTop: '16px' }} />
<Button type="primary" onClick={onCreate} disabled={username===''||password===''||confirmed!==password||!creatable} style={{ alignSelf: 'center', marginTop: '16px', width: '33%' }}>Create Account</Button>
</div>
<Button type="link" onClick={() => setLoginMode(true)} style={{ marginTop: '4px' }}>Account Sign In</Button>
</div>
)
}
return <></>
}

View File

@ -1,4 +0,0 @@
export function Admin() {
return <div>ADMIN</div>
}

View File

@ -1,19 +0,0 @@
import { HashRouter as Router, Routes, Route } from "react-router-dom";
import { Access } from './Access';
import { Admin } from './Admin';
import { User } from './User';
import 'antd/dist/antd.css';
export function Root() {
return (
<Router>
<Routes>
<Route path="/" element={ <Access /> } />
<Route path="/admin" element={ <Admin /> } />
<Route path="/user" element={ <User /> } />
</Routes>
</Router>
)
}

View File

@ -1,29 +0,0 @@
import React, { useContext, useState, useEffect } from 'react'
import { useNavigate } from "react-router-dom";
import { AppContext } from '../context/AppContext';
import { Button } from 'antd';
export function User() {
const [context, setContext] = useState(false)
const appContext = useContext(AppContext);
const navigate = useNavigate();
useEffect(() => {
if (appContext) {
if (appContext.access !== 'user') {
navigate("/")
}
setContext(true)
}
}, [appContext, navigate])
const onLogout = () => {
appContext.actions.logout()
}
if (context) {
return <Button type="link" onClick={() => onLogout()} style={{ marginTop: '4px' }}>Sign Out User</Button>
}
return <></>
}