fix: migrate most components to functional components

Co-authored-by: Matthias Fechner <matthias@fechner.net>
This commit is contained in:
Jannis Mattheis 2025-08-03 21:38:53 +02:00
parent 734113d187
commit 0ca5156fed
21 changed files with 1397 additions and 1622 deletions

View File

@ -7,41 +7,29 @@ import DialogTitle from '@mui/material/DialogTitle';
import TextField from '@mui/material/TextField'; import TextField from '@mui/material/TextField';
import Tooltip from '@mui/material/Tooltip'; import Tooltip from '@mui/material/Tooltip';
import {NumberField} from '../common/NumberField'; import {NumberField} from '../common/NumberField';
import React, {Component} from 'react'; import React, {useState} from 'react';
interface IProps { interface IProps {
fClose: VoidFunction; fClose: VoidFunction;
fOnSubmit: (name: string, description: string, defaultPriority: number) => void; fOnSubmit: (name: string, description: string, defaultPriority: number) => Promise<void>;
} }
interface IState { export const AddApplicationDialog = ({fClose, fOnSubmit}: IProps) => {
name: string; const [name, setName] = useState('');
description: string; const [description, setDescription] = useState('');
defaultPriority: number; const [defaultPriority, setDefaultPriority] = useState(0);
}
export default class AddDialog extends Component<IProps, IState> { const submitEnabled = name.length !== 0;
public state = {name: '', description: '', defaultPriority: 0}; const submitAndClose = async () => {
await fOnSubmit(name, description, defaultPriority);
public render() {
const {fClose, fOnSubmit} = this.props;
const {name, description, defaultPriority} = this.state;
const submitEnabled = this.state.name.length !== 0;
const submitAndClose = () => {
fOnSubmit(name, description, defaultPriority);
fClose(); fClose();
}; };
return ( return (
<Dialog <Dialog open={true} onClose={fClose} aria-labelledby="form-dialog-title" id="app-dialog">
open={true}
onClose={fClose}
aria-labelledby="form-dialog-title"
id="app-dialog">
<DialogTitle id="form-dialog-title">Create an application</DialogTitle> <DialogTitle id="form-dialog-title">Create an application</DialogTitle>
<DialogContent> <DialogContent>
<DialogContentText> <DialogContentText>An application is allowed to send messages.</DialogContentText>
An application is allowed to send messages.
</DialogContentText>
<TextField <TextField
autoFocus autoFocus
margin="dense" margin="dense"
@ -49,7 +37,7 @@ export default class AddDialog extends Component<IProps, IState> {
label="Name *" label="Name *"
type="text" type="text"
value={name} value={name}
onChange={this.handleChange.bind(this, 'name')} onChange={(e) => setName(e.target.value)}
fullWidth fullWidth
/> />
<TextField <TextField
@ -57,7 +45,7 @@ export default class AddDialog extends Component<IProps, IState> {
className="description" className="description"
label="Short Description" label="Short Description"
value={description} value={description}
onChange={this.handleChange.bind(this, 'description')} onChange={(e) => setDescription(e.target.value)}
fullWidth fullWidth
multiline multiline
/> />
@ -66,7 +54,7 @@ export default class AddDialog extends Component<IProps, IState> {
className="priority" className="priority"
label="Default Priority" label="Default Priority"
value={defaultPriority} value={defaultPriority}
onChange={(value) => this.setState({defaultPriority: value})} onChange={(value) => setDefaultPriority(value)}
fullWidth fullWidth
/> />
</DialogContent> </DialogContent>
@ -87,14 +75,4 @@ export default class AddDialog extends Component<IProps, IState> {
</DialogActions> </DialogActions>
</Dialog> </Dialog>
); );
} };
private handleChange(
propertyName: 'description' | 'name',
event: React.ChangeEvent<HTMLInputElement>
) {
const state = this.state;
state[propertyName] = event.target.value;
this.setState(state);
}
}

View File

@ -1,3 +1,4 @@
import React, {ChangeEvent, useEffect, useRef, useState} from 'react';
import Grid from '@mui/material/Grid'; import Grid from '@mui/material/Grid';
import IconButton from '@mui/material/IconButton'; import IconButton from '@mui/material/IconButton';
import Paper from '@mui/material/Paper'; import Paper from '@mui/material/Paper';
@ -9,42 +10,50 @@ import TableRow from '@mui/material/TableRow';
import Delete from '@mui/icons-material/Delete'; import Delete from '@mui/icons-material/Delete';
import Edit from '@mui/icons-material/Edit'; import Edit from '@mui/icons-material/Edit';
import CloudUpload from '@mui/icons-material/CloudUpload'; import CloudUpload from '@mui/icons-material/CloudUpload';
import React, {ChangeEvent, Component, SFC} from 'react'; import Button from '@mui/material/Button';
import ConfirmDialog from '../common/ConfirmDialog'; import ConfirmDialog from '../common/ConfirmDialog';
import DefaultPage from '../common/DefaultPage'; import DefaultPage from '../common/DefaultPage';
import Button from '@mui/material/Button';
import CopyableSecret from '../common/CopyableSecret'; import CopyableSecret from '../common/CopyableSecret';
import AddApplicationDialog from './AddApplicationDialog'; import {AddApplicationDialog} from './AddApplicationDialog';
import {observer} from 'mobx-react';
import {observable} from 'mobx';
import {inject, Stores} from '../inject';
import * as config from '../config'; import * as config from '../config';
import UpdateDialog from './UpdateApplicationDialog'; import {UpdateApplicationDialog} from './UpdateApplicationDialog';
import {IApplication} from '../types'; import {IApplication} from '../types';
import {LastUsedCell} from '../common/LastUsedCell'; import {LastUsedCell} from '../common/LastUsedCell';
import {useStores} from '../stores';
import {observer} from 'mobx-react-lite';
@observer const Applications = observer(() => {
class Applications extends Component<Stores<'appStore'>> { const {appStore} = useStores();
@observable
private deleteId: number | false = false;
@observable
private updateId: number | false = false;
@observable
private createDialog = false;
private uploadId = -1;
private upload: HTMLInputElement | null = null;
public componentDidMount = () => this.props.appStore.refresh();
public render() {
const {
createDialog,
deleteId,
updateId,
props: {appStore},
} = this;
const apps = appStore.getItems(); const apps = appStore.getItems();
const [toDeleteApp, setToDeleteApp] = useState<IApplication>();
const [toUpdateApp, setToUpdateApp] = useState<IApplication>();
const [createDialog, setCreateDialog] = useState<boolean>(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const uploadId = useRef(-1);
useEffect(() => void appStore.refresh(), []);
const handleImageUploadClick = (id: number) => {
uploadId.current = id;
if (fileInputRef.current) {
fileInputRef.current.click();
}
};
const onUploadImage = (e: ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) {
return;
}
if (['image/png', 'image/jpeg', 'image/gif'].indexOf(file.type) !== -1) {
appStore.uploadImage(uploadId.current, file);
} else {
alert('Uploaded file must be of type png, jpeg or gif.');
}
};
return ( return (
<DefaultPage <DefaultPage
title="Applications" title="Applications"
@ -53,12 +62,12 @@ class Applications extends Component<Stores<'appStore'>> {
id="create-app" id="create-app"
variant="contained" variant="contained"
color="primary" color="primary"
onClick={() => (this.createDialog = true)}> onClick={() => setCreateDialog(true)}>
Create Application Create Application
</Button> </Button>
} }
maxWidth={1000}> maxWidth={1000}>
<Grid size={{xs: 12}}> <Grid size={12}>
<Paper elevation={6} style={{overflowX: 'auto'}}> <Paper elevation={6} style={{overflowX: 'auto'}}>
<Table id="app-table"> <Table id="app-table">
<TableHead> <TableHead>
@ -83,70 +92,50 @@ class Applications extends Component<Stores<'appStore'>> {
name={app.name} name={app.name}
value={app.token} value={app.token}
lastUsed={app.lastUsed} lastUsed={app.lastUsed}
fUpload={() => this.uploadImage(app.id)} fUpload={() => handleImageUploadClick(app.id)}
fDelete={() => (this.deleteId = app.id)} fDelete={() => setToDeleteApp(app)}
fEdit={() => (this.updateId = app.id)} fEdit={() => setToUpdateApp(app)}
noDelete={app.internal} noDelete={app.internal}
/> />
))} ))}
</TableBody> </TableBody>
</Table> </Table>
<input <input
ref={(upload) => (this.upload = upload)} ref={fileInputRef}
type="file" type="file"
style={{display: 'none'}} style={{display: 'none'}}
onChange={this.onUploadImage} onChange={onUploadImage}
/> />
</Paper> </Paper>
</Grid> </Grid>
{createDialog && ( {createDialog && (
<AddApplicationDialog <AddApplicationDialog
fClose={() => (this.createDialog = false)} fClose={() => setCreateDialog(false)}
fOnSubmit={appStore.create} fOnSubmit={appStore.create}
/> />
)} )}
{updateId !== false && ( {toUpdateApp != null && (
<UpdateDialog <UpdateApplicationDialog
fClose={() => (this.updateId = false)} fClose={() => setToUpdateApp(undefined)}
fOnSubmit={(name, description, defaultPriority) => fOnSubmit={(name, description, defaultPriority) =>
appStore.update(updateId, name, description, defaultPriority) appStore.update(toUpdateApp.id, name, description, defaultPriority)
} }
initialDescription={appStore.getByID(updateId).description} initialDescription={toUpdateApp?.description}
initialName={appStore.getByID(updateId).name} initialName={toUpdateApp?.name}
initialDefaultPriority={appStore.getByID(updateId).defaultPriority} initialDefaultPriority={toUpdateApp?.defaultPriority}
/> />
)} )}
{deleteId !== false && ( {toDeleteApp != null && (
<ConfirmDialog <ConfirmDialog
title="Confirm Delete" title="Confirm Delete"
text={'Delete ' + appStore.getByID(deleteId).name + '?'} text={'Delete ' + toDeleteApp.name + '?'}
fClose={() => (this.deleteId = false)} fClose={() => setToDeleteApp(undefined)}
fOnSubmit={() => appStore.remove(deleteId)} fOnSubmit={() => appStore.remove(toDeleteApp.id)}
/> />
)} )}
</DefaultPage> </DefaultPage>
); );
} });
private uploadImage = (id: number) => {
this.uploadId = id;
if (this.upload) {
this.upload.click();
}
};
private onUploadImage = (e: ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) {
return;
}
if (['image/png', 'image/jpeg', 'image/gif'].indexOf(file.type) !== -1) {
this.props.appStore.uploadImage(this.uploadId, file);
} else {
alert('Uploaded file must be of type png, jpeg or gif.');
}
};
}
interface IRowProps { interface IRowProps {
name: string; name: string;
@ -161,8 +150,7 @@ interface IRowProps {
fEdit: VoidFunction; fEdit: VoidFunction;
} }
const Row: SFC<IRowProps> = observer( const Row = ({
({
name, name,
value, value,
noDelete, noDelete,
@ -173,12 +161,13 @@ const Row: SFC<IRowProps> = observer(
fUpload, fUpload,
image, image,
fEdit, fEdit,
}) => ( }: IRowProps) => {
return (
<TableRow> <TableRow>
<TableCell padding="normal"> <TableCell padding="normal">
<div style={{display: 'flex'}}> <div style={{display: 'flex'}}>
<img src={config.get('url') + image} alt="app logo" width="40" height="40" /> <img src={config.get('url') + image} alt="app logo" width="40" height="40" />
<IconButton onClick={fUpload} style={{height: 40}} size="large"> <IconButton onClick={fUpload} style={{height: 40}}>
<CloudUpload /> <CloudUpload />
</IconButton> </IconButton>
</div> </div>
@ -193,17 +182,17 @@ const Row: SFC<IRowProps> = observer(
<LastUsedCell lastUsed={lastUsed} /> <LastUsedCell lastUsed={lastUsed} />
</TableCell> </TableCell>
<TableCell align="right" padding="none"> <TableCell align="right" padding="none">
<IconButton onClick={fEdit} className="edit" size="large"> <IconButton onClick={fEdit} className="edit">
<Edit /> <Edit />
</IconButton> </IconButton>
</TableCell> </TableCell>
<TableCell align="right" padding="none"> <TableCell align="right" padding="none">
<IconButton onClick={fDelete} className="delete" disabled={noDelete} size="large"> <IconButton onClick={fDelete} className="delete" disabled={noDelete}>
<Delete /> <Delete />
</IconButton> </IconButton>
</TableCell> </TableCell>
</TableRow> </TableRow>
) );
); };
export default inject('appStore')(Applications); export default Applications;

View File

@ -7,53 +7,38 @@ import DialogTitle from '@mui/material/DialogTitle';
import TextField from '@mui/material/TextField'; import TextField from '@mui/material/TextField';
import Tooltip from '@mui/material/Tooltip'; import Tooltip from '@mui/material/Tooltip';
import {NumberField} from '../common/NumberField'; import {NumberField} from '../common/NumberField';
import React, {Component} from 'react'; import React, {useState} from 'react';
interface IProps { interface IProps {
fClose: VoidFunction; fClose: VoidFunction;
fOnSubmit: (name: string, description: string, defaultPriority: number) => void; fOnSubmit: (name: string, description: string, defaultPriority: number) => Promise<void>;
initialName: string; initialName: string;
initialDescription: string; initialDescription: string;
initialDefaultPriority: number; initialDefaultPriority: number;
} }
interface IState { export const UpdateApplicationDialog = ({
name: string; initialName,
description: string; initialDescription,
defaultPriority: number; initialDefaultPriority,
} fClose,
fOnSubmit,
}: IProps) => {
const [name, setName] = useState(initialName);
const [description, setDescription] = useState(initialDescription);
const [defaultPriority, setDefaultPriority] = useState(initialDefaultPriority);
export default class UpdateDialog extends Component<IProps, IState> { const submitEnabled = name.length !== 0;
public state = {name: '', description: '', defaultPriority: 0}; const submitAndClose = async () => {
await fOnSubmit(name, description, defaultPriority);
constructor(props: IProps) {
super(props);
this.state = {
name: props.initialName,
description: props.initialDescription,
defaultPriority: props.initialDefaultPriority,
};
}
public render() {
const {fClose, fOnSubmit} = this.props;
const {name, description, defaultPriority} = this.state;
const submitEnabled = this.state.name.length !== 0;
const submitAndClose = () => {
fOnSubmit(name, description, defaultPriority);
fClose(); fClose();
}; };
return ( return (
<Dialog <Dialog open={true} onClose={fClose} aria-labelledby="form-dialog-title" id="app-dialog">
open={true}
onClose={fClose}
aria-labelledby="form-dialog-title"
id="app-dialog">
<DialogTitle id="form-dialog-title">Update an application</DialogTitle> <DialogTitle id="form-dialog-title">Update an application</DialogTitle>
<DialogContent> <DialogContent>
<DialogContentText> <DialogContentText>An application is allowed to send messages.</DialogContentText>
An application is allowed to send messages.
</DialogContentText>
<TextField <TextField
autoFocus autoFocus
margin="dense" margin="dense"
@ -61,7 +46,7 @@ export default class UpdateDialog extends Component<IProps, IState> {
label="Name *" label="Name *"
type="text" type="text"
value={name} value={name}
onChange={this.handleChange.bind(this, 'name')} onChange={(e) => setName(e.target.value)}
fullWidth fullWidth
/> />
<TextField <TextField
@ -69,7 +54,7 @@ export default class UpdateDialog extends Component<IProps, IState> {
className="description" className="description"
label="Short Description" label="Short Description"
value={description} value={description}
onChange={this.handleChange.bind(this, 'description')} onChange={(e) => setDescription(e.target.value)}
fullWidth fullWidth
multiline multiline
/> />
@ -78,7 +63,7 @@ export default class UpdateDialog extends Component<IProps, IState> {
className="priority" className="priority"
label="Default Priority" label="Default Priority"
value={defaultPriority} value={defaultPriority}
onChange={(value) => this.setState({defaultPriority: value})} onChange={(e) => setDefaultPriority(e)}
fullWidth fullWidth
/> />
</DialogContent> </DialogContent>
@ -99,14 +84,4 @@ export default class UpdateDialog extends Component<IProps, IState> {
</DialogActions> </DialogActions>
</Dialog> </Dialog>
); );
} };
private handleChange(
propertyName: 'name' | 'description',
event: React.ChangeEvent<HTMLInputElement>
) {
const state = this.state;
state[propertyName] = event.target.value;
this.setState(state);
}
}

View File

@ -1,3 +1,4 @@
import React, {useState} from 'react';
import Button from '@mui/material/Button'; import Button from '@mui/material/Button';
import Dialog from '@mui/material/Dialog'; import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions'; import DialogActions from '@mui/material/DialogActions';
@ -5,30 +6,23 @@ import DialogContent from '@mui/material/DialogContent';
import DialogTitle from '@mui/material/DialogTitle'; import DialogTitle from '@mui/material/DialogTitle';
import TextField from '@mui/material/TextField'; import TextField from '@mui/material/TextField';
import Tooltip from '@mui/material/Tooltip'; import Tooltip from '@mui/material/Tooltip';
import React, {Component} from 'react';
interface IProps { interface IProps {
fClose: VoidFunction; fClose: VoidFunction;
fOnSubmit: (name: string) => void; fOnSubmit: (name: string) => Promise<void>;
} }
export default class AddDialog extends Component<IProps, {name: string}> { const AddClientDialog = ({fClose, fOnSubmit}: IProps) => {
public state = {name: ''}; const [name, setName] = useState('');
public render() { const submitEnabled = name.length !== 0;
const {fClose, fOnSubmit} = this.props; const submitAndClose = async () => {
const {name} = this.state; await fOnSubmit(name);
const submitEnabled = this.state.name.length !== 0;
const submitAndClose = () => {
fOnSubmit(name);
fClose(); fClose();
}; };
return ( return (
<Dialog <Dialog open={true} onClose={fClose} aria-labelledby="form-dialog-title" id="client-dialog">
open={true}
onClose={fClose}
aria-labelledby="form-dialog-title"
id="client-dialog">
<DialogTitle id="form-dialog-title">Create a client</DialogTitle> <DialogTitle id="form-dialog-title">Create a client</DialogTitle>
<DialogContent> <DialogContent>
<TextField <TextField
@ -38,15 +32,13 @@ export default class AddDialog extends Component<IProps, {name: string}> {
label="Name *" label="Name *"
type="email" type="email"
value={name} value={name}
onChange={this.handleChange.bind(this, 'name')} onChange={(e) => setName(e.target.value)}
fullWidth fullWidth
/> />
</DialogContent> </DialogContent>
<DialogActions> <DialogActions>
<Button onClick={fClose}>Cancel</Button> <Button onClick={fClose}>Cancel</Button>
<Tooltip <Tooltip placement={'bottom-start'} title={submitEnabled ? '' : 'name is required'}>
placement={'bottom-start'}
title={submitEnabled ? '' : 'name is required'}>
<div> <div>
<Button <Button
className="create" className="create"
@ -61,11 +53,6 @@ export default class AddDialog extends Component<IProps, {name: string}> {
</DialogActions> </DialogActions>
</Dialog> </Dialog>
); );
} };
private handleChange(propertyName: 'name', event: React.ChangeEvent<HTMLInputElement>) { export default AddClientDialog;
const state = this.state;
state[propertyName] = event.target.value;
this.setState(state);
}
}

View File

@ -1,3 +1,4 @@
import React, {useEffect, useState} from 'react';
import Grid from '@mui/material/Grid'; import Grid from '@mui/material/Grid';
import IconButton from '@mui/material/IconButton'; import IconButton from '@mui/material/IconButton';
import Paper from '@mui/material/Paper'; import Paper from '@mui/material/Paper';
@ -8,39 +9,26 @@ import TableHead from '@mui/material/TableHead';
import TableRow from '@mui/material/TableRow'; import TableRow from '@mui/material/TableRow';
import Delete from '@mui/icons-material/Delete'; import Delete from '@mui/icons-material/Delete';
import Edit from '@mui/icons-material/Edit'; import Edit from '@mui/icons-material/Edit';
import React, {Component, SFC} from 'react'; import Button from '@mui/material/Button';
import ConfirmDialog from '../common/ConfirmDialog'; import ConfirmDialog from '../common/ConfirmDialog';
import DefaultPage from '../common/DefaultPage'; import DefaultPage from '../common/DefaultPage';
import Button from '@mui/material/Button';
import AddClientDialog from './AddClientDialog'; import AddClientDialog from './AddClientDialog';
import UpdateDialog from './UpdateClientDialog'; import UpdateClientDialog from './UpdateClientDialog';
import {observer} from 'mobx-react';
import {observable} from 'mobx';
import {inject, Stores} from '../inject';
import {IClient} from '../types'; import {IClient} from '../types';
import CopyableSecret from '../common/CopyableSecret'; import CopyableSecret from '../common/CopyableSecret';
import {LastUsedCell} from '../common/LastUsedCell'; import {LastUsedCell} from '../common/LastUsedCell';
import {observer} from 'mobx-react';
import {useStores} from '../stores';
@observer const Clients = observer(() => {
class Clients extends Component<Stores<'clientStore'>> { const {clientStore} = useStores();
@observable const [toDeleteClient, setToDeleteClient] = useState<IClient>();
private showDialog = false; const [toUpdateClient, setToUpdateClient] = useState<IClient>();
@observable const [createDialog, setCreateDialog] = useState<boolean>(false);
private deleteId: false | number = false;
@observable
private updateId: false | number = false;
public componentDidMount = () => this.props.clientStore.refresh();
public render() {
const {
deleteId,
updateId,
showDialog,
props: {clientStore},
} = this;
const clients = clientStore.getItems(); const clients = clientStore.getItems();
useEffect(() => void clientStore.refresh(), []);
return ( return (
<DefaultPage <DefaultPage
title="Clients" title="Clients"
@ -49,11 +37,11 @@ class Clients extends Component<Stores<'clientStore'>> {
id="create-client" id="create-client"
variant="contained" variant="contained"
color="primary" color="primary"
onClick={() => (this.showDialog = true)}> onClick={() => setCreateDialog(true)}>
Create Client Create Client
</Button> </Button>
}> }>
<Grid size={{xs: 12}}> <Grid size={12}>
<Paper elevation={6} style={{overflowX: 'auto'}}> <Paper elevation={6} style={{overflowX: 'auto'}}>
<Table id="client-table"> <Table id="client-table">
<TableHead> <TableHead>
@ -72,39 +60,38 @@ class Clients extends Component<Stores<'clientStore'>> {
name={client.name} name={client.name}
value={client.token} value={client.token}
lastUsed={client.lastUsed} lastUsed={client.lastUsed}
fEdit={() => (this.updateId = client.id)} fEdit={() => setToUpdateClient(client)}
fDelete={() => (this.deleteId = client.id)} fDelete={() => setToDeleteClient(client)}
/> />
))} ))}
</TableBody> </TableBody>
</Table> </Table>
</Paper> </Paper>
</Grid> </Grid>
{showDialog && ( {createDialog && (
<AddClientDialog <AddClientDialog
fClose={() => (this.showDialog = false)} fClose={() => setCreateDialog(false)}
fOnSubmit={clientStore.create} fOnSubmit={clientStore.create}
/> />
)} )}
{updateId !== false && ( {toUpdateClient != null && (
<UpdateDialog <UpdateClientDialog
fClose={() => (this.updateId = false)} fClose={() => setToUpdateClient(undefined)}
fOnSubmit={(name) => clientStore.update(updateId, name)} fOnSubmit={(name) => clientStore.update(toUpdateClient.id, name)}
initialName={clientStore.getByID(updateId).name} initialName={toUpdateClient.name}
/> />
)} )}
{deleteId !== false && ( {toDeleteClient != null && (
<ConfirmDialog <ConfirmDialog
title="Confirm Delete" title="Confirm Delete"
text={'Delete ' + clientStore.getByID(deleteId).name + '?'} text={'Delete ' + toDeleteClient.name + '?'}
fClose={() => (this.deleteId = false)} fClose={() => setToDeleteClient(undefined)}
fOnSubmit={() => clientStore.remove(deleteId)} fOnSubmit={() => clientStore.remove(toDeleteClient.id)}
/> />
)} )}
</DefaultPage> </DefaultPage>
); );
} });
}
interface IRowProps { interface IRowProps {
name: string; name: string;
@ -114,7 +101,7 @@ interface IRowProps {
fDelete: VoidFunction; fDelete: VoidFunction;
} }
const Row: SFC<IRowProps> = ({name, value, lastUsed, fEdit, fDelete}) => ( const Row = ({name, value, lastUsed, fEdit, fDelete}: IRowProps) => (
<TableRow> <TableRow>
<TableCell>{name}</TableCell> <TableCell>{name}</TableCell>
<TableCell> <TableCell>
@ -127,16 +114,16 @@ const Row: SFC<IRowProps> = ({name, value, lastUsed, fEdit, fDelete}) => (
<LastUsedCell lastUsed={lastUsed} /> <LastUsedCell lastUsed={lastUsed} />
</TableCell> </TableCell>
<TableCell align="right" padding="none"> <TableCell align="right" padding="none">
<IconButton onClick={fEdit} className="edit" size="large"> <IconButton onClick={fEdit} className="edit">
<Edit /> <Edit />
</IconButton> </IconButton>
</TableCell> </TableCell>
<TableCell align="right" padding="none"> <TableCell align="right" padding="none">
<IconButton onClick={fDelete} className="delete" size="large"> <IconButton onClick={fDelete} className="delete">
<Delete /> <Delete />
</IconButton> </IconButton>
</TableCell> </TableCell>
</TableRow> </TableRow>
); );
export default inject('clientStore')(Clients); export default Clients;

View File

@ -1,3 +1,4 @@
import React, {useState} from 'react';
import Button from '@mui/material/Button'; import Button from '@mui/material/Button';
import Dialog from '@mui/material/Dialog'; import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions'; import DialogActions from '@mui/material/DialogActions';
@ -6,42 +7,24 @@ import DialogContentText from '@mui/material/DialogContentText';
import DialogTitle from '@mui/material/DialogTitle'; import DialogTitle from '@mui/material/DialogTitle';
import TextField from '@mui/material/TextField'; import TextField from '@mui/material/TextField';
import Tooltip from '@mui/material/Tooltip'; import Tooltip from '@mui/material/Tooltip';
import React, {Component} from 'react';
interface IProps { interface IProps {
fClose: VoidFunction; fClose: VoidFunction;
fOnSubmit: (name: string) => void; fOnSubmit: (name: string) => Promise<void>;
initialName: string; initialName: string;
} }
interface IState { const UpdateClientDialog = ({fClose, fOnSubmit, initialName = ''}: IProps) => {
name: string; const [name, setName] = useState(initialName);
}
export default class UpdateDialog extends Component<IProps, IState> { const submitEnabled = name.length !== 0;
public state = {name: ''}; const submitAndClose = async () => {
await fOnSubmit(name);
constructor(props: IProps) {
super(props);
this.state = {
name: props.initialName,
};
}
public render() {
const {fClose, fOnSubmit} = this.props;
const {name} = this.state;
const submitEnabled = this.state.name.length !== 0;
const submitAndClose = () => {
fOnSubmit(name);
fClose(); fClose();
}; };
return ( return (
<Dialog <Dialog open={true} onClose={fClose} aria-labelledby="form-dialog-title" id="client-dialog">
open={true}
onClose={fClose}
aria-labelledby="form-dialog-title"
id="client-dialog">
<DialogTitle id="form-dialog-title">Update a Client</DialogTitle> <DialogTitle id="form-dialog-title">Update a Client</DialogTitle>
<DialogContent> <DialogContent>
<DialogContentText> <DialogContentText>
@ -55,7 +38,7 @@ export default class UpdateDialog extends Component<IProps, IState> {
label="Name *" label="Name *"
type="text" type="text"
value={name} value={name}
onChange={this.handleChange.bind(this, 'name')} onChange={(e) => setName(e.target.value)}
fullWidth fullWidth
/> />
</DialogContent> </DialogContent>
@ -76,11 +59,6 @@ export default class UpdateDialog extends Component<IProps, IState> {
</DialogActions> </DialogActions>
</Dialog> </Dialog>
); );
} };
private handleChange(propertyName: 'name', event: React.ChangeEvent<HTMLInputElement>) { export default UpdateClientDialog;
const state = this.state;
state[propertyName] = event.target.value;
this.setState(state);
}
}

View File

@ -1,21 +1,19 @@
import Paper from '@mui/material/Paper'; import Paper from '@mui/material/Paper';
import {withStyles} from 'tss-react/mui'; import {makeStyles} from 'tss-react/mui';
import * as React from 'react'; import * as React from 'react';
const styles = () => const useStyles = makeStyles()(() => ({
({
paper: { paper: {
padding: 16, padding: 16,
}, },
} as const); }));
interface IProps { interface IProps {
style?: React.CSSProperties; style?: React.CSSProperties;
classes?: Partial<Record<keyof ReturnType<typeof styles>, string>>;
} }
const Container: React.FC<IProps> = ({children, style, ...props}) => { const Container: React.FC<IProps> = ({children, style, ...props}) => {
const classes = withStyles.getClasses(props); const {classes} = useStyles();
return ( return (
<Paper elevation={6} className={classes.paper} style={style}> <Paper elevation={6} className={classes.paper} style={style}>
{children} {children}
@ -23,4 +21,4 @@ const Container: React.FC<IProps> = ({children, style, ...props}) => {
); );
}; };
export default withStyles(Container, styles); export default Container;

View File

@ -3,43 +3,20 @@ import Typography from '@mui/material/Typography';
import Visibility from '@mui/icons-material/Visibility'; import Visibility from '@mui/icons-material/Visibility';
import Copy from '@mui/icons-material/FileCopyOutlined'; import Copy from '@mui/icons-material/FileCopyOutlined';
import VisibilityOff from '@mui/icons-material/VisibilityOff'; import VisibilityOff from '@mui/icons-material/VisibilityOff';
import React, {Component, CSSProperties} from 'react'; import React, {CSSProperties} from 'react';
import {Stores, inject} from '../inject'; import {useStores} from '../stores';
interface IProps { interface IProps {
value: string; value: string;
style?: CSSProperties; style?: CSSProperties;
} }
interface IState { const CopyableSecret = ({value, style}: IProps) => {
visible: boolean; const [visible, setVisible] = React.useState(false);
} const text = visible ? value : '•••••••••••••••';
const {snackManager} = useStores();
class CopyableSecret extends Component<IProps & Stores<'snackManager'>, IState> { const toggleVisibility = () => setVisible((b) => !b);
public state = {visible: false}; const copyToClipboard = async () => {
public render() {
const {value, style} = this.props;
const text = this.state.visible ? value : '•••••••••••••••';
return (
<div style={style}>
<IconButton onClick={this.copyToClipboard} title="Copy to clipboard" size="large">
<Copy />
</IconButton>
<IconButton
onClick={this.toggleVisibility}
className="toggle-visibility"
size="large">
{this.state.visible ? <VisibilityOff /> : <Visibility />}
</IconButton>
<Typography style={{fontFamily: 'monospace', fontSize: 16}}>{text}</Typography>
</div>
);
}
private toggleVisibility = () => this.setState({visible: !this.state.visible});
private copyToClipboard = async () => {
const {snackManager, value} = this.props;
try { try {
await navigator.clipboard.writeText(value); await navigator.clipboard.writeText(value);
snackManager.snack('Copied to clipboard'); snackManager.snack('Copied to clipboard');
@ -48,6 +25,17 @@ class CopyableSecret extends Component<IProps & Stores<'snackManager'>, IState>
snackManager.snack('Failed to copy to clipboard'); snackManager.snack('Failed to copy to clipboard');
} }
}; };
} return (
<div style={style}>
<IconButton onClick={copyToClipboard} title="Copy to clipboard" size="large">
<Copy />
</IconButton>
<IconButton onClick={toggleVisibility} className="toggle-visibility" size="large">
{visible ? <VisibilityOff /> : <Visibility />}
</IconButton>
<Typography style={{fontFamily: 'monospace', fontSize: 16}}>{text}</Typography>
</div>
);
};
export default inject('snackManager')(CopyableSecret); export default CopyableSecret;

View File

@ -1,30 +1,22 @@
import Fab from '@mui/material/Fab'; import Fab from '@mui/material/Fab';
import KeyboardArrowUp from '@mui/icons-material/KeyboardArrowUp'; import KeyboardArrowUp from '@mui/icons-material/KeyboardArrowUp';
import React, {Component} from 'react'; import React from 'react';
class ScrollUpButton extends Component { const ScrollUpButton = () => {
state = { const [state, setState] = React.useState({display: 'none', opacity: 0});
display: 'none', React.useEffect(() => {
opacity: 0, const scrollHandler = () => {
};
componentDidMount() {
window.addEventListener('scroll', this.scrollHandler);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.scrollHandler);
}
scrollHandler = () => {
const currentScrollPos = window.pageYOffset; const currentScrollPos = window.pageYOffset;
const opacity = Math.min(currentScrollPos / 500, 1); const opacity = Math.min(currentScrollPos / 500, 1);
const nextState = {display: currentScrollPos > 0 ? 'inherit' : 'none', opacity}; const nextState = {display: currentScrollPos > 0 ? 'inherit' : 'none', opacity};
if (this.state.display !== nextState.display || this.state.opacity !== nextState.opacity) { if (state.display !== nextState.display || state.opacity !== nextState.opacity) {
this.setState(nextState); setState(nextState);
} }
}; };
window.addEventListener('scroll', scrollHandler);
return () => window.removeEventListener('scroll', scrollHandler);
}, []);
public render() {
return ( return (
<Fab <Fab
color="primary" color="primary"
@ -33,16 +25,13 @@ class ScrollUpButton extends Component {
bottom: '30px', bottom: '30px',
right: '30px', right: '30px',
zIndex: 100000, zIndex: 100000,
display: this.state.display, display: state.display,
opacity: this.state.opacity, opacity: state.opacity,
}} }}
onClick={this.scrollUp}> onClick={() => window.scrollTo(0, 0)}>
<KeyboardArrowUp /> <KeyboardArrowUp />
</Fab> </Fab>
); );
} };
private scrollUp = () => window.scrollTo(0, 0);
}
export default ScrollUpButton; export default ScrollUpButton;

View File

@ -1,3 +1,4 @@
import React, {useState} from 'react';
import Button from '@mui/material/Button'; import Button from '@mui/material/Button';
import Dialog from '@mui/material/Dialog'; import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions'; import DialogActions from '@mui/material/DialogActions';
@ -5,27 +6,22 @@ import DialogContent from '@mui/material/DialogContent';
import DialogTitle from '@mui/material/DialogTitle'; import DialogTitle from '@mui/material/DialogTitle';
import TextField from '@mui/material/TextField'; import TextField from '@mui/material/TextField';
import Tooltip from '@mui/material/Tooltip'; import Tooltip from '@mui/material/Tooltip';
import React, {Component} from 'react';
import {observable} from 'mobx';
import {observer} from 'mobx-react'; import {observer} from 'mobx-react';
import {inject, Stores} from '../inject'; import {useStores} from '../stores';
interface IProps { interface IProps {
fClose: VoidFunction; fClose: VoidFunction;
} }
@observer const SettingsDialog = observer(({fClose}: IProps) => {
class SettingsDialog extends Component<IProps & Stores<'currentUser'>> { const [pass, setPass] = useState('');
@observable const {currentUser} = useStores();
private pass = '';
public render() { const submitAndClose = async () => {
const {pass} = this;
const {fClose, currentUser} = this.props;
const submitAndClose = () => {
currentUser.changePassword(pass); currentUser.changePassword(pass);
fClose(); fClose();
}; };
return ( return (
<Dialog <Dialog
open={true} open={true}
@ -41,7 +37,7 @@ class SettingsDialog extends Component<IProps & Stores<'currentUser'>> {
type="password" type="password"
label="New Password *" label="New Password *"
value={pass} value={pass}
onChange={(e) => (this.pass = e.target.value)} onChange={(e) => setPass(e.target.value)}
fullWidth fullWidth
/> />
</DialogContent> </DialogContent>
@ -62,7 +58,6 @@ class SettingsDialog extends Component<IProps & Stores<'currentUser'>> {
</DialogActions> </DialogActions>
</Dialog> </Dialog>
); );
} });
}
export default inject('currentUser')(SettingsDialog); export default SettingsDialog;

View File

@ -15,6 +15,7 @@ import {MessagesStore} from './message/MessagesStore';
import {ClientStore} from './client/ClientStore'; import {ClientStore} from './client/ClientStore';
import {PluginStore} from './plugin/PluginStore'; import {PluginStore} from './plugin/PluginStore';
import {registerReactions} from './reactions'; import {registerReactions} from './reactions';
import {StoreContext} from './stores';
const {port, hostname, protocol, pathname} = window.location; const {port, hostname, protocol, pathname} = window.location;
const slashes = protocol.concat('//'); const slashes = protocol.concat('//');
@ -61,9 +62,11 @@ const initStores = (): StoreMapping => {
}; };
ReactDOM.render( ReactDOM.render(
<StoreContext.Provider value={stores}>
<InjectProvider stores={stores}> <InjectProvider stores={stores}>
<Layout /> <Layout />
</InjectProvider>, </InjectProvider>
</StoreContext.Provider>,
document.getElementById('root') document.getElementById('root')
); );
unregister(); unregister();

View File

@ -2,7 +2,7 @@ import AppBar from '@mui/material/AppBar';
import Button, {ButtonProps} from '@mui/material/Button'; import Button, {ButtonProps} from '@mui/material/Button';
import IconButton from '@mui/material/IconButton'; import IconButton from '@mui/material/IconButton';
import {Theme} from '@mui/material/styles'; import {Theme} from '@mui/material/styles';
import {withStyles} from 'tss-react/mui'; import {makeStyles} from 'tss-react/mui';
import Toolbar from '@mui/material/Toolbar'; import Toolbar from '@mui/material/Toolbar';
import Typography from '@mui/material/Typography'; import Typography from '@mui/material/Typography';
import AccountCircle from '@mui/icons-material/AccountCircle'; import AccountCircle from '@mui/icons-material/AccountCircle';
@ -14,13 +14,11 @@ import GitHubIcon from '@mui/icons-material/GitHub';
import MenuIcon from '@mui/icons-material/Menu'; import MenuIcon from '@mui/icons-material/Menu';
import Apps from '@mui/icons-material/Apps'; import Apps from '@mui/icons-material/Apps';
import SupervisorAccount from '@mui/icons-material/SupervisorAccount'; import SupervisorAccount from '@mui/icons-material/SupervisorAccount';
import React, {Component, CSSProperties} from 'react'; import React, {CSSProperties} from 'react';
import {Link} from 'react-router-dom'; import {Link} from 'react-router-dom';
import {observer} from 'mobx-react';
import {useMediaQuery} from '@mui/material'; import {useMediaQuery} from '@mui/material';
const styles = (theme: Theme) => const useStyles = makeStyles()((theme: Theme) => ({
({
appBar: { appBar: {
zIndex: theme.zIndex.drawer + 1, zIndex: theme.zIndex.drawer + 1,
[theme.breakpoints.down('sm')]: { [theme.breakpoints.down('sm')]: {
@ -62,14 +60,13 @@ const styles = (theme: Theme) =>
color: 'inherit', color: 'inherit',
textDecoration: 'none', textDecoration: 'none',
}, },
} as const); }));
interface IProps { interface IProps {
loggedIn: boolean; loggedIn: boolean;
name: string; name: string;
admin: boolean; admin: boolean;
version: string; version: string;
classes?: Partial<Record<keyof ReturnType<typeof styles>, string>>;
toggleTheme: VoidFunction; toggleTheme: VoidFunction;
showSettings: VoidFunction; showSettings: VoidFunction;
logout: VoidFunction; logout: VoidFunction;
@ -77,12 +74,18 @@ interface IProps {
setNavOpen: (open: boolean) => void; setNavOpen: (open: boolean) => void;
} }
@observer const Header = ({
class Header extends Component<IProps> { version,
public render() { name,
const {version, name, loggedIn, admin, toggleTheme, logout, style, setNavOpen} = this.props; loggedIn,
admin,
const classes = withStyles.getClasses(this.props); toggleTheme,
logout,
style,
setNavOpen,
showSettings,
}: IProps) => {
const {classes} = useStyles();
return ( return (
<AppBar <AppBar
@ -104,7 +107,15 @@ class Header extends Component<IProps> {
</Typography> </Typography>
</a> </a>
</div> </div>
{loggedIn && this.renderButtons(name, admin, logout, setNavOpen)} {loggedIn && (
<Buttons
admin={admin}
name={name}
logout={logout}
setNavOpen={setNavOpen}
showSettings={showSettings}
/>
)}
<div> <div>
<IconButton onClick={toggleTheme} color="inherit" size="large"> <IconButton onClick={toggleTheme} color="inherit" size="large">
<Highlight /> <Highlight />
@ -123,16 +134,23 @@ class Header extends Component<IProps> {
</Toolbar> </Toolbar>
</AppBar> </AppBar>
); );
} };
const Buttons = ({
showSettings,
name,
admin,
logout,
setNavOpen,
}: {
name: string;
admin: boolean;
logout: VoidFunction;
setNavOpen: (open: boolean) => void;
showSettings: VoidFunction;
}) => {
const {classes} = useStyles();
private renderButtons(
name: string,
admin: boolean,
logout: VoidFunction,
setNavOpen: (open: boolean) => void
) {
const classes = withStyles.getClasses(this.props);
const {showSettings} = this.props;
return ( return (
<div className={classes.menuButtons}> <div className={classes.menuButtons}>
<ResponsiveButton <ResponsiveButton
@ -144,11 +162,7 @@ class Header extends Component<IProps> {
/> />
{admin && ( {admin && (
<Link className={classes.link} to="/users" id="navigate-users"> <Link className={classes.link} to="/users" id="navigate-users">
<ResponsiveButton <ResponsiveButton icon={<SupervisorAccount />} label="users" color="inherit" />
icon={<SupervisorAccount />}
label="users"
color="inherit"
/>
</Link> </Link>
)} )}
<Link className={classes.link} to="/applications" id="navigate-apps"> <Link className={classes.link} to="/applications" id="navigate-apps">
@ -176,8 +190,7 @@ class Header extends Component<IProps> {
/> />
</div> </div>
); );
} };
}
const ResponsiveButton: React.FC<{ const ResponsiveButton: React.FC<{
color: 'inherit'; color: 'inherit';
@ -202,4 +215,4 @@ const ResponsiveButton: React.FC<{
); );
}; };
export default withStyles(Header, styles); export default Header;

View File

@ -1,5 +1,5 @@
import {createTheme, ThemeProvider, StyledEngineProvider, Theme} from '@mui/material'; import {createTheme, ThemeProvider, StyledEngineProvider, Theme} from '@mui/material';
import {withStyles} from 'tss-react/mui'; import {makeStyles} from 'tss-react/mui';
import CssBaseline from '@mui/material/CssBaseline'; import CssBaseline from '@mui/material/CssBaseline';
import * as React from 'react'; import * as React from 'react';
import {HashRouter, Redirect, Route, Switch} from 'react-router-dom'; import {HashRouter, Redirect, Route, Switch} from 'react-router-dom';
@ -18,11 +18,10 @@ import Login from '../user/Login';
import Messages from '../message/Messages'; import Messages from '../message/Messages';
import Users from '../user/Users'; import Users from '../user/Users';
import {observer} from 'mobx-react'; import {observer} from 'mobx-react';
import {observable} from 'mobx';
import {inject, Stores} from '../inject';
import {ConnectionErrorBanner} from '../common/ConnectionErrorBanner'; import {ConnectionErrorBanner} from '../common/ConnectionErrorBanner';
import {useStores} from '../stores';
const styles = (theme: Theme) => ({ const useStyles = makeStyles()((theme: Theme) => ({
content: { content: {
margin: '0 auto', margin: '0 auto',
marginTop: 64, marginTop: 64,
@ -32,7 +31,7 @@ const styles = (theme: Theme) => ({
marginTop: 0, marginTop: 0,
}, },
}, },
}); }));
const localStorageThemeKey = 'gotify-theme'; const localStorageThemeKey = 'gotify-theme';
type ThemeKey = 'dark' | 'light'; type ThemeKey = 'dark' | 'light';
@ -52,34 +51,7 @@ const themeMap: Record<ThemeKey, Theme> = {
const isThemeKey = (value: string | null): value is ThemeKey => const isThemeKey = (value: string | null): value is ThemeKey =>
value === 'light' || value === 'dark'; value === 'light' || value === 'dark';
interface LayoutProps { const Layout = observer(() => {
classes?: Partial<Record<keyof ReturnType<typeof styles>, string>>;
}
@observer
class Layout extends React.Component<LayoutProps & Stores<'currentUser' | 'snackManager'>> {
@observable
private currentTheme: ThemeKey = 'dark';
@observable
private showSettings = false;
@observable
private navOpen = false;
private setNavOpen(open: boolean) {
this.navOpen = open;
}
public componentDidMount() {
const localStorageTheme = window.localStorage.getItem(localStorageThemeKey);
if (isThemeKey(localStorageTheme)) {
this.currentTheme = localStorageTheme;
} else {
window.localStorage.setItem(localStorageThemeKey, this.currentTheme);
}
}
public render() {
const {showSettings, currentTheme} = this;
const { const {
currentUser: { currentUser: {
loggedIn, loggedIn,
@ -89,11 +61,24 @@ class Layout extends React.Component<LayoutProps & Stores<'currentUser' | 'snack
tryReconnect, tryReconnect,
connectionErrorMessage, connectionErrorMessage,
}, },
} = this.props; } = useStores();
const classes = withStyles.getClasses(this.props); const {classes} = useStyles();
const [currentTheme, setCurrentTheme] = React.useState<ThemeKey>(() => {
const stored = window.localStorage.getItem(localStorageThemeKey);
return isThemeKey(stored) ? stored : 'dark';
});
const theme = themeMap[currentTheme]; const theme = themeMap[currentTheme];
const loginRoute = () => (loggedIn ? <Redirect to="/" /> : <Login />); const loginRoute = () => (loggedIn ? <Redirect to="/" /> : <Login />);
const {version} = config.get('version'); const {version} = config.get('version');
const [navOpen, setNavOpen] = React.useState(false);
const [showSettings, setShowSettings] = React.useState(false);
const toggleTheme = () => {
const next = currentTheme === 'dark' ? 'light' : 'dark';
setCurrentTheme(next);
localStorage.setItem(localStorageThemeKey, next);
};
return ( return (
<StyledEngineProvider injectFirst> <StyledEngineProvider injectFirst>
<ThemeProvider theme={theme}> <ThemeProvider theme={theme}>
@ -109,21 +94,21 @@ class Layout extends React.Component<LayoutProps & Stores<'currentUser' | 'snack
<div style={{display: 'flex', flexDirection: 'column'}}> <div style={{display: 'flex', flexDirection: 'column'}}>
<CssBaseline /> <CssBaseline />
<Header <Header
style={{top: !connectionErrorMessage ? 0 : 64}}
admin={admin} admin={admin}
name={name} name={name}
style={{top: !connectionErrorMessage ? 0 : 64}}
version={version} version={version}
loggedIn={loggedIn} loggedIn={loggedIn}
toggleTheme={this.toggleTheme.bind(this)} toggleTheme={toggleTheme}
showSettings={() => (this.showSettings = true)} showSettings={() => setShowSettings(true)}
logout={logout} logout={logout}
setNavOpen={this.setNavOpen.bind(this)} setNavOpen={setNavOpen}
/> />
<div style={{display: 'flex'}}> <div style={{display: 'flex'}}>
<Navigation <Navigation
loggedIn={loggedIn} loggedIn={loggedIn}
navOpen={this.navOpen} navOpen={navOpen}
setNavOpen={this.setNavOpen.bind(this)} setNavOpen={setNavOpen}
/> />
<main className={classes.content}> <main className={classes.content}>
<Switch> <Switch>
@ -135,11 +120,7 @@ class Layout extends React.Component<LayoutProps & Stores<'currentUser' | 'snack
<Route exact path="/login" render={loginRoute} /> <Route exact path="/login" render={loginRoute} />
{loggedIn ? null : <Redirect to="/login" />} {loggedIn ? null : <Redirect to="/login" />}
<Route exact path="/" component={Messages} /> <Route exact path="/" component={Messages} />
<Route <Route exact path="/messages/:id" component={Messages} />
exact
path="/messages/:id"
component={Messages}
/>
<Route <Route
exact exact
path="/applications" path="/applications"
@ -157,7 +138,7 @@ class Layout extends React.Component<LayoutProps & Stores<'currentUser' | 'snack
</main> </main>
</div> </div>
{showSettings && ( {showSettings && (
<SettingsDialog fClose={() => (this.showSettings = false)} /> <SettingsDialog fClose={() => setShowSettings(false)} />
)} )}
<ScrollUpButton /> <ScrollUpButton />
<SnackBarHandler /> <SnackBarHandler />
@ -167,12 +148,6 @@ class Layout extends React.Component<LayoutProps & Stores<'currentUser' | 'snack
</ThemeProvider> </ThemeProvider>
</StyledEngineProvider> </StyledEngineProvider>
); );
} });
private toggleTheme() { export default Layout;
this.currentTheme = this.currentTheme === 'dark' ? 'light' : 'dark';
localStorage.setItem(localStorageThemeKey, this.currentTheme);
}
}
export default withStyles(inject('currentUser', 'snackManager')(Layout), styles);

View File

@ -1,10 +1,9 @@
import Divider from '@mui/material/Divider'; import Divider from '@mui/material/Divider';
import Drawer from '@mui/material/Drawer'; import Drawer from '@mui/material/Drawer';
import {Theme} from '@mui/material/styles'; import {Theme} from '@mui/material/styles';
import React, {Component} from 'react'; import React from 'react';
import {Link} from 'react-router-dom'; import {Link} from 'react-router-dom';
import {observer} from 'mobx-react'; import {observer} from 'mobx-react';
import {inject, Stores} from '../inject';
import {mayAllowPermission, requestPermission} from '../snack/browserNotification'; import {mayAllowPermission, requestPermission} from '../snack/browserNotification';
import { import {
Button, Button,
@ -17,10 +16,10 @@ import {
} from '@mui/material'; } from '@mui/material';
import {DrawerProps} from '@mui/material/Drawer/Drawer'; import {DrawerProps} from '@mui/material/Drawer/Drawer';
import CloseIcon from '@mui/icons-material/Close'; import CloseIcon from '@mui/icons-material/Close';
import {withStyles} from 'tss-react/mui'; import {makeStyles} from 'tss-react/mui';
import {useStores} from '../stores';
const styles = (theme: Theme) => const useStyles = makeStyles()((theme: Theme) => ({
({
root: { root: {
height: '100%', height: '100%',
}, },
@ -36,26 +35,19 @@ const styles = (theme: Theme) =>
color: 'inherit', color: 'inherit',
textDecoration: 'none', textDecoration: 'none',
}, },
} as const); }));
interface IProps { interface IProps {
loggedIn: boolean; loggedIn: boolean;
navOpen: boolean; navOpen: boolean;
classes?: Partial<Record<keyof ReturnType<typeof styles>, string>>;
setNavOpen: (open: boolean) => void; setNavOpen: (open: boolean) => void;
} }
@observer const Navigation = observer(({loggedIn, navOpen, setNavOpen}: IProps) => {
class Navigation extends Component< const [showRequestNotification, setShowRequestNotification] =
IProps & Stores<'appStore'>, React.useState(mayAllowPermission);
{showRequestNotification: boolean} const {classes} = useStyles();
> { const {appStore} = useStores();
public state = {showRequestNotification: mayAllowPermission()};
public render() {
const {loggedIn, appStore, navOpen, setNavOpen} = this.props;
const classes = withStyles.getClasses(this.props);
const {showRequestNotification} = this.state;
const apps = appStore.getItems(); const apps = appStore.getItems();
const userApps = const userApps =
@ -109,7 +101,7 @@ class Navigation extends Component<
<Button <Button
onClick={() => { onClick={() => {
requestPermission(); requestPermission();
this.setState({showRequestNotification: false}); setShowRequestNotification(false);
}}> }}>
Enable Notifications Enable Notifications
</Button> </Button>
@ -117,8 +109,7 @@ class Navigation extends Component<
</Typography> </Typography>
</ResponsiveDrawer> </ResponsiveDrawer>
); );
} });
}
const ResponsiveDrawer: React.FC< const ResponsiveDrawer: React.FC<
DrawerProps & {navOpen: boolean; setNavOpen: (open: boolean) => void} DrawerProps & {navOpen: boolean; setNavOpen: (open: boolean) => void}
@ -140,4 +131,4 @@ const ResponsiveDrawer: React.FC<
</> </>
); );
export default withStyles(inject('appStore')(Navigation), styles); export default Navigation;

View File

@ -1,5 +1,5 @@
import React, {Component} from 'react'; import React from 'react';
import {RouteComponentProps} from 'react-router'; import {useParams} from 'react-router';
import {Markdown} from '../common/Markdown'; import {Markdown} from '../common/Markdown';
import {UnControlled as CodeMirror} from 'react-codemirror2'; import {UnControlled as CodeMirror} from 'react-codemirror2';
import 'codemirror/lib/codemirror.css'; import 'codemirror/lib/codemirror.css';
@ -14,65 +14,47 @@ import Typography from '@mui/material/Typography';
import DefaultPage from '../common/DefaultPage'; import DefaultPage from '../common/DefaultPage';
import * as config from '../config'; import * as config from '../config';
import Container from '../common/Container'; import Container from '../common/Container';
import {inject, Stores} from '../inject';
import {IPlugin} from '../types'; import {IPlugin} from '../types';
import LoadingSpinner from '../common/LoadingSpinner'; import LoadingSpinner from '../common/LoadingSpinner';
import {useStores} from '../stores';
type IProps = RouteComponentProps<{id: string}>; const PluginDetailView = () => {
const {id} = useParams<{id: string}>();
const pluginID = parseInt(id as string, 10);
const {pluginStore} = useStores();
const [currentConfig, setCurrentConfig] = React.useState<string>();
const [displayText, setDisplayText] = React.useState<string>();
interface IState { const pluginInfo = pluginStore.getByIDOrUndefined(pluginID);
displayText: string | null;
currentConfig: string | null;
}
class PluginDetailView extends Component<IProps & Stores<'pluginStore'>, IState> { const refreshFeatures = async () => {
private pluginID: number = parseInt(this.props.match.params.id, 10); await pluginStore.refreshIfMissing(pluginID);
private pluginInfo = () => this.props.pluginStore.getByID(this.pluginID); await Promise.all([refreshConfigurer(), refreshDisplayer()]);
public state: IState = {
displayText: null,
currentConfig: null,
}; };
public componentWillMount() { React.useEffect(() => void refreshFeatures(), [pluginID]);
this.refreshFeatures();
}
public componentWillReceiveProps(nextProps: IProps & Stores<'pluginStore'>) { const refreshConfigurer = async () => {
this.pluginID = parseInt(nextProps.match.params.id, 10); if (pluginInfo?.capabilities.indexOf('configurer') !== -1) {
this.refreshFeatures(); setCurrentConfig(await pluginStore.requestConfig(pluginID));
} }
};
private async refreshFeatures() { const refreshDisplayer = async () => {
await this.props.pluginStore.refreshIfMissing(this.pluginID); if (pluginInfo?.capabilities.indexOf('displayer') !== -1) {
return await Promise.all([this.refreshConfigurer(), this.refreshDisplayer()]); setDisplayText(await pluginStore.requestDisplay(pluginID));
} }
};
private async refreshConfigurer() { if (pluginInfo == null) {
const {
props: {pluginStore},
} = this;
if (this.pluginInfo().capabilities.indexOf('configurer') !== -1) {
const response = await pluginStore.requestConfig(this.pluginID);
this.setState({currentConfig: response});
}
}
private async refreshDisplayer() {
const {
props: {pluginStore},
} = this;
if (this.pluginInfo().capabilities.indexOf('displayer') !== -1) {
const response = await pluginStore.requestDisplay(this.pluginID);
this.setState({displayText: response});
}
}
public render() {
const pluginInfo = this.props.pluginStore.getByIDOrUndefined(this.pluginID);
if (pluginInfo === undefined) {
return <LoadingSpinner />; return <LoadingSpinner />;
} }
const handleSaveConfig = async (newConfig: string) => {
await pluginStore.changeConfig(pluginID, newConfig);
await refreshFeatures();
};
return ( return (
<DefaultPage title={pluginInfo.name} maxWidth={1000}> <DefaultPage title={pluginInfo.name} maxWidth={1000}>
<PanelWrapper name={'Plugin Info'} icon={Info}> <PanelWrapper name={'Plugin Info'} icon={Info}>
@ -83,18 +65,11 @@ class PluginDetailView extends Component<IProps & Stores<'pluginStore'>, IState>
name={'Configurer'} name={'Configurer'}
description={'This is the configuration panel for this plugin.'} description={'This is the configuration panel for this plugin.'}
icon={Build} icon={Build}
refresh={this.refreshConfigurer.bind(this)}> refresh={refreshConfigurer}>
<ConfigurerPanel <ConfigurerPanel
pluginInfo={pluginInfo} pluginInfo={pluginInfo}
initialConfig={ initialConfig={currentConfig != null ? currentConfig : 'Loading...'}
this.state.currentConfig !== null save={handleSaveConfig}
? this.state.currentConfig
: 'Loading...'
}
save={async (newConfig) => {
await this.props.pluginStore.changeConfig(this.pluginID, newConfig);
await this.refreshFeatures();
}}
/> />
</PanelWrapper> </PanelWrapper>
) : null}{' '} ) : null}{' '}
@ -102,22 +77,17 @@ class PluginDetailView extends Component<IProps & Stores<'pluginStore'>, IState>
<PanelWrapper <PanelWrapper
name={'Displayer'} name={'Displayer'}
description={'This is the information generated by the plugin.'} description={'This is the information generated by the plugin.'}
refresh={this.refreshDisplayer.bind(this)} refresh={refreshDisplayer}
icon={Subject}> icon={Subject}>
<DisplayerPanel <DisplayerPanel
pluginInfo={pluginInfo} pluginInfo={pluginInfo}
displayText={ displayText={displayText != null ? displayText : 'Loading...'}
this.state.displayText !== null
? this.state.displayText
: 'Loading...'
}
/> />
</PanelWrapper> </PanelWrapper>
) : null} ) : null}
</DefaultPage> </DefaultPage>
); );
} };
}
interface IPanelWrapperProps { interface IPanelWrapperProps {
name: string; name: string;
@ -178,14 +148,12 @@ interface IConfigurerPanelProps {
initialConfig: string; initialConfig: string;
save: (newConfig: string) => Promise<void>; save: (newConfig: string) => Promise<void>;
} }
class ConfigurerPanel extends Component<IConfigurerPanelProps, {unsavedChanges: string | null}> { const ConfigurerPanel = ({initialConfig, save}: IConfigurerPanelProps) => {
public state = {unsavedChanges: null}; const [unsavedChanges, setUnsavedChanges] = React.useState<string | null>(null);
public render() {
return ( return (
<div> <div>
<CodeMirror <CodeMirror
value={this.props.initialConfig} value={initialConfig}
options={{ options={{
mode: 'yaml', mode: 'yaml',
theme: 'material', theme: 'material',
@ -193,10 +161,10 @@ class ConfigurerPanel extends Component<IConfigurerPanelProps, {unsavedChanges:
}} }}
onChange={(_, _1, value) => { onChange={(_, _1, value) => {
let newConf: string | null = value; let newConf: string | null = value;
if (value === this.props.initialConfig) { if (value === initialConfig) {
newConf = null; newConf = null;
} }
this.setState({unsavedChanges: newConf}); setUnsavedChanges(newConf);
}} }}
/> />
<br /> <br />
@ -204,23 +172,19 @@ class ConfigurerPanel extends Component<IConfigurerPanelProps, {unsavedChanges:
variant="contained" variant="contained"
color="primary" color="primary"
fullWidth={true} fullWidth={true}
disabled={ disabled={unsavedChanges === null || unsavedChanges === initialConfig}
this.state.unsavedChanges === null ||
this.state.unsavedChanges === this.props.initialConfig
}
className="config-save" className="config-save"
onClick={() => { onClick={() => {
const newConfig = this.state.unsavedChanges; const newConfig = unsavedChanges;
this.props.save(newConfig!).then(() => { save(newConfig!).then(() => {
this.setState({unsavedChanges: null}); setUnsavedChanges(null);
}); });
}}> }}>
<Typography variant="button">Save</Typography> <Typography variant="button">Save</Typography>
</Button> </Button>
</div> </div>
); );
} };
}
interface IDisplayerPanelProps { interface IDisplayerPanelProps {
pluginInfo: IPlugin; pluginInfo: IPlugin;
@ -232,13 +196,13 @@ const DisplayerPanel: React.FC<IDisplayerPanelProps> = ({displayText}) => (
</Typography> </Typography>
); );
class PluginInfo extends Component<{pluginInfo: IPlugin}> { interface IPluginInfo {
public render() { pluginInfo: IPlugin;
const { }
props: {
pluginInfo: {name, author, modulePath, website, license, capabilities, id, token}, const PluginInfo = ({pluginInfo}: IPluginInfo) => {
}, const {name, author, modulePath, website, license, capabilities, id, token} = pluginInfo;
} = this;
return ( return (
<div style={{wordWrap: 'break-word'}}> <div style={{wordWrap: 'break-word'}}>
{name ? ( {name ? (
@ -283,7 +247,6 @@ class PluginInfo extends Component<{pluginInfo: IPlugin}> {
) : null} ) : null}
</div> </div>
); );
} };
}
export default inject('pluginStore')(PluginDetailView); export default PluginDetailView;

View File

@ -1,4 +1,4 @@
import React, {Component, SFC} from 'react'; import React, {SFC} from 'react';
import {Link} from 'react-router-dom'; import {Link} from 'react-router-dom';
import Grid from '@mui/material/Grid'; import Grid from '@mui/material/Grid';
import Paper from '@mui/material/Paper'; import Paper from '@mui/material/Paper';
@ -12,17 +12,12 @@ import {Switch, Button} from '@mui/material';
import DefaultPage from '../common/DefaultPage'; import DefaultPage from '../common/DefaultPage';
import CopyableSecret from '../common/CopyableSecret'; import CopyableSecret from '../common/CopyableSecret';
import {observer} from 'mobx-react'; import {observer} from 'mobx-react';
import {inject, Stores} from '../inject';
import {IPlugin} from '../types'; import {IPlugin} from '../types';
import {useStores} from '../stores';
@observer const Plugins = observer(() => {
class Plugins extends Component<Stores<'pluginStore'>> { const {pluginStore} = useStores();
public componentDidMount = () => this.props.pluginStore.refresh(); React.useEffect(() => void pluginStore.refresh(), []);
public render() {
const {
props: {pluginStore},
} = this;
const plugins = pluginStore.getItems(); const plugins = pluginStore.getItems();
return ( return (
<DefaultPage title="Plugins" maxWidth={1000}> <DefaultPage title="Plugins" maxWidth={1000}>
@ -47,10 +42,7 @@ class Plugins extends Component<Stores<'pluginStore'>> {
name={plugin.name} name={plugin.name}
enabled={plugin.enabled} enabled={plugin.enabled}
fToggleStatus={() => fToggleStatus={() =>
this.props.pluginStore.changeEnabledState( pluginStore.changeEnabledState(plugin.id, !plugin.enabled)
plugin.id,
!plugin.enabled
)
} }
/> />
))} ))}
@ -60,8 +52,7 @@ class Plugins extends Component<Stores<'pluginStore'>> {
</Grid> </Grid>
</DefaultPage> </DefaultPage>
); );
} });
}
interface IRowProps { interface IRowProps {
id: number; id: number;
@ -96,4 +87,4 @@ const Row: SFC<IRowProps> = observer(({name, id, token, enabled, fToggleStatus})
</TableRow> </TableRow>
)); ));
export default inject('pluginStore')(Plugins); export default Plugins;

28
ui/src/stores.tsx Normal file
View File

@ -0,0 +1,28 @@
import * as React from 'react';
import {UserStore} from './user/UserStore';
import {SnackManager} from './snack/SnackManager';
import {MessagesStore} from './message/MessagesStore';
import {CurrentUser} from './CurrentUser';
import {ClientStore} from './client/ClientStore';
import {AppStore} from './application/AppStore';
import {WebSocketStore} from './message/WebSocketStore';
import {PluginStore} from './plugin/PluginStore';
export interface StoreMapping {
userStore: UserStore;
snackManager: SnackManager;
messagesStore: MessagesStore;
currentUser: CurrentUser;
clientStore: ClientStore;
appStore: AppStore;
pluginStore: PluginStore;
wsStore: WebSocketStore;
}
export const StoreContext = React.createContext<StoreMapping | undefined>(undefined);
export const useStores = (): StoreMapping => {
const mapping = React.useContext(StoreContext);
if (!mapping) throw new Error('uninitialized');
return mapping;
};

View File

@ -7,36 +7,31 @@ import FormControlLabel from '@mui/material/FormControlLabel';
import Switch from '@mui/material/Switch'; import Switch from '@mui/material/Switch';
import TextField from '@mui/material/TextField'; import TextField from '@mui/material/TextField';
import Tooltip from '@mui/material/Tooltip'; import Tooltip from '@mui/material/Tooltip';
import React, {ChangeEvent, Component} from 'react'; import React from 'react';
interface IProps { interface IProps {
name?: string; name?: string;
admin?: boolean; admin?: boolean;
fClose: VoidFunction; fClose: VoidFunction;
fOnSubmit: (name: string, pass: string, admin: boolean) => void; fOnSubmit: (name: string, pass: string, admin: boolean) => Promise<void>;
isEdit?: boolean; isEdit?: boolean;
} }
interface IState { const AddEditUserDialog = ({
name: string; fClose,
pass: string; fOnSubmit,
admin: boolean; isEdit,
} name: initialName = '',
admin: initialAdmin = false,
}: IProps) => {
const [name, setName] = React.useState(initialName);
const [pass, setPass] = React.useState('');
const [admin, setAdmin] = React.useState(initialAdmin);
export default class AddEditDialog extends Component<IProps, IState> { const namePresent = name.length !== 0;
public state = { const passPresent = pass.length !== 0 || isEdit;
name: this.props.name ?? '', const submitAndClose = async () => {
pass: '', await fOnSubmit(name, pass, admin);
admin: this.props.admin ?? false,
};
public render() {
const {fClose, fOnSubmit, isEdit} = this.props;
const {name, pass, admin} = this.state;
const namePresent = this.state.name.length !== 0;
const passPresent = this.state.pass.length !== 0 || isEdit;
const submitAndClose = () => {
fOnSubmit(name, pass, admin);
fClose(); fClose();
}; };
return ( return (
@ -46,7 +41,7 @@ export default class AddEditDialog extends Component<IProps, IState> {
aria-labelledby="form-dialog-title" aria-labelledby="form-dialog-title"
id="add-edit-user-dialog"> id="add-edit-user-dialog">
<DialogTitle id="form-dialog-title"> <DialogTitle id="form-dialog-title">
{isEdit ? 'Edit ' + this.props.name : 'Add a user'} {isEdit ? 'Edit ' + name : 'Add a user'}
</DialogTitle> </DialogTitle>
<DialogContent> <DialogContent>
<TextField <TextField
@ -57,7 +52,7 @@ export default class AddEditDialog extends Component<IProps, IState> {
value={name} value={name}
name="username" name="username"
id="username" id="username"
onChange={this.handleChange.bind(this, 'name')} onChange={(e) => setName(e.target.value)}
fullWidth fullWidth
/> />
<TextField <TextField
@ -69,14 +64,14 @@ export default class AddEditDialog extends Component<IProps, IState> {
label={isEdit ? 'Password (empty if no change)' : 'Password *'} label={isEdit ? 'Password (empty if no change)' : 'Password *'}
name="password" name="password"
id="password" id="password"
onChange={this.handleChange.bind(this, 'pass')} onChange={(e) => setPass(e.target.value)}
/> />
<FormControlLabel <FormControlLabel
control={ control={
<Switch <Switch
checked={admin} checked={admin}
className="admin-rights" className="admin-rights"
onChange={this.handleChecked.bind(this, 'admin')} onChange={(e) => setAdmin(e.target.checked)}
value="admin" value="admin"
/> />
} }
@ -108,17 +103,5 @@ export default class AddEditDialog extends Component<IProps, IState> {
</DialogActions> </DialogActions>
</Dialog> </Dialog>
); );
} };
export default AddEditUserDialog;
private handleChange(propertyName: 'name' | 'pass', event: ChangeEvent<HTMLInputElement>) {
const state = this.state;
state[propertyName] = event.target.value;
this.setState(state);
}
private handleChecked(propertyName: 'admin', event: ChangeEvent<HTMLInputElement>) {
const state = this.state;
state[propertyName] = event.target.checked;
this.setState(state);
}
}

View File

@ -1,31 +1,41 @@
import Button from '@mui/material/Button'; import Button from '@mui/material/Button';
import Grid from '@mui/material/Grid'; import Grid from '@mui/material/Grid';
import TextField from '@mui/material/TextField'; import TextField from '@mui/material/TextField';
import React, {Component, FormEvent} from 'react'; import React from 'react';
import Container from '../common/Container'; import Container from '../common/Container';
import DefaultPage from '../common/DefaultPage'; import DefaultPage from '../common/DefaultPage';
import {observable} from 'mobx';
import {observer} from 'mobx-react';
import {inject, Stores} from '../inject';
import * as config from '../config'; import * as config from '../config';
import RegistrationDialog from './Register'; import RegistrationDialog from './Register';
import {useStores} from '../stores';
import {observer} from 'mobx-react';
@observer const Login = observer(() => {
class Login extends Component<Stores<'currentUser'>> { const [username, setUsername] = React.useState('');
@observable const [password, setPassword] = React.useState('');
private username = ''; const [registerDialog, setRegisterDialog] = React.useState(false);
@observable const {currentUser} = useStores();
private password = ''; const registerButton = () => {
@observable if (config.get('register'))
private registerDialog = false;
public render() {
const {username, password, registerDialog} = this;
return ( return (
<DefaultPage title="Login" rightControl={this.registerButton()} maxWidth={250}> <Button
id="register"
variant="contained"
color="primary"
onClick={() => setRegisterDialog(true)}>
Register
</Button>
);
else return null;
};
const login = (e: React.MouseEvent<HTMLButtonElement>) => {
e.preventDefault();
currentUser.login(username, password);
};
return (
<DefaultPage title="Login" rightControl={registerButton()} maxWidth={250}>
<Grid size={{xs: 12}} style={{textAlign: 'center'}}> <Grid size={{xs: 12}} style={{textAlign: 'center'}}>
<Container> <Container>
<form onSubmit={this.preventDefault} id="login-form"> <form onSubmit={(e) => e.preventDefault()} id="login-form">
<TextField <TextField
autoFocus autoFocus
id="username" id="username"
@ -35,7 +45,7 @@ class Login extends Component<Stores<'currentUser'>> {
margin="dense" margin="dense"
autoComplete="username" autoComplete="username"
value={username} value={username}
onChange={(e) => (this.username = e.target.value)} onChange={(e) => setUsername(e.target.value)}
/> />
<TextField <TextField
id="password" id="password"
@ -46,7 +56,7 @@ class Login extends Component<Stores<'currentUser'>> {
margin="normal" margin="normal"
autoComplete="current-password" autoComplete="current-password"
value={password} value={password}
onChange={(e) => (this.password = e.target.value)} onChange={(e) => setPassword(e.target.value)}
/> />
<Button <Button
type="submit" type="submit"
@ -54,9 +64,9 @@ class Login extends Component<Stores<'currentUser'>> {
size="large" size="large"
className="login" className="login"
color="primary" color="primary"
disabled={!!this.props.currentUser.connectionErrorMessage} disabled={!!currentUser.connectionErrorMessage}
style={{marginTop: 15, marginBottom: 5}} style={{marginTop: 15, marginBottom: 5}}
onClick={this.login}> onClick={login}>
Login Login
</Button> </Button>
</form> </form>
@ -64,34 +74,12 @@ class Login extends Component<Stores<'currentUser'>> {
</Grid> </Grid>
{registerDialog && ( {registerDialog && (
<RegistrationDialog <RegistrationDialog
fClose={() => (this.registerDialog = false)} fClose={() => setRegisterDialog(false)}
fOnSubmit={this.props.currentUser.register} fOnSubmit={currentUser.register}
/> />
)} )}
</DefaultPage> </DefaultPage>
); );
} });
private login = (e: React.MouseEvent<HTMLButtonElement>) => { export default Login;
e.preventDefault();
this.props.currentUser.login(this.username, this.password);
};
private registerButton = () => {
if (config.get('register'))
return (
<Button
id="register"
variant="contained"
color="primary"
onClick={() => (this.registerDialog = true)}>
Register
</Button>
);
else return null;
};
private preventDefault = (e: FormEvent<HTMLFormElement>) => e.preventDefault();
}
export default inject('currentUser')(Login);

View File

@ -5,7 +5,7 @@ import DialogContent from '@mui/material/DialogContent';
import DialogTitle from '@mui/material/DialogTitle'; import DialogTitle from '@mui/material/DialogTitle';
import TextField from '@mui/material/TextField'; import TextField from '@mui/material/TextField';
import Tooltip from '@mui/material/Tooltip'; import Tooltip from '@mui/material/Tooltip';
import React, {ChangeEvent, Component} from 'react'; import React from 'react';
interface IProps { interface IProps {
name?: string; name?: string;
@ -13,22 +13,20 @@ interface IProps {
fOnSubmit: (name: string, pass: string) => Promise<boolean>; fOnSubmit: (name: string, pass: string) => Promise<boolean>;
} }
interface IState { const RegistrationDialog = ({fClose, fOnSubmit, name: initialName = ''}: IProps) => {
name: string; const [name, setName] = React.useState(initialName);
pass: string; const [pass, setPass] = React.useState('');
} const namePresent = name.length !== 0;
const passPresent = pass.length !== 0;
export default class RegistrationDialog extends Component<IProps, IState> { const handleNameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
public state = { setName(e.target.value);
name: '', };
pass: '',
const handlePassChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setPass(e.target.value);
}; };
public render() {
const {fClose, fOnSubmit} = this.props;
const {name, pass} = this.state;
const namePresent = this.state.name.length !== 0;
const passPresent = this.state.pass.length !== 0;
const submitAndClose = (): void => { const submitAndClose = (): void => {
fOnSubmit(name, pass).then((success) => { fOnSubmit(name, pass).then((success) => {
if (success) { if (success) {
@ -36,6 +34,7 @@ export default class RegistrationDialog extends Component<IProps, IState> {
} }
}); });
}; };
return ( return (
<Dialog <Dialog
open={true} open={true}
@ -53,7 +52,7 @@ export default class RegistrationDialog extends Component<IProps, IState> {
name="username" name="username"
value={name} value={name}
autoComplete="username" autoComplete="username"
onChange={this.handleChange.bind(this, 'name')} onChange={handleNameChange}
fullWidth fullWidth
/> />
<TextField <TextField
@ -66,7 +65,7 @@ export default class RegistrationDialog extends Component<IProps, IState> {
label="Password *" label="Password *"
name="password" name="password"
autoComplete="new-password" autoComplete="new-password"
onChange={this.handleChange.bind(this, 'pass')} onChange={handlePassChange}
/> />
</DialogContent> </DialogContent>
<DialogActions> <DialogActions>
@ -94,11 +93,5 @@ export default class RegistrationDialog extends Component<IProps, IState> {
</DialogActions> </DialogActions>
</Dialog> </Dialog>
); );
} };
export default RegistrationDialog;
private handleChange(propertyName: keyof IState, event: ChangeEvent<HTMLInputElement>) {
const state = this.state;
state[propertyName] = event.target.value;
this.setState(state);
}
}

View File

@ -8,15 +8,14 @@ import TableHead from '@mui/material/TableHead';
import TableRow from '@mui/material/TableRow'; import TableRow from '@mui/material/TableRow';
import Delete from '@mui/icons-material/Delete'; import Delete from '@mui/icons-material/Delete';
import Edit from '@mui/icons-material/Edit'; import Edit from '@mui/icons-material/Edit';
import React, {Component, SFC} from 'react'; import React from 'react';
import ConfirmDialog from '../common/ConfirmDialog'; import ConfirmDialog from '../common/ConfirmDialog';
import DefaultPage from '../common/DefaultPage'; import DefaultPage from '../common/DefaultPage';
import Button from '@mui/material/Button'; import Button from '@mui/material/Button';
import AddEditDialog from './AddEditUserDialog'; import AddEditDialog from './AddEditUserDialog';
import {observer} from 'mobx-react';
import {observable} from 'mobx';
import {inject, Stores} from '../inject';
import {IUser} from '../types'; import {IUser} from '../types';
import {useStores} from '../stores';
import {observer} from 'mobx-react';
interface IRowProps { interface IRowProps {
name: string; name: string;
@ -25,7 +24,7 @@ interface IRowProps {
fEdit: VoidFunction; fEdit: VoidFunction;
} }
const UserRow: SFC<IRowProps> = ({name, admin, fDelete, fEdit}) => ( const UserRow: React.FC<IRowProps> = ({name, admin, fDelete, fEdit}) => (
<TableRow> <TableRow>
<TableCell>{name}</TableCell> <TableCell>{name}</TableCell>
<TableCell>{admin ? 'Yes' : 'No'}</TableCell> <TableCell>{admin ? 'Yes' : 'No'}</TableCell>
@ -40,24 +39,12 @@ const UserRow: SFC<IRowProps> = ({name, admin, fDelete, fEdit}) => (
</TableRow> </TableRow>
); );
@observer const Users = observer(() => {
class Users extends Component<Stores<'userStore'>> { const [deleteUser, setDeleteUser] = React.useState<IUser>();
@observable const [editUser, setEditUser] = React.useState<IUser>();
private createDialog = false; const [createDialog, setCreateDialog] = React.useState(false);
@observable const {userStore} = useStores();
private deleteId: number | false = false; React.useEffect(() => void userStore.refresh(), []);
@observable
private editId: number | false = false;
public componentDidMount = () => this.props.userStore.refresh();
public render() {
const {
deleteId,
editId,
createDialog,
props: {userStore},
} = this;
const users = userStore.getItems(); const users = userStore.getItems();
return ( return (
<DefaultPage <DefaultPage
@ -67,7 +54,7 @@ class Users extends Component<Stores<'userStore'>> {
id="create-user" id="create-user"
variant="contained" variant="contained"
color="primary" color="primary"
onClick={() => (this.createDialog = true)}> onClick={() => setCreateDialog(true)}>
Create User Create User
</Button> </Button>
}> }>
@ -87,8 +74,8 @@ class Users extends Component<Stores<'userStore'>> {
key={user.id} key={user.id}
name={user.name} name={user.name}
admin={user.admin} admin={user.admin}
fDelete={() => (this.deleteId = user.id)} fDelete={() => setDeleteUser(user)}
fEdit={() => (this.editId = user.id)} fEdit={() => setEditUser(user)}
/> />
))} ))}
</TableBody> </TableBody>
@ -96,31 +83,27 @@ class Users extends Component<Stores<'userStore'>> {
</Paper> </Paper>
</Grid> </Grid>
{createDialog && ( {createDialog && (
<AddEditDialog <AddEditDialog fClose={() => setCreateDialog(false)} fOnSubmit={userStore.create} />
fClose={() => (this.createDialog = false)}
fOnSubmit={userStore.create}
/>
)} )}
{editId !== false && ( {editUser && (
<AddEditDialog <AddEditDialog
fClose={() => (this.editId = false)} fClose={() => setEditUser(undefined)}
fOnSubmit={userStore.update.bind(this, editId)} fOnSubmit={userStore.update.bind(this, editUser.id)}
name={userStore.getByID(editId).name} name={editUser.name}
admin={userStore.getByID(editId).admin} admin={editUser.admin}
isEdit={true} isEdit={true}
/> />
)} )}
{deleteId !== false && ( {deleteUser && (
<ConfirmDialog <ConfirmDialog
title="Confirm Delete" title="Confirm Delete"
text={'Delete ' + userStore.getByID(deleteId).name + '?'} text={'Delete ' + deleteUser.name + '?'}
fClose={() => (this.deleteId = false)} fClose={() => setDeleteUser(undefined)}
fOnSubmit={() => userStore.remove(deleteId)} fOnSubmit={() => userStore.remove(deleteUser.id)}
/> />
)} )}
</DefaultPage> </DefaultPage>
); );
} });
}
export default inject('userStore')(Users); export default Users;