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,94 +7,72 @@ import DialogTitle from '@mui/material/DialogTitle';
import TextField from '@mui/material/TextField';
import Tooltip from '@mui/material/Tooltip';
import {NumberField} from '../common/NumberField';
import React, {Component} from 'react';
import React, {useState} from 'react';
interface IProps {
fClose: VoidFunction;
fOnSubmit: (name: string, description: string, defaultPriority: number) => void;
fOnSubmit: (name: string, description: string, defaultPriority: number) => Promise<void>;
}
interface IState {
name: string;
description: string;
defaultPriority: number;
}
export const AddApplicationDialog = ({fClose, fOnSubmit}: IProps) => {
const [name, setName] = useState('');
const [description, setDescription] = useState('');
const [defaultPriority, setDefaultPriority] = useState(0);
export default class AddDialog extends Component<IProps, IState> {
public state = {name: '', description: '', defaultPriority: 0};
const submitEnabled = name.length !== 0;
const submitAndClose = async () => {
await fOnSubmit(name, description, defaultPriority);
fClose();
};
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();
};
return (
<Dialog
open={true}
onClose={fClose}
aria-labelledby="form-dialog-title"
id="app-dialog">
<DialogTitle id="form-dialog-title">Create an application</DialogTitle>
<DialogContent>
<DialogContentText>
An application is allowed to send messages.
</DialogContentText>
<TextField
autoFocus
margin="dense"
className="name"
label="Name *"
type="text"
value={name}
onChange={this.handleChange.bind(this, 'name')}
fullWidth
/>
<TextField
margin="dense"
className="description"
label="Short Description"
value={description}
onChange={this.handleChange.bind(this, 'description')}
fullWidth
multiline
/>
<NumberField
margin="dense"
className="priority"
label="Default Priority"
value={defaultPriority}
onChange={(value) => this.setState({defaultPriority: value})}
fullWidth
/>
</DialogContent>
<DialogActions>
<Button onClick={fClose}>Cancel</Button>
<Tooltip title={submitEnabled ? '' : 'name is required'}>
<div>
<Button
className="create"
disabled={!submitEnabled}
onClick={submitAndClose}
color="primary"
variant="contained">
Create
</Button>
</div>
</Tooltip>
</DialogActions>
</Dialog>
);
}
private handleChange(
propertyName: 'description' | 'name',
event: React.ChangeEvent<HTMLInputElement>
) {
const state = this.state;
state[propertyName] = event.target.value;
this.setState(state);
}
}
return (
<Dialog open={true} onClose={fClose} aria-labelledby="form-dialog-title" id="app-dialog">
<DialogTitle id="form-dialog-title">Create an application</DialogTitle>
<DialogContent>
<DialogContentText>An application is allowed to send messages.</DialogContentText>
<TextField
autoFocus
margin="dense"
className="name"
label="Name *"
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
fullWidth
/>
<TextField
margin="dense"
className="description"
label="Short Description"
value={description}
onChange={(e) => setDescription(e.target.value)}
fullWidth
multiline
/>
<NumberField
margin="dense"
className="priority"
label="Default Priority"
value={defaultPriority}
onChange={(value) => setDefaultPriority(value)}
fullWidth
/>
</DialogContent>
<DialogActions>
<Button onClick={fClose}>Cancel</Button>
<Tooltip title={submitEnabled ? '' : 'name is required'}>
<div>
<Button
className="create"
disabled={!submitEnabled}
onClick={submitAndClose}
color="primary"
variant="contained">
Create
</Button>
</div>
</Tooltip>
</DialogActions>
</Dialog>
);
};

View File

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

View File

@ -7,106 +7,81 @@ import DialogTitle from '@mui/material/DialogTitle';
import TextField from '@mui/material/TextField';
import Tooltip from '@mui/material/Tooltip';
import {NumberField} from '../common/NumberField';
import React, {Component} from 'react';
import React, {useState} from 'react';
interface IProps {
fClose: VoidFunction;
fOnSubmit: (name: string, description: string, defaultPriority: number) => void;
fOnSubmit: (name: string, description: string, defaultPriority: number) => Promise<void>;
initialName: string;
initialDescription: string;
initialDefaultPriority: number;
}
interface IState {
name: string;
description: string;
defaultPriority: number;
}
export const UpdateApplicationDialog = ({
initialName,
initialDescription,
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> {
public state = {name: '', description: '', defaultPriority: 0};
const submitEnabled = name.length !== 0;
const submitAndClose = async () => {
await fOnSubmit(name, description, defaultPriority);
fClose();
};
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();
};
return (
<Dialog
open={true}
onClose={fClose}
aria-labelledby="form-dialog-title"
id="app-dialog">
<DialogTitle id="form-dialog-title">Update an application</DialogTitle>
<DialogContent>
<DialogContentText>
An application is allowed to send messages.
</DialogContentText>
<TextField
autoFocus
margin="dense"
className="name"
label="Name *"
type="text"
value={name}
onChange={this.handleChange.bind(this, 'name')}
fullWidth
/>
<TextField
margin="dense"
className="description"
label="Short Description"
value={description}
onChange={this.handleChange.bind(this, 'description')}
fullWidth
multiline
/>
<NumberField
margin="dense"
className="priority"
label="Default Priority"
value={defaultPriority}
onChange={(value) => this.setState({defaultPriority: value})}
fullWidth
/>
</DialogContent>
<DialogActions>
<Button onClick={fClose}>Cancel</Button>
<Tooltip title={submitEnabled ? '' : 'name is required'}>
<div>
<Button
className="update"
disabled={!submitEnabled}
onClick={submitAndClose}
color="primary"
variant="contained">
Update
</Button>
</div>
</Tooltip>
</DialogActions>
</Dialog>
);
}
private handleChange(
propertyName: 'name' | 'description',
event: React.ChangeEvent<HTMLInputElement>
) {
const state = this.state;
state[propertyName] = event.target.value;
this.setState(state);
}
}
return (
<Dialog open={true} onClose={fClose} aria-labelledby="form-dialog-title" id="app-dialog">
<DialogTitle id="form-dialog-title">Update an application</DialogTitle>
<DialogContent>
<DialogContentText>An application is allowed to send messages.</DialogContentText>
<TextField
autoFocus
margin="dense"
className="name"
label="Name *"
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
fullWidth
/>
<TextField
margin="dense"
className="description"
label="Short Description"
value={description}
onChange={(e) => setDescription(e.target.value)}
fullWidth
multiline
/>
<NumberField
margin="dense"
className="priority"
label="Default Priority"
value={defaultPriority}
onChange={(e) => setDefaultPriority(e)}
fullWidth
/>
</DialogContent>
<DialogActions>
<Button onClick={fClose}>Cancel</Button>
<Tooltip title={submitEnabled ? '' : 'name is required'}>
<div>
<Button
className="update"
disabled={!submitEnabled}
onClick={submitAndClose}
color="primary"
variant="contained">
Update
</Button>
</div>
</Tooltip>
</DialogActions>
</Dialog>
);
};

View File

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

View File

@ -1,3 +1,4 @@
import React, {useEffect, useState} from 'react';
import Grid from '@mui/material/Grid';
import IconButton from '@mui/material/IconButton';
import Paper from '@mui/material/Paper';
@ -8,103 +9,89 @@ import TableHead from '@mui/material/TableHead';
import TableRow from '@mui/material/TableRow';
import Delete from '@mui/icons-material/Delete';
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 DefaultPage from '../common/DefaultPage';
import Button from '@mui/material/Button';
import AddClientDialog from './AddClientDialog';
import UpdateDialog from './UpdateClientDialog';
import {observer} from 'mobx-react';
import {observable} from 'mobx';
import {inject, Stores} from '../inject';
import UpdateClientDialog from './UpdateClientDialog';
import {IClient} from '../types';
import CopyableSecret from '../common/CopyableSecret';
import {LastUsedCell} from '../common/LastUsedCell';
import {observer} from 'mobx-react';
import {useStores} from '../stores';
@observer
class Clients extends Component<Stores<'clientStore'>> {
@observable
private showDialog = false;
@observable
private deleteId: false | number = false;
@observable
private updateId: false | number = false;
const Clients = observer(() => {
const {clientStore} = useStores();
const [toDeleteClient, setToDeleteClient] = useState<IClient>();
const [toUpdateClient, setToUpdateClient] = useState<IClient>();
const [createDialog, setCreateDialog] = useState<boolean>(false);
const clients = clientStore.getItems();
public componentDidMount = () => this.props.clientStore.refresh();
useEffect(() => void clientStore.refresh(), []);
public render() {
const {
deleteId,
updateId,
showDialog,
props: {clientStore},
} = this;
const clients = clientStore.getItems();
return (
<DefaultPage
title="Clients"
rightControl={
<Button
id="create-client"
variant="contained"
color="primary"
onClick={() => (this.showDialog = true)}>
Create Client
</Button>
}>
<Grid size={{xs: 12}}>
<Paper elevation={6} style={{overflowX: 'auto'}}>
<Table id="client-table">
<TableHead>
<TableRow style={{textAlign: 'center'}}>
<TableCell>Name</TableCell>
<TableCell style={{width: 200}}>Token</TableCell>
<TableCell>Last Used</TableCell>
<TableCell />
<TableCell />
</TableRow>
</TableHead>
<TableBody>
{clients.map((client: IClient) => (
<Row
key={client.id}
name={client.name}
value={client.token}
lastUsed={client.lastUsed}
fEdit={() => (this.updateId = client.id)}
fDelete={() => (this.deleteId = client.id)}
/>
))}
</TableBody>
</Table>
</Paper>
</Grid>
{showDialog && (
<AddClientDialog
fClose={() => (this.showDialog = false)}
fOnSubmit={clientStore.create}
/>
)}
{updateId !== false && (
<UpdateDialog
fClose={() => (this.updateId = false)}
fOnSubmit={(name) => clientStore.update(updateId, name)}
initialName={clientStore.getByID(updateId).name}
/>
)}
{deleteId !== false && (
<ConfirmDialog
title="Confirm Delete"
text={'Delete ' + clientStore.getByID(deleteId).name + '?'}
fClose={() => (this.deleteId = false)}
fOnSubmit={() => clientStore.remove(deleteId)}
/>
)}
</DefaultPage>
);
}
}
return (
<DefaultPage
title="Clients"
rightControl={
<Button
id="create-client"
variant="contained"
color="primary"
onClick={() => setCreateDialog(true)}>
Create Client
</Button>
}>
<Grid size={12}>
<Paper elevation={6} style={{overflowX: 'auto'}}>
<Table id="client-table">
<TableHead>
<TableRow style={{textAlign: 'center'}}>
<TableCell>Name</TableCell>
<TableCell style={{width: 200}}>Token</TableCell>
<TableCell>Last Used</TableCell>
<TableCell />
<TableCell />
</TableRow>
</TableHead>
<TableBody>
{clients.map((client: IClient) => (
<Row
key={client.id}
name={client.name}
value={client.token}
lastUsed={client.lastUsed}
fEdit={() => setToUpdateClient(client)}
fDelete={() => setToDeleteClient(client)}
/>
))}
</TableBody>
</Table>
</Paper>
</Grid>
{createDialog && (
<AddClientDialog
fClose={() => setCreateDialog(false)}
fOnSubmit={clientStore.create}
/>
)}
{toUpdateClient != null && (
<UpdateClientDialog
fClose={() => setToUpdateClient(undefined)}
fOnSubmit={(name) => clientStore.update(toUpdateClient.id, name)}
initialName={toUpdateClient.name}
/>
)}
{toDeleteClient != null && (
<ConfirmDialog
title="Confirm Delete"
text={'Delete ' + toDeleteClient.name + '?'}
fClose={() => setToDeleteClient(undefined)}
fOnSubmit={() => clientStore.remove(toDeleteClient.id)}
/>
)}
</DefaultPage>
);
});
interface IRowProps {
name: string;
@ -114,7 +101,7 @@ interface IRowProps {
fDelete: VoidFunction;
}
const Row: SFC<IRowProps> = ({name, value, lastUsed, fEdit, fDelete}) => (
const Row = ({name, value, lastUsed, fEdit, fDelete}: IRowProps) => (
<TableRow>
<TableCell>{name}</TableCell>
<TableCell>
@ -127,16 +114,16 @@ const Row: SFC<IRowProps> = ({name, value, lastUsed, fEdit, fDelete}) => (
<LastUsedCell lastUsed={lastUsed} />
</TableCell>
<TableCell align="right" padding="none">
<IconButton onClick={fEdit} className="edit" size="large">
<IconButton onClick={fEdit} className="edit">
<Edit />
</IconButton>
</TableCell>
<TableCell align="right" padding="none">
<IconButton onClick={fDelete} className="delete" size="large">
<IconButton onClick={fDelete} className="delete">
<Delete />
</IconButton>
</TableCell>
</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 Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
@ -6,81 +7,58 @@ import DialogContentText from '@mui/material/DialogContentText';
import DialogTitle from '@mui/material/DialogTitle';
import TextField from '@mui/material/TextField';
import Tooltip from '@mui/material/Tooltip';
import React, {Component} from 'react';
interface IProps {
fClose: VoidFunction;
fOnSubmit: (name: string) => void;
fOnSubmit: (name: string) => Promise<void>;
initialName: string;
}
interface IState {
name: string;
}
const UpdateClientDialog = ({fClose, fOnSubmit, initialName = ''}: IProps) => {
const [name, setName] = useState(initialName);
export default class UpdateDialog extends Component<IProps, IState> {
public state = {name: ''};
const submitEnabled = name.length !== 0;
const submitAndClose = async () => {
await fOnSubmit(name);
fClose();
};
constructor(props: IProps) {
super(props);
this.state = {
name: props.initialName,
};
}
return (
<Dialog open={true} onClose={fClose} aria-labelledby="form-dialog-title" id="client-dialog">
<DialogTitle id="form-dialog-title">Update a Client</DialogTitle>
<DialogContent>
<DialogContentText>
A client manages messages, clients, applications and users (with admin
permissions).
</DialogContentText>
<TextField
autoFocus
margin="dense"
className="name"
label="Name *"
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
fullWidth
/>
</DialogContent>
<DialogActions>
<Button onClick={fClose}>Cancel</Button>
<Tooltip title={submitEnabled ? '' : 'name is required'}>
<div>
<Button
className="update"
disabled={!submitEnabled}
onClick={submitAndClose}
color="primary"
variant="contained">
Update
</Button>
</div>
</Tooltip>
</DialogActions>
</Dialog>
);
};
public render() {
const {fClose, fOnSubmit} = this.props;
const {name} = this.state;
const submitEnabled = this.state.name.length !== 0;
const submitAndClose = () => {
fOnSubmit(name);
fClose();
};
return (
<Dialog
open={true}
onClose={fClose}
aria-labelledby="form-dialog-title"
id="client-dialog">
<DialogTitle id="form-dialog-title">Update a Client</DialogTitle>
<DialogContent>
<DialogContentText>
A client manages messages, clients, applications and users (with admin
permissions).
</DialogContentText>
<TextField
autoFocus
margin="dense"
className="name"
label="Name *"
type="text"
value={name}
onChange={this.handleChange.bind(this, 'name')}
fullWidth
/>
</DialogContent>
<DialogActions>
<Button onClick={fClose}>Cancel</Button>
<Tooltip title={submitEnabled ? '' : 'name is required'}>
<div>
<Button
className="update"
disabled={!submitEnabled}
onClick={submitAndClose}
color="primary"
variant="contained">
Update
</Button>
</div>
</Tooltip>
</DialogActions>
</Dialog>
);
}
private handleChange(propertyName: 'name', event: React.ChangeEvent<HTMLInputElement>) {
const state = this.state;
state[propertyName] = event.target.value;
this.setState(state);
}
}
export default UpdateClientDialog;

View File

@ -1,21 +1,19 @@
import Paper from '@mui/material/Paper';
import {withStyles} from 'tss-react/mui';
import {makeStyles} from 'tss-react/mui';
import * as React from 'react';
const styles = () =>
({
paper: {
padding: 16,
},
} as const);
const useStyles = makeStyles()(() => ({
paper: {
padding: 16,
},
}));
interface IProps {
style?: React.CSSProperties;
classes?: Partial<Record<keyof ReturnType<typeof styles>, string>>;
}
const Container: React.FC<IProps> = ({children, style, ...props}) => {
const classes = withStyles.getClasses(props);
const {classes} = useStyles();
return (
<Paper elevation={6} className={classes.paper} style={style}>
{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 Copy from '@mui/icons-material/FileCopyOutlined';
import VisibilityOff from '@mui/icons-material/VisibilityOff';
import React, {Component, CSSProperties} from 'react';
import {Stores, inject} from '../inject';
import React, {CSSProperties} from 'react';
import {useStores} from '../stores';
interface IProps {
value: string;
style?: CSSProperties;
}
interface IState {
visible: boolean;
}
class CopyableSecret extends Component<IProps & Stores<'snackManager'>, IState> {
public state = {visible: false};
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;
const CopyableSecret = ({value, style}: IProps) => {
const [visible, setVisible] = React.useState(false);
const text = visible ? value : '•••••••••••••••';
const {snackManager} = useStores();
const toggleVisibility = () => setVisible((b) => !b);
const copyToClipboard = async () => {
try {
await navigator.clipboard.writeText(value);
snackManager.snack('Copied to clipboard');
@ -48,6 +25,17 @@ class CopyableSecret extends Component<IProps & Stores<'snackManager'>, IState>
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,48 +1,37 @@
import Fab from '@mui/material/Fab';
import KeyboardArrowUp from '@mui/icons-material/KeyboardArrowUp';
import React, {Component} from 'react';
import React from 'react';
class ScrollUpButton extends Component {
state = {
display: 'none',
opacity: 0,
};
componentDidMount() {
window.addEventListener('scroll', this.scrollHandler);
}
const ScrollUpButton = () => {
const [state, setState] = React.useState({display: 'none', opacity: 0});
React.useEffect(() => {
const scrollHandler = () => {
const currentScrollPos = window.pageYOffset;
const opacity = Math.min(currentScrollPos / 500, 1);
const nextState = {display: currentScrollPos > 0 ? 'inherit' : 'none', opacity};
if (state.display !== nextState.display || state.opacity !== nextState.opacity) {
setState(nextState);
}
};
window.addEventListener('scroll', scrollHandler);
return () => window.removeEventListener('scroll', scrollHandler);
}, []);
componentWillUnmount() {
window.removeEventListener('scroll', this.scrollHandler);
}
scrollHandler = () => {
const currentScrollPos = window.pageYOffset;
const opacity = Math.min(currentScrollPos / 500, 1);
const nextState = {display: currentScrollPos > 0 ? 'inherit' : 'none', opacity};
if (this.state.display !== nextState.display || this.state.opacity !== nextState.opacity) {
this.setState(nextState);
}
};
public render() {
return (
<Fab
color="primary"
style={{
position: 'fixed',
bottom: '30px',
right: '30px',
zIndex: 100000,
display: this.state.display,
opacity: this.state.opacity,
}}
onClick={this.scrollUp}>
<KeyboardArrowUp />
</Fab>
);
}
private scrollUp = () => window.scrollTo(0, 0);
}
return (
<Fab
color="primary"
style={{
position: 'fixed',
bottom: '30px',
right: '30px',
zIndex: 100000,
display: state.display,
opacity: state.opacity,
}}
onClick={() => window.scrollTo(0, 0)}>
<KeyboardArrowUp />
</Fab>
);
};
export default ScrollUpButton;

View File

@ -1,3 +1,4 @@
import React, {useState} from 'react';
import Button from '@mui/material/Button';
import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
@ -5,64 +6,58 @@ import DialogContent from '@mui/material/DialogContent';
import DialogTitle from '@mui/material/DialogTitle';
import TextField from '@mui/material/TextField';
import Tooltip from '@mui/material/Tooltip';
import React, {Component} from 'react';
import {observable} from 'mobx';
import {observer} from 'mobx-react';
import {inject, Stores} from '../inject';
import {useStores} from '../stores';
interface IProps {
fClose: VoidFunction;
}
@observer
class SettingsDialog extends Component<IProps & Stores<'currentUser'>> {
@observable
private pass = '';
const SettingsDialog = observer(({fClose}: IProps) => {
const [pass, setPass] = useState('');
const {currentUser} = useStores();
public render() {
const {pass} = this;
const {fClose, currentUser} = this.props;
const submitAndClose = () => {
currentUser.changePassword(pass);
fClose();
};
return (
<Dialog
open={true}
onClose={fClose}
aria-labelledby="form-dialog-title"
id="changepw-dialog">
<DialogTitle id="form-dialog-title">Change Password</DialogTitle>
<DialogContent>
<TextField
className="newpass"
autoFocus
margin="dense"
type="password"
label="New Password *"
value={pass}
onChange={(e) => (this.pass = e.target.value)}
fullWidth
/>
</DialogContent>
<DialogActions>
<Button onClick={fClose}>Cancel</Button>
<Tooltip title={pass.length !== 0 ? '' : 'Password is required'}>
<div>
<Button
className="change"
disabled={pass.length === 0}
onClick={submitAndClose}
color="primary"
variant="contained">
Change
</Button>
</div>
</Tooltip>
</DialogActions>
</Dialog>
);
}
}
const submitAndClose = async () => {
currentUser.changePassword(pass);
fClose();
};
export default inject('currentUser')(SettingsDialog);
return (
<Dialog
open={true}
onClose={fClose}
aria-labelledby="form-dialog-title"
id="changepw-dialog">
<DialogTitle id="form-dialog-title">Change Password</DialogTitle>
<DialogContent>
<TextField
className="newpass"
autoFocus
margin="dense"
type="password"
label="New Password *"
value={pass}
onChange={(e) => setPass(e.target.value)}
fullWidth
/>
</DialogContent>
<DialogActions>
<Button onClick={fClose}>Cancel</Button>
<Tooltip title={pass.length !== 0 ? '' : 'Password is required'}>
<div>
<Button
className="change"
disabled={pass.length === 0}
onClick={submitAndClose}
color="primary"
variant="contained">
Change
</Button>
</div>
</Tooltip>
</DialogActions>
</Dialog>
);
});
export default SettingsDialog;

View File

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

View File

@ -2,7 +2,7 @@ import AppBar from '@mui/material/AppBar';
import Button, {ButtonProps} from '@mui/material/Button';
import IconButton from '@mui/material/IconButton';
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 Typography from '@mui/material/Typography';
import AccountCircle from '@mui/icons-material/AccountCircle';
@ -14,62 +14,59 @@ import GitHubIcon from '@mui/icons-material/GitHub';
import MenuIcon from '@mui/icons-material/Menu';
import Apps from '@mui/icons-material/Apps';
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 {observer} from 'mobx-react';
import {useMediaQuery} from '@mui/material';
const styles = (theme: Theme) =>
({
appBar: {
zIndex: theme.zIndex.drawer + 1,
[theme.breakpoints.down('sm')]: {
paddingBottom: 10,
},
const useStyles = makeStyles()((theme: Theme) => ({
appBar: {
zIndex: theme.zIndex.drawer + 1,
[theme.breakpoints.down('sm')]: {
paddingBottom: 10,
},
toolbar: {
},
toolbar: {
justifyContent: 'space-between',
[theme.breakpoints.down('sm')]: {
flexWrap: 'wrap',
},
},
menuButtons: {
display: 'flex',
[theme.breakpoints.down('md')]: {
flex: 1,
},
justifyContent: 'center',
[theme.breakpoints.down('sm')]: {
flexBasis: '100%',
marginTop: 5,
order: 1,
height: 50,
justifyContent: 'space-between',
[theme.breakpoints.down('sm')]: {
flexWrap: 'wrap',
},
},
menuButtons: {
display: 'flex',
[theme.breakpoints.down('md')]: {
flex: 1,
},
justifyContent: 'center',
[theme.breakpoints.down('sm')]: {
flexBasis: '100%',
marginTop: 5,
order: 1,
height: 50,
justifyContent: 'space-between',
alignItems: 'center',
},
},
title: {
[theme.breakpoints.up('md')]: {
flex: 1,
},
display: 'flex',
alignItems: 'center',
},
titleName: {
paddingRight: 10,
},
title: {
[theme.breakpoints.up('md')]: {
flex: 1,
},
link: {
color: 'inherit',
textDecoration: 'none',
},
} as const);
display: 'flex',
alignItems: 'center',
},
titleName: {
paddingRight: 10,
},
link: {
color: 'inherit',
textDecoration: 'none',
},
}));
interface IProps {
loggedIn: boolean;
name: string;
admin: boolean;
version: string;
classes?: Partial<Record<keyof ReturnType<typeof styles>, string>>;
toggleTheme: VoidFunction;
showSettings: VoidFunction;
logout: VoidFunction;
@ -77,107 +74,123 @@ interface IProps {
setNavOpen: (open: boolean) => void;
}
@observer
class Header extends Component<IProps> {
public render() {
const {version, name, loggedIn, admin, toggleTheme, logout, style, setNavOpen} = this.props;
const Header = ({
version,
name,
loggedIn,
admin,
toggleTheme,
logout,
style,
setNavOpen,
showSettings,
}: IProps) => {
const {classes} = useStyles();
const classes = withStyles.getClasses(this.props);
return (
<AppBar
sx={{position: {xs: 'sticky', sm: 'fixed'}}}
style={style}
className={classes.appBar}>
<Toolbar className={classes.toolbar}>
<div className={classes.title}>
<Link to="/" className={classes.link}>
<Typography variant="h5" className={classes.titleName} color="inherit">
Gotify
</Typography>
</Link>
<a
href={'https://github.com/gotify/server/releases/tag/v' + version}
className={classes.link}>
<Typography variant="button" color="inherit">
@{version}
</Typography>
</a>
</div>
{loggedIn && this.renderButtons(name, admin, logout, setNavOpen)}
<div>
<IconButton onClick={toggleTheme} color="inherit" size="large">
<Highlight />
</IconButton>
<a
href="https://github.com/gotify/server"
className={classes.link}
target="_blank"
rel="noopener noreferrer">
<IconButton color="inherit" size="large">
<GitHubIcon />
</IconButton>
</a>
</div>
</Toolbar>
</AppBar>
);
}
private renderButtons(
name: string,
admin: boolean,
logout: VoidFunction,
setNavOpen: (open: boolean) => void
) {
const classes = withStyles.getClasses(this.props);
const {showSettings} = this.props;
return (
<div className={classes.menuButtons}>
<ResponsiveButton
sx={{display: {sm: 'none', xs: 'block'}}}
icon={<MenuIcon />}
onClick={() => setNavOpen(true)}
label="menu"
color="inherit"
/>
{admin && (
<Link className={classes.link} to="/users" id="navigate-users">
<ResponsiveButton
icon={<SupervisorAccount />}
label="users"
color="inherit"
/>
return (
<AppBar
sx={{position: {xs: 'sticky', sm: 'fixed'}}}
style={style}
className={classes.appBar}>
<Toolbar className={classes.toolbar}>
<div className={classes.title}>
<Link to="/" className={classes.link}>
<Typography variant="h5" className={classes.titleName} color="inherit">
Gotify
</Typography>
</Link>
<a
href={'https://github.com/gotify/server/releases/tag/v' + version}
className={classes.link}>
<Typography variant="button" color="inherit">
@{version}
</Typography>
</a>
</div>
{loggedIn && (
<Buttons
admin={admin}
name={name}
logout={logout}
setNavOpen={setNavOpen}
showSettings={showSettings}
/>
)}
<Link className={classes.link} to="/applications" id="navigate-apps">
<ResponsiveButton icon={<Chat />} label="apps" color="inherit" />
<div>
<IconButton onClick={toggleTheme} color="inherit" size="large">
<Highlight />
</IconButton>
<a
href="https://github.com/gotify/server"
className={classes.link}
target="_blank"
rel="noopener noreferrer">
<IconButton color="inherit" size="large">
<GitHubIcon />
</IconButton>
</a>
</div>
</Toolbar>
</AppBar>
);
};
const Buttons = ({
showSettings,
name,
admin,
logout,
setNavOpen,
}: {
name: string;
admin: boolean;
logout: VoidFunction;
setNavOpen: (open: boolean) => void;
showSettings: VoidFunction;
}) => {
const {classes} = useStyles();
return (
<div className={classes.menuButtons}>
<ResponsiveButton
sx={{display: {sm: 'none', xs: 'block'}}}
icon={<MenuIcon />}
onClick={() => setNavOpen(true)}
label="menu"
color="inherit"
/>
{admin && (
<Link className={classes.link} to="/users" id="navigate-users">
<ResponsiveButton icon={<SupervisorAccount />} label="users" color="inherit" />
</Link>
<Link className={classes.link} to="/clients" id="navigate-clients">
<ResponsiveButton icon={<DevicesOther />} label="clients" color="inherit" />
</Link>
<Link className={classes.link} to="/plugins" id="navigate-plugins">
<ResponsiveButton icon={<Apps />} label="plugins" color="inherit" />
</Link>
<ResponsiveButton
icon={<AccountCircle />}
label={name}
onClick={showSettings}
id="changepw"
color="inherit"
/>
<ResponsiveButton
icon={<ExitToApp />}
label="Logout"
onClick={logout}
id="logout"
color="inherit"
/>
</div>
);
}
}
)}
<Link className={classes.link} to="/applications" id="navigate-apps">
<ResponsiveButton icon={<Chat />} label="apps" color="inherit" />
</Link>
<Link className={classes.link} to="/clients" id="navigate-clients">
<ResponsiveButton icon={<DevicesOther />} label="clients" color="inherit" />
</Link>
<Link className={classes.link} to="/plugins" id="navigate-plugins">
<ResponsiveButton icon={<Apps />} label="plugins" color="inherit" />
</Link>
<ResponsiveButton
icon={<AccountCircle />}
label={name}
onClick={showSettings}
id="changepw"
color="inherit"
/>
<ResponsiveButton
icon={<ExitToApp />}
label="Logout"
onClick={logout}
id="logout"
color="inherit"
/>
</div>
);
};
const ResponsiveButton: React.FC<{
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 {withStyles} from 'tss-react/mui';
import {makeStyles} from 'tss-react/mui';
import CssBaseline from '@mui/material/CssBaseline';
import * as React from 'react';
import {HashRouter, Redirect, Route, Switch} from 'react-router-dom';
@ -18,11 +18,10 @@ import Login from '../user/Login';
import Messages from '../message/Messages';
import Users from '../user/Users';
import {observer} from 'mobx-react';
import {observable} from 'mobx';
import {inject, Stores} from '../inject';
import {ConnectionErrorBanner} from '../common/ConnectionErrorBanner';
import {useStores} from '../stores';
const styles = (theme: Theme) => ({
const useStyles = makeStyles()((theme: Theme) => ({
content: {
margin: '0 auto',
marginTop: 64,
@ -32,7 +31,7 @@ const styles = (theme: Theme) => ({
marginTop: 0,
},
},
});
}));
const localStorageThemeKey = 'gotify-theme';
type ThemeKey = 'dark' | 'light';
@ -52,127 +51,103 @@ const themeMap: Record<ThemeKey, Theme> = {
const isThemeKey = (value: string | null): value is ThemeKey =>
value === 'light' || value === 'dark';
interface LayoutProps {
classes?: Partial<Record<keyof ReturnType<typeof styles>, string>>;
}
const Layout = observer(() => {
const {
currentUser: {
loggedIn,
authenticating,
user: {name, admin},
logout,
tryReconnect,
connectionErrorMessage,
},
} = useStores();
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 loginRoute = () => (loggedIn ? <Redirect to="/" /> : <Login />);
const {version} = config.get('version');
const [navOpen, setNavOpen] = React.useState(false);
const [showSettings, setShowSettings] = React.useState(false);
@observer
class Layout extends React.Component<LayoutProps & Stores<'currentUser' | 'snackManager'>> {
@observable
private currentTheme: ThemeKey = 'dark';
@observable
private showSettings = false;
@observable
private navOpen = false;
const toggleTheme = () => {
const next = currentTheme === 'dark' ? 'light' : 'dark';
setCurrentTheme(next);
localStorage.setItem(localStorageThemeKey, next);
};
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 {
currentUser: {
loggedIn,
authenticating,
user: {name, admin},
logout,
tryReconnect,
connectionErrorMessage,
},
} = this.props;
const classes = withStyles.getClasses(this.props);
const theme = themeMap[currentTheme];
const loginRoute = () => (loggedIn ? <Redirect to="/" /> : <Login />);
const {version} = config.get('version');
return (
<StyledEngineProvider injectFirst>
<ThemeProvider theme={theme}>
<HashRouter>
<div>
{!connectionErrorMessage ? null : (
<ConnectionErrorBanner
height={64}
retry={() => tryReconnect()}
message={connectionErrorMessage}
/>
)}
<div style={{display: 'flex', flexDirection: 'column'}}>
<CssBaseline />
<Header
style={{top: !connectionErrorMessage ? 0 : 64}}
admin={admin}
name={name}
version={version}
return (
<StyledEngineProvider injectFirst>
<ThemeProvider theme={theme}>
<HashRouter>
<div>
{!connectionErrorMessage ? null : (
<ConnectionErrorBanner
height={64}
retry={() => tryReconnect()}
message={connectionErrorMessage}
/>
)}
<div style={{display: 'flex', flexDirection: 'column'}}>
<CssBaseline />
<Header
admin={admin}
name={name}
style={{top: !connectionErrorMessage ? 0 : 64}}
version={version}
loggedIn={loggedIn}
toggleTheme={toggleTheme}
showSettings={() => setShowSettings(true)}
logout={logout}
setNavOpen={setNavOpen}
/>
<div style={{display: 'flex'}}>
<Navigation
loggedIn={loggedIn}
toggleTheme={this.toggleTheme.bind(this)}
showSettings={() => (this.showSettings = true)}
logout={logout}
setNavOpen={this.setNavOpen.bind(this)}
navOpen={navOpen}
setNavOpen={setNavOpen}
/>
<div style={{display: 'flex'}}>
<Navigation
loggedIn={loggedIn}
navOpen={this.navOpen}
setNavOpen={this.setNavOpen.bind(this)}
/>
<main className={classes.content}>
<Switch>
{authenticating ? (
<Route path="/">
<LoadingSpinner />
</Route>
) : null}
<Route exact path="/login" render={loginRoute} />
{loggedIn ? null : <Redirect to="/login" />}
<Route exact path="/" component={Messages} />
<Route
exact
path="/messages/:id"
component={Messages}
/>
<Route
exact
path="/applications"
component={Applications}
/>
<Route exact path="/clients" component={Clients} />
<Route exact path="/users" component={Users} />
<Route exact path="/plugins" component={Plugins} />
<Route
exact
path="/plugins/:id"
component={PluginDetailView}
/>
</Switch>
</main>
</div>
{showSettings && (
<SettingsDialog fClose={() => (this.showSettings = false)} />
)}
<ScrollUpButton />
<SnackBarHandler />
<main className={classes.content}>
<Switch>
{authenticating ? (
<Route path="/">
<LoadingSpinner />
</Route>
) : null}
<Route exact path="/login" render={loginRoute} />
{loggedIn ? null : <Redirect to="/login" />}
<Route exact path="/" component={Messages} />
<Route exact path="/messages/:id" component={Messages} />
<Route
exact
path="/applications"
component={Applications}
/>
<Route exact path="/clients" component={Clients} />
<Route exact path="/users" component={Users} />
<Route exact path="/plugins" component={Plugins} />
<Route
exact
path="/plugins/:id"
component={PluginDetailView}
/>
</Switch>
</main>
</div>
{showSettings && (
<SettingsDialog fClose={() => setShowSettings(false)} />
)}
<ScrollUpButton />
<SnackBarHandler />
</div>
</HashRouter>
</ThemeProvider>
</StyledEngineProvider>
);
}
</div>
</HashRouter>
</ThemeProvider>
</StyledEngineProvider>
);
});
private toggleTheme() {
this.currentTheme = this.currentTheme === 'dark' ? 'light' : 'dark';
localStorage.setItem(localStorageThemeKey, this.currentTheme);
}
}
export default withStyles(inject('currentUser', 'snackManager')(Layout), styles);
export default Layout;

View File

@ -1,10 +1,9 @@
import Divider from '@mui/material/Divider';
import Drawer from '@mui/material/Drawer';
import {Theme} from '@mui/material/styles';
import React, {Component} from 'react';
import React from 'react';
import {Link} from 'react-router-dom';
import {observer} from 'mobx-react';
import {inject, Stores} from '../inject';
import {mayAllowPermission, requestPermission} from '../snack/browserNotification';
import {
Button,
@ -17,108 +16,100 @@ import {
} from '@mui/material';
import {DrawerProps} from '@mui/material/Drawer/Drawer';
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) =>
({
root: {
height: '100%',
},
drawerPaper: {
position: 'relative',
width: 250,
minHeight: '100%',
height: '100vh',
},
// eslint-disable-next-line
toolbar: theme.mixins.toolbar as any,
link: {
color: 'inherit',
textDecoration: 'none',
},
} as const);
const useStyles = makeStyles()((theme: Theme) => ({
root: {
height: '100%',
},
drawerPaper: {
position: 'relative',
width: 250,
minHeight: '100%',
height: '100vh',
},
// eslint-disable-next-line
toolbar: theme.mixins.toolbar as any,
link: {
color: 'inherit',
textDecoration: 'none',
},
}));
interface IProps {
loggedIn: boolean;
navOpen: boolean;
classes?: Partial<Record<keyof ReturnType<typeof styles>, string>>;
setNavOpen: (open: boolean) => void;
}
@observer
class Navigation extends Component<
IProps & Stores<'appStore'>,
{showRequestNotification: boolean}
> {
public state = {showRequestNotification: mayAllowPermission()};
const Navigation = observer(({loggedIn, navOpen, setNavOpen}: IProps) => {
const [showRequestNotification, setShowRequestNotification] =
React.useState(mayAllowPermission);
const {classes} = useStyles();
const {appStore} = useStores();
const apps = appStore.getItems();
public render() {
const {loggedIn, appStore, navOpen, setNavOpen} = this.props;
const classes = withStyles.getClasses(this.props);
const {showRequestNotification} = this.state;
const apps = appStore.getItems();
const userApps =
apps.length === 0
? null
: apps.map((app) => (
<Link
onClick={() => setNavOpen(false)}
className={`${classes.link} item`}
to={'/messages/' + app.id}
key={app.id}>
<ListItemButton>
<ListItemAvatar style={{minWidth: 42}}>
<Avatar
style={{width: 32, height: 32}}
src={app.image}
variant="square"
/>
</ListItemAvatar>
<ListItemText primary={app.name} />
</ListItemButton>
</Link>
));
const userApps =
apps.length === 0
? null
: apps.map((app) => (
<Link
onClick={() => setNavOpen(false)}
className={`${classes.link} item`}
to={'/messages/' + app.id}
key={app.id}>
<ListItemButton>
<ListItemAvatar style={{minWidth: 42}}>
<Avatar
style={{width: 32, height: 32}}
src={app.image}
variant="square"
/>
</ListItemAvatar>
<ListItemText primary={app.name} />
</ListItemButton>
</Link>
));
const placeholderItems = [
<ListItemButton disabled key={-1}>
<ListItemText primary="Some Server" />
</ListItemButton>,
<ListItemButton disabled key={-2}>
<ListItemText primary="A Raspberry PI" />
</ListItemButton>,
];
const placeholderItems = [
<ListItemButton disabled key={-1}>
<ListItemText primary="Some Server" />
</ListItemButton>,
<ListItemButton disabled key={-2}>
<ListItemText primary="A Raspberry PI" />
</ListItemButton>,
];
return (
<ResponsiveDrawer
classes={{root: classes.root, paper: classes.drawerPaper}}
navOpen={navOpen}
setNavOpen={setNavOpen}
id="message-navigation">
<div className={classes.toolbar} />
<Link className={classes.link} to="/" onClick={() => setNavOpen(false)}>
<ListItemButton disabled={!loggedIn} className="all">
<ListItemText primary="All Messages" />
</ListItemButton>
</Link>
<Divider />
<div>{loggedIn ? userApps : placeholderItems}</div>
<Divider />
<Typography align="center" style={{marginTop: 10}}>
{showRequestNotification ? (
<Button
onClick={() => {
requestPermission();
this.setState({showRequestNotification: false});
}}>
Enable Notifications
</Button>
) : null}
</Typography>
</ResponsiveDrawer>
);
}
}
return (
<ResponsiveDrawer
classes={{root: classes.root, paper: classes.drawerPaper}}
navOpen={navOpen}
setNavOpen={setNavOpen}
id="message-navigation">
<div className={classes.toolbar} />
<Link className={classes.link} to="/" onClick={() => setNavOpen(false)}>
<ListItemButton disabled={!loggedIn} className="all">
<ListItemText primary="All Messages" />
</ListItemButton>
</Link>
<Divider />
<div>{loggedIn ? userApps : placeholderItems}</div>
<Divider />
<Typography align="center" style={{marginTop: 10}}>
{showRequestNotification ? (
<Button
onClick={() => {
requestPermission();
setShowRequestNotification(false);
}}>
Enable Notifications
</Button>
) : null}
</Typography>
</ResponsiveDrawer>
);
});
const ResponsiveDrawer: React.FC<
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 {RouteComponentProps} from 'react-router';
import React from 'react';
import {useParams} from 'react-router';
import {Markdown} from '../common/Markdown';
import {UnControlled as CodeMirror} from 'react-codemirror2';
import 'codemirror/lib/codemirror.css';
@ -14,110 +14,80 @@ import Typography from '@mui/material/Typography';
import DefaultPage from '../common/DefaultPage';
import * as config from '../config';
import Container from '../common/Container';
import {inject, Stores} from '../inject';
import {IPlugin} from '../types';
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 {
displayText: string | null;
currentConfig: string | null;
}
const pluginInfo = pluginStore.getByIDOrUndefined(pluginID);
class PluginDetailView extends Component<IProps & Stores<'pluginStore'>, IState> {
private pluginID: number = parseInt(this.props.match.params.id, 10);
private pluginInfo = () => this.props.pluginStore.getByID(this.pluginID);
public state: IState = {
displayText: null,
currentConfig: null,
const refreshFeatures = async () => {
await pluginStore.refreshIfMissing(pluginID);
await Promise.all([refreshConfigurer(), refreshDisplayer()]);
};
public componentWillMount() {
this.refreshFeatures();
}
React.useEffect(() => void refreshFeatures(), [pluginID]);
public componentWillReceiveProps(nextProps: IProps & Stores<'pluginStore'>) {
this.pluginID = parseInt(nextProps.match.params.id, 10);
this.refreshFeatures();
}
private async refreshFeatures() {
await this.props.pluginStore.refreshIfMissing(this.pluginID);
return await Promise.all([this.refreshConfigurer(), this.refreshDisplayer()]);
}
private async refreshConfigurer() {
const {
props: {pluginStore},
} = this;
if (this.pluginInfo().capabilities.indexOf('configurer') !== -1) {
const response = await pluginStore.requestConfig(this.pluginID);
this.setState({currentConfig: response});
const refreshConfigurer = async () => {
if (pluginInfo?.capabilities.indexOf('configurer') !== -1) {
setCurrentConfig(await pluginStore.requestConfig(pluginID));
}
};
const refreshDisplayer = async () => {
if (pluginInfo?.capabilities.indexOf('displayer') !== -1) {
setDisplayText(await pluginStore.requestDisplay(pluginID));
}
};
if (pluginInfo == null) {
return <LoadingSpinner />;
}
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});
}
}
const handleSaveConfig = async (newConfig: string) => {
await pluginStore.changeConfig(pluginID, newConfig);
await refreshFeatures();
};
public render() {
const pluginInfo = this.props.pluginStore.getByIDOrUndefined(this.pluginID);
if (pluginInfo === undefined) {
return <LoadingSpinner />;
}
return (
<DefaultPage title={pluginInfo.name} maxWidth={1000}>
<PanelWrapper name={'Plugin Info'} icon={Info}>
<PluginInfo pluginInfo={pluginInfo} />
return (
<DefaultPage title={pluginInfo.name} maxWidth={1000}>
<PanelWrapper name={'Plugin Info'} icon={Info}>
<PluginInfo pluginInfo={pluginInfo} />
</PanelWrapper>
{pluginInfo.capabilities.indexOf('configurer') !== -1 ? (
<PanelWrapper
name={'Configurer'}
description={'This is the configuration panel for this plugin.'}
icon={Build}
refresh={refreshConfigurer}>
<ConfigurerPanel
pluginInfo={pluginInfo}
initialConfig={currentConfig != null ? currentConfig : 'Loading...'}
save={handleSaveConfig}
/>
</PanelWrapper>
{pluginInfo.capabilities.indexOf('configurer') !== -1 ? (
<PanelWrapper
name={'Configurer'}
description={'This is the configuration panel for this plugin.'}
icon={Build}
refresh={this.refreshConfigurer.bind(this)}>
<ConfigurerPanel
pluginInfo={pluginInfo}
initialConfig={
this.state.currentConfig !== null
? this.state.currentConfig
: 'Loading...'
}
save={async (newConfig) => {
await this.props.pluginStore.changeConfig(this.pluginID, newConfig);
await this.refreshFeatures();
}}
/>
</PanelWrapper>
) : null}{' '}
{pluginInfo.capabilities.indexOf('displayer') !== -1 ? (
<PanelWrapper
name={'Displayer'}
description={'This is the information generated by the plugin.'}
refresh={this.refreshDisplayer.bind(this)}
icon={Subject}>
<DisplayerPanel
pluginInfo={pluginInfo}
displayText={
this.state.displayText !== null
? this.state.displayText
: 'Loading...'
}
/>
</PanelWrapper>
) : null}
</DefaultPage>
);
}
}
) : null}{' '}
{pluginInfo.capabilities.indexOf('displayer') !== -1 ? (
<PanelWrapper
name={'Displayer'}
description={'This is the information generated by the plugin.'}
refresh={refreshDisplayer}
icon={Subject}>
<DisplayerPanel
pluginInfo={pluginInfo}
displayText={displayText != null ? displayText : 'Loading...'}
/>
</PanelWrapper>
) : null}
</DefaultPage>
);
};
interface IPanelWrapperProps {
name: string;
@ -178,49 +148,43 @@ interface IConfigurerPanelProps {
initialConfig: string;
save: (newConfig: string) => Promise<void>;
}
class ConfigurerPanel extends Component<IConfigurerPanelProps, {unsavedChanges: string | null}> {
public state = {unsavedChanges: null};
public render() {
return (
<div>
<CodeMirror
value={this.props.initialConfig}
options={{
mode: 'yaml',
theme: 'material',
lineNumbers: true,
}}
onChange={(_, _1, value) => {
let newConf: string | null = value;
if (value === this.props.initialConfig) {
newConf = null;
}
this.setState({unsavedChanges: newConf});
}}
/>
<br />
<Button
variant="contained"
color="primary"
fullWidth={true}
disabled={
this.state.unsavedChanges === null ||
this.state.unsavedChanges === this.props.initialConfig
const ConfigurerPanel = ({initialConfig, save}: IConfigurerPanelProps) => {
const [unsavedChanges, setUnsavedChanges] = React.useState<string | null>(null);
return (
<div>
<CodeMirror
value={initialConfig}
options={{
mode: 'yaml',
theme: 'material',
lineNumbers: true,
}}
onChange={(_, _1, value) => {
let newConf: string | null = value;
if (value === initialConfig) {
newConf = null;
}
className="config-save"
onClick={() => {
const newConfig = this.state.unsavedChanges;
this.props.save(newConfig!).then(() => {
this.setState({unsavedChanges: null});
});
}}>
<Typography variant="button">Save</Typography>
</Button>
</div>
);
}
}
setUnsavedChanges(newConf);
}}
/>
<br />
<Button
variant="contained"
color="primary"
fullWidth={true}
disabled={unsavedChanges === null || unsavedChanges === initialConfig}
className="config-save"
onClick={() => {
const newConfig = unsavedChanges;
save(newConfig!).then(() => {
setUnsavedChanges(null);
});
}}>
<Typography variant="button">Save</Typography>
</Button>
</div>
);
};
interface IDisplayerPanelProps {
pluginInfo: IPlugin;
@ -232,58 +196,57 @@ const DisplayerPanel: React.FC<IDisplayerPanelProps> = ({displayText}) => (
</Typography>
);
class PluginInfo extends Component<{pluginInfo: IPlugin}> {
public render() {
const {
props: {
pluginInfo: {name, author, modulePath, website, license, capabilities, id, token},
},
} = this;
return (
<div style={{wordWrap: 'break-word'}}>
{name ? (
<Typography variant="body2" className="name">
Name: <span>{name}</span>
</Typography>
) : null}
{author ? (
<Typography variant="body2" className="author">
Author: <span>{author}</span>
</Typography>
) : null}
<Typography variant="body2" className="module-path">
Module Path: <span>{modulePath}</span>
</Typography>
{website ? (
<Typography variant="body2" className="website">
Website: <span>{website}</span>
</Typography>
) : null}
{license ? (
<Typography variant="body2" className="license">
License: <span>{license}</span>
</Typography>
) : null}
<Typography variant="body2" className="capabilities">
Capabilities: <span>{capabilities.join(', ')}</span>
</Typography>
{capabilities.indexOf('webhooker') !== -1 ? (
<Typography variant="body2">
Custom Route Prefix:{' '}
{((url) => (
<a
href={url}
target="_blank"
rel="noopener noreferrer"
className="custom-route">
{url}
</a>
))(`${config.get('url')}plugin/${id}/custom/${token}/`)}
</Typography>
) : null}
</div>
);
}
interface IPluginInfo {
pluginInfo: IPlugin;
}
export default inject('pluginStore')(PluginDetailView);
const PluginInfo = ({pluginInfo}: IPluginInfo) => {
const {name, author, modulePath, website, license, capabilities, id, token} = pluginInfo;
return (
<div style={{wordWrap: 'break-word'}}>
{name ? (
<Typography variant="body2" className="name">
Name: <span>{name}</span>
</Typography>
) : null}
{author ? (
<Typography variant="body2" className="author">
Author: <span>{author}</span>
</Typography>
) : null}
<Typography variant="body2" className="module-path">
Module Path: <span>{modulePath}</span>
</Typography>
{website ? (
<Typography variant="body2" className="website">
Website: <span>{website}</span>
</Typography>
) : null}
{license ? (
<Typography variant="body2" className="license">
License: <span>{license}</span>
</Typography>
) : null}
<Typography variant="body2" className="capabilities">
Capabilities: <span>{capabilities.join(', ')}</span>
</Typography>
{capabilities.indexOf('webhooker') !== -1 ? (
<Typography variant="body2">
Custom Route Prefix:{' '}
{((url) => (
<a
href={url}
target="_blank"
rel="noopener noreferrer"
className="custom-route">
{url}
</a>
))(`${config.get('url')}plugin/${id}/custom/${token}/`)}
</Typography>
) : null}
</div>
);
};
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 Grid from '@mui/material/Grid';
import Paper from '@mui/material/Paper';
@ -12,56 +12,47 @@ import {Switch, Button} from '@mui/material';
import DefaultPage from '../common/DefaultPage';
import CopyableSecret from '../common/CopyableSecret';
import {observer} from 'mobx-react';
import {inject, Stores} from '../inject';
import {IPlugin} from '../types';
import {useStores} from '../stores';
@observer
class Plugins extends Component<Stores<'pluginStore'>> {
public componentDidMount = () => this.props.pluginStore.refresh();
public render() {
const {
props: {pluginStore},
} = this;
const plugins = pluginStore.getItems();
return (
<DefaultPage title="Plugins" maxWidth={1000}>
<Grid size={{xs: 12}}>
<Paper elevation={6} style={{overflowX: 'auto'}}>
<Table id="plugin-table">
<TableHead>
<TableRow>
<TableCell>ID</TableCell>
<TableCell>Enabled</TableCell>
<TableCell>Name</TableCell>
<TableCell>Token</TableCell>
<TableCell>Details</TableCell>
</TableRow>
</TableHead>
<TableBody>
{plugins.map((plugin: IPlugin) => (
<Row
key={plugin.token}
id={plugin.id}
token={plugin.token}
name={plugin.name}
enabled={plugin.enabled}
fToggleStatus={() =>
this.props.pluginStore.changeEnabledState(
plugin.id,
!plugin.enabled
)
}
/>
))}
</TableBody>
</Table>
</Paper>
</Grid>
</DefaultPage>
);
}
}
const Plugins = observer(() => {
const {pluginStore} = useStores();
React.useEffect(() => void pluginStore.refresh(), []);
const plugins = pluginStore.getItems();
return (
<DefaultPage title="Plugins" maxWidth={1000}>
<Grid size={{xs: 12}}>
<Paper elevation={6} style={{overflowX: 'auto'}}>
<Table id="plugin-table">
<TableHead>
<TableRow>
<TableCell>ID</TableCell>
<TableCell>Enabled</TableCell>
<TableCell>Name</TableCell>
<TableCell>Token</TableCell>
<TableCell>Details</TableCell>
</TableRow>
</TableHead>
<TableBody>
{plugins.map((plugin: IPlugin) => (
<Row
key={plugin.token}
id={plugin.id}
token={plugin.token}
name={plugin.name}
enabled={plugin.enabled}
fToggleStatus={() =>
pluginStore.changeEnabledState(plugin.id, !plugin.enabled)
}
/>
))}
</TableBody>
</Table>
</Paper>
</Grid>
</DefaultPage>
);
});
interface IRowProps {
id: number;
@ -96,4 +87,4 @@ const Row: SFC<IRowProps> = observer(({name, id, token, enabled, fToggleStatus})
</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,118 +7,101 @@ import FormControlLabel from '@mui/material/FormControlLabel';
import Switch from '@mui/material/Switch';
import TextField from '@mui/material/TextField';
import Tooltip from '@mui/material/Tooltip';
import React, {ChangeEvent, Component} from 'react';
import React from 'react';
interface IProps {
name?: string;
admin?: boolean;
fClose: VoidFunction;
fOnSubmit: (name: string, pass: string, admin: boolean) => void;
fOnSubmit: (name: string, pass: string, admin: boolean) => Promise<void>;
isEdit?: boolean;
}
interface IState {
name: string;
pass: string;
admin: boolean;
}
const AddEditUserDialog = ({
fClose,
fOnSubmit,
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> {
public state = {
name: this.props.name ?? '',
pass: '',
admin: this.props.admin ?? false,
const namePresent = name.length !== 0;
const passPresent = pass.length !== 0 || isEdit;
const submitAndClose = async () => {
await fOnSubmit(name, pass, admin);
fClose();
};
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();
};
return (
<Dialog
open={true}
onClose={fClose}
aria-labelledby="form-dialog-title"
id="add-edit-user-dialog">
<DialogTitle id="form-dialog-title">
{isEdit ? 'Edit ' + this.props.name : 'Add a user'}
</DialogTitle>
<DialogContent>
<TextField
autoFocus
margin="dense"
className="name"
label="Username *"
value={name}
name="username"
id="username"
onChange={this.handleChange.bind(this, 'name')}
fullWidth
/>
<TextField
margin="dense"
className="password"
type="password"
value={pass}
fullWidth
label={isEdit ? 'Password (empty if no change)' : 'Password *'}
name="password"
id="password"
onChange={this.handleChange.bind(this, 'pass')}
/>
<FormControlLabel
control={
<Switch
checked={admin}
className="admin-rights"
onChange={this.handleChecked.bind(this, 'admin')}
value="admin"
/>
}
label="has administrator rights"
/>
</DialogContent>
<DialogActions>
<Button onClick={fClose}>Cancel</Button>
<Tooltip
placement={'bottom-start'}
title={
namePresent
? passPresent
? ''
: 'password is required'
: 'username is required'
}>
<div>
<Button
className="save-create"
disabled={!passPresent || !namePresent}
onClick={submitAndClose}
color="primary"
variant="contained">
{isEdit ? 'Save' : 'Create'}
</Button>
</div>
</Tooltip>
</DialogActions>
</Dialog>
);
}
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);
}
}
return (
<Dialog
open={true}
onClose={fClose}
aria-labelledby="form-dialog-title"
id="add-edit-user-dialog">
<DialogTitle id="form-dialog-title">
{isEdit ? 'Edit ' + name : 'Add a user'}
</DialogTitle>
<DialogContent>
<TextField
autoFocus
margin="dense"
className="name"
label="Username *"
value={name}
name="username"
id="username"
onChange={(e) => setName(e.target.value)}
fullWidth
/>
<TextField
margin="dense"
className="password"
type="password"
value={pass}
fullWidth
label={isEdit ? 'Password (empty if no change)' : 'Password *'}
name="password"
id="password"
onChange={(e) => setPass(e.target.value)}
/>
<FormControlLabel
control={
<Switch
checked={admin}
className="admin-rights"
onChange={(e) => setAdmin(e.target.checked)}
value="admin"
/>
}
label="has administrator rights"
/>
</DialogContent>
<DialogActions>
<Button onClick={fClose}>Cancel</Button>
<Tooltip
placement={'bottom-start'}
title={
namePresent
? passPresent
? ''
: 'password is required'
: 'username is required'
}>
<div>
<Button
className="save-create"
disabled={!passPresent || !namePresent}
onClick={submitAndClose}
color="primary"
variant="contained">
{isEdit ? 'Save' : 'Create'}
</Button>
</div>
</Tooltip>
</DialogActions>
</Dialog>
);
};
export default AddEditUserDialog;

View File

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

View File

@ -5,7 +5,7 @@ import DialogContent from '@mui/material/DialogContent';
import DialogTitle from '@mui/material/DialogTitle';
import TextField from '@mui/material/TextField';
import Tooltip from '@mui/material/Tooltip';
import React, {ChangeEvent, Component} from 'react';
import React from 'react';
interface IProps {
name?: string;
@ -13,92 +13,85 @@ interface IProps {
fOnSubmit: (name: string, pass: string) => Promise<boolean>;
}
interface IState {
name: string;
pass: string;
}
const RegistrationDialog = ({fClose, fOnSubmit, name: initialName = ''}: IProps) => {
const [name, setName] = React.useState(initialName);
const [pass, setPass] = React.useState('');
const namePresent = name.length !== 0;
const passPresent = pass.length !== 0;
export default class RegistrationDialog extends Component<IProps, IState> {
public state = {
name: '',
pass: '',
const handleNameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setName(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 => {
fOnSubmit(name, pass).then((success) => {
if (success) {
fClose();
}
});
};
return (
<Dialog
open={true}
onClose={fClose}
aria-labelledby="form-dialog-title"
id="add-edit-user-dialog">
<DialogTitle id="form-dialog-title">Registration</DialogTitle>
<DialogContent>
<TextField
autoFocus
id="register-username"
margin="dense"
className="name"
label="Username *"
name="username"
value={name}
autoComplete="username"
onChange={this.handleChange.bind(this, 'name')}
fullWidth
/>
<TextField
id="register-password"
margin="dense"
className="password"
type="password"
value={pass}
fullWidth
label="Password *"
name="password"
autoComplete="new-password"
onChange={this.handleChange.bind(this, 'pass')}
/>
</DialogContent>
<DialogActions>
<Button onClick={fClose}>Cancel</Button>
<Tooltip
placement={'bottom-start'}
title={
namePresent
? passPresent
? ''
: 'password is required'
: 'username is required'
}>
<div>
<Button
className="save-create"
disabled={!passPresent || !namePresent}
onClick={submitAndClose}
color="primary"
variant="contained">
Register
</Button>
</div>
</Tooltip>
</DialogActions>
</Dialog>
);
}
const handlePassChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setPass(e.target.value);
};
private handleChange(propertyName: keyof IState, event: ChangeEvent<HTMLInputElement>) {
const state = this.state;
state[propertyName] = event.target.value;
this.setState(state);
}
}
const submitAndClose = (): void => {
fOnSubmit(name, pass).then((success) => {
if (success) {
fClose();
}
});
};
return (
<Dialog
open={true}
onClose={fClose}
aria-labelledby="form-dialog-title"
id="add-edit-user-dialog">
<DialogTitle id="form-dialog-title">Registration</DialogTitle>
<DialogContent>
<TextField
autoFocus
id="register-username"
margin="dense"
className="name"
label="Username *"
name="username"
value={name}
autoComplete="username"
onChange={handleNameChange}
fullWidth
/>
<TextField
id="register-password"
margin="dense"
className="password"
type="password"
value={pass}
fullWidth
label="Password *"
name="password"
autoComplete="new-password"
onChange={handlePassChange}
/>
</DialogContent>
<DialogActions>
<Button onClick={fClose}>Cancel</Button>
<Tooltip
placement={'bottom-start'}
title={
namePresent
? passPresent
? ''
: 'password is required'
: 'username is required'
}>
<div>
<Button
className="save-create"
disabled={!passPresent || !namePresent}
onClick={submitAndClose}
color="primary"
variant="contained">
Register
</Button>
</div>
</Tooltip>
</DialogActions>
</Dialog>
);
};
export default RegistrationDialog;

View File

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