/
Login.tsx
89 lines (82 loc) · 2.79 KB
/
Login.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import { Trans, t } from '@lingui/macro';
import { Center, Container, Paper, Text } from '@mantine/core';
import { useDisclosure, useToggle } from '@mantine/hooks';
import { useEffect } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { setApiDefaults } from '../../App';
import { AuthFormOptions } from '../../components/forms/AuthFormOptions';
import {
AuthenticationForm,
ModeSelector,
RegistrationForm
} from '../../components/forms/AuthenticationForm';
import { InstanceOptions } from '../../components/forms/InstanceOptions';
import { defaultHostKey } from '../../defaults/defaultHostList';
import { checkLoginState } from '../../functions/auth';
import { useServerApiState } from '../../states/ApiState';
import { useLocalState } from '../../states/LocalState';
export default function Login() {
const [hostKey, setHost, hostList] = useLocalState((state) => [
state.hostKey,
state.setHost,
state.hostList
]);
const [server, fetchServerApiState] = useServerApiState((state) => [
state.server,
state.fetchServerApiState
]);
const hostname =
hostList[hostKey] === undefined ? t`No selection` : hostList[hostKey]?.name;
const [hostEdit, setHostEdit] = useToggle([false, true] as const);
const [loginMode, setMode] = useDisclosure(true);
const navigate = useNavigate();
const location = useLocation();
// Data manipulation functions
function ChangeHost(newHost: string): void {
setHost(hostList[newHost]?.host, newHost);
setApiDefaults();
fetchServerApiState();
}
// Set default host to localhost if no host is selected
useEffect(() => {
if (hostKey === '') {
ChangeHost(defaultHostKey);
}
checkLoginState(navigate, location?.state?.redirectFrom, true);
}, []);
// Fetch server data on mount if no server data is present
useEffect(() => {
if (server.server === null) {
fetchServerApiState();
}
}, [server]);
// Main rendering block
return (
<Center mih="100vh">
<Container w="md" miw={400}>
{hostEdit ? (
<InstanceOptions
hostKey={hostKey}
ChangeHost={ChangeHost}
setHostEdit={setHostEdit}
/>
) : (
<>
<Paper radius="md" p="xl" withBorder>
<Text size="lg" weight={500}>
{loginMode ? (
<Trans>Welcome, log in below</Trans>
) : (
<Trans>Register below</Trans>
)}
</Text>
{loginMode ? <AuthenticationForm /> : <RegistrationForm />}
<ModeSelector loginMode={loginMode} setMode={setMode} />
</Paper>
<AuthFormOptions hostname={hostname} toggleHostEdit={setHostEdit} />
</>
)}
</Container>
</Center>
);
}