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 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};
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);
const submitEnabled = name.length !== 0;
const submitAndClose = async () => {
await fOnSubmit(name, description, defaultPriority);
fClose();
};
return (
<Dialog
open={true}
onClose={fClose}
aria-labelledby="form-dialog-title"
id="app-dialog">
<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>
<DialogContentText>An application is allowed to send messages.</DialogContentText>
<TextField
autoFocus
margin="dense"
@ -49,7 +37,7 @@ export default class AddDialog extends Component<IProps, IState> {
label="Name *"
type="text"
value={name}
onChange={this.handleChange.bind(this, 'name')}
onChange={(e) => setName(e.target.value)}
fullWidth
/>
<TextField
@ -57,7 +45,7 @@ export default class AddDialog extends Component<IProps, IState> {
className="description"
label="Short Description"
value={description}
onChange={this.handleChange.bind(this, 'description')}
onChange={(e) => setDescription(e.target.value)}
fullWidth
multiline
/>
@ -66,7 +54,7 @@ export default class AddDialog extends Component<IProps, IState> {
className="priority"
label="Default Priority"
value={defaultPriority}
onChange={(value) => this.setState({defaultPriority: value})}
onChange={(value) => setDefaultPriority(value)}
fullWidth
/>
</DialogContent>
@ -87,14 +75,4 @@ export default class AddDialog extends Component<IProps, IState> {
</DialogActions>
</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 IconButton from '@mui/material/IconButton';
import Paper from '@mui/material/Paper';
@ -9,42 +10,50 @@ 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;
private uploadId = -1;
private upload: HTMLInputElement | null = null;
public componentDidMount = () => this.props.appStore.refresh();
public render() {
const {
createDialog,
deleteId,
updateId,
props: {appStore},
} = this;
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);
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 (
<DefaultPage
title="Applications"
@ -53,12 +62,12 @@ class Applications extends Component<Stores<'appStore'>> {
id="create-app"
variant="contained"
color="primary"
onClick={() => (this.createDialog = true)}>
onClick={() => setCreateDialog(true)}>
Create Application
</Button>
}
maxWidth={1000}>
<Grid size={{xs: 12}}>
<Grid size={12}>
<Paper elevation={6} style={{overflowX: 'auto'}}>
<Table id="app-table">
<TableHead>
@ -83,70 +92,50 @@ class Applications extends Component<Stores<'appStore'>> {
name={app.name}
value={app.token}
lastUsed={app.lastUsed}
fUpload={() => this.uploadImage(app.id)}
fDelete={() => (this.deleteId = app.id)}
fEdit={() => (this.updateId = app.id)}
fUpload={() => handleImageUploadClick(app.id)}
fDelete={() => setToDeleteApp(app)}
fEdit={() => setToUpdateApp(app)}
noDelete={app.internal}
/>
))}
</TableBody>
</Table>
<input
ref={(upload) => (this.upload = upload)}
ref={fileInputRef}
type="file"
style={{display: 'none'}}
onChange={this.onUploadImage}
onChange={onUploadImage}
/>
</Paper>
</Grid>
{createDialog && (
<AddApplicationDialog
fClose={() => (this.createDialog = false)}
fClose={() => setCreateDialog(false)}
fOnSubmit={appStore.create}
/>
)}
{updateId !== false && (
<UpdateDialog
fClose={() => (this.updateId = false)}
{toUpdateApp != null && (
<UpdateApplicationDialog
fClose={() => setToUpdateApp(undefined)}
fOnSubmit={(name, description, defaultPriority) =>
appStore.update(updateId, name, description, defaultPriority)
appStore.update(toUpdateApp.id, name, description, defaultPriority)
}
initialDescription={appStore.getByID(updateId).description}
initialName={appStore.getByID(updateId).name}
initialDefaultPriority={appStore.getByID(updateId).defaultPriority}
initialDescription={toUpdateApp?.description}
initialName={toUpdateApp?.name}
initialDefaultPriority={toUpdateApp?.defaultPriority}
/>
)}
{deleteId !== false && (
{toDeleteApp != null && (
<ConfirmDialog
title="Confirm Delete"
text={'Delete ' + appStore.getByID(deleteId).name + '?'}
fClose={() => (this.deleteId = false)}
fOnSubmit={() => appStore.remove(deleteId)}
text={'Delete ' + toDeleteApp.name + '?'}
fClose={() => setToDeleteApp(undefined)}
fOnSubmit={() => appStore.remove(toDeleteApp.id)}
/>
)}
</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 {
name: string;
@ -161,8 +150,7 @@ interface IRowProps {
fEdit: VoidFunction;
}
const Row: SFC<IRowProps> = observer(
({
const Row = ({
name,
value,
noDelete,
@ -173,12 +161,13 @@ const Row: SFC<IRowProps> = observer(
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,53 +7,38 @@ 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};
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);
const submitEnabled = name.length !== 0;
const submitAndClose = async () => {
await fOnSubmit(name, description, defaultPriority);
fClose();
};
return (
<Dialog
open={true}
onClose={fClose}
aria-labelledby="form-dialog-title"
id="app-dialog">
<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>
<DialogContentText>An application is allowed to send messages.</DialogContentText>
<TextField
autoFocus
margin="dense"
@ -61,7 +46,7 @@ export default class UpdateDialog extends Component<IProps, IState> {
label="Name *"
type="text"
value={name}
onChange={this.handleChange.bind(this, 'name')}
onChange={(e) => setName(e.target.value)}
fullWidth
/>
<TextField
@ -69,7 +54,7 @@ export default class UpdateDialog extends Component<IProps, IState> {
className="description"
label="Short Description"
value={description}
onChange={this.handleChange.bind(this, 'description')}
onChange={(e) => setDescription(e.target.value)}
fullWidth
multiline
/>
@ -78,7 +63,7 @@ export default class UpdateDialog extends Component<IProps, IState> {
className="priority"
label="Default Priority"
value={defaultPriority}
onChange={(value) => this.setState({defaultPriority: value})}
onChange={(e) => setDefaultPriority(e)}
fullWidth
/>
</DialogContent>
@ -99,14 +84,4 @@ export default class UpdateDialog extends Component<IProps, IState> {
</DialogActions>
</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 Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
@ -5,30 +6,23 @@ 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);
const submitEnabled = name.length !== 0;
const submitAndClose = async () => {
await fOnSubmit(name);
fClose();
};
return (
<Dialog
open={true}
onClose={fClose}
aria-labelledby="form-dialog-title"
id="client-dialog">
<Dialog open={true} onClose={fClose} aria-labelledby="form-dialog-title" id="client-dialog">
<DialogTitle id="form-dialog-title">Create a client</DialogTitle>
<DialogContent>
<TextField
@ -38,15 +32,13 @@ export default class AddDialog extends Component<IProps, {name: string}> {
label="Name *"
type="email"
value={name}
onChange={this.handleChange.bind(this, 'name')}
onChange={(e) => setName(e.target.value)}
fullWidth
/>
</DialogContent>
<DialogActions>
<Button onClick={fClose}>Cancel</Button>
<Tooltip
placement={'bottom-start'}
title={submitEnabled ? '' : 'name is required'}>
<Tooltip placement={'bottom-start'} title={submitEnabled ? '' : 'name is required'}>
<div>
<Button
className="create"
@ -61,11 +53,6 @@ export default class AddDialog extends Component<IProps, {name: string}> {
</DialogActions>
</Dialog>
);
}
};
private handleChange(propertyName: 'name', event: React.ChangeEvent<HTMLInputElement>) {
const state = this.state;
state[propertyName] = event.target.value;
this.setState(state);
}
}
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,39 +9,26 @@ 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;
public componentDidMount = () => this.props.clientStore.refresh();
public render() {
const {
deleteId,
updateId,
showDialog,
props: {clientStore},
} = this;
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();
useEffect(() => void clientStore.refresh(), []);
return (
<DefaultPage
title="Clients"
@ -49,11 +37,11 @@ class Clients extends Component<Stores<'clientStore'>> {
id="create-client"
variant="contained"
color="primary"
onClick={() => (this.showDialog = true)}>
onClick={() => setCreateDialog(true)}>
Create Client
</Button>
}>
<Grid size={{xs: 12}}>
<Grid size={12}>
<Paper elevation={6} style={{overflowX: 'auto'}}>
<Table id="client-table">
<TableHead>
@ -72,39 +60,38 @@ class Clients extends Component<Stores<'clientStore'>> {
name={client.name}
value={client.token}
lastUsed={client.lastUsed}
fEdit={() => (this.updateId = client.id)}
fDelete={() => (this.deleteId = client.id)}
fEdit={() => setToUpdateClient(client)}
fDelete={() => setToDeleteClient(client)}
/>
))}
</TableBody>
</Table>
</Paper>
</Grid>
{showDialog && (
{createDialog && (
<AddClientDialog
fClose={() => (this.showDialog = false)}
fClose={() => setCreateDialog(false)}
fOnSubmit={clientStore.create}
/>
)}
{updateId !== false && (
<UpdateDialog
fClose={() => (this.updateId = false)}
fOnSubmit={(name) => clientStore.update(updateId, name)}
initialName={clientStore.getByID(updateId).name}
{toUpdateClient != null && (
<UpdateClientDialog
fClose={() => setToUpdateClient(undefined)}
fOnSubmit={(name) => clientStore.update(toUpdateClient.id, name)}
initialName={toUpdateClient.name}
/>
)}
{deleteId !== false && (
{toDeleteClient != null && (
<ConfirmDialog
title="Confirm Delete"
text={'Delete ' + clientStore.getByID(deleteId).name + '?'}
fClose={() => (this.deleteId = false)}
fOnSubmit={() => clientStore.remove(deleteId)}
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,42 +7,24 @@ 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: ''};
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);
const submitEnabled = name.length !== 0;
const submitAndClose = async () => {
await fOnSubmit(name);
fClose();
};
return (
<Dialog
open={true}
onClose={fClose}
aria-labelledby="form-dialog-title"
id="client-dialog">
<Dialog open={true} onClose={fClose} aria-labelledby="form-dialog-title" id="client-dialog">
<DialogTitle id="form-dialog-title">Update a Client</DialogTitle>
<DialogContent>
<DialogContentText>
@ -55,7 +38,7 @@ export default class UpdateDialog extends Component<IProps, IState> {
label="Name *"
type="text"
value={name}
onChange={this.handleChange.bind(this, 'name')}
onChange={(e) => setName(e.target.value)}
fullWidth
/>
</DialogContent>
@ -76,11 +59,6 @@ export default class UpdateDialog extends Component<IProps, IState> {
</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 = () =>
({
const useStyles = makeStyles()(() => ({
paper: {
padding: 16,
},
} as const);
}));
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,30 +1,22 @@
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);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.scrollHandler);
}
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 (this.state.display !== nextState.display || this.state.opacity !== nextState.opacity) {
this.setState(nextState);
if (state.display !== nextState.display || state.opacity !== nextState.opacity) {
setState(nextState);
}
};
window.addEventListener('scroll', scrollHandler);
return () => window.removeEventListener('scroll', scrollHandler);
}, []);
public render() {
return (
<Fab
color="primary"
@ -33,16 +25,13 @@ class ScrollUpButton extends Component {
bottom: '30px',
right: '30px',
zIndex: 100000,
display: this.state.display,
opacity: this.state.opacity,
display: state.display,
opacity: state.opacity,
}}
onClick={this.scrollUp}>
onClick={() => window.scrollTo(0, 0)}>
<KeyboardArrowUp />
</Fab>
);
}
private scrollUp = () => window.scrollTo(0, 0);
}
};
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,27 +6,22 @@ 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 = () => {
const submitAndClose = async () => {
currentUser.changePassword(pass);
fClose();
};
return (
<Dialog
open={true}
@ -41,7 +37,7 @@ class SettingsDialog extends Component<IProps & Stores<'currentUser'>> {
type="password"
label="New Password *"
value={pass}
onChange={(e) => (this.pass = e.target.value)}
onChange={(e) => setPass(e.target.value)}
fullWidth
/>
</DialogContent>
@ -62,7 +58,6 @@ class SettingsDialog extends Component<IProps & Stores<'currentUser'>> {
</DialogActions>
</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 {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(
<StoreContext.Provider value={stores}>
<InjectProvider stores={stores}>
<Layout />
</InjectProvider>,
</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,13 +14,11 @@ 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) =>
({
const useStyles = makeStyles()((theme: Theme) => ({
appBar: {
zIndex: theme.zIndex.drawer + 1,
[theme.breakpoints.down('sm')]: {
@ -62,14 +60,13 @@ const styles = (theme: Theme) =>
color: 'inherit',
textDecoration: 'none',
},
} as const);
}));
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,12 +74,18 @@ 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 classes = withStyles.getClasses(this.props);
const Header = ({
version,
name,
loggedIn,
admin,
toggleTheme,
logout,
style,
setNavOpen,
showSettings,
}: IProps) => {
const {classes} = useStyles();
return (
<AppBar
@ -104,7 +107,15 @@ class Header extends Component<IProps> {
</Typography>
</a>
</div>
{loggedIn && this.renderButtons(name, admin, logout, setNavOpen)}
{loggedIn && (
<Buttons
admin={admin}
name={name}
logout={logout}
setNavOpen={setNavOpen}
showSettings={showSettings}
/>
)}
<div>
<IconButton onClick={toggleTheme} color="inherit" size="large">
<Highlight />
@ -123,16 +134,23 @@ class Header extends Component<IProps> {
</Toolbar>
</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 (
<div className={classes.menuButtons}>
<ResponsiveButton
@ -144,11 +162,7 @@ class Header extends Component<IProps> {
/>
{admin && (
<Link className={classes.link} to="/users" id="navigate-users">
<ResponsiveButton
icon={<SupervisorAccount />}
label="users"
color="inherit"
/>
<ResponsiveButton icon={<SupervisorAccount />} label="users" color="inherit" />
</Link>
)}
<Link className={classes.link} to="/applications" id="navigate-apps">
@ -176,8 +190,7 @@ class Header extends Component<IProps> {
/>
</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,34 +51,7 @@ 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>>;
}
@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 Layout = observer(() => {
const {
currentUser: {
loggedIn,
@ -89,11 +61,24 @@ class Layout extends React.Component<LayoutProps & Stores<'currentUser' | 'snack
tryReconnect,
connectionErrorMessage,
},
} = this.props;
const classes = withStyles.getClasses(this.props);
} = 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);
const toggleTheme = () => {
const next = currentTheme === 'dark' ? 'light' : 'dark';
setCurrentTheme(next);
localStorage.setItem(localStorageThemeKey, next);
};
return (
<StyledEngineProvider injectFirst>
<ThemeProvider theme={theme}>
@ -109,21 +94,21 @@ class Layout extends React.Component<LayoutProps & Stores<'currentUser' | 'snack
<div style={{display: 'flex', flexDirection: 'column'}}>
<CssBaseline />
<Header
style={{top: !connectionErrorMessage ? 0 : 64}}
admin={admin}
name={name}
style={{top: !connectionErrorMessage ? 0 : 64}}
version={version}
loggedIn={loggedIn}
toggleTheme={this.toggleTheme.bind(this)}
showSettings={() => (this.showSettings = true)}
toggleTheme={toggleTheme}
showSettings={() => setShowSettings(true)}
logout={logout}
setNavOpen={this.setNavOpen.bind(this)}
setNavOpen={setNavOpen}
/>
<div style={{display: 'flex'}}>
<Navigation
loggedIn={loggedIn}
navOpen={this.navOpen}
setNavOpen={this.setNavOpen.bind(this)}
navOpen={navOpen}
setNavOpen={setNavOpen}
/>
<main className={classes.content}>
<Switch>
@ -135,11 +120,7 @@ class Layout extends React.Component<LayoutProps & Stores<'currentUser' | 'snack
<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="/messages/:id" component={Messages} />
<Route
exact
path="/applications"
@ -157,7 +138,7 @@ class Layout extends React.Component<LayoutProps & Stores<'currentUser' | 'snack
</main>
</div>
{showSettings && (
<SettingsDialog fClose={() => (this.showSettings = false)} />
<SettingsDialog fClose={() => setShowSettings(false)} />
)}
<ScrollUpButton />
<SnackBarHandler />
@ -167,12 +148,6 @@ class Layout extends React.Component<LayoutProps & Stores<'currentUser' | 'snack
</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,10 +16,10 @@ 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) =>
({
const useStyles = makeStyles()((theme: Theme) => ({
root: {
height: '100%',
},
@ -36,26 +35,19 @@ const styles = (theme: Theme) =>
color: 'inherit',
textDecoration: 'none',
},
} as const);
}));
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()};
public render() {
const {loggedIn, appStore, navOpen, setNavOpen} = this.props;
const classes = withStyles.getClasses(this.props);
const {showRequestNotification} = this.state;
const Navigation = observer(({loggedIn, navOpen, setNavOpen}: IProps) => {
const [showRequestNotification, setShowRequestNotification] =
React.useState(mayAllowPermission);
const {classes} = useStyles();
const {appStore} = useStores();
const apps = appStore.getItems();
const userApps =
@ -109,7 +101,7 @@ class Navigation extends Component<
<Button
onClick={() => {
requestPermission();
this.setState({showRequestNotification: false});
setShowRequestNotification(false);
}}>
Enable Notifications
</Button>
@ -117,8 +109,7 @@ class Navigation extends Component<
</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,65 +14,47 @@ 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();
const refreshConfigurer = async () => {
if (pluginInfo?.capabilities.indexOf('configurer') !== -1) {
setCurrentConfig(await pluginStore.requestConfig(pluginID));
}
};
private async refreshFeatures() {
await this.props.pluginStore.refreshIfMissing(this.pluginID);
return await Promise.all([this.refreshConfigurer(), this.refreshDisplayer()]);
const refreshDisplayer = async () => {
if (pluginInfo?.capabilities.indexOf('displayer') !== -1) {
setDisplayText(await pluginStore.requestDisplay(pluginID));
}
};
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});
}
}
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) {
if (pluginInfo == null) {
return <LoadingSpinner />;
}
const handleSaveConfig = async (newConfig: string) => {
await pluginStore.changeConfig(pluginID, newConfig);
await refreshFeatures();
};
return (
<DefaultPage title={pluginInfo.name} maxWidth={1000}>
<PanelWrapper name={'Plugin Info'} icon={Info}>
@ -83,18 +65,11 @@ class PluginDetailView extends Component<IProps & Stores<'pluginStore'>, IState>
name={'Configurer'}
description={'This is the configuration panel for this plugin.'}
icon={Build}
refresh={this.refreshConfigurer.bind(this)}>
refresh={refreshConfigurer}>
<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();
}}
initialConfig={currentConfig != null ? currentConfig : 'Loading...'}
save={handleSaveConfig}
/>
</PanelWrapper>
) : null}{' '}
@ -102,22 +77,17 @@ class PluginDetailView extends Component<IProps & Stores<'pluginStore'>, IState>
<PanelWrapper
name={'Displayer'}
description={'This is the information generated by the plugin.'}
refresh={this.refreshDisplayer.bind(this)}
refresh={refreshDisplayer}
icon={Subject}>
<DisplayerPanel
pluginInfo={pluginInfo}
displayText={
this.state.displayText !== null
? this.state.displayText
: 'Loading...'
}
displayText={displayText != null ? displayText : 'Loading...'}
/>
</PanelWrapper>
) : null}
</DefaultPage>
);
}
}
};
interface IPanelWrapperProps {
name: string;
@ -178,14 +148,12 @@ interface IConfigurerPanelProps {
initialConfig: string;
save: (newConfig: string) => Promise<void>;
}
class ConfigurerPanel extends Component<IConfigurerPanelProps, {unsavedChanges: string | null}> {
public state = {unsavedChanges: null};
public render() {
const ConfigurerPanel = ({initialConfig, save}: IConfigurerPanelProps) => {
const [unsavedChanges, setUnsavedChanges] = React.useState<string | null>(null);
return (
<div>
<CodeMirror
value={this.props.initialConfig}
value={initialConfig}
options={{
mode: 'yaml',
theme: 'material',
@ -193,10 +161,10 @@ class ConfigurerPanel extends Component<IConfigurerPanelProps, {unsavedChanges:
}}
onChange={(_, _1, value) => {
let newConf: string | null = value;
if (value === this.props.initialConfig) {
if (value === initialConfig) {
newConf = null;
}
this.setState({unsavedChanges: newConf});
setUnsavedChanges(newConf);
}}
/>
<br />
@ -204,23 +172,19 @@ class ConfigurerPanel extends Component<IConfigurerPanelProps, {unsavedChanges:
variant="contained"
color="primary"
fullWidth={true}
disabled={
this.state.unsavedChanges === null ||
this.state.unsavedChanges === this.props.initialConfig
}
disabled={unsavedChanges === null || unsavedChanges === initialConfig}
className="config-save"
onClick={() => {
const newConfig = this.state.unsavedChanges;
this.props.save(newConfig!).then(() => {
this.setState({unsavedChanges: null});
const newConfig = unsavedChanges;
save(newConfig!).then(() => {
setUnsavedChanges(null);
});
}}>
<Typography variant="button">Save</Typography>
</Button>
</div>
);
}
}
};
interface IDisplayerPanelProps {
pluginInfo: IPlugin;
@ -232,13 +196,13 @@ 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;
interface IPluginInfo {
pluginInfo: IPlugin;
}
const PluginInfo = ({pluginInfo}: IPluginInfo) => {
const {name, author, modulePath, website, license, capabilities, id, token} = pluginInfo;
return (
<div style={{wordWrap: 'break-word'}}>
{name ? (
@ -283,7 +247,6 @@ class PluginInfo extends Component<{pluginInfo: IPlugin}> {
) : null}
</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 Grid from '@mui/material/Grid';
import Paper from '@mui/material/Paper';
@ -12,17 +12,12 @@ 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 = observer(() => {
const {pluginStore} = useStores();
React.useEffect(() => void pluginStore.refresh(), []);
const plugins = pluginStore.getItems();
return (
<DefaultPage title="Plugins" maxWidth={1000}>
@ -47,10 +42,7 @@ class Plugins extends Component<Stores<'pluginStore'>> {
name={plugin.name}
enabled={plugin.enabled}
fToggleStatus={() =>
this.props.pluginStore.changeEnabledState(
plugin.id,
!plugin.enabled
)
pluginStore.changeEnabledState(plugin.id, !plugin.enabled)
}
/>
))}
@ -60,8 +52,7 @@ class Plugins extends Component<Stores<'pluginStore'>> {
</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,36 +7,31 @@ 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,
};
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);
const namePresent = name.length !== 0;
const passPresent = pass.length !== 0 || isEdit;
const submitAndClose = async () => {
await fOnSubmit(name, pass, admin);
fClose();
};
return (
@ -46,7 +41,7 @@ export default class AddEditDialog extends Component<IProps, IState> {
aria-labelledby="form-dialog-title"
id="add-edit-user-dialog">
<DialogTitle id="form-dialog-title">
{isEdit ? 'Edit ' + this.props.name : 'Add a user'}
{isEdit ? 'Edit ' + name : 'Add a user'}
</DialogTitle>
<DialogContent>
<TextField
@ -57,7 +52,7 @@ export default class AddEditDialog extends Component<IProps, IState> {
value={name}
name="username"
id="username"
onChange={this.handleChange.bind(this, 'name')}
onChange={(e) => setName(e.target.value)}
fullWidth
/>
<TextField
@ -69,14 +64,14 @@ export default class AddEditDialog extends Component<IProps, IState> {
label={isEdit ? 'Password (empty if no change)' : 'Password *'}
name="password"
id="password"
onChange={this.handleChange.bind(this, 'pass')}
onChange={(e) => setPass(e.target.value)}
/>
<FormControlLabel
control={
<Switch
checked={admin}
className="admin-rights"
onChange={this.handleChecked.bind(this, 'admin')}
onChange={(e) => setAdmin(e.target.checked)}
value="admin"
/>
}
@ -108,17 +103,5 @@ export default class AddEditDialog extends Component<IProps, IState> {
</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);
}
}
};
export default AddEditUserDialog;

View File

@ -1,31 +1,41 @@
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;
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 (
<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'}}>
<Container>
<form onSubmit={this.preventDefault} id="login-form">
<form onSubmit={(e) => e.preventDefault()} id="login-form">
<TextField
autoFocus
id="username"
@ -35,7 +45,7 @@ class Login extends Component<Stores<'currentUser'>> {
margin="dense"
autoComplete="username"
value={username}
onChange={(e) => (this.username = e.target.value)}
onChange={(e) => setUsername(e.target.value)}
/>
<TextField
id="password"
@ -46,7 +56,7 @@ class Login extends Component<Stores<'currentUser'>> {
margin="normal"
autoComplete="current-password"
value={password}
onChange={(e) => (this.password = e.target.value)}
onChange={(e) => setPassword(e.target.value)}
/>
<Button
type="submit"
@ -54,9 +64,9 @@ class Login extends Component<Stores<'currentUser'>> {
size="large"
className="login"
color="primary"
disabled={!!this.props.currentUser.connectionErrorMessage}
disabled={!!currentUser.connectionErrorMessage}
style={{marginTop: 15, marginBottom: 5}}
onClick={this.login}>
onClick={login}>
Login
</Button>
</form>
@ -64,34 +74,12 @@ class Login extends Component<Stores<'currentUser'>> {
</Grid>
{registerDialog && (
<RegistrationDialog
fClose={() => (this.registerDialog = false)}
fOnSubmit={this.props.currentUser.register}
fClose={() => setRegisterDialog(false)}
fOnSubmit={currentUser.register}
/>
)}
</DefaultPage>
);
}
});
private login = (e: React.MouseEvent<HTMLButtonElement>) => {
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);
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,22 +13,20 @@ 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);
};
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 => {
fOnSubmit(name, pass).then((success) => {
if (success) {
@ -36,6 +34,7 @@ export default class RegistrationDialog extends Component<IProps, IState> {
}
});
};
return (
<Dialog
open={true}
@ -53,7 +52,7 @@ export default class RegistrationDialog extends Component<IProps, IState> {
name="username"
value={name}
autoComplete="username"
onChange={this.handleChange.bind(this, 'name')}
onChange={handleNameChange}
fullWidth
/>
<TextField
@ -66,7 +65,7 @@ export default class RegistrationDialog extends Component<IProps, IState> {
label="Password *"
name="password"
autoComplete="new-password"
onChange={this.handleChange.bind(this, 'pass')}
onChange={handlePassChange}
/>
</DialogContent>
<DialogActions>
@ -94,11 +93,5 @@ export default class RegistrationDialog extends Component<IProps, IState> {
</DialogActions>
</Dialog>
);
}
private handleChange(propertyName: keyof IState, event: ChangeEvent<HTMLInputElement>) {
const state = this.state;
state[propertyName] = event.target.value;
this.setState(state);
}
}
};
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,24 +39,12 @@ 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;
public componentDidMount = () => this.props.userStore.refresh();
public render() {
const {
deleteId,
editId,
createDialog,
props: {userStore},
} = this;
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
@ -67,7 +54,7 @@ class Users extends Component<Stores<'userStore'>> {
id="create-user"
variant="contained"
color="primary"
onClick={() => (this.createDialog = true)}>
onClick={() => setCreateDialog(true)}>
Create User
</Button>
}>
@ -87,8 +74,8 @@ class Users extends Component<Stores<'userStore'>> {
key={user.id}
name={user.name}
admin={user.admin}
fDelete={() => (this.deleteId = user.id)}
fEdit={() => (this.editId = user.id)}
fDelete={() => setDeleteUser(user)}
fEdit={() => setEditUser(user)}
/>
))}
</TableBody>
@ -96,31 +83,27 @@ class Users extends Component<Stores<'userStore'>> {
</Paper>
</Grid>
{createDialog && (
<AddEditDialog
fClose={() => (this.createDialog = false)}
fOnSubmit={userStore.create}
/>
<AddEditDialog fClose={() => setCreateDialog(false)} fOnSubmit={userStore.create} />
)}
{editId !== false && (
{editUser && (
<AddEditDialog
fClose={() => (this.editId = false)}
fOnSubmit={userStore.update.bind(this, editId)}
name={userStore.getByID(editId).name}
admin={userStore.getByID(editId).admin}
fClose={() => setEditUser(undefined)}
fOnSubmit={userStore.update.bind(this, editUser.id)}
name={editUser.name}
admin={editUser.admin}
isEdit={true}
/>
)}
{deleteId !== false && (
{deleteUser && (
<ConfirmDialog
title="Confirm Delete"
text={'Delete ' + userStore.getByID(deleteId).name + '?'}
fClose={() => (this.deleteId = false)}
fOnSubmit={() => userStore.remove(deleteId)}
text={'Delete ' + deleteUser.name + '?'}
fClose={() => setDeleteUser(undefined)}
fOnSubmit={() => userStore.remove(deleteUser.id)}
/>
)}
</DefaultPage>
);
}
}
});
export default inject('userStore')(Users);
export default Users;